﻿var gSite = {    
    success: false, //This will be updated to "TRUE" if calling AdvMember.aspx successfully
    firstTime: true,    
    advMember: false,
    homePage: "http://www.accorhotels.com/gb/home/index.shtml?sourceid=AWEB-{sitecode}-{sitecountry}{extra}&merchantid=par-accor{sitecountry}",
    noArrival: "http://www.accorhotels.com/accorhotels/lien_externe.svlt?goto=rech_ville&nom_ville={keyword}&code_langue={languagecode}&code_chaine={codechain}&sourceid=AWEB-{sitecode}-{sitecountry}{extra}&merchantid=par-accor{sitecountry}",
    withArrival: "http://www.accorhotels.com/accorhotels/lien_externe.svlt?goto=rech_ville_dates&nom_ville={keyword}&jour_arrivee={arrivalday}&mois_arrivee={arrivalmonth}&annee_arrivee={arrivalyear}&nb_nuit={night}&jour_depart={departureday}&mois_depart={departuremonth}&annee_depart={departureyear}&force_origine_motcle=reservez&code_langue={languagecode}&code_chaine={codechain}&sourceid=AWEB-{sitecode}-{sitecountry}{extra}&merchantid=par-accor{sitecountry}",
    siteCode: "",
    siteCountry: "",
    languageCode: "gb",
    codeChain: "ALL",
    keyword: "",
    isAU: false,
    isNZ: false,
    xtor: "ADC-5083",
    externalTrackingCode: "",
    //xtor: "",
    isMigrated: true,
    backupConfig: {arrival: new Date(), locationTab: "", keywordTab: "", advMemberLogin: ""}
};

gSite.urlEncode = function(s) {
    return escape(s).replace("+", "%2B").replace("/", "%2F");
};

gSite.homePageUrl = function() {
    return this.homePage.replace(/{xtor}/, this.urlEncode(this.xtor))
        .replace(/{sitecode}/, this.urlEncode(this.siteCode))
        .replace(/{sitecountry}/g, this.urlEncode(this.siteCountry))
        .replace(/{extra}/g, "");
};

gSite.url = function(city, country, arrival, night, extra) {
   this.keyword = (city == "") ? country : city + "," + country;
   extra = (typeof(extra) == "undefined") ? "" : extra;
    
    if (arrival) {
        var departure = new Date(arrival);
        departure.setDate(departure.getDate() + night);
        var oriUrl = this.withArrival.replace(/{keyword}/, this.urlEncode(this.keyword))
            //.replace(/{xtor}/, this.urlEncode(this.xtor))     // xtor is replaced by external tracking code
            .replace(/{sitecode}/, this.urlEncode(this.siteCode))
            .replace(/{sitecountry}/g, this.urlEncode(this.siteCountry))
            .replace(/{extra}/, this.urlEncode(extra))
            .replace(/{arrivalday}/, this.urlEncode(this.d2(arrival.getDate())))
            .replace(/{arrivalmonth}/, this.urlEncode(this.d2(arrival.getMonth() + 1)))
            .replace(/{arrivalyear}/, this.urlEncode(arrival.getFullYear()))
            .replace(/{departureday}/, this.urlEncode(this.d2(departure.getDate())))
            .replace(/{departuremonth}/, this.urlEncode(this.d2(departure.getMonth() + 1)))
            .replace(/{departureyear}/, this.urlEncode(departure.getFullYear()))
            .replace(/{codechain}/, this.urlEncode(this.codeChain))
            .replace(/{languagecode}/, this.urlEncode(this.languageCode))
            .replace(/{night}/, this.urlEncode(night));
            
        return (typeof(generateNewUrl) == "function") ? generateNewUrl(oriUrl, this.externalTrackingCode) : oriUrl;    
            
    } else {
        var oriUrl = this.noArrival.replace(/{keyword}/, this.urlEncode(this.keyword))
            //.replace(/{xtor}/, this.urlEncode(this.xtor))     // xtor is replaced by external tracking code
            .replace(/{sitecode}/, this.urlEncode(this.siteCode))
            .replace(/{sitecountry}/g, this.urlEncode(this.siteCountry))
            .replace(/{languagecode}/g, this.urlEncode(this.languageCode))
            .replace(/{extra}/, this.urlEncode(extra))
            .replace(/{codechain}/, this.urlEncode(this.codeChain));
            
        return (typeof(generateNewUrl) == "function") ? generateNewUrl(oriUrl, this.externalTrackingCode) : oriUrl;    
    }
};

