// Convert .helpBtn links to AJAX-loaded dialogs.
var ajax_help_buttons = function(domContext) {
    $('.helpBtn', domContext).each(function() {
        $(this).one('click', function() {
            var me = this;
            $.get($(this).attr('href'), function(data){
                var $dialog = $(data).find('.dialog');
                $('body').append($dialog);
                $dialog.dialog({
                        title: $dialog.attr('title'),
                        width: 500,
                        maxHeight: 550
                });
                $(me).click(function() {
                    $dialog.dialog('open');
                    return false;
                });
            });
            return false;
        });
    });
};

var category_setup = function() {
    $(table_selector + " > thead > th").hover(function () {
        $(this).addClass("ui-state-hover");
    }, function () {
        $(this).removeClass("ui-state-hover");
    });

    // Grab help buttons in the details expanders and block tablesorter from
    // getting them in the category view.
    ajax_help_buttons($(table_selector));

    $(table_selector + " thead th").prepend("<span class='indicator'><\/span>");
    $(table_selector + " th").click(function() {
        var details = $('#details');
        details.closest('tr').prev().removeClass('expanded');
        details.remove();
    }).attr('title', 'Click to sort by this column');
    $(table_selector + " td").addClass("has_js").attr('title', 'Click to expand');
    $("#details td").removeAttr('title');
    $(table_selector).tablesorter({ textExtraction : 'complex' }).addClass("tablesorter");
    //FIXME: As far as I can tell, tablesorter doesn't like nested tables. This
    //messes up the appearance of the incidents sub-table in the details
    //expander.
    //FIXME: Tablesorter doesn't want to sort th.icon columns.

};

var details_setup = function(domContext) {
    $('.spoiler', domContext).click(function() {
        $(this).toggleClass('spoiler_js');
    }).removeClass('spoiler').addClass('spoiler_js').attr('title', 'Click to show/hide spoiler');
    $('.spoiler_js', domContext).tipsy({gravity: 'e', fade: true});
    ajax_help_buttons(domContext);
};

$(document).ready(function() {
    $.ajaxSetup({ data : { ajax : 1 }});

    // Filter drop-down
    // (http://aext.net/2009/08/perfect-sign-in-dropdown-box-likes-twitter-with-jquery/)
    $(".filter").click(function(e) {
        e.preventDefault();
        $("fieldset#filter_menu").toggle();
        $(".filter").toggleClass("menu-open");
    });

    $("fieldset#filter_menu").mouseup(function() {
        return false;
    });
    $(document).mouseup(function(e) {
        if($(e.target).parent("a.filter").length === 0) {
            $(".filter").removeClass("menu-open");
            $("fieldset#filter_menu").hide();

            var filter = document.getElementById('filter');
            if (filter) { filter.reset(); }
        }
    });
    $('#filter_menu .tip').tipsy({gravity: 'e', fade: true});

    /* AJAX Throbber
     * Source: http://snipplr.com/view/19456/jquery-throbber/
     * TODO: Instead, inject throbbers into the clicked elements.
     */
    $(document).ready(function(){
        $("#throbber").bind("ajaxSend", function(){
            $(this).show();
        }).bind("ajaxComplete", function(){
            $(this).hide();
        });
    });

    // Categories sidebar
    var selectedTabIdx = $('#tabs').find('li').index($("li[class*='ui-tabs-selected']"));

    $("#categories").tabs({
        cache: true,
        selected: selectedTabIdx
    }).addClass('ui-tabs-vertical ui-helper-clearfix').bind(
        'tabsselect', function(evt, ui) {
            //TODO: Add enough data to this for a popstate handler to do its thing.
            history.pushState({}, "", $(ui.tab).data('url'));
    });
    $("#categories .ui-tabs-nav li").removeClass('ui-corner-top').addClass('ui-corner-left');

    // Details expanders
    // TODO: Rewrite this as a jQuery plugin for reusability.
    $(".entries td").live('click', function(event) {
        // Ignore non-left clicks.
        if (event.button !== 0) { return true; }

        /* Don't handle clicks on the expander */
        if ($(this).parents('[id=details]').length !== 0) {
            return true;
        }

        /* Support toggle. */
        var row = $(this).closest('tr');
        if (row.next().attr('id') == 'details') {
            $('#details').find('.details_content').slideUp(250, function() {
                row.removeClass('expanded');
                $("#details").remove();
            });
            return false;
        }

        /* Close the existing expander here to make it more intuitive in concert
         * with $.get() delays. */
        var details = $('#details');
        details.closest('tr').prev().removeClass('expanded');
        details.remove();

        var me = this;
        var target = $(this).parent().find('a').attr('href');
        $.get(target, function(data) {
            /* TODO: The details expanders should slide open/closed so users
             * don't get the mistaken impression that they're covering things
             * up.
             */
            $(me).closest('tr').after("<tr id='details'><td colspan='6' class='details_inner'><div class='details_content' style='display: none'>" + data + "</div></td></tr>");
            $(me).closest('tr').addClass('expanded');
            $('#details').find('.details_content').slideDown(250);
            // TODO: Try to make this kind of thing an event instead.
            details_setup($('#details'));

            // TODO: Complete my use of this to actually power the back button.
            // TODO: Also hook this into category switching.
            // (Currently only good for un-breaking the reload button on stories)
            if (history.pushState) { history.pushState({}, "", target); }

            if (window.piwikTracker) {
                piwikTracker.setCustomVariable(1, "AJAX", "true", "page");
                piwikTracker.setCustomUrl(target);
                //TODO: Make this more robust.
                piwikTracker.trackPageView($('#details').find('.name').text());
            }
        });

        return false;
    });

    // We only need to run this on document load (?story=XX) and on details
    // expander creation. (AJAX browsing)
    details_setup();

    var details_node = $('#details');
    if (details_node.length !== 0) {
        window.scroll(details_node.offset().left, details_node.offset().top);
    }

    // Deadlinks selector for the problem-reporting GUI
    var dl_sel = function() {
        if ($("select#problem").val() == 'deadlinks') {
            $("#linkselector").show();
            $("#l_details").html('Suggestions:');
            $("#details").height("4em");
        } else {
            $("#linkselector").hide();
            $("#l_details").html('Details:');
            $("#details").height("6em");
        }
    };
    $("select#problem").change(dl_sel);
    dl_sel(); /* Ensure intuitive behaviour on reload */

});

