/*	PANDO ACME DEMO
	LAST MODIFIED: 2007-08-11
	LAST MODIFIED BY: MATTHEW FITZGERALD
	LAST MODIFIED NOTES: INITIAL CREATION
	REQUIREMENTS: http://demo.pandonetworks.com/js/pando.uncompressed.js
	OPTIONAL: http://demo.pandonetworks.com/js/pando.debug.uncompressed.js, http://demo.pandonetworks.com/css/pando.log.uncompressed.css, css/pando-criativebeta.css
	---------------------------------------------------- */
	
/*	AFTER JQUERY IS INCLUDED 
	THIS MUST BE THE FIRST PANDO FILE READ
	jQuery.noConflict() AND (function($){ ... })(jQuery); 
	ALLOWS FOR OTHER JAVASCRIPT FRAMEWORKS THAT USE "$" 
	---------------------------------------------------- */
	
	/**
	 * PLAYER READY
	 * DivX player doesn't have a global callback for player ready
	 * We added it for consistency with other players like JW player 
	 * When it finishes initialization 
	 * See: http://developer.longtailvideo.com/trac/wiki/FlashAPI
	 */
	function divxPlayerReady(thePlayer) {
		if (Pando.log) Pando.log.record("playerReady", "Executed");
		if (Pando.log) Pando.log.record("thePlayer.id", thePlayer.id);
		Pando.Obj.divx_player_listener.domId = String(thePlayer.id);
		
		Pando.Obj.divx_player_listener.init();
		/**
		 * CUSTOM SURVEY REMOVED FOR THIS DEMO
		 * Because Survey Link is positioned inside a container marked with css "position:relative"
		 * DivX player on Windows doesn't understand this
		 * So Before load of divx player, if windows, we reset the container to be "position:static"
		 * The reassignment messes up the positioning of the link for the survey
		 * We also don't have a black skin for the survey link yet, a black skin would match the DivX skin
		 */
		//CUSTOM_SURVEY_LINK_ACTIVATE();
	}
	
	/**
	 * jQuery.noConflict();
	 * (function($){	
	 * 		... code ...
	 * })(jQuery);	
	 * Allows you to use other JavaScript Frameworks Such as Prototype that share the alias "$"
	 */
	
	jQuery.noConflict();
	(function($){				
				
		/**
		 * MY CUSTOM AD PRE ROLL
		 * Create SpotXchange variables
		 * Append spotxchange source to page
		 */
		MY_CUSTOM_AD_PRE_ROLL = function() {
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("MY_CUSTOM_AD_PRE_ROLL", "Executed");
			/*ENDPRECOMPRESSIONZONE*/
			var inp = arguments[0];
			spotx_channel_id = "70443";
			spotx_content_container_id = "pandoAcmeAdPreRollContainer";
			spotx_content_format = "FlashVideo";
			spotx_content_width = inp.pandoWidth;
			spotx_content_height = inp.pandoHeight;
			spotx_ad_done_function = function() { 
				$("#pandoAcmeAdPreRollContainer").hide();
				MY_VIDEO_PLAYER(inp,spotx_ad_found); 
				spotx_ad_done_function = undefined;
				delete(spotx_ad_done_function);
			}; 
			spotx_ad_type = "preroll";
			spotx_ad_click_target = "_blank";
			spotx_ad_max_duration = "35";
			var pathName = window.location.pathname;
			var re = new RegExp("/divx/");
			var re2 = new RegExp("/divx");			
			var pathToMedia = pathName.replace(re, "");
			pathToMedia = pathName.replace(re2, "");
			$("head").append("<script src=\""+pathToMedia+"/media/js/vendors/spotx/spotx.js\" type=\"text/javascript\"></script>");
		};
		
		Pando.Obj.DivxPlayer = { 
			instance: false,
			plugin: false
		};
		
		Pando.DivxPlayer = function() {			
			this.config = {
				domId: false,
				pandoUrl:false
			};			
			this.totalTime = false;
			this.oldstate = "IDLE";
			this.newstate = null;
			this.position = null;
			if (arguments[0]) this.config = $.extend(this.options, arguments[0]);			
			this.__init();		
		};
		
		Pando.DivxPlayer.prototype.__init = function(){
			if (Pando.log) Pando.log.record("Pando.DivxPlayer.config.domId", this.config.domId);
			var domId = this.config.domId;
			Pando.Obj.DivxPlayer.plugin = document.getElementById(domId);				
			Pando.Obj.DivxPlayer.plugin.Open(this.config.pandoUrl);	
			Pando.Obj.DivxPlayer.plugin.Play();	
			if (Pando.log) Pando.log.record("Pando.Obj.DivxPlayer.plugin", "Play()");
		};
		
		Pando.DivxPlayer.prototype.clickableListeners = function(){
			divxPlayer = this;
			divxPlayer.totalTime = Pando.Obj.DivxPlayer.plugin.GetTotalTime();			
			if (Pando.log) Pando.log.record("Pando.DivxPlayer Initializing Total Time for Seeking", divxPlayer.totalTime);
			if (parseInt(divxPlayer.totalTime) == 0) {
				if (Pando.log) Pando.log.record("Pando.DivxPlayer will not work", "Total Time was not extracted from asset.");
			} else {
				if (Pando.log) Pando.log.record("Pando.DivxPlayer Seeking will work", "Images are now clickable.");	
				var divx_listeners = $(".divx_listener");
				for (var i = 0; i < divx_listeners.length; i++) {					
					var divx_listener = divx_listeners[i];		
					$(divx_listener).removeClass("masked");
					$(divx_listener).addClass("unmasked");							
					$(divx_listener).click( function(){
						var elm = this;
						var skip = $(elm).attr("title");
						var skipArray = skip.split(":");
						var minutes = skipArray[0];
						var seconds = skipArray[1];
						var minutesToSeconds = (parseInt(minutes) * 60);
						seconds = parseInt(skipArray[1]);
						var totalSeconds = minutesToSeconds + seconds;
						
						var percentage = Math.floor((totalSeconds / parseInt(divxPlayer.totalTime)) * 100);
							
						if (Pando.log) Pando.log.record("DIVX Attempting SEEK", "TotalTime = "+divxPlayer.totalTime+"\nFind Seconds at = "+totalSeconds+"\nPercentage "+String(percentage));
						try {								   
							Pando.Obj.DivxPlayer.plugin.Seek('DRAG', String(percentage));								
						} catch(e) {
							//alert(e);
							var output = '';
							for (var elm in e) {
								output += elm +" "+ e[elm]+" \n";
							}
							alert(output);
						}
						
						return false;
					});
				}	
			}
		};
		
		Pando.DivxPlayer.prototype.timeCallback = function(current) {
			/**
			 * @param current - measured in seconds
			 */
			this.position = parseInt(current);
			player_time(this);
		};
		
		Pando.DivxPlayer.prototype.statusCallback = function(status) {
			/**
			 * http://www.liquid.gi/Webmaster%20SDK/Webmasters%20Handbook.pdf
			 */
			var s = parseInt(status);

		    switch(s) {
		            	case 1:  
		            		/**
		            		 * OPEN_DONE
		            		 * When reached now have access to following plugin methods
		            		 * plugin.GetTotalTime();
		            		 */
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": OPEN_DONE");   
		                 	this.clickableListeners();		                 	
		                break;
		            	case 2:  
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": COMPLETED");   
		                 	this.newstate = "COMPLETED"; 
		                 	player_state(this);
		                break;
		                case 4:  
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": EMBEDDING START");  
		                break;
		                case 8:
		                case 9:  
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": FULLSCREEN");   
		                 	this.newstate = "FULLSCREEN"; 
		                 	player_state(this);
		                break;
		                case 10:		        
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": PLAYING");   
		                	this.newstate = "PLAYING"; 
		                	player_state(this);
		                break;		
		                case 11:
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": PAUSED");   
		                 	this.newstate = "PAUSED";     
		                 	player_state(this);
		                break;	
		                case 14:
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": STOPPED");    
		                 	this.newstate = "STOPPED"; 
		                 	player_state(this);
		                break;	
		                case 15:
		                	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": BUFFERING START");   
		                 	this.newstate = "BUFFERING"; 
		                 	player_state(this);
		                break; 	
		                case 16:  
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": BUFFERING STOP");   
		                 	this.newstate = "BUFFERING"; 
		                 	player_state(this);
		                break;
		                case 17:  
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": DOWNLOAD START");  
		                break; 
		                case 19:  
		                 	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": DOWNLOAD END");                 	
		                break; 
		                default:
		                	if (Pando.log) Pando.log.record("DIVX Status", "Case "+String(s)+": UNCAUGHT");   
			}		
		};
		
		/** 
		 * CUSTOM CALLACK
		 * Extract Pando Data
		 * Execute ad pre roll function
		 */	
		MY_CUSTOM_CALLBACK = function() {
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("MY_CUSTOM_CALLBACK", "Executed");
			/*ENDPRECOMPRESSIONZONE*/
			$('#pandoAcmeInstallerContainer').hide();
			var pandoUrl = this.pandoUrl;
			var pandoId = this.pandoId;
			var pandoHeight = this.pandoHeight;
			var pandoWidth = this.pandoWidth;
			
			// report pmb install status
            track_pmb_install();
                        
			try {
			MY_CUSTOM_AD_PRE_ROLL({ pandoUrl:pandoUrl, pandoId:pandoId, pandoHeight:pandoHeight, pandoWidth:pandoWidth });
			} catch (err) { }
									
		};	
			
		
		/** 
		 * VIDEO PLAYER
		 * Use Pando Media helper 
		 * Create JW Flash Player
		 */	
		MY_VIDEO_PLAYER = function() {			
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("MY_VIDEO_PLAYER", "Executed");
			/*ENDPRECOMPRESSIONZONE*/
			var inp = arguments[0];
			var pandoUrl = inp.pandoUrl;
			var pandoId = inp.pandoId;
			var pandoHeight = inp.pandoHeight;
			var pandoWidth = inp.pandoWidth;
			
			// track whether the pre-roll was presented or not
            track_ad_shown(arguments[1]);
							
			if(Pando.windows) {
				$("#pandoMediaContainer0").css("position","static");
			}	
			
            var domId = "divxPlugin";
            if ($.browser.msie || $.browser.safari) {
            	domId += "_ie";
            } else {
            	domId += "_np";
            }
            $("#divxContainer").show();
            
            myVideoPlayerFunc = this;
            
            setTimeout(function(){
            	Pando.Obj.DivxPlayer.instance = new Pando.DivxPlayer({ domId: domId, pandoUrl:pandoUrl });
            	myVideoPlayerFunc = undefined;
            	delete(myVideoPlayerFunc);
            },1000);	
		};
		
		CUSTOM_SURVEY_LINK_ACTIVATE = function() {
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("CUSTOM_SURVEY_LINK_ACTIVATE", "Executed");
			/*ENDPRECOMPRESSIONZONE*/
			setTimeout(function(){
				var survey_container = $("#survey_link");
				var playerId = "pandoMediaContainer0";
				var player = $("#"+playerId);
				//var offsets = $(player).offset();
				var height = $(player).height();
				//var offsetTop = offsets.top + height - 40;
				var adjust = 41;
				if ($.browser.msie) {
					adjust = 43;
				}
				var offsetTop = height - adjust;
				var cssObj = {
			        position: 	"absolute",
			        top:		offsetTop+"px",
			        zIndex:		"100"
			    }				
				$(survey_container).css(cssObj);
				$(survey_container).show();
			},3000);				
		};
		
		/**
	     * PANDO_OPT_IN_ERROR to install
	     * Click the dummy button
	     * Change text color to red
		 */
		PANDO_OPT_IN_ERROR = function() {
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("PANDO_OPT_IN_ERROR", "Executed");
			/*ENDPRECOMPRESSIONZONE*/			
			var pandoOptIn = $("#pandoOptIn");
			$(pandoOptIn).addClass("error");
		};
				
		/**
	     * PANDO_OPT_IN to install
	     * Time out necessary for IE
		 */
		PANDO_OPT_IN = function() {		
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("PANDO_OPT_IN", "Executed");
			/*ENDPRECOMPRESSIONZONE*/	
			setTimeout(function() {
				var pandoOptInCheckbox = $("#pandoOptInCheckbox");				
				var pandoInstallButton = $("#pandoInstallButton");				
				var pandoDummyButton = $("#pandoDummyButton");	
				var pandoOptIn = $("#pandoOptIn");			
				if ($(pandoOptInCheckbox).attr("checked")) {
					$(pandoDummyButton).hide();
					$(pandoInstallButton).show();					
					$(pandoOptIn).removeClass("error");
				} else {
					$(pandoInstallButton).hide();
					$(pandoDummyButton).show();					
				}
			}, 100);
		};
		
		/**
		  * PANDO CONFIGURATION OPTIONS
		  * Customize your Pando install experience
		  (change to false true to turn debugger on off)
		  */
		var jarInstallerPath = Pando.config.installer.jar;		
		if ($.browser.safari) jarInstallerPath = "http://"+document.domain+"/acme/media/installer/PDInstallerApplet.jar";  
		//var jarInstallerPath = "http://october.pando.com/javainstaller/PDInstallerApplet.jar"; 
		 
		var PANDO_OPTIONS = {
			log : false,
			push:	{
				upgrade:	"2.2.1.1"
			},
			install: {
				callback: { func: MY_CUSTOM_CALLBACK },
			    container: "pandoAcmeInstallerContainer",
				display: {
					message: "<div id='pandoInstallMessage' class='demoBG' style='display:none;'><br /><h1>INSTALL PLUG-IN</h1><div id='pandoOptIn' class='pandoOptIn' ><input type='checkbox' onclick='PANDO_OPT_IN()' id='pandoOptInCheckbox' />&nbsp; I understand that by installing the plug-in I will be participating in a<br /> &nbsp; private peer-to-peer network &nbsp; ( <a class='whats' href='http://www.pandonetworks.com/faq' target='_blank'>What's this?</a> )</div><input type='button' class='pandoDummyButton' id='pandoDummyButton' onclick='PANDO_OPT_IN_ERROR()' /><input type='button' class='pandoInstallButton' id='pandoInstallButton' style='display:none;'/></div>",
					upgrade: "<div id='pandoInstallUpgrade' class='demoBG' style='display:none;'><br /><h1>UPGRADE PLUG-IN</h1><div id='pandoOptIn' class='pandoOptIn' >We have detected you have installed Pando. <br /><br /> Click below to upgrade to Pando Media Booster. <br /><br /></div><br /><br /><input type='button' class='pandoInstallButton' id='pandoInstallButton' /></div>",
					forceUpgrade: "<div id='pandoInstallForceUpgrade' class='demoBG' style='display:none;'><br /><h1>UPGRADE PLUG-IN</h1><div id='pandoOptIn' class='pandoOptIn' >We have detected you are running an old version of Pando Media Booster. <br /><br /> Click below to install the latest version. <br /><br /></div><br /><br /><input type='button' class='pandoInstallButton' id='pandoInstallButton' /></div>",
					strategy: "<div id='pandoInstallStrategy' class='demoBG' style='display:none;'><span class='title'><br /><h1>When prompted, click <em style='font-size:24px;'>'run'</em></h1></span><center><div id='pandoWarning' style='display:none;'></div></center></div>",
					progress: "<div id='pandoInstallProgress' class='demoBG' style='display:none;'><br /><h1>Installing Player Plug-in</h1><br /><center><div id='pandoContainerBar' style='display:none;'><div id='pandoStatusBar' style='display:none;'></div><div id='pandoStatusText' style='display:none;'>Installing</div><div id='pandoStatusPercent' style='display:none'><span id='pandoProgress'>0%</span></div><div style='display:none' id='pandoLaunchingText'>Launching</div></div></center></div>",
					loading: "<div id='pandoInstallLoading' class='demoBG' style='display:none;'><center><br /><br /><img src='/acme/media/images/ajax-loader.gif' align='middle' border='0' width='220' height='19' /><br><div class='starting'></div></center></div>"
				},
				start:{ listener:"click", id:"pandoInstallButton" }
			},
			installer : { jar: jarInstallerPath }	
		};
		
		if ((Pando.windows || Pando.mac) && (jQuery.browser.msie || jQuery.browser.mozilla || jQuery.browser.safari)) {
			Pando.activate(PANDO_OPTIONS);
		} else {
			$(document).ready(function() {
				var h1HTML = "<h1 style=\"color:#fff;\" >This demo is currently available only for Windows and Mac using Internet Explorer 6+ or FireFox 1.5+. or Safari 3+<br />"+
                                "We are adding support for other operating systems and browsers. Please check again in the future.</h1>";
		      	$("#pandoAcmeAdPreRollContainer").append(h1HTML);
		      	// track users hitting an unsupported browser/os
                local_ga_tracker('/notsupported');
	      	});			
		}
		
		$(document).ready(function(){
			
			var preloadModalBg= new Image(298,444);
			
			$(preloadModalBg).load(function(){
				setTimeout(function(){
					$("#aboutSubModal").animate({ 
						"height": "toggle",
				        "width": "toggle"
				    }, 500, "swing",function(){
				    	$("#aboutSubModalOpen").hide();
						$("#aboutSubModalClose").show();
					});
				},5000);
			}).attr('src', "../acme/media/images/about_submodal_bg.png");		
			
			
			$("#aboutSubModalClose").click(function(){
				$("#aboutSubModal").animate({ 
					"height": "toggle",
			        "width": "toggle"
			    }, 500, "swing",function(){
					$("#aboutSubModalClose").hide();
					$("#aboutSubModalOpen").show();
				});
				
			});
			$("#aboutSubModalOpen").click(function(){
				$("#aboutSubModal").animate({ 
					"height": "toggle",
			        "width": "toggle"
			    }, 500, "swing",function(){
			    	$("#aboutSubModalOpen").hide();
					$("#aboutSubModalClose").show();
				});
				
			});
		});
		
		var demoName = "/acme/divx";
		
		/* tracking functions */
                // set the starting timestamp for the beginning of the install
                var inst_start=0;
                
                install_clicked = function() {
                        local_ga_tracker('/install/clicked');
                        inst_start = new Date();
                }
                
                track_pmb_install = function() {
                   // if no install was involved, track "exists"
                   if (inst_start==0) {
                      local_ga_tracker('/pmb/exists');
                      
                   // otherwise, find out how long the install took and the method (jar/exe)
                   } else {
                
                      var inst_end = new Date();

                      // calculate the elapsed time between the start and the end. 
                      // This is in milliseconds
                      var inst_time = inst_end.getTime() - inst_start.getTime();
                      local_ga_tracker('/install/'+Pando.config.install.strategy+'/'+time_to_timerange(inst_time));
                   }
                }
                
                // track whether an ad was found in the inventory and shown or not
                track_ad_shown=function(shown) {
                   local_ga_tracker('/ad/'+(shown?'shown':'unavailable'));
                }
                
                // track 30 seconds and 60 seconds into the video
                // got to use booleans as this event is fired every 1/10 of a second
                var time30first=true;
                var time60first=true;
                player_time=function(obj) {
                   if (time30first && obj.position==30) {
                      time30first=false;
                      if (Pando.log) Pando.log.record("DIVX TimeCallback", "track 30 seconds into the video"); 
                      local_ga_tracker('/player/video/30');
                   } else if (time60first && obj.position==60) {
                      time60first=false;
                      if (Pando.log) Pando.log.record("DIVX TimeCallback", "track 60 seconds into the video"); 
                      local_ga_tracker('/player/video/60');
                   } else {
                   		//if (Pando.log) Pando.log.record("DIVX TimeCallback", "obj.position = "+obj.position);   
                   }
                }
                
                // track state changes. specifically:
                // moved from idle (stopped) to buffering and then to playing
                // moved from playing to buffering and then back to playing
                // completed
                // paused              
                var buf_start=0;                
                var buf_play_start=0;           
                player_state=function(obj) {
                   if (obj.newstate=="PAUSED") {
                   		obj.oldstate = "PAUSED";                   		
                        local_ga_tracker('/play/pause');
                   } else if (obj.oldstate=="PLAYING" && obj.newstate=="COMPLETED") {
                   		obj.oldstate = "COMPLETED";
                        local_ga_tracker('/play/video/completed');
                   } else if (obj.oldstate=="IDLE" && obj.newstate=="BUFFERING") {
                   		obj.oldstate = "BUFFERING";
                        buf_start=new Date();
                   } else if (obj.oldstate=="BUFFERING" && obj.newstate=="PLAYING") {
                   		obj.oldstate = "PLAYING";
                        if (buf_start!=0) {
                                var buf_end=new Date();
                                local_ga_tracker('/player/video/started/'+time_to_timerange(buf_end.getTime()-buf_start.getTime()));
                                buf_start=0;
                        } else if (buf_play_start!=0) {
                                var buf_play_end=new Date();
                                local_ga_tracker('/player/video/buffering/'+time_to_timerange(buf_play_end.getTime()-buf_play_start.getTime()));
                                buf_play_start=0;
                        } 
                   } else if (obj.oldstate=="PLAYING" && obj.newstate=="BUFFERING") {
                   		obj.oldstate = "BUFFERING";
                        buf_play_start=new Date();
                   } else if (obj.newstate=="STOPPED") {
                   		obj.oldstate = "STOPPED";
                   		player_stop(obj);
                   } else if (obj.newstate=="FULLSCREEN") {
                   		obj.oldstate = "FULLSCREEN";
                   		player_fullscreen(obj);
                   }
                }
                
                player_fullscreen=function(obj) {
                   local_ga_tracker('/player/fullscreen');
                }

                player_stop=function(obj) {
                   local_ga_tracker('/player/stop');
                }

                player_error=function(obj) {
                   local_ga_tracker('/player/error/'+obj.message);
                }
                
                // convert time in seconds to a string we can track
                time_to_timerange=function(t) {
                   // determine the install time thresholds
                   var lc;
                   
                   if(t<1000) 
                      lc = "less_than_1_sec";
                   else if(t<2000) 
                      lc = "1_to_2_secs";
                   else if(t<3000) 
                      lc = "2_to_3_secs";
                   else if(t<4000) 
                      lc = "3_to_4_secs";
                   else if(t<5000) 
                      lc = "4_to_5_secs";
                   else if(t<10000) 
                      lc = "6_to_10_secs";
                   else if(t<30000) 
                      lc = "11_to_30_secs";
                   else if (t<=60000)
                      lc = "31_to_60_secs";
                   else if (t<=120000) 
                      lc = "61_to_120_secs";
                   else if (t<180000) 
                      lc = "121_to_180 secs";
                   else if (t<300000)
                      lc = "181_to_300_secs";
                   else
                      lc="more_than_300_secs"; 
                   return lc;
                }
                
                // this is the generic tracking function
                // everyone uses it as it can offer some logging on top of tracking
                local_ga_tracker=function(msg) {
                   if (Pando.log) Pando.log.record("GA_EVENT", demoName+msg);
                   //alert(msg);
                   pageTracker._trackPageview(demoName+msg);
                }
                
	})(jQuery);	
