﻿jQuery(document).ready(function() {
    $('fieldset.sector span label').addClass('chk');
    $('fieldset.multipleFilters span label').addClass('chk');
    $('#ResetFilter').click(ResetFilter);

    $('.multipleFilters dd > div > .layer').each(function() {
        var layer = $(this);
        $('.selecteer', layer).click(function() {
            UpdateFromMenu($(this).parents('.layer'), $('.SelectedOptions', $(this).parents('.layer').parent()), $('a', $(this).parents('.layer').parent()));
            $(this).parents('.layer').hide();
            $('span.arrow', $(this).parents('.layer').parent()).hide();
            $('.mask').hide();
        });
    });
    var queryparams = {};
    if (window.location.search.length > 0) {
        queryparams = readparams();
    } else if (jQuery.cookie('filterOptions'))
    {
        queryparams = readparams(decodeURIComponent(jQuery.cookie('filterOptions')));
    }
        
    if ($(queryparams).length > 0){
        jQuery.each(queryparams, function(key, val) {
        FilterOptions.put(key, val);
    });
        SetOptions();
        loadLocationOverview(true, $('#locationpagenr').val());
        FilterOptions.remove("resultsperpage");
        
    } else {
        ResetFilter();
    }
});

// Ajax call to retrieve content for LocationOverview div
function loadLocationOverview(optionsChanged, pageNr) {
    if (typeof(optionsChanged) != 'undefined' && optionsChanged == true){
        if (typeof (pageNr) != 'undefined') {
            $('#locationpagenr').val(pageNr);
        } else {
            $('#locationpagenr').val(1);
        }
    }
    var filterOptions = GetLocationFilterParams(optionsChanged);
    jQuery.cookie('filterOptions', filterOptions);
    ShowBusy();
    $.ajax({
        async: true,
        cache: true,
        dataType: 'html',
        url: "/Ajax/LocationOverview.aspx" + filterOptions,
        success: function(response) {
            $("div:#locationOverview").html(Cleaned(response));
            rebindLocationOverview();
            UpdateSelectedLocations();
        },
        complete: function(response) {
            HideBusy();
        }
    });
}

// Ajax call to retrieve content for Subsector checkboxes
function UpdateSubsectorCheckBoxList(target) {
    var value = $(target).val();
    if (value == "" || value == "-") {
        $("#SubSectorCheckBoxList").html("");
        ReInitAccordion();
    }
    else {
        var paramString = "?reqid=" + $("#reqid").val() + "&sector=" + value;
        $.ajax({
            async: true,
            cache: true,
            dataType: 'html',
            url: "/Ajax/SubSectorCheckBoxList.aspx" + paramString,
            success: function(response) {
                $("#SubSectorCheckBoxList").html(response);
                if (response) {
                    $('#SubSectorCheckBoxList').children("input[type='checkbox']").click(function() {
                        {
                            UpdateLocationFilterFromCheckBox('subsector', this);
                        }
                    });
                    var item = FilterOptions.get('subsector');
                    if (typeof (item) != 'undefined') {

                        $('#SubSectorCheckBoxList').children("input[type='checkbox']").each(function() {
                            var subSector = $(this).next().text();
                            var found = $.inArray(subSector, item);
                            if (found != -1) {
                                $(this).attr('checked', true);
                            }
                        });
                    }
                }
            },
            error: function(response) {
                $("#SubSectorCheckBoxList").html("");
            },
            complete: function(response) {
                ReInitAccordion();
            }
        });
    }
};

// Ajax call to retrieve content for district dropdown
function UpdateDistrict(target) {
    var value = $(target).val();
    $("select#DistrictDropdownList").attr('disabled', 'disabled');
   var defaultOption = '<option selected="selected" value="-">Alle stadsdelen</option>';
    if (value == "" || value == "-") {
        $("select#DistrictDropdownList").html(defaultOption);
    }
    else {
        var paramString = "?reqid=" + $("#reqid").val() + "&city=" + value;
        $.ajax({
            async: true,
            cache: true,
            dataType: 'html',
            url: "/Ajax/DistrictDropDown.aspx" + paramString,
            success: function(response) {
                $("select#DistrictDropdownList").html(defaultOption + response);
                if (response) {
                    $("select#DistrictDropdownList").attr('disabled', '');
                    var item = FilterOptions.get('district');
                    if (typeof (item) == 'undefined') {
                        $("select#DistrictDropdownList").val('-');
                    } else {
                        $("select#DistrictDropdownList").val(item[0]);
                    }
                }
            },
            error: function(response) {
                $("select#DistrictDropdownList").html(defaultOption);
            }
        });
    }
}

