/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     enterprise_default
 * @copyright   Copyright (c) 2009 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

// Add validation hints
Validation.defaultOptions.immediate = true;
Validation.defaultOptions.addClassNameToContainer = true;

Event.observe(document, 'dom:loaded', function() {
    var inputs = $$('ul.options-list input');
    for (var i = 0, l = inputs.length; i < l; i ++) {
        inputs[i].addClassName('change-container-classname');
    }
})

if (!window.Enterprise) {
    window.Enterprise = {};
}
Enterprise.templatesPattern =  /(^|.|\r|\n)(\{\{(.*?)\}\})/;

Enterprise.TopCart= {
    initialize: function (container) {
        this.container = $(container);
        this.element = this.container.up(0);
        this.elementHeader = this.container.previous(0);
        this.intervalDuration = 4000;
        this.interval = null;
        this.onElementMouseOut = this.handleMouseOut.bindAsEventListener(this);
        this.onElementMouseOver = this.handleMouseOver.bindAsEventListener(this);
        this.onElementMouseClick = this.handleMouseClick.bindAsEventListener(this);

        this.element.observe('mouseout', this.onElementMouseOut);
        this.element.observe('mouseover', this.onElementMouseOver);
        this.elementHeader.observe('click', this.onElementMouseClick);

    },

    handleMouseOut: function (evt) {
        if($(this.elementHeader).hasClassName('expanded')) {
            this.interval = setTimeout(this.hideCart.bind(this), this.intervalDuration);
        }
    },

    handleMouseOver: function (evt) {
        if (this.interval !== null) {
             clearTimeout(this.interval);
             this.interval = null;
        }
    },

    handleMouseClick: function (evt) {
        if (!$(this.elementHeader).hasClassName('expanded') && !$(this.container.id).hasClassName('process') )  {
            this.showCart();
        }
        else {
            this.hideCart();
        }
    },

    showCart: function (timePeriod) {
        this.container.parentNode.style.zIndex=992;
        new Effect.SlideDown(this.container.id, {duration: 0.5,
            beforeStart: function(effect) {$( effect.element.id ).addClassName('process');},
            afterFinish: function(effect) {$( effect.element.id ).removeClassName('process');}
            });
        $(this.elementHeader).addClassName('expanded');
        if(timePeriod) {
            this.timePeriod = timePeriod*1000;
            this.interval = setTimeout(this.hideCart.bind(this), this.timePeriod);
        }
    },

    hideCart: function () {

        if (!$(this.container.id).hasClassName('process') && $(this.elementHeader).hasClassName('expanded')) {
            new Effect.SlideUp(this.container.id, {duration: 0.5,
                beforeStart: function(effect) {$( effect.element.id ).addClassName('process');},
                afterFinish: function(effect) {
                    $( effect.element.id ).removeClassName('process');
                    effect.element.parentNode.style.zIndex=1;
                    }
                });
        }
        if (this.interval !== null) {
            clearTimeout(this.interval);
            this.interval = null;
        }
        $(this.elementHeader).removeClassName('expanded');
    }
};


Enterprise.Bundle = {
     oldReloadPrice: false,
     initialize: function () {
        this.slider = $('bundleProduct');
        this.xOffset = $('bundle-product-wrapper').getDimensions().width;
     },
     swapReloadPrice: function () {
         Enterprise.Bundle.oldReloadPrice = Product.Bundle.prototype.reloadPrice;
         Product.Bundle.prototype.reloadPrice = Enterprise.Bundle.reloadPrice;
         Product.Bundle.prototype.selection = Enterprise.Bundle.selection;
     },
     reloadPrice: function () {
         var result = Enterprise.Bundle.oldReloadPrice.bind(this)();
         var priceContainer, duplicateContainer = null
         if (priceContainer = $('bundle-product-wrapper').down('.price-box .price-as-configured')) {
            if (duplicateContainer = $('bundle-product-wrapper').down('.duplicate-price-box .price-as-configured')) {
                duplicateContainer.down('.price').update(
                    priceContainer.down('.price').innerHTML
                );
            }
         }
         if (!this.summaryTemplate && $('bundle-summary-template')) {
             this.summaryTemplate = new Template($('bundle-summary-template').innerHTML, Enterprise.templatesPattern);
             this.optionTemplate = new Template($('bundle-summary-option-template').innerHTML, Enterprise.templatesPattern);
             this.optionMultiTemplate = new Template($('bundle-summary-option-multi-template').innerHTML, Enterprise.templatesPattern);
         }

         if (this.summaryTemplate && $('bundle-summary')) {
             var summaryHTML = '';
             for (var option in this.config.options) {
                if (typeof (this.config.selected[option]) !== 'undefined') {
                    var optionHTML = '';
                    for (var i = 0, l = this.config.selected[option].length; i < l; i ++) {
                        var selection = this.selection(option, this.config.selected[option][i]);
                        if (selection && this.config.options[option].isMulti) {
                            optionHTML += this.optionMultiTemplate.evaluate(selection);
                        } else if (selection) {
                            optionHTML += this.optionTemplate.evaluate(selection);
                        }
                    }

                    if (optionHTML.length > 0) {
                        summaryHTML += this.summaryTemplate.evaluate({label:this.config.options[option].title.escapeHTML(), options: optionHTML});
                    }
                }
             }

             $('bundle-summary').update(summaryHTML)
         }
         return result;
     },
     selection: function(optionId, selectionId) {
        if (selectionId == '' || selectionId == 'none') {
            return false;
        }
        var qty = null;
        if (this.config.options[optionId].selections[selectionId].customQty == 1 && !this.config['options'][optionId].isMulti) {
            if ($('bundle-option-' + optionId + '-qty-input')) {
                qty = $('bundle-option-' + optionId + '-qty-input').value;
            } else {
                qty = 1;
            }
        } else {
            qty = this.config.options[optionId].selections[selectionId].qty;
        }

        return {qty: qty, name: this.config.options[optionId].selections[selectionId].name.escapeHTML()};
     },
     start: function () {
        if (!$('bundle-product-wrapper').hasClassName('moving-now')) {
            new Effect.Move(this.slider, {
                x: -this.xOffset, y: 0, mode: 'relative', duration: 1.5,
                beforeStart: function (effect) {
                    $('bundle-product-wrapper').setStyle({height: $('productView').getHeight() + 'px'});
                    $('options-container').show();
                    Enterprise.BundleSummary.initialize();
                    $('bundle-product-wrapper').addClassName('moving-now');
                },
                afterFinish: function (effect) {
                    $('bundle-product-wrapper').setStyle({height: 'auto'});
                    $('productView').hide();
                    $('bundle-product-wrapper').removeClassName('moving-now');
                }
            });
         }
     },
     end: function () {
        if (!$('bundle-product-wrapper').hasClassName('moving-now')) {
            new Effect.Move(this.slider, {
                    x: this.xOffset, y: 0, mode: 'relative', duration: 1.5,
                    beforeStart: function (effect) {
                        $('bundle-product-wrapper').setStyle({height: $('options-container').getHeight() + 'px'});
                        $('productView').show();
                        $('bundle-product-wrapper').addClassName('moving-now');
                    },
                    afterFinish: function (effect) {
                        $('bundle-product-wrapper').setStyle({height: 'auto'});
                        $('options-container').hide();
                        Enterprise.BundleSummary.exitSummary();
                        $('bundle-product-wrapper').removeClassName('moving-now');
                    }
                });
        }
     }
};

