//This functuions hides or showes the eticket options in the form /bonus card or credit card)
//depending on whether the e-ticket option is checked
var installmentActive = false;
var supplementaryOptionsTotalPrice = 0;


function updateETicketOptions(checkedValue){

	if(document.getElementById("eTicketOptions")){

		if(checkedValue == 'eTicket'){
			$("eTicketOptions").show();
		}
		else{
			$("eTicketOptions").hide();
		}
	}

}

/**
 * Is used to request a discount to be applied to the price.
 * @param discountCodeId The id of the input form containing the discount code.
 * @param carrierCodes The carriers of the flights (if any) separated by "#" if more than 1. Can be empty if its a hotel.
 */
function getDiscountAmount(discountCodeId, destinationCity, carrierCodes, supplierCodes, currency) {
	var userAction = "getDiscountAmount";

	var discountCode = document.getElementById(discountCodeId).value;
	var updateMessage = "discountupdate.jsp?userAction=" + userAction + "&discountCode=" + discountCode + "&destinationCity=" + destinationCity + "&carrierCodes=" + carrierCodes + "&supplierCodes=" + supplierCodes + "&currency=" + currency;

	httpUpdate(updateMessage);	//sends the Discount request & executes the result

}

/**
 * Is used to update the discount amount and the price list.
 */
function updateDiscountAmount(discountAmount, isLCC) {
	var discountPriceSpan = document.getElementById("discountPriceSpan");
	discountPriceSpan.innerHTML = "-" + renderCurrency(discountAmount) + " "; //inserts the price and a space to separate the currency

	priceHandler.isLCC = isLCC;
	var discountPriceItem = priceHandler.getPricedItemByName("discount");
	discountPriceItem.setPrice(-discountAmount);
	priceHandler.updatePrices();

	hideId("discountCodeSpan");	//hides the discount code input field
	$('discounthead').hide();
}

/**
 * Is used to report a discount error to the customer and reset update the price list.
 */
function handleDiscountError(discountErrorMessage) {
	var discountPriceItem = priceHandler.getPricedItemByName("discount");
	discountPriceItem.setPrice(0);	//resets any previous discount to
	priceHandler.updatePrices();

	alert(discountErrorMessage);
}

/**
 * Is used to show expire date and CVC information and images of a credit card selected in a dropdown.
 * @param dropDown The select dropdown that contains the credit cards.
 */
function showCreditCard(dropDown, validationName, formName) {

    for (var dropDownIndex = 0; dropDownIndex < dropDown.length; dropDownIndex++) {
        var value = "";
		if (dropDown.options[dropDownIndex].value.indexOf("VI") > -1) {
			value = "VI";
		}
		else {
			value = dropDown.options[dropDownIndex].value;
		}
		
		hideId(document.getElementById("expireDate" + value));
		hideId(document.getElementById("cvc" + value));
	}
	var selectedValue = "";
	if (dropDown.options[dropDown.selectedIndex].value.indexOf("VI") > -1) {
		selectedValue = "VI";
	} else if(dropDown.options[dropDown.selectedIndex].value.indexOf("VE") > -1) {
		selectedValue = "VI";
	} else {
		selectedValue = dropDown.options[dropDown.selectedIndex].value;
	}



    //If we are using Aura credit card we don't want to check the cvc, but
	//for all other cards, therefore, unregister the cvc box for Aura,
	//but register for all other.
	if (validationName) {
		if (selectedValue.indexOf("AU") > -1) {
		    validationName.unreg($(formName).cvcCode);
		    if($('cvcImg') && $('cvcLabel') && $('cvcCode')) {
			$('cvcImg').hide();
			$('cvcLabel').hide();
			$('cvcCode').hide();
		    }
		} 
		else {
		    if($('cvcImg') && $('cvcLabel') && $('cvcCode')) {
			$('cvcImg').show();
			$('cvcLabel').show();
			$('cvcCode').show();
		    }
		    validationName.reg($(formName).cvcCode, valCVC, "", "cvcCodeBad", true);
		}
	}

	$(document.getElementById("expireDate" + selectedValue)).show();
	if (selectedValue.indexOf("AU") == -1) {
	    $(document.getElementById("cvc" + selectedValue)).show();
	}

    // installment check

    

    for (var dropDownIndex = 0; dropDownIndex < dropDown.length; dropDownIndex++) {
        if($('installment_' + dropDown.options[dropDownIndex].value)){
            $('installment_' + dropDown.options[dropDownIndex].value).hide();
        }
    }

    if($('cardType')){
        var selectedCard = $('cardType').value;
        if($('installment_' + selectedCard)){
            $('installment_' + selectedCard).show();
            if($('ins_' + selectedCard + '_1')){
                $('ins_' + selectedCard + '_1').checked = "checked";
                $('installmentInfo').hide();
                if($('avista_'+selectedCard)){
                    $('avista_'+selectedCard).innerHTML = renderCurrency(eval($('installmentfees').value) + eval(rawInstallmentTotal));
                }
            }
        }
    }
}


