/****************************************************
Author: Brian J Clifton, fix by Lary Stucker-http://freshclicks.net, June 2008
Url: http://www.advanced-web-metrics.com
This script is free to use as long as this info is left in

Script for tracking the first and last referrer of a visitor

All scripts presented have been tested and validated by the author and are believed to be correct
as of the date of publication or posting. The Google Analytics software on which they depend is
subject to change, however; and therefore no warranty is expressed or implied that they will
work as described in the future. Always check the most current Google Analytics documentation.
 ****************************************************/

/********
 * And some help from
 * http://www.borism.net/2008/12/24/integrating-google-analytics-and-wufoo/
 */

function _uGC(l,n,s) {
    // used to obtain a value form a string of key=value pairs

    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;
}

function newVisitorCheck() {
    // check if this is a first time visitor
    newVisitor = 0;
    var myCookie = "" + document.cookie + ";";
    var searchName = "__utma=";
    var startOfCookie = myCookie.indexOf(searchName)
    if (startOfCookie == -1) {   // i.e. first time visitor
        newVisitor = 1;
    }

    return newVisitor;
}

function parseQueryString() {
    
    // get the current URL
    var url = window.location.toString();
    //get the parameters
    url.match(/\?(.+)$/);
    var params = RegExp.$1;
    // split up the query string and store in an
    // associative array
    params = params.split("&");
    var queryStringList = {};
 
    for(var i=0;i<params.length;i++)
    {
        var tmp = params[i].split("=");
        queryStringList[tmp[0]] = unescape(tmp[1]);
    }
    return queryStringList;
}

// grab campaign and referrer info from the _utmz cookie
function grabReferrer(){  
   
    var z = _uGC(document.cookie, "__utmz=", ";");
    var urchin = {
        source   : _uGC(z,"utmcsr=", "|"),
        medium   : _uGC(z,"utmcmd=", "|"),
        keyword  : _uGC(z,"utmctr=", "|"),
        content  : _uGC(z,"utmcct=", "|"),
        campaign : _uGC(z,"utmccn=", "|"),
        gclid    : _uGC(z,"utmgclid=", "|"), 
        toValueString : function() {
            var elms = [];
            var tagNames = ["source", "medium", "keyword", "content", "campaign"];
            for (var i = 0; i <  tagNames.length; i++){ 
                var tagName = tagNames[i];
                elms.push(this[tagName]);
            } 
            return elms.join("|");
        },
        toQueryString : function() {
            var elms = [];
            var tagNames = ["source", "medium", "keyword", "content", "campaign"];
            for (var i = 0; i <  tagNames.length; i++){ 
                var tagName = tagNames[i];
                var value = this[tagName];
                
                // returns false for "" or "-", but true anything that starts with [A-Za-z0-9_]
                if (/^\w+/.test(value)) 
                    elms.push(tagName + "=" + value); 
            } 
            return elms.join("&");
        }
    };
    
    //    
    // The gclid is ONLY present when auto tagging has been enabled. 
    // All other variables, except the term variable, will be '(not set)'. 
    // Because the gclid is only present for Google AdWords we can 
    // populate some other variables that would normally 
    // be left blank. 
    // 
    if (urchin.gclid !="-") { 
        urchin.medium = 'cpc';
        urchin.source = 'google';
    }  
    
    return urchin; 
    // pageTracker._setVar("init_ref-" + urchin_medium + "|" + urchin_source+ "|" + urchin_campaign + "|" + urchin_term); // expand initial referrer data to capture med,term, and source- LaryS
}
function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")?  false: true;
}

// Stores the current visit in the cookies. Allows for manually specifying a referrer.
function storeCurrentVisit(refid) {
    var referrer = grabReferrer();
    var params = parseQueryString();   

    if (!refid)
        refid = params["refid"]; 
     
    var currentValues = getCookie("_mbqs");
    var newValues = referrer.toValueString();
    
    // check if new visit
    // If there is a referrer_id, always track that as a visit.
    if (currentValues!=newValues || refid) {
        setCookie("_mbqs", newValues, 400); // 400 day long cookie
        var queryElms = [];
        
        // _refid --> referrer_id
        if (refid)
            queryElms.push("refid=" + refid);          
    
        var referrerQueryString = referrer.toQueryString();    
        if (referrerQueryString != "")
            queryElms.push(referrerQueryString);  
    
        // see tracking_system.rb        
        jQuery.get("/main/track_current_visit?" + queryElms.join("&"))
    }   
}

// path=/ is very important or else it will change between /account and /themes, etc...
function setCookie(key, value, expireDays) {
    var expireDate=new Date();
    expireDate.setDate(expireDate.getDate()+expireDays);
    
    document.cookie = key + "=" + escape(value) +
        ((expireDays==null) ? "" : ";expires=" + expireDate.toGMTString() + "; path=/");
}
// returns NULL if cookie doesn't exist.
function getCookie(key) { 
    var val = unescape(_uGC(document.cookie, key + "=", ";"));
    return (val=="-") ? null : val;
}
function deleteCookie(key) {
    setCookie(key, "", -1);
}

/*******
<script type="text/javascript">
checkFirst();        // checks if this is a new visitor// Moved to execute befire the _getTracker function- LaryS
var pageTracker = _gat._getTracker("UA-12345-1");
pageTracker._initData();
pageTracker._trackPageview();
grabReferrer();      // Grab referrer info
</script>
 ********/
