document.observe("dom:loaded", function() {
    // wrappers for sliding doors on the text inputs
    $$('input.input-text').each(function(item) {
        if(item.hasClassName('qty') == false && item.identify() != 'search' && item.getStyle('display') != 'none' && $(item.parentNode).hasClassName('input-text-wrap') == false && item.hasClassName('cvv') == false) {
            item.wrap(new Element('div').addClassName('input-text-wrap'));
        }
    });

    // click classes for the top-cart
    // $$('.top-cart')[0].observe('click', function(event) {
    //     if(this.hasClassName('over'))
    //         this.removeClassName('over');
    //     else
    //         this.addClassName('over');
    // });

    // hover classes for the top-cart
    if ($$('.top-cart')[0]){
        $$('.top-cart')[0].observe('mouseover', function(event) {
            this.addClassName('over');
        });
    
        $$('.top-cart')[0].observe('mouseout', function(event) {
            this.removeClassName('over');
        });
    }
    //so you can hover over the checkout button
    if($$('#customer_actions .checkout a').last()){
        $$('#customer_actions .checkout a').last().setStyle({position:'relative', zIndex:'9999'});
    }
    // add special class for the top container
    if($$('.top-container')[0]) {
        $$('.menu-container')[0].addClassName('widget-present');
    }

    // put unique classes on level 0 menus
    $$('#menu li.level0 > a > span').each(function(item) {
        if(item.innerHTML == 'A-Z') {
            $(item.parentNode.parentNode).addClassName('az-menu');
        } else {
            $(item.parentNode.parentNode).addClassName(item.innerHTML.toLowerCase() + ' expandable');
        }
    });
    // class the top level spans to avoid direct descendant selectors that IE doesn't like
    $$('#menu li.level0 > a > span').invoke('addClassName', 'level0');

    // position the items in the az-menu and setup the alphabet sprite
/*
    var x = y = col = row = 0;
    var lastItem = null;
    var xOffset = 35;
    var yOffset = 30;
    var xPad = parseInt($$('#menu .az-menu > ul')[0].getStyle('paddingLeft').split('px')[0]);
    var yPad = parseInt($$('#menu .az-menu > ul')[0].getStyle('paddingTop').split('px')[0]);
    $$('#menu li.az-menu li.level1 > a > span').each(function(item, index) {
        $(item.parentNode.parentNode).addClassName('item-' + item.innerHTML.toLowerCase());

        y = yPad + (row * yOffset);
        x = xPad + (col * xOffset) + 4;

        if(row % 2 == 0 || row == 5) {
            x += xOffset / 2;
        }

        var style = {
            top: y + 'px',
            left: x + 'px',
            position: 'absolute'
        };
        item.parentNode.parentNode.setStyle(style);

        col++;
        if((row % 2 == 0 && col == 4) || (row % 2 != 0 && col == 5)) {
            col = 0;
            row++;
        }

        lastItem = item.parentNode.parentNode;
    });

    $$('#menu .az-menu > ul')[0].setStyle({
        height: y + lastItem.getHeight() + yPad * 2 + 'px',
        width: x + (xOffset / 2) + lastItem.getWidth() + xPad * 2 + 'px'
    });
*/

    // position the items in the expandable menus
    $$('#menu .expandable ul, #menu .az-menu ul ul').each(function(item) {
        var x = y = col = row = 0;
        var lastItem = null;
        var yOffset = 30; //parseInt(item.immediateDescendants()[0].getHeight()); ### We can't do this here for positioning reasons
        var xOffset = 0;
        var xPad = 10; //parseInt(item.getStyle('paddingLeft').split('px')[0]); ### For the sake of efficiecy
        var yPad = 10; //parseInt(item.getStyle('paddingTop').split('px')[0]); ### For the sake of efficiency
        var childCount = item.immediateDescendants().size();
        var colCount = 1;
        var rowItemCount = 0;

        // case code for the categories fly-out
        if ($(item.parentNode).hasClassName('category')) {
            childCount -= 1;
        }

        if(childCount > 10 && childCount < 21) {
            colCount = 2;
            item.addClassName('two-col');
        }

        if(childCount > 20) {
            colCount = 3;
            item.addClassName('three-col');
        }

        xOffset = 225;

        // add to the height for fly-outs that have header items
        if (item.hasClassName('has-header')) {
            //yPad += 26;
            item.parentNode.addClassName('has-header');
        }

        // item.immediateDescendants().each(function(item) {
        //  if(xOffset < item.getWidth())
        //      xOffset = item.getWidth();
        // });

        // ### We could do this, but won't for efficiency, if we need padding, hard code the values here
        // var cellWidth = xOffset - parseInt(item.firstDescendant().getStyle('paddingLeft').split('px')[0]) - parseInt(item.firstDescendant().getStyle('paddingRight').split('px')[0]);
        var cellWidth = xOffset;
        
        item.immediateDescendants().each(function(item, index) {
            // don't position the footer and header items
            if (item.hasClassName('footer-item') || item.hasClassName('header-item')) {
                return;
            }

            if(row == rowItemCount) {
                row = 0;
                col++;
                rowItemCount = (childCount - (childCount % colCount)) / colCount + (col <= childCount % colCount ? 1 : 0);

            }
            row++;

            y = yPad + (row * yOffset) - yOffset;
            x = xPad + (col * xOffset) - xOffset;

            var style = {
                top: y + 'px',
                left: x + 'px',
                position: 'absolute',
                width: cellWidth + 'px'
            };
            item.setStyle(style);

            lastItem = item;
        });

        if(colCount > 1) {
            item.insert(new Element('li').addClassName('v-bar bar-one'));
        }

        if(colCount > 2) {
            item.insert(new Element('li').addClassName('v-bar bar-two'));
        }

        var ulHeight = ((childCount - (childCount % colCount)) / colCount + (childCount % colCount != 0 ? 1 : 0)) * yOffset + yPad * 2;

        // special case for those fly-outs that have footer items
        if (item.hasClassName('has-footer')) {
            ulHeight += yOffset - 8;
            item.parentNode.addClassName('has-footer');
        }

        // add special class if both header footer are present
        if (item.hasClassName('has-footer') && item.hasClassName('has-header')) {
            item.parentNode.addClassName('has-footer-and-header');
        }

        item.setStyle({
            height: ulHeight + 'px',
            width: colCount * xOffset + 'px'
        });
    });

    // create the wrappers needed for background images
    $$('#menu ul').each(function(item) {
        if(typeof BrowserIsIE6=="boolean") {
            item.wrap('div', {style: 'display: none;'}).addClassName('wrap');
        } else {
            item.wrap('div').addClassName('wrap-eight')
                .wrap('div').addClassName('wrap-seven')
                .wrap('div').addClassName('wrap-six')
                .wrap('div').addClassName('wrap-five')
                .wrap('div').addClassName('wrap-four')
                .wrap('div').addClassName('wrap-three')
                .wrap('div').addClassName('wrap-two')
                .wrap('div', {style: 'display: none; width: ' + (parseInt(item.getStyle('width').split('px')[0]) + parseInt(item.getStyle('paddingLeft').split('px')[0]) * 2 + 1) + 'px;'})
                .addClassName('wrap');
        }
    });
    
    $$('#menu li.expandable').each(function(item) {
        if (item.hasClassName('has-header')) {
            header = item.firstDescendant().next();
            footer = item.childElements().last();
            wrapper = item.select('div.wrap-eight');

            list = item.select('ul')[0];
            listItem = list.wrap('div');
            listItem.addClassName('nav-content-wrapper');
            list.setStyle({background: 'none'});
            
            content = item.select('div.nav-content-wrapper')[0];
            content.insert({top: header});
            //content.insert({bottom: footer});
            content.firstDescendant().setStyle({display: 'block'});
            //content.childElements.last().setStyle({display: 'block'})
        }
        if (item.hasClassName('has-footer')) {
            footer = item.childElements().last();
            wrapper = item.select('div.wrap-eight');
        
            list = item.select('ul')[0];
            listItem = list.wrap('div');
            listItem.addClassName('nav-content-wrapper');
            list.setStyle({background: 'none'});
            
            content = item.select('div.nav-content-wrapper').last();
            content.insert({bottom: footer});
            // content.firstDescendant().setStyle({display: 'block'});
            // content.childElements.last().setStyle({display: 'block'})
        }
        
    });

    // finally show the menus
    $$('#menu > li').invoke('setStyle', {display: 'block'});

    // category page hover states
    $$('.category-products li.item').invoke('observe', 'mouseover', function(event) {
        this.addClassName('over');
    })
    .invoke('observe', 'mouseout', function(event) {
        this.removeClassName('over');
    });

    // we need these wrappers on sidebar blocks to implement the protruding shadows
    $$('.sidebar > .block .block-content').each(function(item) {
        item.wrap(new Element('div').addClassName('block-content-wrap'));
    });

    // add custom password validation class
    Validation.add('validate-password-short', 'Please enter a valid password. Leading or trailing spaces will be ignored.', function(v) {
        var pass=v.strip(); /*strip leading and trailing spaces*/
        return !(pass.length>0 && pass.length < 2);
    });
    
    
    if($$('form').length > 1) {
        $$('form')[1].focusFirstElement();
    } else if ($('search')) {
        $('search').focus();
        $('search').value = "Search by Keyword or Catalog #";

        $('search').observe('keypress', function() {
            if ($('search').getValue() == "Search by Keyword or Catalog #") {
                $('search').clear();
            }
        });
    }
    
    if (jQuery('title=Shipping Policy')) {
        link = jQuery('[title=Shipping Policy]').attr('href');
        jQuery('[title=Shipping Policy]').attr('href', link + "-lightbox");
        jQuery('[title=Shipping Policy]').colorbox({width:"90%", height:"90%", maxWidth:"900px", maxHeight:"800px", iframe:true});
    }
    
    if (jQuery('.reward-points-link')) {
        link = jQuery('.reward-points-link').attr('href');
        jQuery('.reward-points-link').attr('href', link + "-lightbox");
        jQuery('.reward-points-link').colorbox({width:"90%", height:"90%", maxWidth:"900px", maxHeight:"800px", iframe:true});
    }
    
});

