/**
 * video.js extension
 */
(function($) {
	
	var videoJSExtCount = 0;

	/**
	 * extension for video.js
	 */
	$.videoJSExt = function(el, opts) {
		/* exclude touch devices */
		var uaString = navigator.userAgent;
		if (VideoJS.isIOS()) {
			return;
		}
		/* prepare */
		var _this = this;
		_this.$el = $(el);
		_this.flashVideoSrc = null;
		_this.posterSrc = _this.$el.attr('poster');
		_this.width = _this.$el.attr('width');
		_this.height = _this.$el.attr('height');
		_this.flowPlayerSrc = "http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf";
		_this.$el.find('source').each(function() {
					if ($(this).attr('type') == 'video/mp4') {
						_this.flashVideoSrc = $(this).attr('src');
					}
				});
		_this.options = $.extend({}, {
			noFlashHtml : "<strong>Video Playback in your browser requires Adobe Flash version 10 or newer.</strong>"
		}, opts);

		// $.log('video', el);

		/**
		 * builds the flash player.
		 */
		_this.buildFlashPlayer = function() {
			var flashVars = '{"playlist":[';
			if (_this.posterSrc != '') {
				flashVars += '"' + _this.posterSrc + '",';
			}
			flashVars += '{"url": "' + _this.flashVideoSrc
					+ '","autoPlay":false,"autoBuffering":';
			if (_this.posterSrc != '') {
				flashVars += 'true';
			} else {
				flashVars += 'true';
			}
			flashVars += ',"scaling":"fit","rangeRequests": true}';
			flashVars += "]}";

			if (typeof(swfobject) == 'object') {
				/*
				 * embed using swfobject.
				 */
				var divName = 'videoJsExt'
						+ (videoJSExtCount++);
				var swfObjectStr = '<div id="' + divName + '">';
				swfObjectStr += _this.options.noFlashHtml;
				swfObjectStr += '</div>';
				swfObjectStr += '<script type="text/javascript">\n';
				swfObjectStr += 'swfobject.embedSWF(';
				swfObjectStr += '"' + _this.flowPlayerSrc + '",';
				swfObjectStr += '"' + divName + '",';
				swfObjectStr += '"' + _this.width + '",';
				swfObjectStr += '"' + _this.height + '",';
				swfObjectStr += '"10",';
				swfObjectStr += '{},';
				swfObjectStr += '{config: \'' + encodeURIComponent(flashVars)
						+ '\'},';
				swfObjectStr += '{ allowfullscreen:true, bgcolor: "#000000"';
				if (typeof(_this.options.wmode) == 'string') {
					swfObjectStr += ', wmode: "transparent"';
				}
				swfObjectStr += '}';
				swfObjectStr += ');';
				swfObjectStr += '\n</script>';
				// alert(swfObjectStr);
				return swfObjectStr;
			} else {
				/*
				 * embed using HTML.
				 */
				var objectStr = '<object class="vjs-flash-fallback" width="'
						+ _this.width + '" height="' + _this.height
						+ '" type="application/x-shockwave-flash" ' + 'data="'
						+ _this.flowPlayerSrc + '">';
				objectStr += '<param name="movie" value="'
						+ _this.flowPlayerSrc + '" />';
				objectStr += '<param name="bgcolor" value="#000000"/>';
				if (typeof(_this.options.wmode) == 'string') {
					objectStr += '<param name="wmode" value="' + wmode + '"/>';
				}
				objectStr += '<param name="allowfullscreen" value="true" />';
				objectStr += '<param name="flashvars" value="config='
						+ flashVars.replace(/"/g, "&quot;") + '"/>';
				// <!-- Image Fallback. Typically the same as the poster image.
				// -->
				// <img src="http://video-js.zencoder.com/oceans-clip.png"
				// width="640" height="264" alt="Poster Image"
				// title="No video playback capabilities." />
				objectStr += '</object>'
				return objectStr;
			}
		};

		/**
		 * resolves URIs to the current document.
		 */
		_this.resolveURI = function(src) {
			if (typeof(src) != 'string') {
				return '';
			} else if (src === '') {
				return src;
			} else if (src.match(/^https?:\/\/.*$/) != null) {
				return src;
			}
			var docURI = _this.parseURI(document.location.href);
			var resolved = docURI.scheme + '://' + docURI.authority;
			if (src.indexOf('/') == 0) {
				resolved += src;
			} else {
				resolved += docURI.path + '/' + src;
			}
			// console.log(resolved);
			return resolved;
		};

		/**
		 * modifies the HTML as required.
		 */
		_this.init = function() {
			/* resolve URIs */
			_this.posterSrc = _this.resolveURI(_this.posterSrc);
			_this.flashVideoSrc = _this.resolveURI(_this.flashVideoSrc);
			_this.flowPlayerSrc = _this.resolveURI(_this.flowPlayerSrc);
			/* build HTML */
			_this.$el.wrap('<div class="video-js-box"/>');
			_this.$el.addClass('video-js');
			if (!VideoJS.isIOS() && !VideoJS.browserSupportsVideo()) {
				_this.$el.append(_this.buildFlashPlayer());
			}
			_this.$el.VideoJS(_this.options);
		};

		_this.parseURI = function(uri) {
			var m = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/
					.exec(uri);
			var u = {};
			// Generic components (as specified in RFC3986)
			u.scheme = m[2];
			u.authority = m[4];
			u.path = m[5];
			u.query = m[7];
			u.fragment = m[9];
			u.hostname = null;
			u.port = null;
			if (typeof(m[4]) == 'string') {
				u.hostname = m[4].split(':')[0];
				u.port = m[4].split(':')[1] || '';
			}

			u.params = {};
			if (typeof(m[7]) == 'string') {
				// Parse the query string
				var q = m[7].split('&');
				while (q.length > 0) {
					var x = q.shift().split('=');
					u.params[x[0]] = x[1];
				}
			}

			return u;
		};

		_this.init();

	};

	$.fn.videoJSExt = function(options) {
		return this.each(function() {
					(new $.videoJSExt(this, options));
				});
	}

})(jQuery);

