
function deObfuscate(s) {
	s = s.replace(/@d/g, '.');
	s = s.replace(/@s/g, '/');
	s = s.replace(/@@/g, '@');
	s = s.replace(/[a-zA-Z]/g, function(c) {
		return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
	});
	return s;
}

function clickOb(el) {
	var url = el.getAttribute('obs');
	window.location = deObfuscate(url);
	return false;
}

SplendiaSoftReadyHandlers = [ ];
SplendiaInjectionHandlers = [ ];

function runSoftReadyHandlers() {
	for (var i = 0; i < SplendiaSoftReadyHandlers.length; i++) {
		SplendiaSoftReadyHandlers[i]();
	}
}

function runInjectionHandlers() {
	for (var i = 0; i < SplendiaInjectionHandlers.length; i++) {
		SplendiaInjectionHandlers[i]();
	}
}

/*
var dtemp = new Date();
SplendiaInitialMilestone = {
	'name' : '(pre-handlers)',
	'hit' : dtemp.getTime()
};
SplendiaMilestones = [ ];
function addMilestone(name) {
	var dtemp = new Date();
	SplendiaMilestones.push({
		'name' : name,
		'hit' : dtemp.getTime()
	});
}

function logMilestones() {
	var last = SplendiaInitialMilestone;
	for (var i = 0; i < SplendiaMilestones.length; i++) {
		var current = SplendiaMilestones[i];
		console.log('' + (current.hit - last.hit) + 'ms: ' + current.name);
		last = current;
	}
}
*/

// from the old site
function CreateBookmarkLink() {
	var title = document.title;
	var url = location.href;

	if (title == '')
		title = "SPLENDIA – Luxury & Character Hotels";

	if (url == '')
		url = "www.splendia.com";

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");

	} else if (window.external) { // IE Favorite
		window.external.AddFavorite(url, title);

	} else if(window.opera && window.print) { // Opera Hotlist
		return true;
	}
}

