﻿/// <reference path="jquery.js" />
/// <reference path="jquery-vsdoc.js" />

var isPageLoad = true;
var fileName;
var ratesViewDisplay = false;
var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var weekdaysShort = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
var calTitle = "Choose a date:";
var myLabelYearPosition = 2;
var myLabelMonthPosition = 1;
var myLabelYearSuffix = "";
var myLabelMonthSuffix = " ";
var currentTabId = "Details";
var mapAlreadyShown = false;

function ChangeLanguage(url) {
    window.location = ReverseString(url);
}

function ReverseString(value) {
    if (value == null)
        return null;

    var output = "";
    for (i = 0; i < value.length; i++) {
        output = value.charAt(i) + output;
    }
    return output;
}

function HideLoading(divId) {
    document.getElementById(divId).style.display = "none";
}

function OpenWindow(url) {
    window.open(
        url,
        null,
        'alwaysRaised=1,height=545,width=525,directories=0,locaton=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0'
    ).focus();
}

//reload page with the new querystring name-value pair
function Reload(name, val) {
    var qString = location.search.substr(1)

    if (qString == null || qString.length == 0 || qString.indexOf("gclid=") >= 0)
        qString = query;

    //always reset page to 1
    if (name != "pageIndex") {
        var page = GetQSVal("pageIndex")
        if (page != "0" && page != "") qString = setQStringName(qString, "pageIndex", new Array("0"))
    }

    qString = setQStringName(qString, name, new Array(val.toString()))
    qString = setQStringName(qString, "tabId", new Array(currentTabId.toString()))

    if (typeof path != 'undefined' && path != null && path.length > 0)
        location = path + "?" + qString
    else
        location = location.pathname + "?" + qString

    return false;
}

function setGuestValue(select) {
    document.getElementById('guestValue').value = select.options[select.selectedIndex].value;
    return false;
}

function setRoomValue(select, isAffiliate) {
    if (select.value == "5" && isAffiliate == false) {
        select.selectedIndex = 0;
        var r = confirm(typeof (JavaScriptSearchMoreRoom) == 'undefined' ? 'We only support searching for up to four rooms at once, would you like to use our partner site Hotelplanner.com to search for more rooms?' : JavaScriptSearchMoreRoom);
        if (r == true) {
            var qString = "?sc=HotelsCombined";
            city = "",
                checkin = "",
                checkout = "";

            //if on city or searchResults page
            if (document.getElementById("M_C_SearchResultCity") != null && document.getElementById("M_C_SearchResultCity").value != 0) {
                city = document.getElementById("M_C_SearchResultCity").value;
            }
            else {
                //if on hotel page
                if (document.getElementById("cityNameValue") != null && document.getElementById("cityNameValue").value != 0) {
                    city = document.getElementById("cityNameValue").value;
                }
            }

            //get user selected checkin and ckeckout value
            if ((document.getElementById("hotelCheckin") != null && document.getElementById("hotelCheckin").value != 0) ||
                (document.getElementById("detailTabCheckin") != null && document.getElementById("detailTabCheckin").value != 0) ||
                (document.getElementById("rateTabCheckin") != null && document.getElementById("rateTabCheckin").value != 0)) {
                var checkinDom = document.getElementById("checkinValue");
                checkin = checkinDom == null ? "" : checkinDom.value == 0 ? "" : reFormatDate(checkinDom.value);
            }
            if ((document.getElementById("hotelCheckout") != null && document.getElementById("hotelCheckout").value != 0) ||
                (document.getElementById("detailTabCheckout") != null && document.getElementById("detailTabCheckout").value != 0) ||
                (document.getElementById("rateTabCheckout") != null && document.getElementById("rateTabCheckout").value != 0)) {
                var checkoutDom = document.getElementById("checkoutValue");
                checkout = checkoutDom == null ? "" : checkoutDom.value == 0 ? "" : reFormatDate(checkoutDom.value);
            }

            qString += city == "" ? "" : "&City=" + city;
            qString += checkin == "" ? "" : "&Checkin=" + checkin;
            qString += checkout == "" ? "" : "&Checkout=" + checkout;
            window.open("/ProviderRedirect.aspx?key=2.HPL.EN.USD.0.0.0&url=" + escape("http://www.hotelplanner.com" + qString), "_self");
            return false;
        }
    }
    else {
        document.getElementById('roomValue').value = select.options[select.selectedIndex].value;
    }
    return false;
}

function setHomePageRoomValue(select, languageParameter) {
    if (select.value == "5") {
        select.selectedIndex = 0;
        var r = confirm(typeof (JavaScriptSearchMoreRoom) == 'undefined' ? 'We only support searching for up to four rooms at once, would you like to use our partner sites to search for more rooms?' : JavaScriptHomePageSearchMoreRoom);
        if (r == true) {
            window.open("/GroupBookings.aspx" + languageParameter, "_self");
            return false;
        }
    }
    else {
        document.getElementById('roomValue').value = select.options[select.selectedIndex].value;
    }
    return false;
}

function isFieldEmpty(fieldOneId, fieldTwoId) {
    if (document.getElementById(fieldOneId) != null && document.getElementById(fieldTwoId) != null) {
        if (document.getElementById(fieldOneId).value == 0 || document.getElementById(fieldTwoId).value == 0) {
            alert(typeof (JavaScriptEnterCheckinCheckout) == 'undefined' ? 'Please enter your checkin and checkout date.' : JavaScriptEnterCheckinCheckout)
            return true
        }
    }
    return false;
}

function getDate(dateString) {
    var year = dateString.substr(0, 4)
    var month = dateString.substr(5, 2) - 1 // 0 - 11
    var day = dateString.substr(8, 2)
    return new Date(year, month, day)
}

