var MoreInfo = new Class({
    Implements: [Options, Events],
    
    options: {
        'ele': false,
        'links': false
    },
    
    _visible: false,
    _fadeOut: null,
    
    initialize: function(options) {
        var self = this;
        this.setOptions(options);
        this.options.ele.setStyle('display', 'none');
        
        // clicking on a listing item should open more info box
        this.options.links.addEvent('click', function(e) {
            var url = this.getElements('h2.title a.title_text')[0].get('href');
            self.change_page(url, this);
            new Event(e).stop();
        });
        
        // espacially for tabled devices, clicking anywhere 
        // within the moreinfo box should close it unless it is a button...
        $('more_info').addEvent('click', function(e) {
            if ( e.target.nodeName.toLowerCase() !== 'a' ) {
                new Event(e).stop();
                self.close();
                return false;
            }
        });
    },
    
    change_page: function(url, parent) {
        var self = this;
        
        if ( parent.hasClass('selected') ) return;
        
        new Request.HTML({
            url: url,
            onSuccess: function(tree, elements, html, javascript) {
                $$('div[class*=listing]').removeClass('selected');
                $('more_info').innerHTML = html;
                sf.set_hidden();
                init_sf();
                parent.addClass('selected');
                parent.getParent().addClass('more-info-open');
                
                // get close button and bind event
                var btn = parent.getElements('h2.title a.close')[0];
                btn.addEvent('click', function(e) {
                    new Event(e).stop();
                    self.close();
                    return false;
                });
            }
        }).get();
        
        if ( this._fadeOut !== null ) this._fadeOut.cancel();
        this.options.ele.setStyle('display', 'block');
        
        if ( this.visible ) {
            // if there is a more info page already open, just switch quickly
            this.options.ele.setStyle('opacity', 1);
        } else {
            // if nothing is open yet, fade it in nicely...
            this.options.ele.setStyle('opacity', 0);
            this.options.ele.tween('opacity', 1);
        }
        
        this.visible = true;
    },
    
    close: function() {
        var self = this;
        this.visible = false;
        $$('div[class*=listing]').removeClass('selected');
        $('content_scroller').removeClass('more-info-open');
        this._fadeOut = new Fx.Tween(this.options.ele);
        this._fadeOut.start('opacity', 0).chain(
            function() {
                if ( self.visible == false ) {
                    this.options.ele.setStyle('display', 'none');
                }
            }.bind(this)
        );;
    }
});

