﻿$(document).ready(function () {
	
	window.virtualtournav?virtualtournav():null;
	window.photobook?photobook():null;
	window.languagePicker?languagePicker():null;
	window.photobook?photobook():null;
	window.randomHeader?randomHeader():null;
	window.shoppingCart?shoppingCart():null;
	window.enhanceIntFields?enhanceIntFields():null;
	window.autoSubmit?autoSubmit():null;
	window.contactEqualsDelivery?contactEqualsDelivery():null;

/* listen for keypresses */
	if ($.browser.mozilla) {
		$(document).keypress(checkKey);
	} else {
		$(document).keydown(checkKey);
	}
});

/* virtual tour navigation */
function virtualtournav(){
	$('#virtualtournav>li>a').click(function () {
	
		$('#virtualtournav>li>a').removeClass('active');
		$(this).addClass('active');
		$('#upstairs, #downstairs, #window').hide();
		$($(this).attr('href')).show();
		
		return false;
	
	});
	}

/* photobook search */
function photobook(){
	$('#photobooksearch').submit(function () {
		
		var keyword = $("input#searchphoto").val();
		
		$('#photobookresults').empty();
		$('#photobookresults').show();
		
		$.post("results.lasso", { keyword: keyword },
		function (data) {

			$('#photobookresults').append(data);
			
		});
		
		return false;
		
	});
	}
/* Keystroke actions */	
function checkKey(e) {
		switch (e.keyCode) {
			case 37:
				if($('.previous').attr('href') != undefined) {
					window.location = $('.previous').attr('href');
				}
				/* carousel nav */
				if($('#controls .prev').length>0){
					scrollimage(-1);
					}
				break;
			case 39:
				if($('.next').attr('href') != undefined){
					window.location = $('.next').attr('href'); 
				}
				if($('#controls .next').length>0){
					scrollimage(1);
					}
				break;
			default:
				break;
		}
}

function randomHeader(){
/* Random header */
	
	$('#headerdata').fadeIn(500, function() {
		setTimeout(function() {
			$('#headerdata').fadeOut(250);
		}, 4000);
	});

	$('#randomheader').hover(
		function () {
		
			$('#headerdata').fadeIn(250);
		
		},
		function () {
		
			$('#headerdata').fadeOut(250);
		
		}
	);
	
	$('#randomheader').click(function () {
	
		window.location = $('#randomheader>#headerdata>p>a').attr('href');
	
	});
	}

/* Language picker */

function languagePicker() {

 	if ($('#txt .nl').size() > 0 || $('#txt .fr').size() > 0) {
		$('#txt>h1').eq('0').prepend('<ul id="lang"><li><a class="active" href="#" title="en" onclick="return setLanguageTo(\'en\')">EN</a></li></ul>');	
 	}
 	
	if ($('#txt .nl').size()>0) {
		$('#lang').append('<li><a href="#" title="nl" onclick="return setLanguageTo(\'nl\')">NL</a></li>');
	}

	if ($('#txt .fr').size()>0) {
		$('#lang').append('<li><a href="#" title="fr" onclick="return setLanguageTo(\'fr\')">FR</a></li>');
	}
	if(cookie_get('langpref')) {
		setLanguageTo(cookie_get('langpref'));
	}
}

function setLanguageTo(lang) {
		
		if($('#txt .'+lang).size()>0){
			$('#lang>li>a.active').removeClass('active');
			$('#lang>li>a[title='+lang+']').addClass('active');
			$('body').removeClass('fr nl en EN NL FR');
			$('body').addClass(lang);
			cookie_set('langpref',lang,365*10,'/');
		}
		return false;
	}
// http://techpatterns.com/downloads/javascript_cookies.php //no need to reinvent the wheel
function cookie_set( name, value, expires, path, domain, secure )
	{
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires )
			{
			expires = expires * 1000 * 60 * 60 * 24; //days
			}
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}

