﻿jQuery(document).ready(function()
{
    jQuery('table.ottelukalenteri').tablesorter
    ({
         headers:
         {
             1:
             {
                 type: 'text'
             }
         }
    });
    
    jQuery('table.ottelukalenteri').bind('sortEnd', function()
    {
        console.log('sort ended');
        jQuery(this).tablerows();
    });
    
    jQuery('table.ottelukalenteri tbody td.venue a').click(function()
    {
        var string = jQuery(this).html();
        
        jQuery('table.ottelukalenteri tr.vevent').each(function(i)
        {
            var row = this;
            
            jQuery(this).find('td.venue a').each(function(i)
            {
                if (jQuery(this).html() !== string)
                {
                    jQuery(row).css({display: 'none'});
                    return;
                }
            });
        });
        
        jQuery('table.ottelukalenteri').tablerows();
        window.location.hash = '#' + string;
        
        jQuery('div.legend li.vevent').css('display', 'inline');
        return false;
    });

    jQuery('div.legend ul li')
        .css('cursor', 'pointer')
        .click(function()
        {
            var type = this.className;
            
            jQuery('table.ottelukalenteri tbody tr').each(function(i)
            {
                if (jQuery(this).hasClass(type))
                {
                    jQuery(this).css('display', 'table-row');
                }
                else
                {
                    jQuery(this).css('display', 'none');
                }
            });
            
            // Hide the filter removal button after it has been clicked
            if (jQuery(this).hasClass('vevent'))
            {
                jQuery(this).css('display', 'none');
            }
            else
            {
                jQuery('div.legend li.vevent').css('display', 'inline');
            }
            
            jQuery('table.ottelukalenteri').tablerows();
        });
});

jQuery.fn.tablerows = function()
{
    // Initialize the counter
    var counter = 0;
    
    jQuery(this).find('tbody tr').each(function(i)
    {
        // Skip the invisible thiss
        if (jQuery(this).css('display') == 'none')
        {
            return;
        }
        
        if (counter % 2 == 0)
        {
            jQuery(this).removeClass('odd');
            jQuery(this).addClass('even');
        }
        else
        {
            jQuery(this).removeClass('even');
            jQuery(this).addClass('odd');
        }
        
        counter++;
    });
}