﻿// JScript File

/*  
    Brian Feucht
    03/07/2008
    Parse GA Cookie for campaign variables
*/

/* 
    Function to populate form fields with cookie variables
    For this to work we need three hidden form fields for each variable
    Pass the function the prefix of the name
    The function will populate fields with id prefix + utm_campaign, prefix + utm_medium, prefix + utm_source
 */

function populateGAFields(prefix)
{
    /* Begin http://www.epikone.com/blog/2007/10/29/integrating-google-analytics-with-a-crm/ code */
    /* Parse Google Analyitcs Cookie*/
    var z = _uGC(document.cookie, '__utmz=', ';'); 
    var source  = _uGC(z, 'utmcsr=', '|'); 
    var medium  = _uGC(z, 'utmcmd=', '|'); 
    var term    = _uGC(z, 'utmctr=', '|'); 
    var content = _uGC(z, 'utmcct=', '|'); 
    var campaign = _uGC(z, 'utmccn=', '|'); 
    var gclid   = _uGC(z, 'utmgclid=', '|'); 

    if (gclid !="-") { 
          source = 'google'; 
          medium = 'cpc'; 
    } 
    /* End http://www.epikone.com/blog/2007/10/29/integrating-google-analytics-with-a-crm/ code */

    if ( campaign != "-"){ document.getElementById(prefix + "utm_campaign").value =  campaign;}
    if ( source != "-"){ document.getElementById(prefix + "utm_source").value = source;}
    if ( medium != "-"){ document.getElementById(prefix + "utm_medium").value = medium;}
}

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;
}

