// CT_I_... is an internally defined variable
// window.CT_C_... is an internally named variable that the customer sets
// window.CT_X_... is a customer defined variable to be written as a biscuit
if (typeof(window.CT_C_Debug) == 'undefined') {
	window.CT_C_Debug = 0;
}

//- additionalParams MAY be undefined. If set it MUST be either null or an array of additional parameters to pass, encoded 
//    as "key=value". e.g. additionalParams = [ "some_param=somevalue", "some_other_param=blah" ];
//- server MAY be undefined. If set it MUST be either null or a non-empty string indicating where to send the message
//    to. e.g. server ="jdc.ct.com". do not include protocol or trailing /s.
function CT_RecordView(request, method, additionalParams, server ) {
	// set defaults
	var basicCall = 1;
	if (request == null) {
		request = document.location;
	} else {
		basicCall = 0;
	}
	additionalParams = additionalParams || []; //default
	server = server || CT_I_Path; //default
	
	if (typeof(window.CT_R_PID) != 'undefined') {
		request += (/\?/.test(request) ? '&' : '?') + 'CT_R_PID=' + encodeURIComponent(window.CT_R_PID);
	}
	var orderTotal = 0;
	if (typeof(window.CT_C_OrderTotal) != 'undefined') {
		orderTotal = window.CT_C_OrderTotal;
	}

	// handle biscuits first
	var biscuits = new Array();
	for (var i in window) {
		// if variable name starts with CT_X_ followed by something else 
		if (i.substring(0, 5) == 'CT_X_' && i.length > 5) {
			var s = encodeURIComponent(window[i] + '');
			biscuits.push(i + '=' + s);
		}
	}
	var ctxValue = biscuits.join('%26');

	// setup request fields
	var vals = additionalParams.concat(); //clone array into vals
	vals.push('i=' + CT_I_Datasets.join('&amp;i='));
	vals.push('r=' + encodeURIComponent(request));
	if (CT_I_FirstPartyJDC) {
		if (window.CT_I_FirstPartyDomain && window.CT_I_FirstPartyDomain != '')
			vals.push('fp=' + window.CT_I_FirstPartyDomain);
		else
			vals.push('fp=1');
	}
	if (CT_I_FirstPartyCookies || CT_I_FirstPartyJDC) {
		vals.push('c=' + encodeURIComponent(document.cookie));
	}
	if (method != null) {
		vals.push('s=' + method); // method
		vals.push('f=' + encodeURIComponent(document.location)); // referrer
	} else {
		vals.push('f=' + encodeURIComponent(document.referrer)); // referrer
		if (orderTotal > 0)
			vals.push('e=' + orderTotal);
	}
	if (typeof(CT_I_Subdomain) != 'undefined') {
		vals.push('d=' + encodeURIComponent(CT_I_Subdomain));
	}
	if (ctxValue != '')
		vals.push('U=' + ctxValue); // biscuits
	if (basicCall == 0)
		vals.push('g=1'); // use graphic as response
	if (typeof(CT_I_Protocol) == 'undefined') {
		window.CT_I_Protocol = window.location.protocol;
	}

	// screen dimensions
	vals.push('sd=' + window.screen.width + 'x' + window.screen.height);

	var path = CT_I_Protocol + server + vals.join('&');

	var debug = window.CT_C_Debug;
	if (debug) {
		debugMsg = 'ClickTracks JavaScript Data\n';
		if (orderTotal != 0) {
			debugMsg += 'OrderTotal = ' + orderTotal.toFixed(2) + '\n';
		}
		if (biscuits.length > 0) {
			debugMsg += 'Biscuits:\n  ' + biscuits.join('\n  ') + '\n';
		}
		if (debug > 1) {
			debugMsg += 'Request:\n  ' + path + '\n';
		}
		if (basicCall) {
			debugMsg += '(Basic call)\n';
		} else {
			debugMsg += '(Advanced call)\n';
		}
		debugMsg += '\n\nIf you set any other data, it was not set correctly.\n';
		alert(debugMsg);
	}

	if (basicCall) {
		// called to log the page being loaded, JavaScript can still be added to and executed
		document.write('<'+'script language="javascript" type="text/javascript" src="' + path + '"></'+'script>');
	} else {
		// called by exit tracking or customer activity
		var a = new Image();
		a.src = path;

		var now = new Date();
		now = now.getTime() + 1000;
		var then;
		do {
			then = new Date();
		} while (then.getTime() < now);
	}
} // CT_RecordView()

