// JavaScript Document

/* 
Function set handlers and values to HTML
*/

function initFirstTimePageSettings(){

	/* = Set objectdata
-------------------------------------------------------------------------- */
	initExtraValuesToObjects();

	/* = Set handlers
-------------------------------------------------------------------------- */
	initHeader();

	initFooter();

/* = Set width left and rightbar
-------------------------------------------------------------------------- */

	resizeViewport(); 
	$(window).resize(function() {
		resizeViewport(); 
	});

/* = Set handlers in main Content
-------------------------------------------------------------------------- */

	if($("input[name='javascriptInitBeforeShow']").val().length > 0){
		func = $("input[name='javascriptInitBeforeShow']").val()+"(true)"
		var myFunc = new Function(func);
 		myFunc();
	}

	if($("input[name='javascriptInitAfterShow']").val().length > 0){
		func = $("input[name='javascriptInitAfterShow']").val()+"(true)"
		var myFunc = new Function(func);
 		myFunc();
	}

}

function initHeader(){
/* = Set main navigation
-------------------------------------------------------------------------- */
	menuEnable();

}

function initFooter(){
/* = Place Footer
-------------------------------------------------------------------------- */
	$(".geeky-bits a").unbind("click").click(function(){
		loadNextPage($(this).attr("href"))
		return false;
	})
	setMenuItemSelector( window.location )
	setFooterTop($("#containers").data("currentContainer"),0 )

}

function initSideMenu(){
	
	$(window).unbind("scroll").scroll(function(){
		scrollSideMenu();
	})

	$("#sidemenu").css({opacity:0})

	$("#sidemenu a").unbind("click").click(function(){
		if($(this).parent("li").attr("id") == "download-resume"){
			//registrar new page to google analytics
			googleAnalyticsPage = "/"+$("#documentsettings input[name='url-"+$("#documentsettings input[name='language']").val()+"']").val()+"/downloaded/"
			_gaq.push(['_trackPageview', googleAnalyticsPage]);
		}
		else{
			loadNextPage($(this).attr("href"))
			return false;
		}
	})
	
/*	
	$("#contact-me").unbind("toggle").toggle(function(){
//			cvMenuShowContactForm()
			loadNextPage("http://www.jansons.nl/contact/")
			return false;
		},
		function(){
//			$("#contactform").remove()
			loadNextPage("http://www.jansons.nl/contact/")
			return false;
	})
*/	
	resizeViewport();
	scrollSideMenu(0)
	$("#sidemenu").appendTo( $('#containers') ).animate({opacity:1, 'filter': ''},1000,function(){
		$("#sidemenu").removeClass("sidemenufading")
		scrollSideMenu()
	})
		
	resizeViewport();
	scrollSideMenu(0)
	$("#sidemenu").appendTo( $('#containers') ).animate({opacity:1, 'filter': ''},1000,function(){
		$("#sidemenu").removeClass("sidemenufading")
		scrollSideMenu()
	})
}

function unloadSideMenu(){
	$("#sidemenu").remove()
	$(window).unbind("scroll")
}

function initBeforeHome(){
	sitemapLinks = $("#sitemap a")
	sitemapLinks.unbind("hover").hover(
		function() {
			$(this).parents("#sitemap").addClass( "hover hover-"+$(this).parents("li").attr("class") )
		} ,
		function() { 
			$(this).parents("#sitemap").removeClass( "hover hover-"+$(this).parents("li").attr("class") )
		}
	)
	sitemapLinks.unbind("click").click(function(){
		$(this).parents("#sitemap").addClass( "clicked clicked-"+$(this).parents("li").attr("class") )
		loadNextPage($(this).attr("href"))
		return false
	})
}

function initBeforeCv(){
}

function initAfterCv(){
	initSideMenu()
}

function unloadCv(){
	unloadSideMenu()	
}
function cvMenuShowContactForm(){
//contactform as presented on contactpage.

	contactForm = "<form name=\"contact\" class=\"unsubmitted formlanguage-nl\" id=\"contactform\" action=\"http://www.jansons.nl/processcontactform.php\" method=\"post\"><p id=\"conformationmessage\">Hartelijk dank voor het versturen van je bericht.</p><div id=\"contactmessage\"><div id=\"contactmessage-inner\"><input type=\"hidden\" name=\"language\" id=\"language\" value=\"nl\" /><img src=\"http://www.jansons.nl/images/template/stamp.jpg\" id=\"stamp\" alt=\"\" /><p class=\"formline-name\"><label for=\"name\">Naam:</label><label for=\"name\" class=\"required\">*</label><input tabindex=\"1\" class=\"text fakefocus\" name=\"name\" id=\"name\" type=\"text\" maxlength=\"255\" /></p><p class=\"formline-email\"><label for=\"email\">E-mail:</label><input tabindex=\"2\" class=\"text\" name=\"email\" id=\"email\" type=\"text\" maxlength=\"255\" /> </p><p class=\"formline-message\"><label for=\"message\">Bericht:</label><label for=\"message\" class=\"required\">*</label><textarea tabindex=\"4\" class=\"textarea\" cols=\"35\" rows=\"9\" name=\"message\" id=\"message\"></textarea></p></div></div><div class=\"button\" id=\"buttonsubmit\"><button tabindex=\"5\" type=\"button\" class=\"button-inner\">Verstuur bericht</button></div></form>";
	
	$("#cvmenu").append(contactForm)

	//disable horizontal scrolbars on document.window
	$("body").css({"overflow-x": "hidden","margin": "0"})

	$("#contactform").css({left: "-2500px"})
	$("#contactform").animate({left: "-482px"}, 1000, function(){
		$("#contactform").animate({left: "-502px"}, 250, function(){
			$("#contactform").animate({left: "-500px"}, 125, function(){																  
				initContactFormBefore()
				initContactFormAfter()
				$("body").css({"overflow-x": "visible"})
			})
		})
	})
}

/*
Function animates menu on right side of content.
speed - integer - Optional. Speed of main animation. If speed is "0" -> Top is set without animation
*/
function scrollSideMenu(speed){
	var cvMenu = $("#sidemenu")
	if( cvMenu.length >0 ){
		if( $(document).scrollLeft() >0 ){
			resizeViewport();
		}
	
		if( $("#containers .container").hasClass("page-resume") ){
			var cvMenuOriginalTop = 15
		}
		else{
			var cvMenuOriginalTop =  -16
		}
		var cvMarginTop = 138
		var scrollTop =  parseInt($(document).scrollTop() )
		var cvMenuTop = parseInt( cvMenu.css("top").substring(0, cvMenu.css("top").length - 2) )
		
		animTop = cvMenuOriginalTop
		if(scrollTop < cvMarginTop ){
			var animDirection = parseInt(-1)
			animTop = cvMenuOriginalTop
		}
		else {
			animTop = scrollTop-cvMarginTop
		}	
		if(animTop < cvMenuTop){
			var animDirection = parseInt(-1)	
		}
		else{
			var animDirection = parseInt(+1)	
		}
		if(speed == null){
			speed = 500
		}
	
	
		if(animTop && animTop != cvMenuTop){
			if(speed == 0){
				$("#sidemenu").css({"top": animTop+"px"})	
			}
			else{
				$("#sidemenu").queue("moveStepOne", function(){			
					$(this).stop().animate({"top": animTop + (animDirection*3)+"px"},speed)
				})
				$("#sidemenu").queue("moveStepTwo", function(){			
					$(this).animate({"top": animTop+"px"},150)	
				})
				$("#sidemenu").stop().dequeue("moveStepOne").dequeue("moveStepTwo")
			}
		}
	}
}


function initContactFormBefore(){
	buttons = $(".button")
	buttons.unbind("hover").hover(
		function() { buttonSetHoverOn(this) } ,
		function() { buttonSetHoverOut(this) }
	)
	buttons.unbind("mousedown").mousedown(function(){buttonMouseDown(this) })
	buttons.unbind("mouseup").mouseup(function(){buttonMouseUp(this) })
	
	buttons.unbind("keydown").keydown(function(event) {
		if(event.which == 13) {
			buttonMouseDown(this);
		}
	})
	buttons.unbind("keyup").keyup(function(event) {
		if(event.which == 13) {
			buttonMouseUp(this);
		}
	})
	buttons.find(".button-inner").unbind("focus").focus(function(){
		buttonSetHoverOn($(this).parent())
	})
	buttons.find(".button-inner").unbind("focusout").focusout(function() {
		buttonMouseUp(this);
		buttonSetHoverOut($(this).parent())
	})
}

