﻿$(document).ready(function() {
    var tables = $("table[id='sorteringsbar']");
    if (tables.length > 0) {
        $(tables).each(function() {
            TableSorter.LazyInitialize(this);
        });
    }
});

var TableSorter = {
    Initialize: function(table) {
        $(table).addClass("tablesorter");
        $(table).find("tr:first").wrap("<thead>");
        $(table).find("tr:gt(0)").wrapAll("<tbody>");
        if ($(table).find("tbody tbody").length > 0) { $(table).find("tbody:first").replaceWith($(table).find("tbody:first").html()); }
        $(table).find("tr:gt(0) th").each(function() { $(this).replaceWith("<td>" + $(this).text() + "</td>"); });
        $(table).find("tr:first td").each(function() { $(this).replaceWith("<th>" + $(this).text() + "</th>"); });
        $(table).tablesorter();
        ColumnHeights.SetEqualHeights();
    },
    LazyInitialize: function(table) {
        if (typeof ($.tablesorter) == 'undefined') {
            
            //Added css to masterpage. Unable to get onload event on link tag
            //$("<link>").appendTo("head").attr({ rel: "stylesheet", type: "text/css", href: "/Content/Js/table-sorter/theme/style.css" });
            $.getScript("/content/js/table-sorter/jquery.tablesorter.min.js", function() { TableSorter.Initialize(table); });
        } else {
            TableSorter.Initialize(table)
        }
    }
};

var ColumnHeights = {
    SetEqualHeights: function() {
        if ($("#piccolumn").length == 1) {
            ColumnHeights.SetEqualThreeColumnsHeight();
        } else {
            ColumnHeights.SetEqualTwoColumnsHeight();
        }
    },

    SetEqualTwoColumnsHeight: function() {
        $("#leftcontent, #rightcontent").removeAttr("style");
        var leftHeight = $("#leftcontent").height();
        var rightHeight = $("#rightcontent").height();
        $("#leftcontent, #rightcontent").height(leftHeight > rightHeight ? leftHeight : rightHeight);
    },

    SetEqualThreeColumnsHeight: function() {
        $("#lefthalf, #rightcontent, #piccolumn").removeAttr("style");
        var leftHeight = $("#lefthalf").height();
        var rightHeight = $("#rightcontent").height();
        var picsHeight = $("#piccolumn").height();
        var max = leftHeight > rightHeight ? leftHeight : rightHeight;
        max = max > picsHeight ? max : picsHeight;
        $("#lefthalf, #rightcontent, #piccolumn").height(max);
    }
}
