/* to do: make sure all transitions are css3 where supported */

var currenturl = null;
$(document).ready(function() {
	if(document.location.hash!=''){
		gotohashpage(document.location.hash);
	}else{
		/* Have a huge delay before the initial slideshow starts, that way
		 * people will think the site failed to load and hit refresh. */
		window.setTimeout(function(){
			loadPage('#/main.lasso');
		},1500); 
	}

/*
	$('#subnav>ul>li>a').click(function() {
		if(!$(this).is('.active') && !$(this).parent().parent().is('#sites') || $(this).parent().parent().is('.forcereload')){
			$('#subnav>ul>li>a').removeClass('active');
			$(this).addClass('active');
			loadPage($(this).attr('href'));
		}
	});
*/
	
	mainNav();
	subNav();
	subsubNav();
	subsubsubNav();
	siteLinks();
	controlAction();	
	handleHistory();
	browserDetect();
	contactForm('#newsletterform');
	
});

function browserDetect(){
	var deviceAgent = navigator.userAgent.toLowerCase();
	var iCrap = deviceAgent.match(/(iphone|ipod|ipad|iprobe)/);
	if (iCrap) {
 		/* iPads are slow, jQuery 1.4.3 added a feature to change animation speed
 		 * i haven't been able to test what the best value if on the actual hardware,
 		 * this is just a guess */
 		/* jQuery.fx.interval = 50;*/
 		}
	cssTransitions = $.support.cssProperty('transition');
	//cssTransitions = false; /* disabled css transitions for now */
	//window.alert('Using css transitions? '+cssTransitions);
	}
$.support.cssProperty = (function() {
  function cssProperty(p, rp) {
    var b = document.body || document.documentElement,
    s = b.style;

    // No css support detected
    if(typeof s == 'undefined') { return false; }

    // Tests for standard prop
    if(typeof s[p] == 'string') { return rp ? p : 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 rp ? (v[i] + p) : true; }
    }
  }

  return cssProperty;
})();
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 subsubNav() {
	$('#subnav>ul>li>a').click(function(){
		$('#subnav>ul>li>ul:visible').slideUp();
		gotohashpage($(this).attr('href'));
	});
}

function subsubsubNav() {
	$('#subnav>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);
	if(cssTransitions){
		$('#txt>#slideshow img:not(:last)').show();
	}
	$('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');
		/* :visible doesn't work when using css transitions */
		if(cssTransitions){
			//console.log($('#txt>#slideshow>img.fadeout:first'));
			last = ($('#txt>#slideshow>img.fadeout:first').prev().size()>0?$('#txt>#slideshow>img.fadeout:first').prev():last);
		}
			
		if(last.attr('src')!=$('#txt>#slideshow>img:visible:first:not(.fadeout)').attr('src')) {
			
			if(cssTransitions){
				last.addClass('fadeout');
			}else{
				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').show().animate({width: '280'}, 1000, function() {$(this).children().fadeIn();});
				} else if($('#slideshow.gotofirst').size()>0){
					setTimeout(function() {
						//$('#txt>#slideshow>img').not(':last').fadeOut(1000);
						var tohide = $('#txt>#slideshow>img').not(':last');
						if(cssTransitions){
							$('#txt>#slideshow>img:last').addClass('fadein').removeClass('fadeout');
							tohide.delay(1000).addClass('fadeout');
						}else{
							$('#txt>#slideshow>img:last').fadeIn(1000,function(){tohide.hide()});
						}
						$('#slideshow>#controls>li>a.current').removeClass('current');	
						$('#slideshow>#controls>li>a:first').addClass('current');
					}, slideshowspeed);
				}
			}
		} else {
			if(last.prevAll().size()==0) {
				if(cssTransitions){
					$('#txt>#slideshow>img:last').addClass('fadein');
					$('#txt>#slideshow>img').delay(1000).removeClass('fadeout').removeClass('fadein');
					
				}else{
						
					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');
		if(cssTransitions){
			$('#txt>#slideshow>#desc').hide();
			$('#txt>#slideshow>img').addClass('fadeout');
		}else{
			$('#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')) {
			//console.log('show desc?');
			$('#txt>#slideshow>#desc').show().animate({width: '280'}, 1000, function() {$(this).children().fadeIn();});
			/*image.fadeIn();
		}
		else {
			*/
		}
		if(cssTransitions){
			image.removeClass('fadeout').addClass('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'){
					if(cssTransitions){
						$('#txt>#slideshow img:not(:last)').hide();
						$('#txt>#slideshow img:last').addClass('fadein');
					}
					$('#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){

	$('#subnav, #mainnav').stop(true, true);
	var hashchunks=hash.split('/'); /* Split the string hash on / */
	hashchunks.shift(); /* Get rid of # */

	if(hashchunks.length>1){ /* DO ACTIONS FOR >1 */
		$('#mainnav>ul>li>a.active').removeClass('active');
		$('#mainnav>ul>li>ul>li>a.active').removeClass('active');
		$('#'+hashchunks[0]).prev().addClass('active'); /* Set the correct menu-item to active */
		
		if(!$('#'+hashchunks[0]).is(':visible')){ /* Do this when the correct menu is not open yet */
			$('#mainnav>ul>li>ul:visible').slideUp(); /* Closes other menus */
			$('#'+hashchunks[0]).children().hide(); /* This hides all listitems of the selected menu */
			listitemheight = 19; /* Calculates 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');
			$('#subnav').css("background-color", "#111111");			
		}

		if(hashchunks.length>2){ /* DO ACTIONS FOR >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", "#111111");
							$('#subnav>ul>li>ul:visible').slideUp();
							$('#'+hashchunks[1]).slideDown();
							/*fadeLi('#'+hashchunks[1]);*/
// 						});
					}
					else {
						$('#subnav').css("background-color", "#111111");
						$('#'+hashchunks[1]).slideDown();
					}
				}
				$('#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();

				if($('#subnav a[href='+hash+']').next().is('ul') && !$('#subnav a[href='+hash+']').next().is(':visible')){
					var listing	= $('#subnav 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);
						}
					);
				}
			}
		}
				
	}
	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);
}



/* START OF SIMPLE FUNCTIONS :) */

function contactForm(formid){

	$(formid).live('submit', function(){
		if($(formid+' .required:[value=]').size()>0){
			$(formid+' .required').css('border','1px solid transparent');
			$(formid+' .required[value=]').each(function(){
				$(this).css('border','1px dotted red');
				$(formid+' .error').fadeIn();
			});
		}
		else {
			$.post($(formid).attr('action'), $(formid).serialize(), function(){
			$(formid+' .error').fadeOut();
			$(formid+' fieldset').fadeOut('def', function(){
					$(formid+' .succes').fadeIn();
				});
			});
		}
		return false;
	});
	
}
