/*                                                                            
 * © 2007, World Evolved Services, LLC - PROPRIETARY AND CONFIDENTIAL -       
 * UNAUTHORIZED REPRODUCTION OR USE PROHIBITED                                  
 *                                                                              
 * This document contains proprietary and confidential information, and, except
 * as otherwise expressly stated herein, all information contained herein (the  
 * "Information") is and shall remain the sole and exclusive property of World  
 * Evolved Services, LLC (the "Company").  By reviewing the Information, you    
 * agree that such Information will be held confidential, and that you will not
 * disclose the same to any other persons, including, but not limited to,       
 * competitors and potential competitors of the Company.  You further agree not
 * to reproduce any of the Information without the prior written consent of the
 * Company.                                                                     
 */
/**
 * events.js
 * Canopy Event Tracking Script
 * @author James Kingsbery jkingsbery@reloadnyc.com
 */
var pageLoadTime;

/*
 * Constants
 */
var UNAVAILABLE="UNAVAILABLE"; // Used to indicate that the data was not available.
var UNMEASURED="UNMEASURED";  // Used to indicate we are not currently collecting this
var NOT_APPLICABLE="NOT-APPLICABLE";
var CORRUPTED="CORRUPT";

if (typeof(CANOPY_MOUSE_DEBUG) == "undefined") {
  var CANOPY_MOUSE_DEBUG = new Boolean(false);
}
if (typeof(sensorHost) == "undefined") {
  var sensorHost = "sensors.hq.reloadnyc.com";
}
if(typeof(CANOPY_MOUSE_OVERS)=="undefined"){
	var CANOPY_MOUSE_OVERS=new Boolean(false);
}

/**
 * Returns the client's browser name and version, e.g. Firefox 2
 */
function getBrowser(){
    if(dojo.isIE != undefined){
		return "Internet Explorer " + dojo.isIE;
	} else if(dojo.isFF != undefined){
		return "FireFox " + dojo.isFF;
	} else if(dojo.isMozilla != undefined){
		return "Mozilla " + dojo.isMozilla;
	} else if(dojo.isSafari != undefined){
		return "Safari " + dojo.isSafari;
	} else {
		return undefined;
	}
}

function Transaction(obj){
	this.eventType=obj.eventType;
	this.startTime=obj.startTime || NOT_APPLICABLE;
	this.applicationId=obj.applicationId || NOT_APPLICABLE;
	this.clientVersion=obj.clientVersion || NOT_APPLICABLE;
	this.pageTitle=obj.pageTitle || NOT_APPLICABLE;
	this.sessionId=obj.sessionId || NOT_APPLICABLE;
	this.userId=obj.userId || NOT_APPLICABLE;
	this.page=obj.page || NOT_APPLICABLE;
	this.weSessionId=obj.weSessionId || NOT_APPLICABLE;
	this.protocol = obj.protocol || NOT_APPLICABLE;	
	this.status=obj.status || NOT_APPLICABLE;			
		
	this.renderTime = obj.renderTime || NOT_APPLICABLE;	
	this.clientIP =obj.clientIP || NOT_APPLICABLE;	
	this.method = obj.method || NOT_APPLICABLE;
	this.requestSize = obj.requestSize || NOT_APPLICABLE;
	this.responseSize = obj.responseSize || NOT_APPLICABLE;

	this.referrer = obj.referrer || NOT_APPLICABLE;	

	this.acceptCharset=obj.acceptCharset || NOT_APPLICABLE;
	this.acceptEncoding=obj.acceptEncoding || NOT_APPLICABLE;
	this.acceptLanguage=obj.acceptLanguage || NOT_APPLICABLE;
	this.userAgent=obj.userAgent || NOT_APPLICABLE;
	this.locale = obj.locale || NOT_APPLICABLE;
	this.screenHeight=obj.screenHeight || NOT_APPLICABLE;
	this.screenWidth=obj.screenWidth || NOT_APPLICABLE;
	this.screenColorDepth=obj.screenColorDepth || NOT_APPLICABLE;
	this.flashSupport = obj.flashSupport || NOT_APPLICABLE;
	this.mouseX =obj.mouseX || NOT_APPLICABLE;
	this.mouseY = obj.mouseY || NOT_APPLICABLE;
	this.elementID=obj.elementID || NOT_APPLICABLE;
	this.elementType=obj.elementType || NOT_APPLICABLE;
	this.elementClass=obj.elementClass || NOT_APPLICABLE;

}

/**
 * Returns the client's OS.
 */
function getOS() {
	if (navigator.appVersion.indexOf("Win")!=-1) return "Windows";
	if (navigator.appVersion.indexOf("Mac")!=-1) return "MacOS";
	if (navigator.appVersion.indexOf("X11")!=-1) return "UNIX";
	if (navigator.appVersion.indexOf("Linux")!=-1) return "Linux";
	return "Unknown OS";
}

function PlatformTransaction(){

	//Date should be in this format:
    //2009-03-13T13:35:45.086-00:00
    now = new Date();	
	
	this.startTime = formatDate(new Date(),"yyyy-MM-ddTHH:mm:ss")
		+ "." + (now.getUTCMilliseconds()<=99 ? "0" : "") + (now.getUTCMilliseconds()<=9 ? "0" : "") + now.getUTCMilliseconds() + "-00:00";
	
	this.applicationId = applicationID || "test";
	this.clientVersion="1.0.6";
}

