
//--------------------------------------------------------------------------------------- 
// FileName: 	DSI_WT_TrackFunction.js
//
// Purpose:  	Holds WT_Track object 
//				When a form is filled out and submitted, the dsiWTTrackItem will save the trackable
//				form data into a cookie. This cookie is then loaded and read by the following page
//				and recorded in Web Trend. In order to transfer data between pages, cookies are used.
//
// Dependency:	utilities.js -> loaded by functions.js (dynLoadScript(scripts)) for function: getCookie(name)
//
//				ALSO:
//				Works in tandem with   DSI_WT_TrackData_<Form Name> - Holds the dsiWTTrackItem 
//				data that is specific to each form. All forms that need tracking will need their own
//				DSI_WT_TrackData_<..> js file.
//
// Usage:		On the HTML Form file, use the object name declared in DSI_WT_TrackData_<Form Name> 
//				file, and call method: ReadForm(<validation:t/f>,<form name>). Ensure the form name is passed as a 
//				parameter. The <validation:t/f> serves as pass-through for the validation function. If
//				validation function returns true, then Tracking executes. The result of the validation
//				function is then returned back out to reach the forms "on submit" tag.
//				EX: <form id="signup_form" class="signup" name="signup_form" 
//					 action="/SubscriptionService" method="post" 
//					 onsubmit="return WT_Track.ReadForm(validateRegForm.init(this),signup_form)"> 
//				
//				On the HTML page following the HTML form, go to the <HEAD> section and, using the same
//              object name, call method: WriteTrackingMetaTag() with no parameters.
//				EX: <script type="text/javascript">WT_Track.WriteTrackingMetaTag();</script>
//				
// Debugging	Debugging will throw some alerts. You can set degbugging by changing the alert leve 
//				betwee 0 - no alerts and 5 and so on. The higher the debugging  level, more alerts show.
//
// Date:		12/08/2009
//
// Author:		Sergio Pinheiro
//
//


