/**
   * Copyright(c) 2008 by Ramp, Inc.
   *   All Rights Reserved
   *   10 Fawcett Street
   *   Cambridge, MA  02138
   *   
   * Author:  rhughes
   * Created: Nov 20, 2008
   */
  


//Uuid creates a psuedo-UUID based on RFC4122.  It is not a strict 
//implementation of the RFC but rather a hybrid of  version 1 (time-based) 
//and the Version 4 (random-generation).
//The time-stamp portion of the UUID is generated using the system clock.
//All other fields are randomnly generated.

function Uuid() {
	this.id = this.generate();
}

Uuid.prototype.toString = function() {
	return this.id;
}

Uuid.prototype.generate = function() {

	//Number of 100-nanosecond intervals since Oct 15, 1582
	var time_now = new Date().getTime() ;
	var time_start = new Date(1582, 10, 15, 00, 00, 00).getTime() ;
	var time_interval = (time_now - time_start) * 10000 ;
	
	//Since we have only millisecond precision, add some random nanoseconds
	time_interval += Math.floor(Math.random() * 10000);

	var time_interval_hex = time_interval.toString(16);

	//extract low, middle and high parts of the time interval hex string
	var tlow = time_interval_hex.substr(7,8);
	var tmid = time_interval_hex.substr(3,4);
	var thi  = time_interval_hex.substr(0,3);

	//generate other fields
    var tver = '1';                   //time version=1
	var csh = this.randomHex(16);     //clock seq hi
	var csr = 'f';                    //clock seq reserved = 10xx
	var csl = this.randomHex(256,2);   //clock seq low
	var n1 =  this.randomHex(65536,4); //octets 10,11
	var n2 =  this.randomHex(65536,4); //octets 12,13
	var n3 =  this.randomHex(65536,4); //octets 14,15
	
	return tlow + '-' + tmid + '-' + tver + thi + '-' + csr + csh + csl + n1  + n2  + n3 ; 

}


Uuid.prototype.randomHex = function(max, padlength) {
	var randomnumber = Math.floor(Math.random() * max);
	var hexstr =  randomnumber.toString(16);

	if (typeof(padlength) == 'undefined')
		return hexstr;

	return this.padLeft(hexstr,padlength,'0');
}

Uuid.prototype.padLeft = function(str, padlength, padchar) {

	len = str.length;
	padding = padlength - len;
	if (padding > 0) {
		return Array(padlength + 1 - len).join(padchar) + str;
	}
	return str;
	
}

//--end Uuid


//get and set cookies.

function getCookie(name) {

   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function setCookie(name,value,expires,path,domain,secure) {
    var cookieString = name + "=" +escape(value) +
       ( (expires) ? "; expires=" + expires.toUTCString() : "") +
       ( (path) ? "; path=" + path : "") +
       ( (domain) ? "; domain=" + domain : "") +
       ( (secure) ? "; secure" : "");
    document.cookie = cookieString;
}

//end cookies


// visitor ID 
function setVisitorIdCookie() {

   var expire_date = new Date(new Date().getTime() + (8 * 7 * 86400000));
   var visitor_id = getCookie('EZSESSIONID');
   
   if (visitor_id == null || typeof(visitor_id) == null) {
   	 visitor_id = new Uuid();
   	}
   	
   setCookie('EZSESSIONID',visitor_id,expire_date,'/');
   //setCookie('EZSESSIONID',visitor_id,expire_date);
}

function getVisitorID() {
	setVisitorIdCookie();
	var VisitorID = getCookie('EZSESSIONID');
	return VisitorID;
}
// -- end visitor ID


Date.prototype.toDbTimeString = function () {

	shortYear = this.getYear();
	fullYear = shortYear % 100;
	fullYear += (fullYear < 38) ? 2000 : 1900;
	
	var dbString = 
		fullYear + '-' +
		(1 + this.getMonth()) + '-' +
		this.getDate() + ' ' +
		this.getHours() + ':' +
		this.getMinutes() + ':' +
		this.getSeconds();
		
	return dbString;
 
};

function EZTracker() {
}
if (typeof(EVERYZING) == "undefined") {
	EVERYZING = {};
//	EVERYZING.baseUrl = "http://publishing.ramp.com/";
// Changed 17 Feb 2010 AMH in hope of fixing tracking problem HIGH-66
}
if (typeof(EVERYZING.baseUrl) == "undefined") {
	/*
 http://stackoverflow.com/questions/2277978/get-the-url-of-currently-executing-js-file-when-dynamically-loaded
  http://stackoverflow.com/questions/2255689/how-to-get-the-file-path-of-the-currenctly-executing-javascript-code
 */
	var scripts = document.getElementsByTagName("script"),
	src = scripts[scripts.length-1].src;
	mat = src.match(/^http:\/\/[^\/]*\//);
      EVERYZING.baseUrl = mat;
}
EZTracker.prototype.host = EVERYZING.baseUrl+'tracking/track.jsp';

//track events using http post
EZTracker.prototype.sendTrackingData = function (eventData) {
	
	eventData.visitId = getVisitorID();
	eventData.timestamp = new Date().toDbTimeString();
	eventData.referrer = document.referrer;
	eventData.host = location.hostname;
	eventData.path = location.pathname;
	eventData.agent = (navigator.userAgent || navigator.appVersion);
	if (typeof(eventData.siteId) == 'undefined')
		eventData.siteId = 0;

	//send the event data to the server
	if (typeof(window["jQuery"]) == "undefined")
	{
		var client = xmlHttp();
		 
		 client.open("POST", this.host);
 		 client.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  		 client.send(objectToParams(eventData));
	}
	else
		jQuery.post(this.host, eventData );
  
}

//write out a tracking pixel appended to the given element
EZTracker.prototype.embedTrackingPixel = function (element, eventData) {
	
	eventData.visitId = getVisitorID();
	eventData.timestamp = new Date().toDbTimeString();
	eventData.referrer = document.referrer;
	eventData.host = location.hostname;
	eventData.path = location.pathname;
	eventData.agent = (navigator.userAgent || navigator.appVersion);
	if (typeof(eventData.siteId) == 'undefined')
		eventData.siteId = 0;
  		
        document.getElementById(element).innerHTML = '<img width="1" height="1" src="' 
  		+this.host+'?'
  		+objectToParams(eventData)
		+'"/>';
}



function xmlHttp()
{
	return (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
}

function trackParameters()
{
	var href = window.location.href;
	var splitQ = href.indexOf("?");
	
	var widgetData = new Object;
	
	if(splitQ > -1)
	{
		var paramPiece = href.substring(splitQ+1);
		var paramPieces = paramPiece.split("&");
		for(var i=0;i<paramPieces.length;i++)
		{
			var nameValuePair = paramPieces[i].split("=");
			if(nameValuePair.length==2)
				widgetData[nameValuePair[0]] = nameValuePair[1];
			
		}
	}
	var tracker = new EZTracker();
	tracker.sendTrackingData(widgetData);

}

function objectToParams(o)
{	
	var fullString = "";
	for (var key in o) {
		if(fullString.length > 0) fullString+="&";
  		fullString+=(key + "=" + escape(urlEncode("" + o[key])));
	}
	
	return fullString;
}

function urlEncode(string){
	
	string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
 }

