//sorts table alphabetically; if primaryCol sort indecisive, uses secondaryCol
//assumes first row of table contains column headings
//build an array of arrays
function sortByArea(myTable, primaryCol, secondaryCol) { //table id, column number (first=0), second column number
	
	//copy the table into a 2-dimensional array (myArray); myArray excludes td and tr tags
	var myTable = document.getElementById(myTable);
	var myRows = myTable.getElementsByTagName("tr"); //an array of rows in the table
	var myArray=[];
	for (var rowIndex=1; rowIndex<myRows.length ; rowIndex++) { //starts at second row
		var facultyRow=[];
		var myCells = myRows[rowIndex].getElementsByTagName("td"); //an array of cells in the row
		for(var cellIndex = 0; cellIndex < myCells.length; cellIndex++) {
			facultyRow.push(myCells[cellIndex].innerHTML);
		}
		myArray.push(facultyRow);
	}
	
	//sort the copy of the table
	myArray.sort(function(a, b) {
		a_cellcontents = a[primaryCol];
		b_cellcontents = b[primaryCol];
		pattern = /<.+?>/;  //strip anchor tags, if any; takes 2 passes; first pass for front tag, second for closing
		for (var i=0;i<2;i++) {
			a_cellcontents = a_cellcontents.replace(pattern, "");
			b_cellcontents = b_cellcontents.replace(pattern, "");
		}
		if(a_cellcontents < b_cellcontents) return -1;
		else if (a_cellcontents == b_cellcontents) { //sort on first column
			a_cellcontents = a[secondaryCol];
			b_cellcontents = b[secondaryCol];
			for (var i=0;i<2;i++) {
				a_cellcontents = a_cellcontents.replace(pattern, "");
				b_cellcontents = b_cellcontents.replace(pattern, "");
			}
			if(a_cellcontents < b_cellcontents) return -1;
			else if (a_cellcontents == b_cellcontents) return 0;
			else return 1;
		}		
		else return 1;
	});
	
	//copy myArray data back into the table
	for (var rowIndex=1; rowIndex<myRows.length ; rowIndex++) { //myTable contains one row for headers
		var myCells = myRows[rowIndex].getElementsByTagName("td");
		for(var cellIndex = 0; cellIndex < myCells.length; cellIndex++) {
			myCells[cellIndex].innerHTML=myArray[rowIndex-1][cellIndex]; //myArray starts at row 0
		}
	}
}

