$(document).bind('ready', function (e) {
    // IE 7 version detection fix
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && window.XMLHttpRequest) {
        jQuery.browser.version = '7.0';
    }
    
    // Sortable tables
    if (typeof($.fn.tablesorter) != 'undefined') {
        $.tablesorter.addParser({ 
            id: 'vendor', 
            is: function(s) {
                if (s.match(/<a.*?>(?:\s|\n)*([^<>]*?)(?:\s|\n)*<\/a>/m)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                var result = s.match(/<a.*?>(?:\s|\n)*([^<>]*?)(?:\s|\n)*<\/a>/m);

                if (result) {
                    return result[1].toLowerCase();
                }
                return 0;
            },
            type: 'text' 
        });
               
        $.tablesorter.addParser({ 
            id: 'euro', 
            is: function(s) {
                if (s.match(/^\d+(?:,\d+) €$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/€/,'').replace(/,/,'.'); 
            },
            type: 'numeric' 
        });
        
        $.tablesorter.addParser({ 
           id: 'cent', 
           is: function(s) {
                if (s.match(/^\d+(?:,\d+)? ¢$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/¢/,'').replace(/,/,'.'); 
            },
            type: 'numeric' 
        });
        
        $.tablesorter.addWidget({ 
            id: "repeatHeaders", 
            format: function(table) { 
                if (!this.headers) { 
                    var h = this.headers = [];  
                    $("thead th",table).each(function() { 
                        h.push( 
                            '' + $(this).text() + '' 
                        ); 
                    }); 
                } 
                  
                $("tr.repated-header",table).remove(); 
                    
                for (var i=0; i < table.tBodies[0].rows.length; i++) { 
                    if ((i%5) == 4) { 
                        $("tbody tr:eq(" + i + ")",table).before( 
                            $("").html(this.headers.join("")) 
                        );     
                    } 
                } 
            } 
        });
        
        $.tablesorter.defaults.widgetZebra.css = ['tableRow0', 'tableRow1'];
        
        $('table.sortable').tablesorter({widgets: ['zebra']});
    }
    
    // Floating table headers
    if (!jQuery.browser.msie || parseInt(jQuery.browser.version, 10) >= 7) {
        var tableHeaderDoScroll = function() {
            if (typeof(tableHeaderOnScroll) == 'function') {
                tableHeaderOnScroll();
            }
        };

        // Track positioning and visibility.
        function tracker(e) {
            // Save positioning data.
            var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            
            if (e.viewHeight != viewHeight) {
                e.viewHeight = viewHeight;
                e.vPosition = $(e.table).offset().top + 1;
                e.hPosition = $(e.table).offset().left;
                e.vLength = e.table.clientHeight - 100;
                
                // Resize header and its cell widths.
                var parentCell = $('th', e.table);
                $('th', e).each(function(index) {
                    var cellWidth = parentCell.eq(index).css('width');

                    // Exception for IE7.
                    if (cellWidth == 'auto') {
                        cellWidth = (parentCell.get(index).clientWidth - 22) +'px';
                    }
                
                    $(this).css('width', cellWidth);
                });
                
                if (jQuery.browser.msie) {
                    $(e).css('width', (parseInt($(e.table).css('width')) - 50) + 'px');
                    $(e).css('table-layout', 'fixed');
                } else {
                    $(e).css('width', $(e.table).css('width'));
                }
            }

            // Track horizontal positioning relative to the viewport and set visibility.
            var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
            var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - e.vPosition;
            var visState = (vOffset > 0 && vOffset < e.vLength) ? 'visible' : 'hidden';
            $(e).css({left: -hScroll + e.hPosition +'px', visibility: visState});
        }
        
        // Keep track of all cloned table headers.
        var headers = [];

        $('table.sticky-enabled thead:not(.tableHeader-processed)').each(function () {
            var $table  = $(this).parent('table');
            var table   = $table[0];
            var classes = $table.attr('class');
            
            // Clone thead so it inherits original jQuery properties.
            var headerClone = $(this).clone(true).insertBefore(this.parentNode).wrap('<table class="' + classes + ' sticky-header"></table>').parent().css({
                position: 'fixed',
                top: '-2px'
            });

            // Local fix
            $('th', headerClone).each(function(index) {
                $(this).unbind('click');
                $(this).attr('title', '');
            });
            
            headerClone = $(headerClone)[0];
            headers.push(headerClone);

            // Store parent table.
            headerClone.table = table;
            
            // Finish initialzing header positioning.
            tracker(headerClone);

            $(table).addClass('sticky-table');
            $(this).addClass('tableHeader-processed');
        });

        // Only attach to scrollbars once, even if Drupal.attachBehaviors is called
        // multiple times.
        if (!$('body').hasClass('tableHeader-processed')) {
            $('body').addClass('tableHeader-processed');
            $(window).scroll(tableHeaderDoScroll);
            $(document.documentElement).scroll(tableHeaderDoScroll);
        }

        // Track scrolling.
        var tableHeaderOnScroll = function() {
            $(headers).each(function () {
                tracker(this);
            });
        };

        // Track resizing.
        var time = null;
        var resize = function () {
            // Ensure minimum time between adjustments.
            if (time) {
                return;
            }
            
            time = setTimeout(function () {
                $('table.sticky-header').each(function () {
                    // Force cell width calculation.
                    this.viewHeight = 0;
                    tracker(this);
                });
                
                // Reset timer
                time = null;
            }, 250);
        };
        
        $(window).resize(resize);
    }


    // Table click
    $('table.rate-overview tbody tr').bind('click', function() {
        var url = $(this).find('a').attr('href');
        window.location.href = url;
    });
});