gSite.determineSite = function() {
    //Determine site code
    if (/sofitel/i.test(window.location.host)) {
        this.siteCode = "SOF";
        this.codeChain = this.siteCode;
    } else if (/novotel/i.test(window.location.host)) {
        this.siteCode = "NOV";
        this.codeChain = this.siteCode;
    } else if (/grandmercure/i.test(window.location.host) || /mercuregrand/i.test(window.location.host)) {
        this.siteCode = "MER";
        this.codeChain = this.siteCode;
    } else if (/mercure/i.test(window.location.host)) {
        this.siteCode = "MER";
        this.codeChain = this.siteCode;
    } else if (/ibis/i.test(window.location.host)) {
        this.siteCode = "IBI";
        this.codeChain = this.siteCode;
    } else if (/formule1/i.test(window.location.host)) {
        this.siteCode = "FOR";
        this.codeChain = this.siteCode;
    } else if (/allseasons/i.test(window.location.host)) {
        this.siteCode = "ASE";
        this.codeChain = this.siteCode;
    } else {
        this.siteCode = "ACC";
        this.codeChain = "ALL";
    }
};

gSite.determineCountry = function() {
    //Determine site country
    if ((typeof(gSiteCountry) != "undefined") && (typeof(gSiteCountry) == "string")) {
        //In SSL, we cannot recognize country from URL. So we will check the site country from "siteCountry" variable instead.
        this.siteCountry = gSiteCountry;
    } else {
        var matches = /\.(\w+)$/.exec(window.location.host.toUpperCase());
        if (matches) {
            switch(matches[1]) {
                case "AU":
                case "NZ":
                case "FJ":                    
                case "JP":
                    this.languageCode = "gb";
                    this.siteCountry = matches[1];
                    break;                
                case "CN":                
                    this.languageCode = "zh";
                    this.siteCountry = matches[1];
                    break;
                default:
                    this.siteCountry = "AS";
            }
        }
    }
	this.isAU = (this.siteCountry == "AU");
	this.isNZ = (this.siteCountry == "NZ");
};

gSite.determineXtor = function() {
    if (document.cookie && document.cookie != "") {
        var cookies = document.cookie.split(";");
        for(var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
            if (cookie.substring(0, "xtor".length + 1) == "xtor=") {
                this.xtor = decodeURIComponent(cookie.substring("xtor".length + 1));
                break;
            }
        }
    } 
};

gSite.determineExternalTrackingCode = function() {
    if (typeof(createTracking) == "function") {
        this.externalTrackingCode = createTracking();
    }
};

gSite.generateNights = function() {
    for(var i = 1; i <= 23; i++) {
        $("#TabLocation #cmbNights").append("<option value=\"{order}\">{order}</option>".replace(/{order}/g, i));    
        $("#TabKeyword #cmbNights").append("<option value=\"{order}\">{order}</option>".replace(/{order}/g, i));    
    }    
    $("#TabLocation #cmbNights").prepend("<option value=\"\">-</option>");    
    $("#TabKeyword #cmbNights").prepend("<option value=\"\">-</option>");    
};

