﻿/// <reference path="jquery.js" />
/// <reference path="jquery-vsdoc.js" />

// initialise HC namespaces..
if (typeof(HC) == "undefined") {
    HC = {};
}

// initialise global variables..
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) {
        if (query != "") {
            return qString + "&" + query;
        } else {
            return qString;
        }
    } 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(containerId, select) {
    document.getElementById(containerId + '_GuestValue').value = select.options[select.selectedIndex].value;
    return false;
}

function setRoomValue(containerId, select) {
    
    if (select.value == "5") {
        select.selectedIndex = 0;
        var r = confirm(typeof (JavaScriptSearchMoreRoom) == 'undefined' ? 'ToplaBavulu.com ile aynı anda 4 oda için arama yapabilirsiniz, daha fazla oda için iş ortağımız olan Hotelplanner.com sitesine yönlendirilmek ister misiniz?' : JavaScriptSearchMoreRoom);
        if (r == true) {
            window.open("http://www.otel.toplabavulu.com/ProviderRedirect.aspx?key=" + gHotelPlannerLink, "_self");
            return false;
        }
    }
    else {
        document.getElementById(containerId + '_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 = Date.fromString(document.getElementById(calendar1Id).value, ShortDatePatternVariable);
    var outDate = Date.fromString(document.getElementById(calendar2Id).value, ShortDatePatternVariable);
    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 DoHomePageSearch(languageCode, target, affiliateId, city, domain, brandId, options, containerId) {

    var calendar1Id = containerId + '_Checkin';
    var calendar2Id = containerId + '_Checkout';
    
    if (gSearching) return false;
    
    options = options || {};
    var redirection;
    var affiliateParam;
    var brandParam;
    var host;
    var locationParam = "";  
    var isAutoComplete = false;

    if (document.getElementById(calendar1Id) != null) {
        if (document.getElementById(calendar1Id).value == 0 || document.getElementById(calendar2Id).value == 0) {
            alert(typeof (JavaScriptEnterCheckinCheckout) == 'undefined' ? 'Please enter your checkin and checkout date.' : JavaScriptEnterCheckinCheckout)
            return false
        }
    }

    if (!ValidateCalendarDates(calendar1Id, calendar2Id)) {
        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;
    }

    //convert dates from localized format to default one
    checkinValue = formatDate(Date.fromString(document.getElementById(calendar1Id + "Value").value, ShortDatePatternVariable), DefaultShortDatePatternVariable);
    checkoutValue = formatDate(Date.fromString(document.getElementById(calendar2Id + "Value").value, ShortDatePatternVariable), DefaultShortDatePatternVariable);
    
    //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 = "http://www.otel.toplabavulu.com/Search.aspx?search=" + city + "&checkin=" + checkinValue + "&checkout=" + checkoutValue + "&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 {
        
        var searchTermType = document.getElementById("selectSearchTermType").value;
        redirection = "http://www.otel.toplabavulu.com/SearchTermTypeRedirection.ashx?fileName=" + document.getElementById("selectedFileName").value + "&checkin=" + checkinValue + "&checkout=" + checkoutValue + "&languageCode=" + languageCode + affiliateParam + brandParam + defaultSort + locationParam + "&sttype=" + searchTermType;                
    }

    //Show the searching image
    if (options.changeClass && options.searchButton) {
        $(options.searchButton).removeClass(options.changeClass[0]).addClass(options.changeClass[1]);
    }
    var inputIdParts = calendar1Id.split('_');
    var containerId = inputIdParts[0];
    var guestsEl =document.getElementById(containerId + "_GuestsValue")  ;
    var roomsEl = document.getElementById(containerId + "_RoomsValue");
    redirection += guestsEl == null ? "" : "&Adults=" + guestsEl.value;
    redirection += roomsEl == null ? "" : "&Rooms=" + roomsEl.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) {           
        for (var i = 1; i <= facilityCount; i++) {
            if (document.getElementById("M_C_HotelFacility" + i).checked) {
                var facilityId = $("#M_C_HotelFacility" + i).parent()[0].attributes["faclityId"].value;
                facility += facilityId + ",";
            }
        }
        if (facility != "") {
            var strLen = facility.length;
            facility = facility.slice(0, strLen - 1);
            redirection += "&facilities=" + facility;
        }
    }
    
    //Add disable access (Don't care about the facility above
    //As this should never happen on our site)
    if (HC.disabilityEnabled) {
        redirection += "&facilities=10";
    }
    
    // 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 = "http://www.otel.toplabavulu.com/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 + "http://www.otel.toplabavulu.com/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;
}

// 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();
}