Enterprise.BundleSummary = {
    initialize: function () {
        this.summary = $('bundleSummary');
        this.summaryOffsetTop = $('customizeTitle').getDimensions().height;
        this.summary.setStyle({top:this.summaryOffsetTop + "px"});
        this.summaryContainer = this.summary.up(0);
        this.doNotCheck = false;
        this.summaryStartY = this.summary.positionedOffset().top;
        this.summaryStartY = this.summaryOffsetTop;
        this.summaryStartX = this.summary.positionedOffset().left;
        this.onDocScroll = this.handleDocScroll.bindAsEventListener(this);
        this.GetScroll = setInterval(this.onDocScroll, 50);
        this.onEffectEnds = this.effectEnds.bind(this);
    },

    handleDocScroll: function () {
        if (this.currentOffsetTop == document.viewport.getScrollOffsets().top
            && (this.checkOffset(null) == null)) {
            return;
        } else {
            if (this.currentOffsetTop == document.viewport.getScrollOffsets().top) {
                this.doNotCheck = true;
            }
            this.currentOffsetTop = document.viewport.getScrollOffsets().top;
        }

        if (this.currentEffect) {
            this.currentEffect.cancel();
            var topOffset = 0;
            if (this.summaryContainer.viewportOffset().top < -60) {
               topOffset =  -(this.summaryContainer.viewportOffset().top);
            } else {
               topOffset = this.summaryStartY;
            }
            
            topOffset = this.checkOffset(topOffset);
            if (topOffset === null) {
                this.currentEffect = false;
                return;
            }
            
            this.currentEffect.start({
                x: this.summaryStartX,
                y: topOffset,
                mode: 'absolute',
                duration: 0.3,
                afterFinish: this.onEffectEnds
            });
            
            
            
            return;
        }

        
        this.currentEffect = new Effect.Move(this.summary);
    },
    
    effectEnds: function () {
        if (this.doNotCheck == true) {
            this.doNotCheck = false;
        }
    },
    
    checkOffset: function (offset) {
        if (this.doNotCheck && offset === null) {
            return null;
        }
        var dimensions = this.summary.getDimensions();
        var parentDimensions = this.summary.up().getDimensions();
        if ((offset !== null ? offset : this.summary.offsetTop) + dimensions.height >= parentDimensions.height) {
            offset = parentDimensions.height - dimensions.height;
        } else if (offset === null &&
            this.currentOffsetTop > (this.summaryContainer.viewportOffset().top) &&
            (this.currentOffsetTop - this.summaryContainer.viewportOffset().top) > this.summary.offsetTop) {
            offset = this.currentOffsetTop - this.summaryContainer.viewportOffset().top;
        }
        
        
        return offset;
    },

    exitSummary: function () {
        clearInterval(this.GetScroll);
    }
};

Enterprise.Tabs = Class.create();
Object.extend(Enterprise.Tabs.prototype, {
    initialize: function (container) {
        this.container = $(container);
        this.container.addClassName('tab-list');
        this.tabs = this.container.select('dt.tab');
        this.top = 25;
        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) {
                var height = 0;
                this.tabs[i].addClassName('active');
                Cufon.refresh('.cf');
                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});
                if(this.tabs[i].next('dd').getHeight()){
                    height = this.tabs[i].next('dd').getHeight();
                } else {
                    this.tabs[i].next('dd').childElements().each(function(elem){
                        height += elem.getHeight();
                    });
                }
                this.container.style.height= height + this.top + 'px';
            } else {
                this.tabs[i].removeClassName('active');
                Cufon.refresh('.cf');
                this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
                this.tabs[i].next('dd').hide();
            }
        }
    },
    tabFixing : function(){
            var parenttab = this.container.parentNode.parentNode,
            top = 0;
            if(parenttab.hasClassName("active")){
                this.container.style.height = "";
                top = this.container.getHeight();
            } else {
                parenttab.addClassName("active");
                this.container.style.height = "";
                top = this.container.getHeight();
                parenttab.removeClassName("active");
            }
            this.container.select("dd.tab-container").each(function(elem){
                elem.style.top = top + "px";
            });
            this.top = top;
    },
    fixHeight : function(f){
        var height = 0;
        if(this.activeTab.next('dd').getHeight()){
            height = this.activeTab.next('dd').getHeight();
        } else {
            this.activeTab.next('dd').childElements().each(function(elem){
                height += elem.getHeight();
            });
        }
        this.container.style.height= height + this.top + 'px';
    }
});

Enterprise.ProductTabs = Class.create();
Object.extend(Enterprise.ProductTabs.prototype, {
    initialize: function (container,content,anchor) {
        this.container = $(container);
        this.content = $(content);
        this.tabs = this.container.select('li.tab');
        this.contentTabs = this.content.select('li.content');
        this.activeTab = this.tabs.first();
        if(parseUri(window.location).anchor == anchor) this.activeTab = this.tabs[2];
        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) {
        evt.stop();
        this.activeTab = Event.findElement(evt, 'li');
        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.contentTabs[i].addClassName('active');
                Cufon.refresh('.cf-link');
                this.tabs[i].style.zIndex = this.tabs.length + 2;
            } else {
                this.tabs[i].removeClassName('active');
                this.contentTabs[i].removeClassName('active');
                Cufon.refresh('.cf-link');
                this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
            }
        }
        if(window.tabs){
            window.tabs.tabFixing();
            window.tabs.fixHeight("force");
        }
    }
});