function WebPageEvent(){
	
	this.pageTitle=document.title;
    
	try{
		this.sessionId = $.cookie("ui-userSession");
		this.userId=$.cookie("ui-userId");
	}catch(err){
		// This usually happens if the cookie plugin wasn't loaded
		this.sessionId=UNAVAILABLE;
		this.userId=UNAVAILABLE;
	}
	this.page = location.href || "UNAVAILABLE";
	this.weSessionId=$.cookie("we-session-id") || "NOT-APPLICABLE";
}
WebPageEvent.prototype= new PlatformTransaction();


/**
 * PageAccess object
 */
function PageAccess(){	
	this.eventType = "PageAccess" ;			
	PageAccess.prototype=new WebPageEvent();
	
	// You can only get this from HTTP request/response
	this.protocol = metaAttributes.protocol || UNAVAILABLE;	
      
	//Request was successful...
	this.status=metaAttributes.status || UNAVAILABLE;			
		
	// We cannot get this server side	
	this.renderTime = new Date() - dt;	
	
	this.clientIP = metaAttributes.clientIpAddress || UNAVAILABLE;	
	this.method = metaAttributes.method || UNAVAILABLE;
	this.requestSize = metaAttributes.requestSize || UNAVAILABLE;
	this.responseSize = metaAttributes.responseSize || UNAVAILABLE;

	// This is null when testing locally or if the user got there
	// some way other than clicking a link
	this.referrer = document.referrer || UNAVAILABLE;	

	this.acceptCharset=metaAttributes["headers:accept-charset"] || UNAVAILABLE;
	this.acceptEncoding=metaAttributes["headers:accept-encoding"] || UNAVAILABLE;
	this.acceptLanguage=metaAttributes["headers:accept-language"] || UNAVAILABLE;
	this.userAgent=navigator.userAgent;
	this.locale = dojo.locale;
	this.screenHeight=screen.height;
	this.screenWidth=screen.width;
	this.screenColorDepth=screen.colorDepth;
	this.flashSupport = UNAVAILABLE;
	try{
		this.flashSupport=navigator.plugins["Shockwave Flash"].description;
	}catch(err){ }	
}
PageAccess.prototype = new WebPageEvent();

function SessionCreation(id){
    this.eventType="SessionCreation";
    this.sessionId=id;
}

SessionCreation.prototype = new WebPageEvent();


/**
 * Mouse event object
 */
function MouseEvent(event){
	this.eventType=event.type;	
	var now = new Date();
//	this.startTime = formatDate(new Date(),"yyyy-MM-ddTHH:mm:ss")
//	+ "." + (now.getUTCMilliseconds()<=99 ? "0" : "") + (now.getUTCMilliseconds()<=9 ? "0" : "") + now.getUTCMilliseconds() + "-00:00";
	this.pageTitle=document.title;
	
	this.mouseX = event.pageX;
	this.mouseY = event.pageY;
	this.elementID=event.target.id || NOT_APPLICABLE;
	this.elementType=event.target.nodeName;
	this.elementClass=event.target.className || NOT_APPLICABLE;
}

MouseEvent.prototype = new WebPageEvent();

/**
 * Canopy's default event handling behavior is specified here.
 * This can be overriden by providing a function named canopy_log_event.
 * 
 */
function canopy_event_handler(uiEvent){
	canopy_log_event(new MouseEvent(uiEvent));
}

function canopy_log_event(event){
	if(CANOPY_MOUSE_DEBUG=="true") {
		console.info(event);
	}	
	else {
		var sensor = sensorFactory.getSensor("record://" +  sensorHost + "/com/worldevolved/" + 
			applicationID + "/" + event.eventType);
		//sensor.record(event);
		sensor.record(new Transaction(event));
	}

}

function conditionalMouseHandler(uiEvent){
	if(CANOPY_MOUSE_OVERS=="true"){
		canopy_event_handler(uiEvent);
	}
}

/**
 * Registers the event handler with the DOM. 
 */
function register_event_handlers(){

	$("body").click(canopy_event_handler);
	$("body").mouseout(conditionalMouseHandler);
	$("body").mouseover(conditionalMouseHandler);
}


/*
 * START OF MAIN BLOCK
 */
dt=new Date();
var metas = document.getElementsByTagName('attr');
var metaAttributes = new Object();
for (i = 0; i < metas.length; i++){
	metaAttributes[metas[i].getAttribute('key')]=metas[i].getAttribute('value'); 	
}

$(window).load(function() {
	try{
		var expireNever=new Date();
	    expireNever.setFullYear(2038,0,19);
	    if($.cookie("ui-userId")==undefined) 
	    	$.cookie("ui-userId", Math.floor(Math.random()*Math.pow(2,64)),{expires: expireNever});
	    	PageAccess.prototype=new WebPageEvent();
	    	MouseEvent.prototype=new WebPageEvent();
	    	SessionCreation.prototype=new WebPageEvent();
	    if($.cookie("ui-userSession")==undefined){
	    	var id = Math.floor(Math.random()*Math.pow(2,64))
	    	canopy_log_event(new SessionCreation(id));
	    	$.cookie("ui-userSession", id);
	    	PageAccess.prototype=new WebPageEvent();
	    	MouseEvent.prototype=new WebPageEvent();
	    	SessionCreation.prototype=new WebPageEvent();
	    }
	}
	catch(err){
	        console.info("Couldn't load cookie plugin...");
	        console.info(err);
	}
    register_event_handlers();
	canopy_log_event(new PageAccess());
});

//This event will be triggered both when someone leaves the page or
//if, for example, a download link is clicked.
$(window).unload(function(){	
	//alert(event);
});