// Namespace for common elements.
HC.Common = {
    GenerateQueryString: function(options) {
        options = options || {};
        var qString = "";
        qString = $.param(this.fields);

        if (options.excludeFilename) {
            qString = remQStringName(qString, "fileName");
            qString = remQStringName(qString, "fileType");
        }

        //Remove unwanted parameters
        qString = remQStringName(qString, "currencySymbol");
        qString = remQStringName(qString, "currentPage");

        return qString;
    },

    FloorPrice: function(price) {
        return Math.floor(price / 10) * 10;
    },

    CeilPrice: function(price) {
        return Math.ceil(price / 10) * 10;
    },
    
    GetKey: function(e) {
        var key;
        if (window.event || !e.which) {
            key = e.keyCode;
        } else if (e) {
            key = e.which;
        }
        var keyChar = String.fromCharCode(key);
        return { "key": key, "keyChar": keyChar };
    },
    
    langSwitch: function(e, o) {
        changeLanguage('languageCode', o.options[o.options.selectedIndex].value);
        return false;
    },

    currencySwitch: function (e, o) {
        
        //For Searchprogress page (trying to use the ajax version)
        if (typeof changeLanguageOriginal != "undefined") {
            changeLanguageOriginal("currencyCode", o.options[o.options.selectedIndex].value)
        } else if (HC.SR && HC.SR.Filter) {
            HC.SR.Filter.ChangeCurrency(o);
        } else {
            changeLanguage('currencyCode', o.options[o.options.selectedIndex].value);
        }

        return false;
    }
    
}




// Namespace for cookie handling.
HC.Common.Cookies = {
    cookies: Array(), // cached copy of previously added / fetched cookies.

    add: function(myKey, myValue, myPath, myExpiry) {
        if (document.cookie != null) {
            tmpCookie = "";
            if (myExpiry != null && myExpiry != "") {
                tmpCookie = myKey + "=" + encodeURIComponent(myValue) + "; expires=" + myExpiry + "; path=" + myPath;
            } else {
                tmpCookie = myKey + "=" + encodeURIComponent(myValue) + "; path=" + myPath;
            }
            document.cookie = tmpCookie;
            // add cookie to cache..
            HC.Common.Cookies.cookies[myKey] = tmpCookie;
        }
    },
    
    // retrieve cookie by key/name.  If useCache is true, then retrieve from cached value of this namespace if already fetched / added.
    getCookie: function(myKey, useCache) {
        if (document.cookie != null && document.cookie.length > 0) {
            if (useCache && this.cookies[myKey] != null) {
                return HC.Common.Cookies.cookies[myKey];
            } else {
                var start = document.cookie.indexOf(myKey + "=");
                if (start != -1) {
                    start = start + myKey.length + 1;
                    var end = document.cookie.indexOf(";", start);
                    if (end == -1) {
                        end = document.cookie.length;
                    }
                    return decodeURIComponent(document.cookie.substring(start, end));
                }
            }
        }
        return "";
    },

    // retrieves all cookies and adds to cache. nb. will override whatever is already in the cache for that cookie key.
    getAllCookies: function() {
        var cookies = {};
        if (document.cookie && document.cookie != '') {
            var split = document.cookie.split(';');
            for (var i = 0; i < split.length; i++) {
                var name_value = split[i].split("=");
                name_value[0] = name_value[0].replace(/^ /, '');
                cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
                HC.Common.Cookies.cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]); // cache cookie.
            }
        }
        return cookies;
    }

}

