/** 
* Video Ad Embedder.
* These function require the varibles: 
* dc_ref (reference to the doubeclick XML) 
* gameName (reference to the Flash game to be played). 
* 
* Execution begins with writeDivAndPlayAd -- both the player div and the ad-receiving div are written
* then autoplayer.swf is embedded with the param tag "dc_ref". Flash retrieves the XML and in turn calls setDartCommercial.  
* There are three exit paths - player detects the video ends, timer runs out or error conditions. All Paths lead to 
* embedGameInDiv which swaps in the game for the video player.
* alerts disabled for production testing
*/

//holds a reference to the video player.
var player;
//makes a reference to the end tag accessible after timeout or video 'ended'.
var endTag="";
var timeoutID;
var playerReady;
var duration;

// global variables to render swf
var swfSrc = "";
var swfDuration = "";
var swfStartTag = "";
var swfEndTag = "";
var swfClickTag = "";

//begin by writing a div which will hold the player and then the game embed.
function writeDivAndPlayAd(dc_ref){
	//alert("writeDiv dc_ref= " + dc_ref);
	
	//small div holds retreived startTag and endTag
	document.write('<div id="ad1"></div>');
	document.getElementById("ad1").style.visibility = "hidden";
	//holds the video player and then the game
	document.write('<div id="play1"></div>');

	if (navigator.userAgent.indexOf("Mac") != -1){
		//alert("it's a mac!");
		document.getElementById ( 'play1' ).innerHTML = getFlashEmbedHtml(dc_ref);
		player = window.document.flashVideo;
	} else {
		document.getElementById ( 'play1' ).innerHTML = getFlashEmbedHtml(dc_ref);
		player = window.document.flashVideo;
  	}
	// Set a default timeout to ensure the game is shown if ad call fails
	timeoutID = setTimeout( "playerTrouble('default timeout in writeDivAndPlayAd()')", 45 * 1000 );
}

/**
 * autoplayer.swf is the Flash Video Player adn XML parser. This javascript function
 * writes the object tag which embeds the flash player. It does not load an flv file into
 * the object tag. Note use of dc_ref to pass in the location of the XML. 
 */
function getFlashEmbedHtml ()
{

	var flashHtml = "";
	flashHtml += '<object id="flashVideo" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
	flashHtml += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"';
	flashHtml += 'width="480" height="360" align="middle">';
	flashHtml += '<param name="allowScriptAccess" value="always" />';
	flashHtml += '<param name="movie" value="/jsource/autoparser.swf" />';
	flashHtml += '<param name="quality" value="high" />';
	flashHtml += '<param name="bgcolor" value="#000000" />';
	flashHtml += '<param name="FlashVars" value="clickTag=http://www.adobe.com&debug=false&dc_ref=' + dc_ref + '">';
	flashHtml += '<embed src="/jsource/autoparser.swf" quality="high" bgcolor="#000000" width="480" height="360" name="flashVideo" align="middle"';
	flashHtml += ' FlashVars="clickTag=http://www.adobe.com&debug=false&dc_ref=' + dc_ref + '" '; 
	flashHtml += 'align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"';
	flashHtml += 'pluginspage="http://www.macromedia.com/go/getflashplayer" />';
	flashHtml += '</object>';
	return flashHtml;
}

//starts the video, requests startTag, sets Timer for div switch and endTag request 
function setDartCommercial_original(dc_startTag, dc_endTag, dc_type, dc_duration, dc_src, clickTag){
	if(!dc_src){
		//alert("dc_src is : " + dc_src);
		embedGameInDiv();
	} else {
		//alert("playerReady is " +playerReady);
		endTag = dc_endTag;
		
		//alert("player: " + player);
		player.loadAndPlay(dc_src, 0);
		
		//alert(dc_startTag);
		//alert("dc_duration is: " + dc_duration);
		dc_duration=parseInt(dc_duration);
		dc_duration += 2;
		duration=dc_duration*1000;
		//write startTag
		timeoutID = setTimeout("embedGameInDiv(gameName)", duration);
		//timeoutID = setTimeout("timerFired()", duration);
		
		document.getElementById ( 'ad1' ).innerHTML = '<img src="' + dc_startTag + '">';	
	}
}


