$(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
    $('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();

        filters.each(function(){
            if (!this.checked) {
                return;
            }

            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);

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

            table.find('tbody > tr > td.' + columnClass).each(function(){
                var match = $(this).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(',', '.'));
                    }
                }

                var hide  = false;

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

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

                    case '>':
                        hide = (value <= compareValue);
                        break;

                    case '>=':
                        hide = (value < compareValue);
                        break;

                    case '<':
                        hide = (value >= compareValue);
                        break;

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

                if (hide) {
                    $(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+)? EUR$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/^([\d\.]+(?:,\d+)?) EUR$/,'$1').replace(/\./g, '').replace(/,(\d\d)$/,'.$1'); 
            },
            type: 'numeric' 
        });
        
        $.tablesorter.addWidget({ 
            id: "repeatHeaders", 
            format: function(table) { 
                if (!this.headers) { 
                    var h = this.headers = [];  
                    $("thead th",table).each(function(index) {
                        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 MyOptions = {};
        MyOptions['headers'] = {};
        MyOptions['widgets'] = ['zebra'];

        $('table.sortable thead th').each(function(index) {
        	if ($(this).hasClass('nosort')) {
        		MyOptions['headers'][index] = { sorter: false};
        	}
        });
        
 	   	$('table.sortable').tablesorter( MyOptions );
    }
    
    // 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.anmeldung').attr('href');
	if (typeof(url) != 'undefined') {
		window.open(url,'newPopup','');
	}
	
	var url = $(this).find('a.anbieter').attr('href');
        window.location.href = url;
	return false;
    });    

});

