$.extend({ URLEncode: function (c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        } 
    } return o;
},
    URLDecode: function (s) {
        var o = s;
        var binVal, t, b;
        var r = /(%[^%]{2}|\+)/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            if (m[1] == '+') {
                t = ' ';
            } else {
                b = parseInt(m[1].substr(1), 16);
                t = String.fromCharCode(b);
            }
            o = o.replace(m[1], t);
        }
        return o;
    }
});


// add addtional click events, but don't clear out the current click events
var lastClicker = '';
var list = document.getElementsByTagName('input');
for (var i = 0; i < list.length; i++) {
    if (list[i].type.toLowerCase() == 'submit' || list[i].type.toLowerCase() == 'image') {
        list[i].oldClick = list[i].onclick;

        list[i].onclick = function () {
            lastClicker = this.id;
            if (this.oldClick)
                this.oldClick();
        }
    }
}

function formatSearchURL(url) {
    var sel = $("#find_a_hotel .hotel_type");
    if (sel.length > 0 && url != '' && sel.val() != 0 && sel.val() != '') {
        var holType = $("#find_a_hotel .hotel_type option:selected").text();
        holType = $.URLEncode(holType);

        if (url.indexOf("/country/") > 0) {
            url = url.replace("/country/", "/country_type/")
            url = url.replace("/page0.html", "/" + holType + "/page0.html")
        }
        else if (url.indexOf("/destination/") > 0) {
            url = url.replace("/destination/", "/destination_type/")
            url = url.replace("/page0.html", "/" + holType + "/page0.html")
        }

    }
    return url + '';
}

function addSelectionsCookie() {
    var value = "a:" + $("#find_a_hotel .arriving").val() + "|" + "n:" + $("#find_a_hotel .no-of-nights").val() + "|" + "g:" + $("#find_a_hotel .guests").val();
    setCookie("SearchWidget", value, 10, "/");
    return (getCookie("SearchWidget") != "");
}

function appendSearchCriteria(searchUrl) {
    searchUrl += "&a=" + $("#find_a_hotel .arriving").val();
    searchUrl += "&n=" + $("#find_a_hotel .no-of-nights").val();
    searchUrl += "&g=" + $("#find_a_hotel .guests").val();
    return searchUrl;
}

$.mmdd = function () { }

$.mmdd.hoverIntentTimer = 0;
$.mmdd.hoverIntentDelay = 200;

$.mmdd.initMega = function () {
    this.setHeightEvents(this.megaVars);
};

$.mmdd.megaVars = {
    dropdown: $("#dm"),
    link: $("#mega-target"),
    parent: $("#navigation"),
    height: 300
};

$.mmdd.setHeightEvents = function (target) {
    target.link.bind("mouseenter", function (e) {
        $.mmdd.hoverIntentTimer = window.setTimeout(function () {
            $.mmdd.hoverIntentTimer = 0;
            target.dropdown.show()
            target.link.addClass("down");
        }, $.mmdd.hoverIntentDelay);
    });
    target.link.bind("mouseleave", function (e) {
        if ($.mmdd.hoverIntentTimer > 0) {
            window.clearTimeout($.mmdd.hoverIntentTimer);
            return;
        }
        target.dropdown.hide()
        target.link.removeClass("down");
    })
};



$("#dm").bgiframe();

$.mmdd.initMega();

var ac_el = $("#find_a_hotel .ac");
var ac_sel = $("#find_a_hotel .hotel_type");
var searchURL = $("#find_a_hotel").find(".search_url").val();
var queryTerm = '';
var searchType = $("#find_a_hotel").find(".search_type").val();

ac_el.focus(function (e) {
    if (this.getAttribute("value") == "Country, City or Hotel") {
        this.setAttribute("value", "")
    }
})

doneQueryReplace = true;
var regex = new RegExp("[\\?&]q=([^&#]*)");
var results = regex.exec(window.location.href);
if (results != null) {
    var repl = results[1];
    queryTerm = repl;
    ac_el.val($.URLDecode(repl));
}

