/*
Usare i questo modo
onclick="tableSortSwitch('bTable','1','ai')"

parametri
	1:	id del tbody della tabella da sortare
	2:	numero della colonna su cui fare il sort a partire da 0
	3:	tipo di sort
			"a"		: sort alfanumerico case sensitive
			"ai"	: sort alfanumerico case insensitive
			"d"		: sort per data in formato inglese mm/dd/YYYY
			"de"	: sort per data in formato italiano dd/mm/YYYY
			"n"		: sort per campo numerico
*/


tableTagFILTER="Filter"
currentCol = 0
previousCol = -1
previousDir = 0

var cProgress = new Array("--","\\","|","/")
var nProgress = 0

function inProgress( msg ) {
	if (msg!=null) {
		window.status = msg+":"+cProgress[nProgress] ;
		nProgress = (nProgress<3) ? nProgress+1 : 0	;
	} else
		window.status = "";
}


function compareAlpha(a, b) {
	inProgress( "Sorting");
	if (a[currentCol].innerText < b[currentCol].innerText) { return -1; }
	if (a[currentCol].innerText > b[currentCol].innerText) { return 1; }
	return 0;
}

function compareAlphaIgnore(a, b) {
	inProgress( "Sorting");
	strA = a[currentCol].innerText.toLowerCase();
	strB = b[currentCol].innerText.toLowerCase();
	if (strA < strB) { return -1; }
	else {
		if (strA > strB) { return 1; }
		else { return 0; }
	}
}

function compareDate(a, b) {
	inProgress( "Sorting");
	// this one works with date formats conforming to Javascript specifications, e.g. m/d/yyyy
	datA = new Date(a[currentCol].innerText);
	datB = new Date(b[currentCol].innerText);
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}

function compareDateEuro(a, b) {
	inProgress( "Sorting");
	// this one works with european date formats, e.g. d.m.yyyy
	strA = a[currentCol].innerText.split("/");
	strB = b[currentCol].innerText.split("/")
	datA = new Date(strA[2], strA[1], strA[0]);
	datB = new Date(strB[2], strB[1], strB[0]);
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}

function compareNumeric(a, b) {
	inProgress( "Sorting");
	numA = a[currentCol].innerText
	numB = b[currentCol].innerText
	if (isNaN(numA)) { return 0;}
	else {
		if (isNaN(numB)) { return 0; }
		else { return numA - numB; }
	}
}

function reverseCombo( myCombo ) {
if (myCombo!=null) {
	var index = myCombo.length - myCombo.selectedIndex - 1;
	tmp = new Array(myCombo.length-2); 
	// copy data to tmp vector & destroy combo (-1°element)
	for (i=myCombo.length; i>1; i--) {
		tmp[i-2]=myCombo.options[i-1].text;	
		myCombo.options[i-1]=null;
		}
	tmp.reverse();
	// recreate combo from tmp vector & set selected
	for (i=0; i<tmp.length; i++) {
		myCombo.options[myCombo.length]= new Option(tmp[i],"");	
		myCombo.options[myCombo.length-1].selected = (index == i)
	}
	return true;
} else
	return false;
}

function tableSortSwitch(myTable, myCol, myType) {
d = new Date()
start = d.getSeconds()*1000+d.getMilliseconds()

// with any filter active sort works only to reverse combo
if (getFilter4Row( myTable )!="true") 
	if (reverseCombo( document.all(myTable+myCol+tableTagFILTER) ))
		return 0;
	else
		alert("Ordinamento non possibile con uno o pił filtri attivi");

if ((previousDir==1)&&(myCol==previousCol))  {
	tableSort(myTable, myCol, myType, -1)
} else {
	tableSort(myTable, myCol, myType, 1)
}

d = new Date()
end = d.getSeconds()*1000+d.getMilliseconds()
//alert( ""+end+"-"+start+"="+(end-start))
}

	
function tableSort(myTable, myCol, myType, dir) {

	// with any filter active sort is DANGEROUS, so nothig!
	if (getFilter4Row( myTable )!="true") 
		return 0;

	inProgress( "Sorting")

	// Create a two-dimensional array and fill it with the table's content
	// dir : 1 asc, -1 desc
	var mySource = document.all(myTable);
	var myRows = mySource.rows.length;
	var myCols = mySource.rows(0).cells.length;
	currentCol = myCol
	myText = new Array(myRows)
	
	if ((myCol == previousCol) && (dir == previousDir))
		return 0; //  same sort repeated on same direction: nothing do do!

	// popolate matrix myText with cells pointers
	for (i=0; i < myRows; i++) {
		myText[i] = new Array(myCols)
		for (j=0; j < myCols; j++)
			myText[i][j] = mySource.rows(i).cells(j)	
	}

	if (myCol != previousCol) {
		switch (myType) {
			case "a":
				myText.sort(compareAlpha);
				break;
			case "ai":
				myText.sort(compareAlphaIgnore);
				break;
			case "d":
				myText.sort(compareDate);
				break;
			case "de":
				myText.sort(compareDateEuro);
				break;
			case "n":
				myText.sort(compareNumeric);
				break;
			default:
				myText.sort()
		}
		
		if (dir==-1) myText.reverse(); // clicked reverse direction on new column
	
	}else 	
		if (dir!=previousDir) myText.reverse(); // clicked other direction on same column

	//replace sorted pointers in myText with related innerHtml
	for (i=0; i < myRows; i++) 
		for (j=0; j < myCols; j++) 
			myText[i][j] = myText[i][j].innerHTML

	//Re-write original tables cells with myText html
	for (i=0; i < myRows; i++)
		for (j=0; j < myCols; j++)
			mySource.rows(i).cells(j).innerHTML = myText[i][j]
	

	previousCol = myCol; // remember the current sort column for the next pass
	previousDir = dir; // remember the current sort column for the next pass
    
	inProgress(); //clear
	return 0;
}