//-------------------------------------------------------------------------------

//This class is used for easy access to the ,localized name of the weekday
//and the name of the month of a date. It is initialized by passing
//in one array of monthnames and one array of weekdaynames
//months[0] = "January", months[1] = "February", etc...
//weekdays[0] = "Sunday", weekdays[1] = "Monday", etc...
function DayMonthHandler(months, weekdays){
	//attributes
	this.months = months;
	this.weekdays = weekdays;

	//metods
	this.dateToString = dml_dateToString
	this.dateToStringNoDay = dml_dateToStringNoDay
}

//This function takes a data as a parameter and returns a string repsresentation in the
//following form: Monday 11 April 2005
function dml_dateToString(myDate){
	var dateString = "";
	if(TSApp.settings.currentLanguage == 'LT'){
	   dateString += this.weekdays[myDate.getDay()] + " ";
       dateString += myDate.getFullYear() + " m. ";
       dateString += this.months[myDate.getMonth()] + " ";
       dateString += myDate.getDate() + " d."; 
	} else if(TSApp.settings.currentLanguage == 'FI' || TSApp.settings.currentLanguage == 'NO' || TSApp.settings.currentLanguage == 'LT'){
	   dateString += this.weekdays[myDate.getDay()] + ", ";
	   dateString += "<strong>" + myDate.getDate() + ". ";
	   dateString += this.months[myDate.getMonth()] + "</strong> ";
	   dateString += myDate.getFullYear();
	} else {
	   dateString += this.weekdays[myDate.getDay()] + ", ";
	   dateString += "<strong>" + myDate.getDate() + " ";
	   dateString += this.months[myDate.getMonth()] + "</strong> ";
	   dateString += myDate.getFullYear();
	}
	return dateString;
}

//This function takes a data as a parameter and returns a string repsresentation in the
//following form: Monday 11 April 2005
function dml_dateToStringNoDay(myDate){
    var dateString = "";
    if(TSApp.settings.currentLanguage == 'LT'){
        dateString += myDate.getFullYear() + " m. ";
        dateString += this.months[myDate.getMonth()] + " ";
        dateString += myDate.getDate() + " d."; 
    } else if(TSApp.settings.currentLanguage == 'FI' || TSApp.settings.currentLanguage == 'NO' || TSApp.settings.currentLanguage == 'LT'){
        dateString += "<strong>" + myDate.getDate() + ". ";
        dateString += this.months[myDate.getMonth()] + "</strong> ";
        dateString += myDate.getFullYear();
    } else {
        dateString += myDate.getDate();
        var dayNum = myDate.getDate();
        var dayEnding = '';
        switch (dayNum){
	        case 21:
	            dayEnding = "st ";
	            break;
	        case 31:
	            dayEnding = "st ";
	            break;
	        case 2:
	            dayEnding = "nd ";
	            break;
	        case 22:
	            dayEnding = "rd ";
	            break;
	        case 3:
	            dayEnding = "rd ";
	            break;
	        case 34:
	            dayEnding = "rd ";
	            break;
	        default : dayEnding = "th ";
        }
        dateString += dayEnding;
        dateString += this.months[myDate.getMonth()] + "</strong> ";
        dateString += myDate.getFullYear();
    }
    return dateString;
}

//-------------------------------------------------

//This class represents a charge which sould be added to the total basefare and
//taxes in the form like "servicePack". It is used by the PriceHandler and all
//pricedItems should have a unique name.
function PricedItem(itemName, itemPrice){
	//attributes

	this.itemName = itemName;
	this.itemPrice = itemPrice;

	//methods
	this.getName = pi_getName;
	this.getPrice = pi_getPrice;
	this.setPrice = pi_setPrice;
}

function pi_getName() {
	return this.itemName;
}

function pi_getPrice() {
	return this.itemPrice;
}

function pi_setPrice(price) {
	this.itemPrice = price;
}

//-------------------------------------------------

