/* Create setup_player as a jQuery plugin. */ 
jQuery(function($) {
	$.setup_player = function(conf){
		
		// Make sure we have a conf
		if (typeof conf == 'undefined'){ return false; }
		
		/*	Overriding defaults: any of the values in "urls" or "defaults" can be easily 
			overriden by extending the conf object that we pass to this function. 
			Check the GeckoPlayer demo page for samples. */
				
		// Setup URLs		
		if (!conf.urls.base) { conf.urls.base = '/'; }
		var skin_station = conf.urls.base + "App_Skins/" + conf.urls.stationCode + "/";
		var skin_global = conf.urls.base + "App_Skins/Global/";
		urls = {
			swf: skin_global + "Flash/flowplayer.commercial-3.1.0.swf",
			skinless: skin_global + "Flash/flowplayer.controls-skinless.swf",
			logo: skin_station + "Flash/logo.swf",
			skin: skin_station + "Flash/skin.swf",
			play: skin_station + "Images/btn/" + conf.div + "_play_over.png",
			tracking: conf.urls.base + "Video/RegisterVideoImpression.ashx",
			image: $('#' + conf.div + ' img:first').attr('src')
		}
		// Merge default and custom URLs
		conf.urls = $.extend(urls, conf.urls);

		// Define all our defaults. Quite a few. 
		var defaults = {};
		defaults.autoStart = false;
		defaults.options = {

			key: '#@620efe6a9137a1360b5', // Defaults to *.tipit.net for dev.
			
			contextMenu: [conf.urls.stationCode + ' Media Player 1.0'],
			
			plugins: {                 
				controls: {
					url: conf.urls.skinless,
					skin: 'customskin',
					autoHide:'always',
					hideDelay: 3000,
					zIndex: 2
				},
				customskin: {
					 url: conf.urls.skin, 
					 type: "classLibrary" 
				},
				/* 	We're using a custom logo plugin, instead of the built-in one. 
					The later was doing to much 'magic' and was showing up in crazy places. */
				nLogo: {
					url: conf.urls.logo,
					zIndex: 1,
					fs_top: '12%',	// Since the fullscreen size and aspect ratio is impossible to predict,
					fs_left: '92%'	// we lock it to the top right. 		
				}
			},

			play: { 
				url: conf.urls.play, 
				width: 100, 
				height: 100,
				opacity: 1, 
				fadeSpeed: 500, 
				rotateSpeed: 50 
			},
		
			playlist: conf.playlist,
			
			removeAdsOnFinish: true,
			
			clip: {	// Global settings that apply to all playlist items.
				autoBuffering: true,
				scaling: "fit"
				/* ,duration: 5 // Useful for testing */
			}		
			
		};
		
		// Merge defaults and custom confs
		conf = $.extend(true, defaults, conf);
		
		// Store URLs as options, we'll need them later for plugins
		conf.options.urls = conf.urls;
		
		// Instantiate FlowPlayer
		$f(conf.div, {src: conf.urls.swf, version: [9,115]}, conf.options);
		
		// Setup NewsGecko Plugin
		$f(conf.div).newsgecko(conf);
		
		// Custom no-flash / no-js fallback
		$f(conf.div).customFallback();

		// Add a nice big play button to the splash image
		$("#"+conf.div).hover(function() {
			$(".playButton", this).addClass('playButtonOver');
		}, function() {
			$(".playButton", this).removeClass('playButtonOver');
		}) 
		// And a sweet hack to preload the rollover images		
		.find(".playButton").html('<span class="playButtonOver" />');
	
		// Start playback if required
		if (conf.autoStart){
			$f(conf.div).play();
		}
	}
	

	// NEWSGECKO PLUGIN
	$f.addPlugin("newsgecko", function() { 
		// Adds all the magic required to keep the lizard happy. 
		// - Station's logo conditional display and positioning
		//   (4:3, 16:9, fullscreen, hide if playing an ad)
		// - Tracking for stories and ads
		// - Prevent skipping (scrub forward) of ads
		// - Remove ads from playlist when playback is over.
		
		// self points to current Player instance
		var player = this; 
		
		// LOAD
		// Successful installation of the Flowplayer Flash component in the container.
		player.onLoad(function(clip){
			// Hide the logo. We'll manage it on a per-clip basis.
			player.getPlugin("nLogo").css({opacity: 0});
			// Identify and label each clip as video or ad
			$.each(player.getPlaylist(), function(){		
				this.is_ad = !!(this.videoAdId); // we use !! to turn any value (undefined, zero, null) into bool
				this.is_story = !!(this.videoId);
			});
		});
		
		// BEGIN
		// The first event to fire during the 'lifecyle' of a clip. Playback hasn't started.
		player.onBegin(function(clip){			
			if (clip.is_ad) {player.enableControls(false);}
			else if (clip.is_story) {player.enableControls(true);}	

			player.registerImpression(clip);		
		});	
		
		// START
		// Playback has started, and clip metadata is available.
		player.onStart(function(clip){
			clip.is_wide = (clip.metaData.width / clip.metaData.height > 1.5);

			player.logo_reposition(clip);
		});			
		
		// RESUME
		// Playback is resumed after having been paused.
		player.onResume(function(clip){
			if (clip.is_ad) {player.enableControls(false);}
		});	
		
		// FINISH
		// The clip reaches the end.
		player.onFinish(function(clip){ 
			if (player.getConfig().removeAdsOnFinish){
				// When we finish playing the last clip...
				var playlist = player.getPlaylist();
				if (clip.index == playlist.length - 1){
					/* Remove ads from the playlist. 
					   First we store a list of indexes to remove, then we remove them. */ 
					rm = [];
					$.each(playlist, function(){
						if (this.is_ad){ 
							rm.push(this.index);
						}
					});
					var i = 0; // Since splice changes the indexes, "i" keeps track of removed elements.
					$.each(rm, function(){
						playlist.splice(this + i--, 1);
					});
					// Add the splash image to the playlist, and load it. 
					playlist.push({"url": player.getConfig().urls.image, "duration": 0});
					player.setPlaylist(playlist);
					player.play(playlist.length-1);
				}
			}
		});	

		// FULLSCREEN
		// Going in and out of fullscreen.
		player.onFullscreen(function(clip){
			player.logo_delayed_reposition();
		});		
		player.onFullscreenExit(function(clip){
			player.logo_delayed_reposition();
		});

		
		/* 
		UTILITY FUNCTIONS
		* * * * * * * * */
		
		/* 	A slight delay is needed before repositioning, to allow 
			the player to catch its breath and recalc its dimensions. 
			Otherwise the logo ends up in silly places. */
		player.logo_delayed_reposition = function(){
			clearTimeout(player.fst);
			logo = player.getPlugin("nLogo"); 
			logo.css({opacity: 0});
			player.fst = setTimeout(function(){	
				player.logo_reposition();
			},1000);				
		}
		
		/*	Displays the logo at the proper place, according to:
			- the clip's aspect ratio, 
			- fullscreen status, 
			- story (show logo) vs ad (hide it), 
			- and display settings (don't show the logo at all for the small player). 
		*/
		player.logo_reposition = function(clip){
			
			clip = clip || player.getClip();
						
			logo = player.getPlugin("nLogo");
			logoConf = player.getConfig().plugins.nLogo;

			if (clip.is_story && logoConf.display != 'none'){
				if (player.isFullscreen()){
					logo.css({
						width: logoConf.fs_width,
						height: logoConf.fs_height,
						top: logoConf.fs_top,
						left: logoConf.fs_left
					});					
				} else {
					logo.css({
						width: logoConf.width,
						height: logoConf.height,
						top: logoConf.top,
						left: clip.is_wide ? logoConf.left_wide : logoConf.left
					});
				}
				logo.fadeIn(1500);
			} else { 
				logo.css({opacity: 0});
			}	
		}

		
		player.enableControls = function(status){
			player.getControls().enable({scrubber: status});
		}

				
		player.registerImpression = function(clip){
			var randomnumber = Math.floor(Math.random() * 1000001);
			var tracking = player.getConfig().urls.tracking + "?ticks=" + randomnumber;
			if (tracking == "false"){ tracking = false;}
			// Avoid tracking if no tracking URL was provided,
			// avoid tracking the final static image (or anything else w/o ID)
			if (!tracking || !(clip.videoId || clip.videoAdId)) { return false; }
			// We send 'undefined', because RegisterVideoImpression actually considers 
			// any non-integer value to be null.
			jQuery.get(tracking, {
				VIDEOID: clip.videoId || "undefined",

				VIDEOADID: clip.videoAdId || "undefined"
			})
			return true;
		}

		// Return self (the player object). Useful for chaining. 
		return player; 
	 
	});
	


	// CUSTOM FALLBACK PLUGIN
	$f.addPlugin("customFallback", function() { 
		// We roll our own Flash version detection, instead of the Flowplayer one. 
		// See http://flowplayer.org/forum/8/18754 for rationale.
		// This relies heavily on HTML hooks and contextual CSS.
		$('body').addClass('jsEnabled');
		player = this;
		if (!flashembed.isSupported(player.getFlashParams().version)){
			$('body').addClass('badFlash');
			if (!flashembed.isSupported([6,65])){
				player.onBeforeLoad(function(){ 
					if (getFlash = $("#"+player.getConfig().playerId + " .missingFlash a").attr('href')){
						window.top.location.href = getFlash;
					}
					return false;
				})
			}
		}
		return player;
	});
	
	
});	

