function onLoadMicrosite()
{
	setTotals();
}

/* Newsletter box on Homepage */
function newsletterValid()
{
	if ( !( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test( document.getElementById( 'EMail' ).value ) ) )
	{
		alert("Please enter your email address correctly.");
		return false;
	}

	if( !document.getElementById( 'TAndC' ).checked )
	{
		alert("Please click the box to show you accept the Terms & Conditions.");
		return false;
	}

	return true;
}


/* redirectToLocation */
function redirectToLocation( value )
{
	if( value != "" )
	{
		window.location.href = value;
	}
}


/* on Page Log */
function onPageLog( sessionId, pageName, action, content )
{
	jQuery.post("/onPageLog.php", {sessionId: sessionId, pageName: pageName, action: action, content: content});
}


/* AJAX CALENDAR WIDGET */
var AjaxCalendarDepartFAB_time = 0;
function AjaxCalendarDepartFAB(monthYear){

    //Add hiding Cal
    document.documentElement.onclick = function(e) {
      if(clickedOutsideElement('calSurroundDepartingFAB',e) && document.getElementById("calSurroundDepartingFAB").style.display != "none"){
        if( AjaxCalendarDepartFAB_time == 0 || new Date().getTime() - AjaxCalendarDepartFAB_time > 500 ) {
			closeCalenderAjax( true, true );
			return;
		}
		else
			return;
      }
    };

   closeCalenderAjax( false, true );

    if (monthYear == "") {
        if (document.getElementById("DepartingMatchesFAB").style.display == "block") {
             if( AjaxCalendarDepartFAB_time == 0 || new Date().getTime() - AjaxCalendarDepartFAB_time > 500 ) {
				closeCalenderAjax( true, true );
				return;
			}
			else
				return;
        }else{
          //set start monthYear from field value
          var DateField = document.getElementById("DepartingFAB").value;
          var bits = DateField.split(" ");
          monthYear = getMonthAsInt( bits[1] )+'-'+bits[2];
        }
    }

	AjaxCalendarDepartFAB_time = new Date().getTime();

    ajaxCalendarDepartRequest = initCalendarAjax();

    if (ajaxCalendarDepartRequest == null) {
        //fail silently... ?
        return;
    }

    ajaxCalendarDepartRequest.onreadystatechange = function(){
        if (ajaxCalendarDepartRequest.readyState == 4) {
            if (ajaxCalendarDepartRequest.responseText != "") {
                document.getElementById("DepartingMatchesFAB").style.display = "block";
                document.getElementById("DepartingMatchesFAB").innerHTML = ajaxCalendarDepartRequest.responseText;
                document.getElementById("calSurroundDepartingFAB").style.display = "block";
            }
            else {
                document.getElementById("DepartingMatchesFAB").style.display = "none";
                document.getElementById("calSurroundDepartingFAB").style.display = "none";
            }
        }
        else {
            document.getElementById("DepartingMatchesFAB").style.display = "none";
            document.getElementById("calSurroundDepartingFAB").style.display = "none";
        }
    }

    var url = "/populateCalendar.php?type=depart&monthYear=" + monthYear + "&FAB=1";
    if (window.overridePath != undefined && overridePath != "")
        url = overridePath + "populateCalendar.php?type=depart&monthYear=" + monthYear + "&FAB=1";

    ajaxCalendarDepartRequest.open("GET", url, true);
    ajaxCalendarDepartRequest.send(null);

}

var AjaxCalendarDepart_time = 0;
function AjaxCalendarDepart(monthYear){

    //Add hiding Cal
    document.documentElement.onclick = function(e) {
      if(clickedOutsideElement('calSurroundDeparting',e) && document.getElementById("calSurroundDeparting").style.display != "none"){
        if( AjaxCalendarDepart_time == 0 || new Date().getTime() - AjaxCalendarDepart_time > 500 ) {
			closeCalenderAjax( true, false );
			return;
		}
		else
			return;
      }
    };

    closeCalenderAjax( false, false );

    if (monthYear == "") {
        if (document.getElementById("DepartingMatches").style.display == "block") {
            if( AjaxCalendarDepart_time == 0 || new Date().getTime() - AjaxCalendarDepart_time > 500 ) {
				closeCalenderAjax( true, false );
				return;
			}
			else
				return;
        }else{
          //set start monthYear from field value
          var DateField = document.getElementById("Departing").value;
          var bits = DateField.split(" ");
          monthYear = getMonthAsInt( bits[1] )+'-'+bits[2];
        }
    }

	AjaxCalendarDepart_time = new Date().getTime();

    ajaxCalendarDepartRequest = initCalendarAjax();

    if (ajaxCalendarDepartRequest == null) {
        //fail silently... ?
        return;
    }

    ajaxCalendarDepartRequest.onreadystatechange = function(){
        if (ajaxCalendarDepartRequest.readyState == 4) {
            if (ajaxCalendarDepartRequest.responseText != "") {
                document.getElementById("DepartingMatches").style.display = "block";
                document.getElementById("DepartingMatches").innerHTML = ajaxCalendarDepartRequest.responseText;
                document.getElementById("calSurroundDeparting").style.display = "block";
            }
            else {
                document.getElementById("DepartingMatches").style.display = "none";
                document.getElementById("calSurroundDeparting").style.display = "none";
            }
        }
        else {
            //document.getElementById("DepartingMatches").style.display = "none";
            //document.getElementById("calSurroundDeparting").style.display = "none";
        }
    }

    var url = "/populateCalendar.php?type=depart&monthYear=" + monthYear;
    if (window.overridePath != undefined && overridePath != "")
        url = overridePath + "populateCalendar.php?type=depart&monthYear=" + monthYear;

    ajaxCalendarDepartRequest.open("GET", url, true);
    ajaxCalendarDepartRequest.send(null);
}