//This class is used to calclulate the total price of the booking by adding the selected extra
//pricedItems and is also used to display or hide them in the form.
function PriceHandler(totalFare, paxAdults, paxTeens, paxKids, paxInfants, currency){

	//attributes
	//The totalFare is the total baseFare + the total tax for all passengers
	this.totalFare = totalFare;

	//This information is needed to make calculations of the price of cancellationinsurance as
	//there is one per passenger
	this.paxAdults = paxAdults;
	this.paxTeens = paxTeens;
	this.paxKids = paxKids;
	this.paxInfants = paxInfants;

	//The currency is used for knowing what we should round to
	this.currency = currency;

	//this array will store the priced items
	this.pricedItems = new Array();

	//methods
	this.updatePrices = ph_updatePrices;
	this.addPricedItem = ph_addPricedItem;
	this.getPricedItemByName = ph_getPricedItemByName;
	this.hideAllLines = ph_hideAllLines;
	
	this.isLCC = false;
}

function ph_addPricedItem(pricedItem){
	this.pricedItems[this.pricedItems.length] = pricedItem;
}

function ph_getPricedItemByName(itemName){
	for(i = 0; i < this.pricedItems.length; i++){
		if(itemName == this.pricedItems[i].getName()){
			return this.pricedItems[i];
		}
	}
	return null;
}

