//edit these variables when including this JS on the page
var brightcoveID = "myExperience"; //the id of the player on the page
var expandedID = "AdBanner"; //the id of the HTML element on the page where the 300x250 should be rendered



//TODO: remove all bc_videoPlayer stuff
//-------------------------------------------------------------------------------------- BRIGHTCOVE PLAYER API METHODS
var bc_player, bc_experience, bc_advertising; //brightcove specific global vars
var bc_videoPlayer;

function onTemplateLoaded(experienceID)
{
	bc_player = brightcove.getExperience(brightcoveID);
	
	//experience related
	bc_experience = bc_player.getModule(APIModules.EXPERIENCE);
	bc_experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
	
	//advertising related
	bc_advertising = bc_player.getModule(APIModules.ADVERTISING);
	bc_advertising.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
	
	bc_videoPlayer = bc_player.getModule(APIModules.VIDEO_PLAYER);
	//bc_videoPlayer.addEventListener(BCVideoEvent.STREAM_START, onStreamStart);
	onTemplateLoaded_ext(experienceID);
}

function onTemplateLoaded_ext(experienceID) 
{
	//This is stub for anyone that wants to extend this function.
}

function onStreamStart(pEvent)
{
	bc_videoPlayer.stop();
	bc_videoPlayer.setEnabled(false);
}

function onContentLoad()
{	
	bc_advertising.enableExternalAds();
}

function onExternalAd(pAdString, callback)
{
	//console.log("onExternalAd");
	/*
	 * Options that can be passed in:
	 * type: [expandedBanner, collapsedBanner, both] (defaults to expandedBanner)
	 * expandedId: the element ID of where the expanded banner should be placed
	 * collapsedId: the element ID of where the collapsed banner should be placed
	 * 
	 * "Expanded Banner": This is a throwback to the older monolithic templates we used to use, but the terminology
	 * remained because that's what it still says in the ad XML, but typically an expanded banner is a 300x250 unit,
	 * although it could be anything. It's called the expanded banner because in the larger templates you can click
	 * an "expand" button to reshow the 300x250 at any point.
	 * 
	 * "Collapsed Banner": Also a throwback, but the collapsed banner is usually a 728x90 but could be any unit. It's 
	 * called so because the collapsed banner had a relationship to the expanded banner where when the 300x250 animated
	 * off screen, it looked like it "collapsed" into the 728x90.
	 */
	
	try
	{
		new ExternalAd(pAdString, 
		{
			type: 'expandedBanner',
			expandedId: expandedID
		});
	}
	catch(pError)
	{
		//bc_advertising.resumeAfterExternalAd();
		 bc_advertising.showAd("_blank");
	}
	
	
}
//--------------------------------------------------------------------------------------






/**
 * @author Brandon Aaskov (Brightcove)
 * @version 1.0
 * @projectDescription 
 */

var _brightcoveAd = new Object();
var _companionAds = new Object();

/**
 * Takes care of parsing the XML that comes back from the ad server, building the ad object, and displaying the ads in both the player and on the page. It should be noted that the ad XML that comes back from the ad server needs to be one of the supported Rich Media templates that Brightcove distributes for use with DFP and other ad serving platforms.
 * @param {String} pXML The XML string that gets returned from the ad server. Needs to be one of the templates supported by Brightcove.
 * @param {Object} pOptions An object that contains options for further customization. By default, this function will render the expanded banner (eg type: "expandedBanner") and also write out the banner to a div with the id of "expandedBanner" (eg writeTo: "expandedBanner"). For the type option, you can also choose "collapsedBanner". For the writeTo option, a user can specify the ID of any element they'd like.
 */

