var LightBox = new Class({
	
	options: {
		duration: 1000,
		ParentDisplay: 'displayGallery',
		column: 0,
		ArrowLeft: 'arrowLeft',
		ArrowRight: 'arrowRight',
		ParentDisplay: 'displayGallery',
		currentPage: 1,
		totalPage: null,
		currentItem: 0,
		totalItem: null,
		div: 8,
		imageWidth: 91,
		OverLay: 200,
		thumbsize:80,
		quality: 80,
		square:1,
		wait: false
	},

	initialize: function(element, options){
		this.setOptions(options);
		if( $(element) ){
			this.elements = $(element);	
			this.options.column = Math.ceil($$('#' + element + ' li').length / this.options.div);
			this.image = new Array();
			this.build(this.elements);
		}
	},
	
	build: function(el){
		var list = $$('#' + this.elements.getProperty('id') + ' li a');
		list.each(function(element){
			this.image.push(new Array( element.getProperty('rel'), element.getProperty('title') ) );
		}.bind(this));
		this.options.totalItem = this.image.length;
		this.options.totalPage = Math.ceil(this.image.length / this.options.div);
		
		this.overlay = new Element('div', { 'id': 'overlay',
			'styles': {
				'width': window.getScrollWidth().toInt(),
				'height': window.getScrollHeight().toInt(),
				'opacity': 0
			}
		}).inject(document.body);
		
		this.imgContainer = new Element('div', { 'id': 'imgContainer',
			'styles': {
				'display': 'none',
				'top': (window.getScrollHeight().toInt() - 480) / 2,
				'left': (window.getScrollWidth().toInt() - 480) / 2
			}
		}).inject(document.body);
		
		this.img = new Element('img', {'id': 'DImg', 'styles': { 'opacity': 0 } }).inject(this.imgContainer);
		
		this.hoverNav = new Element('div', {'id': 'hoverNav', 'styles':{'display':'none'} }).inject(this.imgContainer);
		this.previous = new Element('a', { 'id': 'prevLink' }).inject(this.hoverNav);
		this.next = new Element('a', { 'id': 'nextLink' }).inject(this.hoverNav);
		var progress = new Element('div', { 'id': 'progress',
			'styles': {
				'left': (window.getWidth().toInt() - 400) / 2,
				'top': this.imgContainer.getStyle('top').toInt()
			}
		}).inject(document.body);
		var bar = new Element('div', { 'class': 'bar' }).inject(progress);
		
		this.BxGallery = new Element('div', { 'id': 'BxGallery', 'styles': { 'opacity': 0 } }).inject(document.body);
		this.page = new Element('ul', { 'id': 'pageLink' }).inject(this.BxGallery);
		this.arrowLeft = new Element('div', { 'id': 'arrowLeft' }).inject(this.BxGallery).addEvent('click', function(){ this.moveLeft(); }.bind(this));
		this.displayGallery = new Element('div', { 'id': 'displayGallery'}).inject(this.BxGallery);
		this.GalleryList = new Element('ul', { 'id': 'GalleryList' }).inject(this.displayGallery);
		this.arrowRight = new Element('div', { 'id': 'arrowRight' }).inject(this.BxGallery).addEvent('click', function(){ this.moveRight(); }.bind(this));
		
		this.attach();
	},
	
	attach: function(){		
		this.arrowLeft.addEvents({
			'mouseenter': function(){ this.setStyle('background-color', '#333333'); },
			'mouseleave': function(){ this.setStyle('background-color', '#222222'); }
		});
		
		this.arrowRight.addEvents({
			'mouseenter': function(){ this.setStyle('background-color', '#333333'); },
			'mouseleave': function(){ this.setStyle('background-color', '#222222'); }
		});
		
		$$('#' + this.elements.getProperty('id') + ' li a').each(function(element){
			element.addEvent('click', function(){ this.LightboxStart( element.getProperty('rel') ); }.bind(this));
		}.bind(this));
		
		this.createList();
	},
	
	detach: function(){
		$$('#' + this.elements.getProperty('id') + ' li a').each(function(element){ element.removeEvents(); }.bind(this));
	},
	
	updateAttach: function(){
		$$('#' + this.elements.getProperty('id') + ' li a').each(function(element){
			element.addEvent('click', function(){ this.setDisplay( element.getProperty('rel') ); }.bind(this));
		}.bind(this));
	},
	
	LightboxStart: function(current){
		this.overlay.removeEvents();
		var image2 = new Array();
		$$('#' + this.elements.getProperty('id') + ' li a').each(function(element){
			image2.push(element.getProperty('rel'));
		});
		var fx = this.overlay.effects({duration: this.options.OverLayduration, transition: Fx.Transitions.Quart.easeInOut});
		fx.start({ 'opacity': .75 }).chain(function(){
		this.img.setStyle('opacity', 0);
		this.imgContainer.setStyle('display', '');
		
		var busy = false, loadedImages = [];
		var bar = $E('#progress .bar'), progress = $('progress'); 
		if (!busy) {
			busy = true;
			progress.setStyles({
				'visibility': 'visible',
					'left': (window.getScrollWidth().toInt() - progress.getCoordinates().width) / 2,
					'top': (window.getScrollHeight().toInt() - progress.getStyle('height').toInt()) / 2
			});
			new Asset.images(image2, {
				onProgress: function(i) {
					loadedImages[i] = this;
					var percent = 0;
					percent = ((i + 1) * progress.getStyle('width').toInt()) / image2.length;
					bar.setStyle('width', percent).setHTML(i + ' / ' + image2.length);
				},
				onComplete: function(){
					progress.setStyle('visibility', 'hidden');
					busy = false;
					this.detach();
					this.updateAttach();
					this.createPageLink();
						// this.createList();
					this.setDisplay(current);
				}.bind(this)
			});
		}
		}.bind(this));
	},
	
	setDisplay: function(current){
		this.overlay.removeEvents();
		var fx = this.overlay.effects({duration: this.options.OverLayduration, transition: Fx.Transitions.Quart.easeInOut});
		fx.start({ 'opacity': .75 }).chain(function(){
		this.img.setStyle('opacity', 0);
		this.imgContainer.setStyle('display', '');
			this.SlidePosition();
		}.bind(this));
		
		var imageNum = 0;		
		while( this.image[imageNum][0] != current ) {
			imageNum++;
		}
		this.img.setStyle('opacity', 0);

		var im = new Image();
		var im = new Image();
		im.src = this.image[imageNum][0];
		this.img.setProperty('src', this.image[imageNum][0]);
		
		var imCon = this.imgContainer.effects({duration: 400, transition: Fx.Transitions.Quart.easeInOut});
		var left = (window.getWidth().toInt() - im.width) / 2;
		
		imCon.start(1).chain(function(){
			imCon.start({
				'width': im.width,
				'height':im.height,
				'top': this.BxGallery.getCoordinates().bottom + 10,
				'left': (left < 0)?10:left
			});
		}.bind(this)).chain(function(){
			var imgfx = this.img.effects({duration: 500, transition: Fx.Transitions.Quart.easeOut});
			imgfx.start({ 'opacity': 0 }).chain(function(){ imgfx.start({ 'opacity': 1 }); });
			this.moveToCurrent(current);
		}.bind(this));
		
		//this.overlay.setStyles({ 'height' : window.getScrollHeight(), 'width' : window.getScrollWidth()});
		
		this.setItem(current);
		this.updateNav();
		
	},
	
	end: function(e){
		var bxfx = this.BxGallery.effects({duration: this.options.OverLayduration, transition: Fx.Transitions.Quart.easeOut});
		bxfx.start({
			'opacity': 0,
			'top': -1000
		}).chain(function(){ 
			this.imgContainer.setStyles({ 'display': 'none' })
		}.bind(this));
			
		var fx = this.overlay.effects({duration: this.options.duration, transition: Fx.Transitions.Quart.easeInOut});
		fx.start({ 'opacity': 0 });
		//e = new Event(e).stop();
	},
	
	/* Slide management */
	
	createList: function(){
		var list = $$('#' + this.elements.getProperty('id') + ' li');
		this.GalleryList.setStyle('width', list.length * this.options.imageWidth);
		list.each(function(el){
			var li = el.clone().inject(this.GalleryList);
		}.bind(this));
		
		var list = $$('#GalleryList li a');
		list.each(function(el){
			el.removeEvents() 
			el.addEvent('click', function(){ this.setDisplay(el.getProperty('rel')); }.bind(this));
		}.bind(this));
		
		var list = $$('#GalleryList li a img');
		list.each(function(element){
			var img_src = element.getProperty('src').split('/');
			element.setProperty('src', 'libraries/mod_gallery/genImage.inc.php?Folder='+$('folder').getProperty('value')+'&F='+img_src[img_src.length-1]+'&M='+this.options.thumbsize+'&QT='+this.options.quality+'&SQ='+this.options.square+'&C=0');
		}.bind(this));
	},
	
	SlidePosition: function(){
		var bxfx = this.BxGallery.effects({duration: 500, transition: Fx.Transitions.Quart.easeOut});
		bxfx.start({
			'left': ( window.getWidth() - this.BxGallery.getCoordinates().width ) / 2,
			'top' : window.getScrollTop()// + 10
		}).chain(function(){
			bxfx.start({ 'opacity': 1 }).chain(function(){
				this.overlay.addEvent('click', function(){ this.end(); }.bind(this));
			}.bind(this));
		}.bind(this));
	},
	
	createPageLink: function(){
		var len = Math.ceil(this.image.length / this.options.div); 
		
		for(var x=1,i=0; i<len; i++,x++){
			var li = new Element('li', {
				'styles': {
					'float': 'left',
					'margin-left': 10,
					'color': '#888888',
					'cursor': 'pointer'
				}
			}).inject(this.page).setHTML(x);	
		}
		
		$$('#'+this.page.getProperty('id') + ' li').each(function(el){
			el.addEvent('click', function(){
				this.jumpToPage(el.getText().toInt());
			}.bind(this))														  
		}.bind(this));
		
		this.page.setStyles({
			'left': (this.BxGallery.getStyle('width').toInt() - this.page.getStyle('width').toInt()) / 2,
			'top': 10
		});
	},
	
	moveLeft: function(){
		var previous = this.options.currentPage - 1;
		this.scollToPage(previous, 1);
		//this.jumpToPage(previous);
	},
	
	moveRight: function(){
		var next = this.options.currentPage + 1;
		this.scollToPage(next, -1);
		//this.jumpToPage(next);
	},
	
	moveToCurrent: function(current){
		var imageNum = 0;		
		while( this.image[imageNum][0] != current ) {
			imageNum++;
		}
		current = Math.ceil( (imageNum + 1) / this.options.div );
		this.jumpToPage(current);
	},
	
	scollToPage: function(toPageNumber, direction){
		var fx = this.GalleryList.effects({duration: this.options.duration, transition: Fx.Transitions.Quart.easeInOut});
		var left = this.GalleryList.getStyle('left').toInt();
		if(this.options.currentPage != toPageNumber){
			if(!direction) var direction = this.options.currentPage-toPageNumber;
			/*move right*/
			if( toPageNumber > this.options.currentPage  && toPageNumber < this.options.totalPage - direction ){
				this.options.currentPage = toPageNumber;
				fx.start({ 'left' : left - (this.options.imageWidth * this.options.div) });
			}
			
			/*move left*/
			if( toPageNumber < this.options.currentPage && toPageNumber >= direction){
				this.options.currentPage = toPageNumber;
				fx.start({ 'left' : left + (this.options.imageWidth * this.options.div) });
			}
		}
		this.setPage();
	},
	
	jumpToPage: function(toPageNumber){
		var fx = this.GalleryList.effects({duration: this.options.duration, transition: Fx.Transitions.Quart.easeInOut});
		var left = this.GalleryList.getStyle('left').toInt();
		var page = toPageNumber - this.options.currentPage;	
		if(page){
			this.options.currentPage = toPageNumber;
			fx.start({ 'left' : left - (this.options.imageWidth * this.options.div) * page });
		}
		this.setPage();
	},
	
	setPage: function(){
		$$('#'+this.page.getProperty('id') + ' li').each(function(el){
			if(el.getText().toInt() == this.options.currentPage) el.setStyle('color', '#FF0000');
			else el.setStyle('color', '#888888');
		}.bind(this));	
	},
	
	updateNav: function(){
		this.hoverNav.setStyle('display', '');
		if(this.options.currentItem <= 0) this.previous.setStyle('display', 'none');
		else{
			this.previous.setStyle('display', '');
			this.previous.addEvent('click',function(){
				this.setDisplay(this.image[this.options.currentItem - 1][0]);
			}.bind(this));
		}
		
		if(this.options.currentItem == this.options.totalItem) this.next.setStyle('display', 'none');
		else{
			this.next.setStyle('display', '');
			this.next.addEvent('click',function(){
				this.setDisplay(this.image[this.options.currentItem + 1][0]);
			}.bind(this));
		}		
	},
	
	setItem: function(current){
		for(var i=0; i<this.image.length; i++ ) {
			if(this.image[i][0] == current){
				this.options.currentItem = i;
			}
		}
	}
});
LightBox.implement(new Events, new Options);
