$(function () {
    var $pad = $("#sermons-widget");
    if ($pad.length != 1) return;
    initSermons();
    initFilters();
    renderSermons(sermons);
    filterApply();
});

var previousResultsIndex = '';

function filterApply() {
    var bookFilter = new Array();
    $('.bible-book-select :checked').each(function () { bookFilter.push(this.value); });
    var textFilter = $('#sermons-widget-text-filter-text').val().toLowerCase();
    var filteredResultsIndex = '';
    var filteredResults = $.grep(sermons, function (e, i) {
        var ret = true;
        if (textFilter != '') {
            ret = (e.what + "|" + e.who + "|" + e.biblePassages + "|" + e.sermonSeries).toLowerCase().indexOf(textFilter) > -1;
        }
        if (ret && bookFilter.length > 0) {
            var bookMatch = false;
            var thisBooks = e.bibleBooks.split(",");
            $.each(bookFilter, function (i, e) {
                bookMatch = bookMatch || ($.inArray(e, thisBooks) > -1);
            });
            ret = bookMatch;
        }
        if (ret) filteredResultsIndex = filteredResultsIndex + e.id + ",";
        return ret;
    });
    if(filteredResultsIndex != previousResultsIndex) {
        renderSermons(filteredResults);
    }
    previousResultsIndex = filteredResultsIndex;
    
}

function toggleFilterDisplay() {
    var $button = $('#sermons-widget-filter-toggle');
    $('#sermons-widget-filters').toggle(function () {
        if ($button.data("was") == undefined) {
            $button.data("was", $button.text());
        }
        if ("Hide filter..." == $button.text()) {
            $button.text($button.data("was"));
        } else {
            $button.text("Hide filter...");
        }
    });
}

function initFilters() {
    $('#sermons-widget-filter-toggle')
        .click(function (event) {
            event.preventDefault();
            toggleFilterDisplay();
        })
        .show();

    $('#sermons-widget-text-filter-text')
        .keydown(function (event) {
            if (event.keyCode == 13) {
                event.preventDefault();
            }
        })
        .keyup(filterApply)
        .blur(filterApply);

    $('#sermons-widget-filters-apply').click(function (event) {
        event.preventDefault();
        toggleFilterDisplay();
    });

    $("#sermons-widget-filters :checkbox").change(filterApply);

    $("#sermons-widget-bible-book-none").click(function (event) {
        event.preventDefault();
        $("#sermons-widget-filters :checkbox").removeAttr("checked");
        filterApply();
    });

    $("#sermons-widget-OT-none").click(function(event) {
        event.preventDefault();
        $("#sermons-widget-filters .old :checkbox").removeAttr("checked");
        filterApply();
    });

    $("#sermons-widget-OT-all").click(function(event) {
        event.preventDefault();
        $("#sermons-widget-filters .old :checkbox").attr("checked", "checked");
        filterApply();
    });

    $("#sermons-widget-NT-none").click(function(event) {
        event.preventDefault();
        $("#sermons-widget-filters .new :checkbox").removeAttr("checked");
        filterApply();
    });

    $("#sermons-widget-NT-all").click(function(event) {
        event.preventDefault();
        $("#sermons-widget-filters .new :checkbox").attr("checked", "checked");
        filterApply();
    });

    $("#sermons-widget-bible-book-all").click(function (event) {
        event.preventDefault();
        $("#sermons-widget-filters :checkbox").attr("checked", "checked");
        filterApply();
    });
}

function initSermons() {
    sermons = $.grep(sermons, function (e, i) { return e != null; });
}

function renderSermons(sermons) {
    var $pad = $("#sermons-widget");
    if ($pad.length != 1) return;

    $pad.slideToggle(100, function () {
        $pad.children().remove();
        $pad.slideToggle();

        var $sermonTableBody = $("<tbody />").appendTo(
            $("#sermons-template")
            .children()
            .first()
            .clone()
            .appendTo($pad)
        );

        var $sermonTemplate = $("#sermon-template").children().first();

        $.each(sermons, function (i, e) {
            $sermonTemplate
                .children()
                .first()
                .clone()
                .html(function (ti, te) {
                    return te
                        .replace("---what---", e.what)
                        .replace("---who---", e.who)
                        .replace("---when---", new Date(e.when).toDateString())
                        .replace("---biblePassages---", e.biblePassages.replace(",", "<br />"))
                        .replace("---sermonSeries---", e.sermonSeries.replace(",", "<br />"))
                        .replace("---sermonAudio---", e.sermonAudio);
                })
                .appendTo($sermonTableBody);
        });
    });
}
