var Lightbox = {
	bReady : false,
	bActive : false,
	items: [],
	init: function(options){
		this.options = Object.extend({
			resizeDuration: 500,
			resizeTransition: Fx.Transitions.Expo.easeOut,
			initialWidth: 10,
			initialHeight: 10,
			downloadLink: false,
			animateCaption: true,
			defaultIframeWidth : 500, 
			defaultIframeHeight: 300,
			minImageWidth : 600,
			minImageHeight : 300
		}, options || {});

		// IE 6 - XML prolog problem
		if(window.ie6 && document.compatMode=="BackCompat"){
			this.options.animateCaption = false;
		}

		this.anchors = {};
		$each(document.links, function(el, i){
			if (el.rel && el.rel.test(/^lightbox/i)){	
				var arrName = this.getArrayName(el.rel);
			 	if(!$chk(this.anchors[arrName])) this.anchors[arrName] = [];
				this.anchors[arrName].push({href: el.href, title: el.title});
				el.rel = 'lightbox:'+ arrName + ':' + (this.anchors[arrName].length-1);
				el.onclick = this.viewImage.pass(el, this);
			};
		}, this);

		if(this.bReady) return;
		
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);
		
		this.overlay = new Element('div').setProperty('id', 'lightboxOverlay').injectInside(document.body).setStyles('position:absolute; display:block; top:0; left:0; padding:0; margin:0; width:100%; height:0; z-index:999; background: #6E737F; visibility:hidden;');

		this.center = this.overlay.clone().setProperty('id', 'lightboxWrapper').setStyles('position:absolute; z-index:950; border:10px solid #FFF; background:#FFF; left:-1000px; top:-1000px;  width:10px; height:10px; overflow:hidden; z-index:1000;').injectInside(document.body);
//		new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth, height: this.options.initialHeight, marginLeft: -(this.options.initialWidth/2), display: 'none'}).injectInside(document.body);

		this.canvas = this.overlay.clone().setProperty('id', 'lightboxCanvas').setStyles('').injectInside(this.center);
		

//		new Element('div').setProperty('id', 'lbCanvas').injectInside(this.center);
		this.ajaxLoader = this.overlay.clone().setProperty('id', 'ajaxLoader').setStyles('position: absolute; height:40px; width:40px; top: 0; left: 0; background:#333 url(/resources/ajax_16px_333333.gif) no-repeat center; margin:5px; display: none;').setStyle('opacity',0.8).injectInside(this.canvas);
		
		this.controlBar = this.overlay.clone().setProperty('id', 'lightboxControl').setStyles('position: absolute; height:45px; width:100%; top: 0; left: 0; background:url(); margin:0; display: none; visibility: hidden;').setStyle('opacity',0.8).injectInside(this.canvas);
		this.controlBar.setHTML('<div style="float:right; margin: 5px; background:#000; height:14px; padding:13px 20px;">'+
			'<a href="#" style="padding:2px 20px 2px 20px; cursor: pointer;  background:url(/resources/images/lb_controls.gif) no-repeat 0px -234px;" target="_blank" id="lightboxSaveLink">download</a>'+
			'<a href="#" style="padding:2px 0px 2px 20px; cursor: pointer;  background:url(/resources/images/lb_controls.gif) no-repeat 0px -274px;" id="lightboxCloseLink">close</a>'+
			'</div>');
		
		var controlBar = this.controlBar;
		this.canvas.addEvents({
			'mouseenter' : function(){
				controlBar.setStyle('display', '');
			},
			'mouseleave' : function(){
				controlBar.setStyle('display', 'none');
			}			
		});
		
//		this.resetMainImage()
			
	
		this.topContainer = this.overlay.clone().setProperty('id', 'lightboxCaption').setStyles('position: absolute; width:100%; top: 0; left: 0; height: 75px; z-index:1000;').setStyles({'visibility':'hidden'}).injectInside(document.body);
		this.topContainer.setHTML('<table border=0 cellspacing=0 cellpadding=0 style="margin:auto;" id="lightboxCaptionTable"><tr>'+
			'<td><div style="width: 75px; height: 75px; background:url(/resources/images/lb_controls.gif) no-repeat" id="lightboxPrevBlock"></div></td>'+
			'<td id="lightboxTextCell"><div style="color:#CCC; font-size:12px; text-align:center;" id="lightboxCaptionNumbers"></div><div style="color:#FFF; font-size:18px;text-align:center" id="lightboxCaptionText"></div></td>'+
			'<td><div style="width: 75px; height: 75px; background:url(/resources/images/lb_controls.gif) no-repeat -75px 0px" id="lightboxNextBlock"></div></td>'+
			'</tr></table>');		
			
		this.number = $('lightboxCaptionNumbers');
		this.caption = $('lightboxCaptionText');
		this.captionWrapper = $('lightboxCaptionTable');
		this.saveLink = $('lightboxSaveLink').setStyle('display', this.options.downloadLink ? '':'none');
		this.closeLink = $('lightboxCloseLink');	
		
//		this.textWrapper = this.overlay.clone().setStyles('margin: auto;height: 75px;').injectInside(this.topContainer);		

		this.prevLink = new Element('a').setProperties({id: 'lbPrevLink', href: '#', title: 'Previous image'}).setStyle('display', 'none').injectInside('lightboxPrevBlock');
		this.nextLink = this.prevLink.clone().setProperties({'id': 'lbNextLink', title: 'Next image'}).injectInside('lightboxNextBlock');
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

		this.closeLink.onclick = this.overlay.onclick = this.close.bind(this);


		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			center: this.center.effects({duration: this.options.resizeDuration, transition: this.options.resizeTransition, onComplete: nextEffect}),
			top: this.captionWrapper.effect('margin-top', {duration: 300}),
			image: this.canvas.effect('opacity', {duration: 500, onComplete: nextEffect})
		};
		
		this.bReady = true;
		
