﻿$(document).ready(function () {

    var optionCutOff = 7;

    // Init functions
    loadSelectionList();
    showOrHideOptions(optionCutOff);

    // Add a loading graphic to the asynchronous popups
    /*
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_initializeRequest(function (sender, args) {
        // Start loading
        //$('#content').addClass('loading');
        //$('.loadingbar').show();
    });

    prm.add_endRequest(function (sender, args) {
        // Done loading
        //$('#content').removeClass('loading');
        //$('.loadingbar').hide();
    });
    */

    $(".f_section_txt 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", "");
            }
        }

        $('body,html').animate({
            scrollTop: 0
        },
            400);


        var filterURL = createURL();
        loadPage(filterURL, true);
    });

    $(".select_btn").click(function () {

        $('body,html').animate({
            scrollTop: 0
        },
            400);

        var filterURL = createURL("merk");
        loadPage(filterURL, true);
    });

    $("#ctl00_phContent_vtSearchResult_sorting").val($("#hfSort").val());

    $("#ctl00_phContent_vtSearchResult_sorting").change(function () {
        $("#hfSort").val($(this).val());
        var filterURL = createURL();
        loadPage(filterURL, true);

    });

    $("#ctl00_phContent_vtSearchResult_result").val($("#hfResult").val());

    $("#ctl00_phContent_vtSearchResult_result").change(function () {
        $("#hfResult").val($(this).val());
        var filterURL = createURL();
        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);
    });


    ////////////////////////
    // PAGING //////////////
    ////////////////////////

    var selectedIndex = $("#ctl00_phContent_vtSearchResult_divPaging .active").text();
    var indexLength = $("#ctl00_phContent_vtSearchResult_divPaging .pagination_btn:last").text();

    if (selectedIndex > 4) {
        $("#ctl00_phContent_vtSearchResult_divPaging .pagination_btn:first").after("<div style='width:15px;float:left;padding: 10px 0 10px 5px;'>...</div>");
        $("#ctl00_phContent_vtSearchResult_divPaging2 .pagination_btn:first").after("<div style='width:15px;float:left;padding: 10px 0 10px 10px;'>...</div>");
    }
    if (selectedIndex < indexLength - 3) {
        $("#ctl00_phContent_vtSearchResult_divPaging .pagination_btn:last").before("<div style='width:15px;float:left;padding: 10px 0 10px 5px;'>...</div>");
        $("#ctl00_phContent_vtSearchResult_divPaging2 .pagination_btn:last").before("<div style='width:15px;float:left;padding: 10px 0 10px 10px;'>...</div>");
    }

    ////////////////////////
    // Register click URL //
    ////////////////////////

    $(".item").click(function () {

        var parent = $(this).parent();

        var clickUrl = $("[type='hidden']", parent).val();
        try {
            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
                });
            }
        } catch (err) { }

        var host = window.location.host;
        var urlDetails = $("[rel='nofollow']", this).attr("href");

        if (urlDetails != "" && urlDetails != undefined)
            window.location = "http://" + host + urlDetails;

        return false;

    });

    $(".opleiding").click(function () {
        window.location = $(this).attr('href');
        return false;
    });

    $(".instelling").click(function () {
        window.location = $(this).attr('href');
        return false;
    });

    //////////////////////////
    // Pagination functions //
    //////////////////////////

    $(".pagination_btn").click(function () {
        //$("#filter_loading").show();

        //$('#content').addClass('loading');
        //$(".loadingbar").show();
        return true;
    });

    $(".paging_next").click(function () {
        //$("#filter_loading").show();

        //$('#content').addClass('loading');
        //$(".loadingbar").show();
        return true;
    });

    $(".paging_prev").click(function () {

        var filterURL = createURL();
        var current = parseInt($('#ctl00_phContent_vtSearchResult_divPaging .active').text());
        var pageNumber = current - 1;
        if (current == 0) {
            pageNumber = 0;
        }
        else {

            if (pageNumber != 1) {
                filterURL += "&p=" + pageNumber;
            }
            //if ($("#hfSort").val() != "")
            //filterURL += "&sort=" + $("#hfSort").val();
            loadPage(filterURL, true);
        }
        return false;
    });

    //////////////////////////////
    // End pagination functions //
    //////////////////////////////

    //////////////////////////////
    // Toggle show/hide options //
    //////////////////////////////

    $(".toggleOptions").click(function () {

        var li = $(this).parent().prev();
        var optionCount = $("li", li).length;

        $("li::not(visible)", li).fadeIn();
        //$("li::not(visible)", li).show();

        $(this).parent().hide();

    });

    $(".toggleOptionsBrand").click(function () {

        $(".allbrands_container").show();
    });

    $(".toggleOptionsBrandHide").click(function () {

        $(".allbrands_container").hide();
    });

    $(".toggleOptionsBrand2").click(function () {

        $(".allbrands_container2").show();
    });

    $(".toggleOptionsBrandHide2").click(function () {

        $(".allbrands_container2").hide();
    });

    $(".ab_tab_1").click(function () {
        $(".ab_c_1").show();
        $(".ab_c_2").hide();
        $(".ab_c_3").hide();
        $(".ab_c_4").hide();

        $('.ab_tab_1').addClass('active');
        $('.ab_tab_2').removeClass('active');
        $('.ab_tab_3').removeClass('active');
        $('.ab_tab_4').removeClass('active');
    }); 

    $(".ab_tab_2").click(function () {
        $(".ab_c_1").hide();
        $(".ab_c_2").show();
        $(".ab_c_3").hide();
        $(".ab_c_4").hide();

        $('.ab_tab_1').removeClass('active');
        $('.ab_tab_2').addClass('active');
        $('.ab_tab_3').removeClass('active');
        $('.ab_tab_4').removeClass('active');
    });

    $(".ab_tab_3").click(function () {
        $(".ab_c_1").hide();
        $(".ab_c_2").hide();
        $(".ab_c_3").show();
        $(".ab_c_4").hide();

        $('.ab_tab_1').removeClass('active');
        $('.ab_tab_2').removeClass('active');
        $('.ab_tab_3').addClass('active');
        $('.ab_tab_4').removeClass('active');
    });

    $(".ab_tab_4").click(function () {
        $(".ab_c_1").hide();
        $(".ab_c_2").hide();
        $(".ab_c_3").hide();
        $(".ab_c_4").show();

        $('.ab_tab_1').removeClass('active');
        $('.ab_tab_2').removeClass('active');
        $('.ab_tab_3').removeClass('active');
        $('.ab_tab_4').addClass('active');
    });

    //////////////////////////////
    // Tooltip //
    //////////////////////////////

    $(".tooltip_link").click(function (event) {
        if ($(".tooltip").css("display", "block")) {
            $(".tooltip").hide();
        }
        $(this).next().show();
        return false;
    });

    $(".tooltip_close").click(function (event) {
        $(".tooltip").hide();
        return false;
    });

    $(".tooltipDetails").click(function (event) {
        window.location = $(this).attr('href');
        return false;
    });

    //  Show results button on homepage
    $("#show_results, .advanced_search_home").click(function () {

        $("#hfFilterBaseURL").val('/zoeken/');
        var filterURL = createURL("filter");
        loadPage(filterURL, true, true);

    });

});


