﻿//  ************************************************************************************************
//	Name: URLTrackingForAdClick.js
//	Location: /Includes [on Tenzing and CanadaWebHosting.com sites (tentative)]
//	Author: Harsh Naik
//	Creation Date: 13-May-2009
//	DB Interaction: No
//	Type: Include
//	Description: It provides functionality to grab advertisement URL parameters from any page in site 
//				  and prepare them for CRM compitable format. This is used for HTML pages. This is a javascript
//                replica file of URLTrackingForAdClick.asp                
//	************************************************************************************************

var nCookieInterval = 3; //duration to keep cookie on client machine (in months)
var sCookieName = "CWHAdTrack";

var arrAdVariables = new Array(7);

//0-query string name
//1-session name/Cookie key name
//2-CRM mail name
//3-value
//4-validation reg exp
//5-isMandatory? (1 - mandatory, 0 - optioal)
//6-place holder value (use this value when there is no valid value found in query string/cookie)
//						        0				1					2					3	4								5		6
arrAdVariables[0] = new Array("utm_source",		"AD_UTM_SOURCE",	"crm_utm_source",	"",	"^(([a-zA-Z]{2})+([0-9]{4}))$",	"1",	"OG0000");
arrAdVariables[1] = new Array("utm_group",		"AD_UTM_GROUP",		"crm_utm_group",	"",	"^([0-9]){3}$",					"0",	"000");
arrAdVariables[2] = new Array("utm_ad",			"AD_UTM_AD",		"crm_utm_ad",		"",	"^([0-9]){2}$",					"0",	"00");
arrAdVariables[3] = new Array("utm_word",		"AD_UTM_WORD",		"crm_utm_word",		"",	"^([0-9a-zA-Z\s]){1,100}$",		"0",	"Z");
arrAdVariables[4] = new Array("utm_medium",		"AD_UTM_MEDIUM",	"crm_utm_medium",	"",	"^([A-Z]){1,3}$",				"0",	"ZZZ");
arrAdVariables[5] = new Array("utm_campaign",	"AD_UTM_CAMPAIGN",	"crm_utm_campaign",	"",	"^([0-9]){3}$",					"0",	"000");
arrAdVariables[6] = new Array("utm_content",	"AD_UTM_CONTENT",	"crm_utm_content",	"",	"^([0-9]){2}$",					"0",	"00");
arrAdVariables[7] = new Array("utm_term",		"AD_UTM_TERM",		"crm_utm_term",		"",	"^([0-9a-zA-Z\s\-]){1,100}$",	"0",	"Z");

var bAdParametersExist, bAdURLUsable;

// Check whether defined URL parameters are there in URL or not, if not then user is not coming from Ad link or values already taken

AdVarExist()

if (bAdParametersExist)
{
    //Get data
	GetAdWordsValues()
	
	//Validate data
	ValidateAdWordsValues()
	
	if (bAdURLUsable)
	{
	    //add new values to the cookie
		SetCookieForAd()
	}
	else
	{
	    //Not doing anything in this case.
	    //SendMailForIncorrectAdURL()
	}
}
else
{
    //No need to do anything - user might be coming directly or broken URL or tracking values already stored to session/cookie
}

//----------------------------------------------------
//Functions and Subroutines

function isArray(obj) 
{
    if (obj == null) return false;
    return obj.constructor == Array;
}

function querystring(name)   // returns a named value from the querystring
{
   var tmp = ( location.search.substring(1) );
   var i   = tmp.toUpperCase().indexOf(name.toUpperCase()+"=");

   if ( i >= 0 )
   {
      tmp = tmp.substring( name.length+i+1 );
      i = tmp.indexOf("&");
      return unescape( tmp = tmp.substring( 0, (i>=0) ? i : tmp.length ));
   }

   return("");
}

function ThisInThis(sString, sStringToBeSearched)
{
    if(sString=='' || sStringToBeSearched == '')
        return false;
    
    if (sString.indexOf(sStringToBeSearched) >= 0)
        return true;
    else    
        return false;
}


function GetAdWordsValues()
{
    //Description:
	//This sub routine gets the value for an ad parameter from query string, 
    //validates it and stores in "value" field of the arrAdVariables array.
	//If no valid values found then it stores default value

    if (isArray(arrAdVariables))
    {
        var i, sTempVal;
        for(i=0;i<arrAdVariables.length;i++)
        {
            sTempVal = querystring(arrAdVariables[i][0]);
            if (ValidateValue_Ad(sTempVal,arrAdVariables[i][4]))
                arrAdVariables[i][3] = sTempVal;
            else
                arrAdVariables[i][3] = arrAdVariables[i][6];
           
           sTempVal = ""
        }
    }
}

function SetCookieForAd()
{
    //Description:
	//This sub routine sets the cookie for storing ad parameter values.
	//The cookie is set to expire after given months (defined by nCookieInterval constant)
	
	var strCookieInformation = "";
	var dtCookieExpiryDate = new Date();
	
	if (isArray(arrAdVariables))
    {
        var i, nInterval;
        dtCookieExpiryDate.setMonth(new Date().getMonth() + nCookieInterval);
        for(i=0;i<arrAdVariables.length;i++)
        {
            if(strCookieInformation != "")
            {
                strCookieInformation = strCookieInformation + "&" + arrAdVariables[i][1] + "=" + arrAdVariables[i][3];
            }
            else
            {
                strCookieInformation = arrAdVariables[i][1] + "=" + arrAdVariables[i][3];
            }
            //document.cookie = arrAdVariables[i][1] + '=' + arrAdVariables[i][3] + 'expires=' + dtCookieExpiryDate;
        }
        //document.cookie = sCookieName + '=' + escape(strCookieInformation) + ';expires=' + dtCookieExpiryDate;
        document.cookie = sCookieName + '=' + strCookieInformation + ';expires=' + dtCookieExpiryDate;
    }
}


