var dom = (document.getElementsByTagName) ? true : false;
var ie5 = (document.getElementsByTagName && document.all) ? true : false;

if (ie5 || dom)
    initSortTable();

function initSortTable() {
	
}



function sortTableAsc(tableNode, nCol, bDesc, sType) {
    var tBody = tableNode.tBodies[0];
    var trs = tBody.rows;
    var trl= trs.length;
    var a = new Array();
    
    for (var i = 0; i < trl; i++) {
        a[i] = trs[i];
    }
    
    var start = new Date;
 //   window.status = "Sorting data...";
    a.sort(compareByColumnAsc(nCol,bDesc,sType));
 //   window.status = "Sorting data done";
    
    for (var i = 0; i < trl; i++) {
        tBody.appendChild(a[i]);
       // window.status = "Updating row " + (i + 1) + " of " + trl +
         //               " (Time spent: " + (new Date - start) + "ms)";
    }
    
    // check for onsort
    if (typeof tableNode.onsort == "string")
        tableNode.onsort = new Function("", tableNode.onsort);
    if (typeof tableNode.onsort == "function")
        tableNode.onsort();
}

function sortTableDes(tableNode, nCol, bDesc, sType) {
    var tBody = tableNode.tBodies[0];
    var trs = tBody.rows;
    var trl= trs.length;
    var a = new Array();
    
    for (var i = 0; i < trl; i++) {
        a[i] = trs[i];
    }
    
    var start = new Date;
   // window.status = "Sorting data...";
    a.sort(compareByColumnDes(nCol,bDesc,sType));
    //window.status = "Sorting data done";
    
    for (var i = 0; i < trl; i++) {
        tBody.appendChild(a[i]);
       // window.status = "Updating row " + (i + 1) + " of " + trl +
        //                " (Time spent: " + (new Date - start) + "ms)";
    }
    
    // check for onsort
    if (typeof tableNode.onsort == "string")
        tableNode.onsort = new Function("", tableNode.onsort);
    if (typeof tableNode.onsort == "function")
        tableNode.onsort();
}


function CaseInsensitiveString(s) {
    return String(s).toUpperCase();
}

function parseDate(s) {
    return Date.parse(s.replace(/\-/g, '/'));
}

/* alternative to number function
 * This one is slower but can handle non numerical characters in
 * the string allow strings like the follow (as well as a lot more)
 * to be used:
 *    "1,000,000"
 *    "1 000 000"
 *    "100cm"
 */

function toNumber(s) {
    return Number(s.replace(/[^0-9\.]/g, ""));
}
/*** Asc  ****/
function compareByColumnAsc(nCol, bDescending, sType) {
    var c = nCol;
    var d = bDescending;
    
    var fTypeCast = String;
    
    if (sType == "Number")
        fTypeCast = Number;
    else if (sType == "Date")
        fTypeCast = parseDate;
    else if (sType == "CaseInsensitiveString")
        fTypeCast = CaseInsensitiveString;

    return function (n1, n2) {
        if (fTypeCast(getInnerText(n1.cells[c])) < fTypeCast(getInnerText(n2.cells[c])))
            return -1;
        if (fTypeCast(getInnerText(n1.cells[c])) > fTypeCast(getInnerText(n2.cells[c])))
            return +1;
        return 0;
    };
}
/*Des*/
function compareByColumnDes(nCol, bDescending, sType) {
    var c = nCol;
    var d = bDescending;
    
    var fTypeCast = String;
    
    if (sType == "Number")
        fTypeCast = Number;
    else if (sType == "Date")
        fTypeCast = parseDate;
    else if (sType == "CaseInsensitiveString")
        fTypeCast = CaseInsensitiveString;

    return function (n1, n2) {
        if (fTypeCast(getInnerText(n1.cells[c])) < fTypeCast(getInnerText(n2.cells[c])))
            return 1;
        if (fTypeCast(getInnerText(n1.cells[c])) > fTypeCast(getInnerText(n2.cells[c])))
            return -1;
        return 0;
    };
}


