var imgCaching = [];
var openMenu = false;

$.support.transition = (function(){
    var thisBody = document.body || document.documentElement,
    thisStyle = thisBody.style,
    support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined;
    
    return support;
})();
if ($.support.transition) $('body').addClass('transitions');
else $('body').addClass('no-transitions');
$('body').addClass('hover');
var scrollWidth = 18;
(getScrollbarWidth = function() {
	var a = $('<div id="scroll-checker"><div/></div>').appendTo('body');
	scrollWidth = (100 - a.find('div').width());
	a.remove();
})();

createPrevNext = function(){
	var href;
	var prev = links.prevItem(current);
	var next = links.nextItem(current);
	var ul  = $('<ul class="prev-next"/>');
	if (prev && $(prev).is('a')) { 
		$('<li class="prev" data-id="'+prev.parent().attr('id')+'"/>').append(prev.clone()).appendTo(ul);
		href = $(prev).attr('href');
		if (!imgCaching[href]) {
			$.ajax({url: $(prev).attr('href'),success: function(d){
				$(d).find('img');
				imgCaching[href] = true;
			}});
		}
	}
	if (next && $(next).is('a')) { 
		$('<li class="next" data-id="'+next.parent().attr('id')+'"/>').append(next.clone()).appendTo(ul);
		href = $(prev).attr('href');
		if (!imgCaching[href]) {
			$.ajax({url: $(next).attr('href'),success: function(d){
				$(d).find('img');
				imgCaching[href] = true;
			}});
		}
	}
	if (next || prev) $('.content').append(ul);
	$('.prev > a > span').prepend('&laquo;&nbsp;');
	$('.next > a > span').append('&nbsp;&raquo;');
};

function createScroller() {
	$('.content-container').append('<div id="scroller"><div id="dragger"></div></div>');
	
	$scroller = $('#scroller');
	$dragger = $('#dragger');
	$container = $('.content');
	$scrollcontainer = $('#scroll-helper');
	$scrollcontainer.css({right: -scrollWidth});
	$container.css({marginRight: scrollWidth-13});
	
	$scroller.click(function(e){
		var top = $dragger.position()['top'];
		var clickPos = 0;
		if (e.pageY-50<top) {
			clickPos = top - $dragger.height();
		}
		else {
			clickPos = top + $dragger.height();
		}
		$scrollcontainer.stop().animate({scrollTop: (clickPos/scrollRatio)});
	});
	$dragger.draggable({
		containment: 'parent', axis: "y",
		drag: function(e, ui) {
		$scrollcontainer.stop().scrollTop(ui.position.top/scrollRatio);
		}
	});
	
	
}
var iRatio = 1600/995;
var wRatio;
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
if (!readCookie('exp_screenWidth')) {
	$.ajax({url: '/screen/'+screen.width});
}

var links = [];
var current = $('#home-sequence li:first').data('id');
$('#nav-full li').each(function(i,li){
	var li = $(li);
	var a = $('> a', li);
	if (li.hasClass('here')) current = li.attr('id'); 
	links[li.attr('id')] = a;
});
$('#nav-full > li').each(function(){
	var li = $(this);
	li.data('height',Math.max(0,li.height()-171));
});

function hideMenu() {
	
	$('div.content').addClass('animating').animate({marginTop: $container.data('top')}, function(){
		$(this).removeClass('animating');
	});
	$('.menu').animate({bottom: 0}, function(){
		openMenu = false;	
	});
	$('.footer').animate({paddingBottom: 0});
}
function showMenu() {
	openMenu = true;
	var height = parseInt($('li.parent-here', $('#nav-full')).first().data('height'),10);
	if (!height) return;
	
	var contentTop = parseInt($container.data('top'),10);
	$('div.content').animate({marginTop: Math.max(0,contentTop-height)});
	$('.menu').animate({bottom: height});
	$('.footer').animate({paddingBottom: height});
	
}
var $dragger, $scroller, $container;
/*showMenu();
setTimeout(function(){hideMenu();},1000);
*/
$(window).resize(function(){
	resizeFunctions();
});

resizeFunctions = function(){
	wRatio = $(window).width()-20/$(window).height()-111;
	
	if (wRatio>iRatio) {
		var width = Math.max(($(window).height()-111)*iRatio,750);
		var margin = ($(window).width()-width)/2;
		
		if (margin<10) {
			$('.wrapper').css({width: $(window).width()-20, left: 10, right: 10 });
		}
		else { 
			$('.wrapper').css({width: width, left: margin, right: margin} );
		}
		
	}
	else {
		$('.wrapper').css({width: $(window).width()-20, left: 10, right: 10 });
	}
	
	
	
	var windowHeight = $(window).height();
	var bgHeight = $('#bg').height();
	var imgHeight = $('#bg > img').height();
	
	if (imgHeight<bgHeight) {
		$('#bg > img').css({bottom: 0, top: 'auto'});
		$('#bg').addClass('fading');
		$('#bg em').css({bottom: (imgHeight -44)});
	}
	else {
		$('#bg > img').css({top: (bgHeight-imgHeight)/2, bottom: 'auto' });
		$('#bg').removeClass('fading');
	}
	
	
	$('.content-container').width($('.menu').width()).css({
		left: $('.menu').offset()['left']
	});
	
	positionContent();
	calculateScroll();
	$('body').css({visibility: 'visible'});
}

