/* Main file to serve companion Banners (static, dynamic and float)*/

//global variable which will hold reference to all the players and their banners and individual setting
if (yumePlayerList == undefined){
	var yumePlayerList = {};
}
/*
This is the main class which contains methods that are used globally
*/
function YumePlayerObject (){
}
// Method used to add players to the global object yumePlayerList
YumePlayerObject.addPlayer = function(playerRef){
	var refId = playerRef.playerID;
	playerRef.init();
	yumePlayerList[refId] = new YumePlayer;
	yumePlayerList[refId] = playerRef;
}
// member which specifies the z-index for the floating companion banners
YumePlayerObject.zIndex = 1000;
//Function to figure out the X, Y, Width and Height of the object\div element
YumePlayerObject.findPlayerPos = function(yume_find_pos_obj) {
	var pObj = {};
	pObj.curleft = 0; pObj.curtop = 0; pObj.curW = 0; pObj.curH = 0;
	pObj.curW=getDivProp(yume_find_pos_obj,"width")
	pObj.curH=getDivProp(yume_find_pos_obj,"height")
	if(yume_find_pos_obj.offsetParent)
		while(1) {
			pObj.curleft += yume_find_pos_obj.offsetLeft;
			pObj.curtop += yume_find_pos_obj.offsetTop;
			if(!yume_find_pos_obj.offsetParent)
				break;
			yume_find_pos_obj = yume_find_pos_obj.offsetParent;
		}
	else if(yume_find_pos_obj.x){
		pObj.curleft += yume_find_pos_obj.x;
		pObj.curtop += yume_find_pos_obj.y;
	}
	return pObj;
}
//------------------------------------------------------------Individual player instantiation-------------------------------------
//function to initialize player
function YumePlayer(playerID){
	this.playerID = playerID;
	this.banners = {};
	this.jsRollAd = null;
	this.iframeBannerUrl= null;
	this.floatCb = 'off';
	this.floatCbTemp = 'off';
}
/*function called when the player is added to the global list
Here we create the banner object by checking what divs are present and what needs to be created.
Additionally the object passed in from the HTML is nullified.
*/
YumePlayer.prototype.init= function(){
	this.floatCbTemp = this.floatCb;
	for (i in this.banners){
		if (this.banners[i].cbdiv == undefined){
			if (document.getElementById(this.banners[i]) != undefined && document.getElementById(this.banners[i]) != null){
				var cbObj = new YumeBanner();
				cbObj.cbdiv = document.getElementById(this.banners[i]);
				var posObj = YumePlayerObject.findPlayerPos(cbObj.cbdiv)
				cbObj.frameX = posObj.curleft;
				cbObj.frameY = posObj.curtop;
				cbObj.w = posObj.curW;
				cbObj.h = posObj.curH;
				switch(i.toLowerCase()){
					case "mediumrectangle": cbObj.region = "medrect";break;	
					case "wideskyscraper": cbObj.region ="widesky";break;
					case "leaderboard": cbObj.region ="leaderboard";break;	
					case "31rect": cbObj.region ="31rect";break;	
					case "fullbanner": cbObj.region ="fullban";break;	
				}
				cbObj.divId = this.banners[i];
				var frameExists = cbObj.cbdiv.getElementsByTagName("iframe");
				if (frameExists[0] != null && frameExists[0] != undefined){
					cbObj.iframe = frameExists[0];
					cbObj.frameId = frameExists[0].id;
				}else {
					cbObj.frameId = cbObj.divId+'frame';
				}
				
				cbObj.floatBanner = false;
				this.banners[i] = null;
				this.banners[cbObj.region] = cbObj;
			}else {
				this.banners[i] = null;
			}
		}
	}
}
/*
This function is called be flash. It is the entry point for serving banners, jsRoll ads and floating banners
*/
YumePlayer.prototype.yume_flash_callback = function(command, arg1, arg2, arg3, arg4, arg5,arg6){
	this.floatCbTemp = (arg6!=undefined && this.floatCb !="off")?arg6:this.floatCb;
	try{
		display_yume_flash_callback_events(command, arg1, arg2, arg3, arg4, arg5);
	}catch(e){}
	var curType;
	//To identify the type of Banner
	switch(command){
		case 'companionbanner/iframe': curType="iframe"; break;
		case 'companionbanner/image': curType=(arg5 == "application/x-shockwave-flash")?"swf":(yume_img_is_swf(arg1) > 0)?"iframe":"image"; break;
		case 'companionbanner/html':curType="html";break;
		case 'companionbanner/js':curType="js";break;
	}
	//to identify the region of the companion YumeBanner
	var cbW=0; var cbH=0; var cbId;
	switch(arg3){
		//need to check if this is required as server does not supports it --- case "cb1":
		case "cb_medrect1": cbId="medrect"; cbW=300; cbH=250; break;	
		case "cb_leaderboard1": cbId="leaderboard"; cbW=728; cbH=90; break;
		case "cb_widesky1": cbId="widesky"; cbW=160; cbH=600; break;
		case "cb_31rect1": cbId="31rect"; cbW=300; cbH=100; break;
		case "cb_fullban1": cbId="fullban"; cbW=468; cbH=60; break;
		case "roll_1": cbId="jsrollad"; cbW=300; cbH=250; break;
	}	
	if (cbId != undefined){
		if (cbId == "jsrollad"){
			this.jsRollAd = new YumeBanner();
			this.jsRollAd.floatBanner = true;
		}
		if (cbId=="medrect" && (this.floatCbTemp == "on" || (this.floatCbTemp == "default" && (this.banners[cbId] == null || this.banners[cbId] == undefined)))){
			cbId +="_float";
			if (this.banners[cbId] != undefined){
				this.banners[cbId].removeDynDiv();
				this.banners[cbId] = null;
			}
			this.banners[cbId] = new YumeBanner();
			this.banners[cbId].floatBanner = true;
		}
	}
	if((this.banners[cbId] != undefined  && cbId != undefined) || cbId == "jsrollad"){
		var divObj = (cbId == "jsrollad")?this.jsRollAd:this.banners[cbId];
		divObj.playerRef = this;
		divObj.playerID = this.playerID;
		divObj.region = (cbId.indexOf("_float")>0)?cbId.substring(0, cbId.indexOf("_float")):cbId;
		divObj.backfill = false;
		divObj.w = cbW;
		divObj.h = cbH;
		divObj.type = curType;
		divObj.src = arg1;
		divObj.linkUrl = arg2;
		divObj.trackers = arg4;
		if (!divObj.floatBanner){
			if (divObj.iframe == null){
				divObj.createIframe();
			}
			divObj.loadBanner();
		}else {
			divObj.createFloatingDiv();
		}
	}
	switch(command){	
		case 'yume_leader_start':for (i in this.banners){
									if (this.banners[i] != null){
										this.banners[i].backfill = true;
									}
								}
		case 'yume_preroll_start':
		case 'yume_postroll_start':
		case 'yume_midroll_start': this.closeHandler();this.hideRollDiv(); break;
								
		case 'yume_leader_end':
		case 'yume_preroll_end':
		case 'yume_postroll_end':
		case 'yume_midroll_end':this.hideRollDiv(); break;

		case 'yume_ad_end':this.closeHandler();	break;
		
		case 'yume_end': if (arg1 != 0 ){break;}
		case 'yume_ad_start': this.backfillRequiredCB();
	}
}
// If the div is present for a particular banners and the playlist doesn't contains any banner request then the backfill banner is requested
YumePlayer.prototype.backfillRequiredCB = function(){
	for (i in this.banners){
		if (this.banners[i] != null){
			var divObj =  this.banners[i];
			if (divObj.backfill){
				var n_rand=Math.floor(Math.random()*100001);
				divObj.src = this.iframeBannerUrl+"&width="+ divObj.w+"&height="+ divObj.h+"&imu="+divObj.region+"&rand="+n_rand;
				if (divObj.iframe == null){
					divObj.createIframe();
				}
				divObj.type = "iframe";
				divObj.loadBanner();
			}
		}
	}
}
// function to remove the floating companion banner when the ad completes or the close button is clicked
YumePlayer.prototype.closeHandler= function(){
	try{
	for (i in this.banners){
		if (this.banners[i] != null){
			if (i.indexOf("float") > 0){
				this.banners[i].removeDynDiv();
			}
		}
	}
	}catch(e){}
}
// function to hide the jsRoll div when it is completed 
YumePlayer.prototype.hideRollDiv = function(){
	this.jsRollAd.cbdiv.innerHTML="";
	this.jsRollAd.cbdiv.style.visibility = 'hidden';
	document.body.removeChild(this.jsRollAd.cbdiv);
	this.jsRollAd = null;
} 
//------------------------------------------------ YumeBanner Class--------------------------------------------
/* 
This class assumes that the div is already present or created.
*/
function YumeBanner(){
	this.id = null;
	this.playerID= null;
	this.divId = null;
	this.cbdiv = null;
	this.fadeDiv = null;
	this.transDiv = null;
	this.closeDiv = null;
	this.image = null;
	this.w = 0;
	this.h = 0;
	this.l = 0;
	this.t = 0;
	this.frameX = 0;
	this.frameY = 0;
	this.frameId = null;
	this.iframe = null;
	this.src = null;
	this.trackers = [];
	this.linkUrl = null;
	this.type = null;
	this.region = null;
	this.backfill = true;
	this.yumefloatDiv = null;
	//default values for float CB
	this.floatPos = "right"
	this.floatXoffset = 10;	this.floatYoffset = 10;
	this.closeXoffset = 2;this.closeYoffset = 0;
	this.timeToFade = 2000.0;
	this.closeBtnWidth=10;
	this.floatBanner= false;
	this.playerRef = null;
	//------------------------
}
// function to create dynamic iframes in the provided div
YumeBanner.prototype.createIframe = function(){
	//this.cbdiv.style.position="relative";
	if (this.floatBanner && this.region != "jsrollad"){
		this.frameX = this.frameY = 10;
	}
	this.iframe=document.createElement("iframe");
	this.iframe.setAttribute("id", this.frameId);
	this.iframe.style.width=this.w + "px";
	this.iframe.style.height=this.h + "px";	
	if (this.floatBanner){
		this.iframe.style.position="absolute";
	}
	this.iframe.style.left=this.frameX+"px";
	this.iframe.style.top=this.frameY+"px";
	this.iframe.style.border="0";
	this.iframe.style.overflow="hidden";
	this.iframe.style.visibility="hidden";
	this.iframe.scrolling="no";
	this.iframe.marginWidth="0";
	this.iframe.marginHeight="0";        
	this.iframe.frameBorder="0";
	this.iframe.topmargin="0";
	this.iframe.leftmargin="0";
	this.cbdiv.appendChild(this.iframe);
	var doc = this.iframe.document;
    if(this.iframe.contentDocument)
        doc = this.iframe.contentDocument; // For NS6
    else if(this.iframe.contentWindow)
        doc = this.iframe.contentWindow.document; // For IE5.5 and IE6
    doc.open();
    doc.writeln("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'><html><head><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'><title>Empty Page</title></head><body></body></html>");
    doc.close();
	
}
// function to load the banners when ever required  - regular and backfill
YumeBanner.prototype.loadBanner = function(){
	var htmlString = "";
	var tracker_str="";
	try{
		for (i=0; i<this.trackers.length; i++) {
			tracker_str += "<img width='1' height='1' src=\""+this.trackers[i]+"\" style='position:absolute;'></img>";
		}
	}catch(e){
	}
	//alert(this.type +":"+ this.src);
	switch(this.type){
		case "image":
					if (this.linkUrl != 'null') {
						htmlString="<a href='"+this.linkUrl+"' target='_blank'><img src=\""+this.src+"\" border='0' width='"+this.w+"' height='"+this.h+"'></a>";
					} else {
						htmlString ="<img src=\""+this.src+"\" border='0' width='"+this.w+"' height='"+this.h+"'>";
					}
					htmlString += tracker_str; break;
		case "iframe": if(this.src.indexOf(".swf")<0){
							htmlString = "<iframe src=\""+this.src+"\"height='"+this.h+"'width='"+this.w+"' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' topmargin='0' leftmargin='0' style='overflow:hidden'></iframe>";
						}else {
							htmlString="<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='"+this.w+"' height='"+this.h+"'> <param name='bgcolor' value='#E3F0EB' />  <param name='movie' value='"+this.src+"'><param name='allowScriptAccess' value='always'> <param name='wmode' value='transparent'> <param name='quality' value='high'><embed src=\""+this.src+"\" bgcolor='#E3F0EB' quality='high' wmode='transparent' allowScriptAccess='always' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='"+this.w+"' height='"+this.h+"'></embed></object>";
					htmlString += tracker_str; break;
						}
						break;
		case "swf":if (this.src.indexOf(".swf?", 0 || this.linkUrl.indexOf("spotxchange", 0) > 0) > 0) {
						//do nothing
					}else {
						if (this.linkUrl != null)this.src += "?clickTAG="+escape(this.linkUrl);
					}
					htmlString="<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='"+this.w+"' height='"+this.h+"'> <param name='bgcolor' value='#E3F0EB' />  <param name='movie' value='"+this.src+"'><param name='allowScriptAccess' value='always'> <param name='wmode' value='transparent'> <param name='quality' value='high'><embed src=\""+this.src+"\" bgcolor='#E3F0EB' quality='high' wmode='transparent' allowScriptAccess='always' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='"+this.w+"' height='"+this.h+"'></embed></object>";
					htmlString += tracker_str; break;
					break;
		case "js": htmlString = "<iframe src='serve_js.html?js_url="+escape(this.src)+"'height='"+this.h+"'width='"+this.w+"' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' topmargin='0' leftmargin='0' style='overflow:hidden'></iframe>";
				break;
		case "html":htmlString = this.src+tracker_str;
	}
	try{
		this.iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML=htmlString;
		this.backfill = false;
	}catch(e){
		try{
			this.iframe.src = this.src;
			this.backfill = false;
		}catch(e){}
	}
	this.iframe.style.visibility="visible";
	if (this.fadeDiv != null){
		this.fade();
		var refObj = this;
		setTimeout(function(){refObj.delayHandler();},2000);
	}
	this.cbdiv.style.visibility="visible";
}
// function to create additional divs for floating banners and jsroll ads
YumeBanner.prototype.createFloatingDiv = function(){
	this.floatBanner= true;
	this.divId = this.playerID+this.region;
	this.frameId = this.divId+'frame';
	
	this.yumefloatDiv=document.createElement('div');
	this.yumefloatDiv.id = this.divId;
	this.yumefloatDiv.className = this.divId;
	this.yumefloatDiv.style.width=(this.w)+"px";
	this.yumefloatDiv.style.height=(this.h)+"px";
	
	if (this.region != "jsrollad"){
		this.yumefloatDiv.style.width=(this.w+20)+"px";
		this.yumefloatDiv.style.height=(this.h+20)+"px";
		this.yumefloatDiv.style.border="1px solid";
	}
	this.yumefloatDiv.style.position="absolute";
	this.yumefloatDiv.style.zIndex = YumePlayerObject.zIndex++;
	this.yumefloatDiv.style.visibility="hidden";
	this.yumefloatDiv.type = this.type;
	this.yumefloatDiv.src =this.src;
	this.yumefloatDiv.linkUrl =this.linkUrl;
	this.yumefloatDiv.trackers =this.trackers;
	this.cbdiv = this.yumefloatDiv;
	
	if (this.region != "jsrollad"){
		this.transDiv = document.createElement('div');
		this.transDiv.id = this.divId+"trans";
		this.transDiv.className = this.divId+"trans";
		this.transDiv.style.backgroundColor="#000000";	
		this.transDiv.style.opacity='0.5';
		this.transDiv.style.filter='alpha(opacity = 50)';
		this.transDiv.style.position="absolute";	
		this.transDiv.style.width=(this.w+20)+"px";
		this.transDiv.style.height=(this.h+20)+"px";
		this.transDiv.style.left="0px";
		this.transDiv.style.top="0px";
		
		this.fadeDiv = document.createElement('div');
		this.fadeDiv.id = this.divId+"fade";
		this.fadeDiv.className = this.divId+"fade";
		this.fadeDiv.style.backgroundColor="#999999";	
		this.fadeDiv.style.opacity='1';
		this.fadeDiv.style.filter='alpha(opacity = 100)';
		this.fadeDiv.style.position="absolute";	
		this.fadeDiv.style.width=(this.w+20)+"px";
		this.fadeDiv.style.height=(this.h+20)+"px";
		
		this.image= document.createElement("img");
		this.image.setAttribute('onLoad', this.loadHandler());
		try {
			var closeBtnURL = (yume_domain_name == undefined)?"close_btn.png":yume_domain_name+"/yumeweb/include/advertiser/playersdk/close_btn.png";
			this.image.setAttribute("src",closeBtnURL);
		}catch(e){
			this.image.setAttribute("src","close.png");
		}
		this.image.setAttribute('border','0px');
		this.image.id=this.divId+"image";	
		this.image.style.width = "10px";
		this.image.style.height = "10px";
		var refObj = this;	
		this.closeDiv= document.createElement('div');
		this.closeDiv.id = this.divId+"close";
		this.closeDiv.className = this.divId+"close";
		this.closeDiv.style.position="absolute";
		this.closeDiv.appendChild(this.image);
		this.closeDiv.onclick=function(){refObj.playerRef.closeHandler();};
		this.closeDiv.style.cursor='pointer';
		this.closeDiv.style.cursor='hand';
		this.closeDiv.style.top=this.closeYoffset+"px";
		this.closeDiv.style.left="0px";
	}
	document.body.appendChild(this.yumefloatDiv);
	if (this.region != "jsrollad"){
		this.yumefloatDiv.appendChild(this.transDiv);	
		this.createIframe();
		this.yumefloatDiv.appendChild(this.closeDiv);
		this.yumefloatDiv.appendChild(this.fadeDiv);
		this.positionDiv();	
		setTimeout(function(){refObj.loadBanner();},1000);	
	}else {
		this.createIframe();
		this.positionDiv();	
		this.loadBanner();
	}
}
// function to remove the floating div.
YumeBanner.prototype.removeDynDiv = function(){	
	try{
		this.floatCbTemp = this.floatCb;
		this.cbdiv.innerHTML="";
		this.cbdiv.style.visibility = 'hidden';
		document.body.removeChild(this.cbdiv);
	}catch(e){}
}
// function to fetch the image element
YumeBanner.prototype.loadHandler= function(){
	this.img=document.getElementById(this.divId+"image");
}
// function to position the floating div or the jsRoll ad
YumeBanner.prototype.positionDiv = function(){
	var div_x;	var div_y;
	this.player=document.getElementById(this.playerID);	
	this.playerPos = YumePlayerObject.findPlayerPos(this.player);
	if (this.region != "jsrollad"){
		switch(this.floatPos){
			case "right": div_x=this.playerPos.curleft + this.playerPos.curW + this.floatXoffset;
						  div_y=this.playerPos.curtop; 
						  break;
			case "left": div_x=this.playerPos.curleft - getDivProp(this.cbdiv,"width") - this.floatXoffset;
						  div_y=this.playerPos.curtop; 
						  break;
			case "top": div_x=this.playerPos.curleft 
						  div_y=this.playerPos.curtop- getDivProp(this.cbdiv,"height") - this.floatyoffset;; 
						  break;		 
			case "bottom": div_x=this.playerPos.curleft ;
						  div_y=this.playerPos.curtop+ this.playerPos.curH + this.floatYoffset; 
						  break;				 
		}
	}else {
		div_x = this.playerPos.curleft + ((this.playerPos.curW - 300)/2);
		div_y = this.playerPos.curtop + ((this.playerPos.curH - 250)/2);
	}
	this.cbdiv.style.left=div_x+"px";
	this.cbdiv.style.top=div_y+"px";
	if (this.region != "jsrollad"){
		this.fadeDiv.style.left="0px";
		this.fadeDiv.style.top="0px";
		this.closeDiv.style.left=getDivProp(this.cbdiv,"width") - this.closeBtnWidth - this.closeXoffset +"px";
	}
}
//function call to hide the fade div when floating banner is served
YumeBanner.prototype.delayHandler = function(){
	this.fadeDiv.style.visibility="hidden";
}
// function to start the fade animation when floating banner is served
YumeBanner.prototype.fade = function (){
  var element = this.fadeDiv;  
  if(element == null)   return;
  if(element.FadeState == null){
    if(element.style.opacity == null || element.style.opacity == '' || element.style.opacity == '1')
      element.FadeState = 2;
    else
      element.FadeState = -2;
  }
  if(element.FadeState == 1 || element.FadeState == -1)  {
    element.FadeState = element.FadeState == 1 ? -1 : 1;
    element.FadeTimeLeft = this.timeToFade - element.FadeTimeLeft;
  } else  {
    element.FadeState = element.FadeState == 2 ? -1 : 1;
    element.FadeTimeLeft = this.timeToFade;
	var refObj = this;
    setTimeout(function(){refObj.animateFade(new Date().getTime());}, 33);
  }  
}
//function for fade animation when floating banner is served
YumeBanner.prototype.animateFade = function(lastTick){  
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;
  var element = this.fadeDiv;
  if(element.FadeTimeLeft <= elapsedTicks) {
    element.style.opacity = element.FadeState == 1 ? '1' : '0';
    element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    return;
  }
 
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/this.timeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;
  element.style.opacity = newOpVal;
  element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
  var refObj = this;
  setTimeout(function(){refObj.animateFade(curTick);}, 33);
}

//--------------------------------------------------Common functions----------------------------------------------
// return 1 if img_url is a SWF, 0 otherwise
function yume_img_is_swf(img_url) {
	var ix_getElement=img_url.indexOf("/getElement?", 0);
	var ix_extSWF=img_url.indexOf("ext=.swf", 0);
	var rc=0;
	if (ix_getElement > 0 && ix_extSWF > ix_getElement) {
		rc=1;
	}
	return rc;
}
//function to return int values of the div properties
function getDivProp(obj,prop){
	var return_value;	
	if(obj.style[prop] == "" || obj.style[prop]==undefined) {
		return_value=obj[prop];
	} else {		
		return_value=obj.style[prop];
		return_value=return_value.split("px")[0];
	}
	return Number(return_value);	
}
