
/*
 * Metrics: tracks the user within the player via a metrics package
 */


// pProject: the Omniture project id
function Metrics( pAccountId, pProject )
{
    this.AccountId = pAccountId;
	this.Project = pProject;
	
	this.CurrentClip = null;
	this.CurrentLocation = -1;
	
	this.LastTrackedLocation = 0;
	this.LastTrackedIntervalLocation = 0;
	
	this.KeyInterval = [ 20 ]; //an array of "key times" to track. This case will track at 20 seconds.
	this.KeyIntervalPercentage = [ 80 ]; //an array of "key times" to track as a percentage of video duration. This case will track at 80% complete.
	
	this.KeyPoints = new Array();
	
	this.trackingIntervalToken = null;

	this.TRACKING_INTERVAL = 120; //in seconds
	this.REACHED_CLIP_POINT_INTERVAL = 10; //in seconds
	
	this.IsTrackingVideo = false;
	this.HasSentVideoStart = false;
	
	this.ShouldUseParallelTracking = false;
	
	this.HasReachedEightyPercent = false;
	
	Metrics.__instance = this;
}

Metrics.UseMetricsOverridePlayName = false;
Metrics.VIDEO_LABEL = "CustomLinkForVideoTracking";
Metrics.VIDEOPLAYER_SITESECTION = "VideoPlayer";


Metrics.StopClip = function(){

}

Metrics.StartClip = function(){

} 
Metrics.GetInstance = function()
{
	if( ! Metrics.__instance )
	{
		Metrics.__instance = new Metrics( "chumtvthecomedynetwork", "The Comedy Network Video Player" ); 
		return Metrics.__instance;
	}
	else
	{
		return Metrics.__instance;
	}
}

Metrics.GetVideoTitle = function( pVideo )
{
    if( pVideo.Title != undefined && pVideo.Title != "undefined" && pVideo.Title != null )
    {
        return Metrics.TrimLabel( pVideo.Title );
    }
    
     return Metrics.TrimLabel( pVideo.Permalink );
}

Metrics.GetVideoDuration = function( pVideo )
{
	if( pVideo.Duration != undefined && pVideo.Duration != "undefined" && pVideo.Duration != null && pVideo.Duration > 0 )
    {
        try
        {
			return parseInt( "" + pVideo.Duration );  
		}
		catch(e) {}
    }
    
     return 0;
}

Metrics.GetVideoId = function( pVideo )
{
    if( pVideo.ClipId != undefined && pVideo.ClipId != "undefined" && pVideo.ClipId != null )
    {
        return pVideo.ClipId;
    }
    
    return -1;
}

Metrics.GetVideoPath = function( pVideo )
{
    if( ! pVideo.SiteMap )
    {
        if( pVideo.Permalink )
        {
			return Metrics.TrimLabel( pVideo.Permalink );
		}
		
		return Metrics.TrimLabel( pVideo.Title );
    }
    else
    {
        var Label = "";
        for( var i = pVideo.SiteMap.length - 1; i >= 0; i-- )
        {
            if( Label != "" )
            {
                Label += "|";
            }
            Label += pVideo.SiteMap[i][0].replace( /[|]/ig, "" );
            try
            {
                Label += "[" + /[0-9]+$/i.exec( pVideo.SiteMap[i][1] ) + "]";
            }
            catch( err )
            {}
        }
        Label += "|Clip[" + pVideo.ClipId + "]"; 

        return Metrics.TrimLabel( Label );
    }
}


Metrics.TrimLabel = function( pLabel )
{
	if( pLabel.length > 100 )
	{
		return pLabel.substring( 0, 99 );
	}
	
	return pLabel;	 
}

