﻿$(document).ready(function () {

    var optionCutOff = 3;

    // Init functions
    loadSelectionList();
    showOrHideOptions(optionCutOff);

    $(".sidebar_menu_item_content input[type=checkbox]").click(function () {

        if ($(this).hasClass("qreValue") || $(this).hasClass("qrsValue")) {

            if ($(this).attr("checked")) {
                $(".qreValue, .qrsValue").attr("checked", "");
                $(this).attr("checked", "true");
            }
            else {
                $(".qreValue, .qrsValue").attr("checked", "");
                $(this).attr("checked", "");
            }
        }

        var filterURL = createURL();
        loadPage(filterURL, true);
    });

    $(".sidebar_menu_item_content select").change(function () {

        var filterURL = createURL(true);
        $("#filter_loading").css("height", ($("#sidebar_menu_content").height() + 35) + "px");
        $("#filter_loading").show()
        loadPage(filterURL, true);

    });

    $("#loadSelectionList li").click(function () {
        $(this).remove();

        $("[name='" + $(this).attr("id") + "']").attr("checked", "");

        if ($(this).attr("id") == "qSelect")
            $("#hfQuery").val('');

        var filterURL = createURL();

        loadPage(filterURL, true);
    });


    ////////////////////////
    // Register click URL //
    ////////////////////////


    $(".item").click(function () {

        var clickUrl = $("[type='hidden']", this).val();

        callClickURL(clickUrl);

        var host = window.location.host;

        window.location = "http://" + host + $("[title='Lees meer']", this).attr("href");

        return false;
    });


    $(".read_more_trip, .btn_look").click(function () {

        var clickUrl = $(this).parent().parent().parent().parent().parent().find("[type='hidden']").val()

        callClickURL(clickUrl);

        var host = window.location.host;

        window.location = "http://" + host + $(this).attr("href");

        return false;
    });

    function callClickURL(clickUrl) {
        if (clickUrl) {
            setTimeout(function () {
                if ($.browser.msie && window.XDomainRequest) {
                    var xdr = new XDomainRequest();
                    xdr.open("get", clickUrl);
                    xdr.send();
                }
                else {
                    $.ajax({
                        type: "POST",
                        url: clickUrl,
                        data: null,
                        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                        cache: false,
                        async: false
                    });
                }
            }, 100);
        }
    }

    //////////////////////////
    // Pagination functions //
    //////////////////////////  

    $(".pagination_btn").click(function () {
        if ($(this).hasClass("active"))
            return false;
        else
            showLoadingImg();
    });

    $(".previous_btn").click(function () {
        showLoadingImg();
    });

    $(".next_btn").click(function () {
        showLoadingImg();
    });

    //////////////////////////////
    // End pagination functions //
    //////////////////////////////


    //////////////////////////////
    // Sort function            //
    //////////////////////////////

    $(".sort_link, .iconcontainer").click(function () {

        var filterURL = createURL();

        if ($(this).hasClass("title"))
            filtername = "title";
        else if ($(this).hasClass("stars"))
            filtername = "metaSterren";
        else if ($(this).hasClass("pricesort"))
            filtername = "price";
        else if ($(this).hasClass("count"))
            filtername = "count";

        if ($("#container-" + filtername + " .icon_arrow_up").attr("class") == "icon_arrow_up active")
            filterURL += "&sort=" + filtername + "|desc";
        else
            filterURL += "&sort=" + filtername + "|asc";

        //loadPage(filterURL, false);
        if (window.location.href.indexOf("zoek-en-boek") != -1)
            loadPage(filterURL, false);
        else
            loadPageWithDifferentBase(filterURL, "/zoek-en-boek");
    });


    //////////////////////////////
    // Toggle show/hide options //
    //////////////////////////////

    $(".toggleOptions, .bluetoggle").click(function () {

        var li = $(this).parent().prev();
        var optionCount = $("li", li).length

        $("li::not(visible)", li).fadeIn();
        $(this).parent().hide();
    });

    $(".advanced_search").click(function () {

        $("#hfAdvancedSearch").val(true);

        $(".advanced").fadeIn(function () { $(".advanced_search").parent().fadeOut(); });

        return false;
    })


    $(".change_country select").change(function () {
        window.location = "/" + $(this).val() + "/";
    });

    $(".change_place select").change(function () {
        var link = $("#hfFilterBaseURL").val();
        var linkArray = link.split("/");

        window.location = $(this).val();
        //alert("/" + link[1] + "/" + linkArray[2] + "/" + $(this).val() + "/");
    });

    $(".item_cat_country").click(function () {
        window.location = $(".btn_look_cat_country", this).attr("href");
    });

    //  Show results button on homepage
    $("#show_results, .advanced_search_home").click(function () {

        $("#hfFilterBaseURL").val('/zoeken/');
        var filterURL = createURL(true);
        loadPage(filterURL, true, true);

    });


    // Custom budget functions
    $(".suggestion_btn, #suggestion_btn").click(function () {
        var intRegex = /^\d+$/;

        if (intRegex.test($("[name='surprise']").val()))
            window.location = $("[name='surprise_location']").val() + "?budget-max=" + $("[name='surprise']").val();
    });


    $("[name='surprise']").keydown(function (event) {
        if (event.keyCode == 46 || event.keyCode == 8) {
        } else {
            if (event.keyCode < 95) {
                if (event.keyCode < 48 || event.keyCode > 57) {
                    event.preventDefault();
                }
            } else {
                if (event.keyCode < 96 || event.keyCode > 105) {
                    event.preventDefault();
                }
            }
        }
    });

});