var AjaxCalendarArriveFAB_time = 0;
function AjaxCalendarArriveFAB(monthYear){

    //Add hiding Cal
    document.documentElement.onclick = function(e) {
      if(clickedOutsideElement('calSurroundArrivingFAB',e) && document.getElementById("calSurroundArrivingFAB").style.display != "none"){
		if( AjaxCalendarArriveFAB_time == 0 || new Date().getTime() - AjaxCalendarArriveFAB_time > 500 ) {
			closeCalenderAjax( false, true );
			return;
		}
		else
			return;
      }
    };

    closeCalenderAjax( true, true );

    if (monthYear == "") {
        if (document.getElementById("ArrivingMatchesFAB").style.display == "block") {
            if( AjaxCalendarArriveFAB_time == 0 || new Date().getTime() - AjaxCalendarArriveFAB_time > 500 ) {
			closeCalenderAjax( false, true );
			return;
		}
		else
			return;
        }else{
          //set start monthYear from field value
          var DateField = document.getElementById("ArrivingFAB").value;
          var bits = DateField.split(" ");
          monthYear = getMonthAsInt( bits[1] )+'-'+bits[2];
        }
    }

	AjaxCalendarArriveFAB_time = new Date().getTime();

    ajaxCalendarArriveRequest = initCalendarAjax();

    if (ajaxCalendarArriveRequest == null) {
        //fail silently... ?
        return;
    }

    ajaxCalendarArriveRequest.onreadystatechange = function(){
        if (ajaxCalendarArriveRequest.readyState == 4) {
            if (ajaxCalendarArriveRequest.responseText != "") {
                document.getElementById("ArrivingMatchesFAB").style.display = "block";
                document.getElementById("ArrivingMatchesFAB").innerHTML = ajaxCalendarArriveRequest.responseText;
                document.getElementById("calSurroundArrivingFAB").style.display = "block";
            }
            else {
                document.getElementById("ArrivingMatchesFAB").style.display = "none";
                document.getElementById("calSurroundArrivingFAB").style.display = "none";
            }
        }
        else {
            //document.getElementById("ArrivingMatchesFAB").style.display = "none";
            //document.getElementById("calSurroundArrivingFAB").style.display = "none";
        }
    }

    var url = "/populateCalendar.php?type=arrive&monthYear=" + monthYear + "&FAB=1";
    if (window.overridePath != undefined && overridePath != "")
        url = overridePath + "populateCalendar.php?type=arrive&monthYear=" + monthYear + "&FAB=1";

    ajaxCalendarArriveRequest.open("GET", url, true);
    ajaxCalendarArriveRequest.send(null);
}

//The names of the months for showing in frontend
// used in functions
// getMonthAsInt()
// checkCalendarDepartAjax()
var MonthName = new Array( "Jan",
							"Feb",
							"Mar",
							"Apr",
							"May",
							"Jun",
							"Jul",
							"Aug",
							"Sep",
							"Oct",
							"Nov",
							"Dec"
            );

/**
 * This function returns the int value of the var month.
 *
 * @param monthString String
 * @author sebastain.thoss
 */
function getMonthAsInt( monthString )
{
    for( i = 0; i < MonthName.length; i++ )
    {
        if( monthString == MonthName[i] )
        {
            return i+1;
        }
    }
}

var AjaxCalendarArrive_time = 0;
function AjaxCalendarArrive(monthYear){

    //Add hiding Cal
    document.documentElement.onclick = function(e) {
      if(clickedOutsideElement('calSurroundArriving',e) && document.getElementById("calSurroundArriving").style.display != "none"){
        if( AjaxCalendarArrive_time == 0 || new Date().getTime() - AjaxCalendarArrive_time > 500 ) {
			closeCalenderAjax( false, false );
			return;
		}
		else
			return;
      }
    };

    closeCalenderAjax( true, false );

    if (monthYear == "") {
        if (document.getElementById("ArrivingMatches").style.display == "block") {
			if( AjaxCalendarArrive_time == 0 || new Date().getTime() - AjaxCalendarArrive_time > 500 ) {
				closeCalenderAjax( false, false );
				return;
			}
			else
				return;
        }else{
          //set start monthYear from field value
          var DateField = document.getElementById("Arriving").value;
          var bits = DateField.split(" ");
          monthYear = getMonthAsInt( bits[1] )+'-'+bits[2];
        }
    }

	AjaxCalendarArrive_time = new Date().getTime();

    ajaxCalendarArriveRequest = initCalendarAjax();

    if (ajaxCalendarArriveRequest == null) {
        //fail silently... ?
        return;
    }

    document.getElementById("ArrivingMatches").style.display = "block";
    ajaxCalendarArriveRequest.onreadystatechange = function(){
        if (ajaxCalendarArriveRequest.readyState == 4) {
            if (ajaxCalendarArriveRequest.responseText != "") {
                document.getElementById("ArrivingMatches").innerHTML = ajaxCalendarArriveRequest.responseText;
                document.getElementById("calSurroundArriving").style.display = "block";
            }
            else {
                document.getElementById("ArrivingMatches").style.display = "none";
                document.getElementById("calSurroundArriving").style.display = "none";
            }
        }
        else {
            //document.getElementById("ArrivingMatches").style.display = "none";
            //document.getElementById("calSurroundArriving").style.display = "none";
        }
    }

    var url = "/populateCalendar.php?type=arrive&monthYear=" + monthYear;
    if (window.overridePath != undefined && overridePath != "")
        url = overridePath + "populateCalendar.php?type=arrive&monthYear=" + monthYear;

    ajaxCalendarArriveRequest.open("GET", url, true);
    ajaxCalendarArriveRequest.send(null);

    //Update Depart Callendar

}



