var varbookNowOpen = false;
var varshowRoomOpts = false;
var varshowCorpOptions = false;
var varShowSearch = false;

function checkFlashContainer(newWidth){
    if(document.getElementById("flashContainer")){
       document.getElementById("flashContainer").style.width =  newWidth +"px";
    }
}

function resizeBookingModule(newWidth){
    if(document.getElementById("bookNowMod")){
        document.getElementById("bookNowMod").style.width = newWidth + "px";
        positionDivIframe("bookNowMod", "bookNowModIframe", 1);
    }
}

function showRoomOpts(){
	if(varshowRoomOpts){
		var tempVar = (varshowCorpOptions) ? true : false;
		hideAll();
		if(tempVar){
            showCorpOptions();
        }
        else{
            checkFlashContainer(771);
        }
        return false;
	}
	if(varshowCorpOptions){
        showBothOpts();
    }
	else{
        hideAll();
        resizeBookingModule(376);
        checkFlashContainer(564);
    }
	document.getElementById("roomOptionsExpand").className = "expand";
	document.getElementById("roomOptions").className = "locked";
	hideElemnts();
	varshowRoomOpts = true;
}

function showCorpOptions(){
	if(varshowCorpOptions){
		var tempVar = (varshowRoomOpts) ? true : false;
		hideAll();
		if(tempVar){showRoomOpts() }
        else{checkFlashContainer(771);}
        return false;
	}
	if(varshowRoomOpts){
        showBothOpts()
    }
	else{
        hideAll();
        resizeBookingModule(404);
        checkFlashContainer(536);
    }
	document.getElementById("corpOptionExpand").className = "expand";
	document.getElementById("corpOptions").className = "locked";
	hideElemnts();
	varshowCorpOptions = true;
}

function showBothOpts(){
    resizeBookingModule(595);
    checkFlashContainer(345);
}

function positionDivIframe(divId, iframeId, displayFlag){
    var popUpDiv = document.getElementById(divId);
    var popUpIframe = document.getElementById(iframeId);
    if(popUpDiv && popUpIframe && document.documentElement.currentStyle){
        if(displayFlag){
            popUpIframe.style.width   = popUpDiv.offsetWidth;
            popUpIframe.style.height  = popUpDiv.offsetHeight;
            popUpIframe.style.zIndex  = popUpDiv.currentStyle["zIndex"] - 1;
            popUpIframe.style.display = "block";
        }
        else{
            popUpIframe.className = 'hiddenIframe';
        }
    }

}

function hideElemnts(){
	document.getElementById("btnFindRates").style.display = "none";
	//document.getElementById("checkRes").style.display = "none";
	document.getElementById("btnExapnd").className = "";
}

function showSearch(){
	var tempVar = false;
	if (varShowSearch){tempVar = true;}
	hideAll();
	if(tempVar){return false;}
	document.getElementById("bookNowMod").style.width = "366px";
	document.getElementById("moreSearchExpand").className = "expand";
	document.getElementById("searchMore").className = "locked";
    checkFlashContainer(574);
    varShowSearch = true;
}

function hideAll(){
    resizeBookingModule(169);
    document.getElementById("roomOptionsExpand").className = "hide";
	document.getElementById("corpOptionExpand").className = "hide";
	document.getElementById("moreSearchExpand").className = "hide";
	document.getElementById("btnExapnd").className = "hide";
	document.getElementById("btnFindRates").style.display = "block";
	//document.getElementById("checkRes").style.display = "block";
	document.getElementById("roomOptions").className = "";
	document.getElementById("corpOptions").className = "";
    if(document.getElementById("searchMore")){document.getElementById("searchMore").className = "";}
    varshowRoomOpts = false;
	varshowCorpOptions = false;
	varShowSearch = false;
    checkFlashContainer(940);
}

function showBookNow(){
    var bookingModule = document.getElementById("bookNowMod");
    if(varbookNowOpen){
        positionDivIframe("bookNowMod", "bookNowModIframe", 0);
        bookingModule.style.height = "1px";
		bookingModule.style.visibility = "hidden";
		hideAll();
        varbookNowOpen = false;
    }
    else{
        checkFlashContainer(771);
        bookingModule.style.height = "410px";
        bookingModule.style.visibility = "visible";
        positionDivIframe("bookNowMod", "bookNowModIframe", 1);
        varbookNowOpen = true;
    }
}
function hideBookNow(){
    varbookNowOpen = true;
    showBookNow();
}

