/* Code provided by SwellPath: http://www.swellpath.com/02/2011/add-google-analytics-data-to-zoho-lead-forms/ */
/* if there is a trackmaster class form check to see if there are tracking elements in it */
/* if not create them.  Regardless parse the cookie and populate the elements */
/* this could be abstracted further to a function that takes a class name, so that, say,
 * all "wpcf7-form" class forms go through this 
 */

if($('form.trackmaster').length > 0){
	/* taken from http://cutroni.com/blog/2007/10/29/integrating-google-analytics-with-a-crm/ */
	function _uGC(l,n,s) {
		if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
		var i,i2,i3,c="-";
		i=l.indexOf(n);
		i3=n.indexOf("=")+1;
		if (i > -1) {
		i2=l.indexOf(s,i); if (i2 < 0) { i2=l.length; }
		c=l.substring((i+i3),i2);
		}
		return c;
	}
	var zString = _uGC(document.cookie, '__utmz=', ';');
	/* end taken */
	/* make sure there is a parsed cookie before we bother */
	if(zString.length > 0){
	/*wrap _uGC to be useful to the checkNCreate */ 
	function getuGC(zString,dtype){
		return _uGC(zString,dtype + '=','|');
	}
	/* if the required elements don't exist, add them */
	/* then assign their values by calling the above*/
	function checkNCreate(zString,formLabel,cookieLabel){
		if($('form.trackmaster input[name=' + formLabel + ']').length==0){
		$('form.trackmaster').prepend('<input  id="' + formLabel + '" name="' + formLabel + '" type="hidden" value="" />');
		} 
		$('form.trackmaster input#' + formLabel).val(getuGC(zString,cookieLabel));
		
	}
	/* add what we need to the form */
	checkNCreate(zString, 'LEADCF5','utmcsr'); /* source */
	checkNCreate(zString, 'LEADCF6','utmcmd'); /* medium */
	checkNCreate(zString, 'LEADCF9','utmctr'); /* term */
	checkNCreate(zString, 'LEADCF8','utmcct'); /* content */
	checkNCreate(zString, 'LEADCF7','utmccn'); /* campaign */
	/*checkNCreate(zString, '00NA0000001xYUI','utmclid'); */ /* gclid */
	}
}