function initContactFormAfter(){
	setValidationOnContactform()
	$("#buttonsubmit").unbind("click").click(function(){
		submitForm($(this).parents("form"))
		animateFormOnContactPage()
		return false;
	})
	$("#contactform input[name='name']").focus();
	$(".formline-name .fakefocus").removeClass("fakefocus")	
}

/*
Function sets validation on contactform.
*/
function setValidationOnContactform(){
	language = $("#contactform input[name='language']").val()
	errorTextName = (language == "nl") ? "Vul een naam in die uit tenminste twee lettertekens bestaat." : "Please fill in a name which is at least two characters long.";
	errorTextEmail = (language == "nl") ? "Vul een geldig e-mailadres in." : "Please fill in a correct emailadress.";
	errorTextMessage =(language == "nl") ? "Schrijf een bericht." : "Please write a message.";
	
	$("#contactform").validate({
		rules: {
			name: {
				required: true,
				minlength: 2
			},
			email: {
				email: true
			},			
			message: {
				required: true
			}
		},
		messages: {
			name: {	
				required: errorTextName,
				minlength: errorTextName
			},
			email: errorTextEmail,
			message: errorTextMessage
		}
	});

}
/*
Function if form == valid and form == unsubmitted -> submits form in AJAX
e - (Jquery HTML) object - form which needs to be submitted
*/
function submitForm(e){
	if(e.valid() && e.hasClass("unsubmitted")){
		$.ajax({
			type: 'POST',
			url: "http://www.jansons.nl/processcontactform.php",
			data: e.serialize(),
			success: function(){
					//registrar new page to google analytics
					googleAnalyticsPage = "/"+$("#documentsettings input[name='url-"+$("#documentsettings input[name='language']").val()+"']").val()+"/submitted/"
					_gaq.push(['_trackPageview', googleAnalyticsPage]);
				}
			});
	}
	e.removeClass("unsubmitted").addClass("submitted")
}

/*
Function animates "form -> postcard" and animates "postcard -> move to left". Function specificly written for contactfom on contactpage.
*/
function animateFormOnContactPage(){
	if($("#contactform").valid()){
		message = $("#contactmessage")
		labels =message.find("label")
		texts = message.find(".text")
		textarea = message.find(".textarea")
		timeBuildToPostcard = 800
		timeShowPostcard=1250
		timeSendPostcard=1400
		
		//begin: animate message to postcard
		//hide button
		$("#buttonsubmit").animate({opacity:0},timeBuildToPostcard,function(){
			$("#buttonsubmit").hide();													  
		})
		//hide labels
		labels.animate({opacity:0},(timeBuildToPostcard/2),function(){
			//show postcard
			$(this).css({"display":"none"})
			$("#contactmessage-inner").css({width:"600px","margin-left":"50px"}).animate({borderColor:"#DAD4C0",backgroundColor:"#F5EED9"},(timeBuildToPostcard/2))
			$("#contactmessage-inner p").css({"margin-left":"27px"})
			//show stamp
			$("#stamp").css({opacity:0}).show().animate({opacity:1},(timeBuildToPostcard/2))
		})
		//animate <input type="text" /> to adresslines on postcard
		texts.css({"border-style": "solid"}).animate({borderTopColor:"#F5EED9",borderRightColor:"#F5EED9",borderLeftColor:"#F5EED9",backgroundColor:"#F5EED9"},timeBuildToPostcard)
		//animate <textarea /> to "message on postcard"
		textarea.css({"border-style": "solid"}).animate({borderColor:"#F5EED9",backgroundColor:"#F5EED9"},timeBuildToPostcard,function(){
			//if textarea has a scrollbar -> animate to "show complete message" and reset footer
			if(textarea.get(0).scrollHeight > textarea.height()){
				textarea.css({overflow:"hidden"})
			}
		})
		//end: animate message to postcard
		
		//start: send postcard, show "conformationmessage" and reset footer
		$("#conformationmessage").css({opacity:0})
		//wait untill postcard is made
		message.animate({opacity:1},(timeBuildToPostcard+timeShowPostcard),function(){
			//"send postcard"
			message.animate({left:"-2000px"},timeSendPostcard)
			//show "conformationmessage"
			$("#conformationmessage").animate({opacity:1},timeSendPostcard)
			//reset footer
			$("#footer").animate({opacity:1},(timeSendPostcard/2),function(){
				setFooterTop($("#containers").data("currentContainer"),(timeSendPostcard/2))
			})
		})
		//end: send postcard, show "conformationmessage" and reset footer
	}
}

function initPortfolioLiteBit(initFirstTimePageSettings){	
/* = Set "image is loaded" behaviour of thumbnails
-------------------------------------------------------------------------- */	
	var thumbnails = $("img.thumbnail")
	thumbnails.one("load",function(){
		$(this).parents(".creation").removeClass("creationthumbnailunloaded")
	}).each(function(){
		if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
		$(this).trigger("load");
	}); 


/* = Hover on photo
-------------------------------------------------------------------------- */

	var creations = $("#creations .creation")

	creations.unbind("hoverIntent").hoverIntent({	
		over: function(){
			onPhotoOver( $(this) );
		},
		out: function(){
			onPhotoOut( $(this) )
		}
	});

	creations.unbind("click").click(function(){
		creationClick($(this))
	});

	creations.unbind("mousedown").mousedown(function(){creationMouseDown(this) })
	creations.unbind("mouseup").mouseup(function(){creationMouseUp(this) })

/* = Click on Filter element
-------------------------------------------------------------------------- */
	$("#portfolio-filter a").unbind("click").click(function(){
		setPortfolioFilter($(this),true)
	})
	
/* = set correct PortfolioFilter setting on complete page
-------------------------------------------------------------------------- */
	e = $("#portfolio-filter .filter-item-selected a")

	if( $("html").attr("lang") == "nl" ){
		$("#documentsettings input[name='url-nl']").val( e.attr("href").substring(2, $(e).attr("href").length - 1 ) )
		$("#documentsettings input[name='url-en']").val( $("input[name='"+$(e).attr("id")+"']").val() )	
	}
	else{
		$("#documentsettings input[name='url-nl']").val( $("input[name='"+$(e).attr("id")+"']").val() )
		$("#documentsettings input[name='url-en']").val( $(e).attr("href").substring(2, $(e).attr("href").length - 1 )	)			
	}

}

