// WebTrends Utilities
// Created by Panalysis (c) all rights reserved
/**
* WebTrends Extension Methods. Extends existing WebTrends.js object
* @constructor
* @public
* @author Panalysis Pty Ltd
* @version 1.0.5 2010-10-20
* @return void
*/

/**
* Sets the DCSID for the Form Tracking methods. This will not override the default DCSID specified in the original WebTrends object
* @public
* @param {String} DCSID. The ID for the Data Source as specified in WebTrends.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.SetFormDCSID = function(DCSID)
{
	this.FormDCSID = DCSID;
	this.fErrorCookie = "wtfe";
	this.fCompletedCookie = "wtfc";
	this.CurrentForm = "";
	this.fError = false;
	this.fCorrected = false;
	this.fStart = false;
	
	if(typeof(this['TrackFields']) == "undefined")
		this['TrackFields'] = true;
	this.SelectedVehicles = {};
}

/**
* Tells WebTrends that the form specified was loaded. This method can be called upon the page load of a form
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.TrackFormLoad = function(FormID)
{
	if(this.CurrentForm.toLowerCase() != FormID.toLowerCase())
	{
		var d = new Date();
		this._SetCookie(this.fErrorCookie,"",d);
		this._SetCookie(this.fCompletedCookie,"",d);
	}
	
	if(document.referrer != "")
		this.DCSext.FormReferringPage = this._GetReferrer();
	else
		this.DCSext.FormReferringPage = "No Referrer";
	
	
	this.DCSext.FormID = FormID;
	this.DCSext.FormLoad = 1;
	this.DCSext.FieldFormID = FormID;
	this._SetFieldData(FormID);
	
	this._SendData("","","/forms/" + FormID + "/TrackFormLoad");
}

/**
* Tells WebTrends that the form specified was started. This method can be called once a user has entered their cursor into any field on the form.
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.TrackFormStart = function(FormID)
{
	if(this.fStart == false)
	{
		this.DCSext.FormID = FormID;
		this.DCSext.FormStart = 1;
		this.DCSext.FieldFormID = FormID;
		this._SetFieldData(FormID);
		this.fStart = true;
		this._SendData("","","/forms/" + FormID + "/TrackFormStart");
		
	}
}

/**
* Tells WebTrends that the form specified was submitted. This method must be called on the final completion page when the form has been successfully submitted.
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.TrackFormSubmit = function(FormID)
{
	var isCorrected = false;
	var strCE = this._GetCookie(this.fErrorCookie);
	var strCC = this._GetCookie(this.fCompletedCookie);
	
	if(strCE != "")
		this.DCSext.FormSubmitError = 1;
		
	this.DCSext.FormID = FormID;
	this.DCSext.FormSubmit = 1;
	this.DCSext.FieldFormID = FormID;
	if(this.fCorrected==true)
		this.DCSext.FormCorrected=1;
	
	this.DCSext.FormSelectedVehicles = this._buildVehicleString();
	
	this._SetFieldData(FormID);
	var completedFields = new Array();
	var errorFields = new Array();
	var strErrFields ="";
	if(strCE != "")
		errorFields = strCE.split("|");
	if(strCC != "" && this.TrackFields)
	{
		completedFields = strCC.split("|");
		var nErr = 0;
		for(var i=0; i<completedFields.length;i++)
		{
			for(var y=0; y<errorFields.length; y++)
			{
				if(completedFields[i].toLowerCase()==errorFields[y].toLowerCase())
				{
					if(nErr>0)
						strErrFields += ";";
						
					strErrFields += errorFields[y];
					nErr ++;
				}
			}
		}

		if(strErrFields != "")
		{
			//this.DCSext.FieldFormID = FormID;
			this.DCSext.FieldName = strErrFields;
			this.DCSext.FieldErrorSubmitted = 1;
			//this._SendData("","","/forms/" + FormID + "/TrackFormSubmitFieldData");
		}
	}
	
	
	this._SendData("","","/forms/" + FormID + "/TrackFormSubmit");

		
	var d = new Date();
	this._SetCookie(this.fErrorCookie,"",d);
	this._SetCookie(this.fCompletedCookie,"",d);
}

/**
* Sends the status of an individual field to WebTrends.<p>This method is executed when a field in a form has a non-null value and expects either "Complete" or "Error" if there is a validation error.
* @example
* &lt;input type="text".. onblur="myFunc() ...&gt;
* ...
* &lt;script type="text/javascript"&gt;
* function myFunc(){
*  var isError = false
*   // some validation code 
*
*  if(isError)
*    _trackingObj.TrackFormField("FormID","FieldName","Error");
*  else
*    _trackingObj.TrackFormField("FormID","FieldName","Complete");
* }
* &lt;/script&gt;
*
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @param {String} Fieldname. Name of the field.
* @param {String} FieldStatus. Either Error or Complete.
* @author Panalysis Pty Ltd
* @version 1.0.1
* @return void
*/
WebTrends.prototype.TrackFormField = function(FormID, Fieldname, FieldStatus)
{
	if(! this.TrackFields)
		return;
		
	if(FieldStatus.toLowerCase()=="error" && ! this._FieldHadError(Fieldname) && this.fStart==true)
	{
		this.TrackFormError(FormID);
		this.DCSext.FieldError = 1;
		this._SetFieldErrorCookie(Fieldname);
	}
	else if(FieldStatus.toLowerCase()=="complete" && ! this._FieldIsComplete(Fieldname))
	{
		// is this a correction
		if(this._FieldHadError(Fieldname))
		{
			this.fCorrected = true;
		}
		
		this.DCSext.FieldComplete = 1;
		this._SetFieldCompletedCookie(Fieldname);
	}
	else
		return;
		
	this.DCSext.FieldFormID = FormID;
	this.DCSext.FieldName = Fieldname;
	this._SendData("","","/forms/" + FormID + "/TrackFormField");

}

