/**
 * 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;

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).childElements().last().addClassName('last');
         }
         return result;
     },
     selection: function(optionId, selectionId) {
        if (selectionId == '' || selectionId == 'none') {
            return false;
        }
        var qty = null;
        if (this.config.options[optionId].selections[selectionId].customQty == 1 && !this.config['options'][optionId].isMulti) {
            if ($('bundle-option-' + optionId + '-qty-input')) {
                qty = $('bundle-option-' + optionId + '-qty-input').value;
            } else {
                qty = 1;
            }
        } else {
            qty = this.config.options[optionId].selections[selectionId].qty;
        }

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

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

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

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

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

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

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


Enterprise.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 popUpMenu(element,trigger) {
        var iDelay = 2000;
        var new_popup = 0;
        var sTempId = 'popUped';
        if (document.getElementById(sTempId)) {
            var eTemp = document.getElementById(sTempId);
            $(sTempId).previous(0).down('.switcher').removeClassName('list-opened');
            new Effect.Fade (eTemp, { duration:0.3 });
            eTemp.id = sNativeId;
            clearTimeout(tId);
            document.onclick = null;
        }

        sNativeId = 'popId-'+$(element).up(1).id;
        var el = $(sNativeId);
        el.id = sTempId;

        if (eTemp && el == eTemp) {
            hideElement();
        } else {
            $(element).addClassName('list-opened');
            $(sTempId).getOffsetParent().style.zIndex = 994;
            new Effect.Appear (el, { duration:0.3 });
            tId=setTimeout("hideElement()",2*iDelay);
        }
        new_popup = 1;
        document.onclick = function() {
            if (!new_popup) {
                hideElement();
                document.onclick = null;
            }
            new_popup = 0;
        }

        el.onmouseout = function() {
            if ($(sTempId)) {
                $(sTempId).addClassName('faded');
                tId=setTimeout("hideElement()",iDelay);
            }
        }

        el.onmouseover = function() {
            if ($(sTempId)) {
                $(sTempId).removeClassName('faded');
                clearTimeout(tId);
            }
        }

        hideElement = function() {
            //el.hide();
            new Effect.Fade (el, { duration:0.3 });
            $(element).removeClassName('list-opened');
            el.getOffsetParent().style.zIndex = 1;
            el.id = sNativeId;
            if (tId) {clearTimeout(tId);}
        }
} */