// validate dates
function ValidateDates() {
    var inDate = getDate(document.getElementById("checkinValue").value)
    var outDate = getDate(document.getElementById("checkoutValue").value)
    var currentDate = new Date();

    //validate checkin - checkout difference (date range too big)
    if ((outDate - inDate) / 86400000 >= 31) {  //86400000 is one days in milliseconds
        alert(typeof (JavaScriptPeriodOfStay) == 'undefined' ? 'Your period of stay should be no longer than 30 nights.' : JavaScriptPeriodOfStay)
        return false
    }

    // validate checkout <= checkin
    if (outDate - inDate <= 0) {
        alert(typeof (JavaScriptEnsureCheckoutAfterCheckin) == 'undefined' ? 'Please ensure that the check-out date is after the check-in date.' : JavaScriptEnsureCheckoutAfterCheckin)
        return false
    }

    //validate checkin/checkout is less than one year in advance
    if ((outDate - currentDate) / 86400000 >= 363) {
        alert(typeof (JavaScriptBookWithinOneYear) == 'undefined' ? 'You cannot book more than 1 year in advance.' : JavaScriptBookWithinOneYear)
        return false;
    }
    return true
}

//unencode url-encoded string
function URLDecode(urlStr) {
    return unescape(urlStr.replace(/\+/g, " "))
}

//replace or add name/value pairs in url-encoded querystring
function setQStringName(qString, name, arrVal) {
    var qStringNew = remQStringName(qString, name)
    var start = qStringNew == "" ? 1 : 0
    //for (var i in arrVal) 
    for (var i = 0; i < arrVal.length; i++)
        qStringNew += "&" + escape(name) + "=" + escape(arrVal[i])
    return qStringNew.substr(start)
}

//remove all name/value pairs with the passed name from url-encoded querystring
function remQStringName(qString, name) {
    var i
    var qStringNew = ""

    if (qString != "") {
        var curName
        var arrNameVal = qString.split('&')
        //for (i in arrNameVal) {		
        for (i = 0; i < arrNameVal.length; i++) {
            curName = URLDecode(arrNameVal[i].split('=')[0])

            if (curName.toLowerCase() != name.toLowerCase()) qStringNew += "&" + arrNameVal[i]
        }
    }
    return qStringNew.substr(1)
}

//extract (first!) value from querystring for the passed name
function GetQSVal(qsName) {
    try {
        var qsPair
        var i
        var qString = location.search.substr(1)

        if (qString == null || qString.length == 0)
            qString = query;

        var arrNameVal = qString.split('&')
        //for (i in arrNameVal) {	
        for (i = 0; i < arrNameVal.length; i++) {
            qsPair = arrNameVal[i].split('=')
            if (URLDecode(qsPair[0]).toLowerCase() == qsName.toLowerCase()) return URLDecode(qsPair[1])
        }
    }
    catch (e) {
    }
    return ""
}

function GetUrlFromKey(key) {
    var url = "/";
    url += "ProviderRedirect";
    url += ".aspx?";
    url += key;
    return url;
}

function getCookie(cookieName) {
    if (document.cookie != null && document.cookie.length > 0) {
        var start = document.cookie.indexOf(cookieName + "=");
        if (start != -1) {
            start = start + cookieName.length + 1;
            var end = document.cookie.indexOf(";", start);
            if (end == -1) {
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(start, end));
        }
    }
    return ""
}

function SearchKeyPress(eventObject, languageCode, target, affiliateId, city, domain, brandId) {
    if (eventObject.keyCode == 13) {
        eventObject.returnValue = false;
        eventObject.cancel = true;
        return DoSearch(languageCode, target, affiliateId, city, domain, brandId);
    }
}

//only used by two affiliate search boxes
function CitySelect(cityFileName) {
    document.getElementById(cityFileName).checked = "checked";
    document.getElementById("citySearch").value = ""
    document.getElementById("selectedFileName").value = cityFileName
}

