/**
 * Script:  C3TableSort.js
 * Desc:    Client-Side DHTML Table Sort routine used by the C3DataGrid Control.
 */


// Execute function when document readystate changes.
document.attachEvent('onreadystatechange',TableSort_Initialize);
//addEvent(document, "readystatechange", TableSort_Initialize);
//addEvent(window, "load", TableSort_Initialize);
//document.onreadystatechange=TableSort_Initialize;


var nTableSortColumnIndex;
var sTableSortIconUrlArrowUp   = '/c3.net/images/TableSortUp.gif'
var sTableSortIconUrlArrowDown = '/c3.net/images/TableSortDown.gif'
var sTableSortStyle            = 'text-Decoration:none;'


function TableSort_Initialize() {

//alert('TableSort_Initialize - document.readyState='+document.readyState);

    // Find all tables with class sortable and make them sortable.
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            TableSort_MakeSortable(thisTbl);
        }
    }

    // Find all tables with C3DataGrid "TableSort=Yes" attribute and make them sortable.
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if ((thisTbl.getAttribute("TableSort") == 'Yes') && (thisTbl.id)) {
            TableSort_MakeSortable(thisTbl);
        }
    }
}


function TableSort_MakeSortable(table) {

    // Any rows in table?  If not, then we are done.
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    
    // Assume first row is the header, and make its contents clickable links.
    for (var i=0;i<firstRow.cells.length;i++) {

        // Set table cell object reference.
        var cell = firstRow.cells[i];

        // Add column index attribute.
        cell.setAttribute('TableSortColumnIndex', String(i),0);

        // Check for C3DataGrid "TableSortColumn=No" Sort attribute - assume sortable if not found.
        if (cell.getAttribute("TableSortColumn") != 'No') {
            var txt = TableSort_GetInnerText(cell);
            cell.innerHTML = '<a href="#" style="' + sTableSortStyle + '" title="Click to Sort By ' + txt + '" onclick="TableSort_ReSortTable(this);return false;">' + txt + '<span class="TableSortArrowClass">&nbsp;&nbsp;&nbsp;</span></a>';
        }
//alert('Making Sortable! \ncell.getAttribute='+cell.getAttribute("TableSortColumnIndex")+' \ncell.innerHTML='+cell.innerHTML);
    }
}


function TableSort_GetInnerText(el) {

    if (typeof el == "string") return el;
    if (typeof el == "undefined") { return el };
    if (el.innerText) return el.innerText;	//Not needed but it is faster
    var str = "";

    var cs = el.childNodes;
    var l = cs.length;

    for (var i = 0; i < l; i++) {
        switch (cs[i].nodeType) {
            case 1:  //ELEMENT_NODE
                str += TableSort_GetInnerText(cs[i]);
                break;
            case 3:  //TEXT_NODE
                str += cs[i].nodeValue;
                break;
        }
    }

    return str;
}


function TableSort_ReSortTable(lnk) {

    // Get the span.
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }

    var spantext = TableSort_GetInnerText(span);
    var td = TableSort_GetParent(lnk,'TD');
    var table = TableSort_GetParent(td,'TABLE');
    var column = td.getAttribute('TableSortColumnIndex');

//alert('Table Sort! \ntd.getattribute='+td.getAttribute("TableSortColumnIndex")+' \ntd.outerHTML='+td.outerHTML+' \nspantext='+spantext+' \nlnk.outerHTML='+lnk.outerHTML+' \ncolumn='+column+' \nlnk.tagName='+lnk.tagName+' \nlnk.id='+lnk.id+' \ntd.cellIndex='+td.cellIndex);

    // Determine data type for column.
    if (table.rows.length <= 1) return;
    var itm = TableSort_GetInnerText(table.rows[1].cells[column]);
    sortfn = TableSort_SortByCaseInSensitive;

    if (TableSort_IsDate(itm)) sortfn = TableSort_SortByDate;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = TableSort_SortByDate;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = TableSort_SortByDate;
    if (itm.match(/^[£$]/)) sortfn = TableSort_SortByCurrency;
    if (itm.match(/^[\d\.]+$/)) sortfn = TableSort_SortByNumeric;

    // Create array of column values.
    nTableSortColumnIndex = column;
    var firstRow = new Array();
    var newRows = new Array();
    var padRows = new Array();
    var lastsortablerow = table.rows.length;
    var padidx = 0;

    for (i=0;i<table.rows[0].length;i++) { 
        firstRow[i] = table.rows[0][i]; 
    }
    for (j=1;j<table.rows.length;j++) { 
        if (table.rows[j].C3PadRow=="true") {
            if (padidx==0) lastsortablerow = j;
            padRows[padidx] = table.rows[j];
            padidx++;
        } else {
            newRows[j-1] = table.rows[j]; 
        }
    }

    // Sort the array using the determined data type.  If it fails, then try sorting
    // the array using the default type.
    try { 
        newRows.sort(sortfn);
    } catch(er) {
        sortfn = TableSort_SortByCaseInSensitive;
        newRows.sort(sortfn);
    } 

    var ARROW = "";

    // Set sort direction indicator.
    if (span.getAttribute("TableSortDirection") == 'down') {
        ARROW = "&nbsp;<img border=0 src='" + sTableSortIconUrlArrowUp + "'>";
        newRows.reverse();
        span.setAttribute('TableSortDirection','up');
    } else {
        ARROW = "&nbsp;<img border=0 src='" + sTableSortIconUrlArrowDown + "'>";
        span.setAttribute('TableSortDirection','down');
    }
    
    // We appendChild rows that already exist to the tbody, 
    // so it moves them rather than creating new ones.

    // don't do sortbottom rows.
    for (i=0;i<newRows.length;i++) { 
        if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);
    }

    // do sortbottom rows only.
    for (i=0;i<newRows.length;i++) { 
        if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);
    }

    // do padding rows only.
    for (i=0;i<padRows.length;i++) { 
        table.tBodies[0].appendChild(padRows[i]);
    }

    var sTableSortItemCssClass = table.TableSortItemCssClass;
    var sTableSortItem = table.TableSortItem;
    var sTableSortItemAltCssClass = table.TableSortItemAltCssClass;
    var sTableSortItemAlt = table.TableSortItemAlt;

