var Section = Class.create({
    initialize : function(container, trigger, contents, isOpen){
        this.container = container;
        this.trigger = trigger;
        this.contents = contents;
        this.expanded = isOpen;
        this.reservedHeight = 0;
        this.setup();
    },
    setup : function(){
        this.trigger.invoke('observe', 'click', this.open.bind(this));
        this.boundClose = this.close.bind(this);
        document.observe('section:opened', this.boundClose);
        this.contents.observe('section:entered', this.open.bind(this));
        this.list = new FadeList(this.contents, this.contents.down('.panel'), '.top_level a');
    },
    open : function(ev, suppressEvent){
        ev.stop();
        this.container.addClassName("active");
        document.stopObserving('section:opened', this.boundClose);
        if (!suppressEvent) {
            document.fire('section:opened'); this.container.fire('section:clicked');
        }
        document.observe('section:opened', this.boundClose);
        if (! this.expanded){
            this.contents.slideDown({
                duration:.5,
                queue:'end'
            });
        }
        this.expanded = true;
    },
    close : function(ev){
        ev.stop();
        this.container.removeClassName("active");
        if (this.expanded){

            // this gets reset so set it now
            this.reservedHeight = this.list.options.prev.getHeight();

            this.contents.slideUp({
                duration:.4,
                queue:'end',
                afterFinish:function(){

                    // set top level to product categories
                    this.list.target.fade({
                        duration:.4,
                        afterFinish:function(){
                            this.list.target.setStyle({
                                height:''
                            }).childElements().invoke('remove');
                            this.list.options.prev.appear();

                            if(this.reservedHeight > 0){
                                this.list.container.setStyle({
                                    height:this.reservedHeight+'px'
                                });
                            }
                            this.list.active = false;
                        }.bind(this)
                    });
                }.bind(this)
            });
        }
        this.expanded = false;
    }
});

var FadeList = Class.create({
    initialize : function(container, target, selector, options){
        this.container = container;
        this.loader = this.container.down('.loader');
        this.target = target;
        this.items = container.select(selector);
        this.options = Object.extend({
            prev : this.target.previous('div'),
            hideTarget : true
        }, options || {});
        this.items.invoke('observe', 'click', this.options.call || this.call.bind(this));
        this.container.observe('section:reset', this.close.bind(this));
        if (this.options.hideTarget && !this.target.hasClassName('inited')){
            this.target.hide();}
        if (this.target.hasClassName('inited')){
            this.initCatRevealed();
        }
    },
    call : function(ev){
        ev.stop();
        if (this.active) { return; }
        this.active = true;
        this.loader.show();
        this.container.fire('section:entered');
        var item = ev.element();
        var href = item.hasAttribute("href") ? item.readAttribute('href') : item.up('a[href]').readAttribute('href');
        //SWFAddress.setValue(href);

        new Ajax.Updater(this.target, href, {
            insertion:'bottom',
            onComplete: function(r){
                this.target.select('.second_level:last-child .back').invoke('observe', 'click', this.close.bind(this));
                this.afterCall(r);
				//new PromptSelect($('link_data'));
            }.bind(this)
        });
    },
    afterCall : function(r){

        this.options.prev.fade({
            duration:.4,
            queue:'end'
        });
        this.container.morph({
            height:this.target.getHeight()+'px'
        });
        this.target.appear({
            queue:'end',
            duration:.4,
            afterFinish:function(){
                this.loader.fade();
            }.bind(this)
        });
        new FadeProd(this.container, this.target, '.second_level .listing td a', {
            prev:this.target.down(),
            hideTarget:false,
            cleanup:this.close.bind(this)
        });

        document.fire('category:opened');
    },
    close : function(ev){
        ev.stop();
 
        this.container.morph({
            height:this.options.prev.getHeight()+'px'
        });
        this.target.fade({
            duration:.4,
            afterFinish:function(){
                this.target.setStyle({
                    height:''
                }).childElements().invoke('remove');
            }.bind(this)
        });
        this.options.prev.appear({
            duration:.4,
            queue:'end'
        });
        this.active = false;
        var type = {
            "dietary": "DS",
            "otc": "OTC",
            "rx": "Rx"
        };
        //SWFAddress.removeEventListener(SWFAddressEvent.CHANGE, handleChange);
        //SWFAddress.setValue("/products/"+type[this.target.up('.category').readAttribute('id')]);
        //SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
        
    },
    initCatRevealed : function(){
        this.target.select('.second_level:first-child .back').invoke('observe', 'click', this.close.bind(this));
        var f = new FadeProd(this.container, this.target, '.second_level:first-child .listing td a', {
            prev:this.target.down('.second_level:first-child'),
            hideTarget:false,
            cleanup:this.close.bind(this)
        });
        if (this.target.select('.second_level').length > 1){
            f.initRevealed();
        }

    }
});