//Hide Calendar
function clickedOutsideElement(elemId,e) {
	var theElem = getEventTarget(e);
	while(theElem != null) {
		if (theElem.id == elemId) {
			return false;
		}
		theElem = theElem.offsetParent;
	}
	return true;
}

function getEventTarget(e) {
	var targ;
	if (e != null && e.target != null) {
		targ = e.target;
	} else {
		if (e != null && e.srcElement != "") {
			targ = e.srcElement;
		} else {
			targ = window.event.srcElement;
		}
	}
	if(targ != null) {
		if (targ.nodeType == 3) {
			targ = targ.parentNode;
		}
	}
	return targ;
}







function initCalendarAjax(){
    //function to create and return a XMPHTTP object
    var ajaxCalendarRequest;
    ajaxCalendarRequest = false;
    try {
        // create Opera 8.0+/Firefox/Safari XMPHTTP object
        ajaxCalendarRequest = new XMLHttpRequest();
        return ajaxCalendarRequest;
    }
    catch (e) {
        // try creating IE object if above fails
        try {
            ajaxCalendarRequest = new ActiveXObject("Msxml2.XMLHTTP");
            return ajaxCalendarRequest;
        }
        catch (e) {

            try {
                ajaxCalendarRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                //browser doesn't support ajax
                return false;
            }
        }
    }
    return;
}

function setCalendarArriveAjaxFAB(val){
    document.getElementById("ArrivingFAB").value = val;
	closeCalenderAjax( false, true );
    checkCalendarDepartAjax('FAB',false);
	$("#DepartingFAB").focus();
}

function setCalendarDepartAjaxFAB(val){
    document.getElementById("DepartingFAB").value = val;
	closeCalenderAjax( true, true );
    checkCalendarDepartAjax('FAB',true);
	$("#mainCurrFAB").focus();
}

function setCalendarArriveAjax(val){
    document.getElementById("Arriving").value = val;
	closeCalenderAjax( false, false );
    checkCalendarDepartAjax('',false);
	$("#Departing").focus();
}

function setCalendarDepartAjax(val){
    document.getElementById("Departing").value = val;
	closeCalenderAjax( true, false );
    checkCalendarDepartAjax('',true);
	$("#Guests").focus();
}

function closeCalenderAjax( isDepart, isFab )
{
	var surround = "calSurroundArriving";
	var match = "ArrivingMatches";

	if( isDepart ) {
		surround = "calSurroundDeparting";
		match = "DepartingMatches";
	}

	if( isFab ) {
		surround += "FAB";
		match += "FAB";
	}

	try {
		document.getElementById( surround ).style.display = "none";
		document.getElementById( match ).style.display = "none";
	}
	catch( e ){
//		console.debug( surround +" or "+ match +" not found"  );
	}
}

/**
 * This function parse the Date from the input field.
 *
 * @param dateString String
 */
function parseDate(dateString)
{
	var bits = dateString.split(" ");
	var date = new Date();
	date.setFullYear( bits[2]-0+2000, getMonthAsInt(bits[1] ) - 1, bits[0] );
	date.setHours( 12, 0, 0, 0 );
	return date;
}

function addDaysToCalendar(objArrow, calId) {
	objArrow = $(objArrow);
	var isBackArrow = !(-1 == objArrow.attr('class').indexOf('BackArrow'));
	var daysNumber = isBackArrow ? -1 : 1;
	var inputDate = $('#'+calId);

	var curTime = new Date();
	curTime.setHours(0);
	curTime.setMinutes(0);
	curTime.setMilliseconds(0);
	
	var newDate = parseDate(inputDate.val());
	newDate.setDate(newDate.getDate() + daysNumber);

	if (isBackArrow && newDate.getTime() < curTime.getTime()) {
		return;
	}

	var day = newDate.getDate();
	if (day < 10) {
		day = '0'+day;
	}
	var month= MonthName[newDate.getMonth()];
	var year = newDate.getFullYear() - 2000;
	newDate = day+' '+month+' '+year;
	inputDate.val(newDate);

	$('#DatesDynamic > form').submit();
}

