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




//-------------------------------------------------------------------------------------- BRIGHTCOVE PLAYER API METHODS
var bc_player, bc_experience, bc_advertising; //brightcove specific global vars

function onTemplateLoaded()
{
	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);//externalAd
	bc_advertising.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
}

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

function onExternalAd(pAdString, callback)
{
	/*
	 * 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.
	 */
	new ExternalAd(pAdString, 
	{
		type: 'collapsedBanner',
		collapsedId: collapsedID
	});
}
//--------------------------------------------------------------------------------------

/**
 * @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)
{	
	//pXML = this.xmlReplace(pXML);
	var showAd = true;
	var hideBanner = 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)
	{	
		//we should never freeze the player so I am putting this in a wrapper
		try {
			//console.log(pXML.ad);
			if (pXML.ad.indexOf("<a ") !== -1) 
			{
				showAd = false;
				bc_advertising.resumeAfterExternalAd();
				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 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") && adXML.firstChild.getAttribute("trackStartURLs") !== "")
				ad.trackStartURLs = adXML.firstChild.getAttribute("trackStartURLs").split(",");
			
			
			if(adXML.firstChild.getAttribute("trackMidURLs") && adXML.firstChild.getAttribute("trackMidURLs") !== "")
				ad.trackMidURLs = adXML.firstChild.getAttribute("trackMidURLs").split(",");
			
			if(adXML.firstChild.getAttribute("trackEndURLs") && 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;
	
			var isOverlay = false;

			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) 
				{
					if(_brightcoveAd.type == "collapsedBanner") 
					{
						ad.type = "synchedBanner728x90";
						ad.expandedBannerURL = currentNode.firstChild.nodeValue;
					}
					else _companionAds.expandedBannerURL = currentNode.firstChild.nodeValue;
				}
				if(currentNode.nodeName == "expandedBannerClickURL" && currentNode.firstChild) 
				{
					if(_brightcoveAd.type == "collapsedBanner") ad.expandedBannerClickURL = currentNode.firstChild.nodeValue;
					else _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 == "overlayURL" && currentNode.firstChild)
				{
					isOverlay = true;
					ad.overlayURL = currentNode.firstChild.nodeValue;
				}	
				if(currentNode.nodeName == "overlayClickURL" && currentNode.firstChild) ad.overlayClickURL = currentNode.firstChild.nodeValue;
				
				//Adding in for the banner only campaign they are running.
				if(currentNode.nodeName == "bannerURL" && currentNode.firstChild) {
					_companionAds.collapsedBannerURL = currentNode.firstChild.nodeValue;
					hideBanner = false;
				}
				if(currentNode.nodeName == "bannerClickURL" && currentNode.firstChild) _companionAds.collapsedBannerClickURL = currentNode.firstChild.nodeValue;
				currentNode = currentNode.nextSibling;
			}
			if(isOverlay) {
				ad.type = "synchedOverlay728x90";
			} else if(!ad.videoURL) { 
				showAd = false;
			}
			
			return ad;
			
		} catch (e) {
			bc_advertising.resumeAfterExternalAd();
			showAd = false;
			return null;
		}
	}
	
	this.createSwf = function(pURL, pClickThrough, pId)
	{
		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="728" height="90" id="bannerAd" 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="728" height="90" name="collapsedBanner" 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";
	}
	
	/**
	 * 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);
	} else if(document.getElementById(_brightcoveAd.collapsedId) && hideBanner) {
		document.getElementById(_brightcoveAd.collapsedId).innerHTML = "";
		bc_advertising.resumeAfterExternalAd();;
	} else {
		bc_advertising.resumeAfterExternalAd();
	}
}


