/**
 * 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) 2010 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

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

Validation.add('validate-password-login', 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.', function(v) {
                var pass=v.strip(); /*strip leading and trailing spaces*/
                return !(pass.length>0 && pass.length < 6);
            });

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

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

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

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

    },

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

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

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

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

    hideCart: function () {

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


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

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

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

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

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

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

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

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

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

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

Enterprise.Tabs = Class.create();
Object.extend(Enterprise.Tabs.prototype, {
    initialize: function (container) {
        this.container = $(container);
        this.tabs = this.container.select('dt');
        this.activeTab = this.tabs.first();
        this.activeTab.addClassName('active');
        this.activeTab.next('dd').addClassName('active');
        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].next('dd').addClassName('active');
            } else {
                this.tabs[i].removeClassName('active');
                this.tabs[i].next('dd').removeClassName('active');
            }
        }
    }
});


Enterprise.Slider = Class.create();

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

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

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

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

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

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

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

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

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

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

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

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


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

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

function toggleMemberMenu(link){
    var menuContainer = document.getElementById('mMenu');
    var link = $(link)
    //var titleBg = document.getElementById("member-title-bg");
    //var bgStart = document.getElementById("member-title-bg-st");
    if (!link.className) { link.className = '' }
 
    if(menuContainer.style.display == 'none') {
        menuContainer.style.display = 'block';
        link.up('li').addClassName('active')
        //bgStart.className = "member-title-bg-st-hov";
    }else{
        menuContainer.style.display = "none";
        link.up('li').removeClassName('active');
        //bgStart.className = "";
    }
}

function toggleCheckbox(checkbox){
    var checkbox = $(checkbox)
    if( checkbox.hasClassName('checked') == false ) {
        $(checkbox).down('input').setAttribute('checked', 'checked');
        $(checkbox).addClassName('checked')
    }else{
        $(checkbox).removeClassName('checked');
        $(checkbox).down('input').setAttribute('checked', '');
    }
}

function focusInput(inpt){
        $(inpt).addClassName('active');
    }
function focusoutInput(inpt){
        $(inpt).removeClassName('active');
    }



$$('#ma-payment .cvv-what-is-this').each(function(el){
    Event.observe(el, 'click', toggleToolTip);
});
function toggleToolTip(event){
    if($('payment-tool-tip')){
        $('payment-tool-tip').setStyle({
            top: (Event.pointerY(event)-480)+'px'
        })
        $('payment-tool-tip').toggle();
    }
    Event.stop(event);
}

if($('payment-tool-tip-close')){
    Event.observe($('payment-tool-tip-close'), 'click', toggleToolTip);
}
if($('tool-tip-content')){
    Event.observe($('tool-tip-content'), 'click', toggleToolTip);
}

function showCVV() {
    if($('payment-tool-tip')){
        $('payment-tool-tip').setStyle({
            top: 'auto',
            bottom: '50px',
            left: '70px'
        })
        $('payment-tool-tip').toggle();
    }
    if($('payment-tool-tip-close')){
        Event.observe($('payment-tool-tip-close'), 'click', toggleToolTip);
    }
    if($('tool-tip-content')){
        Event.observe($('tool-tip-content'), 'click', toggleToolTip);
    }
}

function selectCards() {
    var listItems = $$('#saved-cards .cardbox');
    listItems.each(function(e){
        e.observe('click', function(event){
            listItems.each(function(el){
                el.removeClassName('selected');
                el.down('input.radio').checked = false;
            });
            e.addClassName('selected');
            e.down('input.radio').checked = true;
        }.bind(this));
        e.observe('mouseover', function(event){ e.addClassName('hovered'); }.bind(this));
        e.observe('mouseout', function(event){ e.removeClassName('hovered'); }.bind(this));
        if(e.down('input.radio').checked == true) {
            e.addClassName('selected');
        } else {
            e.removeClassName('selected');
        }
    });
}
Event.observe(window, 'load', function() {
    selectCards();
});