// Populate current selections
function loadSelectionList() {

    if ($("#hfQuery").val() != "" && $("#hfQuery").val() != undefined)
        $('#loadSelectionList').append("<li title='Verwijder deze selectie' id='qSelect'><div class='icon_selected'></div>Zoek op: '" + $("#hfQuery").val() + "'</li>");

    $(".sidebar_menu_item_content input[type=checkbox]").each(

        function () {
            if ($(this).attr("checked")) {
                $('#loadSelectionList').append("<li title='Verwijder deze selectie' id='" + $(this).attr("name") + "'><div class='icon_selected'></div>" + $(this).next().text().trim() + "</li>");                
            }
            else if ($(this).hasClass("qmmGegarandeerd")) {
                var v = $(this).parent();

                if (v.text().trim().indexOf("0") > -1)
                    v.parent().parent().parent().parent().remove();
            }
        }
    );               
}


function showOrHideOptions(optionCutOff) {

    $(".sidebar_menu_item_content").each(function () {   

        if (!$(this).hasClass("budget")) {
            var optionCount = $("li", this).length;

            if (optionCount > optionCutOff)
                $("li.hideItem", this).hide();
            else
                $(".toggleOptions", this).parent().hide();

            var optionCountVisible = $("li:visible", this).length;

            if (optionCount == optionCountVisible)
                $(".toggleOptions", this).parent().hide();
        }
    });    
}


function createURL(selectbox) {

    var filterURL = "";
    var vCurrentType = "";

    var qreFound = false;

    if (selectbox) {

        $(".sidebar_menu_item_content select").each(

            function () {

                var vValue = $(this).val();

                if (vValue != "0") {

                    var vType = $(this).attr("class").toLowerCase();

                    if (vValue == "751") {
                        vValue = "750";
                        vType = "qrsValue";
                    }

                    filterURL += createFriendlyFilter(vType, vValue, vCurrentType);

                    vCurrentType = vType;
                }
            }
        );
    }
    else {
        $(".sidebar_menu_item_content input[type=checkbox]").each(

        function () {

            if ($(this).attr("checked")) {

                var vType = $(this).attr("class").toLowerCase();

                var vValue = $(this).attr("value");

                filterURL += createFriendlyFilter(vType, vValue, vCurrentType);

                vCurrentType = vType;
            }
        }
    );
    }

    filterURL = Url.decode(filterURL).toLowerCase();
    filterURL = filterURL.replace("gegarandeerd=on", "gegarandeerd=true");

    if ($("#hfAdvancedSearch").val() != "" && $("#hfAdvancedSearch").val() != "false" && $("#hfAdvancedSearch").val() != "False")     
        filterURL += "&advanced=" + $("#hfAdvancedSearch").val();           

    if ($("#hfQuery").val() != "")
        filterURL += "&q=" + $("#hfQuery").val();    

    return filterURL;
}


