//addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;

function ts_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 += ts_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 addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  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("Handler could not be removed");
  }
} 


function clickSort(lnk, col) {
    // 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 = ts_getInnerText(span);
    var td = lnk.parentNode;
	//
    var column = col ? col : td.cellIndex;
	//alert (column+" по "+lnk.type)

    var table = getParent(td,'TABLE');
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;

	if (lastClick) {
		lastClick.innerHTML = '<img src="/images/icons/sort_down_gray.gif" border="0" width="8" height="9">';
	}

	if(lastClick == span) {
		if(reverse == false) {
	        ARROW = '<img src="/images/icons/sort_down.gif" border="0" width="8" height="9">';
		     reverse = true;
		}
		else {
			 ARROW = '<img src="/images/icons/sort_up.gif" border="0" width="8" height="9">';
			reverse = false;
		}
	}
	else {
	    ARROW = '<img src="/images/icons/sort_down.gif" border="0" width="8" height="9">';
		reverse = true;
		lastClick = span;
	}
	span.innerHTML = ARROW;
	insertionSort (table.tBodies[0], table.tBodies[0].rows.length-1, reverse, column, lnk.type)

	if (!table.getAttribute("sort_noindex")) {
		for(i=0;i<table.tBodies[0].rows.length;i++) {
			table.tBodies[0].rows[i].cells[0].innerHTML = i+1;
		}
	}


}

// t - tbody
// iRowEnd - последняя строка 
// reverse - порядок сортировки
// iColumn - колонка, по которой сортируем
// iSortType - тип данных

//insertionSort(tbody[i], tbody[i].rows.length-1,  reverse, clickObject.selectIndex, clickObject.type);

function insertionSort(t, iRowEnd, fReverse, iColumn, iSortType)
{
	// выходим, если сортирока по столбцу не нужна
	//if (iSortType==0) return;

    var iRowInsertRow, iRowWalkRow, current, insert;

    for ( iRowInsert = 0 + 1 ; iRowInsert <= iRowEnd ; iRowInsert++ )
    {
        if (!isNaN(iColumn)) {	
			//alert (typeof(t.childNodes[iRowInsert].childNodes[iColumn]));
			if( typeof(t.childNodes[iRowInsert].childNodes[iColumn]) != "undefined")
	     		      textRowInsert = ts_getInnerText(t.childNodes[iRowInsert].childNodes[iColumn]);

			else
				textRowInsert = "";

	    } else {
	           textRowInsert = ts_getInnerText(t.childNodes[iRowInsert]);
    	}

    	for ( iRowWalk = 0; iRowWalk <= iRowInsert ; iRowWalk++ )
	    {
           if (!isNaN(iColumn)) {
				if(typeof(t.childNodes[iRowWalk].childNodes[iColumn]) != "undefined")
					textRowCurrent = ts_getInnerText(t.childNodes[iRowWalk].childNodes[iColumn]);
				else
					textRowCurrent = "";
	       } else {
				textRowCurrent = ts_getInnerText(t.childNodes[iRowWalk]);
     		}
			//
			// We save our values so we can manipulate the numbers for
			// comparison
			//
			current = textRowCurrent;
			insert  = textRowInsert;


			//  If the value is not a number, we sort normally, else we evaluate	
			//  the value to get a numeric representation
			//

			if (iSortType == "date") {
				// сортируем даты
			    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
			    aa =  current;
			    bb =  insert;
			    if (aa.length == 10) {
			        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
			    } else {
			        yr = aa.substr(6,2);
			        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
			        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
			    }
			    if (bb.length == 10) {
			        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
			    } else {
			        yr = bb.substr(6,2);
			        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
			        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
			    }
				current = dt1;
				insert = dt2;
			}
			else if ( iSortType == "number" ) {
				current = current.replace(/\,/g, ".");
				current = parseFloat(current.replace(/\s/g, ""));
				if (isNaN(current) && fReverse) {current = -2147483648; }
				if (isNaN(current) && !fReverse) {current = 2147483647; }
				insert = insert.replace(/\,/g, ".");
				insert = parseFloat(insert.replace(/\s/g, ""));
				if (isNaN(insert) && fReverse) {insert = -2147483648; }
				if (isNaN(insert) && !fReverse) {insert = 2147483647; }
			}
			else {	
				current	= current.toLowerCase();
				insert	= insert.toLowerCase();
			}

			//alert (fReverse+"\n"+insert+"\n"+current)

            if ( (   (!fReverse && insert < current)
                 || ( fReverse && insert > current) )
                 && (iRowInsert != iRowWalk) ) 			{
			    eRowInsert = t.childNodes[iRowInsert];
	            eRowWalk = t.childNodes[iRowWalk];
	            t.insertBefore(eRowInsert, eRowWalk);
	            iRowWalk = iRowInsert; // done
            }


        }
    }
}

var reverse;
var activeCol;
var lastClick;