Metrics.StartedClip = function( pVideo )
{
	var CurrentClip = pVideo;
	
	if( ! CurrentClip )
	{
	    CurrentClip = Playlist.GetInstance().Current;
	}
	
	if( ! CurrentClip.IsAd )
	{
	    


	    if( CurrentClip != Metrics.GetInstance().CurrentClip )
	    {
	        Metrics.GetInstance().CurrentClip = CurrentClip;

	        Metrics.GetInstance().LastTrackedLocation = 0;
			Metrics.GetInstance().LastTrackedIntervalLocation = 0;
			Metrics.GetInstance().IsTrackingVideo = true;
			Metrics.GetInstance().HasReachedEightyPercent = false;
			Metrics.GetInstance().HasSentVideoStart = false;
			
	        if( CurrentClip.Duration > 0 )
	        {
				Metrics.SendStartedClip( CurrentClip );	
				Metrics.InitializeKeyPoints( CurrentClip );
				
				Metrics.GetInstance().HasSentVideoStart = true;
			}
			/*else
			{
				//sometimes the clips don't have a duration immediately, so give it awhile...
				setTimeout( function() { Metrics.SendStartedClip( CurrentClip );Metrics.InitializeKeyPoints( CurrentClip ); }, 2500 );
			}*/
		
			if( Metrics.GetInstance().trackingIntervalToken != null )
			{
				clearInterval( Metrics.GetInstance().trackingIntervalToken );
				Metrics.GetInstance().trackingIntervalToken = null;
			}
			var _Metrics = Metrics.GetInstance();
			_Metrics.trackingIntervalToken = setInterval(	function() 
															{ 
																_Metrics.LastTrackedIntervalLocation  += _Metrics.TRACKING_INTERVAL;
																Metrics.OnIntervalClipTime	( CurrentClip,
																							 _Metrics.LastTrackedIntervalLocation 
																							);
															}, ( _Metrics.TRACKING_INTERVAL * 1000 ) );
	    }
    }
    
    
}

Metrics.InitializeKeyPoints = function ( pVideo )
{
	var CurrentClip = pVideo; 
	
	if( ! CurrentClip )
	{
	    CurrentClip = Playlist.GetInstance().Current;
	}
	
	Metrics.GetInstance().KeyPoints = new Array();
	
	for( i=0; i< Metrics.GetInstance().KeyInterval.length; i++ )
	{
		var keyPoint =  parseInt( Metrics.GetInstance().KeyInterval[ i ] );
		Metrics.GetInstance().KeyPoints.push( keyPoint );
	}
	
	if( CurrentClip.Duration > 0 )
	{
		for( i=0; i< Metrics.GetInstance().KeyIntervalPercentage.length; i++ )
		{
			var keyPoint = parseInt( ( Metrics.GetInstance().KeyIntervalPercentage[ i ] / 100 ) * CurrentClip.Duration );
			Metrics.GetInstance().KeyPoints.push( keyPoint );
		}
	}
}

Metrics.EndedClip = function( pVideo )
{
	var CurrentClip = Playlist.GetInstance().Current;
	
	if( ! CurrentClip )
	{
	    CurrentClip = pVideo;
	}

	if( ! CurrentClip.IsAd )
	{
		if( Metrics.GetInstance().IsTrackingVideo )
		{
			var VideoProbablyEndedNaturally = Metrics.GetInstance().HasReachedEightyPercent && ( CurrentClip.Duration - Metrics.GetInstance().LastTrackedLocation ) < Metrics.GetInstance().TRACKING_INTERVAL;
			
			if( VideoProbablyEndedNaturally ) // we need to let them know that the video was watched until the end
			{
				Metrics.SendEndedClip( CurrentClip,  Metrics.GetVideoDuration( CurrentClip ) );
			}
			
			Metrics.GetInstance().IsTrackingVideo = false;
			Metrics.GetInstance().HasReachedEightyPercent = false;
		}
    }
}

Metrics.TrackSearch = function( pSearchTerm, pNumberOfResults )
{
	var s = Metrics.GetTrackingInstance( null );		
	
	var searchResults = parseInt( pNumberOfResults ) > 0 ? ("" + pNumberOfResults ) : "zero";
	
	s.linkTrackVars		= "prop1,eVar1,prop2,events";
	s.linkTrackEvents	= "event1";

	s.prop1= s.eVar1 = pSearchTerm.toLowerCase();
	s.prop2= searchResults;
	s.events = "event1";
	
	var label = Metrics.TrimLabel( "Search for " + pSearchTerm  + " had " + pNumberOfResults + " results." );
	Metrics.TrackLink( s, true, "o", Metrics.VIDEO_LABEL );
}

