var currenturl = null;
$(document).ready(function() {
	if(document.location.hash!=''){
		gotohashpage(document.location.hash);
	}else{
		/* Have a huge delay before the initial slideshow starts.
		 * I personally think this is pure GENIUS and I wish I'd thought 
		 * of this gem of usability. */
		window.setTimeout(function(){
			loadPage('#/main.lasso');
			},1500); 
	}

	$('#subnav>ul>li>a').click(function() {
		if(!$(this).is('.active') && !$(this).parent().parent().is('#sites')) {
			$('#subnav>ul>li>a').removeClass('active');
			$(this).addClass('active');
			loadPage($(this).attr('href'));
		}
	});
	
	mainNav();
	subNav();
	siteLinks();
	controlAction();	
	handleHistory();
});

var loopImg;

function mainNav() {
	$('#mainnav>ul>li>a').click(function() {
		gotohashpage($(this).attr('href'));
	});
}

function subNav() {
	$('#mainnav>ul>li>ul>li>a').click(function() {
		gotohashpage($(this).attr('href'));
	});
}

function siteLinks() {
	$('.site_collage').live('mouseover', function() {
		$(this).animate({opacity: '0.4'}, 170);
	});
	$('.site_collage').live('mouseout', function() {
		$(this).animate({opacity: '1'}, 1000);
	});	
}

var slideshowspeed = 2000; /* ms between image changes */
function slideShow() {
	if($('#slideshow').is('.controls')) {
		$('#controls').remove();
		$('#slideshow').append('<ul id="controls"></ul>');
		$('#slideshow>img').each(function(i) {
			$('#slideshow>ul').append('<li><a href="#" rel="'+i+'"></a></li>');
		});
	}
	$('#slideshow>ul>li>a:first').addClass('current');
	clearInterval(loopImg);
	$('a').click(function() {clearInterval(loopImg);});
	loopImg = setInterval(function() {
		var current = $('#slideshow>#controls>li>a.current');
		current.removeClass('current');
		current.parent().next().children().addClass('current');

		var last = $('#txt>#slideshow>img:visible:last');
		if(last.attr('src')!=$('#txt>#slideshow>img:visible:first').attr('src')) {
			last.fadeOut(1000);
		}
		

		/* stop looping if there's a description OR if there's a no-repeat class */
		if($('#desc').size()>0 || $('#slideshow.no-repeat').size()>0) {
			if(last.prevAll().size()==1 || last.prevAll().size()==0) {
				clearInterval(loopImg);
				if($('#txt>#slideshow>#desc').size()>0){
					$('#txt>#slideshow>#desc').animate({width: '280'}, 1000, function() {$(this).children().fadeIn();});
				} else if($('#slideshow.gotofirst').size()>0){
					setTimeout(function() {
					$('#txt>#slideshow>img').not(':last').fadeOut(1000);
					$('#txt>#slideshow>img:last').fadeIn(1000);
						$('#slideshow>#controls>li>a.current').removeClass('current');	
						$('#slideshow>#controls>li>a:first').addClass('current');
					}, slideshowspeed);
				}
			}
		} else {
			if(last.prevAll().size()==0) {
					setTimeout(function() {
					$('#txt>#slideshow>img:last').fadeIn(1000, function() {
						$('#txt>#slideshow>img').fadeIn('def');
					});
				}, 500);
				
			}
		}
		
	}, slideshowspeed);
}

function controlAction() {
	$('#slideshow>#controls>li>a').live('click', function() {
		clearInterval(loopImg);
		$('#slideshow>#controls>li>a.current').removeClass('current');	
		$(this).addClass('current');
		$('#txt>#slideshow>img, #txt>#slideshow>#desc').hide();
		$('#txt>#slideshow>#desc').children().hide();		
		$('#txt>#slideshow>#desc').css('width','2px');

		var i = ($('#slideshow>img').size() - $(this).attr('rel') - 1);
		
		var image = $('#txt>#slideshow>img:eq('+i+')');
		
		if(image.attr('src') == $('#txt>#slideshow>img:first').attr('src')) {
			$('#txt>#slideshow>#desc').animate({width: '280'}, 1000, function() {$(this).children().fadeIn();});
			image.fadeIn();
		}
		else {
			image.fadeIn();
		}
		
		return false;
	});
}