function quoteString(str) {
    var c, i, l = str.length, o = '';
    for (i = 0; i < l; i += 1) {
        c = str.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '';
}

/*
function deObfuscate(s) {
	s = s.replace(/@d/g, '.');
	s = s.replace(/@s/g, '/');
	s = s.replace(/@@/g, '@');
	s = s.replace(/[a-zA-Z]/g, function(c) {
		return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
	});
	return s;
}
*/

// equal sized columns
function equalHeights()
{
	if ($('.home_layout').length > 0) {
		var containerH = $('.home_layout_wrapper').height() - 2;
		$('.home_layout_consumer').each(function() {
			if ($(this).hasClass('sub_column_right_with_borders')) {
				$(this).height(containerH - 20);
			} else {
				$(this).height(containerH);
			}
		});
	} else {
		var containerH = $('.sizer_parent').height();
		var headerAdjust = ($('.column_left_bot_box').length > 0) ? 209 : 0;
		$('.sizer_column_left').height(containerH - headerAdjust);
		$('.sizer_column_right').height(containerH);
	}
}

function cancelHeights()
{
	if ($('.home_layout').length > 0) {
		$('.home_layout_consumer').css('height', 'auto');
	}

	if ($('.column_left_bot_box').length > 0) {
		$('.column_left_bot_box').css('height', 'auto');
	}
	$('.sizer_column_left, .sizer_column_right').css('height', 'auto');
}

function balanceColumns()
{
	setTimeout(function() {
		equalHeights();
	}, 100);
}

function balanceColumnsSlow()
{
	setTimeout(function() {
		cancelHeights();
		equalHeights();
	}, 500);
}

function cancelBalanceColumns()
{
	cancelHeights();
}

/** 
 *	Splendia State object
 *
 *	This object holds a copy of all the javascript state that is required to build the
 *	site correctly on each page load, also to do things like make sure certain data
 *	parameters are available to javascript from the server side.
 *
 *	There are certain actions taken in the php code that requires coordination with the
 *	javascript functionality to enable or disable certain things, like popups, how they
 *	react to button clicks, etc.
 *
 	*** WARNING ****:	this object will most likely disappear because now, there are 
 						better ways to do this which dont involve being retarded
 */
var Splendia	=	new Object();
Splendia.UI		=	new Object();

Splendia.UI.showMessage = function(message,text,status)
{
	if(!message){
		text.replace("<br>","\n");
		text.replace("<br/>","\n");
		
		alert(text);
	}else{
		var type = (status == true) ? "success-message" : "error-message";
		message.attr("class","message "+type);
		message.html(text);
		message.show("slow");
	}
}

Splendia.UI.hideMessage = function(message)
{
	message.attr("class","message");
	message.hide("slow");
	message.html("");
}

Splendia.Form = function(node,onSuccess,onMode)
{
	var __node;
	var __onSuccess;
	var __onMode;
	var __onSend;
	var __onComplete;
	
	this.constructor = function(node,onSuccess,onMode)
	{
		this.__node			=	$(node);
		this.__onSuccess	=	onSuccess || this.defaultSuccess;
		this.__onMode		=	onMode || this.defaultMode;
		this.__onSend		=	this.defaultSend;
		this.__onComplete	=	this.defaultComplete;		
		
		var	submit			=	$("input.submit_button:not(.change-recaptcha)",this.__node);
		var change			=	$(".change-recaptcha",this.__node);
		var	parentObject	=	this;
		
		this.reset();
		
		submit.click(function(){	return parentObject.send($(this));	});
		change.click(function(){	Recaptcha.reload(); return false;	});
		
		return this; 
	}
	
	this.reset = function()
	{
		this.resetFormErrors();
		Splendia.UI.hideMessage($(".message:not(.dont-erase)",this.__node));
	}
	
	this.defaultSend			=	function(node)	{ 											};
	this.setSendCallback		=	function(cb)	{	this.__onSend = cb;		return this;	};
	
	this.defaultComplete		=	function(node)	{											};
	this.setCompleteCallback	=	function(cb)	{	this.__onComplete = cb;	return this;	};
	
	this.defaultSuccess			=	function(node)	{											};
	this.setSuccessCallback		=	function(cb)	{	this.__onSuccess = cb;	return this;	};
	
	this.defaultMode			=	function(node)	{	return "ajax";							};
	this.setModeCallback		=	function(cb)	{	this.__onMode = cb;		return this;	};
	
	this.send = function(node)
	{
		this.__onSend(node);
		
		var mode = this.__onMode(node);
		
		switch(mode){
			case "post":	{	return this.sendPOST(node);	}break;
			case "ajax":	{	return this.sendAJAX(node);	}break;
		};
		
		return false;
	}
	
	this.sendPOST = function(node)
	{
		var form = node.parents().find("form").eq(0);
		
		this.reset();
		
		form.submit();
		
		return true;
	}
	
	this.sendAJAX = function(node)
	{
		var	form			=	node.parents().find("form").eq(0);
		var	sending			=	$(".sending",form);
		var	action			=	$("input[name='action']",form).attr("value") || form.attr("action");
		var	message			=	$(".message",form);
		var	parentObject	=	this;
		
		sending.css("visibility","visible");
		
		this.reset();
		
		$.post(action,form.serialize(),function(reply){
			parentObject.__onComplete(node);
			
			sending.css("visibility","hidden");
			
			Splendia.UI.showMessage(message,reply.message,reply.success);
			
			if(reply.success == false){
				parentObject.processFormErrors(reply.errors,form);
			}else{
				parentObject.__onSuccess(node);
			}
		},"json");
		
		return false;
	}
	
	this.resetFormErrors = function()
	{
		var element = $("[name]",this.__node);
		element.removeClass("form-error-border");
		if(element.attr("type") == "checkbox") element.parent().find("label").removeClass("form-error-background");
	}
	
	this.processFormErrors = function(errors,form)
	{
		for(var a=0;a<errors.length;a++){
			//	Special case when the recaptcha field is the incorrect field
			if(errors[a][0] == "recaptcha_response_field") Recaptcha.reload();
			
			var element = $("[name='"+errors[a][0]+"']",form);
			
			element.addClass("form-error-border");
			if(element.attr("type") == "checkbox") element.parent().find("label").addClass("form-error-background");
		}
	}
	
	return this.constructor(node,onSuccess,onMode);
}

Splendia.LoginForm = function(node,onSuccess,onMode)
{
	//	For the future, a customised version of the Form class
	
	//jQuery.extend(true,this,new Splendia.Form);
	//return this.constructor(node,onSuccess,onMode);
}

/******************************************************************************************
	FAQS SATELLITE OBJECT
******************************************************************************************/
var FAQS = function(){}
FAQS.setup = function()
{ 
	$('.faqs ul li a').click(function(ev) {
		var id = $(this).attr('id');
		$('.faqs .list #'+id+'b').slideToggle('fast');
		$('.faqs .list .entry:not(#'+id+'b)').hide();
	
		$(this).toggleClass('selected');
		$('.faqs ul li a:not(#' + id + ')').removeClass('selected');
		
		//	maybe content starts to overflow, call rebalance
		balanceColumns();
		
		return false;
	});
}

/******************************************************************************************
	JOBS SATELLITE OBJECT
******************************************************************************************/
var Jobs = function(){}
Jobs.setup = function()
{
	$(".jobs table tbody tr")
		.hover(
			function(){	$(this).addClass('b2');		},
			function(){	$(this).removeClass('b2');	}
		)
		.click(
			function(){ Jobs.show(this,$(this).attr("id"));	}
		);
}

Jobs.show = function(elem,id){
	$('#job' + id).slideToggle('fast');
	$('.entry:not(#job' + id + ')').hide();

	$(elem).toggleClass('b');
	$('.jobs table tr:not('+id+')').removeClass('b');
}

/******************************************************************************************
	TABROW OBJECT
******************************************************************************************/
var TabRow = function(tabs,popup)
{
	this.constructor = function(tabs,popup){
		var parentObject = this;
		
		$(tabs).each(function(){ 
			this.replace("#","");
			$("#"+this,popup).click(function(){ return parentObject.change($(this).attr("id")); });
		});
	}
	
	this.change = function(id){
		$('#tab_' + id,popup).show();
		$('.details_tabs_container .tab:not(#tab_'+id+')',popup).hide();
		$('#' + id,popup).addClass('selected');
		$('.details_tabs_container .tab_chooser li:not(#' + id + ')',popup).removeClass('selected');
		
		return false;
	}
	
	this.constructor(tabs,popup);
}

/******************************************************************************************
	POPUP OBJECT
******************************************************************************************/
var Popup = function()
{
	var __node;
	var __name;
	
	this.constructor = function(){
		this.reset();
		
		//	Setup all the registered methods for creating/controlling popups
		this.signIn();
		this.newsletter();
		this.booking();
		this.customerCare();
		this.sendToFriend();
		this.share();
		this.changeLang();
		this.changeCurr();
	};
	
	this.reset = function()
	{
		this.__node = false;
		this.__name = false;
	}
	
	this.show = function(node)
	{
		var samePopup = this.__name == ($(node).attr("id"));
		this.hide();

		if (!samePopup) {
			this.__node = $(".popup",$(node));
			this.__name = $(node).attr("id");

			$(this.__node).show();
			
			//	CARLOS: please document what this does and why we need it
			$(".label",this.__node).toggleClass("mini_popup_selected_opt");
		}
	};
	
	this.hide = function()
	{
		if(this.__node) $(this.__node).hide();
		this.reset();
	};
	
	this.compare = function(node)
	{
		return (this.__name == $(node).attr("id")) ? true : false;
	}
	
	this.stopAutocloser = function(popup)
	{
		$(".popup",popup).click(function(event){ event.stopPropagation(); });
	}
	
	this.setupLoginFocus = function(popup)
	{
		$("input[type='text']",popup).focus(function(){ this.value = "";});
		$("form .overlay .hideme",popup).focus(function(){ 
			$(this).css("display","none"); 
			$("form .overlay input[name='password']",popup).focus();
		});
	}
	
	this.setupFavouriteHover = function(open){
		open.hover(
			function(){ $("img",open).css("visibility","hidden"); }, 
			function(){ $("img",open).css("visibility","visible"); }
		);
	};
	
	this.showMessage = function(message,popup,text,status)
	{
		if(!this.compare(popup)) message = false;
		
		Splendia.UI.showMessage(message,text,status);
	}
	
	this.hideMessage = function(message)
	{
		Splendia.UI.hideMessage(message);
	}
	
	this.signIn = function()
	{
		var popup			=	$("#signin_link");
		var open			=	$(".label",popup);
		var forgot			=	$(".forgot",popup);
		var register		=	$(".register",popup);
		var	sending			=	$(".sending",popup);
		var form			=	$("form",popup);
		var message			=	$(".message",popup);
		var submit			=	$(".submit_button",form);
		var actionLogin		=	$("input[name='action_login']",form).val();
		var actionForgot	=	$("input[name='action_forgot']",form).val();
		var actionRegister	=	$("input[name='action_register']",form).val();
		var parentObject	=	this;
		
		this.stopAutocloser();
		this.setupLoginFocus(popup);
				
		// sign in mini popup
		open.click(function(){
			if(!open.hasClass("logged_in")){
				enableLogin();
				parentObject.show(popup);
				return false;
			}
		});
		
		register.click(function(){ window.location = actionRegister; });
		
		//	FIXME: The embedded translations here might be better coming through the JSON object than sent directly here (carlos?? agree??)
		var enableForgot = function(){
			submit.unbind("click");
			submit.click(executeForgot);
			submit.attr("value",miscTranslations.misc_recover_p);
			
			forgot.unbind("click");
			forgot.click(enableLogin);
			
			forgot.text(miscTranslations.misc_cancel_recover);
			
			parentObject.hideMessage(message);
			
			$(".overlay",popup).hide();
			
			return false;
		}
		
		var enableLogin = function(){
			submit.unbind("click");
			submit.click(executeLogin);
			submit.attr("value","Ok");
			
			forgot.unbind("click");
			forgot.click(enableForgot);
			
			forgot.text(miscTranslations.misc_forgot_p);
			
			parentObject.hideMessage(message);
			
			$(".overlay",popup).show();
			
			return false;
		}
		
		var executeLogin = function(){
			parentObject.hideMessage(message);
			
			sending.css("visibility","visible");
		
			$.post(actionLogin,form.serialize(),function(reply){
				sending.css("visibility","hidden");
				
				parentObject.showMessage(message,popup,reply.message,reply.success);
				
				if(reply.success) window.location.reload();
			},"json");
			
			return false;
		};
		
		var executeForgot = function(){
			parentObject.hideMessage(message);
			
			sending.css("visibility","visible");
			
			$.post(actionForgot,form.serialize(),function(reply){
				sending.css("visibility","hidden");
				
				parentObject.showMessage(message,popup,reply.message,reply.success);
			},"json");
			
			return false;
		}
		
		submit.click(executeLogin);
		forgot.click(enableForgot);
	};
	
	this.booking = function()
	{
		var popup			=	$("#booking_link");
		var open			=	$(".label",popup);
		var forgot			=	$(".forgot",popup);
		var	sending			=	$(".sending",popup);
		var form			=	$("form",popup);
		var message			=	$(".message",popup);
		var submit			=	$(".submit_button",form);
		var actionLogin		=	$("input[name='action_login']",form);
		var actionForgot	=	$("input[name='action_forgot']",form);
		var action			=	actionLogin.val();
		var parentObject	=	this;
		
		this.stopAutocloser();
		this.setupLoginFocus(popup);
		
		// bookings mini popup
		open.click(function() {
			if(!open.hasClass("logged_in")){
				parentObject.show(popup);
				return false;
			}
		});
		
		var enableForgot = function(){
			submit.unbind("click");
			submit.click(executeForgot);
			submit.attr("value",miscTranslations.misc_recover_p);
			
			forgot.unbind("click");
			forgot.click(enableLogin);
			
			forgot.text(miscTranslations.misc_cancel_recover);
			action = actionForgot.val();
			
			parentObject.hideMessage(message);
			
			$(".overlay",popup).hide();
			
			return false;
		}
		
		var enableLogin = function(){
			submit.unbind("click");
			submit.click(executeLogin);
			submit.attr("value","Ok");
			
			forgot.unbind("click");
			forgot.click(enableForgot);
			
			forgot.text(miscTranslations.misc_forgot_p);
			action = actionLogin.val();
			
			parentObject.hideMessage(message);
			
			$(".overlay",popup).show();
			
			return false;
		}
		
		var executeLogin = function(){
			parentObject.hideMessage(message);
			
			sending.css("visibility","visible");
		
			$.post(action,form.serialize(),function(reply){
				sending.css("visibility","hidden");
				
				parentObject.showMessage(message,popup,reply.message,reply.success);
				
				if(reply.success) window.location = reply.redirect;
			},"json");
			
			return false;
		};
		
		var executeForgot = function(){
			parentObject.hideMessage(message);
			
			sending.css("visibility","visible");
			
			$.post(action,form.serialize(),function(reply){
				sending.css("visibility","hidden");
				
				parentObject.showMessage(message,popup,reply.message,reply.success);
			},"json");
			
			return false;
		}
		
		submit.click(executeLogin);
		forgot.click(enableForgot);
	}
	
	this.newsletter = function()
	{
		var	open			=	$(".newsletter_link .open-newsletter");
		var	popup			=	open.parents().find(".newsletter_link").eq(0);
		var parentObject	=	this;
		
		//	Setup ONLY for the popup (the popup has a link inside with class open-newsletter, search the parents for that popup
		this.stopAutocloser(popup);
		this.setupFavouriteHover(open);
		
		open.click(function(){
			var pnode	=	$(this).parents().find(".newsletter_link").eq(0);
			var form	=	$("form",pnode);
			var message	=	$(".message",pnode);
			var	sending	=	$(".sending",pnode);
			
			form[0].reset();
			sending.css("visibility","hidden");
			
			parentObject.hideMessage(message);
			parentObject.show(pnode);
			return false;
		});
	}
	
	this.customerCare = function()
	{
		var open			=	$(".customercare_link .open-customer-care");
		var popup			=	open.parents().find(".customercare_link").eq(0);
		var close			=	$(".close_button",popup);
		var clock			=	false;
		var parentObject	=	this;
		
		this.stopAutocloser();
		
		open.click(function(){
			var form	=	$("form",popup);
			var message	=	$(".message",popup);
			var sending	=	$(".sending",popup);
			
			form[0].reset();
			parentObject.hideMessage(message);
			sending.css("visibility","hidden");
			
			clock = setInterval(jsclock(popup),1000);
					
			parentObject.show(popup);
			return false;
		});
		
		close.click(function(){
			parentObject.hide();
			
			clearInterval(clock);
			clock = false;
			
			return false;
		});
		
		new TabRow(["customer_care_phone","customer_care_email"],popup);
	}
	
	this.sendToFriend = function()
	{
		var popup			=	$("#send_friend_link");
		var open			=	$(".open-send-friend",popup);
		var close			=	$(".close_button",popup)
		var form			=	$("form",popup);
		var submit			=	$("#submit",form)
		var message			=	$(".message",popup);		
		var parentObject	=	this;
		
		this.stopAutocloser();
		this.setupFavouriteHover(open);
				
		open.click(function(){
			parentObject.hideMessage(message);
			parentObject.show(popup);
			
			return false;
		});
	
		close.click(function(){
			parentObject.hide();
			
			return false;
		});
		
		new Splendia.Form(popup);
	}
	
	this.share = function()
	{
		var popup			=	$("#share_link");
		var open			=	$(".open-share",popup);
		var parentObject	=	this;
		
		this.stopAutocloser(popup);
		this.setupFavouriteHover(open);
		
		open.click(function(){
			parentObject.show(popup);
			return false;
		});
	}

	this.changeLang = function()
	{
		var popup			=	$("#lang_selector");
		var open			=	$(".open-changelang",popup);
		var parentObject	=	this;
		
		this.stopAutocloser(popup);
		
		open.click(function(){
			parentObject.show(popup);
			return false;
		});
	}

	this.changeCurr = function()
	{
		var popup			=	$("#currency_selector");
		var open			=	$(".open-changecurr",popup);
		var parentObject	=	this;
		
		this.stopAutocloser(popup);
		
		open.click(function(){
			parentObject.show(popup);
			return false;
		});
	}
	
	this.constructor();
}
Popup.instance = false;

function jsclock(popup)
{
	return(function(){
		var currentTime;
		currentTime = new Date();
		
		var currentHours	=	currentTime.getHours();
		var currentMinutes	=	currentTime.getMinutes();
		var currentSeconds	=	currentTime.getSeconds();
		
		// Pad the minutes and seconds with leading zeros, if required
		currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
		currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
		
		// Choose either "AM" or "PM" as appropriate
		var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
		
		// Convert the hours component to 12-hour format if needed
		currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
		
		// Convert an hours component of "0" to "12"
		currentHours = ( currentHours == 0 ) ? 12 : currentHours;
		
		// Compose the string for display
		var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
		
		// Update the time display
		$(".jsclock",popup).text(currentTimeString);
	});
}

//$(document).ready(function()
SplendiaSoftReadyHandlers.push(function()
{
	// debug clicky clicky
	$('.version_string').click(function(){
		$('.debug_hide').toggle();
	});

	//	Open a form object to control the hotelier join form
	if($(".hotelier_join").length)		new Splendia.Form(".hotelier_join")
												.setSendCallback(		function(node){	$(node).attr("disabled","disabled");	})
												.setCompleteCallback(	function(node){	$(node).attr("disabled","");			});
												

	//	Open a form object to control the club profile form
	if($(".club_profile").length)		new Splendia.Form(".club_profile");

	//	Open a form object to control all the newsletter signup forms
	if($(".newsletter_link").length)	new Splendia.Form($(".newsletter_link"));

	//	Open a form object to control all the customer care forms
	if($(".customer_care_form").length)	new Splendia.Form($(".customer_care_form"));

	//	Open a form object to control the signup club form
	//	FIXME: Change .signup_stage1 to just .club_signup or something
	if($(".club .signup_stage1 form").length) new Splendia.Form($(".club .signup_stage1 form"),function(){ 
		window.location = $(".club .signup_stage1 form input[name='redirect']").val(); 
	});

	initCurrencySelector();
	initLanguageSelector();

	Jobs.setup();	//	Job satellite setup
	FAQS.setup();	//	FAQS satellite setup

	$('.rooms_block').click(function() {
		window.location = $(this).attr('click');
	});

	$('.newsletter_input_optional_text').bind('change focus', function() {
		$(this).val('');
		$(this).removeClass('newsletter_input_optional_text');
		$(this).unbind('change focus');
	});
	
	// hotel props
	$('.view_all_hotels_remove_filters').click(function() {
		FacilitiesMarked = {};
		FacilitiesResolve();
		FacilitiesRebuildListing();
		FacilitiesSendAjax();
	});
	$('.facilityC:not(.zeroF)').click(function() {
		FacilitiesToggle($(this).attr('faid'));
		FacilitiesResolve();
		FacilitiesRebuildListing();
		FacilitiesSendAjax();
	});
	
	$('#hotel_list_order').change(function(ev) {
		window.location = this.options[this.selectedIndex].value;
	});
	/*
	if ($('#facilitiesF').length > 0) {
		FacilitiesResolve();
		FacilitiesRebuildListing();
	}
	*/
	
	
	$('.collapser').click(function() {
		var id = 'landmarks_' + $(this).attr('id');
		$('#' + id + ' li.hide').toggle();
		$('#' + id + ' a span.h').toggle();
		$('#' + id + ' a span.s').toggle();
		cancelBalanceColumns();
		balanceColumns();
		return false;
	});

	initHotelDetails();
	
	$('#hotel_rooms_dates_bar_change').click(function() {
		$('#rooms_header_with_dates').hide();
		$('#rooms_header').show();
		cancelBalanceColumns();
		balanceColumns();
		return false;
	});

	//$('table.prod_table select').change(function() {
	$('.prod_table_select').change(function() {
		var id = $(this).attr('id');

		var rate = $(this).attr('restrictrate');
		var totalExistingRates = { 'nonrefun' : 0, 'normal' : 0 };
		var totalRates = { 'nonrefun' : 0, 'normal' : 0 };
		var totalRateNonrefun = 0;
		var totalRateNormal = 0;
		var totalSelection = 0;

		// count first
		$('table.prod_table select').each(function() {
			var thisRate = $(this).attr('restrictrate');
			totalRates[thisRate] += this.selectedIndex;
			totalExistingRates[thisRate]++;
			totalSelection += this.selectedIndex;
		});

		// restrict second
		$('table.prod_table select').each(function() {
			var thisRate = $(this).attr('restrictrate');
			if (thisRate != rate && totalRates[rate] > 0) {
				this.selectedIndex = 0;
				$(this).attr('disabled', 'disabled');
			} else {
				$(this).removeAttr('disabled');
			}
		});

		// message if needed
		if (totalSelection > 0 && totalExistingRates['nonrefun'] > 0 && totalExistingRates['normal'] > 0) {
			$('.warn_mixed_rates').show();
		} else {
			$('.warn_mixed_rates').hide();
		}

		var parentID = $(this).parents('.room_block').attr('id');
		BookingRecalcProductAvailSelection(parentID);

		var r = BookingBuildProductSelection();
		bookingRoomSelection = r.sel;
		var i = r.total;
		var s = r.query;
		$('.totalRooms').html(''+i);
		$('.totalPrice').html('...');
		$.getJSON(
			'/index.php?resource=ajax&component=AjaxChangeProducts',
			{ 'product_selection' : s, 'product_hotel_id' : searchFixedHotel, 'product_datestart' : initialDatestart, 'product_dateend' : initialDateend},
			function(data) {
				bookingRoomSubtotals = data.prices;
				bookingRoomTotal = data.total;
				BookingUpdatePrices();
			}
		);

	});

	$('.product_info_popup_trigger2').click(function() {
		var id = $(this).attr('id');
		$('#popup_' + id).toggle();
		$('.occ_info_popup:not(#popup_' + id + ')').hide();

		return false;
	});

	$('.occ_info_popup .close').click(function() {
		$(this).parents('.occ_info_popup').hide();
	});

	$('.room_desc_popup_trigger').click(function() {
		var id = $(this).attr('id').substring(6);
		
		$('.desc_room_image_selector').removeClass('desc_room_image_selector_current');
		$('.desc_room_image').hide();

		$('#' + id + ' .desc_room_image:first').show();
		$('#' + id + ' .desc_room_image_selector:first').addClass('desc_room_image_selector_current');

		$('body').append($('#' + id).get(0));

		var breath = ($(window).height() - $(this).height());
		
		$('#' + id).css('left', ($(window).width() - 500)/2 + 'px');
		$('#' + id).css('top', (100 + $(window).scrollTop()) + 'px');

		$('#' + id).toggle();
		$('.desc_popup:not(#' + id + ')').hide();

		//$('.room_desc_popup_extra_filler').show();
		//cancelBalanceColumns();
		//balanceColumns();

		return false;
	});
	$('.desc_popup .close').click(function() {
		$(this).parents('.desc_popup').hide();

		//$('.room_desc_popup_extra_filler').hide();
		//cancelBalanceColumns();
		//balanceColumns();
	});

	initPegasus();
	//initHotelAccess();	
	
	$('.desc_room_image_selector').click(function() {
		var id = $(this).attr('id');
		$('.desc_room_image:not(#full_' + id + ')').hide();
		$('#full_' + id).show();
		$('.desc_room_image_selector').removeClass('desc_room_image_selector_current');
		$(this).addClass('desc_room_image_selector_current');
		return false;
	});

	Popup.instance = new Popup();

	initBooking();
	initPageLoginForm();
	initClubHotels();

	// dont hate me :(
	var ad_interval = setInterval(function() {
		if ($("#listing_ad_area_id a[href*='empty.gif']").parents('div.listing_ad_area').hide().length > 0) {
			cancelBalanceColumns();
			balanceColumns();
			clearInterval(ad_interval);
		}
	}, 200);
});

function initPegasus()
{
	if ($('#hotel_page').length <= 0) {
		return;
	}
	
	$('.pegasus_popup_trigger').click(function() {

/*
		var id = $(this).attr('id').substring(6);
		var ajax = $(this).attr('ajax');

		$.get(ajax, function(data) {
			$('#' + id + ' .remote').html(data);
		});

		$('#' + id).toggle();
		$('.desc_popup:not(#' + id + ')').hide();

		$('.room_desc_popup_extra_filler').show();
		cancelBalanceColumns();
		balanceColumns();

		return false;
*/
		var id = $(this).attr('id').substring(6);
		var ajax = $(this).attr('ajax');

		$.get(ajax, function(data) {
			$('#' + id + ' .remote').html(data);
		});

		$('body').append($('#' + id).get(0));

		var breath = ($(window).height() - $(this).height());
		
		$('#' + id).css('left', ($(window).width() - 500)/2 + 'px');
		$('#' + id).css('top', (100 + $(window).scrollTop()) + 'px');

		$('.pegasus_popup:not(#' + id + ')').hide();

		$('#' + id).show();

		return false;
	});

	$('.pegasus_popup .close').click(function() {
		$(this).parents('.pegasus_popup').hide();

		$('.room_desc_popup_extra_filler').hide();
		cancelBalanceColumns();
		balanceColumns();
	});
}

function initCurrencySelector()
{
	// currency selector
	/*
	$('#currency_selector').click(function() {
		$('#currency_list').toggle();
		return false;
	});
	* */
	$('#currency_list li a').click(function(ev) {
		$('#currency_selected').text($(ev.target).text());
		//$('#currency_list').toggle();
	});
}

function initLanguageSelector()
{
	// lang selector
	/*$('#lang_selector').click(function() {
		$('#lang_list').toggle();
		return false;
	});*/
	
	$('#lang_list li a').click(function(ev) {
		window.location = ev.target.href;
	});
}

function initPageLoginForm()
{		
	var showForgot = function(){
		var form			=	$(this).parents().find(".login_area form").eq(0);
		var actionForgot	=	$("input[name='action_forgot']",form);
		var message			=	$(".message",form);
		
		$(".password_area",form).hide();
		$(".forgot_area",form).show();
		
		Splendia.UI.hideMessage(message);
		form.attr("action",actionForgot.val());
		
		return false;
	};
	
	var hideForgot = function(){
		var form			=	$(this).parents().find(".login_area form").eq(0);
		var actionLogin		=	$("input[name='action_login']",form);
		var message			=	$(".message",form);
		
		$(".password_area",form).show();
		$(".forgot_area",form).hide();
						
		Splendia.UI.hideMessage(message);
		form.attr("action",actionLogin.val());
		
		return false;
	};
	
	var success = function(button){
		var form			=	$(button).parents().find(".login_area form").eq(0);
		var type			=	$("input[name='type']",form).val();
		var actionLogin		=	$("input[name='action_login']",form);
		
		if(type == "club" || type == "booking"){
			if(form.attr("action") == actionLogin.val()){
				window.location.reload();
			}
		}
	}
	
	var mode = function(button){
		var form			=	$(button).parents().find(".login_area form").eq(0);
		var type			=	$("input[name='type']",form).val();
		var actionLogin		=	$("input[name='action_login']",form);
		
		if(type == "hotel" && form.attr("action") == actionLogin.val()) return "post";
		
		return "ajax";
	}
	
	var form = $(".login_area form");
	new Splendia.Form(form,success,mode);
	
	$(".remind_password",form).click(showForgot);
	$(".cancel_recovery",form).click(hideForgot);
}

function initClubHotels()
{
	if ($('#club_hotels_page').length <= 0) {
		return;
	}
	
	var clubHotelSelected = false;
	
	var openCountry = function(event){
		closeCountry(event);
		
		clubHotelSelected = $(this);
		clubHotelSelected.addClass("show_country");
		
		cancelBalanceColumns();
		balanceColumns();
		
		return false;
	};
	
	var closeCountry = function(event){
		if(clubHotelSelected){
			clubHotelSelected.removeClass("show_country");
		}	
	}
	
	$(".club_hotels .country").each(function(){
		$(this).click(openCountry);
	});
	
	$(".club_hotels .country .city a").each(function(){
		$(this).click(function(){ window.location = $(this).attr("href"); });
	});
}

function initBooking()
{
	if ($('#booking_page').length <= 0) {
		return;
	}

	// booking
	$('#booking_open_promo').click(function() {
		$('.booking_promo_form').show();
		$('.booking_promo_trig').hide();
		return false;
	});

	$('#booking_close_promo').click(function() {
		$('.booking_promo_form').hide();
		$('.booking_promo_trig').show();
		return false;
	});
	
	$('.booking_content input, .booking_content select').bind('change focus', function() {
		$(this).parents().removeClass('fail');
		$(this).parents().removeClass('fail2');
	});

	// affiliates form takes advantage of this too
	$('.affiliates_content input, .affiliates_content select').bind('change focus', function() {
		$(this).parents().removeClass('fail');
	});

	$('.book_optional_text').bind('change focus', function() {
		$(this).val('');
		$(this).removeClass('book_optional_text');
		$(this).unbind('change focus');
	});

	$('#book_club_wish_to_join,#book_club_wish_to_join_label').click(function() {
		if ($('#book_club_wish_to_join').is(':checked')) {
			$('#optional_club_creation_sub_form').addClass('creation_enabled');

			$('#book_club_login_now').removeAttr('checked');
			$('#optional_club_login_sub_form').hide();

			$('#book_club_login_now').hide();
			$('#book_club_login_now_label').hide();

		} else {
			$('#optional_club_creation_sub_form').removeClass('creation_enabled');

			$('#book_club_login_now').show();
			$('#book_club_login_now_label').show();
		}
	});

	$('#book_club_login_now,#book_club_login_now_label').click(function() {
		if ($('#book_club_login_now').is(':checked')) {
			$('#optional_club_login_sub_form').show();

			$('#book_club_wish_to_join').removeAttr('checked');
			$('#optional_club_creation_sub_form').removeClass('creation_enabled');

			$('#book_club_wish_to_join').hide();
			$('#book_club_wish_to_join_label').hide();

		} else {
			$('#optional_club_login_sub_form').hide();

			$('#book_club_wish_to_join').show();
			$('#book_club_wish_to_join_label').show();
		}
	});

	$('#book_submit_button').click(function() {
		$('.book_optional_text').val('');
		$('#submit_mode').val('book');
		$('#proposal_mode').val('no');
		$('#book_submit_button,#book_submit_button_proposal').attr("disabled", "disabled");
		$('.book_submit_indicator').css('visibility', 'visible');
		document.bookform.submit();
	});

	$('#book_submit_button_proposal').click(function() {
		$('.book_optional_text').val('');
		$('#submit_mode').val('book');
		$('#proposal_mode').val('yes');
		$('#book_submit_button,#book_submit_button_proposal').attr("disabled", "disabled");
		$('.book_submit_indicator').css('visibility', 'visible');
		document.bookform.submit();
	});

	$('#book_club_login_submit').click(function() {
		$('.book_optional_text').val('');
		$('#submit_mode').val('login');
		document.bookform.submit();
	});

	$('#book_promocode_submit').click(function() {
		$('.book_optional_text').val('');
		$('#submit_mode').val('promocode');
		document.bookform.submit();
	});

	$('#book_promocode_cancel_submit').click(function() {
		$('.book_optional_text').val('');
		$('#submit_mode').val('promocodecancel');
		document.bookform.submit();
	});

	$('#book_club_register_submit').click(function() {
		$('.book_optional_text').val('');
		$('#submit_mode').val('register');
		document.bookform.submit();
	});

	var bookingRemoveSameCurrency = function() {
		var selected = $('#payment_currency option:selected').val();
		var def = $('#payment_currency').attr('defcur');
		if (selected == def) {
			$('#payment_currency_equiv').hide();
		} else {
			$('#payment_currency_equiv').show();
		}
	};

	bookingRemoveSameCurrency();

	$('#payment_currency').change(bookingRemoveSameCurrency);
}

function initHotelDetails()
{
	if ($('#hotel_page').length <= 0) {
		return;
	}

	// hotel details
	$('.hotel_details .details_image_thumb_pager a').click(function() {
		var id = $(this).attr('id');
		$('.hotel_details #th_' + id).show();
		$('.hotel_details .details_image_thumb_page:not(#th_' + id + ')').hide();
		return false;
	});
	$('.hotel_details .details_image_thumb').click(function() {
		var rel = $(this).attr('rel');
		$('.hotel_details .load_p').show();
		$('.hotel_details .details_image').load(function () {
			$('.hotel_details .load_p').hide();
		});  
		$('.hotel_details .details_image').attr('src', rel);
	});
	var detailTabClick = function (id) {
		$('.hotel_details #tab_' + id).show();
		$('.hotel_details .details_tabs_container .tab:not(#tab_' + id + ')').hide();
		$('.hotel_details #' + id).addClass('selected');
		$('.hotel_details .details_tabs_container .tab_chooser li:not(#' + id + ')').removeClass('selected');
		if (id == 'c_rooms') {
			location.hash = '#rooms';
		} 
		if (id == 'c_desc') {
			location.hash = '#desc';
		} 
		if (id == 'c_review') {
			location.hash = '#review';
		} 
		cancelBalanceColumns();
		balanceColumns();
	}

	$('.hotel_details .details_tabs_container .tab_chooser li').click(function() {
		var id = $(this).attr('id');
		detailTabClick(id);
	});

	$('.hotel_details li.rec').click(function() {
		detailTabClick('c_review');
	});

	if (location.hash == '#rooms') {
		detailTabClick('c_rooms');
	}
	else if (location.hash == '#desc') {
		detailTabClick('c_desc');
	}
	else if (location.hash == '#review') {
		detailTabClick('c_review');
	}

	// in-column button
	$('.submitBooking').click(function() {
		if (BookingHotelPageNeedsRooms()) {
			detailTabClick('c_rooms');
			BookingFlashRoomSelection();
		} else {
			$('.submitBooking,.submitBookingTop').attr("disabled", "disabled");
			BookingSubmitStart();
		}
	});

	// in-column button - pegasus
	$('.submitBookingPegasus').click(function() {
		var $el = $(this);
		var prod = $el.attr('prod');
		var rooms = $el.attr('rooms');
		var adults = $el.attr('adults');
		BookingSubmitStartPegasus(prod, rooms, adults);
	});

	// out of column button, always available
	$('.submitBookingTop').click(function() {
		var needsDates = BookingHotelPageNeedsDates();
		var needsRooms = BookingHotelPageNeedsRooms();
		if (needsDates) {
			detailTabClick('c_rooms');
			BookingFlashDateSelection();
		}
		else
		{
			if (!needsDates && roomPageOkToSendDates) {
				hotelPageSearchButtonAction();
			}
			else
			{
				if (needsRooms) {
					detailTabClick('c_rooms');
					BookingFlashRoomSelection();
				}
				if (!needsDates && !needsRooms) {
					$('.submitBooking,.submitBookingTop').attr("disabled", "disabled");
					BookingSubmitStart();
				}
			}
		}
	});
}

//	FIXME: This should be removed, it's not used anymore.
function initHotelAccess()
{
	var popup	=	$("#hotelier_remind_password .popup");
	var form	=	$("#hotelier_remind_password .popup form");
	
	$("#hotelier_remind_password a").click(function(){
		if(form.length == 0) return false;
		
		popup.show();
		return false;
	});
	
	$("#hotelier_remind_password .popup .close_button").click(function(){
		popup.hide();
		return false;
	});
	
	$("#hotelier_remind_password .popup .submit").click(function(){
		var data = form.serialize();
		$.post(form.attr("action"),data,function(data){
			alert("success = "+data.success);
		},"json");
		
		return false;
	});
}

function BookingSubmitStart() {
	var r = BookingBuildProductSelection();
	window.location = '/index.php?resource=redirector&component=RedirectStartBooking&mode=splendia' +
		'&datestart=' + encodeURIComponent(searchBoxStartDate) + 
		'&dateend='   + encodeURIComponent(searchBoxEndDate) +
		'&product_selection='   + encodeURIComponent(r.query)
	;
}

function BookingSubmitStartPegasus(prod, rooms, adults) {
	var r = BookingBuildProductSelection();
	window.location = '/index.php?resource=redirector&component=RedirectStartBooking&mode=pegasus' +
		'&datestart=' + encodeURIComponent(searchBoxStartDate) + 
		'&dateend='   + encodeURIComponent(searchBoxEndDate) +
		'&prod='      + encodeURIComponent(prod) +
		'&rooms='     + encodeURIComponent(rooms) +
		'&adults='    + encodeURIComponent(adults)
	;
}

function BookingRecalcProductAvailSelection(id) {
	var fillOption = function(n) {
		var r = '';
		for (var j = 0; j <= n; j++) {
			r += '<option>' + j + '</option>';
		}
		return r;
	};

	var max = bookingRoomMaxAvail[id];

	var selected = 0;

	$('#' + id + ' select').each(function() {
		selected += this.selectedIndex;
	});

	var available = max - selected;

	$('#' + id + ' select').each(function() {
		var i = this.selectedIndex;
		var localAvail = available + this.selectedIndex;
		//if (i < localAvail) {
			$(this).html(fillOption(localAvail));
			this.selectedIndex = i;
		//}
	});
}

function BookingBuildProductSelection() {
	var selection = { };
	var s = '{';
	var first = true;
	var i = 0;

	$('table.prod_table select').each(function() {
		if (!first) s = s + ',';
		var id = this.getAttribute('id').substring(4);
		var val = this.selectedIndex;
		selection[id] = val;
		i = i + parseInt(val);
		s = s + '"' + id + '" : "' + val + '"';
		first = false;
	});
	s = s + '}';
	return { 'total': i, 'sel': selection, 'query': s };
}

function BookingHotelPageNeedsDates() {
	return searchBoxStartDate == false || searchBoxEndDate == false;
}

function BookingHotelPageNeedsRooms() {
	var total = 0;
	$('table.prod_table select').each(function() {
		total += this.selectedIndex;
	});
	return total <= 0;
}

function BookingFlashDateSelection() {
	$.scrollTo('+=40px', 500);
	$('.submitBookingTopErr').show().animate({color: '#888888'}, 360)
		.animate({color: '#888888'}, 5720)
		.animate({color: 'white'}, 360);
	
	$('#rooms_header').animate({ backgroundColor: 'white' }, 360)
    	.animate( { backgroundColor: '#F1F0EE' }, 360)
    	.animate( { backgroundColor: 'white' }, 360)
    	.animate( { backgroundColor: '#F1F0EE' }, 360);
}

function BookingFlashRoomSelection() {
	$.scrollTo('#scrollProdTableTarget', 500);

	$('.sideNoRoomsMsg').show().animate({color: '#888888'}, 360)
		.animate({color: '#888888'}, 5720)
		.animate({color: 'white'}, 360);

	$('table.prod_table select').animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
    	.animate( { backgroundColor: 'white' }, 120)
    	.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
    	.animate( { backgroundColor: 'white' }, 120)
    	.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
    	.animate( { backgroundColor: 'white' }, 120);
}

function BookingUpdatePrices() {
	$.each(bookingRoomSubtotals, function(k, v) {
		$('#sub' + k).html(''+v);
	});
	$('.totalPrice').html(''+bookingRoomTotal);
}

function FacilitiesSendAjax() {
	var q = [];
	$.each(FacilitiesMarked, function(k, v) {
		if (v) {
			q.push(k);
		}
	});
	var q2 = q.join(',');
	$.get(
		'/index.php',
		{
			'resource' : 'ajax',
			'component' : 'AjaxSaveAdvanced',
			'q' : q2
		}
	);
}

function FacilitiesRebuildListing() {
	var htmlE = [];
	var htmlF = [];
	
	var total = 0;
	var totalMarked = 0;
	$.each(FacilitiesAvailable, function(k, v) {
		var marked = FacilitiesMarked[k];
		var name = FacilitiesTrans[k];
		var html = '<li faid="'+ k +'" class="facilityC ' + (v <= 0 ? ' zeroF' : '') + ' ' + (marked  ? ' markedF' : '') + '"><div class="count">' + v + '</div><div class="text">' + name + '</div></li>';
		totalMarked += marked ? 1 : 0;
		if (FacilitiesCat[k] == 'e') {
			htmlE.push({ 'name' : name, 'html' : html });
		} else {
			htmlF.push({ 'name' : name, 'html' : html });
		}
		total++;
	});

	var comp = function(a, b) {
		if (a.name < b.name)
			return -1;
		else if (a.name > b.name)
			return 1;
		else
			return 0;
	};
	htmlE.sort(comp);
	htmlF.sort(comp);

	var phtmlE = '';
	$.each(htmlE, function() {
		phtmlE += this.html;
	});

	var phtmlF = '';
	$.each(htmlF, function() {
		phtmlF += this.html;
	});
	

	$('#facilitiesE').html(phtmlE);
	$('#facilitiesF').html(phtmlF);

	if (total <= 0) {
		$('.hide_when_no_hotels').hide();
		return;
	}

	$('.facilityC:not(.zeroF)').click(function() {
		FacilitiesToggle($(this).attr('faid'));
		FacilitiesResolve();
		FacilitiesRebuildListing();
		FacilitiesSendAjax();
	});

	var i = 0;
	$.each(FacilitiesHotel, function(k, hotel) {
		if (FacilitiesHotelIsPresent(hotel.facilities)) {
			//$('#hotel' + hotel.id).slideDown();
			$('#hotel' + hotel.id).show();
			i = i + 1;
		} else {
			//$('#hotel' + hotel.id).slideUp();
			$('#hotel' + hotel.id).hide();
		}
	});
	$('#listing_found_count').html('' + i);
	$('#listing_found_count').html('' + i);

	if (totalMarked > 0) {
		$('.listing_found_count_total').show();
		$('.view_all_hotels_remove_filters').show();
	} else {
		$('.listing_found_count_total').hide();
		$('.view_all_hotels_remove_filters').hide();
	}

	cancelBalanceColumns();
	balanceColumns();
}

function FacilitiesToggle(f) {
	FacilitiesMarked[f] = !FacilitiesMarked[f];
}

function FacilitiesInitialMarks() {
	// all the possible facilities, unfiltered
	$.each(FacilitiesHotel, function(k, hotel) {
		$.each(hotel.facilities, function(k2, v) {
			FacilitiesMarked[k2] = false;
		});
	});
}

function FacilitiesHotelIsPresent(facilities) {
	// test 2: it has all marked facilities
	var test2 = true;
	$.each(FacilitiesMarked, function(k2, v2) {
		if (v2) {
			test2 = test2 && facilities[k2];
		}
	});
	return test2;
}

function FacilitiesAreValid(facilities, current) {
	// the hotel "passes the exam" when it complies with BOTH:
	// it has the current facility
	// it has all marked facilities
	
	// test 1: it has the current facility
	var test1 = false;
	$.each(facilities, function(k2, v2) {
		test1 = test1 || (k2 == current);
	});

	// test 2: it has all marked facilities
	var test2 = true;
	$.each(FacilitiesMarked, function(k2, v2) {
		if (v2) {
			test2 = test2 && facilities[k2];
		}
	});

	return test1 && test2;
}

function FacilitiesResolve() {

	FacilitiesAvailable = { };

	// all the possible facilities, unfiltered
	$.each(FacilitiesHotel, function(k, hotel) {
		$.each(hotel.facilities, function(k2, v) {
			FacilitiesAvailable[k2] = 0;
		});
	});

	// now fix the counts
	$.each(FacilitiesAvailable, function(k, v) {
		$.each(FacilitiesHotel, function(kh, hotel) {
			if (FacilitiesAreValid(hotel.facilities, k)) {
				FacilitiesAvailable[k]++;
			}
		});
	});
}

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

//	Some mousewheel plugin I wanted for jquery
/**
 * 
 * credits for this plugin go to brandonaaron.net
 * 	
 * unfortunately his site is down
 * 
 * @param {Object} up
 * @param {Object} down
 * @param {Object} preventDefault
 */
jQuery.fn.extend({
	mousewheel: function(up, down, preventDefault) {
		return this.hover(
			function() {
				jQuery.event.mousewheel.giveFocus(this, up, down, preventDefault);
			},
			function() {
				jQuery.event.mousewheel.removeFocus(this);
			}
		);
	},
	mousewheeldown: function(fn, preventDefault) {
		return this.mousewheel(function(){}, fn, preventDefault);
	},
	mousewheelup: function(fn, preventDefault) {
		return this.mousewheel(fn, function(){}, preventDefault);
	},
	unmousewheel: function() {
		return this.each(function() {
			jQuery(this).unmouseover().unmouseout();
			jQuery.event.mousewheel.removeFocus(this);
		});
	},
	unmousewheeldown: jQuery.fn.unmousewheel,
	unmousewheelup: jQuery.fn.unmousewheel
});


jQuery.event.mousewheel = {
	giveFocus: function(el, up, down, preventDefault) {
		if (el._handleMousewheel) jQuery(el).unmousewheel();
		
		if (preventDefault == window.undefined && down && down.constructor != Function) {
			preventDefault = down;
			down = null;
		}
		
		el._handleMousewheel = function(event) {
			if (!event) event = window.event;
			if (preventDefault)
				if (event.preventDefault) event.preventDefault();
				else event.returnValue = false;
			var delta = 0;
			if (event.wheelDelta) {
				delta = event.wheelDelta/120;
				if (window.opera) delta = -delta;
			} else if (event.detail) {
				delta = -event.detail/3;
			}
			if (up && (delta > 0 || !down))
				up.apply(el, [event, delta]);
			else if (down && delta < 0)
				down.apply(el, [event, delta]);
		};
		
		if (window.addEventListener)
			window.addEventListener('DOMMouseScroll', el._handleMousewheel, false);
		window.onmousewheel = document.onmousewheel = el._handleMousewheel;
	},
	
	removeFocus: function(el) {
		if (!el._handleMousewheel) return;
		
		if (window.removeEventListener)
			window.removeEventListener('DOMMouseScroll', el._handleMousewheel, false);
		window.onmousewheel = document.onmousewheel = null;
		el._handleMousewheel = null;
	}
};

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 * @author Ariel Flesler
 * @version 1.4
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

//////////////////////////////////////////////////////////////
// HI. i'm isolated in my own ready handler for a reason.
// yes, in the bottom of this file. don't move me inside
// another ready handler or to anywhere else in this file.
// have a nice day :)
//////////////////////////////////////////////////////////////
$(document).ready(function() {

	$('.autoclosing_popup').click(function() { return false; });

	document.onclick = function(ev){
		/*
			Eventually this will change because now there is a popup manager allowing only 
			one popup to be open at once, therefore the autoclosing_popup classes which were 
			needed before, are not needed now, just call the Popup.instance.hide() method 
			and the currently open popup will close.
		*/
		$('.autoclosing_popup').hide(); // no guts no glory
		if(typeof(Popup) !== "undefined") Popup.instance.hide();
		if ($('.autoclosing_popup_completion').length > 0 && typeof(hackCompletionExternalCloseHandler) !== "undefined") {
			hackCompletionExternalCloseHandler();
		}
	};

	// yes, this, here, let it be, for the sake of webkit&co
	balanceColumnsSlow();
});
//////////////////////////////////////////////////////////////



Maps_GM_map = false;
Maps_GM_try_load = true;

Maps_current_element = 'map_dialog_map';
Maps_current_xml = false;
Maps_current_lat = false;
Maps_current_lon = false;
Maps_current_zoom = false;
Maps_current_overlays = [];

function MapsGoogleAPIReady() {
	if (GBrowserIsCompatible()) {
		if (Maps_GM_map === false) {
			Maps_GM_map = new GMap2(document.getElementById(Maps_current_element));
			Maps_GM_map.addControl(new GLargeMapControl());
			Maps_GM_map.addControl(new GMapTypeControl());
		}
		MapsLoadXML(Maps_current_xml);
		Maps_GM_map.setCenter(new GLatLng(Maps_current_lat, Maps_current_lon), Maps_current_zoom);
	}
}

function MapsCreateIcon()
{ 
	HotelIcon = new GIcon();
	HotelIcon.image = '/images/mapmarkers/ic_hot.png';
	HotelIcon.iconSize = new GSize(14,18);
	HotelIcon.shadowSize = new GSize(14,18);
	HotelIcon.iconAnchor = new GPoint(7,9);
	HotelIcon.infoWindowAnchor = new GPoint(7,9);
	HotelIcon.infoShadowAnchor = new GPoint(7,9);
	PoiIcon = new GIcon();
	PoiIcon.image = '/images/mapmarkers/ic_inf.png';
	PoiIcon.iconSize = new GSize(14,18);
	PoiIcon.shadowSize = new GSize(14,18);
	PoiIcon.iconAnchor = new GPoint(7,9);
	PoiIcon.infoWindowAnchor = new GPoint(7,9);
	PoiIcon.infoShadowAnchor = new GPoint(7,9);	
}

function MapsLoadXML(file_xml) {
	if (GBrowserIsCompatible()) {
		var request = GXmlHttp.create();
		request.open('GET',file_xml, true);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				MapsRemoveOverlays();
				MapsCreateIcon();
				var xmlsource = request.responseXML;
				var markerlist = xmlsource.documentElement.getElementsByTagName("Markers");
				//xmlsource.documentElement.getElementsByTagName("Markers");
				for (var i=0;i < markerlist.length;i++) {
					var name = markerlist[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
					var cat = false;
					if (markerlist[i].getElementsByTagName("CatImage").length > 0) {
						cat = markerlist[i].getElementsByTagName("CatImage")[0].childNodes[0].nodeValue;
					}
					var addr = false;
					if (markerlist[i].getElementsByTagName("Addr").length > 0) {
						addr = markerlist[i].getElementsByTagName("Addr")[0].childNodes[0].nodeValue;
					}
					var link = false;
					if (markerlist[i].getElementsByTagName("Link").length > 0) {
						link = markerlist[i].getElementsByTagName("Link")[0].childNodes[0].nodeValue;
					}
					var linkText = false;
					if (markerlist[i].getElementsByTagName("LinkText").length > 0) {
						linkText = markerlist[i].getElementsByTagName("LinkText")[0].childNodes[0].nodeValue;
					}
					MapsAddMarker(parseFloat(markerlist[i].getAttribute("lng")),
							  parseFloat(markerlist[i].getAttribute("lat")),
							  markerlist[i].getAttribute("type"),
							  name, cat, addr, link, linkText);
				}
			}
		}
		request.send(null);
	}
}

