/*
 * Ad: an individual ad package to be displayed.  Includes all co-ad elements.
 */
function Ad( pPrerollFormat, pAfterFunction )
{
	this.PrerollVideo = null; // a Video object
	this.BigBox = ""; // the URL of the ad javascript that will serve a Big Box ad unit
	this.StartImageTracker = ""; // the URL of an image to serve when the preroll video starts
	this.EndImageTracker = ""; // the URL of an image to serve when the preroll video ends
	this.PrerollFormat = pPrerollFormat; // the format of the PrerollVideo
	
	this.AfterFunction = pAfterFunction; // the function to call after an ad is loaded
	this.IsLoaded = false;
	this.IsDestroyed = false;
	
	this.LastAdCall = "";
	this.LoaderTag = null;
	
	this.AdIndex = Ad.SetInstance( this );
	return this.AdIndex;
	
}
Ad.DARTSite = "video.ctv";

Ad.GetInstance = function( i )
{
	if( ! Ad.__instance )
	{
		throw "Trying to get an instance of the Ad before it has been initialized";
		return;
	}
	else if( i != null && i >= 0 )
	{	
		return Ad.__instance[i];
	}
	else
	{
		return Ad.__instance[ Ad.__instance.length - 1 ];
	}
}
Ad.SetInstance = function( pAd )
{
	if( ! Ad.__instance )
	{
		Ad.__instance = new Array();
	}
	
	Ad.__instance.push( pAd );
	
	return Ad.__instance.length - 1;
}

Ad.DARTVideoTag = function( pVideo )
{
    if( ! pVideo.SiteMap )
    {
        return "default;permalink=;clip=" + pVideo.ClipId;
    }
    else
    {
        var AdCall = "";
        for( var i = pVideo.SiteMap.length - 1; i >= 0; i-- )
        {
            if( AdCall == "" )
            {
                AdCall += pVideo.SiteMap[i][0].replace( /[^a-zA-Z0-9]/ig, "" ) + ";permalink=";
            }
            
            AdCall += "/" + pVideo.SiteMap[i][0].replace( /[^a-zA-Z0-9]/ig, "" );
        }
        
        AdCall += "/ClipId" + pVideo.ClipId; 
        
        AdCall += ";clip=" + pVideo.ClipId;
        

        return AdCall;
    }
}


Ad.GetPreroll = function (pFormat, pAfterFunction, ord, tile) {
    var NewAd = new Ad(pFormat, pAfterFunction);
    var AdIndex = Ad.SetInstance(NewAd);

    // Load the Javascript on the page

    var full = Player.Fullscreen;

    var AdCall = "http://ad.doubleclick.net/pfadx/" + Ad.DARTSite + "/";

     if (full == "true" || full==true) {
        AdCall += "f/";
    }

    var UpcomingVideo = Playlist.GetInstance().FindNext();

    AdCall += Ad.DARTVideoTag(UpcomingVideo);

    AdCall += ";sz=1x1";

    if (ord == null) {
        ord = Ad.GenerateOrd();
    }

    AdCall += ";ord=" + ord;

    if (tile != null) {
        AdCall += ";tile=" + tile;
    }

    // AdCall += ";fullScreen=" + full;
    //demographics
    //AdCall = "http://ad.doubleclick.net/pfadx/ctv.ctvwatch.ca/billsdesk;kw=bill;sz=1x1;ord=6365884;format=flv";

    //canvas test
    //AdCall = "http://ad.doubleclick.net/pfadx/ctv.ctvwatch.ca/RobsonArms;permalink=/RobsonArms/Season3/Ep312quotMyBrothersKeeperquot/ClipId49744;clip=49744;sz=1x1;ord=6243214;format=flv";

    //AdCall = "http://ad.doubleclick.net/pfadx/ctv.ctvwatch.ca/billsdesk;permalink=/TheDailyShowwithJonStewart/FullEpisodes/June282010/ClipId319520;clip=319520;sz=1x1;ord=2650393;fullScreen=true;format=flv";

    // Javascript will call back to Ad.Load(...)
    //********DEBUG*********//
    if (pFormat == Format.FlashVideo) {
        var AdScript = document.createElement("script");
        AdScript.src = AdCall + ";format=flv";
        Log("Getting an ad from " + AdScript.src);
        AdScript.type = "text/javascript";

        document.getElementsByTagName("head")[0].appendChild(AdScript);

        NewAd.LoaderTag = AdScript;

        NewAd.LastAdCall = AdScript.src;
    }
    else {

        var AdScript = document.createElement("script");
        AdScript.src = AdCall + ";format=wmv";
        Log("Getting an ad from " + AdScript.src);
        AdScript.type = "text/javascript";
        document.getElementsByTagName("head")[0].appendChild(AdScript);

        NewAd.LoaderTag = AdScript;

        NewAd.LastAdCall = AdScript.src;
    }
    //********DEBUG*********//

    setTimeout("Ad.GetInstance(" + AdIndex + ").CheckForLoadFailure()", 4000);

    return NewAd;

}
Ad.Load = function( pAdInfo )
{
	var _Ad = Ad.GetInstance();
	
	if( ! pAdInfo.Preroll )
	{
		Log( "Ad.Load was called with invalid parameters.  A standard big box ad will be served." );
		
		if( Interface.SetBigBoxAd ) { Interface.SetBigBoxAd(); }
		
		return;
	}
	
	if( ! _Ad.IsDestroyed )
	{
		_Ad.PrerollVideo = new Video( { Url:pAdInfo.Preroll, Format:_Ad.PrerollFormat, IsAd:true, Duration:pAdInfo.PrerollDuration, Permalink:pAdInfo.CoAdLink } );
		_Ad.BigBox = pAdInfo.CoAdCode;
		_Ad.StartImageTracker = pAdInfo.StartPlayImage;
		_Ad.EndImageTracker = pAdInfo.EndPlayImage;

		if( Interface.SetBigBoxAd ) { Interface.SetBigBoxAd( _Ad.BigBox ); }
		
		_Ad.PrerollVideo.OnStart = function()
		{
			Log( "Started playing the ad" );
			if( _Ad.StartImageTracker ) ( new Image() ).src = _Ad.StartImageTracker;
			
			//if( Interface.SetBigBoxAd ) { Interface.SetBigBoxAd( _Ad.BigBox ); }
		}
		
		_Ad.PrerollVideo.OnEnd = function()
		{
			Log( "Ended playing the ad" );
			if( _Ad.EndImageTracker ) ( new Image() ).src = _Ad.EndImageTracker;
		}
		
		
		_Ad.IsLoaded = true;
		
		setTimeout( function() { _Ad.AfterFunction( _Ad.PrerollVideo ) }, 350 );
	}
}

