/*
	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;

		/*
		$$('.enable-lightbox').each(function(el, index)	{
				// check if we have links because they can be grouped
		
			if (el.tagName == 'A')	{
				if (!$defined(this.lbElements[el.name]))	{
					this.lbElements[el.name] = new Array;
				}
				this.lbElements[el.name].push(el);
				//el.onclick = this.openLightBox.pass([el.name, (this.lbElements[el.name].length -1)], this);
				el.addEvent('click',function(e){
					this.openATagLightBox(e);
				});
			} else {
				this.lbElements[el.id] = el;
				el.onclick = this.openLightBox.pass(el.id, this);
				el.setStyle('display', 'none');
			}
		}, this);
		*/

	   
		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:'block',
			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){

		window.fireEvent( 'hht-track' , [ 'lightbox_open', 'lbAjaxContainer', '' ] );

		this.lbElements['lbAjaxContainer'].innerHTML = '';
		
			// open lightbox with wait
		this.openLightBox('lbAjaxContainer', null, '', false);
		
			// send ajax request 
		var ajax = new Ajax( url, {
			method: 'get',
			update: $('lbAjaxContainer'),
			evalScripts: true,
			onComplete: function(){
					// onload show content
				this.changeContent('lbAjaxContainer');
			}.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 lightbox_id = el.getProperty ( 'name' ) ;
					this.lbElements[lightbox_id].push(el);
				}, 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';
		
		if (message)	{
			this.center.setStyle("width" , "400px");
			this.canvas.innerHTML = message;
			var canvas_size = this.canvas.getSize();
		} else {
			this.canvas.innerHTML = '';
		}
		
		this.prevLink.setStyle('display','none');
		this.nextLink.setStyle('display','none');
		this.center.setStyle('height', this.options.initialHeight);
		this.center.setStyle('width' , this.options.initialWidth);
		
		this.nextLink.style.display = this.prevLink.style.display = 'none';
		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, '' ] );
		
		e = new Event(e).stop();
		this.groupIndex--;
		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 %= 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(e){
				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.debug(["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);
		}

		if ( el = this.lbElements[elIdName] ) {
			// element found
		} else {
			var new_item = $(elIdName);
			if ( new_item ){
				this.lbElements[elIdName] = new_item;
				el = new_item;
			}
		}
		
		
		if (elIndex != null)	{
			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.onclick = this.changeContent.pass( [elIdName, prev ], 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.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.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.debug(['loadContent', el]);
			
		this.effectStep = 1;
		this.lightboxMode = '';
		
		if (el.tagName == 'A')	{
			this.lightboxMode = 'image';
			this.preload = new Image();
			this.preload.onload = this.nextEffect.bind(this);
			this.preload.src   = el.href;
			this.preload.title = el.title;

			var caption = el.getProperty('hht:caption');
			var caption_parts = caption.split('|');

			this.preload.caption = '';
			this.preload.copyright = '';
			
			if ( caption && caption_parts ){
				if ( caption_parts[0] ) this.preload.caption   = caption_parts[0];
				if ( caption_parts[1] ) this.preload.copyright = caption_parts[1];
			}
				
		} else {
			this.lightboxMode = 'html';
			this.preload = new Object ();
			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.preload.innerHTML = el.innerHTML;
			this.preload.title = el.title;
			this.nextEffect(); //asynchronous loading
			
		}
	
	},

	nextEffect: function()	{
	
		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.image.onclick = this.next.bind(this);

							// copyright
						if ( this.preload.copyright ) {
							var copyright = new Element('div').setProperty('class', 'lb_copyright').setText( '  ' + this.preload.copyright ).injectInside(this.canvas);
						} else {
							var copyright = new Element('div').setProperty('class', 'lb_copyright').injectInside(this.canvas);
						}
							// caption
						if ( this.preload.caption ) {
							var caption = new Element('div').setProperty('class', 'lb_footer').setText( '  ' + this.preload.caption ).injectInside(this.canvas);
						} else {
							var caption = new Element('div').setProperty('class', 'lb_footer').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 = 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"
						});
						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 = '';
				break;
		}

		return false;
	
	},

	close: function() {
		// if (this.step < 0) return;
		// this.step = -1;
		
		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 )
		});
	
		// 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();
});

