﻿/// <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 currentRateTabId = "rateViewSimple";
var mapAlreadyShown = false;
var gSearching = 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 JSObfuscateURL(url) {
    return ReverseString(url);
}

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();
}


function changeLanguage(name, val) {
    var qString = location.search.substr(1);
    qString = AppendFilename(qString);

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

    //Pass across the page size if available
    var pageSize = $("#pageSize");
    if (pageSize.length == 1) {
        qString = setQStringName(qString, "pageSize", [pageSize[0].value])
    }

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

    //Remove customFileName
    qString = remQStringName(qString, 'fileNameType');
    if (typeof gCityFileName != "undefined") {
        qString = setQStringName(qString, "fileName", [gCityFileName]);
    }

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

    return false;
}

function AppendFilename(qString) {

    if (!qString) return query;
    if (qString.indexOf("fileName") == -1) {
        return qString + "&" + query;
    } else {
        return qString;
    }
}

//reload page with the new querystring name-value pair
function Reload(name, val) {

    var qString = location.search.substr(1)
    qString = AppendFilename(qString);

    //Change the currency in the returnPath as well
    if (name == "currencyCode") {
        var returnPath = GetQSVal("returnPath");
        if (returnPath) {
            returnPath = remQStringName(returnPath, "currencyCode");
            returnPath = setQStringName(returnPath, "currencyCode", [val]);
            returnPath = remQStringName(returnPath, "lowRate");
            returnPath = remQStringName(returnPath, "highRate");
            qString = remQStringName(qString, "returnPath");
            qString = setQStringName(qString, "returnPath", [returnPath]);
        }
    }


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

    //Pass across the page size if available
    var pageSize = $("#pageSize");
    if (pageSize.length == 1) {
        qString = setQStringName(qString, "pageSize", [pageSize[0].value])
    }

    qString = setQStringName(qString, name, new Array(val.toString()))
    qString = setQStringName(qString, "tabId", new Array(currentTabId.toString()))
    qString = setQStringName(qString, "rateTabId", new Array(currentRateTabId.toString()))
    qString = remQStringName(qString, "scroll");
    //Remove customFileName
    qString = remQStringName(qString, 'fileNameType');
    if (typeof gCityFileName != "undefined") {
        qString = setQStringName(qString, "fileName", [gCityFileName]);
    }

    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) {

    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 site Hotelplanner.com to search for more rooms?' : JavaScriptSearchMoreRoom);
        if (r == true) {
            window.open("/ProviderRedirect.aspx?key=" + gHotelPlannerLink, "_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, " "))
    return decodeURIComponent(urlStr);
}

//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 += "&" + encodeURIComponent(name) + "=" + encodeURIComponent(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, options) {

    if (gSearching) return false;

    options = options || {};
    var redirection;
    var affiliateParam;
    var brandParam;
    var host;
    var locationParam = "";
    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;
                // If Location supplied by autosuggest
                var locationID = document.getElementById("selectedLocationID").value;
                if (locationID && !isNaN(locationID)) {
                    locationParam = "&locationId=" + locationID + "&sort=Distance-asc";
                }
            }
        }
    }
    city = encodeURIComponent(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=" + encodeURIComponent(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=" + encodeURIComponent(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=" + encodeURIComponent(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 + locationParam;

    }

    //Show the searching image
    if (options.changeClass && options.searchButton) {
        $(options.searchButton).removeClass(options.changeClass[0]).addClass(options.changeClass[1]);
    }

    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;
    }

    if (options.append) redirection += options.append;
    redirection = host + redirection;

    gSearching = true;
    switch (target) {
        case "_blank":
            gSearching = false;
            window.open(redirection).focus();
            break;
        case "_parent":
            window.parent.location = redirection;
            break;
        case "_top":
            window.top.location = redirection;
            break;
        default:
            setTimeout(function() { window.location = redirection; }, 10);  // _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');

/********************************* Language Flags ********************************************/
function addLanguageFlags(flagDomain, languageCode) {
    var flag = "<ul id=\"languageUl\" style=\"display:none\"  >";
    flag += addFlag("EN", flagDomain, languageCode);
    flag += addFlag("DE", flagDomain, languageCode); // German
    flag += addFlag("ES", flagDomain, languageCode); // Spanish
    flag += addFlag("FR", flagDomain, languageCode); // French
    flag += addFlag("IT", flagDomain, languageCode); // Italian
    flag += addFlag("CS", flagDomain, languageCode); // Chinese Simplified
    flag += addFlag("CN", flagDomain, languageCode); // Chinese Traxditional
    flag += addFlag("JA", flagDomain, languageCode); // Japanese
    flag += addFlag("KO", flagDomain, languageCode); // Korean
    flag += addFlag("PT", flagDomain, languageCode); // Portugues
    flag += addFlag("EL", flagDomain, languageCode); // Greek
    flag += addFlag("RO", flagDomain, languageCode); // Romanian
    flag += addFlag("RU", flagDomain, languageCode); // Russian
    flag += addFlag("NL", flagDomain, languageCode); // Dutch
    flag += "</ul>";
    $('#languageFlag').html(flag);
    $('#languageUl').show();
    document.onmousedown = hideLauguageFlag;
}
function addFlag(flagCode, flagDomain, languageCode) {
    if (flagCode == languageCode) {
        return "<li><div><a><img src=\"" + flagDomain + "/Images/flags/" + flagCode + "-w.gif\" /></a></div></li>";
    }
    else {
        return "<li><div><a href=\"javascript:changeLanguage('languageCode', '" + flagCode + "'); displayNone('languageUl');\"><img src=\"" + flagDomain + "/Images/flags/" + flagCode + "-w.gif\" /></a></div></li>";
    }
}
// visibility control for hotel.aspx page rate tab first calendar and city.aspx first calendar
function hideLauguageFlag(e) {
    var target = (e ? e.target : event.srcElement);
    var flagUl = document.getElementById("languageUl");
    var flagSelected = document.getElementById("selected");
    if (flagUl != null && flagSelected != null) {
        (isChild(target, flagUl) || isChild(target, flagSelected)) ? null : flagUl.style.display = 'none';
    }
}

//add flags for pages in Widgets folder, can be removed after update Widgets files
function showLanguageFlags(flagDomain, languageCode, currentUrl) {
    var flag = "<ul id=\"languageUl\" style=\"display:none\">";
    flag += addFlagLink("EN", flagDomain, languageCode, currentUrl);
    flag += addFlagLink("DE", flagDomain, languageCode, currentUrl); // German
    flag += addFlagLink("ES", flagDomain, languageCode, currentUrl); // Spanish
    flag += addFlagLink("FR", flagDomain, languageCode, currentUrl); // French
    flag += addFlagLink("IT", flagDomain, languageCode, currentUrl); // Italian
    flag += addFlagLink("CS", flagDomain, languageCode, currentUrl); // Chinese Simplified
    flag += addFlagLink("CN", flagDomain, languageCode, currentUrl); // Chinese Traxditional
    flag += addFlagLink("JA", flagDomain, languageCode, currentUrl); // Japanese
    flag += addFlagLink("KO", flagDomain, languageCode, currentUrl); // Korean
    flag += addFlagLink("PT", flagDomain, languageCode, currentUrl); // Portugues
    flag += addFlagLink("EL", flagDomain, languageCode, currentUrl); // Greek
    flag += addFlagLink("RO", flagDomain, languageCode, currentUrl); // Romanian
    flag += addFlagLink("RU", flagDomain, languageCode, currentUrl); // Russian
    flag += addFlagLink("NL", flagDomain, languageCode, currentUrl); // Dutch         
    flag += "</ul>";
    $('#languageFlag').html(flag);
    $('#languageUl').show();
    document.onmousedown = hideLauguageFlag;
}
function addFlagLink(flagCode, flagDomain, languageCode, currentUrl) {
    if (flagCode == languageCode) {
        return "<li><div><a><img src=\"" + flagDomain + "/Images/flags/" + flagCode + "-w.gif\" /></a></div></li>";
    }
    else {
        return "<li><div><a href=\"javascript:Reload('languageCode', '" + flagCode + "'); displayNone('languageUl');\"><img src=\"" + flagDomain + "/Images/flags/" + flagCode + "-w.gif\" /></a></div></li>";
    }
}
/************************************End of Language Flags **********************************************/

//Custom function to turn strings into ellipsis
String.prototype.ellipsisString = function(length) {

    var result = this;
    if (this.length > length + 1) {
        result = result.substring(0, length);
        result = result.substring(0, result.lastIndexOf(' '));
        var lastChar = result.charAt(result.length - 1);
        if (lastChar == "." || lastChar == "," || lastChar == "-") {
            if (result.length > 1) {
                result = result.substring(0, result.length - 1);
            }
        }
        return result + "...";
    } else {
        return this;
    }

    return this + length;
}


//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;
        var checkinDate = day + "/" + month + "/" + year;
        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;
        var checkoutDate = day + "/" + month + "/" + year;
        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
    this.hideDiv = function(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);

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

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";
}