function showWidgetBanner() {
    if ($('widget_banner_closed').getStyle('display') != 'none') {
        $('widget_banner_closed').slideUp({duration: 0.6});
    }
    setTimeout("$$('.widget-banner')[0].slideDown({duration: 0.6})", 500);
}

function hideWidgetBanner() {
    $$('.widget-banner')[0].slideUp({duration: 0.6});
    setTimeout("$('widget_banner_closed').slideDown({duration: 0.6})", 500);
}

function toggleMenu(el, over) {
    var validClasses = ['az-menu', 'category', 'condition', 'brand', 'guides', 'specials'];
    var classNames = el.classNames();
    var menuClass = 'over';

    classNames.each(function(item, index) {
       if (validClasses.any(function(cName) { return cName == item; })) {
           menuClass = item + '-over';
       }
    });

    if (over) {
        $(el).addClassName(menuClass)
            .immediateDescendants()[1]
            .addClassName('active')
            .show();
    }
    else {
        $(el).removeClassName(menuClass)
            .immediateDescendants()[1]
            .removeClassName('active')
            .hide();
    }
}

function collateralReadMore(event) {
    if (this.hasClassName('expanded')) {
        this.removeClassName('expanded')
        $('collateral-tabs').morph('height: 400px;');
        $$('#collateral-tabs .tab-container, #collateral-tabs .tab-container .tab-content').invoke('morph', 'height: 360px;');
    } else {
        contentHeight = parseInt($('collateral-tabs').parentNode.identify().split('collateral_height_')[1]);

        this.addClassName('expanded')
        $('collateral-tabs').morph('height: ' + (contentHeight + 40) + 'px;');
        $$('#collateral-tabs .tab-container, #collateral-tabs .tab-container .tab-content').invoke('morph', 'height: ' + contentHeight + 'px;');
    }

    event.stop();
}