Metrics.ReachedClipKeyPoint = function( pSeconds )
{
	var CurrentClip = Metrics.GetInstance().CurrentClip;
	
	if( CurrentClip )
	{
		if( ! Metrics.GetInstance().HasSentVideoStart )
		{
			Metrics.SendStartedClip( CurrentClip );	

            /*var playerNameToRecord = Metrics.GetInstance().Project;*/

            var playerNameToRecord = "Pop-up Player";

            var dartId = "ctv.thecomedynetworkwatch.ca";
            var comscoreID= "8016415";
			Metrics.InitializeKeyPoints( CurrentClip );
					
			Metrics.GetInstance().HasSentVideoStart = true;

            COMSCORE.beacon({
                c1: 1,
                c2: "3005664",
                c3: "",
                c4: comscoreID,
                c5: CurrentClip.ClipId,
                c6: CurrentClip.Title
            });
		}
		
		for( i=0; i < Metrics.GetInstance().KeyPoints.length; i++ )
		{
			if( ( Metrics.GetInstance().KeyPoints[ i ] - pSeconds ) < Metrics.GetInstance().REACHED_CLIP_POINT_INTERVAL )
			{
				Metrics.OnKeyPointClipTime( CurrentClip, Metrics.NonZero(  Metrics.GetInstance().KeyPoints[ i ] ) );
				Metrics.GetInstance().KeyPoints.splice( i, 1 );
				i--;
			}
		}
	}
}

Metrics.GetVideoLabel = function( pVideo )
{
    if( ! pVideo.SiteMap )
    {
        return pVideo.Permalink;
    }
    else
    {
        var Label = "";
        for( var i = pVideo.SiteMap.length - 1; i >= 0; i-- )
        {
            if( Label != "" )
            {
                Label += "|";
            }
            Label += pVideo.SiteMap[i][0].replace( /[|]/ig, "" );
            try
            {
                Label += "[" + /[0-9]+$/i.exec( pVideo.SiteMap[i][1] ) + "]";
            }
            catch( err )
            {}
        }
        Label += "|Clip[" + pVideo.ClipId + "]"; 
        return Label;
    }
}