//This function will calculate the total price for the booking by adding all selected
//pricedItems to the totalFare and displaying the result. It will also make sure that
//only selected pricedItems are displayed as lines in the form.
function ph_updatePrices(){
	this.hideAllLines();
	var totalPrice = this.totalFare;
	var totalPriceInclHandlFee = this.totalFare;
	
	var discount = this.getPricedItemByName("discount");
	if (discount && discount.getPrice() != 0) {
        $("sbtotal").show();
        $("sbtotalh1").show();
         $("discountPriceLine").show();
         var discountAmount = discount.getPrice();
         if (!this.isLCC) {
         if (-discountAmount > totalPrice) {	//if the Discount amount is greater than the total Invoice amount
            discountAmount = -totalPrice;
        }
	} else {
		if (-discountAmount > totalPrice + this.totalFare) {	//if the Discount amount is greater than the total Invoice amount
			discountAmount = -totalPrice + this.totalFare;
		}
	}
		$("discountPriceSpan").innerHTML = "- "+renderCurrency(-discountAmount) + " ";	//updates the Discount amount if modified according to Invoice total amount
		totalPrice += discountAmount;
	}


    supplementaryOptionsTotalPrice = 0;

	var deliveryOptions = document.ccForm.deliveryOption;
	if (deliveryOptions != null) {
		for(i = 0; i < deliveryOptions.length; i++){
			if(deliveryOptions[i].checked){
				if(deliveryOptions[i].value == "letter"){
					var letter = this.getPricedItemByName("letter");
					totalPrice += letter.getPrice();
					supplementaryOptionsTotalPrice += letter.getPrice();
					$("letterLine").show();
					$("letterLineZero").hide();
					$("expressLetterLineZero").show();
				}
				if(deliveryOptions[i].value == "expressLetter"){
					var expressLetter = this.getPricedItemByName("expressLetter");
					totalPrice += expressLetter.getPrice();
					supplementaryOptionsTotalPrice += expressLetter.getPrice();
					$("expressLetterLine").show();
					$("expressLetterLineZero").hide();
					$("letterLineZero").show();
				}
			}
		}
	}

	if (deliveryOptions != null) {
	    if(deliveryOptions.value == "letter"){
		    var letter = this.getPricedItemByName("letter");
		    totalPrice += letter.getPrice();
		    supplementaryOptionsTotalPrice += letter.getPrice();
	    }
	    if(deliveryOptions.value == "expressLetter"){
		    var expressLetter = this.getPricedItemByName("expressLetter");
		    totalPrice += expressLetter.getPrice();
		    supplementaryOptionsTotalPrice += expressLetter.getPrice();
	    }
	}
	var servicePack = $("servicePack");
	if(servicePack != null && servicePack.checked){
		var servicePack = this.getPricedItemByName("servicePack");
		totalPrice += servicePack.getPrice();
		supplementaryOptionsTotalPrice += servicePack.getPrice();
		$("servicePackLine").show();
		$("servicePackLineZero").hide();
	}
	else if(servicePack != null && servicePack.type == 'hidden'){
		var servicePack = this.getPricedItemByName("servicePack");
		totalPrice += servicePack.getPrice();
		supplementaryOptionsTotalPrice += servicePack.getPrice();
	}
	else if (servicePack != null) {
	    $("servicePackLine").hide();
        $("servicePackLineZero").show();
	}
	
	var sms = document.getElementById("sms");
	if (sms != null && sms.checked) {
		var sms = this.getPricedItemByName("sms");
		totalPrice += sms.getPrice();
		supplementaryOptionsTotalPrice += sms.getPrice();
		if($("smsLine")) $("smsLine").show();
		if($("smsLineZero")) $("smsLineZero").hide();
	}
	else if (sms != null && sms.type == 'hidden') {
		var sms = this.getPricedItemByName("sms");
		totalPrice += sms.getPrice();
		supplementaryOptionsTotalPrice += sms.getPrice();
	}
	else if (sms != null) {
	  $("smsLineZero").show();
		$("smsLine").hide();
	}
	
	var airlineLiq = document.getElementById("airlineLiquidation");
	if (airlineLiq != null && airlineLiq.checked) {
		var airlineLiq = this.getPricedItemByName("airlineLiquidation");
		totalPrice += airlineLiq.getPrice();
		supplementaryOptionsTotalPrice += airlineLiq.getPrice();
		$("airlineLiquidationLine").show();
		$("airlineLiquidationLineZero").show();
	}
	else if (airlineLiq != null && airlineLiq.type == 'hidden') {
		var airlineLiq = this.getPricedItemByName("airlineLiquidation");
		totalPrice += airlineLiq.getPrice();
		supplementaryOptionsTotalPrice += airlineLiq.getPrice();
	}
	else if (airlineLiq != null) {
	  $("airlineLiquidationLineZero").show();
	  $("airlineLiquidationLine").hide();
	}
	
	var travelInsurance = document.getElementById("travelInsurance");
	if(travelInsurance != null && travelInsurance.checked){
		var travelInsurance = this.getPricedItemByName("travelInsurance");
		totalPrice += travelInsurance.getPrice();
		supplementaryOptionsTotalPrice += travelInsurance.getPrice();
		$("travelInsuranceLine").show();
		$("travelInsuranceLineZero").hide();
	}
	else if(travelInsurance != null && travelInsurance.type == 'hidden'){
		var travelInsurance = this.getPricedItemByName("travelInsurance");
		totalPrice += travelInsurance.getPrice();
		supplementaryOptionsTotalPrice += travelInsurance.getPrice();
	}
	else if (travelInsurance != null) {
	  $("travelInsuranceLineZero").show();
	$("travelInsuranceLine").hide();
	}
	var cancellationInsurance = document.getElementById("cancellationInsurance");
	if(cancellationInsurance != null && cancellationInsurance.checked){

		//both adults and teens get adultInsurance. Infants don't have insurance
		if((this.paxAdults + this.paxTeens) > 0){
			var adultInsurance = this.getPricedItemByName("adultInsurance");
			totalPrice += (this.paxAdults + this.paxTeens) * adultInsurance.getPrice();
			supplementaryOptionsTotalPrice += (this.paxAdults + this.paxTeens) * adultInsurance.getPrice();
		}
		if(this.paxKids > 0){
			var kidInsurance = this.getPricedItemByName("kidInsurance");
			totalPrice += this.paxKids * kidInsurance.getPrice();
			supplementaryOptionsTotalPrice += this.paxKids * kidInsurance.getPrice();
		}
		if(document.getElementById("adultInsuranceLine") != null){
			$("adultInsuranceLine").show();
			$("adultInsuranceLineZero").hide();
		}
	}
	else if(cancellationInsurance != null && cancellationInsurance.type == 'hidden'){

		//both adults and teens get adultInsurance. Infants don't have insurance
		if((this.paxAdults + this.paxTeens) > 0){
			var adultInsurance = this.getPricedItemByName("adultInsurance");
			totalPrice += (this.paxAdults + this.paxTeens) * adultInsurance.getPrice();
			supplementaryOptionsTotalPrice += (this.paxAdults + this.paxTeens) * adultInsurance.getPrice();
		}
		if(this.paxKids > 0){
			var kidInsurance = this.getPricedItemByName("kidInsurance");
			totalPrice += this.paxKids * kidInsurance.getPrice();
			supplementaryOptionsTotalPrice += this.paxKids * kidInsurance.getPrice();
		}
	}
	else if (cancellationInsurance != null) {
	  $("adultInsuranceLineZero").show();
		$("adultInsuranceLine").hide();
	}
	var handlingFee = this.getPricedItemByName("handlingFee");
	if(handlingFee){
        totalPrice += handlingFee.getPrice();
        totalPriceInclHandlFee += handlingFee.getPrice();
    }

	
	var packageDiscount = this.getPricedItemByName("packageDiscount");
	if (packageDiscount != null) {
		totalPrice += packageDiscount.getPrice();
	}

	var totalPriceLineBeforeDiscount = $("totalPriceLineBeforeDiscount");
    if(totalPriceLineBeforeDiscount){
        if(discountAmount){
           totalPriceLineBeforeDiscount.innerHTML = renderCurrency(totalPrice - discountAmount);
        } else {
           totalPriceLineBeforeDiscount.innerHTML = renderCurrency(totalPrice);
        }
    }

    var paymentDrop = $('paymentDrop');

    if(paymentDrop){
        if($('paymentDrop').options[$('paymentDrop').selectedIndex].parentNode.id == 'ccopt'){
            var ccFee = this.getPricedItemByName("cc_" + $('paymentDrop').value).getPrice();
            totalPrice += ccFee;
            if($('paymentfee')){
                $('paymentfeespan').update(renderCurrency(ccFee));
                $('paymentfee').show();
            }
        } else {
            if($('paymentfee')){
                $('paymentfee').hide();
            }
        }
    }

	var totalPriceLine = $("totalPriceLine");
	totalPriceLine.innerHTML = renderCurrency(totalPrice);


    if ($("supplementaryOptionsTotalPriceLine")){
	   $("supplementaryOptionsTotalPriceLine").innerHTML = renderCurrency(supplementaryOptionsTotalPrice);
	}
	
	if($("totalPriceHandlingFeeLine")) $("totalPriceHandlingFeeLine").show();

    var taxes = 0;
    var originalDiff = 0;
    if ($('installmentTaxes')) {
	taxes = eval($('installmentTaxes').value);
    }
    if ($('installmentOriginalDiff')) {
	originalDiff = eval($('installmentOriginalDiff').value);
    }
    
    // installments
    if(installmentActive && $("installmentExtras")){

        var insRadio = $('cardType').value;
        if(supplementaryOptionsTotalPrice > 0 && insRadio && !$('ins_' + insRadio + '_1').checked){
            $('installmentInfo').show();
        }  else {
            $('installmentInfo').hide();
        }
        $("installmentExtras").innerHTML = renderCurrency(supplementaryOptionsTotalPrice + handlingFee.getPrice() + eval(taxes) + eval(originalDiff));
        $('installmentfees').value = supplementaryOptionsTotalPrice + handlingFee.getPrice() + eval(taxes) + eval(originalDiff);

    }
    if($('cardType')){
        var selDrop = $('cardType').value;
        if(installmentActive && $('avista_'+selDrop)){
            $('avista_'+selDrop).innerHTML = renderCurrency(eval($('installmentfees').value) + eval(rawInstallmentTotal));
        }
    }

}