// Populate current selections
function loadSelectionList() {

    if ($("#hfQuery").val() != "" && $("#hfQuery").val() != undefined) {
        $('#loadSelectionList').append("<li title='Verwijder deze selectie' id='qSelect'><span class=\"icon_selection color\"></span><span>Zoek op: '" + $("#hfQuery").val() + "'</span></li>");
    }
    
    $(".f_section_txt input[type=checkbox]").each(

        function () {
            if ($(this).attr("checked")) {
                $('#loadSelectionList').append("<li title='Verwijder deze selectie' id='" + $(this).attr("name") + "'><span class='icon_selection color'></span><span>" + $(this).next().text().trim() + "</span></li>");
            }
        }
    );               
}

function showOrHideOptions(optionCutOff) {
    $(".f_section").each(function () {
        //        if (!$(this).is(".merk")) {
        var optionCount = $("li", this).length;

        var item = $(".top");
        item.show();

        if (optionCount > optionCutOff) {
            $("li:gt(" + (optionCutOff - 1) + ")", this).hide();
        }
        else {
            $(".toggleOptions", this).parent().hide();
        }
        //        }
    });
}


function createURL(selectbox) {

    var filterURL = "";
    var vCurrentType = "";
    var checkCat = false;

    var qreFound = false;

    if (selectbox == "filter") {

        $(".f_section select").each(

            function () {

                var vValue = $(this).val();

                if (vValue != "0") {

                    var vType = $(this).attr("class").toLowerCase();

                    filterURL += createFriendlyFilter(vType, vValue, vCurrentType);
                    vCurrentType = vType;
                }
            }
        );
        }
        else if (selectbox == "merk") {
            $(".allbrands_c input[type=checkbox]").each(
            function () {

                if ($(this).attr("checked")) {

                    var vType = "qmmmerk";

                    var vValue = $(this).attr("value");

                    filterURL += createFriendlyFilter(vType, vValue, vCurrentType);

                    vCurrentType = vType;
                }
            }
        );

            $(".f_section_txt input[type=checkbox]").each(
            function () {
                if ($(this).attr("checked") && $(this).attr("class").toLowerCase() != "qmmmerk") {

                    var vType = $(this).attr("class").toLowerCase();

                    var vValue = $(this).attr("value");

                    filterURL += createFriendlyFilter(vType, vValue, vCurrentType);

                    vCurrentType = vType;
                }
            }
        );
    }
        else {
            $(".f_section_txt input[type=checkbox]").each(

        function () {

            if ($(this).attr("checked")) {

                if ($(this).attr("class").toLowerCase() == "qmmcategorie") {
                    checkCat = true;
                }
            }
        }
    );

        $(".f_section_txt input[type=checkbox]").each(

        function () {

            if ($(this).attr("checked")) {

                //if (($(this).attr("class").toLowerCase() == "qmmsubcategorie" && checkCat == true) | $(this).attr("class").toLowerCase() != "qmmsubcategorie") {
                    var vType = $(this).attr("class").toLowerCase();

                    var vValue = $(this).attr("value");

                    filterURL += createFriendlyFilter(vType, vValue, vCurrentType);

                    vCurrentType = vType;
                //}
            }
        }
    );
    }

    filterURL = Url.decode(filterURL).toLowerCase();
    if ($("#hfQuery").val() != "")
        filterURL += "&q=" + $("#hfQuery").val();

    if ($("#hfSort").val() != "")
        filterURL += "&sort=" + $("#hfSort").val();

    if ($("#hfResult").val() != "")
        filterURL += "&n=" + $("#hfResult").val();

    return filterURL;
}


