//<![CDATA[

/****************************************************************
* File:	genCookies.js
*
* Author:	Chris Rodbourne
*
* Date:		2006-01-30
*
* Purpose:	To allow the genericform (or any other script) to backfill form on loading and save
*			form value data on submission for later back-filling again.
*
* Use:		1. Call gcBackFill on page load (<BODY onLoad="gcBackFill();">)
*			2. On Submission call gcStoreFormData(XXX) where XXX is the form's name
*
* Mods:		CPR 20070215 - Added URL parser useful full pulling args from requests
*
****************************************************************/

/******* CONSTANTS *******/

var	gcLHSData;
var gcRHSData;

/****************************************************************
*
* Function:		gcBackFill
*
* Purpose:		Called on onLoad in BODY tag - to see if cookie is set and if so
*				backfill any fields in the form from the cookie values
*
* Params:		The form name, e.g. "genericform"
*
* Returns:		Nothing
*
*****************************************************************/
function gcBackFill(formname)
{
	var cookieData = GetCookie("gcFormData");
	if (cookieData != null)
	{
		var gcCookieData = cookieData.split("###");
		if (gcCookieData.length)
		{
			gcLHSData = gcCookieData[0].split(":::");
			gcRHSData = gcCookieData[1].split(":::");

			var formRef = document.forms[formname];

			for (var i = 0; i < formRef.elements.length; i++)
			{
				var xel = formRef.elements[i];

				if (xel.type == "text" || xel.type == "checkbox" || xel.type == "textarea" || xel.type == "select-one" || xel.type == "radio")
				{
					for (j = 0; j < gcLHSData.length; j++)
					{
						var theName = CleanName(gcLHSData[j].toLowerCase());				// Remove punctuation etc
						if (theName == xel.name.toLowerCase())
						{
							if (xel.type == "text" || xel.type == "textarea")
							{
								xel.value = gcRHSData[j];
							} else if (xel.type == "checkbox" && (gcRHSData[j] == "checked" || gcRHSData[j] == "1" || gcRHSData[j] == "on" || gcRHSData[j] == "yes" || gcRHSData[j] == "Yes")) {
								xel.checked = true;
							} else if (xel.type == "select-one") {
								xel.selectedIndex = gcRHSData[j];
							} else if (xel.type == "radio") {
								if (gcRHSData[j] == xel.value)
								{
									xel.checked = true;
								}
							}
						}
					}
				}
				else
				{
					if (xel.type != "hidden" && xel.type != "submit" && xel.type != "select-multiple")
					{
						alert("gcBackFill: Invalid question type - not handled - " + xel.type);
						break;
					}
				}
			}
		}
	}
	return true;
}


/****************************************************************
*
* Function:		gcStoreFormData
*
* Purpose:		Called on form submission to store form data in cookie
*				NOTE: We merge form results with existing cookie values (to not lose data from other forms)
*
* Params:		The form name, e.g. "genericform"
*
* Returns:		Nothing
*
*****************************************************************/
function gcStoreFormData(formname)
{
	var LHS = "";
	var RHS = "";
	var formRef = document.forms[formname];

	for (j = 0; j < formRef.elements.length; j++)			// Add all form elements directly into Cookie String
	{
		var xel = formRef.elements[j];						// Get form type and check it's one to save!

		if (xel.type == "text" || xel.type == "checkbox" || xel.type == "textarea" || xel.type == "select-one" || xel.type == "radio")
		{
			var validatedName = CleanName(xel.name.toLowerCase());
			LHS = LHS + validatedName + ":::";

			if (xel.type == "text" || xel.type == "textarea")
			{
				RHS = RHS + xel.value;
			} else if (xel.type == "checkbox" && xel.checked) {
				RHS = RHS + "checked";
			} else if (xel.type == "select-one") {
				RHS = RHS + xel.selectedIndex;
			} else if (xel.type == "radio") {

				if (xel.checked)
				{
					RHS = RHS + xel.value;
				}
			}
			RHS = RHS + ":::";
		} else {
			if (xel.type != "hidden" && xel.type != "submit" && xel.type != "select-multiple")
			{
				alert("gcStoreFormData: Invalid question type - not handled - " + xel.type);
				break;
			}
		}
	}

	if (gcLHSData != null)
	{
		for (j = 0; j < gcLHSData.length; j++)
		{
			var found = false;
			for (i = 0; i < formRef.elements.length; i++)		// and if not just updated by form values then copy old values
			{
				var xel = formRef.elements[i];
				if (xel.name.toLowerCase() == gcLHSData[j].toLowerCase())
				{
					found = true;
				}
			}
			if (!found)
			{
				LHS = LHS + gcLHSData[j] + ":::";
				RHS = RHS + gcRHSData[j] + ":::";
			}
		}
	}

	LHS = LHS.substring(0, LHS.length - 3);					// Truncate trailing colons
	RHS = RHS.substring(0, RHS.length - 3);

	var gcCookieSet = LHS + "###" + RHS;

	SetCookie("gcFormData", gcCookieSet, 1000);

	return true;
}


/****************************************************************
*
* Function:		CleanName
*
* Purpose:		Remove punctuation characters etc etc from the single name passed
*
* Params:		The field name from the generic form (may include punctuation)
*
* Returns:		The cleaned name
*
*****************************************************************/
function CleanName(theName)
{
	var output = '';
	var valid="123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";

    for (var i = 0; i < theName.length; i++)
	{
		if (valid.indexOf(theName.charAt(i)) != -1)
		{
         	output += theName.charAt(i);
		}
	}

	return output;
}


/****************************************************************/
function GetCookie(name)
{
	var arg = name + "=";  
	var alen = arg.length;  
	var clen = document.cookie.length;  
	var i = 0;  
	while (i < clen)
	{
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg)      
			return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	}
	return null;
}

/****************************************************************/
function getCookieVal(offset)
{  
	var endstr = document.cookie.indexOf (";", offset);  
	if (endstr == -1)    
	endstr = document.cookie.length;  
	return unescape(document.cookie.substring(offset, endstr));
}

/****************************************************************/
function SetCookie(name, value)
{
	if (value == '<tmpl_var name="crmvars">') return;

	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;  
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;  

	var expDays = expires;
	var exp = new Date(); 
	exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

	document.cookie = name + "=" + escape (value) + 
	((expires == null) ? "" : ("; expires=" + exp.toGMTString())) + 
	((path == null) ? "" : ("; path=" + path)) +  
	((domain == null) ? "" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

/****************************************************************/
function DeleteCookie (name)
{  
	var exp = new Date();  
	exp.setTime (exp.getTime() - 1);  
	var cval = GetCookie (name);  
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

/****************************************************************/


/****************************************************************/
// getLocationArgs - Get the string that follows the "?" in the window's location.
/****************************************************************/

var GETDATA = new Array();

function getLocationArgs(sGet)
{
	if (sGet) // if has a value...
	{
		sGet = sGet.substr(1);						// Drop the leading "?"
											    	// Generate a string array of the name value pairs.
		var sNVPairs = sGet.split("&");				// Each array element will have the form "foo=bar"
    
		for (var i = 0; i < sNVPairs.length; i++)	// Now, for each name-value pair, we need to extract the name and value.
		{
			var sNV = sNVPairs[i].split("=");		// So, sNVPairs[i] contains the current element...  Split it at the equals sign.
        
			var sName = sNV[0];						// Assign the pair to the GETDATA array.
	        var sValue = sNV[1];
			GETDATA[sName] = sValue;
    	}
	}
}


//]]>
