
$(document).ready(function () {

    // store in a cookie whether instant filtering is on
    if ($.cookie("enable_instant_filtering") == null || $.cookie("enable_instant_filtering") == "")
        $.cookie("enable_instant_filtering", "false", { expires: 7 });

    var cbk_Instant = $("#cbk_Instant");

    if ($.cookie("enable_instant_filtering") == "true")
        cbk_Instant.attr("checked", "true");

    cbk_Instant.click(function () {
        $.cookie("enable_instant_filtering", this.checked, { expires: 7 });
    });

    var showFilter = $("#hdn_showFilter").attr("value");

    var hdn_sortBy = $("#hdn_sortBy");
    var hdn_sortMode = $("#hdn_sortMode");

    var opened_pnl_Filter = null;

    // iterate through all the TH elements of the table
    // each TH element's class attribute has the format "header_propertyName" where propertyName is the name of the respective 
    // property
    $("thead th").each(function (i, th) {
        // extract the the property name from the class attribute's value
        var propertyName = th.className.substring(th.className.indexOf("_") + 1);
        // get a reference to the A element that has the "filterButton" value defined as its class attribute
        var a_Filter = $(th).find("a.filterButton")[0];
        // get a reference to the A element which has an id defined as "a_propertyName" where propertyName is the name of the 
        // respective property
        var a_HeaderName = $("#a_" + propertyName);

        // create a filter panel for this property 
        var pnl_Filter = createFilterPanel(a_Filter, propertyName);

        // attach a handler to the click event for the a_Filter element 
        $(a_Filter).click(function () {
            $(this).find("img")[0].src = "/Content/Images/down.ico";

            // if an other filter panel is open, then close it
            if (opened_pnl_Filter != null)
                opened_pnl_Filter.hide();

            // show the create filter panel
            pnl_Filter.show();

            // remember that this filter panel was shown
            opened_pnl_Filter = pnl_Filter;

            // for each checkbox shown on the created filter panel store the value of each checkbox's actual value (true or false)
            // in the attribute "initialValue". This way we will know how the checkboxes looked prior to any modification in case 
            // the user closes the filter panel
            $("#pnl_Filter_" + propertyName + " input[type='checkbox']").each(function (i, input) {
                $(input).attr("initialValue", $(input).attr("checked"));
            });

            // if instant filtering is on
            if ($("#hdn_showFilter").attr("value") != "") {
                // check whether we have to scroll down on the filter popup
                var hdn_scrollTop = $("#hdn_scrollTop");

                if (hdn_scrollTop.attr("value") != "") {
                    $("#popupDiv_" + propertyName).attr("scrollTop", hdn_scrollTop.attr("value"));
                }
            }
        });

        // attach a handler to the click event for the a_HeaderName element
        a_HeaderName.click(function () {

            // if sorting was already executed by this property name in ascending order, then set the sort mode to descending
            if (hdn_sortBy.attr("value") == propertyName &&
                hdn_sortMode.attr("value") == "asc") {
                hdn_sortMode.attr("value", "desc");
            }
            // set up values which identify a new sorting expression
            else {
                hdn_sortBy.attr("value", propertyName);
                hdn_sortMode.attr("value", "asc");
            }

            submit(false);
        });

        // check if the showFilter variable equals this property name which means that the filter popup was opened and
        // instant filtering was on when the page was submitted. If it does we pop up the filter panel 
        if (showFilter == propertyName)
            $(a_Filter).click();

        // check if sorting was executed once
        if (hdn_sortBy.attr("value") == propertyName) {
            var descImg = $($(th).find("img.sortImage")[0]);
            var ascImg = $($(th).find("img.sortImage")[1]);
            
            // show the sort image
            if (hdn_sortMode.attr("value") == "asc")
                ascImg.css("display", "block");
            else
                descImg.css("display", "block");
        }
    });

    $("#ddl_pageSizes").change(function () {
        var pageSize = this.options[this.selectedIndex].value;

        $("#hdn_pageSize").attr("value", pageSize);
        $("#hdn_showFilter").attr("value", "");

        submit(false);
    });

    initializePageLinks();
});

// attaches an event handler to each page index element
function initializePageLinks() {
    $("#table_Persons tfoot a").each(function (i, value) {
        $(value).click(function () {
            $("#hdn_page").attr("value", this.innerHTML);

            $("#hdn_showFilter").attr("value", "");

            submit(false);
        });
    });
}

// sets up the values of the hidden fields based on the checkbox values on the filter panel which corresponds the propertyName 
// property
function setupFilterValues(propertyName) {
    $("#pnl_Filter_" + propertyName + " input").each(function (i, input) {
        var hdn_input =
            $("#div_" + propertyName + " input[name='filter_" + propertyName + "_" + input.value + "'][type='hidden']");

        hdn_input.attr("value", input.checked);
    });
};

