function selectAsSubmit(elem_or_id) {
    var select = jQuery((typeof elem_or_id === "string") ?
        document.getElementById(elem_or_id) : elem_or_id);
    var mousey = false;
    function submit () {
        select.closest("form").submit();
    }
    function rodent () {
        mousey = true;
    }
    function changed () {
        if (mousey) {
            submit();
        }
    }
    select.mousedown(rodent);
    select.change(changed);
}
function aggregatorEffects($) {
    selectAsSubmit("agg-jump-source");
    $("#agg-jump-button").addClass("hide");
    var agg_ts_conf = {
        dateFormat: 'uk',
        cancelSelection: false,
        textExtraction: 'complex', // this is jQuery(node).text();
        widgets: ['zebra'],
        sortClassAsc: 'headerSortUp',
        sortClassDesc: 'headerSortDown',
        headerClass: 'header'
    };
    // table sorter
    // add tablesort to all tables with 'sortable' class
    $('table.sortable').tablesorter(agg_ts_conf);
    // add title attributes to sortable <th>s
    $('table.sortable th').each(function(){
        $(this).attr('title', 'Sort by '+ $(this).text());
    });
    // advanced search options hidden unless they were used on this query
    var advanced_used = $("#search_source").val() !== "___all___";
    $("#agg-search-advanced-h").collapsible(advanced_used);
    // pagination of the open, forthcoming, closed sections
    function apage(event) {
        event.preventDefault();
        // instead of following, replace the whole section
        var section = $(this).closest("div.batched-consultations");
        var r = /\s*(\S+\s+)*consultations-((search-)?(open|forthcoming|closed))/;
        var sectionKind = r.exec(section[0].className)[2];
        var url = this.href;
        // strip &ajaxSection off the end if it's there already
        var s = /(.*)&ajaxSection=(search-)?(open|forthcoming|closed)(.*)/;
        var u = s.exec(url);
        if (u) url = u[1] + u[4];
        s = /(.*)&deliv_notheme=?(.*)/;
        u = s.exec(url);
        if (u) url = u[1] + u[2];
        // and then add it on again afterwards
        url = url+"&ajaxSection="+sectionKind+"&deliv_notheme";
        function table_resort() {
            $(this).find("table.sortable").tablesorter(agg_ts_conf);
        }
        section.load(url,"",table_resort);
    }
    $("div.batched-consultations ul.agg-controls a").live("click", apage);
}
jQuery(aggregatorEffects);

