/**
 * Tabs
 * Builds and launches a tab driven div populated with an external HTTP response
 *
 * @usage
 * var tabs = new Tabs($('tabContainer'), {
 *      'tabSelector': '.tabOption'
 *  });
 *
 * Modified version of SimpleTabs: Harald Kirschner <mail@digitarald.de>
 *
 * @author Josh Zeigler <jzeigler@resource.com>
 * @author John Keber <jkeber@resource.com>
 */
 
var Tabs = new Class({

    /**
     * Options
     * 
     * show: Number, default 0: index for the initial selected tab
     * tabSelector: String, default ".tabDefault". Selector to find the tab elements under the given parent element
     * classMenu: String, default ".tabOption". className for the ul that hold the tab items
     * classWrapper: String, default "tabWrapper". className for the wrapper that holds the container elements
     * classContainer:  String, default "tabContainer". className for the single container elements
     * onShow: Event. Fires when a container is shown, arguments: (tabElement, containerElement, tabIndex, tabElementOld, containerElementOld, tabIndexOld)
     * onHide: Event. Fires when a container is hidden, same arguments
     * onRequest: Event. Fires when Ajax request starts, same arguments
     * onComplete: Event. Fires when Ajax request is completed successfully, same arguments
     * onFailure: Event. Fires when a Ajax request fails, same arguments
     * getContent: Function. Callback to return the tab content element for an entry element, default is Element::getNext()
     * 
     */
    options: {
        'show': 0,
        'tabSelector': '.tabOption',
        'classWrapper': 'tabWrapper',
        'classMenu': 'tabMenu',
        'classContainer': 'tabContainer',
        'onShow': function(toggle, container, index) {
            toggle.addClass('tabSelected');
            container.setStyle('display', '');
        },
        'onHide': function(toggle, container, index) {
            toggle.removeClass('tabSelected');
            container.setStyle('display', 'none');
        },
        'onRequest': function(toggle, container, index) {
            container.addClass('tabLoading');
        },
        'onComplete': function(toggle, container, index) {
            container.removeClass('tabLoading');
        },
        'onFailure': function(toggle, container, index) {
            container.removeClass('tabLoading');
        },
        'getContent': null
    },

    /**
     * Constructor
     * 
     * @param {Element} The parent Element that holds the entry elements
     * @param {Object} Options
     */
    initialize: function(el, showTab, options) {
        this.setOptions(options);
        this.element = $(el);
        this.showTab = showTab;
        this.selected = null;
        this.build();
    },

    build: function() {
        this.entries = [];
        this.menu = new Element('ul', {'class': this.options.classMenu});
        this.wrapper = new Element('div', {'class': this.options.classWrapper});
        this.element.getElements(this.options.tabSelector).each(function(el) {

            var content = el.href || (this.options.getContent ? this.options.getContent.call(this, el) : el.getNext());
            this.addTab(el.innerHTML, el.title || el.innerHTML, content, el.href);
        }, this);
        this.element.empty().adopt(this.menu).adopt(this.wrapper);
        if (this.entries.length){
	    if (this.showTab.length){
	        this.select(this.showTab.toInt()-1);
	    }else{
	        this.select(this.options.show);
	    }
       	}

    },

    /**
     * Add a new tab at the end of the tab menu
     * 
     * @param {String} inner Text
     * @param {String} Title
     * @param {Element|String} Content Element or URL for Ajax
     */
    addTab: function(text, title, content,href) {
        if ($type(content) == 'string' && !$(content)) var url = content;
        var container = $(content) || new Element('div');
        
        if(href.contains('#')){
            this.entries.push({            
                'name': title,
                'container': container.setStyle('display', 'none').addClass(this.options.classContainer).inject(this.wrapper),
                'toggle': new Element('li').adopt(new Element('a', {
                    'href': '#',
                    'title': title,
                    'onclick': 'return(false)'
                }).setHTML(text)).inject(this.menu),
                'url': url || null
            });
        
        } else {
            this.entries.push({            
                'name': title,
                'container': container.setStyle('display', 'none').addClass(this.options.classContainer).inject(this.wrapper),
                'toggle': new Element('li').adopt(new Element('a', {
                    'href': '#',
                    'title': title,
                    'events': {
                        'click': this.onClick.bindWithEvent(this, [this.entries.length])
                    }
                }).setHTML(text)).inject(this.menu),
                'url': url || null
            });
        }
        return this;
    },

    onClick: function(evt, index) {
        $('productTabs').focus();
        
        if(index != this.selected) {
            evt.stop();
            var entry = this.entries[this.selected];

            var tabImage = $("tab_" + entry.name);
            tabImage.src = "/wcsstore/AmericanSignature/images/asf_prodpg/tab_" + entry.name + ".gif";
            //tabImage.addClass('mouseover_on');
            //mouseoverSetup("tab_" + entry.name);

            this.select(index);
        }
        return(false);
    },

    /**
     * Select the tab via tab-index
     * 
     * @param {Number} Tab-index
     */
    select: function(index) {
        if (this.selected === index || !this.entries[index]) return this;
        var entry = this.entries[index];
        
        var params = [entry.toggle, entry.container, index];
        if (this.selected !== null) {
            var current = this.entries[this.selected];
            if (this.ajax && this.ajax.running) this.ajax.cancel();
            params.concat([current.toggle, current.container, this.selected]);
            this.fireEvent('onHide', [current.toggle, current.container, this.selected]);
        }
        
        var tabImage = $("tab_" + entry.name);
        tabImage.src = "/wcsstore/AmericanSignature/images/asf_prodpg/tab_" + entry.name + "_on.gif";
        tabImage.removeEvents('mouseenter');
        tabImage.removeEvents('mouseleave');
        //tabImage.removeClass('mouseover_on');
        
        this.fireEvent('onShow', params);
        if (entry.url && !entry.loaded) {
            this.ajax = new Ajax(entry.url, $merge({
                'onRequest': this.fireEvent.pass(['onRequest', params], this),
                'onFailure': this.fireEvent.pass(['onFailure', params], this),
                'onComplete': function(resp) {
                    entry.loaded = true;
                    entry.container.empty().setHTML(resp);
                    this.fireEvent('onComplete', params);
                }.bind(this)
            }, this.options.ajaxOptions)).request();
        }
        this.selected = index;
        return this;
    }

});

Tabs.implement(new Events, new Options);