/**
 * This function check the departure date whether it's before or at
 * the same day as arrival date.
 * If departure date is lower equal the arrival date the one date
 * will be moved to to the next valid day.
 * Which dats moved appends on the var isDepartingLeading
 * If isDepartingLeading is false the departure date will be moved
 * If isDepartingLeading is true the arrival date will be moved
 *
 * @param type String postfix of the date fields
 * @param isDepartingLeading Boolean if true it will move the arrival date
 */
function checkCalendarDepartAjax(type, isDepartingLeading)
{
	var startDate = parseDate(document.getElementById("Arriving" + type).value);
	var endDate = parseDate(document.getElementById("Departing" + type).value);

	if (startDate >= endDate)
	{
		var newDate = null;
		if( isDepartingLeading )
		{
			newDate = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate() - 0 - 1);
		}
		else
		{
			 newDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() - 0 + 1);
		}

		var year = 0;
		if (newDate.getFullYear() < 2010)
		{
			year = "0" + (newDate.getFullYear() - 2000);
		}
		else
		{
			year = newDate.getFullYear() - 2000;
		}

		var month = MonthName[newDate.getMonth() - 0];

		var day = newDate.getDate();
		if (day < 10)
		{
			day = "0" + day;
		}

		if( isDepartingLeading )
		{
			document.getElementById("Arriving" + type).value = day + " " + month + " " + year;
		}
		else
		{
			document.getElementById("Departing" + type).value = day + " " + month + " " + year;
		}

	}
	else // I'm not sure if need this part of JS
	{
		if( document.getElementById("maximumStayWarn" + type) != null )
		{
			document.getElementById("maximumStayWarn" + type).style.display = "none";
		}
	}
}

/* AJAX SEARCH WIDGET */
var selectedItem = 0;
var prevDestination = '';
var t = false;
function AjaxDestinationKey(key) {
	clearTimeout(t);
    if( key == 40 || key == 39 )
	{
			selectedItem++;
			if(!$("#lides_"+selectedItem))selectedItem--;
    }

    if( key == 38 || key == 37 )
	{
        if (selectedItem > 0)
            selectedItem--;
			if(!$("#lides_"+selectedItem))selectedItem++;
    }

	if( key == 40 || key == 39 || key == 38 || key == 37 )
	{

		$( "#lides_"+(selectedItem-1 ) ).removeClass( 'selected' );
		$( "#lides_"+(selectedItem+1 ) ).removeClass( 'selected' );
		$( "#lides_"+selectedItem).addClass( 'selected' );
	}

    if( key == 9 || key == 13 )
	{
		if ( selectedItem > 0 )
		{
			if (document.getElementById("DestinationMatches").style.display == "block")
			{
				var tmpDestination = document.getElementById( "des_"+selectedItem ).innerHTML;
				document.getElementById("Destination").value = $('<textarea />').html( tmpDestination ).val();
				document.getElementById("DestinationMatches").style.display = "none";
				selectedItem = 0;
				$("#Arriving").focus();
				return false;
			}
		}
		return;
	}

	if(prevDestination == document.getElementById("Destination").value )
	{
		return;
	}

	prevDestination = document.getElementById("Destination").value;
	selectedItem = 0;
	t = setTimeout("AjaxDestination()", 150);

}

function AjaxDestinationHide(){
    if (document.getElementById("DestinationMatches"))
	{
        document.getElementById("DestinationMatches").style.display = "none";
//		document.getElementById("mainCurr").style.display = "block";
//		document.getElementById("Guests").style.display = "block";
	}
}

function AjaxDestination(){
    ajaxDestinationRequest = initDestinationAjax();

    if (ajaxDestinationRequest == null) {
        //fail silently... ?
        return false;
    }

    ajaxDestinationRequest.onreadystatechange = function(){
        var responseText = ajaxDestinationRequest.responseText;
        var matches = document.getElementById('DestinationMatches');
        if (4 == ajaxDestinationRequest.readyState && responseText && '' != responseText && matches) {
            //hide calendars
            var arrivingMatchesFAB, departingMatchesFAB, arrivingMatches, departingMatches;
            if (arrivingMatchesFAB = document.getElementById('ArrivingMatchesFAB')) {
                arrivingMatchesFAB.style.display = 'none';
            }
            if (departingMatchesFAB = document.getElementById('DepartingMatchesFAB')) {
                departingMatchesFAB.style.display = 'none';
            }
            if (arrivingMatches = document.getElementById('ArrivingMatches')) {
                arrivingMatches.style.display = 'none';
            }
            if (departingMatches = document.getElementById('DepartingMatchesFAB')) {
                departingMatches.style.display = 'none';
            }

            matches.style.display = 'block';
            matches.innerHTML = ajaxDestinationRequest.responseText;
        }
    }

    var destination = document.getElementById('Destination');
    if (destination) {
        var url = '/populateDestinations.php?q=' + escape(destination.value) + '&selectedItem=0';
        if (window.overridePath != undefined && '' != overridePath)
            url = overridePath + 'populateDestinations.php?q=' + escape(destination.value) + '&selectedItem=0';

        ajaxDestinationRequest.open('GET', url, true);
        ajaxDestinationRequest.send(null);
    }

    return false;
}

