/*
Version 1.3
 */

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)
{
	BCGannett._madeAdRequest= 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) 
		{
			BCGannett.advertisingModule.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") !== "") 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;
				_companionAds.expandedBannerType = currentNode.getAttribute("type");
			}
			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;
			//Overlays
			if (currentNode.nodeName == "overlayURL" && currentNode.firstChild){
				ad.overlayURL = currentNode.firstChild.nodeValue;
			}
			if (currentNode.nodeName == "overlayClickURL" && currentNode.firstChild){
				ad.overlayClickURL = currentNode.firstChild.nodeValue;
			}
			if (currentNode.nodeName == "overlayDuration" && currentNode.firstChild){
				ad.overlayDuration = currentNode.firstChild.nodeValue;
			}
			if (currentNode.nodeName == "overlayBegin" && currentNode.firstChild){
				ad.overlayBegin = currentNode.firstChild.nodeValue;
			}
			currentNode = currentNode.nextSibling;
		}
		return ad;
	}
	
	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="300" height="250" id="'+pId+'" 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";
	}
	
	this.createIframe= function(pURL,id,iframeid){
		var _i = ['<iframe id="', iframeid, '" width="300" height="250" frameborder="no" scrolling="no" vspace="0" hspace="0" marginheight="0" marginwidth="0" src="', pURL,'"></iframe>'].join("");

		if(document.getElementById(id)){

			document.getElementById(id).innerHTML=_i;
		}
	};
	
	this.createJavaScriptAd = function(pURL, pId)
	{
		var scriptElem = document.createElement('script'); 
	    scriptElem.setAttribute('src', pURL); 
	    scriptElem.setAttribute('type','text/javascript');
	    
	    var iframeElem = document.createElement("iframe");
	    iframeElem.setAttribute("width", 300);
	    iframeElem.setAttribute("height", 250);
	    iframeElem.appendChild(scriptElem);
	    
	    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 = {};
		
		if(!pAd.expandedBannerType) pAd.expandedBannerType = "default";
		
		switch (_brightcoveAd.type)
		{
			case "expandedBanner":
				if(pAd.expandedBannerURL) externalAds["expandedBanner"] = {clickURL: pAd.expandedBannerClickURL, srcURL: pAd.expandedBannerURL, id: _brightcoveAd.expandedId, type: "expandedBanner", codeType: pAd.expandedBannerType};
				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", codeType: pAd.expandedBannerType};
				if(pAd.collapsedBannerURL) externalAds["collapsedBanner"] = {clickURL: pAd.collapsedBannerClickURL, srcURL: pAd.collapsedBannerURL, id: _brightcoveAd.collapsedId, type: "collapsedBanner"};
				break;
		}
	
		this.removeAd(_companionAds);
		
		for(var i in externalAds)
		{
			var banner = externalAds[i];

			if(banner.codeType.toLowerCase() == "iframe")
			{
				this.createIframe(banner.srcURL, banner.id, pOptions.iframeId);
			}
			else if(banner.codeType.toLowerCase() == "javascript")
			{
				this.createJavaScriptAd(banner.srcURL, banner.id);
			}
			else 
			{
				(banner.srcURL.indexOf('.swf') !== -1) ? this.createSwf(banner.srcURL, banner.clickURL, banner.id) : this.createImage(banner.srcURL, banner.clickURL, banner.id);	
			}
		}
	};
	
	this.createOverlay = function (pAd,duration,time) {
		var overlay= {};
		
		if(pAd.overlayURL){
			overlay= {
				type: "overlay",
				overlayURL: pAd.overlayURL,
				overlayClickURL: pAd.overlayClickURL,
				duration: (pAd.overlayDuration) ? pAd.overlayDuration : duration,
				overlayBegin: (pAd.overlayBegin) ? pAd.overlayBegin : time
			};
		}
		
		return overlay;
	};
	
	this.showAds = function(ad, companion){
			BCGannett.advertisingModule.showAd(ad);
			if(document.getElementById(pOptions.companionId)){
				var _id= document.getElementById(pOptions.companionId);		
				if(typeof companion.collapsedBannerURL=="undefined" && typeof companion.expandedBannerURL=="undefined"){
					this.getRemnantAd(pOptions.expandedId);
					return;
				}
			}else{
				return;
			}
	};
	
	this.getRemnantAd = function(id){
		if(!document.getElementById(pOptions.iframeId)){
			this.createIframe("",id,pOptions.iframeId);
		}
		
		this.setRemnantAd(pOptions.adUrl, pOptions.alias, pOptions.iframeId);
	};
	
	this.setRemnantAd= function(adUrl,alias,iframeid) {
		if(typeof gmtiCommonLibQuerySt=="function"){
			var orgKey = gmtiCommonLibQuerySt(adUrl,"key");
		}else{
			var orgKey = "";
		}
		
		var adBuiltUrl = ['http://' + adtechserver , 
				'/adiframe/3.0/' ,
				adtechnetworkid ,
				'/133600/0/-1/ADTECH;size=300x250;header=yes;cc=2;alias=' ,
				alias ,
				';cookie=info;key=' ,
				orgKey ,
				';adct=204;grp=' ,
				window.adgroupid ,
				';misc=' ,
				new Date().getTime()].join("");
									
		if(document.getElementById(iframeid)){
			document.getElementById(iframeid).src = adBuiltUrl;
		}
	};
	
	this.removeAd= function(adInfo){
		var _ad= (adInfo) ? document.getElementById(adInfo.expandedId) : document.getElementById(adInfo.collapsedId);
		
		try{
			if(_ad){
				if(typeof _ad.childNodes[0] != "undefined"){
					_ad.removeChild(_ad.childNodes[0]);
				}
			}
		}catch(e){}
	};
	
	var ad = this.buildAd(pXML);
	
	try{
		if(BCGannett._overlaysOn== true){
			BCGannett._overlay= new Overlay(pOptions);
			BCGannett._overlay.roadblockExperience(ad);
			(ad.overlayDuration) ? BCGannett._overlay.setOverlayDuration(ad.overlayDuration) : BCGannett._overlay.setOverlayDuration((BCGannett.videoPlayerModule.getCurrentVideo().length)/1000) ;
			if(ad.overlayBegin){
				BCGannett._overlay.setOverlayBegin(ad.overlayBegin);
			}
			BCGannett._overlay.setOverlayAdData(this.createOverlay(ad, BCGannett._overlay.getOverlayDuration(), BCGannett._overlay.getOverlayBegin()));
			if(Math.floor(BCGannett.videoPlayerModule.getVideoPosition()) == BCGannett._overlay.getOverlayBegin()){
				BCGannett.advertisingModule.showAd(BCGannett._overlay.getOverlayAdData());
				return;
			}else if(BCGannett._overlay.isJustOverlays()== true){
				if(typeof ad.videoURL != "undefined"){
					ad.videoURL= "";
					ad.videoClickURL= "";
				}
				BCGannett._overlay.resetJustOverlays();
			}
		}
	}catch(e){

	}
	
	if(!ad && document.getElementById(pOptions.companionId)){
		BCGannett.advertisingModule.resumeAfterExternalAd();
		this.getRemnantAd(pOptions.expandedId);
		return;
	}else if(!ad && !document.getElementById(pOptions.companionId)){
		BCGannett.advertisingModule.resumeAfterExternalAd();
		return;
	}else if(ad && !document.getElementById(pOptions.companionId)){
		BCGannett.advertisingModule.showAd(ad);
		return;
	}
	
	if(document.getElementById(pOptions.companionId)){
		this.createBanner(_companionAds);
		(ad) ? this.showAds(ad,_companionAds) : BCGannett.advertisingModule.resumeAfterExternalAd();
	}else{
		(ad) ? BCGannett.advertisingModule.showAd(ad) : BCGannett.advertisingModule.resumeAfterExternalAd();
	}
	
	//reset companion object for next ad
	_companionAds={};
}