//This function will hide all dynamic lines in the form.
function ph_hideAllLines(){
	if($("letterLine")) $("letterLine").hide();
	if($("expressLetterLine")) $("expressLetterLine").hide();
	if($("servicePackLine")) $("servicePackLine").hide();
	if($("travelInsuranceLine")) $("travelInsuranceLine").hide();
	if($("adultInsuranceLine")) $("adultInsuranceLine").hide();
	if($("kidInsuranceLine")) $("kidInsuranceLine").hide();
	if($("discountPriceLine")) {
        $("discountPriceLine").hide();
		$("sbtotal").hide();
		$("sbtotalh1").hide();
	}
	if($("smsLine")) $("smsLine").hide();
	if($("totalPriceHandlingFeeLine")) $("totalPriceHandlingFeeLine").hide();
}

//------------------------------------------------------------------------
// this function will round a float to the chosen number of decimals.
function roundNumber(number, decimals){
	number = number * Math.pow(10, decimals);
	number = Math.round(number);
	number = number / Math.pow(10, decimals);
	return number;
}

function renderCurrency(amount){
	var negative = false;
	if (amount < 0) {
		amount = -amount;
		negative = true;
	}
	var intNum = Math.floor(amount).toString();
   var decNum = (Math.round((amount - Math.floor(amount))*100)/100).toString();

   //integer
   if (intNum.length> 3) {
		var start = intNum.length % 3;

		if (start){ 
			var intNumStr=intNum.substr(0,start)+",";

		} else {
			var intNumStr="";

		}
   	for (var i=start; i<intNum.length-3; i+=3){
			intNumStr += intNum.substr(i,3) + ",";
		}
		intNumStr += intNum.substr(intNum.length-3,3);
   }	else {
		intNumStr = intNum;
	}

   //decimal
	while (decNum.length <4) decNum += "0";
		decNum = decNum.substr(2,4)
	//full
	var newStr = '';
	
	if(intNumStr.indexOf(',')){
		var newPreInt = intNumStr.split(',')[0];
		var newPostInt = intNumStr.split(',')[1];
		newStr = TSApp.settings.currencyTemplate.replace('PRESEP', newPreInt);
		if (newPostInt != undefined) {
			newStr = newStr.replace('POSTSEP', newPostInt);
		}
		else {
			newStr = newStr.replace(/\D?POSTSEP/, '');
		}
	} else {
		newStr = TSApp.settings.currencyTemplate.replace('PRESEP', '');
		newStr = newStr.replace('POSTSEP', intNumStr);
	}
	if(decNum != '00'){
		newStr = newStr.replace('POSTCOMMA', decNum);
	} else {
		newStr = newStr.replace(/\D?POSTCOMMA/, '');
	}

	if (negative) {
		newStr = "-" + newStr;
	}
    return newStr.replace(/^\s*|\s*$/g,'');	
}

