var Ultrabox = {
    init: function() {
        this.anchors = [];
        $each(document.links, function(el) {
            if (el.rel && el.rel.test(/^lightbox/i)) {
                $(el).addEvent('click', this.click.bindAsEventListener(this));
                this.anchors.push(el);
            }
        }, 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);
//        this.watermark = new Element('div', {'id': 'ubWatermark'}).injectInside(this.overlay);
        this.watermark = new Element('div', {'id': 'ubWatermark'}); // create, but dont display .injectInside(this.overlay);
        
        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);
        
        if(window.ie6) {
            var url = this.watermark.getStyle('backgroundImage').match(/url\(["']?(.*?)["']?\)/)[1];
            this.watermark.setStyle('backgroundImage', 'none');
            this.watermark.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+url+"', sizingMethod='crop')"
        }
        this.watermarkSize = {width: this.watermark.getStyle('width').toInt(), height: this.watermark.getStyle('height').toInt()};
        this.watermark.onclick = this.close.bind(this);
        this.box = new Element('div', {'id': 'ubBox'}).injectInside(wrapper);
//        var closeBtn = new Element('a', {'id':'ubClose', 'href': '#'}).injectInside(this.box);
//        closeBtn.setText('CLOSE');
//        closeBtn.onclick = this.close.bind(this);
        this.image = new Element('div', {'id':'ubImage'}).injectInside(this.box);
        this.image.onclick = this.next.bind(this);
        this.title = new Element('div', {'id':'ubTitle'}).injectInside(this.box);
//        this.caption = new Element('div', {'id':'ubCaption'}).injectInside(this.box);
        this.caption = new Element('div', {'id':'ubCaption'});  // create it, but dont show it.
        
        if(this.anchors.length > 1) {
            this.navBox = new Element('div', {'id': 'ubNavbox' }).injectInside(this.box);
            this.prevLink = new Element('a', {'id': 'ubPrevLink', 'href': '#', 'title': 'Previous' }).injectInside(this.navBox);
            this.slash = new Element('span' ).injectInside(this.navBox);
            this.slash.setHTML(' / ');
            this.nextLink = this.prevLink.clone().setProperty('id', 'ubNextLink').setProperty('title', 'Next').injectInside(this.navBox);
            this.prevLink.setHTML('&lt; PREV');
            this.nextLink.setHTML('NEXT &gt;');
            this.prevLink.onclick = this.previous.bind(this);
            this.nextLink.onclick = this.next.bind(this);
        }
        
        
        this.box.setStyle('display', 'none');
        
        this.fx = {
            overlayColor: this.overlay.effect('backgroundColor', {duration:500}).set('#000000'),
            overlayOpacity: this.overlay.effect('opacity', {duration:500}),
            box:this.box.effect('opacity', {duration:500}).hide()
        }
    },
    
    click: function(e) {
        e = new Event(e);
        var link = e.target.parentNode.parentNode;
        var linkNum;
        var count = this.anchors.length;
        for (var i = 0; i < count; i++) {
            if(this.anchors[i].href == link.href) {
                linkNum = i;
                break;
            }
        }
        this.fx.overlayOpacity.set(0.2);
        this.open(linkNum);
        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)
        }
        
    },
    
    open: function(linkNum) {
        this.activeLink = linkNum;
        this.watermark.setStyle('display','block');
        this.position();
        this.setup(true);
        this.changeBackground(this.anchors[linkNum].rel.split('-')[1]);
        this.request(linkNum);
        return false;
    },
    
    close: function() {
        if(this.preload) {
            this.preload.onload = Class.empty;
            this.preload = null
        }
        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 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);
        this.overlay.setStyle('display', open ? 'block' : 'none');
        document[fn]('keydown', this.eventKeyDown);
        //this.step = 0;
    },
    
    request: function (linkNum) {
        this.box.setStyle('display','none');
        this.fx.box.stop();
        this.fx.box.set(0);
        this.throbber.setStyle('display', 'block');
        this.position();
        if(this.ajaxRequest) this.ajaxRequest.cancel();
        this.ajaxRequest = new Ajax(this.anchors[this.activeLink].href, {method: 'get', onComplete:this.change.bind(this)});
        this.ajaxRequest.setHeader('X-Request', 'JSON');
        this.ajaxRequest.request();
    },
    
    change: function(response) {
        var json = eval(response);
        
        this.titleText = json.title;
        this.captionText = json.caption;
        this.imageURL = json.img;
        
        this.preload = new Image();
        this.preload.onload = this.show.bind(this);
        this.preload.src = this.imageURL;

    },
    
    show: function() {
        this.throbber.setStyle('display', 'none');
//        this.title.setHTML(this.titleText);
        this.title.setHTML(this.captionText);
        this.caption.setHTML(this.captionText);
        this.image.setStyle('backgroundImage', 'url('+this.imageURL+')');
        this.image.setStyle('width', this.preload.width);
        this.image.setStyle('height', this.preload.height);
        this.box.setStyle('width', this.preload.width);
        this.box.setStyle('display', '');
        this.fx.box.set(0);
        
        
        var top = Math.max(0, Math.round((window.getHeight() - this.box.offsetHeight) * 0.5));
        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);
        this.fx.box.start(1);
    },
    
    position: function() {
        this.overlay.setStyles({'top': 0, 'height': window.getScrollHeight()});
        var l = window.getWidth() - this.watermarkSize.width;
        var t = window.getHeight() - this.watermarkSize.height;
        this.watermark.setStyles({'top': t, 'left': l});
        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.anchors.length - 1 : n;
        this.open(n);
        return false;
    },
    
    next: function() {
        var n = this.activeLink + 1;
        n = n >= this.anchors.length ? 0 : n;
        this.open(n);
        return false;
    }
}

var Suckerfish = {
    init: function() {
        this.menu = $('menu');
        this.menu.addEvent('mouseover', this.over.bind(this, this.menu))
        this.menu.addEvent('mouseout', this.out.bind(this, this.menu))
        
        this.anchors = $$(this.menu.getElementsByTagName('a'));
        this.anchors.each(function(el) {
            el.addEvent('mouseover', this.over.bind(this, el));
            el.addEvent('mouseout', this.out.bind(this, el));
        }, this)

        
        
    },
    over: function(item) {
        item.addClass('over');
    },
    out: function(item) {
        item.removeClass('over');
    }
}

window.addEvent('domready', function() {
    Ultrabox.init();
//    Suckerfish.init();
});