function DoSearch(languageCode, target, affiliateId, city, domain, brandId) {

    var redirection;
    var affiliateParam;
    var brandParam;
    var host;
    var isAutoComplete = false;

    if (document.getElementById('hotelCheckin') != null) {
        if (document.getElementById('hotelCheckin').value == 0 || document.getElementById('hotelCheckout').value == 0) {
            alert(typeof (JavaScriptEnterCheckinCheckout) == 'undefined' ? 'Please enter your checkin and checkout date.' : JavaScriptEnterCheckinCheckout)
            return false
        }
    }

    if (!ValidateDates())
        return false

    //in home page, if city name is autocomplete text, redirect to searchResults.aspx, otherwise redirect to search.aspx    
    if (document.getElementById('citySearch') != null && document.getElementById('selectedCityName') != null) {
        if (document.getElementById('citySearch').value != 0 && document.getElementById('selectedCityName').value != 0) {
            if (document.getElementById('citySearch').value == document.getElementById('selectedCityName').value) {
                isAutoComplete = true;
            }
        }
    }

    city = escape(city)
    if (typeof (brandId) == 'undefined' || brandId == "0") {
        brandParam = '';
    }
    else {
        brandParam = '&brandId=' + brandId
    }

    if (affiliateId == null || affiliateId == '') {
        affiliateParam = '';
        host = '';
    }
    else {
        affiliateParam = '&a_aid=' + affiliateId;
        // backwards compatability for existing affiliate scripts
        if (typeof (domain) == 'undefined' || domain == '') {
            host = 'http://www.hotelscombined.com'
        }
        else {
            host = 'http://' + domain;
        }
    }

    var defaultSort = GetQSVal("sort");
    if (document.getElementById("M_C_Locations") != null) {
        if (sortDistance) {
            defaultSort = "Distance-asc";
        }
    }  
    if (defaultSort.length > 0) {
        defaultSort = "&sort=" + defaultSort;
    }

    //if come from home page without an autocompleted city name or come from city/searchResult pages with a new city name entered in the 'City' textbox
    if ((document.getElementById("citySearchRadio") != null && document.getElementById("citySearchRadio").checked && !isAutoComplete) || document.getElementById("M_C_SearchResultCity") != null) {

        if (city == null || city.length < 3) {
            alert(typeof (JavaScriptEnterCityName) == 'undefined' ? 'Please enter a city name that is at least 3 characters in length' : JavaScriptEnterCityName);
            return false;
        }
        redirection = "/Search.aspx?search=" + city + "&checkin=" + document.getElementById("checkinValue").value + "&checkout=" + document.getElementById("checkoutValue").value + "&languageCode=" + languageCode + affiliateParam + brandParam + defaultSort;

        //if come from city or search result pages, add query info
        if (document.getElementById("M_C_SearchResultCity") != null) {
            var currency = document.getElementById("M_C_currencies");
            redirection += currency == null ? "" : "&currencyCode=" + currency.options[currency.selectedIndex].id;

            if (document.getElementById("M_C_LowRate") != null) {
                if (document.getElementById("M_C_LowRate").value != null && document.getElementById("M_C_LowRate").value != 0) {
                    redirection += "&lowRate=" + escape(document.getElementById("M_C_LowRate").value);
                }
            }
            if (document.getElementById("M_C_HighRate") != null) {
                if (document.getElementById("M_C_HighRate").value != null && document.getElementById("M_C_HighRate").value != 0) {
                    redirection += "&highRate=" + escape(document.getElementById("M_C_HighRate").value);
                }
            }

            redirection += GetStarValue(redirection, document.getElementById("M_C_Star5"), "star5");
            redirection += GetStarValue(redirection, document.getElementById("M_C_Star4"), "star4");
            redirection += GetStarValue(redirection, document.getElementById("M_C_Star3"), "star3");
            redirection += GetStarValue(redirection, document.getElementById("M_C_Star2"), "star2");
            redirection += GetStarValue(redirection, document.getElementById("M_C_Star1"), "star1");
            redirection += "&cityName=" + city;

            if (document.getElementById("M_C_HotelName") != null) {
                if (document.getElementById("M_C_HotelName").value != null && document.getElementById("M_C_HotelName").value != 0) {
                    redirection += "&hotelName=" + escape(document.getElementById("M_C_HotelName").value);
                }
            }

            if (document.getElementById("M_C_ShowSoldOut") != null) {
                redirection += document.getElementById("M_C_ShowSoldOut").checked ? "" : "&showSoldOut=false";
            }

            if (document.getElementById("M_C_InstantOnly") != null) {
                redirection += document.getElementById("M_C_InstantOnly").checked ? "" : "&instantOnly=false";
            }
        }
    } else {
        redirection = "/SearchResults.aspx?fileName=" + document.getElementById("selectedFileName").value + "&checkin=" + document.getElementById("checkinValue").value + "&checkout=" + document.getElementById("checkoutValue").value + "&languageCode=" + languageCode + affiliateParam + brandParam + defaultSort;
    }

    redirection += document.getElementById("guestValue") == null ? "" : "&Adults=" + document.getElementById("guestValue").value;
    redirection += document.getElementById("roomValue") == null ? "" : "&Rooms=" + document.getElementById("roomValue").value;

    // locations
    var locations = document.getElementById("M_C_Locations");
    if (locations != null) {
        if (locations.value != 0) {
            redirection += "&locationId=" + locations.options[locations.selectedIndex].value;
        }
    }
    // location distance
    var distance = document.getElementById("M_C_Distance");
    if (distance != null) {
        if (distance.value != 0) {
            redirection += "&distance=" + distance.options[distance.selectedIndex].value;
        }
    }

    // hotel brands
    if (document.getElementById("p-chain") != null) {
        if (chainId != null && chainId != "") {
            if (document.getElementById("M_C_HotelChainAll") != null) {
                if (document.getElementById("M_C_HotelChainAll").checked == false) {
                    var checkedChain = "";
                    var chain = chainId.split(',');

                    for (var i = 0; i < chain.length; i++) {
                        if (document.getElementById("M_C_HotelChain" + chain[i]) != null) {
                            if (document.getElementById("M_C_HotelChain" + chain[i]).checked) {
                                checkedChain += chain[i] + ",";
                            }
                        }
                    }
                    if (checkedChain != "") {
                        var strLen = checkedChain.length;
                        checkedChain = checkedChain.slice(0, strLen - 1);
                        redirection += "&chain=" + checkedChain;
                    }
                }
            }
        }
    }
    
    // add facilities to query if come from search result page
    if (document.getElementById("M_C_HotelFacility1") != null) {   
        var facility = "";
        for (var i = 1; i <= facilityCount; i++) {
            if (document.getElementById("M_C_HotelFacility" + i).checked) {
                facility += i + ',';
            }
        }
        if (facility != "") {
            var strLen = facility.length;
            facility = facility.slice(0, strLen - 1);
            redirection += "&facilities=" + facility;
        }
    }

    // add noPropType to query if some property types are unchecked
    var noPropType = "";
    for (var i = 0; i <= 9; i++) {
        if (document.getElementById("M_C_PropertyType" + i) != null) {
            if (document.getElementById("M_C_PropertyType" + i).checked == false) {
                noPropType += i + ',';
            }
        }
    }
    if (noPropType != "") {
        var strLen = noPropType.length;
        noPropType = noPropType.slice(0, strLen - 1);
        redirection += "&noPropType=" + noPropType;
    }
 
    redirection = host + redirection;

    switch (target) {
        case "_blank":
            window.open(redirection).focus();
            break;
        case "_parent":
            window.parent.location = redirection;
            break;
        case "_top":
            window.top.location = redirection;
            break;
        default:
            window.location = redirection; // _self
    }
    return false;
}