ac_el.autocomplete("/Handlers/FindHotelHandler.ashx", {
    max: 15,
    delay: 200,
    cacheLength: 10,
    minChars: 1,
    mustMatch: false,
    matchSubset: false,
    matchContains: false,
    selectFirst: false,
    autoFill: false,
    scroll: false,
    extraParams: {
        hoteltype: function () {
            return ac_sel.attr("value")
        },
        lang: currentLanguage,
        epslanguage: currentLanguage
    },
    formatItem: function (item) {
        return item[0];
    }

});

//Make sure the search URL is cleared if the user types anything
ac_el.keyup(function (e) {
    var key = e.keyCode;
    // Up, down, or enter key
    if (key != 40 && key != 38 && key != 13) {
        searchURL = '';
    }
})


//Flush the cache on select change
ac_sel.change(function (e) {
    ac_el.flushCache();
})

//Flag ac_on to prevent form submit
ac_el.result(function (event, item) {
    var searchResult = item[0];
    if (searchResult.indexOf("(") > 0) {
        searchResult = searchResult.substring(0, item[0].indexOf("(", 0) - 1);
        ac_el.val(searchResult);
    }

    searchURL = item[1];
    searchType = item[2];
});

var findInProgress = false;

// If we have a search URL as returned by the auto complete function then use that rather than 
// submitting the search to the server
$("#aspnetForm").bind("submit", function (e) {
    var buttonName = "_FindHotelButton";
    if (lastClicker.length < buttonName.length || lastClicker.substr(lastClicker.length - buttonName.length) != buttonName)
        return;

    e.preventDefault();

    if (findInProgress)
        return;

    if (($("#find_a_hotel .ac_input").val() == "" || $("#find_a_hotel .ac_input").val().toLowerCase() == $("#find_a_hotel .defaultDestination").val().toLowerCase())) {
        if ($("#find_a_hotel .hotel_type").length == 0 || $("#find_a_hotel .hotel_type").val() == 0) {
            $("#find_a_hotel .ac_input").focus();
            return;
        }
    }

    findInProgress = true;

    // perform a club login
    if ($(".club-member :checkbox").attr("checked") == true) {
        var index = ($(".club_membership_number").length > 1 ? 1 : 0);

        $.ajax({
            type: "POST",
            async: false,
            url: "/Handlers/ClubLoginHandler.ashx",
            data: "mn=" + $(".club_membership_number").get(index).value + "&pwd=" + $(".club_password").get(index).value + "&rm=" + ($(".club-remember :checkbox")[index].checked ? "1" : "0"),
            success: function (data) {
                if (data != "0")
                    return;

                var index = ($(".club_membership_number").length > 1 ? 1 : 0);

                if ($(".club-remember :checkbox")[index].checked) {
                    var value = "authMembershipNumber=" + $(".club_membership_number").get(index).value + ";authPassword=" + $(".club_password").get(index).value;
                    setCookie("authUser", value, 15, "/");
                }
                else
                    setCookie("authUser", "", -15, "/");
            }
        });
    }

    if (searchURL != '') {

        var url = searchURL;
        url = formatSearchURL(url);

        if (
            searchType == "HOTEL" &&
            $("#find_a_hotel").find(".arriving").val() &&
            $("#find_a_hotel").find(".arriving").val() !== 'dd/mm/yyyy' &&
            $("#find_a_hotel").find(".no-of-nights").val() &&
            $("#find_a_hotel").find(".guests").val()
        ) {
            url += "?redirectToBooking=true";
        }
        //            //only append term for non hotel searches.
        //            if (searchType != "HOTEL")
        //            {
        //               url += "?q=" + $.URLEncode(ac_el.val());
        //            }

        if (url.indexOf("/hotelfinder", 0) > 0) {
            var sel = $("#find_a_hotel .hotel_type");
            if (sel.val() != 0) {
                var holType = $("#find_a_hotel .hotel_type option:selected").text();
                holType = $.URLEncode(holType);
                url += "&t=" + holType;
            }

            if (!addSelectionsCookie())
                url = appendSearchCriteria(url);

            location.href = url;
        }
        else {
            if (!addSelectionsCookie())
                url = appendSearchCriteria(url);

            location.href = url;
        }
    }
    else {
        $.ajax({
            url: "/Handlers/FindHotelHandler.ashx",
            data: $.extend({
                q: ac_el.val(),
                limit: 15,
                lang: currentLanguage,
                epslanguage: currentLanguage,
                hotelType: ac_sel.attr("value")
            }, {
                hoteltype: function () {
                    return $("select[name=hotel_type]").attr("value")
                }
            }
				),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var errorUrl = "/hotelfinder/keyword/" + $.URLEncode(ac_el.val()) + "/page0.html";
                errorUrl = formatSearchURL(errorUrl);
                errorUrl += "?q=" + $.URLEncode(ac_el.val());

                if (errorUrl.indexOf("/hotelfinder", 0) > 0) {
                    var sel = $("#find_a_hotel .hotel_type");
                    if (sel.val() != 0) {
                        var holType = $("#find_a_hotel .hotel_type option:selected").text();
                        holType = $.URLEncode(holType);
                        errorUrl += "&t=" + holType;
                    }

                    if (!addSelectionsCookie())
                        errorUrl = appendSearchCriteria(errorUrl);

                    location.href = errorUrl;
                }
                else {
                    if (!addSelectionsCookie())
                        errorUrl = appendSearchCriteria(errorUrl);

                    location.href = errorUrl;
                }
            },
            success: function (data) {
                // get the entered form value

                var val = ac_el.val() + " ";
                if (val.length > 0 && data.length > 0) {
                    var terms = new Array();
                    var urls = new Array();
                    var types = new Array();

                    while (data.indexOf("|") != -1) {
                        var term = data.substr(0, data.indexOf("|")) + " ";
                        //var url = data.substr(data.indexOf("|") + 1);

                        var url = data.substr(data.indexOf("|") + 1, data.indexOf("|", data.indexOf("|") + 1) - data.indexOf("|") - 1);
                        if (url.indexOf("\r\n") != -1)
                            url = url.substr(0, url.indexOf("\r\n"));
                        data = (data.indexOf("\r\n") != -1 ? data = data.substr(data.indexOf("\r\n") + 2) : "");
                        terms.push(term);
                        urls.push(url);
                    }

                    for (i = 0; i < terms.length; i++) {
                        var term = terms[i];

                        if (val.length > term.length)
                            continue;

                        if (term.toLowerCase().substr(0, val.length) == val.toLowerCase()) {
                            searchURL = urls[i];
                            searchURL = formatSearchURL(searchURL);

                            if (term.indexOf("(") > 0)
                                term = term.substring(0, term.indexOf("(", 0) - 1);

                            //only append term for non hotel searches.
                            //                                if (searchType != "HOTEL")
                            //                                {
                            //                                   searchURL += "?q=" + $.URLEncode(term);
                            //                                }

                            if (searchURL.indexOf("/hotelfinder", 0) > 0) {
                                var sel = $("#find_a_hotel .hotel_type");
                                if (sel.val() != 0) {
                                    var holType = $("#find_a_hotel .hotel_type option:selected").text();
                                    holType = $.URLEncode(holType);
                                    searchURL += "&t=" + holType;
                                }
                            }
                            break;
                        }
                    }
                }

                if (searchURL.length > 0) {
                    if (!addSelectionsCookie())
                        searchURL = appendSearchCriteria(searchURL);

                    location.href = searchURL;
                }
                else {
                    document.getElementById("__EVENTTARGET").value = lastClicker;

                    if (!addSelectionsCookie())
                        document.getElementById("__EVENTARGUMENT").value = appendSearchCriteria("").substr(1);
                    document.forms[0].submit();
                }
            }
        });
    }
});