function createFriendlyFilter(vType, vValue, vCurrentType) {

    var friendlyFilterName = "";

    if (vType.indexOf("land") > -1) 
        friendlyFilterName = "landen";
    else if (vType.indexOf("categorie") > -1)
        friendlyFilterName = "soorten";
    else if (vType.indexOf("gebied") > -1)
        friendlyFilterName = "gebieden";
    else if (vType.indexOf("plaats") > -1)
        friendlyFilterName = "plaatsen";
    else if (vType.indexOf("maand") > -1)
        friendlyFilterName = "perioden";
    else if (vType.indexOf("dagen") > -1)
        friendlyFilterName = "lengtes";
    else if (vType.indexOf("dagen") > -1)
        friendlyFilterName = "lengtes";
    else if (vType.indexOf("transporttype") > -1)
        friendlyFilterName = "transporttypen";
    else if (vType.indexOf("verzorging") > -1)
        friendlyFilterName = "verzorgingstypen";
    else if (vType.indexOf("aantalpersonen") > -1)
        friendlyFilterName = "aantal-personen";
    else if (vType.indexOf("sterren") > -1)
        friendlyFilterName = "sterren";
    else if (vType.indexOf("verblijftype") > -1)
        friendlyFilterName = "verblijftypen";
    else if (vType.indexOf("kamer") > -1)
        friendlyFilterName = "kamertypen";
    else if (vType.indexOf("luchthaven") > -1)
        friendlyFilterName = "luchthavens";
    else if (vType.indexOf("gegarandeerd") > -1)
        friendlyFilterName = "gegarandeerd";
    else if (vType.indexOf("qre") > -1)
        friendlyFilterName = "budget-max";
    else if (vType.indexOf("qrs") > -1)
        friendlyFilterName = "budget-min";

    if (vType != vCurrentType)
        return "&" + friendlyFilterName + "=" + Url.encode(vValue.replace("%2C", "-"));
    else
        return "," + Url.encode(vValue.replace("%2C", "-"));
}



function loadPage(filterURL, loadMenu, breakOutFrame) {
   
    showLoadingImg();
    /*
    if (loadMenu) {
    $("#filter_loading").css("height", ($("#sidebar_menu_content").height() + 35) + "px");
    $("#filter_loading").show()
    }
    */
    var host = window.location.host;
    var base = $("#hfFilterBaseURL").val()

    if (filterURL != "")
        var url = "http://" + host + base + "?" + filterURL.substring(1, filterURL.length).toLowerCase();
    else
        var url = "http://" + host + base;    

    if (breakOutFrame)
        top.location.href = url
    else
        window.location = url
}

function loadPageWithDifferentBase(filterURL, replaceBaseValue) {    
    var host = window.location.host;
    var base = $("#hfFilterBaseURL").val()
    base = base.replace(replaceBaseValue, "");
    
    if (filterURL != "")
        var url = "http://" + host + base + "?" + filterURL.substring(1, filterURL.length).toLowerCase();
    else
        var url = "http://" + host + base;        
    
    window.location = url
}

function showLoadingImg() {
/*
    $(".divSearch, #content_right, #content_left, .tabs, .toptext, .content_header, .content_bottom, .directly_to_big").hide();
    $(".loadingbar").show();
    $(".item_header").hide();
*/
}

var Url = {

    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

function resetLayer() {
    var inputid = document.getElementById("" + trq + "");
    var posh = inputid.offsetHeight;
    var posx = getOffset(document.getElementById("" + trq + "")).left;
    var posy = getOffset(document.getElementById("" + trq + "")).top + posh;
    
    if (navigator.appVersion.indexOf("MSIE 7.") != -1) {
        posx = posx - 0;
        posy = posy + 0;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else {
        posx = posx - 0;
        posy = posy + 0;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    if (navigator.appVersion.indexOf("MSIE 7.") != -1) {
        posx = posx;
        posy = posy - 0;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.appVersion.indexOf("MSIE 8.") != -1) {
        posx = posx + 0;
        posy = posy - 0;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.userAgent.indexOf("Chrome") != -1 && navigator.userAgent.indexOf("Windows") != -1) {
        posx = posx;
        posy = 211;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";        
    }
    else if (navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Windows") != -1) {
        posx = posx - 0;
        posy = 288;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.userAgent.indexOf("Firefox") != -1 && navigator.userAgent.indexOf("Mac") != -1) {
        posx = posx + 3;
        posy = posy - 1;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Mac") != -1) {
        posx = posx + 1;
        posy = 288;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.userAgent.indexOf("Chrome") != -1 && navigator.userAgent.indexOf("Mac") != -1) {
        posx = posx + 0;
        posy = 288;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else {
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
}
