/**
 * @name	/javascript/correct_agent.js
 */
// The Purpose of this file is to try and eliminate (or at least reduce to a minimal level)
// the so called "Pot Noodle" bookins where the SEO system fails to idenify the refer(r)er 
// via php, and assigns a WEB1 agent (or other default agent code, depending on site) while
// hxtrack retrieves a refer(r)er via javascript.
//
// In order to fix this, this Javascript will look for a referer if none has been found in
// SEO and correct the agent codes in cookies and hidden fields in the forms on the page if 
// one is found and it is deemed to be a search engine.
//
// Started 13/Nov/2007 TMW.
// Ollie 9/6/08 - commented out a bunch of alerts
// Paul 3/2/10 - commented out a bunch of comments ready for {previewable}

function do_the_thang () {
	var referrer;
	if (referrer = get_referrer()) {
		if (is_search_engine (referrer)) {
			update_forms (searchAgentCode);
			update_cookies (searchAgentCode);
		}
	}
}

function get_referrer () {
	if (document.referrer) return document.referrer;
	if (!window.opener) return null;
	if (!window.opener.location) return null;
	return window.opener.location.href;
}

function update_forms (newAgentCode) {
	var thisForm;
	var thisField;
//	alert ('Looking for stuff there are ' + document.forms.length + ' forms.');
	for (var i = 0 ; i < document.forms.length; i++) {
		thisForm = document.forms[i];
//		alert ('Found a form, its action is:' + thisForm.action);
		for (var j = 0 ; j < thisForm.elements.length ; j++) {
			thisField = thisForm.elements[j];
//			alert ('Found a field, its name is' + thisField.name);
			if (thisField.name == 'agent') {
//				alert ('Found a form with an agent field. Its value is: ' + thisForm.agent.value);
				if (thisForm.agent.value == defaultAgentCode) {
//					alert ('Updated field.');
					thisForm.agent.value = newAgentCode;
				}
			} 
		}
	}
}

function update_cookies (newAgentCode) {
	document.cookie = 'agent=' + newAgentCode + ';path=/';
} 

function is_search_engine (url) {
	if (url.indexOf ('google') != -1) 
		return true;
	if (url.indexOf ('yahoo') != -1)
		return true;
	if (url.indexOf ('tobestool.net') != -1)
		return true;
	return false;
}