var FadeProd = Class.create(FadeList, {
    afterCall : function(r){
        var sub = this.target.down('.second_level:last-child');
        sub.hide();
        this.options.prev.fade({
            duration:.4,
            afterFinish:function(){
                [this.target, this.container].invoke('morph', {
                    height: sub.getHeight()+'px'
                },{
                    duration:.8
                });
                sub.appear({
                    queue:'end',
                    duration: .4,
                    afterFinish:function(){
                        this.loader.fade();
                    }.bind(this)
                });
            }.bind(this)
        });
        sub.select('.wayback').invoke('observe', 'click', this.cleanup.bind(this));
       //SWFAddress.setValue(r);
    },
    close : function($super, ev){
        ev.stop();
        var subs = this.target.down('.second_level:last-child');
        [this.target, this.container].invoke('morph', {
            height:this.options.prev.getHeight()+'px'
        });
        subs.fade({
            duration:.4,
            afterFinish:function(){
                subs.remove();
            }
        });
        this.options.prev.appear({
            duration:.4,
            queue:'end'
        });
        this.active = false;
    },
    cleanup : function(ev){
        this.options.cleanup(ev);
    },
    initRevealed : function(){
        var panel = this.target.down('.second_level:last-child');
        panel.select('.back').invoke('observe', 'click', this.close.bind(this));
        panel.select('.wayback').invoke('observe','click', this.cleanup.bind(this));
    },
    initCatRevealed : function(){}
});

document.observe('dom:loaded', function(){
    // preload images
    searchimage = new Image();
    searchimage.src = "/img/buttons/btn_search_on.gif";
	
	
    //categories
    $$('.category').each(function(el){
        var s = new Section(el, el.select('.category_head', 'a.toggle'), el.down('.content'), el.hasClassName("active"));
    	
        //top nav
        var btn = $('nav_'+el.readAttribute('id')).observe('click', function(e){
            s.open.call(s, e);
        });
        el.observe('section:clicked', function(e){
            
            var type = {
                "dietary": "DS",
                "otc": "OTC",
                "rx": "Rx"
            };
            //SWFAddress.setValue("/products/"+type[el.readAttribute('id')]);
            btn.addClassName('active').adjacent('.active').invoke('removeClassName', 'active');
        });
        document.observe("open:all", function(e){
            s.open(e, true);
        });
    });
    //open all
    $('nav_all').observe('click', function(e){
        e.stop();
        document.fire('open:all');
        e.element().up('li').addClassName('active').adjacent('.active').invoke('removeClassName', 'active');
    });

    //search
    var search_box = $('content_search').down('.text');
    Event.observe(search_box, 'focus', function() {
        search_box.addClassName("active");
        search_box.value = '';
    });
    Event.observe(search_box, 'blur', function() {
        if(search_box.value == '')
            search_box.value = 'Enter keyword or cpc code';
        search_box.removeClassName("active");
    });	
	

	
    try {
        document.execCommand('BackgroundImageCache', false, true);
    } catch(e) {}
});