// Namespace for navigation, link handling and accessibility of links.
HC.Common.Navigation = {
    myWins: Array(),
    puQueue: Array(),
    puCookieQueue: Array(),

    // parses querystrings into hash array.
    parseQueryString: function(qs) {
        var result = {};
        if (qs == null || typeof (qs) == "undefined") {
            qs = location.search ? location.search : '';
        }
        if (qs.indexOf('?') > -1) {
            qs = qs.substring(qs.indexOf('?') + 1);
        }
        qs = qs.replace(/\+/g, ' ');
        var params = qs.split(/[;&]/g);
        for (var i = 0; i < params.length; i++) {
            // extract this component's key-value pairs
            var kvp = params[i].split('=');
            var key = decodeURIComponent(kvp[0]);
            var value = decodeURIComponent(kvp[1]);
            if (!result[key]) {
                result[key] = [];
            }
            result[key].push((kvp.length == 1) ? '' : value);
        }
        return result;
    },

    // adds new popunders to namespace.
    addPopUnder: function(myKey, myUrl, myCities) {
        HC.Common.Navigation.puQueue[myKey] = {};
        HC.Common.Navigation.puQueue[myKey].url = JSObfuscateURL(myUrl);
        //HC.Common.Navigation.puQueue[myKey].cities = eval('(' + myCities + ')');
        HC.Common.Navigation.puQueue[myKey].cities = myCities;
    },

    // removes a popunder from the namespace.
    removePopUnder: function(myKey) {
        HC.Common.Navigation.puQueue[myKey] = null;
        delete HC.Common.Navigation.puQueue[myKey];
    },

    // allows for text replacement of popunder urls with the myUpdates hash.
    updatePopUnderDetails: function(myUrl) {
        // setup updates..
        var myUpdates = Array();

        // parse querystring for search request as translations have already happened.
        var params = HC.Common.Navigation.parseQueryString(myUrl);

        // Get form values and associate to translation keys for popunder url modification.
        var temp = "";
        var tempStr = "";
        for (myKey in params) {
            switch (myKey) {
                case 'checkin':
                    tempStr = params[myKey] + "";
                    temp = tempStr.split("-");
                    myUpdates['{checkin_day}'] = temp[2];
                    myUpdates['{checkin_month}'] = temp[1];
                    myUpdates['{checkin_year}'] = temp[0];
                    break;
                case 'checkout':
                    tempStr = params[myKey] + "";
                    temp = tempStr.split("-");
                    myUpdates['{checkout_day}'] = temp[2];
                    myUpdates['{checkout_month}'] = temp[1];
                    myUpdates['{checkout_year}'] = temp[0];
                    break;
                case 'fileName':
                    myUpdates['{cityid}'] = params[myKey];
                    break;
            }
        }

        // for each pop under..
        for (myKey in HC.Common.Navigation.puQueue) {
            // check if popunder requires city translated to an appropriate identity..
            if (HC.Common.Navigation.puQueue[myKey].url.indexOf("{cityid}") > -1) {
                // yes, popunder requires city translation.
                // If popunder has cities translation list then change translation key: {cityid} to have value of match in translation list.
                if (HC.Common.Navigation.puQueue[myKey].cities[myUpdates['{cityid}']] != null) {
                    myUpdates['{cityid}'] = HC.Common.Navigation.puQueue[myKey].cities[myUpdates['{cityid}']];
                } else {
                    // not a valid city, so do not show popunder for this search..
                    // remove popunder from puQueue..
                    HC.Common.Navigation.removePopUnder(myKey); // remove the popunder from queue.
                    HC.Common.Navigation.removePopUnderCookie(myKey); // remove the associated cookie in cookie queue with it.
                }
            }
            // replace all patterns in url, if the popunder has not been removed..
            if (HC.Common.Navigation.puQueue[myKey] != null) {
                i = 0;
                for (myRegExp in myUpdates) {
                    i++;
                    HC.Common.Navigation.puQueue[myKey].url = HC.Common.Navigation.puQueue[myKey].url.replace(myRegExp, myUpdates[myRegExp]);
                }
                if (i <= 1) {
                    // issue with parsing, so fail this method.
                    return false;
                }
            }
        }
        return true;
    },

    // setup new coookies to namespace for pending popunders.
    addPopUnderCookie: function(myKey, myValue, myPath, myExpiry) {
        // jquery converts date, so no need to here. need to convert if jquery removed.
        HC.Common.Navigation.puCookieQueue[myKey] = {};
        HC.Common.Navigation.puCookieQueue[myKey].value = myValue;
        HC.Common.Navigation.puCookieQueue[myKey].path = myPath;
        HC.Common.Navigation.puCookieQueue[myKey].expiry = myExpiry; // expected as number of days.
    },

    // remove cookie from cookie queue.
    removePopUnderCookie: function(myKey) {
        if (HC.Common.Navigation.puCookieQueue[myKey] != null) {
            // found cookie to remove.
            HC.Common.Navigation.puCookieQueue[myKey] = null; // remove from length of associative array.
            delete HC.Common.Navigation.puCookieQueue[myKey]; // remove null element from array. (can't just do this without line above)
        } else {
            // cookie could be a child cookie of one of the cookies in the cookie queue.
            myKey2 = myKey.replace("([.+/-:*?^$])", "\\$1");
            var myExp = new RegExp("(" + myKey2 + "\\$[^\\|]*\\|)", "ig");
            //alert(myExp);
            var tmpResult = "";
            for (myCookieKey in HC.Common.Navigation.puCookieQueue) {
                tmpValue = decodeURIComponent(HC.Common.Navigation.puCookieQueue[myCookieKey].value);
                //alert("Searching this string: " + tmpValue);
                HC.Common.Navigation.puCookieQueue[myCookieKey].value = tmpValue.replace(myExp, "");
                //alert("new value = " + HC.Common.Navigation.puCookieQueue[myCookieKey].value);
            }
        }
    },

    // directs user to myUrl and caters for queued popunders (hash) to be opened in separate windows keeping current window focused.
    gotoPage: function(myUrl) {
        // update popunder details..
        if (HC.Common.Navigation.updatePopUnderDetails(myUrl)) {
            // setup popunders..
            myTop = 0;
            myLeft = 0;
            myHeight = 400;
            myWidth = 600;
            // display queued popunders.
            for (var myKey in HC.Common.Navigation.puQueue) {
                // update popunder url with search criteria..

                // open popunder..
                if (HC.Common.Navigation.puQueue[myKey].options != null) {
                    HC.Common.Navigation.myWins[myKey] = window.open("/pu.aspx?i=" + encodeURIComponent(HC.Common.Navigation.puQueue[myKey].url), myKey, HC.Common.Navigation.puQueue[myKey].options);
                } else {
                    myTop = myTop + 20;
                    myLeft = myLeft + 20;
                    myOptions = "width=" + myWidth + ",height=" + myHeight + ",top=" + myTop + ",left=" + myLeft + ",scrollbars=yes,menubar=yes,statusbar=yes,resizable=yes";
                    HC.Common.Navigation.myWins[myKey] = window.open("/pu.aspx?i=" + encodeURIComponent(HC.Common.Navigation.puQueue[myKey].url), myKey, myOptions);
                }
                window.focus(true);
            }
            // TODO: should check here to see if popunders were successful.
            HC.Common.Navigation.puQueue = Array(); // reset popunder queue.
            // try to add queued cookies..
            for (var myKey in HC.Common.Navigation.puCookieQueue) {
                HC.Common.Cookies.add(myKey, HC.Common.Navigation.puCookieQueue[myKey].value, HC.Common.Navigation.puCookieQueue[myKey].path, HC.Common.Navigation.puCookieQueue[myKey].expiry);
            }
            HC.Common.Navigation.puCookieQueue = Array(); // reset popunder cookie queue.
        }

        // navigate user window to myUrl location if provided.
        if (myUrl != null && myUrl != "") {
            location.href = myUrl;
        }
        return false;
    },

    // opens a new window (popup) and make it focused.
    newPage: function(key, myUrl) {
        var i = this.myWins.length;
        myWins[key] = window.open(myUrl, key);
        myWins[key].focus(true);
        return;
    }

}
function findPos(obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
    }
    return { x: curleft, y: curtop };
}

