function log(output){
	try {
		console.log(output); 
	} catch(e) { 
		console = { 
			log: function(){} 
		}
		if ( typeof(firebug) != 'undefined' ){
			console.log =  function(output){firebug.log(output);}
			return true;		
		}
	}
}


$(document).ready( function(){
	QuickSearch.init();
	SearchBox.init();
	SearchBoxAdjust.init();
	TabContent.init();
	SpecificSearch.init();
	
	SendAFriend.init();
	
	// required by 404
	overallSearch.init();
	
	// GA event tracking
	ExternalLinks.init();
	
	// Execute functions that were added from within the template (sometimes we just need to)
	if ( typeof(onLoadFunctions) != 'undefined' && onLoadFunctions.length){
		for (var i=0; i< onLoadFunctions.length; i++){
			onLoadFunctions[i]();	
		}
	}
});


var HomePage = function() {
	function init() {
		Hero.init();
		initTabs();
		initAgenda();
		initNewsletter();
		initShare();
	}
	
	function initTabs() {
		$("ul.itabs li a").click(function() {
			var a = $(this);
			a.closest('ul').children().removeClass('active');
			a.closest('li').addClass('active');
			if(a.parent().attr("tab")) {
				a.closest('div').find('.tabcontent').hide();
				$("#"+a.parent().attr("tab")).show();
			}
		});
	}
	
	function initAgenda() {
		/* commented out for now, because it's not browser compatible atm
		$(".agendahome .description").each(function() {
			var block = $(this);
			var blockHeight = block.height();
			
			while(block.attr('scrollHeight') > blockHeight) {
				var txt = block.text();
				block.text(txt.substr(0, txt.length-4)+"...");
			}
		});
		*/
	}
	
	function initNewsletter() {
		$("#newslettersubscribe").submit(function() {
			var form = $(this);
			$.ajax({
				type: 'POST',
				url: form.attr('action'),
				data: form.serialize(),
				success: newsletterReturn,
				dataType: 'json'
			});
			return false;
		});
	}
	
	function newsletterReturn(data) {
		if (data.message) {
			$('div.newslettercol').html(data.message);
			initNewsletter();
		}
	}
	
	var sharepoptimer;
	var box;
	function initShare() {
		box = $("#shareOptions");
		$(".addthis_button").mouseover(function() {
			clearTimeout(sharepoptimer);
			box.show();
		}).mouseout(shareOut);
		
		box.mouseover(function() {
			clearTimeout(sharepoptimer);
		}).mouseout(shareOut);
	}
	function shareOut() {
		sharepoptimer = setTimeout(function() {
			box.hide();
		}, 400);
	}
	
	return {
		init: init
	}
}();

var Hero = function() {
	var locked = false; //locks the hero during transition
	var autoTimer;
	var curIndex = 0;
	var bullets; 
	var heroFader;
	var bodyFader;
	
	function init() {
		bullets = $("#hero-container .bullets a");
		heroFader = $("#herofader");
		bodyFader = $("#bodyfader");
		
		heroFader.css('opacity', 0);
		bodyFader.css('opacity', 0);
		$("#hero-container .extra:first").show();
		
		bullets.click(function() {
			var a = $(this);
			heroSwitchTo(bullets.index(a), 1000);
		});
		setAutoTimer();
	}
	
	function heroSwitchTo(index, fadeTime) {
		setAutoTimer();
		if(locked) return;
		
		curIndex = index;
		
		bullets.removeClass('active');
		bullets.eq(index).addClass('active');
		var color = bullets.eq(index).attr('c');
		index += 1;
		
		var heroImg = new Image();
		var bgImg = new Image();
		heroImg.src = "/img/hero/"+index+".jpg";
		bgImg.src = "/img/hero/"+index+"bg.jpg";
		
		heroImg.onLoad = heroSwitchImage(heroImg, bgImg, color, fadeTime)
		
	}
	
	function heroSwitchImage(heroImg, bgImg, color, fadeTime) {
		locked = true;
		bullets.parent().addClass("locked");
		
		
		if(heroFader.css('opacity') == 0) {
			heroFader.css('background-image', "url('"+heroImg.src+"')");
			bodyFader.css('background-image', "url('"+bgImg.src+"')");
			bodyFader.css('background-color', color);
			heroFader.fadeTo(fadeTime, 1, heroFadeDone);
			bodyFader.fadeTo(fadeTime, 1, heroFadeDone);
		}
		else {
			 $("#hero-container").css('background-image', "url('"+heroImg.src+"')");
			$("body").css('background-image', "url('"+bgImg.src+"')");
			$("body").css('background-color', color);
			heroFader.fadeTo(fadeTime, 0, heroFadeDone);
			bodyFader.fadeTo(fadeTime, 0, heroFadeDone);
		}
		
		$("#hero-container .extra").fadeOut(fadeTime).eq(curIndex).fadeIn(fadeTime);
		var bullet = bullets.eq(curIndex);
		if(bullet.hasClass("movie")) {
			$("#hero-container .playmovie").fadeIn(fadeTime).click(function() {
				location.href = bullet.attr('url');
			});
		} else {
			$("#hero-container .playmovie").fadeOut(fadeTime);
		}
	}
	
	function heroFadeDone() {
		locked = false;
		bullets.parent().removeClass("locked");
	}
	
	function setAutoTimer() {
		clearTimeout(autoTimer);
		autoTimer = setTimeout(function() {
			heroSwitchTo((curIndex + 1) % 4, 3000); 
		}, 8000);
	}
	
	return {
		init: init
	}
}();