//		this.preloadPrev = new Image();
//		this.preloadNext = new Image();
	},
	getArrayName : function(rel){
		var currRel = rel.replace(']', '');
		var arrName = currRel.split('[')[1];
		return arrName;
	},
	resetMainImage : function(){
		if(!this.currentImage) {
			this.currentImage = new Image();
			$(this.currentImage).setProperties({width: '100%'}).injectInside(this.canvas);
		};
		this.currentImage.src = '';
		this.currentImage.onload = function(){};
	},
	viewImage: function(link){
		var labels = link.rel.split(':');
		var arrName = labels[1];
		var itemNumber = labels[2];
		this.items.length = 0;
		this.items = this.anchors[arrName].copy();
		return this.open(itemNumber);
	},
	open: function(itemNumber){
		this.setup(true);
		this.position();		
		this.activeItem  = itemNumber.toInt();
		
//		alert(this.items[itemNumber].href)
		this.preload = new Image();
		this.preload.onload = this.nextEffect.bind(this);
		this.preload.setAttribute('src', this.items[itemNumber].href);
//		this.preload.src = this.items[itemNumber].href;
		
		this.title = this.items[itemNumber].title || this.extractFileName(this.items[itemNumber].href, 0);
		this.step = this.bActive ? 4 : 0;	
		
		this.controlBar.style.visibility = 'hidden';
		
		if(!this.bActive) {
			this.fx.image.hide();
			this.overlay.setStyles({'background':'#6E737F url(/resources/ajax_48px_6E737F.gif) no-repeat', 'background-position': 'center ' +  (window.getScrollTop() + window.getHeight() / 2 - 48 ) + 'px'});
			this.fx.overlay.start(0.8);			
		} else {
			this.ajaxLoader.setStyle('display', '');
		};
		
		return false;
		
	},
	position: function(){
		//IE6 - XML prolog problem.
//		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();
//		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
//		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		var pageSize = window.getSize(); //getSiteDimensions();
//		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();

		var wh = pageSize.scrollSize.y;
		var st = pageSize.scroll.y;// document.body.scrollTop  || document.documentElement.scrollTop;

		this.overlay.setStyles({top: 0, height: wh /*, width:ww+'px'*/});
	},
	resizeCanvas : function(){
	},
	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		if (window.ie) elements.extend(document.getElementsByTagName('select'));
		elements.each(function(el){ el.style.visibility = open ? 'hidden' : ''; });
		var fn = open ? 'addEvent' : 'removeEvent';
		this.fx.center.options.duration = this.options.resizeDuration;
		this.fx.center.options.transition = this.options.resizeTransition;
