
/*** Variables ***/
function PesTracker() {};
PesTracker._path = "/tracker";

var add_vars = new Array("promo_code","contact_id","tracker_client_id","vendor_id"); //variables from cookies
var extra_info = {}; // extra info set by the page
var req_params = {}; // request parameters in url

/*** Functions ***/

// default empty error handler for DWR
var notifyError = function(data){};

function getImageHandler(h) {
    var make_image_request  = function() {

        var s = convertToQueryString(h);
        var tImage = new Image();
        // TODO - remove hardcoded server name in image src
        tImage.src  = PesTracker._path + "/image/a.gif?" + s;
    };
    return make_image_request;

}

// get cookie values of variables in add_vars and put them in the hash
function addAdditionalVars(h) {
    for (i in add_vars) {

        c_val = getCookie(add_vars[i]);
        if (c_val!=null) {
            h[add_vars[i]] = c_val;
        }
    }
}

// function to construct global hashmap of request parameters;
function parseReqParams() {

    if (!req_params.parsed) {
        search = window.location.search;

        if (search != null && search != "") {
            param_string = search.split('?');
            param_array = param_string[1].split('&');
            for (i in param_array) {
                pair = param_array[i].split('=');
                req_params[pair[0]] = pair[1];
            }
        }
        req_params.parsed = true;
    }
}

// get page url
// for non PES pages this is the document.URL property
// For PES pages, get the page_name property, since the document.URL is not correct due to a forward on the server side
function getPageUrl(doc) {
    var page_url = doc.URL;
    if (doc.forms[0] != undefined) {
        if (doc.forms[0]["tracker_page_name"] != undefined) {
            var pes_page = doc.forms[0]["tracker_page_name"].value;
            if (typeof(pes_page) == "undefined") {
                page_url = doc.URL;
            } else if (pes_page == "") {
                page_url = doc.URL;
            } else {
                page_url = pes_page;
            }
        }
    }
    return page_url;
}

// increments the value of the cookie 'name' amd sets it
function incrementCookie(name) {
    count = getCookie(name);

    if (count == null) {
        count = 0;
    }
    count++;
    setCookie(name,count);
    return count;
}

// convert a map into a query string for a url
function convertToQueryString(h) {
    var s = "";
    for (key in h) {
        s += key + "=" + h[key] + "&";
    }
    return s;
}

// Flattens out a hash of hashes into a string of the form
// "label1:key1=value1,key2=value,;label2:key1=value1,key2=value2"
function flatten(bighash) {
    s = "";
    for (label in bighash) {
        s += label + ":";
        hash = bighash[label];
        for (k in hash) {
            s += k + "=" + hash[k] + ',';
        }
        s += ";";
    }
    return s;
}

// Get cookie value
function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return null;
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: /)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    var ExpireDate = new Date ();
    ExpireDate.setTime(ExpireDate.getTime() + (expires * 24 * 3600 * 1000));

    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + ExpireDate.toGMTString() : "") +
        ((path) ? "; path=" + path : "; path=/") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


// Store hash of hashes,
// label is app name thats storing the info eg 'PES', 'CATALOG'
// key is app_name like GLOBAL, PES, CATALOG and
// value is hashmap of key/values for the particular app
function addExtraInfo(label, key, value) {
    hash = extra_info[label];
    if ((typeof(hash) == undefined) || (hash == null)) {
        hash = new Object();
        extra_info[label] = hash;
    }
    hash[key] = value;
}

// Set a new onload func - thanks Scott!
function set_onload_func(new_func) {

    // preserve any existing onLoad function
    var old_onload_func = window.onload; // note the lack of ()

    // create a closure that combines the page's OLD (if any) with our NEW behavior
    var closure = {};
    if (old_onload_func == undefined || old_onload_func == null) {
        closure = function() { new_func(); }
    } else {
        var closure = function() { old_onload_func(); new_func(); }
    }

    // set the onload method to be our spiffy closure
    window.onload = closure;

}

// function called by the page to track itself
function logVisit() {

    var tracker_data = {}; // info sent to the logVisit function on the server

    // Get current page, referrer
    tracker_data["url"] = getPageUrl(document);
    tracker_data["ref_url"] = document.referrer;

    // check for additional variables set in cookies and add them to tracker_data
    addAdditionalVars(tracker_data);

    // increment tracker page count cookie
    tracker_data["tracker_count"] = incrementCookie("tracker_count");

    // Convert promo code from the url into a  cookie
    if (req_params["promo_code"]!=null) {
        setCookie("promo_code", req_params["promo_code"]);
    }

    // Add extra_info from the page to tracker_data
    tracker_data["extra_info"] = flatten(extra_info);

    // set Error handler function to send info as an Image request in case the ajax call fails.
    DWREngine.setErrorHandler(getImageHandler(tracker_data));

    // Send info to server
    UserTracker.log(tracker_data);

    // set empty error handler after image request
    DWREngine.setErrorHandler(notifyError);
}


// this function should be set as onClick handler for links that need to be tracked
// onClick=trackObject('somecontextcode',this,'somecontextcategory')
function trackObject(context_code,url,context_category) {

    var tracker_data = {}; // info sent to the logVisit function on the server

    // Get current page, referrer

    //if 'this' is an input field,  get action of the pes form
    if (url.type != null) {
        if (url.type == "submit") {
            f = get_pes_form();
            url = f.action;

        }
    }
    tracker_data["url"] = url.toString()+'-onClick';
    tracker_data["ref_url"] = document.url;

    // check for additional variables set in cookies and add them to tracker_data
    addAdditionalVars(tracker_data);

    // increment tracker page count cookie
    tracker_data["tracker_count"] = incrementCookie("tracker_count");

    // add context_code and context_category to tracker_data
    tracker_data["context_code"] = context_code.toString();
    tracker_data["context_category"] = context_category.toString();

    // Send info to server
    UserTracker.log(tracker_data);

    return false;
}

// CR 6698915 22-may-2008 SI - to support Omniture & Sun Startup Essentials
function copy_cookie_to_promo_code_cookie(cookie_name)
{
	var val = getCookie(cookie_name);
	setCookie("promo_code", val);
}

/* stuff to be done when this js file is loaded */

// set error handler for dwr
DWREngine.setErrorHandler(notifyError);

// Parse request parameters
parseReqParams();
