/**
 * 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) 2008 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 = 500;
        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);

		new Effect.Opacity(this.container.id, {to : 0, duration: 0});
    },

    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;
        }
		this.showCart();
    },

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

    showCart: function (timePeriod) {
		if($(this.elementHeader).hasClassName('expanded')){
			return;
		}
        Enterprise.TopCompare.hideCompare();
		this.container.style.display = 'block';
        new Effect.Opacity(this.container.id, {
			duration: 0.2,
			from: 0,
			to: 1,
            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 (typeof(this.container) !== 'undefined') {
            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;
                        effect.element.parentNode.up('.nav-bar').style.zIndex=2;
                        }
                    });
            }
            if (this.interval !== null) {
                clearTimeout(this.interval);
                this.interval = null;
            }
            $(this.elementHeader).removeClassName('expanded');
        }
    }
};

Enterprise.TopCompare = {
    initialize: function (container) {
        this.container = $(container);
        this.element = this.container.up(0);
        this.elementHeader = this.container.previous(0);
        this.intervalDuration = 500;
        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);

		new Effect.Opacity(this.container.id, {to : 0, duration: 0});
    },

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

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

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

    showCompare: function (timePeriod) {
		if($(this.elementHeader).hasClassName('expanded')){
			return;
		}
        Enterprise.TopCart.hideCart();
        this.container.parentNode.style.zIndex = 992;
		this.container.style.display = 'block';
		new Effect.Opacity(this.container.id, {
			duration: 0.2,
			from: 0,
			to: 1,
			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.hideCompare.bind(this), this.timePeriod);
        }
    },

    hideCompare: function () {

        if (!$(this.container.id).hasClassName('process') && $(this.elementHeader).hasClassName('expanded')) {
			new Effect.Opacity(this.container.id, {
				duration: 0.2,
				from: 1,
				to: 0,
                beforeStart: function(effect) {$( effect.element.id ).addClassName('process');},
                afterFinish: function(effect) {
                    effect.element.style.display = 'none';
                    $( 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');
     },
     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);
             if(typeof(fixPoptionsHeight) !== "undefined"){
                 fixPoptionsHeight();
             }
         }
         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: -939, 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: 939, 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.summaryContainer = this.summary.up(0);
        this.doNotCheck = false;
        this.summaryStartY = this.summary.positionedOffset().top;
        this.summaryStartY = 61;
        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.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';
            } else {
                this.tabs[i].removeClassName('active');
                this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
                this.tabs[i].next('dd').hide();
            }
        }
    }
});

Enterprise.ColTabs = Class.create();
Object.extend(Enterprise.ColTabs.prototype, {
    initialize: function (container) {
        this.container = $(container);
        this.tabs = this.container.select('li.tab');
        this.activeTab = this.tabs.first();
        this.tabs.first().addClassName('first');
        this.tabs.last().addClassName('last');
        for (var i = 0, l = this.tabs.length; i < l; i ++) {
            this.tabs[i].observe('click', this.handleTabClick.bindAsEventListener(this, this.tabs[i].id));
        }
        this.select();
    },
    handleTabClick: function (evt,tId) {
        this.activeTab = $(tId);
        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');
            } else {
                this.tabs[i].removeClassName('active');
                $(this.tabs[i].id+'-cont').hide();
            }
            new Effect.Appear ($(this.activeTab.id+'-cont'), { duration:0.5 });
        }
    }
});


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, {
            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, {
                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);
}

Enterprise.productPopUpMenu = Class.create();
Object.extend(Enterprise.productPopUpMenu.prototype, {
     initialize: function () {
        $$('.list-product-options').each(function(menuItem){
            var _this = this;
            menuItem.hover(
                function() {
                    _this.reset();
                    _this.show(menuItem);
                },
                function() {
                    _this.hide(menuItem);
                },
                {
                    enterDelay: 0,
                    leaveDelay: 0
                }
            );
            //Event.observe(element, 'mouseover', this.show.bind(this,element));
            //Event.observe(element, 'mouseout', this.hide.bind(this,element));
        }.bind(this));
     },
     show: function (e) {
	 	//var elId = e.title;
        var elId = e.id.replace(/[A-Za-z]*/, '');
	 	if ($('product_options_box'+elId) && $('product_options_box_url'+elId)) {
			_drops = false;
            this.currentUrl = $('product_options_box_url'+elId).innerHTML;
			$('product_options_box_url'+elId).innerHTML = '';
            var area = 'product_options_box'+elId;
			if (this.currentUrl) {
				new Ajax.Updater(area, this.currentUrl, {
					evalScripts: true,
					method: 'get',
					onComplete: function(){
						new Varien.DropdownsMu('dropdown');
					},
					onFailure: function(){
						$('product_options_box_url'+elId).innerHTML = this.currentUrl;
					}
				});
			}
        }

        //this.reset();
        this.currentPopup = $('productPopup'+elId);
        this.currentImage = $('productImage'+elId);
        this.productPopupC = $('productPopupC'+elId);

        this.currentProductPopupCont = $('productPopupCont'+elId);
        this.currentPopup.style.zIndex='999';
        this.currentImage.style.zIndex='1000';
        this.currentProductPopupCont.addClassName('active');
        //new Effect.Appear(this.currentProductPopupCont, { durations:0.3 });
        if($('rollImage'+elId)){
            if(/MSIE (5\.5|6).+Win/.test(navigator.userAgent) ){
                if ($('rollImage'+elId).src == BLANK_IMG){
                    this.currentImage.down('img').style.filter = $('rollImage'+elId).style.filter;
                } else {
                    this.currentImage.down('img').style.filter = "none;"
                }
            }
            this.currentImage.down('img').src = $('rollImage'+elId).src;
        }
        if (typeof(this.currentPopup.initFunction) == "function") {
            this.currentPopup.initFunction();
        }
        if (fancyList) {
			for (var key in fancyList) {
				fancyList[key].refreshMargin();
			}

		}
     },
     hidePopUp: function (el) {
         el.removeClassName('active');
     },
     hide: function (e) {
        //var elId = e.title;
        var elId = e.id.replace(/[A-Za-z]*/, '');
        this.currentPopup = $('productPopup'+elId);
        this.currentImage = $('productImage'+elId);
        this.currentProductPopupCont = $('productPopupCont'+elId);
        this.currentPopup.style.zIndex=1;
        this.currentImage.style.zIndex=1;
        //setTimeout(this.hidePopUp.bind(this,$('productPopupCont'+elId)), 1000);
        if($('rollImageOrig'+elId)){
            if(/MSIE (5\.5|6).+Win/.test(navigator.userAgent) ){
                if ($('rollImageOrig'+elId).src == BLANK_IMG){
                    this.currentImage.down('img').style.filter = $('rollImageOrig'+elId).style.filter;
                } else {
                    this.currentImage.down('img').style.filter = "none;"
                }
            }
            this.currentImage.down('img').src = $('rollImageOrig'+elId).src;
        }
        this.currentProductPopupCont.removeClassName('active');
     },
     reset: function(){
         $$('.product-popup').each(function(pp){ pp.style.zIndex = '1'; });
         $$('.list-product-options').each(function(po){ po.removeClassName('active'); });
         $$('.product-image').each(function(im){
             im.setStyle({
                 zIndex:'1'
             });
         });
     }
});

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);
        if(marginSelect > 0){
        $('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.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));
        }
    },
    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();
            }
        }
        this.hideDDall();
    }
};

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);
                }
            }
        }
        //new Varien.DropdownsMu($('dd'+this.attrId).className);
        //e.addClassName('active');
        this.hideAllDD();
    },
    cleanSelected: function(){
        $$(this.elIdent).each(function(element){
            element.removeClassName('active');
        }.bind(this));
    }
};

function decorateCorners(force) {
    var corners = $$('.top-table-alt-top');
    var cornersRght = $$('.top-table-alt-rght');
    if(force){
        for(i=0;i<corners.length;i++){
            corners[i].down('div').setStyle({height: corners[i].offsetHeight+'px'});
            cornersRght[i].down('div').setStyle({height: (corners[i].offsetHeight - 4)+'px'});
        }
    }else{
        Event.observe(window, 'load', function() {
            for(i=0;i<corners.length;i++){
                corners[i].down('div').setStyle({height: corners[i].offsetHeight+'px'});
                cornersRght[i].down('div').setStyle({height: (corners[i].offsetHeight - 8)+'px'});
            }
        });
    }
}

function setLocationIE6(url){
    setTimeout(function()
    {
        window.location = url;
    }, 0);
}


// sliding left nav for WP pages
jQuery(document).ready( function($){
	$('#menu > li > a').click( function(){
		var ul = $(this).next('ul.children');
		
		if(ul.size() == 0){
			return true;
		}
		
		if(ul.is(':visible')){
			ul.slideUp(200);
			$(this).removeClass('open');
		}
		else{
			ul.slideDown(200);
			$(this).addClass('open');
		}
		return false;
	});
});

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(" "));
}();