//		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
//		window[fn]('resize', this.eventPosition);		
		document[fn]('keydown', this.eventKeyDown);				
	},
	getDimensionsScale : function(){
		var maxWidth=window.getWidth() - 100;
		var w_scale=1;
		if(maxWidth<this.preload.width){
		    w_scale=maxWidth/this.preload.width;
		};
		return w_scale;

	},
	nextEffect: function(){
		if(this.step == 0){
			var ww = window.getWidth();
			this.center.setStyles({opacity: 1, top: window.getScrollTop() + window.getHeight() / 2 - 40, width: this.options.initialWidth, height: this.options.initialHeight, left: (ww/2 - (this.options.initialWidth + 20)/2).toInt()});
			this.step = 1;
			this.nextEffect();
			return false;
//			console.log('w: %s  h: %s', this.preload.width, this.preload.height)
		};
		if(this.step == 1){
			this.overlay.setStyles({'background':'#6E737F'});
			var ww = window.getWidth();
			var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
			var st = window.getScrollTop();
			var wt, at;
			if(wh - this.preload.height > 170){ 
				 wt = (wh - this.preload.height - 20)/2 + st
				 at = wt;
			}
			else {
				wt = 75 + st;
				at = this.topContainer.style.top.toInt() + 75;
			};
				
			this.top = wt;//this.bActive ? at : wt;
			
			this.topContainer.setStyles({top: st});	
			this.center.style.display = '';
			
			if(this.image) this.image.remove();
			
			var k = this.getDimensionsScale();
			this.originalSizes = [this.preload.width, this.preload.height];
			this.fx.center.start({top: this.top, left: (ww/2 - ( this.preload.width*k + 20)/2).toInt(), height: this.preload.height*k, width: this.preload.width*k});
			this.step = 2;	
			return false;			
		};
		if(this.step == 2){
			this.position();			
			this.overlay.setStyles({height: this.overlay.style.height.toInt() + 25 });
			
			this.number.setHTML( (this.items.length == 1) ? '' : 'Image ' + (this.activeItem+1) + ' of ' + this.items.length );	
			this.caption.setHTML(this.title);			
			
			this.image = $(this.preload).injectInside(this.canvas).setStyles({'width': this.center.style.width, 'height': this.center.style.height});
			
			this.saveLink.href = this.preload.src;				
//			this.currentImage.src = this.preload.src;	
			
//			$(this.preload).remove();		
			this.preload.onload = Class.empty;
			this.preload = null;
			
			
			this.fx.image.start(1);
			this.step++;
			return false;
		};
		if(this.step == 3){
			this.bActive = true;

			this.topContainer.setStyles({visibility:''});
			this.controlBar.style.visibility = '';
			this.fx.top.start(0);
//			this.prevLink.style.height = this.nextLink.style.height = this.center.style.height;
			if(this.activeItem > 0 && this.items.length > 1)
				this.prevLink.setStyle('display', '');
			if(this.activeItem < this.items.length - 1  && this.items.length > 1)
				this.nextLink.setStyle('display', '');
			return false;
		};
		if(this.step == 4){
			this.prevLink.style.display = this.nextLink.style.display = 'none';
			this.ajaxLoader.setStyle('display', 'none');
			this.fx.image.start(0);
			this.step = 1;
			return false;
		};
		if(this.step == 5){
			this.fx.center.options.duration = 100;
			this.fx.center.options.transition = Fx.Transitions.linear;
			this.prevLink.style.display = this.nextLink.style.display = 'none';

			this.topContainer.style.visibility = 'hidden';
			this.captionWrapper.style.marginTop = '-75px';

			
			this.fx.center.start({opacity: 0});		
			this.step++;
			return false;
		};
		if(this.step == 6){
			var overlay = this.overlay;
			this.fx.overlay.start(0).chain(function(){
				overlay.setStyles({top:0, height: 0});
			},this);
			this.center.style.display = 'none';
			this.bActive = false;
			this.step++;
			return false;
		};			
	},
	close : function(){
		this.step = 5;
		this.nextEffect();
		return false;
	},
	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();
		}
	},
	previous: function(){
		return this.items[this.activeItem-1] ? this.open(this.activeItem-1) : false;
	},

	next: function(){
		return this.items[this.activeItem+1] ? this.open(this.activeItem+1) : false;

	},
	extractFileName: function(fullpath, lnght) {
		var element_work = fullpath;
		var etab = fullpath.split("/");
	
		nbr_elements = etab.length;
		fullpath = etab[nbr_elements-1];
		return fullpath;
	}	
};

