﻿ //<![CDATA[
 
 /*This is analytics code for setting custom utmv cookies based on the querystring variable "q". 

 1)The Google Analytics account number is set below.

 2)Note that this code has the Google page tracking code as well so you should not have additional      Google code linked on the same page as this script or you will have problems.It will be ideal to link this page to a template page.

 3) Testing for this will be to go to the test page with a query string value "q={test value}" and then ensure that the UTMV cookie has this value after visting the page. Final test will be to ensure that the data shows up on the Google account. The {test value} should be a ATC value of a Sales Force campaign.

 3)If you need to get campaign information from this code and add to registrations then set a 
   hidden input variable and set its value to the property "this.campaignName"

  Modified By: Nate Ramanan 06-10-2011*/
 
 //California Communities Google Hit Tracker: UA-4147743-2 
 this.gaaccountid='UA-4147743-2';
 
 /*
 *  @author:    Danny Ng
 *  @notes:     Free to use and distribute without altering this comment. Would appreciate a link back :)
 */
 
 gaCookies();
// Strip leading and trailing white-space
String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g, ''); }
 
// Check if string is empty
String.prototype.empty = function() {
    if (this.length == 0)
        return true;
    else if (this.length > 0)
        return /^\s*$/.test(this);
}
 
// Breaks cookie into an object of keypair cookie values
function crumbleCookie(c)
{
    var cookie_array = document.cookie.split(';');
    var keyvaluepair = {};
    for (var cookie = 0; cookie < cookie_array.length; cookie++)
    {
        var key = cookie_array[cookie].substring(0, cookie_array[cookie].indexOf('=')).trim();
        var value = cookie_array[cookie].substring(cookie_array[cookie].indexOf('=')+1, cookie_array[cookie].length).trim();

        keyvaluepair[key] = value;
    }

    if (c)
        return keyvaluepair[c] ? keyvaluepair[c] : null;

    return keyvaluepair;
}
 

function gaCookies()
{
    // Cookie syntax: domain-hash.unique-id.ftime.ltime.stime.session-counter
    var utma = function() {
        var utma_array;
		
        if (crumbleCookie('__utma'))
            utma_array =  crumbleCookie('__utma').split('.');
        else
            return null;
 
        var domainhash = utma_array[0];
        var uniqueid = utma_array[1];
        var ftime = utma_array[2];
        var ltime = utma_array[3];
        var stime = utma_array[4];
        var sessions = utma_array[5];
 
        return {
            'cookie': utma_array,
            'domainhash': domainhash,
            'uniqueid': uniqueid,
            'ftime': ftime,
            'ltime': ltime,
            'stime': stime,
            'sessions': sessions
        };
    };
 
    // Cookie syntax: domain-hash.gif-requests.10.stime
    var utmb = function() {
        var utmb_array;

        if (crumbleCookie('__utmb'))
            utmb_array = crumbleCookie('__utmb').split('.');
        else
            return null;
        var gifrequest = utmb_array[1];
 
        return {
            'cookie': utmb_array,
            'gifrequest': gifrequest
        };
    };
 
    // Cookie syntax: domain-hash.value
    var utmv = function() {
        var utmv_array;

        if (crumbleCookie('__utmv'))
            utmv_array = crumbleCookie('__utmv').split('.');
        else
            return null;
 
        var value = utmv_array[1];
 
        return {
            'cookie': utmv_array,
            'value': value
        };
    };
 
    // Cookie syntax: domain-hash.ftime.?.?.utmcsr=X|utmccn=X|utmcmd=X|utmctr=X
    var utmz = function() {
        var utmz_array, source, medium, name, term, content, gclid;

        if (crumbleCookie('__utmz'))
            utmz_array = crumbleCookie('__utmz').split('.');
        else
            return null;
 
        var utms = utmz_array[4].split('|');
        for (var i = 0; i < utms.length; i++) {
            var key = utms[i].substring(0, utms[i].indexOf('='));
            var val = decodeURIComponent(utms[i].substring(utms[i].indexOf('=')+1, utms[i].length));
            val = val.replace(/^\(|\)$/g, '');  // strip () brackets
            switch(key)
            {
                case 'utmcsr':
                    source = val;
                    break;
                case 'utmcmd':
                    medium = val;
                    break;
                case 'utmccn':
                    name = val;
                    break;
                case 'utmctr':
                    term = val;
                    break;
                case 'utmcct':
                    content = val;
                    break;
                case 'utmgclid':
                    gclid = val;
                    break;
            }
        }
 
        return {
            'cookie': utmz_array,
            'source': source,
            'medium': medium,
            'name': name,
            'term': term,
            'content': content,
            'gclid': gclid
        };
    };
 
        // Establish public methods
 
    // utma cookies
    this.getDomainHash = function() { return (utma() && utma().domainhash) ? utma().domainhash : null };
    this.getUniqueId = function() { return (utma() && utma().uniqueid) ? utma().uniqueid : null };
 
    this.getInitialVisitTime = function() { return (utma() && utma().ftime) ? utma().ftime : null };
    this.getPreviousVisitTime = function() { return (utma() && utma().ltime) ? utma().ltime : null };
    this.getCurrentVisitTime = function() { return (utma() && utma().stime) ? utma().stime : null };
    this.getSessionCounter = function() { return (utma() && utma().sessions) ? utma().sessions : null };
 
    // utmb cookies
    this.getGifRequests = function() { return (utmb() && utmb().gifrequest) ? utmb().gifrequest : null };
 
    // utmv cookies
    this.getUserDefinedValue = function () { return (utmv() && utmv().value) ? decodeURIComponent(utmv().value) : null };
 
    // utmz cookies
    this.getCampaignSource = function () { return (utmz() && utmz().source) ? utmz().source : null };
    this.getCampaignMedium = function () { return (utmz() && utmz().medium) ? utmz().medium : null };
    this.getCampaignName = function () { return (utmz() && utmz().name) ? utmz().name : null };
    this.getCampaignTerm = function () { return (utmz() && utmz().term) ? utmz().term : null};
    this.getCampaignContent = function () { return (utmz() && utmz().content) ? utmz().content : null };
    this.getGclid = function () { return (utmz() && utmz().gclid) ? utmz().gclid : null };
    
}