// creates a filter panel that hosts checkboxes for the possible filter texts in the respective column of the table
// the parameter "a" is the A element with the class value of "filterButton"
function createFilterPanel(a, propertyName) {
    // get the hidden elements for the column
    var filterElements = $("#div_" + propertyName + " input[type='hidden']");

    var panelBodyHtml = "";

    var isAnyFilterOn = false;

    // iterate through the hidden elements. Each hidden element has a name attribute of "filter_propertyName_filterText" where 
    // propertyName is the name of the property and filterText is the actual filter text
    filterElements.each(function (i, hidden) {
        var name = hidden.name;

        var filterText = name.substring(name.indexOf("_", name.indexOf("_") + 1) + 1);

        // create a checkbox with a state based on the hidden element
        if (hidden.value.toLowerCase() == "true") {
            panelBodyHtml +=
                "<input class='popupCheckBox' type='checkbox' value='" + filterText + "' checked='checked' />";

            isAnyFilterOn = true;
        } else
            panelBodyHtml +=
                "<input class='popupCheckBox' type='checkbox' value='" + filterText + "' />"

        panelBodyHtml += "<span>" + filterText + "</span><br />";
    });

    if (isAnyFilterOn) {
        $($(a).parent().find("a")[0]).addClass("filtered");
    }

    var thWidth = $(a.parentNode).width();

    if (thWidth < 150)
        thWidth = 150;

    // create the filter panel
    var pnl_Filter =
        new YAHOO.widget.Panel(
            "pnl_Filter_" + propertyName,
            {
                width: (thWidth + 20) + "px",
                height: "210px",
                close: true,
                draggable: false,
                zindex: 4,
                modal: false,
                visible: false
            });

    // subscribe to the hide event
    pnl_Filter.hideEvent.subscribe(function () {
        // a.getElementsByTagName("img")[0].src = "/Content/Images/up.ico";
        $(a).find("img")[0].src = "/Content/Images/up.jpg";

        // set the values of the checkboxes back to the initial values, i.e. to those values that were set when the filter
        // panel was opened up
        $("#pnl_Filter_" + propertyName + " input[type='checkbox']").each(function (i, input) {
            var initialValue = $(input).attr("initialValue");

            if (initialValue != "") {
                $(input).attr("checked", initialValue.toLowerCase() == "true");
            }
        });

        // reset the value of the hdn_showFilter element because the filter popup was closed
        $("#hdn_showFilter").attr("value", "");
    });

    var popupDivId = "popupDiv_" + propertyName;

    pnl_Filter.setHeader("<div style='text-align: left;'>Filter by " + propertyName + "</div>");
    pnl_Filter.setBody(
            "<div id='" + popupDivId + "' class='yui-skin-sam' style='text-align: left; overflow: scroll; width: " + thWidth + "px; height: 140px;'>" +
            panelBodyHtml +
            "</div>" +
            "<input type='button' id='btn_Filter' value='Filter' /><input type='button' id='btn_ClearFilter' value='Clear all' />");

    // show the filter panel
    pnl_Filter.render(a.parentNode.getElementsByTagName("div")[0]);

    var popupDiv = $("#" + popupDivId);

    // get a reference to the filter button on the the filter panel
    var btn_Filter = $($("#pnl_Filter_" + propertyName + " input[type='button']")[0]);

    // attach handler
    btn_Filter.click(function() {
        setupFilterValues(propertyName);

        $("#hdn_showFilter").attr("value", "");

        // store the amount by which the popupDiv is scrolled down
        $("#hdn_scrollTop").attr("value", popupDiv.attr("scrollTop"));

        submit(true);

        pnl_Filter.hide();
    });

    // get a reference to the clear filter button on the filter panel
    var btn_ClearFilter = $($("#pnl_Filter_" + propertyName + " input[type='button']")[1]);

    btn_ClearFilter.click(function () {
        $("#pnl_Filter_" + propertyName + " input[type='checkbox']").each(function (i, input) {
            input.checked = false;
        });

        setupFilterValues(propertyName);

        submit(true);

        pnl_Filter.hide();

        return false;
    });

    // iterate through each checkbox on the filter panel
    $("#pnl_Filter_" + propertyName + " .popupCheckBox").each(function (i, value) {
        // attach event handler 
        $(value).click(function () {
            // if instant filtering is on  
            if ($("#cbk_Instant").attr("checked")) {

                // $.disabledPopupName = "pnl_Filter_" + propertyName;

                // disable the popup panel
                changePopupStatus(false, "pnl_Filter_" + propertyName);

                setupFilterValues(propertyName);

                $("#hdn_showFilter").attr("value", propertyName);

                // store the amount by which the popupDiv is scrolled down
                $("#hdn_scrollTop").attr("value", popupDiv.attr("scrollTop"));

                submit(true);
            }
        });
    });

    return pnl_Filter;
}

function submit(resetPaging) {
    // reset paging means we set the page index to 1
    if (resetPaging)
        $("#hdn_page").attr("value", "1");

    document.getElementById("btn_submit").click();
}

// enable or disable the controls on the filter panel
function changePopupStatus(enable, panelName) {
    // enable/disable every checkbox on this filter panel
    $("#" + panelName + " input").each(function (i, input) {
        if (enable)
            $(input).removeAttr("disabled");
        else
            $(input).attr("disabled", "disabled");
    });

    // enable/disable every span on this filter panel
    $("#" + panelName + " span").each(function (i, span) {
        if (enable)
            $(span).css("color", "");
        else
            $(span).css("color", "#ccc");
    });
}