function checkCards() {
    var isChecked = false;
    var listItems = $$('#list-cards ul li.list-item');
    listItems.each(function(e){
        e.observe('click', function(event){
            listItems.each(function(el){
                el.removeClassName('selected');
                el.down('input.radio').checked = false;
            });
            e.addClassName('selected');
            e.down('input.radio').checked = true;
        }.bind(this));
        e.observe('mouseover', function(event){ e.addClassName('hovered'); }.bind(this));
        e.observe('mouseout', function(event){ e.removeClassName('hovered'); }.bind(this));
        if(e.down('input.radio').checked == true) {
            e.addClassName('selected');
            isChecked = true;
        } else {
            e.removeClassName('selected');
        }
    });
    if(!isChecked) {
        if(listItems[0]) {
            listItems[0].addClassName('selected');
            listItems[0].down('input.radio').checked = true;
        }
    }
}
Event.observe(window, 'load', function() {
    checkCards();
});




function preloader(id,type) {
    var e_id = id;
    var e_type = type;
    if(e_type=='') e_type='block';
    if($(e_id)) {
        $(e_id).style.display=type;
   }
}

function overlayStart(){
    if($('lightwindow_title_bar_close_link')) $('lightwindow_title_bar_close_link').style.display = 'none';
    if($('startOverlay')) $('startOverlay').style.display = 'block';
}

function overlayStop(){
    if($('lightwindow_title_bar_close_link')) $('lightwindow_title_bar_close_link').style.display = 'inline';
    if($('startOverlay')) $('startOverlay').style.display = 'none';
}

function jstr_replace(haystack, needle, replacement) { 
    var temp = haystack.split(needle); 
    return temp.join(replacement); 
}


Event.observe(window, 'load', function() {
    function lightwindowExternal(){}
    /* Main Light Window */
    lightWindow = new lightwindow();
    $$('.lb-terms').each(function(trms){
        Event.observe(trms, 'click', function(e){
            e.stop();
            lightWindow.activateWindow({
                href: BASE_URL + 'terms/',
                title: 'MAGENTO GO&trade; SERVICE TERMS',
                width: 900,
                height: 620,
                lbstyle: 'white'
            });
        });
    });
    
    $$('.lb-privacy').each(function(trms){
        Event.observe(trms, 'click', function(e){
            e.stop();
            lightWindow.activateWindow({
                href: BASE_URL + 'magento-privacy-policy/',
                title: 'MAGENTO PRIVACY POLICY',
                width: 900,
                height: 620,
                lbstyle: 'white'
            });
        });
    });
    
    $$('.lb-subscribe').each(function(trms) {
        Event.observe(trms, 'click', function(e) {
            var content = $('newsletter_subscribe'),
                div = document.createElement('div'),
                cloneId = 'newsletter_subscribe_clone';

            div.setAttribute('id', cloneId);
            div.setAttribute('style', 'display: none;');
            Element.update(div, content.innerHTML);
            content.insert({before: div});
            lightWindow.activateWindow({
                href: document.location.href + '#' + cloneId,
                height: 508
            });
            
            e.stop();
        })
    });
    /*
    var contactUsBut = $$('.contact-us-popup');
    if(contactUsBut.length > 0){
        //contactUs = new lightwindow();
        contactUsBut.each(function(but){
            but.observe('click', function(e){
                e.stop();
                if(but.rel != ''){
                    lightWindow.activateWindow({
                        href: but.rel,
                        title: 'Need help?',
                        width: 735,
                        height: 520
                    });
                }
            });
        });
    }
    */
});

function submitForm() {
    var dataForm = new VarienForm('mktForm_1016', false);
    if (Prototype.Browser.WebKit){
        $$('select.validate-select').each(function(sel) {
            if (sel.value == ''){
                sel.up(0).addClassName('validation-error');
                } else {
                     sel.up(0).removeClassName('validation-error');
                    }
            }
        ); 
    }
    return dataForm.submit();
}

function setReturnUrl(u, anc) {
    var retUrl = jstr_replace(u, '#', '') + anc;
    if($('returnURL1')) $('returnURL1').value = retUrl;
    if($('returnURL2')) $('returnURL2').value = retUrl;
}

function deactivateLightwindow() {
    lightWindow.deactivate();
}

