/**
 * 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
 */
if (!window.Enterprise) {
    window.Enterprise = {};
}
Enterprise.templatesPattern =  /(^|.|\r|\n)(\{\{(.*?)\}\})/;

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

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.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;
    }
});

(function () {

    var eventMatchers = {
        'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
        'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
    };
    var defaultOptions = {
        pointerX: 0,
        pointerY: 0,
        button: 0,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false,
        bubbles: true,
        cancelable: true,
        simulated: true
    };

    Event.simulate = function (element, eventName) {
        var options = Object.extend(defaultOptions, arguments[2] || {});
        var oEvent, eventType = null;

        element = $(element);

        for (var name in eventMatchers) {
            if (eventMatchers[name].test(eventName)) {
                eventType = name;
                break;
            }
        }

        if (!eventType) {
            throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
        }

        if (document.createEvent) {
            oEvent = document.createEvent(eventType);
            if (eventType == 'HTMLEvents') {
                oEvent.initEvent(eventName, options.bubbles, options.cancelable);
            }
            else {
                oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView, options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
            }
            element.dispatchEvent(oEvent);
        }
        else {
            options.clientX = options.pointerX;
            options.clientY = options.pointerY;
            oEvent = Object.extend(document.createEventObject(), options);
            element.fireEvent('on' + eventName, oEvent);
        }
        return element;
    };

    Element.addMethods({
        simulate: Event.simulate
    });
})();


