//Namespace
if (typeof EnergyApps === "undefined"){ EnergyApps = { Gallery: {} }; }
if (typeof(EnergyApps.Gallery) === "undefined"){
	EnergyApps.Gallery= {
		Manager : {},
		MyGallery: {},
		Layer : {}
	};
}

if( EnergyApps.Webfeature == null ) {
	EnergyApps.Webfeature = {};
}
/**
 * @class EnergyApps.Webfeature.Element
 * @namespace EnergyApps.Webfeature
 * @extends Publicis.Observable
 * @constructor
 * @param {Object} cfg Configuration options
 * @author Sebastian Sauer
 */
EnergyApps.Webfeature.Element = function( config ){

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

	this.featureData = false;

	if( ! config.container instanceof Element ) {
		throw Error( "no parent element given." );
	}
	/**
	 * @cfg {Element} container
	 */
	this.parent = config.container;

	/**
	 * @cfg {String} href
	 */

	this.setBasePath( config.href  );
	this.getSwfContainer();

	this.registerEvent([
		/**
		 * @event destroy
		 * Fires when flash component gets unloaded
		 * @param {EnergyApps.Webfeature.Element} this
		 */
		"unload"
	]);

};

Publicis.extend( EnergyApps.Webfeature.Element, Publicis.Observable, {
	getSwfContainer : function() {
		var id = Publicis.uniqueId (),
		container = new Element( "div", {
			id : id
		});

		this.swfContainer = container;

		this.parent.update( container );
	},
	/**
	 * @private
	 * @returns {String}
	 */
	getBasePath: function (hashpath){
		if( ! hashpath ) {
			return "";
		}
		// replace first hash
		return hashpath.replace( /#/, "" );
	},
	/**
	 * @param {String} hashpath : #webfeature=/path/to/feature
	 * @returns {EnergyApps.Webfeature.Element} this
	 */
	setBasePath : function( hashpath ) {
		this.basepath = this.getBasePath( hashpath );
		this.url = this.basepath + "/config.xml";
		return this;
	},
	/**
	 * @returns {EnergyApps.Webfeature.Element} this
	 */
	load: function (){
		try {
			this.getSwfContainer();
			var xhr = new Ajax.Request( this.url, {
				method: 'get',
				onSuccess: this.requestOK.bind(this),
				onFailure : this.requestNotOK.bind(this),
				onException: this.requestNotOK.bind(this)
			} );
		} catch (e) {
			this.requestNotOK();
		}
		return this;
	},
	/**
	 * @private
	 */
	requestOK: function (response){
		try {
			if (null === response.responseXML) {
				this.requestNotOK();
				return;
			}
			var xml = response.responseXML;
			this.featureData = this.parseXMLResponse(xml, this.basepath);
			swfobject.embedSWF(
				this.featureData.href,
				this.swfContainer.id,
				"960",
				"393",
				"9.0.0",
				'/apps/features/swfobject/expressInstall.swf',
				this.featureData.flashVars,
				this.featureData.flashParams,
				null,
				this.callbackSWFObject.bind(this)
			);
		}catch(e){
			this.requestNotOK();
		}
	},
	requestNotOK: function (){
		if( this.featureData && this.featureData.fallback && this.featureData.fallback.img ){
			this.swfContainer.update(
				new Element( "img", { src : this.featureData.fallback.img } )
			);
		}
	},
	callbackSWFObject: function (e){
		if (e.success === false){
			this.requestNotOK();
		}
	},
	parseXMLResponse : function (xmldoc, basepath){
		var data = {href: "", flashVars: {}, flashParams: {}, fallback: {}}, item = false, subitems = false, subitem = false, fallbackItems = false;
		var root = xmldoc.documentElement;
		var children = root.childNodes;
		data.href = basepath + root.getAttribute('href');
		for (var i = 0; i < children.length; i++) {
			item = children[i];
			if (item.nodeType != 1){
				continue;
			}
			if (item.nodeName == "flashParams" || item.nodeName == "flashVars" || item.nodeName == "flashInfo"){
				subitems = item.childNodes;
				for (var j = 0; j < subitems.length; j++) {
					subitem = subitems[j];
					if (subitem.nodeType != 1) {
						continue;
					}
					if (item.nodeName != "flashInfo") {
						data[item.nodeName][subitem.getAttribute("name")] = this.getNodeVal(subitem);
					}else if (subitem.nodeName == "fallback"){
						fallbackItems = subitem.childNodes;
						for (var k = 0; k < fallbackItems.length; k++) {
							if (fallbackItems[k].nodeType == 1){
								if (fallbackItems[k].nodeName == "text") {
									data.fallback.text = this.getNodeVal(fallbackItems[k]);
								}
								if (fallbackItems[k].nodeName == "img") {
									data.fallback.img = basepath + fallbackItems[k].getAttribute("src");
								}
							}
						}
					}
				}
			}
		}
		//Obligatory flash params
		data.flashParams.wmode = "transparent";
		data.flashParams.scale = "noscale";
		data.flashParams.salign = "TL";

		data.flashVars.basepath = basepath;
		return data;
	},

	getNodeVal : function (node) {
		try {
			if(node.textContent) {
				return node.textContent;
			}
			return node.text;
		} catch (e) { return ''; }
	},
	unload : function () {
		swfobject.removeSWF( this.swfContainer.id );
		this.fireEvent( "unload", this );
	}

});

/**
 * manager for galleries
 * @class EnergyApps.Gallery.Manager
 * @namespace EnergyApps.Gallery
 * @extends Publicis.Observable
 * @author Jonas Bach
 * @constructor
 */
EnergyApps.Gallery.Manager = function () {
	// call parent constructor
	EnergyApps.Video.Manager.superclass.constructor.call(this);

	// options
	this.config = {
		selector: '.pub_gallery',
		slideDuration: 3
	};
	this._renderGalleries();
};

Publicis.extend(EnergyApps.Gallery.Manager , Publicis.Observable, {
	/**
	 * create MyGallery instances for each gallery
	 * @private
	 */
	_renderGalleries: function(){
		this.galleries = [];
		$$(this.config.selector).each(function(item){
			this.galleries.push(new EnergyApps.Gallery.MyGallery(item, this.config.slideDuration, this.galleries.length));
		}.bind(this));
	}
});


/**
 * single Gallery
 * provides functionality like slideshol, next/prev buttons etc
 * @class EnergyApps.Gallery.Manager
 * @namespace EnergyApps.Gallery
 * @extends Publicis.Observable
 * @author Jonas Bach
 * @constructor
 */
EnergyApps.Gallery.MyGallery = function (item, slideDuration, galleryId) {
	// call parent constructor
	EnergyApps.Gallery.MyGallery.superclass.constructor.call(this);
	this._container = item;
	this._slideDuration = slideDuration;
	this._galleryId = galleryId;
	this._renderGallery();
	this._renderLayer();
};


Publicis.extend(EnergyApps.Gallery.MyGallery , Publicis.Observable, {
	_renderGallery: function(){
		// initialize variables
		this._container.addClassName('has_js');
		this._active = null;
		this._thumbnails = this._container.select('.thumbs li');
		this._small_images = [];
		this._descriptions = [];
		this._navi_links = [];
		this._slideshow = false;
		this._slideshowTimer = null;

		if(this._thumbnails.length < 1){
			return;
		}else if(this._thumbnails.length > 1){

			// add navigation if more than 1 element
			this._playstop = new Element('a',{
				'href':'javascript:void(0)',
				'class':'playstop'
			}).update('Play');

			var prev = new Element('a',{
				'href':'javascript:void(0)',
				'class':'prev'
			}).update('&laquo;');

			var next = new Element('a',{
				'href':'javascript:void(0)',
				'class':'next'
			}).update('&raquo;');

			this._navi = new Element('ul',{
				'class':'navi'
			});

			var naviContainer = new Element('div',{
				'class':'navi_container'
			}).insert(this._playstop).insert(prev).insert(this._navi).insert(next);

			this._container.insert(naviContainer);

			// functionality for next/prev
			prev.observe('click', function(event){
				this.stopSlideshow();
				this.setPrevious();
			}.bind(this));

			next.observe('click', function(event){
				this.stopSlideshow();
				this.setNext();
			}.bind(this));

			// slideshow
			this._playstop.observe('click', function(event){
				if(this._slideshow){
					this.stopSlideshow();
				}else{
					this.startSlideshow();
				}
			}.bind(this));
		}

		// small img container
		this._imgContainer = new Element('div', {
			'class':'img_container'
		});

		// descriptions container
		this._descrContainer = new Element('div', {
			'class':'descr_container'
		});

		// inserting
		this._container.down('.thumbs').insert({
			before: this._imgContainer
		});

		this._container.insert(this._descrContainer);

		// add layer
		this._layer = new EnergyApps.Gallery.Layer({
			layerType : "gallery",
			idContainer: "gallery_container_"+this._galleryId,
			manager: this
		});

		// add elements
		this._thumbnails.each(function(item) {
			this.addElement(item);
		}.bind(this));

		// set first picture
		this.setActive(0);
	},

	_renderLayer:function(){
	},

	addElement: function(el){

		// move img
		var small_img = el.down('.boxed');
		this._imgContainer.insert(small_img);

		this._small_images.push(small_img);

		// move descr
		var descrWrapper = new Element('div', {
			'class':'descr_wrap'
		});
		descrWrapper.insert(el.down('h3'));
		descrWrapper.insert(el.down('p'));
		this._descrContainer.insert(descrWrapper.hide());
		this._descriptions.push(descrWrapper);

		// add Event to thumbnail
		var index = this._thumbnails.indexOf(el);

		el.down('a').observe('click', function(event){
			this.stopSlideshow();
			this.setActive(index);
		}.bind(this));

		// add Event to small image
		small_img.observe('click', function(event){
			Event.stop(event);
			this.stopSlideshow();
			this._layer.opener = Event.findElement(event, 'a');
			this._layer.open();
		}.bind(this));

		// add navi link
		if(this._navi){
			var navlink = new Element('a', {
				'href':'javascript:void(0)'
			}).update(index+1);


			this._navi.insert(
				new Element('li',{
				'class':(index==0?'first':'')
				}).insert(navlink)
			);
			this._navi_links.push(navlink);

			navlink.observe('click', function(event){
				this.stopSlideshow();
				this.setActive(index);
			}.bind(this));
		}
	},

	setActive:function(index){
		if(this._active !== index){
			this._active = index;

			// indicate active thumb
			this._thumbnails.invoke('removeClassName', 'active');
			this._thumbnails[index].addClassName('active');

			// indicate active navi link
			this._navi_links.invoke('removeClassName', 'active');
			if( this._navi_links[ index ] ) {
				this._navi_links[index].addClassName('active');
			}

			// show img and descr
			this._small_images.invoke('removeClassName', 'active');
			this._small_images[index].addClassName('active');
			this._descriptions.invoke('hide');
			this._descriptions[index].show();
		}
	},

	setPrevious:function(){
		this.setActive(this._active===0?this._thumbnails.length-1:this._active-1);
	},

	setNext:function(){
		this.setActive(this._active===this._thumbnails.length-1?0:this._active+1);
	},

	startSlideshow: function(){
		this._slideshowTimer = new PeriodicalExecuter(function(){
			this.setNext();
		}.bind(this), 3);
		this._playstop.update('Stop');
		this._slideshow = true;
	},

	stopSlideshow: function(){
		if(this._slideshowTimer !== null){
			this._slideshowTimer.stop();
			this._playstop.update('Play');
			this._slideshow = false;
		}
	}
});


/**
 * @class EnergyApps.Gallery.Layer
 * @namespace EnergyApps.Gallery
 * @extends Publicis.Lightbox
 * @constructor
 * @param {Object} config Configuration options
 * @author Jonas Bach
 * @author Sebastian Sauer
 */
EnergyApps.Gallery.Layer = function (config) {
	EnergyApps.Gallery.Layer.superclass.constructor.call(this, config);

	// make next/prev links work
	this.container = $(this.idContainer).down(' .contentlayer_2_content');

	var links = $$('#' + this.idContainer + ' a');

	if( config.manager._thumbnails && config.manager._thumbnails.length > 0 ) {
		links[0].addClassName('first').observe( 'click', function(){
			this.setPrevious();
		}.bind(this) );

		links[1].observe('click', function(){
			this.setNext();
		}.bind(this));
	} else {
		links[0].hide();
		links[1].hide();
	}

	this.webfeatureElement = false;

	this.activeElement = false;

	this.config.feature = {
		width : 989,
		height: 393
	};

	// apply content function on open
	this.addListener("open", function (){
		this._applyContent();
	}.bind(this));

	this.webFeatureActive = false;

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


	_applyContent: function() {
		if( this.opener.hasAttribute( "data-feature" ) ) {
			this._insertFeature();
			return;
		}
		this._insertElement()
	},
	_getWebFeatureElement : function() {
		if( ! this.webfeatureElement ) {
			var cfg = {
				href : this.opener.readAttribute( "data-feature" ),
				container : this.container
			};
			this.webfeatureElement = new EnergyApps.Webfeature.Element( cfg );

			this.webfeatureElement
				.on( "unload", function () {
					this.webFeatureActive = false;
				}, this );
		}
		return this.webfeatureElement;
	},
	_insertFeature : function() {

		this.node.setStyle({
			'width': this.config.feature.width + 'px',
			'height': this.config.feature.height + 20 + 'px'
		});

		this._getWebFeatureElement()
			.setBasePath( this.opener.readAttribute( "data-feature" ) )
			.load();

		this.webFeatureActive = true;
	},
	_insertElement : function() {

		this.activeFrameId = this.id + '-video';

		// delete former content in IE etc.
		if( $('#'+this.id+'-video') && Prototype.Browser.IE ){
			$('#'+this.id+'-video').remove();
		}

		var url = this.opener.readAttribute( 'href' ),
			// bug IE: can't use down to traverse dom :'(
			flashVideo = this.opener.select( '.flv' ),
			html5Videos = this.opener.select( '.html5' ),
			videoElement,
			videoProperties,
			flashParams,
			flashVars,
			activeFrame = new Element('div',{
				'id': this.id + '-video'
			});

		flashVideo = ( flashVideo.length > 0 )
			? $( flashVideo[ 0 ] )
			: undefined;

		if( html5Videos && html5Videos.length > 0 ) {
			html5Videos.each( function ( el, index) {
				el = $(el);
			} );
		}

		if( !! flashVideo ) {
			videoProperties = {
				width: parseInt( flashVideo.readAttribute( 'data-width' ), 10 ),
				height: parseInt( flashVideo.readAttribute( 'data-height' ), 10 )
			};

			// initialize flashvars / param
			flashParams = {
				allowFullscreen: 'true',
				wmode: 'transparent',
				scale: 'noscale',
				salign: 'TL'
			};

			flashVars = {
				path: this._getVideoUrl( flashVideo.readAttribute( 'data-src' ) ),
				width: videoProperties.width,
				height: videoProperties.height,
				autoPlay: 'true'
			};

			// resize layer
			this.node.setStyle({
				'width': videoProperties.width + 'px',
				'height': videoProperties.height + 20 + 'px'
			});

			// check for html5 fallback

			if( html5Videos && html5Videos && html5Videos.length && ! Info.browser.isIE ) {
				videoElement = new EnergyApps.Video.Element(
					this._getHtml5VideoConfig( html5Videos[ 0] )
				);
				activeFrame.update( videoElement.get().setStyle( { display: "block" } ) );
			}

			this.container.update( activeFrame );

			if( Publicis.hasFlash() ) {
				swfobject.embedSWF(
					"/apps/videoplayer/siemens/Standalone_3.0.3.swf",
					this.activeFrameId,
					videoProperties.width,
					videoProperties.height,
					"9.0.0",
					"",
					flashVars,
					flashParams
				);
			}
			return;
		} else if( ! flashVideo && html5Videos.length > 0 && ! Info.browser.isIE ) {
			videoProperties = this._getHtml5VideoConfig( html5Videos[ 0 ] );
			videoElement = new EnergyApps.Video.Element(
				videoProperties
			);
			activeFrame.update( videoElement.get().setStyle( { display: "block" } ) );

			// resize layer
			this.node.setStyle({
				'width': videoProperties.width + 'px',
				'height': videoProperties.height + 20 + 'px'
			});

			this.container.update( activeFrame );
			return;
		}

		// image
		var img = new Element('img', {
			alt: ' '
		});

		//add loading indicator
		this.container.addClassName('loading');

		// insert
		img.onload = function(){
			// set layer size
			setTimeout(function(){
				this.node.setStyle({
					'width': img.width + 'px',
					'height': img.height + 20 + 'px'
				});
				// remove loader
				this.container.removeClassName('loading').update(img);
			}.bind(this), 0);

		}.bind(this);
		img.writeAttribute({'src':url});

	},
	/**
	 * provides config for EnergyApps.Video.Element,
	 * iterates over all span nodes representing html5 videos
	 *
	 * @param {Element} video span
	 * @returns {PlainObject} | false
	 */
	_getHtml5VideoConfig : function ( el  ) {
		var videos = [ el ],
			config = {
				width: el.readAttribute( 'data-width' ),
				height: el.readAttribute( 'data-height' )
			};

		while( el.next( '.html5' ) ) {
			el = el.next( '.html5' );
			videos.push( el );
		}

		videos.each( function ( video ) {
			var type = Publicis.trim( video.readAttribute( 'data-type' ) );
			if( !! type ) {
				config[ type ] = video.readAttribute( 'data-src' );
			}
		} );

		return config;
	},

	setPrevious: function(){

		if( this.webFeatureActive ) {
			this._getWebFeatureElement().unload();
		}

		// get prev item and set it as opener
		var tmp = ( this.config.manager._active === 0 )
			? this.config.manager._thumbnails.length - 1
			: this.config.manager._active-1;
		this.opener = this.config.manager._small_images[tmp];

		//now switch content
		this._applyContent();

		// also setPrevious in gallery
		this.config.manager.setPrevious();
	},

	setNext: function(){

		if( this.webFeatureActive ) {
			this._getWebFeatureElement().unload();
		}
		// get next item and set it as opener
		var tmp = this.config.manager._active===this.config.manager._thumbnails.length-1?0:this.config.manager._active+1;
		this.opener = this.config.manager._small_images[tmp];

		//now switch content
		this._applyContent();

		// also setNext in gallery
		this.config.manager.setNext();
	},
	/**
	 * grabs the video source given from openengine and
	 * builds absolute web path for siemens web player
	 * @private
	 * @return string
	 * @see EnergyApps.Video.Manager
	 */
	_getVideoUrl : EnergyApps.Video.Manager.prototype._getVideoUrl
});

