var display_ajaxProcessing = '<div align="center"><img src="images/icons/loading_big.gif" /></div><div align="center" class="gensmall">Processing request...</div>'
var display_ajaxProcessingL = '<div align="center"><img src="images/icons/loading_large.gif" /></div><div align="center" class="genmed">Processing request...</div>'
var checkors = ["validate_reg-mIcI5a.php","validate_log-mIcI5a.php","validate_cre-mIcI5a.php","validate_cap-mIcI5a.php","delete_logs.php"];
// Timer variable
var t;
//Create a boolean variable to check for a valid Internet Explorer instance.
var xmlhttp = false;
//Check if we are using IE.
try {
	//If the Javascript version is greater than 5.
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	//If not, then use the older active x object.
	try {
		//If we are using Internet Explorer.
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
		//Else we must be using a non-IE browser.
		xmlhttp = false;
	}
}
//If we are using a non-IE browser, create a javascript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	xmlhttp = new XMLHttpRequest();
}
// Function to checkInput sometime in future
// TODO: How to pass object HTMLInput (input) through setTimeout func. Does not get passed properly to checkInput()!
function delayed_checkInput(formName, input, checkor, delay) {
	delay = (delay <= 0) ? 500: delay;
	clearTimeout(t);
	t = setTimeout('checkInput(\'' + formName + '\', \'' + input.name + '\', \'' + input.value + '\', \'' + checkor + '\')', delay);
}
// Function to check input
function checkInput(formName, name, value, checkor) {
	// Step 1: Make URL & id of div and span elements from input id
	checkor = inc_alias + checkors[checkor];
	var nameLength = name.length;
	var div_id = "div_" + name;
	var span_id = "span_" + name;
	var url = "ci=1&" + name + "=" + value;
	// Are we sending a variable which needs to be confirmed against another input?
	if (name.charAt(nameLength-1) == "C") {
		var original = name.slice(0,-1);
		var toConfirmAgainst = document.forms[formName].elements[original];
		url += "&" + original + "=" + toConfirmAgainst.value;
		//alert("Original: " + original + ", toConfirmAgainst: " + toConfirmAgainst.value);
	}
	//alert("Name:" + name + ", Value:" + value + ", URL:" + checkor + url);
	// Display loading icon
	document.getElementById(span_id).innerHTML = '<img src="images/icons/loading_squares.gif" />';
	// Step 2: Submit request
	xmlhttp.open("POST", checkor);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			// Catch response
			xmlDoc = xmlhttp.responseXML;
			// Process XML data
			//document.getElementById("div_errors").innerHTML = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
			if (parseInt(xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue) == 0) {
				// Failure - Display cross & errors
				document.getElementById(div_id).innerHTML = xmlDoc.getElementsByTagName("errors")[0].childNodes[0].nodeValue;
				document.getElementById(span_id).innerHTML = '<img src="images/icons/cross.png" />';
			} else {
				// Positive - Display tick
				document.getElementById(span_id).innerHTML = '<img src="images/icons/tick.png" />';
				document.getElementById(div_id).innerHTML = '';
			}
		}
	}
	xmlhttp.send(url);
	return false;
	// Step 3: Display tick/cross & extra message (if any)
	
}
// Function to validate form input
function validateForm(formName, submitButton, validator, clearInputs) {
	var proceed = true;
	validator = inc_alias + checkors[validator];
	// Step 1: Replace Submit button with please wait message
	document.getElementById("div_submit").innerHTML = display_ajaxProcessing;
	// Step 1.5: Before any processing, if we require captcha verification, do that first
	if (isPresent(document.forms[formName].doCaptcha)) {
		proceed = validateCaptcha(formName,false);
	}
	//alert("Proceed: " + proceed);
	// Can we proceed?
	if (proceed == false) {
		/*time = new Date();
		time = time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()+':'+time.getMilliseconds();
		alert("Cannot proceed ("+ time +")");*/
		// Cannot proceed, restorer submit button
		/*var onclick = new String(submitButton.onclick);
		//alert("Original: " + onclick);
		//document.getElementById("test").innerHTML = escape(onclick);
		onclick = onclick.replace("function onclick(event) {","");
		// Begin: IE
		onclick = onclick.replace("function onclick()","");
		onclick = onclick.replace("{","");
		onclick = onclick.replace("\n","");
		// End: IE
		onclick = onclick.replace("\t","");
		onclick = onclick.replace("\n","");
		onclick = onclick.replace(/\u0020/g,"");
		onclick = onclick.replace("}","");
		onclick = onclick.replace(/\"/g,"'");*/
		//document.getElementById("div_submit").innerHTML = "<input id=\"" + submitButton.id + "\" name=\"" + submitButton.name + "\" type=\"submit\" value=\"" + submitButton.value + "\" class=\"" + submitButton.className + "\" onClick=\"" + onclick + "\" />";
		document.getElementById("div_submit").innerHTML = "<input id=\"" + submitButton.id + "\" name=\"" + submitButton.name + "\" type=\"submit\" value=\"" + submitButton.value + "\" class=\"" + submitButton.className + "\" />";
		return false;
	}
	/*time = new Date();
	time = time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()+':'+time.getMilliseconds();
	alert("Can Proceed ("+ time +")");*/
	// Step 2: Go through all form elements and append values to url
	var element;
	var restoreSubmit = true;
	var url = new String();
	for (i = 0; i < document.forms[formName].elements.length; i++) {
		element = document.forms[formName].elements[i];
		url += (!url.length) ? element.name + '=' + escape(element.value): '&' + element.name + '=' + escape(element.value);
	}
	//alert(url);
	xmlhttp.open("POST", validator);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			//document.getElementById("div_errors").innerHTML = xmlhttp.responseText;
			xmlDoc = xmlhttp.responseXML;
			/*x = xmlDoc.childNodes;
			for (i=0;i<x.length;i++) {
				alert('nodeName: ' + x[i].nodeName + ', nodeType: ' + x[i].nodeType + ', nodeValue: ' + x[i].nodeValue);	
			}*/
			//alert("Error code: " + xmlDoc.parseError.errorCode + "<br />Error reason: " + xmlDoc.parseError.reason + "<br />Error line: " + xmlDoc.parseError.line);
			/* NOTE: The following are both correct, however only (2) works in FIREFOX
				(1) xmlDoc.getElementsByTagName("result")[0].text;
				(2) xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue
			*/
			//alert('Result: ' + xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue);
			//alert('Errors: ' + xmlDoc.getElementsByTagName("errors")[0].childNodes[0].nodeValue);
			//alert('Message: ' + xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue);
			if (parseInt(xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue) == 0) {
				// Clear any messages
				document.getElementById("div_message").innerHTML = "";
				// Errors - Display errors
				document.getElementById("div_errors").innerHTML = xmlDoc.getElementsByTagName("errors")[0].childNodes[0].nodeValue;	
				// If Captcha verification is required, refresh captcha image
				if (isPresent(document.forms[formName].doCaptcha))
					document.getElementById('siimage').src = inc_alias + 'sic201/securimage_show.php?sid=' + Math.random();
			} else {
				// Clear any error output
				document.getElementById("div_errors").innerHTML = "";
				//alert('Message: ' + xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue);
				document.getElementById("div_message").innerHTML = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
				// Need to update fields?
				var updates = xmlDoc.getElementsByTagName("updates")[0].childNodes[0].nodeValue;
				if (updates != "none") {
					//alert('Updates: ' + xmlDoc.getElementsByTagName("updates")[0].childNodes[0].nodeValue);
					// Format - field_name:updated_value
					var updatesArr = updates.split(":");
					document.getElementById(updatesArr[0]).innerHTML = updatesArr[1];
				}
				// Need to redirect
				var redirectUrl = xmlDoc.getElementsByTagName("redirect")[0].childNodes[0].nodeValue;
				if (redirectUrl != "none") {
					restoreSubmit = false;
					redirectUrl = redirectUrl.split(":");
					//alert("Redirect[0]: " + redirect[0] + ", 1: " + redirect[1]);
					if (redirectUrl[1] == "alert") {
						alert(xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue);
						redirect(redirectUrl[0]);
					} else {
						//alert('Redirect: ' + xmlDoc.getElementsByTagName("redirect")[0].childNodes[0].nodeValue);
						setTimeout('redirect(\'' + redirectUrl[0] + '\')', 2000);
					}
				}
				// Ordered to clear all inputs?
				if (clearInputs == true) {
					for (i = 0; i < document.forms[formName].elements.length; i++) {
						element = document.forms[formName].elements[i];
						element.value = "";
					}
				}
			}
			// Scroll to message placeholder (remove multiple # tags)
			var temp_url = window.location.href.split("#");
			window.location.href = temp_url[0] + "#td_msg";
			if (restoreSubmit == true) {
				// Final Step: Create onclick string & restore submit button
				/*var onclick = new String(submitButton.onclick);
				onclick = onclick.replace("function onclick(event) {","");
				// Begin: IE
				onclick = onclick.replace("function onclick()","");
				onclick = onclick.replace("{","");
				onclick = onclick.replace("\n","");
				// End: IE
				onclick = onclick.replace("\t","");
				onclick = onclick.replace("\n","");
				onclick = onclick.replace(/\u0020/g,"");
				onclick = onclick.replace("}","");
				onclick = onclick.replace(/\"/g,"'");*/
				document.getElementById("div_submit").innerHTML = "<input id=\"" + submitButton.id + "\" name=\"" + submitButton.name + "\" type=\"submit\" value=\"" + submitButton.value + "\" class=\"" + submitButton.className + "\" />";	
			}
		}
	}
	xmlhttp.send(url);
	return false;
}