function GetStarValue(qString, starElement, starName) {
    if (starElement == null || starElement.checked) {
        return "";
    } else {
        return "&" + starName + "=false";
    }
}

function DoCitySearchBoxSearch(languageCode, target, affiliateId, fileName, domain, brandId, applyFilters) {
    var redirection;
    var affiliateParam;
    var brandParam;
    var host;

    if (isFieldEmpty('hotelCheckin', 'hotelCheckout')) {
        return false;
    }
    else {
        if (!ValidateDates())
            return false

        if (typeof (brandId) == 'undefined' || brandId == "0") {
            brandParam = '';
        }
        else {
            brandParam = '&brandId=' + brandId
        }

        if (affiliateId == null || affiliateId == '') {
            affiliateParam = '';
            host = '';
        }
        else {
            affiliateParam = '&a_aid=' + affiliateId;
            // backwards compatability for existing affiliate scripts
            if (typeof (domain) == 'undefined' || domain == '') {
                host = 'http://www.hotelscombined.com'
            }
            else {
                host = 'http://' + domain;
            }
        }

        var guest = document.getElementById('guestValue') == null ? "" : "&Adults=" + document.getElementById("guestValue").value;
        var room = document.getElementById('roomValue') == null ? "" : "&Rooms=" + document.getElementById('roomValue').value;

        redirection = "/SearchResults.aspx?fileName=" + fileName + "&checkin=" + document.getElementById("checkinValue").value + "&checkout=" + document.getElementById("checkoutValue").value + "&languageCode=" + languageCode + affiliateParam + brandParam + guest + room;

        if (applyFilters) {
            redirection = SetStarValue(redirection, document.getElementById("Star5"), 'star5');
            redirection = SetStarValue(redirection, document.getElementById("Star4"), 'star4');
            redirection = SetStarValue(redirection, document.getElementById("Star3"), 'star3');
            redirection = SetStarValue(redirection, document.getElementById("Star2"), 'star2');
            redirection = SetStarValue(redirection, document.getElementById("Star1"), 'star1');
            redirection = setQStringName(redirection, "sort", new Array(document.getElementById("sortBy").options[document.getElementById("sortBy").selectedIndex].value));

            var currency = document.getElementById("currencies");
            redirection = setQStringName(redirection, 'currencyCode', new Array(currency.options[currency.selectedIndex].text))

            if (document.getElementById("AvailableOnly").checked) {
                redirection = remQStringName(redirection, "availableOnly");
            }
            else {
                redirection = setQStringName(redirection, "availableOnly", new Array("false"));
            }
        }

        redirection = host + redirection;

        switch (target) {
            case "_blank":
                window.open(redirection).focus();
                break;
            case "_parent":
                window.parent.location = redirection;
                break;
            case "_top":
                window.top.location = redirection;
                break;
            default:
                window.location = redirection; // _self
        }

        return false;
    }
}

function DoHotelSearch(languageCode, hotelFileName, target, affiliateId, domain, brandId) {
    var affiliateParam;
    var host;
    var brandParam;

    if (typeof (brandId) == 'undefined' || brandId == "0") {
        brandParam = '';
    }
    else {
        brandParam = '&brandId=' + brandId
    }

    if (affiliateId == null || affiliateId == '') {
        affiliateParam = '';
        host = '';
    }
    else {
        affiliateParam = '&a_aid=' + affiliateId;
        // backwards compatability for existing affiliate scripts
        if (typeof (domain) == 'undefined' || domain == '') {
            host = 'http://www.hotelscombined.com'
        }
        else {
            host = 'http://' + domain;
        }
    }

    var guest = document.getElementById('guestValue') == null ? "" : "&Adults=" + document.getElementById("guestValue").value;
    var room = document.getElementById('roomValue') == null ? "" : "&Rooms=" + document.getElementById('roomValue').value;

    var redirection = host + "/Hotel.aspx?tabId=Rates&fileName=" + hotelFileName + "&checkin=" + document.getElementById("checkinValue").value + "&checkout=" + document.getElementById("checkoutValue").value + "&languageCode=" + languageCode + affiliateParam + brandParam + guest + room;

    switch (target) {
        case "_blank":
            window.open(redirection).focus();
            break;
        case "_parent":
            window.parent.location = redirection;
            break;
        case "_top":
            window.top.location = redirection;
            break;
        default:
            window.location = redirection; // _self
    }

    return false;
}

var providers = new Array('RTG', 'HTC', 'GTA', 'PLN', 'IHG', 'BKS', 'LRM', 'VNR', 'LMT', 'GTS', 'EXP', 'HOT', 'ATV', 'ALR', 'OPD', 'ORB', 'CTS', 'TCY', 'LMN', 'SKH', 'HDE', 'AMZ');

var currentMarketingTextIndex = 0;
function ShowMarketingText() {
    var newItem = document.createElement('li');
    newItem.innerHTML = marketingText[currentMarketingTextIndex];
    document.getElementById("waitingMarketingText").appendChild(newItem);
    if (currentMarketingTextIndex < marketingText.length - 1) {
        currentMarketingTextIndex += 1;
        setTimeout(ShowMarketingText, 3000);
    }
}