// Rebind links etc in overview div after ajax load
function rebindLocationOverview() {
    $('.locationOverview .listWrapper ul li div a:not(.remove)').unbind('click', Cordaan.Compare.Add);
    $('.locationOverview .listWrapper ul li div a.remove').unbind('click', Cordaan.Compare.Remove);
    $('span.resultsPerPage select').unbind('change', ChangeLocationRpP);
    $('div.paginator a.next').unbind('click', LoadNextLocationPage);
    $('div.paginator a.previous').unbind('click',LoadPreviousLocationPage);
    $('div.paginator ul li a').unbind('click', LoadLocationPage);

    Cordaan.Compare.Init();
    $('span.resultsPerPage select').change(ChangeLocationRpP);
    $('div.paginator a.next').click(LoadNextLocationPage);
    $('div.paginator a.previous').click(LoadPreviousLocationPage);
    $('div.paginator ul li a').click(LoadLocationPage);
}

function UpdateLocationFilterFromCity(key, target, districts) {
    FilterOptions.remove("district");
    if (typeof (districts) != "undefined") {
        FilterOptions.put("district", districts);
    }
    UpdateDistrict(target);
    UpdateLocationFilterFromDropDown(key, target);
}

function UpdateLocationFilterFromSector(key, target, subsectors) {
    FilterOptions.remove("subsector");
    if (typeof (subsectors) != "undefined") {
        FilterOptions.put("subsector",subsectors);
    }
    UpdateSubsectorCheckBoxList(target);
    UpdateLocationFilterFromDropDown(key, target);
}

function UpdateFromMenu(menu, selectedArea, link) {
    var SelectedAreaText = "";
    $(menu).find("input:checkbox").each(function() {
        if (! $(this).attr("checked")){
            FilterOptions.remove($(this).attr("name"), $(this).val());
        }
    });
    $(menu).find("input:checkbox").each(function() {
        if ($(this).attr("checked")){
            FilterOptions.replace($(this).attr("name"), $(this).val());
            SelectedAreaText += '<label for="sel_' +
                                $(this).attr("id") +
                                '"><input id="sel_' +
                                $(this).attr("id") +
                                '" name = "' +
                                $(this).attr("name") +
                                '" value = "' +
                                $(this).val() +
                                '" type="checkbox" checked />' +
                                $(this).parent().text() +
                                '</label><br />';
        }
    });

    selectedArea.html(SelectedAreaText);
    if ($(menu).find("input:checkbox:checked'").length > 0) {
    $(selectedArea).find("input:checkbox").each(function() {
        $(this).click(function() {
            RemoveFromMenu($(this), menu, link);
        });
    });
        link.text('Pas selectie aan');
    }
    else {
        link.text('Maak een selectie');
    }
    loadLocationOverview(true);
}

function RemoveFromMenu(target, menu, link) {
    var id=$(target).attr("id")
    var name = $(target).attr("name")
    id = id.substr(4, id.length);
    $(menu).find('input:checkbox[id=' + id + ']').each(function() {
        $(this).attr("checked", "");
    });
    
    $(target).parent().next().remove();
    $(target).parent().remove();
    if ($(menu).find("input:checkbox:checked'").length == 0) {
        link.text('Maak een selectie');
    }     
    FilterOptions.remove(name, $(target).val());
    loadLocationOverview(true);
}

