/*
	HHT-Lightbox v0.1 - All in one lightbox
	by Martun Ficzel

	Inspired by  Thomas Hempel (http://www.typo3-unleashed.net)
	Inspired by Slimbox by Christophe Beyls
*/
var hhtLightbox = new Class({
 	
	init: function() {
		
		this.lightboxMode = '';
		this.options = {
			enable_debug : false,
			resizeDuration: 200,
			resizeTransition: false,	// default transition
			initialWidth: 250,
			initialHeight: 250,
			minWidth: 150,
			minHeight: 150,
			maxWidth: 900,
			maxHeight: 600,
			animateCaption: true,
			showCounter: true,
			closed: true
		};

		this.lbElements = new Object;

		this.eventKeyDown  = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);
		
		// create markup for Lightbox
		/*	
			<div id="lbOverlay"></div>
			<div id="lbCenter">
				<div id="lbControl">
					<div id="lbPages"><a href="###">1</a>...</div>
					<div id="lbClose"><a><img/></a></div>
				</div>
				<div id="lbCanvas">
					<div>
						<a id="lbPrevLink"></a>
						<a id="lbNextLink"></a>
						<!-- img or iframe element is inserted here -->
					</div>
				</div>
			</div>
		*/
  		
			// lightbox background
		this.overlay = new Element('div').setProperty('id', 'lbOverlay').injectInside(document.body);
		this.overlay.onclick = this.close.bind(this);
		
			// lightbox center 
		this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({
			width: this.options.initialWidth+'px',
			height: this.options.initialHeight+'px',
			display: 'none',
			left:'50%',
			marginLeft: (this.options.initialWidth/-2) -42
		}).injectInside(document.body);
		
			// create lightbox control
		this.lightboxControl = new Element('div').setProperty('id','lbControl').setStyles({
			overflow:'hidden',
			height:"35px",
			marginTop:'0px'
		});

		this.lightboxPages   = new Element('div').setProperty('id','lbPages');
		this.lightboxPages.setStyles({marginRight:"80px"});
		this.lightboxPages.injectInside(this.lightboxControl);
		
			// ;
		var className = "lbClose"; 
		var lang  = $$('HTML').getProperty('lang'); 
		if (lang == 'de-DE'){
			className += ' lbClose_de'; 
		}
		if (lang == 'en-UK'){
			className += ' lbClose_en'; 
		}
		
		this.lightboxClose   = new Element('div').addClass(className).injectInside(this.lightboxControl);
		this.lightboxControl.injectInside(this.center);
		this.lightboxClose.onclick = this.close.bind(this);
		
			// lightbox canvas
		this.canvasContainer = new Element('div').setProperty('id', 'lbCanvas');
		this.canvas = new Element('div').injectInside(this.canvasContainer);
		this.canvasContainer.injectInside(this.center);
		
			// create bottom Element for prev and next links
		this.prevLink = new Element('a').setProperties({'id': 'lbPrevLink'}).setStyle('display', 'none').injectInside(this.canvasContainer);
		this.nextLink = this.prevLink.clone().setProperties({id: 'lbNextLink'}).injectInside(this.canvasContainer);

		if (lang == 'de-DE'){
			this.prevLink.setProperties({'title' : 'zurück'});
			this.nextLink.setProperties({'title' : 'vor'});
		}
		if (lang == 'en-UK'){
			this.prevLink.setProperties({'title' : 'previous'});
			this.nextLink.setProperties({'title' : 'next'});
		}

		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);
	
			// create Ajax container 
		this.lbAjaxContainer = new Element('div').setProperty('id', 'lbAjaxContainer').injectInside(document.body);
		this.lbAjaxContainer.setStyles({
			display:'none',
			position:'absolute',
			visibility:'hidden',
			width:'586px',
			height:'auto'
		});
		this.lbElements['lbAjaxContainer'] = this.lbAjaxContainer;
		
			// Build effects
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 150}).hide(),
			resize: this.center.effects({duration: 300, onComplete: nextEffect}),
			fade: this.canvas.effect('opacity', {duration: 300, onComplete: nextEffect}),
			control: this.lightboxControl.effects({duration: 150})
		};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
	
	},

	keyboardListener: function(event)	{
	
		switch (event.keyCode)	{
			case 27: case 88: case 67: this.close(); break;
			case 37: case 80: this.previous(); break;	
			case 39: case 78: this.next();
		}
	
	},

	openDomObjectLightbox:function(dom_object){

		window.fireEvent( 'hht-track' , [ 'lightbox_open', 'lbAjaxContainer', '' ] );
		
		dom_object.injectInside(this.lbElements['lbAjaxContainer']);
		this.openLightBox('lbAjaxContainer', null, '', false);
		this.changeContent('lbAjaxContainer');
		
	},

	openHtmlLightbox:function(html){
		window.fireEvent( 'hht-track' , [ 'lightbox_open', 'lbAjaxContainer', '' ] );

		this.lbElements['lbAjaxContainer'].innerHTML = html;
		this.openLightBox('lbAjaxContainer', null, '', false);
		this.changeContent('lbAjaxContainer');
	},

	openAjaxLightbox:function(url, width){
		
		window.fireEvent( 'hht-track' , [ 'lightbox_open', 'lbAjaxContainer', '' ] );

		if(width) {
			this.wishedLightboxWidth = width;
		}

		//this.lbElements['lbAjaxContainer'].innerHTML = '';
		this.canvas.empty();
		
			// open lightbox with wait
		this.openLightBox('lbAjaxContainer', null, '', false);
		
			// send ajax request 
		var ajax = new Ajax( url, {
			method: 'get',
			update: this.canvas,
			evalScripts: true,
			onComplete: function(){
					// onload show content
				// this.loadContent(this.lbAjaxContainer);
				this.changeContent(this.canvas);
				// 
				// empty ajax container
				// this.lbAjaxContainer.empty();
			}.bind(this)
		}).request();
	}, 
	
	openImageGallery:function( event ){

		event = new Event(event);
		event.stop();

		var target = new Element( event.target );
		var lightbox_id = target.getProperty ( 'name' );
		
		while ( ( target.getProperty( 'name' ) == '' || target.getProperty( 'name' ) == undefined ) && target.getParent() ){
			target = target.getParent();
			lightbox_id = target.getProperty ( 'name' );
		}

		if ( lightbox_id ) {
			if ( !this.lbElements[lightbox_id] ) {
				this.lbElements[lightbox_id] = new Array();
				other_items = $$( '.enable-lightbox[name=' + lightbox_id + ']' );
				other_items.each( function(el, index) {

					var item = new Element('a',{
						itemMode : 'image',
						href: el.getProperty ( 'href' ),
						name: el.getProperty ( 'name' ),
						title: el.getProperty ( 'title' ),
						caption: el.getProperty ( 'hht:caption' ),
						copyright: el.getProperty ( 'hht:copyright' ),
						copyrightUrl: el.getProperty ( 'hht:copyrightUrl' )
					});
					this.lbElements[lightbox_id].push(item);

					
				}, this);
			}
			window.fireEvent( 'hht-track' , [ 'gallery_start', lightbox_id, '' ] );
			this.openLightBox( lightbox_id, 0, '', true);
		}
		
	},

	openATagLightBox:function(e){

		e      = new Event(e);
		target = new Element(e.target);
		
		while(!target.hasClass('enable-lightbox') && target.getParent()){
			target = target.getParent();
		}		

		e.stop();		
		if ( target.hasClass('enable-lightbox') ){
			this.openLightBox(target.name, 0, '', true);
		}
	
	},
	
	openLightBox: function(elIdName, elIndex, message, loadContent)	{
	
		
		if(window.ie6){
			$$('select').addClass('th_lightbox_hide');
		}
		
		this.position();
		this.setup(false);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
	
		this.center.className = 'lbLoading';
		
		var width = this.options.initialWidth;
		var height = this.options.initialHeight;
		
		if (message)	{
			this.center.setStyle("width" , "400px");
			this.canvas.innerHTML = message;
			var canvas_size = this.canvas.getSize();
		} else {
			if ( this.center.getStyle('display') == 'block' ) {
				var width  = this.center.getStyle('width');
				var height = this.center.getStyle('height');
			} else {
				this.canvas.innerHTML = '';
			}
		}
		
		this.prevLink.setStyle('display','none');
		this.nextLink.setStyle('display','none');
		this.center.setStyle('height', height );
		this.center.setStyle('width' , width );
		
		this.lightboxPages.setText(''); 
		
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.5);
		
		this.options.closed = false;
		
		if (loadContent)	{
			if (elIndex != null)	{
				this.changeContent(elIdName, elIndex);
			} else {
				this.loadContent($(elIdName));
			}
		} else {
			
		}
		
		return false;
	
	},

	
	position: function()	{
	
		var bodySize = $(document.body).getSize();
		var width  = (bodySize.size.x > window.getWidth()  ) ? bodySize.size.x : window.getWidth();
		var height = (bodySize.size.y > window.getHeight() ) ? bodySize.size.y : window.getHeight();
		
		this.overlay.setStyles({
			'position':'absolute',
			'top'   : 0, 
			'left'  : 0,
			'width' : width,
			'height': height
		});
	
	},

	previous: function(e)	{

		window.fireEvent( 'hht-track' , [ 'gallery_prev', this.groupName, '' ] );

		var el = this.lbElements[this.groupName];
		this.groupIndex = (this.groupIndex - 1 + el.length ) % el.length;

		this.changeContent(this.groupName, this.groupIndex);
	
	},

	next: function(e)	{

		window.fireEvent( 'hht-track' , [ 'gallery_next', this.groupName, '' ] );
		
		var el = this.lbElements[this.groupName];
		this.groupIndex = (this.groupIndex + 1 + el.length ) % el.length;
		this.changeContent(this.groupName, this.groupIndex);
		
	},

	setup: function(open)	{
		
		var elements = $$('object');
		if (open){
			/*
			elements.each(function(el){
				el.setProperty( 'lbBackupStyle' , el.getStyle('visibility') );
				el.setStyle('visibility','hidden');
			});
			*/
			window.addEvent('scroll', this.eventPosition);
			window.addEvent('resize', this.eventPosition);
			document.addEvent('keydown', this.eventKeyDown);
		
		} else {
			/*
			elements.each(function(el){
				if (el.getProperty( 'lbBackupStyle')) {
					el.setStyle('visibility',  el.getProperty( 'lbBackupStyle'));
				}
			});
			*/
			window.removeEvent('scroll', this.eventPosition);
			window.removeEvent('resize', this.eventPosition);
			document.removeEvent('keydown', this.eventKeyDown);
		}
		
		this.step = 0;
		
	},

	changeContent: function(elIdName, elIndex, elTitle )	{

		// console.log(["changeContent", elIdName, elIndex ]);
		
		this.groupName = elIdName;
		
			// hide old content and display loading screen
		this.center.className = 'lbLoading';
		this.nextLink.style.display = this.prevLink.style.display = 'none';
		this.lightboxPages.setText('');
		
		// add title
		if (elTitle){	
			new Element('span').setHTML( elTitle ).injectInside(this.lightboxPages);
		}

		var el = this.lbElements[elIdName];
		if ( el ) {
			
		} else {
			var new_item = $(elIdName);
			if ( new_item ){		
				this.lbElements[elIdName] = new_item;
				el = new_item;
			}
		}
		
		
		if (elIndex != null)	{
			var elCount = this.lbElements[elIdName].length;
			
			if (elIndex < 0)	{
				elIndex = 0;
			}
	
			if (elIndex > (elCount -1))	{
				elIndex = elCount -1;
			}
				
				// add numbers for lightbox and current page
			if (elCount>1){
				
				var pagination =  new Element('div').setProperty('class', 'page').setStyle('text-align','center').injectInside(this.lightboxPages);
				var next = elIndex+1 ;
				var prev = elIndex-1 ; 
				
				if (prev < 0) prev = elCount-1;
				if (next > ( elCount - 1 ) ) next = 0;
					
					// prev link
				var page = new Element('span').setProperty('class', 'page').injectInside(pagination);
				var prev_link = new Element('a').setProperties({'href':'javascript:void(0);' }).setHTML( "&nbsp;&lt;&nbsp;" ).injectInside(page);
				prev_link.removeEvent('click');
				prev_link.addEvent('click',  this.changeContent.pass( [elIdName, prev ], this ) );
				// prev_link.onclick = this.changeContent.pass( , this);
				
					// image links
				for (var i = 0; i < elCount; i++)	{
					if (i == elIndex)	{
						new Element('span').setProperty('class', 'selectedPage').setText(i+1 ).injectInside(pagination);
					} else {
						var page = new Element('span').setProperty('class', 'page').injectInside(pagination);
						var link = new Element('a').setProperties({'href':'javascript:void(0);' }).setText(i+1 ).injectInside(page);
						link.removeEvent('click');
						link.addEvent('click',  this.changeContent.pass( [elIdName, i ], this ) );
						// link.onclick = this.changeContent.pass( [elIdName, i ], this);
					}
				}
				
					// next link
				var page = new Element('span').setProperty('class', 'page').injectInside(pagination);
				var next_link = new Element('a').setProperties({'href':'javascript:void(0);' }).setHTML( "&nbsp;&gt;&nbsp;" ).injectInside(page);
				next_link.removeEvent('click');
				next_link.addEvent('click',  this.changeContent.pass( [elIdName, next ], this ) );
				// next_link.onclick = this.changeContent.pass( [elIdName, next ], this);
				
					// newline
				var br = new Element('br').injectInside(pagination);
				
			}
			
				// add title and copyright notice
			var title   = this.lbElements[elIdName][elIndex].getProperty('title');
			new Element('div').setProperty('class', 'lb_title').setText( '  ' + title ).injectInside(this.lightboxPages);
			
			this.groupIndex = elIndex;
			if (elIndex > 0)	{
				this.prevLink.style.display = 'block';
			}

			if (elIndex < (this.lbElements[elIdName].length -1))	{
				this.nextLink.style.display = 'block';
			}
			
			el = el[elIndex];
		} 

		this.loadContent(el);
		return false;
	
	},

	loadContent: function( el ) {
	
		// console.log( ['loadContent', el, el.getTag() ]);

		this.effectStep   = 1;
		this.lightboxMode = '';
		
		if (el.getTag() == 'a' )	{

			this.preloadInfo  = {
				caption       : el.getProperty('caption'),
				copyright     : el.getProperty('copyright'),
				copyrightUrl  : el.getProperty('copyrightUrl')
			};

			this.lightboxMode = 'image';
			this.preload = $( new Image() );
			this.preload.onload = this.nextEffect.bind(this);
			this.preload.src    = el.href;
			this.preload.title  = el.title;
			

			
		} else {

			this.lightboxMode = 'html';
			this.preload = $( new Element('div') );
			this.preloadInfo  = { 
				caption       : '',
				copyright     : '',
				copyrightUrl  : ''
			};
			
			this.preload.innerHTML = el.innerHTML;
			this.preload.title = el.title;
			var elSize = el.getSize();
			this.preload.width  = (elSize.size.x) ? elSize.size.x : parseInt(el.style.width);
			this.preload.height = (elSize.size.y) ? elSize.size.y : parseInt(el.style.height);
			this.nextEffect(); //asynchronous loading
			
		}
	
	},

	nextEffect: function()	{
		
		// console.log( 'nextEffect' );

		switch (this.effectStep)	{
			case 1:

					// empty lightbox
				this.canvas.setHTML('');
				this.fx.fade.set(0);
			
					// load the content into the lightbox 
				switch ( this.lightboxMode ){
					case 'image':

						this.image = new Element('img').setProperties( {
							'src'   : this.preload.src,
							'title' : this.preload.title
						} ).injectInside(this.canvas);
						
						this.canvas.setProperty('foo','bar');
						
						this.image.onclick = this.next.bind(this);

							// copyright
						var copyright;
						if ( this.preloadInfo.copyright ) {
							copyright = new Element('div').setProperty('class', 'lb_copyright').injectInside(this.canvas);
							if ( this.preloadInfo.copyrightUrl ){
								new Element('a')
									.setProperty( 'href', this.preloadInfo.copyrightUrl )
									.setProperty( 'title', 'copyright: ' + this.preloadInfo.copyright )
									.setText( '© '+ this.preloadInfo.copyright )
									.injectInside(copyright);
							} else {
								new Element('span').setText( '© ' + this.preloadInfo.copyright ).injectInside(copyright);
							}
							
						} else {
							copyright = new Element('div').setProperty('class', 'lb_copyright').setText( '' ).injectInside(this.canvas);
						}
						
							// caption
						var caption;
						if ( this.preloadInfo.caption ) {
							caption = new Element('div').setProperty('class', 'lb_footer').setText( '  ' + this.preloadInfo.caption ).injectInside(this.canvas);
						} else {
							caption = new Element('div').setProperty('class', 'lb_footer').setText( '' ).injectInside(this.canvas);
						}
						
						var size = this.image.getSize().size;
						this.canvas.setProperty('class', 'lightbox-image');
						this.canvas.setStyles({
							width:  "" + size.x + "px"
						});

						var footer_height = copyright.getSize().size.y + caption.getSize().size.y + 20;
						if (footer_height < 60) footer_height = 60;

						this.canvas.setStyles({ 
							height: "" + (size.y + footer_height) + "px"
						});

						break;
					case 'html':
					default:						
						this.canvas.setHTML(this.preload.innerHTML); 
						this.canvas.setProperty('class', 'lightbox-content');
						this.canvas.setStyles({
							width:"568px",
							height:"auto"
						});
						if(this.wishedLightboxWidth) {
							this.canvas.setStyle('width',this.wishedLightboxWidth);
						}

						videoContent = this.canvas.getElement('div.hht_videoplayer_content');
						if(videoContent) {
							flashPlayer = videoContent.getProperty('hht:flashplayer');
							flashVars = videoContent.getProperty('hht:flashvars');
							flashVarsJs = videoContent.getProperty('hht:flashvars_js');
							videoContentId = videoContent.getProperty('id');

							if(flashPlayer && flashVars && flashVarsJs && videoContentId) {
								swfobject.embedSWF ( 
									flashPlayer + '?' + flashVars,
									videoContentId, 
									548, 
									327, 
									'9.0.124', 
									'', 
									flashVarsJs ,
									{allowfullscreen:'true' , allowscriptaccess:"always"}
								 );
							}
						}

						break;
				}

					// get target Size	
				var canvasSize = this.canvas.getSize();
			
					// set height of control area min 30px
				
				this.theWidth = canvasSize.size.x;
				if (this.theWidth < this.options.minWidth)	{
					this.theWidth = this.options.minWidth;
				}
		
				if (this.theWidth > this.options.maxWidth)	{
					this.theWidth = this.options.maxWidth;
				}

				this.theHeight = canvasSize.size.y;
				if (this.theHeight < this.options.minHeight) {
					this.theHeight = this.options.minHeight;
				}
				
					// resize
				this.effectStep++;
				this.fx.resize.start({
					width:   '' + ( this.theWidth  + 18 )  + 'px', 
					height:  '' + ( this.theHeight + 48 ) + 'px',
					marginLeft: ""+ ( (this.theWidth)/(-2) -42 )+"px"
				});
				break;
				
			case 2:
					// fade in
				this.effectStep++;	
				this.fx.fade.start(1);
				break;
				
			case 3:
					// remove waiting image
				this.center.className = '';
				this.center.setStyle('height','auto');
				if ( this.lightboxMode != 'image'){ 
					this.canvas.setStyle('height','auto');
				}
				break;
		}

		return false;
	
	},

	close: function() {
		
		// if (this.step < 0) return;
		// this.step = -1;
		
		//this.groupIndex = (this.groupIndex - 1 + el.length ) % el.length;

		
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		
		if(window.ie6){
			$$('select').removeClass('th_lightbox_hide');
		}
		
		for (var f in this.fx) this.fx[f].stop();
		this.center.setStyles({
			width:  this.options.initialWidth+'px', 
			height: this.options.initialHeight+'px',
			display: 'none',
			left:'50%',
			marginLeft: ( (this.options.initialWidth/-2)-42 )
		});
		
		// stop flash playback
		var o = $E('object' ,this.canvas);
		if (o && o.sendEvent){
			o.sendEvent( 'stop' ); 
		}
		
		var e = $E('embed' ,this.canvas);
		if (e && e.sendEvent) {
			e.sendEvent( 'stop' );
		}
		
		// empty canvas
		if (this.canvas){
			this.canvas.empty();
		}
		
		// this.canvas.setStyles
		this.fx.overlay.chain( this.setup.pass(false, this) ).start(0);
		this.options.closed = true;
		
		
		return false;
	}
});


window.addEvent('domready', function()	{		
	HHT_Lightbox = new hhtLightbox();
	HHT_Lightbox.init();
});