function MapsRemoveOverlays() {
	$.each(Maps_current_overlays, function() {
		Maps_GM_map.removeOverlay(this);
	});
	Maps_current_overlays = [];
}

function MapsAddMarker(x,y,type,title, cat, addr, link, linkText) {
	var point = new GPoint(parseFloat(x),parseFloat(y));

	if(type=='hotel') {
		var marker = new GMarker(point,HotelIcon);
	} else {
		var marker = new GMarker(point,PoiIcon);
	}

	GEvent.addListener(marker,'click',function() {
		var html = '';
		if (link !== false) {
			html += '<a style="display: block; text-decoration: none; color: black" href="'+link+'">';
		}
 		html += '<b>' + title;
		if (cat !== false) {
			html += ' <img src="'+cat+'">';
		}
		html += '</b><br><br>';
		if (addr !== false) {
			html += addr;
		}
		if (link !== false) {
			html += '</a>';
		}

		if (linkText !== false) {
			html += '<br><br><a href="' + link + '">'+linkText+'</a>';
		}
		marker.openInfoWindowHtml(html);
	});

	Maps_GM_map.addOverlay(marker);
	Maps_current_overlays.push(marker);
}

$(document).ready(function(){
	$(".map_box .map").click(function() {
		MapsOpenGoogleMapsDefault();
	});
	
	$(".map_box .map_label").click(function() {
		MapsOpenGoogleMapsDefault();
	});

	$(".hotel_page_map_link").click(function() {
		MapsOpenGoogleMapsDefault();
		return false;
	});

	$("#show_hotels_on_map").click(function() {
		MapsOpenGoogleMapsDefault();
		return false;
	});
	$(".map_box .map_hotel_marker").click(function() {
		MapsOpenGoogleMapsDefault();
	});

	/* handled by the link javascript: call
	$(".listing_hotel_map_link").click(function() {
		MapsOpenGoogleMapsHotel(this);
	});
	*/

});