/******************************
 * 
 * We should detect external clicks and track GA events
 * 
 ******************************/

var ExternalLinks = function(){
	
	function init() {
		$("a[href^='http:']:not([href*='" + window.location.host + "'])").each(function() {               
			$(this).click(function(){
				try {
					TexelTracker.trackEvent('Uitgaande links',$(this).attr('href'));
				} catch(err){}
				return true;
			});
		});
	}
	
	// Reveal public functions
	return {
		init: init
	}
}();



/******************************
 * 
 * Suggestion based QuickSearch that's available through entire site
 * 
 ******************************/
var QuickSearch = function(){
	
	var lastTimeout;
	var formContainer = null;
	var form = null;
	var input = null;
	var resultsEl = null; // This will be a div which contains the list that the ajax call returns
	var hasResults = false;
	
	var lastQuery = ''; // Store last searchquery here
	
	function init(){
		form = $('#quicksearch');
		if ( !form.length ){ return false; }
		
		formContainer = $('#quicksearch-container'); 
		input = $('#quicksearch-field');
		input.val(input.attr("sug")).addClass("sug");
		input.bind('keyup click', function(e){
			e.stopPropagation();// Otherwise event would bubble up to body (and closes the result thing)
			// remove last timeout so request only the last request gets send
			if (lastTimeout) clearTimeout(lastTimeout);
			// set a timeout: some people type faster than their shadows
			lastTimeout = setTimeout( search, 400);
		});
		input.focus(function() {
			var el = $(this);
			if(el.val() == el.attr("sug")) {
				el.val("");
				el.removeClass("sug");
			}
		});
		input.blur(function() {
			 var el = $(this);
			 if(el.val() == "") {
				el.val(el.attr("sug"));
				el.addClass("sug");
			}
		});
		
		form.submit(handleSubmit);
	}

	function search() {

		var query = input.val();
		if ( query == lastQuery || query.length <= 2){
			
			if ( hasResults ){
				showResults();	
			}
			return false;
			
		}else if( query == '' ){
			hideResults();
			hasResults = false;
			return false;
		}
		lastQuery = query;
		Ajax.doRequest( 'quicksearch' , { q:query }, handleSearch );
	}
	
	function handleSearch( resp ){

		// First initialize containers and events to show results
		if (! resultsEl ){
			resultsEl = $('<div></div>').attr('id', 'results-el').appendTo( formContainer ).click( handleResultContainerClick );
			
			$('#results-el li').live('mouseover', function(){
				$(this).addClass('hover');
			}).live('mouseout', function(){ 
				$(this).removeClass('hover')
			});
			// Make sure the resultbox closes when clicked outside it ( handleResultContainerClick prevents closing when clicking the results itself)
			$(document).click( function(e){
				hideResults();
			});
		}

		if ( parseInt(resp.data.count)  && resp.data.html != '' ){
			showResults(resp.data.html);
			hasResults = true
		}else{
			hideResults();
			hasResults = false;
		}

	}
	
	// Handle all clicks on the result a perform different actions based on the element that has been clicked
	function handleResultContainerClick( e ){
		
		if (e.target.id == 'view-all'){
			// This is the view all link obviously
			form.submit();
			return false;
		}
		var url = $(e.target).closest('li').find('a').attr('href');
		document.location.href = url;
		return false;
		
	}
	
	function hideResults( clear ){
		resultsEl.hide();
		
		if ( clear!= undefined && clear ){
			resultsEl.html('');
		}
	}
	
	function showResults( html ){
		if (!resultsEl){ return false;}
		
		if ( html != undefined ){
			resultsEl.html( html );
		}
		resultsEl.show();
	}
	
	function handleSubmit() {
		//change this, then also change SearchAndResultsManager.encodeSearchKey()
		var field = $("#quicksearch-field");
		if(field.val() == field.attr("sug")) {
			field.val("");
		}
		var val = encodeURIComponent($.trim(field.val()).replace(/\s+/g, "-").replace(/[\/\\]/g, ''));
		var form = $(this);
		//form.attr("action", form.attr("action") + "/" + val);
		location.href = form.attr("action") + "/" + val;
		return false;
	}
	
	// Reveal public functions
	return {
		init: init
	}
}();


/******
 * 
 * 	Searchbox contains code for the Slice & dice searchbox ( changing options based on what you choose)
 * 
 */