function initPortfolioHeavyBit(initFirstTimePageSettings){	
/* = Set correct URLs in <form name="documentsettings" id="documentsettings" />
-------------------------------------------------------------------------- */
	selectedLink = $("#portfolio-filter .filter-item-selected a")

	if( $("html").attr("lang") == "nl" ){
		$("#documentsettings input[name='url-nl']").val( selectedLink.attr("href").substring(2, selectedLink.attr("href").length - 1 ) )
		$("#documentsettings input[name='url-en']").val( $("input[name='"+selectedLink.attr("id")+"']").val() )	
	}
	else{
		$("#documentsettings input[name='url-nl']").val( $("input[name='"+selectedLink.attr("id")+"']").val() )
		$("#documentsettings input[name='url-en']").val( selectedLink.attr("href").substring(2, selectedLink.attr("href").length - 1 )	)			
	}
	setPageAdressToTranslationElement()

/* = Show all creations
-------------------------------------------------------------------------- */
	unLoadedThumbs = $("#creations .creation-loadoutofviewport img.thumbnail")
	$.each(unLoadedThumbs, function(){
		$(this).attr("src", $(this).attr("alt")).attr("alt","")
		$(this).parents(".creation").removeClass("creation-loadoutofviewport")
	})

	//calculate animating hide/show of creations
	newHeight = ( ( Math.ceil ( ( $('.creation_enabled').length) / 3 ) ) * $(".creation").outerHeight(true) )+ $("#portfolio-header").outerHeight(true)
	//animate new filter settings
	setFooterTop($("#containers").data("currentContainer"), 0, newHeight)
	

/* = Set all creation elements which need to be hidden to .hide()
-------------------------------------------------------------------------- */

	$(".creation_disabled").hide();
	$(".creation_disabled .shadow").hide();
	$("#containers .container2").hide();

/* = Colorbox: Photo Gallery
-------------------------------------------------------------------------- */
	$("a[rel='gallery']").unbind("colorbox").colorbox({
		slideshow:true,
		slideshowAuto:false,
		transition:"fade",
		opacity: 1,
		title: function(){
			title = $(this).parents(".creation").find("h2").text() 
			title = ((title.charAt(title.length-1,1) == "*") ? title.substring(0,title.length-1) : title)
			return title
		},
		current: "Afbeelding {current} van {total}",
		scrolling: false,
		previous: "Vorige foto",
		next: "Volgende foto",
		close:"Sluit scherm",
		slideshowStart:"Start Diaserie",
		slideshowStop:"Stop Diaserie",
		onOpen: function(){
					setCboxNewHash(this,null,initFirstTimePageSettings)
					setCboxControllers(this)
					$("#cboxControlBar").removeClass("cbox-hide").addClass("cbox-show")
					cboxControle_show();
					$(".animatehidecreationtext").find(".shadow").dequeue();
			},
		onCleanup: function(){
					$("#cboxControlBar").removeClass("cbox-show").addClass("cbox-hide")
					$("#cboxControlBar").hide()
					setCboxNewHash(null,true)
			},
		OnComplete: function(){
					if($("#colorbox").hasClass("cboxSlideshow_on")){
						setCboxNewHash()
					}
			}
	});

	$("#cboxOverlay").unbind("mousemove").mousemove(function() {
		cboxControle_show();
	})	
	$("#colorbox").unbind("mousemove").mousemove(function() {
		clearTimeouter();				
	})

	$("#cboxControlBar").unbind("hover").hover(function(){
		clearTimeouter()
	})

	$(".creation_disabled .creationphotos .cboxElement").removeClass("cboxElement").removeAttr("rel");

/* = If selected photo in URL: click on selected photo
-------------------------------------------------------------------------- */
	if($("input[name='selectedPhoto']").length){
		photo = $("input[name='selectedPhoto']").val().replace(/-/g, " ")
		$(".creationphotos a:Contains('"+photo+"')").click();
	}

/* = Update social media settings
-------------------------------------------------------------------------- */
/*
	$("#portfolio-filter .social-share").animate({"opacity":1},500,function(){
		//set twitterbutton
		var twitterWidgets = document.createElement('script');
		twitterWidgets.type = 'text/javascript';
		twitterWidgets.async = true;
		twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
		document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
		
		$(".tweet-inner").css({"display":"none"});
		$("#portfolio-filter .tweet-inner").animate({"opacity":1},1000,function(){
			$(".tweet-inner").css({"display":"block"});
		})
	})
	
	//set Facebook buttons
	var e = document.createElement('script');
	e.type = 'text/javascript';
	e.async = true;
	e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js#appId=192564867460764&xfbml=1';
	document.getElementsByTagName('head')[0].appendChild(e);

	$(".facebook-inner").css({"display":"none"});
	setFacebookButtons($("#portfolio-filter .social-share"))
	$("#portfolio-filter .tweet-share").animate({"opacity":1},1500,function(){
		$(".facebook-inner").css({"display":"block"});
	})
*/
}

function initAfterGeekyBits(){
	$(".main a[href*='www.jansons.nl']").unbind("click").click(function(){
		loadNextPage($(this).attr("href")); 
		return false
	})
	initSideMenu()
}

function unloadBeforeGeekyBits(){
	unloadSideMenu()	
}

/*
Function displays info texts
e - (Jquery HTML) object - object on which is click
*/

function creationMouseDown(e){
	thumb.animate({bottom:"34px",right:"42px"},75)
	shadow.animate({bottom:"-70px",right:"-69px",height:"416px",width:"374px",opacity:0.6,'filter': ''},75)	
}
function creationMouseUp(e){
	thumb.animate({bottom:"39px",right:"45px"},75)
	shadow.animate({bottom:"-76px",right:"-74px",height:"422px",width:"380px",opacity:0.5,'filter': ''},75)
}

	
/*
Function opens photogallery
e - (Jquery HTML) object - object on which is click
*/
function creationClick(e){
	//Workaround: In order to stop propagation in combination with colorbox in browsers IE7/FF/Chrome. Delay in detecting het $("#colorbox").css is needed. JQuery event.stopPropagation() in combination with colorbox does not work correctly in Chrome/IE/FF
	$(e).find(".thumbnail").animate({opacity:1},150,function(){
		if($("#colorbox").css("display") == "none"){
			$(e).find(".creationphotos ul a:first").click()
		}
	})
}

/* 
Function enables "onclicks" on menu items. Including click on regular menu items, logo and "translate" button
*/
function menuEnable(){
	
	$("#header").removeClass("faded")
	//set click in #menu
	$("#menu a").animate({"opacity":1, 'filter': ''},150,function(){
		$("#menu a").unbind("click").click(function(){
			loadNextPage($(this).attr("href"))
			return false
		})  
	})
	//set click in #logo
	$("#logo").animate({"opacity":1, 'filter': ''},150, function(){
		$("#logo").unbind("click").click(function(){
			loadNextPage($(this).attr("href"))
			return false;
		})
		//set state of menu in CSS to "menu is enabled"
		$("#header").removeClass("menu_disabled").addClass("menu_enabled")	
	});

}

/* 
Function disables "onclicks" on menu items. Including disabling click on regular menu items, logo and "translate" button
*/
function menuDisable(){
	menuLinks = $("#menu a")
	//set state of menu in CSS to "menu is disabled"
	$("#header").removeClass("menu_enabled").addClass("menu_disabled")

	//removing onClick on links in menu (and logo)	
	$.each(menuLinks,function(key, value){
		$(this).unbind("click").click(function(){ return false;}).animate({"opacity":0.3, 'filter': ''},250);
	})
	
	$("#logo").unbind("click").click(function(){ return false;}).animate({"opacity":0.75, 'filter': ''},250,function(){
		$("#header").addClass("faded")
		$("#logo").css({"opacity":1, 'filter': ''})
		menuLinks.css({"opacity":1, 'filter': ''})
		
	})

}