gSite.updateWhenAdvMemberLoginLogout = function() {
    var showNights = this.isMigrated || !(this.advMember || this.isAU || this.isNZ);
    $("#TabLocation .Night").css("visibility", showNights ? "visible" : "hidden");
    $("#TabLocation .txt span").css("visibility", showNights ? "visible" : "hidden");
    $("#TabKeyword .Night").css("visibility", showNights ? "visible" : "hidden");
    $("#TabKeyword .txt span").css("visibility", showNights ? "visible" : "hidden");
    this.updatePromotionLinks();
    this.updateValidationRules(showNights);	
	this.updateAdvMemberBox();	
	//Show alert box when login as AD+
	if (this.advMember && (typeof(AClubAlert) == "object")) AClubAlert.Execute();
    
    if (showNights) {   
        $("#TabLocation #cmbDay4Location").prepend("<option value=\"\">-</option>").find("option:first").attr("selected", "selected");
        $("#TabLocation #cmbMonthYear4Location").prepend("<option value=\"\">-</option>").find("option:first").attr("selected", "selected");
        $("#TabLocation #cmbNights option:first").attr("selected", "selected");
        $("#TabKeyword #cmbDay").prepend("<option value=\"\">-</option>").find("option:first").attr("selected", "selected");
        $("#TabKeyword #cmbMonthYear").prepend("<option value=\"\">-</option>").find("option:first").attr("selected", "selected");        
        $("#TabKeyword #cmbNights option:first").attr("selected", "selected");
    } else {
        $("#TabLocation #cmbDay4Location option[value='']").remove();
        $("#TabLocation #cmbMonthYear4Location option[value='']").remove();
        $("#TabKeyword #cmbDay option[value='']").remove();
        $("#TabKeyword #cmbMonthYear option[value='']").remove();

        var d = this.d2(this.backupConfig.arrival.getDate());
        var my = this.d2(this.backupConfig.arrival.getMonth() + 1) + "/" + this.backupConfig.arrival.getFullYear();             
        $("#TabLocation #cmbDay4Location option[value=" + d + "]").attr("selected", "selected");
        $("#TabLocation #cmbMonthYear4Location option[value=" + my + "]").attr("selected", "selected");
        $("#TabKeyword #cmbDay option[value=" + d + "]").attr("selected", "selected");
        $("#TabKeyword #cmbMonthYear option[value=" + my + "]").attr("selected", "selected");
    }
    
    //Fire event to append all "a" tag linking to www.accorhotels.com with external tracking
    $("div#divTracking").trigger("track");
};

gSite.updateAdvMemberBox = function() {	
	//We don't allow brand site to sign in as Adv+
	this.backupConfig.advMemberLogin = $("#advContent form").attr("onsubmit");
	$("#advContent form").removeAttr("onsubmit").unbind("submit");
	if (!/ACC/i.test(this.siteCode) && $("#contents #right #greatrate").length && !this.advMember) {		
		$("#advContent .advInput").css("display", "none");
		$("#advContent form").submit(
			function() {
				window.location.href = (/AU|NZ|FJ/.test(gSite.siteCountry) ? "http://www.accorhotels.com.au/advplus" : "http://www.accorhotels-asia.com/advplus");
				return false;
			}
		);
	} else {
		var match = /return\s+(.+)/.exec(this.backupConfig.advMemberLogin);
		var fn = function() { return eval(match[1]);};
		$("#advContent form").submit(fn);
	}
};

gSite.updatePromotionLinks = function() {
    var openNewWindow = ((!this.isMigrated) && (this.advMember || this.isAU || this.isNZ)) ? false : true;
    //var openNewWindow = (this.isAU) ? false : true;
    var regex = /(\d+):(.*)\|(\w*):(.+)/; //CityId:City|CountryCode:Country
    
    if ($("span#HomePage").length) {
        if (openNewWindow) {
            //Great Rates
            $("#right #greatrate li a").each(function() {
                    var match = regex.exec($(this).next().text());
                    if (match) {
                        $(this).attr("href", gSite.url(match[2], match[4], null, 1, "-GRR"));
                    }                    
                });
        } else {
            //Great Rates
            $("#right #greatrate li a").each(function() {
                    var match = regex.exec($(this).next().text());
                    if (match) {
                        $(this).attr("href", "/search/default.aspx?city=" + match[1] + "&country=" + match[3]);
                    }
                });
        }
    }
};

/*
* This function will add "target=_blank" to all promotion links.
*
gSite.updatePromotionLinks = function() {
    var openNewWindow = (this.advMember || this.isAU) ? false : true;
    var regex = /(\d+):(\w*)\|(\w*):(\w+)/; //CityId:City|CountryCode:Country
    
    if ($("span#HomePage").length) {
        if (openNewWindow) {
            //Promotions
            $(".leftBox a, .rightBox a", "PromoBlock_PromoBlockRow2").attr("target", "_blank");
            //Promotion and Specials
            $("#promotion_List a").attr("target", "_blank");
            //Great Rates
            $("#right #greatrate li a").attr("target", "_blank").each(function() {
                    var match = regex.exec($(this).next().text());
                    if (match) {
                        $(this).attr("href", gSite.url(match[2], match[4], null, 1, "-GRR"));
                    }                    
                });
        } else {
            //Promotions
            $(".leftBox a, .rightBox a", "PromoBlock_PromoBlockRow2").removeAttr("target");
            //Promotion and Specials
            $("#promotion_List a").removeAttr("target");
            //Great Rates
            $("#right #greatrate li a").removeAttr("target").each(function() {
                    var match = regex.exec($(this).next().text());
                    if (match) {
                        $(this).attr("href", "/search/default.aspx?city=" + match[1] + "&country=" + match[3]);
                    }
                });
        }
    }
};
*/