/**
* Tells WebTrends that the form specified contained an error which was corrected prior to form submission.
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.TrackFormCorrection = function(FormID)
{
	this.DCSext.FieldFormID = FormID;
	if(this.fCorrected==false) // only fire once per form
	{
		this.fCorrected==true;
	}
}

/**
* Tells WebTrends that the form specified contained an error.
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.TrackFormError = function(FormID)
{
	if(this.fError == false && this.fStart==true) // only fire once per form and only once the user has attempted to complete the form to prevent counting false submissions
	{
		this.DCSext.FormID = FormID;
		this.DCSext.FormError = 1;
		this.fError = true;
		this._SendData("","","/forms/" + FormID + "/TrackFormError");
	}
}

/**
* Triggered when a vehicle is added to the form via the user's selecting a checkbox and when the form is submitted with the selected vehicles.
* @public
* @param {String} FormID. A string identifier for the form as specified in the ID attribute for the form. This will be reported in WebTrends.
* @param {String|Array} Vehicle. Name of the vehicle/s added to the form.
* @param {String} FieldStatus. Either Submitted or Added.
* @example
* var v = new Array(3);
* v[0] = "Corolla Hatch";
* v[1] = "Avensis";
* v[2] = "Kluger";
* _tag1.AddVehicle("TestForm",v,"Added");
* // OR
* _tag1.AddVehicle("TestForm","Corolla Hatch","Submit");
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype.AddVehicle = function(FormID,Vehicle,FormStatus)
{
	if(! this.TrackFields)
		return;
	var sv = {};
	$("input.car-selection").each(function(i,n){
		if(n.value.toLowerCase()!="please select")
			sv[n.value]=1;
	});
	this.SelectedVehicles = sv;
	
	this.DCSext.VehicleFormID = FormID;
	var vStr ="";
	var fStr = "";
	if(Vehicle instanceof Array)
	{
		for(var i=0; i<Vehicle.length; i++)
		{
			this.SelectedVehicles[Vehicle[i]]=1;
		}
	}
	else
		this.SelectedVehicles[Vehicle]=1;
	
	vStr = this._buildVehicleString();
	
	fStr = this.DCSext.VehicleFormID;
	if(FormStatus != null && FormStatus != "")
		fStr += "-" + FormStatus;
	if(FormStatus=="Submit")
		this.DCSext.FormSubmit=1;
	else
		this.DCSext.FormStart=1;
	this.DCSext.FormSelectedVehicles = vStr;
	this._SendData(fStr,vStr,"/forms/" + FormID + "/TrackVehicle");
}



//********* Private Methods *****************//