function tableSelector(myTable, myColNum) {

	var myCombo = document.all(myTable+myColNum+tableTagFILTER);
	if (myCombo.length>0) //select filter already popolated
		return 0; // already created

	var mySource = document.all(myTable);
	var myRows = mySource.rows.length;
	var myCol = myColNum*1;

	// popolate available filter with cells innerText
	var distinct = new Array();
	for (i=0; i < myRows; i++) {
		var cellText = mySource.rows(i).cells(myCol).innerText;

		// detect if value is already loaded
		var found = false;		
		for (j=0; j<distinct.length; j++) {
			found = (cellText==distinct[j]);
			if (found) break;
		}
		if (!found)	distinct[distinct.length] = cellText;
	}
	
	// sort distinct values
	distinct.sort();
	
	//add 'none filter' as first selection
	myCombo.options[myCombo.length] = new Option("-- tutti --", "");
	
	// assign data to combo
	var maxDistinct = 0;
	for (i=0; i<distinct.length; i++) {
		if (distinct[i].length>maxDistinct) maxDistinct=distinct[i].length	
		myCombo.options[myCombo.length] = new Option(distinct[i], "");
	}
		
	// set combo width
	myCombo.style.pixelWidth = 25+maxDistinct*6;

	return 1;  //new creation
}

function tableFilterCount(myTable, target) {

	var counter = tableFilter(myTable);	
	var myRows = document.all(myTable).rows.length;
	
	var myFooter = document.all(target);
	if (counter<myRows)
		myFooter.innerText = "Filtrati "+counter+" su "+myRows+" elementi"
	else
		myFooter.innerText = myRows+" elementi"
	
	return 0;
}

function getFilter4Row( myTable ){

	var mySource = document.all(myTable);
	var myCols = mySource.rows(0).cells.length;
	var filter4row= "true"
	
	//define filter for each row
	for (j=0; j<myCols; j++) {
		
		// find defined select by id
		var myCombo = document.all(myTable+ j +tableTagFILTER); 

		// exist selector with selection ?
		if ((myCombo != null)&&(myCombo.selectedIndex>0))
			filter4row += "&&(mySource.rows(i).cells("+j+").innerText=='"+myCombo.options[myCombo.selectedIndex].text+"')";			
	}

	return filter4row;
}

function tableHideFilter( myTable, myColNum ) {

	var myCombo = document.all(myTable+myColNum+tableTagFILTER); 

	// if none filter setted, clear combo
	if ((myCombo != null)&&(myCombo.selectedIndex==0)){
		for (i=myCombo.length; i>0; i--) 
			myCombo.options[i-1]=null;	
		myCombo.style.pixelWidth = 20;
	}
	
	return 0;
}


function tableFilter( myTable ) {
	var mySource = document.all(myTable);
	var myRows = mySource.rows.length;
	var counter = 0

	var filter4row = getFilter4Row( myTable );

	// evaluate filter for each row
	for (i=0; i < myRows; i++){
		inProgress( "Filtering")
		
		var show = eval( filter4row );
		if (show) counter ++;
		mySource.rows(i).style.display = (show ? 'block' : 'none');
	}
		
	inProgress(); //clear
	
	return counter;
}

function popupRow( obj ) {
	//obj.title = obj.innerText;
}

