/// <reference path="jquery-1.3.1-vsdoc.js" />
//Tracking
function reservationTracking(propertyId) {
	var source = getfromurl("source");
	var referer = document.referrer;
	var propertyId;
	$.ajax({
		type: "POST",
		url: "/common/modules/roccoforte/roccobe/roccobe_gui/handler/ReservationTracking.ashx",
		data: "source=" + source + "&referer=" + escape(referer) + "&property_id=" + propertyId,
		success: function(response) {
		}
	});
}

function getValueFromQuerystring(value) {
	var querystrings = window.location.search.substring(1);
	var join = querystrings.split("&");
	for (i = 0; i < join.length; i++) {
		var each = join[i].split("=");
		if (each[0] == value) {
			return each[1];
		}
	}
}

function getfromurl(value) {
	var url = '' + this.location;
	var from = url.indexOf(value)
	if (from == -1) {
		return 'none';
	}
	else {
		var value = url.substring(from);
		value = value.substring(value.indexOf('=') + 1);
		value = value.substr(0, 4);
		return value;
	}
}

//Validate purpose (type of visitor)
//at the time of writting (there are only two 1. leisure, 2. business)
function validatePurposes() {
	var purposeToStayId = $("#PurposeToStayIdHiddenField").val();
	var bookCheckInDayDropDownListId = $("#BookCheckInDayDropDownListIdHiddenField").val();
	var bookCheckOutDayDropDownListId = $("#BookCheckOutDayDropDownListIdHiddenField").val();
	var bookCheckInMonthDropDownListId = $("#BookCheckInMonthDropDownListIdHiddenField").val();
	var bookCheckOutMonthDropDownListId = $("#BookCheckOutMonthDropDownListIdHiddenField").val();
	var numberOfGuestsDropDownListId = $("#NumberOfGuestsDropDownListIdHiddenField").val();
	var numberOfRoomsDropDownListId = $("#NumberOfRoomsDropDownListIdHiddenField").val();
	var errorMessageForVisitorType = $("#ValidateTypeHiddenLabel").html();
	var errorMessageForDateTime = $("#ValidateTodayDateHiddenLabel").html();
	var flashTitle = $("#FlashTitleHiddenField").val();
	var currentPropertyUrl = $("#CurrentPropertyURL").val();
	var purposeOfStay;
	var curentProperty = getValueFromQuerystring("property");
	purposeOfStay = $("#VisitorTypeDropDownList").val();
	if (purposeOfStay == "-1") {
		alert(errorMessageForVisitorType);
		return false;
	}
	else {
		//Get selected date from dropdownlist
		var selectedDate = $("#" + bookCheckInDayDropDownListId).val();
		var selectedMonth = $("#" + bookCheckInMonthDropDownListId).val();
		var checkOutDay = $("#" + bookCheckOutDayDropDownListId).val();
		var checkOutMonth = $("#" + bookCheckOutMonthDropDownListId).val();
		var numberOfGuests = $("#" + numberOfGuestsDropDownListId).val();
		var numberOfRooms = $("#" + numberOfRoomsDropDownListId).val();

		//Split the values
		var temp = new Array();
		temp = selectedMonth.split("-");
		var out_temp = new Array();
		out_temp = checkOutMonth.split("-");

		//Create new date objects
		var checkInDate = new Date();
		var checkOutDate = new Date();
		var todayDate = new Date();
		var maxDate = new Date();

		//Set selected values
		checkInDate.setFullYear(temp[1], temp[0] - 1, selectedDate);
		//set check out date
		checkOutDate.setFullYear(out_temp[1], out_temp[0] - 1, checkOutDay);
		//Get today date
		todayDate.setFullYear(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate());
		//check that its less than 7 days
		if (curentProperty != null && curentProperty != undefined && curentProperty == "verdura") {
			maxDate.setFullYear(temp[1], temp[0] - 1, (parseInt(selectedDate) + 90));
		}
		else {
			maxDate.setFullYear(temp[1], temp[0] - 1, (parseInt(selectedDate) + 7));
		}

		if (checkInDate < todayDate) {
			alert(errorMessageForDateTime);
			return false;
		}
		else {
			if (checkOutDate > maxDate || numberOfGuests == "2+" || numberOfRooms == "3+") {
				window.location.href = "http://" + currentPropertyUrl + "/special/booking-enquiries";
				return false;
			}
			else {
				var flashLoader = "<object width=\"282\" height=\"145\" id=\"roccoforte_reservation_loader\" data=\"" + flashTitle + "\" type=\"application/x-shockwave-flash\">" +
								  "<param name=\"wmode\" value=\"transparent\">" +
								  "<param name=\"movie\" value=\"" + flashTitle + "\" />" +
								  "</object>";
				var fieldset = $("#roccobe").children("fieldset");
				if ($(fieldset).is(":visible") == true) {
					$("#roccobe").children("fieldset").fadeOut("slow", function() {
						$("#roccobe_flashloader").html(flashLoader);
					});
				} else {
					$("#roccobe_flashloader").html("<div></div>");
					setTimeout(function() { $("#roccobe_flashloader").html(flashLoader); }, 1000);
				}
				return true;
			}
		}
	}
}