function MapsOpenGoogleMapsDefault() {
	Maps_current_element = 'map_dialog_map';
	Maps_current_xml = mapUri;
	Maps_current_lat = mapLat;
	Maps_current_lon = mapLon;
	Maps_current_zoom = mapZoom;
	MapsOpenGoogleMaps();
}

function MapsOpenGoogleMapsDetailed(xml, lat, lon, zoom) {
	Maps_current_element = 'map_dialog_map';
	Maps_current_xml = xml == false ? mapUri : xml;
	Maps_current_lat = lat;
	Maps_current_lon = lon;
	Maps_current_zoom = zoom == -1 ? mapZoom : zoom;
	MapsOpenGoogleMaps();
}

function MapsOpenGoogleMaps() {
	if (Maps_GM_try_load) {

/*
		$("#map_dialog").dialog({
			autoOpen: true,
			modal: true,
			width: 700,
			height: 500,
			resizable: false
		});
*/

		var dialog = document.createElement("div");
		var $dialog = $(dialog);
		$dialog.addClass('map2_dialog');
		$dialog.css('top', (100 + $(window).scrollTop()) + 'px');
		$dialog.css('left', (($(window).width() - 700)/2) + 'px');
		$dialog.append($("#map_dialog"));
		$dialog.append('<div class="close"><img alt="" src="/close.gif"/></div>');
		$('body').append(dialog);

		$("#map_dialog_map").show();

		$('.map2_dialog .close').click(function() {
			$(".map2_dialog").hide();
		});

	    var script = document.createElement('script');
	    script.type = 'text/javascript';
	    script.src = mapJSLoadURL;
	    document.body.appendChild(script);

	    Maps_GM_try_load = false;

	} else {

		//$("#map_dialog").dialog("open");
		
		$(".map2_dialog").css('top', (100 + $(window).scrollTop()) + 'px');
		$(".map2_dialog").toggle();

		MapsGoogleAPIReady();

	}
}