gSite.updateValidationRules = function(showNights) {
    var regex = /return\s+(g?)(ValidateSearch4Location)/;
    var regex2 = /return\s+(g?)(ValidateSearch)/;
    var fn = null;
    var fn2 = null;
    $("#TabLocation form").removeAttr("onsubmit").unbind("submit");        
    $("#TabKeyword form").removeAttr("onsubmit").unbind("submit");            
    if (showNights) {
        fn = function() { return eval(gSite.backupConfig.locationTab.replace(regex, "g$2")); };
        fn2 = function() { return eval(gSite.backupConfig.keywordTab.replace(regex2, "g$2")); };
    } else {
        fn = function() { return eval(gSite.backupConfig.locationTab.replace(regex, "$2")); };
        fn2 = function() { return eval(gSite.backupConfig.keywordTab.replace(regex2, "$2")); };
    }
    
    $("#TabLocation form").submit(fn);
    $("#TabKeyword form").submit(fn2);
    //The below commands will show warning message when we treat ADV+ as poublic
    //$("#TabLocation form").submit(function() { return gSite.advSearch(fn, $("#TabLocation form")[0]); });
    //$("#TabKeyword form").submit(function() { return gSite.advSearch(fn2, $("#TabKeyword form")[0]); });
};

gSite.advSearch = function(callback, scope) {
    if (this.advMember) {        
        if ($("div#divAdvWarning").size() > 0) {
            $("div#divAdvWarning a:first").unbind("click").click(gSite.hideAdvPlusMessageBox);
            $("div#divAdvWarning a:eq(1)").unbind("click").click(function() { 
                gSite.hideAdvPlusMessageBox();
                window.setTimeout(function() { callback.call(scope); }, 500)
                return false; 
            });
            
            var ref = $("button[type=submit]", scope); 
            this.showAdvPlusMessageBox(ref);
        }
        return false;
    } else {
        return callback.call(scope);
    }
};

gSite.showAdvPlusMessageBox = function(ref) {
    var offset = ref.offset();
    var cOffset = $("#wrapper #contents").offset();
    if (offset.left < 800) {
        $("div#divAdvWarning").css(
            {
                left: ref.width() + offset.left - cOffset.left + "px",
                top: offset.top - cOffset.top + "px"
            }).show("fast");
    } else {        
        $("div#divAdvWarning .btop img").removeAttr("width").removeAttr("height").attr("src", "/images/bubble/bubble_ptop400.gif");     
        $("div#divAdvWarning .pleft").removeClass("pleft").addClass("bleft");
        $("div#divAdvWarning").css(
            {
                left: offset.left - cOffset.left + ref.width() -  $("div#divAdvWarning").width() + "px",
                top: offset.top - cOffset.top + ref.height() + "px"
            }).show("fast");
    }
};

gSite.hideAdvPlusMessageBox = function() {
    $("div#divAdvWarning").hide("fast");
    return false;
};

gSite.updateAdvMember = function() {
    $.ajax({
        type: "GET",
        url: "/remote/advmember.aspx",
        cache: false,
        timeout: 5000,
        dataType: "json",
        success: function(json, status) {
            gSite.success = true;
            gSite.advMember = json.AdvMember.isAuthenticated;
            gSite.languageCode = json.AdvMember.languageCode;
        },
        error: function(XMLHttpRequest, status) {
            gSite.success = false;
            gSite.advMember = false;
        },
        complete: function(XMLHttpRequest, status) {
            // To make it compatible to the old version
            if (!gSite.firstTime && (typeof(updateAdvMember_onComplete) == "function")) updateAdvMember_onComplete();
            gSite.updateWhenAdvMemberLoginLogout();
            gSite.firstTime = false;
        }
    });
};

