var sortDirection = 1;
var $bookTable;

var filterRows = function($table, filterText) {
    var re = new RegExp(filterText, 'i');
    $('tbody tr', $table).each(function(index) {
        var $this = $(this);
        if($this.text().match(re))
            $this.show();
        else
            $this.hide();
    });
    colorAlternateRows($bookTable);
};

var insertStyleRules = function(rules) {
    $('head').append('<style>'+rules+'</style>');
};

var changeColors = function(colorSet) {
    var rules = '';
    switch(colorSet) {
        case 'quiet':
            rules = '.odd {background-color: #F7F4F2;}'
                +'.even {background-color: #FFFFFF;}'
                +'#helpDiv {background-color: #dddddd;}'
                +'.bookListTitle {color: #444444;}'
            break;
        case 'bright':
            rules = '.odd {background-color: #ffc;}'
                +'.even {background-color: #cef;}'
                +'#helpDiv {background-color: #FEE59E;}'
                +'.bookListTitle {color: #786E29;}'
            break;
    }
    insertStyleRules(rules);
};
            

$(document).ready(function() {
    // Get the $bookTable variable for general use
    $bookTable = $('#booktable');
    $helpDiv = $('#helpDiv');
    $helpToggle = $('#helpToggle');
    
    $('#colorButton').click(function(ev) {
        changeColors(this.checked ? 'quiet' : 'bright');
        ev.stopPropagation();
    });
    
    // Set up the help
    $helpDiv.hide().click(function() {
        $helpToggle.click();
    });
    $helpToggle.click(function() {
        var newLinkText;
        if($helpDiv.is(':visible')) {
            $helpDiv.hide('normal');
            newLinkText = 'Show Help';
        } else {
            $helpDiv.show('normal');
            newLinkText = 'Hide Help';
        }
        $helpToggle.text(newLinkText);
    });
    
    // Set up filtering
    $('#filterText').val('').keyup(function() {
        filterRows($bookTable, $(this).val());
    });
    
    // Do the initial alternate row coloring.
    colorAlternateRows($bookTable);
    
    // Set up the sort-alpha rows
    $('th', $bookTable).each(function(column) {
        if( $(this).is('.sort') ) {
            var findSortKey = null;
            if($(this).is('.bydate')) {
                findSortKey = function($cell) {
                    return Date.parse($cell.text());
                }
            } else {
                findSortKey = function($cell) {
                    return $cell.find('.sort-key').text().toUpperCase()
                        + ' ' + $cell.text().toUpperCase();
                }
            }
            $(this).addClass('clickable').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            }).click(function() {
                // Remove other direction markers and add one for this sort.
                $('th', $bookTable).each(function(col2) {
                    var mark = '';
                    if(col2==column) {
                        if($(this).is('.sort-asc')) {
                            sortDirection = -1;
                            mark = " (Z->A)";
                            $(this).removeClass("sort-asc");
                        } else {
                            sortDirection = 1;
                            mark = " (A->Z)";
                            $(this).addClass("sort-asc");
                        }
                    }
                    $('span.sort-direction', this).text(mark);
                });
                // Get the tbody rows
                var rows = $bookTable.find('tbody > tr').get();
                // Generate a sort key for each row, do it once now for efficiency
                $.each(rows, function(index, row) {
                    row.sortKey = findSortKey($(row).children('td').eq(column));
                });
                // Sort the rows array
                rows.sort(colCompare);
                // Reinsert the rows in sorted order
                var $tbody = $bookTable.children('tbody');
                $.each(rows, function(index, row) {
                    $tbody.append(row);
                    row.sortKey = null;
                });
                sortDirection = -sortDirection;
                colorAlternateRows($bookTable);
            });
        }
    });
    
});

var colCompare = function(a, b) {
    if(a.sortKey < b.sortKey) return -sortDirection;
    if(a.sortKey > b.sortKey) return sortDirection;
    return 0;
};

var colorAlternateRows = function($table) {
    $('tbody tr:visible:odd', $table).removeClass('even').addClass('odd');
    $('tbody tr:visible:even', $table).removeClass('odd').addClass('even');
}