var Ultrabox = {
    init: function() {
        
		this.showslideshow = $('lightbox');
		this.showslideshow.addEvent('click', this.click.bindAsEventListener(this));

        this.eventAnimateBox = this.animateBox.bind(this);
        this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
        this.eventPosition = this.position.bind(this);
        this.overlay = new Element('div', {'id': 'ubOverlay'}).injectInside(document.body);
        this.overlay.onclick = this.close.bind(this);
        
        var wrapper = new Element('div', {'id': 'ubWrapper'}).injectInside(document.body);
        this.throbber = new Element('div', {'id': 'ubThrobber'}).injectInside(wrapper).setStyle('display', 'none');
        this.throbber.onclick = this.close.bind(this);

        this.box = new Element('div', {'id': 'ubBox'}).injectInside(wrapper);
        this.ubcontent = new Element('div', {'id':'ubContent'}).injectInside(this.box);
        var closeBtn = new Element('a', {'id':'ubClose', 'href': '#'}).injectInside(this.box);
        closeBtn.setText('CLOSE');
        closeBtn.onclick = this.close.bind(this);        
        
      	this.box.setStyle('display', 'none');
        
        this.fx = {
            overlayColor: this.overlay.effect('backgroundColor', {duration:500}).set('#FFF'),
            overlayOpacity: this.overlay.effect('opacity', {duration:500}),
            box:this.box.effect('opacity', {duration:500}).hide()
        }
    },
    
    click: function(e) {
        e = new Event(e);
        this.fx.overlayOpacity.set(0.2);      
		this.prepare(this.showslideshow);
        e.preventDefault();
    },
    
    changeBackground: function(color) {
        if(this.overlay.getStyle('opacity') <= 0.25) {
            this.fx.overlayColor.stop();
            this.fx.overlayColor.set(color);
        } else {
            this.fx.overlayColor.stop();
            if(this.overlay.getStyle('backgroundColor') != color) {
                this.fx.overlayColor.start(color);
            }
        }
        
        if(this.overlay.getStyle('opacity') < 0.95) {
            this.fx.overlayOpacity.start(0.95)
        }
        
    },
    
    prepare: function(linkUrl) {
        this.activeLink = 0;
        this.position();
        this.setup(true);
        this.changeBackground('#FFF');
        
        if(this.ajaxRequest) this.ajaxRequest.cancel();
        this.ajaxRequest = new Ajax(linkUrl, {method: 'get', update: this.ubcontent, onComplete:this.recieve.bind(this)});
        this.ajaxRequest.request();
        return false;
    },

    recieve: function() {
    	this.sampleimages=$$('div.sampleimage');
		$each(this.sampleimages, function(el) {
			$(el).setStyle('display','none')
        });

        if(this.sampleimages.length > 1) {
            this.prevLink = new Element('a', {'id': 'ubPrevLink', 'href': '#', 'title': 'Previous' }).injectInside(this.box);
            this.nextLink = this.prevLink.clone().setProperty('id', 'ubNextLink').setProperty('title', 'Next').injectInside(this.box);
            this.prevLink.setHTML('&lt;');
            this.nextLink.setHTML('&gt;');
            this.prevLink.onclick = this.previous.bind(this);
            this.nextLink.onclick = this.next.bind(this);
        }

		this.showimage=$$('div.showimage');
		this.showimage.setStyle('display','block');
		this.countcurrent=$$('span.countcurrent');
		this.counttotal=$$('span.counttotal');
		this.counttotal.setText(this.sampleimages.length);
		
		this.request(0,0);
    },

	open: function(imageNum) {
		var curImage = this.activeLink;
		this.activeLink = imageNum;
        this.position();
        this.setup(true);
        this.changeBackground('#FFF');
        this.request(imageNum, curImage);
        return false;
    },
    
    close: function() {
        this.throbber.setStyle('display', 'none');
        this.fx.overlayOpacity.removeEvent('onComplete', this.eventAnimateBox);
        this.fx.overlayColor.removeEvent('onComplete', this.eventAnimateBox);
        this.fx.box.stop();
        this.fx.overlayColor.stop();
        this.fx.overlayOpacity.stop();
        this.box.setStyle('display', 'none');
        this.fx.overlayOpacity.chain(this.setup.pass(false, this)).start(0);
        return false;
    },
    
    setup: function(open) {
        var fn = open ? 'addEvent' : 'removeEvent';
        window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
        this.overlay.setStyle('display', open ? 'block' : 'none');
        document[fn]('keydown', this.eventKeyDown);
        //this.step = 0;
    },
    
    request: function(imageNum, curImage) {
        this.box.setStyle('display','none');
		
		this.sampleimages[curImage].setStyle('display','none');
		this.sampleimages[imageNum].setStyle('display','block');

		this.countcurrent.setText(imageNum+1);
        this.fx.box.stop();
        this.fx.box.set(0);
        this.throbber.setStyle('display', 'block');
        this.position();

		if (this.sampleimages[imageNum].getElement("img")){
			this.preload = new Image();	        
	        this.preload.src = this.sampleimages[imageNum].getElement("img").src;
			this.preload.onload = this.show(imageNum, this.preload.width);
		} else this.show(imageNum, 470);
    },
	
	makeItWork: function() {
		
    },
    
    show: function(imageNum, preloadWidth) {
        this.throbber.setStyle('display', 'none');
		
		if (this.sampleimages[imageNum].getElement("img")){
			var sampleimagewidth = preloadWidth+34;
		} else if (this.sampleimages[imageNum].getElement("object")){
			var sampleimagewidth = 514;
		} else sampleimagewidth = 800;
		
		
		this.box.setStyle('width', sampleimagewidth);
		this.box.setStyle('display', '');
        this.fx.box.set(0);
                
		var top = 100;
        top += window.getScrollTop();
        
        this.box.setStyle('top', top);
        
        if(this.fx.overlayOpacity.timer != null) {
            this.fx.overlayOpacity.addEvent('onComplete', this.eventAnimateBox.bind(this));
        }else if(this.fx.overlayColor.timer != null) {
            this.fx.overlayColor.addEvent('onComplete', this.eventAnimateBox.bind(this));
        } else {
            this.animateBox();
        }
		
		
    },
    
    animateBox: function() {
        this.fx.overlayOpacity.removeEvent('onComplete', this.eventAnimateBox);
        this.fx.overlayColor.removeEvent('onComplete', this.eventAnimateBox);
        if (window.webkit){
			this.fx.box.start('onComplete', this.makeItWork());
		} else this.fx.box.start(1);
		
		
    },
    
    position: function() {
        this.overlay.setStyles({'top': 10, 'height':window.getScrollHeight()});
        var l = window.getWidth();
        var t = window.getHeight();
        if(this.throbber.getStyle('display') == 'block') {
            this.throbber.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
        }
    },
    
    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() {
        var n = this.activeLink - 1;
        n = n < 0 ? this.sampleimages.length - 1 : n;
        this.open(n);
        return false;
    },
    
    next: function() {
        var n = this.activeLink + 1;
        n = n >= this.sampleimages.length ? 0 : n;
        this.open(n);
        return false;
    }
}

window.addEvent('domready', function() {
    
	if($('lightbox')) Ultrabox.init();
});