dsiWTTrackItem = function()
{
	var FieldMap_cookiename = [];
	var FieldMap_formfieldname = [];
	var confWT_Track = [];
	var lDebug = new obj_dsi_Debug();
		
	// Read debug value from URL. if missing, defaul to zero. 0 = debug off, 1...5 = level of debug
	// messages. Higher level = more messages		
	lDebug.setLevel(!dsi_getUrlVars()["debug"]?0:dsi_getUrlVars()["debug"]);
	
	// Properties
	this.field = confWT_Track;  
	this.cookieName = "";
	
	// Create a Debug object and expose it as a property
	this.Debug = lDebug;	
	
	// Methods
	// Adds data to the WT_track array
	this.add = function(CookieFieldName, FormFieldName, Trackthis, UseMetaTag)
	{ 
		FieldMap_cookiename[FieldMap_cookiename.length] = CookieFieldName.toUpperCase();
		FieldMap_formfieldname[FieldMap_formfieldname.length] = FormFieldName.toUpperCase();
		confWT_Track[confWT_Track.length] = {track: Trackthis, data: "", metaTag: UseMetaTag};
	}
	
	// Retrieves form field name when supplied associated cookie field name
	this.getFormFNbyCookieFN = function(cookiename)
	{
		var result = FieldMap_formfieldname[this.indexOfCookieFN(cookiename.toUpperCase())];
		this.Debug.add(5, "getFormFNbyCookieFN->param: " + cookiename + "\nResult: " + result);
		return result
	}
	
	// Retrieves cookie field name when supplied associated form field name	
	this.getCookieFNbyFormFN = function(formfieldname)
	{
		var result = FieldMap_cookiename[this.indexOfFormFN(formfieldname.toUpperCase())];
		this.Debug.add(5, "getCookieFNbyFormFN->param: " + formfieldname + "\nResult: " + result);	
		return result;
	}

	// Retrieves the tracking record that matches cookie name	
	this.getWTField = function(cookiename)
	{
		var result = confWT_Track[FieldMap_cookiename.indexOf(cookiename.toUpperCase())];
		this.Debug.add(5, "getWTField->param: " + cookiename + "\nResult.track: " + result);		
		return result;		
	}

	// Retrieves array location of the form field name		
	this.indexOfFormFN = function(name)
	{
		var result = FieldMap_formfieldname.indexOf(name.toUpperCase());
		this.Debug.add(5,"indexOfFormFN->param: " + name + "\nResult: " + result);			
		return result;
	}	

	// Retrieves array location of the cookie field name	
	this.indexOfCookieFN = function(name)
	{
		var result = FieldMap_cookiename.indexOf(name.toUpperCase());
		this.Debug.add(5, "indexOfCookieFN->param: " + name + "\nResult: " + result);			
		return result;	
	}	

	// Displays a debugging alert beased on the debugging level set.
	// level 0 = debug off, 1...5...* = level of debug messages. Higher level = more messages
	// If debug level is high enough, the message will show.
	//
/*	this.Debug = function(level, string) 
	{
		if (level <= this.iDebug) alert(string);	
	}
*/	

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	//--------------------------------------------------------------------------------------- 
	// Reads the data from the form and saves it to a cookie for WT tracking.
	// only one cookie will be saved per form. All data elements are concatenated into
	// one string as "&"-delimited, and having "name=value" format. This is to overcome
	// the 20 cookie limitation of some browsers.
	//
	// by Sergio Pinheiro
	//
	this.ReadForm = function (validated, objForm)
	{
		var formElements = "";
		var ltempWT_trackObj;
		var lCookieName;

		//this.cookieName = objForm.name;
		this.Debug.show(1, "ReadForm->Form name: " + this.cookieName + "\nValidated: " + validated); 
		
		// Do nothing if form fails validation
		if(validated)
		{
			// Iterate through all form fields		
			for (var n=0; n < objForm.elements.length; n++) 
			{
				// Skip over "False members of a radio group.
				if (objForm.elements[n].type == "radio" && !objForm.elements[n].checked) 
				{
					continue;
				}
			//	else if (objForm.elements[n].type == "checkbox" && objForm.elements[n].checked) formElements.add(objForm.elements[n]);
				else 
				{
					// Get cookie name for WT field tracking record fetch
					lCookieName = this.getCookieFNbyFormFN(objForm.elements[n].name);	
					if(lCookieName) 
					{
						this.Debug.add(3, "ReadForm-> Form Field Name : " + objForm.elements[n].name + "\nCookie Name : " + lCookieName + "; -> " + objForm.elements[n].value);
						
						//Fetch WTField tracking record
						ltempWT_trackObj = this.getWTField(lCookieName);
						if (ltempWT_trackObj != null)
						{
							// Track data only if configured to do so. Saves space in cookie by not tracking blanks
							this.Debug.add(3, "ReadForm->Found Track Record: \n Track: " + ltempWT_trackObj.track);
							if (ltempWT_trackObj.track)
							{
				//				formElements += n + ": " + objForm.elements[n].name + "=" + objForm.elements[n].value + "\n";
				//				formElements += "&" + objForm.elements[n].name + "=" + objForm.elements[n].value;
								// Record the data. If multiple form fields map to same cookie, data is concatenated				
								ltempWT_trackObj.data += objForm.elements[n].value + " ";
							}
						}
					}
				}
				this.Debug.show();				
			}
			this.WriteWTCookie();	
		}		
		return validated;
	}


	//--------------------------------------------------------------------------------------- 
	// Iterates through WT tracking array and saves the data element into a cookie.
	// If tracking is false and length is 0, element is omitted.
	//
	// by Sergio Pinheiro
	//
	this.WriteWTCookie = function()
	{	
		var lCookieData = "";

		// Write the debug level into the cookie in order to debug it in the follow up page.
		lCookieData = "debug=" + this.Debug.getLevel();
		
		for (var n=0; n<confWT_Track.length; n++)
		{
			if (confWT_Track[n].track && dsi_trim(confWT_Track[n].data).length > 0)
			{
				lCookieData += "&" + FieldMap_cookiename[n] + "=" + dsi_trim(confWT_Track[n].data);
			}
		}

		// Finally - Write the cookie
		this.Debug.show(1, "WriteWTCookie->Cookie String: " + lCookieData);
		if (lCookieData.length > 0)	this.AddCookie(this.cookieName, lCookieData);	
	}

	//--------------------------------------------------------------------------------------- 
	// Adds a cookie 
	//
	// by Sergio Pinheiro
	this.AddCookie = function (lItemName, lData) 
	{ 
		var exp = new Date(); 
	   
		this.Debug.add(1,"AddCookie->params.Name: " + lItemName);
		this.Debug.add(2,"AddCookie->params.Data: " + lData);
		this.Debug.show();
	   
		// expires in 3 months   (months, days, hours, minutes, seconds, milliseconds) 
//		exp.setTime(exp.getTime() + (3*30*24*60*60*1000)); 
		exp.setTime(exp.getTime() + (5*60*1000)); // cookie lives 5 minutes

		document.cookie = lItemName + "=" + escape(lData); 
		document.cookie = "expires=" + exp.toGMTString(); 
	} 	
	
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++		

	//--------------------------------------------------------------------------------------- 
	// Reads data from a cookie and writes a Web Trend's meta tag for tracking the data.
	// Data is obtained from a form and saved when form submitted. Tracking should
	// take place on follow-up page. Therefore, this function should appear on 
	// the followup page.
	//
	// by Sergio Pinheiro
	//
	this.WriteTrackingMetaTag = function()
	{
		var cookie = getCookie(this.cookieName);
		var cookieData = this.ParseWTTrackingCookie(cookie);
		var metaDataTag;
		
		// Set the debug value as transfered in from the Form page
		this.Debug.setLevel(cookieData["debug"]);
		
		this.Debug.add(1,"WriteTrackingMetaTag->");
		this.Debug.add(2,"WriteTrackingMetaTag->cookie: " + cookie);		
		
		// Loop through elements of tracking array.
		for(var n = 0; n < cookieData.length; n++)
		{
			this.Debug.add(3,"WriteTrackingMetaTag->cookieData[" + n +"] : " + cookieData[n] + 
			             "\ncookie Value: " + cookieData[cookieData[n]]);
			
			metaDataTag = this.getWTField(cookieData[n]);
			if (metaDataTag != null)
			{
				
/****** SPECIAL CONDITION - BENICAR **************
				if(cookieData[n] == "DRUG_STAT")
				{
					var Drug_Stat_Data = cookieData[cookieData[n]].split(" ");

					this.Debug.add(4, "DRUG_STAT->Split ->\n0:" + Drug_Stat_Data[0] + "\n1:" + Drug_Stat_Data[1] + "\n2:" + Drug_Stat_Data[2] + "\n3:" + Drug_Stat_Data[3]);
					if (Drug_Stat_Data[0] == "no") cookieData[cookieData[n]] = "Opt In Consumer Undiagnosed"
					else if (Drug_Stat_Data[1] == "none") cookieData[cookieData[n]] = "Opt In Consumer"
					else if (Drug_Stat_Data[2] == "yes") cookieData[cookieData[n]] = "Opt In Consumer On Drug"
					else cookieData[cookieData[n]] = "Opt In Consumer Competitor";

					//		case "no ": 			document.writeln(metaDataTag.metaTag.replace("%s", "Opt In Consumer Undiagnosed"));
					//		case "yes none ": 		document.writeln(metaDataTag.metaTag.replace("%s", "Opt In Consumer"));
					//		case "yes 1-2 yes ": 	document.writeln(metaDataTag.metaTag.replace("%s", "Opt In Consumer On Drug"));
					//		case "yes 3 yes ": 		document.writeln(metaDataTag.metaTag.replace("%s", "Opt In Consumer On Drug"));
					//		case "yes 1-2 no ": 	document.writeln(metaDataTag.metaTag.replace("%s", "Opt In Consumer Competitor"));
					//		case "yes 3 no ": 		document.writeln(metaDataTag.metaTag.replace("%s", "Opt In Consumer Competitor"));
				}
/****** SPECIAL CONDITION **************/
/****** SPECIAL CONDITION - EVOXAC **************/
				if(cookieData[n] == "DRUG")
				{
					var Drug_Stat_Data = cookieData[cookieData[n]].split(" ");

					this.Debug.add(4, "DRUG_STAT->Split ->\n0:");
					if (Drug_Stat_Data[0].toUpperCase() == "NO") cookieData[cookieData[n]] = "Anonymous Consumer"
					else cookieData[cookieData[n]] = "Opt In Consumer On Drug";
				}

/****** SPECIAL CONDITION **************/

				this.Debug.add(3,"WriteTrackingMetaTag->metaDataTag: " + metaDataTag.metaTag.replace("%s", cookieData[cookieData[n]]));		
				document.writeln(metaDataTag.metaTag.replace("%s", cookieData[cookieData[n]]));	

//				var newcontent = document.createElement('meta');
////				newcontent.setAttribute('name', 'WT.z_city');
////				newcontent.setAttribute('content', 'Jersey City');
//				newcontent.name="WT.z_city";
//				newcontent.content="Jersey City";
//				var HeadID = document.getElementsByTagName("head")[0];
//				HeadID.appendChild(newcontent);			

			}
		}
		this.Debug.show();
		this.DeleteCookie(this.cookieName);
	}

	//---------------------------------------------------------------------------------------
	// Logs the search query and count of items returned (0 or > 0)
	// If items returned are > 0, logs also "WT.oss_nz" with content	= 1.
	// also, all links returned need "?WT.z_oss_s=1" affixed to their URL.
	//
	this.logSearch = function(sQuery, iItemsFound)
	{
//		var sQuery = dsi_getUrlVars()["query"];
		this.Debug.add(2, "Query Logged --> " + sQuery + "; Found --> " + iItemsFound);
		
		// Create the meta tag WT data in the <Head> on the first pass
		// all passes thereafter are to update the search result links only
		if (sQuery.length > 0) 
		{
			WriteTagToElement('head', 'meta', 'WT.oss', sQuery);
			WriteTagToElement('head', 'meta', 'WT.oss_r', iItemsFound);
			if (iItemsFound > 0) WriteTagToElement('head', 'meta', 'WT.z_oss_nz', '1');
		}
	}
	
	
	//---------------------------------------------------------------------------------------
	// All links returned need "?WT.z_oss_s=1" affixed to their URL. This
	// function determins whether to use "?" or "&"
	//	
	this.logSearchLink = function(sLink)
	{
		this.Debug.add(2, "Link --> " + sLink);	
			
		// If there is a link, append "WT.z_oss_s=1" to all links of search result
		if (sLink.length > 0) 
		{
			if (sLink.indexOf("?") > 0) document.location.href = sLink + '&WT.z_oss_s=1'
			else document.location.href = sLink + '?WT.z_oss_s=1'
		}		
	}

	
	//--------------------------------------------------------------------------------------- 
	// Breaks up a WT Tracking cookie into it's elements 
	//
	// by Sergio Pinheiro
	//
	this.ParseWTTrackingCookie = function(objCookie)
	{    
		var vars = [], hash;    
		var hashes = objCookie.split('&');    

		this.Debug.add(1,"ParseWTTrackingCookie->");
		
		for(var i = 0; i < hashes.length; i++)    
		{        
			hash = hashes[i].split('=');        
			vars.push(hash[0]);        
			vars[hash[0]] = hash[1];    
		}   
		return vars;
	}	
	
	//--------------------------------------------------------------------------------------- 
	// Deletes a cookie 
	//
	// by Sergio Pinheiro
	this.DeleteCookie = function(lItemName) 
	{ 
		var exp = new Date(); 
	   
		this.Debug.show(1,"DeleteCookie->param: " + lItemName);
		
		// expires yesturday 
		exp.setTime(exp.getTime() -1*1000*60*60*24); 
		document.cookie = lItemName + "=; expires=" + exp.toGMTString(); 
	} 


	//--------------------------------------------------------------------------------------- 
	// This function lists all tag elements of type "META"
	//
	// by Sergio Pinheiro
	this.TestMetaData = function()
	{
		var list=document.documentElement.getElementsByTagName("*"); 		
		var tt;
		
		// Do only if debug is on
		if (this.Debug.iDebug > 0)
		{
			for(var i=0; i<list.length; i++) 
			{
				if(list[i].tagName=="META") 
				{tt += list[i].getAttribute('name') + ": " + list[i].getAttribute('content') + "\n";}
			} 
			alert("META tags on page: \n" + tt); 
		}
	}
	
	this.Clear = function()
	{
		for (var i=0; i < confWT_Track.length; i++) confWT_Track[i].data = "";
	}
	
	

}