hackCompletionExternalCloseHandler = null;

jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	var directEnter = false;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	$results.addClass('autoclosing_popup');
	$results.addClass('autoclosing_popup_completion');

	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$('body').append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				directEnter = true;
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
		if ($input.val() == $input.attr('title') || $input.val() == $input.attr('titled') || $input.val() == $input.attr('titleh'))
			$input.val('');
		//$('#popup_locations_trigger').hide();
		$('#popup_locations_trigger').attr('src', '/images/header/icon_destinations_list_blank.gif');
		$('#popup_locations').hide();
	})
	.blur(function() {
		// track whether the field has focus
		//hasFocus = false;
		//hideResults();
		//if ($input.val() == '')
		//	$input.val($input.attr('title'));
		//if ($input.attr('mode') != 'hotel')
			//$('#popup_locations_trigger').show();
		$('#popup_locations_trigger').attr('src', '/images/header/icon_destinations_list.gif');
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		/*if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) )
			return hideResultsNow();*/
			
			//return $results.hide();

		var v = $input.val();
		//if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			
			currentSearchPopupNames = [];
			currentSearchPopupIDs = [];

			hideResultsNow();
			
			//$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		var i = 0;
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}

		// spl //////////
		//i = active;
		// spl //////////

		i = $(li).attr('customIndex');

		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(currentSearchPopupNames[i]);
		$input.attr('directenter', directEnter ? 'true' : 'false');
		setSearchLocationID(currentSearchPopupIDs[i]);

		currentSearchPopupNames = [];
		currentSearchPopupIDs = [];

		hideResultsNow();

		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {

		// special case: down to 1 result
		//if (currentSearchPopupIDs.length == 1) {
			//selectItem($results.find('li'));
		//}

		// special case: "select first"
		if (currentSearchPopupIDs.length > 0) {
			selectItem($results.find('li:first'));
		}

		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {

		// special case: down to 1 result
		//if (currentSearchPopupIDs.length == 1) {
			//selectItem($results.find('li'));
		//}

		// special case: "select first"
		if (currentSearchPopupIDs.length > 0) {
			selectItem($results.find('li:first'));
		}

		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}

		/*
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
		*/
	};

	hackCompletionExternalCloseHandler = hideResultsNow;

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			//if( !hasFocus || data.length == 0 ) return hideResultsNow();
			//if(data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;


		// prevent input blur from closing the ul too early
/*
		$(ul).hover(function() {
				$input.blur(function() {
					hasFocus = false;
				});
			},
			function() {
				$input.blur(function() {
					hasFocus = false;
					hideResults();
				});
			}
		);
*/

		if (num <= 0) {
			var div = document.createElement("div");
			div.innerHTML = '<div class="ac_error_c">0 ' + searchBoxTranslations['s_no_results'] + ' <b>' + $input.val() + '</b></div>';
			$(div).addClass("ac_error");
			ul.appendChild(div);
			$('#popup_locations_trigger').attr('src', '/images/header/icon_destinations_list.gif');
		} else {
			$('#popup_locations_trigger').attr('src', '/images/header/icon_destinations_list_blank.gif');
			for (var i=0; i < num; i++) {
				var row = data[i];
				if (!row) continue;
				var li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if (row.length > 1) {
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
				$(li).attr('customIndex', i);
				ul.appendChild(li);
	
				$(li).click(function(e) {
					e.preventDefault();
					e.stopPropagation();
					selectItem(this);
				}).hover(
					function(e) {
						$(this).addClass("ac_over");
					},
					function(e) {
						$(this).removeClass("ac_over");
					}
				);
			}
		}
		return ul;
	};

	function requestData(q) {
		searchDataDelegate();
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		q = transformNA(q);
		var x = 0;
		var y = 0;
		var bsub = [];
		var csub = [];
		var i = 0;
		currentSearchPopupIDs = [];
		currentSearchPopupNames = [];
		var pIDsA = [];
		var pIDsB = [];
		var pNamesA = [];
		var pNamesB = [];
		for (var j = 0; j < currentSearchNames.length; j++) {
			var index = currentSearchNames[j].indexOf(q);
			if (index >= 0) {
				var endIndex = index + q.length;
				var bolded = currentSearchDisplays[j*currentSearchSkip].substring(0, index);
				bolded += "<b>";
				bolded += currentSearchDisplays[j*currentSearchSkip].substring(index, endIndex);
				bolded += "</b>";
				bolded += currentSearchDisplays[j*currentSearchSkip].substring(endIndex);
				if (index == 0) {
					bsub[x] = [ bolded ];
					pIDsA[x] = currentSearchDisplays[j*currentSearchSkip+1];
					pNamesA[x] = currentSearchNameOnly[j*currentSearchSkip];
					x++;
				} else if (index > 0) {
					csub[y] = [ bolded ];
					pIDsB[y] = currentSearchDisplays[j*currentSearchSkip+1];
					pNamesB[y] = currentSearchNameOnly[j*currentSearchSkip];
					y++;
				}
			}
			if (x > options.maxItemsToShow)
				break;
		}

		currentSearchPopupIDs = pIDsA.concat(pIDsB);
		currentSearchPopupNames = pNamesA.concat(pNamesB);

		return bsub.concat(csub);
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 0;
	options.matchContains = options.matchContains || 1;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};


datepickerRegional = {
		clearText: 'Effacer', clearStatus: '',
		closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
		prevText: '&#x3c;Pr&eacute;c', prevStatus: 'Voir le mois pr&eacute;c&eacute;dent',
		prevBigText: '&#x3c;&#x3c;', prevBigStatus: '',
		nextText: 'Suiv&#x3e;', nextStatus: 'Voir le mois suivant',
		nextBigText: '&#x3e;&#x3e;', nextBigStatus: '',
		currentText: 'Courant', currentStatus: 'Voir le mois courant',
		monthNames: ['Janvier','F&eacute;vrier','Mars','Avril','Mai','Juin',
		'Juillet','Ao&ucirc;t','Septembre','Octobre','Novembre','D&eacute;cembre'],
		monthNamesShort: ['janv.','f&eacute;vr.','mars','avr.','mai','juin',
		'juil.','ao&ucirc;t','sept.','oct.','nov.','d&eacute;c.'],
		monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre ann&eacute;e',
		weekHeader: 'Sm', weekStatus: '',
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
		dateFormat: 'dd/mm/yy', firstDay: 0, 
		initStatus: 'Choisir la date', isRTL: false
};



function stringToDate(date) {
	var c = date.split('/');
	var d = parseInt(c[0], 10);
	var m = parseInt(c[1], 10) - 1;
	var y = parseInt(c[2], 10) + 2000;

	var myDate = new Date(y, m, d);
	myDate.setDate(myDate.getDate());
	return myDate;
}

function dateToString(date) {
	var d = '' + date.getDate();
	var m = '' + (date.getMonth() + 1);
	if (d.length == 1) d = '0' + d;
	if (m.length == 1) m = '0' + m;
	return '' + d + '/' + m + '/' + ('' + date.getFullYear()).substring(2, 4);
}

function resetStartDate(date) {
	searchBoxStartDate = date; 
}

function resetEndDate(date) {
	searchBoxEndDate = date; 
}

searchFirstIntervalCalc = true;

function newDateInterval() {
	newDateIntervalProto(true);
}

function stringToNaturalDate(date) {
	var c = date.split('/');
	var d = c[0];
	var m = parseInt(c[1], 10) - 1;
	var y = c[2];
	return d + '-' + datepickerRegional.monthNamesShort[m] + '-' + y;
}

function newDateIntervalProto(preserveStart) {
	if (searchBoxStartDate !== false || searchBoxEndDate !== false) {
		$('.cancel_block .cancel').css('display', 'block');
	}

	if (searchBoxEndDate !== false) {
		var sel = $('#label_dateend,#label_dateend_r');
		sel.html(stringToNaturalDate(searchBoxEndDate));
	}
	if (searchBoxStartDate !== false) {
		$('#label_datestart,#label_datestart_r').html(stringToNaturalDate(searchBoxStartDate));
	}

	if (searchBoxStartDate === false && searchBoxEndDate !== false) {
		var end = stringToDate(searchBoxEndDate);
		end.setDate(end.getDate() - 1);
		searchBoxStartDate = dateToString(end);
		$('#label_datestart,#label_datestart_r').html(stringToNaturalDate(searchBoxStartDate));
	} else if (searchBoxStartDate !== false && searchBoxEndDate === false) {
		var start = stringToDate(searchBoxStartDate);
		start.setDate(start.getDate() + 1);
		searchBoxEndDate = dateToString(start);
		$('#label_dateend,#label_dateend_r').html(stringToNaturalDate(searchBoxEndDate));
	} else if (searchBoxStartDate === false && searchBoxEndDate === false) {
		return;
	}

	var start = stringToDate(searchBoxStartDate);
	var end = stringToDate(searchBoxEndDate);
	var nights = Math.floor(end.getTime() / 86400000) - Math.floor(start.getTime() / 86400000);

	if (nights <= 0) {
		if (preserveStart) {
			var start = stringToDate(searchBoxStartDate);
			start.setDate(start.getDate() + 1);
			searchBoxEndDate = dateToString(start);
			$('#label_dateend,#label_dateend_r').html(stringToNaturalDate(searchBoxEndDate));
		} else {
			var end = stringToDate(searchBoxEndDate);
			end.setDate(end.getDate() - 1);
			searchBoxStartDate = dateToString(end);
			$('#label_datestart,#label_datestart_r').html(stringToNaturalDate(searchBoxStartDate));
		}
	}

	start = stringToDate(searchBoxStartDate);
	end = stringToDate(searchBoxEndDate);
	nights = Math.floor(end.getTime() / 86400000) - Math.floor(start.getTime() / 86400000);

	$('#nights_n').html("" + nights + " " + searchBoxTranslations['s_nights']);
	if (searchFirstIntervalCalc) {
		$('.totalNights').text("" + nights);
		$('td.nights').text("" + nights);
	}
}

function cancelDateInterval() {
	var mode = searchMode;
	var sid = searchLocationID !== false ? searchLocationID : -1;
	if (typeof(searchFixedHotel) != 'undefined') { 
		sid = searchFixedHotel;
		mode = 'hotel';
	}
	window.location = '/index.php?resource=redirector&component=RedirectStaticSearch&mode=' + mode +  '&searchlist_id=' + sid + '&fromCancelDates=' + encodeURIComponent(window.location);
}

function findValue(li) { }

function selectItem(li) { }

/*
function transformNA(q) {
	var q = q.split('');
	var r = new Array();
	var sec = "\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00d2\u00d3\u00d4\u00d5\u00d5\u00d6\u00d8\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00c8\u00c9\u00ca\u00cb\u00e8\u00e9\u00ea\u00eb\u00f0\u00c7\u00e7\u00d0\u00cc\u00cd\u00ce\u00cf\u00ec\u00ed\u00ee\u00ef\u00d9\u00da\u00db\u00dc\u00f9\u00fa\u00fb\u00fc\u00d1\u00f1\u00de\u00df\u00ff\u00fd";
	var rep = ['A','A','A','A','A','A','a','a','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','e','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','t','s','y','y'];
	for (var i = 0; i < q.length; i++) {
		if (sec.indexOf(q[i]) != -1) {
			r[i] = rep[sec.indexOf(q[i])];
		} else {
			r[i] = q[i];
		}
	}
	return r.join('').toLowerCase();
}
*/

currentSearchNames = false;
currentSearchDisplays = false;
currentSearchNameOnly = false;

currentSearchSkip = 0;

currentSearchPopupNames = [];
currentSearchPopupIDs = [];

// location popup ////////////////////////////////////////////////////////

function sizeForLocColumns(c) {
	$('#popup_locations').css('width', '' + (c*152) + 'px');
}

function addCloseButton(html)
{
	html += "<div class='close'><img src='/close.gif' alt='' /></div>";
	
	return html; 
}

function setupCloseButton()
{
	$("#popup_locations .close").click(function(){
		$("#popup_locations").hide();
	});
}

function locationsBuildCountrySelection()
{
	var cols = 1;
	var html = '';
	
	html += addCloseButton(html);

	html += '<div class="column"><h5>'+searchBoxTranslations['s_main_countries']+'</h5>';
	for(var i = 0; i < LocationNames.length; i+=4) {
		if (LocationNames[i+3] == 3) {
			html += '<a href="javascript:locationsBuildCitySelection(' + "'" + LocationNames[i+2] + "'" + ', false)">' + LocationNamesNoHTML[i] + '</a><br/>';
		}
	}
	html += '</div>';

	var i = 0;
	var c = 0;

	var genCol = function() {
		while (i < LocationNames.length && c < 24) {
			if (LocationNames[i+3] == 0 || LocationNames[i+3] == 3) {
				html += '<a href="javascript:locationsBuildCitySelection(' + "'" + LocationNames[i+2] + "'" + ', false)">' + LocationNamesNoHTML[i] + '</a><br/>';
				c++;
			}
			i+=4;
		}
		c = 0;
		cols++;
	};
	html += '<div class="column"><h5>'+searchBoxTranslations['s_all_countries']+'</h5>'; genCol(); html += '</div>';
	/*if (i < LocationNames.length) { html += '<div class="column"><h5>&nbsp;</h5>'; genCol(); html += '</div>'; }*/
	if (i < LocationNames.length) { html += '<div class="column"><h5>&nbsp;</h5>'; genCol(); html += '</div>'; }
	if (i < LocationNames.length) { html += '<div class="column"><h5>&nbsp;</h5>'; genCol(); html += '</div>'; }
	if (i < LocationNames.length) { html += '<div class="column"><h5>&nbsp;</h5>'; genCol(); html += '</div>'; }

	sizeForLocColumns(cols);
	$('#popup_locations').html(html);

	if ($.browser.msie && $.browser.version == '6.0') {
		// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
		$('#popup_locations').prepend(document.createElement('iframe'));
	}

	setupCloseButton();
}

function locationsBuildCitySelection(code, start)
{
	var cols = 2;
	var html = '';

	html += addCloseButton(html);

	html += '<div class="column"><h5>'+searchBoxTranslations['s_country']+'</h5>';
	html += '<b>' + CountryNames[code] + '</b><br/><br/><br/>';
	html += '<h5>'+searchBoxTranslations['s_main_cities']+'</h5>';
	for(var i = 0; i < LocationNames.length; i+=4) {
		if (LocationNames[i+3] == 4 && LocationNames[i+2] == code) {
			html += '<a href="javascript:locationsSelectedLoc(' + LocationNames[i+1] + ', &quot;' + quoteString(LocationNamesNoHTML[i]) + '&quot;)">' + LocationNamesNoHTML[i] + '</a><br/>';
		}
	}
	html += '<br/><br/><br/><br/><a href="javascript:locationsBuildCountrySelection()">'+searchBoxTranslations['s_back_countries']+'</a><br/>';
	
	html += '</div>';


	html += '<div class="column"><h5>'+searchBoxTranslations['s_all_regions']+'</h5>';
	for(var i = 0; i < LocationNames.length; i+=4) {
		if (LocationNames[i+3] == 1 && LocationNames[i+2] == code) {
			html += '<a href="javascript:locationsSelectedLoc(' + LocationNames[i+1] + ', &quot;' + quoteString(LocationNamesNoHTML[i]) + '&quot;)">' + LocationNamesNoHTML[i] + '</a><br/>';
		}
	}
	html += '</div>';

	var i = 0;

	if (start !== false) {
		i = start;
	}

	var c = 0;
	var genCol = function() {
		while (i < LocationNames.length && c < 24) {
			if ((LocationNames[i+3] == 2 || LocationNames[i+3] == 4) && LocationNames[i+2] == code) {
				html += '<a href="javascript:locationsSelectedLoc(' + LocationNames[i+1] + ', &quot;' + quoteString(LocationNamesNoHTML[i]) + '&quot;)">' + LocationNamesNoHTML[i] + '</a><br/>';
				c++;
			}
			i+=4;
		}
		c = 0;
		cols++;
	};
	html += '<div class="column"><h5>'+searchBoxTranslations['s_all_cities']+'</h5>';
	genCol();
	if (start !== false && start != 0) {
		// doesn't fit, add a page link
		html += '<br/><a href="javascript:locationsBuildCitySelection(' + "'" + code + "'" + ', 0)">'+searchBoxTranslations['s_prev']+'</a><br/>';
	} 
	html += '</div>';
	if (i < LocationNames.length) { html += '<div class="column"><h5>&nbsp;</h5>'; genCol(); html += '</div>'; }
	if (i < LocationNames.length) { html += '<div class="column"><h5>&nbsp;</h5>'; genCol(); html += '</div>'; }
	if (i < LocationNames.length) {
		html += '<div class="column"><h5>&nbsp;</h5>';
		genCol();
		if (i < LocationNames.length) {
			// doesn't fit, add a page link
			html += '<br/><a href="javascript:locationsBuildCitySelection(' + "'" + code + "'" + ', ' + i + ')">'+searchBoxTranslations['s_next']+'</a>';
		} 
	 	html += '</div>';
 	}

	sizeForLocColumns(cols);
	$('#popup_locations').html(html);

	if ($.browser.msie && $.browser.version == '6.0') {
		// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
		$('#popup_locations').prepend(document.createElement('iframe'));
	}

	setupCloseButton();
}

function locationsSelectedLoc(locID, name)
{
	//$('#locationID').val(locID);
	setSearchLocationID(locID);
	$('#searchInput').val(name);
	$('#popup_locations').hide();
}
//////////////////////////////////////////////////////////////////////////

function setSearchLocationID(id)
{
	var directEnter = $('#searchInput').attr('directenter') == 'true';
	searchLocationID = id;
	if (id !== false) {
		//$('#searchButton,#searchButton_r').removeAttr('disabled');
		$('#searchButton,#searchButton_r').removeClass('submit_disabled');
	} else {
		//$('#searchButton,#searchButton_r').attr('disabled', 'disabled');
		$('#searchButton,#searchButton_r').addClass('submit_disabled');
	}

	if (directEnter) {
		genericSearchButtonAction();
	}
}

function searchFindPos(obj) {
	
	var curleft = obj.offsetLeft || 0;
	var curtop = obj.offsetTop || 0;
	while (obj = obj.offsetParent) {
		curleft += obj.offsetLeft;
		curtop += obj.offsetTop;
	}
	return {x:curleft,y:curtop};
}

/******************************************************/
/* calendar 2.0 */
/******************************************************/

window.SplendiaCalendar = function(displayElement, extraCSS, triggers, callbacks) {
	var thisCalendar = this;
	this.displayElement = displayElement;
	this.extraCSS = extraCSS;
	this.callbacks = callbacks;
	$.each(triggers, function(i, val) {
		$(val).click(function() {
			thisCalendar.toggle();
			return false;
		});
	});
	this.$node = false;
}

window.SplendiaCalendar.prototype = {

	toggle: function() {
		this.prebuild();
		
		if (this.$node.css('display') == 'none') {
			$('.sc_container').hide();
			this.show();
		} else {
			this.hide();
		}

	},

	prebuild: function() {
		if (this.$node === false) {
			this.$node = $('<div class="sc_container autoclosing_popup" style="'+this.extraCSS+'"></div>');
			$('body').append(this.$node);
			this.$node.click(function() { return false; });
		}
		this.reposition();
	},

	findPos: function(obj) {
		obj = $(obj).get(0);
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	},

	reposition: function() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = this.findPos(this.displayElement);
		// reposition
		this.$node.css({
			//width: parseInt(iWidth) + "px",
			top: (pos.y + $(this.displayElement).get(0).offsetHeight) + "px",
			left: pos.x + "px"
		});
	},

	hide: function() {
		this.$node.hide();
	},

	show: function() {
		this.render();
		this.$node.show();
	},

	parseDate: function(d) {
		var c = d.split('/');
		var d = parseInt(c[0], 10) - 1;
		var m = parseInt(c[1], 10) - 1;
		var y = parseInt(c[2], 10) + 2000;
		return { 'day' : d, 'month' : m, 'year' : y };
	},

	nextMonth: function(year, month) {
		month++;
		if (month > 11) {
			year++;
			month = 0;
		}
		return { 'year' : year, 'month' : month };
	},

	prevMonth: function(year, month) {
		month--;
		if (month < 0) {
			year--;
			month = 11;
		}
		return { 'year' : year, 'month' : month };
	},

	render: function() {
		var base = this.parseDate(this.callbacks.getToday());
		var selected = this.callbacks.getSelected();
		if (selected != false) {
			base = this.parseDate(selected);
		}

		this.renderMonth(base);
	},

	renderMonth: function(base) {
		//var pager = page > 0 ? '<div class="pager"></div>' : '';

		var today = this.parseDate(this.callbacks.getToday());

		var prev = this.prevMonth(base.year, base.month);
		prev = this.prevMonth(prev.year, prev.month);
		var next = this.nextMonth(base.year, base.month);
		next = this.nextMonth(next.year, next.month);

		var zeroBased = today.month + today.year*12;
		var leftParity = ((base.month + base.year*12) - zeroBased) % 2;
		if (leftParity == 1) {
			base = this.prevMonth(base.year, base.month);
		}

		var nextYear = this.parseDate(this.callbacks.getToday());
		nextYear.year++;

		var pager = today.year == base.year && today.month == base.month ? '' : '<div class="pager"></div>';
		var html = '<div class="month_panel month_left"><div class="month_name">' + pager + this.callbacks.getMonthName(base.month) + ' ' + base.year + '</div>';
		html += this.generateMonth(base.year, base.month);
		html += '</div>';

		base = this.nextMonth(base.year, base.month);

		var pager = base.year >= nextYear.year && base.month >= nextYear.month  ? '' : '<div class="pager"></div>';
		html += '<div class="month_panel month_right"><div class="month_name">' + pager  + this.callbacks.getMonthName(base.month) + ' ' + base.year + '</div>';
		html += this.generateMonth(base.year, base.month);
		html += '</div>';

		html += '<div class="sc_footer"><div class="close">'+this.callbacks.getClose()+'</div>'+this.callbacks.getLabel()+'</div>';

		this.$node.html(html);

		var thisCalendar = this;

		$('.month_left .pager', this.$node).click(function() {
			thisCalendar.renderMonth(prev);
		});

		$('.month_right .pager', this.$node).click(function() {
			thisCalendar.renderMonth(next);
		});

		$('.cl', this.$node).click(function() {
			thisCalendar.callbacks.selectionMade($(this).attr('spdate'));
			thisCalendar.hide();
		});

		$('.sc_footer .close', this.$node).click(function() {
			thisCalendar.hide();
		});
	},

	day1Offset: function(year, month) {
		var d = new Date(year, month, 1);
		var d = d.getDay() - 1;
		return d >= 0 ? d : 6;
	},

	daysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	buildSPDate: function(year, month, day) {
		var d = '' + (day + 1);
		var m = '' + (month + 1);
		if (d.length == 1) d = '0' + d;
		if (m.length == 1) m = '0' + m;
		return '' + d + '/' + m + '/' + ('' + year).substring(2, 4);
	},

	generateMonth: function(year, month) {
		var selected = this.callbacks.getSelected();
		if (selected == false)
			selected = -9999;
		else {
			selected = this.parseDate(selected);
			if (selected.month == month && selected.year == year)			
				selected = selected.day;
			else
				selected = -9999;
		}

		var today = this.parseDate(this.callbacks.getToday());
		var cutoffDay = -9999;
		if (today.month == month && today.year == year)
			cutoffDay = today.day;
		
		var i = -this.day1Offset(year, month);
		var n = this.daysInMonth(year, month);
		var html = '<table cellpadding="0" cellspacing="0" class="month">';

		html += '<tr>';
		var j = 0;
		while (j < 7) {
			html += '<th>'+this.callbacks.getDayName(j)+'</th>';
			j++;
		}
		html += '</tr>';

		var h = 0;
		while (h < 6) {
			html += '<tr>';
			for (var j = 0; j < 7; j++, i++) {
				if (i < n && i >= 0) {
					var klass = 'noday';
					if (i >= cutoffDay) {
						klass = 'cl';
						if (i == selected)
							klass += " sel";
						else
							klass += " day";
					}
					var spdate = this.buildSPDate(year, month, i);
					html += '<td spdate="' + spdate + '" class="' + klass + '">' + (i + 1) + '</td>';
				} else
					html += '<td>&nbsp;</td>';
			}
			html += '</tr>';
			h++;
		}
		html += '</table>';
		return html;
	}

};