var tooltip=function(){
 var id = 'tt';
 var top = 3;
 var left = 3;
 var maxw = 300;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;
 return{
  show:function(v,w){
   if(tt == null){
    tt = document.createElement('div');
    tt.setAttribute('id',id);
    t = document.createElement('div');
    t.setAttribute('id',id + 'top');
    c = document.createElement('div');
    c.setAttribute('id',id + 'cont');
    b = document.createElement('div');
    b.setAttribute('id',id + 'bot');
    tt.appendChild(t);
    tt.appendChild(c);
    tt.appendChild(b);
    document.body.appendChild(tt);
    tt.style.opacity = 0;
    tt.style.filter = 'alpha(opacity=0)';
    document.onmousemove = this.pos;
   }
   tt.style.display = 'block';
   c.innerHTML = v;
   tt.style.width = w ? w + 'px' : 'auto';
   if(!w && ie){
    t.style.display = 'none';
    b.style.display = 'none';
    tt.style.width = tt.offsetWidth;
    t.style.display = 'block';
    b.style.display = 'block';
   }
  if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
  h = parseInt(tt.offsetHeight) + top;
  clearInterval(tt.timer);
  tt.timer = setInterval(function(){tooltip.fade(1)},timer);
  },
  pos:function(e){
   var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
   var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
   tt.style.top = (u - h) + 'px';
   tt.style.left = (l + left) + 'px';
  },
  fade:function(d){
   var a = alpha;
   if((a != endalpha && d == 1) || (a != 0 && d == -1)){
    var i = speed;
   if(endalpha - a < speed && d == 1){
    i = endalpha - a;
   }else if(alpha < speed && d == -1){
     i = a;
   }
   alpha = a + (i * d);
   tt.style.opacity = alpha * .01;
   tt.style.filter = 'alpha(opacity=' + alpha + ')';
  }else{
    clearInterval(tt.timer);
     if(d == -1){tt.style.display = 'none'}
  }
 },
 hide:function(){
  clearInterval(tt.timer);
   tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
  }
 };
}();


    function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
        var arrElements = (strTagName == "* q" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
        var oCurrent;
        var oAttribute;
        for(var i=0; i<arrElements.length; i++){
            oCurrent = arrElements[i];
            oAttribute = oCurrent.getAttribute(strAttributeName);
            if(typeof oAttribute == "string" && oAttribute.length > 0){
                if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                    arrReturnElements.push(oCurrent);
                }
            }
        }
        return arrReturnElements;
    }

    var lens_type;
    var lens_material;
    var step;
    var lens_package_selected = false;
    var lens_material_selected = false;


    function reveal_next(arg1, step){
        var cart_form = $('product_addtocart_form'); //prototype object NOT jquery
        var validation = new Validation(cart_form);
        var data;
        var data_elements = new Array();
        if(arg1 != null){
            var item_type = arg1.parentNode.getAttribute('item_type');
            data = arg1.parentNode.getAttribute(item_type);
        }

        var step_1    = jQuery('#step_1');
        var step_2    = jQuery('#step_2');
        var step_3    = jQuery('#step_3');
        var options_container = jQuery('#options-container');

        var single_lens 	 = jQuery('#single_lens');
        var bifocal_lens         = jQuery('#bifocal_lens');
        var progressive_lens     = jQuery('#progressive_lens');
        var nonprescription_lens = jQuery('#nonprescription_lens');
        
        var OD_CYL 	= jQuery('#OD_CYL');
        var OD_AXIS     = jQuery('#OD_AXIS');
        var OS_CYL      = jQuery('#OS_CYL');
        var OS_AXIS     = jQuery('#OS_AXIS');
        var OD_ADD      = jQuery('#OD_ADD');
        var OS_ADD      = jQuery('#OS_ADD');

        configurePrescription();

        switch(step) {
            case 0:
            //Assume the form needs reseting
                window.lens_type = null;
                window.lens_material = null;
                window.lens_package_selected = false;
                window.lens_material_selected = false;

                options_container.slideDown('800');

            //Now begin enabling and moving forward
                for(p in window.prescription_types) {
                    if(window.prescription_types[p] == 'single_lens'
                        || window.prescription_types[p] == 'bifocal_lens'
                        || window.prescription_types[p] == 'progressive_lens'
                        || window.prescription_types[p] == 'nonprescription_lens'){
                            jQuery('#'+window.prescription_types[p]).show();
                    }
                }
                jQuery('html,body').animate({scrollTop: jQuery("#productView").innerHeight()+200}, 2000);
                window.step = 0;
            break;
            
            case 1:
                window.lens_type = data;
                
                single_lens.removeClass('validation-failed');
                bifocal_lens.removeClass('validation-failed');
                progressive_lens.removeClass('validation-failed');
                nonprescription_lens.removeClass('validation-failed');
                if(window.lens_type == 'single') {
                    jQuery('#advice-required-entry-OD_ADD').hide();
                    jQuery('#advice-required-entry-OS_ADD').hide();
                    OD_ADD.removeClass('validation-failed required-entry');
                    OS_ADD.removeClass('validation-failed required-entry');
                }

                if(window.lens_type == 'nonprescription') {
                        jQuery("#non_rx").show();
                        jQuery("#pre_created_prescription").val('no_prescription');
                        jQuery("#OD_SPH").val('0.00');
                        jQuery("#OS_SPH").val('0.00');
                        jQuery("#PD").val('63.0');
                        jQuery("#OD_CYL").val('');
                        jQuery("#OS_CYL").val('');
                        jQuery("#OD_AXIS").val('');
                        jQuery("#OS_AXIS").val('');
                        jQuery("#OD_ADD").val('');
                        jQuery("#OS_ADD").val('');

                        jQuery('#pdp_prescription').hide();
                        jQuery("#non_rx").html("No Prescription Needed.");
                  } else {
//                        jQuery("#pre_created_prescription").val('');
//                        jQuery("#OD_SPH").val('');
//                        jQuery("#OD_CYL").val('');
//                        jQuery("#OD_AXIS").val('');
//                        jQuery("#OD_ADD").val('');
//                        jQuery("#PD").val('');
//                        jQuery("#OS_SPH").val('');
//                        jQuery("#OS_CYL").val('');
//                        jQuery("#OS_AXIS").val('');
//                        jQuery("#OS_ADD").val('');
//                        jQuery('#pdp_prescription').show();

                  }


                if(window.lens_material_selected == true || window.step >= 2) {
                    data_elements = getElementsByAttribute(document ,'li', 'item_type', 'lens_material_type');
                    for(i in data_elements) {
                        if(data_elements[i] != undefined && data_elements[i].style != undefined) {
                            data = jQuery(data_elements[i]);
                            if(data.attr('lens_prescription_type')==window.lens_type) {
                                data.show();
                                if(data.attr('lens_material_type') == window.lens_material) {
                                    var input_array = data.children('input:first-child')
                                    input_array[0].checked = true;

                                    bundle.changeSelection(input_array[0]);
                                    
                                    window.lens_material = input_array[0].parentNode.getAttribute('lens_material_type');
                                    window.lens_material_selected = true;
                                    data_elements = getElementsByAttribute(document ,'li', 'item_type', 'lens_material_type');
                                    for(i in data_elements) {
                                            data = data_elements[i];
                                            if(data != undefined && data.style != undefined) jQuery(data).removeClass('pdp_green');
                                    }
                                    jQuery(input_array[0].parentNode).addClass('pdp_green');

                                }
                            }
                            else
                                data.hide();
                        }
                    }
                }


            break;

            case 2:
                if (validatePrescription() && validation.validate() == true) {
                    data_elements = getElementsByAttribute(document ,'li', 'item_type', 'lens_material_type');
                    for(i in data_elements) {
                        if(data_elements[i] != undefined && data_elements[i].style != undefined) {
                            data = jQuery(data_elements[i]);
                            if(data.attr('lens_prescription_type')==window.lens_type) {
                                data.show();
                            }
                        }
                    }
                    window.step = 2;
                    jQuery("#next_step").hide();
                    jQuery("#step3_content").slideDown();
                }
            break;

            case 3:

                if(arg1.parentNode.getAttribute('item_type') == 'lens_material_type') {
                    window.lens_material = arg1.parentNode.getAttribute('lens_material_type');
                    window.lens_material_selected = true;
                    data_elements = getElementsByAttribute(document ,'li', 'item_type', 'lens_material_type');
                    for(i in data_elements) {
                            data = data_elements[i];
                            if(data != undefined && data.style != undefined) jQuery(data).removeClass('pdp_green');
                    }
                    jQuery(arg1.parentNode).addClass('pdp_green');

                    data_elements = getElementsByAttribute(document ,'li', 'item_type', 'coating');                    
                    for(i in data_elements) {
                        if(data_elements[i] != undefined && data_elements[i].style != undefined) {
                            data = jQuery(data_elements[i]);
                            if(data.attr('coating_material') != undefined && data.attr('coating_material').match(window.lens_material)!=null) {
                                jQuery(data_elements[i]).slideDown();
                            }
                            else
                                jQuery(data_elements[i]).slideUp();
                                data.removeClass('pdp_green');
                                input_array = data.children('input:first-child')
                                input_array[0].checked = false;
                        }
                    }

                    
                }

                if(arg1.parentNode.getAttribute('item_type') == 'coating' || arg1.value == '') {
                    data_elements = getElementsByAttribute(document ,'li', 'item_type', 'coating');
                    for(i in data_elements) {
                            data = data_elements[i];
                            if(data != undefined && data.style != undefined) jQuery(data).removeClass('pdp_green');
                    }
                    //addClass(arg1.parentNode, 'pdp_green');
                    jQuery(arg1.parentNode).addClass('pdp_green');
                    window.lens_package_selected = true;
                }

                if(window.lens_material_selected == true && window.lens_package_selected == true)
                    jQuery('#add_to_cart').slideDown();
            break;
        }
        opConfig.reloadPrice();
    }

    function configurePrescription(){
        //Always require Sphere and PD
        jQuery('#OD_SPH').addClass('required-entry');
        jQuery('#OS_SPH').addClass('required-entry');
        jQuery('#PD').addClass('required-entry');

        //Check requirements for cyc
        if(jQuery('#OD_CYL').val() != '' || jQuery('#OD_AXIS').val() != '') {
            jQuery('#OD_CYL').addClass('required-entry');
            jQuery('#OD_AXIS').addClass('required-entry');
        }
        else {
            jQuery('#OD_CYL').removeClass('required-entry');
            jQuery('#OD_AXIS').removeClass('required-entry');
        }

        if(jQuery('#OS_CYL').val() != '' || jQuery('#OS_AXIS').val() != '') {
            jQuery('#OS_CYL').addClass('required-entry');
            jQuery('#OS_AXIS').addClass('required-entry');
        }
        else {
            jQuery('#OS_CYL').removeClass('required-entry');
            jQuery('#OS_AXIS').removeClass('required-entry');
        }

        if(window.lens_type == 'single'){
            //require PD, R_SPH and L_SPH
            jQuery('#OD_ADD').removeClass('required-entry');
            jQuery('#OS_ADD').removeClass('required-entry');

        } else if(window.lens_type == 'bifocal' || window.lens_type == 'progressive'){
            //require PD, R_SPH, L_SPH, R_ADD, and L_ADD
            jQuery('#OD_ADD').addClass('required-entry');
            jQuery('#OS_ADD').addClass('required-entry');
        }

        

    }

    function requireById(Id,enabled ) {
        var myElement = document.getElementById(Id);
        if(enabled == true)
            addClass(myElement,'required-entry');
        if(enabled == false)
            removeClass(myElement,'required-entry');

    }

    function getSelectByParentId(parentId){
        var myElement = document.getElementById(parentId);
        if(myElement == null) {
        }
        else {
            for(j in myElement.childNodes) {
                if(myElement.childNodes[j] != null && myElement.childNodes[j].nodeName=='SELECT'){
                    return myElement.childNodes[j];
                }
            }
        }
        return false;
    }

    function hasClass(ele,cls) {
        if(ele.className != undefined)
            return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
        else
            return false;
    }

    function addClass(ele,cls) {
        if (!this.hasClass(ele,cls)) ele.className += " "+cls;
    }

    function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
                var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
                ele.className=ele.className.replace(reg,' ');
        }
    }

    function validatePrescription() {
        var isValid = true;

        var single_lens          = jQuery('#single_lens');
        var bifocal_lens         = jQuery('#bifocal_lens');
        var progressive_lens     = jQuery('#progressive_lens');
        var nonprescription_lens = jQuery('#nonprescription_lens');

        if(window.lens_type == null){
            single_lens.addClass('validation-failed');
            bifocal_lens.addClass('validation-failed');
            progressive_lens.addClass('validation-failed');
            nonprescription_lens.addClass('validation-failed'); 
            isValid = false;
        }

        checkCYL();
        return isValid;

    }