Metrics.ApplyKnownSections = function( sInstance, pVideo )
{
	//change to support newstyle self serve metrics and the oneclip player.
	if (sInstance.trackingServerSecure == "" || sInstance.trackingServerSecure == null){
		sInstance.trackingServerSecure = s.trackingServerSecure;
		sInstance.trackingServer = s.trackingServer;
		s_siteSection = s.eVar6;
		s_siteCategory = s.eVar23;
		s_siteName = s.eVar22;
		sInstance.un = s.un;
	}
	
	var hasSSiteSection = typeof( s_siteSection ) != undefined && typeof( s_siteSection ) != "undefined" && typeof( s_siteSection ) != null;
	var hasSSubSection1 = typeof( s_subSection1 ) != undefined && typeof( s_subSection1 ) != "undefined" && typeof( s_subSection1 ) != null;
	var hasSSiteCategory= typeof( s_siteCategory ) != undefined && typeof( s_siteCategory ) != "undefined" && typeof( s_siteCategory ) != null;
	var hasSSiteName	= typeof( s_siteName ) != undefined && typeof( s_siteName ) != "undefined" && typeof( s_siteName ) != null;
	
	var prefix = "";

	if( hasSSiteSection && s_siteSection != ""  )
	{
		sInstance.linkTrackVars += prefix + "prop6,eVar6";
		sInstance.prop6 = sInstance.eVar6 = sInstance.channel = sInstance.hier1 = s_siteSection;
	}
	else
	{
		sInstance.linkTrackVars += prefix + "prop6,eVar6";
		sInstance.prop6 = sInstance.eVar6 = sInstance.channel = sInstance.hier1 = Metrics.VIDEOPLAYER_SITESECTION;
	}
	
	prefix = sInstance.linkTrackVars == "" ? "" : ( ( sInstance.linkTrackVars.length > 0 && sInstance.linkTrackVars.substring( sInstance.linkTrackVars - 1 ) == "," ) ? "" : "," );

	if( hasSSubSection1 && s_subSection1 != ""  )
	{
		sInstance.linkTrackVars += prefix + "prop7,eVar7"
		sInstance.prop7 = sInstance.eVar7 = s_subSection1;
		
		sInstance.hier1 += prefix + s_subSection1;
	}
	
	prefix = sInstance.linkTrackVars == "" ? "" : ( ( sInstance.linkTrackVars.length > 0 && sInstance.linkTrackVars.substring( sInstance.linkTrackVars - 1 ) == "," ) ? "" : "," );

	
	if( hasSSiteCategory && s_siteCategory != "" && hasSSiteName && s_siteName != "" )
	{
		sInstance.linkTrackVars += prefix + "prop22,eVar22,prop23,eVar23,prop24,eVar24"
		
		sInstance.prop22 = sInstance.eVar22 = s_siteName;
		sInstance.prop23 = sInstance.eVar23 = s_siteCategory;
		sInstance.prop24 = sInstance.eVar24 = s_siteCategory + ":Video";
		
	}

	prefix = sInstance.linkTrackVars == "" ? "" : ( ( sInstance.linkTrackVars.length > 0 && sInstance.linkTrackVars.substring( sInstance.linkTrackVars - 1 ) == "," ) ? "" : "," );
	
	s.linkTrackVars		+= prefix + "prop5,prop11,eVar11,prop12,eVar12,prop13,eVar13,prop16,eVar16,prop17,eVar17,prop18,eVar18,prop20,eVar20,prop21,eVar21,hier1";
	
	sInstance.linkTrackVars = s.linkTrackVars;
	sInstance.prop16	= sInstance.eVar16 = Metrics.GetVideoTitle( pVideo );
	sInstance.prop17	= sInstance.eVar17 = Metrics.GetVideoId ( pVideo );
	sInstance.prop20	= sInstance.eVar20 = Metrics.GetVideoPath( pVideo );
	sInstance.prop21	= sInstance.eVar21 = Metrics.GetVideoDuration( pVideo );
	
	sInstance.prop5		= sInstance.eVar5 = "Video";
	
	sInstance.prop18	= sInstance.eVar18 ="Pop-up Player";
	
    if (this.UseMetricsOverridePlayName){
	    var playerNameToRecord = Metrics.GetInstance().Project;
	
	    if (playerNameToRecord == "")
	    {
	        playerNameToRecord = "Pop-up Player";
	    }
        
        sInstance.prop18	= sInstance.eVar18 = playerNameToRecord;
    }
	
	
}

Metrics.GetTrackingInstance = function( pVideo )
{
	var hasSAccount		= typeof( s_account ) != undefined && typeof( s_account ) != "undefined" && typeof( s_account ) != null;
	
	var accountName		= hasSAccount ? s_account : Metrics.GetInstance().AccountId;
	var s = null;
	
	s = s_gi( accountName );
	s.linkTrackVars = "";
	s.linkTrackEvents = "None";
	
	s.prop1 = s.eVar1 = "";
	s.prop2 = s.eVar2 = "";
	s.prop5 = s.eVar5 = "";
	s.prop6 = s.eVar6 = "";
	s.prop7 = s.eVar7 = "";
	s.prop8 = s.eVar8 = "";
	s.prop16 = s.eVar16 =  "";
	s.prop17 = s.eVar17 = "";
	s.prop20 = s.eVar20 = "";
	s.prop18 = s.eVar18 = "";
	s.prop20 = s.eVar20 = "";
	s.prop21 = s.eVar21 = "";
	
	s.hier1 = "";
	s.events= "";
	s.products= "";
	
	if( pVideo )
	{
		Metrics.ApplyKnownSections( s, pVideo );
	}
	
	return s;
}

Metrics.SendStartedClip = function( pVideo )
{
    
    Utility.Log("SendStartedClip");
	var CurrentClip = pVideo; 
	
	if( ! CurrentClip )
	{
	    CurrentClip = Playlist.GetInstance().Current;
	}
	var full = Player.Fullscreen;
	var s = Metrics.GetTrackingInstance( pVideo );
		
		
	s.linkTrackVars	  += ",products,events";
	s.linkTrackEvents = "event5,event7";
	
	s.events="event5,event7"; 
	s.products=";;;;event7=0";
	
	var label =  Metrics.TrimLabel( "[ClipId=" + Metrics.GetVideoId( pVideo ) + "] started"  );
	
	Metrics.TrackLink(s, true, "o", Metrics.VIDEO_LABEL );
}


