/*
	jQuery amazingVideo plugin - v1.0
	Copyright 2011 b:dreizehn, Germany

	"jQuery amazingVideo plugin" is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.
	
	"jQuery amazingVideo plugin" is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.
	
	You should have received a copy of the GNU Lesser General Public License
	along with "jQuery amazingVideo plugin".	If not, see <http://www.gnu.org/licenses/>.
*/

(function($, undefined) {

	$.amazingVideo = function(el, options) {
		// avoid scope issues
		var me = this;
		
		// shorthand options notation
		var opts;
		
		// initialization function; private
		me.init = function() {

			// store DOM element and jQuery object for later use
			me.el = el;
			me.$el = $(el);
			// store the video type, could be "mp4", "webm", "ogg" or "flash"
			me.videoType = null;
			// store the source URL to the video, useful for flash fallback
			me.videoSource = null;
			// filled with the flowplayer "player" object, otherwise with our custom object that can pause
			me.player = null;
			
			// remove any existing backups panel data
			var old_me = me.$el.data('amazingVideo');
			if (old_me !== undefined)
				me.$el.removeData('amazingVideo');
			
			// add a reverse reference to the DOM element
			me.$el.data('amazingVideo', me);
			
			// default video player options: autoplay, preload
			me.defaultOptions = {
				autoplay: false,
				preload: true
			}
			if (me.$el.attr('autoplay')) {
				me.defaultOptions.autoplay = true;
			}

			// store options
			opts = me.options = $.extend({}, me.defaultOptions, options);
			
			
			var supportedVideoFormats = b13.util.browser.supportsVideo();
			// evaluate which format can be used
			me.$el.children('source').each(function() {
				var videoType = $(this).prop('type');
				if (me.videoType == null) {
					if (videoType.indexOf('video/mp4') !== -1 &&  supportedVideoFormats.h264 == 'probably') {
						me.videoType = videoType;
						me.videoSource = $(this).prop('src');
						$(this).addClass('amazing-source-in-use');
						if ($('.prvList').length > 0){
							me.initPoster();
						}
					} else if (videoType.indexOf('video/webm') !== -1 &&  supportedVideoFormats.webm == 'probably') {
						me.videoType = videoType;
						me.videoSource = $(this).prop('src');
						$(this).addClass('amazing-source-in-use');
						if (videoType.indexOf('video/ogg') !== -1 && supportedVideoFormats.ogg == 'probably') {
						
						}
						if ($('.prvList').length > 0){
							me.initPoster();
						}
					} else if (videoType.indexOf('video/ogg') !== -1 && supportedVideoFormats.ogg == 'probably') {
 						me.videoType = videoType; 
						me.videoSource = $(this).prop('src');
						$(this).addClass('amazing-source-in-use'); 
					}
				} else {
					// we have already found one
//					$(this).remove();
// doesn't work ;-)
				}
				// Der Kunde möchte auch im FF die Flash-Datei gezeigt bekommen, weil hier die Farbechtheit besser ist.
				// FF 4 und FF5 behaupten zwar sie könnten webM abspielen, kann er aber nicht.
				if (jQuery.browser.mozilla && jQuery.browser.version.slice(0,3) > 3.6 ) {
					me.videoType = false;
				}
			});

			// flash fallback
			if (!me.videoType) {
				me.videoType = 'flash';
					// todo, find the source with MP4, and save it to me.videoSource
				if (me.$el.data('flashvideo')) {
					me.videoSource = me.$el.data('flashvideo');
				} else {
					me.videoSource = me.$el.children('source').first().prop('src');
				}
				me.initPoster();
				me.initFlashPlayer();
			
			} else {
				// define the player API for HTML5 players
				me.player = {
					play: function() {
						
						me.el.play();
					},
					pause: function() {
						me.el.pause();
					},
					duration: function() {
						// TODO
					},
					getVolume: function() {
						return me.el.volume;
					},
					setVolume: function(newVolume) {
						me.el.volume = newVolume;
					},
					mute: function() {
						me.el.muted = true;
					},
					unmute: function() {
						me.el.muted = false;
					},
					isMuted: function() {
						return (me.el.muted ? true : false);
					},
					ended: function() {
						return (me.el.ended ? true : false);
					}
				
				}
			}
			
			// initialize events
			me.initEvents();
			
			return me;
		};

		me.initEvents = function() {
			var hoverTimeout = 0;
			me.$el.parents('.prvItem').hover(function() {
				// play video on mouse enter

				// pause other players
				$('.amazingVideo').each(function() {
					var amazingVideoObj = $(this).data('amazingVideo');
					if (amazingVideoObj.isPlaying()) {
						amazingVideoObj.pause();
						amazingVideoObj.load();
						
					}
				});
				
				
				hoverTimeout = window.setTimeout(function() {
					me.play();
				}, 300);
				
			}, function(evt) {
				$.fx.off = true;
				$.fx.off = false;

				// leaving the video again
				window.clearTimeout(hoverTimeout);
				me.pause();

				// continue random player
				var enteredElement = $(evt.relatedTarget);
				if (!enteredElement.hasClass('prvItem') && enteredElement.parents('.prvItem').length == 0) {
					b_playRandomVideo();
				}
			});
			me.$el.delegate('.play', "click", function() {
				me.controls.play();
			});
			me.$el.delegate('.stop', "click", function() {
				me.controls.stop();
			});
			me.$el.bind('ended', function() {
				me.end();
			});
		};

		// initializes the flowplayer
		// see the API documentation for more details
		// http://flowplayer.org/documentation/api/index.html
		me.initFlashPlayer = function() {
			
			if (!me.el.id) {
				var flashId = 'amazingVideoWithFlash' + Math.round(Math.random()*100000);
			} else {
				var flashId = 'amazingVideoWithFlash' + me.el.id;
			}
			me.$el.before('<a href="'+ me.videoSource + '" id="'+ flashId +'" class="amazingVideoWithFlash" style="position: absolute; z-index: 50; display:none;  width: ' + me.$el.prop('width' ) +'px; height: '+ me.$el.prop('height') + 'px;"></a>');
			// me.$el.hide();
			
//  					key: "#@faff4c6666f9e31fd58"
	
			me.player = flowplayer(flashId, {
					src: "http://releases.flowplayer.org/swf/flowplayer.commercial-3.2.7.swf",
  					wmode: "transparent"
				}, {
  					key: "#@faff4c6666f9e31fd58",
					autoPlay: true, 
				// video will be buffered when splash screen is visible
					autoBuffering: false,
					play: null,
					onFinish: function() {
						me.$el.trigger('ended');
					},
					plugins: {
						// disable autoloading of the controlbar plugin
						controls: null
					}
			});
		};



		// event to start / continue playing the video
		me.play = function() {
				me.$el.siblings('img').fadeOut('slow');
					//flash
				me.$el.siblings('a').fadeIn('fast');
				me.$el.addClass('video-playing');
				me.player.play();
				if (me.videoType == 'flash') {
					me.$el.trigger('play');
				}
		};
		
		me.pause = function() {
				me.player.pause();

					//if flash is playing hide the a tag 
				me.end();
				if (me.videoType == 'flash') {
					me.$el.trigger('pause');
				}
		};
		
		me.isPlaying = function() {
			return me.$el.hasClass('video-playing');
		}
		
		me.end = function() {
				me.$el.siblings('a').fadeOut('fast'); 
				me.$el.siblings('img').fadeIn('slow');
				me.$el.removeClass('video-playing');
		}

/*		me.controls = function() {
			var controls {
				play: ,
				stop: ,
				volume: ,
				fullscreen
			}
		}
*/
		me.initPoster = function() {
			// get width, height and img src for the poster
			me.poster = {
				src: me.$el.prop('poster'),
				width: me.$el.prop('width'),
				height: me.$el.prop('height')
			}
			me.$el.before('<img class="poster amazingVideoPoster" src="' + me.poster.src + '" width="'+ me.poster.width +'" height="'+ me.poster.height +'" style="position: absolute;" /> ');


			return me;
		};
		
		// initialize ourself
		me.init();
	};

		
	$.fn.amazingVideo = function(options) {
	   // apply all util functions to ourself (for use in templates, etc.)
	   //$.extend($.amazingVideo, <insert your util object here>);
		return this.each(function() {
			(new $.amazingVideo(this, options));
		});
	};

})(jQuery);