function positionContent() {

	var ccHeight = $scrollcontainer.height();
	var cHeight = $container.height()+80;
	var contentMargin = Math.max((ccHeight-cHeight),0);
	
	var height = parseInt($('li.parent-here', $('#nav-full')).first().data('height'),10);
	
	$container.css({marginTop: openMenu ? Math.max(0, (contentMargin-height)) : contentMargin}).data('top',contentMargin);
	if (contentMargin>0) $scroller.hide();
	else {
		$scroller.show();
	}
}


function calculateScroll() {
	var scrollerHeight = $scroller.height();
	var scrollHeight = $container.height() + 80;
	var delta = scrollHeight - $scrollcontainer.height();
	scrollRatio = scrollerHeight/scrollHeight;
	var draggerHeight = $scrollcontainer.height()*scrollRatio; 
	
	$dragger.height(draggerHeight);
		if (!$scrollcontainer.hasClass('scrollable')) {
		$scrollcontainer.addClass('scrollable').scroll(function(){
			$dragger.css({top: $scrollcontainer.scrollTop()*scrollRatio});
		});
	}
	
}


var scrollRatio;

function checkLoaded() {
	$('.js #bg img').each(function(){
		if (!this.complete) {
			setTimeout(checkLoaded,10);
		}
		else {
			$('.js #bg').addClass('loaded');
			onUpdateFunctions();
			$('body').removeClass('waiting');
		}
	});
	
}

onUpdateFunctions = function(){
	
	
	createPrevNext();
	
	$('table.referenties').tablesorter({sortList: [[0,0]]}); 
	
	$('table.publicaties').tablesorter({
		textExtraction: function(node){
			return node.childNodes[0].innerHTML;
		},
		sortList: [[1,1]]
	});
	
	createScroller();
	
	resizeFunctions();
	
	$(".content a[href^='http://']").attr("target","_blank");
	
	$('.content-container').removeClass('processing');
	
	
}



Array.prototype.nextItem = function(index){
	var flag = false;
	var a = this;
	
	for (var i in a) {
		if (flag) return a[i];
		if (i==index) flag = true;
	}
}
Array.prototype.prevItem = function(index){
	var prev = false;
	var a = this;
	
	for (var i in a) {
		
		if (i==index) return a[prev];
		prev = i;
	}
}

checkLoaded();

$(document).keyup(function(e){
	switch(e.keyCode) {
	case 37:
			getContent(links.prevItem(current), false);
		break;
	case 39:
			getContent(links.nextItem(current), false);
		break;
	}
});
$('.menu a').live('click',function(e){
	getContent($(this), true);
	return false;
});
var currentPath;
function getContent(a, clicked) {
	$('body').addClass('waiting');
	a = $(a);
	var href = a.attr('href');
	if (!href) return false;
	current = a.parent().attr('id');
	
	$.ajax({
		url: href,
		success: function(data){
			
		
			// setting title
			var title = $(data).find('.content').attr('title') + ' | Frederiks & van der Nat';
			
			currentPath = href.replace('http://'+document.location.hostname,'');
			
			if (title) {
				try {
					$('title').html(title);
					
				}
				catch(e){
					document.title = title;
				}
				if (typeof window.history.pushState == 'function') {
					history.pushState({}, title[1], href);
				}
				else {
					document.location.hash =currentPath;
				}    
				
				if (clicked) {
					_gaq.push(['_trackPageview', currentPath]);
				}
			}
			
			var height = $(a).parents('li').reverse().first().data('height');
			
			
			
			
			$('.content-container').addClass('processing').html('');
			// setting current classes
			$('.menu .here, .menu .parent-here').removeClass('here parent-here');
			a.parents('li').addClass('parent-here');
			
			if (!clicked) {
				height = 0;
				$('.content-container').html($(data).find('div#scroll-helper'));
				$('.footer').css({paddingBottom: height});
				$('.content').attr('title','');
				$('#bg').removeClass('loaded').html($(data).find('#bg img'));
				

				checkLoaded();
				
				hideMenu();
			}
			else {
				openMenu = true;
				$('.menu').animate({bottom: height},function(){
					$('.content-container').html($(data).find('div#scroll-helper'));
					$('.content').attr('title','');
					$('#bg').removeClass('loaded').html($(data).find('#bg img'));

					checkLoaded();
					
					
				});
				$('.footer').animate({paddingBottom: height});
			}
			
			
			
			
			
		}
	});
	
}
$('#bg, .content-container').live('mouseenter',function(){
	hideMenu();
})
$('.menu > ul > li.parent-here, .menu > ul > li.here').live('mouseenter',function(){
	showMenu();
});




$('div.menu').hover(function(e){
	$('body').addClass('hover');
	
},function(e){
	
});
$('.content-container').hover(function(e){
	$('body').addClass('hover');
	
},function(e){
	$('body').removeClass('hover');
});
$('.content').attr('title','');
$.fn.reverse = [].reverse;
if (document.location.hash) {
	try {
		var segments = document.location.hash.split('/');
		var s='';
		while (s=='' && segments.length) s = segments.pop();
		getContent($('#nav-full-'+s+' > a'));
	}
	catch(e) {
		
	}
}
$('.prev-next a').live('click',function(){
	getContent($('#'+$(this).parent().attr('data-id')+' > a'), false);
	return false;
});


window.onpopstate = function(event) {
	if(document.location.pathname!=currentPath) {
		var arr = ($.trim(document.location.pathname.replace(/\//gi,' '))).split(' ');
		getContent($('li#nav-full-'+arr[arr.length-1]+' > a:first'), false);
	}
};


