$(document).ready(function() {	
	
	//////////////////////////////////////////////////////////////////
	/////////////////////////// MOBILE??? ////////////////////////////
	//////////////////////////////////////////////////////////////////

	var mobile = false;
	var tiny_screen = false;
	
	if (navigator.userAgent.match(/Android/i) ||
		navigator.userAgent.match(/webOS/i) ||
		navigator.userAgent.match(/iPhone/i) ||
		navigator.userAgent.match(/iPod/i) ||
		navigator.userAgent.match(/iPad/i)
		){
		mobile = true;
	}	
	
	// Big fat top navigation in case of Mobile browsers
	//if (mobile) {
	//	$('#main_navigation').find('li').css({fontSize: '40px', marginLeft: '40px'});
	//}


	//////////////////////////////////////////////////////////////////
	//////////////////////// Transition Test /////////////////////////
	//////////////////////////////////////////////////////////////////
	
	//var css_transitions = supportsTransitions();

	//function supportsTransitions() {
		//var b = document.body || document.documentElement;
		//var s = b.style;
		//var p = 'transition';
		//if(typeof s[p] == 'string') {return true; }

		// Tests for vendor specific prop
		//v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'],
		//p = p.charAt(0).toUpperCase() + p.substr(1);
		//for(var i=0; i<v.length; i++) {
		//  if(typeof s[v[i] + p] == 'string') { return true; }
		//}
		//return false;
	//}
	
	var css_transitions = false;
	if ($('html').hasClass('csstransitions')) {
		css_transitions = true;
	} else {
		css_transitions = false;
	}
	

	//////////////////////////////////////////////////////////////////
	/////////////////////////// Carousel /////////////////////////////
	//////////////////////////////////////////////////////////////////
	
	var $carousel_images = $('#carousel_images');
	var $project_image = $('.project_image');
	var $project_navigation = $('#project_navigation');
	var $project_nav_link = $('.project_nav_link');
	var project_image_size = $project_image.size();
	var middle_project_number = Math.floor(project_image_size/2);
	var image_width = $project_image.width();
	var image_height = $project_image.height();
	var anim_speed = 400;
	var anim_ease = 'easeInOutQuad';
	var pos_dynamic = $carousel_images.css('left'); // Fluctuating carousel position
	var active_image_number = middle_project_number; // Initialize "active" project
	
	// Fade in images when loaded?
	//$(window).load(function() {
	//	$project_image.fadeIn(500);
	//});
	
	// Initialize
	$carousel_images.width(project_image_size*image_width); // Get width based on # of images
	// Set position and add delay before giving the carousel Transition effects
	$carousel_images.css({left: -(middle_project_number*image_width)}).queue(function(){ 
		setTimeout(function(){
			$carousel_images.addClass('transitions').dequeue(); 
		}, 10 ); 
	});
	
	// Click events
	$('.projects').find('#logo').click(function(e) {
		e.preventDefault();
		if (state_list) {
			showVideos();
		}
		caRotate(middle_project_number);
	});
	
	$($project_nav_link).click(function() {		
		var nav_position = $project_nav_link.index(this);
		caRotate(nav_position);	
	});
	
	// Mobile Swiping
	//$carousel_images.wipetouch({
	//	wipeLeft: function() {
	////		caRotate(active_image_number + 1);
	//	},
	//	wipeRight: function() {
	//		caRotate(active_image_number - 1);
	//	},
	//	wipeUp: function() {
	//		return false;
	//	}, 
	//	wipdeDown: function() {
	//		return false;
	//	}
	//});
	
	$carousel_images.swipe({
		swipeLeft: function() {
			caRotate(active_image_number + 1);
		},
		swipeRight: function() {
			caRotate(active_image_number - 1);
		},
		threshold: 20,
		triggerOnEnd: false,
		allowPageScrol: 'vertical'
	});
	
	// Carousel Rotate!
	function caRotate(image_number) {
		// Stop if nav is clicked on current image
		if (image_number == active_image_number) {
			return false;
		}
		
		active_image_number = image_number; // Store current image
		navigate(active_image_number); // Update Navigation
		pos_dynamic = active_image_number * image_width; // Store current position
		
		// Show videos if list is still up
		if (state_list) {
			showVideos();
		}
		
		// Run the animation
		if (css_transitions) {
			$carousel_images.css({left: -pos_dynamic});
		} else if (!css_transitions) {
			$carousel_images.stop(true, true).animate({left: -pos_dynamic}, anim_speed*2, anim_ease);	
		}
	}
	

	//////////////////////////////////////////////////////////////////
	////////////////////////// NAVIGATION ////////////////////////////
	//////////////////////////////////////////////////////////////////
	
	// Set the navigation
	navigate(active_image_number);
	// Physically center navigation
	//centerNav();
	
	// Make sure project navigation + social links don't bunch during resize
	//var min_nav_width = $project_navigation.width() + $('#social_links').width() + $('#project_list_trigger').width();
	//if (min_nav_width > $('#carousel_navigation').css('min-width')) {
	//	$('#carousel_navigation').css({'min-width': min_nav_width});
	//}
	
	function navigate(x) {
		$project_nav_link.removeClass('active_nav_link');
		$($project_nav_link[x]).addClass('active_nav_link');
	}
	
	//function centerNav() {
	//	var nav_pos_y = $('.main_width').width()/2 - $project_navigation.width()/2;
	//	$project_navigation.css({left: nav_pos_y});
	//}
	
	//var resize_timer = 0;
	//$(window).resize(function() {
	//	clearTimeout(resize_timer);
	//	resize_timer = setTimeout(centerNav(), 100);
	//});

	
	//////////////////////////////////////////////////////////////////
	/////////////////////////// VIDEO LIST ///////////////////////////
	//////////////////////////////////////////////////////////////////
	
	var $project_list = $('#project_list');
	var $project_list_trigger = $('#project_list_trigger');
	var $carousel_frame = $('#carousel_frame');
	var state_list = false;
	var project_list_height = $project_list.outerHeight();
	
	$project_list_trigger.click(function() {
		if (state_list === false) {
			showList();
		} else {
			showVideos();
		}
	});
	
	// Sorting List
	$('#project_list_sort .trigger').click(function() {
		if ($(this).hasClass('active_sort')) {
			return false;
		} else {
			$(this).siblings('.active_sort').removeClass('active_sort');
			$(this).addClass('active_sort');
			sortList(this);
		}
	});
	
	function sortList(trigger) {
		$(trigger).parent('ul').siblings('div.active_sort').removeClass('active_sort').fadeOut(200, function() {
			$(this).siblings('div').addClass('active_sort').fadeIn();
		});
	}
	
	// Show / Hide List
	function showList() {	
		state_list = !state_list;
		$project_navigation.animate({opacity: '0'}, anim_speed, function() {
			$project_navigation.css({visibility: 'hidden'});
		});
		$project_list_trigger.addClass('active');
		$carousel_images.fadeOut(anim_speed, anim_ease);
		setTimeout(function() {
			$project_list.fadeIn(anim_speed, anim_ease);
		}, anim_speed / 2);
		if (css_transitions) {
			$carousel_frame.css({height: project_list_height});
		} else if (!css_transitions) {
			$carousel_frame.animate({height: project_list_height}, anim_speed, anim_ease);
		}
	}
	
	function showVideos() {
		state_list = !state_list;
		$project_navigation.css({visibility: 'visible'}).animate({opacity: '1'}, anim_speed);
		$project_list_trigger.removeClass('active');
		$carousel_images.stop(true, true).fadeIn(anim_speed, anim_ease);
		$project_list.fadeOut(anim_speed, anim_ease);
		if (css_transitions) {
			$carousel_frame.css({height: image_height});
		} else if (!css_transitions) {
			$carousel_frame.animate({height: image_height}, anim_speed, anim_ease);
		}
	}
	

	//////////////////////////////////////////////////////////////////
	/////////////////////////// CONTACT //////////////////////////////
	//////////////////////////////////////////////////////////////////
	
	// Condense Client List for Mobile
	var $client = $('.client');
	if ($client.width() < 500) {
		var $second_ul = $client.children('ul:first').next('ul');
		var $fourth_ul = $second_ul.next('ul').next('ul');
		mergeLists($second_ul);
		mergeLists($fourth_ul);
	}
	
	function mergeLists(ul) {
		var $this = ul;
		$this.find('li').each(function() {
			$(this).appendTo($(this).parent('ul').prev('ul'));
		});
		$this.remove();
	}
	
	// More Awards
	function showAwards() {
		$('#awards_trigger').live('click', function() {
			$('#more_awards').slideToggle();
		});
	}
	
	showAwards();
	
	//////////////////////////////////////////////////////////////////
	/////////////////////////// FANCYBOX /////////////////////////////
	//////////////////////////////////////////////////////////////////
	
	// Vids
	if (!mobile) {
		$('.fancy_link').click(function() {
			// Scale for window
			var vid_height = $(window).height() * .75;
			var vid_width = $(window).width() * .6;
			// Make sure proportions are ok
			if ((vid_width / vid_height) < 1.6) {
				vid_height = vid_width / 1.6;
			}
			// Make sure it's not too small
			var min_video_width = 300;
			if (vid_width < min_video_width) {
				var scaling = vid_width / min_video_width;
				vid_width = min_video_width;
				vid_height = vid_height / scaling;
			}
			// Finally run Fancybox
			$.fancybox({
			'padding'       : 10,
			'cyclic'        : true,
			'autoScale'     : false,
			'transitionIn'  : 'fade',
			'transitionOut' : 'fade',
			'width'         : vid_width,
			'height'        : vid_height,
			'href'			: this.href,
			'type'          : 'iframe',
			'showNavArrows' : false
			});
			
			return false;
		});
	}
	
	// About
	if (!mobile) {
		$('#main_navigation ul li a:contains(About)').click(function(e) {
			e.preventDefault();
			
			var trigger_url = $(this).attr('href');
			var host = 'http://' + document.location.hostname;
			var fixed_url = trigger_url.replace(/^http:\/\/[A-Za-z\.]+/, host);
			
			$.ajax({
				url	: fixed_url,
				dataType : 'text',
				success : function(data) {
					var content = $(data).filter('#main');

					$.fancybox({
						'content' : content,
						'padding' : 20,
						'transitionIn'  : 'fade',
						'transitionOut' : 'fade'
					});
				}
			});
		});
	}

	
	/////////////////////////////////////////////////////////
	///////////////////// SOCIAL LINKS //////////////////////
	/////////////////////////////////////////////////////////
	
	// Center the social link hover info
	$('#social_links').find('span').each(function() {
		$(this).css({left: -($(this).width()/2 + $(this).parent('li').width()/2)});
	});
	
	$('#social_links').find('a').hover(function() {
		$(this).find('span').stop(true, true).fadeIn();
	}, function() {
		$(this).find('span').stop(true, true).fadeOut();
	});
	
	
	/////////////////////////////////////////////////////////
	//////////////////////// FIXES //////////////////////////
	/////////////////////////////////////////////////////////
	
	// Pagination
	
	$('.pagination').find('span.current').parent('li').addClass('active_pagination');
	
	// Fix single project embed dimensions
	
	var $single_project = $('.single_project');
	
	if ($single_project[0]) {
		fixWidth($single_project.find('iframe'));
	}
	
	function fixWidth(embed) {
		//var embed = $single_project.find('iframe');
		var embed_width = embed.width();
		var embed_height = embed.height();
		var main_width = embed.closest('div').width();
		
		embed.attr('scrolling', 'no');	// fix mobile resizing issue
		
		if (embed_width != main_width ) {
			var proportion = embed_height / embed_width;
			var percent_change = main_width / embed_height;
			var fixed_height = (embed_height * percent_change) * proportion;	
			$(embed).css({height: fixed_height, width: main_width});
		} else {
			return false;
		}
	}
	
	$('#blog_posts').find('iframe').each(function() {
		fixWidth($(this));
	});
	
	
	// Embeds on top of modals! NO!
	(function() {
		var embeds = document.getElementsByTagName('embed');
		if (embeds[0]) {
			window.onload = fix_flash();
			function fix_flash() {
				// loop through every embed tag on the site
				var embeds = document.getElementsByTagName('embed');
				for(i=0; i<embeds.length; i++)  {
					embed = embeds[i];
					var new_embed;
					// everything but Firefox & Konqueror
					if(embed.outerHTML) {
						var html = embed.outerHTML;
						// replace an existing wmode parameter
						if(html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
							new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i,"wmode='opaque'");
						// add a new wmode parameter
						else 
							new_embed = html.replace(/<embed\s/i,"<embed wmode='opaque' ");
						// replace the old embed object with the fixed version
						embed.insertAdjacentHTML('beforeBegin',new_embed);
						embed.parentNode.removeChild(embed);
					} else {
						// cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
						new_embed = embed.cloneNode(true);
						if(!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase()=='window')
							new_embed.setAttribute('wmode','opaque');
						embed.parentNode.replaceChild(new_embed,embed);
					}
				}
				// loop through every object tag on the site
				var elementToAppend = document.createElement('param');
				elementToAppend.setAttribute('name', 'wmode');
				elementToAppend.setAttribute('value', 'opaque');
				var objects = document.getElementsByTagName('object');
				for (var i = 0; i < objects.length; i++) {
					var newObject = objects[i].cloneNode(true);
					elementToAppend = elementToAppend.cloneNode(true);
					newObject.appendChild(elementToAppend);
					objects[i].parentNode.replaceChild(newObject, objects[i]);
				}
			} // End fix_flash
		} // End if
	})();

});