function assignValueFromQuerystring(propertyName, language, checkInDay, checkInMonth, checkOutDay, checkOutMonth, numberOfGuests, numberOfRooms, visitorType, iPackage, sender, packageCode) {
	try {
		if (checkInMonth.indexOf(".") > -1) {
			checkInMonth = checkInMonth.replace(".", "-");
			checkOutMonth = checkOutMonth.replace(".", "-");
			if (checkInMonth.substring(0, 1) == "0") {
				checkInMonth = checkInMonth.substring(1, checkInMonth.length);
			}
			if (checkOutMonth.substring(0, 1) == "0") {
				checkOutMonth = checkOutMonth.substring(1, checkOutMonth.length);
			}
		}
		if (checkInMonth.indexOf("/") > -1) {
			checkInMonth = checkInMonth.replace("/", "-");
			checkOutMonth = checkOutMonth.replace("/", "-");
			if (checkInMonth.substring(0, 1) == "0") {
				checkInMonth = checkInMonth.substring(1, checkInMonth.length);
			}
			if (checkOutMonth.substring(0, 1) == "0") {
				checkOutMonth = checkOutMonth.substring(1, checkOutMonth.length);
			}
		}
		$("#VisitorTypeDropDownList").val(visitorType);
		$("#" + $("#BookCheckInDayDropDownListIdHiddenField").val()).val(checkInDay);
		$("#" + $("#BookCheckOutDayDropDownListIdHiddenField").val()).val(checkOutDay);
		$("#" + $("#BookCheckInMonthDropDownListIdHiddenField").val()).val(checkInMonth);
		$("#" + $("#BookCheckOutMonthDropDownListIdHiddenField").val()).val(checkOutMonth);
		$("#" + $("#NumberOfGuestsDropDownListIdHiddenField").val()).val(numberOfGuests);
		$("#" + $("#NumberOfRoomsDropDownListIdHiddenField").val()).val(numberOfRooms);
		$("#" + $("#PackageCodeIdHiddenField").val()).val(packageCode);
		$("#roccobe").children("fieldset").css("display", "none");
		$("#GoToStageTwoLinkButton").click();
		WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GoToStageTwoLinkButton", "", false, "", "Default.aspx?property=" + propertyName + "&language=" + language + "&stage=2", false, true))
	} catch (e) { }
}

//Show/hide details button(s) on stage 2 and 3
function showHideDetails(targetControlId, toggleControlId) {
	if (document.getElementById(targetControlId) && document.getElementById(toggleControlId)) {
		var speed = 250;
		var targetControl = document.getElementById(targetControlId);
		var toggleControl = document.getElementById(toggleControlId);
		if ($("#" + targetControlId).hasClass("active") == true) {
			$("#" + targetControlId).slideUp(speed);
			$("#" + toggleControlId).html($("#ShowDetailsLabel").html());
			$("#" + targetControlId).removeClass("active");
		}
		else {
			$("#" + targetControlId).slideDown(speed);
			$("#" + toggleControlId).html($("#HideDetailsLabel").html());
			$("#" + targetControlId).addClass("active");
		}
	}
}

function fixLinks() {
	var text = document.getElementById('corporaterepeatercontainer');
}

