﻿// JScript File
function sort(id, column, sortDefaultAscending) {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion >= 8) {
            var divtable = document.getElementById(id);
            if (divtable == null) { return; }

            var table = divtable.firstChild;
            if (table == null) { return; }

            var tbody = table.firstChild;
            var row = tbody.firstChild;
        }
    }
    else {//andere browsers
        var divtable = document.getElementById(id);
        if (divtable == null) { return; }

        var table = divtable.firstElementChild;
        if (table == null) { return; }

        var tbody = table.firstElementChild;
        var row = tbody.firstChild;
    }

    var firstNode;
    var lastNode;
    var lastNodeIndex = 0;
    var isSortedAscending = true;
    var isSortedDescending = true;
    var sortCount = 1;

    for (; row != null; row = row.nextSibling) {
        if (column >= row.childNodes.length) continue;
        var data = row.cells[column];
        if (data == null) continue;

        if (data.attributes['sort'] == null) continue;

        var sort = data.attributes['sort'].nodeValue;

        if (parseInt(sort, 10) == 1) firstNode = row;
        if (parseInt(sort, 10) > lastNodeIndex) { lastNode = row; lastNodeIndex = parseInt(sort, 10); }

        if (isSortedAscending) {
            isSortedAscending = parseInt(sort, 10) == sortCount;
        }
        if (isSortedDescending) {
            isSortedDescending = parseInt(sort, 10) + sortCount == lastNodeIndex + 1;
        }
        sortCount++;
    }

    var insertNode;

    var iStart;
    var iEnd;
    var iIncr;

    if (!isSortedAscending && !isSortedDescending) {
        if (sortDefaultAscending) isSortedAscending = true; else isSortedDescending = true;
    }

    if (isSortedAscending) {
        insertNode = firstNode;
        iStart = 2;
        iEnd = lastNodeIndex + 1;
        iIncr = 1;
    }
    if (isSortedDescending) {
        insertNode = lastNode;
        iStart = lastNodeIndex - 1;
        iEnd = 0;
        iIncr = -1;
    }

    for (var i = iStart; i != iEnd; i += iIncr) {
        var newNode;

        for (row = tbody.firstChild; row != null; row = row.nextSibling) {
            if (column >= row.childNodes.length) continue;
            var data = row.cells[column];
            if (data == null) continue;

            if (data.attributes['sort'] == null) continue;

            var sort = data.attributes['sort'].nodeValue;

            if (parseInt(sort, 10) == i) { newNode = row; break; }
        }

        tbody.insertBefore(newNode, insertNode);

        insertNode = newNode;
    }
}

