// JavaScript Document
//V3.01.A - http://www.openjs.com/scripts/jx/
jx = {
	//Create a xmlHttpRequest object - this is the constructor. 
	getHTTPObject : function() {
		var http = false;
		//Use IE's ActiveX items to load the file.
		if(typeof ActiveXObject != 'undefined') {
			try {http = new ActiveXObject("Msxml2.XMLHTTP");}
			catch (e) {
				try {http = new ActiveXObject("Microsoft.XMLHTTP");}
				catch (E) {http = false;}
			}
		//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
		} else if (window.XMLHttpRequest) {
			try {http = new XMLHttpRequest();}
			catch (e) {http = false;}
		}
		return http;
	},
	// This function is called from the user's script. 
	//Arguments - 
	//	url	- The url of the serverside script that is to be called. Append all the arguments to 
	//			this url - eg. 'get_data.php?id=5&car=benz'
	//	callback - Function that must be called once the data is ready.
	//	format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
	//			the string will be 'eval'ed before returning it. Default:'text'
	load : function (url, params, callback, format, elementId) {
		var http = this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
		if(!http || !url) return;
		if (http.overrideMimeType) http.overrideMimeType('text/xml');

		if(!format) var format = "text";//Default return type is 'text'
		format = format.toLowerCase();
		
		//Kill the Cache problem in IE.
		var now = "uid=" + new Date().getTime();
		url += (url.indexOf("?")+1) ? "&" : "?";
		url += now;

		http.open("POST", url, true);

		//Send the proper header information along with the request
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");

		http.onreadystatechange = function () {//Call a function when the state changes.
			if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
				if(http.status == 200) {
					var result = "";
					if(http.responseText) result = http.responseText;
					
					//If the return is in JSON format, eval the result before returning it.
					if(format.charAt(0) == "j") {
						//\n's in JSON string, when evaluated will create errors in IE
						result = result.replace(/[\n\r]/g,"");
						result = eval('('+result+')'); 
					}
	
					//Give the data to the callback function.
					if(callback) callback(result, elementId);
				} else { //An error occured
					if(error) error(http.status);
				}
			}
		}
		http.send(params);
	},
	init : function() {return this.getHTTPObject();}
}

function checkFields(actionUrl) {
	var error = false;
	if (document.getElementById('url').value == '') {
		error = true;
		setError('url', 'Please enter the url');
	}
	if (
		(document.getElementById('searchKeywords1').value == '') && 
		(document.getElementById('searchKeywords2').value == '') && 
		(document.getElementById('searchKeywords3').value == '') && 
		(document.getElementById('searchKeywords4').value == '') && 
		(document.getElementById('searchKeywords5').value == '')
		)
	{
		error = true;
		setError('searchKeywords1', 'Please enter a search phrase or keyword');
	}
	
	if (error === false) {
		document.getElementById('url').disabled = true;
		document.getElementById('checkRankingsButton').disabled = true;
		var n = 1;
		var m = 5;
		for (n = 1; n <= m; n++) {
			setProcessing('searchKeywords' + n, actionUrl)
		}
	}
	return false;
}

function setError(id, errorText) {
	if (!document.getElementById(id+'Error')) {
		var newDiv = document.createElement('div');
		newDiv.setAttribute('class', 'grcfError');
		newDiv.setAttribute('id', id+'Error');
		newDiv.innerHTML = errorText;
		document.getElementById(id+'Label').appendChild(newDiv); 
	}
}

function clearErrorField(element) {
	var id = element.id;
	if (document.getElementById(id + 'Error')) document.getElementById(id + 'Label').removeChild(document.getElementById(id + 'Error'));
}

function setProcessing(id, actionUrl) {
	if (document.getElementById(id).value != '') {
		document.getElementById(id).style.display = 'none';
		if (!document.getElementById(id+'Processing')) {
			var newDiv = document.createElement('div');
			newDiv.setAttribute('class', 'grcfProcessing');
			newDiv.setAttribute('id', id+'Processing');
			newDiv.innerHTML = 'Please wait, checking \'' + document.getElementById(id).value + '\'';
			document.getElementById(id+'Label').appendChild(newDiv); 
			var params = 'ajax_request=true&url='+document.getElementById('url').value+'&keyword='+document.getElementById(id).value + '&id=' + id;
			jx.load(actionUrl, params, manageGoogleResults, 'text', id);
		}
	} else {
		document.getElementById(id).disabled = true;
	}
}

function manageGoogleResults(result, id) {
	if (!document.getElementById(id+'Result')) {
		if (document.getElementById(id + 'Processing')) document.getElementById(id + 'Label').removeChild(document.getElementById(id + 'Processing'));
		var newDiv = document.createElement('div');
		newDiv.setAttribute('class', 'grcfResult');
		newDiv.setAttribute('id', id+'Result');
		newDiv.innerHTML = result;
		document.getElementById(id+'Label').appendChild(newDiv);
		document.getElementById('grcfContactFields').style.display = 'block';
	}
}

function grcf_checkFields() {
	var success = true;
	if (document.getElementById('contactName').value == '') {
		success = false;
		setError('contactName', 'Please enter your name');
	}
	
	if ((document.getElementById('contactEmail').value == '') && (document.getElementById('contactPhone').value == '')) {
		success = false;
		setError('contactEmail', 'Please enter your email address or phone number');
	} else if (document.getElementById('contactEmail').value != '') {
		var contactEmail = document.getElementById('contactEmail').value
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if (!contactEmail.match(emailPattern)) {
			success = false;
			setError('contactEmail', 'The email address you have entered is invalid');
		}
	}
	if (success == true) document.getElementById('url').disabled = false;
	return success;
}