function SetOptions() {
    var keys = FilterOptions.keys();
    $(keys).each(function() {
        var item = FilterOptions.get(this);
        if (this == 'subsector' || this == 'district' || this == 'resultsperpage') {
        } else if (this == 'sector') {
            var target = $('fieldset.sector select');
            $(target).val(item[0]);
            UpdateLocationFilterFromSector('sector', target, FilterOptions.get('subsector'))
        } else if (this == 'city') {
            var target = $('#CityDiv select');
            $(target).val(item[0]);
            UpdateLocationFilterFromCity('city', target, FilterOptions.get('district'))
        } else if (this == 'targetgroups') {
            $('#TargetGroupDiv').find("input[type='checkbox']").each(function() {
                var targetGroup = $(this).next().text();
                var found = $.inArray(targetGroup, item);
                if (found != -1) {
                    $(this).attr('checked', true);
                }
            });
        } else if (this == 'zzpvalues') {
            $('#ZzpDiv > select').val(item[0]);
        } else {
            $('.checkboxesArea').find('input:checkbox[id=' + this + ']').each(function() {
                $(this).attr("checked", "checked");
                var link = $('a', $(this).parents('.layer').parent());
                var menu = $(this).parents('.layer');
                var selectedArea = $('.SelectedOptions', $(this).parents('.layer').parent());
                var selectedAreaText = selectedArea.html();
                selectedAreaText += '<label for="sel_' +
                                $(this).attr("id") +
                                '"><input id="sel_' +
                                $(this).attr("id") +
                                '" name = "' +
                                $(this).attr("name") +
                                '" value = "' +
                                $(this).val() +
                                '" type="checkbox" checked />' +
                                $(this).parent().text() +
                                '</label><br />';
                selectedArea.html(selectedAreaText);
                link.text('Pas selectie aan');
                $(selectedArea).find("input:checkbox").each(function() {
                    $(this).click(function() {
                        RemoveFromMenu($(this), menu, link);
                    });
                });
            });
        }
    });
}

function ResetFilter() {
    FilterOptions = new FilterOptionManager();
    $("select#DistrictDropdownList").html('<option selected="selected" value="-">Alle stadsdelen</option>');
    $("select#DistrictDropdownList").attr('disabled', 'disabled');
    $("#SubSectorCheckBoxList").html("");

    $("div.filters").find("select").each(function() {
        $(this).val($("#" + $(this).attr("id") + " option:first").val());
    });

    $('.multipleFilters dd > div > .SelectedOptions').each(function() {
        $(this).html("");
    });
    $('.multipleFilters dd > div > a').each(function() {
        $(this).text('Maak een selectie');
    });

    ReInitAccordion();
    Cordaan.Compare.Menu.RemoveAll();
    loadLocationOverview(true);
}

function ChangeLocationRpP() {
    $('#locationpagenr').val(1);
    loadLocationOverview();
}

function LoadNextLocationPage() {
    var pageNr = $('div.paginator ul li a.current span').slice(0, 1).text();
    var nextPageNr = parseInt(pageNr) + 1;
    $('#locationpagenr').val(nextPageNr);
    loadLocationOverview();
}

function LoadPreviousLocationPage() {
    var pageNr = $('div.paginator ul li a.current span').slice(0, 1).text();
    var previousPageNr = parseInt(pageNr) - 1;
    $('#locationpagenr').val(previousPageNr);
    loadLocationOverview();
}

function LoadLocationPage() {
    var pageNr = $(this).children("span").text();
    if (typeof (pageNr) != 'undefined') {
        $('#locationpagenr').val(pageNr);
    }
    loadLocationOverview();
}

function GetLocationFilterParams(optionsChanged) {
    var paramString = "?reqid="+ $("#reqid").val();
    paramString += GetLocationFilterParam('resultsperpage', 'span.resultsPerPage select');
    paramString += GetLocationFilterParam('pagenr', '#locationpagenr');
    paramString += FilterOptions.asParams();
    if (typeof(optionsChanged) != 'undefined' && optionsChanged == true){
        paramString += "&FilterOptionsChanged=true";
    }
    return paramString;
}

function GetLocationFilterParam( key, target) {
    var targetValue = $(target).val();
    if (typeof (targetValue) != 'undefined' && targetValue != '') {
        return "&"+key+"="+targetValue;
    }
    return "";
}

function UpdateLocationFilterFromDropDown(key, target) {
    var value = $(target).val();
    if (value == "" || value == "-") {
    FilterOptions.remove(key);
    } else {
    FilterOptions.replace(key, value);
    }
    loadLocationOverview(true);
}

function UpdateLocationFilterFromCheckBox(key, target) {
    if ($(target).is(':checked')) {
        FilterOptions.add(key, $(target).next().text());
    } else {
        FilterOptions.removefrom(key, $(target).next().text());
    }
    loadLocationOverview(true);
}