function loadPage(link) {
	var url = link;
	url=url.split('/');
	url='_content/'+url[url.length-1];
	$('#txt').fadeOut(700,
		function(){
			$(this).empty();
			$(this).load(url, function() {

			if ($('#txt>#slideshow').size() != '0') {
					$('#txt>#slideshow img').imgpreload(function(){
						if(backuptimeout>0) //check if the other timeout hasn't fired yet
							{
								clearTimeout(backuptimeout);
								var tmptimeout = window.setTimeout(function(){
									$('#txt').fadeIn(700,slideShow);
									},100); //small timeout to make sure the images are actually loaded
							}
						});
					//If for some reason an image won't load (404's, network error, IE user, show everything anyway after 5 secs)
					var backuptimeout = window.setTimeout(function(){
							$('#txt').fadeIn(700,slideShow);
							backuptimeout = 0;
									},5000);
			}else{
				$(this).fadeIn(700);
			}
		});
	});
}

function fadeLi(element) {
	if(element=='#'){
		return false;
		}
	$(element+'>li').hide();
	$(element).show();
	$(element+'>li:first').fadeIn(200, function() {loopLi(element);});
		
}

function loopLi(element) {
	$(element+'>li:visible:last').next().fadeIn(200, function() {loopLi(element);});
}

function handleHistory(){
		$(window).hashchange(function() { checkUrlChange(location.hash) });
		$('a[href^=#]').live('click',function(){
			currenturl=$(this).attr('href');
			});
	}
function checkUrlChange(){
	if(document.location.hash!=currenturl && document.location.hash!=''){
		gotohashpage(document.location.hash);
		currenturl=document.location.hash;
		}
	}
