/**
 * HTML5 and Flash Video Playback Application
 *
 * @author			chris 
 * @copyright (c) 	Yellowspace
 * @date      		25.9.2010
 * @version   		$Id$
 *
 * @license video.js is licensed under the terms of the Open Source
 * LGPL 3.0 license. Commercial use is permitted to the extent that the 
 * code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 * 
 * License details: http://www.gnu.org/licenses/lgpl.html
 *
 *
 
 Articles
 	http://diveintohtml5.org/video.html
 	http://wiki.whatwg.org/wiki/Video_type_parameters
 	http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#video
 	
 Last Changes 
 
 Flash Video Playback needs
	<script type="text/javascript" src="/local/javascripts/video/swfobject.js"></script>
	<script type="text/javascript" src="/local/javascripts/video/flowplayer/flowplayer-3.2.2.min.js"></script>
	<script type="text/javascript" src="/local/javascripts/video/video.js"></script> 
 
 Example (ORDER IS IMPORTANT: iphone_video, ipad_video, mp4_video, flash_video)
	<script type="text/javascript">
	var defaults = [{
			ikey:'iphone_video',
			src:'YOUR VIDEO SRC', 
			width:480,
			height:270,
			type: 'video/mp4;', 
			id:'flowmovie',
			poster_img:{src:'YOUR SPLASH SCREEN SRC',width:480,height:270}
		},{
			ikey:'mp4_video',
			src:'YOUR VIDEO SRC', 
			width:480,
			height:270,
			type: 'video/mp4;', // with codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'
			id:'flowmovie',
			flowplay_context:'class="flowmovie" id="flowmovie"',
			close_button:true,
			poster_img:{src:'YOUR SPLASH SCREEN SRC',width:480,height:270}
		},{
			ikey:'flash_video',
			src:'YOUR VIDEO SRC', 
			width:480,
			height:270,
			type: 'video/flash;',
			id:'flowmovie',
			flowplayer_context:'class="flowmovie"',
			loadPlayer:true, // or use your own conf
			poster_img:{src:'YOUR SPLASH SCREEN SRC',width:480,height:270}
		}];
	
	var tpl = TV.loadVideoPlayer(defaults);
	document.write(tpl);
	</script>
 */