//validate the form on stage 4 
function validateGuestInfo() {
	var sTitle = document.getElementById('TitleDropDownList')[document.getElementById('TitleDropDownList').selectedIndex].value;
	var sfname = document.getElementById('FirstnameTextBox').value;
	var ssname = document.getElementById('SurnameTextBox').value;
	var saddress1 = document.getElementById('Address1TextBox').value;
	var saddress2 = document.getElementById('Address2TextBox').value;
	var spcode = document.getElementById('PostCodeTextBox').value;
	var scity = document.getElementById('CityTextBox').value;
	var scountry = document.getElementById('CountryDropDownList')[document.getElementById('CountryDropDownList').selectedIndex].value;
	var stel = document.getElementById('TelTextBox').value;
	var semail = document.getElementById('EmailTextBox').value;
	var screditno = document.getElementById('CreditCardNumberTextBox').value;
	var snameoncard = document.getElementById('NameOnCardTextBox').value;
	var sCardType = document.getElementById('CardTypeDropDownList').value;
	var scc_Exp_M = document.getElementById('CardExpiryMonthDropDownList').value;
	var scc_Exp_Y = document.getElementById('CardExpiryYearDropDownList').value;
	//Get the error messages from hidden fields
	var firstnameErrorMessage = document.getElementById("ValidateFirstnameHiddenLabel");
	var lastnameErrorMessage = document.getElementById("ValidateLastnameHiddenLabel");
	var emailErrorMessage = document.getElementById("ValidateEmailHiddenLabel");
	var telephoneErrorMessage = document.getElementById("ValidateTelephoneHiddenLabel");
	var address1ErrorMessage = document.getElementById("ValidateAddress1HiddenLabel");
	var postcodeErrorMessage = document.getElementById("ValidatePostCodeHiddenLabel");
	var cityErrorMessage = document.getElementById("ValidateCityHiddenLabel");
	var countryErrorMessage = document.getElementById("ValidateCountryHiddenLabel");
	var nameOnCardErrorMessage = document.getElementById("ValidateNameOnCardHiddenLabel");
	var cardNumberErrorMessage = document.getElementById("ValidateCardNumberHiddenLabel");
	var expiryMonthErrorMessage = document.getElementById("ValidateExpiryMonthHiddenLabel");
	var expiryYearErrorMessage = document.getElementById("ValidateExpiryYearHiddenLabel");
	var termsErrorMessage = document.getElementById("ValidateTermsHiddenLabel");
	var nonRomanCharactersMessage = document.getElementById("ValidateRomanCharactersHiddenLabel");

	if (sfname == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(firstnameErrorMessage.innerHTML);
		return false;
	}
	if (ssname == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(lastnameErrorMessage.innerHTML);
		return false;
	}
	if (saddress1 == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(address1ErrorMessage.innerHTML);
		return false;
	}
	if (spcode == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(postcodeErrorMessage.innerHTML);
		return false;
	}
	if (scity == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(cityErrorMessage.innerHTML);
		return false;
	}
	//Validate email address
	var regularExpression = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	if (!regularExpression.test(semail)) {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(emailErrorMessage.innerHTML);
		return false;
	}
	else {
		//Validate working email
		var result = true;
		$.ajax({
			type: "POST",
			async: false,
			url: "/common/modules/roccoforte/handler/ValidateEmail.ashx",
			data: "email=" + semail,
			success: function(response) {
				if (response == "false") {
					result = false;
				}
			}
		});
		if (result == false) {
			alert(emailErrorMessage.innerHTML);
			return false;
		}
	}

	if (scountry == '0') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(countryErrorMessage.innerHTML);
		return false;
	}
	if (document.getElementById('IAgreeTermsCheckBox').checked == false) {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(termsErrorMessage.innerHTML);
		return false;
	}
	//invalid number
	if (screditno == '' || screditno == '5496317567819477') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(cardNumberErrorMessage.innerHTML);
		return false;
	}

	var credit_length = (screditno.length);
	var credit_checker = 0;
	var the_char;
	var reverse_counter = 0;
	var char_counter = 0;
	for (var iDx = credit_length; iDx > 0; iDx--) {
		char_counter = iDx - 1;
		the_char = parseInt(screditno.charAt((char_counter)));
		reverse_counter += 1;

		if ((reverse_counter % 2) != 0) {
			credit_checker += the_char
		}
		else {
			the_char = the_char * 2;
			if (the_char > 9) {
				temp_value = parseInt(the_char / 10) + (the_char % 10);
				the_char = temp_value;
				credit_checker += the_char;
			}
			else {
				credit_checker += the_char
			}
		}
	}
	if ((credit_checker % 10) != 0) {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(cardNumberErrorMessage.innerHTML);
		return false;
	}
	if (snameoncard == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(nameOnCardErrorMessage.innerHTML);
		return false;
	}
	if (scc_Exp_M == '-1') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(expiryMonthErrorMessage.innerHTML);
		return false;
	}
	if (scc_Exp_Y == '-1') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(expiryYearErrorMessage.innerHTML);
		return false;
	}
	if (scc_Exp_M != '-1' && scc_Exp_Y != '-1') {
		var todayDate = new Date();
		todayDate.setFullYear(todayDate.getFullYear(), todayDate.getMonth(), 1);
		var selectedDate = new Date();
		selectedDate.setFullYear("20" + scc_Exp_Y, scc_Exp_M - 1, 1);
		if (selectedDate < todayDate) {
			alert(expiryYearErrorMessage.innerHTML);
			return false;
		}
	}
	if (stel == '') {
		document.getElementById('GoToStageFiveLinkButton').disabled = false;
		alert(telephoneErrorMessage.innerHTML);
		return false;
	}

	//Validate roman characters
	var matchString = new RegExp("[^\x00-\x80]+");
	if (sTitle.match(matchString)
	|| sfname.match(matchString)
	|| ssname.match(matchString)
	|| saddress1.match(matchString)
	|| saddress2.match(matchString)
	|| spcode.match(matchString)
	|| scity.match(matchString)
	|| scountry.match(matchString)
	|| stel.match(matchString)
	|| semail.match(matchString)) {
		alert(nonRomanCharactersMessage.innerHTML);
		return false;
	}
	return true;
}