/* Best Price Guarantee popup */

function tooltipShow(sourceObj, tooltipElementId) {
    var tooltip = document.getElementById('tt1');
    var ttOverlay = document.getElementById('ttOverlay');
    var pos = findPos(sourceObj);
        
    tooltip.style.display = 'block';
    tooltip.style.top = (pos.y + 20) + "px";
    tooltip.style.left = (pos.x - 250) + "px";
        ttOverlay.style.display = 'block';
    ttOverlay.style.top = (pos.y + 20) + "px";
    ttOverlay.style.left = (pos.x - 250) + "px";
}
function tooltipHide(tooltipElementId) {
    var tooltip = document.getElementById('tt1');
    tooltip.style.display = 'none';
    var ttOverlay = document.getElementById('ttOverlay');
    ttOverlay.style.display = 'none';

}
function bestPriceGuaranteePopup() {
    tooltipHide('tt1');
    window.open('/BestPriceGuaranteePopup.aspx', '', 'toolbar=0,status=0,menubar=0,scrollbars ,width=400,height=500', true);

    }

   
    
/* Date Format Localization */
var MONTH_NAMES = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var DAY_NAMES = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
function LZ(x) { return (x < 0 || x > 9 ? "" : "0") + x }
/// ------------------------------------------------------------------
// formatDate (date_object, format)

// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date, format) {
    format = format + "";
    var result = "";
    var i_format = 0;
    var c = "";
    var token = "";
    var y = date.getFullYear() + "";
    var M = date.getMonth();
    var dw = date.getDay();
    var d = date.getDate();
    var yyyy, yy, MMM, MM, dd;
    // Convert real date parts into formatted versions
    var value = new Object();
    if (y.length < 4) { y = "" + (y - 0 + 1900); }
    value["y"] = "" + y;
    value["yyyy"] = y;
    value["yy"] = y.substring(2, 4); ;
    value["M"] = M + 1;
    value["MM"] = LZ(M + 1);
    value["MMM"] = Date.abbrMonthNames[M];
    value["MMMM"] = Date.monthNames[M];
    value["m"] = M + 1;
    value["mm"] = LZ(M + 1);
    value["mmm"] = Date.abbrMonthNames[M];
    value["mmmm"] = Date.monthNames[M];
    value["NNN"] = Date.monthNames[M + 11];
    value["d"] = d;
    value["dd"] = LZ(d);
    value["dddd"] = Date.dayNames[dw];


    while (i_format < format.length) {
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        if (value[token] != null) { result = result + value[token]; }
        else { result = result + token; }
    }
    return result;
}

/* End Date Format Localization */
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;
}

/************ Deals Box ******************/
HC.DealsBox = {
    dealsClicked: function (TableID, RefTableID) {
        var email = $("#emailAddressInput").val();
        var page = "/User/AddUserEmail.aspx?Email=" + encodeURIComponent(email) + "&TableID=" + TableID + "&RefTableID=" + RefTableID;
        window.open(page, "Deals", 'toolbar=0,status=0,menubar=0,scrollbars ,width=400,height=300');
        return false;
    },
    //Call back function from the open window
    addressValidated: function () {
        $("#emailAddressInput").val("");
    },

    //Privacy popup
    privacyPopup: function (languageCode) {
        var page = '/AboutUs/Privacy.aspx?PopUp=true';
        if (languageCode !== undefined) {
            page = page + '&languageCode=' + languageCode;
        }
        window.open(page, 'Privacy', 'toolbar=0,status=0,menubar=0,scrollbars ,width=1000,height=600');

        return false;
    }
}

