//Namespace
if (typeof(EnergyApps)=== "undefined") {
	EnergyApps = {
		Video: {
			Manager : {},
			AbstractLayer : {},
			Layer : {},
			Element : {}
		}
	};
}
if (typeof(EnergyApps.Video) === "undefined"){
	EnergyApps.Video = {
		Manager : {},
		AbstractLayer : {},
		Layer : {},
		Element : {}
	};
}
/**
 * manager for rendering video tags
 * replaces any existing <video /> tag with a clickable image
 * (on click layer opens and plays a flash video)
 * @class EnergyApps.Video.Manager
 * @namespace EnergyApps.Video
 * @extends Publicis.Observable
 * @author Sebastian Sauer
 * @constructor
 * @param {Object} cfg
 */
EnergyApps.Video.Manager = function () {
	// call parent constructor
	EnergyApps.Video.Manager.superclass.constructor.call(this);

	this.counter = 0;

	this._findVideos();
};

Publicis.extend(EnergyApps.Video.Manager , Publicis.Observable, {
	/**
	 * grabs the video source given from openengine and
	 * builds absolute web path for siemens web player
	 * @private
	 * @return string
	 */
	_getVideoUrl : function ( path ) {
	
		if( ! ( /\.\./ ).test( path ) ) {
			return path;
		}	
	
		var queryPath = window.location.pathname,
			queryParts = queryPath.split(/\//),
			tmp = "";
		
		if( ( /\.*(htm|html|php)/i ).test( queryPath ) ) {
			queryParts.pop();
		}
		tmp = queryParts.join( '/' );
		if( '/' !== ( tmp ).substr( -1 ) ) {
		    tmp += '/';
		}
		if( '/' !== ( tmp ).substr( 1, 1 ) ) {
		    tmp = '/' + tmp;
		}
		tmp = window.location.protocol + '//' + window.location.hostname + tmp;
		
		return tmp + path;
	},
	/**
	 * @private
	 */
	_findVideos: function() {
		$A( document.getElementsByTagName( "video" ) ).each( function ( video ) {
			this.bindVideo.call( this, video )
		}.bind( this ) );
	},
	/**
	 * @param {Element} video
	 * @param {Boolean parseUrl} [optional] default: true
	 * @return EnergyApps.Video.Layer
	 */
	bindVideo : function (video, parseUrl ){
		video = $(video);

		if( typeof parseUrl === "undefined" ) {
			parseUrl = true;
		}

		this.counter += 1;

		var title = video.readAttribute('title'),
			width = parseInt(video.readAttribute('width'), 10),
			height = parseInt(video.readAttribute('height'), 10),
			thumbnail = video.readAttribute('data-thumb'),
			src = video.down('source').readAttribute('src'),
			startImage = video.readAttribute('poster'),
			autoplay,
			hasImage = false,
			flashvars = {},
			params = {},
			link,
			container,
			image,
			that = this;
		autoplay = video.readAttribute('autostart') == "true";

		params.allowFullscreen = "true";
		params.allowScriptAccess = "always";
		params.wmode = "transparent";
		params.scale = "noscale";
		params.salign = "TL";

		if( parseUrl ) {
			src = this._getVideoUrl(src);
		}

		flashvars.path = src;
		flashvars.title = title;
		flashvars.startImage = startImage;
		flashvars.autoPlay = autoplay;

		container = new Element('div', {
				'class': 'video_container'
			})
			.update(
				(function () {
					link = new Element ('a', {
						'class': 'open_video video_container',
						href: src ,
						id : "open_video_" + that.counter
					}).update(
						/**
						 * update link (thumbnail or text, preferred = thumb)
						 * @closure
						 */
						(function (){
							if(typeof(thumbnail) === "string" && thumbnail.length > 0) {
								hasImage = true;
								image = new Element ('img', {
									'src' : thumbnail,
									'alt' : title
								});
								return image;
							} else {
								return title;
							}
						})()
					);
					return link;
				})()
		);
		if(hasImage) {
			var img = video.next(),
				h = img.height,
				w = img.width;

			if( h == 0 ) {
				var $clone = img.clone();
				$('footer-position-wrapper').insert($clone);
				h = $clone.getDimensions().height || 20;
				w = $clone.getDimensions().width || 100;
				$clone.remove();
			}
			img.remove();

			container.setStyle({
				'height' : (h + 10).toString() + 'px',
				'width' : (w + 10).toString() + 'px'
			});
			link.setStyle({
				'height' : h.toString() + 'px',
				'width' : w.toString() + 'px'
			});
		} else {
			link.addClassName('no_thumb');
		}
		video.replace(container);
		var layer = new EnergyApps.Video.Layer({
			layerType : "video",
			idContainer: "webvideo_container_" + this.counter,
			idSwf: "webvideo_container_container_" + this.counter,
			trigger: $('open_video_' + this.counter),
			manager: this,
			width : width,
			height : height,
			flashParams : params,
			flashVars : flashvars
		});
		return layer;
	}
});

EnergyApps.Video.AbstractLayer = function (config) {
	EnergyApps.Video.AbstractLayer.superclass.constructor.call(this, config);

	this.addListener("close", function (){

		var position;
		if( !! this.opener ) {
			
			// get back to where the click comes from
			position = Publicis.getPosition( this.opener );
			if( ! this.opener.getHeight() ) {
			    return;
			}
			window.scrollTo( position.left, position.top );
		}

		if( ! Publicis.hasFlash() || ! this.activeFrameId ) {
			return;
		}

		swfobject.removeSWF( this.activeFrameId );

	}, this);

};
Publicis.extend( EnergyApps.Video.AbstractLayer , Publicis.Lightbox, {} );

/**
 * @class EnergyApps.Video.Layer
 * @namespace EnergyApps.Video
 * @extends Publicis.Lightbox
 * @constructor
 * @param {Object} cfg Configuration options
 * @author Sebastian Sauer
 */
EnergyApps.Video.Layer = function (config) {
	EnergyApps.Video.Layer.superclass.constructor.call(this, config);
	/**
	 * @cfg {Sring} url Url to load in iframe
	 */
	if(typeof this.url === "undefined") {
		this.url = (typeof(config.url) !== "undefined") ? config.url : $(this.trigger).readAttribute('href');
	}

	this.videoContainer = $(this.idContainer).firstDescendant();
	this.addListener("open", function (){
		try {
			var video = this.videoContainer.firstDescendant();
			if(video !== null) {
				return;
			}
			this.activeFrameId = this.videoContainer.id + "_" + Date.parse(new Date());
			video = this.video = $(document.createElement('div'));
			video.writeAttribute({
				id : this.activeFrameId
			});

			this.videoContainer.insert(video);
			swfobject.embedSWF(
				"/apps/videoplayer/siemens/Standalone_3.0.3.swf",
				this.activeFrameId,
				this.width,
				this.height,
				"9.0.0",
				"",
				config.flashVars,
				config.flashParams
			);
		} catch(e) {}
	}, this);

};
Publicis.extend(EnergyApps.Video.Layer , EnergyApps.Video.AbstractLayer, {});

/**
 * represents one video element
 *
 * @class EnergyApps.Video.Element
 * @namespace EnergyApps.Video
 * @extends Publicis.Observable
 * @constructor
 * @param {Object} config Configuration options
 * @author Sebastian Sauer
 */
EnergyApps.Video.Element = function( config ) {

	EnergyApps.Video.Element.superclass.constructor.call(this, config);

	config.width = ( !! config.width )
		? parseInt( config.width, 10 )
		: 320;
	config.height = ( !! config.height )
		? parseInt( config.height, 10 )
		: 240;

	/**
	 * @cfg {Number} width Video width (default 320)
	 */
	config.width = ( config.width > 0)
		? config.width
		: 320;
	/**
	 * @cfg {Number} height Video height (default 240)
	 */
	config.height = ( config.height > 0 )
		? config.height
		: 240;

	/**
	 * @cfg {Boolean} autoplay (default false)
	 */
	config.autoplay = ( typeof config.autoplay !== "undefined" )
		? !! config.autoplay
		: true;

	this.config = config;

	var video;

	video = new Element( "video", {
		width : config.width,
		height : config.height
	});
	video.writeAttribute( "controls" );
	if( this.config.autoplay ) {
		video.writeAttribute( "autoplay" );
	}

	this.video = video;

	this.registerEvent( [
		/**
		 * @event beforeupdate
		 * @param {EnergyApps.Video.Element} this
		 * @param {Object} data
		 * @see EnergyApps.Video.Element.update
		 * Fires before video component gets updated. Return false to stop open.
		 */
		"beforeupdate",
		/**
		 * @event update
		 * @param {EnergyApps.Video.Element} this
		 * Fires after video component gets updated.
		 */
		"update"
	] );

	this.update( config );
}

Publicis.extend( EnergyApps.Video.Element, Publicis.Observable, {

	/**
	 * @returns {Element} video
	 */
	get : function () {
		return this.video;
	},
	/**
	 * @param {Object} data
	 * @returns {Element} video
	 */
	update : function ( data ) {

		var video, sources = [];

		if( ! data || ( ! data.h264 && ! data.webm && ! data.theora ) ) {
			// no data or no video
			return this.video;
		}

		if( false === this.fireEvent( "beforeupdate", this, data ) ) {
			return this.video;
		}

		// mp4 first!! (ios3 fails otherwise)
		if( data.h264 && data.h264.length > 0 ) {
			sources.push(
				'<source src="' + data.h264 + '"  type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />'
			);
		}
		if( data.webm && data.webm.length > 0 ) {
			sources.push(
				'<source src="' + data.webm + '" type=\'video/webm; codecs="vp8, vorbis"\' />'
			);
		}
		if( data.theora && data.theora.length > 0 ) {
			sources.push(
				'<source src="' + data.theora + '"  type=\'video/ogg; codecs="theora, vorbis"\' />'
			);
		}
		this.video.update( sources.join( "" ) );

		this.fireEvent( "update", this );

		return this.video;
	}

} );

