//global variable indicating which column the user clicked on
var selected_col;

/**
 * Is called by code inside table.js when someone clicks on a table header.
 * This sorts each column alphabetically (by using Javascript sort() fucntion)
 * using the comparator function sortCol() below.  All sorting directly modifies
 * the table with the body node id = tblbody
 * 
 * @param col the column that we want to sort on
 * @return
 */
function sortTable(col) {
	selected_col = col;

	//sort the table using the comparator function sortCol
	var tblContents_sorted = tblContents.sort(sortCol);
	
	var tbl = document.getElementById("tblbody");
	var tbl_rows = tbl.childNodes;
	
	//iterate over the sorted table contents and change the HTML DOM to
	//reflect the changes
	for (i = 0; i < tbl_rows.length; i++) {
		var row_entries = tbl_rows[i].childNodes;
		for (j = 0; j < tblContents[i].length; j++) {
			var cell_kids = row_entries[j].childNodes;
			
			//set the text, and modify the translation word verification status
			cell_kids[0].innerHTML = tblContents_sorted[i][j].word;
			if (cell_kids.length > 1) {
				setStatus(tblContents_sorted[i][j].status, row_entries[j]);
			}
		}
	}                                         
}

/**
 * Depending on the status of the word in the table, it will either set the
 * checkbox to be unverified, verified or rejected
 * status = 0 means unverified
 * status = 1 means verified
 * status = -1 means rejected
 * @param status the status of the cell, one of 0, 1 or -1
 * @param a td HTML DOM object that should contain at least two children, a 
 * span and an img object
 * @return 
 */
function setStatus(status, cell) {
	if (status == 0) {
		setUnverified(cell);
	}
	else if (status == 1) {
		setVerified(cell);
	}
	else if (status == -1) {
		setRejected(cell);
	}	
}

/**
 * Comparator function specific to this app.  Will sort the table alphabetically
 * on the "currently selected column", as determined by the variable 
 * selected_col
 * @param w1 the first object, which will be an array, or a row
 * @param w2 the second object, which will be an array, or the next row
 * @return
 */
function sortCol(w1, w2) {
	
	//grab the word in the row at selected_col
	var firstWord = w1[selected_col].word.toLowerCase();
	var secondWord = w2[selected_col].word.toLowerCase();
	
	if (firstWord < secondWord) {
		return -1;
	}
	else if (firstWord > secondWord) {
		return 1;
	}
	else {
		return 0;
	}
}