function cookie_get( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function photobook() {
	//activate first img
	$('.scrollwrapper img:eq(0)').addClass('active');
	//add some padding to the right so scrolling looks better
	$('.scrollwrapper img:last').css('margin-right',$('.scrollwrapper').width());
	$('.next').click(function(){scrollimage(1)});
	$('.prev').click(function(){scrollimage(-1)});
	checkcontrols();
}
function scrollimage(dir){
	$('.scrollwrapper').stop(true,true); //finish current animations
	var activeindex = $('.scrollwrapper img').index($('.scrollwrapper img.active'));
	activeindex+=dir;
		if($('.scrollwrapper img:eq('+activeindex+')').length>0){
			//get .active width
			if(dir>0){
				var activewidth = $('.scrollwrapper img.active').width();
			}else{
				var activewidth = $('.scrollwrapper img:eq('+activeindex+')').width();
			}
			var currentscroll = $('.scrollwrapper').scrollLeft();
			var target = currentscroll+(activewidth*dir);

			$('.scrollwrapper').animate(
				{scrollLeft: target}
				,500,'linear');
			$('.scrollwrapper img.active').removeClass('active');
			$('.scrollwrapper img:eq('+activeindex+')').addClass('active');
			var carousel_content = $('.scrollwrapper img:eq('+activeindex+')').attr('title');
			$('#carousel_content').html(carousel_content.replace(/\n/g,'<br />'));
			/* check whether next/prev links should be enabled disabled */
			checkcontrols();
		}
	}
function checkcontrols(){
	var activeindex = $('.scrollwrapper img').index($('.scrollwrapper img.active'));
	if(activeindex==0){
			$('#controls .prev').addClass('disabled');
		}else{
			$('#controls .prev').removeClass('disabled');
		}
	if(activeindex==$('.scrollwrapper img').length-1){
		$('#controls .next').addClass('disabled');
	}else{
		$('#controls .next').removeClass('disabled');
	}
	}
function shoppingCart(){
	if($('#cart').size()>0){
		/* hardcoded '25px', not sure how else to do this without changing the css too much.
		 * if you change the 'top' position of the 'fixed' class, change this value too.
		 * */
		var toppos = 25;
		var top = parseInt($('#cart').offset().top,10) - parseInt($('#cart').css('margin-top').replace(/auto/, 0),10) - toppos;
			$(window).scroll(function (event) {
			  var y = $(this).scrollTop();
			  if (y >= top) {
					$('#cart').addClass('fixed');
			  } else {
					$('#cart').removeClass('fixed');
			  }
			});
		}
	}
var incrementImage='/_js/increment.png';
var decrementImage='/_js/decrement.png';
function enhanceIntFields()
	{
	var intFields = $('input.int');
	for(i=0;i<intFields.length;i++)
		{
		/* add - */
		img = document.createElement("img");
		img.setAttribute("src",decrementImage);
		img.setAttribute("alt","-");
		img.setAttribute("title","less");
		img.setAttribute("class","fieldmodify"); //good browsers
		img.setAttribute("className","fieldmodify"); //IE
		
		img.onclick = function(){incrementField(this.previousSibling.previousSibling,-1);};
		intFields[i].parentNode.insertBefore(img,intFields[i].nextSibling);
		
		/* add + */
		img = document.createElement("img");
		img.setAttribute("class","fieldmodify"); //good browsers
		img.setAttribute("className","fieldmodify"); //IE
		img.setAttribute("src",incrementImage);
		img.setAttribute("alt","+");
		img.setAttribute("title","more");
		
		img.onclick = function(){incrementField(this.previousSibling,1);};
		intFields[i].parentNode.insertBefore(img,intFields[i].nextSibling);
		
		intFields[i].onfocus = function(){this.select();}
		}
	}
function incrementField(field,amount,negative)
	{
	if((negative!=true && (parseInt(field.value)+amount)<0) ||isNaN(parseInt(field.value)))
		{
		field.value=0;
		field.setAttribute("value",0);
		if(field.onchange)
			{
			field.onchange();
			}
		return;
		}
	field.value=parseInt(field.value)+amount;
	field.setAttribute("value",parseInt(field.value));
	if(field.onchange)
		{
		field.onchange(); // force the onchange event
		}
	}
/* ******************************
submits forms when the selectbox has a class of 'submitonchange'
also hides submit buttons with class of 'jshide'
****************************** */
function autoSubmit()	{
	var listboxes = new Array;
	var uselesssubmitbuttons = new Array;
	listboxes = $('select.submitonchange');
	uselesssubmitbuttons = $('.jshide');
	for(i=0;i<listboxes.length;i++)
		{
		listboxes[i].onchange=function(){ submitForm(this);};
		}
	for(i=0;i<uselesssubmitbuttons.length;i++)
		{
		uselesssubmitbuttons[i].style.display='none';
		}	
	}
function submitForm(e){
	e.parentNode.parentNode.submit();
	}	
/* disable delivery fields if the checkbox  'contactequalsdelivery'is checked
and yes, i could've picked a longer id if I wanted to.
 */
function contactEqualsDelivery(){
	$('#contactequalsdelivery').change(function(){
				setDisabled('delivery',$(this).attr('checked'));
				$(this).blur();
				});
	/* just for IE, because the onChange event is so hard to get right */
	$('#contactequalsdelivery').click(function(){
		$(this).trigger( 'change' );
		});

	}

/* use this to enable/disable a bunch of input fields using their class name */	
function setDisabled(classname,which)
	{
	var fields = $('.'+classname);
	//console.log(fields);
		for(i=0;i<fields.length;i++)
			{
			//console.log(which);
			fields[i].disabled=which;
			/* needed for IE */
			if(which==true)
				{
				fields[i].style.backgroundColor='#ddd';
				}else{
				fields[i].style.backgroundColor='';
				}
			}
	}