WebTrends.prototype._buildVehicleString = function()
{
	// build the string
	var c=0,vStr="";
	
	for(var i in this.SelectedVehicles)
	{
		if(c>0)
		{
			vStr += ";";
		}
		vStr += i;
		c++;
	}
	return vStr;
}

/**
* Sends data to WebTrends
* @private
* @param {String} ContentGroup. The ID for the content group to be reported in WebTrends for this request.
* @param {String} ContentSubGroup. The ID for the content sub group to be reported in WebTrends for this request.
* @param {String} URL. The URL to be reported in WebTrends for this request.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype._SendData = function(contentGroup,contentSubGroup,uri)
{
	
	this.dcsVar();
	var oldDCSID="";
	var oldWTCGN = "";
	var oldWTCGS = "";
	var oldURL = "";
	
	if(this.FormDCSID != "")
	{
		oldDCSID = this.dcsid;
		this.dcsid = this.FormDCSID;
	}
	oldWTCGN = this.WT.cg_n;
	oldWTCGS = this.WT.cg_s;
	oldURL = this.DCS.dcsuri;
	
	if(contentGroup != null)
		this.WT.cg_n = contentGroup;
	else
		delete this.WT.cg_n;
		
	if(contentSubGroup != null)
		this.WT.cg_s = contentSubGroup;
	else
		delete this.WT.cg_s;
		
	if(uri != "")
		this.DCS.dcsuri = escape(uri);
		
	this.dcsFPC();
	this.dcsTag();
	
	if(oldDCSID != "")
		this.dcsid = oldDCSID;
	if(oldWTCGN != "")
		this.WT.cg_n = oldWTCGN;
	if(oldWTCGS != "")
		this.WT.cg_s = oldWTCGS;
	if(oldURL != "")
		oldURL = oldURL;
		
	this.DCSext = {};
}

/**
* Sets a cookie containing all fields in the form that contained an error
* @private
* @param {String} Fieldname. Name of the field.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype._SetFieldErrorCookie = function(Fieldname)
{
	var strC = this._GetCookie(this.fErrorCookie);
	var errorFields = new Array(50);
	var maxID=0;
	if(strC != "")
	{
		var tmpErrorFields = strC.split("|");
		for(var i=0; i<tmpErrorFields.length; i++)
			errorFields[i] = tmpErrorFields[i];
			
		maxID = tmpErrorFields.length;
	}
	
	var found=false;
	for(var y=0; y<errorFields.length; y++)
	{
		if(errorFields[y] != null && errorFields[y].toLowerCase() == Fieldname.toLowerCase())
		{
			found=true;
			break;
		}
	}
	
	if(found==false && maxID<50)
	{
		if(Fieldname.length>76)
			errorFields[maxID] = Fieldname.substring(0,76);
		else
			errorFields[maxID] = Fieldname;
	}
		
	var cVal="";
	for(var x=0; x<=maxID; x++)
	{
		if(x>0)
			cVal += "|";
		
		cVal += errorFields[x];
	}
	
	if(cVal != "")
		this._SetCookie(this.fErrorCookie,cVal);
}

/**
* Sets a cookie containing all fields in the form that were successfully completed
* @private
* @param {String} Fieldname. Name of the field.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype._SetFieldCompletedCookie = function(Fieldname)
{
	var strC = this._GetCookie(this.fCompletedCookie);
	var completedFields = new Array(50);
	var maxID=0;
	if(strC != "")
	{
		var tmpCompletedFields = strC.split("|");
		for(var i=0; i<tmpCompletedFields.length; i++)
			completedFields[i] = tmpCompletedFields[i];
			
		maxID = tmpCompletedFields.length;
	}
	
	var found=false;
	for(var y=0; y<completedFields.length; y++)
	{
		if(completedFields[y] != null && completedFields[y].toLowerCase() == Fieldname.toLowerCase())
		{
			found=true;
			break;
		}
	}
	
	if(found==false && maxID<50)
	{
		if(Fieldname.length>80)
			completedFields[maxID] = Fieldname.substring(0,80);
		else
			completedFields[maxID] = Fieldname;
	}
		
	var cVal="";
	for(var x=0; x<=maxID; x++)
	{
		if(x>0)
			cVal += "|";
		
		cVal += completedFields[x];
	}
	
	if(cVal != "")
		this._SetCookie(this.fCompletedCookie,cVal);
}

/**
* Checks whether a field has previously registered an error for this form
* @private
* @param {String} Fieldname. Name of the field.
* @author Panalysis Pty Ltd
* @version 1.0
* @return true if an error has been recorded, false if not
*/
WebTrends.prototype._FieldHadError = function(Fieldname)
{
	var strC = this._GetCookie(this.fErrorCookie);
	var errorFields = new Array(50);
	if(strC != "")
	{
		var errorFields = strC.split("|");
	}
	
	for(var i=0; i<errorFields.length; i++)
	{
		if(errorFields[i] != null && errorFields[i].toLowerCase()==Fieldname.toLowerCase())
			return true;
	}
	
	return false;
}