Enterprise.Slider = Class.create();

Object.extend(Enterprise.Slider.prototype, {
    initialize: function (container, config) {
        this.container = $(container);
        this.config = {
            panelCss: 'slider-panel',
            sliderCss: 'slider',
            itemCss: 'slider-item',
            slideButtonCss: 'slide-button',
            slideButtonInactiveCss: 'inactive',
            forwardButtonCss: 'forward',
            backwardButtonCss: 'backward',
            pageSize: 6,
            scrollSize: 2,
            slideDuration: 1.0,
            slideDirection: 'horizontal',
            fadeEffect: true
        };

        Object.extend(this.config, config || {});

        this.items = this.container.select('.' + this.config.itemCss);
        this.isPlaying = false;
        this.isAbsolutized = false;
        this.offset = 0;
        this.onClick = this.handleClick.bindAsEventListener(this);
        this.sliderPanel = this.container.down('.' + this.config.panelCss);
        this.slider =  this.sliderPanel.down('.' + this.config.sliderCss);
        this.container.select('.' + this.config.slideButtonCss).each(
            this.initializeHandlers.bind(this)
        );
        this.updateButtons();
        
        Event.observe(window, 'load', this.initializeDimensions.bind(this));
    },
    initializeHandlers: function (element) {
        if (element.hasClassName(this.config.forwardButtonCss) ||
            element.hasClassName(this.config.backwardButtonCss)) {
            element.observe('click', this.onClick);
        }
    },
    handleClick: function (evt) {
        var element = Event.element(evt);
        if (!element.hasClassName(this.config.slideButtonCss)) {
            element = element.up('.' + this.config.slideButtonCss);
        }

        if (!element.hasClassName(this.config.slideButtonInactiveCss)) {
           element.hasClassName(this.config.forwardButtonCss) || this.backward();
           element.hasClassName(this.config.backwardButtonCss) || this.forward();
        }
        Event.stop(evt);
    },
    updateButtons: function () {
        var buttons = this.container.select('.' + this.config.slideButtonCss);
        for (var i = 0, l = buttons.length; i < l; i++) {
            if (buttons[i].hasClassName(this.config.backwardButtonCss)) {
                if (this.offset <= 0) {
                    buttons[i].addClassName(this.config.slideButtonInactiveCss);
                }
                else {
                    buttons[i].removeClassName(this.config.slideButtonInactiveCss);
                }
            }else if (buttons[i].hasClassName(this.config.forwardButtonCss)) {
                if (this.offset >= this.items.length - this.config.pageSize) {
                    buttons[i].addClassName(this.config.slideButtonInactiveCss);
                }
                else {
                    buttons[i].removeClassName(this.config.slideButtonInactiveCss);
                }
            }
        }
    },
    initializeDimensions: function () {
        if ((this.config.slideDirection == 'horizontal' && this.sliderPanel.style.width) ||
            (this.config.slideDirection != 'horizontal' && this.sliderPanel.style.height)) {
            return this;
        }
        var firstItem = this.items.first();
        var offset = 0;
        if (this.config.slideDirection == 'horizontal') {
            offset = (parseInt(firstItem.getStyle('margin-left')) + parseInt(firstItem.getStyle('margin-right'))) * (this.config.pageSize - 1);
            this.sliderPanel.setStyle({width: (firstItem.getDimensions().width * this.config.pageSize + offset) + 'px'});
        } else {
            offset = (parseInt(firstItem.getStyle('margin-bottom')) + parseInt(firstItem.getStyle('margin-top'))) * (this.config.pageSize - 1);
            this.sliderPanel.setStyle({height: (firstItem.getDimensions().height * this.config.pageSize + offset) + 'px'});
        }
        
        var dimensions = this.sliderPanel.getDimensions();
        
        var sliderParent = this.sliderPanel.up();
        /*
        dimensions.height += parseInt(sliderParent.getStyle('padding-top'));
        dimensions.height += parseInt(sliderParent.getStyle('padding-bottom'));
        dimensions.width += parseInt(sliderParent.getStyle('padding-left'));
        dimensions.width += parseInt(sliderParent.getStyle('padding-right'));
    
        if (sliderParent.down('.slide-button')) {
            var buttonDimensions = sliderParent.down('.slide-button').getDimensions();
            if (this.config.slideDirection == 'horizontal') {
                dimensions.width += 2 * buttonDimensions.width;
            } else {
                dimensions.height += 2 * buttonDimensions.height;
            }
        }
        */
        sliderParent.setStyle({
            width: dimensions.width + 'px',
            height: dimensions.height + 'px'
        });
        return this;
    },
    absolutize: function () {
        if (!this.isAbsolutized) {
            this.isAbsolutized = true;
            var dimensions = this.sliderPanel.getDimensions();
            this.sliderPanel.setStyle({
                height: dimensions.height + 'px',
                width: dimensions.width + 'px'
            });
            
            this.slider.absolutize();
        }
    },
    
    forward: function () {
        if (this.offset + this.config.pageSize <= this.items.length - 1) {
            this.slide(true);
        }
    },
    backward: function () {
        if (this.offset > 0) {
            this.slide(false);
        }
    },
    slide: function (isForward) {

        if (this.isPlaying) {
            return;
        }
        this.absolutize();
        this.effectConfig = {
            duration: this.config.slideDuration
        };
        if (this.config.slideDirection == 'horizontal') {
            this.effectConfig.x = this.getSlidePosition(isForward).left;
        } else {
            this.effectConfig.y = this.getSlidePosition(isForward).top;
        }
        this.start();

    },
    start: function ()
    {
        if (this.config.fadeEffect) {
            this.fadeIn();
        } else {
            this.move();
        }
    },
    fadeIn: function ()
    {
        new Effect.Fade(this.slider.up('div.slider-panel'), {
            from: 1.0,
            to:0.5,
            afterFinish: this.move.bind(this),
            beforeStart: this.effectStarts.bind(this),
            duration: 0.3
        });
    },
    fadeOut: function ()
    {
        new Effect.Fade(this.slider.up('div.slider-panel'), {
                from: 0.5,
                to:1.0,
                afterFinish: this.effectEnds.bind(this),
                duration: 0.3
        });
    },
    move: function ()
    {
        if (this.config.fadeEffect) {
            this.effectConfig.afterFinish = this.fadeOut.bind(this);
        } else {
            this.effectConfig.afterFinish = this.effectEnds.bind(this);
            this.effectConfig.beforeStart = this.effectStarts.bind(this);
        }

        new Effect.Move(this.slider, this.effectConfig);
    },
    effectStarts: function () {
        this.isPlaying = true;
    },
    effectEnds: function () {
        this.isPlaying = false;
        this.updateButtons();
    },
    getSlidePosition: function (isForward) {
        var targetOffset;
        if (isForward) {
            targetOffset = Math.min(this.items.length - this.config.pageSize, this.offset + this.config.scrollSize)
        }
        else {
            targetOffset = Math.max(this.offset - this.config.scrollSize, 0);
        }
        this.offset = targetOffset;
        var item = this.items[targetOffset];
        var itemOffset = {left:0, top:0};

        itemOffset.left = -(item.cumulativeOffset().left
                       -  this.slider.cumulativeOffset().left + this.slider.offsetLeft);
        itemOffset.top = -(item.cumulativeOffset().top
                       -  this.slider.cumulativeOffset().top + this.slider.offsetTop);
        return itemOffset;
    }
});