var SearchBox = function(){
	
	var selectedGroupType; // 1 (house)o r 0 (hotel)
	var _numberOfString = "";
	
	function init(){
		if ( !$('form#search-box').length ) {return false;}

		$('#grouptype').change( handleAccoTypeChange );
		$('#duration').change(handleDurationChange );
		
		$('#rooms').change(handleRoomAmountChange );
		
		$( '#home_search_submit').click( function(){
			submit();
			return false;
		});

		
		_numberOfString = $("label[for=rooms]").html();
		
		initDatePicker();
		initDatePicker("ticket_datepicker", null, "ticket");
		handleAccoTypeChange();
	}
	
	
	function initDatePicker( id, onSelectDate, prefix ){
		
		triggerElId = id || 'datepicker';
		if(prefix != undefined && prefix != "") prefix = prefix + "-";
		else prefix = "";
		
		// initialise the "Select date" link
		var startDate = new Date();
		var endDate = new Date(startDate.getFullYear() + 2, 11, 31);
		var startStr = startDate.getDate() + "/" + (startDate.getMonth()+1) + "/" + startDate.getFullYear();
		var endStr = endDate.getDate() + "/" + (endDate.getMonth()+1) + "/" + endDate.getFullYear();
		
		$('#' + triggerElId ).datePicker(
				// associate the link with a date picker
				{
					createButton:false,
					startDate:startStr,
					endDate:endStr
				}
			).bind(
				// when the link is clicked display the date picker
				'click', function(){

					updateSelects($(this).dpGetSelected()[0], prefix);
					$(this).dpDisplay();
					return false;
				}
			).bind(
				// when a date is selected update the SELECTs
				'dateSelected',	function(e, selectedDate, $td, state){
					updateSelects(selectedDate, prefix);
					if ( typeof( onSelectDate ) == 'function' ){
						onSelectDate();
					}
				}
			).bind( 'dpClosed',	function(e, selected){
					updateSelects(selected[0], prefix);
				}
			);

		bindSelectChange(triggerElId, prefix);
		// listen for when the selects are changed and update the picker
		
		
		// default the position of the selects to today
		var today = new Date();
		updateSelects(today.getTime(), prefix);
		
		// and update the datePicker to reflect it...
		$('#'+prefix+'pick-day').trigger('change');

	}
	
	function updateSelects( selectedDate, prefix ){
		var selectedDate = new Date(selectedDate);
		$('#'+prefix+'pick-day option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
		
		// Adjust it to work with leading zero's
		var month = (selectedDate.getMonth()+1).toString();
		var withLeadingZero = month.length == 1 ? '0' + month : month;
		$('#'+prefix+'pick-month option[value=' + withLeadingZero + ']').attr('selected', 'selected');
		$('#'+prefix+'pick-year option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');

	}
	
	function bindSelectChange(id, prefix) {
		$('#'+prefix+'pick-day, #'+prefix+'pick-month, #'+prefix+'pick-year')
		.bind(
			'change',
			function(){
				var d = new Date(
					$('#'+prefix+'pick-year').val(),
					$('#'+prefix+'pick-month').val() -1,
					$('#'+prefix+'pick-day').val()
				);
				$('#' + id).dpSetSelected(d.asString());
			}
		);
	}

	function handleAccoTypeChange(){
		var box = $("#grouptype");
		var val = box.val();
		var type = val.substr(0, val.indexOf("_"));
		var id = val.substr(val.indexOf("_") + 1);
		
		updateAdultSelect( id );

		selectedGroupType = type;
		switch(type) { 
			
			case "0":
				$("#search-box").addClass('type0');
				if ($("#input_days").length > 0) {	
					$("#duration").val("0");
					$("#input_days, #durationOtherLabel ").show();
					$("#periodSelect, #duration").hide();
				}
				if ($("#childSelect").length > 0) {
					$("#childSelect").show();
				}
				if ($("#arrivalSelect").length > 0) {
					$("#arrivalSelect").show();
				}
				break;
			default:
				$("#search-box").removeClass('type0');
				if ($("#periodSelect").length > 0) {	
					$("#duration,#periodSelect").show();
					$("#input_days,#durationOtherLabel").hide();
				}
				if ($("#childSelect").length > 0) {
					$("#childSelect").hide();
				}
				if ($("#arrivalSelect").length > 0) {
					$("#arrivalSelect").hide();
				}
				handleDurationChange();
			
			/*
			case "0":
				$("#duration").val("0");
				$("#input_days,#childSelect, #arrivalSelect, #durationOtherLabel ").show();
				$("#periodSelect, #duration").hide();
				break;
			default:
				$("#duration, #periodSelect").show();
				$("#childSelect, #durationOtherLabel, #arrivalSelect").hide(); 
				handleDurationChange();
			*/
		}
		
		$("#rooms-label").html(_numberOfString +' '+ gtUnits[box[0].selectedIndex]);
	}
	
	function handleDurationChange() {
		
		var val = $("#duration").val();
		//dirty solution with the selectedGroupType?
		switch(val) {
			case "0":
				$("#input_days, #arrivalSelect").show();
				$("#periodSelect").hide();
				break;
			case "14":
			case "21":
				$("#input_days, #periodSelect").hide();
				$("#arrivalSelect").show();
				selectedGroupType = 0;
				break;
			default:
				$("#input_days, #arrivalSelect").hide();
				$("#periodSelect").show();
				selectedGroupType = 1;
		}
	}
	

	function handleRoomAmountChange(){
		// Adjust max nr of people, based on selected amount of rooms ( i.e. with two rooms, max nr of people is doubled)
		var val = $("#grouptype").val();
		var id = val.substr(val.indexOf("_") + 1);
		updateAdultSelect(id);
	}
	
	
	function updateAdultSelect( groupTypeId ){
		
		// New since feb 2010: Take into account nr of accommodations
		var roomAmount = parseInt( $('#rooms').val(), 10 );
		
		if(gtIdsNumberOfPersons[groupTypeId]){
			var range = gtIdsNumberOfPersons[groupTypeId];
			if(range.length == 2) {
				var sel = $("#adults");
				var maximumPeople = range[1] * roomAmount;
				fillSelectWithNumbers(sel, range[0], maximumPeople);
			}
		}
	}
	
	function fillSelectWithNumbers( el, start, end ){

		if ( !el.length ) return false;
	
		var selected = el.val();	
		el.empty();
	
		for (var i = start; i <= end; i++) {
			var opt = $('<option></option>').text(i).attr('value', i).appendTo( el );
			if ( i == selected ){
				opt.attr('selected', 'selected');
			}
		}
	}

	function submit(){
		
		if ( $('#periodSelect').css('display') == 'none'){			
			var mydate = new Date();
			mydate.setHours(0);
			mydate.setMinutes(0);
			mydate.setSeconds(0);
			mydate.setMilliseconds(0);

			mydate.setFullYear( $('#pick-year').val(), parseFloat($('#pick-month').val(), 10)-1 ,$('#pick-day').val() );
		//	log(mydate);
			var gmtSeconds = mydate.getTimezoneOffset()*60;
			var tempvalue = parseInt((mydate.getTime() / 1000) - gmtSeconds);
			tempvalue = tempvalue + '-' + tempvalue;
			$('#arrival').val( tempvalue );
		}else{
			//log(2);
			$('#arrival').val( document.forms['search'].arrivalOptions.value ); 
		}

		$('#search-box').submit();
		return false;
	}
	
	return {
		init:init,
		initDatePicker:initDatePicker // Use this in multiple places
	}
}();



var SearchBoxAdjust = function(){
	
	var selectedGroupType; // 1 (house)o r 0 (hotel)
	var _numberOfString = "";
	
	function init(){
		if ( !$('form#search-adjust').length) {return false;}

		$("#search-adjust-toggler").click(function() {
			$('form#search-adjust').toggle();	
			return false;
		});
		if(openAdjust){
			$("#search-adjust-toggler").click();
		}

		$('#grouptype-adjust').change( handleAccoTypeChange );
		$('#duration-adjust').change(handleDurationChange );
		$('#rooms-adjust').change(handleRoomAmountChange );
		$("#search-adjust-submit").click( function() {
			submit();
			return false;
		});
		
		
		_numberOfString = $("#rooms-adjust-label").text();
		initDatePicker();
		handleAccoTypeChange();

	}
	
	
	function initDatePicker( id, onSelectDate ){
		
		triggerElId = id || 'datepicker-adjust';
		
		var startDate = new Date();
		var endDate = new Date(startDate.getFullYear() + 2, 11, 31);
		var startStr = startDate.getDate() + "/" + (startDate.getMonth()+1) + "/" + startDate.getFullYear();
		var endStr = endDate.getDate() + "/" + (endDate.getMonth()+1) + "/" + endDate.getFullYear();

		// initialise the "Select date" link
		$('#' + triggerElId).datePicker(
				// associate the link with a date picker
				{
					createButton:false,
					startDate:startStr,
					endDate:endStr
				}
			).bind(
				// when the link is clicked display the date picker
				'click', function(){

					updateSelects($(this).dpGetSelected()[0]);
					$(this).dpDisplay();
					return false;
				}
			).bind(
				// when a date is selected update the SELECTs
				'dateSelected',	function(e, selectedDate, $td, state){
					updateSelects(selectedDate);
					if ( typeof( onSelectDate ) == 'function' ){
						onSelectDate();
					}
				}
			).bind( 'dpClosed',	function(e, selected){
					updateSelects(selected[0]);
				}
			);

		// listen for when the selects are changed and update the picker
		$('#pick-day-adjust, #pick-month-adjust, #pick-year-adjust')
			.bind(
				'change',
				function(){

					var d = new Date(
						$('#pick-year-adjust').val(),
						$('#pick-month-adjust').val() -1,
						$('#pick-day-adjust').val()
					);
					$('#' + triggerElId).dpSetSelected(d.asString());
				}
			);
		
		// default the position of the selects to today
		var today = new Date();
		updateSelects(today.getTime());
		
		// and update the datePicker to reflect it...
		$('#pick-day-adjust').trigger('change');

	}
	
	function updateSelects( selectedDate ){
		var selectedDate = new Date(selectedDate);
		$('#pick-day-adjust option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
		
		// Adjust it to work with leading zero's
		var month = (selectedDate.getMonth()+1).toString();
		var withLeadingZero = month.length == 1 ? '0' + month : month;
		$('#pick-month-adjust option[value=' + withLeadingZero + ']').attr('selected', 'selected');
		$('#pick-year-adjust option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');

	}

	function handleAccoTypeChange(){
		
		var box = $("#grouptype-adjust");
		var val = box.val();
		var type = val.substr(0, val.indexOf("_"));
		var id = val.substr(val.indexOf("_") + 1);
		
		updateAdultSelect( id );
		
		selectedGroupType = type;
		switch(type) {
			case "0":
				if ($("#input_days-adjust").length > 0) {	
					$("#duration-adjust").val("0");
					$("#input_days-adjust, #durationOtherLabel-adjust").show();
					$("#periodSelect-adjust, #duration-adjust").hide();
				}
				if ($("#childSelect-adjust").length > 0) {
					$("#childSelect-adjust").show();
				}
				if ($("#arrivalSelect-adjust").length > 0) {
					$("#arrivalSelect-adjust").show();
					$("#periodSelect-adjust").hide();
				}
				break;
			default:
				if ($("#duration-adjust").length > 0) {	
					$("#input_days-adjust, #durationOtherLabel-adjust").hide();
					$("#periodSelect-adjust, #duration-adjust").show();
				}
				if ($("#childSelect-adjust").length > 0) {
					$("#childSelect-adjust").hide();
				}
				if ($("#periodSelect-adjust").length > 0) {
					$("#arrivalSelect-adjust").hide();
					$("#periodSelect-adjust").show();
				}
		}
		handleDurationChange();
		if (box[0].selectedIndex != undefined) {
			selIndex = box[0].selectedIndex;
		} else {
			selIndex = 3; // standaard op kamers
		}
		$("label[for=rooms]").html(_numberOfString +' '+ gtUnits[selIndex]);
	}
	
	function handleDurationChange() {
		var val = $("#duration-adjust").val();

		//dirty solution with the selectedGroupType?
		switch(val) {
			case "0":
				$("#input_days-adjust, #arrivalSelect-adjust").show();
				$("#periodSelect-adjust").hide();
				break;
			case "14":
			case "21":
				$("#input_days-adjust, #periodSelect-adjust").hide();
				$("#arrivalSelect-adjust").show();
				selectedGroupType = 0;
				break;
			default:
				$("#input_days-adjust, #arrivalSelect-adjust").hide();
				$("#periodSelect-adjust").show();
				selectedGroupType = 1;
		}
	}
	
	
	function handleRoomAmountChange(){
		// Adjust max nr of people, based on selected amount of rooms ( i.e. with two rooms, max nr of people is doubled)
		var val = $("#grouptype-adjust").val();
		var id = val.substr(val.indexOf("_") + 1);
		updateAdultSelect(id);
	}
	
	
	function updateAdultSelect( groupTypeId ){
		
		// New since feb 2010: Take into account nr of accommodations
		var roomAmount = parseInt( $('#rooms-adjust').val(), 10 );
		
		if(gtIdsNumberOfPersons[groupTypeId]){
			var range = gtIdsNumberOfPersons[groupTypeId];
			if(range.length == 2) {
				var sel = $("#adults-adjust");
				var maximumPeople = range[1] * roomAmount;
				fillSelectWithNumbers(sel, range[0], maximumPeople);
			}
		}
	}
	
	
	function fillSelectWithNumbers( el, start, end ){
	
		if ( !el.length ) return false;
	
		var selected = el.val();	
		el.empty();
	
		for (var i = start; i <= end; i++) {
			var opt = $('<option></option>').text(i).attr('value', i).appendTo( el );
			if ( i == selected ){
				opt.attr('selected', 'selected');
			}
		}
	}

	function submit(){
		if ( $('#periodSelect-adjust').css('display') == 'none'){			
			var mydate = new Date();
			mydate.setHours(0);
			mydate.setMinutes(0);
			mydate.setSeconds(0);
			mydate.setMilliseconds(0);
			mydate.setFullYear( $('#pick-year-adjust').val(), parseFloat($('#pick-month-adjust').val()) -1 ,$('#pick-day-adjust').val() );	
			var gmtSeconds = mydate.getTimezoneOffset()*60;
			var tempvalue = parseInt((mydate.getTime() / 1000) - gmtSeconds);
			tempvalue = tempvalue + '-' + tempvalue;
			document.forms['search-adjust'].arrival.value = tempvalue;
		}else{
			document.forms['search-adjust'].arrival.value = document.forms['search-adjust'].arrivalOptions.value ;
		}
	
		var durationOther = $('#durationOther');
		if (durationOther.css('display') == 'none'){
			// Hack to not send durationOther = 1 if it's not relevant
			durationOther.remove();
		}
		$('#search-adjust').submit();
		return false;
	}
	
	return {
		init:init,
		initDatePicker:initDatePicker // Use this in multiple places
	}
}();




/*******************************************************************************
 * 
 * This is the send-a-friend module
 * 
 ******************************************************************************/ 

var SendAFriend = function() {
	
	// Initialisation...
	function init(){
		// Setting send a friend link...
		$("a[href='#send-a-friend']").click( openPopup );
	}
	
	// Gets the form template...
	function openPopup(e){
		e.preventDefault();
		//win.open('', Array());
		win.loadUrl('/ajax/sendafriend_form', handle_getform );
		//Ajax.doRequest( 'sendafriend_form' , '', handle_getform );
		return false;
	}
	
	// Shows the form in the pop-up...
	function handle_getform(  ){
		//if ( resp.status ){
		//	win.open(resp.data.html, new Array());
			//win._setLoading(false);
			$('#win .close_popup').click( closePopup );
			$('#saf_send').click( sendEmail );
		//}
	}
	
	// Tries to send an email...
	function sendEmail(){
		var err = $('#win .popup_error:first'); // Error message holder
		var success = $('#win .popup_success:first'); // Success message holder
		var s_email = $('#saf_sender_email').val(); // Sender email
		var s_name = $('#saf_sender_name').val(); // Sender name
		var r_email = $('#saf_email').val(); // Recipient email
		var loc = window.location.href;
		var canonical = $('link[rel="canonical"]').attr('href');
		if(canonical) {
			loc = window.location.hostname + canonical;
		}
		
		// Hiding prievious errors...
		if(err.html().replace(/[\n\s]/gi,'') != ''){
			err.fadeOut('fast');
		}
		// Hiding prievious report...
		if(success.html().replace(/[\n\s]/gi,'') != ''){
			success.fadeOut('fast');
		}
		
		win._setLoading(true);
		Ajax.doRequest( 'sendafriend' , {s_email : s_email, s_name : s_name, r_email : r_email, url : loc}, handle_send );
	}
	
	// Handles sending responce...
	function handle_send( resp ){
		win._setLoading(false);
		
		// if there are errors in the input...
		if( resp.status == 2 || resp.status == 0){
			$('#win .popup_error:first').html(resp.message).fadeIn('slow');
		} else {
			$('#win .popup_success:first').html(resp.message).fadeIn('slow');
			$('#saf_sender_email').val('');
			$('#saf_sender_name').val('');
			$('#saf_email').val('');
		}
	}
	
	// Closes the pop-up...
	function closePopup(){
		win._hide();
	}
	
	return {
		init:init
	}
	
}();





/*******************************************************************************
 * 
 * Ajax object provides functionality for fetching remote content. ALL requests
 * should run through here, so that we can handle them in a uniform manner - and
 * add or adjust functionality  
 * 
 ******************************************************************************/ 

var Ajax = function(){

	var baseUrl =  '/ajax/';
	var queue = new Array();
	
	function doRequest( action , params, onSuccess, onFailure  ){

		var request = function(){
			$.ajax({
				type: 'GET',
				url: baseUrl + action ,
				data: params,
				success: handleSucceededRequest,
				error: handleFailedRequest,
				dataType: 'json'
			});
		};
		
		// Add to queue
		queue.push( { req: request, onSuccess: onSuccess, onFailure: onFailure} );

		// If no other requests are running , execute this one immediately
		if(queue.length == 1){
			request();
		}
	}
	
	function handleSucceededRequest( resp ){
		
		// Execute callback (if defined)
		if(queue[0].onSuccess){
			queue[0].onSuccess(resp);
		}
		// Remove request from queue
		queue.shift();
		
		// If needed, execute next request in queue
		if( queue.length ){
			queue[0].req();	
		}
	}
	function handleFailedRequest(){
		// Remove this request from the queue
		queue.shift();
		util.throwError('Seems to be a server side error request');
	}
	
	// Public functions
	return {
		doRequest: doRequest
	}	
}();

var util = function(){
	
	var loadingEl = null;
	
	function setLoading( loading ){

		if (!loadingEl){
			loadingEl = $('<div id="loading-indicator"></div>').appendTo('body');
		}
		if ( loading == undefined || loading  ){
			loadingEl.show();
		}else{
			loadingEl.hide();
		}
	}
	
	function throwError( msg ){
		setLoading(false);
		throw new Error( 'Texel Error: ' +  msg);
	}
	
	return {
		setLoading:setLoading,
		throwError: throwError
	};
	
}();


var SpecificSearch = function() {
	var _initialized = false;
	var _JQsearchForm;
	
	function init() {
		if(_initialized) {
			return;
		}
		_JQsearchForm = $('#search-specific-box');
		
		if ( !_JQsearchForm.length) {
			return false;
		}

		//enter button fix
		_JQsearchForm.find('input').keydown(function(e){
	        if (e.keyCode == 13) {
	            $(this).parents('form').submit();
	            return false;
	        }
	    });

		$("#search_specific_submit").click(submitForm);
		
		_JQsearchForm.submit(function(){
			
			submitForm();
			return false;
		});
		
		_initialized = true;
	}
	
	function submitForm() {	
		var goto = '';
		var value = $("#input-search-by-name").val();
		var action = _JQsearchForm.attr('action');
		if (value != '') {
			goto = action + value;
		} else {
			value = $("#input-search-by-accommodationnumber").val();
			goto = action + value; 
		}		
		window.location.href = goto;
		return false;
	}
	
	return {
		init:init
	};
}();




var TabContent = function() {
	var _initialized = false;
	
	function init() {
		if(_initialized) {
			return;
		}
		
		$("div.tabcontent").each(function() {
			var tabContent = $(this);
			tabContent.find("ul.tabs li").each(function(n) {
				if( this.className == "active") {
					tabContent.find("div.tab").eq(n).show();
				}
			});
		});
	
		//click action
		$("div.tabcontent ul.tabs li a").click(function() {
			var tabContent = $(this).parents('div.tabcontent');
	
			var scope = this;
			var index = -1;
			tabContent.find("ul.tabs li a").each(function(n) {
				if(scope.innerHTML == this.innerHTML) {
					index = n;
				}
			});
			
			tabContent.find("div.tab").hide().eq(index).show();
			tabContent.find("ul.tabs li").removeClass("active").eq(index).addClass("active");
			return false;
		});
		
		_initialized = true;
	}
	
	
	return {
		init:init
	};
	
}();

//and again it grows and grows, 100th function wins a prize!  (les)
// I inserted win object, did I won, Les? (Gintaras)


/*******************************************************************************
 * 
 * This is a pop-up window object.
 * 
 ******************************************************************************/ 
 
var win = {
	active : false,
	overlay : null,
	dialog : null,
	content: null,
	ie6 : navigator.userAgent.indexOf("MSIE 6")>=0 ,

	open : function ( message, buttons, type ){

		if (type != undefined) {
			this._setType(type);
		} else {
			this._setType('');
		}

		if( !this.dialog ){	this._createDialog();}

		this._setContent( message );
		this._setButtons( buttons );
		this._show();
	},
	loadUrl : function( url, callback ){
		this._setType('notificon');
		if( !this.dialog ){this._createDialog();}
		win._setLoading( true );
		$.get( url, function(data){
			win._setContent( data.data.html );
			callback();
			win._show();
			win._setLoading ( false);
		});

	},
	loadSpecUrl : function( url, callback, type ){
		this._setType(type);
		if( !this.dialog ){this._createDialog();}
		win._setLoading( true );
		$.get( url, function(data){
			win._setContent( data );
			callback();
			win._show();
			win._setLoading ( false);
		});

	},
	_setType: function(type){
			this.winContentClass  = type;
			this.winDialogClass = type;
			this.winLoadingClass = type;
	},
	_toggleAllSelects : function ( show ){
		if(show){
			$('#site select').css('visibility', 'visible');
		}else{
			$('#site select').css('visibility', 'hidden');
		}
	},
	_setButtons: function(buttons){
		this.buttonContainer.html('');

		if( typeof(buttons) == 'object' && buttons.length){
			for( var i=0; i<buttons.length; i++){
				this.buttonContainer.append(buttons[i]);
			}
		}else{
			this.buttonContainer.append(buttons);
		}

	},
	_setContent : function( content ){
		this.winContent.html( content );
	},
	_clearContent : function(){
		this.winContent.html('');
		this.buttonContainer.html('');
	},
	_show : function(){
		if (win.ie6){
			$('body').addClass('js');
			win._toggleAllSelects(false);
		}
		win.overlay.show();
		this.dialog.attr('class','');
		this.dialog.addClass(this.winDialogClass);
		this.winContent.attr('class','');
		this.winContent.addClass(this.winContentClass);
		win.dialog.show();
		win.active = true;
	},
	_hide : function(){
		if (win.ie6){
			$('body').removeClass('js');
			win._toggleAllSelects(true);
		}
		win.overlay.hide();
		win.dialog.hide();
		win._clearContent();
		win.active = false;

	},
	_createDialog : function(){
		this.overlay = 	$('<div></div>').attr('id', 'overlay').appendTo('body');
		this.winLoading = $('<div></div>').attr('id', 'win-loading').html('<img src="/img/ajax-loader.gif" />').appendTo('body');
		this.winContent = $('<div></div>').attr('id', 'win-content');
		this.winContent.addClass(this.winContentClass);
		this.winLoading.addClass(this.winLoadingClass);

		this.buttonContainer = $('<div></div>').attr('id', 'button-container-dynamic');
		// Put it all together and append to body
		this.dialog = $('<div></div>').attr('id', 'win').append( this.winContent ).append( this.buttonContainer ).appendTo('body');
	},
	_setLoading : function( loading ){
		if(loading){
			this.winLoading.attr('class','');
			this.winLoading.addClass(this.winLoadingClass);
			this.winLoading.show();
		}else{
			this.winLoading.css('display', 'none');
		}

	}
}


var Truncate = function(){
	
	var initialized = false;
	
	function init( readMoreText ){
		
		if (initialized){
			return false;
		}
		
		var maxLength = 100;
		var $toTruncate = $('p.truncate-me');
		
		$toTruncate.each( function(){
			
			var $p = $(this);
			var content = $p.html();
			
			if ( content.length > maxLength ){
				// Needs to be truncated
				var link = $('<a href="#">' + readMoreText + '</a>').click( function(){
					$(this).parent().hide().next('p').show();
					return false;
				});
				var truncated = $('<p>' + content.substring(0, maxLength) + '...</p>').append(link);
				$p.hide().before(truncated);
			}
		});
		
		initialized = true;
	}
	
	
	return {
		init:init
		
	};
	



}();

$(document).ready(
	function() {
		$('.add-to-cart').each(function() {
			var target = $(this);
			var p = target.parent('div.priceblock').find('select[name="edition"]');
			if (p.length > 0) {
				target.attr('href', target.attr('url') + p.val());
			}
		});
		
		$('select.edition').change(function() {
			var p = $(this).closest('div.priceblock').find('a.add-to-cart');
			p.attr('href', p.attr('url') + $(this).val());
		});
	});

	
function fly(fileID, width, height) {
	fly(fileID, width, height, 0);
}

function fly(fileID, width, height, scroll) {
	win = window.open(fileID , "fly", "menubar=0,scrollbars=" + scroll + ",toolbar=0,location=0,directories=0,status=0,resizable=1,width=" + width + ",height=" + height);
	win.resizeTo(width, height);	
}

function flyown(obj, width, height) {
	fly(obj.href, width, height, 1);
}	

function toggleLike(obj) {
	var entityId = obj.getAttribute('entityId');
	$.get('/ajax/like/?entityId=' + entityId, function(data) {
		if (data == '1') {
			alert('done');
		} else {
			alert('failed');
		}
	});
}

var overallSearch = function() {
	var firstLoad = true;
	var typeId = 0;
	var pageSwitch = false;	//set to true when switching page bij clicking (for faster loading)
	
	function init() {
		Pagination.init(searchGoto);
		History.init(pageLoad);
		initSearchFilter();
		$("#searchOverall").live('submit', submitOverallsearch);
	}
	
	function searchGoto(pageNumber) {
		var url = "p="+pageNumber;
		if(parseInt(typeId) > 0) {
			url += '&typeId='+typeId;
		}
		pageSwitch = true;
		History.add(url);
	}
	
	function pageLoad(hash) {
		if(firstLoad && hash == "") {
			$("#overallsearch").css('visibility', "visible");
			firstLoad = false;
			return;
		}
		
		var url = '?'+hash+'&inited=1';
		
		//load only results into resultlist if switching page by clicking pagination nav
		if(!pageSwitch) {
			var r = $("#resultlist");
			$("#overallsearch").load(url, function() {
				if(firstLoad) {
					$("#overallsearch").css('visibility', "visible");
					firstLoad = false;
				}
				Pagination.init(searchGoto);
			});
			
		}
		else {
			//fast page switching: load only result list
			url += '&switchpage=1';
			var container = $("#resultlist");
			container.load(url);
			var r = /p=(\d+)/;
			var p = 1;
			if(hash.match(r)) {
				p = parseInt(RegExp.$1);
			}
			Pagination.setPage(p);
			pageSwitch = false;
		}
		
		//set filter styles
		if(hash.indexOf("typeId") != -1) {
			if(hash.match(/typeId=(\d+)/)) {
				typeId = parseInt(RegExp.$1);
				setTypeFilterView();
			}
		}
	}
	
	function initSearchFilter() {
		// unbind first to not have double binding
		$("#typeSearchFilter").find("a").unbind('click');
		$("#typeSearchFilter").find("a").click(function() {
			var newTypeId = $(this).closest("li").attr("typeid");
			if(newTypeId == typeId) {
				typeId = 0;
			} else {
				typeId = newTypeId;
			}
			setTypeFilterView();
			applyTypeFilter(typeId);
		});
	}
	
	//set the type filter styles
	function setTypeFilterView() {
		var lis = $("#typeSearchFilter li");
		lis.removeClass("inactive applied");
		lis.filter("[typeid="+typeId+"]").addClass("applied");
	}
	
	//load the results
	function applyTypeFilter(typeId) {
		var url = "";
		if(parseInt(typeId) > 0) {
			url += '&typeId='+typeId;
		}
		
		History.add(url);
	}
	
	function submitOverallsearch() {
		$("#quicksearch-field").val($(this).children("input:first").val());
		$("#quicksearch").submit();
		return false;
	}
			
	
	return {
		init: init
	}
}();

/*
 * Use history for ajax calls that generate a page (outside slice&dice). Its 'pageload' function is called after: 
 * 		- a pageload (of course) 
 * 		- calling the add function 
 * 		- clicking the browsers back or forward button
 */ 
var History = function(){

	function init(callback){
		$.history.init(callback);
	}
	
	function add( hash ){
		$.history.load(hash);
	}
	return {
		init:init,
		add:add
	};
}();


/*
 * build a standard, non-slicedice pagination. works with pagination.html template
 * @param goTo function handle to handle click events
 */
var Pagination = function() {
	var total = 0;
	var limit = 0;
	var currentPage = 1;
	var goToHandle;
	var nextLink = null;
	var prevLink = null;
	var pages;
	var paginationContainers;
	
	function init(goToFunc) {
		goToHandle = goToFunc;
		
		var ptotal = $("#ptotal").val();
		var plimit = $("#plimit").val();
		var pcurrentPage = $("#pcurrentPage").val();
		if(ptotal != "") total = parseInt(ptotal);
		if(plimit != "") limit = parseInt(plimit);
		if(pcurrentPage != "") currentPage = parseInt(pcurrentPage);
		
		paginationContainers = $('div.pagination'); 
		
		// Calculate pagination values
		pages = Math.ceil(total/limit);
		nextLink = $('a.p-next').click( function(){
			goTo( Math.min( (currentPage+1), pages ) );
			scroll(0,0);
		});
		
		prevLink = $('a.p-previous').click( function(){
			goTo( Math.max( (currentPage-1), 1 ) );
			scroll(0,0);
		});
		
		build();
	}
	
	function build() {
		if ($('#disablePagination').val() != '1') {
			buildPagination();
		}
	}
	
	function buildPagination() {
		
		var firstInCurrentSet = ( (currentPage-1) * limit ) + 1;
		var lastInCurrentSet = Math.min( (currentPage * limit), total ); 
		
		// Display numbers in text
		$('ul.p-total-pages', paginationContainers).text( pages );
		$('span.p-total-results', paginationContainers).text( total );

		$('span.p-first-in-set', paginationContainers).text( firstInCurrentSet );
		$('span.p-last-in-set', paginationContainers).text( lastInCurrentSet );
		
		
		// Bind page link events once here, with 'live'			
		$('ul.p-pages li').live( 'click', function(){
			if ( currentPage == parseInt( $(this).text()) ){
				return false;
			}
			goTo( $(this).text() );					
			scroll(0,0);
		});
		
		// Hide next and previous when needed
		if ( currentPage == pages ){
			nextLink.css('visibility', 'hidden');
		}else{
			nextLink.css('visibility', 'visible');
		}
		if ( currentPage == 1){
			prevLink.css('visibility', 'hidden');
		}else{
			prevLink.css('visibility', 'visible');
		}
		
		// Build a list with all page numbers
		var toShow = 5;
		
		var firstToShow = Math.max( (currentPage -  Math.floor(toShow/2)  ), 1);
		var lastToShow = Math.min( Math.max ( currentPage + Math.floor(toShow/2), toShow ), pages);
		
		var items = [];
		for ( var i = firstToShow; i <= lastToShow ; i++ ){
			if( currentPage != i ){
				items.push('<li>', i, '</li>');
			}else{
				items.push('<li class="current">', i, '</li>');
			}
		}
	
		$('ul.p-pages').html( items.join('') );
		if(pages == 1) {
			$(".page-info").css("visibility", "hidden");
		}
		else {
			$(".page-info").css("visibility", "visible");
		}
	}
	
	function goTo(pageNumber) {
		setPage();
		goToHandle(pageNumber);
	}
	
	/**
	 * for external page switching, this will update the pagination
	 */
	function setPage(pageNumber) {
		currentPage = pageNumber;
		build();
		//updateStyle();
	}
	
	function updateStyle() {
		var pages = $('ul.p-pages');
		pages.each(function() {
			$(this).children().removeClass("current");
			$(this).children().eq(currentPage-1).addClass("current");
		});
	}
	
	return {
		init: init,
		setPage: setPage
	}
	
}();