/*
Function sets Portfoliofilter. Function also calculates heigth of content in new filtersettings before the filter is applied, in order to let the animation of the Footer run at the same time as the Filtersettingsanimation.
e - (Jquery HTML) object - object on which is click
setHistory - boolean - If "true" -> adress is put into bbq.state;
*/
function setPortfolioFilter(e,setHistory){
	if( !( $("#portfolio-filter").hasClass("filter_disabled")) &&  !( e.parents("li").hasClass("filter-item-selected") ) ){
		speed = 1750
		disableSpeed=750
		enableSpeed=500
		newHeight = 0
		filter = "."+e.attr("rel")

		if(setHistory == true){
			pageReload=false;
			jQuery.bbq.pushState("http://www.jansons.nl/"+e.attr("href"),2)
		}

		//registrar new page to google analytics	
		googleAnalyticsPage = e.attr("href")
		googleAnalyticsPage = googleAnalyticsPage.replace("#!","/")
		_gaq.push(['_trackPageview', googleAnalyticsPage]);

		//Adjust <head />
		$("link[rel='canonical']").attr("href","http://www.jansons.nl"+googleAnalyticsPage)
		
		//set filter selection in filter
		$("#portfolio-filter li").removeClass("filter-item-selected")
		e.parent().addClass("filter-item-selected")
		$('#portfolio-filter .social-share').appendTo( e.parent() );

		//set Document Title (does not use jQuery $("title").text( titleString ) as it misteriously crashes in IE7.
		documentTitle = $("#portfoliosettings [name='"+$(e).attr("id")+"-altpagetitle']").val()
		document.title = documentTitle
		$("#documentsettings input[name='title']").val(documentTitle)
/*
		//update social media settings: update twitter message. Tweetbutton will be visible when last animation is completed.
		$(".tweet-inner").css({"display":"none"});
		setTweet($("#portfolio-filter .tweet-share iframe"),$("#portfoliosettings [name='"+$(e).attr("id")+"-tweettext']").val(),"http://www.jansons.nl"+googleAnalyticsPage)

		//update social media settings: remove Facebook buttons. Facebook buttons will be visible when last animation is completed.
		$(".facebook-inner fb:like").remove()
		$(".facebook-inner script").remove()
		$(".facebook-inner").css({"display":"none"});
		//update social media settings: set new facebook buttons
		setFacebookButtons($("#portfolio-filter .social-share"))
*/
		//set translationelements to new selection
		if( $("html").attr("lang") == "nl" ){
			$("#documentsettings input[name='url-nl']").val( $(e).attr("href").substring(2, $(e).attr("href").length - 1 ) )
			$("#documentsettings input[name='url-en']").val( $("input[name='"+$(e).attr("id")+"']").val() )	
		}
		else{
			$("#documentsettings input[name='url-nl']").val( $("input[name='"+$(e).attr("id")+"']").val() )
			$("#documentsettings input[name='url-en']").val( $(e).attr("href").substring(2, $(e).attr("href").length - 1 )	)			
		}

		setPageAdressToTranslationElement();

		//disables filter
		$("#portfolio-filter").removeClass("filter_enabled").addClass("filter_disabled")
		
		$("#portfolio-filter a").unbind("click").click(function(){ return false;}).animate({"opacity":0.3, 'filter': ''},250)

		//sets className to new filter settings (including the selection of large photo's needed for the photogallery)
		$('.creation_enabled').removeClass('creation_enabled').addClass('creation_disabled').find(".creationphotos a").removeClass("cboxElement").removeAttr("rel")
		$(filter).removeClass('creation_disabled').addClass('creation_enabled').find(".creationphotos a").addClass("cboxElement").attr("rel", "gallery")

		//start animating hide/show of creations
		newHeight += ( ( Math.ceil ( ( $('.creation_enabled').length) / 3 ) ) * $(".creation").outerHeight(true) )+ e.parents("#portfolio-header").outerHeight(true)

		//animates new filter settings
		setFooterTop(e.parents(".container").attr("id"), speed, newHeight)		
		
		$.each($(".creation_disabled"),function(keyA, value){
			if(keyA<4){
				$(this).hide(speed)
			}
			else{
				$(this).hide()
			}
			$(this).find(".shadow").hide()
			$(this).find(".creationtext").hide()
		})

		$.each($(".creation_enabled"),function(keyB){
			if(keyB<4){
				$(this).find(".creationtext").hide()
				$(this).show(speed,function(){
					$(this).addClass("creation-fadein").find(".shadow").fadeIn(1000,function(){
						$(this).parents(".creation").removeClass("creation-fadein")					
					})	
					$(this).find(".creationtext").show()
				})
			}
			else{
				$(this).animate({opacity:1, 'filter': ''},speed,function(){
					$(this).show()
					$(this).find(".creationtext").show()
					$(this).find(".shadow").css({"display":"block"}).animate({opacity:1, 'filter': ''},150);
				})
			}
		})
		
		//disable filter
		$.each($("#portfolio-filter a"), function(key){
			$(this).unbind("click").click(function(){ return false;}).animate({"opacity":0.3, 'filter': ''},disableSpeed,function(){
				
				//pauze in animation
				$(this).animate({"opacity":0.3, 'filter': ''},speed-disableSpeed-enableSpeed, function(){
					
					//enable filter
					$(this).animate({"opacity":1, 'filter': ''},enableSpeed, function(){
						$(this).unbind("click").click(function(){ setPortfolioFilter($(this),true) })
						if( (key+1) ==	$("#portfolio-filter a").length){							
							$("#portfolio-filter").removeClass("filter_disabled").addClass("filter_enabled")
							$("#portfolio-filter a").unbind("click").click(function(){ setPortfolioFilter($(this),true) })
							$(".tweet-inner").css({"display":"block"});
							$(".facebook-inner").css({"display":"block"});
						}
					})
				})
			})
		})
	}
}

/*
Function sets Tweet.
e - (Jquery HTML) object - iframe which includes the twitterbutton
tweet - string - Text of tweet
url - string - url to be linked to in tweet
*/
function setTweet(e,tweet, url){
	//adjust Tweetmessage in filter
	tweetParams = jQuery.deparam($(e).attr("src"))
	tweetParams["url"] = url
	tweetParams["text"] = tweet	
	$(e).querystring( tweetParams );
	$(e).attr("src", $(e).attr("src").replace(/\+/gi," ") )
}

/*
Function runs when photogallery is initiated. Function builds controlbar (and the buttons with behaviour in the controlbar).
e - (Jquery HTML) object - object (link) on which is clicked
*/
function setCboxControllers(e){
	
	//perform only once when colorbox is created.
	if( $("#cboxControlBar").length == 0 ){
		
		//Initialize controlbar
		$("body").prepend("<div id=\"cboxControlBar\" class=\"cboxSlideshow_off\"><div id=\"cboxControls\"></div></div>") 
		
		controlbar = $("#cboxControlBar")
		controls = $("#cboxControls")
		buttonPartFirst = "<div class=\"button\" id=\"" 
		buttonPartSecond = "\"><div class=\"button-inner\"></div></div>"
		
		//Set button Previous
		controls.append(buttonPartFirst+"cboxButtonPrevious"+buttonPartSecond).find("#cboxButtonPrevious").click( function(){
			$("#cboxPrevious").click()
			setCboxNewHash()
		 })

		//set button Slideshow
		controls.append(buttonPartFirst+"cboxButtonSlideshow"+buttonPartSecond).find("#cboxButtonSlideshow").toggle(
			function() {
				controlbar.removeClass("cboxSlideshow_off").addClass("cboxSlideshow_on")
				$("#cboxSlideshow").click()
				$("#cboxButtonSlideshow .button-inner").html($("#cboxSlideshow").html())
			}, 
			function() {
				controlbar.removeClass("cboxSlideshow_on").addClass("cboxSlideshow_off")
				$("#cboxSlideshow").click()
				$("#cboxButtonSlideshow .button-inner").html($("#cboxSlideshow").html())		
		});
		
		//Set button Next
		controls.append(buttonPartFirst+"cboxButtonNext"+buttonPartSecond).find("#cboxButtonNext").click( function(){
			$("#cboxNext").click()		
			$("#cboxNext").animate({opacity:1, 'filter': ''},totalButtonAnimationTime,function(){	
				setCboxNewHash()			
			})
		})

		//set button Close
		controls.append(buttonPartFirst+"cboxButtonClose"+buttonPartSecond).find("#cboxButtonClose").click(function(){
			$(this).animate({opacity:1, 'filter': ''},totalButtonAnimationTime,function(){
				$("#cboxClose").click()
			})
		})
		
		//Set standardbehaviour on all standard buttons
		$("#cboxControls .button").unbind("hover").hover(
			function() { buttonSetHoverOn(this) } ,
			function() { buttonSetHoverOut(this) }
		)
		$("#cboxControls .button").unbind("mousedown").mousedown(function(){buttonMouseDown(this) })
		$("#cboxControls .button").unbind("mouseup").mouseup(function(){buttonMouseUp(this) })
		
		//set default texts to buttons
		$("#cboxControls").animate({opacity:1},1500,function(){
			$("#cboxButtonPrevious .button-inner").html($("#cboxPrevious").html())
			$("#cboxButtonSlideshow .button-inner").html($("#cboxSlideshow").html())
			$("#cboxButtonNext .button-inner").html($("#cboxNext").html())
			$("#cboxButtonClose .button-inner").html($("#cboxClose").html())
		})

		//set Title & Current number of photos
		$("#cboxTitle").appendTo(controlbar)
		$("#cboxCurrent").appendTo(controlbar)		
		
		//set behaviour timer to <div id="cboxControlBar">
		controlbar.hover(
			function(){
				controlbar.addClass("hover")
			},
			function(){
				controlbar.removeClass("hover")
				cboxControle_show();
			}
		)
	}
}

/* 
Function takes address of the newly displayed photo in photogallery and pushes it as a new address into the history.
e - jQuery object - Link on which is clicked and which triggered the initation of the photogallery
noTitle - boolean - If "true" - the title of the photo should not be incorperated into the newhash.
*/
function setCboxNewHash(e,noTitle,initFirstTimePageSettings){	
	delayTime = 500
	if(initFirstTimePageSettings != true){
		$("#portfolio-filter").animate({opacity:1, 'filter': ''},delayTime,function(){	
			title = "";
			if($(e).length){
				title= $(e).text().replace(/ /g, "-").toLowerCase()+"/"
			}
			else if(!noTitle){
				title= $(".creation a[href$="+$("#cboxPhoto").attr("src")+"]").text().replace(/ /g, "-").toLowerCase()+"/"
			}
			newHash = $("#portfolio-filter .filter-item-selected a").attr("href")+title;
			
			//registrar new page to google analytics	
			googleAnalyticsPage = newHash.replace("#!","/").replace("=","")
			_gaq.push(['_trackPageview', googleAnalyticsPage]);
	
			pageReload = false;
			jQuery.bbq.pushState("http://www.jansons.nl/"+newHash,2)	
		})
	}
}

