$(document).ready(function () {

    $("form[action$='MaintainList']").submit(function () {
        $.ajax({
            url: $(this).attr("action"),
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            // this function gets called on an AJAX update
            success: function (result) {
                var tbody = $("#table_Persons tbody");

                // delete all rows of the table
                tbody.find("tr").each(function (i, element) {
                    $(element).remove();
                });

                // iterate through the new items
                $(result.Items).each(function (i, item) {
                    // create a TR element and set the class attribute to "odd" for each odd number record
                    var tr = "<tr " + ((i + 1) % 2 == 0 ? "class='odd'" : "") + ">";

                    // iterate through each of the properties of the current item
                    $.each(item, function (property, value) {
                        // check whether the property value contains the text "Date"; if it does, then we need to convert it 
                        // to a proper date format (it looks like this: "/Date(545346000000)/")
                        if (value.toString().indexOf("Date") != -1) {
                            var re = /-?\d+/;
                            var m = re.exec(value);
                            var d = new Date(parseInt(m[0]));

                            value = d.format("m/d/yyyy HH:MM:ss TT");
                        }

                        // create a TD element for each property
                        tr += "<td>" + value + "</td>";
                    });

                    tr += "</tr>";

                    tbody.append(tr);
                });

                var td = $("#table_Persons tfoot td");

                // remove all of the A elements in the TFOOT section of the table which indicate the possible page indices
                td.find("a").each(function (i, element) {
                    $(element).remove();
                });

                // create an A element for each page index
                for (var i = 1; i <= result.Pages; ++i)
                    td.append("<a href='#' class='" + (i == result.Page ? "selectedPage" : "defaultPage") + "'>" + i + "</a>");

                // set the current page
                $("hdn_page").attr("value", result.Page);

                // print the total number of records below the table
                $("#span_NumberOfRecords").html(result.NumberOfRecords);

                initializePageLinks();

                // if a filter panel was disabled because of update then enable it
                if ($.disabledPopupName != null)
                    changePopupStatus(true, $.disabledPopupName);

                // hide the loading image
                handleLoadingImage(false);
            }
        });

        return false;
    });

    // 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 columns = [];
    var opened_pnl_Filter = null;

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

    // 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);

        columns.push(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.jpg";

            // 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"));
            });
        });

        // attach a handler to the click event for the a_HeaderName element
        a_HeaderName.click(function () {
            // disable any sort image that might be visible
            $.each($.find("img.sortImage"), function (i, img) {
                $(img).css("display", "none");
            });

            var descImg = $($(th).find("img.sortImage")[0]);
            var ascImg = $($(th).find("img.sortImage")[1]);

            // 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") {
                descImg.css("display", "block");

                hdn_sortMode.attr("value", "desc");
            }
            // set up values which identify a new sorting expression
            else {
                ascImg.css("display", "block");

                hdn_sortBy.attr("value", propertyName);
                hdn_sortMode.attr("value", "asc");
            }

            submit(false);
        });
    });

    // attach a handler to the click event for the ddl_pageSizes element
    $("#ddl_pageSizes").change(function () {
        var pageSize = this.options[this.selectedIndex].value;

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

        submit(false);
    });

    initializePageLinks();

    // attach a handler to the click event for the a_ClearAllFilters element 
    $("#a_ClearAllFilters").click(function () {
        // uncheck all filter checkboxes on each filter panel
        $(".popupCheckBox").each(function (i, input) {
            if ($(input).attr("checked"))
                $(input).removeAttr("checked");
        });

        // set up the filter values by setting the hidden values for each column based on the filter panels' checkboxes
        for (var i = 0; i < columns.length; ++i)
            setupFilterValues(columns[i]);

        // hide any sort images
        $.each($.find("img.sortImage"), function (i, img) {
            $(img).css("display", "none");
        });

        // reset values that identify a sorting
        $("#hdn_sortBy").attr("value", "");
        $("#hdn_sortMode").attr("value", "");

        submit(true);
    });
});

// enables or disables the loading image
function handleLoadingImage(enable) {
    var img_Loader = $("#img_Loader");

    if (enable) {
        var table_Persons = $("#table_Persons");

        var x = table_Persons.offset().left + table_Persons.width() / 2 - img_Loader.width() / 2;
        var y = table_Persons.offset().top + table_Persons.height() / 2 - img_Loader.height() / 2;

        img_Loader.css("left", x).css("top", y).css("display", "block");
    }
    else
        img_Loader.css("display", "none");
}

// 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) {

    // check if any filter is on
    var isAnyFilterOn = false;

    $("#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);

        if (input.checked)
            isAnyFilterOn = true;
    });

    // if any filter is on, set the class of the "a_propertyName" to "filtered"
    if (isAnyFilterOn)
        $("#a_" + propertyName).addClass("filtered");
    // else remove the "filtered" class value
    else
        $("#a_" + propertyName).removeClass("filtered");
};

// 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' />";
        else
            panelBodyHtml +=
                "<input class='popupCheckBox' type='checkbox' value='" + filterText + "' />"

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

    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).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");
            }
        });
    });

    pnl_Filter.setHeader("<div style='text-align: left;'>Filter by " + propertyName + "</div>");
    pnl_Filter.setBody(
            "<div 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]);

    // 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);

        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]);

    // attach event handler
    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")) {
                // store the name of the disabled filter panel's name
                $.disabledPopupName = "pnl_Filter_" + propertyName;

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

                setupFilterValues(propertyName);

                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");
    
    // set the checkboxes' initialValue attribute value to empty string
    $.each($.find("*[initialValue]"), function (i, input) {
        $(input).attr("initialValue", "");
    })

    document.getElementById("btn_Submit").click();

    // show loading image
    handleLoadingImage(true);
}

// 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");
    });
}

function onSuccess_ClearAllFilters(ajaxContext) {

}

function onFailure_ClearAllFilters(ajaxContext) {

}

function onSuccess_SubmitForm(ajaxContext) {

}

function onFailure_SubmitForm(ajaxContext) {

}