//$(document).ready(function()
SplendiaSoftReadyHandlers.push(function()
{
	// do not run the search setup if there is no search box
	if (typeof(window['searchMode']) == "undefined" ) {
		return;
	}

	var popup = document.createElement('div');
	popup.setAttribute('id', 'popup_locations');
	var input = document.getElementById('searchInput');
	// BUGFIX: Stop looking at input, when it doesnt exist
	if(input){
		var pos = searchFindPos(input);
		$(popup).hide().css({
			top: (pos.y + input.offsetHeight + 4) + "px",
			left: pos.x + "px"
		});
	}
	$('body').append(popup);

	window.initialDatestart = searchBoxStartDate;
	window.initialDateend = searchBoxEndDate;

	$('#searchInput').attr('mode', 'dest');

	function setSearchMode(mode) {
		if (mode == searchMode)
			return;

		setSearchLocationID(false);

		if (mode == "destination") {
			$('#radio_destination').attr('class', 'radio_selected');
			$('#radio_hotel').attr('class', 'radio_unselected');
			//$('#searchInput').val('');
			$('#searchInput').val($('#searchInput').attr('titled'));
			$('#searchInput').attr('mode', 'dest');
			$('#searchInput').animate({ width : '169px' }, 'normal', function() { $('#popup_locations_trigger').show('normal'); } );
			$('.search_box .submit').val(searchBoxTranslations['s_search']);

			searchMode = "destination";
			currentSearchNames = LocationNamesNA;
			currentSearchDisplays = LocationNames;
			currentSearchNameOnly = LocationNamesNoHTML;
			currentSearchSkip = 4;
		} else {
			$('#radio_destination').attr('class', 'radio_unselected');
			$('#radio_hotel').attr('class', 'radio_selected');
			//$('#searchInput').val('');
			$('#searchInput').val($('#searchInput').attr('titleh'));
			$('#searchInput').attr('mode', 'hotel');
			$('#popup_locations_trigger').hide('normal', function() { $('#searchInput').animate({ width : '182px' }, 'normal'); });
			$('#popup_locations').hide();
			$('.search_box .submit').val(searchBoxTranslations['s_book']);
		
			searchMode = "hotel";
			currentSearchNames = HotelNamesNA;
			currentSearchDisplays = HotelNames;
			currentSearchNameOnly = HotelNamesNoHTML;
			currentSearchSkip = 4;
		}
		//$("#searchInput")[0].autocompleter.flushCache();
	}

	currentSearchNames = LocationNamesNA;
	currentSearchDisplays = LocationNames;
	currentSearchNameOnly = LocationNamesNoHTML;
	currentSearchSkip = 4;

	$('#searchInput').autocompleteArray(
		[ 'filler' ],
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:false,
			maxItemsToShow:20,
			selectOnly:1,
			selectFirst:1
		}
	);

	// location popup ////////////////////////////////////////////////////////
	$('#popup_locations_trigger').click(function () {
		searchDataDelegate();
		locationsBuildCountrySelection();
		$('#popup_locations').toggle();
	});

	// room selector ////////////////////////////////////////////////////////
	$('#rooms_selector').click(function() {
		$('#rooms_list').slideToggle('fast');
	});
	$('#rooms_selector_r').click(function() {
		$('#rooms_list_r').slideToggle('fast');
	});
	//$('#rooms_selector li a,#rooms_selector_r li a').click(function(ev) {
	$('.room_selector_room_e').click(function(ev) {
		var t = $(ev.target).text();
		$('#rooms_selected,#rooms_selected_r').text(t);
		searchBoxRooms = t.substring(0, 1);
		$('#rooms_list,#rooms_list_r').hide();
		return false;
	});

	// adults selector ////////////////////////////////////////////////////////
	$('#adults_selector').click(function() {
		$('#adults_list').slideToggle('fast');
	});
	$('#adults_selector_r').click(function() {
		$('#adults_list_r').slideToggle('fast');
	});
	//$('#adults_selector li a,#adults_selector_r li a').click(function(ev) {
	$('.adults_selector_room_e').click(function(ev) {
		var t = $(ev.target).text();
		$('#adults_selected,#adults_selected_r').text(t);
		searchBoxAdults = t.substring(0, 1);
		$('#adults_list,#adults_list_r').hide();
		return false;
	});

	$('#radio_destination').click(function(ev) {
		setSearchMode("destination");
	});

	$('#radio_hotel').click(function(ev) {
		setSearchMode("hotel");
	});

	genericSearchButtonAction = function(ev) {
		if (searchLocationID !== false) {
			var dA = '';
			var dE = '';
			var dR = '&rooms=' + searchBoxRooms;
			var dAd = '&adults=' + searchBoxAdults;
			if (searchBoxStartDate !== false && searchBoxEndDate !== false) {
				dA = '&datestart=' + searchBoxStartDate;
				dE = '&dateend=' + searchBoxEndDate;
			}
			window.location = '/index.php?resource=redirector&component=RedirectStaticSearch&mode=' + searchMode +  '&searchlist_id=' + searchLocationID + dA + dE + dR + dAd;
		} else {
			$('#searchInput').animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
		    	.animate( { backgroundColor: 'white' }, 120)
		    	.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
		    	.animate( { backgroundColor: 'white' }, 120)
		    	.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
		    	.animate( { backgroundColor: 'white' }, 120);
		}
	}
	$('#searchButton').click(genericSearchButtonAction);

	// the hotel page always submits an hotel search, not a location search
	hotelPageSearchButtonActionProto = function(scrollToRooms) {
		if (searchFixedHotel !== false) {
			var dA = '';
			var dE = '';
			var dR = '&rooms=' + searchBoxRooms;
			var dAd = '&adults=' + searchBoxAdults;
			if (searchBoxStartDate !== false && searchBoxEndDate !== false) {
				dA = '&datestart=' + searchBoxStartDate;
				dE = '&dateend=' + searchBoxEndDate;
			}
			var dS = scrollToRooms ? '&roomscroll=1' : '';
			window.location = '/index.php?resource=redirector&component=RedirectStaticSearch&mode=hotel' + '&searchlist_id=' + searchFixedHotel + dA + dE + dR + dAd + dS;
		}
	};

	hotelPageSearchButtonAction = function() {
		hotelPageSearchButtonActionProto(false);
	};

	$('#searchButton_r').click(function() { hotelPageSearchButtonActionProto(true); } );

	// setup is done, now use initial params to set saved state /////////////
	if (searchBoxStartDate !== false || searchBoxEndDate !== false) {
		newDateInterval();
	}

	// avoid changes to nights display in the booking tab
	searchFirstIntervalCalc = false;

	if (searchMode != 'destination') {
		$('#radio_destination').attr('class', 'radio_unselected');
		$('#radio_hotel').attr('class', 'radio_selected');
		$('#popup_locations_trigger').hide();
		$('#searchInput').css('width', '182px');
		$('.search_box .submit').val(searchBoxTranslations['s_book']);
	
		searchMode = "hotel";
		currentSearchNames = HotelNamesNA;
		currentSearchDisplays = HotelNames;
		currentSearchNameOnly = HotelNamesNoHTML;
		currentSearchSkip = 4;
	}

	// init location
	setSearchLocationID(searchLocationID);

	// calendar 2.0
	var callbacksBase = function() { };
	callbacksBase.prototype = {
		getMonthName: function(month) {
			return datepickerRegional.monthNames[month];
		},
		getDayName: function(day) {
			if (day == 6)
				return datepickerRegional.dayNamesMin[0];
			return datepickerRegional.dayNamesMin[day+1];
		},
		getClose: function() {
			return searchBoxTranslations['s_close'];
		},
		getToday: function() {
			return searchBoxTodayDate;
		}
	};

	var callbacksS = new callbacksBase();
	callbacksS.getSelected = function() {
		return searchBoxStartDate;
	}
	callbacksS.getLabel = function() {
		return searchBoxTranslations['s_date_arr'];
	}
	callbacksS.selectionMade = function(selected) {
		resetStartDate(selected);
		newDateIntervalProto(true);
	}

	var callbacksE = new callbacksBase();
	callbacksE.getSelected = function() {
		return searchBoxEndDate;
	}
	callbacksE.getLabel = function() {
		return searchBoxTranslations['s_date_dep'];
	}
	callbacksE.selectionMade = function(selected) {
		resetEndDate(selected);
		newDateIntervalProto(false);
	}

	var cal1 = new SplendiaCalendar('#datestart', '', ['#datestart', '#fake-trigger-start'], callbacksS);
	var cal2 = new SplendiaCalendar('#dateend', '', ['#dateend', '#fake-trigger-end' ], callbacksE);
	var cal3 = new SplendiaCalendar('#datestart_r', '', ['#datestart_r', '#fake-trigger-start_r'], callbacksS);
	var cal4 = new SplendiaCalendar('#dateend_r', '', ['#dateend_r', '#fake-trigger-end_r' ], callbacksE);

	var damnIE6 = function () {
		if ($.browser.msie && $.browser.version == '6.0') {
			$('select').toggle();
		}
	};
/*
	var startPickerOnScreen = false;
	var endPickerOnScreen = false;
	var startPickerOnScreen2 = false;
	var endPickerOnScreen2 = false;

	$('#fake-trigger-start').click(function() {
		if (startPickerOnScreen) {
			$('#datestart').datepicker('hide');
		} else {
			$('#datestart').datepicker('show');
		}
	});

	$('#fake-trigger-end').click(function() {
		if (endPickerOnScreen) {
			$('#dateend').datepicker('hide');
		} else {
			$('#dateend').datepicker('show');
		}
	});

	$('#fake-trigger-start_r').click(function() {
		if (startPickerOnScreen2) {
			$('#datestart_r').datepicker('hide');
		} else {
			$('#datestart_r').datepicker('show');
		}
	});

	$('#fake-trigger-end_r').click(function() {
		if (endPickerOnScreen2) {
			$('#dateend_r').datepicker('hide');
		} else {
			$('#dateend_r').datepicker('show');
		}
	});

	$("#datestart").datepicker({
		duration: '',
		dateFormat: 'dd/mm/y',
		firstDay: 1,
		numberOfMonths: 2,
		changeMonth: false,
		changeYear: false,
		mandatory: true,
		showOn: "focus",
		minDate: new Date(),
		maxDate: '+1y',
		beforeShow: function () { damnIE6(); startPickerOnScreen = true; },
		onClose: function() { damnIE6(); startPickerOnScreen = false; },
		onSelect: function(date) { resetStartDate(date); newDateIntervalProto(true) }
	});
	$("#datestart_r").datepicker({
		duration: '',
		dateFormat: 'dd/mm/y',
		firstDay: 1,
		numberOfMonths: 2,
		changeMonth: false,
		changeYear: false,
		mandatory: true,
		showOn: "focus",
		minDate: new Date(),
		maxDate: '+1y',
		beforeShow: function () { damnIE6(); startPickerOnScreen2 = true; },
		onClose: function() { damnIE6(); startPickerOnScreen2 = false; },
		onSelect: function(date) { resetStartDate(date); newDateIntervalProto(true) }
	});

	$("#dateend").datepicker({
		duration: '',
		dateFormat: 'dd/mm/y',
		firstDay: 1,
		numberOfMonths: 2,
		changeMonth: false,
		changeYear: false,
		mandatory: true,
		showOn: "focus",
		minDate: new Date(),
		maxDate: '+1y',
		beforeShow: function () { damnIE6(); endPickerOnScreen = true; },
		onClose: function() { damnIE6();  endPickerOnScreen = false; },
		onSelect: function(date) { resetEndDate(date); newDateIntervalProto(false) }
	});
	$("#dateend_r").datepicker({
		duration: '',
		dateFormat: 'dd/mm/y',
		firstDay: 1,
		numberOfMonths: 2,
		changeMonth: false,
		changeYear: false,
		mandatory: true,
		showOn: "focus",
		minDate: new Date(),
		maxDate: '+1y',
		beforeShow: function () { damnIE6(); endPickerOnScreen2 = true; },
		onClose: function() { damnIE6();  endPickerOnScreen2 = false; },
		onSelect: function(date) { resetEndDate(date); newDateIntervalProto(false) }
	});
*/
});