/**
 * Is used to create a popup window into the document.
 */
function createPopup(id, frameId, titleText, messageText, closeText){
	var popup = "";

	if (frameId == "popupFrameXLarge") {
		popup += "<div id='" + id + "' class='popupXLarge' style='z-index: 1;'>";
	}
	else {
		popup += "<div id='" + id + "' class='popupLarge' style='z-index: 1;'>";
	}
	popup += "<div class='boxmain' width='100%' height='100%'>";
	popup += "<div class='boxmainhead'>";
	popup += "<h2>" + titleText + "</h2>";
	popup += "</div>";
	popup += "<div class='boxmainbody'>";
	popup += "<div class='boxsub'>";
	popup += "<div class='boxsubhead'>";
	popup += "<h2>" + titleText + "</h2>";
	popup += "</div>";
	popup += "<div class='boxsubbody'>";
	popup += "<table border='0'/>";
	popup += "<tr><td valign='top'>"+ messageText + "</td></tr>";
	popup += "<tr><td align='right' valign='bottom'>";
	popup += "<a class='fakesubmit' href='#' onclick=\"return hidePopup('" + id + "', '" + frameId + "');\">" + closeText + "</a>";
	popup += "</td></tr></table></div></div></div></div></div>";

	document.write(popup);
}

//------------------------------------------------------------------------
// Check that the two email adresses are identical.

function valBothEmailIdentical(form, parm) {
	var e = form.elements;
	var emailVar = e['billingEmail'].value;
	var emailVarConf = e['billingEmailConfirm'].value;

	if (emailVarConf == 0 || emailVar == 0) {
		return true;
	}

	if (e['billingEmail'].value != e['billingEmailConfirm'].value) {
		return false;
	}
	else {
		return true;
	}
}


//------------------------------------------------------------------------
//

function valCellPhonePresentForSMS(form, parm) {

	var cellPhone = document.getElementById('billingPhoneCell');
	var sms = document.getElementById('sms');
	if (sms != null && sms.checked && cellPhone.value == '') {
		return false;
	}
	else {
		return true;
	}
}

function hideCellPhoneWarning(sms) {

	if (!sms.checked) {
		if (document.getElementById('billingPhoneCellMandatoryForSMS')) {
			hideId('billingPhoneCellMandatoryForSMS');
		}
	}
}
//------------------------------------------------------------------------
//

var hotelImages = new Array();
var imgCnt = 0;

function addHotelImage(imageUrl) {
	if (imageUrl.indexOf("missing") == -1) {
		if (imageUrl != "") {
			var mImage = new Image();
			mImage.src = imageUrl;
			
			this.hotelImages[this.imgCnt] = mImage;
			this.imgCnt++;
		}
	}
}

function showLessHotelInfo() {
	$('hDescr').show();
	$('hFullDescr').hide();
	$('hDescrMoreLink').show();
	$('hDescrLessLink').hide();
}

function showFullHotelInfo() {
	$('hDescr').hide();
	$('hFullDescr').show();
	$('hDescrMoreLink').hide();
	$('hDescrLessLink').show();
}

var slideShowCnt = 4;
var currentImg = 1;

function startSlideShow() {
	setTimeout("runSlideShow()", 3000);
}

var imgSize = 164;

function regImgSize(size) {
	imgSize = size;
}