gSite.backup = function() {
    var arrival = $("#TabLocation #cmbDay4Location").val() + "/" + $("#TabLocation #cmbMonthYear4Location").val();
    var match = /(\d{2})\/(\d{2})\/(\d{4})/.exec(arrival);
	if (match) this.backupConfig.arrival = new Date(Number(match[3]), Number(match[2]) - 1, Number(match[1]));
    this.backupConfig.locationTab = $("#TabLocation form").attr("onsubmit");
    this.backupConfig.keywordTab = $("#TabKeyword form").attr("onsubmit");
	this.backupConfig.advMemberLogin = $("#advContent form").attr("onsubmit");
};

gSite.d2 = function(n) {
    var pad = "0" + n;
    return (pad.length > 2) ? pad.substring(1, pad.length) : pad;
};

gSite.init = function() {    
    this.backup();
    this.determineSite();
    this.determineCountry();
    //this.determineXtor();
    this.determineExternalTrackingCode();
    this.determineXtor();
    this.overwriteLanguageBar();
    this.overwriteFooter();
    this.removeLinks();
    this.generateNights();
    this.updateAdvMember();
    this.initValidationRules();       
    //Temporary solutions
    this.removeAdvPlusLinks();
};

gSite.removeAdvPlusLinks = function() {
    if (/https?:\/\/[^\/]+\/advplus\//.test(window.location.href)) {
        $("div#footer, div#siteMenu").remove();
        $("div#breadCrumb > a:lt(2)").each(function() {            
            $(this).after($(this).html()).remove();
        });
    }
};

gSite.overwriteFooter = function() {
    $("#footer select[name=accor-sites]").find("option[value*=accorhotels.com]")
        .attr("value", gSite.homePageUrl());
};

gSite.removeLinks = function() {
    var $el = $("div#breadCrumb a:first");
    $el.after($el.html()).remove();
};

gSite.overwriteLanguageBar = function() {
    $("#language li a[href*=SwitchLanguage(]").each(
        function() {
            var match = /SwitchLanguage\('(\w+)'\)/.exec($(this).attr("href"));
            if (match) {
                $(this).attr("href", "#").click(function() { return gSwitchLanguage(match[1]); });            
            }
        }
    );
};

gSite.initValidationRules = function() {
    $(".device select[name^=cmbDay]").change(gAutoSelectNights);
    $(".device select[name^=cmbMonthYear]").change(gAutoSelectNights);
};

//Call initial function
$(document).ready(
    function() {
        gSite.init.call(gSite);
    }
);