Ad.prototype.BigBoxImage = function()
{
	if( Interface && Interface.GetInstance && Interface.GetInstance() )
	{
		var _Interface	= Interface.GetInstance();
		var iFrameDoc	= _Interface.BigBoxHolder.contentDocument ? _Interface.BigBoxHolder.contentDocument : ( _Interface.BigBoxHolder.contentWindow ? _Interface.BigBoxHolder.contentWindow.document : document.frames[ 0 ] );
		var images		= iFrameDoc.getElementsByTagName("img");
		
		if( images && images.length > 0 )
		{
			return images[ 0 ].src;	
		}
	}
	
	return "";
}

Ad.prototype.BigBoxSWF = function()
{
	if( Interface && Interface.GetInstance && Interface.GetInstance() )
	{
		var _Interface	= Interface.GetInstance();
		var iFrameDoc	= _Interface.BigBoxHolder.contentDocument ? _Interface.BigBoxHolder.contentDocument : ( _Interface.BigBoxHolder.contentWindow ? _Interface.BigBoxHolder.contentWindow.document : document.frames[ 0 ] );
		
		var flashObject = iFrameDoc.getElementsByTagName( "object" );
		var embed		= iFrameDoc.getElementsByTagName( "embed" );
		
		if( flashObject &&  flashObject.length > 0 )
		{
			flashObject = flashObject[ 0 ];
			
			var params	= flashObject.getElementsByTagName( "param" );
			
			for( i=0; i< params.length; i++ )
			{
				if( params[ i ].name.toLowerCase() == "movie" || params[ i ].value.toLowerCase().indexOf(".swf") > -1 )
				{
					if( params[ i ].value )
					{
						return params[ i ].value;
					}
				}
			}
		}

		if( embed &&  embed.length > 0 )
		{
			if( embed[ 0 ].src )
			{
				return embed[ 0 ].src;
			}
		}
		
	}
	
	return "";
}

Ad.prototype.BigBoxTargetURL = function()
{
	if( Interface && Interface.GetInstance && Interface.GetInstance() )
	{
		var _Interface	= Interface.GetInstance();
		var iFrameDoc	= _Interface.BigBoxHolder.contentDocument ? _Interface.BigBoxHolder.contentDocument : ( _Interface.BigBoxHolder.contentWindow ? _Interface.BigBoxHolder.contentWindow.document : document.frames[ 0 ] );
		
		var anchors		= iFrameDoc.getElementsByTagName("a");
		if( anchors && anchors.length > 0 )
		{
			return anchors[ 0 ].href;	
		}
	}
	
	return "";
}

Ad.prototype.CheckForLoadFailure = function() 
{
	if( ! this.IsLoaded )
	{
		this.Destroy();
		Playlist.GetInstance().Next( true ); // continue with the playlist without loading the ad
		//throw "Failed to load Ad with '" + this.PrerollFormat + "' format." /*+ "The ad was " + this.LastAdCall*/;
	}
	else
	{
		this.IsVerified = true;
	}
	
	this.LastAdCall = "";
}

Ad.prototype.Destroy = function()
{
	this.IsDestroyed = true;
	
	try
	{
		this.LoaderTag.parentNode.removeChild( this.LoaderTag ); 
	}
	catch( Error )
	{}
	
	Log( "Destroyed Ad " + this.AdIndex );
	
	Ad.__instance[ this.AdIndex ] = null;

}

Ad.GenerateOrd = function () {
    return Math.round(10000000 * Math.random());
}