function CT_ProcClick(evt) {
	evt = (evt) ? evt : ((window.event) ? event : null);
	if (evt) {
		var e = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
		if (e) {
			while (e) {
				var link = '';
				switch(e.tagName) {
					case 'A':
					case 'AREA':
						link = e.href;
						break;
					case 'INPUT':
						if (e.form) {
							e = e.form;
							link = e.action;
							if (link == '') link = document.location.href;
						} else {
							link = '';
						}
						break;
				}
				switch(e.tagName) {
					case 'A':
					case 'AREA':
						if (link != '') {
							if (!CT_LocalLink(link))
								CT_RecordView(link, 'EXIT');
							else if (CT_TrackFileExtension(link))
								CT_RecordView(link, 'GET');
						}
						e = 0;
						break;
					default:
						e = (e.parentElement) ? e.parentElement : e.parentNode;
						break;
				}
			}
		}
	}
} // CT_ProcClick

function CT_TrackFileExtension(link) {
	link = link.split(/\?/)[0]; // get everything up to but not including ?
	link = link.toLowerCase();
	var l1 = link.length;
	for (var index = 0; index < CT_I_OtherFileExtensionsToReport.length; index++) {
		if (CT_I_OtherFileExtensionsToReport[index] != '' && link.substring(l1-CT_I_OtherFileExtensionsToReport[index].length-1) == '.' + CT_I_OtherFileExtensionsToReport[index].toLowerCase()) {
			return true;
		}
	}
	return false;
}