var hoverMenuManager = new Array();
function showInfo(e, parentElement, divId){
    if(!hoverMenuManager[divId]){
        var tempDiv = document.getElementById("rsHover_" + divId);
        document.body.appendChild(tempDiv);
        hoverMenuManager[divId] = tempDiv;
    }
    var infoDiv = hoverMenuManager[divId];
    var posX = getElementOffsetLeft(parentElement);
    var posY = getElementOffsetTop(parentElement);
    infoDiv.style.display = 'block';
    infoDiv.style.left = posX + "px";
    infoDiv.style.top = posY-infoDiv.offsetHeight + "px";
}
function hideInfo(divId){
    hoverMenuManager[divId].style.display = 'none';
}

function searchHotels(){
    document.getElementById("destinationTab").className = "";
    document.getElementById("hotelTab").className = "locked";
    document.getElementById("selectDestinations").style.display = "none";
    document.getElementById("selectHotels").style.display = "block";
    document.bookingForm.searchType.value = "property";
    document.bookingForm.action = "/whotels/search/results/property_ratelist.html";
}

function searchDestinations(){
    document.getElementById("hotelTab").className = "";
    document.getElementById("destinationTab").className = "locked";
    document.getElementById("selectHotels").style.display = "none";
    document.getElementById("selectDestinations").style.display = "block";
    document.bookingForm.searchType.value = "destination";
    document.bookingForm.action = "/whotels/search/results/destination.html";
}

function toggleBedPreference(){
    var propertyValue = document.bookingForm.propertyID.value;
    var destinationValue = document.bookingForm.destinationID.value;
    var bedType = document.bookingForm.bedTypePreference;
    if(propertyValue==0 && destinationValue==''){
        bedType.selectedIndex = 0;
        bedType.disabled = true;
    }
    else{
        bedType.disabled = false;
    }
}

function validateForm_onSubmit(htmlForm, webFormObj) {
    var searchFormObj = webFormObj;
    searchFormObj.form = htmlForm;

    setErrorMsgDisplay(0);
    searchFormObj.resetErrors();

    dateStatus = booking_checkDates(searchFormObj);
    numericFieldStatus = checkNumeric(searchFormObj);
    checkFavoriteSearchWHBM(searchFormObj);

    if (searchFormObj.hasErrors()) {
        if (document.bookingForm.hasOpenDateError){
            if(searchFormObj.form.searchType.value == "property"){

                outputOpenDateError_bm();
            }else{
                outputDestinationOpenDateError();
            }
        }else{
            var titleTagWhoops = document.getElementById("whoopsHeader");

            if (titleTagWhoops.style.display=='none'){
                var titleTagSoon = document.getElementById("openingSoonHeader");
                titleTagWhoops.style.display='block';
                titleTagSoon.style.display='none';
            }
        }
        searchFormObj.showErrors();
        setErrorMsgDisplay(1);
        return false;
    } else {
        return true;
    }
}
function checkFavoriteSearchWHBM(searchFormObj) {
    if(searchFormObj.form.searchType.value == "destination"){
        if (searchFormObj.form.destinationID.value == '') {
            searchFormObj.addError("~destinationNotSelectedError_bm");
        }
    }else{
        if (searchFormObj.form.propertyID.value < 1) {
            searchFormObj.addError("~propertyNotSelectedError_bm");
        }
    }
}

function setErrorMsgDisplay(displayFlag){
    var errorBlock = document.getElementById("errorBlock_booking");
    errorBlock.style.display = (displayFlag) ? "block" : "none";

    if(document.documentElement.currentStyle){
        var errorIframe = document.getElementById("errorBlockIframe");
        if(displayFlag){
            errorIframe.style.width   = errorBlock.currentStyle["width"];
            errorIframe.style.height  = errorBlock.clientHeight;
            errorIframe.style.top     = errorBlock.currentStyle["top"];
            errorIframe.style.left    = errorBlock.currentStyle["left"];
            errorIframe.style.margin  = errorBlock.currentStyle["margin"];
            errorIframe.style.zIndex  = errorBlock.currentStyle["zIndex"] -1;
            errorIframe.style.display = "block";
        }
        else{
            errorIframe.style.display = "none";
        }
    }
}