function initDestinationAjax(){
    //function to create and return a XMPHTTP object
    var ajaxDestinationRequest;
    ajaxDestinationRequest = false;
    try {
        // create Opera 8.0+/Firefox/Safari XMPHTTP object
        ajaxDestinationRequest = new XMLHttpRequest();
        return ajaxDestinationRequest;
    }
    catch (e) {
        // try creating IE object if above fails
        try {
            ajaxDestinationRequest = new ActiveXObject("Msxml2.XMLHTTP");
            return ajaxDestinationRequest;
        }
        catch (e) {

            try {
                ajaxDestinationRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                //browser doesn't support ajax
                return false;
            }
        }
    }
    return;
}

function setDestinationAjax(val)
{
	while( val.indexOf( "==" ) != -1 )
		val = val.replace("==", "'");

	while( val.indexOf( "%%" ) != -1 )
		val = val.replace("%%", '"');

	document.getElementById("DestinationMatches").style.display = "none";
	document.getElementById("Destination").value = val;

	$("#Destination").focus();
	return false;
}


/* BOOKING / ENTER DETAILS REDIRECTION */
function CheckChosenCardType(){
}

function TermsWindow(url){
    SmallWin = window.open(url, "Terms", "scrollbars,resizable,height=420,width=600");
    if (window.focus) {
        SmallWin.focus();
    }
    if (SmallWin.opener == null) {
        SmallWin.opener = window;
    }
}

function ToggleTerms(id){
    if (id == 1) {
        if (document.theForm.TermsAndConditions1.checked == true) {
            document.theForm.TermsAndConditions2.checked = true;
        }
        else {
            document.theForm.TermsAndConditions2.checked = false;
        }
    }
    else
        if (id == 2) {
            if (document.theForm.TermsAndConditions2.checked == true) {
                document.theForm.TermsAndConditions1.checked = true;
            }
            else {
                document.theForm.TermsAndConditions1.checked = false;
            }
        }
}

function togglePayPal(){
    switchDivs('paybypaypal', 'paybycard');
    document.getElementById('PayPal').value = (document.getElementById('PayPal').value == '1') ? '0' : '1';
    return false;
}

function checkEnterDetails(){
	var oNat = document.getElementById('Nationality');
	var paypal = document.getElementById('PayPal').value == '1' ? 1 : 0;

	var d = new Date();
	var curr_month = d.getMonth();
	var curr_year = d.getFullYear();
	if (document.theForm.CCExpYear.value < curr_year) {
		alert("Please enter a credit card expiry date in the future.");
		return false;
	}
	if (document.theForm.CCExpYear.value == curr_year && document.theForm.CCExpMonth.value < curr_month) {
		alert("Please enter a credit carde expiry date in the future.");
		return false;
	}

	if (document.theForm.FirstName.value == "" || document.theForm.LastName.value == "") {
		alert("We need your full name to confirm the booking.");
		return false;
	}

	if (document.theForm.EmailAddress.value == "") {
		alert("Please enter your email address. We need it to send you the booking confirmation.");
		return false;
        }

	if (document.theForm.EmailAddress.value.toLowerCase() != document.theForm.ConfirmEmailAddress.value.toLowerCase()) {
		alert("Please ensure that you have confirmed your email address properly.");
		return false;

	}

	if (document.theForm.PhoneNumber.value == "") {
		alert("Please enter your phone number.");
		return false;
	}

	if (oNat.value == "") {
		alert("Please select your nationality.");
		return false;
	}

	if (!paypal && document.theForm.CCNumber.value == "") {
		alert("Please enter a valid Credit Card Number.");
		return false;
	}

	if (!paypal && document.theForm.CCName.value == "") {
		alert("Please enter the name as it appears on the credit card.");
		return false;
	}

	if (document.theForm.TermsAndConditions1.checked == false && document.theForm.TermsAndConditions2.checked == false) {
		alert("Please click the box to show you accept the terms and conditions.\nYou must accept the terms and conditions for us to confirm your booking.");
		return false;
	}

	window.scrollTo(0, 0);
	document.getElementById('submitBtnCC').onclick = '';
	document.getElementById('submitBtnPP').onclick = '';

	return true;
}

function ToggleDiv(Id, State){
    div = document.getElementById(Id);
    if (div) {
        div.style.display = State;
    }
}

function registerBillingCurrency(currency){
    var rand = Math.random();
    //document.images.currencyImage.src = "/getbillcurrency_img.php?BillingCurrency="+currency+"&r="+rand;
    document.getElementById('Currency').value = currency;
}

