tkutils.createNamespace("CNN");

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

CNN.AbstractOmnitureTriggerCommand = function()
{
};

// Static 'now' date on client machine
CNN.AbstractOmnitureTriggerCommand._clientStartMs = (new Date()).getTime();

CNN.AbstractOmnitureTriggerCommand.prototype.doCommand = function(context)
{
	switch (context.getTriggerType())
	{
		case 'start': this._doStartCommand(context); break;
		case 'end': this._doEndCommand(context); break;
		default: break;
	}
};

CNN.AbstractOmnitureTriggerCommand.prototype._doStartCommand = function(context)
{
	var s = this._createReportingObject(context);
	var vid = this._getVideoId(context);
	s.pageName = vid;
	s.eVar1 = vid;
	s.prop6 = vid;
	s.prop11 = vid;
	s.prop1 = "";
	s.prop4 = "video";
	s.prop5 = this._getPageType();
	s.eVar5 = this._getPageType();
	var ev = 'event5, event8';
	var subcategory = "";
	if(context.getPlayableNode().getPlayableData().getDataObject().subcategory != undefined){
		subcategory = context.getPlayableNode().getPlayableData().getDataObject().subcategory;
	}
	s.prop16 = subcategory;

//	if (this._didAdPlayBefore(context))
//	{
//		ev += ', event4';
//	}

	/* TODO - currently NOT reporting the hour-with-15-minute-interval or the day-of-week.					
	var timeO = this._calcTimeStrings();
	s.prop9 = timeO.h15;
	s.prop11 = timeO.dow;
	*/
	s.events = ev;
	this._reportSpecificStartValues(context, s);
	this._postReportingObject(context, s, true, 'Start');

	s.linkTrackVars='None'; 
	s.linkTrackEvents='None';
	var isTurnerDomain = false;
	if(location.hostname.indexOf('turner.com')>0) { isTurnerDomain = true; }
	if(!isTurnerDomain) { // don't add tracking image to internal player
		var cnnScImgSrc = '';
  		var cnnScTitle = escape(context.getPlayableNode().getPlayableData().getDataObject().headline);
    		var cnnScRandom = Math.ceil(Math.random()*1000000000);
		cnnScImgSrc += 'http://secure-us.imrworldwide.com/cgi-bin/m?ci=us-100120';
  		cnnScImgSrc += '&tl=dav0-' + cnnScTitle;
   		cnnScImgSrc += '&c6=vc,b01';
		cnnScImgSrc += '&cc=1';
  		cnnScImgSrc += '&rnd=' + cnnScRandom;
  		document.images['cookieCrumb'].src = cnnScImgSrc;
	}
};

CNN.AbstractOmnitureTriggerCommand.prototype._doEndCommand = function(context)
{
	var s = this._createReportingObject(context);
	var vid = this._getVideoId(context);
	s.linkTrackVars='eVar20,eVar21,eVar22,events'; 
	s.linkTrackEvents='event7';
	s.eVar20 = vid;
	s.eVar21 = '';
	s.eVar22 = '';
	s[this._getVideoIdEvar()] = vid;
	s.events = 'event7';
	this._postReportingObject(context, s, false, 'End');
	
	var isTurnerDomain = false;
	if(location.hostname.indexOf('turner.com')>0) { isTurnerDomain = true; }
	if(!isTurnerDomain) { // don't add tracking image to internal player
		var cnnScImgSrc = '';
		var cnnScTitle = escape(context.getPlayableNode().getPlayableData().getDataObject().headline);
		var cnnScRandom = Math.ceil(Math.random()*1000000000);
  		cnnScImgSrc += 'http://secure-us.imrworldwide.com/cgi-bin/m?ci=us-100120';
  		cnnScImgSrc += '&tl=dav2-' + cnnScTitle;
   		cnnScImgSrc += '&c6=vc,b01';
 		cnnScImgSrc += '&cc=1';
  		cnnScImgSrc += '&rnd=' + cnnScRandom;
  		document.images['cookieCrumb'].src = cnnScImgSrc;
	}

};

CNN.AbstractOmnitureTriggerCommand.prototype._postReportingObject = function(context, s, hit, cType)
{
	this._dumpReportingObject(context, s);
	if (hit)
	{
		s.t();
	}
	else
	{
		s.tl(tkutils.getGlobalNamespace(), 'o', this._getCustomTriggerPrefix() + cType);
	}
};