Enterprise.PopUpMenu = {
    currentPopUp: null,
    documentHandlerInitialized: false,
    popUpZIndex: 994,
    hideDelay: 2000,
    hideOnClick: true,
    hideInterval: null,
    //
    initializeDocumentHandler: function () {
        if (!this.documentHandlerInitialized) {
            this.documentHandlerInitialized = true;
            Event.observe(
                document.body,
                'click',
                this.handleDocumentClick.bindAsEventListener(this)
            );
        }
    },
    handleDocumentClick: function (evt) {
        if (this.currentPopUp !== null) {
            var element = Event.element(evt);
            if (!this.currentPopUp.onlyShowed && this.hideOnClick) {
                this.hide();
            } else {
                this.currentPopUp.onlyShowed = false;
            }
        }
    },
    handlePopUpOver: function (evt) {
        if (this.currentPopUp !== null) {
            this.currentPopUp.removeClassName('faded');
            this.resetTimeout(0);
        }
    },
    handlePopUpOut: function (evt) {
        if (this.currentPopUp !== null) {
            this.currentPopUp.addClassName('faded');
            this.resetTimeout(1);
        }
    },
    show: function (trigger) {
        this.initializeDocumentHandler();

        var container = $(trigger).up('.switch-wrapper');
        if (!$('popId-' + container.id)) {
            return;
        }

        if (this.currentPopUp !== null && $('popId-' + container.id) !== this.currentPopUp) {
            this.hide(true);
        } else if (this.currentPopUp !== null && this.currentPopUp === $('popId-' + container.id)) {
            this.hide();
            return;
        }

        this.currentPopUp = $('popId-' + container.id);
        this.currentPopUp.container = container;
        this.currentPopUp.container.oldZIndex = this.currentPopUp.container.style.zIndex;
        this.currentPopUp.container.style.zIndex = this.popUpZIndex;
        new Effect.Appear(this.currentPopUp, {duration:0.3});


        if (!this.currentPopUp.isHandled) {
            this.currentPopUp.observe('mouseover', this.handlePopUpOver.bindAsEventListener(this));
            this.currentPopUp.observe('mouseout', this.handlePopUpOut.bindAsEventListener(this));
            this.currentPopUp.isHandled = true;
        }
        this.currentPopUp.onlyShowed = true;
        this.currentPopUp.container.down('.switcher').addClassName('list-opened');
        this.resetTimeout(2);
    },
    hide: function () {
        if (this.currentPopUp !== null) {
            if (arguments.length == 0) {
                new Effect.Fade(this.currentPopUp, {duration: 0.3});
            } else {
                this.currentPopUp.hide();
            }
            this.currentPopUp.container.style.zIndex = this.currentPopUp.container.oldZIndex;
            this.resetTimeout(0);
            this.currentPopUp.container.down('.switcher').removeClassName('list-opened');
            this.currentPopUp = null;
        }
    },
    resetTimeout: function (delay) {
        if (this.hideTimeout !== null) {
            clearTimeout(this.hideTimeout);
            this.hideTimeout = null;
        }
        if (delay) {
            this.hideTimeout = setTimeout(
                this.hide.bind(this),
                this.hideDelay * delay
            );
        }
    }
};


function popUpMenu(element) {
   Enterprise.PopUpMenu.show(element);
}