function booking_checkDates(searchFormObj) {
    if ((searchFormObj.form.arrivalDate.value == dateFormatString) && (searchFormObj.form.departureDate.value == dateFormatString)) {
        //return searchFormObj.addError("~datesAreRequiredError_bm","arrivalDateLabel_bm","departureDateLabel_bm");
        return true;
    }

    var checkIn = new validBookingDate(searchFormObj.form.arrivalDate);
    var checkOut = new validBookingDate(searchFormObj.form.departureDate);

    if (!(checkIn.valid) && (!checkOut.valid) ) {
        searchFormObj.addError("~ciAnddepartureDatesInvalidError_bm", "arrivalDateLabel_bm","departureDateLabel_bm")
    } else if (!checkIn.valid ) {
        searchFormObj.addError("~arrivalDateInvalidError_bm","arrivalDateLabel_bm")
    } else if (!checkOut.valid ) {
        searchFormObj.addError("~departureDateInvalidError_bm","departureDateLabel_bm")
    } else if ( (checkIn.valid) & (checkOut.valid)  ) {
        var datesDelta = checkIn.diffDate( checkOut.d);
        var nowDelta = checkIn.diffDate(new Date());

        if (nowDelta > 0 ) {
            searchFormObj.addError("~checkInEarlierThanTodayError_bm","arrivalDateLabel_bm");
        } else if (nowDelta < -561) {
            searchFormObj.addError("~bookToFarInFutureError_bm","arrivalDateLabel_bm");
        } else if (datesDelta < 0) {
            searchFormObj.addError("~departureBeforeArrivalError_bm","departureDateLabel_bm");
        } else if (datesDelta > 31) {
            searchFormObj.addError("~maximumLengthStayExceededError_bm", "arrivalDateLabel_bm","departureDateLabel_bm");
        } else if (datesDelta < 1) {
            searchFormObj.addError("~arrivalEqualsDepartureError_bm", "arrivalDateLabel_bm","departureDateLabel_bm");
        }
        if(searchFormObj.form.searchType.value == "property"){

            var openingDateObj = validateOpeningDate_bm(searchFormObj.form);
            if (openingDateObj!=null){
               var openDelta = checkIn.diffDate(openingDateObj.openDate);
                if (openDelta>0){
                    document.bookingForm.hasOpenDateError = true;
                    document.bookingForm.propertyOpeningDate = openingDateObj.openDateDisplay;
                    searchFormObj.addError("checkinDateBeforeOpendate_bm", "arrivalDateLabel_bm");

                }
            }
       }else{
            var openingDateObj = validateDestinationOpenDate(searchFormObj.form,checkIn);
               if (openingDateObj!=null){
               var openDelta = checkIn.diffDate(openingDateObj.openDate);
                if (openDelta>0){
                    document.bookingForm.hasOpenDateError = true;
                    document.bookingForm.propertyOpeningDate = openingDateObj.openDateDisplay;
                    document.bookingForm.destinationName = searchFormObj.form.destinationID.options[searchFormObj.form.destinationID.selectedIndex].text;
                    searchFormObj.addError("checkinDateBeforeDestinationOpendate_bm", "arrivalDateLabel_bm");

                }
            }
        }
    }
    return true;
}

function checkNumeric(searchFormObj){
    var allowedCharacters = "- ";

    var set = searchFormObj.form.corporateAccountNumber.value;
    set = yuiLang.trim(set);
    var ata = searchFormObj.form.iataNumber.value;
    ata = yuiLang.trim(ata);
    var pro = searchFormObj.form.promotionCode.value;
    pro = yuiLang.trim(pro);
	var rate = searchFormObj.form.ratePlanName.options[searchFormObj.form.ratePlanName.selectedIndex].value;
    rate = yuiLang.trim(rate);
    // 1. check for errors in the numeric fields : SET and ATA number
    set = stripCharsInBag(set, allowedCharacters);
    if (set != '' && !isInt(set)) {
        searchFormObj.addError("~corporateAccountNumberNotNumericError_bm","corporateAccountNumberLabel_bm");
    }
    if (ata != '' && !isInt(ata)) {
        searchFormObj.addError("~iataNotNumericError_bm","iataNumberLabel_bm");
    }
	// 2. check if both promo code & rate plan are filled
	if(pro != '' && rate != '') {
        searchFormObj.addError("~bothPromoRateSetError_bm","promotionCodeLabel_bm", "ratePlanNameLabel_bm");
	}

    // 3. check if both promo code and SET number  are entered
    if(set !='' && pro !=''){
        searchFormObj.addError("~bothPromoCodeSetNumError_bm","promotionCodeLabel_bm", "corporateAccountNumberLabel_bm");
    }

    // 4. check if rateplan and SET number have values
    // only allow this combination if the values are consistent with the Auto SET enhancement (AAA)
     var ratePlanArray = (searchFormObj.form.ratePlanList.value).split(",");
    if (!(set == '' || rate == '' || (ratePlanArray.contains(rate) && set == searchFormObj.form.AAAsetNum.value))) {
        searchFormObj.addError("~bothSetNumRateSetError_bm","corporateAccountNumberLabel_bm", "ratePlanNameLabel_bm");
	}
}

