var statusIndex;

/*
	Effectively a constructor - runs the instant the .js file is loaded by the browser.
*/
init();

/*
	init() - Is run as the .js file loads in the browser.
	at this point, the full HTML document has not yet loaded therefore
	the DOM Tree is not fully built.
	
	This function attaches the 'initialise' function to the window onload event
	when the HTML document is loaded, initialise() is called.
*/
function init()
{
	
	if (window.addEventListener) 
	{
       	window.addEventListener('load', initialise, false);
       	return true;
   	}
	else if (window.attachEvent)
	{
       	var r = window.attachEvent('onload', initialise);
      	return r;
   	}
	else
	{
       	return false;
   	}
}

/*
	initialise() Called when the HTML document has completed loading -> DOM Tree is complete.
	
	//TODO will do more	
	Attaches an onchange event to all of the select elements.
	When a user changes a grade in the system, saveData() is called
	to save the change to the database.
*/
function initialise()
{
	/* If the loginForm is present, give it focus */
	var loginForm;
	if (loginForm = document.getElementById('loginForm'))
	{
		document.getElementById('loginForm_username').focus();
	}
	
	var dropdowns = document.getElementsByTagName('select');
	for(i in dropdowns)
	{
		dropdowns[i].onchange = saveData;
	}
	
	/*Determine the status column*/
	var rows = document.getElementsByTagName('tr');
	if (rows.length>0){statusIndex = rows[0].getElementsByTagName('th').length-1;}
	else {statusIndex = -1;}
	//statusIndex = document.getElementsByTagName('tr')[0].getElementsByTagName('th');
}

/*
	saveData() Called when onchange event is fired from a 'select' element
	This is where the magic happens.
	
	updates the interface to show that something is happening in the background
	fires an AJAX call and saves the change to the database.
	
	If the call is successful, the interface is updated to reflect success.
	If the call fails, the interface is updated to reflect failure.
*/
function saveData()
{
	/*if (document.getElementById('EOYreportTable'))
	{
		var s = this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('td')[8];
		if (s.className == 'status')
		{
			var statusCell = s;
		}
		else {var statusCell = this.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('td')[8];}
	}
	else
	{
		var statusCell = this.parentNode.parentNode.getElementsByTagName('td')[statusIndex];
	}*/
	var statusCell = determineStatusCell(this, false);
	var img = document.createElement('img');
	img.src='style/indicator16.gif';
	
	statusCell = clearAllContent(statusCell);
	statusCell.appendChild(img);
	
	this.style.backgroundColor='rgb(255,223,0)';
	/* Use name attribute to save saving status to enable twirller to be replaced */
	this.name='saving';
	
	if (window.XMLHttpRequest)
	{ /* moz + IE 7 */
		var xml = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{ /* < IE 7 */
		var xml = new ActiveXObject('Microsoft.XMLHTTP');
	}
	xml.onreadystatechange = function()
	{
		
		if (xml.readyState == 4)
		{
			if (xml.status != 200)
			{
				//TODO
				//Needs better error handling.
				//dropdown.style.backgroundColor='rgb(255,0,0)';
				alert('There was a problem contacting the server'+"\n"+'Please check your internet connection and try again.');
				/*Release resources */
				delete xml;
			}
			else
			{
				var response = xml.responseXML;
				var status = response.getElementsByTagName('status')[0];
				var row = status.getAttribute('row');
				var criteria = status.getAttribute('criteria');
				
				/*var cells = document.getElementById('s'+row).getElementsByTagName('td');
				var i = 0;
				while(cells[i].className != criteria) {i++;}
				var dropdown = cells[i].firstChild;
				var statusCell = cells[statusIndex];*/
				
				var dropdowns = document.getElementById('s'+row).getElementsByTagName('select');
				//var i = 0;
				var dropdown;
				for(var i=0; i<dropdowns.length; i++)
				{
					if (dropdowns[i].className == criteria || dropdowns[i].parentNode.className == criteria)
					{
						dropdown = dropdowns[i];
					}						
				}
				//while(cells[i].className != criteria) {i++;}
				//var 
				var statusCell = determineStatusCell(dropdown, false);
				

				dropdown.style.backgroundColor='rgb(255,255,255)';
				dropdown.name = '';
				statusCell = clearAllContent(statusCell);
				statusCell.appendChild(document.createTextNode('Saved'));
				statusCell.style.color = 'rgb(0,0,0)';
				
				window.clearInterval(statusCell.id.substring(1, statusCell.id.length));
				
				//statusCell.id = 'i'+window.setInterval('fadeText("'+dropdown.parentNode.parentNode.id+'")', 80);
				statusCell.id = 'i'+window.setInterval('fadeText("s'+row+'")', 80);
			}
		}
	}
	
	var classId = document.getElementById('classId').firstChild.nodeValue;
	if (document.getElementById('EOYreportTable'))
	{
		var n = this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id
		if(n == 'EOYreportTable')
		{
			n = this.parentNode.parentNode.parentNode.parentNode.parentNode.id
		}
		var adminNo = n.substring(1,n.length);
	}
	else {var adminNo = this.parentNode.parentNode.id.substring(1, this.parentNode.parentNode.id.length);}
	var criteria = this.parentNode.className;
	var value = this.value;
	
	xml.open('POST', 'ajax/saveData_xml.php', true);
	xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	var postVars = 'classId='+classId+'&adminNo='+adminNo+'&criteria='+criteria+'&value='+value;
	xml.send(postVars);
	
	//console.log(postVars);
}

function determineStatusCell(node, fromRow)
{
	
	
	if (document.getElementById('EOYreportTable'))
	{
		if (fromRow)
		{
			return node.getElementsByTagName('td')[8];
		}
		else
		{
			var s = node.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('td')[8];
			if (s.className == 'status')
			{
				return s;
			}
			else {return node.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('td')[8];}
		}
	}
	else
	{
		if(fromRow)
		{
			return node.getElementsByTagName('td')[statusIndex];
		}
		else
		{
			return node.parentNode.parentNode.getElementsByTagName('td')[statusIndex];
		}
	}
}

/*
	fadeText(stausRow) - Fades the text in the 7th column of the supplied row in the reports table.
	replaces the twirller if there are still values waiting to save.
*/
function fadeText(statusRow)
{
	//var cells = document.getElementById(statusRow).getElementsByTagName('td');
	var row = document.getElementById(statusRow);
	//var statusCell = cells[statusIndex];
	var statusCell = determineStatusCell(row, true);
	var col = statusCell.style.color.substring(4, statusCell.style.color.indexOf(','));
	col = parseInt(col);
	col=col+25;
	statusCell.style.color = "rgb("+col+","+col+","+col+")";
	if (col > 238)
	{
		window.clearInterval(statusCell.id.substring(1, statusCell.id.length));
		statusCell = clearAllContent(statusCell);

		var i = 1; var found = false;
		var dropdowns = row.getElementsByTagName('select');
		while (!found && i<statusIndex)
		{
			//if(cells[i].firstChild.name != '') 
			if(dropdowns[i].name != '')
			{
				found = true;
				var img = document.createElement('img');
				img.src='style/indicator16.gif';
				statusCell.appendChild(img);
			}
			i++;
		}
	}
}

/*
	clearAllContent(obj) - clears the supplied object of all children.
*/
function clearAllContent(obj)
{
	var nObj = obj.cloneNode(false);
	obj.parentNode.insertBefore(nObj,obj);
	obj.parentNode.removeChild(obj);
	return nObj;
}