/* 
Function is controller for "hovering on photo"
e - (HTML) object - Element on which is hovered
*/
function onPhotoOver(e){
	thumb = e.find("img.thumbnail")
	shadow = e.find("img.shadow")
	eCText = e.find(".creationtext")
	eCTextChildren = eCText.children()

	var textMinheight = 244
	var textWidth = 192
	var textAnimWidth = 158
	var textRight = -126
	var textTop = -87
	
	var thumbWidth = 200
	var thumbHeight = 260
	var shadowWidth = 380
	var shadowHeight = 422
	var shadowRight = -74
	var shadowBottom = -76

	if( !e.hasClass("animateshowhover") ){	
		//begin calculating height of <div class=".creation-text />
		var textHeight = 0;
		eCText.css({"width": textWidth+"px"})
		$.each(eCTextChildren, function() {
			textHeight += $(this).outerHeight(true);
		});
		if(textHeight < textMinheight ){
			textHeight = textMinheight
		}
		eCText.css({"width": "10px"})
		//end calculating height of <div class=".creation-text />
		
		var thumbWidthAnim = thumbWidth+10
		var thumbHeightAnim = thumbHeight+12
		
		var shadowWidthAnim = shadowWidth+5
		var shadowHeightAnim = shadowHeight+5
		var shadowRightAnim = shadowRight+5
		var shadowBottomAnim = shadowBottom+5	
		
		var textTopAnimOne = 122
		var textRightAnimOne = -100
		var textHeightAnimOne = 25
		var textWidthAnimOne = 40
		
		var textTopAnimTwo = textTop-10
		var textRightAnimTwo = textRight-10
		var textHeightAnimTwo = textHeight
		var textWidthAnimTwo = textWidth+10

		thumb.queue("showThumbOne",function(){
			$(this).animate({ width: thumbWidthAnim+"px",height:thumbHeightAnim+"px"}, 450)
		})
		thumb.queue("showThumbTwo", function(){
			$(this).animate({ width: thumbWidth+"px",height:thumbHeight+"px"}, 250);
		})

		shadow.queue("showShadowOne",function(){
			$(this).parents(".creation").addClass("animateshowhover").removeClass("animateclosehover")
			$(this).animate({ width: shadowWidthAnim+"px", height: shadowHeightAnim+"px","right":shadowRightAnim+"px","bottom":shadowBottomAnim+"px", opacity: 0.49, 'filter': '' }, 450)
		})
		
		shadow.queue("showShadowTwo",function(){
			$(this).animate({ width: shadowWidth+"px", height: shadowHeight+"px","right":shadowRight+"px","bottom":shadowBottom+"px", opacity: 0.5, 'filter': '' }, 250, function(){
				$(this).parents(".creation").removeClass("animateshowhover").removeClass("animateclosehover")
			})
		})
		
		eCText.queue("showTextOne",function(){
			$(this).animate({right:textRightAnimOne+"px",top:textTopAnimOne+"px", width: textWidthAnimOne+"px", height: textHeightAnimOne+"px", opacity: "0.9", 'filter': ''},230)
		})
		
		eCText.queue("showTextTwo",function(){
			$(this).css({"z-index":"8"}).animate({right:textRightAnimTwo+"px", top:textTopAnimTwo+"px", width:textWidthAnimTwo+"px", height: textHeightAnimTwo+"px"},245)
		})
		
		eCText.queue("showTextThree", function(){			
			
			$(this).animate({right:textRight+"px", top:textTop+"px", width:textWidth+"px", height: textHeight+"px"},250,function(){
				$(this).parents(".creation").removeClass("animateshowcreationtext").addClass("showcreationtext").removeClass("animatehover").addClass("showhover")
			})
			
		})
		
		thumb.dequeue("showThumbOne").dequeue("showThumbTwo")
		shadow.dequeue("showShadowOne").dequeue("showShadowTwo")
		eCText.dequeue("showTextOne").dequeue("showTextTwo").dequeue("showTextThree")
	}
}

/* 
Function is controller for "hovering out photo"
e - (Jquery HTML) object - Element on which is hovered
*/
function onPhotoOut(e){

	thumb = e.find("img.thumbnail")
	shadow = e.find("img.shadow")
	eCText = e.find(".creationtext")

	thumbWidth = 100
	thumbHeight = 130
	
	shadowWidth = 140
	shadowHeight = 173
	shadowRight = 19
	shadowBottom = 7

	var textTopAnimOne = 122
	var textRightAnimOne = -100
	var textHeightAnimOne = 25
	var textWidthAnimOne = 25

	if(!e.hasClass("animateclosehover")){
		shadow.queue("hideShadowOne",function(){		
			$(this).css("z-index", "9").animate({ width: shadowWidth-5+"px", height: shadowHeight-5+"px","right":shadowRight-3+"px","bottom":shadowBottom-3+"px", opacity: 0.99, 'filter': '' }, 450).parents(".creation").removeClass("showhover").removeClass("animateshowhover").addClass("animateclosehover")																																									
  		})
		
		shadow.queue("hideShadowTwo",function(){	
			$(this).animate({ width: shadowWidth+"px", height: shadowHeight+"px","right":shadowRight+"px","bottom":shadowBottom+"px", opacity: 1, 'filter': '' }, 150, function(){
				$(this).parents(".creation").removeClass("animateclosehover").removeClass("animateshowhover")
			});
		})

		thumb.queue("hideThumbOne",function(){
			$(this).animate({ width: thumbWidth-8+"px",height:thumbHeight-10+"px"}, 450)
		})
		thumb.queue("hideThumbTwo", function(){
			$(this).animate({ width: thumbWidth+"px",height:thumbHeight+"px"}, 150);
		})

		eCText.queue("hideTextOne", function(){
			$(this).animate({right:textRightAnimOne+"px", top:textTopAnimOne+"px",width:textWidthAnimOne+"px", height:textHeightAnimOne+"px"},200, function() {
				eCText.css("z-index","8")
			 })
		})
		
		eCText.queue("hideTextTwo", function(){
			$(this).animate({right:"75px", top:"85px", width: "5px", height: "5px", opacity: "1", 'filter': ''},200,function(){
				e.removeClass("animatehidecreationtext").addClass("hidecreationtext").removeClass("animatehover").addClass("hidehover")
			})
		})
		
		thumb.stop(true,false).dequeue("hideThumbOne").dequeue("hideThumbTwo")
		shadow.stop(true,false).dequeue("hideShadowOne").dequeue("hideShadowTwo")
		eCText.stop(true,false).dequeue("hideTextOne").dequeue("hideTextTwo")		
		
	}

}

/* 
Function animates the clicking of the button (only "pressing on the button")
e - (Jquery HTML) object - Element on which is clicked
*/
var totalButtonAnimationTime = 100;

function buttonClickAnimation(e){
	inner = $(e).find(".button-inner")

	$(inner).animate({"top": "2px", "left":"2px"},75, function(){
		$(inner).animate({"top": "0px", "left":"0px"},75)
	})
}

function buttonMouseDown(e){
	$(e).addClass("button-mousedown");
	$(e).find(".button-inner").animate({"top": "2px", "left":"2px"},75)
}

function buttonMouseUp(e){
	$(e).find(".button-inner").animate({"top": "0px", "left":"0px"},75, function(){
		$(e).removeClass("button-mousedown");
	})
}

function buttonSetHoverOn(e){
	$(e).addClass("button-hover")
}

