// globals

// user settings
var res = "www.copper.net/webServices/clickTracker/clickTracker.aspx";
var epi = ""; // extra page info
var pt = ""; // page type
var exp = ""; // session cookie expiration time in minutes (int)

var pInfo = ""; // page info (ie. "conversion" or "signup - step1")
var logQuerystrings = 0; // keep the querystring at the end of page references (0 or 1)


// constants
var __SESSIONID = "__ctsid";
var __MEDIUM = "__ctm";
var __HOST = "__cth";
var __PAGE = "__ctp";
var __PAGEINFO = "__ctpi";
var __KEYWORD = "__ctkw";
var __REFERRELHOST = "__ctrh";
var __REFERRELPAGE   = "__ctrp";
var __REFERRELTERMS  = "__ctrt";


// querystring values to check for keywords
var _keywordNames = new Array();
_keywordNames[0] = "kw";
_keywordNames[1] = "ovraw";


//-- Auto/Organic Sources and Keywords
var _organicSources = new Array();
var _organicKeywords = new Array();

_organicSources[0] = "google";          _organicKeywords[0] = "q";
_organicSources[1] = "yahoo";           _organicKeywords[1] = "p";
_organicSources[2] = "msn";             _organicKeywords[2] = "q";
_organicSources[3] = "aol";             _organicKeywords[3] = "query";
_organicSources[4] = "aol";             _organicKeywords[4] = "encquery";
_organicSources[5] = "lycos";           _organicKeywords[5] = "query";
_organicSources[6] = "ask";             _organicKeywords[6] = "q";
_organicSources[7] = "altavista";       _organicKeywords[7] = "q";
_organicSources[8] = "netscape";        _organicKeywords[8] = "query";
_organicSources[9] = "cnn";             _organicKeywords[9] = "query";
_organicSources[10] = "looksmart";      _organicKeywords[10] = "qt";
_organicSources[11] = "about";          _organicKeywords[11] = "terms";
_organicSources[12] = "mamma";          _organicKeywords[12] = "query";
_organicSources[13] = "alltheweb";      _organicKeywords[13] = "q";
_organicSources[14] = "gigablast";      _organicKeywords[14] = "q";
_organicSources[15] = "voila";          _organicKeywords[15] = "rdata";
_organicSources[16] = "virgilio";       _organicKeywords[16] = "qs";
_organicSources[17] = "live";           _organicKeywords[17] = "q";
_organicSources[18] = "baidu";          _organicKeywords[18] = "wd";
_organicSources[19] = "alice";          _organicKeywords[19] = "qs";
_organicSources[20] = "yandex";         _organicKeywords[20] = "text";
_organicSources[21] = "najdi";          _organicKeywords[21] = "q";
_organicSources[22] = "aol";            _organicKeywords[22] = "q";
_organicSources[23] = "club-internet";  _organicKeywords[23] = "q";
_organicSources[24] = "mama";           _organicKeywords[24] = "query";
_organicSources[25] = "seznam";         _organicKeywords[25] = "q";
_organicSources[26] = "search";         _organicKeywords[26] = "q";
_organicSources[27] = "szukaj";         _organicKeywords[27] = "szukaj";
_organicSources[28] = "szukaj";         _organicKeywords[28] = "qt";
_organicSources[29] = "netsprint";      _organicKeywords[29] = "q";
_organicSources[30] = "google.interia"; _organicKeywords[30] = "q";
_organicSources[31] = "szukacz";        _organicKeywords[31] = "q";
_organicSources[32] = "yam";            _organicKeywords[32] = "k";
_organicSources[33] = "pchome";         _organicKeywords[33] = "q";