CNN.AbstractOmnitureTriggerCommand.prototype._createReportingObject = function(context)
{
	var s = tkutils.getGlobalNamespace().s_gi(this._getOmnitureAccount());
	var vid = this._getVideoId(context);
	s.eVar20 = vid;
	s[this._getVideoIdEvar()] = vid;
	return s;
};

CNN.AbstractOmnitureTriggerCommand.prototype._dumpReportingObject = function(context, s)
{
	if (this._getLogger().isDebugEnabled())
	{
		var report = 'OMNITURE REPORT FOR ' + context.getTriggerType();
		var propDataArray = CNN.AbstractOmnitureTriggerCommand.dumpObjectValues(s);
		var filterPrefixes = ['vpm_','vl_'];
		for (var i=0; i<propDataArray.length; i++)
		{
			var pd = propDataArray[i];
			if (!(pd.t === 's' || pd.t === 'n' || pd.t === 'b'))
			{
				continue;
			}
			var filtered = false;
			for (var j=0; j<filterPrefixes.length; j++)
			{
				if (pd.n.indexOf(filterPrefixes[j]) === 0)
				{
					filtered = true;
					break;
				}
			}
			if (filtered)
			{
				continue;
			}
			report += ('\n' + pd.n + ': ' + pd.v);
		}
		this._getLogger().debug(report);
	}
};

/**
  * Static method
 */
CNN.AbstractOmnitureTriggerCommand.dumpObjectValues = function(theObject)
{
	if (!theObject)
	{
		return [];
	}
	var propArray = [];
	var propName = '';
	for (propName in theObject)
	{
		propArray.push(propName);	
	}
	propArray.sort();
	var dArray = [];
	for (var i=0; i<propArray.length; i++)
	{
		var pd = {t: '', n: propArray[i], v: ''}; // t = type, n = name, v = value
		var pv = theObject[pd.n];
		pd.t = (typeof(pv)).charAt(0);
		if (!(pd.t === 'o' || pd.t === 'f' || pd.t === 'u'))
		{
			pd.v = pv.toString();
		}
		dArray.push(pd);
	}
	return dArray;
};

CNN.AbstractOmnitureTriggerCommand.prototype._getOmnitureAccount = function()
{
	return xmp.baseplayer.BasePlayer.getSettingsManager().getContextNode().getString('omniture account', '');
};

CNN.AbstractOmnitureTriggerCommand.prototype._getVideoId = function(context)
{
	var node = context.getPlayableNode();
	return node.getPlayableData().getDataObject().id;
};

CNN.AbstractOmnitureTriggerCommand.prototype._reportSpecificStartValues = function(context, s)
{
	// default does nothing
};

CNN.AbstractOmnitureTriggerCommand.prototype._getVideoIdEvar = function()
{
	throw new Error('must override');
};

CNN.AbstractOmnitureTriggerCommand.prototype._getPageType = function()
{
	throw new Error('must override');
};

CNN.AbstractOmnitureTriggerCommand.prototype._getLogger = function()
{
	throw new Error('must override');
};

CNN.AbstractOmnitureTriggerCommand.prototype._getCustomTriggerPrefix = function()
{
	throw new Error('must override');
};

CNN.AbstractOmnitureTriggerCommand.prototype._calcTimeStrings = function()
{
	return this._calcTimeStringsGeneric(tkutils.getGlobalNamespace().cnnCurHour, 
		tkutils.getGlobalNamespace().cnnCurMin, 
		tkutils.getGlobalNamespace().cnnCurDay);
};

CNN.AbstractOmnitureTriggerCommand.prototype._calcTimeStringsGeneric = function(curHour, curMin, curDOW)
{
	var retVal = { h15: '', dow: '' };
	if (typeof(curHour)==='undefined'||typeof(curMin)==='undefined'||typeof(curDOW)==='undefined')
	{
		return retVal;
	}
	var diffMs = (new Date()).getTime() - CNN.AbstractOmnitureTriggerCommand._clientStartMs;
	if (diffMs < 0)
	{	// did user set system clock into the past after xmp started?
		return retVal;
	}
	var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var doyi = 0; // day of week index
	for (var i=0; i<days.length; i++)
	{
		if (curDOW === days[i])
		{
			doyi = i;
			break;
		}
	}
	// NOTE: Jan 1, 1995 was a Sunday.  Note that this scheme works so long as 
	// diffMs is not enough to take us past Feb 28, because leap years will mess things up, 
	// but highly doubtful someone will leave xmp running for more than 59 days.
	// Note that since we are only calculating hours, 15-minute intervals, and day of the week, 
	// it is OK to do calculations with a date in the past.
	var calcStartMs = Date.UTC(1995, 0, (1 + doyi), curHour, curMin);
	var finalDate = new Date(calcStartMs + diffMs);
	retVal.dow = days[finalDate.getUTCDay()];
	var min15 = 15 * (Math.floor(finalDate.getUTCMinutes()/15));
	retVal.h15 = finalDate.getUTCHours().toString() + ':' + ((min15 === 0) ? '00' : min15.toString());
	if (retVal.h15.length === 4) { retVal.h15 = '0' + retVal.h15; }	
	return retVal;
};