function buttonSetHoverOut(e){
	$(e).removeClass("button-hover")
	if( $(e).hasClass("button-mousedown") ){
		buttonMouseUp(e)
	}
}
/* 
Function animates the loading of a new page. Including the actual AJAX loading of the content of the new page.
newPageLink - string - address of page which needs to be loaded
*/
function loadNextPage(newPageLink){
	var currentContainer = $( "#"+$("#containers").data("currentContainer") )
	var nextContainer = $( "#"+$("#containers").data("nextContainer") )	
	var currentLanguage = $("html").attr("lang")

	var hideLeft = currentContainer.data("hideLeft")
	var hideSpeed = currentContainer.data("hideSpeed")
	var displaySpeed = nextContainer.data("displaySpeed")
	var delaySpeed = nextContainer.data("delaySpeed")
	var showLeft = nextContainer.data("hideLeft") + 1
	var pageExitDirection = showLeft < 0 ? -1 : +1
	
	newPageLink = String(newPageLink)	
	newHash = newPageLink.split(".nl/")
	newHashLink = "http://www.jansons.nl/"+newHash[newHash.length-1]
	googleAnalyticsPageFileName = "/"+newHash[newHash.length-1]
	newHash = "#!"+newHash[newHash.length-1]

	currentUrl = window.location.href.split("#")	
	currentLink = $("#documentsettings input[name='url-"+$("html").attr("lang")+"']").val()
	if(currentLink.length>1){
		currentLink = currentLink+"/"
	}
	currentLink = "http://www.jansons.nl/"+currentLink

	samePage=true;
	if(currentLink != newHashLink || currentLink != newPageLink ){
		samePage= false;
	}
	if(currentLink == "http://www.jansons.nl/portfolio/alles/" || currentLink == "http://www.jansons.nl/portfolio-english/everything/" ){
		if("http://www.jansons.nl/portfolio/" == newHashLink || "http://www.jansons.nl/portfolio-english/" == newPageLink ){
			samePage= true;
		}
	}
	if(currentLink == "http://www.jansons.nl/portfolio/" || currentLink == "http://www.jansons.nl/portfolio-english/" ){
		if("http://www.jansons.nl/portfolio/alles/" == newHashLink || "http://www.jansons.nl/portfolio-english/everything" == newPageLink ){
			samePage= true;
		}
	}

//	msg("samePage: "+samePage +"<br/><br/>"+"win.loc.h.len: "+window.location.hash.length+"<br/><br/>"+"currentLink: "+currentLink +"<br/><br/>"+"currentUrl: "+ currentUrl[0]+"<br/><br/>"+"newHashLink: "+newHashLink+"<br/><br/>"+"win.loc.h: "+window.location.hash+"<br/><br/>"+"newpageLink: "+newPageLink)

	if( !($("#content").hasClass("pageloading")) &&  samePage == false ){
		$("#content").addClass("pageloading")
		
		//disable menu items
		menuDisable()
		
		//add adress to browserhistory plugin
		pageReload=false;
		jQuery.bbq.pushState(newHash,2)

		//registrar new page to google analytics
		_gaq.push(['_trackPageview', googleAnalyticsPageFileName]);
					
		//set MenuItemSelector
		setMenuItemSelector( newPageLink )
	
		//disable horizontal scrolbars on document.window
		$("body").css({"overflow-x": "hidden","margin": "0"})

		//start of animations
		//hide currentContainer
		currentContainer.queue("currentContainerAnimOne",function(){
			$(this).animate({'top':0+"px",'left': (pageExitDirection*50)+"px"},400,function(){
				$(this).css({"z-index":"0"})
			 })
		})
		
		currentContainer.queue("currentContainerAnimTwo",function(){
			$(this).animate({ left: hideLeft+"px"},hideSpeed,function(){
				
				//clears currentContainer of HTML elements (in order to eliminate double "ID"'s if content in currentContainer and nextContainer is simular)
				$(this).html("");
				//removes page-class of currentContainer. Since the actual pageClass is unknown, all classes are deleted, after which the class "container" is added
				$(this).hide()
				$(this).removeClass().addClass("container");

				if($(this).parents("#content").find("input[name='javascriptUnloadAfterUnshow']").val().length > 0){
					func = $(this).parents("#content").find("input[name='javascriptUnloadAfterUnshow']").val()+"()"
					var myFunc = new Function(func);
					myFunc();
				}

			})
		})

		if(currentContainer.parents("#content").find("input[name='javascriptUnloadBeforeUnshow']").val().length > 0){
			func = currentContainer.parents("#content").find("input[name='javascriptUnloadBeforeUnshow']").val()+"()"
			var myFunc = new Function(func);
			myFunc();
		}

		currentContainer.dequeue("currentContainerAnimOne").dequeue("currentContainerAnimTwo");
		
		//load new content
		// set all other page elements to new content. 
		// function fires after new content is animated 1px, so nextContainer has correct heigth and width 

		nextContent = document.createElement("div");
		$(nextContent).load(newPageLink + " #content", function(){

			//add pageClass to nextContainer
			nextContainer.addClass( $(nextContent).find("input[name='pageClass']").val() )
			
			nextContainer.show().html( $(nextContent).find(".main") )
			
			nextContainer.queue("nextContainerAnimOne",function(){
				$(this).animate({ left:(showLeft +10)+"px"},10,function(){

					//set new documentssettings in <form name="documentsettings" id="documentsettings" />
					$("#documentsettings input[name='language']").val( $(nextContent).find("#documentsettings input[name='language']").val() )
					$("#documentsettings input[name='title']").val( $(nextContent).find("#documentsettings input[name='title']").val() )
					$("#documentsettings input[name='canonical']").val( $(nextContent).find("#documentsettings input[name='canonical']").val() )					
					$("#documentsettings input[name='pageClass']").val( $(nextContent).find("#documentsettings input[name='pageClass']").val() )
					$("#documentsettings input[name='url-nl']").val( $(nextContent).find("#documentsettings input[name='url-nl']").val() )
					$("#documentsettings input[name='url-en']").val( $(nextContent).find("#documentsettings input[name='url-en']").val() )	
					$("#documentsettings input[name='opengraphdescription']").val( $(nextContent).find("#documentsettings input[name='opengraphdescription']").val() )						
					
					$('head meta[name=keywords]').attr('content', $(nextContent).find("#documentsettings input[name='keywords']").val() );
					$('head meta[name=description]').attr('content', $(nextContent).find("#documentsettings input[name='description']").val() );

					$('head meta[property=og:title]').attr('content', $(nextContent).find("#documentsettings input[name='title']").val() );
					$('head meta[property=og:url]').attr('content', $(nextContent).find("#documentsettings input[name='canonical']").val() );
					$('head meta[property=og:description]').attr('content', $(nextContent).find("#documentsettings input[name='opengraphdescription']").val() );
					
					//add javascript behaviour to AJAXloaded content. If animation stutters software engineer decides which behaviour can be put in function performed in <input name="javascriptInitBeforeShow"> and <input name="javascriptInitAfterShow">
					if($(nextContent).find("input[name='javascriptInitBeforeShow']").val().length > 0){
						func = $(nextContent).find("input[name='javascriptInitBeforeShow']").val()+"()"
						var myFunc = new Function(func);
						myFunc();
					}
					
					//translate Menu & set language settings
					translateDesign( $(nextContent) )
					
					//Change footer
					setFooterTop($("#containers").data("nextContainer"))
					
					setFooterContent( $(nextContent) )
					//set MenuItemSelector (for the newFooter)
					setMenuItemSelector( newPageLink )
	
					//set Document Title (does not use jQuery $("title").text( titleString ) as it misteriously crashes in IE7.
					document.title = $(nextContent).find("input[name='title']").val()
					$("head link[rel='canonical']").attr("href", $(nextContent).find("#documentsettings input[name='canonical']").val() )
					
					//show nextContainer
					resizeViewport(); //so header will not be displayed under the sidebars
				})
			})
			
			nextContainer.queue("nextContainerAnimTwo",function(){
				$(this).animate({ left: (pageExitDirection*-18)+"px"},displaySpeed,function(){
					$(this).css({"z-index":"1001"})
				})
			})
			
			nextContainer.queue("nextContainerAnimThree",function(){
				$(this).animate({top:0+"px", left: (pageExitDirection*2)+"px"},250)
			})

			nextContainer.queue("nextContainerAnimFour",function(){
				$(this).animate({left:"0px",top:"0px"},125, function(){
					//add javascript behaviour to AJAXloaded content. If animation stutters software engineer decides which behaviour can be put in function performed in <input name="javascriptInitBeforeShow"> and <input name="javascriptInitAfterShow">
					if($(nextContent).find("input[name='javascriptInitAfterShow']").val().length > 0){
						func = $(nextContent).find("input[name='javascriptInitAfterShow']").val()+"()"
						var myFunc = new Function(func);
						myFunc();
						window[ $(nextContent).find("input[name='javascriptInitAfterShow']").val() ]()
					}
					
					//gracefull degredation: set the CSS if jQuery.animate fails.
					nextContainer.css({"left":"0px"})
					
					setFooterTop(nextContainer.attr("id"),0)
					$("#containers").data({
						"currentContainer" : nextContainer.attr("id"),
						"nextContainer" : currentContainer.attr("id")
					})
					
					//update <form id ="documentsettings" />
					$("#documentsettings input[name='javascriptInitBeforeShow']").val( $(nextContent).find("#documentsettings input[name='javascriptInitBeforeShow']").val() )
					$("#documentsettings input[name='javascriptInitAfterShow']").val( $(nextContent).find("#documentsettings input[name='javascriptInitAfterShow']").val() )	
					$("#documentsettings input[name='javascriptUnloadBeforeUnshow']").val( $(nextContent).find("#documentsettings input[name='javascriptUnloadBeforeUnshow']").val() )
					$("#documentsettings input[name='javascriptUnloadAfterUnshow']").val( $(nextContent).find("#documentsettings input[name='javascriptUnloadAfterUnshow']").val() )	

					// set new pageAdresses to translationElements in document
					setPageAdressToTranslationElement()
					//enable menu
					menuEnable()
					$("body").css({"overflow-x": "visible"})
					$("#content").removeClass("pageloading")
					$(nextContent).remove();
				})
			})

		nextContainer.dequeue("nextContainerAnimOne").delay(delaySpeed).dequeue("nextContainerAnimTwo").dequeue("nextContainerAnimThree").dequeue("nextContainerAnimFour")
		})
	}
}