Metrics.SendEndedClip = function( pVideo, pSeconds )
{
	var CurrentClip = pVideo; 
	
	if( ! CurrentClip )
	{
	    CurrentClip = Playlist.GetInstance().Current;
	}
	
	var timeDelta = pSeconds - Metrics.GetInstance().LastTrackedLocation;
	
	var s = Metrics.GetTrackingInstance( pVideo );
	
	s.linkTrackVars	  += ",products,events";
	s.linkTrackEvents ="event6,event7";
	
	Utility.Log("SendEndedClip");
	s.events="event6,event7";
	s.products=";;;;event7=" + timeDelta ;

	var label = Metrics.TrimLabel( "[ClipId=" + Metrics.GetVideoId( pVideo ) + "] ended" );
	Metrics.TrackLink( s, true, "o", Metrics.VIDEO_LABEL );
	
	s.Media.stop(CurrentClip.Title,pSeconds);
}

Metrics.OnIntervalClipTime = function( pVideo, pSeconds )
{
	var timeDelta = pSeconds - Metrics.GetInstance().LastTrackedLocation;
		
	Metrics.GetInstance().LastTrackedLocation = pSeconds;
	
	Utility.Log("SendClipTime:"+timeDelta);
	Metrics.SendClipTime( pVideo, timeDelta );
}
Metrics.OnKeyPointClipTime = function( pVideo, pSeconds )
{
	var timeDelta = pSeconds - Metrics.GetInstance().LastTrackedLocation;	
	Metrics.GetInstance().LastTrackedLocation = pSeconds;
	
	var s = Metrics.GetTrackingInstance( pVideo );
	var full = Player.Fullscreen;
	
	//console.log("Fullscreen is " + Player.Fullscreen);
	
	if( pSeconds == 20 )
	{	   
		s.linkTrackVars +=",events,products";
			
		if (full == true || full == "true")
		{
		    s.linkTrackEvents="event7,event9,event21";
		    s.events="event7,event9,event21";    	
		    s.products=";;;;event7=" + timeDelta+";event21="+full;
		    Utility.Log("OnKeyPointClipTime:event7=" + timeDelta+";event21="+full);
		}
		else
		{
		    s.linkTrackEvents="event7,event9";
		    s.events="event7,event9";
		    s.products=";;;;event7=" + timeDelta;
		    Utility.Log("OnKeyPointClipTime:event7=" + timeDelta);
		}
		
		var label = Metrics.TrimLabel( "[ClipId=" + Metrics.GetVideoId( pVideo ) + "] reached " +  pSeconds + " seconds" );
		Metrics.TrackLink( s, true, "o", Metrics.VIDEO_LABEL );
	}
	else 
	{
		s.linkTrackVars +=",events,products";
	
	    if (full == true || full == "true")
		{
		    s.linkTrackEvents ="event7,event10,event22";
		    s.events="event7,event10,event22";
		    s.products=";;;;event7=" + timeDelta+";event22="+full;
		    Utility.Log("OnKeyPointClipTime:event10,event7=" + timeDelta+";event22="+full);
		}
		else
		{
            s.linkTrackEvents ="event7,event10";
		    s.events="event7,event10";
		    s.products=";;;;event7=" + timeDelta;
		    Utility.Log("OnKeyPointClipTime:event10,event7=" + timeDelta);
		}
		
		Metrics.GetInstance().HasReachedEightyPercent = true;
		
		var label = Metrics.TrimLabel( "[ClipId=" + Metrics.GetVideoId( pVideo ) + "] reached " +  pSeconds + " seconds" );
		Metrics.TrackLink( s, true, "o", Metrics.VIDEO_LABEL );
	}
}
Metrics.SendClipTime = function( pVideo, pSeconds )
{
	if( pSeconds > 0 )
	{
	    var full = Player.Fullscreen;
		var s= Metrics.GetTrackingInstance( pVideo );
		
		s.linkTrackVars +=",events,products";
		s.linkTrackEvents="event7";
		
		s.events="event7";
		s.products=";;;;event7=" + pSeconds;
        Utility.Log("OnKeyPointClipTime:event7=" + pSeconds);
		var elapsedTime = Metrics.GetInstance().LastTrackedLocation;
		var label = Metrics.TrimLabel( "[ClipId=" + Metrics.GetVideoId( pVideo ) + "] reached " +  elapsedTime + " seconds" );
		
		Metrics.TrackLink( s, true, "o", Metrics.VIDEO_LABEL );
	}
}