function ToggleCurrency(Id){
    registerBillingCurrency(Id);
    if (Id == "USD") {
        document.getElementById("STG_link").className = "CURR_linkOff";
        document.getElementById("USD_link").className = "CURR_linkOn";
        document.getElementById("EUR_link").className = "CURR_linkOff";
        ToggleDiv("USDBillTotal2", "inline");
        ToggleDiv("EURBillTotal2", "none");
        ToggleDiv("STGBillTotal2", "none");
        ToggleDiv("USDBillTotal2_pp", "inline");
        ToggleDiv("EURBillTotal2_pp", "none");
        ToggleDiv("STGBillTotal2_pp", "none");
        ToggleDiv("USDBookingFeeDisplay", "inline");
        ToggleDiv("STGBookingFeeDisplay", "none");
        ToggleDiv("EURBookingFeeDisplay", "none");
        ToggleDiv("USDBillTotalDisplay", "inline");
        ToggleDiv("STGBillTotalDisplay", "none");
        ToggleDiv("EURBillTotalDisplay", "none");
        ToggleDiv("USDDepositBillDisplay", "inline");
        ToggleDiv("STGDepositBillDisplay", "none");
        ToggleDiv("EURDepositBillDisplay", "none");
        ToggleDiv("USDBalanceDisplay", "inline");
        ToggleDiv("EURBalanceDisplay", "none");
        ToggleDiv("GBPBalanceDisplay", "none");
    }
    if (Id == "GBP") {
        document.getElementById("STG_link").className = "CURR_linkOn";
        document.getElementById("USD_link").className = "CURR_linkOff";
        document.getElementById("EUR_link").className = "CURR_linkOff";
        ToggleDiv("USDBillTotal2", "none");
        ToggleDiv("EURBillTotal2", "none");
        ToggleDiv("STGBillTotal2", "inline");
        ToggleDiv("USDBillTotal2_pp", "none");
        ToggleDiv("EURBillTotal2_pp", "none");
        ToggleDiv("STGBillTotal2_pp", "inline");
        ToggleDiv("STGBookingFeeDisplay", "inline");
        ToggleDiv("USDBookingFeeDisplay", "none");
        ToggleDiv("EURBookingFeeDisplay", "none");
        ToggleDiv("STGBillTotalDisplay", "inline");
        ToggleDiv("EURBillTotalDisplay", "none");
        ToggleDiv("USDBillTotalDisplay", "none");
        ToggleDiv("STGDepositBillDisplay", "inline");
        ToggleDiv("USDDepositBillDisplay", "none");
        ToggleDiv("EURDepositBillDisplay", "none");
        ToggleDiv("GBPBalanceDisplay", "inline");
        ToggleDiv("EURBalanceDisplay", "none");
        ToggleDiv("USDBalanceDisplay", "none");
    }
    if (Id == "EUR") {
        document.getElementById("STG_link").className = "CURR_linkOff";
        document.getElementById("USD_link").className = "CURR_linkOff";
        document.getElementById("EUR_link").className = "CURR_linkOn";
        ToggleDiv("USDBillTotal2", "none");
        ToggleDiv("EURBillTotal2", "inline");
        ToggleDiv("STGBillTotal2", "none");
        ToggleDiv("USDBillTotal2_pp", "none");
        ToggleDiv("EURBillTotal2_pp", "inline");
        ToggleDiv("STGBillTotal2_pp", "none");
        ToggleDiv("EURBookingFeeDisplay", "inline");
        ToggleDiv("STGBookingFeeDisplay", "none");
        ToggleDiv("USDBookingFeeDisplay", "none");
        ToggleDiv("EURBillTotalDisplay", "inline");
        ToggleDiv("STGBillTotalDisplay", "none");
        ToggleDiv("USDBillTotalDisplay", "none");
        ToggleDiv("EURDepositBillDisplay", "inline");
        ToggleDiv("STGDepositBillDisplay", "none");
        ToggleDiv("USDDepositBillDisplay", "none");
        ToggleDiv("EURBalanceDisplay", "inline");
        ToggleDiv("GBPBalanceDisplay", "none");
        ToggleDiv("USDBalanceDisplay", "none");
    }
    calcTotals();
}

function calcTotals(){
    updateDiv("USDBookingFeeDisplay", "$" + currFormat(USDBookingFee));
    updateDiv("STGBookingFeeDisplay", "&pound;" + currFormat(STGBookingFee));
    updateDiv("EURBookingFeeDisplay", "&euro;" + currFormat(EURBookingFee));
    updateDiv("USDBillTotal2", "$" + currFormat(USDTotal));
    updateDiv("USDBillTotal2_pp", "$" + currFormat(USDTotal));
    updateDiv("USDBillTotalDisplay", "$" + currFormat(USDTotal));
    updateDiv("STGBillTotal2", "&pound;" + currFormat(STGTotal));
    updateDiv("STGBillTotal2_pp", "&pound;" + currFormat(STGTotal));
    updateDiv("STGBillTotalDisplay", "&pound;" + currFormat(STGTotal));
    updateDiv("EURBillTotal2", "&euro;" + currFormat(EURTotal));
    updateDiv("EURBillTotal2_pp", "&euro;" + currFormat(EURTotal));
    updateDiv("EURBillTotalDisplay", "&euro;" + currFormat(EURTotal));
    if (document.getElementById("TotAmtEUR")) {
        document.getElementById("TotAmtEUR").value = EURTotal;
        document.getElementById("TotAmtUSD").value = USDTotal;
        document.getElementById("TotAmtGBP").value = STGTotal;
    }
}

function updateDiv(divId, html){
    var e = document.getElementById(divId);
    if (e) {
        e.innerHTML = html;
    } else {
        alert("Can\'t set value for: " + divId);
    }
}

function checkAvailabilityForm(){
    if (beds == 0) {
        alert("You must select which rooms you would like to book.");
	return false;
    }

    return true;
}