/**
 * creates an object tag with for id found in path that is width x height
 * in size.
 */
function flashEmbed(path, id, width, height)
{
    // alert ( 'in FlashEmbed' );
    writeVar='<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,22,0" WIDTH="' + width;
    writeVar+='" HEIGHT="' + height + '" id="'+ id + '">';
    writeVar+='<PARAM NAME="movie" VALUE="' + path + '"><PARAM NAME="quality" VALUE="high">';
    writeVar+='<PARAM NAME="AllowScriptAccess" VALUE="always"><EMBED src="' + path + '"';
    writeVar+=' quality="high" WIDTH="' + width + '" HEIGHT="' + height + '" NAME="' + id + '"';
    writeVar+=' AllowScriptAccess="always" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">';
    writeVar+='</EMBED></OBJECT>';
    // alert( "in flashEmbed: " + writeVar);
    return writeVar;
}

/**
 * puts either start or end tag in ad1 div to track impressions.
 */
var seenOnce = 0;
function renderImpression ( startOrEndTag )
{
    //alert( "renderImpression() startOrEndTag=" + startOrEndTag );
    if ( !endTag || endTag == "undefined" || endTag == "" )
    {
        //alert ( "not using end tag" );
    }
    else
    {
        startOrEndTag = endTag;
        endTag = "";
        // alert ( "start or end tag: " + startOrEndTag + " or end tag: " + endTag );
    }

    if ( startOrEndTag && startOrEndTag != null && startOrEndTag != 'undefined' )
    {
        //alert ( "** now trying to track impression: " + startOrEndTag );
        var adDiv = document.getElementById ( 'ad1' );

        if ( adDiv != null )
        {
            // alert ( "*** adding the start tag" );
            adDiv.innerHTML = '<img src="' + startOrEndTag + '" width="1" height="1">';
        }
        else
        {
            // alert ( 'adDiv is null' );
        }
    }
    else
    {
        // alert ( "*** start or end tag not showing up OK" );
    }
}

/**
 * to combat Macintosh issue of swf inside a swf, we will replace the div with the autoparser.swf
 * with an object tag of the swf source from DART.
 */
function renderSwf ()
{
    // called from timer
    // alert( "*** in renderSwf: " + swfSrc );
    swfDuration = parseInt( swfDuration );

    // alert ( "about to render " + dc_src + " and update duration to: " + dc_duration );
    var preplayArea = window.document.getElementById ( "play1" );

    if ( preplayArea != null )
    {
        // this issues an impression for the start tag
        renderImpression ( swfStartTag );

        swfSrc = swfSrc + "?clickTag=" + swfClickTag;

        // alert ( "*** contents: " + flashEmbed( swfSrc , "preplayMovie", 480, 360 ) );
        preplayArea.innerHTML = flashEmbed( swfSrc , "preplayMovie", 480, 360 );

        //grace period
        duration = parseInt ( swfDuration );
        endTag = swfEndTag;

	// Give some padding to the preplay duration to account for swf loading
        duration += 2;

	// Set the timeout to render the game after the ad is done
	var preplayDurationTimer = setTimeout( "embedGameInDiv()", duration * 1000 );
    }
}


// adding SW version here
/**
 * called from autoparser. Starts the video, requests startTag, sets Timer for div switch and
 * endTag request.
 */