function CT_LocalLink(link) {
	var pieces = link.match(/^https?:\/\/([^\/]+)\//);
	if (pieces) {
		var l = pieces[1].length;
		for (var i in CT_I_LocalLinks){
			if (pieces[1] == CT_I_LocalLinks[i])
				return true;
		}
		return false;
	}
	return true;
} // CT_LocalLink

if (CT_I_EnableExitTracking) {
	if (document.addEventListener) { // handle DOM 2 (Mozilla 6)
		document.addEventListener('click', CT_ProcClick, false);
	} else {
		document.attachEvent('onclick', CT_ProcClick);
	}
}

CT_RecordView();

//PNH this function called at the bottom of this file (after other pre-requisite functions are defined
GG.trackLead = function() {

	var fullServerPath = '//' + GG.LCF.server + '/cgi-bin/ctasp-server.cgi?';
	var leadCookieName = GG.getLeadCookieName();
	if( null !== GG.findSingleCookieValue( leadCookieName ) )
		CT_RecordView( null, null, [ 'GG=1' ], fullServerPath );
}

GG.LCF.init = function() {
	//extract and store the GG Lead ID as a global variable (ack!)
	GG.LCF.LeadID = GG.findSingleCookieValue( GG.LCF.cookieName );

	var matches = {};
	for (var f = 0; f < document.forms.length; f++) {
		var Form = document.forms[f];
		for (var i in paths) {
			var matchShouldBe = 0;
			var matchCount = 0;
			var path = paths[i];
			for (var j in path) {
				var value = path[j];
				var match = false;
				switch(j) {
				case 'id':
					matchShouldBe--;
					break;
				case 'ActionURL':
					for (var v = 0; v < value.length; v++) {
						if (Form.action == value[v]) match = true;
					}
					break;
				case 'FormFieldExists':
					var fieldCount = 0;
					var fieldShouldBe = 0;
					for (var v = 0; v < value.length; v++) {
						if (Form[value[v]]) fieldCount++;
						fieldShouldBe++;
					}
					if (fieldCount == fieldShouldBe && fieldCount > 0) match = true;
					break;
				case 'FormFieldValue':
					for (var v = 0; v < value.length; v++) {
						var pair = value[v].split(/=/);
						if (Form[pair[0]] && Form[pair[0]].value == pair[1]) match = true;
					}
					break;
				case 'FormID':
					for (var v = 0; v < value.length; v++) {
						if (Form.id == value[v]) match = true;
					}
					break;
				case 'FormName':
					for (var v = 0; v < value.length; v++) {
						if (Form === document.forms[value[v]]) match = true;
					}
					break;
				case 'LandingURL':
					for (var v = 0; v < value.length; v++) {
						if (window.location.href == value[v]) match = true;
					}
					break;
				case 'ReferringURL':
					for (var v = 0; v < value.length; v++) {
						if (document.referrer == value[v]) match = true;
					}
					break;
				case 'AddFields':
					matchShouldBe--;
					break;
				}
				if (match) matchCount++;
				matchShouldBe++;
			}
			if (matchShouldBe == matchCount && matchCount > 0) {
				if (!matches[Form]) {
					GG.LCF.manipulateForm(Form, path.id, path.AddFields);
					matches[Form] = 1;
				}
			}
		}
	}
}

GG.LCF.manipulateForm = function(form, formId, addFields) {
	if( form.onsubmit )
		form.gg_origOnSubmit = form.onsubmit;
	form.onsubmit = GG.LCF.onsubmit;

	if( form.action )
		form.gg_origAction = form.action;
	form.action = "javascript:GG.LCF.onActionSubmit( this );";


	//inject lead identifier for use by SalesForce
	if (!addFields) {
		addFields = {};
	}
	if (GG.LCF.salesForceLeadIdFieldName) {
		addFields[GG.LCF.salesForceLeadIdFieldName] = GG.LCF.LeadID;
	}
	addFields.GGFORMID = formId;
	for (var i in addFields) {
		form.appendChild(GG.renderHiddenField(i, addFields[i]));
	}
}

GG.LCF.onActionSubmit = function( form ) {
	GG.LCF.handleFormSubmissionRequest( form );
}

GG.LCF.onsubmit = function(e) {
	e = e || window.event;

	//e.currentTarget gives us the element the event is currently
	//bubbling/capturing through, rather than e.target which gives us the source of the event (not always what we want)
	if (e.target) targ = e.currentTarget; 
	else if (e.srcElement) targ = e.srcElement;

	//stop propagation of intercepted submit event
	if( e.stopPropogation ) //W3DOM
		e.stopPropogation();
	else if( typeof(e.cancelBubble) != 'undefined' ) //IE
		e.cancelBubble = true;

	if( e.preventDefault ) //W3DOM
		e.preventDefault();
	else if ( typeof(e.returnValue) != 'undefined' ) //IE
		e.returnValue = false;



	GG.LCF.handleFormSubmissionRequest( targ );
}

GG.LCF.handleFormSubmissionRequest = function( form ) {

	var dictFormData = GG.extractFormData( form );

	//inject GG lead id info into the form data for JDC
	dictFormData.gg_uniqueid = GG.LCF.LeadID;

	var aFormData = new Array();
	for( var key in dictFormData ) {
		aFormData.push( encodeURIComponent( key ) + '=' + encodeURIComponent( dictFormData[key] ) );
	}
	GG.postHiddenForm(
		window.location.protocol + '//' + GG.LCF.server + GG.LCF.recordCgi,
		{ i: GG.LCF.datasetId,
			data: aFormData.join('&'),
			stem: window.location.pathname,
			rnd: Math.random()
		},
		function(){ GG.LCF.onBackChannelSubmissionComplete(form); }
	);
}

GG.LCF.onBackChannelSubmissionComplete = function( form ) {

	//add a cookie such that JDC records future visits
	var expirationDate = new Date(2020, 12, 31, 0, 0, 0);
	document.cookie = GG.getLeadCookieName() + '=' + GG.LCF.LeadID + '; expires=' + expirationDate.toGMTString() + '; path=/';

	form.onsubmit = form.gg_origOnSubmit || null;
	form.action = form.gg_origAction || "";

	form.submit();
}

GG.getLeadCookieName = function() {
	return 'gg_uniqueid_' + GG.LCF.datasetId;
}

GG.extractFormData = function( form ) {
	var formData = {};
	var aInputEls = form.getElementsByTagName('input');
	for( var i = 0; i < aInputEls.length; i++ )
		formData[aInputEls[i].name] = aInputEls[i].value;
	return formData;
}

GG.findCookieValues = function( strKey ) {
	var cookies = document.cookie.split(/; ?/);
	for (var i = 0; i < cookies.length; i++) {
		var kvpCookie = cookies[i].split(/=/);
		if( kvpCookie[0] == strKey )
			return kvpCookie[1].split(/:/);
	}
	return null;
}

GG.findSingleCookieValue = function( strKey ) {
	var aCookies = GG.findCookieValues( strKey );
	if( aCookies )
		return aCookies[0];
	else
		return null;
}

GG.renderHiddenField = function( name, value ) {
	var newField = document.createElement('input');
	newField.type = 'hidden';
	newField.name = name;
	newField.value = value;
	return(newField);
}

GG.postHiddenForm = function( targetUrl, formData, onPostComplete ) {
	var remotingDiv = GG.getRemotingDiv(targetUrl);

	//fill form with hidden input data
	for( var key in formData )
		remotingDiv.form.appendChild(GG.renderHiddenField(key, formData[key]));

	remotingDiv.locationChangeTimer = setInterval(
		function() {
			var bLocationChanged = false;
			try {
				bLocationChanged = ( "about:blank" != remotingDiv.iframe.location.href );
			} catch(err) {
				//if we're not allowed to look at the iframe's location (which is why the exception was thrown)
				//then it must have changed!
				bLocationChanged = true;
			}

			if( bLocationChanged ) {
				onPostComplete();
				clearInterval( remotingDiv.locationChangeTimer );
			}
		},
		200
	);

	remotingDiv.form.submit();
}

GG.getRemotingDiv = function(url) {
	var remotingDiv = document.getElementById('remotingDiv');
	if( !remotingDiv ) {
		remotingDiv = document.createElement('div');
		remotingDiv.id = 'remotingDiv';
		remotingDiv.innerHTML = "<iframe name='remotingFrame' id='remotingFrame' style='border:0;width:0;height:0;'></iframe>";

		document.body.appendChild(remotingDiv);
		remotingDiv.iframe = frames['remotingFrame'];

		remotingDiv.form = document.createElement('form');
		remotingDiv.form.setAttribute('id', 'remotingForm');
		remotingDiv.form.setAttribute('target', 'remotingFrame');
		remotingDiv.form.target = 'remotingFrame';
		remotingDiv.form.setAttribute('method', 'post');
		remotingDiv.form.setAttribute('action', url); // Tim copied this here from below

		remotingDiv.appendChild(remotingDiv.form);
	}

	return remotingDiv;
}

GG.trackLead();

//PNH 15-Feb-07
//Form Identification stuff

function addRemoteScript( strScriptLocation ) {
	document.write('<'+'script type="text/javascript" src="' + strScriptLocation + '"></'+'script>');
}

if( window.name == "GG_FORM_LOCATOR_FRAME" ) {
//if( true ) {
	var serverBaseUri = GG.LCF.GlenGarryURI;

	addRemoteScript( serverBaseUri + "/js/prototype/prototype.js" );
	addRemoteScript( serverBaseUri + "/js/scriptaculous/scriptaculous.js?load=effects,dragdrop" );
	addRemoteScript( serverBaseUri + "/js/modalog/animator.js" );
	addRemoteScript( serverBaseUri + "/js/modalog/modalog.js" );
	addRemoteScript( serverBaseUri + "/js/firebugx.js" );
	addRemoteScript( serverBaseUri + "/js/gg_common.js" );
	addRemoteScript( serverBaseUri + "/js/leadcaptureform.js" );

	GG.SERVER_BASE_URI = serverBaseUri;
	document.write( '<'+'script type="text/javascript">' );
	document.write( 'GG.onLoadLocatorFrame();' );
	document.write( '</'+'script>' );


} else {
	GG.LCF.init();
}

