/*
	Slimbox v1.41 - The ultimate lightweight Lightbox clone
	by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/

var Lightbox = {

	init: function(options){
		this.options = $extend({
			resizeDuration: 200,
			resizeTransition: false,	// default transition
			initialWidth: 300,
			initialHeight: 300,
			animateCaption: false,
			showCounter: false
		}, options || {});

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^lightbox/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		this.overlay = new Element('div', {'id': 'lbOverlay','styles': {'display':'none'}}).injectInside(document.body);

		this.center = new Element('div', {'id': 'lbCenter', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'display': 'none'}}).injectInside(document.body);
		
        this.headerHolder = new Element('div', {'id': 'lbHeaderHolder', 'style': {'display': 'block'}}).injectInside(this.center);
		this.header = new Element('div', {'id': 'lbHeader'}).injectInside(this.headerHolder);
		
		this.origPic = new Element('a', {'id': 'lbOrigPic', 'target': '_blank'}).injectInside(this.header);
		this.origPicSpan = new Element('span', {'id': 'lbOrigPicSpan'}).injectInside(this.origPic);
		this.origPicSpan.setHTML('Ava originaalpilt uues aknas');
		this.origPicIcon = new Element('img', {'src': base_url+'images/lb_orig_pic.gif', 'width': '19px', 'height': '19px', 'alt': 'Ava originaalpilt uues aknas'}).injectInside(this.origPic);
		
		this.closeBtn = new Element('a', {'id': 'lbCloseBtn', 'href': '#'});
		this.closeBtn.injectInside(this.header).onclick = this.overlay.onclick = this.close.bind(this);
		this.closeBtnSpan = new Element('span', {'id': 'lbCloseBtnSpan'}).injectInside(this.closeBtn);
		this.closeBtnSpan.setHTML('Sulge');
		this.closeBtnImg = new Element('img', {'src': base_url+'images/lb_close.gif', 'width': '19px', 'height': '19px', 'alt': 'Sulge'}).injectInside(this.closeBtn);		
		
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.header);
		
		this.image = new Element('div', {'id': 'lbImage'}).injectInside(this.center);
		this.prevLink = new Element('a', {'id': 'lbPrevLink', 'href': '#', 'styles': {'display': 'none'}, 'title': 'Eelmine'}).injectInside(this.image);
		this.nextLink = this.prevLink.clone().setProperty('id', 'lbNextLink').setProperty('title', 'J\u00e4rgmine').injectInside(this.image);
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

		this.bottomHolder = new Element('div', {'id': 'lbBottomHolder', styles:{ 'display': 'none'}}).injectInside(document.body);
		this.bottom = new Element('div', {'id': 'lbBottom'}).injectInside(this.bottomHolder);
		this.caption = new Element('h1', {'id': 'lbCaption'}).injectInside(this.bottom);
		
		this.priceHolder = new Element('div', {'id': 'lbPriceHolder'}).injectInside(this.bottom);
		this.price = new Element('div', {'id': 'lbPrice'}).injectInside(this.priceHolder);
				
		this.buyBtn = new Element('a', {'id': 'lbBuyBtn', 'href': '#', 'class': 'link_button'}).injectInside(this.priceHolder);
		this.buyBtnSpan = new Element('span', {'id': 'lbBuyBtnSpan'}).injectInside(this.buyBtn);
		this.buyBtnSpan.setHTML('Pane ostukorvi ');
		this.buyBtnIcon = new Element('img', {'src': base_url+'images/but_red_add.gif', 'width': '14px', 'height': '14px', 'alt': ''}).injectInside(this.buyBtnSpan);
		
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.priceHolder);
		
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 200}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.image.effect('opacity', {duration: 50, onComplete: nextEffect})
		};

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

	click: function(link){
		if (link.rel.length == 8) return this.show(link.href, link.title);

		var j, imageNum, images = [];
		this.anchors.each(function(el){
			if (el.rel == link.rel){
				for (j = 0; j < images.length; j++) if(images[j][0] == el.href) break;
				if (j == images.length){
				    var str = el.title.split(';');
					images.push([el.href, str[0], str[1], str[2]]);
					if (el.href == link.href) imageNum = j;
				}
			}
		}, this);
		return this.open(images, imageNum);
	},

	show: function(url, title){
		return this.open([[url, title]], 0);
	},

	open: function(images, imageNum){
		this.images = images;
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.overlay.setStyles({display: ''});
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

	position: function(){
		this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
	},

	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},

	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.changeImage(this.activeImage-1);
	},

	next: function(){
		return this.changeImage(this.activeImage+1);
	},

	changeImage: function(imageNum){
		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;

		this.prevLink.style.display = this.nextLink.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'lbLoading';

		this.preload = new Image();
		this.preload.onload = this.nextEffect.bind(this);
		
		this.preload.src = this.getUrl(this.images[imageNum][0]);
		return false;
	},

    getUrl: function(image_url) {
        //XXX: Make optimal calculations from real sizes of elements
        if(image_url.indexOf("?")!=-1) {
    		var container_width = window.getWidth()-20;
    		var container_height = window.getHeight()-(window.getHeight() / 15)-170;
    		image_url = image_url+'&container_width='+container_width+'&container_height='+container_height
    		return image_url;
        }
        return image_url;
    },
	
	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';
			this.image.style.backgroundImage = 'url('+this.getUrl(this.images[this.activeImage][0])+')';
			this.image.style.width = this.header.style.width = this.preload.width+'px';
			this.image.style.height = this.prevLink.style.height = this.nextLink.style.height = this.preload.height+'px';
			this.caption.setHTML(this.images[this.activeImage][1] || '');
			if(this.images[this.activeImage][2] && this.images[this.activeImage][3]) {
			     this.buyBtn.setStyle('display','block');
			     this.origPic.setStyle('display','inline');
			     this.origPic.setProperty('href', this.images[this.activeImage][0]);
			     this.price.setHTML(fmtKr(this.images[this.activeImage][2]));
			     var product_id = this.images[this.activeImage][3];
			     this.buyBtn.onclick = function() { addToCart(product_id); };
			     productTracker._trackEvent('Show picture', (this.images[this.activeImage][1] || ''), this.activeImage);
			} else {
			    this.buyBtn.setStyle('display','none');
			    this.origPic.setStyle('display','none');
			}
			/*this.number.setHTML((!this.options.showCounter || (this.images.length == 1)) ? '' : 'Image '+(this.activeImage+1)+' of '+this.images.length);*/

			if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage-1][0];
			if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage+1][0];
			
			this.headerHolder.style.display = this.bottomHolder.style.display = 'block';
			this.center.setStyles({top: this.top});
			
			if (this.center.clientHeight != this.image.offsetHeight){
				this.fx.resize.start({height: this.image.offsetHeight+this.headerHolder.clientHeight});
				break;
			}
			this.step++;
		case 2:
			if (this.center.clientWidth != this.image.offsetWidth){
				this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
				break;
			}
			this.step++;
		case 3:
			
			this.fx.image.start(1);
			break;
		case 4:
		case 5:
			if (this.activeImage) this.prevLink.style.display = '';
			if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
			this.bottomHolder.setStyles({top: this.top+this.center.clientHeight, width: this.center.offsetWidth, marginLeft: -this.center.offsetWidth/2});
			this.step = 0;
		}
	},

	close: function(){
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.headerHolder.style.display = this.bottomHolder.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
	}
};

window.addEvent('domready', Lightbox.init.bind(Lightbox));