function parseUri (str) {
    var    o   = parseUri.options,
        m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
        name:   "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};




Enterprise.selectDropdowns = Class.create();
Enterprise.selectDropdowns.prototype = {
    initialize: function(attr){
        var sd = this;
        $$(attr).each(function(element){
            if(element.title && $(element.title)){
                sd.selectfill($(element.title),element);
            }
        });
    },
    hideDDall: function() {
        $$('.ddlist').each(function(item){
            item.style.display = 'none';
        });
    },
    selectfill: function(sel,fancy){
        if(sel.options){
            var selectInner = '';
            var selectIndex = 0;
            for(i=0;i<sel.options.length;i++){
                if(sel.options[i].innerHTML != '' && sel.options[i].innerHTML != '&nbsp;' && sel.options[i].innerHTML != ' '){
                    if(i == 0) selectIndex = sel.options[i].innerHTML;
                    if(sel.options[i].selected == true){
                        selectInner += '<li><a href="javascript:void(0);" class="ddOption'+fancy.id+' active" rel="'+sel.options[i].value+'"">'+sel.options[i].innerHTML+'</a></li>';
                        selectIndex = sel.options[i].innerHTML;
                    }else{
                        selectInner += '<li><a href="javascript:void(0);" class="ddOption'+fancy.id+'" rel="'+sel.options[i].value+'"">'+sel.options[i].innerHTML+'</a></li>';
                    }
                }
            }
            $(fancy.id+'-list').innerHTML = selectInner;
            $(fancy.id+'-header-val').innerHTML = selectIndex;
            $$('.ddOption'+fancy.id).each(function(element){
                Event.observe(element, 'click', this.makeSelection.bind(this,element,sel.id,fancy.id))
            }.bind(this));
            this.fitContainers($(fancy.id+"-list").offsetWidth,fancy.offsetWidth,$(fancy.id+"-content"),fancy,$(fancy.id+"-opt"));
        }
    },
    makeSelection: function(arg,selId,ddId){
        for(i=0;i<$(selId).options.length;i++){
            if($(selId).options[i].value == arg.rel){
                $$('.ddOption'+ddId).each(function(element){
                    element.removeClassName('active');
                });
                $(selId).options[i].selected = "selected";
                $(ddId+'-header-val').innerHTML = $(selId).options[i].innerHTML;
                arg.addClassName('active');
                if(document.all){
                    $(selId).fireEvent("onchange");
                }else{
                    var evt = document.createEvent("HTMLEvents");
                    evt.initEvent("change", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    $(selId).dispatchEvent(evt);
                }
            }
        }
        if($('region_id')){
            if($('region_id').style.display == 'none'){
                $('regionSel').hide();
                $('regionCont').show();
            }else{
                $('regionSel').show();
                $('regionCont').hide();
            }
        }
        if($('billing:region_id')){
            if($('billing:region_id').style.display == 'none'){
                $('billing_regionSel').style.display = 'none';
                $('billing_regionCont').style.display = 'block';
            }else{
                $('billing_regionSel').style.display = 'block';
                $('billing_regionCont').style.display = 'none';
            }
        }
        if($('shipping:region_id')){
            if($('shipping:region_id').style.display == 'none'){
                $('shipping_regionSel').style.display = 'none';
                $('shipping_regionCont').style.display = 'block';
            }else{
                $('shipping_regionSel').style.display = 'block';
                $('shipping_regionCont').style.display = 'none';
            }
        }
        if($('region_id')){
            if($('region_id').style.display == 'none'){
                $('regionSel').style.display = 'none';
                $('regionCont').style.display = 'block';
            }else{
                $('regionSel').style.display = 'block';
                $('regionCont').style.display = 'none';
            }
        }
        this.fitContainers($(ddId+"-list").offsetWidth,$(ddId).offsetWidth,$(ddId+"-content"),$(ddId),$(ddId+"-opt"));
        this.hideDDall();
        new Varien.Dropdowns('dropdown');
        var selectDropdowns = new Enterprise.selectDropdowns('.select-dropdown');
    },

    fitContainers: function(cw,dw,c,dd,opt){
        //alert(cw+" :: "+dw+" :: "+opt.offsetWidth);
        var pw = dd.parentNode.offsetWidth;
        if( pw < dw && !dd.style.width){
            this.fixTitle(dd);
        }
        if(cw > dw){
            if(cw > pw){
                cw = pw;
            }
            dd.style.width = cw+'px';
            if(navigator.userAgent.indexOf("MSIE 6") > 0){
                dd.firstChild.style.width = (cw - 30)+"px";
            }
        }else{
            c.style.width = dw+'px';
        }
    },

    fixTitle: function(dd){
        setTimeout(function(){
            if(dd.getElementsByTagName("dt")[0] && dd.getElementsByTagName("dt")[0].getElementsByTagName("span")[0] ){
                var span = dd.getElementsByTagName("dt")[0].getElementsByTagName("span")[0],
                pw = dd.parentNode.offsetWidth,
                dw = dd.offsetWidth,
                str = span.innerHTML;
                span.title = str;
                while (pw < dw){
                    str = str.substr(0, str.length - 1);
                    span.removeChild(span.firstChild);
                    span.innerHTML = str + " ...";
                    pw = dd.parentNode.offsetWidth;
                    dw = dd.offsetWidth;
                }
            }
        },0)
    }
};

Enterprise.fancyOptionsMu = Class.create();
Enterprise.fancyOptionsMu.prototype = {
    initialize: function(elIdent,attrId,contWidth,productId,serialNumber){
        this.elIdent = elIdent;
        this.attrId = attrId;
        this.productId = productId;
        if (serialNumber != null && serialNumber != undefined && serialNumber != false) {
            this.serialNumber = serialNumber;
        } else {
            this.serialNumber = false;
        }
        this.contWidth = contWidth;
        var marginSelect = ((this.contWidth - $('dd'+this.attrId).offsetWidth)/2);
        $('dd'+this.attrId).style.marginLeft = marginSelect+'px';
        $('dd'+this.attrId).style.visibility = "visible";
        $$(this.elIdent).each(function(element){
            Event.observe(element, 'click', this.selOption.bind(this,element))
        }.bind(this));
    },
    hideAllDD: function(){
        $$('.ddlist').each(function(item){
            item.style.display = 'none';
        });
    },
    refreshMargin: function(){
        var marginSelect = ((this.contWidth - $('dd'+this.attrId).offsetWidth)/2);
        $('dd'+this.attrId).style.marginLeft = marginSelect+'px';
    },
    selOption: function(e){
        e = Element.extend(e);
        var selected = e.rel.split('_')[0];
        this.cleanSelected;
        var optionContainer = $('attribute'+this.attrId);
        var prId = e.rel.split('_')[1];
        var spId = 'spConfig'+this.productId;
        if (this.serialNumber != false) {
            spId += '_' + this.serialNumber;
        }
        if(selected == ''){
            eval(spId).fillSelect(optionContainer);
            eval(spId).configureElement(optionContainer);
        }
        if (prId != this.productId) {
            return;
        }
        if (this.serialNumber) {
            var serId = e.rel.split('_')[2];
            if (serId != this.serialNumber) {
                return;
            }
        }
        if(selected != ''){
            for(var j=0;j<optionContainer.options.length;j++){
                if(optionContainer.options[j].value == selected){
                    optionContainer.options[j].selected = selected;
                    eval(spId).configureElement(optionContainer);
                }
            }
        }
        this.hideAllDD();
    },
    cleanSelected: function(){
        $$(this.elIdent).each(function(element){
            element.removeClassName('active');
        }.bind(this));
    }
};

function goToUrl(url){
    if(url != '') document.location = url;
}

function toggleItem(item,dur){
    closeToggleItems('toggle-item',1);
    if(!dur) dur = 0.2; 
    var thisItem = $(item);
    var thisItemLnk = $(item+'-link');
    if(thisItem.style.display == 'none'){
        new Effect.BlindDown(thisItem, {duration:dur, afterFinish: function(){thisItem.style.height = ''}});
        if(thisItemLnk) thisItemLnk.addClassName('active');
    }else{
        new Effect.BlindUp(thisItem, {duration:dur, afterFinish: function(){thisItem.style.height = ''}});
        if(thisItemLnk) thisItemLnk.removeClassName('active');
    }
}
function closeToggleItem(item,force){
    var dur = 0.2; 
    var thisItem = $(item);
    var thisItemLnk = $(item+'-link');
    if(force){
        thisItem.style.display = 'none';
        thisItem.style.height = '';
    }else{
        new Effect.BlindUp(thisItem, {duration:dur, afterFinish: function(){thisItem.style.height = ''}});
    }
    if(thisItemLnk){
    	thisItemLnk.removeClassName('active');
    }
}

function closeToggleItems(clas,force){
    if(!force) force = 0;
    $$('.'+clas).each(function(i){
        closeToggleItem(i.id,force);
    });
}

Enterprise.ProductMedia = Class.create();
Enterprise.ProductMedia.prototype = {
    initialize: function(iconsClass,imageCont,zoomContainer,zoomImage,zoomButton,imageLoader,altContainer){
        this.icons = $$('.'+iconsClass);
        this.image = $(imageCont);
        this.zoomContainer = $(zoomContainer);
        this.zoomImage = $(zoomImage);
        this.zoomButton = $(zoomButton);
        this.imageLoader = $(imageLoader);
        this.icons.each(function(icon){
            Event.observe(icon, 'click', this.showImage.bind(this,icon))
        }.bind(this));
        Event.observe($('closeZoom'), 'click', this.hideZoom.bind(this));
        Event.observe(this.zoomButton, 'click', this.showZoom.bind(this));
        if((this.icons.length < 2) && $(altContainer)){
            $(altContainer).style.display = 'none';
        }
    },
    showImage: function(icon,evt){
        Event.stop(evt);
        if(icon.rel){
            this.image.innerHTML = '';
            this.zoomButton.style.display = 'none';
            this.imageLoader.style.display = 'block';
            var imagesAlt = explode('|',icon.rel);
            var newImage = new Image(450,450);
            newImage.src = imagesAlt[0];
            this.zoomImage.src = imagesAlt[1];
            var that = this;
            newImage.onload = function(){
                that.imageLoader.style.display = 'none';
                that.image.innerHTML = '<img src="'+newImage.src+'" width="450"/>';
                new Effect.Appear(newImage,{duration:0.5});
                new Effect.Appear(that.zoomButton,{duration:0.5});
            };
        }
    },
    showZoom: function(evt){
        Event.stop(evt);
        new Effect.BlindDown(this.zoomContainer,{duration:0.5});
    },
    hideZoom: function(evt){
        Event.stop(evt);
        new Effect.BlindUp(this.zoomContainer,{duration:0.5});
    }

};

Enterprise.ProductBuyOptions = Class.create();
Enterprise.ProductBuyOptions.prototype = {
    initialize: function(mainContainerSelector, popupContainerSelector){
        this.mainContainerSelector = mainContainerSelector;
        this.popupContainerSelector = popupContainerSelector;
        this.items = $$(this.mainContainerSelector);
        this.items.each(function(item){
            if(item.down(this.popupContainerSelector)){
                jQuery(item).hover(this.showPopup.bind(this,item,item.down(this.popupContainerSelector)), this.hidePopup.bind(this,item,item.down(this.popupContainerSelector)));
            }
        }.bind(this));
    },
    showPopup: function(item,popup,evt){
        popup.style.display = 'none';
        popup.style.visibility = 'visible';
        popup.down('.popup-inner').style.height = (item.offsetHeight-2)+'px';
        if(popup.down('dd.top')){
            popup.down('dd.top').style.height = (item.offsetHeight-52)+'px';
        }
        item.addClassName('active');
        popup.style.display = 'block';
        if(popup.down('dt.bot') && (navigator.userAgent.indexOf("MSIE 8") > 0) ){
            var tmp = popup.down('dt.bot');
            popup.down('dt.bot').remove();
            popup.down('dl').appendChild(tmp);
        }
        if(popup.down('dt.bot') && ((navigator.userAgent.indexOf("MSIE 7") > 0) || (navigator.userAgent.indexOf("MSIE 6") > 0)) ){
            item.parentNode.parentNode.parentNode.style.position = "relative";
            item.parentNode.parentNode.parentNode.style.zIndex = "990";
            item.parentNode.parentNode.parentNode.parentNode.parentNode.style.position = "relative";
            item.parentNode.parentNode.parentNode.parentNode.parentNode.style.zIndex = "990"
        }
    },
    hidePopup: function(item,popup,evt){
        item.removeClassName('active');
        popup.style.display = 'none';
        if(popup.down('dt.bot') && ((navigator.userAgent.indexOf("MSIE 7") > 0) || (navigator.userAgent.indexOf("MSIE 6") > 0)) ){
            item.parentNode.parentNode.parentNode.style.position = "";
            item.parentNode.parentNode.parentNode.style.zIndex = "";
            item.parentNode.parentNode.parentNode.parentNode.parentNode.style.position = "";
            item.parentNode.parentNode.parentNode.parentNode.parentNode.style.zIndex = ""
        }
    }
};

function explode( delimiter, string ) {
    var emptyArray = {0: ''};

    if ( arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    return string.toString().split ( delimiter.toString() );
}

Enterprise.fancyOptions = Class.create();
Enterprise.fancyOptions.prototype = {
    initialize: function(elIdent,attrId,contWidth){
        this.elIdent = elIdent;
        this.attrId = attrId;
        var marginSelect = ((contWidth - $('dd'+this.attrId).offsetWidth)/2);
        $('dd'+this.attrId).style.marginLeft = marginSelect+'px';
        $$(this.elIdent).each(function(element){
            Event.observe(element, 'click', this.selOption.bind(this,element))
        }.bind(this));
    },
    hideAllDD: function(){
        $$('.ddlist').each(function(item){
            item.style.display = 'none';
        });
    },
    selOption: function(e){
        var selected = e.rel;
        this.cleanSelected;
        var optionContainer = $('attribute'+this.attrId);
        if(selected == ''){
            spConfig.fillSelect(optionContainer);
            spConfig.configureElement(optionContainer);
        }else{
            for(i=0;i<optionContainer.options.length;i++){
                if(optionContainer.options[i].value == selected){
                    optionContainer.options[i].selected = selected;
                    spConfig.configureElement(optionContainer);
                }
            }
        }
        new Varien.Dropdowns($('dd'+this.attrId).className);
        //e.addClassName('active');
        this.hideAllDD();
    },
    cleanSelected: function(){
        $$(this.elIdent).each(function(element){
            element.removeClassName('active');
        }.bind(this));
    }
};

Enterprise.QuickAddToCart = Class.create();
Enterprise.QuickAddToCart.prototype = {
    initialize:function(mainContainerSelector,mainContainerPattern,popupContainerClass, popupContentSourceUrl){
        this.mainContainerSelector = mainContainerSelector;
        this.mainContainerPattern = mainContainerPattern;
        this.popupContentSourceUrl = popupContentSourceUrl;
        this.popupContainerClass = popupContainerClass;
        this.loadingClassName = "loading";
        this.loadedClassName = "loaded";
        this.dropObject;
        if($$(this.mainContainerSelector)){
            var items = $$(this.mainContainerSelector);
            for(var i=0;i<items.length;i++){
                jQuery(items[i]).hover(this.showPopup.bind(this,items[i]), this.hidePopup.bind(this,items[i]));
            }
        }
    },
        
    showPopup: function(item,evt){
        var content = '';
        var productId = this.getProductId(item);
        var categoryId = this.getCategoryId(item);
        if((this.getIsContentLoading(item) == false) && (this.getIsContentLoaded(item) == false)){
            this.getPopupContainer(item).addClassName(this.loadingClassName);
            var request = new Ajax.Request(
                    this.popupContentSourceUrl,
                    {method: 'get', asynchronous:true, onSuccess: this.addProductPopup.bind(this,item), onFailure: function(){}, parameters: {product_id:productId, category_id: categoryId}}
                );
        }
        this.dropObject = new Varien.DropdownsMu('dropdown');
    },
    hidePopup: function(item,evt){
        if (this.dropObject !== undefined){
            this.dropObject.hideDDall();
        }
    },
    
    getPopupContainer:function(item){
        var productId = this.getProductId(item);
        return item.select("div[class*="+this.popupContainerClass+productId+"]")[0];
    },
    
    getIsContentLoading: function(item){
        if(this.getPopupContainer(item).hasClassName(this.loadingClassName)){
            return true;
        }
        else{
            return false;
        }
    },

    getIsContentLoaded: function(item){
        if(this.getPopupContainer(item).hasClassName(this.loadedClassName)){
            return true;
        }
        else{
            return false;
        }
    },
    
    getProductId: function(element){
        var id = element.getAttribute('class') || element.className;
        id = id.replace(this.mainContainerPattern, '\$1');
        id = id.match(/[0-9]+/)[0];
        return id;
    },
    getCategoryId: function(element){
        var categoryValue = element.select('.main-container-category');
        if (categoryValue.length > 0) {
            categoryValue = categoryValue[0];
        }
        return categoryValue && typeof categoryValue != 'undefined'
            ? categoryValue.value
            : '';
    },
    addProductPopup: function(item,transport){
        var content = this.evalResponse(transport);
        if (content){
            var productId = this.getProductId(item);
            var popupContainer = this.getPopupContainer(item);
            popupContainer.addClassName(this.loadedClassName);
            popupContainer.removeClassName(this.loadingClassName);
            popupContainer.update(content);
            this.dropObject = new Varien.DropdownsMu('dropdown');
            Cufon.refresh('.cf-link-wh',
            			  '.presale-item'
            			  );
            popupContainer.style.height = (item.offsetHeight-2)+'px';

            
            if(popupContainer.down('dd.top')){
               popupContainer.down('dd.top').style.height = (item.offsetHeight-52)+'px';
            }
    }
    },
    evalResponse: function(transport){
        if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
        }
        return response;
    }
}


var mainNav = function() {

    var main = {
        obj_nav :   $(arguments[0]) || $("nav"),

        settings :  {
            show_delay      :   0,
            hide_delay      :   0,
            _ie6            :   /MSIE 6.+Win/.test(navigator.userAgent),
            _ie7            :   /MSIE 7.+Win/.test(navigator.userAgent)
        },

        init :  function(obj, level) {
            obj.lists = obj.childElements();
            obj.lists.each(function(el,ind){
                main.handlNavElement(el);
                if((main.settings._ie6 || main.settings._ie7) && level){
                    main.ieFixZIndex(el, ind, obj.lists.size());
                }
            });
            if(main.settings._ie6){
                //main.ieBgFix(obj);
            }
            if(main.settings._ie6 && !level){
                document.execCommand("BackgroundImageCache", false, true);
            }
        },

        handlNavElement :   function(list) {
            if(list !== undefined && list.tagName != "ins"){
                list.onmouseover = function(){
                    main.fireNavEvent(this,true);
                };
                list.onmouseout = function(){
                    main.fireNavEvent(this,false);
                };
                if(list.down("ul")){
                    main.init(list.down("ul"), true);
                }
            }
        },

        ieFixZIndex : function(el, i, l) {
            if(el.tagName.toString().toLowerCase().indexOf("iframe") == -1){
                el.style.zIndex = l - i;
            } else {
                el.onmouseover = "null";
                el.onmouseout = "null";
            }
        },

        ieBgFix : function(el){
            var sp = document.createElement("ins");
            sp.className = "iefix";
            el.insertBefore(sp, el.firstChild);
        },

        fireNavEvent :  function(elm,ev) {
            if(ev){
                elm.addClassName("over");
                elm.down("a").addClassName("over");
                if(elm.childElements()[1]){
                    var nextUl = elm.childElements()[1];
                    if(nextUl.hasClassName('level1') && !nextUl.bgSeted){
                        var bp = (0 - parseInt(908-(elm.down("a").offsetLeft+(elm.down("a").offsetWidth/2))));
                        if(main.settings._ie6 && nextUl.firstChild.tagName == "INS"){
                            nextUl.firstChild.style.left = bp + "px";
                        } else {
                            nextUl.style.backgroundPosition = bp+'px 0';
                        }
                        nextUl.bgSeted = true;
                    }
                    main.show(nextUl);
                }
            } else {
                elm.removeClassName("over");
                elm.down("a").removeClassName("over");
                if (elm.childElements()[1]) {
                    main.hide(elm.childElements()[1]);
                }
            }
        },

        show : function (sub_elm) {
            if (sub_elm.hide_time_id) {
                clearTimeout(sub_elm.hide_time_id);
            }
            sub_elm.show_time_id = setTimeout(function() {
                if (!sub_elm.hasClassName("shown-sub")) {
                    sub_elm.style.display='none';
                    sub_elm.addClassName("shown-sub");
                    new Effect.BlindDown(sub_elm, {duration:0.1,afterFinish:function(){sub_elm.style.height='50px';}});
                }
            }, main.settings.show_delay);
        },

        hide : function (sub_elm) {
            if (sub_elm.show_time_id) {
                clearTimeout(sub_elm.show_time_id);
            }
            sub_elm.hide_time_id = setTimeout(function(){
                if (sub_elm.hasClassName("shown-sub")) {
                    new Effect.BlindUp(sub_elm, {duration:0.1,afterFinish:function(){sub_elm.removeClassName("shown-sub")}});
                }
            }, main.settings.hide_delay);
        }

    };
    if (arguments[1]) {
        main.settings = Object.extend(main.settings, arguments[1]);
    }
    if (main.obj_nav) {
        main.init(main.obj_nav, false);
    }
};

document.observe("dom:loaded", function() {
    var del = ( /MSIE 6/.test(navigator.userAgent)) ? 200 : 100;
    mainNav("nav", {"show_delay":del,"hide_delay":del});
    mainNav("topnav", {"show_delay":del,"hide_delay":del});
    mainNav("topSubNav", {"show_delay":del,"hide_delay":del});
});



if(/MSIE [67]/.test(navigator.userAgent)){
    var intId = setInterval(function(){
        if(document && document.documentElement){
            clearInterval(intId);
            document.documentElement.style.visibility = "hidden";
        }
    },200)
    window.onload = function(){
        clearInterval(intId);
        document.documentElement.style.visibility = "visible";
        setTimeout(function(){
            document.documentElement.className = document.documentElement.className;
        }, 100)
    }
}

function refreshDropdowns(){
    new Varien.Dropdowns('dropdown');
    var selectDropdowns = new Enterprise.selectDropdowns('.select-dropdown');
}

BannerRotator = Class.create({
    initialize: function(id, delay ) {
        this.obj = $(id);
        this.delay  = delay ;
        this.array = this.obj.childElements();
        this.length = this.array.length;
        this.pos = 0;
        this.start();
    },
    hide: function(){
        var d = this.delay ,
        next = ((this.pos + 1) == this.length)? 0 : this.pos  + 1;
        afterfinish =  (function(){
            this.pos = (this.pos == this.length-1)? this.pos = 0 : ++this.pos,
            this.hide();
        }).bind(this);
        new Effect.Parallel([
            Effect.Fade(this.array[this.pos],{sync: true}),
            Effect.Appear(this.array[next],{sync: true})
        ],{
            duration: 1,
            delay : d,
            afterFinish :afterfinish
        });
       
    },
    start: function(){
        if(this.length == 1)
            return;
        for(var i = 1, l = this.length; l > i; i ++){
            this.array[i].hide();
        }
        Event.observe(window, 'load', this.hide.bind(this));
        
    }
});


BannerSwitcher = Class.create({
    initialize: function(container, banner_list, switcher_list ) {
        this.cont = $(container);
        this.b_list = $(banner_list);
        this.b_items = this.b_list.childElements();
        this.s_list = $(switcher_list);
        this.s_items = this.s_list.childElements();
        this.index = 0;
        this.animated = false;
        this.start();
    },
    change : function(idx){
        if(this.index == idx || this.animated)
            return
        this.animated = true;
        var afterfinish =  (function(){
            this.index = idx;
            this.animated = false;
        }).bind(this);
        new Effect.Parallel([
            Effect.Fade(this.b_items[this.index],{sync: true}),
            Effect.Appear(this.b_items[idx],{sync: true})
        ],{
            duration: 1,
            afterFinish :afterfinish
        });
    },
    refresh:function(){
        for(var _i = 0, _l = this.s_items.length; _l > _i; _i++ ){
            this.s_items[_i].style.visibility = "visible";
        }
        Cufon.replace('.b_switcher p');
    },
    start: function(){
        this.s_list.update();
        for(var i = 0, l = this.b_items.length; l > i; i++ ){
            var switcher = this.b_items[i].down("div.b_switcher");
            switcher = switcher.removeClassName("hidden").wrap('li');
            this.s_list.appendChild(switcher);
            if(i!=this.index){
                this.b_items[i].hide();
            }
        }
        this.s_items = this.s_list.childElements();
        for(var _i = 0, _l = this.s_items.length; _l > _i; _i++ ){
            this.s_items[_i].observe('click', this.change.bind(this,_i));
        }
        Event.observe(window, 'load', this.refresh.bind(this));

    }
});

var cssFix = function(){
  var u = navigator.userAgent.toLowerCase(),
  addClass = function(el,val){
    if(!el.className) {
      el.className = val;
    } else {
      var newCl = el.className;
      newCl+=(" "+val);
      el.className = newCl;
    }
  },
  is = function(t){return (u.indexOf(t)!=-1)};
  addClass(document.getElementsByTagName('html')[0],[
    (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
      :is('firefox/2')?'gecko ff2'
      :is('firefox/3')?'gecko ff3'
      :is('gecko/')?'gecko'
      :is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
      :is('konqueror')?'konqueror'
      :is('applewebkit/')?'webkit safari'
      :is('mozilla/')?'gecko':'',
    (is('x11')||is('linux'))?' linux'
      :is('mac')?' mac'
      :is('win')?' win':''
  ].join(" "));
}();

function topSearchToggle(itemClick,itemSlide,speedSlide) {
	$jQ(itemClick).click(function(){
			if($jQ(this).hasClass('active')){
				$jQ(this).removeClass('active');
				$jQ(itemSlide).slideUp(speedSlide);
				return false
			} else {
				$jQ(this).addClass('active');
				$jQ(itemSlide).slideDown(speedSlide);
				return false
			}
		});
	$jQ('.closeDiv a',itemSlide).click(function(){
		$jQ(itemClick).removeClass('active');
		$jQ(itemSlide).slideUp(speedSlide);
		return false
	});
}

function showTimes() {
	$jQ('.second:hidden').next('.seconds').hide();
	$jQ('.days:hidden').next('.day').hide();
}