function chooseConactsUsTab(tab) {
        var retUrl = jstr_replace(location.href, '#', '') + '#sales-thank-you';
        var marketoForm  = '<form onsubmit="setReturnUrl(location.href, \'#sales-thank-you\');" id="mktForm_1016" action="http://info.magento.com/index.php/leadCapture/save" enctype="application/x-www-form-urlencoded" method="post">'
        +'<fieldset style="margin-bottom:10px;">'
        +'<ul class="form-list">'
        +'<li><label class="required" for="FirstName"><em>*</em>First Name</label>'
        +'<div class="input-box"><input id="FirstName" class="input-text required-entry" name="FirstName" type="text" maxlength="47"/></div>'
        +'</li>'
        +'<li><label class="required" for="LastName"><em>*</em>Last Name</label>'
        +'<div class="input-box"><input id="LastName" class="input-text required-entry" name="LastName" type="text" maxlength="47"/></div>'
        +'</li>'
        +'<li><label class="required" for="Email"><em>*</em>Email Address</label>'
        +'<div class="input-box"><input id="Email" class="input-text validate-email required-entry" title="Email Address" name="Email" type="text" maxlength="47"/></div>'
        +'</li>'
        +'<li><label class="required" for="Phone"><em>*</em>Phone Number</label>'
        +'<div class="input-box"><input id="Phone" class="input-text required-entry" title="Phone" name="Phone" type="text" maxlength="47"/></div>'
        +'</li>'
        +'<li><label class="required" for="Company"><em>*</em>Company</label>'
        +'<div class="input-box"><input id="Company" class="input-text required-entry" name="Company" type="text" maxlength="47"/></div>'
        +'</li>'
        +'<li><label class="required" for="Country"><em>*</em>Country</label>'
        +'<div class="input-box"><select id="Country" class="validate-select" name="Country" onchange="updateStateBox()" size="1"> <option value="">Select Country</option><option value="United States">United States</option><option value="Canada">Canada</option><option value="France">France</option><option value="Germany">Germany</option><option value="United Kingdom">United Kingdom</option><option value="Afghanistan">Afghanistan</option><option value="Aland Islands">Aland Islands</option><option value="Albania">Albania</option><option value="Algeria">Algeria</option><option value="American Samoa">American Samoa</option><option value="Andorra">Andorra</option><option value="Angola">Angola</option><option value="Anguilla">Anguilla</option><option value="Antarctica">Antarctica</option><option value="Antigua and Barbuda">Antigua and Barbuda</option><option value="Argentina">Argentina</option><option value="Armenia">Armenia</option><option value="Aruba">Aruba</option><option value="Australia">Australia</option><option value="Austria">Austria</option><option value="Azerbaijan">Azerbaijan</option><option value="Bahamas">Bahamas</option><option value="Bahrain">Bahrain</option><option value="Bangladesh">Bangladesh</option><option value="Barbados">Barbados</option><option value="Belarus">Belarus</option><option value="Belgium">Belgium</option><option value="Belize">Belize</option><option value="Benin">Benin</option><option value="Bermuda">Bermuda</option><option value="Bhutan">Bhutan</option><option value="Bolivia">Bolivia</option><option value="Bosnia and Herzegovina">Bosnia and Herzegovina</option><option value="Botswana">Botswana</option><option value="Bouvet Island">Bouvet Island</option><option value="Brazil">Brazil</option><option value="British Indian Ocean Territory">British Indian Ocean Territory</option><option value="British Virgin Islands">British Virgin Islands</option><option value="Brunei">Brunei</option><option value="Bulgaria">Bulgaria</option><option value="Burkina Faso">Burkina Faso</option><option value="Burundi">Burundi</option><option value="Cambodia">Cambodia</option><option value="Cameroon">Cameroon</option><option value="Cape Verde">Cape Verde</option><option value="Cayman Islands">Cayman Islands</option><option value="Central African Republic">Central African Republic</option><option value="Chad">Chad</option><option value="Chile">Chile</option><option value="China">China</option><option value="Christmas Island">Christmas Island</option><option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option><option value="Colombia">Colombia</option><option value="Union of the Comoros">Union of the Comoros</option><option value="Congo">Congo</option><option value="Cook Islands">Cook Islands</option><option value="Costa Rica">Costa Rica</option><option value="Croatia">Croatia</option><option value="Cuba">Cuba</option><option value="Cyprus">Cyprus</option><option value="Czech Republic">Czech Republic</option><option value="Democratic Republic of Congo">Democratic Republic of Congo</option><option value="Denmark">Denmark</option><option value="Disputed Territory">Disputed Territory</option><option value="Djibouti">Djibouti</option><option value="Dominica">Dominica</option><option value="Dominican Republic">Dominican Republic</option><option value="East Timor">East Timor</option><option value="Ecuador">Ecuador</option><option value="Egypt">Egypt</option><option value="El Salvador">El Salvador</option><option value="Equatorial Guinea">Equatorial Guinea</option><option value="Eritrea">Eritrea</option><option value="Estonia">Estonia</option><option value="Ethiopia">Ethiopia</option><option value="Falkland Islands">Falkland Islands</option><option value="Faroe Islands">Faroe Islands</option><option value="Federated States of Micronesia">Federated States of Micronesia</option><option value="Fiji">Fiji</option><option value="Finland">Finland</option><option value="French Guyana">French Guyana</option><option value="French Polynesia">French Polynesia</option><option value="French Southern Territories">French Southern Territories</option><option value="Gabon">Gabon</option><option value="Gambia">Gambia</option><option value="Georgia">Georgia</option><option value="Ghana">Ghana</option><option value="Gibraltar">Gibraltar</option><option value="Greece">Greece</option><option value="Greenland">Greenland</option><option value="Grenada">Grenada</option><option value="Guadeloupe">Guadeloupe</option><option value="Guam">Guam</option><option value="Guatemala">Guatemala</option><option value="Guinea">Guinea</option><option value="Guinea-Bissau">Guinea-Bissau</option><option value="Guyana">Guyana</option><option value="Haiti">Haiti</option><option value="Heard Island and McDonald Islands">Heard Island and McDonald Islands</option><option value="Honduras">Honduras</option><option value="Hong Kong">Hong Kong</option><option value="Hungary">Hungary</option><option value="Iceland">Iceland</option><option value="India">India</option><option value="Indonesia">Indonesia</option><option value="Iran">Iran</option><option value="Iraq">Iraq</option><option value="Iraq-Saudi Arabia Neutral Zone">Iraq-Saudi Arabia Neutral Zone</option><option value="Ireland">Ireland</option><option value="Israel">Israel</option><option value="Italy">Italy</option><option value="Ivory Coast">Ivory Coast</option><option value="Jamaica">Jamaica</option><option value="Japan">Japan</option><option value="Jordan">Jordan</option><option value="Kazakhstan">Kazakhstan</option><option value="Kenya">Kenya</option><option value="Kiribati">Kiribati</option><option value="Kuwait">Kuwait</option><option value="Kyrgyz Republic">Kyrgyz Republic</option><option value="Laos">Laos</option><option value="Latvia">Latvia</option><option value="Lebanon">Lebanon</option><option value="Lesotho">Lesotho</option><option value="Liberia">Liberia</option><option value="Libya">Libya</option><option value="Liechtenstein">Liechtenstein</option><option value="Lithuania">Lithuania</option><option value="Luxembourg">Luxembourg</option><option value="Macau">Macau</option><option value="Macedonia">Macedonia</option><option value="Madagascar">Madagascar</option><option value="Malawi">Malawi</option><option value="Malaysia">Malaysia</option><option value="Maldives">Maldives</option><option value="Mali">Mali</option><option value="Malta">Malta</option><option value="Marshall Islands">Marshall Islands</option><option value="Martinique">Martinique</option><option value="Mauritania">Mauritania</option><option value="Mauritius">Mauritius</option><option value="Mayotte">Mayotte</option><option value="Mexico">Mexico</option><option value="Moldova">Moldova</option><option value="Monaco">Monaco</option><option value="Mongolia">Mongolia</option><option value="Montserrat">Montserrat</option><option value="Morocco">Morocco</option><option value="Mozambique">Mozambique</option><option value="Myanmar">Myanmar</option><option value="Namibia">Namibia</option><option value="Nauru">Nauru</option><option value="Nepal">Nepal</option><option value="Netherlands">Netherlands</option><option value="Netherlands Antilles">Netherlands Antilles</option><option value="New Caledonia">New Caledonia</option><option value="New Zealand">New Zealand</option><option value="Nicaragua">Nicaragua</option><option value="Niger">Niger</option><option value="Nigeria">Nigeria</option><option value="Niue">Niue</option><option value="Norfolk Island">Norfolk Island</option><option value="North Korea">North Korea</option><option value="Northern Mariana Islands">Northern Mariana Islands</option><option value="Norway">Norway</option><option value="Oman">Oman</option><option value="Pakistan">Pakistan</option><option value="Palau">Palau</option><option value="Occupied Palestinian Territories">Occupied Palestinian Territories</option><option value="Panama">Panama</option><option value="Papua New Guinea">Papua New Guinea</option><option value="Paraguay">Paraguay</option><option value="Peru">Peru</option><option value="Philippines">Philippines</option><option value="Pitcairn Islands">Pitcairn Islands</option><option value="Poland">Poland</option><option value="Portugal">Portugal</option><option value="Puerto Rico">Puerto Rico</option><option value="Qatar">Qatar</option><option value="Reunion">Reunion</option><option value="Romania">Romania</option><option value="Russia">Russia</option><option value="Rwanda">Rwanda</option><option value="Saint Helena and Dependencies">Saint Helena and Dependencies</option><option value="Saint Kitts &amp; Nevis">Saint Kitts &amp; Nevis</option><option value="Saint Lucia">Saint Lucia</option><option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option><option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option><option value="Samoa">Samoa</option><option value="San Marino">San Marino</option><option value="Sao Tome and Principe">Sao Tome and Principe</option><option value="Saudi Arabia">Saudi Arabia</option><option value="Senegal">Senegal</option><option value="Seychelles">Seychelles</option><option value="Sierra Leone">Sierra Leone</option><option value="Singapore">Singapore</option><option value="Slovakia">Slovakia</option><option value="Slovenia">Slovenia</option><option value="Solomon Islands">Solomon Islands</option><option value="Somalia">Somalia</option><option value="South Africa">South Africa</option><option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option><option value="South Korea">South Korea</option><option value="Spain">Spain</option><option value="Spratly Islands">Spratly Islands</option><option value="Sri Lanka">Sri Lanka</option><option value="Sudan">Sudan</option><option value="Suriname">Suriname</option><option value="Svalbard and Jan Mayen Islands">Svalbard and Jan Mayen Islands</option><option value="Swaziland">Swaziland</option><option value="Sweden">Sweden</option><option value="Switzerland">Switzerland</option><option value="Syria">Syria</option><option value="Taiwan">Taiwan</option><option value="Tajikistan">Tajikistan</option><option value="Tanzania">Tanzania</option><option value="Thailand">Thailand</option><option value="Togo">Togo</option><option value="Tokelau">Tokelau</option><option value="Tonga">Tonga</option><option value="Trinidad and Tobago">Trinidad and Tobago</option><option value="Tunisia">Tunisia</option><option value="Turkey">Turkey</option><option value="Turkmenistan">Turkmenistan</option><option value="Turks and Caicos Islands">Turks and Caicos Islands</option><option value="Tuvalu">Tuvalu</option><option value="Uganda">Uganda</option><option value="Ukraine">Ukraine</option><option value="United Arab Emirates">United Arab Emirates</option><option value="United Nations Neutral Zone">United Nations Neutral Zone</option><option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option><option value="Uruguay">Uruguay</option><option value="US Virgin Islands">US Virgin Islands</option><option value="Uzbekistan">Uzbekistan</option><option value="Vanuatu">Vanuatu</option><option value="Vatican City">Vatican City</option><option value="Venezuela">Venezuela</option><option value="Vietnam">Vietnam</option><option value="Wallis and Futuna Islands">Wallis and Futuna Islands</option><option value="Western Sahara">Western Sahara</option><option value="Yemen">Yemen</option><option value="Zambia">Zambia</option><option value="Zimbabwe">Zimbabwe</option><option value="Serbia">Serbia</option><option value="Montenegro">Montenegro</option><option></option> </select></div>'
        +'</li>'
        +'<li id="statebox" style="height: 0px;">'
        +'</li>'
        +'<li><label class="required" for="mgo_monthly_transactions__c" style="line-height:20px;"><em>*</em>Average orders per month</label>'
        +'<div class="input-box"><select size="1" id="mgo_monthly_transactions__c" name="mgo_monthly_transactions__c" class="validate-select"><option value="">Select</option><option value="Less than 100">Less than 100</option><option value="100 - 150">100 - 150</option><option value="151 - 300">151 - 300</option><option value="301- 750">301- 750</option><option value="751 - 1,500">751 - 1,500</option><option value="More than 1,500">More than 1,500</option></select></div>'
        +'</li>'
        +'<li style="height: 85px;"> <label class="required" for="Comments__c">Comments:</label>'
        +'<div class="input-box"><textarea id="Comments__c" style="width: 408px; resize: none;" cols="49" rows="5" name="Comments__c"></textarea></div>'
        +'</li>'
        +'</ul>'
        +'<div class="clearer">&nbsp;</div>'
        +'</fieldset>'
        +'<div class="buttons-set" style="width: 650px; text-align: right !important;"><button type="button" class="but-submit" style="position: relative; left: 90px;" title="Submit" onclick="submitForm();">Submit</button> <button class="but-cancel" style="position: relative; right: 105px;" title="Cancel" onclick="deactivateLightwindow(); return false">Cancel</button>&nbsp;&nbsp;</div>'
        +'<span style="display: none;"><input name="_marketo_comments" type="text" /></span> <input name="lpId" type="hidden" value="-1" /> <input name="subId" type="hidden" value="36" /> <input name="kw" type="hidden" /> <input name="cr" type="hidden" /> <input name="searchstr" type="hidden" /> <input name="lpurl" type="hidden" value="http://info.magento.com/ContactUs-MagentoGo.html?cr={creative}&amp;kw={keyword}" /> <input name="formid" type="hidden" value="1016" /> <input id="returnURL1" name="returnURL" type="hidden" value="'+retUrl+'" /> <input id="returnURL2" name="retURL" type="hidden" value="'+retUrl+'" /> <input name="_mkt_disp" type="hidden" value="return" /> <input name="_mkt_trk" type="hidden" /> </form>';
        
        var salesforceForm = '<form onsubmit="setReturnUrl(location.href, \'#support-thank-you\');" id="caseform" method="post" action="' + BASE_URL.replace('http:', 'https:') + 'cases/index/savecase/">'
        +'<fieldset style="margin-bottom:10px;">'
        +'<ul class="form-list">'
        +'<li class="fields-wide">'
        +'<label class="required" for="firstname">First Name:<em>*</em></label>'
        +'<div class="input-box">'
        +'<input type="text" title="First Name" class="input-text required-entry" name="firstname" id="firstname">'
        +'</div>'
        +'</li>'
        +'<li class="fields-wide">'
        +'<label class="required" for="lastname">Last Name:<em>*</em></label>'
        +'<div class="input-box">'
        +'<input type="text" title="Last Name" class="input-text required-entry" name="lastname" id="lastname">'
        +'</div>'
        +'</li>'
        +'<li class="fields-wide">'
        +'<label class="required" for="email">Email:<em>*</em></label>'
        +'<div class="input-box">'
        +'<input type="text" title="Email" class="input-text validate-email required-entry" name="email" id="email">'
        +'</div>'
        +'</li>'
        +'<li class="fields-wide">'
        +'<label class="required" for="phone">Phone:<em>*</em></label>'
        +'<div class="input-box">'
        +'<input type="text" title="Phone" class="input-text required-entry" name="phone" id="phone">'
        +'</div>'
        +'</li>'
        +'<li class="fields-wide">'
        +'<label class="required" for="subject">Subject:<em>*</em></label>'
        +'<div class="input-box">'
        +'<input type="text" title="Subject" class="input-text required-entry" name="subject" id="subject">'
        +'</div>'
        +'</li>'
        +'<li class="fields-wide">'
        +'<label class="required" for="description">Description:<em>*</em></label>'
        +'<div class="input-box"><textarea id="description" style="width: 408px; resize: none;" cols="49" rows="5" name="description" class="required-entry textarea-validation-passed"></textarea></div>'
        +'</ul>'
        +'</fieldset>'
        +'<input type="hidden" name="source" value="contact-us-form">'
        +'<input type="hidden" name="return_url" value="'+window.location.href+'">'
        +'<div class="clearer">&nbsp;</div>'
        +'<div class="buttons-set" style="width: 650px; text-align: right !important; margin-top: 60px;"><button class="but-submit" style="position: relative; left: 90px;" type="button" title="Submit" onclick="submitCaseForm();">Submit</button> <button class="but-cancel" style="position: relative; right: 105px;" title="Cancel" onclick="deactivateLightwindow(); return false">Cancel</button>&nbsp;&nbsp;</div>'
        +'<form>';
        $('go-form').innerHTML = (tab == 'marketo' ? marketoForm : salesforceForm);
        var wlink = (tab == 'marketo' ? '/go/contact-us/sales' : '/go/contact-us/technical');
        try{
            if(typeof(pageTracker) == 'object'){
            var newTrack = wlink;
            pageTracker._trackPageview(newTrack);
            }
        }catch(err){ alert(error); }
        loadWebkitSelects();
}