/*
Represents a function that changed the get the value
from the value hiddenfield id and put it in the
selected value hiddenfield (to allow .net to pickup on the next stage)
*/
function checkPreferenceValue(checkboxId, valueHiddenFieldId, selectedValueHiddenFieldId) {
	var checkbox = document.getElementById(checkboxId);
	var selectedHiddenField = document.getElementById(selectedValueHiddenFieldId);
	var value;
	if (checkbox.checked == true) {
		value = document.getElementById(valueHiddenFieldId).value;
		selectedHiddenField.value = value;
	}
	else {
		selectedHiddenField.value = "";
	}
}


//Takes rate code and the id of submit button
//to wire up the rate code to the submit button's link
function stageTwoResortType(rateCodeReference, submitButtonId) {
	//Get property name and selected language
	var propertyName = $("#PropertyNameHiddenField").val();
	var selectedLanguage = $("#SelectedLangaugeHiddenField").val();
	$("#" + submitButtonId).attr("href", "/Default.aspx?property=" + propertyName + "&language=" + selectedLanguage + "&stage=3&ratecode=" + rateCodeReference + "&resort=true");
}

//Takes room code and the id of submit button
//to wire up the rate code to the submit button's link
function stageThreeResortType(roomCodeReference, submitButtonId) {
	//Get property name and selected language
	var propertyName = $("#PropertyNameHiddenField").val();
	var selectedLanguage = $("#SelectedLangaugeHiddenField").val();
	$("#" + submitButtonId).attr("href", "/Default.aspx?property=" + propertyName + "&language=" + selectedLanguage + "&stage=3a&roomcode=" + roomCodeReference + "&resort=true");
}

function cancelBooking(reservationNumber, propertyId, language, arrivalDate, departureDate, numberOfRooms, rateName, roomName, title, firstname, surname, email) {
	$.ajax({
		type: "POST",
		url: "/common/modules/roccoforte/roccobe/roccobe_gui/handler/CancellationHandler.ashx",
		data: "command=cancel_booking&reservation_number=" + reservationNumber + "&property_id= " + propertyId + "&language=" + language + "&arrival_date=" + arrivalDate + "&departure_date=" + departureDate + "&number_of_rooms=" + numberOfRooms + "&rate_name=" + rateName + "&room_name=" + roomName + "&title=" + title + "&firstname=" + firstname + "&surname=" + surname + "&email=" + email,
		success: function(response) {
			$("#canvas #image_container #content").fadeOut("slow", function() {
				$("#canvas #image_container #content").html(response).fadeIn("slow");
			});
			if ($("#roccobe").size() > 0) {
				$("#roccobe").fadeOut("slow", function() {
					$("#roccobe").html(response).fadeIn("slow");
				});
			}
			else if ($("#roccobe_cancellation_container").size() > 0) {
				$("#roccobe_cancellation_container").fadeOut("slow", function() {
					$("#roccobe_cancellation_container").html(response).fadeIn("slow");
				});
			}
			else if ($("#content").size() > 0) {
				$("#content").fadeOut("slow", function() {
					$("#content").html(response).fadeIn("slow");
				});
			}
		}
	});
}

