/*
 * jQuery.h5Video. Wrapper code to play html5 video when flash is not available
 *
 * Copyright (c) 2010 NBCUDPS
 *
 * Maintained by Cristiana Yambo
 * cristiana.yambo@nbcuni.com
 *
 * Launch : December 2010
 * Version : 0.9
 * Released: December 14,2010
 * 
 * Features: 
 * - Automatically switches to html5 video when flash is not available
 * - Automatically loads clip metadata when clip is played
 * - Provides a wrapper to Outlet functions so code that depends on Outlet will not have to be rewritten
 * - Messages a user when the video is not available through KT
 * Example: 
 *  jQuery('#videoplayer').h5Video({swfObject:so,videoId:"1247303");
 * Requirements:
 * - jquery
 * - external CSS :
 *  - player div needs to be sized to size of flash player
 *  - player div needs styles for .wait
 *  - player div needs styles for the message that appears when the clip does not exist, now it is in span.message inside the player div
 * Current Issues: 
 * - If passed in a comma delimited playlist it will only play the first clip
 * - Not all outlet functions are wrapped, so additional ones will need to be added as needed
 * - Not all video events are wrapped
 * - Events callbacks do not receive the proper event object in the parameters
 */

(function($){
	var settings;
	var id;
	var outletInitted = false;
	var embeddedPlayer = false;
	var metadata = false;
	$.fn.h5Video = function(options){	
		settings = $.extend({}, $.fn.h5Video.defaults, options);
		settings.videoId = parseInt(settings.videoId);
		if(!(id = $(this).attr('id'))){
			id = 'h5Video'+Math.floor(Math.random()*100000);
			$(this).attr('id',id);
		}
		// settings.swfObject = null;
		
		//determine if we have flash
		if(settings.swfObject && settings.swfObject.installedVer && settings.swfObject.installedVer.major){ 
			settings.swfObject.write(id);
		}
		else{
			//no flash, switch to KT
			if(settings.wrapOutlet){
				$.fn.h5Video.wrapOutlet(this);
			}
			$.fn.h5Video.loadVideo(this);
		}
	};
	$.fn.h5Video.loadVideo = function(curr){
		//empty out any messages or existing players
		$(curr).html('');
		$(curr).addClass('wait');
		// settings.videoId = '693362'; // hardcoded for lack of assets
		
		//first grab the metadata of the clip
		$.getJSON(settings.servicesURL+settings.clipInfoPath+settings.videoId,function(data){
			//saving metadata 
			if(data.metadata){
				metadata=$.fn.h5Video.processMetadata(data);
			}
			else{
				metadata=false;
			}
			//trigger the event that we updated the metadata
			$(curr).trigger('updatedMetadata');
			//check to see if the clip is available in Kiptronics
			$.getJSON(settings.servicesURL+settings.smilPath+settings.videoId,
				function(data){ 
					var sizes = data.head.layout["root-layout"];
					var videos = data.body["switch"].video; // switch is acting like a reserved word

					settings.videoWidth = sizes.width;
					settings.videoHeight = sizes.height;
					var foundVideo = false;
					$(videos).each(function(i,item){ 
						if(typeof console=='object') console.log('item.src: '+item.src);
						if( /kmedia/i.test(item.src) ){ // Found a KT asset path
							foundVideo=true;
							settings.videoPath = item.src;
							$(item["param"]).each(function(i,param){
								if( /content\-type/i.test(param.name) ){ // Found the mime type
									settings.videoMimetype = param.value;
								}
							});
							if(!$.fn.h5Video.setPlayer(curr)){
								foundVideo = false;
							}
						}
					}); 
					$(curr).removeClass('wait');
					if(!foundVideo){
						$(curr).html(settings.unavailableMessage);
					}
					else{
						//bind the end clip event to the player div because we created our own events 
						//this is to allow for items to bind to the end event without having the video tag in the player div
						$('#'+settings.videoTagId).bind('ended',function(){$(curr).trigger('clipEnded')})
					}
			});
		});

	}
	$.fn.h5Video.processMetadata = function(md){
		if(md.metadata!==undefined){
			md=md.metadata;
		}
		if(md.description!==undefined){
			//swapping metadata fields to match outlet response
			var title = md.headline;
			var subtitle = md.title;
			md.title = title;
			md.subtitle = subtitle;
			//return it in the properties node, because that is what the outlet getMetaData does
			return {properties:md};
		}
		return false;
	}
	$.fn.h5Video.wrapOutlet = function(curr){
		//creates a wrapper around the outlet functions so that external code does not have to be rewritten
		if(outletInitted){
			return;
		}
		outletInitted = true;

		function Outlet(){};
		//add any Outlet functions here
		Outlet.prototype.getOutletExtension = function(){
			function EmbeddedPlayer(){};
			//add any EmbeddedPlayer functions here and try to create the correct analog
			EmbeddedPlayer.prototype.playVideo = function(videoId){
				settings.videoId = parseInt(videoId);
				$.fn.h5Video.loadVideo(curr);
			}
			EmbeddedPlayer.prototype.addEventListener = function(type,callback){
				//these are bound to custom events on the player div, this is to allow events to exist when the player itself does not
				//when passing the callback add in an empty object to the params to simulate the event passed
				//we might need to fully create the event stub, and data if needed
				switch(type){
					case 'Player.end':
						$(curr).bind('clipEnded',function(){callback({})});
					break;
					case 'CONTENT_METADATA.clip_info_update':
						$(curr).bind('updatedMetadata',function(){callback({})});
					break;
				}
			}
			EmbeddedPlayer.prototype.getMetaData = function(){
				if(metadata){
					return metadata;
				}
				return settings.metaDataStub;
			}
			EmbeddedPlayer.prototype.updateAdData = function(){
				//stub does not need to do anything
			}

			embeddedPlayer=embeddedPlayer?embeddedPlayer:new EmbeddedPlayer();
			return embeddedPlayer;
		}
		Outlet.prototype.isAvailable = function(){
			return false;
		}
		if(window['Outlet']===undefined){
			window['Outlet'] = new Outlet();
			//check to see if the onOutletEvent is defined, if so, run it
			if(typeof window['onOutletEvent']==='function'){
				onOutletEvent({type:'outletInited'});
			}
			
		}
	}
	$.fn.h5Video.setPlayer = function(curr){
		//grabs the player and centers it in the player div
		var v = $.fn.h5Video.getPlayer();
		if(v){
			//for some reason you cant use position:absolute on a video element in the ipad, it does not display at all
			//so this has to be tricked with margins
			$(curr).css({textAlign:'left',padding:0});
			$(curr).html(v);
			var h = parseInt(settings.videoHeight);
			var w = parseInt(settings.videoWidth);
			var selH = $(curr).innerHeight();
			var top = Math.floor((selH-h)/2);
			var selW = $(curr).innerWidth();
			var left = Math.floor((selW-w)/2);
			
			// if(typeof console=='object') console.log('w: '+w+' selw: '+selW+' left: '+left);
			$('#'+settings.videoTagId,curr).css({marginTop:top,marginLeft:left});
			$(window).load(function(){
				//trying to autoplay
				//ios4.2.1 this does not work
				$('#'+settings.videoTagId)[0].load();
				$('#'+settings.videoTagId)[0].play();
			});

			return true;
		}
		return false;

	}
	$.fn.h5Video.getPlayer = function() {
		//this will create the video tag to put in the player div
		if(settings.videoId && settings.videoWidth!==undefined && settings.videoHeight!==undefined){
			var html = '<video id="' + settings.videoTagId + '"';
			html += ' width="' + settings.videoWidth + '" height="' + settings.videoHeight + '"';
			// html += preview ? ' poster="' + preview + '"' : '';
			html += ' controls="true" autoplay="true" preload="auto">';
			html += '<source  src="' + settings.videoPath + '" type="' + settings.videoMimetype + '"></source>';
			html += '</video>';
			return html;
		}
		return false;
	}


	$.fn.h5Video.defaults = {
		swfObject:null, //swfobject passed in from the page
		videoId:null, //videoId of currently playing item
		servicesURL: 'http://videoservices.nbcuni.com',  //base services URL, do not include a slash
		unavailableMessage: '<span class="message">This video is not available on your device</span>', //message to display when the video is not available
		smilPath: '/player/smil?version=SMIL21&output=json&callback=?&clipId=', //url to get SMIL file to see if clip is available in Kiptronics
		clipInfoPath: '/player/clip?output=json&callback=?&clipId=', //url to get the metadata about the clip
		wrapOutlet: true, //if this is true it will simulate the outlet object so other items still work
		videoTagId: 'html5Video', //ID of the video element,
		//this stub is returned when there is no metadata, it makes it so that any code that relies on any properties will not cause an error
		metaDataStub: {"properties":{"path": [],"description": "","headline": "","title": "","clipid": 0,"folderpath": "","showInNav": "","mezznimagepath": "","thumburl": "","geoip": "","publishdate": 0,"iswidgetable": "","videoads": "","preroll": "","midroll": "","adplaylist": "","cliplength": "","network": {"name": "","id": "","active": "","metric0": "","imageurl": "","externalkey": "","fullpageconfigpath": "","placement": 0,"continuousPlay": "","metric0": "","metric0": "","metric0": "","metric0": "","metric0": "","metric0": "","metric0": "","metric0": "","metric0": "","sponsorImageUrl": "","widgetId": "","commscore_publisher": "","error": null,"errordis": null},"externalkey": "","guid": "","maturecontent": "","permalink": "","placement": 0,"showcomments": "","showtime": "","suppressTimer": "","thirdpartyclip": "","useincontinuous": "","usenielsen": "","useomniture": "","geoflag": "","domainflag": "","imageUrl": "","thirdpartclip": "","tab": "","show": "","pageName": "","chapterDetails": {"segment": []},"episodesequence": null}}
	};
})(jQuery);