//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;
}

// Updated By: Daniel
// Update Date: 20/07/2009
// Added a centerOffset option and an absoluteY option.
// Options:
//  options.sorting - boolean - true to show sorting
//  options.paging - boolean - true to show paging
//  options.loading - boolean - true to show loading
//  options.loadingHotel - boolean - true to show loading hotel
//  options.absoluteY - Puts the popup in an absoluteY position of the value.
//  options.centerOffset - Adds the offset to the center calculation.
function DisplayFiltering(options) {

    options = options || {};
    $("#filterDiv").remove();
    var text = "";
    if (options.sorting) {
        text = typeof (citySearchPageSortingResults) == 'undefined' ? 'Sorting Results...' : citySearchPageSortingResults;
    } else if (options.paging) {
        text = typeof (citySearchPageLoadingResults) == 'undefined' ? 'Loading Page...' : citySearchPageLoadingPage;
    } else if (options.loading) {
        text = typeof (citySearchPageLoadingResults) == 'undefined' ? 'Loading Results...' : citySearchPageLoadingResults;
    } else if (options.loadingHotel) {
        text = typeof (citySearchPageLoadingHotel) == 'undefined' ? 'Loading Hotel...' : citySearchPageLoadingHotel;
    } else {
        text = typeof (cityPageFilteringResults) == 'undefined' ? 'Filtering Results...' : cityPageFilteringResults;
    }

    //Setup filter    
    var filterDiv = $('<div id="filterDiv" class="filterDiv"><div id="filterText">' + text + '</div></div>');
    filterDiv.remove().appendTo("body").show();

    var filterWidth = filterDiv.width();
    var windowWidth = $(window).width();
    var scrollTop = $(window).scrollTop();
    var centerOffset = options.centerOffset === undefined ? 0 : options.centerOffset;
    var centerPosition = (windowWidth / 2 - (filterWidth / 2)) + centerOffset;
    var topPosition = options.absoluteY === undefined ? scrollTop + 300 : options.absoluteY;
    var leftPosition = options.absoluteCenter === undefined ? centerPosition - 15 : options.absoluteCenter - (filterWidth / 2);
    filterDiv.css({ left: leftPosition + "px", top: topPosition + "px" });


    var filterText = $("#filterText", filterDiv);
    var top = filterDiv.height() / 2 - (filterText.height() / 2);
    var left = filterDiv.width() / 2 - (filterText.width() / 2);
    filterText.css({ "top": top + "px", "left": left + "px" });
}

function HideFiltering() {
    $("#filterDiv").hide();
}

//Write out a hidden or visible div
function writeDivVisibleHidden(id, hidden) {

    var div = '<di' + 'v ';
    div += 'id="' + id + '"';
    div += ' class="obsfucated"';
    if (hidden) {
        div += ' style="display:none;"';
    }
    div += "/>";
    document.write(div);
}

//Close said div
function closeDiv() {
    document.write('</di' + 'v>');
}

//Toggle the currently selected category
function showTopDestinationCategory(myObj, categoryId) {
    //Hide the existing category and highlight the correct category heading
    myObj = $(myObj.parentNode);
    myObj.siblings(".selected").removeClass("selected");
    myObj.addClass("selected");
    $("#homeTopDestinations").find(".obsfucated").hide();
    $("#categoryList_" + categoryId).show();
}
