$(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'
    }

    // Table filter
    $('a.table-filter-disable').bind('click', function(){
        $(this).parent().find('input.table-filter').attr('checked', '');
        $(this).parent().find('input.table-filter').eq(0).change();
    });

    $('input.table-filter').bind('change', function(){
        var tableId = $(this).attr('data-table-id');
        var table   = $('#' + tableId);
        var filters = $('input.table-filter[data-table-id="' + tableId + '"]');

        table.find('tbody > tr').show();

        var columnClasses = {};

        filters.each(function(){
            columnClasses[$(this).attr('data-column')] = null;
        });

        for (var columnClass in columnClasses) {
            table.find('tbody > tr > td.' + columnClass).each(function(){
                var show       = false;
                var anyChecked = false;
                var column     = $(this);

                filters.filter('[data-column="' + columnClass + '"]').each(function(){
                    if (!this.checked || show) {
                        return;
                    }

                    anyChecked = true;

                    var columnClass     = $(this).attr('data-column');
                    var format          = $(this).attr('data-format');
                    var type            = $(this).attr('data-type');
                    var compareValue    = $(this).attr('data-compare-value');
                    var compareOperator = $(this).attr('data-compare-operator');
                    var regex           = new RegExp(format);

                    var match = column.text().match(regex);
                    var value;

                    if (!match) {
                        if (type == 'string') {
                            value = '';
                        } else {
                            value = 0;
                        }
                    } else {
                        if (type == 'string') {
                            value = match[1];
                        } else {
                            value = parseFloat(match[1].replace(',', '.'));
                        }
                    }

                    if (type != 'string') {
                        compareValue = parseFloat(compareValue);
                    }

                    switch (compareOperator) {
                        case '=':
                            show = (value == compareValue);
                            break;

                        case '!=':
                            show = (value != compareValue);
                            break;

                        case '>':
                            show = (value > compareValue);
                            break;

                        case '>=':
                            show = (value >= compareValue);
                            break;

                        case '<':
                            show = (value < compareValue);
                            break;

                        case '<=':
                            show = (value <= compareValue);
                            break;
                    }
                });

                if (anyChecked && !show) {
                    $(this).parent().hide();
                }
            });
        }
    });

    $('input.table-filter').attr('checked', '');

    // Sortable tables
    if (typeof($.fn.tablesorter) != 'undefined') {
        $.tablesorter.addParser({ 
            id: 'vendor', 
            is: function(s) {
                if (s.match(/<a.*? class="anbieter">(?:\s|\n)*([^<>]*?)(?:\s|\n)*<\/a>/m)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                var result = s.match(/<a.*? class="anbieter">(?:\s|\n)*([^<>]*?)(?:\s|\n)*<\/a>/m);

                if (result) {
                    return result[1].toLowerCase();
                }
                return 0;
            },
            type: 'text' 
        });
               
        $.tablesorter.addParser({ 
            id: 'price', 
            is: function(s) {
                if (s.match(/^\d+(?:,\d+)? .( pro (MB|Min))?$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/^(\d+(?:,\d+)?) .( pro (MB|Min))?$/,'$1').replace(/,/,'.'); 
            },
            type: 'numeric' 
        });
		
        $.tablesorter.addParser({ 
            id: 'pricespan', 
            is: function(s) {
                if (s.match(/<span>\d+(?:,\d+)? .<\/span>/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
				return s.replace(/^[\s\S]*<span>(\d+(?:,\d+)?) .<\/span>[\s\S]*$/,'$1').replace(/,/,'.'); 
            },
            type: 'numeric' 
        });

        $.tablesorter.addParser({ 
            id: 'contract', 
            is: function(s) {
                if (s.match(/^(Kein Vertrag|\d+ Monate)$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/(\d+) Monate/,'$1').replace(/Kein Vertrag/,'0'); 
            },
            type: 'numeric' 
        });

        $.tablesorter.addParser({ 
            id: 'throttling', 
            is: function(s) {
                if (s.match(/^\d+ [KMGT]B$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/(\d+) [KMGT]B/,'$1') ;
            },
            type: 'numeric' 
        });

        $.tablesorter.addParser({ 
            id: 'speed', 
            is: function(s) {
                if (s.match(/Down: \d+,\d+.*Up: \d+,\d+/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/Down: (\d+,\d+).*Up: \d+,\d+.*/,'$1').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'];
        
        var options = {};
        options['headers'] = {};
        options['widgets'] = ['zebra'];

        $('table.sortable thead th').each(function(index) {
        	if ($(this).hasClass('disable-sorting')) {
        		options['headers'][index] = { sorter: false};
        	}
        });

        $('table.sortable').tablesorter(options);
    }
    
    // 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 = jQuery(this).find('a.logo').attr('href');
	if (typeof(url) != 'undefined') {
		window.open(url,'newPopup','');
	}
	
	var url = $(this).find('a.anbieter').attr('href');
        window.location.href = url;
	return false;
    });
});

