// Overlay Video Player for iPad
WebKitVideo = Class.create({
	options: {
		//poster: 'http://trailers-dev.apple.com/trailers/global/images/quicktime/qt_endstate640x360.jpg', // Poster Frame
		closeOnFinish: false, // Close overlay after video finishes playing?
		triggers: '.WebKitVideo' // CSS Selector to collect triggers
	},

	events: {
		//onInit: function(){ try{ console.info('WebKitVideo:onInit');} catch(e){} },
		//beforePop: function(){ try{ console.info('WebKitVideo:beforePop');} catch(e){} },
		//afterPop: function(){ try{ console.info('WebKitVideo:afterPop');} catch(e){} },
		//beforeClose: function(){ try{ console.info('WebKitVideo:beforeClose');} catch(e){} },
		//afterClose: function(){ try{ console.info('WebKitVideo:afterClose');} catch(e){} },
		//onVideoStart: function(){ try{ console.info('WebKitVideo:onVideoStart');} catch(e){} },
		//onShowClose: function(){ try{ console.info('WebKitVideo:onShowClose');} catch(e){} },
		//onVideoEnd: function(){ try{ console.info('WebKitVideo:onVideoEnd');} catch(e){} }
	},

	initialize: function(options, triggers, events) {
		// Merge options with defaults
		if(!options) options = {};
		Object.extend(this.options,options);

		// Merge event functions with defaults
		if(!events) events = {};
		Object.extend(this.events,events);

		this.data = {};
		this.data.elements = [];
		this.data.movies = [];
		this.ViewMaster = document.body;

		this._fire('onInit');

		this.triggers = $$(this.options.triggers);
		if(triggers){ this.triggers = this.triggers.concat($$(triggers)); }
		if(this.triggers.length > 0){ this._setTriggers(); }
	},

	_fire: function(ev, memo){
		memo = memo ? memo : this;
		this.ViewMaster.fire('WebKitVideo:'+ev, memo);
		if(typeof(this.events[ev]) === 'function'){
			this.events[ev]();
		}
	},

	_setTriggers: function(){
		this.triggers.each(function(t){
			if(t.getAttribute('href')){
				var h = t.getAttribute('href');
				//t.href = '#';
				this.data.elements.push(t);
				this.data.movies.push(h);
			} else if(t.getAttribute('onclick')) {
				var h = t.getAttribute('onclick');
				h = h.split("'");
				h = h[1];
				if(h.indexOf('.mov') != -1 || h.indexOf('.m4v')){
					this.data.elements.push(t);
					this.data.movies.push(h);
					t.setAttribute('onclick','');
				}
			}
			t.observe('click', function(e){
				e.stop();
				
				el = e.findElement('a') ? e.findElement('a') : e.findElement('input');
				index = this.data.elements.indexOf(el);
				this._createOverlay(index);
			}.bind(this));
		}.bind(this));
	},

	_getDimensions: function(url){
		this.dimensions = {};
		this.dimensions.viewPort = this.ViewMaster.getDimensions();
		if(url.indexOf('?') !== -1){
			var ar = url.split('?')[1];
			var amp = (ar.indexOf('&amp;') !== -1) ? '&amp;' : '&';
			
			// Get url params separately (by either & or &amp;
			var ar = ar.split(amp);

			// Define vars
			var w = null;
			var h = null;

			// Check if width/height exist in url params
			ar.each(function(r){
				if(r.indexOf('width=') !== -1){
					w = isNaN(parseFloat(r.split('width=')[1])) ? w : parseFloat(r.split('width=')[1]);
				} else if(r.indexOf('height=') !== -1){
					h = isNaN(parseFloat(r.split('height=')[1])) ? h : parseFloat(r.split('height=')[1]);
				}
			});			

			// Stretch video to width of viewport, with a little margin, and retain ratio
			var ratio = h/w;
		}
		var r = ratio !== undefined && ratio !== 0 ? ratio : .5625;
		var w = this.dimensions.viewPort.width - 100;
		this.dimensions.video = {
			width: w,
			height: w * r
		};

		return this.dimensions;
	},

	_replay: function(){
		this.closeShowing = false;
		if(this.endState){
			this.endState.remove();
			delete this.endState;
		}
		if(this.video){
			this.video.show()
			this._fire('onVideoStart');
			this.video.play();
		}
		if(this.closeState){
			this.closeState.setStyle('opacity: 0');
		}
	},

	_close: function(){
		this._fire('beforeClose');

		this.closeShowing = false;
		if(this.overlay){
			this.overlay.setStyle('opacity: 0');
			removeOverlay = function(){
				this.overlay.remove();
				delete this.overlay;
				this._fire('afterClose');
			};
			removeOverlay.bind(this).delay(.75);
		}
		if(this.endState){ delete this.endState; }
		if(this.closeState){ delete this.closeState; }
		if(this.video){ this.video.pause(); delete this.video; }
		if(this.overlayScreen){ this.overlayScreen.remove(); delete this.overlayScreen; }
	},

	_showClose: function(){
		if(this.closeShowing !== true){
			this._fire('onShowClose');
			
			this.closeShowing = true;
			this.video.pause();
			this.video.hide();
			this.closeState.setStyle('opacity: 1');
		}
	},

	_createOverlay: function(index){
		this._fire('beforePop');

		this._createVideo(this.data.movies[index]);
		this._createCloseState(this.data.movies[index]);

		this.overlay = new Element('div', {
			'id': 'WebKitVideo-Overlay',
			'style': "width: "+this.dimensions.video.width+"px; margin-left:-"+(this.dimensions.video.width/2)+"px; height: "+this.dimensions.video.height+"px; margin-top:-"+(this.dimensions.video.height/2)+"px; opacity: 0;"
		});

		this.overlayScreen = new Element('div', {
			'id': 'WebKitVideo-OverlayScreen',
			'style': "height: "+this.dimensions.viewPort.height+"px;"
		});

		this.overlayScreen.observe('click', this._showClose.bind(this));
		this.ViewMaster.insert(this.overlayScreen);

		if(AC.Detector.isiPad() || AC.Detector.isMobile()){ // fix for airplay
			this.overlay.innerHTML = this.video.outerHTML;
			this.video = this.overlay.getElementsByTagName('video')[0];
		}
		else {
			this.overlay.insert(this.video);
		}
		
		this.overlay.insert(this.closeState);
		this.ViewMaster.insert(this.overlay);
		this._fire('afterPop');
		
		this.overlay.setStyle('opacity: 1');
		
		this._fire('onVideoStart');
		this.video.play();
	},

	_createEndState: function(url){
		this.video.hide();
		this.closeShowing = true;

		this.endState = new Element('div', {
			'class': 'endState',
			'style': 'width: ' + this.dimensions.video.width + 'px; padding-top: ' + (this.dimensions.video.height/2) + 'px; height: ' + (this.dimensions.video.height/2) + 'px;'
		});
		
		p = new Element('p');

		this.endStatePlay = new Element('a', {
			'href': url,
			'class': 'pillbutton'
		}).update('<span>Watch Again</span><b>&gt;</b>');
		this.endStatePlay.observe('click', function(e){ e.stop(); this._replay(); }.bind(this));

		this.endStateClose = new Element('a', {
			'href': '#',
			'class': 'close'
		}).update('<span>Close</span><b>x</b>');
		this.endStateClose.observe('click', function(e){ e.stop(); this._close(); }.bind(this));

		p.insert(this.endStateClose);
		p.insert(this.endStatePlay);
		this.endState.insert(p);

		this.overlay.insert(this.endState);
	},

	_createCloseState: function(url){
		this.closeState = new Element('div', {
			'class': 'closeState',
			'style': 'width: ' + this.dimensions.video.width + 'px; padding-top: ' + (this.dimensions.video.height/2) + 'px; height: ' + (this.dimensions.video.height/2) + 'px;'
		});
		
		p = new Element('p');

		this.closeStatePlay = new Element('a', {
			'href': url,
			'class': 'pillbutton'
		}).update('<span>Continue Watching</span><b>&gt;</b>');
		this.closeStatePlay.observe('click', function(e){ e.stop(); this._replay(); }.bind(this));

		this.closeStateClose = new Element('a', {
			'href': '#',
			'class': 'close'
		}).update('<span>Close</span><b>x</b>');
		this.closeStateClose.observe('click', function(e){ e.stop(); this._close(); }.bind(this));
		p.insert(this.closeStateClose);
		
		this.closeStateClose = new Element('a', {
			'href': '#',
			'class': 'pillbutton'
		}).update('<span>Close</span><b>x</b>');
		this.closeStateClose.observe('click', function(e){ e.stop(); this._close(); }.bind(this));
		p.insert(this.closeStateClose);
		
		p.insert(this.closeStatePlay);
		this.closeState.insert(p);

		this.closeState.setStyle('opacity: 0;');

		return this.closeState;
	},

	_createObject: function(url) {
		if(!this.video){
			this._getDimensions(url);
	
			this.video = document.createElement('object');
			this.video.setAttribute('codebase', 'http://www.apple.com/qtactivex/qtplugin.cab#version=7,3,0,0');
			this.video.setAttribute('classid', 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B');
			
			var addParam = function(name, value){
				var param = new Element('param', {
					'name': name,
					'value': value
				});
				this.video.insert(param);
			}.bind(this);
			
			addParam('href', url);
			addParam('target', 'myself');
			addParam('cache', true);
			
			if (this.dimensions.video) {
				if (!isNaN(parseInt(this.dimensions.video.width, 10))) {
					this.video.setAttribute('width', this.dimensions.video.width);
				}
				if (!isNaN(parseInt(this.dimensions.video.height, 10))) {
					this.video.setAttribute('height', this.dimensions.video.height);
				}
			}
		}

		this.video.stopObserving('ended');
		this.video.observe('ended', function(){
			this._fire('onVideoEnd');
			if(this.options.closeOnFinish){
				this._close();
			} else {
				this._createEndState(url);
			}
		}.bind(this));

		return this.video;
	},

	_createVideo: function(url) {
		if(!this.video){
			this._getDimensions(url);
	
			this.video = document.createElement('video');
			this.video.setAttribute('src', url);
			this.video.setAttribute('controls', true)
			this.video.setAttribute('poster', this.options.poster)

			// airplay
			this.video.setAttribute('airplay', 'allow');
			this.video.setAttribute('x-webkit-airplay', 'allow');
			
			if (this.dimensions.video) {
				if (!isNaN(parseInt(this.dimensions.video.width, 10))) {
					this.video.setAttribute('width', this.dimensions.video.width);
				}
				if (!isNaN(parseInt(this.dimensions.video.height, 10))) {
					this.video.setAttribute('height', this.dimensions.video.height);
				}
			}
		}

		this.video.stopObserving('ended');
		this.video.observe('ended', function(){
			this._fire('onVideoEnd');
			if(this.options.closeOnFinish){
				this._close();
			} else {
				this._createEndState(url);
			}
		}.bind(this));

		return this.video;
	}
});

// Hex to RGB converters
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)};
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)};
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)};
function cutHex(h) { h = (h.length === 4) ? '' + h[0]+h[1]+h[1]+h[2]+h[2]+h[3]+h[3] : h; return (h.charAt(0)=="#") ? h.substring(1,7):h};
