/*
 * New Project 1
 * Copyright(c) 2006, Jack Slocum.
 * 
 * This code is licensed under BSD license. Use it as you wish, 
 * but keep this copyright intact.
 */

 //
 // Tv JS Framework starts here
 // Dependency: YUI framework, Base TV class
 // 

 // Namespace declaration
 if (typeof Tv == "undefined") {
	 
	 var Tv = function() {};
	
	 // Class declaration
	 Tv.Campaign 	= function() {};
	 Tv.Session	 	= function() {};
	 Tv.Event		= function() {};
	 Tv.Page		= function() {};
	 Tv.Meeting		= function() {};
	 Tv.Tag			= function(name) {
		Tv.Event.Log(Tv.Event.TagContext, Tv.Event.Names['TAGGING'], escape(name));
	 };
	 Tv.Logging		= false;
	 //Tv.Tag			= function() {};
	 Tv.Tags		= {};
 };
 
 //
 // Tv.Event class definition
 //
 (function() {
	 
	 var evt = Tv.Event;
	 
	 // static members 
	 evt.Logging 		= true;
	 evt.CallTypePixel	= 'pixel';  // ajax / pixel
	 evt.CallTypeAjax	= 'ajax';  // ajax / pixel
	 evt.PageContext 	= 'Page';
	 evt.MeetingContext	= 'Meeting';
	 evt.TagContext		= 'Tag';
	 evt.InstantRevenueContext	= 'InstantRevenue';
	 evt.CookieCheck	= 'CookieCheck';
	 evt.CookieEnabled = true;

	// static methods
	 evt.Log = function( context, eventId, params, callType) {

		if(Tv.Event.CookieEnabled===false) {
			context=evt.CookieCheck;
			eventId = '';
			params='';
		}

		if (evt.Logging == false)  // Not intereseted in logging events
			return;


		if(params == undefined){
			params = '';
		}else{
			params = '&tag='+ escape(params);
		}
		
		if (callType == undefined) {
			callType = evt.CallTypePixel;
		}

		if (eventId == undefined) {
			eventId = 'NULL';
		}
		
		var defaultParams = 'vi='+Tv.Session.visitorId + 
							'&si='+Tv.Session.sessionId+ 
							'&ui='+Tv.UserId +
							'&ut='+Tv.UserType +
							'&pi='+Tv.Page.id + 
							'&ei='+eventId;

		var contextParams = '';	

		if (context === Tv.Event.MeetingContext) {
			contextParams = '&mi='+Tv.Meeting.id + '&mt=' + Tv.Meeting.type+'&fi='+Tv.Session.pageTrackId;
		} else if (context === Tv.Event.PageContext) {
			contextParams = '&cmpi='+Tv.Campaign.id + '&cmpt=' + Tv.Campaign.type;
		} else if (context === Tv.Event.TagContext) {
			contextParams = '&cmpi='+Tv.Campaign.id + '&cmpt=' + Tv.Campaign.type + '&fi=' + Tv.Session.pageTrackId + params;
		} else if (context === Tv.Event.InstantRevenueContext) {
			//contextParams = params;
			contextParams ='&dn='+Tv.DomainName +'&salsrc='+Tv.SaleSource +'&mtype='+Tv.MeetingType +'&mid='+Tv.MeetingID +'&cmpi='+Tv.Campaign.id +'&li='+Tv.UserLoginId+'&ci='+Tv.UserContractId+'&cn='+Tv.UserContractName;
		} /*else if (context === Tv.Event.TagContext) {
			contextParams = '&ui='+Tv.Campaign.userId+'&ut='+Tv.Campaign.userType+'&ul='+Tv.Campaign.userLogin+'&ci='+Tv.Campaign.contractorId+'&cn='+Tv.Campaign.contractorName+'&mi='+Tv.Campaign.meetingId+'&mt='+Tv.Campaign.meetingType+'&cid='+Tv.Campaign.campaignId+'&dn='+Tv.Campaign.domain+'&ss='+Tv.Campaign.salesSource + params;
		}*/

		var tvaJsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
		evt.LogURL 	= tvaJsHost + Tv.Event.Host + '/trkanalytics/log'+ context + 'Event' + '/';
		var logURI	= evt.LogURL + ((evt.LogURL.indexOf("?") > -1)?"&":"?") + defaultParams + contextParams;
				
		if (evt.CallTypeAjax == callType) {
			evt.FireAjax(logURI);
		} else if (evt.CallTypePixel == callType) {
			evt.FirePixel(logURI);
		} 
	};
	 
	 evt.FireAjax = function(logURI) {

		var eventCallBack = {
			success:OnLogEventSuccess,
			failure:OnLogEventFailure,
			argument:logURI
		};
		
		var _qs = "ct="+ evt.CallTypeAjax;
		YAHOO.util.Connect.asyncRequest("GET", logURI+((logURI.indexOf("?") > -1)?"&":"?")+ _qs, eventCallBack);
		
		function OnLogEventSuccess(e) {};
		function OnLogEventFailure(e) {};
	};
	 
	 evt.FirePixel = function(logURI) {
		try {
			if(Tv.Logging){
				var _pix = document.createElement("img");

				if(_pix) {
					var _qs = "ct="+evt.CallTypePixel+"&magicid=" + (new Date()).getTime() + Math.ceil(Math.random() * 1000);

					_pix.width  = 1;
					_pix.height = 1;
					_pix.id = (new Date()).getTime() + Math.ceil(Math.random() * 1000);
					_pix.src = logURI +((logURI.indexOf("?") > -1)?"&":"?") + _qs;

					document.body.appendChild(_pix);
				}
			}
		} catch(e) {};
	};

	evt.CheckCookieEnabled = function(){

		var cookieEnabled=(navigator.cookieEnabled)? true : false
		//if not IE4+ nor NS6+
		if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
			document.cookie="tva"
			cookieEnabled=(document.cookie.indexOf("tva")!=-1)? true : false
		}		
		Tv.Event.CookieEnabled = cookieEnabled;
		//Tv.Event.CookieEnabled = false;
	};
	
	evt.serialize = function(mixed_value) {
	
		var _utf8Size = function (str) {
	    var size = 0, i = 0, l = str.length, code = '';
			for (i = 0; i < l; i++) {
				code = str.charCodeAt(i);
			
				if (code < 0x0080) {
					size += 1;
				} else if (code < 0x0800) {
					size += 2;
				} else {
					size += 3;
				}
			}
			return size;
		};
		var _getType = function (inp) {
			var type = typeof inp, match;
			var key;

			if (type === 'object' && !inp) {
				return 'null';
			}
			if (type === "object") {
				if (!inp.constructor) {
					return 'object';
				}
				var cons = inp.constructor.toString();
				match = cons.match(/(\w+)\(/);
				if (match) {
					cons = match[1].toLowerCase();
				}
				var types = ["boolean", "number", "string", "array"];
				for (key in types) {
					if (cons == types[key]) {
						type = types[key];
						break;
					}
				}
			}
			return type;
		};
		var type = _getType(mixed_value);
		var val, ktype = '';
    
		switch (type) {
			case "function": 
				val = ""; 
				break;
			case "boolean":
				val = "b:" + (mixed_value ? "1" : "0");
				break;
			case "number":
				val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
				break;
			case "string":
				val = "s:" + _utf8Size(mixed_value) + ":\"" + mixed_value + "\"";
				break;
			case "array":
			case "object":
				val = "a";
				/*
				if (type == "object") {
					var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
					if (objname == undefined) {
						return;
					}
					objname[1] = this.serialize(objname[1]);
					val = "O" + objname[1].substring(1, objname[1].length - 1);
				}
				*/
				var count = 0;
				var vals = "";
				var okey;
				var key;
				for (key in mixed_value) {
					if (mixed_value.hasOwnProperty(key)) {
					   ktype = _getType(mixed_value[key]);
					   if (ktype === "function") { 
						   continue; 
					   }
				   
					   okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
					   vals += this.serialize(okey) +
							   this.serialize(mixed_value[key]);
					   count++;
					}
				}
				val += ":" + count + ":{" + vals + "}";
				break;
			case "undefined": // Fall-through
			default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
				val = "N";
				break;
		}
		if (type !== "object" && type !== "array") {
			val += ";";
		}
		return val;
	
	};

})();

// Tv.Tag class definition goes here
 (function() {
	 tag = Tv.Tag;
	 tag.Tagger = function(tags) {		
		if(typeof tags === "object")
			tags = Tv.Event.serialize(tags);	

		Tv.Event.Log(Tv.Event.TagContext, Tv.Event.Names['TAGGING'], tags);
	 };

	tag.recordOutboundLink = function (frm,tag) {
		if((typeof Tv!="undefined")&&(Tv.Tag))
			Tv.Tag.Tagger(tag);
		setTimeout('document.location = "' + frm.href + '"', 100);
	};

	tag.recordPostLink = function (frm,tag) {
		if((typeof Tv!="undefined")&&(Tv.Tag))
			Tv.Tag.Tagger(tag);
		setTimeout('document.forms["'+frm.name+'"].submit()',100);		
	};

 })();

(function() {
 Tv.OnLoad = function() {
	if(Tv.Tags) {
		Tv.Tag.Tagger(Tv.Tags);
	}
}
})();

if(Tv.Event != "undefined")
	Tv.Event.CheckCookieEnabled();

if (window.addEventListener){
	window.addEventListener('load', Tv.OnLoad, false);
}else if (window.attachEvent){
	window.attachEvent('onload', Tv.OnLoad);
}