function sortColumnWithHold(e) {
    // find table element
    var el = ie5 ? e.srcElement : e.target;
    var table = getParent(el, "TABLE");
    
    // backup old cursor and onclick
    var oldCursor = table.style.cursor;
    var oldClick = table.onclick;
    
    // change cursor and onclick    
    table.style.cursor = "wait";
    table.onclick = null;
    
    // the event object is destroyed after this thread but we only need
    // the srcElement and/or the target
    var fakeEvent = {srcElement : e.srcElement, target : e.target};
    
    // call sortColumn in a new thread to allow the ui thread to be updated
    // with the cursor/onclick
    window.setTimeout(function () {
        sortColumnAsc(fakeEvent);
        sortColumnDes(fakeEvent);
        // once done resore cursor and onclick
        table.style.cursor = oldCursor;
        table.onclick = oldClick;
    }, 100);
}

function sortColumnAsc(e,sTableId) {
    var tmp = e.target ? e.target : e.srcElement;
    var tHeadParent = getParent(tmp, "THEAD");
    var el = getParent(tmp, "TD");

    if (tHeadParent == null)
        return;
        
    if (el != null) {
        var p = el.parentNode;
        var i;

        // typecast to Boolean
        el._descending = !Boolean(el._descending);

        if (tHeadParent.arrow != null) {
            if (tHeadParent.arrow.parentNode != el) {
                tHeadParent.arrow.parentNode._descending = null;    //reset sort order        
            }
            tHeadParent.arrow.parentNode.removeChild(tHeadParent.arrow);
        }
            

        // get the index of the td
        var cells = p.cells;
        var l = cells.length;
        for (i = 0; i < l; i++) {
            if (cells[i] == el) break;
        }

        //var table = getParent(el, "TABLE");
        var table = document.getElementById(sTableId);
        // can't fail
        
        sortTableAsc(table,i,el._descending, el.getAttribute("type"));
        
        alternate(table);
    }
}

function sortColumnDes(e,sTableId,stype) {
    var tmp = e.target ? e.target : e.srcElement;
    var tHeadParent = getParent(tmp, "THEAD");
    var el = getParent(tmp, "TD");

    if (tHeadParent == null)
        return;
        
    if (el != null) {
        var p = el.parentNode;
        var i;

        // typecast to Boolean
        el._descending = !Boolean(el._descending);

        if (tHeadParent.arrow != null) {
            if (tHeadParent.arrow.parentNode != el) {
                tHeadParent.arrow.parentNode._descending = null;    //reset sort order        
            }
            tHeadParent.arrow.parentNode.removeChild(tHeadParent.arrow);
        }
    

        // get the index of the td
        var cells = p.cells;
        var l = cells.length;
        for (i = 0; i < l; i++) {
            if (cells[i] == el) break;
        }
        
        var table = document.getElementById(sTableId);
        //var table = getParent(el, "TABLE");
        // can't fail
        if(stype==null)
        	stype=el.getAttribute("type")
        sortTableDes(table,i,el._descending,stype);
        
        alternate(table);
        
    }
}
function sortColumnByNumberAsc(number,sTableId,stype) {
    
    
    var table = document.getElementById(sTableId);

    sortTableAsc(table,number,true,stype);
    
    alternate(table);
    
}


function getInnerText(el) {
    if (ie5) 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 += getInnerText(cs[i]);
                break;
            case 3:    //TEXT_NODE
                str += cs[i].nodeValue;
                break;
        }
        
    }
    
    return str;
}

function 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 getParent(el.parentNode, pTagName);
}

function alternate(table) {
	// Take object table and get all it's tbodies.
	var tableBodies = table.getElementsByTagName("tbody");
	// Loop through these tbodies
	for (var i = 0; i < tableBodies.length; i++) {
		// Take the tbody, and get all it's rows
		var tableRows = tableBodies[i].getElementsByTagName("tr");
		// Loop through these rows
		// Start at 1 because we want to leave the heading row untouched
		for (var j = 0; j < tableRows.length; j++) {
			//alert(tableRows.length);
			// Check if j is even, and apply classes for both possible results
			if ( (j % 2) == 0  ) {
				if ( !(tableRows[j].className.indexOf('roweven') == -1) ) {
					tableRows[j].className = tableRows[j].className.replace('roweven', 'rowodd');
				} else {
					if ( tableRows[j].className.indexOf('rowodd') == -1 ) {
						tableRows[j].className += " rowodd";
					}
				}
			} else {
				if ( !(tableRows[j].className.indexOf('rowodd') == -1) ) {
					tableRows[j].className = tableRows[j].className.replace('rowodd', 'roweven');
				} else {
					if ( tableRows[j].className.indexOf('roweven') == -1 ) {
						tableRows[j].className += " roweven";
					}
				}
			} 
		}
	}
}
//-->