/**
 * Google AdWords and Yahoo! Search Marketing url parameters tracking.
 *
 * @author Yuriy Tumakha <tumakha@gmail.com>
 * @since August 18, 2005
 * @version 1.0
 */

var days = 90; //Days to expiration date of the cookie

      // 2005-11-02 Vichka
         tracking();

function tracking()
{
    if (queryParam('referral') != false) {
        createCookie('source', 'Google', days);
        param2cookie('referral');
        param2cookie('campaign');
        param2cookie('ad_group');
        param2cookie('keyword');
    } else
    // 2005-10-31 Vichka
    // change 'referral' >> 'refferal' (in query_string)
    if (queryParam('refferal') != false) {
        createCookie('source', 'Google', days);
        param2cookie('refferal','referral');
        param2cookie('campaign');
        param2cookie('ad_group');
        param2cookie('keyword');
    } else
    if (queryParam('source') != false) {
        param2cookie('source');
        param2cookie('kw','keyword');
    }
}

/**
 * Create a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [days]     Days to expiration date of the cookie
 */
function createCookie(name, value, days)
{
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    var ck = name+"="+value+expires+"; path=/";
    document.cookie = ck;
}

/**
 * Parsing query string
 */
function PageQuery(q) {
    if (q.length > 1) this.q = q.substring(1, q.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if (q) {
        for(var i=0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }

    this.getKeyValuePairs = function() {
        return this.keyValuePairs;
    }

    this.getValue = function(s) {
        for (var j=0; j < this.keyValuePairs.length; j++) {
            // 2005-10-31 Vichka
            // case-insensitive string comparison 
            if(this.keyValuePairs[j].split("=")[0].toLowerCase() == s.toLowerCase())
            return unescape(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 queryParam(key)
{
    var page = new PageQuery(window.location.search);
    return page.getValue(key);
}

function param2cookie(name, nameCookie)
{
    var value = queryParam(name);
               // 2005-10-31 Vichka
               // set other Cookie Name
    if (value) createCookie(nameCookie ? nameCookie : name, value, days);
}