// Function to validate Captcha
function validateCaptcha(formName,submitButton) {
	//alert("FormName: " + formName + ", Action: " + document.forms[formName].action + ", SubMitButton: " + submitButton.name);
	//TODO: Figure out why sometimes declaring submitButton stops form from submitting, i.e. from project.php (new bid)
	//SOLUTION: replace onClick on submitButton with onSubmit on the form
	proceed = false;
	if (submitButton) {
		//alert("Replacing submit button");
		// This is an external request (ajax does not process rest of form). Replace Submit button with please wait message
		document.getElementById("div_submit").innerHTML = "<div align=\"left\" style=\"width:200px;\">" + display_ajaxProcessing + "</div>";
	}
	params = "code=" + document.forms[formName].code.value;
	var validator = inc_alias + checkors[3];
	xmlhttp.open("POST", validator, false);
	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	// Suppress caching
	xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
	// Says that when the server has recieved x bytes (as defined in content-length) it should CLOSE the connection. Now this is just fine if you don't want any data back from the server, but if you need to do a little processing & maybe pass back an acknowledgment then you should not add connection close to your headers,
	//xmlhttp.setRequestHeader("Content-length", params.length);
	//xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	if (xmlhttp.status == 200) {
		xmlDoc = xmlhttp.responseXML;
		time = new Date();
		time = time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()+':'+time.getMilliseconds();
		//alert('Response ('+ time +'): ' + xmlhttp.responseText);
		//alert('ResultCaptcha: ' + xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue);
		//alert('ErrorsCaptcha: ' + xmlDoc.getElementsByTagName("errors")[0].childNodes[0].nodeValue);
		if (parseInt(xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue) == 0) {
			// Produce error alert
			alert(xmlDoc.getElementsByTagName("errors")[0].childNodes[0].nodeValue);
			// Refresh the captcha image
			document.getElementById('siimage').src = inc_alias + 'sic201/securimage_show.php?sid=' + Math.random();	
			// Clear the code input field
			document.forms[formName].code.value = '';
		} else {
			// Allow to proceed
			proceed = true;
		}
	}
	// Reset the xmlhttp, event handlers might be lost
	xmlhttp.abort();
	if (submitButton && (proceed == false)) {
		// Better effect if we don't restore the button when successful
		//alert("Restoring submit button");
		// Final Step: Create onclick string & restore submit button
		/*var onclick = new String(submitButton.onclick);
		//alert("OnClick1: " + onclick);
		onclick = onclick.replace("function onclick(event) {","");
		// Begin: IE
		onclick = onclick.replace("function onclick()","");
		onclick = onclick.replace("{","");
		onclick = onclick.replace("\n","");
		// End: IE
		onclick = onclick.replace("\t","");
		onclick = onclick.replace("\n","");
		onclick = onclick.replace(/\u0020/g,"");
		onclick = onclick.replace("}","");
		onclick = onclick.replace(/\"/g,"'");
		// Extra check for seperating return|validatecaptcha
		onclick = onclick.replace("returnv","return v");*/
		//alert("OnClick2: " + onclick);
		document.getElementById("div_submit").innerHTML = "<input id=\"" + submitButton.id + "\" name=\"" + submitButton.name + "\" type=\"submit\" value=\"" + submitButton.value + "\" class=\"" + submitButton.className + "\" />";	
		//document.forms[formName].submit();
	}
	return proceed;
}

