﻿// Bronwen - extend mootools
tabSwapper = Fx.Base.extend({

    getOptions: function(){
        return {
            startTab: 0,    
            tabClass: 'tabs',
            onActive: function(toggler){
                toggler.addClass('current');
            },
            onBackground: function(toggler){
                toggler.removeClass('current');
            },
            cookieName:''
        };
    },


    initialize: function(container, links, blocks, options){
        this.setOptions(this.getOptions(), options);

        this.tabs = [] ;
        this.links = $$(links);
        this.blocks = $$(blocks);
        this.now = -1 ;

        // add bulleted list to container
        this.tabContainerList = new Element('ul').addClass(this.options.tabClass) ;
        this.tabContainerList.injectBefore( $(container).getChildren()[0] ) ;
        // getFirst() isn't working!
        // $(container).getFirst() returns false, so $x.getChildren() instead
        
        this.links.each(function(link, i){
            tab = new Element('li')
            new Element('span').appendText(link.innerHTML).injectInside(tab);
            tab.injectInside(this.tabContainerList);
            tab.addEvent('click', this.display.bind(this, i));
            tab.addEvent('mouseenter', this.mouseOver.bind(this, i));
            tab.addEvent('mouseleave', this.mouseOut.bind(this, i));

            this.tabs.push(tab);
            link.setStyle('display','none');
        }, this);

        if(this.options.cookieName && this.getCookie()) 
            this.display( $(this.getCookie()) );
        else 
            this.display(this.options.startTab);
    },

    saveCookie: function(index){
        // save ID of block
        if (index==null)return;
        if (index >= this.blocks.length) index = 0;
        Cookie.set(this.options.cookieName, this.blocks[index].id, 3);
    },
    getCookie: function(){
        return $pick(Cookie.get(this.options.cookieName), false);
    },
    mouseOver: function(index) {
        this.tabs[index].addClass('hover')
    },
    mouseOut: function(index) {
        this.tabs[index].removeClass('hover')
    },

    display: function(index){
    
        if (index == null) index = this.options.startTab;
        index = ($type(index) == 'element') ? this.blocks.indexOf(index) : index;
    
        if (index === this.now) return this;
        if (index >= this.tabs.length) index = 0;
        this.now = index;
        this.blocks.each(function(el, i){
            if (i != index){
                this.fireEvent('onBackground', [this.tabs[i], el]);
                el.setStyle('display', 'none');
            } else {
                this.fireEvent('onActive', [this.tabs[i], el]);
                el.setStyle('display', 'block');
            }
        }, this);
        if(this.options.cookieName) this.saveCookie(index);
    }

});