//***************

    function read_cookie(cookie_name) {
      var my_cookie=""+document.cookie;
      var ind=my_cookie.indexOf(cookie_name);
      if (ind==-1 || cookie_name=="") return ""; 
      var ind1=my_cookie.indexOf(';',ind);
      if (ind1==-1) ind1=my_cookie.length; 
      return unescape(my_cookie.substring(ind+cookie_name.length+1,ind1));
    }
    //Customized function to set utmv value which is present in the querystring as "q"
    this.GetUpdatedUtmvValue = function () {
       var appendValue = getQuerystring("q", "");
       var newVar = "";
       var getVar = this.getUserDefinedValue();  
       var hasValue = -1;
       if (getVar != null)
            getVar = getVar.split("1=q=")[1].split("=")[0] ;
       else
            getVar="";
            
       hasValue = getVar.indexOf(appendValue);  
      if ( hasValue == -1 &&  appendValue !="") 
      {
      var length = getVar.length;
      if (length > 45)
      {
        var campArr = getVar.split("|");
        var newVal = "";
        if (campArr.length >1)
        {
             len=campArr.length; 
            for (var i=1;i<len;i++){
                if (i==1)
                    newVal = campArr[i];
                else
                    newVal = newVal + "|" + campArr[i];            
                
            }
        }
        getVar = newVal; 
      }
        if (  getVar!="")
            getVar = getVar + "|";                      
        newVar = getVar  + appendValue; // append the value
      }
     return newVar ;     
    }
    function getQuerystring(key, default_)
    {
      if (default_==null) default_=""; 
      key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
      var qs = regex.exec(window.location.href);
      if(qs == null)
        return default_;
      else
        return qs[1];
    }
    function superSetVar(appendValue) {
      var getVar = read_cookie('__utmv');       // read the __utmv cookie
      hasValue = getVar.indexOf(appendValue);   // does the cookie already have the value we want to append?
      if ( hasValue == -1 ) {                   // if the new value is not already in the cookie
        removePrefix = /^.*\.(.*)/.exec(getVar);  // __utmv cookie has the format 12345678.cookieValue - remove the ## prefix
        if (removePrefix && removePrefix[1]) {
          newVar = removePrefix[1] + appendValue; // append the value
        }else{
          newVar = appendValue;                 // this will execute if the cookie was not already set.
        }
          var superSetVarTracker = _gat._getTracker("UA-1-1");  // set up a tracker to call _setVar from          
          superSetVarTracker._initData();  
          superSetVarTracker._setVar(newVar);                   // call _setVar with the new value
      }
    }

    function unSetVar(removeValue){
      var getVar = read_cookie('__utmv');         // read the __utmv cookie
      hasValue = getVar.indexOf(removeValue);     // does the cookie have the value we want to remove?
      if ( hasValue != -1 ) {                     // if the value is in the cookie then . . .  otherwise, there is nothing further to do.
        removePrefix = /^.*\.(.*)/.exec(getVar);  // __utmv cookie has the format 12345678.cookieValue - remove the ## prefix
        if (removePrefix && removePrefix[1]) {    // if we remove the prefix then. . .
          //
          var re = removeValue + '[^/]*';
          re = new RegExp(re,'g');
          newVar = removePrefix[1].replace(re,""); // newVar = removePrefix[1] MINUS removeValue
          //
          var superSetVarTracker = _gat._getTracker("UA-1-1");  // set up a tracker to call _setVar from
          superSetVarTracker._initData();  
          superSetVarTracker._setVar(newVar);                   // call _setVar with the new value
        }
        
      }
    }
      var _gaq = _gaq || [];
     _gaq.push(['_setAccount', gaaccountid]);
    this.campaignName=GetUpdatedUtmvValue(); 
 
     if (campaignName!='') {
         _gaq.push(['_setCustomVar', 1, 'q', campaignName, 1]);
     }
     
     (function () {
         var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
         ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
         var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
     })();
     
     //]]>  