// Querystring Functions
function PageQuery(q)
{
    if(q.length > 1)
        q = q.substring(1, q.length);
    else
        q = null;
    
    this.keyValuePairs = new Array();
    
    if(q)
    {
        for(var i=0; i < q.split("&").length; i++)
        {
            this.keyValuePairs[i] = q.split("&")[i];
        }
    }
    
    this.getKeyValuePairs = function() { return this.keyValuePairs; }
    
    this.getValue = function(s)
    {
        for(var j=0; j < this.keyValuePairs.length; j++)
        {
            if(this.keyValuePairs[j].split("=")[0].toLowerCase() == s.toLowerCase())
                return this.keyValuePairs[j].split("=")[1];
        }
        
        return false;
    }

    this.getParameters = function()
    {
        var a = new Array(this.getLength());
        for(var j=0; j < this.keyValuePairs.length; j++)
        {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        
        return a;
    }
    
    this.getLength = function() { return this.keyValuePairs.length; } 
}

function queryString(key)
{
    var page = new PageQuery(window.location.search); 
    
    return unescape(page.getValue(key)); 
}

// Cookie functions
function setSessionCookie(cookieName, cookieValue)
{
    document.cookie = cookieName + "=" + escape(cookieValue);
}

function setCookie(cookieName, cookieValue, timeToExpireInMinutes)
{
    var date = new Date();
    
    date.setMinutes(date.getMinutes() + timeToExpireInMinutes);
    document.cookie = cookieName + "=" + escape(cookieValue) + "; expires=" + date.toGMTString();
}

function deleteCookie(cookieName)
{
    document.cookie = cookieName + "= ; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

function getCookieValue(cookieName)
{
    var exp = new RegExp(escape(cookieName) + '=([^;]+)');

    if(exp.test(document.cookie + ';'))
    {
        exp.exec(document.cookie + ';');
        return unescape(RegExp.$1);
    }
    else
        return null;
}

// GUID functions
function generateGuid()
{
    var result, i, j;
    
    result = '';
    for(j=0; j<32; j++)
    {
        if(j == 8 || j == 12 || j == 16 || j == 20)
            result = result + '-';
        
        i = Math.floor(Math.random()*16).toString(16).toUpperCase();
        result = result + i;
    }
    
    return result;
}

function S4()
{
    return ( ( ( 1+Math.random() ) * 0x10000 ) | 0 ).toString(16).substring(1);
}

function generateGuid2()
{
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()).toUpperCase();
}


// main
function clickTracker()
{
    var req = document.location.protocol + "//" + res;

    var sid = getCookieValue("ctsid");
    if(!sid)
    {
        sid = generateGuid2();
        if(exp != null && exp != "")
            setCookie("ctsid", sid, exp);
        else
            setSessionCookie("ctsid", sid);
    }
    var qs = "?sid=" + sid;

    if(epi && epi != "")
        qs = qs + "&epi=" + epi;
    

    if(pt && pt != "")
        qs = qs + "&pt=" + pt;
    

    var i = new Image(1,1);
    i.src = req + qs;
    i.onload=function() { doNothing(); }
}

function doNothing() { return; }

function pageClick()
{
    var req = document.location.protocol + "//" + "www.copper.net/webServices/clickTracker/pageclick.aspx?" + __SESSIONID + "=" + _getSessionID() + "&" + _buildInfoString();
    
    //alert(req);
    var i = new Image(1,1);
    i.src = req;
    i.onload=function() { doNothing(); }
}

function _getSessionID()
{
    var id = getCookieValue(__SESSIONID);
    
    if(!id)
    {
        id = Math.round(Math.random() * 2147483647) ^ Math.round((new Date).getTime() / 1000);
        
        if(exp && exp != "")
            setCookie(__SESSIONID, id, exp);
        else
            setSessionCookie(__SESSIONID, id);
    }
    
    return id;
}

function _buildInfoString()
{
    var ref = document.referrer,
        medium = "",
        keyword = "",
        refHost = "",
        refPage = "",
        refTerms = "",
        i = 0;
    
    for(var x = 0; x < _keywordNames.length; x++)
    {
        keyword = queryString(_keywordNames[x]);
        if(keyword != "false")
            break;
    }
        
    if(!ref || ref == "")
        medium = "direct";
    else if ((i = ref.indexOf("://")) > -1)
    {
        medium = "referrel";

        // strip "http(s)://"
        refHost = ref.substring(i + 3, ref.length);
        
        // get/set/strip path
        if((i = refHost.indexOf("index.html")) > -1)
        {
            refPage = refHost.substring(i, refHost.length);
            refHost = refHost.substring(0, i);
            
            // stip querystring from path
            if((i = refPage.indexOf("?")) > -1 && logQuerystrings == 0)
                refPage = refPage.substring(0, i);
        }
            
        // we're now left with just the host of the referrer, find which organicSource matches host
        for(var x = 0; x < _organicSources.length; x++)
        {
            if(refHost.toLowerCase().indexOf(_organicSources[x].toLowerCase()) > -1)
            {
                medium = "organic";
            
                // found host, now see if source's keyword is set
                if((i = ref.toLowerCase().indexOf("?" + _organicKeywords[x].toLowerCase() + "=")) > -1
                        || (i = ref.toLowerCase().indexOf("&" + _organicKeywords[x].toLowerCase() + "=")) > -1)
                {
                    // found keyword, set terms (skip over the keyword and the '=')
                    refTerms = ref.substring(i + _organicKeywords[x].length + 2, ref.length);
                    
                    // strip from '&' to end
                    if((i = refTerms.indexOf("&")) > -1)
                        refTerms = refTerms.substring(0, i);
                }
                
                break; // matched source, no need to continue
            }
        }
        
    }
    
    if(medium != "direct" && keyword != "false")
        medium += " (paid)";
    
    return __MEDIUM + "=" + medium
            + "&" + __HOST + "=" + document.domain
            + "&" + __PAGE + "=" + escape(document.location.pathname + (logQuerystrings == 0 ? "" : document.location.search))
            + "&" + __PAGEINFO + "=" + escape(pInfo)
            + "&" + __KEYWORD + "=" + (keyword == "false" ? "" : escape(keyword))
            + "&" + __REFERRELHOST + "=" + refHost
            + "&" + __REFERRELPAGE + "=" + escape(refPage)
            + "&" + __REFERRELTERMS + "=" + escape(refTerms);
}

// replaces ' ' (space) with '+'
function _encodeSpaces(s)
{
    var n = "";

    if (!s || s == "")
        return "";

    for (var i = 0; i < s.length; i++)
    {
        if (s.charAt(i) == " ")
            n += "+";
        else
            n += s.charAt(i);
    }

    return n;
}