// Function to delete a row and reload updated version
function delRow(input, validator, div_content) {
	// Step 1: Show loading image in content div
	validator = inc_alias + checkors[validator];
	document.getElementById(div_content).innerHTML = display_ajaxProcessingL;
	// Extract id of row to be deleted
	id = input.id;
	url = "?id=" + id;
	// Step 3: Send request to validator
	//alert("Validator: " + validator + url);
	xmlhttp.open("GET", validator + url);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			//document.getElementById("div_errors").innerHTML = xmlhttp.responseText;
			xmlDoc = xmlhttp.responseXML;
			/*x = xmlDoc.childNodes;
			for (i=0;i<x.length;i++) {
				alert('nodeName: ' + x[i].nodeName + ', nodeType: ' + x[i].nodeType + ', nodeValue: ' + x[i].nodeValue);	
			}*/
			//alert("Error code: " + xmlDoc.parseError.errorCode + "<br />Error reason: " + xmlDoc.parseError.reason + "<br />Error line: " + xmlDoc.parseError.line);
			/* NOTE: The following are both correct, however only (2) works in FIREFOX
				(1) xmlDoc.getElementsByTagName("result")[0].text;
				(2) xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue
			*/
			//alert('Result: ' + xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue);
			//alert('Message: ' + xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue);
			//alert('Response ('+ time +'): ' + xmlhttp.responseText);
			if (parseInt(xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue) == 0) {
				// Errors - Display errors
				document.getElementById("div_errors").innerHTML = xmlDoc.getElementsByTagName("errors")[0].childNodes[0].nodeValue;	
			} else {
				// Clear any error output
				document.getElementById("div_errors").innerHTML = "";
				//alert('Message: ' + xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue);
				document.getElementById(div_content).innerHTML = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
			}
		}
	}
	xmlhttp.send(null);
	return false;
}