/* bgiframe plugin for jquery - automatically adds iframe for hiding select boxes in layered elements in IE6
* Usage: $('#divWrapper').bgiframe(); // applies iframe beneath element with id = divWrapper.
*/
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
* $Rev: 2446 $
*
* Version 2.1.1
*/
$.fn.bgIframe = $.fn.bgiframe = function (s) {
    // This is only for IE6
    if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
        s = $.extend({
            top: 'auto', // auto == .currentStyle.borderTopWidth
            left: 'auto', // auto == .currentStyle.borderLeftWidth
            width: 'auto', // auto == offsetWidth
            height: 'auto', // auto == offsetHeight
            opacity: true,
            src: 'javascript:false;'
        }, s || {});
        var prop = function (n) { return n && n.constructor == Number ? n + 'px' : n; },
		html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' +
		            'style="display:block;position:absolute;z-index:-1;' +
			            (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') +
					    'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' +
					    'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' +
					    'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' +
					    'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' +
				'"/>';
        return this.each(function () {
            if ($('> iframe.bgiframe', this).length == 0)
                this.insertBefore(document.createElement(html), this.firstChild);
        });
    }
    return this;
};
/* end bgiframe plugin */

/************ Book Now Popup stuff *************/
var popId = "hc_popupSearch";
/*  Create the "PopUp" window   */
function createPop() {
    var width = "545px",
        height = "300px";

    // Create semi-transparent div to cover the screen
    e = document.createElement("div");
    e.id = "PopupTransparent";
    e.style.opacity = ".5";
    e.style.MozOpacity = ".5";
    e.style.KhtmlOpacity = ".5";  // older konqueror and safari
    e.style.filter = "alpha(opacity=50)";
    e.style.height = "100%";
    e.style.width = "100%";
    e.style.zIndex = "800";
    oContainer = document.body.appendChild(e);

    // if the document is longer than the screen height (it scrolls)
    if (getWindowHeight() + 24 > oContainer.offsetHeight) {
        e.style.height = (getWindowHeight() + 24) + "px";
    }

    // center the outside div within the viewable section of the document
    var left = (getWindowSize()[0] / 2) + getScrollXY()[0] - (getNumericPortion(width) / 2);
    var top = (getWindowSize()[1] / 2) - (getNumericPortion(height) / 2);
    e = document.getElementById(popId);
    e.style.height = height;
    e.style.width = width;
    e.style.left = left + "px";
    e.style.zIndex = "900";
    e.style.display = 'block';
    document.body.appendChild(e);

    // position of underlay iframe's parent
    var underlayParentPos = $("#hc_popupSearch").offset();

    // IE 7, mozilla, safari, opera 9    
    if (typeof document.body.style.maxHeight != "undefined") {
        e.style.position = 'fixed';
        e.style.top = top + "px";

        $(".chkPriceUnderlay").css({ top: underlayParentPos.top + 10, left: underlayParentPos.left, display: "block" });
    }
    // IE6, older browsers
    else {
        e.style.position = 'absolute';
        e.style.height = "450px";

        // 'fixed' position for IE6
        $(e).addClass('ie6fixed');

        // applying the same fix to underlay iframe
        $(".chkPriceUnderlay").addClass('ie6fixed');

        // not updating 'top' in this case, as 'ie6fixed' is taking care of it
        $(".chkPriceUnderlay").css({ left: underlayParentPos.left, display: "block" });

        // checkprice underlay fix for select boxes
        $("#PopupTransparent").bgIframe();
    }

}


function closePopUp() {
    e = document.getElementById("PopupTransparent");
    document.body.removeChild(e);
    document.getElementById(popId).style.display = 'none';

    $(".chkPriceUnderlay").css({ display: "none" });
    $(".hc_f_s_medLng").css({ display: "block" });
}  


jQuery.fn.hint = function (blurClass) {
    if (!blurClass) {
        blurClass = 'blur';
    }

    return this.each(function () {
        // get jQuery version of 'this'
        var $input = jQuery(this),

        // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = jQuery(this.form),
      $win = jQuery(window);

        function remove() {
            if ($input.val() === title && $input.hasClass(blurClass)) {
                $input.val('').removeClass(blurClass);
            }
        }

        // only apply logic if the element has the attribute
        if (title) {
            // on blur, set value to title attr if text is blank
            $input.blur(function () {
                if (this.value === '') {
                    $input.val(title).addClass(blurClass);
                }
            }).focus(remove).blur(); // now change all inputs to title

            // clear the pre-defined text when form is submitted
            $form.submit(remove);
            $win.unload(remove); // handles Firefox's autocomplete
        }
    });
};

$(function () {
    $("#emailAddressInput").hint();
});