function updateStateBox() {
    var country = $('Country');
    var statebox = $('statebox');
    
    var usStates = '<label class="required" for="State"><em>*</em>State</label>'
    +'<div class="input-box"><select class="validate-select" size="1" id="State" name="State"><option value="">Select State</option><option value="AK">AK</option><option value="AL">AL</option><option value="AR">AR</option><option value="AZ">AZ</option><option value="CA">CA</option><option value="CO">CO</option><option value="CT">CT</option><option value="DE">DE</option><option value="FL">FL</option><option value="GA">GA</option><option value="HI">HI</option><option value="IA">IA</option><option value="ID">ID</option><option value="IL">IL</option><option value="IN">IN</option><option value="KS">KS</option><option value="KY">KY</option><option value="LA">LA</option><option value="MA">MA</option><option value="MD">MD</option><option value="ME">ME</option><option value="MI">MI</option><option value="MN">MN</option><option value="MO">MO</option><option value="MS">MS</option><option value="MT">MT</option><option value="NC">NC</option><option value="ND">ND</option><option value="NE">NE</option><option value="NH">NH</option><option value="NJ">NJ</option><option value="NM">NM</option><option value="NV">NV</option><option value="NY">NY</option><option value="OH">OH</option><option value="OK">OK</option><option value="OR">OR</option><option value="PA">PA</option><option value="RI">RI</option><option value="SC">SC</option><option value="SD">SD</option><option value="TN">TN</option><option value="TX">TX</option><option value="UT">UT</option><option value="VA">VA</option><option value="VT">VT</option><option value="WA">WA</option><option value="WI">WI</option><option value="WV">WV</option><option value="WY">WY</option></select></div>';
    
    if (country.value == 'United States') {
        statebox.style.height = '39px';
        statebox.innerHTML = usStates;
    } else {
        statebox.style.height = '0px';
    }
    var dataForm = new VarienForm('mktForm_1016', true);
    }