/**
* Checks whether a field has previously completed a field in the form
* @private
* @param {String} Fieldname. Name of the field.
* @author Panalysis Pty Ltd
* @version 1.0
* @return true if a field has been completed, false if not
*/
WebTrends.prototype._FieldIsComplete = function(Fieldname)
{
	var strC = this._GetCookie(this.fCompletedCookie);
	var completedFields = new Array(50);
	if(strC != "")
	{
		var completedFields = strC.split("|");
	}
	
	for(var i=0; i<completedFields.length; i++)
	{
		if(completedFields[i] != null && completedFields[i].toLowerCase()==Fieldname.toLowerCase())
			return true;
	}
	
	return false;
}


/**
* Sets a cookie
* @private
* @param {String} cookieName. Name of the cookie.
* @param {String} cookieValue. The value to store.
* @param {Date} expire. Optional expiry date and time of the cookie.
* @param {String} strDomain. The domain name to specify the scope of the cookie.
* @author Panalysis Pty Ltd
* @version 1.0
* @return void
*/
WebTrends.prototype._SetCookie = function(cookieName,cookieValue,expire,strDomain) {
	var pdm = "";
	if (strDomain && strDomain!="") 
		pdm=" domain="+strDomain+";"; 

	if((typeof(expire)).toLowerCase() == "date")
		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + "; path=/;" + pdm;
	else
		document.cookie = cookieName+"="+escape(cookieValue) + "; path=/;" + pdm;
}


/**
* Returns the value for a specified cookie
* @private
* @param {String} cookieName. Name of the cookie.
* @author Panalysis Pty Ltd
* @version 1.0
* @return {String} Cookie value
*/
WebTrends.prototype._GetCookie = function(cookieName){
	var _ucookies = document.cookie.split(";");
	for(i = 0; i < _ucookies.length; i++){
		var np = _ucookies[i].split("=");
		if(this._Trim(np[0].toLowerCase()) == cookieName.toLowerCase())
		{
			var val ="";
			for(i=1;i<np.length;i++)
			{
				if(i>1)
					val += "=";
				
				val += np[i];
			}
			return unescape(this._Trim(val));
		}
	}
	return "";
}