function Overlay(gelement, type) {
	if (this === window) throw new Error("use new dude");

	var
		_options= gelement,
		_overlayDuration= _options.overlayDuration || 3600,
		_overlayBegin= _options.overlayBegin || 10,
		_overlayAd= {},
		_justOverlays= false,
		roadblock= false;
	;

	this.createArray= createArray;

	this.getOverlayDuration= getOverlayDuration;
	this.setOverlayDuration= setOverlayDuration;
	this.getOverlayBegin= getOverlayBegin;
	this.setOverlayBegin= setOverlayBegin;
	this.getOverlayAdData= getOverlayAdData;
	this.setOverlayAdData= setOverlayAdData;
	this.resetOverlayAdData= resetOverlayAdData;
	this.isJustOverlays= isJustOverlays;
	this.setJustOverlays= setJustOverlays;
	this.resetJustOverlays= resetJustOverlays;
	this.isRoadBlock= isRoadBlock;
	this.resetRoadBlock= resetRoadBlock;
	this.setRoadBlock= setRoadBlock;
	this.roadblockExperience= roadblockExperience;
	
	function isRoadBlock(){
		return roadblock;
	}
	function resetRoadBlock(){
		roadblock= false;
	}
	function setRoadBlock(){
		roadblock= true;
	}
	
	function roadblockExperience(xmlData){	
		if(typeof xmlData.overlayURL != "undefined" && 
			(typeof xmlData.expandedBannerURL != "undefined" ||
			typeof xmlData.collapsedBannerURL != "undefined")){
				setRoadBlock();
			
		}	
	}
	
	function createArray(data){
		var arr= new Array();
		arr.push(data);
		return arr;
	}
	
	function getOverlayDuration(){
		return _overlayDuration;
	}
	
	function setOverlayDuration(duration){
		_overlayDuration= duration;
	}
	
	function getOverlayBegin(){
		return _overlayBegin;
	}
	
	function setOverlayBegin(time){
		_overlayBegin= time;
	}
	
	function getOverlayAdData(){
		return _overlayAd;
	}
	
	function setOverlayAdData(data){
		_overlayAd = data;
	}
	
	function resetOverlayAdData(){
		_overlayAd= {};
	}
	
	
	
	function isJustOverlays(){
		return _justOverlays;
	};
	function setJustOverlays(){
		_justOverlays= true;
	}
	function resetJustOverlays(){
		_justOverlays= false;
	}
	
};

