xmp.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';

};

// CNN.AbstractOmnitureTriggerCommand.prototype._doMidCommand = function(context)
//{
//	var s = this._createReportingObject(context);
//	var vid = this._getVideoId(context);
//	s.linkTrackVars='eVar20,eVar21,eVar22,events'; 
//	s.linkTrackEvents='event6'; 
//	s.eVar20 = vid;
//	s.eVar21 = '';
//	s.eVar22 = '';
//	s[this._getVideoIdEvar()] = vid;
//	s.events = 'event6';
//	this._postReportingObject(context, s, false, 'Mid');
//};

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');
	
};

CNN.AbstractOmnitureTriggerCommand.prototype._postReportingObject = function(context, s, hit, cType)
{
	this._dumpReportingObject(context, s);
	if (hit)
	{
		s.t();
	}
	else
	{
		s.tl(xmp.getGlobalNamespace(), 'o', this._getCustomTriggerPrefix() + cType);
	}
};

CNN.AbstractOmnitureTriggerCommand.prototype._createReportingObject = function(context)
{
	var s = xmp.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.util.SettingsManager.getInstance().
		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._didAdPlayBefore = function(context)
//{
//	var lba = this._getLookBehindNodeArray(context);
//	for (var i=0; i<lba.length; i++)
//	{
//		var node = lba[i];
//		if (node.getNodeTypeName() === 'Content')
//		{
//			return false;
//		}
		// NOTE: 'isAd' set by CNNRules.CannotHaveTwoSequentialAdsRule
//		if (node.getPlayableData().getRuntimeMetadata('isAd', false))
//		{
//			return true;
//		}
//	}
//	return false;
//};

//CNN.AbstractOmnitureTriggerCommand.prototype._getLookBehindNodeArray = function(context)
//{
//	var listener = context.getMetadata('nodeListener', {});
//	return listener.getPlayer().getLookBehindNodeArray();
//};

CNN.AbstractOmnitureTriggerCommand.prototype._calcTimeStrings = function()
{
	return this._calcTimeStringsGeneric(xmp.getGlobalNamespace().cnnCurHour, 
		xmp.getGlobalNamespace().cnnCurMin, 
		xmp.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.BVPOmnitureTriggerCommand = function()
{
	this._logger = new xmp.util.internals.CategoryLogger( 'BVPOmnitureTriggerCommand' );
};

xmp.DERIVE_CLASS( CNN.AbstractOmnitureTriggerCommand, CNN.BVPOmnitureTriggerCommand );

CNN.BVPOmnitureTriggerCommand.prototype._getVideoIdEvar = function()
{
	return 'eVar21';
};

CNN.BVPOmnitureTriggerCommand.prototype._getPageType = function()
{
	return 'bvp';
};

CNN.BVPOmnitureTriggerCommand.prototype._getCustomTriggerPrefix = function()
{
	return 'CNN BVP: ';
};

CNN.BVPOmnitureTriggerCommand.prototype._reportSpecificStartValues = function(context, s)
{
	var pm = CNNPlaylistManager.getInstance();
	var thisTab = pm.tab;
	if(pm.activePlaylist == 'myARplaylist'){
		thisTab = pm.getCurrentVideoTab();
		s.events += ', event6';
	}
	if(thisTab != 'notab' && !pm.videoWasLinked()){
		s.eVar17=thisTab;
		s.events += ', event4';
	}
};

CNN.BVPOmnitureTriggerCommand.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);
	// commenting out for now until we get these created
};

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


CNN.NielsenTriggerCommand = function() {
};

CNN.NielsenTriggerCommand.prototype.doCommand = function(context) {
	var isTurnerDomain = false;
	if (location.hostname.indexOf('turner.com')>0) { isTurnerDomain = true; }

	if (!isTurnerDomain) { 	// don't add tracking image to internal player
		var cnnScRandom = Math.ceil(Math.random()*1000000000);
  		var cnnScTitle = escape(context.getPlayableNode().getPlayableData().getDataObject().headline);
		switch (context.getTriggerType()) {
			case 'start':{
				var cnnScImgt1 = 'dav0-' + cnnScTitle;
				break;
			}
			case 'end':{
				var cnnScImgt1 = 'dav2-' + cnnScTitle;
				break;
			}
			default:{
				return false;
			}
		}

		var cnnScImgSrc = 'http://secure-us.imrworldwide.com/cgi-bin/m?ci=us-100120&tl=' + cnnScImgt1 + '&c6=vc,b01&cc=1&rnd=' + cnnScRandom;
		cnnScImg = new Image();
		cnnScImg.src = cnnScImgSrc;
	}
};