function gValidateSearch(frm) {
    var intError = 0;
    var err = "";
    var accommodationType = 'All';
    
    if (isEmpty(frm.txtSearch.value)) {
        intError = 1;
        err += 'Please enter a keyword to search\n';
    }

    if (!isValidHTMLInput(frm.txtSearch.value)) {
        intError = 1;
        err += 'Keyword is invalid\n';
    }
        
    var isArrivalSelected = (($("#TabKeyword #cmbDay").val() + $("#TabKeyword #cmbMonthYear").val() + $("#TabKeyword #cmbNights").val()) != "");    
    if (isArrivalSelected && 
        (
            !isValidDate($("#TabKeyword #cmbDay").val() + "/" + $("#TabKeyword #cmbMonthYear").val())
            || (Number($("#TabKeyword #cmbNights").val()) <= 0)
        )) 
    {
        err += 'Please select a valid arrival date and night(s)\n';
        intError = 1;
    }         

    if ((!(frm.chkHotel.checked || frm.chkApartment.checked))&& (intError != 1)) {
        err += 'Please specify type of accommodation to search\n';
        intError = 1;
    }
    else {
        var result = 0;
        if (frm.chkHotel.checked) result += parseInt(frm.chkHotel.value);
        if (frm.chkApartment.checked) result += parseInt(frm.chkApartment.value);
        switch (result) {
            case 1:
                accommodationType = 'Hotel';
                break;
            case 2:
                accommodationType = 'Apartment';
                break;
        }
    }
    
    if (intError) {
        alert(err);
        return false;
    } else {
        //AdvantagePlus warning
        if (gSite.advMember) gSite.advPlusWarning();
        
        //if (gSite.advMember || gSite.isAU) {   
        if (!gSite.isMigrated && gSite.isAU) {   
            //Original               
            window.location.href = frm.action + '?date=' + frm.cmbDay.options[frm.cmbDay.selectedIndex].value + '/' + frm.cmbMonthYear.options[frm.cmbMonthYear.selectedIndex].value + '&keyword=' + frm.txtSearch.value + '&mm=' + frm.mm.value + '&booking=' + frm.booking.value + '&accommodation=' + accommodationType;
        } else {            
            //Not AU Sites 
            var matches = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(frm.cmbDay.options[frm.cmbDay.selectedIndex].value + "/" + frm.cmbMonthYear.options[frm.cmbMonthYear.selectedIndex].value);            
            var arrival = null;
            var nights = 1;
            if (matches) {
                arrival = new Date(Number(matches[3]), Number(matches[2]) - 1, Number(matches[1]));
                nights = Number($("#TabKeyword #cmbNights").val());
            }
            //alert(gSite.url("", frm.txtSearch.value, arrival, nights, "-HPR"));
            window.location.href = gSite.url("", frm.txtSearch.value, arrival, nights, "-HPR");
            /*
            var feature = "width={w},height={h},top=0,left=0,location=1,menubar=1,resizable=1,scrollbars=1,status=1,titlebar=1,toolbar=1".replace(/{w}/, screen.width).replace(/{h}/, screen.height);
            window.open(gSite.url("", frm.txtSearch.value, arrival, nights, "-HPR")
                        , "gWindow"
                        , feature);            
            */
        }
        return false;
    }
};

function gValidateSearch4Location(frm, prefix) {
    var intError = 0;
    var err = "";
    var accommodationType = 'All';
    var country, countryText;
    var city, cityText;
    
    if ($("#TabLocation select[id$=selCountries]")[0].selectedIndex == 0) {
        err += 'Please select a country to search\n';
        intError = 1;
    }
    
    var isArrivalSelected = (($("#TabLocation #cmbDay4Location").val() + $("#TabLocation #cmbMonthYear4Location").val() + $("#TabLocation #cmbNights").val()) != "");    
    if (isArrivalSelected && 
        (
            !isValidDate($("#TabLocation #cmbDay4Location").val() + "/" + $("#TabLocation #cmbMonthYear4Location").val())
            || (Number($("#TabLocation #cmbNights").val()) <= 0)
        )) 
    {
        err += 'Please select a valid arrival date and night(s)\n';
        intError = 1;
    }
            
    if((!(frm.chkHotel.checked || frm.chkApartment.checked)) && (intError != 1)) {
        err += 'Please specify type of accommodation to search\n';
        intError = 1;
    }
    else {
        var result = 0;
        if (frm.chkHotel.checked) result += parseInt(frm.chkHotel.value);
        if (frm.chkApartment.checked) result += parseInt(frm.chkApartment.value);
        switch (result) {
            case 1:
                accommodationType = 'Hotel';
                break;
            case 2:
                accommodationType = 'Apartment';
                break;
        }
    }
    
    if (intError) {
        alert(err);
        return false;
    } else {       
        //AdvantagePlus warning
        if (gSite.advMember) gSite.advPlusWarning(); 
        
        country = $("#TabLocation select[id$=selCountries]").val();
        countryText = (typeof(gCountries) == "undefined") ? $("#TabLocation select[id$=selCountries]").find(":selected").text() : gSite.enCountry(country);        
        
        if (frm.cmbSearchLocation.value.lastIndexOf("_all") == -1) {
            city = frm.cmbSearchLocation.value;
            cityText = (typeof(gCountries) == "undefined") ? frm.cmbSearchLocation.options[frm.cmbSearchLocation.selectedIndex].text : gSite.enCity(city);
        } else {
            city = "";
            cityText = "";
        }

        if (country == "OTHER") {
            window.location.href = "http://www.accorhotels.com";
        //} else if (gSite.advMember || gSite.isAU) {   
        } else if (!gSite.isMigrated && gSite.isAU) {   
            //Original               
            window.location.href = frm.action + '?date=' + frm.cmbDay4Location.options[frm.cmbDay4Location.selectedIndex].value + '/' + frm.cmbMonthYear4Location.options[frm.cmbMonthYear4Location.selectedIndex].value + '&country=' + country + '&city=' + city + '&mm=' + frm.mm.value + '&booking=' + frm.booking.value + '&accommodation=' + accommodationType;
        } else {
            //Not AU Sites 
            var matches = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(frm.cmbDay4Location.options[frm.cmbDay4Location.selectedIndex].value + "/" + frm.cmbMonthYear4Location.options[frm.cmbMonthYear4Location.selectedIndex].value);            
            var arrival = null;
            var nights = 1;
            if (matches) {
                arrival = new Date(Number(matches[3]), Number(matches[2]) - 1, Number(matches[1]));
                nights = Number($("#TabLocation #cmbNights").val());
            }
            //alert(gSite.url(cityText, countryText, arrival, nights, "-HPR"));
            window.location.href = gSite.url(cityText, countryText, arrival, nights, "-HPR");
            /*
            var feature = "width={w},height={h},top=0,left=0,location=1,menubar=1,resizable=1,scrollbars=1,status=1,titlebar=1,toolbar=1".replace(/{w}/, screen.width).replace(/{h}/, screen.height);
            window.open(gSite.url(cityText, countryText, arrival, nights, "-HPR")
                        , "gWindow"
                        , feature);                        
            */
        }
        return false;
    }
};