function runSlideShow() {
	if (slideShowCnt >= this.hotelImages.length) slideShowCnt = 0;
	if (currentImg > 3) currentImg = 1;
	
	if (!this.hotelImages[slideShowCnt].complete) {
		//This image is not valid, or has not been loaded yet
		slideShowCnt++;
		if (slideShowCnt >= this.hotelImages.length) slideShowCnt = 0;
	}
	
	//We need to scale the image
	var origW = this.hotelImages[slideShowCnt].width;
	var origH = this.hotelImages[slideShowCnt].height;
	var maxSize = imgSize;
	
	var scaleW = origW / maxSize;
	var scaleH = origH / maxSize;
	var scale = Math.max(scaleW, scaleH);
	var newW = origW / scale;
	var newH = origH / scale;
	
	document.getElementById('hImg' + currentImg).width = newW;
	document.getElementById('hImg' + currentImg).height = newH;
	
	document.getElementById('hImg' + currentImg).src = this.hotelImages[slideShowCnt].src;
	currentImg++;
	slideShowCnt++;
	
	setTimeout("runSlideShow()", 3000);
}

function preFillCustomerInfo() {
	var params = getParams();

	if (params['billingTitle']) {
		setSelectValue(document.ccForm.billingTitle, params['billingTitle'])
	}
	if (params['billingFirstName']) {
		document.ccForm.billingFirstName.value = params['billingFirstName'];
	}
	if (params['billingLastName']) {
		document.ccForm.billingLastName.value = params['billingLastName'];
	}
	if (params['billingPhoneDay']) {
		document.ccForm.billingPhoneDay.value = params['billingPhoneDay'];
	}
	if (params['billingPhoneCell']) {
		document.ccForm.billingPhoneCell.value = params['billingPhoneCell'];
	}
	if (params['billingEmail']) {
		document.ccForm.billingEmail.value = params['billingEmail'];
	}
	if (params['billingEmailConfirm']) {
		document.ccForm.billingEmailConfirm.value = params['billingEmailConfirm'];
	}
	if (params['billingAddressOne']) {
		document.ccForm.billingAddressOne.value = params['billingAddressOne'];
	}
	if (params['billingAddressTwo']) {
		document.ccForm.billingAddressTwo.value = params['billingAddressTwo'];
	}
	if (params['billingPostalCode']) {
		document.ccForm.billingPostalCode.value = params['billingPostalCode'];
	}
	if (params['billingCity']) {
		document.ccForm.billingCity.value = params['billingCity'];
	}
	if (params['billingCountry']) {
		setSelectValue(document.ccForm.billingCountry, params['billingCountry'])
	}
	if (params['billingAddressTwo']) {
		document.ccForm.billingAddressTwo.value = params['billingAddressTwo'];
	}
	//CC info, only store type
	if (params['cardType']) {
		setSelectValue(document.ccForm.cardType, params['cardType'])
	}
	//Passager info x 4
	for (var i=1; i < 10; i++) {
		if (params['paxAdult'+i+'Title']) {
			setSelectValue(eval('document.ccForm.paxAdult' + i + 'Title'), params['paxAdult'+i+'Title'])
		}
		if (params['paxAdult'+i+'First']) {
			eval('document.ccForm.paxAdult' + i + 'First').value = params['paxAdult'+i+'First'];
		}
		if (params['paxAdult'+i+'Last']) {
			eval('document.ccForm.paxAdult' + i + 'Last').value = params['paxAdult'+i+'Last'];
		}
	}
	for (var i=1; i < 10; i++) {
		if (params['paxTeen'+i+'Title']) {
			setSelectValue(eval('document.ccForm.paxTeen' + i + 'Title'), params['paxTeen'+i+'Title'])
		}
		if (params['paxTeen'+i+'First']) {
			eval('document.ccForm.paxTeen' + i + 'First').value = params['paxTeen'+i+'First'];
		}
		if (params['paxTeen'+i+'Last']) {
			eval('document.ccForm.paxTeen' + i + 'Last').value = params['paxTeen'+i+'Last'];
		}
			if (params['paxTeen'+i+'Age']) {
			setSelectValue(eval('document.ccForm.paxTeen' + i + 'Age'), params['paxTeen'+i+'Age'])
		}
	}
	for (var i=1; i < 10; i++) {
		if (params['paxKid'+i+'Title']) {
			setSelectValue(eval('document.ccForm.paxKid' + i + 'Title'), params['paxKid'+i+'Title'])
		}
		if (params['paxKid'+i+'First']) {
			eval('document.ccForm.paxKid' + i + 'First').value = params['paxKid'+i+'First'];
		}
		if (params['paxKid'+i+'Last']) {
			eval('document.ccForm.paxKid' + i + 'Last').value = params['paxKid'+i+'Last'];
		}
			if (params['paxKid'+i+'Age']) {
			setSelectValue(eval('document.ccForm.paxKid' + i + 'Age'), params['paxKid'+i+'Age'])
		}
	}
	for (var i=1; i < 10; i++) {
		if (params['paxInfant'+i+'Title']) {
			setSelectValue(eval('document.ccForm.paxInfant' + i + 'Title'), params['paxInfant'+i+'Title'])
		}
		if (params['paxInfant'+i+'First']) {
			eval('document.ccForm.paxInfant' + i + 'First').value = params['paxInfant'+i+'First'];
		}
		if (params['paxInfant'+i+'Last']) {
			eval('document.ccForm.paxInfant' + i + 'Last').value = params['paxInfant'+i+'Last'];
		}
			if (params['paxInfant'+i+'Age']) {
			setSelectValue(eval('document.ccForm.paxInfant' + i + 'Age'), params['paxInfant'+i+'Age'])
		}
	}
}