// example how to enable tracking for the "role" data
// WT_Track.getField("role").track = true;

// Required includes: utilities.js -> loaded by functions.js (dynLoadScript(scripts))
// Functions: getCookie(name)



function test(myform)
{alert("test");}


// Writes a new tag into the identified element
function WriteTagToElement(sElement, sTag, sTagName, sTagContent)
{
	var HeadID = document.getElementsByTagName(sElement)[0];			
	var newcontent;
	
	newcontent = document.createElement(sTag);
	newcontent.name = sTagName;
	newcontent.content = sTagContent;
	HeadID.appendChild(newcontent);	
}



//--------------------------------------------------------------------------------------- 
// Parses the URL address into an array.
// Calling getUrlVars() function would return you the following array:
//   {"me"    : "myValue", "name2" : "SomeOtherValue"}
//
// by Roshambo @ http://snipplr.com/users/Roshambo/
//
function dsi_getUrlVars(){    
	var vars = [], hash;    
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    
	
	for(var i = 0; i < hashes.length; i++)    
	{        
		hash = hashes[i].split('=');        
		vars.push(hash[0]);        
		vars[hash[0]] = hash[1];    
	}   
	return vars;
}


//--------------------------------------------------------------------------------------- 
// Searches an array formatted as "name=value" and returns the first name (or value)
// item found in the array.
//
// by Sergio Pinheiro
//
function dsi_ArrayFind(dataArray, searchName)
{
	var aName = new Array();
	var aValue = new Array();
	
	for (var i = 0; i<dataArray.length; i++)
	{
		tToken=dataArray[i].split("=");
		aName[i]=tToken[0];
		aValue[i]=tToken[1];
	}
	
	if (searchName != "") return aValue[aName.indexOf(searchName)];
	//else if (value != "") return aName[aValue.indexOf(name)];
	else return -1;

}