/* 
Function sets the selected item in the menu to "menu-item-selected"
pageLink - string - link of page which is selected.
*/
function setMenuItemSelector(pageLink){
	var currentLanguage = $("html").attr('lang')	
	menuLink = String(pageLink).split(".nl/")
	menuLink = menuLink[1].split("/");
	if(menuLink[0].length > 0){
		menuLink[0] += "/"
	}
	menuLink = "http://www.jansons.nl/"+menuLink[0]
	var e = $("a[href$='"+menuLink+"']")

	//if menu item is not a "translationbutton"
	if( !e.hasClass("translate") ){
		//set the menuItemSelector
		$(".menu-item-selected").removeClass("menu-item-selected")
		$(e).parent().addClass("menu-item-selected")
	}
}
/* 
Function sets every translationElement.data(language).pageAdress in document to the clickedElement.data(translationElement.translateTo).pageAdress. A translationElement has extra data added: translationElement.data(languages).translateTo
e - jQuery HTML object - Element on which is clicked. (clickedElement)
*/
function setPageAdressToTranslationElement(){
	var currentLanguage = $("html").attr('lang')

	//search through all <a> elements to see if it is a translationElement
	$("a").each(function(key,translationEl){
		//if <a> is a translationElement
		if($(translationEl).data(currentLanguage) && $(translationEl).data(currentLanguage).translateTo){
			// set translationElement.href
			translateLink = $("#documentsettings input[name='url-"+ $(translationEl).data(currentLanguage).translateTo +"']").val()
			if(translateLink.length > 0){
				translateLink +="/"
			}
			translateLink = "http://www.jansons.nl/"+translateLink;
			$(translationEl).attr("href", translateLink)
			//set pageAdress of translationElement
			$(translationEl).data("nl").pageAdress = $("#documentsettings input[name='url-nl']").val()
			$(translationEl).data("en").pageAdress = $("#documentsettings input[name='url-en']").val()
		}
	})
}

/* 
Function sets the variables for the menu items and the <html> attribute "lang". The Javascript which is commented out is Javascript which return the different menu item settings in CSS code in a string ing HTML.
nextContent - jQuery HTML object - <div> in which the <div id="content"> content of the next page has been loaded.
*/
function translateDesign(nextContent){
	var nextLanguage = nextContent.find("input[name='language']").val()
	var currentLanguage = $("html").attr("lang")
//	var css=""

	if( currentLanguage != nextLanguage ) {

		var menulinks = $("#menu a");
		var menuMarginRight = 11; //margin-right in px of last menu > li
		var liMarginLeft = 26;
		var liLeft = 0
		var speed = $("#"+$("#containers").data("nextContainer")).data("delaySpeed") + $("#"+$("#containers").data("nextContainer")).data("displaySpeed")

		//set state of menu in CSS to "translation in progress"
		$("#header").removeClass("translate_disabled").addClass("translate_enabled")		

		//change adresses in logo
		$("#logo").attr("href", "http://www.jansons.nl/"+$("#logo").data(nextLanguage).pageAdress )

		//calculating CSS "left" value of first <li> in menu		
		liLeft = parseInt($("#menu").css("width").substring(0, $("#menu").css("width").length - 2))
		
		$.each(menulinks, function(key) {
			liLeft -= $(this).data(nextLanguage).wordLength
		})
		liLeft -= (menulinks.length -1 )* liMarginLeft
		liLeft -= menuMarginRight

		//change each menu item
		$.each(menulinks, function(key) {

				var width = $(this).data(nextLanguage).wordLength

				var bgPosition = $(this).data(nextLanguage).BGImageStart +"px -54px"

				//change menu item links
				$(this).attr("href", "http://www.jansons.nl/"+$(this).data(nextLanguage).pageAdress )

				//change backgroundimages to new language


				//$(this).animate({"background-position": bgPosition},speed,function(){
				//$(this).animate({"opacity": "0","filter": ""},100,function(){
/*
					if(key == ($("#menu li a").length - 1) ){
						//change classname in Body
						bodyClassOld = "language-"+currentLanguage;
						bodyClassNew = "language-"+nextLanguage;
						$("body").removeClass(bodyClassOld).addClass(bodyClassNew)			

						//set current language of HTML document
						$("html").attr("lang", nextLanguage).attr("xml:lang", nextLanguage)
						
						//set text in menu element "translate"
						$(this).html($(this).data(nextLanguage).translateText);

						//set state of menu in CSS to "translation finished"
						$("#header").removeClass("translate_enabled").addClass("translate_disabled")
					}
					*/
				//})
				//set text in menu element "translate"
				$(this).html($(this).data(nextLanguage).translateText);
				
				menulinks.fadeOut("fast")
				$(this).parent().animate({"width": width+"px", "top":"0","left":liLeft+"px"},speed, function(){
					if(key == ($("#menu li a").length - 1) ){
						//change classname in Body
						bodyClassOld = "language-"+currentLanguage;
						bodyClassNew = "language-"+nextLanguage;
						$("body").removeClass(bodyClassOld).addClass(bodyClassNew)			

						//set current language of HTML document
						$("html").attr("lang", nextLanguage).attr("xml:lang", nextLanguage)

						//set state of menu in CSS to "translation finished"
						$("#header").removeClass("translate_enabled").addClass("translate_disabled")
					}	
					menulinks.fadeIn("fast")
				})

			//calculate settings: return CSS value "left" and "width "in px for menu > li
//			css += ".language-"+nextLanguage +" #menu .menu-child-"+(key+1) +"{ <br/> width:"+ width +"px;<br>left:"+ liLeft +"px;<br>}<br>"

			//calculate CSS "left" value of next <li> in menu
			liLeft += width + liMarginLeft;
		})

	}

//calculate: return CSS value "left" and "width "in px for menu > li
//msg(css)
}