/**
* Returns the a string value with white space removed from start and end of string
* @private
* @param {String} val. The string value to be trimmed.
* @author Panalysis Pty Ltd
* @version 1.0
* @return {String} trimmed string
*/
WebTrends.prototype._Trim = function(val)
{
	return val.replace(/^\s+|\s+$/g, '') ;
}

/**
* Returns the a string value with the referring page
* @private
* @author Panalysis Pty Ltd
* @version 1.0
* @return {String} referring URL
*/
WebTrends.prototype._GetReferrer = function(val)
{
	var r="";
	if(document.referrer.toLowerCase().indexOf('toyota.com.au')>0)
	{
		if (window.RegExp){
			var refRE=new RegExp("https?:\/\/(.*)","i");
			var m = document.referrer.match(refRE);
			if(m.length>1)
				r = m[1];
		}
		else
			r = document.referrer;
	}
	else
		r = document.referrer;
		
	return r;
}

/**
* Creates an associative array of field names from the current form
* @private
* @param {String} val. Optional. The ID or name of the form. If null the value from current form will be used
* @author Panalysis Pty Ltd
* @version 1.0
* @return {void}
*/
WebTrends.prototype._GetFieldList = function(val)
{
	if(typeof(this.fields) == "undefined")
		this.fields = {};
		
	var fID="";
	if(val != null)
		fID = val;
	else if(this.CurrentForm != "")
		fID = this.CurrentForm;
	else
		return;
		
	var fList = new Object();
	var fEl;
	if(document.forms[fID])
		fEl = document.forms[fID].elements;
	else
		return;
	
	for(var i=0; i<fEl.length; i++)
	{
		if(typeof(fEl[i].name) != "undefined")
		{
			if(typeof(fEl[i].type) != "undefined")
			{
				if(fEl[i].type.toLowerCase() == "hidden")
					continue;
			}
			if(typeof(this.fields[fEl[i].name])=="undefined")
			{
				this.fields[fEl[i].name]= {
					formload:1,
					formstart:0,
					fieldstart:0,
					fielderror:0,
					fieldsubmit:0
				};
			}
		}
	}
}

/**
* Creates an associative array of field names from the current form
* @private
* @param {String} FormID. Optional. The ID or name of the form. If null the value from current form will be used
* @author Panalysis Pty Ltd
* @version 1.0
* @return {void}
*/
WebTrends.prototype._SendFieldData = function(FormID)
{
	this._GetFieldList(FormID);
	var fStr = "";
	var isFirst = 1;
	if(typeof(this.fields)=="undefined")
	{
		this.DCSext={};
		return;
	}
		
	for(var i in this.fields)
	{
		if(isFirst==1)
			isFirst = 0;
		else
			fStr += ";";
		
		fStr += i;
	}
	if(fStr != "")
	{
		this.DCSext.FieldName = fStr;
		this._SendData("","","/forms/" + FormID + "/TrackFormFieldLoad");
		this.DCSext.FieldName = "";
	}
	else
		this.DCSext={};
}


/**
* Creates an associative array of field names from the current form
* @private
* @param {String} FormID. Optional. The ID or name of the form. If null the value from current form will be used
* @author Panalysis Pty Ltd
* @version 1.0
* @return {void}
*/
WebTrends.prototype._SetFieldData = function(FormID)
{
	this._GetFieldList(FormID);
	var fStr = "";
	var isFirst = 1;
	if(typeof(this.fields)=="undefined")
	{
		return;
	}
		
	for(var i in this.fields)
	{
		if(isFirst==1)
			isFirst = 0;
		else
			fStr += ";";
		
		fStr += i;
	}
	if(fStr != "")
		this.DCSext.FieldName = fStr;
}

