/***************************************************************************************************
JQUERY FLVSHADOWBOX PLUGIN v1.0  
@author => Keegan Watkins 2008
@updated => Jeremy Brown 08.13.2009 / added absolute paths to SWF location.
***************************************************************************************************/
// This function is called from Flash when the flvplayer swf has loaded. Argument is a 
// JSON String that contains the dimensions of the player. WARNING: This function is 
// called more than once, therefore do not add functionality here that would be 
// dangerous if repeated. 
function updateContainer(jsonString /*String*/) {
	FLVSHADOWBOX.view.updateContainer(jsonString);
}
/****************************************************************************************************
****************************************************************************************************/


// Setup namespace: 
var FLVSHADOWBOX = { 

//--MODEL--//----------------------------------------------------------------------------------------->		
		
		model : {
			videos: { /* Empty object to be populated with ShadowBoxInstance objects after initialization */ },
			// Constructor for instances
			ShadowBoxInstance : function(instance, name /* Object, String */){
					// Reference to the <embed> or <object> tag's ID
					this.domID = "spotlight_" + name;
					// Assign flvPath property, used to assign FLVPlayer flashvars
					this.flvPath =	instance.flvPath;
					// If webTrends object is included...
					if (instance.webTrends) {
						// Add new Array property to the shadowBoxInstance
						this.webTrendsMap = [ ];
						//Loop through the "key-value" pairs in the webTrends object, using the "key" as counter ...
						for (var key in instance.webTrends) {
							// ..access the corresponding value by plugging in loop counter...
							var value = instance.webTrends[key];
							// ...and first add the "key" to the new array...
							this.webTrendsMap.push(key);
							// ...and then add the "value" to the new array
							this.webTrendsMap.push(value);
						}
					}
					return this;
			},
			// Styles object to hold groups of CSS styles, named after the element they're applied to.
			styles : {
				closeButton : {
					height: "20px",
					width: "20px",
					zIndex: "2001",
					background: "transparent url(/images/misc/neutral/flvshadowbox/close.png) no-repeat"
				},
				overlay : {
					width: "100%",
					height: "100%",
					background: "#000 fixed",
					position: "absolute",
					top: "0",
					left: "0",
					zIndex: "100",
					opacity : ".7",
					filter: "alpha(opacity=70)"
				},
				spotlightParent : {
					position: "relative",         
			 		height: "161px",               
			 		width:  "215px",
					padding: "0"
				},
				spotlightContainer : {
					position: "absolute",          
	 				height: "161px",             
	 				width: "215px",                 
					top: "0",
					left: "0",
					zIndex: "100"
				},
				playerContainer : {
					opacity:"0", 
					filter:"alpha(opacity=0)",
					position:"fixed", 
					top:"0", 
					left: "0", 
					height:"1px", 
					width:"1px",
					zIndex: "2000"
				}
			}
		}, 
		
//--VIEW--//------------------------------------------------------------------------------------------>		
		
		view : {
			// The spotlight swf passes its instance reference from above, used as key to find instance object
			createShadowBox : function(instance /*String*/) {
				// Create, append, and style the overlay.
				jQuery("<div id='shadow_overlay' class='shadow_parts'></div>").appendTo("body").css(FLVSHADOWBOX.model.styles.overlay).stretchToPage();
				// Create, append, and style the close button 
				jQuery("<a id='close-button' class='shadow_parts' href='#'></a>").appendTo("body").css(FLVSHADOWBOX.model.styles.closeButton);
				// Create, append, and style the player container
				jQuery("<div id='player-container' class='shadow_parts'></div").appendTo("body").css(FLVSHADOWBOX.model.styles.playerContainer);
				// Finally, attach event handlers
				FLVSHADOWBOX.controller.attachShadowBoxEvents();
				// Check to see if instance object has webTrendsMap array, if so...
				if (FLVSHADOWBOX.model.videos[instance].webTrendsMap) {
					// ...call WebTrends, passing in the array of key-value pairs as individual arguments
					/*
					 * This is a technique used to pass array items as arguments. In a situation where a function like
					 * dcsMultiTrack() can accept unlimited key-value pairs as alternating arguments, using an array is ideal. 
					 * However, if we simply pass the array into a call to dcsMultiTrack, it becomes a single argument 
					 * of the type Array, and not a list of arguments that map to the array items. So, we use the apply() 
					 * method to unpack our array as arguments that are then passed in to dcsMultiTrack. Handy.
					 */
					dcsMultiTrack.apply(this, FLVSHADOWBOX.model.videos[instance].webTrendsMap); // Becomes dcsMultiTrack('key','value','key2','value2','key3','value3');
				} 
				// Reference to the video's file path as mapped to instance object's flvPath property.
				var video = FLVSHADOWBOX.model.videos[instance].flvPath;
				// Embed the FLVPlayer swf using swfobject
				var swfPath = "http://www.ni.com/swf/flv/flvplayer2.swf?url=" + video;
				var player = new SWFObject(swfPath,"flvplayer","100%","100%","#000","8");
				player.addParam("wmode", "transparent");
				player.addParam("allowScriptAccess","always");
				player.write('player-container');
			},
			updateContainer : function(jsonString /*String*/) {	
				// Parse JSON string into object...
				var params = eval('(' + jsonString + ')');
				// ...and create reference to video's width...
				var w = parseInt(params.playerWidth);
				// ...and the video's height
				var h = parseInt(params.playerHeight);
				// Style the player's container DIV
				jQuery("#player-container").css({
					width:  w + "px",
					height: (h - 45) + "px",  // override reserved space
					position: (FLVSHADOWBOX.controller.utils.isIE() == 6) ? "absolute" : "fixed",
					//Center player on page
					top: FLVSHADOWBOX.controller.utils.getHeightOffset(h) - 2 + "px",
					left: FLVSHADOWBOX.controller.utils.getWidthOffset(w) + "px",
					opacity: "1",
					filter: "alpha(opacity=100)"
				});
				jQuery("#close-button").css({
					position: (FLVSHADOWBOX.controller.utils.isIE() == 6) ? "absolute" : "fixed",
					// Place over top-right corner of player-container
					top: (FLVSHADOWBOX.controller.utils.getHeightOffset(h) - 2) + "px",
					left: (FLVSHADOWBOX.controller.utils.getWidthOffset(w) + w -20) + "px"
				});
			} 
		}, 
		
//--CONTROLLER--//------------------------------------------------------------------------------------>
		
		controller : {
			init : function(options /*Object*/){
				// Loop through multidimensional options object:
				// i.e each loop => divID: {flvPath : "/path_to_video/", webTrends : {key: "value", key2: "value2", key3: "value3"}} 
				for (var instance in options) {
					// Use instance constructor to dynamically create instance objects and attach them as properties to the 
					// FLVSHADOWBOX.model.videos object, passing in the instance object and the name of the instance object
					FLVSHADOWBOX.model.videos[instance] = new FLVSHADOWBOX.model.ShadowBoxInstance(options[instance], instance);
					// Find the page language: Select language meta tag and store "content" attribute
					var pageLanguage = jQuery("meta[name=Language]").attr("content");
					// Embed spotlight swf in container using swfobject. Send flashvars by appending them as a query string.
					var swfPath = "http://www.ni.com/swf/flv/spotlight.swf?flvID=" + instance + "&ctaLang=" + pageLanguage;
					var spotlight = new SWFObject(swfPath, "spotlight_" + instance, "215", "161", "#000", "8");
					spotlight.addParam("wmode", "transparent");
					spotlight.addParam("allowScriptAccess", "always");
					spotlight.write(instance);
					// Apply styles for keeping the swf "tiled" over the parent, stored as object in model
					jQuery("#" + instance).css(FLVSHADOWBOX.model.styles.spotlightContainer);	
					// Store reference to parent's image's source.
					var img = jQuery("#" + instance).parent().find("img").attr("src");
					// Knowing that the parent has a link and image as children for graceful degradation, remove them. Then, use the 
					// image path stored above to set parent's background back to image. Tricky.
					jQuery("#" + instance).parent().children("img, a").remove().end().css({
						background: "transparent url(" + img + ") no-repeat center"
					});
				}
				// Apply styles to the spotlight's parent, stored as object in model
				jQuery(".feature_wrapper").css(FLVSHADOWBOX.model.styles.spotlightParent);
			}, 
			
			// Bind events to the overlay and close button
			attachShadowBoxEvents : function() {
				jQuery("#shadow_overlay").click(FLVSHADOWBOX.controller.utils.removeShadowBox);
				jQuery("#close-button").click(FLVSHADOWBOX.controller.utils.removeShadowBox);
			},
			
			utils : {
				// Called when the overlay or close-button is clicked
				removeShadowBox : function() {
					// Unbind the event handlers for the link and overlay
					jQuery("#shadow_overlay, #close-button").unbind();
					// Remove the pieces of the ShadowBox
					jQuery(".shadow_parts").remove();
					return false;
				},
				
				// Returns IE version or false. Use init-time branching to re-write method internally after initial determination.
				isIE : function() {
					// Store the first number of the browser version i.e "6" or "7"
					var version = parseInt(jQuery.browser.version.substring(0,1));
					// Rewrite function by redefining here. NOTE: IE version utilizes "version" variable through the closure.
					FLVSHADOWBOX.controller.utils.isIE = (jQuery.browser.msie) ? function() {return version;} : function() {return false;};
					// After rewriting, return the expected result.
					return (jQuery.browser.msie) ? version : false;
				},
				
				// Returns the offset needed to vertically center player on page, based on height argument
				getHeightOffset : function(h /*Number*/) {
					if (jQuery.browser.msie) { 
						return (jQuery.browser.version == 6) ? ((jQuery(window.document).height() - h) / 2) : ((jQuery(window).height() - h) / 2) ;
					} else {
						return (window.innerHeight - h) / 2;
					}
				},
				
				// Returns the offset needed to horizontally center player on page, based on width argument
				getWidthOffset : function(w /*Number*/) {
					return (jQuery.browser.msie) ? (jQuery(window).width() - w) / 2 : (window.innerWidth - w) / 2;
				}
			}
		} 
};

// Quick jQuery extension, takes the wrapped set and stretches to page dimensions.
jQuery.fn.stretchToPage = function() {
	return this.each(function() {
		jQuery(this).css({height: jQuery(document).height(), width: jQuery(document).width()});
	});
};