function createFriendlyFilter(vType, vValue, vCurrentType) {

    var friendlyFilterName = "";

    if (vType.indexOf("subcategorie") > -1)
        friendlyFilterName = "subcategorie";
    else if (vType.indexOf("categorie") > -1)
        friendlyFilterName = "categorie";
    else if (vType.indexOf("thema") > -1)
        friendlyFilterName = "thema";
    else if (vType.indexOf("merk") > -1)
        friendlyFilterName = "merk";
    else if (vType.indexOf("inhoud") > -1)
        friendlyFilterName = "inhoud";
    else if (vType.indexOf("aantal") > -1)
        friendlyFilterName = "aantal";
    else if (vType.indexOf("toedieningsvorm") > -1)
        friendlyFilterName = "toedieningsvorm";
    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) {

    //$(".divSearch, #content_right, #content_left, .tabs, .toptext, .content_header, .content_bottom, .directly_to_big").hide();
    //$(".loadingbar").show();
    //$(".item_header").hide();

    if (loadMenu) {
        //$("#filter_loading").show();

        //$('#content').addClass('loading');
        //$('.loadingbar').show();
    }

    var host = window.location.host;
    var base = $("#hfFilterBaseURL").val();

    var url = "http://" + host + base;
    if (filterURL.length > 0)
        url += "?" + filterURL.substring(1, filterURL.length).toLowerCase();

    if (breakOutFrame)
        top.location.href = url;
    else
        window.location = url;

}