/* BASIC MICROSITE */
function swapDiv(Id){
    div = document.getElementById(Id);
    if (div.style) {
        if (div.style.display == 'block') {
            dontDisplayDiv(Id);
            document.images['enquiryButton'].src = '/images/enquiry_button1.png';
        }
        else
            if (div.style.display == 'none') {
                displayDiv(Id);
                document.images['enquiryButton'].src = '/images/close_form.png';
            }
    }
    else {
        if (div.display == 'block') {
            dontDisplayDiv(Id);
            document.images['enquiryButton'].src = '/images/enquiry_button1.png';
        }
        else
            if (div.display == 'none') {
                displayDiv(Id);
                document.images['enquiryButton'].src = '/images/close_form.png';
            }
    }
}


/* MICROSITE PHOTO/VIDEO TABS */
function photoVideoSwitch( showVideo )
{
	if( showVideo )
	{
		jQuery('.photosVideoDiv #videos').css( "display", "block" );
		jQuery('.photosVideoDiv #photos').css( "display", "none" );
		jQuery('.propInfoContainer .otherInfo').css( "width", "336px" );
		jQuery('.propInfoContainer .otherInfo .photosVideoDiv').css( "width", "336px" );
		jQuery('#hideVideoPanel').removeClass( 'mediaTabsOn' );
		jQuery('#hideVideoPanel').addClass( 'mediaTabsOff' );
		jQuery('#showVideoPanel').removeClass( 'mediaTabsOff' );
		jQuery('#showVideoPanel').addClass( 'mediaTabsOn' );
	}
	else
	{
		jQuery('.photosVideoDiv #videos').css( "display", "none" );
		jQuery('.photosVideoDiv #photos').css( "display", "block" );
		jQuery('.propInfoContainer .otherInfo').css( "width", "" );
		jQuery('.propInfoContainer .otherInfo .photosVideoDiv').css( "width", "" );
		jQuery('#hideVideoPanel').removeClass( 'mediaTabsOff' );
		jQuery('#hideVideoPanel').addClass( 'mediaTabsOn' );
		jQuery('#showVideoPanel').removeClass( 'mediaTabsOn' );
		jQuery('#showVideoPanel').addClass( 'mediaTabsOff' );
	}
}

function switchDivs(divOne, divTwo){
    changeDiv(divOne);
    changeDiv(divTwo);
}

function changeDiv(Id){
    div = document.getElementById(Id);
    if (div) {
        if (div.style) {
            if (div.style.display == 'block') {
                dontDisplayDiv(Id);
            }
            else
                if (div.style.display == 'none') {
                    displayDiv(Id);
                }
        }
        else {
            if (div.display == 'block') {
                dontDisplayDiv(Id);
            }
            else
                if (div.display == 'none') {
                    displayDiv(Id);
                }
        }
    }
}

function displayDiv(Id){
    div = document.getElementById(Id);
    if (div) {
        if (div.style) {
            div.style.display = 'block';
        }
        else {
            div.display = 'block';
        }
    }
}

function dontDisplayDiv(Id){
    div = document.getElementById(Id);
    if (div) {
        if (div.style) {
            div.style.display = 'none';
        }
        else {
            div.display = 'none';
        }
    }
}


/* FAB MAP WIDGET */
var fabMapVisible = 0;
function ShowFabMap(){
    if (fabMapLat != "" && fabMapLng != "") {
        if (fabMapVisible == 0) {
			document.getElementById('contentcontainer').style.backgroundImage = "url(../../images/new/content_back_map.png)";
            displayDiv("FabMap");
            addFabMap("FabMap", "latID", "lngID", fabMapLat, fabMapLng, 14, '');
            document.getElementById('OpenMapButton').src = "/images/new/hidemap.png";
            fabMapVisible = 1;
        } else {
            document.getElementById('OpenMapButton').src = "/images/new/openmap.png";
            dontDisplayDiv("FabMap");
            fabMapVisible = 0;
        }
    }
}


/* FAB BOOKING TABLE */
var beds = 0;

