(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function(imgs) {
    var args_len = imgs.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = imgs[i];
      cache.push(cacheImage);
    }
  };
})(jQuery);

$(document).ready(function(){

//	$("#mainNav").before("loc: " + window.location + "<br/>");
	
	var defaultNav		= "productions",	// Front page
		currentNav 		= null,				// Most recent top-level navigation
		currentSubNav 	= null,				// Most recent sub-menu navigation
		fadeOutSpeed 	= 300,				// Transitional speeds in ms for page navigation
		fadeInSpeed 	= 300,
		backClass 		= "td.backMagic",	// Specification for where to bind background image events
		backMagic		= true,				// Background image events are disabled w/ this flag during fades
		recentHash		= "",
		
		backMenu		= "productions",
		backgammon		= ["pluck", "sacred", "new", "stops", "sandy", "1001", "loop"],
		backImages		= ".bkgimages",
		backRecent		= "",
		
		vimeoWidth		= 1000, //1000,
		vimeoHeight		= 750, //750,

		// Bind events to menu showing background images on mouseover
		bindBackgroundEvents = function() {
		
			$(backClass + ' > a').mouseenter(function(){
				
				if(backMagic) {
					var index = $(backClass + ' > a').index(this);
					$(backImages).hide();
					if(index >= 0) {
						$(backImages + ":eq(" + index + ")").show();
					}
				}
			});

			$(backClass + ' > a').mouseleave(function(){
				if(backMagic) {
					$('.bkgimages').hide();
				}
			});

		},
	
	

		checkBackground = function(content) {
			if(content !== backRecent) {
				for(var i=0, j=backgammon.length; i<j; i++){
					if(content === "#" + backMenu + "-" + backgammon[i]) {
						$(backImages).fadeOut(5000);
						$(backImages + ":eq(" + (i + 7) + ")").fadeIn(5000);					
					} 
				}
				backRecent = content;
			};
		},

	
		// Resize background images dynamically
		measureWindow = function(){

			bindBackgroundEvents();
			$(window).resize(_IMGresize);

			function _IMGresize(){

				$("#wrapper").css('height', '100%');

				var container   = $(backImages),
					imageWidth	= 800,
					imageHeight	= 600,
					winW		= $(window).width(),
					winH		= $(window).height(),
					imgW		= 0,
					imgH		= 0,
					leftOffset	= 0,
					topOffset	= 0,
					imgRatio	= imageWidth/imageHeight,
					winRatio	= winW/winH;

				container.css("top",0).css("left",0).css("height",601).css("width",801);

				if(imgRatio >= winRatio) {
					imgH = winH;
					imgW = imgH * imgRatio;
					$(".bkgimages IMG").width(imgW).height(imgH);
					leftOffset = (imgW-winW) / -2;
				} else {
					imgW = winW;
					imgH = imgW / imgRatio;
					$(".bkgimages IMG").width(imgW).height(imgH);
					topOffset = (imgH-winH) / -2;
				}
				
				container.css("left",leftOffset).css("width",imgW).css("top",topOffset).css("height",imgH);
			};

			_IMGresize();
			$(backClass).css('visibility','visible').show();
		},
	
	
		// Highlight current page and sub-page on top bars
		highlightCurrentNav = function(){
			$("#mainNav > a").css("color", "");
			$("#mainNav > a[href='#" + currentNav + "']").css("color", "#ffffff");
			if(currentSubNav) {
				$("#subNav > a").css("color", "");
				$("#subNav > a[href='#" + currentNav + "-" + currentSubNav + "']").css("color", "#ffffff");
			}
		},
	


		disableSelection = function(target){
		    if (typeof target.onselectstart !== "undefined") {  // IE
		        target.onselectstart = function(){ return false; };
			}
		    else if (typeof target.style.MozUserSelect !== "undefined") {  // Firefox
		        target.style.MozUserSelect = "none";
			}
		    else { // Opera, etc
		        target.onmousedown = function(){ return false; };
			}
		    target.style.cursor = "default";
		},

	
		// Bind events to navigation links
		bindNavEvents = function(targetObj) {

			// Bind to any suitable anchor tags within the given selector
			$(targetObj + " a.nav").bind("click", function(){

				// Prevent extra backgrounds from displaying or hanging around
				backMagic = false;

				// Figure out where link wants to go
				var href   = $(this).attr("href").substr(1);
				var target = (href.indexOf("-") === -1) ? [href] : href.split("-");
			
				// Send it there
				navigateTo(target);

				// Prevent link from reloading page
				return false;
			});
		
			// Bind events for background images
			bindBackgroundEvents();	
			
		},
		
		
		// Bind events to shadowbox links
		bindShadowbox = function() {
			
			Shadowbox.clearCache();
		    var el = ($("div#content > p > a.shadow").get());
		    for (var i = 0; i < el.length; i++) {
				Shadowbox.addCache(el[i]);
		    }
			var imgs = [];
			$("div#content > p > a.shadow").each(function(){
				imgs.push($(this).attr("href"));		
			});
			$.preLoadImages(imgs);
		},


		// Swap out content with nifty fades
		fadeChange = function(target, source, delay) {
			
			$(target).fadeOut(fadeOutSpeed, function() {
				
				// Swap out content between fades
				$(target).html($(source).html());
				
				// Check for embedded vimeo & replace markup with embed code
				$(target + " > div.vimeo").each(function() {
					var vid = $(this).html();
					$(this).html('<iframe src="http://player.vimeo.com/video/' + vid + '?title=0&amp;byline=0&amp;portrait=0" width="' + vimeoWidth + '" height="' + vimeoHeight + '" frameborder="0"></iframe>').show();
				});
							
				// Delay the fade-in if there wasn't any content to fade out in the first place
				if(delay){
					var func = function(target, source) {
						$(target).fadeIn(fadeInSpeed, function(){ backMagic = true; });
						if(target==="#content") { checkBackground(source); }
					};
					window.setTimeout(func, fadeInSpeed, target, source);				

				// Otherwise fade it in straightaway
				} else {
					$(target).fadeIn(fadeInSpeed, function(){ backMagic = true; });
					if(target==="#content") { checkBackground(source); }
				}
				highlightCurrentNav();
				bindNavEvents(target);
			});
		},
	
	
		// Navigate to a particular page
		navigateTo = function(target) {

			var nav      	= target[0] || "productions",
				subNav   	= target[1] || null,
				hasSub   	= $("#" + nav + "-subNav").length > 0,
				prevNav  	= currentNav,
				prevSub  	= currentSubNav,
				prevHasSub  = $("#" + prevNav + "-subNav").length > 0,
				defaultSub 	= $("#" + nav + "-default").length > 0,
				delay		= !prevHasSub || (prevNav === "productions" && prevSub === null);

			// Default lower-level nav?
			if(defaultSub && subNav === null) {
				subNav = $("#" + nav + "-default").html();
			}
				
			// Lower level nav link (sub-category)
			if(subNav){
				if(nav !== prevNav || delay) {
					fadeChange("#subNav", "#" + nav + "-subNav", delay);
				}
				fadeChange("#content", "#" + nav + "-" + subNav, false);
				window.setTimeout(bindShadowbox, fadeOutSpeed + 100);
				
				currentNav	  = nav;
				currentSubNav = subNav;

				highlightCurrentNav();
			}

			// Top-level nav link
			if(!subNav) {
		
				currentNav 	  = nav;
				currentSubNav = null;

				// Show new sub-pages navbar, if one exists
				if (nav !== "productions" && $("#" + nav + "-subNav").length > 0){
					// Yeah, it does
					fadeChange("#subNav", "#" + nav + "-subNav", delay);
				} else {
					// Nope, it doesn't 
					$("#subNav").fadeOut(fadeOutSpeed);
				}
				// Fade in new content
				fadeChange("#content", "#" + nav, false);
				window.setTimeout(bindShadowbox, fadeOutSpeed + 100);
			}
		
			// Update the window hash
			location.hash = recentHash = "#" + nav + ((subNav) ? "-" + subNav : "");
		
		};
		
	
	// Check for hash changes to enable back button in browser
	$(window).hashchange(function(){
		var hash   = location.hash.replace("#", "");
		recentHash = hash = (hash==="") ? defaultNav : hash;
//		$("#mainNav").before("RECENTHASH: " + recentHash + " / HASH: " + hash + "<br/>");

		navigateTo((hash.indexOf('-') !== -1) ? hash.split('-') : [hash]);
	});

	// Bind top level navigation & front-page image resizer (init)
	bindNavEvents("#mainNav");
	measureWindow();

	disableSelection(document.getElementById("mainNav"));
	disableSelection(document.getElementById("subNav"));

	var imgs = [];
	$("li > img").each(function(){
		imgs.push($(this).attr("src"));		
	});
	$.preLoadImages(imgs);

	$(window).hashchange();
//	navigateTo(["productions-sacred"]);
});