var currentProviderStatusIndex = 0;
var searchProgressInterval = 2000;
var statusArray;
var progress1Complete = false;
var progress2Complete = false;
var progress3Complete = false;
var progress4Complete = false;
var progress5Complete = false;
var progress6Complete = false;
var progress7Complete = false;
var autoFire = true;
var fireCount = 0;

function GetInterval() {
    return searchProgressInterval;
}

function FireEvent() {
    fireCount++;

    if (!progress1Complete) {
        ShowProviderStatus();
        if (autoFire) {
            setTimeout(FireEvent, GetInterval() * Math.random());
        }
        return;
    }

    if (!progress2Complete) {
        document.getElementById('progressLine1Image').style.display = "none";
        document.getElementById('progressLine2Number').style.display = "inline";
        document.getElementById('progressLine2Image').style.display = "inline";
        document.getElementById('M_C_ProgressLine2').style.display = "inline";
        progress2Complete = true;
        if (autoFire) {
            setTimeout(FireEvent, GetInterval() * 10);
        }
        return;
    }

    if (!progress3Complete) {
        document.getElementById('progressLine2Image').style.display = "none";
        document.getElementById('progressLine3Number').style.display = "inline";
        document.getElementById('progressLine3Image').style.display = "inline";
        document.getElementById('M_C_ProgressLine3').style.display = "inline";
        progress3Complete = true;
        if (autoFire) {
            setTimeout(FireEvent, GetInterval() * 5);
        }
        return;
    }

    if (!progress4Complete) {
        document.getElementById('progressLine3Image').style.display = "none";
        document.getElementById('progressLine4Number').style.display = "inline";
        document.getElementById('progressLine4Image').style.display = "inline";
        document.getElementById('M_C_ProgressLine4').style.display = "inline";
        progress4Complete = true;
        if (autoFire) {
            setTimeout(FireEvent, GetInterval());
        }
        return;
    }

    if (!progress5Complete) {
        document.getElementById('progressLine4Image').style.display = "none";
        document.getElementById('progressLine5Number').style.display = "inline";
        document.getElementById('progressLine5Image').style.display = "inline";
        document.getElementById('M_C_ProgressLine5').style.display = "inline";
        progress5Complete = true;
        return;
    }

    if (typeof (finishInterval) != 'undefined') {
        clearInterval(finishInterval);
    }
    HideLoading("waiting");
}

function ShowProviderStatus() {
    document.getElementById('progressLine1Data').innerHTML = statusArray[currentProviderStatusIndex];

    if (currentProviderStatusIndex < statusArray.length - 2) {
        currentProviderStatusIndex++;
    }
    else {
        document.getElementById('progressLine1Image').style.display = "none";
        document.getElementById('progressLine1Data').innerHTML = "&nbsp;";
        progress1Complete = true;
    }
}