function ExternalAd(pXML, pOptions)
{	
	//console.log(pXML);
	//pXML = this.xmlReplace(pXML);
	var showAd = true;
	
	if (pOptions) 
	{
		_brightcoveAd.expandedId = (pOptions.expandedId) ? pOptions.expandedId : "expandedBanner";
		_brightcoveAd.collapsedId = (pOptions.collapsedId) ? pOptions.collapsedId : "collapsedBanner";
		_brightcoveAd.type = (pOptions.type) ? pOptions.type : "expandedBanner";
	}
	else
	{
		_brightcoveAd.expandedId = "expandedBanner";
		_brightcoveAd.collapsedId = "collapsedBanner";
		_brightcoveAd.type = "expandedBanner";
	}
	
	/**
	 * Parses the XML from the ad server and builds the ad object from it.
	 * @param {Object} pXML The XML returned from the ad server.
	 */
	this.buildAd = function(pXML)
	{	
		if (pXML.ad.indexOf("<a ") !== -1) 
		{
			bc_advertising.showAd("_blank");
			showAd = false;
			return;
		}
	
		if (window.ActiveXObject)
	  	{
			//parses the XML for IE browsers
			var adXML = new ActiveXObject("Microsoft.XMLDOM");
			adXML.async = false;
			adXML.loadXML(pXML.ad);
		}
		else if (window.XMLHttpRequest)
		{
			var adXML = (new DOMParser()).parseFromString(pXML.ad, "text/xml"); //parses the XML for Mozilla browsers
		}
		
		var ad = new Object();
		ad.type = "videoAd";
		
		var rootNodeName = adXML.firstChild.nodeName;
		if(rootNodeName == "Banner300x60" || rootNodeName == "SynchedBanner300x60") bc_advertising.showAd("_blank");
		
		var nodeItems = adXML.firstChild.childNodes.length;
		var currentNode = adXML.firstChild.firstChild;
		
		//get the root node attributes
		ad.duration = (adXML.firstChild.getAttribute("duration") !== "") ? Number(adXML.firstChild.getAttribute("duration")) : 15;
		if(adXML.firstChild.getAttribute("trackStartURLs") !== "") ad.trackStartURLs = adXML.firstChild.getAttribute("trackStartURLs").split(",");
		if(adXML.firstChild.getAttribute("trackMidURLs") !== "") ad.trackMidURLs = adXML.firstChild.getAttribute("trackMidURLs").split(",");
		if(adXML.firstChild.getAttribute("trackEndURLs") !== "") ad.trackEndURLs = adXML.firstChild.getAttribute("trackEndURLs").split(",");
		if(adXML.firstChild.getAttribute("trackPointURLs") && (adXML.firstChild.getAttribute("trackPointURLs") !== "")) ad.trackPointURLs = adXML.firstChild.getAttribute("trackPointURLs").split(",");
		ad.trackPointTime = (adXML.firstChild.getAttribute("trackPointTime") && (adXML.firstChild.getAttribute("trackPointTime") !== "")) ? Number(adXML.firstChild.getAttribute("trackPointTime")) : 0;
	
		for(var i = 0; i < nodeItems; i++)
		{
			//checks to see if the current nodes are in our Rich Media Templates and assigns them if they exist
			if(currentNode.nodeName == "videoURL" && currentNode.firstChild) ad.videoURL = currentNode.firstChild.nodeValue; 
			if(currentNode.nodeName == "videoClickURL" && currentNode.firstChild) ad.videoClickURL = currentNode.firstChild.nodeValue;
			if(currentNode.nodeName == "expandedBannerURL" && currentNode.firstChild) _companionAds.expandedBannerURL = currentNode.firstChild.nodeValue;
			if(currentNode.nodeName == "expandedBannerClickURL" && currentNode.firstChild) _companionAds.expandedBannerClickURL = currentNode.firstChild.nodeValue;
			if(currentNode.nodeName == "collapsedBannerURL" && currentNode.firstChild) _companionAds.collapsedBannerURL = currentNode.firstChild.nodeValue;
			if(currentNode.nodeName == "collapsedBannerClickURL" && currentNode.firstChild) _companionAds.collapsedBannerClickURL = currentNode.firstChild.nodeValue;
			if(currentNode.nodeName == "bannerURL" && currentNode.firstChild) _companionAds.expandedBannerURL = currentNode.firstChild.nodeValue; 
			if(currentNode.nodeName == "bannerClickURL" && currentNode.firstChild) _companionAds.expandedBannerClickURL = currentNode.firstChild.nodeValue; 
			if(currentNode.nodeName == "showAd" && currentNode.firstChild) 
			{
				if(currentNode.firstChild.nodeValue == "false") showAd = false;
				//console.log("SHOW AD IS: "+showAd);
			}
			
			currentNode = currentNode.nextSibling;
		}
		
		return ad;
	}
	
	this.createSwf = function(pURL, pClickThrough, pId)
	{
		var time = new Date();
		
		var objectTag = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="300" height="250" id="'+time.getTime()+'" align="middle">\n';
		objectTag += '\t<param name="allowScriptAccess" value="always" />\n';
		objectTag += '\t<param name="movie" value="' + pURL + '" />\n';
		objectTag += '\t<param name="quality" value="high" />\n';
		objectTag += '\t<param name="bgcolor" value="#ffffff" />\n';
		objectTag += '\t<param name="wmode" value="transparent" />\n'; 
		objectTag += '\t<param name="FlashVars" value="clickTag=' + pClickThrough + '" />\n';
		objectTag += '\t<embed src="' + pURL + '" quality="high" bgcolor="#ffffff" width="300" height="250" name="expandedBanner" align="middle" allowScriptAccess="always" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="clickTag='+pClickThrough+'" />\n';
		objectTag += '</object>\n';
		
		if(document.getElementById(pId)) document.getElementById(pId).innerHTML = objectTag;
	}
	
	this.createImage = function(pURL, pClickThrough, pId)
	{
		if(document.getElementById(pId)) document.getElementById(pId).innerHTML = "<a href='" + pClickThrough + "' target='_blank' ><img src='" + pURL + "' /></a>\n";
		/*
		if(document.getElementById(pId))
		{
			var iframeElem = document.createElement('iframe');
			iframeElem.setAttribute('width', '300');
			iframeElem.setAttribute('height', '250');
			iframeElem.setAttribute('scrolling', 'no');
			iframeElem.setAttribute('frameborder', '0');
			iframeElem.setAttribute('src', pURL);
			
			document.getElementById(pId).innerHTML = '';
			document.getElementById(pId).appendChild(iframeElem);
		}
		*/
	}
	
	/**
	 * Writes the banner out to the page, and determines wheter or not it's a swf or regular image so that the correct tags are written to the page.
	 * @param {Object} pAd The ad object containing all of the information to display an ad in the player and render an ad on the page.
	 */
	this.createBanner = function(pAd)
	{
		var externalAds = {};
		
		switch (_brightcoveAd.type)
		{
			case "expandedBanner":
				if(pAd.expandedBannerURL) externalAds["expandedBanner"] = {clickURL: pAd.expandedBannerClickURL, srcURL: pAd.expandedBannerURL, id: _brightcoveAd.expandedId, type: "expandedBanner"};
				break;
			case "collapsedBanner":
				if(pAd.collapsedBannerURL) externalAds["collapsedBanner"] = {clickURL: pAd.collapsedBannerClickURL, srcURL: pAd.collapsedBannerURL, id: _brightcoveAd.collapsedId, type: "collapsedBanner"};
				break;
			case "both":
				if(pAd.expandedBannerURL) externalAds["expandedBanner"] = {clickURL: pAd.expandedBannerClickURL, srcURL: pAd.expandedBannerURL, id: _brightcoveAd.expandedId, type: "expandedBanner"};
				if(pAd.collapsedBannerURL) externalAds["collapsedBanner"] = {clickURL: pAd.collapsedBannerClickURL, srcURL: pAd.collapsedBannerURL, id: _brightcoveAd.collapsedId, type: "collapsedBanner"};
				break;
		}
				
		for(var i in externalAds)
		{
			var banner = externalAds[i];
			(banner.srcURL.indexOf('.swf') !== -1) ? this.createSwf(banner.srcURL, banner.clickURL, banner.id) : this.createImage(banner.srcURL, banner.clickURL, banner.id);	
		}
	}

	var ad = this.buildAd(pXML);
	this.createBanner(_companionAds);
	if(showAd) bc_advertising.showAd(ad);
}
