/*	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
	 * Global function required by JW Player
	 * This function is executed by the JW Flash Player 
	 * When it finishes initialization 
	 * See: http://developer.longtailvideo.com/trac/wiki/FlashAPI
	 */
	function playerReady(thePlayer) {
		if (Pando.log) Pando.log.record("playerReady", "Executed");
		Pando.Obj.jw_flash_listener.obj = window.document[thePlayer.id];
		CUSTOM_SURVEY_LINK_ACTIVATE();
		addListeners();
	}
	
	/**
	 * ADD LISTENERS
	 * After the JW Flash Object is embeded in the page
	 * We need to create a JavaScript DOM reference to it
     * The creation of this DOM element is not instantaneous
     * addListeners polls itself until the DOM reference is saved
     * We use a custom global namespace Pando.Obj to store all our global accessed objects
     * We create a global namespace for JW called Pando.Obj.jw_flash_listener
     * We place the DOM reference as a property of this object called Pando.Obj.jw_flash_listener
	 */
	function addListeners() {		
		if (Pando.log) Pando.log.record("addListeners", "Executed");
		if (Pando.Obj.jw_flash_listener.obj) {
			Pando.Obj.jw_flash_listener.init();
		} else {
			setTimeout("addListeners()",100);
		}
	}
	
	/**
	 * jQuery.noConflict();
	 * (function($){	
	 * 		... code ...
	 * })(jQuery);	
	 * Allows you to use other JavaScript Frameworks Such as Prototype that share the alias "$"
	 */
	
	jQuery.noConflict();
	(function($){				
		
		/**
		 * 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 = "645";
			spotx_content_height = "415";
			spotx_ad_done_function = function() { 
				if(typeof(spotx_ad_found) == 'undefined' || spotx_ad_found == false) { 
					$("#pandoAcmeAdPreRollContainer").hide("fast", function(){
						MY_VIDEO_PLAYER(inp,spotx_ad_found); 
					});					
				} else {
					$("#pandoAcmeAdPreRollContainer").hide("fast", function(){
						MY_VIDEO_PLAYER(inp,spotx_ad_found); 
					});
				}
			}; 
			spotx_ad_type = "preroll";
			spotx_ad_click_target = "_blank";
			spotx_ad_max_duration = "35";
			var pathName = window.location.pathname;
			var re = new RegExp("/rtmp/");
			var re2 = new RegExp("/rtmp");			
			var pathToMedia = pathName.replace(re, "");
			pathToMedia = pathName.replace(re2, "");
			$("head").append("<script src=\""+pathToMedia+"/media/js/vendors/spotx/spotx.js\" type=\"text/javascript\"></script>");
		};
		
		/** 
		 * 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;
			
			/*BEGINPRECOMPRESSIONZONE*/
			if (Pando.log) Pando.log.record("MY_CUSTOM_CALLBACK", "pandoUrl = "+pandoUrl);
			/*ENDPRECOMPRESSIONZONE*/
			
			// report pmb install status
            track_pmb_install();
			
			var media = new Pando.Media();
			var flash = media.flash();
			if (flash != "0,0,0") {
				MY_CUSTOM_AD_PRE_ROLL({ pandoUrl:pandoUrl, pandoId:pandoId, pandoHeight:pandoHeight, pandoWidth:pandoWidth });
			} else {
				$("#pandoMediaPlayer_0").show();
			}
							
			Pando.Obj.jw_flash_listener = {
				obj: null,
				init: function() {
					var jw_listeners = $(".jw_listener");

					for (var i = 0; i < jw_listeners.length; i++) {
						var jw_listener = jw_listeners[i];				
						$(jw_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;
							try {
								Pando.Obj.jw_flash_listener.obj.sendEvent('SEEK', totalSeconds);
							} catch(e) {
								//alert(e);
								var output = '';
								for (var elm in e) {
									output += elm +" "+ e[elm]+" \n";
								}
								alert(output);
							}
							return false;
						});
					}	
					
					// adding some listeners for event tracking
                    Pando.Obj.jw_flash_listener.obj.addViewListener('FULLSCREEN','player_fullscreen');
                    Pando.Obj.jw_flash_listener.obj.addViewListener('STOP','player_stop');
                    Pando.Obj.jw_flash_listener.obj.addModelListener('STATE','player_state');
                    Pando.Obj.jw_flash_listener.obj.addModelListener('TIME','player_time');
                    Pando.Obj.jw_flash_listener.obj.addModelListener('ERROR', 'player_error');
				}	
			};
						
		};	
		
		/** 
		 * 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]);
			
			/**
			 * SWF OBJECT VARS
			 */
			var domId = "pandoMediaPlayer_"+pandoId;			 
						 
			var flashvars = {				 
				autostart:true,
				file:"foo.flv", 
				id:domId,
				streamer: escape(pandoUrl),
				stretching: "exactfit"
			}
		
			var params = {
				allowfullscreen:"true", 
				allowscriptaccess:"always",
				quality:'high',
				wmode:'transparent'
			}
		
			var attributes = {
				id:domId,  
				name:domId
			}
			$("#pandoMediaPlayer_0").show();
			swfobject.embedSWF("http://www.pando.com/dl/download/player4.swf", domId, pandoWidth, pandoHeight, "9.0.115", true, flashvars, params, attributes);
						
		};
		
		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 height = $(player).height();

				var adjust = 49;
				if ($.browser.msie) {
					adjust = 44;
				}
				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.3.0.0"
			},
			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) {
			Pando.activate(PANDO_OPTIONS);
		} else {
			$(document).ready(function() {
				var h1HTML = "<h1 style=\"color:#fff;\" >This demo is currently available only for Windows using Internet Explorer 6+ or FireFox 2.0+ and for Mac OS 10.4+ using Safari 3.0+ or Firefox 3.0+. <br />"+
                                "We are adding support for other operating systems and browsers. Please check again in the future.</h1>";
		      	$("#pandoAcmeAdPreRollContainer").append(h1HTML);
		      	
                local_ga_tracker('/notsupported');
	      	});			
		}
		*/
		Pando.activate(PANDO_OPTIONS);
		/*
		if ((Pando.windows) && (jQuery.browser.msie || jQuery.browser.mozilla)) {
			Pando.activate(PANDO_OPTIONS);
		} else {
			$(document).ready(function() {
				var h1HTML = "<h1 style=\"color:#fff;\" >This demo is currently available only for Windows using Internet Explorer 6+ or FireFox 1.5+. <br />"+
                                "We are adding support for other operating systems and browsers. Please check again in the future.</h1>";
		      	$("#pandoAcmeAdPreRollContainer").append(h1HTML);
		      	
                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/rtmp";
		
		/* 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;
                      local_ga_tracker('/player/video/30');
                   } else if (time60first && obj.position==60) {
                      time60first=false;
                      local_ga_tracker('/player/video/60');
                   }
                }
                
                // 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") {
                        local_ga_tracker('/play/pause');
                   } else if (obj.oldstate=="PLAYING" && obj.newstate=="COMPLETED") {
                        local_ga_tracker('/play/video/completed');
                   } else if (obj.oldstate=="IDLE" && obj.newstate=="BUFFERING") {
                        buf_start=new Date();
                   } else if (obj.oldstate=="BUFFERING" && obj.newstate=="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") {
                        buf_play_start=new Date();
                   }
                }
                
                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);	