function GetInstellingTooltipByIsat(isat) {
    var next = $(this).next();
    $(".contentTooltip").html("");

    $.ajax({
        type: "POST",
        url: "/SearchResult.asmx/GetInstellingByIsat",
        data: '{isat: "' + isat + '"}',
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $(".contentTooltip").html(data.d);
            $(next).show();

            $(".tooltipDetails").click(function (event) {
                window.location = $(this).attr('href');
                return false;
            });


        },
        error: function (xhr, status, errord) {
            //alert("error ajax");
        }
    });
}

//GetStedenByIsat
function GetStedenByIsat(isat) {
    var next = $(this).next();
    $(".contentTooltip").html("");

    $.ajax({
        type: "POST",
        url: "/SearchResult.asmx/GetStedenByIsat",
        data: '{isat: "' + isat + '"}',
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $(".contentTooltip").html(data.d);
            $(next).show();

            $(".tooltipDetails").click(function (event) {
                window.location = $(this).attr('href');
                return false;
            });
        },
        error: function (xhr, status, errord) {
            //alert("error ajax");
        }
    });
}

function closeTypeResult() {
    document.getElementById("divtyperesult").style.display = "none";
    document.getElementById("divtyperesult").innerHTML = "";
}

function GetStedenByInstellingId(instellingId) {
    var next = $(this).next();
    $(".contentTooltip").html("");

    $.ajax({
        type: "POST",
        url: "/SearchResult.asmx/GetStedenByInstellingId",
        data: '{instellingId: "' + instellingId + '"}',
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $(".contentTooltip").html(data.d);
            $(next).show();
            
            $(".tooltipDetails").click(function (event) {
                window.location = $(this).attr('href');
                return false;
            });


        },
        error: function (xhr, status, errord) {
            //alert("error ajax");
        }
    });
}

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 - 25;
    var posy = getOffset(document.getElementById("" + trq + "")).top + posh + 4;

    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 = 80;
        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 - 2;
        posy = 157;
        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 = 83;
        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 = 83;
        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";
    }
}

function resetLayerThirdParty() {
    var inputid = document.getElementById("" + trq + "");
    var posh = inputid.offsetHeight;
    var posx = getOffset(document.getElementById("" + trq + "")).left - 25;
    var posy = getOffset(document.getElementById("" + trq + "")).top + posh + 4;

    if (navigator.appVersion.indexOf("MSIE 7.") != -1) {
        posx = posx - 526;
        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 - 526;
        posy = posy - 0;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.appVersion.indexOf("MSIE 9.") != -1) {
        posx = posx - 526;
        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 - 526;
        posy = 80;
        document.getElementById("divtyperesult").style.left = posx + "px";
        document.getElementById("divtyperesult").style.top = posy + "px";
    }
    else if (navigator.userAgent.indexOf("Firefox") != -1 && navigator.userAgent.indexOf("Windows") != -1) {
        posx = posx - 526;
        posy = 80;
        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 - 2;
        posy = 157;
        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 - 526;
        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 - 526;
        posy = 83;
        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 - 526;
        posy = 83;
        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";
    }

    return true;
}

function removeLayer() {
    if (document.getElementById('divtyperesult'))
    alert();
}