function setTotals(){

	if( typeof( Selects ) == "undefined" )
		return;

    var warn = menu = menuNum = val = displayed = displayedExplained = "";
    var showChosen = price = displayedBeds = beds = 0;
    var warnImg = "<img src='/images/note_icon.gif' align='left' valign='bottom' width='13' height='13' border='0' alt='Warning!' /> &nbsp; ";

    //reset Private Warnings
    for (i = 2; i <= 5; i++) {
        document.getElementById('PrivateWarning_' + i).value = '0';
    }

    for (var i = 0; i < Selects.length; i++) {
        menu = document.getElementById(Selects[i]);
		if( menu == undefined )
			continue;
		if( menu.selectedIndex == -1 )
			menu.selectedIndex = 0;
		
        menuNum = parseInt(Selects[i].replace(/Rooms/, ''));
        val = parseInt(menu.options[menu.selectedIndex].value);
        displayed = parseInt(menu.options[menu.selectedIndex].text);
        displayedExplained = "";
        if (displayed != val) {
            if (Warnings[i].length && warn.indexOf(Warnings[i]) == -1) {
                warn += "<p>" + warnImg + Warnings[i] + "</p>";
            }
            displayedExplained += '<span id="Availability_MoreGuestsExplained" title="' + Warnings[i] + '">(' + val + ')</span>';
            // Set Private Warnings
            if (document.getElementById('PrivateWarning_' + val)) {
                document.getElementById('PrivateWarning_' + val).value = Warnings[i];
            }
        }
        beds += val;
        displayedBeds += displayed;
        price += val * Prices[i];
        if (val > 0) {
            document.getElementById('ChosenNum' + menuNum).innerHTML = Math.ceil(val / Beds[i]);
            document.getElementById('ChosenPrice' + menuNum).innerHTML = currFormat(val * Prices[i]);
            document.getElementById('Chosen' + menuNum).style.display = '';
            showChosen = 1;
        }
        else {
            document.getElementById('Chosen' + menuNum).style.display = 'none';
        }
    }
    if (warn.length) {
//        document.getElementById('privateMessage').innerHTML = warn;
//        document.getElementById('privateMessage').style.display = '';
    }
    else {
//        document.getElementById('privateMessage').innerHTML = '';
//        document.getElementById('privateMessage').style.display = 'none'
    }
    if (showChosen) {
        document.getElementById('ChosenHead').style.display = '';
        document.getElementById('ChosenTotal').style.display = '';
    }
    else {
        document.getElementById('ChosenHead').style.display = 'none';
        document.getElementById('ChosenTotal').style.display = 'none';
    }
    var deposit = price / 10;
    document.getElementById('PayNow').innerHTML = symbol +" "+ currFormat(deposit)
    document.getElementById('PayNowTotal').innerHTML = symbol +" "+ currFormat(price);
    var GroupBookingBlock = document.getElementById('Availability_GroupBookingBlock');
    var PayNowBlock = document.getElementById('Availability_PayNowBlock');
    var NoGroupBlock = document.getElementById('Availability_NoGroupBlock');
    var PayNowButton = document.getElementById('Availability_SubmitButton_Holder');
    if (beds > GroupBookingPax) {
        //GroupBookingBlock.style.display = 'block';
        PayNowBlock.style.display = 'none';
        NoGroupBlock.style.display = 'block';
        //PayNowButton.style.display = 'none';
    }
    else {
        //GroupBookingBlock.style.display = 'none';
        PayNowBlock.style.display = 'block';
        NoGroupBlock.style.display = 'none';
        //PayNowButton.style.display = 'block';
    }
}

function currFormat(amount){
    amount -= 0;
    amount = (amount == Math.floor(amount)) ? amount + '.00' : ((amount * 10 == Math.floor(amount * 10)) ? amount + '0' : amount);
    amount = amount.toString();
    bits = amount.split('.');
    return bits[0] + '.' + bits[1].substring(0, 2);
}



/* FAB REFINEMENT PANEL */
function ShowDynamicDates(){
    if (jQuery('#DatesStatic').length && $('#DatesDynamic').length) {
        jQuery('#DatesStatic').attr('style', 'display:none');
        jQuery('#DatesDynamic').attr('style', 'display:block');
    }
}

function doRefineCurrency(newCurr){
	document.getElementById('dosearchFAB').value = 0;
	document.getElementById('fabRefineAction').value = "changeCurrency";
	document.getElementById('fabRefineForm').submit();
}

function doRefineSort(newSort){
	document.getElementById('fabRefineForm').submit();
}

/* SLIDESHOW */
var SlideShowStatus = "stopped";
var SlideShowTimer = 0;
var SlideShowCurrent = 1;
function SlideShowNext() {
	if (SlideShowCurrent < SlideCount)
	{
		jQuery('#SlideShowTag'+SlideShowCurrent).hide();
		SlideShowCurrent++;
		jQuery('#SlideShowTag'+SlideShowCurrent).show();
	}
	else
	{
		jQuery('#SlideShowTag'+SlideShowCurrent).hide();
		SlideShowCurrent = 1;
		jQuery('#SlideShowTag'+SlideShowCurrent).show();
	}
}

function SlideShowStop() {
	clearInterval(SlideShowTimer);

	if (jQuery('#SlideShowControl').length) {
		jQuery('#SlideShowControl').attr('src', '/images/play.gif');
		jQuery('#SlideShowControl').attr('alt', 'Play Images');
	}

	SlideShowStatus = "stopped";
}

function SlideShowControl() {
	if (SlideShowStatus == "running") {
		clearInterval(SlideShowTimer);

		if (jQuery('#SlideShowControl').length) {
			jQuery('#SlideShowControl').attr('src', '/images/play.gif');
			jQuery('#SlideShowControl').attr('alt', 'Play Images');
		}

		SlideShowStatus = "stopped";
	}
	else
	{
		if (SlideShowStatus == "stopped") {
			if (jQuery('#SlideShowControl').length) {
				jQuery('#SlideShowControl').attr('src', '/images/pause.gif');
				jQuery('#SlideShowControl').attr('alt', 'Pause Images');
			}

			SlideShowStatus = "running";
			SlideShowTimer = setInterval("SlideShowNext()", 3000);
		}
	}
}

function SlideShowPrev() {
	if (SlideShowCurrent > 1)
	{
		jQuery('#SlideShowTag'+SlideShowCurrent).hide();
		SlideShowCurrent--;
		jQuery('#SlideShowTag'+SlideShowCurrent).show();
	}
	else
	{
		jQuery('#SlideShowTag'+SlideShowCurrent).hide();
		SlideShowCurrent = SlideCount;
		jQuery('#SlideShowTag'+SlideShowCurrent).show();
	}
}