function submitCaseForm() {
    var dataForm = new VarienForm('caseform', true);
    if (Prototype.Browser.WebKit){
        $$('select.validate-select').each(function(sel) {
            if (sel.value == ''){
                sel.up(0).addClassName('validation-error');
                } else {
                     sel.up(0).removeClassName('validation-error');
                    }
            }
        ); 
    }
    
    if ($('description').value == ''){
        $('description').removeClassName('textarea-validation-passed');
        $('description').addClassName('textarea-validation-failed');
    } else {
        $('description').removeClassName('textarea-validation-failed');
        $('description').addClassName('textarea-validation-passed');
    }

    return dataForm.submit();
}

function loadWebkitSelects(id){
    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0){
        var selector = 'select';

        if (undefined != id) {
            selector += '#' + id;
        }

    $$('input["input:-webkit-autofill"]').each(function(el){
        if(el.id != 'billing:region'){
        Element.insert( el, {'after': el.cloneNode(true) } );
        el.remove();
        }
    });
    $$(selector).each(function(sel){
        var bgImage = sel.getStyle('backgroundImage');
        var bgWidth = sel.getStyle('width');
        bgWidth = bgWidth.replace('px','');
        sel.style.background = 'url('+SKIN_URL+'images/select-arrow.gif) no-repeat '+(bgWidth-24)+'px 10px !important';
        sel.wrap('div', { 'style': 'background-image:'+bgImage+';width:'+bgWidth+'px;height:39px;' });
    });
    }else if (navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
    $$(selector).each(function(sel){
        var bgImage = sel.getStyle('backgroundImage');
        var bgWidth = sel.getStyle('width');
        bgWidth = bgWidth.replace('px','');
        sel.style.background = 'url('+SKIN_URL+'images/select-arrow.gif) no-repeat '+(bgWidth-24)+'px 10px !important';
        sel.wrap('div', { 'style': 'background-image:'+bgImage+';width:'+bgWidth+'px;height:39px;' });
    });
    }
}

jQuery(document).ready(function(){
    jQuery('.greybutton').each(function(){
        jQuery(this).mousedown(function(){ jQuery(this).addClass('active')}).mouseup(function(){ jQuery(this).removeClass('active'); });
    });
});