var bookingForm = new WebForm();
function validateBookingInfo(form){
    if(form.searchType.value == 'property'){
        form.destinationID.selectedIndex = 0;
    }
    else{
        form.propertyID.selectedIndex = 0;
    }
    promoCode_onFocus();
    return validateForm_onSubmit(form, bookingForm);
}
function promoCode_onFocus(){
    if(defaultPromoText == document.bookingForm.promotionCode.value){
        document.bookingForm.promotionCode.value = '';
    }
}

function promoCode_onBlur(){
    if((document.bookingForm.promotionCode.value != defaultPromoText) && (document.bookingForm.promotionCode.value == '')){
        document.bookingForm.promotionCode.value = defaultPromoText;
    }
}

function checkBookingDates(form, event) {
    formObj = form;
    if (event.type == "focus")   {
        if(formObj.arrivalDate.hasFocus == "true")    {
            var checkIn = new validDate(formObj.arrivalDate);
            if (  !checkIn.valid ) { formObj.arrivalDate.value="";}
        }
        if(formObj.departureDate.hasFocus == "true")    {
            var checkOut = new validDate(formObj.departureDate);
            if (  !checkOut.valid ) { formObj.departureDate.value="";}
        }
    }
    if (event.type == "blur")   {
        if(formObj.arrivalDate.hasFocus == "false")    {
            var checkOut = new validBookingDate(formObj.departureDate);
            var checkIn = new validBookingDate(formObj.arrivalDate);
            if ( checkIn.valid ) {
                checkIn.setField();
                if (checkOut.valid ) { before = (checkIn.diffDate(checkOut.d) <= 0);}
                if ( (! (checkOut.valid)) || before) {
                    checkOut.setD(checkIn.d);
                    checkOut.nextDay();
                    checkOut.setField();
                }
            } else {
                formObj.arrivalDate.value=dateFormatString;
            }
        }
        if(formObj.departureDate.hasFocus == "false")    {
            var checkOut = new validDate(formObj.departureDate);
            if ( checkOut.valid ) { checkOut.setField(); } else {formObj.departureDate.value=dateFormatString;}
        }
    }
}
function isInt(s){
	var re = /^\d+$/
	return (s.search(re) == -1) ? false : true;
}

//-------------------------------
// renamed copy of validDate from WebForm, work around for advance search page funtion overwrite
function validBookingDate(_field) {
	var field;
	var d;

	field = _field;

	_s  = field.value;
	_d = getDateFromField(field, dateFormatString);
	this.valid = true;
	if ( isNaN(_d.getDate() ) ) {  // Basically, this allows the functions to gracefully return to the format string instead of putting a date in the field.
			this.valid = false;
	}

	this.d = _d;
	var xxxdgetY = function() {
		var y = (self.d.getYear() + 10000) % 100;
		y += (y < 38) ? 2000 : 1900;
		return y
	}
	this.setField = function() {
		writeDateToField(field, this.d, dateFormatString);
	}
	this.setD = function(_d) {self.d = _d}
	this.nextDay = function() {return this.d.setDate(self.d.getDate()+1);}
	this.diffDate = function(dd) {
		return  Math.round( (makeDate(dd).getTime() - makeDate(self.d).getTime()) / (1000*60*60*24) );
	}
	function makeDate(md) {
		return new Date( fixYear(md.getYear()), md.getMonth(), md.getDate() );
	}
	function lZero(nr) {if (nr < 10) nr = "0" + nr;return nr;}

	var self = this;
	return this;
}
//-------------------------------