// initialise HC namespaces..
if (typeof (HC) == "undefined") {
    var HC = {};
}

// initialise global variables..
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 = " ";

HC.gSearching = false;
HC.currentTabId = "Details";
HC.currentRateTabId = "rateViewSimple";

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

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

HC.QS = {
    AppendFilename: function(qString) {
        if (!qString) {
		    return HC.query;
	    }
	
        if (qString.indexOf("fileName") == -1) {
            if (HC.query != "") {
                if (qString.indexOf("languageCode") > -1) {
                    qString = this.remQStringName(qString, "languageCode");
                }
                return qString + "&" + HC.query;
            } 
			else {
                return qString;
            }
        } 
		else {
            return qString;
        }
    },

    //unencode url-encoded string
    URLDecode: function(urlStr) {
        return decodeURIComponent(urlStr);
    },
	
	//replace or add name/value pairs in url-encoded querystring
	setQStringName: function (qString, name, arrVal) {
		var qStringNew = this.remQStringName(qString, name);
		var start = qStringNew == "" ? 1 : 0;
		
		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
	remQStringName: function (qString, name) {
		var i;
		var qStringNew = "";

		if (qString != "") {
			var curName;
			var arrNameVal = qString.split('&');
			for (i = 0; i < arrNameVal.length; i++) {
				curName = this.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
	GetQSVal: function(qsName) {
		try {
			var qsPair;
			var i;
			var qString = location.search.substr(1);
			
			if (qString == null || qString.length == 0) {
				qString = HC.query;
			}

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

};

//reload page with the new querystring name-value pair
function Reload(name, val) {
    var qString = location.search.substr(1);
    qString = HC.QS.AppendFilename(qString);
    
    //Change the currency in the returnPath as well
    if (name == "currencyCode") {
        var returnPath = HC.QS.GetQSVal("returnPath");
        if (returnPath) {
            returnPath = HC.QS.remQStringName(returnPath, "currencyCode");
            returnPath = HC.QS.setQStringName(returnPath, "currencyCode", [val]);
            returnPath = HC.QS.remQStringName(returnPath, "lowRate");
            returnPath = HC.QS.remQStringName(returnPath, "highRate");
            qString = HC.QS.remQStringName(qString, "returnPath");
            qString = HC.QS.setQStringName(qString, "returnPath", [returnPath]);
        }
    }
        
    //always reset page to 1
    if (name != "pageIndex") {
        var page = HC.QS.GetQSVal("pageIndex");
        if (page != "0" && page != "") {
			qString = HC.QS.setQStringName(qString, "pageIndex", new Array("0"));
		}
    }
    
    //Pass across the page size if available
    var pageSize = $("#pageSize");
    if (pageSize.length == 1) {
        qString = HC.QS.setQStringName(qString, "pageSize", [pageSize[0].value]);
    }
    
    qString = HC.QS.setQStringName(qString, name, new Array(val.toString()));
    qString = HC.QS.setQStringName(qString, "tabId", new Array(HC.currentTabId.toString()));
    qString = HC.QS.setQStringName(qString, "rateTabId", new Array(HC.currentRateTabId.toString()));
    qString = HC.QS.remQStringName(qString, "scroll");
    
	//Remove customFileName
    qString = HC.QS.remQStringName(qString, 'fileNameType');
    if (typeof gCityFileName != "undefined") {
        qString = HC.QS.setQStringName(qString, "fileName", [gCityFileName]);
    }
    
	// display view layout..
    qString = HC.QS.remQStringName(qString, "view");
    qString += "&view=" + HC.Design.GetSRLayout();

    if (qString.indexOf("&") == 0) {
        qString = qString.substr(1);
    }

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

    return false;
}

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


function setRoomValue(containerId, select, target) {
    if (target == undefined || target == null) {
        target = "_self";
    }

    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=" + HC.gHotelPlannerLink, target);
            return false;
        }
    }
    else {
        document.getElementById(containerId + '_Rooms').value = select.options[select.selectedIndex].value;
    }
    return false;
}

function getDate(dateString) {
    var year = dateString.substr(0, 4);
    var month = dateString.substr(5, 2) - 1;
    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)
    // 86400000 is one days in milliseconds
    if ((outDate - inDate) / 86400000 >= 31) {
        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 >= 364) {
        alert(typeof (JavaScriptBookWithinOneYear) == 'undefined' ? 'You cannot book more than 1 year in advance.' : JavaScriptBookWithinOneYear);
        return false;
    }
    return true;
}


/************************************************************************
/******************* Get Search Results ********************************/
/* Functions used for getting search results from info in search boxes */
/***********************************************************************/

function GetRates(containerId, options) {
    options = options || {};
    var calendar1Id = containerId + '_Checkin';
    var calendar2Id = containerId + '_Checkout';
    var checkinValue = document.getElementById(calendar1Id).value;
    var checkoutValue = document.getElementById(calendar2Id).value;

    var guests = document.getElementById(containerId + "_GuestsValue").value;
    var rooms = document.getElementById(containerId + "_RoomsValue").value;

    var checkin = '';
    var checkout = '';

    if (checkinValue && checkoutValue) {
        checkin = HC.Calendar.formatDate(Date.fromString(checkinValue, ShortDatePatternVariable), DefaultShortDatePatternVariable);
        checkout = HC.Calendar.formatDate(Date.fromString(checkoutValue, ShortDatePatternVariable), DefaultShortDatePatternVariable);
    }

    if (!ValidateCityName()) {
        return false;
    }

    if (checkin || checkout) {
        if (!ValidateCalendarDates(calendar1Id, calendar2Id)) {
            return false;
        }
    } 
    else {
        alert(typeof (JavaScriptEnterCheckinCheckout) == 'undefined' ? 'Please enter your checkin and checkout date.' : JavaScriptEnterCheckinCheckout);
        return false;
    }

    if (!ValidateGuestsRooms(guests, rooms)) {
        return false;
    }

    //Change ICON to searching
    if (options.changeClass && options.searchButton) {
        $(options.searchButton).removeClass(options.changeClass[0]).addClass(options.changeClass[1]);
    }

    //Redirect appropriately
    //used on the hotel page to skip loading of filters as there aren't any
    var autocompleteState = RetrieveAutocompleteState();
    if ((options.skipFilters == true) && (autocompleteState.cityChanged == false)) {
        autocompleteState.query = "fileName=" + document.getElementById("originalFileName").value;
    }

    //Setup the search variables
    HC.Common.fields.checkin = checkin;
    HC.Common.fields.checkout = checkout;
    HC.Common.fields.adults = guests;
    HC.Common.fields.rooms = rooms;

    //Nothings change so just search using existing filter criteria with prices reset, or option is set to skip filters (as we are
    //coming from the hotel page and there are not any filters set) so skip setting filters
    if ((autocompleteState.isAutocompleted && !autocompleteState.cityChanged) && (options.skipFilters != true)) {
        //Reset the prices
        HC.SR.Filter.fields.lowRate = null;
        HC.SR.Filter.fields.highRate = null;
        HC.SR.Filter.fields.showSoldOut = "true";

        //Modify the search
        HC.SR.ParentPage = "/SearchResults.aspx";
        HC.SR.Search({ pageReload: true, displayFiltering: false });
    } 
    else {
        SearchResultsSearch(autocompleteState);
    }
}

function ValidateCityName() {
    if ($('#M_C_SearchBox1_SearchResultCity').val().length < 3) {
        alert(typeof (JavaScriptEnterCityName) == 'undefined' ? 'Please enter a city name that is at least 3 characters in length' : JavaScriptEnterCityName);
        return false;
    }
    return true;
}

function SearchResultsSearch(autocompleteState) {
    var fileName = autocompleteState.query;
    var path = "currencyCode=" + HC.Common.fields.currencyCode + "&languageCode=" + HC.Common.fields.languageCode;
    var ratesQuery = "Adults=" + HC.Common.fields.adults + "&rooms=" + HC.Common.fields.rooms + "&checkin=" + HC.Common.fields.checkin + "&checkout=" + HC.Common.fields.checkout;
    var city = autocompleteState.searchQuery;

    //Value Autocompleted with dates
    if (fileName) {
        path = "/SearchTermTypeRedirection.ashx?" + path + "&" + ratesQuery + "&" + fileName;
    } 
    else {
        path = "/Search.aspx?search=" + encodeURIComponent(city) + "&" + path + "&" + ratesQuery;
    }

    HC.Common.Navigation.gotoPage(path);

    return false;
}

function QueryForAutocomplete() {
    var query = null;
    query = "fileName=" + document.getElementById("selectedFileName").value;
    var locationID = document.getElementById("selectedLocationID").value;
    
    if (locationID && !isNaN(locationID)) {
        query += "&locationId=" + locationID + "&sort=Distance-asc";
    }

    query += "&sttype=" + document.getElementById('selectSearchTermType').value;

    return query;
}

function RetrieveAutocompleteState() {
    var autoComplete = {};
    var inputBoxValue = $("#M_C_SearchBox1_SearchResultCity")[0].value;
    var autocompleteValue = $("#selectedCityName")[0].value;
    var originalValue = HC._originalCityCountry;

    //Nothings changed
    if (inputBoxValue.toUpperCase() == originalValue.toUpperCase()) {
        autoComplete.isAutocompleted = true;
        autoComplete.cityChanged = false;

        return autoComplete;
    }

    //Check if there is a match to make sure the value has been truly autcomplete
    if (inputBoxValue == autocompleteValue) {
        autoComplete.isAutocompleted = true;
        autoComplete.cityChanged = true;
        autoComplete.query = this.QueryForAutocomplete();
    } 
    else {
        autoComplete.isAutocompleted = false;
        autoComplete.searchQuery = inputBoxValue;
    }
    return autoComplete;
}

/********************************************************************************/
/************** End of search results functions *********************************/
/********************************************************************************/


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

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

//this function used only by legacy search boxes
function DoHomePageSearch(languageCode, target, affiliateId, city, domain, brandId, options, containerId) {
    var calendar1Id = containerId + '_Checkin';
    var calendar2Id = containerId + '_Checkout';

    if (HC.gSearching) {
        return false;
    }
    
    options = options || {};
    var redirection;
    var affiliateParam;
    var brandParam;
    var host;
    var locationParam = "";  
    var isAutoComplete = false;

    if (!ValidateCalendarDates(calendar1Id, calendar2Id, true)) {
        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 = HC.QS.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 = HC.Calendar.formatDate(Date.fromString(document.getElementById(calendar1Id + "Value").value, ShortDatePatternVariable), DefaultShortDatePatternVariable);
    checkoutValue = HC.Calendar.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_SearchBox1_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=" + encodeURIComponent(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_SearchBox1_SearchResultCity") != null) {
            var currency = document.getElementById("M_C_Filter1_currencies");
            redirection += currency == null ? "" : "&currencyCode=" + currency.options[currency.selectedIndex].id;

            if (document.getElementById("M_C_Filter1_LowRate") != null) {
                if (document.getElementById("M_C_Filter1_LowRate").value != null && document.getElementById("M_C_Filter1_LowRate").value != 0) {
                    redirection += "&lowRate=" + encodeURIComponent(document.getElementById("M_C_Filter1_LowRate").value);
                }
            }

            if (document.getElementById("M_C_Filter1_HighRate") != null) {
                if (document.getElementById("M_C_Filter1_HighRate").value != null && document.getElementById("M_C_Filter1_HighRate").value != 0) {
                    redirection += "&highRate=" + encodeURIComponent(document.getElementById("M_C_Filter1_HighRate").value);
                }
            }

            redirection += HC.Common.GetStarValue(redirection, document.getElementById("M_C_Filter1_M_C_Star5"), "star5");
            redirection += HC.Common.GetStarValue(redirection, document.getElementById("M_C_Filter1_M_C_Star4"), "star4");
            redirection += HC.Common.GetStarValue(redirection, document.getElementById("M_C_Filter1_M_C_Star3"), "star3");
            redirection += HC.Common.GetStarValue(redirection, document.getElementById("M_C_Filter1_M_C_Star2"), "star2");
            redirection += HC.Common.GetStarValue(redirection, document.getElementById("M_C_Filter1_M_C_Star1"), "star1");
            redirection += "&cityName=" + city;

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

            if (document.getElementById("M_C_Filter1_ShowSoldOut") != null) {
                redirection += document.getElementById("M_C_Filter1_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 = "/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]);
    }

    //if checkin and checkout date were not specified redirect to static city page
    var checkinText = document.getElementById(calendar1Id).value;
    var checkoutText = document.getElementById(calendar2Id).value;
    var cityFileName =  document.getElementById('selectedFileName').value;
    if (!checkinText && !checkoutText) {
        setTimeout(function () { window.location = host + "City/" + cityFileName + '.htm'; }, 10); // _self
        return;
    }

    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_Filter1_HotelFacility1") != null) {           
        for (var i = 1; i <= facilityCount; i++) {
            if (document.getElementById("M_C_Filter1_HotelFacility" + i).checked) {
                var facilityId = $("#M_C_Filter1_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_Filter1_PropertyType" + i) != null) {
            if (document.getElementById("M_C_Filter1_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;

    HC.gSearching = true;

    switch (target) {
        case "_blank":
            HC.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 DoCitySearchBoxSearch(languageCode, target, affiliateId, fileName, domain, brandId, applyFilters) {
    var redirection;
    var affiliateParam;
    var brandParam;
    var host;

    if (HC.Common.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 = HC.Common.SetStarValue(redirection, document.getElementById("M_C_Filter1_Star5"), 'star5');
            redirection = HC.Common.SetStarValue(redirection, document.getElementById("M_C_Filter1_Star4"), 'star4');
            redirection = HC.Common.SetStarValue(redirection, document.getElementById("M_C_Filter1_Star3"), 'star3');
            redirection = HC.Common.SetStarValue(redirection, document.getElementById("M_C_Filter1_Star2"), 'star2');
            redirection = HC.Common.SetStarValue(redirection, document.getElementById("M_C_Filter1_Star1"), 'star1');
            redirection = HC.QS.setQStringName(redirection, "sort", new Array(document.getElementById("sortBy").options[document.getElementById("sortBy").selectedIndex].value));

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

            if (document.getElementById("AvailableOnly").checked) {
                redirection = HC.QS.remQStringName(redirection, "availableOnly");
            }
            else {
                redirection = HC.QS.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;
}

//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) {
        (HC.Common.isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
        (HC.Common.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) {
        (HC.Common.isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
        (HC.Common.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) {
        (HC.Common.isChild(target, checkinCalDiv) || target == checkinDiv) ? null : checkinCalDiv.style.display = 'none';
        (HC.Common.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;
}

/***************** 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 AffiliateClick(requestUrl, friendlyUrl) {
    var expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 365);
    var isFramed = (self != top);

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

// Namespace for common elements.
HC.Common = {

    //Please all common init stuff here
    Init: function () {

        this.GoogleTrackLanguageCurrencyChange();

    },

    JSObfuscateURL: function (url) {
        return ReverseString(url);
    },

    isFieldEmpty: function (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;
    },

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

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

    isChild: function (child, parent) {
        while (child) {
            if (child == parent) {
                return true;
            }
            child = child.parentNode;
        }
        return false;
    },

    Jsl: function (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;
    },

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

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

    isChild: function (child, parent) {
        while (child) {
            if (child == parent) {
                return true;
            }
            child = child.parentNode;
        }
        return false;
    },

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

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

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

    GenerateQueryString: function (options) {
        options = options || {};
        var fields = this.fields;
        var qString;

        qString = "languageCode=" + fields.languageCode;
        qString += "&currencyCode=" + fields.currencyCode;

        if (!options.excludeFilename) {
            qString += "&fileName=" + fields.fileName;
            qString += "&fileType=" + fields.fileType;
        }

        //Remove date/people stuff
        if (!options.excludeDates) {
            if (fields.checkin) qString += "&checkin=" + fields.checkin;
            if (fields.checkout) qString += "&checkout=" + fields.checkout;
            if (fields.adults) qString += "&adults=" + fields.adults;
            if (fields.rooms) qString += "&rooms=" + fields.rooms;
        }

        return qString;
    },

    GenerateHotelQueryString: function (fileName, options) {
        options = options || {};
        var qString = "fileName=" + fileName;
        if (options.tabId) qString += "&tabId=" + options.tabId;
        if (options.rateTabId) qString += "&rateTabId=" + options.rateTabId;

        //Setup any generation options
        var genOptions = {};
        genOptions.excludeFilename = true;
        if (options.excludeDates) {
            genOptions.excludeDates = true;
        }

        qString += "&" + HC.Common.GenerateQueryString(genOptions);
        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) {
        HC.Language.changeLanguage('languageCode', o.options[o.options.selectedIndex].value);
        return false;
    },

    currencySwitch: function (o) { // accept string values or select object..
        //For Searchprogress page (trying to use the ajax version)
        if (typeof (o) == "object") {
            val = o.options[o.options.selectedIndex].value;
        }
        else {
            val = o;
        }

        if (typeof changeLanguageOriginal != "undefined") {
            changeLanguageOriginal("currencyCode", val);
        }
        else if (HC.SR && HC.SR.Filter) {
            HC.SR.Filter.ChangeCurrency(val);
        }


        if (HC.SR && HC.SR.Filter) {
            HC.SR.Filter.ChangeCurrency(val);
        }
        else {
            HC.Language.changeLanguage('currencyCode', val);
        }

        return false;
    },

    writeDisplayNoneDivStart: function (id) {
        document.write('<div id="' + id + '" style="display:none;">');
    },

    writeDivEnd: function () {
        document.write('</div>');
    },

    expandContractGlobalSites: function (e) {
        var $holder = $("#internationLinksHolder");
        $holder.toggle();
        var $img = $("#globalSitesLink img");
        var newSource = $img[0].src;

        //Toggle the image
        if ($holder.is(":visible")) {
            newSource = newSource.replace("/interlinking-arrow-right.gif", "/interlinking-arrow-down.gif");
            $img[0].src = newSource;
            $img.removeClass("contracted").addClass("expanded");
        }
        else {
            newSource = newSource.replace("/interlinking-arrow-down.gif", "/interlinking-arrow-right.gif");
            $img[0].src = newSource;
            $img.removeClass("expanded").addClass("contracted");
        }
    },

    findPos: function (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 };
    },

    getNumericPortion: function (str) {
        return str.match(/\d*/);
    },

    getScrollXY: function () {
        var scrOfX = 0;
        var scrOfY = 0;
        if (typeof (window.pageYOffset) == 'number') {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        }
        else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        }
        else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return [scrOfX, scrOfY];
    },

    getWindowSize: function () {
        var myWidth = 0;
        var myHeight = 0;
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        }
        else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return [myWidth, myHeight];
    },

    /**************** Google Anayltics ****************/
    GoogleTrackLanguageCurrencyChange: function () {

        $(function () {

            $("#langSwitch").change(function () {
                HC.Common.AnalyticsTrackEvent("Language Change", this.value);
            });

            $("#currencySwitch").change(function () {
                HC.Common.AnalyticsTrackEvent("Currency Change", this.value);
            });
            
        });

    },

    AnalyticsTrackEvent: function (category, action, label) {

        var track;
        if (arguments.length == 3) {
            track = ['_trackEvent', category, action, label];
        }
        else {
            track = ['_trackEvent', category, action];
        }

        if (typeof _gaq != "undefined") {
            _gaq.push(track);
        } else {
            $(function () {
                if (typeof _gaq != "undefined") {
                    _gaq.push(track);
                }
            });
        }
    },

    IsIE6: function () {
        if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
            return true;
        } else {
            return false;
        }
    }

};


HC.Common.Form = {
    //This function will return from the supplied form element name, all html element types listed in .find().
    //Only if those elements have a "name" attribute. 
    //It will return an object of type {"element name" : "element value"}.
    GetFormValuesObject: function (selector, form) {
        var formValues = {};

        if (form == undefined || form == null || form == "") {
            form = 'form';
        }

        var a = $(form + "")
                    .find(selector + " input,textarea,select,hidden")
                    .serializeArray();
        $.each(a, function () {
            if (formValues[this.name]) {
                if (!formValues[this.name].push) {
                    formValues[this.name] = [formValues[this.name]];
                }
                formValues[this.name].push(this.value || '');
            } else {
                formValues[this.name] = this.value || '';
            }
        });
        return formValues;
    }
}


// Namespace for status displays/messages
HC.Common.Status = {
	DisplayFiltering: function(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.
		options = options || {};
		
		$("#filterDiv").remove();
		
		var text = "";
		if (options.sorting) {
		    text = typeof (HC.Translations.searchPageSortingResults) == 'undefined' ? 'Sorting Results...' : HC.Translations.searchPageSortingResults;
		} 
		else if (options.paging) {
		    text = typeof (HC.Translations.searchPageLoadingResults) == 'undefined' ? 'Loading Page...' : HC.Translations.searchPageLoadingPage;
		} 
		else if (options.loading) {
		    text = typeof (HC.Translations.searchPageLoadingResults) == 'undefined' ? 'Loading Results...' : HC.Translations.searchPageLoadingResults;
		} 
		else if (options.loadingHotel) {
		    text = typeof (HC.Translations.searchPageLoadingHotel) == 'undefined' ? 'Loading Hotel...' : HC.Translations.searchPageLoadingHotel;
		} 
		else {
		    text = typeof (HC.Translations.pageFilteringResults) == 'undefined' ? 'Filtering Results...' : HC.Translations.pageFilteringResults;
		}

		//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);
		var zIndex = 999;

		filterDiv.css({ left: leftPosition + "px", top: topPosition + "px", "z-index": zIndex });

		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" ,  "z-index": zIndex});
	},
	HideFiltering: function() {
		$("#filterDiv").hide();
	}
};


// Namespace for popups
HC.Common.Popups = {
    popId: "hc_popupSearch",

    createPop: function () {
        var width = "490px";
        var height = "";
        var docHeight = $(document).height();
        var winHeight = $(window).height();

        // IE8 has a bug with opacity and block heights (limit is 4096px - 2^12, higher results in solid bg)
        var $trans = $('<div>');
        $trans.attr("id", "PopupTransparent");
        if ($.browser.msie && $.browser.version.substr(0, 1) == 8) {
            $trans.css({ "position": "fixed" });
            $trans.height(winHeight);
        }
        else {
            $trans.height(docHeight);
        }
        $trans.appendTo('#hc_bodyElements');

        // center the outside div within the viewable section of the document
        var left = (HC.Common.getWindowSize()[0] / 2) + HC.Common.getScrollXY()[0] - (HC.Common.getNumericPortion(width) / 2);
        var top = (HC.Common.getWindowSize()[1] / 2) - (250 / 2);
        e = document.getElementById(this.popId);
        //e.style.height = height;
        e.style.width = width;
        e.style.left = left + "px";
        e.style.zIndex = "900";
        e.style.display = 'block';
        $(e).appendTo('#hc_bodyElements');

        // 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: top + 40, left: left, display: "block", position: "fixed" });
        }
        // IE6, older browsers
        else {
            e.style.position = 'absolute';
            e.style.height = "auto";

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

    closePopUp: function () {
        $("#PopupTransparent").remove();

        document.getElementById(this.popId).style.display = 'none';

        $(".chkPriceUnderlay").css({ display: "none" });
    },

    bestPriceGuaranteePopup: function () {
        var languageCode = "EN";
        if (typeof HC.gLanguageCode != undefined) {
            languageCode = HC.gLanguageCode;
        }

        HC.Common.Tooltip.tooltipHide('tt1');
        window.open('/BestPriceGuaranteePopup.aspx?languageCode=' + languageCode, '', 'toolbar=0,status=0,menubar=0,scrollbars ,width=400,height=500', true);
    },

    bestPriceGuaranteePopupFooter: function (element) {
        window.open(element.href, '', 'toolbar=0,status=0,menubar=0,scrollbars ,width=400,height=500', true);
    },

    questionAndAnswersPopup: function (hotelName, hotelId) {
        window.open('/AskHotelQuestion.aspx?hotelName=' + hotelName + '&hotelId=' +hotelId, '', 'toolbar=0,status=0,menubar=0,location=0,scrollbars,width=491,height=250', true);
        return false;
    }

};

// Namespace for creating tooltips.
HC.Common.Tooltip = {
    tooltips: Array(), // array of all current page tooltips. 'add' method adds the tooltip to this array.

    // initialise a new tooltip div with specific content..
    add: function (myId, myContent) {
        this.tooltips[myId] = $('<div class="hc_tooltip"><div class="hc_tooltip_bg"></div></div>');
        this.tooltips[myId].attr('id', myId);
        this.tooltips[myId].html(this.tooltips[myId].html() + myContent);
        this.tooltips[myId].appendTo('#hc_bodyElements');
    },

    // display requested tooltip..
    show: function (mySourceObj, myId) {
        var tempId = '#' + myId;
        var pos = HC.Common.findPos(mySourceObj);
        var myWidth = $(tempId).innerWidth();
        var myHeight = $(tempId).innerHeight();
        var myX = pos.x - myWidth + $(mySourceObj).innerWidth();
        myX += "px";
        var myY = (pos.y + $(mySourceObj).innerHeight()) + "px";
        //this.showOverlay(myX, myY, myWidth, myHeight);
        $(tempId).css('top', myY);
        $(tempId).css('left', myX);
        $(tempId).bgIframe();
        $(tempId).animate({
            opacity: 'toggle'
        }, 300);
    },

    // hide requested tooltip..
    hide: function (myId) {
        $('#' + myId).animate({
            opacity: 'toggle'
        }, 300, 'linear', function () {
            HC.Common.Tooltip.hideOverlay();
        });
    },

    showOverlay: function ($myObj) {
        $myObj.bgiFrame();
    },

    hideOverlay: function () {
        $('#ttOverlay').hide();
    },

	/* Best Price Guarantee popup */
	tooltipShow: function (sourceObj, tooltipElementId) {
		var tooltip = document.getElementById('tt1');
		var ttOverlay = document.getElementById('ttOverlay');
		var pos = HC.Common.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";
	},

	tooltipHide: function (tooltipElementId) {
		var tooltip = document.getElementById('tt1');
		if (tooltip != null) {
			tooltip.style.display = 'none';
			var ttOverlay = document.getElementById('ttOverlay');
			ttOverlay.style.display = 'none';
		}
	}
}


// 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(),

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

    // directs user to myUrl 
    gotoPage: function (myUrl) {

        // navigate user window to myUrl location if provided.
        if (myUrl != null && myUrl != "") {
            location.href = myUrl;
        }
        return false;
    }
};

/************ Deals Box ******************/
HC.DealsBox = {
    dealsClicked: function (TableID, RefTableID, languageCode, emailSelector) {
        if (emailSelector == undefined) {
            emailSelector = "#emailAddressInput";
        }
        var email = $(emailSelector).val();
        var page = "/User/AddUserEmail.aspx?Email=" + encodeURIComponent(email) + "&TableID=" + TableID + "&RefTableID=" + RefTableID + "&languageCode=" + languageCode;
        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("");
        $("#emailAddress").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 */


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
        var title = $input.attr('title');
        var $form = jQuery(this.form);
        var $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 () {
    var emailInput = $("#emailAddressInput");
    if (emailInput.length > 0) {
        $("#emailAddressInput").hint();
    }

    emailInput = $("#emailAddress");
    if (emailInput.length > 0) {
        $("#emailAddress").hint();
    } 

});



// Design / layout related js..
HC.Design = {
    // list of hover classes associated to each type of search result listing layout.
    // The value array is the search result item class in element 0 and the respective hover class in element 1.
    // ie. Search Result Layout : (search result item class, search result item class onhover).
    SRI_Classes: {
        "hc_sr_summary": Array("hc_m_v4", "hc_m_v11", "hc_m_v20"),
        //"hc_sr_list": Array("hc_m_v6", "hc_m_v11"),
        "hc_sr_list": Array("hc_m_v6", "hc_m_v6"),
        "hc_sr_photo": Array("hc_m_v6", "hc_m_v11"),
        "hc_sr_map": Array("hc_m_v6", "hc_m_v6"),
        "hc_deals_summary": Array("hc_m_v23", "hc_m_v24")
    },

    SRI_Classes_selected: {
        "hc_sr_summary": Array("hc_m_v4_lite", "hc_m_v11_lite", "hc_m_v20_lite"),
        //"hc_sr_list": Array("hc_m_v6_lite", "hc_m_v11_lite"),
        "hc_sr_list": Array("hc_m_v6_lite", "hc_m_v6_lite"),
        "hc_sr_photo": Array("hc_m_v6", "hc_m_v11"),
        "hc_sr_map": Array("hc_m_v6", "hc_m_v6"),
        "hc_deals_summary": Array("hc_m_deals_lite")
    },

    // constant reg expression for pattern matching module classes.
    ModuleClassRegExp: "(^hc_m[_v1234567890lite]*$)|( hc_m[_v1234567890lite]*$)|(^hc_m[_v1234567890lite]* )|( hc_m[_v1234567890lite]* )",

    // initialise the search results tracking variable.
    CurrentSRLayout: "hc_sr_summary",

    // Set Search Result item classes.. used to overwrite defaults above..
    SetSRIClass: function (myLayout, myDefaultClass, myHoverClass) {
        this.SRI_Classes[myLayout] = Array(myDefaultClass, myHoverClass);
    },

    SetSRISelectedClass: function (myLayout, myDefaultClass, myHoverClass) {
        this.SRI_Classes_selected[myLayout] = Array(myDefaultClass, myHoverClass);
    },

    // Removes all module classes from an object.
    RemoveModule: function (myObj) {
        // remove old module..
        if ($(myObj)[0] != null) {
            var myReg = new RegExp(HC.Design.ModuleClassRegExp, "g");
            var myNewClass = $(myObj)[0].className.replace(myReg, "");
            $(myObj)[0].className = myNewClass;
        }
    },

    // retrieve / set the current search result layout.
    GetSRLayout: function () {
        return HC.Design.CurrentSRLayout;
    },

    SetSRLayout: function (myVal) {
        HC.Design.CurrentSRLayout = myVal;
    },

    // initialise the search results items.
    SetupSRIs: function (mySRIs) {
        if (mySRIs == null) {
            mySRIs = $('#hc_sr').children('.hc_sri');
        }

        mySRIs.hover(
            function (event) {
                HC.Design.RemoveModule(this);
                $(this).addClass(HC.Design.SRI_Classes[HC.Design.CurrentSRLayout][1]);
            },
            function (event) {
                HC.Design.RemoveModule(this);
                $(this).addClass(HC.Design.SRI_Classes[HC.Design.CurrentSRLayout][0]);
            }
        );

        HC.Design.SetupSelectedSRI();
    },

    SetupSelectedSRI: function () {
        // initialise selected sri, if present..
        HC.Design.RemoveModule('#selectedHotel');
        $('#selectedHotel').addClass(HC.Design.SRI_Classes_selected[HC.Design.CurrentSRLayout][0]);
        // setup hover events on selected hotel with lite version of container, if present..
        $('#selectedHotel').hover(
            function (event) {
                HC.Design.RemoveModule(this);
                $(this).addClass(HC.Design.SRI_Classes_selected[HC.Design.CurrentSRLayout][1]);
            },
            function (event) {
                HC.Design.RemoveModule(this);
                $(this).addClass(HC.Design.SRI_Classes_selected[HC.Design.CurrentSRLayout][0]);
            }
        );
    },

    ActivateMapLayout: function (activateLayout) {
        if (activateLayout) {
            // hide footer in main map
            $('#main-map-footer').hide();
            // open main map if not already
            if (HC.SR.Maps != null && !HC.SR.Maps.IsMapExpanded) {
                $('#sidebar-map-expand').mousedown();
            }
            // hide sidebar map
            $('#sidebar-map').hide();
            // add scrollable results
            $('#hc_sr').addClass('hc_sr_scroll');
            // fix column wrapping
            $('#hc_r_3').css('padding-top', '505px');
            $('#hc_r_4').css('margin-top', '505px');
        }
        else {
            $('#main-map-footer').show();
            $('#sidebar-map').show();
            if (HC.SR == null) {
                $('#hc_r_3').css('padding-top', '0');
                $('#hc_r_4').css('margin-top', '0');
            }
            else if (!HC.SR.Maps || !HC.SR.Maps.IsMapExpanded) {
                $('#hc_r_3').css('padding-top', '0');
                $('#hc_r_4').css('margin-top', '0');
            }
            else {
                $('#hc_r_3').css('padding-top', '590px');
                $('#hc_r_4').css('margin-top', '590px');
            }
            $('#hc_sr').removeClass('hc_sr_scroll');
        }
    },

    // Used to change layouts of the search result items.
    ActivateLayout: function (myLayout) {
        // remove old layout..
        myOldLayout = HC.Design.CurrentSRLayout;

        if (myLayout == null) {
            myLayout = HC.Design.GetSRLayout();
        }

        // get search result wrapper..
        mySR = $('#hc_sr');

        // remove old layout from search result items..
        mySRIs = mySR.children('.hc_sri');
        mySRIs.removeClass(HC.Design.SRI_Classes[myOldLayout][0] + " " + HC.Design.SRI_Classes[myOldLayout][1]); // remove both static and hover layouts.
        mySRIs.removeClass(HC.Design.SRI_Classes_selected[myOldLayout][0] + " " + HC.Design.SRI_Classes_selected[myOldLayout][1]); // remove both static and hover layouts.
        if (HC.Design.SRI_Classes[myLayout] != null && HC.Design.SRI_Classes[myLayout] != "") {
            mySRIs.removeClass(HC.Design.SRI_Classes[myLayout][0] + " " + HC.Design.SRI_Classes[myLayout][1]); // remove both static and hover layouts.
        }

        if (HC.Design.SRI_Classes_selected[myLayout] != null && HC.Design.SRI_Classes_selected[myLayout] != "") {
            mySRIs.removeClass(HC.Design.SRI_Classes_selected[myLayout][0] + " " + HC.Design.SRI_Classes_selected[myLayout][1]); // remove both static and hover layouts.
        }

        // apply layout class to Search Results wrapper..
        mySR.removeClass(myOldLayout).addClass(myLayout);

        // set new layout tracking var..
        HC.Design.SetSRLayout(myLayout);

        // fix view dropdown in sort filter..
        $('select#view').val(myLayout);

        // add appropriate layout class for each search result item..
        mySRIs.addClass(HC.Design.SRI_Classes[myLayout][0]);

        // handle map manipulation..
        if (myLayout == "hc_sr_map") {
            HC.Design.ActivateMapLayout(true);
        }
        else {
            HC.Design.ActivateMapLayout(false);
        }

        // setup roll-over effects..
        HC.Design.SetupSRIs(mySRIs);
    },

    // public method for response to view select box on page.
    SwitchLayout: function (myObj) {
        var myLayout = myObj.options[myObj.options.selectedIndex].value;
        this.ActivateLayout(myLayout);
    },

    // Animates the open / close slide effect for dt links controlling their dd associate.
    ToggleDD: function (myObj) {
        var $element = $(myObj).closest('dt').next('dd');
        $element.animate({ "height": "toggle", "opacity": "toggle" }, 300, 'swing', function () {
            var visible = $element.is(":visible");
        });
    },

    /* Test function to move main map to be inline into the hotel's search result item (like features)
    * Buggy and needs to be implemented properly.
    * A better way would be to cut the "main-map" node out of the dom and insert it in the respective dd.
    */
    ToggleMapDD: function (myObj) {
        myMap = document.getElementById("main-map");
        $(myObj).closest('dt').next('dd').html(myMap.innerHTML);
        $(myObj).closest('dt').next('dd').css("display", "block");
        $(myObj).closest('dt').next('dd').css("height", "342px");
        myMap.innerHTML = "";
        myMap.id = "";
        $(myObj).closest('dt').next('dd').attr("id", "main-map");
        setTimeout("HC.SR.Maps.OpenHotelInfoWindow('1180044');", 1000);
    },

    // Add design related querystring variables for links
    GenerateQueryString: function () {
        // add view value to query string.
        myQS = "view=" + HC.Design.GetSRLayout();
        return myQS;
    },

    // scroll to map
    ScrollToMap: function () {
        HC.SR.Maps.MainMap.ScrollToMap();
    },

    // update pagination clone in map interface
    UpdateMapPaging: function () {
        $('#main-map-footer .paginationListWrap').remove();
        $('#main-map-footer p.tooManyPages').remove();

        var $pagination = $('.paginationListWrap').clone();
        var $ul = $pagination.find("ul");
        $ul.attr("id", "HC_paging_top");

        //If on city page we need to override the event
        if (HC.SR && HC.SR._isCityPage) {
            $ul.mousedown(HC.City.PagingEventDelegate);
        }

        //Add the tracking
        if (HC.SR && HC.SR.Paging) {
            $ul.mousedown(function (event) {
                HC.SR.Paging.AnalyticsDelegate(event, "Map");
            });
        }

        $pagination.appendTo('#main-map-footer');

        var $tooManyPages = $('#pagination p.tooManyPages').clone();
        $tooManyPages.appendTo('#main-map-footer');
    },

    // hide / show module content
    OpenModuleContent: function ($myObj) {
        // where $myObj is the hc module wrapping div.
        $myObj.removeClass('hc_m_hide');
    },

    CloseModuleContent: function ($myObj) {
        // where $myObj is the hc module wrapping div.
        $myObj.addClass('hc_m_hide');
    },

    ToggleModuleContent: function ($myObj) {
        // where $myObj is the hc module wrapping div.
        if ($myObj.hasClass('hc_m_hide')) {
            // open filter..
            HC.Design.OpenModuleContent($myObj);
        }
        else {
            // close filter..
            HC.Design.CloseModuleContent($myObj);
        }
    },

    HideObj: function ($myObj, removeObj) {
        // animate object for added element..
        if (removeObj) {
            $myObj.animate({ "height": "0", "opacity": 0 }, 300, 'swing', function () {
                var visible = $(this).is(":visible");
                $(this).remove();
            });
        } else {
            $myObj.animate({ "height": "0", "opacity": 0 }, 300, 'swing', function () {
                var visible = $(this).is(":visible");
            });
        }
    },
    ShowObj: function ($myObj) {
        // animate object for added element..

        $myObj.animate({ "height": "auto", "opacity": 1 }, 300, 'swing', function () {
            var visible = $(this).is(":visible");
            $(this).removeClass("hc_hide");
        });
    },

    togglePlane: function (clickId, elementId) {
        // toggle state of link
        var $clickId = $("#" + clickId);
        if ($clickId.length == 1) {
            if ($clickId.hasClass("plane_open")) {
                $clickId.toggleClass("plane_open");
            } else {
                $clickId.toggleClass("plane_open");
            }
        }

        $("#" + elementId).toggle();
    },

    ShowDatePrompt: false // initialise flag.
    /*
    EnableDatePrompt: function (myContainers, mySubElements) {
    // pops up the date popover when any sub-element is clicked within each relative container..
    if (!HC.Common.IsIE6()) { // only implement for everythign but ie6.
    HC.Design.ShowDatePrompt = true; // re-initialise flag.
    for (var i = 0; i < myContainers.length; i++) {
    $myContainer = $(myContainers[i]);
    $myContainer.delegate(mySubElements[i], "mouseup", function (event) {
    if (HC.Design.ShowDatePrompt) {
    $(this).blur();
    HC.Common.Popups.createPop();
    return false; // cancel mousedown event.
    } else {
    return true; // allow mousedown event to be handled by original handler.
    }
    });
    }
    }
    */
    /*
    EnableDatePrompt: function (myContainers, mySubElements) {
    // pops up the date popover when any sub-element is clicked within each relative container..
    HC.Design.ShowDatePrompt = true; // re-initialise flag.
    for (var i = 0; i < myContainers.length; i++) {
    $myContainer = $(myContainers[i]);
    $myContainer.bind("click", function (event) {
    if (HC.Design.ShowDatePrompt) {
    event.preventDefault();
    event.stopPropagation();
    HC.Common.Popups.createPop();
    $(this).blur();
    return false; // cancel mousedown event.
    } else {
    return true; // allow mousedown event to be handled by original handler.
    }
    }, false);
    }
    }
    */
};


//Keeping the code here for the moment
HC.HomePage = {
    _currentSearchType: null,
    _destinationAutocomplete: null,
    _values: {},
    _sharedInput: null,
    _searchTermTypeInput: null,
    _searchButtonID: null,

    init: function ($destination, $hotel, options) {
        options = options || {};

        $destination.bind("click", { type: "destination" }, this.setSearchType);
        $hotel.bind("click", { type: "hotelname" }, this.setSearchType);

        //Need to disable this when switching
        this._destinationAutocomplete = options.destinationAutocomplete.autocompleter;
        this._sharedInput = options.sharedInput;
        this._searchTermTypeInput = options.searchTermTypeInput;
        this._searchButtonID = options.searchButtonID;

        $destination[0].checked = true;
        this._currentSearchType = "destination";
    },

    setSearchType: function (event) {
        var me = HC.HomePage;
        var type = event.data.type;

        //Save the previous value and wipe
        me._values[me._currentSearchType] = { input: me._sharedInput.value, searchTermType: me._searchTermTypeInput.value };
        me._sharedInput.value = "";

        //Set the current type and load any previous values
        me._currentSearchType = type;
        var values = me._values[type];
        if (values) {
            me._sharedInput.value = values.input;
            me._searchTermTypeInput.value = values.searchTermType;
        }

        me.selected[type]();
        $(me._sharedInput).focus();
    },

    selected: {
        destination: function () {
            $(HC.HomePage._sharedInput).unbind("keyup.hotelname", HC.HomePage.performSearch);
            HC.HomePage._destinationAutocomplete.enable();
        },

        hotelname: function () {
            HC.HomePage._destinationAutocomplete.disable();
            HC.HomePage._searchTermTypeInput.value = "6";

            $(HC.HomePage._sharedInput).bind("keyup.hotelname", HC.HomePage.performSearch);
        }
    },

    performSearch: function (e) {
        if (e.keyCode == 13) {
            $("#" + HC.HomePage._searchButtonID).click();
        }
    },

    SearchBtn: function (languageCode, target, affiliateId, city, domain, brandId, options, containerId) {
        var calendar1Id = containerId + '_Checkin';
        var calendar2Id = containerId + '_Checkout';
        var calendar1Value = document.getElementById(calendar1Id + "Value").value;
        var calendar2Value = document.getElementById(calendar2Id + "Value").value;
        var datesSupplied = false;

        if (calendar1Value && calendar2Value) {
            datesSupplied = true;
        }

        if (HC.gSearching) {
            return false;
        }

        options = options || {};
        var redirection = '';
        var affiliateParam;
        var brandParam;
        var host;
        var locationParam = "";
        var isAutoComplete = false;

        if (!ValidateCalendarDates(calendar1Id, calendar2Id, true, options.bypassDateValidation)) {
            return false;
        }

        //in home page, if city name is autocomplete text, redirect to searchResults.aspx, otherwise redirect to search.aspx    
        if (options.isAutoComplete || (document.getElementById('citySearch') != null && document.getElementById('selectedCityName') != null)) {
            if (options.isAutoComplete || (document.getElementById('citySearch').value != 0 && document.getElementById('selectedCityName').value != 0)) {
                if (options.isAutoComplete || (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" || brandId == null) {
            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;
            }
        }

        //Add disable access (Don't care about the facility above
        //As this should never happen on our site)
        var accessibleParam = "";
        if (HC.disabilityEnabled) {
            accessibleParam = "&facilities=10";
        }

        //convert dates from localized format to default one
        if (datesSupplied) {
            checkinValue = HC.Calendar.formatDate(Date.fromString(calendar1Value, ShortDatePatternVariable), DefaultShortDatePatternVariable);
            checkoutValue = HC.Calendar.formatDate(Date.fromString(calendar2Value, ShortDatePatternVariable), DefaultShortDatePatternVariable);
        }

        var searchTermType = document.getElementById("selectSearchTermType").value;
        var searchTermTypeID;
        if (searchTermType != "") {
            searchTermTypeID = searchTermType;
            searchTermType = "&sttype=" + searchTermType;
        }

        var guestsEl = document.getElementById(containerId + "_Guests");
        var roomsEl = document.getElementById(containerId + "_Rooms");

        //Redirect to Search page if not autocompleted and not a hotelname search
        if (!isAutoComplete && searchTermTypeID != "6") {
            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=" + encodeURIComponent(city) + "&languageCode=" + languageCode + searchTermType + affiliateParam + brandParam + accessibleParam;
            if (datesSupplied) {
                redirection += "&checkin=" + checkinValue + "&checkout=" + checkoutValue;
                redirection += ((guestsEl == null) || (guestsEl.value < 1)) ? "&Adults=1" : "&Adults=" + guestsEl.value;
                redirection += ((roomsEl == null) || (roomsEl.value < 1)) ? "&Rooms=1" : "&Rooms=" + roomsEl.value;
                if (options.label != undefined) {
                    redirection += "&label=" + options.label;
                }
            }

            setTimeout(function () { HC.HomePage.SearchBtnTarget(target, redirection); }, 10);
            return;
        }

        //Show searching text
        if (options.changeClass && options.searchButton) {
            //$(options.searchButton).removeClass(options.changeClass[0]).addClass(options.changeClass[1]);
            $(options.searchButton).addClass(options.changeClass[1]);
            // change text string..
            $(options.searchButton).html(options.searchingStr);
        }

        var inputIdParts = calendar1Id.split('_');
        var containerId = inputIdParts[0];

        //Pass query for hotel search
        if (searchTermTypeID == "6") {
            redirection = "/SearchTermTypeRedirection.ashx?search=" + encodeURIComponent(city);
        }
        else {
            redirection = "/SearchTermTypeRedirection.ashx?fileName=" + document.getElementById("selectedFileName").value;
        }

        redirection += ((guestsEl == null) || (guestsEl.value < 1)) ? "&Adults=1" : "&Adults=" + guestsEl.value;
        redirection += ((roomsEl == null) || (roomsEl.value < 1)) ? "&Rooms=1" : "&Rooms=" + roomsEl.value;

        if (datesSupplied) {
            redirection += "&checkin=" + checkinValue;
            redirection += "&checkout=" + checkoutValue;
        }
        redirection += "&languageCode=" + languageCode;
        redirection += affiliateParam + brandParam + locationParam + searchTermType + accessibleParam;
        if (options.label != undefined) {
            redirection += "&label=" + options.label;
        }
        redirection = host + redirection;

        HC.HomePage.SearchBtnTarget(target, redirection);

        return false;
    },

    SearchBtnTarget: function (target, url) {
        HC.gSearching = true;
        switch (target) {
            case "_blank":
                HC.gSearching = false;
                window.open(url).focus();
                break;
            case "_parent":
                window.top.location = url;
            case "_top":
                window.top.location = url;
                break;
            default:
                setTimeout(function () { window.location = url; }, 10);  // _self
        }
        return false;
    }
};


/* The following appears to be used in some legacy static files, probably remove later on to save footprint */
HC.Language = {
	changeLanguage: function(name, val) {
		var qString = location.search.substr(1);
		qString = HC.QS.AppendFilename(qString);
		
		//always reset page to 1
		var page = HC.QS.GetQSVal("pageIndex");
		if (page != "0" && page != "") {
			qString = HC.QS.setQStringName(qString, "pageIndex", new Array("0"));
		}

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

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

		//remove lowrate and highrate as currency type has changed.
		if (name == 'currencyCode') {
			qString = HC.QS.remQStringName(qString, 'lowRate');
			qString = HC.QS.remQStringName(qString, 'highRate');
		}

		//adjust the return path
		if (name == "languageCode") {
			var returnPath = HC.QS.GetQSVal("returnPath");
			if (returnPath) {
				returnPath = HC.QS.remQStringName(returnPath, "languageCode");
				returnPath = HC.QS.setQStringName(returnPath, "languageCode", [val]);
				qString = HC.QS.remQStringName(qString, "returnPath");
				qString = HC.QS.setQStringName(qString, "returnPath", [returnPath]);
			}
		}

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

		return false;
	},

    addLanguageFlags: function (flagDomain, languageCode) {
        var flag = "<ul id=\"languageUl\" style=\"display:none\"  >";
        flag += this.addFlag("EN", flagDomain, languageCode);
        flag += this.addFlag("DE", flagDomain, languageCode); // German
        flag += this.addFlag("ES", flagDomain, languageCode); // Spanish
        flag += this.addFlag("FR", flagDomain, languageCode); // French
        flag += this.addFlag("IT", flagDomain, languageCode); // Italian
        flag += this.addFlag("CS", flagDomain, languageCode); // Chinese Simplified
        flag += this.addFlag("CN", flagDomain, languageCode); // Chinese Traxditional
        flag += this.addFlag("JA", flagDomain, languageCode); // Japanese
        flag += this.addFlag("KO", flagDomain, languageCode); // Korean
        flag += this.addFlag("PT", flagDomain, languageCode); // Portugues
        flag += this.addFlag("EL", flagDomain, languageCode); // Greek
        flag += this.addFlag("RO", flagDomain, languageCode); // Romanian
        flag += this.addFlag("RU", flagDomain, languageCode); // Russian
        flag += this.addFlag("NL", flagDomain, languageCode); // Dutch
        flag += "</ul>";

        $('#languageFlag').html(flag);
        $('#languageUl').show();
        document.onmousedown = HC.Language.hideLanguageFlag;
    },

    addFlag: function (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:HC.Language.changeLanguage('languageCode', '" + flagCode + "'); HC.Common.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
    hideLanguageFlag: function (e) {
        var target = (e ? e.target : event.srcElement);
        var flagUl = document.getElementById("languageUl");
        var flagSelected = document.getElementById("selected");
        if (flagUl != null && flagSelected != null) {
            (HC.Common.isChild(target, flagUl) || HC.Common.isChild(target, flagSelected)) ? null : flagUl.style.display = 'none';
        }
    },

    //add flags for pages in Widgets folder, can be removed after update Widgets files
    showLanguageFlags: function (flagDomain, languageCode, currentUrl) {
        var flag = "<ul id=\"languageUl\" style=\"display:none\">";
        flag += this.addFlagLink("EN", flagDomain, languageCode, currentUrl);
        flag += this.addFlagLink("DE", flagDomain, languageCode, currentUrl); // German
        flag += this.addFlagLink("ES", flagDomain, languageCode, currentUrl); // Spanish
        flag += this.addFlagLink("FR", flagDomain, languageCode, currentUrl); // French
        flag += this.addFlagLink("IT", flagDomain, languageCode, currentUrl); // Italian
        flag += this.addFlagLink("CS", flagDomain, languageCode, currentUrl); // Chinese Simplified
        flag += this.addFlagLink("CN", flagDomain, languageCode, currentUrl); // Chinese Traxditional
        flag += this.addFlagLink("JA", flagDomain, languageCode, currentUrl); // Japanese
        flag += this.addFlagLink("KO", flagDomain, languageCode, currentUrl); // Korean
        flag += this.addFlagLink("PT", flagDomain, languageCode, currentUrl); // Portugues
        flag += this.addFlagLink("EL", flagDomain, languageCode, currentUrl); // Greek
        flag += this.addFlagLink("RO", flagDomain, languageCode, currentUrl); // Romanian
        flag += this.addFlagLink("RU", flagDomain, languageCode, currentUrl); // Russian
        flag += this.addFlagLink("NL", flagDomain, languageCode, currentUrl); // Dutch         
        flag += "</ul>";

        $('#languageFlag').html(flag);
        $('#languageUl').show();
        document.onmousedown = HC.Language.hideLanguageFlag;
    },

    addFlagLink: function (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 + "'); HC.Common.displayNone('languageUl');\"><img src=\"" + flagDomain + "/Images/flags/" + flagCode + "-w.gif\" /></a></div></li>";
        }
    }
};


HC.Pagination = {
    reloadPage: function (name, val) {
        HC.Common.Status.DisplayFiltering({ paging: true });
        Reload(name, val);
    }
};

//ToDo - Fix up for affiliates
//Temp function wrappers until we have a better solution for Affiliates.
function changeLanguage(name, val) {
    return HC.Language.changeLanguage(name, val);
}

function showLanguageFlags(name, val) {
    return HC.Language.showLanguageFlags(flagDomain, languageCode, currentUrl);
}

function addLanguageFlags(flagDomain, languageCode) {
    return HC.Language.showLanguageFlags(flagDomain, languageCode);
}

function addFlag(flagCode, flagDomain, languageCode) {
    return HC.Language.addFlag(flagCode, flagDomain, languageCode);
}

function hideLanguageFlag(e) {
    return HC.Language.hideLanguageFlag(e);
}

function addFlagLink(flagCode, flagDomain, languageCode, currentUrl) {
    return HC.Language.addFlagLink(flagCode, flagDomain, languageCode, currentUrl);
}


