// JavaScript Document

$(document).ready(function() {
	
		var main_container = $("#container");
		var featured_projects = $(".featured_projects");
		var floating_menu = $("#main_menu");
		var second_menu = $("#second_menu");
		var third_menu = $("#third_menu");
		var work_holder = $(".work_holder");
		var work_items = $(".work_holder .work");
		var back_button = $("#backbutton");
		var sortClass = "";
		var initial_load = true;
		var last_hash = "";
		var last_filter = "";
		var base_href = $("base").attr("href");
		//var scrollElem = scrollableElement('html', 'body');
		var scrollElem = 'html, body';
		var floatingmenutop = floating_menu.css("top");
		var floatingmenuoffset;
		var second_menu_in = false;
		var third_menu_in = false;
		var size;
		var widththreshold = 1600;
	
		
		//fader
		$(document).ready(function() {
			$('.featured_projects').cycle({
				fx:     'fade',
				before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
					
					$(nextSlideElement).find(".content").css({opacity:0, marginBottom: 0});
		
					
				}, 
				after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
					
					$(nextSlideElement).find(".content").animate({opacity: 1, marginLeft: 0}, 1500, "easeOutExpo");
					
					//$(currSlideElement).find(".huge").animate({opacity:0}, 500);
					
					
				},
				delay:  9000,
				speed: 1500,
				pause: 1,
				slideResize: true,
				containerResize: false,
				width: '100%',
				fit: 1
			})
		});
		
			// use the first element that is "scrollable"
		  function scrollableElement(els) {
			for (var i = 0, argLength = arguments.length; i <argLength; i++) {
			  var el = arguments[i],
				  $scrollElement = $(el);
			  if ($scrollElement.scrollTop()> 0) {
				return el;
			  } else {
				$scrollElement.scrollTop(1);
				var isScrollable = $scrollElement.scrollTop()> 0;
				$scrollElement.scrollTop(0);
				if (isScrollable) {
				  return el;
				}
			  }
			}
			return [];
		  }
				
		
		// Fix filter URL
		
		$(".single_container .work_nav, #main_menu li a").each(function() {
			var fixedURL = $(this).attr("href").substr(1);	
			$(this).attr("href", fixedURL);
		});
		
		function getMenuOffset() {
			if ($(window).width() >= widththreshold) {
				size = "large";
				floatingmenuoffset = 402;
			} else {
				size = "small";
				floatingmenuoffset = 300;
			}	
			
			//floating_menu.css("top", floatingmenuoffset);
			
		}
		
		// ISOTOPE 
		
		getMenuOffset();
		
		floatingmenutop = floatingmenuoffset;
		
		$(window).resize(function() {
			
			getMenuOffset();
			//adjustfloatingmenu();
			$('.work_holder').isotope('reLayout');
			$('#three_wrapper').isotope('reLayout');
			
		});
	
		$(window).load(function() {
		
		// hash change event
	
		$(window).hashchange( function(){
			
			if (last_hash == "#") {
				last_hash = "#Home";
			}
			
			//back_button.attr("href", last_hash);	
	
			last_hash = location.hash;
			
			
			if(location.hash == "#Home" || location.hash.indexOf("#Home") != -1) {
				window.location.hash = 'Home';
				//page change animation
	
				$(".single_container").animate({'opacity' : 0}, 600, function() {
					anim_home_in();
				});
			} else {
				loadhashpage();
			}
			
		})
		
		// onload
		
		
		if (window.location.hash == "" || window.location.hash == "#Home") {
			window.location.hash = 'Home';
			last_hash = 'Home';
			anim_home_in();
			
		} else {
			loadhashpage();
		}
	
	
				
		$('.work_holder').isotope({
				  // options
				  itemSelector : '.work',
				  hiddenStyle : { opacity : 0, scale : 1 } 
		 });
		 
		});
				
			function doIsotope(sortClass) {
								
						floatingmenutop = floatingmenuoffset / 2.55;	
						adjustfloatingmenu();
						
						$(".work").addClass("expanded");
						$(".work .label").fadeTo(250,1);
						
						var $newItems = $('.work.to_add.' + sortClass);
						$newItems.removeClass("to_add");
						$newItems.children("img").each(function() {
							var newsrc = $(this).attr("data");
							$(this).attr("src", newsrc)	;
									
						});
						
					
						$('.work_holder').isotope({ filter: sortClass }, function() {
								work_items = $(".work_holder .work");
								//siblingEffect(work_items);
								adjustfloatingmenu();
								
						});
						
						
						
						
						if ($newItems) {
							$('.work_holder').isotope( 'insert', $newItems, function() {
						
							});
						}	
								
				
				//last_filter = sortClass;	
			}

	
	
	
	
	function loadhashpage() {
		
		//alert(window.location.hash);
		URLSegment = window.location.hash.substr(6);
		
		if
		(window.location.hash.indexOf("Work") != -1) {
			//load single work
			loadcontent(URLSegment);
			
			$(".main_menu li").removeClass("current");
			$(".main_menu li.home").addClass("current");
			
		} 
		else if
		(window.location.hash.indexOf("Page") != -1) {
			//load single work
			$(".main_menu li").removeClass("current");
			$(".main_menu li." + URLSegment).addClass("current");
			loadpage(URLSegment);
			
			third_menu.find("a").stop(true,true).not("." + URLSegment).animate({"color" : "#869ca5"}, 150);
			third_menu.find("a." + URLSegment).stop(true,true).animate({"color" : "#FFFFFF"}, 150);
		
		
			//singlecontent(window.location.hash.substr(6));
		} 
		else if
		(window.location.hash.indexOf("Sort") != -1) {
			//load filter
			sortClass = "." + URLSegment;
			
			//remove all current non-def tags from menu
			$(".temp_tag").fadeTo(250,0, function() {
				$(this).slideUp(250, function() {
					$(this).remove();	
				});
			});
			
			//check if non-default tag
			var non_default = true;
			
			floating_menu.children("li").not(".temp_tag").each(function() {
				if($(this).children("a").hasClass(sortClass.substr(1))) {
					non_default = false
				}
			});
			
			if (non_default == true) {
				var theTag = sortClass.substr(1);
				var newTag = '<li class="temp_tag"><a href="#Sort/'+theTag+'" class="'+theTag+'">'+theTag+'</a></li>'
				floating_menu.find("a").animate({"color" : "#869ca5"}, 150);
				floating_menu.prepend(newTag).fadeTo(250,1);
			}
			
			//check if initial load
			if (initial_load == true) {
				anim_home_in(true);
			} else {
				//check if coming from work page
				if (!$(".single_container").css("opacity") || $(".single_container").css("opacity") == 0) {
						
						doSorting(sortClass);
				} else {
					$(".single_container").animate({'opacity' : 0}, 600, function() {
						anim_home_in();
						doSorting(sortClass);
					});	
				}
				
			}
			
		}
			
	}
	
	function doSorting(sortClass) {
		
		
		
		$("#main_menu li a").not(sortClass).animate({"color" : "#869ca5"}, 150);
		$("#main_menu li a" + sortClass).animate({"color" : "#FFFFFF"}, 150);
		
		if ($(".featured_projects").hasClass("featureHidden")) {
			
				$(scrollElem).animate({scrollTop: 0}, 400, function() {
					doIsotope(sortClass);
				});	
	
		
		} else {
			
			$(scrollElem).animate({scrollTop: 0}, 400, function() {
				$(".featured_projects").animate({"bottom": "200px", 'opacity' : 0, 'height' : 0, 'margin-bottom' : 0}, 1000, 'easeInOutExpo', function() {
				doIsotope(sortClass);
				$(this).addClass("featureHidden");
				});
			});

			
		}
	}
	
				
	// animations
	
	function anim_out() {
		
		work_holder.animate({opacity:0}, 600);
		main_container.children(".single_container").animate({opacity:0}, 600);
			
	}
	
	function anim_menu_out(menu) {
		
		if (menu == second_menu) { 
			second_menu_in = false;
		}
		
		if (menu == third_menu) { 
			third_menu_in = false;
		}
		
		menu.children("li").each(function(index) {
			$(this).stop().delay(80 * index).show().animate({"margin-left": "-200px", 'opacity' : 0}, 600, 'easeInExpo', function() {
			});
		})
	}
	
	function anim_menu_in(menu) {
		if (menu == second_menu) { 
			second_menu_in = true;
		}
		
		if (menu == third_menu) { 
			third_menu_in = true;
		}
		
		menu.show();
		menu.children("li").css({"margin-left": "-200px", 'opacity' : 0});
		menu.children("li").each(function(index) {
			$(this).delay(80 * index).show().animate({"margin-left": "0px", 'opacity' : 1}, 600, 'easeOutExpo');
		})
		
	}
	
	function anim_home_in(callback) {
		
		//$('.work_holder').isotope('reLayout');
		
		if (!featured_projects.hasClass("featureHidden")) {
			floatingmenutop = floatingmenuoffset;
		}
		
		adjustfloatingmenu();
		
		initial_load = false;
		
		$(".main_menu li").removeClass("current");
		$(".main_menu li.home").addClass("current");
		
		//scroll to top
		$(scrollElem).animate({scrollTop: 0}, 400);
		
		//remove any stray containers
		main_container.children(".single_container").remove();	
		
		work_holder.show();
		
		
		work_holder.css({opacity:1});
		work_items.css({opacity:0});

		anim_menu_out(second_menu);
		anim_menu_out(third_menu);
		
		if (!featured_projects.hasClass("featureHidden")) {
			
			featured_projects.show();
				
		}
			
			featured_projects.css({"bottom": "200px", 'opacity' : 0})
			featured_projects.stop().delay(100).animate({"bottom": "0", 'opacity' : 1}, 1000, 'easeOutExpo', function() {
			
				anim_menu_in(floating_menu);	
				
				if (callback) {
					
					//isotope callback (kinda) after home anim
					
					doSorting(sortClass);
					
				}
				
			});
			

		$('.work_holder').isotope('reLayout');
		
	
			work_items.not(".isotope-hidden").each(function(index) {
				$(this).stop().delay(200 * index).fadeTo(250,1);
			});
		
	
	}
	
	//sibling highlight effect
	function siblingEffect(where) {
		where.not(".hasSiblingEffect").hover(
			function(){
			
						//$(this).stop().fadeTo(200,0.5);
	
			},
			
			function(){
	
					
						//$(this).stop().fadeTo(200,1);
		
		});
		

	}
	work_items = $(".work_holder .work");
	siblingEffect(work_items);
	
	// AJAX (Spray & Wipe) Functions! //
	
	function loadpage(url) {
		
		//floatingmenutop = floatingmenuoffset / 2.15;	
		//adjustfloatingmenu();
		
		anim_out();
		$(scrollElem).animate({scrollTop: 0}, 400);
		
		
		
		featured_projects.stop().delay(100).animate({"bottom": "200px", 'opacity' : 0}, 600, 'easeInOutExpo', function() {
				
				getMenuOffset();
				floatingmenutop = floatingmenuoffset / 1.4;	
				adjustfloatingmenu();
				anim_menu_out(floating_menu);
				anim_menu_out(second_menu);
				
				if (url == "contact") {
					anim_menu_out(third_menu);
				}
	
				//single content load complete
				work_holder.hide();
				featured_projects.hide();
				
				var loadthis = url;
				
				var oldcontainer = main_container.children(".single_container")
				var single_container = $("<div>");
				
				single_container.addClass("single_container");
				single_container.appendTo(main_container);
				main_container.append('<div class="clear"></div>');
				single_container.css({'opacity' : 0});
			
			
				single_container.load(loadthis, function() {
					
					if (loadthis == "about") {
						//$('#third_menu li a').stop(true,true).animate({"background-color" : "#b1d5d7"}, 250);
					} else {
						//$('#third_menu li a').stop(true,true).animate({"background-color" : "#0c394a"}, 250);
					}
					
					
					
					oldcontainer.remove();
					
					$('#three_wrapper').isotope({
							  // options
							  resizable: false,
							  itemSelector : '.three_col',
							  hiddenStyle : { opacity : 0, scale : 1 } 
					});
					
					if (url == "people") {
						$(".person:nth-child(3)").css({marginTop :58});
						$(".person").css({"opacity" : 0});
					}
					
					
					
					single_container.animate({'opacity' : 1}, 600, 'easeInExpo', function() {
						
						if (url == "people") {
							$(".person").delay(600).each(function(index) {
								$(this).delay(150 * index).animate({"opacity" : 1}, 200, "easeOutExpo");
							})
						}
						
						
						if (!third_menu_in && url != "contact") {
							anim_menu_in(third_menu);
						}
						
						if (!second_menu_in && url == "contact") {
							anim_menu_in(second_menu);
						}
						
					});
					
				});
				
		});
			
	}
	
	function loadcontent(url) {
			
			anim_out();
			
			floatingmenutop = floatingmenuoffset / 2.5;
			
			second_menu.css("top", floatingmenutop);
			
			featured_projects.stop().delay(100).animate({"bottom": "200px", 'opacity' : 0}, 600, 'easeInExpo', function() {
	
				//anim menu out if showing
				anim_menu_out(floating_menu);
				
				//scroll to top
				//alert("scroll to top");
				$(scrollElem).animate({scrollTop: 0}, 400);
				
				var loadthis = url;
				
				var oldcontainer = main_container.children(".single_container")
				var single_container = $("<div>");
				
				single_container.addClass("single_container");
				
				single_container.appendTo(main_container);
			
				main_container.append('<div class="clear"></div>');
				
				single_container.css({'opacity' : 0});
			
				single_container.load(loadthis, function() {
					
					oldcontainer.remove();
					
					//create dynamic links
					
					//createWorkLinks($(".single_container .work_nav"));
					
					siblingEffect($(".relatedClient"));
					siblingEffect($(".taglist li"));
					
					//fix url
					
					$(".single_container .fix_me").each(function() {
						var fixedURL = $(this).attr("href").substr(1);	
						$(this).attr("href", fixedURL);
					});
					
					
					
					//single content load complete
					work_holder.hide();
					featured_projects.hide();
					
					adjustfloatingmenu();
					
					$(".work_images div").css({'opacity' : 0});
					$(".work_images div").each(function(index) {
						$(this).delay(300 * index).fadeTo(350,1);	
					});
				
					single_container.animate({'opacity' : 1}, 600, 'easeInExpo', function() {
						
						if (!second_menu_in) {
							anim_menu_in(second_menu);
						}
						
					});
					
				});
			
			});
		}
	
	
	
	// END AJAX, you are now squeaky clean //
	
	
	
	// Newsletter 
	
	$(".magicmail").css({opacity: 0});
	$(".magicmail input, .magicmail button").css({opacity: 0, bottom: 20});
	
	$(".magicmail input.text").click(function(){
		$(this).select();
	});
	
	$(".newsletter").mouseover(function(event){
		event.preventDefault();
		$(".magicmail").stop().show().animate({opacity: 1}, 500, "easeOutExpo");
		$(".magicmail .element").each(function(index){
			$(this).stop().delay(index * 100).animate({opacity: 1, bottom: 0}, 300, "easeOutExpo");	
		});
	})
	
	$(".magicmail").mouseleave(function(event){
		event.preventDefault();
		$(".magicmail").stop().show().animate({opacity: 0}, 500, "easeOutExpo");
		$(".magicmail input, .magicmail button").stop().animate({opacity: 0, bottom: 20}, 300, "easeOutExpo");	
		
	})
	
		
	
	// Variables
	floatingmenu = $(".floating_menu");
	
	// Floating menu
	scrollspeed = 1200;
	
	// Scroll into view 
	$(window).bind('scrollstop', function(){
		adjustfloatingmenu();
	});
	
	
	
	function adjustfloatingmenu() {
			
			difference = ($(window).scrollTop() - floatingmenutop);
			if (difference > 0) {
				floatingmenu.stop().animate({'top' : floatingmenutop + difference}, scrollspeed, 'easeOutExpo')
			} else {
				floatingmenu.stop().animate({'top' : floatingmenutop}, scrollspeed, 'easeOutExpo')
			}
		}
	
	// Main menu stuff
	speed = 200;
	
	$("#main_menu li a").click(function(event){
		//event.preventDefault();
		last_filter = $(this).attr("href");
		$(this).animate({"color" : "#FFFFFF"}, 150);
		$(this).parent().siblings().children("a").animate({"color" : "#869ca5"}, 150);
	}); 
	
	//back button
	$("#second_menu li a").click(function(event){
				
		event.preventDefault();
		//window.location.hash = $(this).attr("href");
		window.location.hash = "Home";
	}); 
	
	$(".floating_menu li").hover(
		function() {
			//mouseover
			hovered = $(this);
			$(this).find("a").stop().animate({'margin-left' : 20}, speed);
		},
		
		function() {
			//mouseout	
			$(this).find("a").stop().animate({'margin-left' : 0}, speed);
		}
		
	);
	
	
});



// Special Scroll functions

(function(){
 
    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);
 
    special.scrollstart = {
        setup: function() {
 
            var timer,
                handler =  function(evt) {
 
                    var _self = this,
                        _args = arguments;
 
                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'scrollstart';
                        jQuery.event.handle.apply(_self, _args);
                    }
 
                    timer = setTimeout( function(){
                        timer = null;
                    }, special.scrollstop.latency);
 
                };
 
            jQuery(this).bind('scroll', handler).data(uid1, handler);
 
        },
        teardown: function(){
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
        }
    };
 
    special.scrollstop = {
        latency: 300,
        setup: function() {
 
            var timer,
                    handler = function(evt) {
 
                    var _self = this,
                        _args = arguments;
 
                    if (timer) {
                        clearTimeout(timer);
                    }
 
                    timer = setTimeout( function(){
 
                        timer = null;
                        evt.type = 'scrollstop';
                        jQuery.event.handle.apply(_self, _args);
 
                    }, special.scrollstop.latency);
 
                };
 
            jQuery(this).bind('scroll', handler).data(uid2, handler);
 
        },
        teardown: function() {
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
        }
    };
 
})();