//Yahoo Calendar
function setupCal(checkin, checkout, checkinId, checkoutId, checkinCalId, checkoutCalId, numOfCal) {
    var theMindate = new Date();
    var min_date = theMindate.getDate();
    var min_month = theMindate.getMonth();
    min_month++;
    var min_year = theMindate.getFullYear();
    theMindate = min_month + "/" + min_date + "/" + min_year;
    var theMaxdate = min_month + "/" + min_date + "/" + (min_year + 1);

    //make yesterday selectable for checkin calendar(due to time zone differnce)
    var earlyMindate = new Date();
    earlyMindate.setDate(min_date - 1);
    var early_month = earlyMindate.getMonth();
    early_month++;
    earlyMindate = early_month + "/" + earlyMindate.getDate() + "/" + earlyMindate.getFullYear();

    if (checkin == null || checkout == null) {
        checkin = dateFormat(min_month) + "/" + dateFormat(min_date) + "/" + min_year;
        checkout = checkin;
    }

    //get calendar selected date
    var checkinSelection = document.getElementById(checkinId).value == 0 ? checkout : reFormatDate(document.getElementById(checkinId).value);
    var checkoutSelection = document.getElementById(checkoutId).value == 0 ? checkout : reFormatDate(document.getElementById(checkoutId).value);

    //get calendar seleted month
    var checkinCalPage = checkin.substr(0, 2) + checkin.substr(5, 5);
    var checkoutCalPage = checkout.substr(0, 2) + checkout.substr(5, 5);

    // setup checkin calendar
    var checkinCal = new YAHOO.widget.CalendarGroup("checkinCal", checkinCalId,
                                                { pages: numOfCal,
                                                    mindate: earlyMindate,
                                                    maxdate: theMaxdate,
                                                    navigator: true
                                                });
    checkinCal.cfg.setProperty("pagedate", checkinCalPage, false);
    checkinCal.cfg.setProperty("selected", checkinSelection + ", " + checkoutSelection, false);

    //add international features
    checkinCal.cfg.setProperty("MONTHS_LONG", monthsLong);
    checkinCal.cfg.setProperty("WEEKDAYS_SHORT", weekdaysShort);
    checkinCal.cfg.setProperty("MY_LABEL_YEAR_POSITION", myLabelYearPosition);
    checkinCal.cfg.setProperty("MY_LABEL_MONTH_POSITION", myLabelMonthPosition);
    checkinCal.cfg.setProperty("MY_LABEL_YEAR_SUFFIX", myLabelYearSuffix);
    checkinCal.cfg.setProperty("MY_LABEL_MONTH_SUFFIX", myLabelMonthSuffix);
    checkinCal.render();

    //set the input field as the calendar trigger        
    var checkinShow = document.getElementById(checkinId);
    YAHOO.util.Event.addListener(checkinShow, "click", checkinCal.show, checkinCal, true);

    //handle calendar select event
    checkinCal.selectEvent.subscribe(checkinHandleSelect, checkinCal, true);
    checkinCal.hide();

    function checkinHandleSelect(type, args, obj) {
        var dates = args[0];
        var date = dates[0];
        var year = date[0], month = dateFormat(date[1]), day = dateFormat(date[2]);
        var checkinDate = year + "-" + month + "-" + day;
        checkinSelection = month + "/" + day + "/" + year;
        document.getElementById(checkinId).value = checkinDate;
        document.getElementById("checkinValue").value = checkinDate;
        document.getElementById("checkoutValue").value = document.getElementById(checkoutId).value;
        checkinCal.hide();

        //update checkout calendar start month according to checkin date
        checkinCalPage = date[1] + "/" + year;
        checkoutCal.cfg.setProperty("pagedate", checkinCalPage, false);

        //update checkout calendar highlight dates
        if (document.getElementById(checkoutId).value != 0) {
            checkoutSelection = reFormatDate(document.getElementById(checkoutId).value);
        }
        checkinCal.cfg.setProperty("selected", checkinSelection + ", " + checkoutSelection, false);
        checkoutCal.cfg.setProperty("selected", checkinSelection + ", " + checkoutSelection, false);
        checkinCal.render();
        checkoutCal.render();
    }

    // setup checkout calendar    
    var checkoutCal = new YAHOO.widget.CalendarGroup("checkoutCal", checkoutCalId,
                                                { pages: numOfCal,
                                                    mindate: theMindate,
                                                    maxdate: theMaxdate,
                                                    navigator: true
                                                });
    checkoutCal.cfg.setProperty("pagedate", checkoutCalPage, false);
    checkoutCal.cfg.setProperty("selected", checkinSelection + ", " + checkoutSelection, false);

    //add international features 
    checkoutCal.cfg.setProperty("MONTHS_LONG", monthsLong);
    checkoutCal.cfg.setProperty("WEEKDAYS_SHORT", weekdaysShort);
    checkoutCal.cfg.setProperty("MY_LABEL_YEAR_POSITION", myLabelYearPosition);
    checkoutCal.cfg.setProperty("MY_LABEL_MONTH_POSITION", myLabelMonthPosition);
    checkoutCal.cfg.setProperty("MY_LABEL_YEAR_SUFFIX", myLabelYearSuffix);
    checkoutCal.cfg.setProperty("MY_LABEL_MONTH_SUFFIX", myLabelMonthSuffix);
    checkoutCal.render();

    //set the input field as the calendar trigger
    var checkoutShow = document.getElementById(checkoutId);
    YAHOO.util.Event.addListener(checkoutShow, "click", checkoutCal.show, checkoutCal, true);

    //handle calendar select event
    checkoutCal.selectEvent.subscribe(checkoutHandleSelect, checkoutCal, true);
    checkoutCal.hide();

    function checkoutHandleSelect(type, args, obj) {
        var dates = args[0];
        var date = dates[0];
        var year = date[0], month = dateFormat(date[1]), day = dateFormat(date[2]);
        var checkoutDate = year + "-" + month + "-" + day;
        checkoutSelection = month + "/" + day + "/" + year;
        document.getElementById(checkoutId).value = checkoutDate;
        document.getElementById("checkinValue").value = document.getElementById(checkinId).value;
        document.getElementById("checkoutValue").value = checkoutDate;

        //update checkout calendar highlight dates
        if (document.getElementById(checkinId).value != 0) {
            checkinSelection = reFormatDate(document.getElementById(checkinId).value);
        }
        checkinCal.cfg.setProperty("selected", checkinSelection + ", " + checkoutSelection, false);
        checkoutCal.cfg.setProperty("selected", checkinSelection + ", " + checkoutSelection, false);
        checkinCal.render();
        checkoutCal.render();

        checkoutCal.hide();
    }

    //hide calendar when user click anywhere outside the calendar
    function hideDiv(e) {
        var target = (e ? e.target : event.srcElement);
        var checkinCalDiv = document.getElementById(checkinCalId);
        var checkinDiv = document.getElementById(checkinId);
        var checkoutCalDiv = document.getElementById(checkoutCalId);
        var checkoutDiv = document.getElementById(checkoutId);
        if (checkinCalDiv != null && checkinDiv != null && checkoutCalDiv != null && checkoutDiv != null) {
            (isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
            (isChild(target, checkoutCalDiv) || target == checkoutDiv) ? null : checkoutCalDiv.style.display = 'none';
        }

        //if it is hotel page, set additional visibility control for the calendars on rate tab
        if (document.getElementById("detailTabCheckin") != null || document.getElementById("rateTabCheckin") != null) {
            hideHotelDiv(e)
            hideRateDiv(e)
        }

        //if it is city page, set additional visibility control for both calendars
        if (document.getElementById("popupCheckin") != null) {
            hideHotelDiv(e)
            //hidePopupDiv(e)
        }
    }
    document.onclick = hideDiv
}

// visibility control for hotel.aspx page rate tab first calendar and city.aspx first calendar
function hideHotelDiv(e) {
    var target = (e ? e.target : event.srcElement);
    var checkinCalDiv = document.getElementById("checkinCalContainer");
    var checkinDiv = document.getElementById("hotelCheckin");
    var checkoutCalDiv = document.getElementById("checkoutCalContainer");
    var checkoutDiv = document.getElementById("hotelCheckout");
    if (checkinCalDiv != null && checkinDiv != null && checkoutCalDiv != null && checkoutDiv != null) {
        (isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
        (isChild(target, checkoutCalDiv) || target == checkoutDiv) ? null : checkoutCalDiv.style.display = 'none';
    }
}
// visibility control for hotel.aspx page rate tab second calendar.
function hideRateDiv(e) {
    var target = (e ? e.target : event.srcElement);
    var checkinCalDiv = document.getElementById("rateTabCheckinCalContainer");
    var checkinDiv = document.getElementById("rateTabCheckin");
    var checkoutCalDiv = document.getElementById("rateTabCheckoutCalContainer");
    var checkoutDiv = document.getElementById("rateTabCheckout");
    if (checkinCalDiv != null && checkinDiv != null && checkoutCalDiv != null && checkoutDiv != null) {
        (isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
        (isChild(target, checkoutCalDiv) || target == checkoutDiv) ? null : checkoutCalDiv.style.display = 'none';
    }
}
// visibility control for city.aspx page popup calendar.
function hidePopupDiv(e) {
    var target = (e ? e.target : event.srcElement);
    var checkinCalDiv = document.getElementById("popupCheckinCalContainer");
    var checkinDiv = document.getElementById("popupCheckin");
    var checkoutCalDiv = document.getElementById("popupCheckoutCalContainer");
    var checkoutDiv = document.getElementById("popupCheckout");
    if (checkinCalDiv != null && checkinDiv != null && checkoutCalDiv != null && checkoutDiv != null) {
        (isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
        (isChild(target, checkoutCalDiv) || target == checkoutDiv) ? null : checkoutCalDiv.style.display = 'none';
    }
}

//change date format from yyyy-mm-dd to mm/dd/yyyy
function reFormatDate(date) {
    var year = date.substr(0, 4);
    var month = date.substr(5, 2);
    var day = date.substr(8, 2);
    return month + "/" + day + "/" + year;
}

function dateFormat(date) {
    return date.toString().length == 1 ? "0" + date : date;
}

//check if child is a childNode of parent
function isChild(child, parent) {
    while (child) {
        if (child == parent)
            return true;
        child = child.parentNode;
    }
    return false;
}
/***************** End of yahoo calendar ************************/


/********************** dropdown checkin box **********************/
//changes departure month when arrival month is changed
function checkinUpdated() {

    inM = document.getElementById("checkinMonth");
    inD = document.getElementById("checkinDay");
    outM = document.getElementById("checkoutMonth");
    outD = document.getElementById("checkoutDay");

    var res = adjustDate(inM.options.selectedIndex, inD);
    if (res != 0) {
        outD.options.selectedIndex = 0;
        if (inM.options.selectedIndex == 11) {
            outM.options.selectedIndex = 0
        } else if (res == 4) {
            outM.options.selectedIndex = inM.options.selectedIndex + 1;
            outD.options.selectedIndex = 0;
        } else {
            outM.options.selectedIndex = inM.options.selectedIndex + 1;
            outD.options.selectedIndex = 1;
        }
    } else {
        outM.options.selectedIndex = inM.options.selectedIndex;
        if (outD.options.selectedIndex <= inD.options.selectedIndex) {
            outD.options.selectedIndex = inD.options.selectedIndex + 2;
        }
    }

    var checkinMonth = inM.options[inM.selectedIndex].value * 1;
    var checkinDay = inD.options[inD.selectedIndex].value * 1;
    var checkoutMonth = outM.options[outM.selectedIndex].value * 1;
    var checkoutDay = outD.options[outD.selectedIndex].value * 1;
    document.getElementById("checkinValue").value = getYear(inM.selectedIndex) + "-" + checkinMonth + "-" + checkinDay;
    document.getElementById("checkoutValue").value = getYear(outM.selectedIndex) + "-" + checkoutMonth + "-" + checkoutDay;
    return;
}

function checkoutUpdated() {
    outM = document.getElementById("checkoutMonth");
    outD = document.getElementById("checkoutDay");
    adjustDate(outM.options.selectedIndex, outD);

    var checkoutMonth = outM.options[outM.selectedIndex].value * 1;
    var checkoutDay = outD.options[outD.selectedIndex].value * 1;
    document.getElementById("checkoutValue").value = getYear(outM.selectedIndex) + "-" + checkoutMonth + "-" + checkoutDay;
    return;
}

function isLeapYear(yrStr) {
    var leapYear = false;
    var year = parseInt(yrStr, 10);
    // every fourth year is a leap year
    if (year % 4 == 0) {
        leapYear = true;
        // unless it's a multiple of 100
        if (year % 100 == 0) {
            leapYear = false;
            // unless it's a multiple of 400
            if (year % 400 == 0) {
                leapYear = true;
            }
        }
    }
    return leapYear;
}


function getDaysInMonth(mthIdx, YrStr) {
    // all the rest have 31
    var maxDays = 31
    // expect Feb. (of course)
    if (mthIdx == 1) {
        if (isLeapYear(YrStr)) {
            maxDays = 29;
        } else {
            maxDays = 28;
        }
    }

    // thirty days hath...
    if (mthIdx == 3 || mthIdx == 5 || mthIdx == 8 || mthIdx == 10) {
        maxDays = 30;
    }
    return maxDays;
}

function getYear(mthIdx) {
    var today = new Date()
    var theYear = parseInt(today.getFullYear())

    if (mthIdx < today.getMonth()) {
        theYear = (parseInt(today.getFullYear()) + 1)
    }

    return theYear
}

// do not allow selection of days that are not valid
// return non-zero if it is the last day of the month
function adjustDate(mthIdx, Dt) {
    var value = 0;
    var theYear = getYear(mthIdx)
    var numDays = getDaysInMonth(mthIdx, theYear);

    if (mthIdx == 1) {
        if (Dt.options.selectedIndex + 2 < numDays) {
            return 0;
        } else {
            if (Dt.options.selectedIndex + 1 > numDays) {
                Dt.options.selectedIndex = numDays - 1;
            }
            //check for leap year
            if ((Dt.options.selectedIndex + 1) == numDays) {
                return 1;
            } else {
                return 4;
            }
        }
    }

    if (Dt.options.selectedIndex + 2 < numDays) {
        value = 0;
    } else {
        if (Dt.options.selectedIndex + 1 > numDays) {
            Dt.options.selectedIndex--;
            value = 3;
        } else if (Dt.options.selectedIndex + 1 == numDays) {
            //index is 31 or 30
            value = 2;
        } else {
            value = 4;
        }
    }
    return value;
}
/********************** end of dropdown checkin box **********************/

function over(o) {
    o.className = "list listMouseover";
}

function out(o) {
    o.className = "list";
}

function SetStarValue(qString, starElement, starName) {
    if (starElement == null || starElement.checked) {
        return remQStringName(qString, starName);
    }
    else {
        return setQStringName(qString, starName, new Array("false"))
    }
}

function CreateHttpRequest() {
    var request;

    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
            }
        }
    }
    return request
}



function OpenReviews(hotelId, pageIndex, numberOfReviews, languageCode) {
    window.open('/Reviews.aspx?hotelId=' + hotelId + '&pageIndex=' + pageIndex + '&numberOfReviews=' + numberOfReviews + '&languageCode=' + languageCode, "reviews", "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1,width=600")
}

function Jsl(location, languagecode) {
    var str = '';
    if (location == 'p')
        str = '/AboutUs/Privacy.aspx';
    else
        str = '/AboutUs/TermsOfUse.aspx';

    if (languagecode.length > 0)
        str = str + '?languageCode=' + languagecode;

    window.location = str;
}





function onFocus(f, def) {
    var w = document.getElementById(f);
    if (w.value == def) {
        w.value = "";
    }
    w.style.color = "";
}

function onBlur(f, def) {
    var w = document.getElementById(f);
    if (w.value.length == 0 || w.value == def) {
        w.style.color = "gray";
        w.value = def;
    }
    else {
        w.style.color = "";
    }
}

function outM(email) {
    document.write(ReverseString(email));
}

function AffiliateClick(requestUrl, friendlyUrl) {
    var expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 365);

    document.cookie = 'AffiliateClickIDBefore=true;expires=' + expiryDate.toGMTString();

    var img = new Image();
    img.src = "/" + "AffiliateClick" + "." + "ashx?requestUrl=" + requestUrl + "&friendlyUrl=" + friendlyUrl + "&random=" + Math.random().toString();

    document.cookie = 'AffiliateClickIDAfter=true;expires=' + expiryDate.toGMTString();
}

