/// <reference path="jquery-1.6.2-vsdoc.js" />
/// <reference path="scripte.js" />
/*!
* jquery.fixedHeaderTable. The jQuery fixedHeaderTable plugin
*
* Copyright (c) 2010 Mark Malek
* http://fixedheadertable.mmalek.com
*
* Licensed under MIT
* http://www.opensource.org/licenses/mit-license.php
* 
* http://docs.jquery.com/Plugins/Authoring
* jQuery authoring guidelines
*
* Version : 1.1.2 beta
*
* modifyed by Intact Sep 2010
* 
*/
(function ($j) { //wird ohne Parameter verwendet
    $j.fn.fixedHeaderTable = function (options) {
        var defaults = {
            loader: false,
            footer: false,
            colBorder: true,
            cloneHeaderToFooter: false,
            autoResize: false,
            onComplete: null,
            heightPercentOfWindow: null,
            widthPercentOfWindow: null,
            rightFixPointID: null,
            minWidth: 0,
            resizing: false,
            ignore: false,
            rebuild_init: false
        };

        var options = $j.extend(defaults, options); // get the defaults or any user set options

        return this.each(function () {
            var obj = $j(this); // the jQuery object the user calls fixedHeaderTable on (Div um Tabelle herum)
            var origWidth = obj.width();

            buildTable(obj, options);

            /* When the browser is resized set a javascript timeout (setTimeout()) on the build table function.
            * If the browser is continuously being resized, reset the timeout. If the browser hasn't been resized
            * for 200ms then exectue buildTable.
            */
            if (options.autoResize == true) {
                // if true resize the table when the browser resizes
                $j(window).resize(function () {
                    options.resizing = true;
                    if (obj[0].resizeTable) {
                        // if a timeOut is active cancel it because the browser is still being resized
                        clearTimeout(obj[0].resizeTable);
                    }

                    // setTimeout is used for resizing because some browsers will call resize() while the browser is still being resized which causes performance issues.
                    // if the browser hasn't been resized for 200ms then resize the table
                    obj[0].resizeTable = setTimeout(function () {
                        var jetzt = new Date();
                        if (obj[0].timeStampLast == null || jetzt.getTime() - 195 > obj[0].timeStampLast.getTime()) //Endlosschleifen verhindern
                            buildTable(obj, options, true);
                        obj[0].timeStampLast = new Date();

                    }, 200);
                });
                options.origWidth = obj.width();
            }
        });
    };

    var table = function () {
        this.resizeTable; // stores the value of the resize javascript timeout (setTimeout)
    }

    function getScrollbarWidth(obj) { //temporäres <p> in <div> um Scrollbar "abzumessen"

        obj.append('<div class="t_fixed_header_scroll_outer"></div>');
        var oute = $j('div.t_fixed_header_scroll_outer');
        oute.append('<p class="t_fixed_header_scroll_inner"> &nbsp; </p>');
        var inn = $j('p.t_fixed_header_scroll_inner');

        var w1 = (inn.innerWidth()); //keine Scrollbar
        oute.css('overflow', 'scroll');
        var w2 = inn.innerWidth(); //mit Scrollbar
        var sw = w1 - w2; //Scrollbarbreite, wenn eine erstellt wurde :)

        if (w1 == w2) { //es wurde wahrscheinlich keine erstellt...
            if ($j.browser.msie == true) {
                sw = 20; // default width of scrollbar for IE
            }
            else if (jQuery.browser.safari == true) {
                sw = 15; // default width of scrollbar for Safari
            }
            else {
                sw = 20; // default width of scrollbar for everyone else(FireFox, Chrome, Opera etc)
            }
        }
        oute.remove();
        if ($j.browser.webkit == true)
            sw += 2;
        if ($j.browser.mozilla == true)
            sw += 1;
        return sw;
    }

    function buildTable(obj, options, rebuild) {
        if (options.rebuild_init)
            rebuild = true;
        var objClass = obj.attr('class');
        var hasTable = obj.find("table").size() > 0; // returns true if there is a table
        var hasTHead = obj.find("thead").size() > 0; // returns true if there is a thead
        var hasTBody = obj.find("tbody").size() > 0; // returns true if there is a tbody
        var styles = obj.attr('style');
        //        if (styles != undefined && obj.attr("ignore") != "true" && ((styles.toLowerCase().indexOf("width", 0) > -1) || (styles.toLowerCase().indexOf("height", 0) > -1)))
        //            obj.attr("hadsizestyle", "true");

        if (hasTable && hasTHead && hasTBody) {
            var parentDivWidth = obj.innerWidth(); // get the width of the parent DIV
            //Workaround, wenn Grid in Tabelle platziert ist
            if (obj.parent().length > 0 && obj.parent()[0].tagName == "TD") {
                obj.width(obj.parent().width());
                parentDivWidth = obj.width();
                if (parentDivWidth > $j(window).width() || (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 7)) {
                    obj.width($j(window).width() - 40);
                    parentDivWidth = obj.width();
                }
            }

            var parentDivHeight = obj.innerHeight(); // get the height of the parent DIV
            var tableBodyWidth = parentDivWidth; // width of the div surrounding the tbody (overflow:auto)
            var footerHeight = 0;
            var scrollbarwidth = getScrollbarWidth(obj);


            var winWidth = $j(window).width();
            var docWidth = $j(document).width();
            if ($j(obj).offset().left > 30) {
                winWidth -= $j(obj).offset().left;
                parentDivWidth = winWidth - 22;
                if (!options.widthPercentOfWindow)
                    obj.width(parentDivWidth);
            }
            var hasRightPointObj = false;
            if (options.rightFixPointID != null && (hasRightPointObj = $j(options.rightFixPointID).length > 0))
                parentDivWidth -= ($j(options.rightFixPointID).outerWidth() + 18);
            if (options.widthPercentOfWindow != null)
                parentDivWidth = Math.floor(parentDivWidth * (options.widthPercentOfWindow / 100.0)) - 10;
            if (options.minWidth > 0 && parentDivWidth < options.minWidth)
                parentDivWidth = options.minWidth;
            if (!rebuild)
                obj.lastWidth = parentDivWidth;
            else if (obj.lastWidth !== parentDivWidth || (obj.find(".dragresizer").length > 0 && obj.lastWidth == parentDivWidth)) {
                rebuild = false;
                obj.lastWidth = parentDivWidth;
            }

            var winHeight = $j(window).height();
            //wenn keine Breite oder Höhe am Formular gesetzt wurde, wird der verfügbare Platz im Browserfenster berechnet und verwendet
            if (options.heightPercentOfWindow != null) {
                var minTop = 0;
                jQuery("div.fh").each(function (i, fhDiv) {
                    var posTop = $j(fhDiv).offset().top;
                    if (i == 0 || (posTop > 0 && posTop < minTop))
                        minTop = posTop;
                });
                var myPlace = Math.floor(winHeight - minTop - $j("div#DPB").outerHeight() - 10);
                parentDivHeight = Math.floor(myPlace * (options.heightPercentOfWindow / 100.0)) - 10;
                var parentRegister = $j(obj).closest(".regItem");
                if (parentRegister && parentRegister.length == 1) {
                    var heightOfTopRegister = $j(obj).offset().top - parentRegister.offset().top + 20;
                    if (heightOfTopRegister > 0 && parentDivHeight > heightOfTopRegister + 50)
                        parentDivHeight -= heightOfTopRegister;
                }
                if (hasRightPointObj && $j(options.rightFixPointID).outerWidth() > parentDivHeight)
                    parentDivHeight += $j("div#DPB").outerHeight(); //Wenn das Referenzobjekt größer ist als der sichtbare Bereich, braucht der Platz für die Pagebuttons nicht abgezogen werden.
                $j(obj).css("height", parentDivHeight);
            }
            if (styles == undefined || (styles != undefined && (styles.toLowerCase().indexOf("width", 0) <= -1))) {
                var tempa = $j(window).width() - obj.offset().left - 20;
                if (tempa < parentDivWidth)
                    parentDivWidth = tempa;
            }
            if (styles == undefined || (styles != undefined && (styles.toLowerCase().indexOf("height", 0) <= -1))) {
                var tempo = winHeight - obj.offset().top;
                //MS11: da ohne options.heightPercentOfWindow nicht groeszer resized wurde und mit options.heightPercentOfWindow unten zu viel offset
                if (tempo < parentDivHeight || (!options.heightPercentOfWindow && tempo > obj.innerHeight() && options.resizing))
                    parentDivHeight = tempo;
            }

            jQuery('.fht_table_body tr div.icon-row a').show();
            if (!rebuild)
                obj.find('div.fht_fixed_header').remove();

            if (obj.find('div.fht_table_body').size() == 0)
                obj.wrapInner('<div class="fht_table_body"></div>');

            var table = obj.find('div.fht_table_body table:eq(0)');
            var tableWidth = parentDivWidth;
            //nicht verwendet
            if (options.footer && !options.cloneHeaderToFooter) {
                var footerId = options.footerId;
                var footerHeight = obj.find('#' + footerId).outerHeight(); // store the footer height.  Used later to determine the allowed height for scrolling the table
                // if footer is true and its not a cloned footer
                if (!options.footerId) {
                    // notify the developer they wanted a footer and didn't provide content
                    $j('body').css('background', '#f00');
                    alert('Footer ID required');
                }
                else {
                    var footerId = options.footerId;
                    $j('#' + footerId).appendTo(obj); // move the user created footer inside the table parent div.
                }
            }
            //alle header width angaben entfernen
            if (!rebuild)
                obj.find('div.fht_table_body table thead tr:first th').each(function () {
                    $j(this).removeAttr('width');
                });

            var headerHeight = table.find('thead').outerHeight();
            var bodyHeight = table.find('tbody').outerHeight();
            if (options.footer && options.cloneHeaderToFooter)
                footerHeight = headerHeight;
            if (headerHeight + bodyHeight + footerHeight < parentDivHeight) {
                parentDivHeight = headerHeight + bodyHeight + footerHeight + 25;
                $j(obj).css("height", parentDivHeight);
            }
            var tableBodyHeight = parentDivHeight - headerHeight - footerHeight - 3;
            if (tableBodyHeight < 80) {
                parentDivHeight += 80 - tableBodyHeight
                $j(obj).css("height", parentDivHeight);
                tableBodyHeight = 80;
            }
            //wenn Höhe übergeben wird, darf der Div Table Body nicht um Scrollbarbreite vergrößert werden (Checklisten)
            var scrollbarausgleich = 0;
            obj.find('div.fht_table_body').css({ 'width': parentDivWidth + 'px', 'height': tableBodyHeight + scrollbarausgleich + 'px' });
            table.css('width', '100%');

            tableWidth = tableWidth - scrollbarwidth;
            obj.find('.fht_table_body').css('overflow', 'auto');

            table.css('width', tableWidth + 'px');

            if (!rebuild) {
                if (obj.find('div.fht_fixed_header').size() == 0) {  //hier werden Attribute an die Header Tabelle übergeben: width, class, cellspacing, id
                    if (obj.find(".dragresizer").length > 0)
                        var divi = obj.find(".dragresizer");
                    else
                        var divi = obj;
                    divi.prepend('<div class="fht_fixed_header"><table width="' + /*(obj.find('div.fht_table_body table:eq(0)').width())*/tableWidth + 'px" id="' + obj.find('div.fht_table_body table:eq(0)').attr('id') + '_fixedHeader" class="' + obj.find('div.fht_table_body table:eq(0)').attr('class') + '" cellspacing="' + obj.find('div.fht_table_body table:eq(0)').attr('cellspacing') + '"></table></div>');
                }
            }
            if (bodyHeight - headerHeight <= tableBodyHeight + scrollbarwidth) //Tabellenhoehe <= Divhoehe
                var scrollbarplatz = 0;
            else var scrollbarplatz = scrollbarwidth;

            // Problem bei mehrzeiligen headern wenn hoehe explizite gesetzt: hd 0032838
            //obj.find('div.fht_fixed_header').css({ 'width': parentDivWidth - scrollbarplatz + 'px', 'height': table.find('thead').outerHeight() + 'px', 'overflow': 'hidden' });
            obj.find('div.fht_fixed_header').css({ 'width': parentDivWidth - scrollbarplatz + 'px', 'overflow': 'hidden' });

            //zb. bei Checkliste, wenn Tabelle 100% in Zelle sein soll
            var widthi = table.attr('width');
            if (widthi != "" || widthi != undefined)
                obj.find('div.fht_fixed_header table').attr('width', widthi);

            if (!rebuild) {
                var i = 0; try {
                    obj.find('div.fht_table_body table thead tr:first th').each(function () { //wegen jQuery/IE8 Bug bei width() "$j(this).width()" => "$j.css(this, "width")"
                        var width = 0; //anscheinend jQuery und Prototype noConflict in jQuery etwas buggy bei width(),etc. Berechnungen => workarounds
                        if ($j.browser.msie == true || $j.browser.opera == true)
                            width = $j(this).width() + 1; //$j.css(this, 'width')
                        else if ($j.browser.webkit == true)
                            width = $j(this).width() + 1;
                        else //FF
                            width = $j(this).width() + 1;

                        $j(this).attr('width', width + 'px');
                        if ($j(this).find('.empty-cell').size() == 0) {
                            $j(this).wrapInner('<div class="empty-cell" style="width:' + width + 'px;"></div>');
                        }
                        else
                            $j(this).find('.empty-cell').css("width", width);

                        if ($j(this).is(':first-child')) {
                            $j(this).addClass('first-cell');
                        }

                        if ($j(this).is(':last-child')) {
                            $j(this).addClass('last-cell');
                        }
                    });
                } catch (e) { } //htmlfile:invalide argument? tbody (fast) leer?  
            }

            if (rebuild)
                return;

            var tableHeader = obj.find('div.fht_table_body table thead');
            var tableHeaderZiel = obj.find('div.fht_fixed_header table');
            tableHeader.clone().appendTo(tableHeaderZiel);
            //Margin-top negativ um untere Tabelle hinter Header zu verschieben -- eq(0), weil sonst auch tables in tables angegriffen werden!
            obj.find('div.fht_table_body table:eq(0)').css({ 'margin-top': -(obj.find('div.fht_table_body table thead:eq(0)').outerHeight()) + 'px' });

            if (options.footer && options.cloneHeaderToFooter)// put cloned header here
                obj.find('div.fht_fixed_header').clone().appendTo(obj);

            if (options.loader) // if true hide the loader
                $j('.' + options.loaderClass).fadeOut('medium');

            $j.isFunction(options.onComplete) && options.onComplete.call(this);

            obj.find('div.fht_table_body').scroll(function () {
                //                if ($j.browser.mozilla) //ohne Ruckeln, aber jQuery Problem mit überschriebenem Prototype scrollTo in IE
                //                    obj.find("div.fht_fixed_header").scrollLeft(obj.find('div.fht_table_body').scrollLeft());
                //                else
                obj.find('.fht_fixed_header table').css('margin-left', (-this.scrollLeft) + 'px'); // scroll the fixed header equal to the table body's scroll offset
                if (options.footer && options.cloneHeaderToFooter) // if a cloned footer is visible it needs to be scrolled too
                    obj.find('.fht_fixed_footer_border').css('margin-left', (-this.scrollLeft) + 'px');
            });
            obj.find('div.fht_table_body').scroll();
            widthCorrection(obj);

            if (obj.attr('ignore') != 'true') { //sollte skype plugin aktiv sein und die tabelle nach ca 1000ms auseinanderschieben wird das gecheckt und einmal resized.
                var objektid = "." + obj.attr('class');
                objektid = objektid.split(" ");
                window.setTimeout(function () { if ($j(objektid[0]).find('.fht_table_body table').width() > $j(objektid[0]).find('.fht_fixed_header table').width()) { $j(objektid[0]).fixedHeaderTable({ autoResize: true, resizing: true, rebuild_init: true }); } }, 1501);
                obj.attr('ignore', 'true');
            }
        }
    }

    function widthCorrection(obj) {
        var tblBody = obj.find('div.fht_table_body'), tblHeader = obj.find('div.fht_fixed_header table');
        var maxWidthCorrection = {};
        tblHeader.find("thead tr:first th:visible").not("th.dn").each(function (i, th) {
            var tht = $j(this);
            maxWidthCorrection[i] = { innerWidthHeader: tht.innerWidth(), /*outerWidthHeader: tht.outerWidth(),*/objTH: tht };
        });

        tblBody.find("tbody tr:first td:visible").not("td.dn").each(function (i, td) {
            var tdt = $j(this);
            if (maxWidthCorrection[i]) {
                maxWidthCorrection[i].innerWidthBody = tdt.innerWidth();
                maxWidthCorrection[i].objTD = tdt;
            }
        });

        if (tblBody.find("tr").not("tr.nav").length > 1) { //sonst wird Breite der Fusszeile in erstes th geschrieben, wenn tabelle leer
            for (var i in maxWidthCorrection) {
                if (maxWidthCorrection[i].innerWidthHeader == maxWidthCorrection[i].innerWidthBody)
                    continue;
                if (maxWidthCorrection[i].innerWidthHeader > maxWidthCorrection[i].innerWidthBody) {
                    maxWidthCorrection[i].objTD.contents().wrapAll("<div ce=1></div>");
                    var newDiv = maxWidthCorrection[i].objTD.find("div[ce=1]");
                    if (newDiv.length == 0)
                        newDiv = maxWidthCorrection[i].objTD.append("<div ce=1></div>").find("div[ce=1]");
                    newDiv.css("width", maxWidthCorrection[i].innerWidthHeader);
                    var diff = maxWidthCorrection[i].objTD.outerWidth() - maxWidthCorrection[i].objTH.outerWidth();
                    newDiv.css("width", maxWidthCorrection[i].objTD.innerWidth() - diff * 2);
                }
                else if (maxWidthCorrection[i].innerWidthHeader < maxWidthCorrection[i].innerWidthBody) {
                    maxWidthCorrection[i].objTH.contents().wrapAll("<div ce=1></div>");
                    var newDiv = maxWidthCorrection[i].objTH.find("div[ce=1]");
                    if (newDiv.length == 0)
                        newDiv = maxWidthCorrection[i].objTH.append("<div ce=1></div>").find("div[ce=1]");
                    newDiv.css("width", maxWidthCorrection[i].innerWidthBody);
                    var diff = maxWidthCorrection[i].objTH.outerWidth() - maxWidthCorrection[i].objTD.outerWidth();
                    newDiv.css("width", maxWidthCorrection[i].objTH.innerWidth() - diff * 2);
                }
            }
        }
    }
})(jQuery);