function SetCookieForDirectNeed(sValueString)
{
    //Description:
	//This sub routine sets the cookie from given values. Used mainly for special event promotion tracking.
	//E.g. - SetCookieForDirectNeed "WE0001,000,00,Z"
	//The cookie is set to expire after 1 hour.
	
	var arrVals;
	var strCookieInformation = "";
	var dtCookieExpiryDate = new Date();
	if (sValueString != "")
	{
	    arrVals = sValueString.split(",");
	    if (isArray(arrVals) && isArray(arrAdVariables))
	    {
	        var i, sTempVal, bUseDefault;
	        dtCookieExpiryDate.setHours(new Date().getHours() + 1);
	        for(i=0;i<arrAdVariables.length;i++)
	        {
	            if (i <= arrVals.length)
	            {
	                sTempVal = arrVals[i];
	                if (!ValidateValue_Ad(sTempVal,arrAdVariables[i][4]))
	                {
	                    sTempVal = arrAdVariables[i][6];
	                }
	                bUseDefault = false;
	                //document.cookie = arrAdVariables[i][1] + '=' + sTempVal + 'expires=' + dtCookieExpiryDate;
	            }
	            else
	            {
	                bUseDefault = true;
	               //document.cookie = arrAdVariables[i][1] + '=' + arrAdVariables[i][6] + 'expires=' + dtCookieExpiryDate;
	            }
	            
	            if(strCookieInformation != "")
                {
                    strCookieInformation = strCookieInformation + "&" + arrAdVariables[i][1] + "=" + bUseDefault?arrAdVariables[i][6]:sTempVal;
                }
                else
                {
                 strCookieInformation = arrAdVariables[i][1] + "=" + bUseDefault?arrAdVariables[i][6]:sTempVal;
                }
	        }
	        //document.cookie = sCookieName + '=' + escape(strCookieInformation) + ';expires=' + dtCookieExpiryDate;
	        document.cookie = sCookieName + '=' + strCookieInformation + ';expires=' + dtCookieExpiryDate;
	    }
	}
}

function ValidateAdWordsValues()
{
    //Description:
    //This sub routine checks the stored values for ad parameters and sets bAdURLUsable flag.
    
    if(isArray(arrAdVariables))
    {
        var i;
        for(i=0;i<arrAdVariables.length;i++)
        {
            //if(bAdURLUsable=='')
            if (bAdURLUsable != false || bAdURLUsable != true)
                bAdURLUsable = ValidateValue_Ad(arrAdVariables[i][3],arrAdVariables[i][4]);
            else
                bAdURLUsable = bAdURLUsable && ValidateValue_Ad(arrAdVariables[i][3],arrAdVariables[i][4]);
        }
    }
}

function AdVarExist()
{
    //Description:
    //This sub routine checks whether mandatory parameters exist in URL's query string or not.
	//And accordingly set bAdParametersExist flag
	
	var sQueryStringFromURL;
	sQueryStringFromURL = location.search.substring(1);
	if (isArray(arrAdVariables))
	{
	    var i;
	    for(i=0;i<arrAdVariables.length;i++)
	    {
	        if(arrAdVariables[i][5] == "1")
	        {
	            if (bAdParametersExist != false || bAdParametersExist != true)
	            {
	                bAdParametersExist = ThisInThis(sQueryStringFromURL, arrAdVariables[i][0]);
	                
	            }
	            else
	            {
	                bAdParametersExist = bAdParametersExist && ThisInThis(sQueryStringFromURL, arrAdVariables[i][0]);
	            }
	        }
	    }
	}
}

function ValidateValue_Ad(sValue,sRegEx)
{
    //Description:
	//This function validates the value based on regular expression provided.
	
	if (sValue == '')
	    return false;
	if (sRegEx == '')
	    return true;
	
	var regEx = new RegExp(sRegEx);
	regEx.ignoreCase = false;
	regEx.global = false;
	
	if (sValue.search(regEx) == -1)
	    return false;
    else    
        return true;
}

//function SendMailForIncorrectAdURL()
//{
//    alert("For now alerting instead of sending an email");
//}

//function GetValueForAdVar(sCookieVarName)
//{
//    //Description:
//    //This function returns value of ad parameter from cookie.
//    
//    return readCookieVariable(readCookie(sCookieName),sCookieVarName);
//}


//function RebuildAdQueryString()
//{
//    //Description:
//	//This function returns query string with ad parameters
//	//It is called from DynamicProcessForm.asp
//}

//function RebuildAdQueryStringFromCookies()
//{
//	//Description:
//    //This function rebuilds query string with ad parameters using values stored in cookie.
//}

//function readCookie(name) 
//{
//	var nameEQ = name + "=";
//	var ca = document.cookie.split(';');
//	for(var i=0;i < ca.length;i++) {
//		var c = ca[i];
//		while (c.charAt(0)==' ') c = c.substring(1,c.length);
//		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
//	}
//	return null;
//}

//function readCookieVariable(c_name, c_par)
//{
//  if (document.cookie.length>0)
//  {
//    c_start=document.cookie.indexOf(c_name + "=");
//    if (c_start!=-1)
//    { 
//      c_start=c_start + c_name.length+1 ;
//      c_end=document.cookie.indexOf(";",c_start);
//      if (c_end==-1) c_end=document.cookie.length
// 
//			if (typeof(c_par) != "undefined") {
//		  	return getPar(c_par, unescape(document.cookie.substring(c_start,c_end)));
//		  } else {
//			  return unescape(document.cookie.substring(c_start,c_end));
//			}
//    } 
//  }
//  return ""
//}