function VideoPlayback() {
	
	this.flashplayer = { // use your own conf (best way for lots of videos!) or overwirte these settings...
		id:'flowplayer',
		path: '/local/javascripts/video/flowplayer/flowplayer-3.1.5.swf',
		settings: {
			//key: f_key,
			clip:  { 
				autoPlay: true, 
				autoBuffering: true,
				title:''
			},
			onLoad: function(){
				this.setVolume(100);
			},
			canvas: {
				backgroundColor: "#000000",
				backgroundGradient: 'none'
			},
			onStart: function(){
				//alert("player loaded");
			},	
			//log:{level:'debug'},
			plugins: {
				controls: {
					tooltipColor: '#3d3d3d',
					backgroundGradient: 'none',
					bufferGradient: 'none',
					timeBgColor: '#3d3d3d',
					sliderGradient: 'none',
					borderRadius: '0px',
					buttonColor: '#000000',
					backgroundColor: '#3d3d3d',
					buttonOverColor: '#3d3d3d',
					progressColor: '#3d3d3d',
					progressGradient: 'medium',
					volumeSliderColor: '#000000',
					timeColor: '#cbcbcb',
					tooltipTextColor: '#ffffff',
					volumeSliderGradient: 'none',
					bufferColor: '#cbcbcb',
					durationColor: '#cbcbcb',
					sliderColor: '#000000',
					height: 24,
					opacity: 1.0,
					stop:true
				}
			}			
		}
	};
	
	this.close_button = {
		src:'/local/javascripts/video/_img/close.png',
		wr_style:'position:relative;',
		style:'float:right;cursor:pointer;display:none;right:-10px;top:-10px;position:absolute;z-index:2;'
	};
	this.html5_controls = 'preload controls'; //preload="none"
	this.verbose = false;
	
	//---------------------------------------------------------------------------------------
	
	this.loadVideoPlayer=function(p) {
		
		// start with iphone, ipad, mp4, flash
	
		if(this.verbose == true && typeof console == 'object') console.log('x start '+p.length+' player '+ navigator.userAgent+': %o',p);
		if(!p) return 'no conf defined...';
		var tpl = '';
		var playableVideo = false;
		var html5Playback = false;
		var matchingtype = false;
		var vd = {};
		
		for(i=0;i<p.length;i++) { //vformats in p
			
			var vformat = p[i].ikey;
			vd[vformat] = p[i]; // conversion to object to get a better handle
						
			var playable = this.SupportsHTML5VideoFormat(p[i]['type']);
			
			if(this.verbose == true && typeof console == 'object') console.log('x video '+vformat+' playable? '+ playable +': %o',p[i]);
			
			// if we got an iphone and an iphone version is defined: used it
			if(
				((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
				&& (vformat == 'iphone_video')
				&& (playable)
			) {
				var playableVideo = p[i];
				var html5Playback = true;	
				var matchingtype = playable;
				break;
			} 
			// same on ipad...
			else if(
				(navigator.userAgent.match(/iPad/i))
				&& (vformat == 'ipad_video')
				&& (playable)
			) {
				var playableVideo = p[i];
				var html5Playback = true;	
				var matchingtype = playable;
				break;				
			}	
			
			// find the best matching version
			if(playable == 'probably') {
				var playableVideo = p[i];
				var html5Playback = true;
				var matchingtype = playable;
			} else if(playable == 'maybe') {
				if(matchingtype == 'probably') continue; // we found allready a better matching... 
				var playableVideo = p[i];
				var html5Playback = true;
				var matchingtype = playable;
			}
			
		}
		
		if(this.verbose == true && typeof console == 'object') console.log('x html5Playback? '+ html5Playback+' with '+playableVideo.ikey+': %o',playableVideo);
		
		// flash fallback
		if(html5Playback == false) {
			if(vd.flash_video) var playableVideo = vd.flash_video; // play flash
			else if(vd.mp4_video) var playableVideo = vd.mp4_video; // play mp4 through flash
		}

		// isar only
		//var dtw = playableVideo.width;
		dtw = detectSWFWidth(playableVideo.id,playableVideo.width);
		if(dtw != playableVideo.width) {
			playableVideo.width = dtw;
			//playableVideo.poster_img.width = playableVideo.width;
			playableVideo.height = parseInt((playableVideo.width / 4) *3); // 4/3
			//playableVideo.poster_img.height = playableVideo.height;
		}		

		
		if(html5Playback) {
			// || Ext.isGecko3 --> needs different format
			
			if(playableVideo) {
				
				var video_style = '';
				if(playableVideo.poster_img) {
					tpl += '<a class="mp4videoplayer" style="cursor:pointer;display:block;background-image:url('+playableVideo.poster_img.src+');background-repeat:no-repeat;background-position: 50% 50%; ';
					if(playableVideo.poster_img.width) tpl += 'width:'+playableVideo.poster_img.width+'px; ';
					if(playableVideo.poster_img.height) tpl += 'height:'+playableVideo.poster_img.height+'px ';
					tpl += '" id="'+playableVideo.id+'_splash" ';
					tpl += 'onclick="TV.playHTML5Video(\''+playableVideo.id+'\');return false;" /><img src="'+playableVideo.poster_img.src+'" width="1" height="1" /></a>';
					var video_style = 'style="display:none;" '
				}

				if(playableVideo.close_button) {
					if(typeof playableVideo.close_button == 'object') {
						if(playableVideo.close_button.src) this.close_button.src = playableVideo.close_button.src;
						if(playableVideo.close_button.wr_style) this.close_button.wr_style = playableVideo.close_button.wr_style;
						if(playableVideo.close_button.style) this.close_button.style = playableVideo.close_button.style;
					}
					tpl += '<div class="close-video-wr" '; 
					tpl += 'style="width:'+playableVideo.width+'px;'+this.close_button.wr_style+'">';
					tpl += '<img src="'+this.close_button.src+'" id="'+playableVideo.id+'_closeimg" ';
					tpl += 'style="'+this.close_button.style+'" ';
					tpl += 'onclick="TV.controlHTML5Video(\''+playableVideo.id+'\',\'stop\');" class="close-video" />';
					tpl += '</div>';					
				}
				
				tpl += '<video onerror="TV.failed(event)" '+video_style;
				if(playableVideo.poster_img) tpl += 'poster="'+playableVideo.poster_img.src+'" ';
				tpl += 'id="'+playableVideo.id+'" ';
				tpl += 'width="'+playableVideo.width+'" height="'+playableVideo.height+'"';
				if(playableVideo.html5_controls) this.html5_controls = playableVideo.html5_controls;
				tpl += this.html5_controls+'>';
				tpl += '<source ';
				tpl += 'src="'+playableVideo.src+'" type=\''+playableVideo.type+'\' />';
				tpl += '</video>';
			}
		} else { // flash
			
			tpl += '<a '+playableVideo.flowplayer_context+' href="'+playableVideo.src+'" id="'+playableVideo.id+'"';
			tpl += 'style="display:block;width:'+playableVideo.width+'px;height:'+playableVideo.height+'px;';
			if(playableVideo.poster_img) {
				//tpl += '<div style="overflow:hidden;width:'+playableVideo.width+'px;height:'+playableVideo.height+'px;">';
				tpl += 'background-image:url('+playableVideo.poster_img.src+');background-repeat:no-repeat;background-position: 50% 50%;">';
				tpl += '<img src="'+playableVideo.poster_img.src+'" width="1" height="1" />';
				//if(playableVideo.poster_img.width) tpl += 'width="'+playableVideo.poster_img.width+'" ';
				//if(playableVideo.poster_img.height) tpl += 'height="'+playableVideo.poster_img.height+'"  />'
				//tpl += '</div>';
			} else tpl += '">';
			tpl += '</a>';			
			if(playableVideo.loadPlayer) {
				OnLoadFunctions[OnLoadFunctions.length] = "TV.setFlashPlayerConf({id:'"+playableVideo.id+"'});";
			}
		}
				
		return tpl;
	}
	

	this.controlHTML5Video = function(id,c) {
				
		switch(c) {
			case'close':
			case'stop':
				if(typeof $(id).pause == 'function') $(id).pause();
				$(id+'_splash').style.display='block';
				if($(id+'_closeimg')) {
					$(id+'_closeimg').style.display='none';
				}
				$(id).style.display='none';
				break;
			case'pause':
				if(typeof $(id).pause == 'function') $(id).pause();
		}
		
	}
	

	this.playHTML5Video = function(id) {
		if($(id+'_splash')) $(id+'_splash').style.display='none';
		if($(id+'_closeimg')) {
			$(id+'_closeimg').style.display='block';
		}
		$(id).style.display='block';
		$(id).play();
	}
	
	
	this.pauseHTML5HeadPlayer = function(e,id) {
		if(typeof $(id).pause == 'function') $(id).pause();
	}

	this.SupportsHTML5Video=function() {
	  return !!document.createElement('video').canPlayType;
	}

	this.SupportsHTML5VideoFormat=function(format) {
		if (!this.SupportsHTML5Video()) { return false; }
		var v = document.createElement("video");
		if(v) return v.canPlayType(format);
		else return false
	}

	this.setFlashPlayerConf = function(params) {
		if(document.domain.indexOf('yellowspace')) {}; // develop?
		if(this.flashplayer.id == 'flowplayer') var player = flowplayer(params.id, this.flashplayer.path,this.flashplayer.settings);
		//if(typeof console == 'object') console.log('x player: %o',player);
	}
		
	//---------------------------------------------------------------------------------------
	this.failed = function(e) {
	   // video playback failed - show a message saying why
		var message = 'Unknown error';
		switch (e.target.error.code) {
			case e.target.error.MEDIA_ERR_ABORTED:
				var message = 'You aborted the video playback.';
				break;
			case e.target.error.MEDIA_ERR_NETWORK:
				var message = 'A network error caused the video download to fail part-way.';
				break;
			case e.target.error.MEDIA_ERR_DECODE:
				var message = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.';
				break;
			case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
				var message = 'The video could not be loaded, either because the server or network failed or because the format is not supported.';
				break;
			default:
				var message = 'An unknown error occurred.';
				break;
		}
	   
	    if(typeof console == 'object') console.log('x '+ message+': %o',e);
	   
	 }

	//---------------------------------------------------------------------------------------
	this.preloadImages = function(images){
        var preload = Ext.get(document.body).createChild({tag:"div", style:"display:none"});
        if(images && images.length > 0) {
			Ext.each(images, function(image){
				if (typeof(image)=='string'){
				 image={src:image}
				}
								
				if (image.src){
					preload.createChild({tag:"img", src:image.src});
				}
				
				if (image.fullSrc){
					preload.createChild({tag:"img", src:image.fullSrc});
				}
			}, this);
        } else if(typeof images == 'object') {
        	for(img_sid in images) {
  				if (images[img_sid].src){
					preload.createChild({tag:"img", src:images[img_sid].src});
				}      		
        	} 
        }
    }
}


TV = new VideoPlayback();


function loadFlowConf() {
	flowplayer("a.flowmovie", '/local/javascripts/video/flowplayer/flowplayer-3.1.5.swf', {
	key: false,
	  clip:  { 
		  //scaling: 'fit',
		  autoPlay: true, 
		  autoBuffering: true,
		  play: null
		},
    	//log:{level:'debug'},
	  canvas: {
		  backgroundColor: "#1a1a1a",
		  backgroundGradient: 'none'
		  },
		onLoad: function(clip,h){
			//if(typeof console == 'object') console.log('x onLoad clip: %o',clip);
			//if(typeof console == 'object') console.log('x onLoad this: %o',this);
			//alert("player loaded");
		},	
		onStart: function(clip,h){
			//if(typeof console == 'object') console.log('x onStart '+this.isResized+' clip: %o',clip);
			//if(typeof console == 'object') console.log('x onStart h: %o',h);
			//if(typeof console == 'object') console.log('x onStart this: %o',this);	
			//if(typeof console == 'object') console.log('x onStart this.getParent(): %o',this.getParent());	
			
			// set container to video size
			var wrapper = this.getParent();
			w_width = parseInt(wrapper.style.width); // max boundaries
			w_height = parseInt(wrapper.style.height); // max boundaries
			var xrate = false;
			
			if(!this.isResized) {
				
				//if(typeof console == 'object') console.log('x w_width p: %o',w_width);
				//if(typeof console == 'object') console.log('x clip.metaData.width p: %o',clip.metaData.width);
				if(clip.metaData.width && clip.metaData.width >0 && w_width > clip.metaData.width) {
					//clip.scaling='fit';
					wrapper.style.width = clip.metaData.width + 'px';
					//if(typeof console == 'object') console.log('x NEW: clip.metaData.width p: %o',clip.metaData.width);
					this.isResized = true;
				} else if(clip.metaData.width && clip.metaData.width >0 && w_width < clip.metaData.width) {
					// do it by your self
				}
				
				
				//if(typeof console == 'object') console.log('x w_height p: %o',w_height);
				//if(typeof console == 'object') console.log('x clip.metaData.height p: %o',clip.metaData.height);
				if(clip.metaData.height && clip.metaData.height >0 && w_height > clip.metaData.height) {
					//clip.scaling='fit';
					wrapper.style.height = clip.metaData.height + 'px';
					this.isResized = true;
					//if(typeof console == 'object') console.log('x NEW: clip.metaData.height p: %o',clip.metaData.height);
				} else if(clip.height && clip.height >0 && w_height < clip.metaData.height) {
					// do it by your self
				}			
			}
			//alert("player loaded");
		},			
		/*logo: { 
			url: 'http://www.thomaskramer.com/images/logo.png', 
			top: 30, 
			right: 30, 
			opacity: 1, 
			fullscreenOnly: true, 
			displayTime: 0, 
			linkUrl: '#'
		},*/
	  plugins: {
		controls: {
		  tooltipColor: '#5F747C',
		  backgroundGradient: 'none',
		  bufferGradient: 'none',
		  timeBgColor: '#555555',
		  sliderGradient: 'none',
		  borderRadius: '0px',
		  buttonColor: '#d8030a',
		  backgroundColor: '#222222',
		  buttonOverColor: '#050505',
		  progressColor: '#eb0003',
		  progressGradient: 'medium',
		  volumeSliderColor: '#000000',
		  timeColor: '#0b0a0a',
		  tooltipTextColor: '#ffffff',
		  volumeSliderGradient: 'none',
		  bufferColor: '#000000',
		  durationColor: '#de020a',
		  sliderColor: '#000000',
		  height: 24,
		  opacity: 1.0,
		  stop:true
		}
	  }
	});
	
}
OnLoadFunctions[OnLoadFunctions.length] = "loadFlowConf()";