/* 
Function animates footer to new height according to height of content.
containerId - String - ID of the HTML element in which the content is placed (for instance: if footer needs to be placed under <div id="container1" />, value to be passed: "container1")
speed - Integer - Speed of animation in milliseconds - optional. If speed is 0, no animation will be used
newHeight - Integer - Number of pixels the footer.css.top needs to become - optional . If newHeight is passed, the standard marginFooter will not be used.
*/
function setFooterTop(containerId, speed, newHeight){

	var footer = $("#footer")
	var largeDistance = 30
	var oldHeight = parseInt($("#footer").css("top").substring(0, $("#footer").css("top").length - 2))-20
	if( $("#"+containerId).hasClass("page-portfolio") ) { 
		marginFooter = 0
	}
	else{
		var marginFooter = 100 // if newHeight is passed, the standard marginFooter will not be used.
	}
	
	if(!newHeight){
		var newHeight = parseInt( $("#"+containerId).find(".main").outerHeight(true) ) + marginFooter
	}

	if(speed == null) {
		var speed = $("#"+$("#containers").data("nextContainer")).data("delaySpeed") + $("#"+$("#containers").data("nextContainer")).data("displaySpeed")
	}

	//set heights for steps in animation
	var footerDirection = newHeight < oldHeight ? -1 : +1
	StepOne = parseInt( (footerDirection*-5)+parseInt(newHeight) )
	StepTwo = parseInt( (footerDirection*2)+parseInt(newHeight) )

	// if footer moves "a large distance" (var largeDistance)
	if(speed == 0){
		footer.stop().css({top: newHeight+"px"})
	}
	// if footer moves "a large distance" (var largeDistance)
	else if(newHeight < (oldHeight-largeDistance) || newHeight > (oldHeight+largeDistance)  ){
		footer.stop(false,false).animate({top: StepOne+"px"},speed, function(){
			footer.animate({ top: StepTwo+"px"},250,function(){
				footer.animate({ top: newHeight+"px"},125)
			})
		})
	}
	// if footer moves a short distance
	else if(!(newHeight == oldHeight)){
		footer.stop(false,false).animate({ top: newHeight+"px"},speed)
	}
}

/* 
Function sets the innerHTML of the footer to newfooter.innerHTML, if currentFooter.innerHTML != newfooter.innerHTML
nextContent - jQuery HTML object - <div> in which the <div id="content"> content of the next page has been loaded.
*/
function setFooterContent(nextContent){
	currentFooter = $("#content #footer")
	nextFooter = nextContent.find("#footer")

	if( currentFooter.html() != nextFooter.html() ){
		currentFooter.html( nextFooter.html())
		$(currentFooter).find(".geeky-bits a").unbind("click").click(function(){
			loadNextPage( $(this).attr("href") )
			return false;
		})
	}

}

/* 
Function resizes width sidebars (HTML elements left and right to the main content) to width of the browser
*/
function resizeViewport(){
	//calculate according to new width of browser viewport
	windowWidth = parseInt($(window).width())
	contentWidth = parseInt($("#content").css("width").substring(0, $("#content").css("width").length - 2));

	sidebarWidth= 0;
	if(windowWidth > contentWidth){
		sidebarWidth= Math.floor(( $(window).width() - contentWidth) / 2);
		$("#leftbar").css({width: sidebarWidth+"px"});
		$("#rightbar").css({width: sidebarWidth+"px"});
		if($("#sidemenu").length>0){
			var cvMenuTop = $("#sidemenu").css("top")
			$("#sidemenu").removeAttr("style").css({"top":cvMenuTop});
		}
	}
	else{	
		$("#leftbar").css({width: "0px"});
		$("#rightbar").css({width: "0px"});		

		if($("#sidemenu").length>0){
			$("#sidemenu").css({"left":windowWidth-194+"px"});
		}
	}
	
}

/* 
Function hides bar with controls in photogallery with the help of a global integer "timer".
*/
var timer = 0
function cboxControle_show(){
	visibleTime = 2000 // time in miliseconds in which the controlbar is visible.
	
	// only execute function when the controlbox is visible
	if( $('#cboxControlBar').hasClass("cbox-show") ){

		//kill setTimeout
		clearTimeouter()
		
		//show controlbar
		$('#cboxControlBar').fadeIn();
		
		//set new function to be executed after timeout
		timer = setTimeout(function() {				
			//hide controlbar if controlbar is not hovered on						
			if( !($('#cboxControlBar').hasClass("hover") ) ){
				$('#cboxControlBar').fadeOut()
			}
		}, visibleTime)
		
	}
}
/*
Function sets the global integer timer (which is used in hiding bar with controls in photogallery) to zero. See also function cboxControle_show
*/
function clearTimeouter(){
	if (timer != 0) {
		clearTimeout(timer);
		timer = 0;
	}
}

/*
global boolean: helps to determine if the browsers' "backward" and "forward" buttons are clicked when the window.location(.hash) is changed. Javascript cannot set or get values of the object "browserbutton". This global helps to determine if (one of) the browserbuttons is clicked. The standard value of the global is "true". The value is set to "false" (in javascript) everytime the window.location(.hash) is changed. If the global is not set to "false" (via javascript) when the window.location(.hash) is changed, the backward or forwardbutton is clicked, and the page should perform its "reload" action. The reloadaction ends with resetting the global boolean to "true".
*/
pageReload=false;

/* 
Function determines which elements behaviour should be triggered when the user clicks on the back/forward button of the browser. Any javascript which alters the windows.location should a) set the global boolean "pageReload" to "false"; and b) push the hash into the $.bbq.state (via the function $.bbq.pushState). "BBQ" is a plugin which documentation is found here: http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html.
*/
$(function(){
	$(window).bind( 'hashchange', function() {
		//add jQuery custom regular expression, as $(windows).bind fires before "$(document).ready"
		jQuery.expr[':'].Contains = function(a,i,m){
			return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
		};
		// if the hashchange event is fired without the use of any javascript (if hashchange is fired due to user pressing back/forwardbutton)
		if(pageReload==true){
			
			hashArray = window.location.hash.split("/")
			if (hashArray[0].length == 0){
				nextPageAddress = String(window.location)
			}
			else{
				nextPageAddress = "http://www.jansons.nl/"+String(window.location.hash).replace("#!","")
			}
			
			newVariablesArray = nextPageAddress.split(".nl/")
			newVariablesArray = newVariablesArray[1].split("/")
			
			if(newVariablesArray.length < 4){
				$("#cboxButtonClose").click()
				currentLinkArray = $("#documentsettings input[name='url-"+$("html").attr("lang")+"']").val().split("/")
				if( (currentLinkArray[0] == "portfolio" && newVariablesArray[0] == "portfolio" ) || (currentLinkArray[0] == "portfolio-english" && newVariablesArray[0] == "portfolio-english" )  ){
					if(newVariablesArray[1].length<1){
						if(newVariablesArray[0] == "portfolio"){
							newVariablesArray[1] = "alles"
						}
						else{
							newVariablesArray[1] = "everything"	
						}
					}
					setPortfolioFilter($("#portfolio-filter a:Contains('"+newVariablesArray[1]+"')"))
				}
				else{
					loadNextPage(nextPageAddress)
				}
			}
			else if(newVariablesArray.length > 3) {
				photo = newVariablesArray[2].replace(/-/g, " ")
				$(".creationphotos a:Contains('"+photo+"')").click();
			}		
		}
		//reset the global boolean to it default value
		pageReload=true;
	});
	$(window).trigger( 'hashchange' );
});

/* 
Function set facebookbuttons "like" and "send"
e - jQuery element - element in which the buttons need to be placed
*/
function setFacebookButtons(e) {  

	//Set the default values, use comma to separate the settings 
	var o = {  
		appID: '192564867460764',
		sendButton: false,
		buttonWidth: 500,
		buttonHeight: 20,
		showfaces: false,
		font: 'lucida grande',
		layout: 'normal',
		action: 'like',
		colorscheme: 'light'
	} 
	var dynUrl = jQuery("head link[rel=canonical]").attr("href");

	// Apply the like button to an element on the page and include all available options
	jQuery(e).find(".facebook-share .facebook-inner").html('<div id="fb-root"></div><fb:like href="'+dynUrl+'" width="'+o.buttonWidth+'" height="'+o.buttonHeight+'" show_faces="'+o.showfaces+'" font="'+o.font+'" layout="'+o.layout+'" action="'+o.action+'" colorscheme="'+o.colorscheme+'" send="false"/><div class="facebook-coverup"></div>');

	jQuery(e).find(".facebook-send .facebook-inner").html('<div id="fb-root"></div><fb:send href="'+dynUrl+'" font="'+o.font+'" /><div class="facebook-coverup-send-bottom"></div><div class="facebook-coverup-send-left"></div>');

//	FB.init({appId: o.appID, status: true, cookie: true, xfbml: true});
}

/* - Debugger
Function puts out message
msg - string - 	message which needs to be displayed
*/
function msg(msg, place){
	var place = "#leftbar"; 		
	var d = new Date();
	var h = d.getHours();
	var m = d.getMinutes();
	var s = d.getSeconds();
	var ms = d.getMilliseconds();
	$(place).html( $(place).html() +"<div class=\"errormessage\"><b>"+h+" : "+m+" : "+s+" : "+ms+" - msg:</b><br/>"+ msg +"</div>");
	$(place).css({"overflow-y":"scroll"})
}