Metrics.TrackLink = function( sInstance, param1, param2, param3 )
{
	if( ! Metrics.CanTrack )
	{
		Metrics.CanTrack = ( typeof( s_gi ) == "function" ); //the h code is already on the page if s_gi is a function
	}
	
	if( Metrics.CanTrack )
	{
		sInstance.IsTrackLink = true;
		sInstance.tl( param1,param2,param3 );
		sInstance.IsTrackLink = false;
	}
}

// The user navigated to pLocation in the library interface
Metrics.NavigatedTo = function( pLocation )
{
	var s= Metrics.GetTrackingInstance();
	
	s.linkTrackEvents = "None";
	s.linkTrackVars = "None";
	
	s.prop5 = s.eVar5 = "AJAX Web Page";
	//try
	//{
		Metrics.TrackLink( s, true, "o", pLocation );
	//}
	//catch(e)
	//{}
}

// There was the error pError loading the video pVideo.
Metrics.ErrorPlayingClip = function( pVideo, pError )
{
    var s= Metrics.GetTrackingInstance();
    
    s.linkTrackEvents = "None";
	s.linkTrackVars = "None";
    
    s.prop5 = s.eVar5 = "AJAX Error Page";
    
    try
    {
        Metrics.TrackLink( s, true, "o", "Error_" + pError + "_" + Metrics.GetVideoPath( pVideo ) );
    }
    catch( err )
    {
        Metrics.TrackLink( s, this, "o", "Error_" + pError );
    }
    
    if( Metrics.GetInstance().trackingIntervalToken != null )
	{
		clearInterval( Metrics.GetInstance().trackingIntervalToken );
		Metrics.GetInstance().trackingIntervalToken = null;
	}
}



Metrics.InteractedWithElement = function( pElementName )
{
	var s= Metrics.GetTrackingInstance();
	
	s.linkTrackEvents = "None";
	s.linkTrackVars = "None";
	
	s.prop5 = s.eVar5 = "Web Page Element Interaction";
	
	 Metrics.TrackLink( s, this, "o", pElementName );
}

Metrics.NonZero = function( pNumber )
{
    if( pNumber == -1 )
    {
        return 1;
    }
    else
    {
        return Math.abs( pNumber );
    }
}


	Metrics.CanTrack = ( typeof( s_gi ) == "function" ); //the h code is already on the page if s_gi is a function
	var autoTrackDNE = typeof( _AUTO_TRACK ) == undefined || typeof( _AUTO_TRACK ) == "undefined";
	var oldAutoTrack = false;
	
	if( ( ! autoTrackDNE ) && ( ! Metrics.CanTrack ) )
	{
		oldAutoTrack = _AUTO_TRACK;
	}
	
	var _AUTO_TRACK = oldAutoTrack;
		
	if( !  Metrics.CanTrack )
	{
		var handlerFunction	= function() { Metrics.CanTrack = true; };
		var head			= document.getElementsByTagName("body")[0];
		var newScript		= document.createElement("script");
		
		newScript.type		= "text/javascript";
		newScript.src		= "http://metrics.ctvdigital.net/global/GlobalPageTracking.js";
		
		newScript.onload = handlerFunction;
		if( newScript.onload == handlerFunction )
		{
			// DO NOTHING
		}
		else if( newScript.addEventListener )
		{
			newScript.addEventListener( "load", handlerFunction, false );
		}
		else if( newScript.attachEvent ) 
		{
			newScript.attachEvent( "onload", handlerFunction );
		}

		var isIE = navigator && navigator.appName && navigator.appName.indexOf("Explorer") > -1;
		if( isIE )
		{
			var oldOnLoad = window.onload;
			
			var onloadFunction = function() { head.appendChild( newScript ); if( oldOnLoad ) { oldOnLoad(); } };
			
			window.onload = onloadFunction;
		}
		else
		{
			head.appendChild( newScript );
		}
	}