function setDartCommercial(dc_startTag, dc_endTag, dc_type, dc_duration, dc_src, clickTag)
{
    var dartContents =  "*** arguments for setDartCommercial: \r\n";
    dartContents +=     "dc_startTag: " + dc_startTag + "\r\n";
    dartContents +=     "dc_endTag: " + dc_endTag + "\r\n";
    dartContents +=     "dc_type: " + dc_type + "\r\n";
    dartContents +=     "dc_duration: " + dc_duration + "\r\n";
    dartContents +=     "dc_src: " + dc_src + "\r\n";
    dartContents +=     "clickTag: " + clickTag + "\r\n";

    //alert ( dartContents );
    //alert ( "startTag " + dc_startTag );
    if ( ( !dc_src )  || ( dc_duration == "undefined" ) || ( dc_duration == null ) &&
           ( clickTag == "undefined" ) || ( clickTag == null ) )
    {
         //alert("dc_src is : " + dc_src);
        // leave the div alone
    }
    else if ( dc_type == "swf" )
    {
        // 5 frame black swf to play just so parser can unload
        // fixes Macintosh issue
        player.loadAndPlay ( "/jsource/black.swf", 0 );

        swfSrc = dc_src;
        swfDuration = dc_duration;
        swfStartTag = dc_startTag;
        swfEndTag = dc_endTag;
        swfClickTag = clickTag;

        var swfTimer = setTimeout ( "renderSwf()", 1000 );
    }
    else
    {
        //alert ( "endTag: " + dc_endTag );
        endTag = dc_endTag;

        //alert("player in setDartCommercial: " + player + " and src: " + dc_src );
        player.loadAndPlay( dc_src, 0 );

        //alert(dc_startTag);
        dc_duration=parseInt( dc_duration );

        var impressionTimer = setTimeout ( "embedGameInDiv()", ( dc_duration + 1 ) * 1000 );

		// AG code does not use updatePreplayDuration(), commented out for now
        //grace period
        //dc_duration += 2;
        // alert ( 'preplay duration: ' + dc_duration );
        //duration = dc_duration * 1000;
        //updatePreplayDuration ( dc_duration );

        //alert(duration);

		// Set the startTag which is to track impressions
        var myAd1 = document.getElementById ( 'ad1' );

        if ( myAd1 != null )
        {
            //alert ( "found myAd1! and startTag: " + dc_startTag );
            myAd1.innerHTML = '<img src="' + dc_startTag + '" height="1" width="1">';
        }
        else
        {
			//alert ( "myAd1 is null!" );
        }
    }
}

function handlePlayStateChangeEvent(state)
{
	if (state == "ready")
	{
		playerReady=true;
		//need to ensure current state is ready before calling ad placement. 	
	}
	if (state == "ended")
	{
		embedGameInDiv();
	}
	if (state == "buffering")
	{
		//alert("buffering");
	}
}
function playerTrouble(desc){
	// alert(desc);
	// alert("playerTrouble called embedGameInDiv which returned to playerTrouble");
	embedGameInDiv();
	// Call script, send notification, details, possibly tally error, count on  time interval
	/*$(function(){ 
	          $.get(                              
	            'script.php',                
	            {issue:Preplay Package Empty, id:1, page:pageName, send:1, instance:name},                  
	            function(data) { alert(data); }   
	          );
	});
	*/ 	
}

//gameName is set at embedding
function embedGameInDiv(){	
	//alert("embedGameInDiv");
	//clear the timeout just in case
	if(timeoutID) {clearTimeout(timeoutID);}
	//alert(timeoutID);
	
	if ( endTag && endTag != null && endTag != 'undefined' )
	{
	    document.getElementById ( 'ad1' ).innerHTML = '<img src="' + endTag + '">';	
	}
	flashContents=writeFlash(gameName, gameWidth, gameHeight);
	//alert(flashContents);
	document.getElementById ('play1').innerHTML = flashContents;
}

function divContents(){
	//alert(document.getElementById('play1').innerHTML);
}

//callable by the Flash if it has something to say.
function triggerAlert(alertText){
	//alert(alertText);
}

//standard embed does the document.write, I just need the assembled string.
function writeFlash(path, width, height)
{
	writeVar='<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,22,0" WIDTH="' + width;
	writeVar+='" HEIGHT="' + height + '" id="FlashContent">';
	writeVar+='<PARAM NAME="movie" VALUE="' + path + '"><PARAM NAME="quality" VALUE="high">';
	writeVar+='<PARAM NAME="AllowScriptAccess" VALUE="never"><EMBED src="' + path + '"';
	writeVar+=' quality="high" WIDTH="' + width + '" HEIGHT="' + height + '" NAME="FlashContent"';
	writeVar+=' AllowScriptAccess="never" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">';
	writeVar+='</EMBED></OBJECT>';
	return writeVar;
}