function makeRequest(serverPage, objID) {
	var obj = document.getElementById(objID);
	xmlhttp.open("GET", serverPage);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			obj.innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.send(null);
}

// Function to create tooltip
function showTip(e) {
	var obj = document.getElementById("tooltip");
	obj.style.visibility = "visible";
	obj.style.height = "100px";
	obj.style.width = "100px";
	obj.style.position = "absolute";
	obj.style.border = "2px double #000000";
	obj.style.color = "#CCCCCC";
	var posx = 0; var posy = 0;
	posx = (findPosX (e) + 1);
	posy = (findPosY (e) + 23);
	//posx = e.clientX + document.body.scrollLeft;
	//posy = e.clientY + document.body.scrollTop;
	obj.style.left = posx + "px";
	obj.style.top = posy + "px";
	obj.innerHTML = "Tooltip now showing..."
}
function hideTip (e){
	var obj = document.getElementById("tooltip");
	obj.style.visibility = "hidden";
	obj.style.height = "0px";
	obj.style.width = "0px";
}
function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x){
		curleft += obj.x;
	}
	return curleft;
}
function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y){
		curtop += obj.y;
	}
	return curtop;
}
function redirect(url) {
	window.location = url;
}
// Function to check if a field/variable exists
function isPresent(obj){
  return typeof(obj)!='undefined';
}