function checkStarAnyChanged() {
    if (document.getElementById('M_C_Star1').checked) {
        document.getElementById('M_C_Star2').checked = true;
        document.getElementById('M_C_Star3').checked = true;
        document.getElementById('M_C_Star4').checked = true;
        document.getElementById('M_C_Star5').checked = true;
    }
}

function checkStarChanged() {
    if (document.getElementById('M_C_Star2').checked == false || document.getElementById('M_C_Star3').checked == false || document.getElementById('M_C_Star4').checked == false || document.getElementById('M_C_Star5').checked == false) {
        document.getElementById('M_C_Star1').checked = false;
    }
}

function showHotel(fileName, languageCode, tabId) {
    var qString = "";
    qString = setQStringName(qString, "fileName", new Array(fileName))
    qString = setQStringName(qString, "languageCode", new Array(languageCode))
    qString = setQStringName(qString, "tabId", new Array(tabId))

    window.open("/Hotel.aspx?" + qString, "_blank");
}

function sponsoredLink() {
    window.open("http://services.google.com/feedback/online_hws_feedback").focus();
}

function displayNone(id) {
    document.getElementById(id).style.display = "none";
}

function displayBlock(id) {
    document.getElementById(id).style.display = "";
}

function changeRateSearch(id) {
    document.getElementById(id).style.display = "";
    document.getElementById('changeRateSearchSpen').style.display = "none";
    document.getElementById('M_C_RatesSearchInfoBottom').style.display = "none";
    document.getElementById('M_C_RatesSearchInfoTop').style.display = "inline";
}

//Progress Bar
var progIndex
function progress() {
    document.getElementById("progressDiv").style.width = (progressBarSecond * 10) + "px";
    document.getElementById("inProgressDiv").innerHTML = "";
    document.getElementById("outProgressDiv").style.width = 0;

    progIndex = 0;
    progressBar();
}

function progressBar() {
    if (progIndex <= (progressBarSecond * 10)) {
        if (progIndex > 40) {
            document.getElementById("inProgressDiv").innerHTML = parseInt(progIndex / (progressBarSecond / 10)) + "%";
        }

        document.getElementById("outProgressDiv").style.width = progIndex + "px";
        setTimeout("progressBar();", 100);
        progIndex++;
    }
}

//round a number to certain decimal points
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function robotCheck() {
    document.write("<input type='hidden'" + "name='isrobot'" + " value='false'/>")
}

function cleanArray(array) {
    for (var i = array.length - 1; i >= 0; i--) {
        array.splice(i, 1);
    }
    return array;
};

function leftTrim(str, cha) {
    while (str.substring(0, 1) == cha) {
        str = str.substring(1, str.length);
    }
    return str;
}