function modifyReservation() {
	var reservationNumber = $.trim($("#reservation").val());
	var surname = $.trim($("#surname").val());
	if (reservationNumber == "") {
		alert("Please enter your reservation number.");
	}
	else if (surname == "") {
		alert("Please enter your surname.");
	}
	else {
		$.ajax({
			type: "POST",
			url: "/common/modules/roccoforte/roccobe/roccobe_gui/handler/CancellationHandler.ashx",
			data: "command=get_details&reservation_number=" + reservationNumber + "&surname=" + surname,
			success: function(response) {
				$("#canvas #image_container #content").fadeOut("slow", function() {
					$("#canvas #image_container #content").html(response).fadeIn("slow");
				});
				$("#roccobe").fadeOut("slow", function() {
					$("#roccobe").html(response).fadeIn("slow");
				});
				if ($("#content").size() > 0) {
					$("#content").fadeOut("slow", function() {
						$("#content").html(response).fadeIn("slow");
					});
				}
			}
		});
	}
	return false;
}


//Shows popup and make an ajax call to populate the curently showing
//rates on the screen with the new currency
function popupCurrencyConverter(stage) {
	var fromCurrency = $("#CurrentCurrencyHiddenField").val();
	var toCurrency = $("#CurrencyDropDownList").val();
	var type = stage;
	if (toCurrency != "-1") {
		$("#roccobe_s" + stage + "_popup_rate").load("/common/modules/roccoforte/roccobe/roccobe_gui/Handler/CurrencyConverter.ashx?fromcurrency=" + fromCurrency + "&tocurrency=" + toCurrency + "&stage=" + stage, "GET", function() {
			$("#roccobe_s" + stage + "_overlay").show();
			$("#roccobe_s" + stage + "_currency_converter_popup").slideDown("slow");
			$(".roccobe_s" + stage + "_close_popup_hyperlink").click(function() {
				$("#roccobe_s" + stage + "_currency_converter_popup").slideUp("slow");
				$("#roccobe_s" + stage + "_overlay").hide();
			});
		});
	}
}

function cleanId(originalId, newId) {
	$("#" + originalId).attr("id", newId);
}

function createSlideShowEffect() {
	$(".roccobe_s3_slideshow_container").each(function() {
		slideshowEngine = new imageslideshowEngine();
		slideshowEngine.images = $(this).children("img").get();
		slideshowEngine.init(5000, 500);
	});
}

function validateLoginForm() {
	var username = $(".corporate_username_textbox").val();
	var password = $(".corporate_password_textbox").val();
	var errorMessageForUsername = $("#ErrorMessageForUsernameHiddenLabel").html();
	var errorMessageForPassword = $("#ErrorMessageForPasswordHiddenLabel").html();
	if (username == "") {
		alert(errorMessageForUsername);
		return false;
	}
	if (password == "") {
		alert(errorMessageForPassword);
		return false;
	}
	if (username != "" && password != "") {
		return true;
	}
}

function hideVisitorType() {
	$(".visitortype").hide();
}

function showPromotion() {
	$(".roocobe_promotion_container").fadeIn("fast");
	//Setup multiple promotions
	$(".roocobe_promotion_container .promotion_item").each(function(index) {
		if (index != 0) {
			$(this).css("display", "none");
		}
	});
	//Handle multiple promotions (not implemented yet)
}
function closePromotion() {
	$(".roocobe_promotion_container").fadeOut("fast");
	return false;
}

function conversion(propertyId, selectedRateCode, totalAmount, currentLanguage) {
	try {
		pageTracker._addTrans("'" + propertyId + "', '" + selectedRateCod + "', '" + totalAmount + "', '0', '0', '', '', '" + currentLanguage + "'");
		pageTracker._trackTrans();
	} catch (e) { }
}

function validateRomanCharacters(value) {
	var matchString = new RegExp("[a-zA-Z0-9]");
	if (value.value.match(matchString)) {
		return true;
	}
	else {
		return false;
	}
}

function adjustPromotedRatesLayout() {
	if ($("#promoted_rates_container").size() > 0) {
		$("#rates").attr("style", "margin-top:0px!important");
	}
}