Varien.inputDecorator = Class.create({
    initialize: function() {
        this.ie_6 = navigator.userAgent.indexOf('MSIE 6') > 0;
        this.ie_7 = navigator.userAgent.indexOf('MSIE 7') > 0;
        this.ie_8 = navigator.userAgent.indexOf('MSIE 8') > 0;
        this.web_kit = navigator.userAgent.indexOf('AppleWebKit') > 0;
        this.inputs_text  = $$('input[type=text],input[type=password]');
        this.textareas  = $$('textarea');
        this.inputs_check  = $$('input[type=checkbox].custom-checkbox');
        this.inputs_radio  = $$('input[type=radio]');
        this.selects  = $$('select.custom-select' , '.opc select:not([id$=_id])', '.account-create select:not([name$=_id])', '.my-account-page select:not([name$=_id])', '.saved-address select', '#billing-address #billing-address-select');
        //this.decorateTxt(this.inputs_text);
        //this.decorateTextArea(this.textareas);
        this.decorateChk(this.inputs_check);
        //this.decorateRadio(this.inputs_radio);
        this.decorateSelect(this.selects);
        document.observe('click', this.inputCustomCheck.bind(this));
        Ajax.Responders.register({onComplete:this.inputCustomCheck.bind(this)});
    },

    decorateTxt: function(elm) {
        for(var i = 0, l = elm.size(); i < l; i++){
            elm[i].wrap('span').addClassName('input-text-wrp-inner').wrap('span').addClassName('input-text-wrp');
            elm[i].decorated =  elm[i].parentNode.parentNode;
            if(elm[i].style.display){
                elm[i].decorated.style.display = elm[i].style.display;
            }
        }
    },

    decorateTextArea: function(elm) {
        for(var i = 0, l = elm.size(); i < l; i++){
            // The wrap property is reserved on textareas as a proprietary extension to HTML in MSIE
            Element.wrap(elm[i],'span').addClassName('textarea-wrp-bl').
                wrap('span').addClassName('textarea-wrp-br').
                wrap('span').addClassName('textarea-wrp-tr').
                wrap('span').addClassName('textarea-wrp-tl');
            elm[i].decorated =  elm[i].parentNode.parentNode.parentNode.parentNode;
            if(elm[i].style.display){
                elm[i].decorated.style.display = elm[i].style.display;
            }
        }
    },

    decorateChk: function(elm) {
        for(var i = 0, l = elm.size(); i < l; i++){
            elm[i].wrap('span').addClassName('input-check-state').wrap('span').addClassName('input-check-wrp');
            elm[i].decorated =  elm[i].parentNode.parentNode;
            if(elm[i].checked){
                elm[i].parentNode.parentNode.addClassName('checked');
            }
            if(elm[i].style.display){
                elm[i].decorated.style.display = elm[i].style.display;
            }
            var ie = this.ie_6 || this.ie_7 || this.ie_8;
            elm[i].decorated.observe('click', function(event){
                var chk = this.down('input');
                if(event.target.tagName == "INPUT"){
                    chk = event.target;
                    event.stopPropagation();
                    chk.blur();
                    chk.focus();
                    return;
                } else if(ie) {
                    if(chk.checked){
                        chk.checked = false;
                    } else {
                        chk.checked = true;
                    }
                }
                Event.stop(event);
                chk.simulate('click');
                chk.simulate('change');
            });
            elm[i].observe('change', function(event){
                var elem = this.decorated;
                if(this.checked){
                    elem.addClassName('checked');
                } else {
                    elem.removeClassName('checked');
                }
            });
        }
    },

    decorateRadio: function(elm) {
        for(var i = 0, l = elm.size(); i < l; i++){
            elm[i].wrap('span').addClassName('input-radio-state').wrap('span').addClassName('input-radio-wrp');
            elm[i].decorated =  elm[i].parentNode.parentNode;
            if(elm[i].checked){
                elm[i].parentNode.parentNode.addClassName('checked');
            }
            if(elm[i].style.display){
                elm[i].decorated.style.display = elm[i].style.display;
            }
            var ie = this.ie_6 || this.ie_7 || this.ie_8;
            elm[i].decorated.observe('click', function(event){
                var chk = this.down('input');
                if(chk.checked){
                    return;
                }
                if(event.target.tagName == "INPUT"){
                    chk = event.target;
                    event.stopPropagation();
                    chk.blur();
                    chk.focus();
                    return;
                } else if(ie) {
                    if(!chk.checked){
                        chk.checked = true;
                    }
                }
                chk.simulate('click');
                chk.simulate('change');
            });
            elm[i].observe('change', function(event){
                var inputs = document.getElementsByName(this.name),
                elem,
                i = 0 ,
                l = inputs.length;
                for(; i < l; i++ ){
                    elem = inputs[i].decorated;
                    if(inputs[i].checked){
                        elem.addClassName('checked');
                    } else {
                        elem.removeClassName('checked');
                    }
                }
            });
        }
    },

    decorateSelect: function(selects) {
        for(var i = 0, l = selects.size(); i < l; i++){
            var select = selects[i];
            select.addClassName('hidden_select');
            Element.insert(select, {'before' : this.buildSelect(select)});
            select.decorated = select.previous('div.custom-dropdown');
            this.fixTitles(select.decorated);
            if(this.ie_7){
                if(!select.decorated.up('#co-payment-form')){
                    if(typeof $(select.decorated).up('.form-list li') != "undefined"){
                        $(select.decorated).up('.form-list li').setStyle({
                            zIndex: 100 - i,
                            position: 'relative'
                        });
                    }
                }
            }
            /*if(document.loaded){
                this.selectFixWidth(select);
            } else {
                Event.observe(window,'load', this.selectFixWidth.bind(this, select));
            }*/
            this.createEvents(select);
            if(select.style.display){
                select.decorated.style.display = select.style.display;
            }
            if( select.disabled){
                select.decorated.down('dl').addClassName('disabled');
            } 
        }
    },
    
    fixTitles: function(select){
        $(select).select('a').each(function(item){
            var elem = item.up(0),
                str = item.innerHTML,
                elemPadding = parseInt($(elem).getStyle('paddingLeft')) + parseInt($(elem).getStyle('paddingRight'));
                Event.observe(window, 'load', function(){
                while (elem.offsetWidth < item.offsetWidth + elemPadding) {
                    str = str.substr(0, str.length - 1);
                    item.innerHTML = str + " ...";
                    if(elem.offsetWidth >= item.offsetWidth + elemPadding){
                        break;
                    }
                    if (elem.offsetWidth == 0) {
                    	break;
                    }
                }
                });
        });
    },

    buildSelect: function(select){
        var sel_id = (select.id)? ' rel_id_' + select.id:'',
        sel_cl = (select.className)? select.className.replace(/\s|^/g,' rel_cls_'):'',
        opt_list = '<div class="custom-dropdown'+ sel_id + sel_cl +'"><dl><dt><a href="#" onclick="return false">'+ select.options[select.selectedIndex].text +'</a></dt><dd><div><ul>';
        for(var i = 0, l = select.length; i < l ; i++){
            opt_list += '<li><a href="'+ select.options[i].value +'" onclick="return false" title="' + select.options[i].text + '">' + select.options[i].text + '</a></li>';
        }
        opt_list += '</ul></div><span class="dropdown_bot"></span></dd></dl></div>';
        return opt_list;
    },

    createEvents:function(select){
        var list = select.decorated.select('li a');
        for(var i = 0, l = list.length; i < l ; i++){
            list[i].observe('click', this.updateSelect.bind(this, select, i, null));
        }
        select.observe('change', this.updateSelect.bind(this, select, null , 'change'));
        select.decorated.down('dt').observe('click', this.dropdownToggle.bind(this, select));
        select.decorated.down('dl').observe('mouseover', function(){this.addClassName('over');});
        select.decorated.down('dl').observe('mouseout', function(){this.removeClassName('over');});
        select.observe('focus', this.dropdownToggle.bind(this, select, 'open'));
        select.observe('blur', this.dropdownToggle.bind(this, select, 'close'));
        document.observe('click', this.dropdownCloseAll.bind(this));
    },

    updateSelect: function(select, item, ev ){
        if(ev == 'change'){
            select.decorated.down('dt a').innerHTML = (select.options[select.selectedIndex].text) ? select.options[select.selectedIndex].text : '&nbsp;' ;
        } else if(select.selectedIndex != item){
            select.decorated.down('dt a').innerHTML = (select.options[item].text) ? select.options[item].text : '&nbsp;';
            select.selectedIndex = item;
            select.simulate('change');
            this.dropdownToggle(select, 'close', 'blur');
        } else {
            this.dropdownToggle(select, 'close', 'blur');           
        }
        
    },

    dropdownToggle : function(select, force, sim){
        if(select.disabled){
            return false;
        }
        var elem = (select.tagName == 'DL') ? select : select.decorated.down('dl');
        if(typeof force == "string"){
            if(force == "open") {
                elem.addClassName('open');
            } else if (force == "close"){
                elem.removeClassName('open');
            }
        } else {
            if(elem.hasClassName('open')) {
                elem.removeClassName('open');
                select.simulate('blur');
            } else {
                elem.addClassName('open');
                select.simulate('focus');
            }
        }
        if(sim == 'blur'){
            select.simulate('blur');
        }
    },

    dropdownCloseAll : function(event){
        var selects  = $$('div.custom-dropdown dl.open'),
        select = event.element();
        for(var i = 0, l = selects.size(); i < l; i++){
            if(selects[i] != select && selects[i] != select.parentNode && selects[i] != select.parentNode.parentNode){
                this.dropdownToggle( selects[i], 'close');
            }
        }
    },

    inputCustomCheck : function(){
        var inputs  = $$(/*'input[type=text]','input[type=password]','input[type=checkbox]','input[type=radio]',*/'select.custom-select'),
        new_inputs_text = [],
        new_inputs_check = [],
        new_inputs_radio = [],
        new_selects = [];
        for(var i = 0, l = inputs.size(); i < l ; i++){
            if(inputs[i].decorated === undefined){
                if(inputs[i].nodeName == 'SELECT'){
                    new_selects[new_selects.length] = inputs[i];
                } else if (inputs[i].type == 'checkbox') {
                    new_inputs_check[new_inputs_check.length] = inputs[i];
                } else if (inputs[i].type == 'radio') {
                    new_inputs_radio[new_inputs_radio.length] = inputs[i];
                } else  {
                    new_inputs_text[new_inputs_text.length] = inputs[i];
                }

            } else {
                if(inputs[i].style.display != inputs[i].decorated.style.display){
                    inputs[i].decorated.style.display = inputs[i].style.display;
                }
                if( inputs[i].disabled){
                    if(inputs[i].nodeName == 'SELECT'){
                        inputs[i].decorated.down('dl').addClassName('disabled');
                    } else {
                        inputs[i].decorated.addClassName('disabled');
                    }
                } else {
                    if(inputs[i].nodeName == 'SELECT'){
                        inputs[i].decorated.down('dl').removeClassName('disabled');
                    } else {
                        inputs[i].decorated.removeClassName('disabled');
                    }
                }

            }
        }
        if(new_selects.length !== 0){
            this.decorateSelect(new_selects);
        }
        if(new_inputs_check.length !== 0){
            this.decorateChk(new_inputs_check);
        }
        if(new_inputs_radio.length !== 0){
            this.decorateRadio(new_inputs_radio);
        }
        if(new_inputs_text.length !== 0){
            this.decorateTxt(new_inputs_text);
        }
    },

    updateSelectOptions : function(select){
        var opt_list = '', list;
        for(var i = 0, l = select.length; i < l ; i++){
            opt_list += '<li><a href="'+ select.options[i].value +'" onclick="return false">' + select.options[i].text + '</a></li>';
        }
        select.decorated.down('dt a').innerHTML = select.options[select.selectedIndex].text;
        select.decorated.down('ul').innerHTML = opt_list;
        list = select.decorated.select('li a');
        for(i = 0, l = list.length; i < l ; i++){
            list[i].observe('click', this.updateSelect.bind(this, select, i, null));
        }
        //this.selectFixWidth(select);
    },

    selectFixWidth : function( select ){
        var elem = select.decorated,
        elem_drop = elem.down('div'),
        elem_dd = elem.down('dd'),
        bool_scroll = elem_drop.offsetHeight > 200,
        w_drop,
        parent = null,
        callFix = (function(){
            elem_dd.style.width = "";
            elem.style.width = ""
            elem.style.position = "relative";
            w_drop = elem_drop.offsetWidth;
            bool_scroll = elem_drop.offsetHeight > 200;
            if (w_drop === 0){
                parent = elem.parentNode;
                while(parent.parentNode && parent.offsetWidth < 4 && parent.parentNode.offsetWidth < 4){
                    parent = parent.parentNode;
                }
                if(parent.style.display){
                    parent.oldDisplay = parent.style.display;
                }
                parent.style.display= "block";
                w_drop = elem_drop.offsetWidth;
                bool_scroll = elem_drop.offsetHeight > 200;
            }
            elem_dd.style.width = (w_drop) + "px";
            elem.style.width = (w_drop) + "px";
            if( this.ie_6){
                elem.style.overflow = 'hidden';
                elem.down('dl').style.display = 'block';
                elem_dd.style.overflowX = 'hidden';
                elem_drop.style.width = (w_drop-6) + "px";
                elem_drop.style.overflowX = 'hidden';
                elem.down('dt').style.display = 'block';
            }

            elem.style.position = "";
            if(parent){
                parent.style.display = parent.oldDisplay || "";
                parent.removeAttribute('oldDisplay');
            }

            if(bool_scroll){
                elem.down('dl').addClassName('scroll');
            }
        }).bind(this);
        
        //WebKit font-face loading bug fix;
        if(this.web_kit){
            window.setTimeout(callFix, 100);
        } else {
            callFix();
        }
    }

});

document.observe("dom:loaded", function() {
    window.inputs = new Varien.inputDecorator();
});


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.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.Top = Class.create()
Enterprise.Top.prototype = {
    initialize: function (container) {
        this.container = $(container);
        this.element = this.container.up(0);
        this.elementHeader = this.container.previous(0);
        this.intervalDuration = 400;
        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('mouseover', 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');
        this.container.show();
        if(timePeriod) {
            this.timePeriod = timePeriod*400;
            this.interval = setTimeout(this.hideCart.bind(this), this.timePeriod);
        }
    },

    hideCart: function () {

        this.container.hide();
        /*
        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.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 = ""
        }
    }
};

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;
    }
}