function gotohashpage(hash){
	/* do some magic to show the right menus */
	/* this might not be the best way to do this, but meh */
	$('#subnav, #mainnav').stop(true, true);
	var hashchunks=hash.split('/');
	hashchunks.shift(); /* get rid of # */
	if(hashchunks.length>1){
		$('#mainnav>ul>li>a.active').removeClass('active');
		$('#mainnav>ul>li>ul>li>a.active').removeClass('active');
		$('#'+hashchunks[0]).prev().addClass('active');
		
		if(!$('#'+hashchunks[0]).is(':visible'))	{
				$('#mainnav>ul>li>ul:visible').slideUp();
				$('#'+hashchunks[0]).children().hide();
				listitemheight = 19; /* calculate list height */
				listheight = 30-listitemheight; /* margin height - height of 1 child */
				
				$('#'+hashchunks[0]).children().each(function(){
					listheight+=listitemheight;
				});
				$('#'+hashchunks[0]).css('height','0px').animate(
					{height: listheight+'px'},
					500,
					'linear', 
					function() {
					fadeLi('#'+hashchunks[0]);
				});
			}
		/* handle exception where menu is in the other div */
		if($('#mainnav>ul>li>a[rel='+hashchunks[0]+']').size()>0){
			$('#mainnav>ul>li>a[rel='+hashchunks[0]+']').addClass('active');
			$('#subnav a.active').removeClass('active');
			}

		
			


		if(hashchunks.length>2){
			$('a[rel='+hashchunks[1]+']').addClass('active');
			if($('#'+hashchunks[1]).size()>0) {
				if(!$('#'+hashchunks[1]).is(':visible')){
					if($('#subnav>ul').is(':visible')) {
						$('#subnav>ul:visible').fadeOut(1000, function() {
							$('#subnav').css("background-color", "#191818");
							fadeLi('#'+hashchunks[1]);
						});
					}
					else {
						$('#subnav').css("background-color", "#191818");
						fadeLi('#'+hashchunks[1]);
					}
				}
				$('#subnav a.active').removeClass('active');
				$('#subnav a[href='+hash+']').addClass('active');
			}
		} else
		{
			/* get rel="" value for link */
			var activeid = $('a[href='+hash+']').attr('rel');
			if(activeid!=''){
				if(!$('#subnav #'+activeid).is(':visible')){
					
					$('#subnav>ul').hide();
					if($('#subnav>#'+activeid).size()>0){					
						$('#subnav').css("background-color", "#111");
						fadeLi('#'+activeid);
						}else{
						$('#subnav').css("background-color", "#191818");
						}
					}
					$('#subnav>ul a.active').removeClass('active');
			}else{
				//hide everything except the ul containing the active class
				
				$('a[href='+hash+']').addClass('active');
				$('#subnav>ul:not(a.active)').hide();
				$('#subnav a.active').parent().parent().show();
			}
		}
		

		
		}else{ /*shorter hashes */

			if(!$('#mainnav a[href='+hash+']').next().is(':visible')){
				$('#mainnav>ul>li>ul:visible').slideUp();
			}
			$('#mainnav a.active').removeClass('active');
			$('#mainnav a[href='+hash+']').addClass('active');

			if($('#mainnav a[href='+hash+']').next().is('ul') && !$('#mainnav a[href='+hash+']').next().is(':visible')){
				var listing	= $('#mainnav a[href='+hash+']').next().attr('id');
				
					$('#'+listing).children().hide();
					listitemheight = 19; /* calculate list height */
					listheight = 30-listitemheight; /* margin height - height of 1 child */
					
					$('#'+listing).children().each(function(){
						listheight+=listitemheight;
					});
					$('#'+listing).css('height','0px').animate(
						{height: listheight+'px'},
						500,
						'linear', 
						function() {
						fadeLi('#'+listing);
					});
				}
				
			
			/* handle exception where menu is in the other div */
			/* get id to show */
			var idtoshow = $('#mainnav a[href='+hash+']').attr('rel');
			if(idtoshow!=''){
				//$('#subnav').css("background-color", "#111");
				$('#subnav ul:not(#'+idtoshow+')').hide();
				$('#subnav .active').removeClass('active');
				if(!$('#'+idtoshow).is(':visible')){
					$('#subnav').css("background-color", "#111");
					fadeLi('#'+idtoshow);
					}
				}else{
					$('#subnav').css("background-color", "#191818");
					$('#subnav ul').hide();
				}
			
		}
	$('a[href='+hash+']').addClass('active');
	/* load right page */
	loadPage(hash);
	}
// http://farinspace.com/2009/05/jquery-image-preload-plugin/
function imgpreload(imgs,settings)
{
	// settings = { each:Function, all:Function }
	if (settings instanceof Function) { settings = {all:settings}; }

	// use of typeof required
	// https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Instanceof_Operator#Description
	if (typeof imgs == "string") { imgs = [imgs]; }

	var loaded = [];
	var t = imgs.length;
	var i = 0;

	for (i; i<t; i++)
	{
		var img = new Image();
		img.onload = function()
		{
			loaded.push(this);
			if (settings.each instanceof Function) { settings.each.call(this); }
			if (loaded.length>=t && settings.all instanceof Function) { settings.all.call(loaded); }
		};
		img.src = imgs[i];
	}
}

if (typeof jQuery != "undefined")
{
	(function($){
		$.imgpreload = imgpreload;
		$.fn.imgpreload = function(settings)
		{
			settings = $.extend({},$.fn.imgpreload.defaults,(settings instanceof Function)?{all:settings}:settings);
			this.each(function()
			{
				var elem = this;
				imgpreload($(this).attr('src'),function()
				{
					if (settings.each instanceof Function) { settings.each.call(elem); }
				});
			});
			var urls = [];
			this.each(function()
			{
				urls.push($(this).attr('src'));
			});
			var selection = this;
			imgpreload(urls,function()
			{
				if (settings.all instanceof Function) { settings.all.call(selection); }
			});
			return this;
		};
		// public
		$.fn.imgpreload.defaults =
		{
			each: null // callback invoked when each image in a group loads
			, all: null // callback invoked when when the entire group of images has loaded
		};
	})(jQuery);
}