function gAutoSelectNights() {
    var match = /li(TabKeyword|TabLocation)/.exec($(".device li.active")[0].id);    
    if (match != null) {
        var activeTab = "#" + match[1];
        var arrivalDay = $("select[name^=cmbDay]", activeTab).val();
        var arrivalMonthYear = $("select[name^=cmbMonthYear]", activeTab).val();
        if ((arrivalDay != "") && (arrivalMonthYear != "")) {
            $("#cmbNights option:eq(1)", activeTab).attr("selected", "selected");
        } else if ((arrivalDay + arrivalMonthYear) == "") {
            $("#cmbNights option:first", activeTab).attr("selected", "selected");
        } 
    }
};

function gSwitchLanguage(lang) {
    var currentUrl = window.location.href;
    currentUrl.match(/([^\?|#]+)\??([^#]*)(?:#)?(.*)/i);
    var path = RegExp.$1;
    var query = RegExp.$2;
	var hash = RegExp.$3;
    
    query = query.replace(/__languagecode__=\w*&?/i, "");
    var l = (query == "") ? "" : "&";
    l = l + "__languagecode__=" + lang;
	var h = (hash == "") ? "" : "#";
	h = h + hash;
    var newUrl = path + "?" + query + l + h;
    switch(lang) {
        case "zh":
        case "ch":
            var url = "http://www.accorhotels.com/zh/home/index.shtml?xtor={xtor}&sourceid=AWEB-{sitecode}-{sitecountry}&code_chaine={codechain}&merchantid=par-accor{sitecountry}";
            window.location.href = url
                                    .replace(/{xtor}/g, gSite.xtor)
                                    .replace(/{sitecode}/g, gSite.siteCode)
                                    .replace(/{sitecountry}/g, gSite.siteCountry)
                                    .replace(/{codechain}/g, gSite.codeChain);
            break;
        default:
            window.location.href = newUrl;    
            break;
    }  
    return false;  
};

gSite.advPlusWarning = function() {
    alert('Accor Advantage Plus Members. Please note, Rates offered here do not include your members\' discount and benefits. To View and Book your Members\' Rates please go to your Members\' home page and start a search.');
};

gSite.enCountry = function(countryCode) {
    var enName = "";
    if (typeof(gCountries) != "undefined") {
        $.each(gCountries, function() {
            if (this.Code == countryCode) {
                enName = this.Name;
                return false;
            }
        });
    }
    
    return enName;
};

gSite.enCity = function(cityId) {
    var enName = "";
    if (typeof(gCountries) != "undefined") {
        $.each(gCountries, function() {
            if (enName != "") return false;
            $.each(this.Cities, function() {
                if (this.Id == cityId) {
                    enName = this.Name;
                    return false;
                }
            });
        });
    }
        
    return enName;
};