Enterprise.CLSTabs = Class.create();
Object.extend(Enterprise.CLSTabs.prototype, {
    initialize: function (container) {
        this.container = $(container);
        this.container.addClassName('tab-list');
        this.tabs = this.container.select('dt.tab');
        this.activeTab = this.tabs.first();
        this.tabs.first().addClassName('first');
        this.tabs.last().addClassName('last');
        this.onTabClick = this.handleTabClick.bindAsEventListener(this);
        for (var i = 0, l = this.tabs.length; i < l; i ++) {
            this.tabs[i].observe('click', this.onTabClick);
        }
        this.select();
    },
    handleTabClick: function (evt) {
        this.activeTab = Event.findElement(evt, 'dt');
        this.select();
    },
    select: function () {
        for (var i = 0, l = this.tabs.length; i < l; i ++) {
            if (this.tabs[i] == this.activeTab) {
                this.tabs[i].addClassName('active');
                this.tabs[i].style.zIndex = this.tabs.length + 2;
                // this.tabs[i].next('dd').show();
                new Effect.Appear (this.tabs[i].next('dd'), { duration:0.5 });
                this.tabs[i].parentNode.style.height=this.tabs[i].next('dd').getHeight() + 15 + 'px';

                // show the pager
                var pagerId = this.tabs[i].identify() + '_pager';
                if($(pagerId)) {
                    $(pagerId).show();
                }
                $$('.' + pagerId).invoke('show');
            } else {
                this.tabs[i].removeClassName('active');
                this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
                this.tabs[i].next('dd').hide();

                // hide the pager
                var pagerId = this.tabs[i].identify() + '_pager';
                if($(pagerId)) {
                    $(pagerId).hide();
                }
                $$('.' + pagerId).invoke('hide');
            }
        }
    }
});