function ReInitAccordion(){
	if(jQuery.browser.msie && jQuery.browser.version.charAt('0') == '6') {
  	$('.multipleFilters dl').accordion('destroy');
  	$('.multipleFilters dl').accordion({
  		header: 'dt',
  		alwaysOpen: false,
  		active: false,
  		autoheight: false,
  		selectedClass: 'expand'
  	}).bind("change.ui-accordion", function(event, ui) {
  		if(ui) {
  			$('.multipleFilters dd .layer').hide();
  			$('.multipleFilters dd span.arrow').hide();
  			$('.multipleFilters dd').css('overflow', 'visible'); // accordion bug, styles stays on
  			$('.mask').hide();
  		}
  	});
  }
 }

 function UpdateSelectedLocations(menuUl) {
     if (menuUl == null) {
         menuUl = $('.compareSelection .layerWrapper ul');
     }
     $('li:not(.empty)', menuUl).each(function() {
         var menuId = $('input', this).attr('value');
         var contentLi = $('.locationOverview .listWrapper ul li[id=' + menuId + ']');
         if (typeof (contentLi) != 'undefined') {
             var contentLink = $('div a', contentLi);
             contentLink.text('Verwijder');
             contentLink.attr('title', 'Verwijder')
             contentLink.addClass('remove');
             contentLink.unbind('click');
             contentLink.click(Cordaan.Compare.Remove);
         }
     });
 }

function ShowBusy() {
     // Show content mask
     $('.columnContent .mask').show();

     var layer = $('#busyWheel');
     var container = layer.parent();
     var left =(container.width() - layer.width()) / 2;
     var top = (container.height() - layer.height()) / 2;
     if (left > 0){
        layer.css('left', left);
     }
     if (top > 0){
        layer.css('top', top);
     }
     layer.show();
}

function HideBusy() {
    $('#busyWheel').hide();
    $('.columnContent .mask').hide();
}


function Cleaned(htmlCode) {
    var result = htmlCode;
    var startPosition = result.indexOf("<h2>");
    var endPosition = result.indexOf("</form>");
    result = result.substr  (startPosition, endPosition);
    return result;
 }

 // map containing all key-values and methods to manage it
function FilterOptionManager() {
    if (typeof (OptionsMap) == 'undefined') {
        var OptionsMap = {};
    }

// create a key-value or add the value to an existing key
    this.add = function(key, value) {
        var item = OptionsMap[key];
        if (item) {
            OptionsMap[key].push(value);
        }
        else {
            OptionsMap[key] = [ value ];
        }
    };

// create a key-value or replace the value of an existing key
    this.replace = function(key, value) {
        OptionsMap[key] = [ value ];
    };

    // create a key-value or replace the value of an existing key !Assumes value to be an array!
    this.put = function(key, value) {
        OptionsMap[key] = value;
    };

    // remove a key-value from the map completely
    this.remove = function(key) {
        var item = OptionsMap[key];
        if (item) {
            delete OptionsMap[key];
        }
    };

    // remove a key-value from the map completely
    this.removefrom = function(key, value) {
        var item = OptionsMap[key];
        if (item) {
            if (typeof (item) == 'string' && item == value) {
                delete OptionsMap[key];
            } else {
                OptionsMap[key]  = jQuery.grep(item, function(val) {
                    return val != value;
                });
            }
        }
    };

    // returns the value (string, array, undefined) corresponding to the key
    this.get = function(key) {
        return OptionsMap[key];
    };

    // returns the value (string, array, undefined) corresponding to the key
    this.keys = function() {
        var a = [];
        $.each(OptionsMap, function(k) { a.push(k) });
        return a;
    };
    
    // returns all key-values as a query parameter string
    this.asParams = function() {
        var paramString = jQuery.param(OptionsMap);
        if (paramString != "") {
            return "&" + paramString;
        }
        return "";
    }
}

function readparams(paramString) {
    var params = {};
    var paramsArr = [];
    if (typeof (paramString) != 'undefined') {
        paramsArr = paramString.substr(1,paramString.length).split('&');
    }
    else if (window.location.search.length){
        paramsArr = window.location.search.substr(1,window.location.search.length).split('&');
    }
    $.each(paramsArr, function(x, y) {
        var temp = y.split('=');
        if (temp.length == 2 && temp[0] != 'reqid' && temp[0] != 'FilterOptionsChanged') {
            if (temp[0] == 'pagenr') {
                $('#locationpagenr').val(temp[1]);
            }
            else {
                var key = temp[0];
                var item = params[key];
                if (item) {
                    params[key].push(temp[1].replace(/[+]/g, ' '));
                }
                else {
                    params[key] = [temp[1].replace(/[+]/g, ' ')];
                }
            }
        }
    });
    return params;
}

// create an instance of the map
if (typeof (FilterOptions) == 'undefined') {
    var FilterOptions = new FilterOptionManager();
}