//Parent page location
var cnnWinLoc = window.location.pathname;
var cnnWinLocRegExp = /\/$/; 
if(cnnWinLocRegExp.test(cnnWinLoc)){cnnWinLoc = cnnWinLoc + "index.html";}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

CNN.SpecialsOmnitureTriggerCommand = function()
{
	this._logger = xmp.baseplayer.BasePlayer.createCategoryLogger( 'SpecialsOmnitureTriggerCommand' );
};

xmp.DERIVE_CLASS( CNN.AbstractOmnitureTriggerCommand, CNN.SpecialsOmnitureTriggerCommand );

CNN.SpecialsOmnitureTriggerCommand.prototype._getVideoIdEvar = function()
{
	return 'eVar19';
};

CNN.SpecialsOmnitureTriggerCommand.prototype._getPageType = function()
{
	return 'specials';
};

CNN.SpecialsOmnitureTriggerCommand.prototype._getCustomTriggerPrefix = function()
{
	return 'CNN Specials: ';
};

CNN.SpecialsOmnitureTriggerCommand.prototype._reportSpecificStartValues = function(context, s)
{
	if (typeof(cnnSectionName) !== "undefined") {s.channel=cnnSectionName;s.eVar2=cnnSectionName;} else {s.channel="";s.eVar2="";}
	if (typeof(cnnSubSectionName) !== "undefined") {s.server=cnnSubSectionName;s.eVar3=cnnSubSectionName;} else {s.server="";s.eVar3="";}
	s.eVar18 = cnnWinLoc;
};

CNN.SpecialsOmnitureTriggerCommand.prototype._getLogger = function()
{
	return this._logger;
};

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

CNN.WebstatTriggerCommand = function()
{
};

CNN.WebstatTriggerCommand.prototype.doCommand = function(context)
{
	switch (context.getTriggerType())
	{
		case 'start': this._doStartCommand(context); break;
		default: break;
	}
};

CNN.WebstatTriggerCommand.prototype._doStartCommand = function(context)
{
	var node = context.getPlayableNode();
	var pingUrl = node.getPlayableData().getDataObject().id+'/tracking.vidt';
	xmp.net.AjaxRequestManager.ping('videoTracking', pingUrl);
};

///////////////////////////////////////////////////////////////////////////////
// Comscore
///////////////////////////////////////////////////////////////////////////////

CNN.ComscoreTriggerCommand = function() {
};

CNN.ComscoreTriggerCommand.prototype.doCommand = function(context) {
	if (context.getTriggerType() == 'start') {
		var is_video = true;
		var show_level = escape(context.getPlayableNode().getPlayableData().getDataObject().headline);
		CNN.ComscoreTriggerCommand.pingBeacon(is_video, show_level);
	}
};

/**
 * actual beacon ping broken out into its own function so AdNodeListener.prototype.handleRender can
 * use it as welol 
 * @param {boolean} is_video (is ad or video)
 * @param {Object} show_level (show title if video, empty if ad)
 */
CNN.ComscoreTriggerCommand.pingBeacon = function(is_video,show_level) {
	var urlLoc = 'http://beacon.securestudies.com/scripts/beacon.dll';
	// Content Distributor ID
	var urlQS1 = '?CXNID=3005117';
	// Content Owner ID
	var urlQS2 = '&CDID=3005117';
	// Location where viewed ID
	var urlQS3 = '&CPID=3005117';
	// Genre content
	if (is_video) {
		var urlQS4 = '&CGID=020100';
	} else {
		var urlQS4 = '&CGID=010000';
	}
	// show level
	var urlQS5 = '&CBID=' + show_level;
	var comscoreUrl = urlLoc + urlQS1 + urlQS2 + urlQS3 + urlQS4 + urlQS5 + '&rnd=' + Math.ceil(Math.random()*1000000000);
	cnnCmScImg = new Image();
	cnnCmScImg.src = comscoreUrl;
};