//alert('TableSort Styles:\nTableSortItemCssClass='+table.TableSortItemCssClass+'\nTableSortItemAltCssClass='+table.TableSortItemAltCssClass+'\nTableSortItem='+table.TableSortItem+'\nTableSortItemAlt='+table.TableSortItemAlt);

    // Reapply alternating row colors.
    if(table.TableSortItemCssClass) {
        for (j=1;j<table.rows.length;j++) { 
            if ((table.rows[j].DGRowSelFlag!='true') && (table.rows[j].IsSelected!='true'))  {
                if (j%2 == 0) {
                    table.rows[j].className = sTableSortItemCssClass;
                    table.rows[j].style.cssText = sTableSortItem;
                } else {
                    table.rows[j].className = sTableSortItemAltCssClass;
                    table.rows[j].style.cssText = sTableSortItemAlt;
                }
            }
        }
    }

    // Delete any other arrows that may be showing.
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'TableSortArrowClass') {
            if (TableSort_GetParent(allspans[ci],"table") == TableSort_GetParent(lnk,"table")) {   // In the same table as us?
                allspans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';
            }
        }
    }
        
    span.innerHTML = ARROW;

    table.focus();

}


function TableSort_GetParent(el, pTagName) {

    if (el == null) return null;
    else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
        return el;
    else
        return TableSort_GetParent(el.parentNode, pTagName);
}


function TableSort_SortByDate(a,b) {

    // Convert DateA to date object and ensure it's a valid date.
    var dDateA = new Date(TableSort_GetInnerText(a.cells[nTableSortColumnIndex]));
    if(isNaN(dDateA)) return 1;

    // Convert DateB to date object and ensure it's a valid date.
    var dDateB = new Date(TableSort_GetInnerText(b.cells[nTableSortColumnIndex]));
    if(isNaN(dDateB)) return 1;

    // Return indicator based on less than, greater than, or equal.
    if (dDateA==dDateB) return 0;
    if (dDateA<dDateB)  return -1;
    return 1;

}


function TableSort_IsDate(sDateToTest) {

    // Determine if passed value is a date or not.
    var dDate, bResult;
    var dDate = new Date(sDateToTest);
    isNaN(dDate)? bResult=false : bResult=true;
    return bResult;

}


function TableSort_SortByCurrency(a,b) { 

    aa = TableSort_GetInnerText(a.cells[nTableSortColumnIndex]).replace(/[^0-9.]/g,'');
    bb = TableSort_GetInnerText(b.cells[nTableSortColumnIndex]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);

}


function TableSort_SortByNumeric(a,b) { 

    aa = parseFloat(TableSort_GetInnerText(a.cells[nTableSortColumnIndex]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(TableSort_GetInnerText(b.cells[nTableSortColumnIndex])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;

}


function TableSort_SortByCaseInSensitive(a,b) {

    aa = TableSort_GetInnerText(a.cells[nTableSortColumnIndex]).toLowerCase();
    bb = TableSort_GetInnerText(b.cells[nTableSortColumnIndex]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;

}


function addEvent(elm, evType, fn, useCapture) {

    // addEvent and removeEvent.
    // cross-browser event handling for IE5+, NS6 and Mozilla.

    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    } else if (elm.attachEvent) {
        var r = elm.attachEvent("on"+evType, fn);
        return r;
    } else {
        alert("jsTableSort.js - Event Handler could not be attached!");
    }
} 