function writeExCtrl(id){
	if(document.getElementById && document.getElementById(id) && document.getElementById(id).innerHTML){
	  var stringen = document.getElementById(id).innerHTML.replace(/&gt;/gi,'>').replace(/&lt;/gi, '<').replace(/&amp;/gi, '&').replace(/&amp/gi, '&').replace(/&lt/gi, '<').replace(/&gt/gi, '>');
	  var ststr1, strstr2;
	  version = parseFloat(navigator.appVersion.split("MSIE")[1]);
      if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
	       ststr1 = 12;
	       ststr2 = 4;
	       
	  } else {
	       ststr1 = 0;
	       ststr2 = 4;
	       
	  }
	  var stringen2 = stringen.substr(ststr1,parseInt(stringen.length-ststr2));
	  document.write(stringen2);
	 // document.write(stringen2);
	}
}

function fixFireFox(id){
    if (!checkIt('msie')){
    var stringen = document.getElementById(id).innerHTML.replace(/&gt;/gi,'>').replace(/&lt;/gi, '<').replace(/&amp;/gi, '&').replace(/&amp/gi, '&').replace(/&lt/gi, '<').replace(/&gt/gi, '>');
	$(id).innerHTML = stringen;  
	}
}

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*---------------------------------------------*/
/* 	this function is used in commonbooking
/*	- makes 'Your Travel Extras' shown correct
/* ---------------------------------------------*/
function removeLastTblBorder(divRef)
{
	var tables = divRef.getElementsByTagName('table');
	var amountTbls = tables.length;
	if(amountTbls > 0){
		tables[amountTbls-1].className = 'noneStripes mb30px';
		divRef.style.borderBottom = "2px solid #ebebeb";
    	divRef.style.paddingBottom = "10px";
		}
}

function toggleInstallmentInfo(){
    if(supplementaryOptionsTotalPrice > 0){
        $('installmentInfo').show();        
    } else if (supplementaryOptionsTotalPrice == 0 && $('installmentfees').value > 0) {
	$('installmentInfo').show();
	$('installmentExtras').innerHTML = renderCurrency($('installmentfees').value);
    }
}

function bookRegOptions(option) {
    if (option.id == 'bookLogin') {
        option.checked="checked";
        document.ccForm.bookNoReg.checked = "";
        document.ccForm.bookQuickReg.checked = "";
        $('quickSignUpDiv').hide();
        $('loginDiv').show();
    }
    else if (option.id == 'bookQuickReg') {
        option.checked="checked";
        document.ccForm.bookNoReg.checked = "";
        document.ccForm.bookLogin.checked = "";
        $('loginDiv').hide();
        $('signInNotValid').hide();
        $('quickSignUpDiv').show();
    }
    else {
        option.checked="checked";
        document.ccForm.bookQuickReg.checked = "";
        document.ccForm.bookLogin.checked = "";
        $('loginDiv').hide();
        $('quickSignUpDiv').hide();
        $('signInNotValid').hide();
    }
}

function bookForgotPassword() {    
    $('bookForgotDiv').show();
}

function regSignUp(bfV) {
    bfV.reg(document.ccForm.signUpEmail, valEmail, "", "signUpEmailBad", true);
    bfV.reg(document.ccForm.signUpEmailRetyped, valEmail, "", "signUpEmailMismatch", true);
    bfV.reg(document.ccForm.signUpEmailRetyped, validateQuickSignUp, "", "signUpEmailMismatch", true);
}

function unregSignUp(bfV) {
    bfV.unreg(document.ccForm.signUpEmail);
    bfV.unreg(document.ccForm.signUpEmailRetyped);
    bfV.unreg(document.ccForm.signUpEmailRetyped);
}

function validateQuickSignUp() {
    return document.ccForm.signUpEmail.value == document.ccForm.signUpEmailRetyped.value;
}