//--------------------------------------------------------------------------------------- 
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
//
// by Steve Levithan
//
function dsi_trim (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}


// Used for debugging alert messages. It can display one message at a time with .show(lvl, msg)
// or queue up a bunch of messages with .add() and then display them in one dialogue with .show(null, null)
// lvl identifies what debugging level the message belongs to. If the debugging level is lower than msg
// level, then message will NOT display. This helps control information overload.
// The message queue mechanism increases flow of application by eliminating many unnecessary "OK" dialogues.
//
// By Sergio pinheiro
//
obj_dsi_Debug = function()
{
	var msg = "";
	var iDebug = "";
	
	this.add = function(lLevel, lmsg)
	{
		if (lLevel <= this.iDebug) msg += lmsg + "\n";
	}
	
	// Shows either the direct message or the message queue. Clear queue after it is displayed.
	this.show = function(lLevel, lmsg) 
	{
		if (!lmsg)			// display queue if not empty. Then clear queue
		{ 
			if (msg.length > 0) alert(msg);		
			msg = "";
		}
		else if (lLevel <= this.iDebug) alert(lmsg);	// display direct message
	}	
	
	this.setLevel = function(level)
	{
		this.iDebug = level;
	}
	
	this.getLevel = function()
	{
		return this.iDebug;
	}	
};	

// Create the Object 
var WT_Track = new dsiWTTrackItem();
// WT_Track.Debug.setLevel(4);
