var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

document.observe("dom:loaded", function() { 
    //hiding & toggling side navigation
    sideNav();

    //centering page vertically
    //arg: initial vertical body background position (in pixels)
    //centerVertically(-1869);

    //fix for IE png transparency bug
    pngFix();
    
    //setting background-image for category page
    setCategoryBackground();
    
    
    //show big image in mosaic products list
    mosaicZoom();
    
    //displaying tabs on product page
    productInfoToggle();
    
    //double carousel 
    //args: 
    //1 - width of the element of big products list
    //2 - width of the element of small products list
    //3 - number of visible elements of small products list
    doubleCarousel(260, 66);
    
    //displaying shop assistant
    showAssistant();
    
    //fix wrong button position in IE6 on checkout page
    fixIE();

    //displaying discount code field 
    showDiscountBox();

    //checking if conditions were accepted
    checkAccept();

  
}); 

function sideNav() { 
    //toggle side navigation
    toggleSideNav();
}

function centerVertically(initialBgPos) {
    var pageBody = $$('body')[0]; 
    //var initialBgPos =  parseInt(pageBody.getStyle('backgroundPosition').split(' ')[1].replace('px', '')); 
    var pageHeight = $$('.wrapper')[0].getHeight();
    
    updatePosition = function() { 
        if(document.viewport.getHeight() > pageHeight + 30) {
            var pageMove = Math.floor((document.viewport.getHeight() - pageHeight - 60)/2);
            var newBgPos = pageMove + initialBgPos;
            pageBody.setStyle({
                paddingTop: pageMove + 'px',
                backgroundPosition: '0 ' + newBgPos + 'px'
            });
        }
        else {
            pageBody.setStyle({
                paddingTop: 0,
                backgroundPosition: '0 ' + initialBgPos + 'px'
            });        
        }
    }

    updatePosition();
    Event.observe(window, 'resize', updatePosition);
}


function pngFix() {
    if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6)) {
        var toFix = $$('.pngfix');
        for (var i=0;i<toFix.length; i++) {
            var bgImg = toFix[i].getStyle('backgroundImage');
    			if(bgImg.indexOf(".png")!=-1){
    				var iebg = bgImg.split('url("')[1].split('")')[0];
    				toFix[i].setStyle({backgroundImage: 'none'});
    				toFix[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
    			}
        }
    }
}




function setCategoryBackground() {
    if($('category-page')) { 
        var navItems = $$('.side-nav > li > ul > li, .side-nav > li');
        var defaultImg = $('category-page').style.backgroundImage;
        
        for(var i=0, images=[]; i<navItems.length; i++) {
            var newSrc =  navItems[i].down('a', 0).readAttribute('rel'); 
            images.push(new Image());
            images.last().src = newSrc;    
        
            navItems[i].observe('mouseover', function(event) {
                var affectedLi = Event.findElement(event, 'LI');
                var relevantLi = (affectedLi.up('div', 1).hasClassName('makeScroll'))?affectedLi.up('li') : affectedLi;
                var imgUrl = 'url(' + /*this*/relevantLi.down('a', 0).readAttribute('rel') + ')'; 
                $('category-page').style.backgroundImage = imgUrl;
            });
        } 
        
        Event.observe(document, 'mouseover', function(event) {
            if(!Event.element(event).up('.side-nav')) 
                $('category-page').style.backgroundImage = defaultImg; 
        });
    }
}

function toggleSideNav() {
    $$('.side-nav > li > ul > li > a').each(function(el) {
        el.observe('click', function(event) {
            var slideDiv = this.next('.makeScroll');
            var activeDiv = $$('.side-nav > li > ul > li.active .makeScroll')[0];
            if(activeDiv) {
                Effect.SlideUp(activeDiv,{ duration: 0.4, afterFinish: function() {$$('.scroll-innerBox, .makeScroll').invoke('setStyle', {bottom: 'auto'});} });
            }
            if(!slideDiv.parentNode.hasClassName('active')) {
                Effect.SlideDown(slideDiv,{ duration: 0.4, afterFinish: function() {$$('.scroll-innerBox, .makeScroll').invoke('setStyle', {bottom: 'auto'});}  });
                slideDiv.parentNode.addClassName('active');                      
            }
            if(activeDiv)    
                activeDiv.parentNode.removeClassName('active');
                
            Event.stop(event);  
        });
    });
}


function mosaicZoom() {
    var nameWrapper = $$('.mosaic-list-container .main-image span')[0];
    var bigImg = $$('.mosaic-list-container .main-image img')[0];
    if(bigImg)
    {
        var spacer = bigImg.src;
        bigImg.src = $$('.mosaic-list li a')[0].readAttribute('rel');
        if(nameWrapper) 
            nameWrapper.innerHTML = $$('.mosaic-list li a')[0].readAttribute('title');
        $$('.mosaic-list li a').invoke('observe', 'mouseover', function() {
            bigImg.src = spacer;
            var imgLoc = this.readAttribute('rel');
            var prName = this.readAttribute('title');
            setTimeout(function() {bigImg.src = imgLoc; if(nameWrapper) nameWrapper.innerHTML = prName;}, 1);
        });
        
    }
}


function productInfoToggle() {
    var list = $$('.product-info')[0];
    var sections = $$('.product-info-section > .inside');
    var openers = $$('.product-info > li > a'); 
    var closers = $$('.product-info img.close'); 
    openers.invoke('observe', 'click', function(event) {
        if(!this.hasClassName('active')) {        
            if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6))
                $$('.product-description select').invoke('setStyle', {visibility: 'hidden'});
               
            var checkActive = false;
            for(var i=0; i<openers.length; i++) {
                if(openers[i].hasClassName('active'))
                    checkActive = true;
            }
            sections.invoke('hide');           
            openers.invoke('removeClassName', 'active');
            this.addClassName('active');
            if(checkActive)
                this.next('.product-info-section').down('.inside').show();
            else
                Effect.SlideDown(this.next('.product-info-section').down('.inside'), {duration: 0.6});
            
        }
        else {
            this.removeClassName('active');
            Effect.SlideUp(this.next('.product-info-section').down('.inside'), 
                {
                    duration: 0.6,
                    afterFinish: function() { 
                        if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6))
                            $$('.product-description select').invoke('setStyle', {visibility: 'visible'});
                    }                                        
            });

        }
        Event.stop(event);
    });
    
    closers.invoke('observe', 'click', function() {
        openers.invoke('removeClassName', 'active');
        Effect.SlideUp(this.up('.inside'), 
            {
                duration: 0.6,
                afterFinish: function() { 
                    if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6))
                        $$('.product-description select').invoke('setStyle', {visibility: 'visible'});
                }                                        
        });        
    });
}

function doubleCarousel(bigElementWidth, smallElementWidth) {
    var carouselContainter = $('products-carousel-container')
    if(carouselContainter) {
        var carouselContainerWidth = carouselContainter.getWidth(); 
        var trackContainer = $('scrollh-track-container');
        carouselContainter.style.overflow = 'hidden';
        var bigCarousel = $$('.products-carousel')[0];
        var carouselLength = bigCarousel.childElements().length;
        
        //if (carouselLength > 3) {
            trackContainer.show();   
            var trackWidth = $('scrollh-track').getWidth(); 
            var scrollRight = $('scrollh-track-right');
            var scrollLeft = $('scrollh-track-left');
            var smallCarousel = $$('.products-mini-carousel')[0];
            var bigCarouselWidth = carouselLength * bigElementWidth;
            var smallCarouselContainerWidth = $('products-mini-carousel-container').getWidth();
            var smallCarouselWidth = carouselLength * smallElementWidth + 1;
            var handle = $('scrollh-handle');
            var handleWidth = handle.getWidth();
            var bigScrollingWidth = bigCarouselWidth - carouselContainerWidth;
            var smallScrollingWidth = smallCarouselWidth - smallCarouselContainerWidth;
            
            
            bigCarousel.style.width = bigCarouselWidth + 'px';
            smallCarousel.style.width = smallCarouselWidth + 'px';
        
            var timer;
            var hSlider = new Control.Slider(handle, 'scrollh-track', {
                onSlide: function(val) {onSlideFunction(val)},
                onChange: function(val) {onSlideFunction(val)}
            });
            
            if(carouselLength <=3) 
                hSlider.setDisabled();
            
            onSlideFunction = function(val) {
                if(carouselLength > 3) {
                    bigCarousel.setStyle({left: (-1)*Math.floor(val*bigScrollingWidth) + 'px'});
                    if(carouselLength > 6)
                        smallCarousel.setStyle({left: (-1)*Math.floor(val*smallScrollingWidth) + 'px'});
                }
            }
            
            scrollLeft.observe('mousedown', function(event) {
                if (Event.isLeftClick(event))
                    if(carouselLength > 3) { 
                        timer = setInterval(function() {hSlider.setValueBy(-0.025);}, 25);
                        Event.stop(event);
                    }
            });
            
            scrollLeft.observe('mouseup', function() {
                clearInterval(timer);
            });  
            
            scrollLeft.observe('mouseout', function() {
                clearInterval(timer);
            });  

            scrollRight.observe('mousedown', function(event) {
                if (Event.isLeftClick(event))
                    if(carouselLength > 3) { 
                        timer = setInterval(function() {hSlider.setValueBy(0.025);}, 25);
                        Event.stop(event);
                    }
            });
                   
            scrollRight.observe('mouseup', function() {
                clearInterval(timer);
            });         

            scrollRight.observe('mouseout', function() {
                clearInterval(timer);
            });  

        
        //}
    }   
}

function updateNav(carrousel_ul, left_btn, right_btn, carrousel_ul_width, carrousel_area_width, el_width) { 
        if(carrousel_ul.positionedOffset()[0] >= el_width){
            left_btn.removeClassName('active');}
        else
            left_btn.addClassName('active');

        if(carrousel_ul.positionedOffset()[0] + carrousel_ul_width + el_width <= carrousel_area_width) 
            right_btn.removeClassName('active');
        else
            right_btn.addClassName('active');
}


function showAssistant() {
    var opener = $('sa-opener');
    var shoppingAssistant = $('shopping-assistant');
    if(opener && shoppingAssistant) {
        opener.observe('click', function() {
            var overlay = document.createElement('DIV');
            overlay.id = 'overlay';
            Element.extend(overlay);
            
            overlay.setStyle({
                opacity: 0,
                width: document.viewport.getWidth() + 'px',
                height: document.viewport.getHeight() + 'px'
            });
            
            shoppingAssistant.insert({before: overlay});
            Effect.Fade(overlay, {
                duration: 0.3,
                from: 0,
                to: 0.3,
                afterFinish: function() {shoppingAssistant.addClassName('visible'); }
            });
                       
        });
        
        Event.observe(window, 'resize', function() {
            var overlay = $('overlay')
            if(overlay) {
                var viewportWidth = document.viewport.getWidth();
                var viewportHeight = document.viewport.getHeight();
                var wrapper = $$('.wrapper')[0];
                var wrapperWidth = wrapper.getWidth();
                var wrapperHeight = wrapper.getHeight();
                overlay.setStyle({
                    width: ((viewportWidth > wrapperWidth)?viewportWidth:wrapperWidth) + 'px',
                    height: ((viewportHeight > wrapperHeight)?viewportHeight:wrapperHeight)+ 'px'
                });
            }
        });
        
        shoppingAssistant.down('img.close').observe('click', function() {
            shoppingAssistant.removeClassName('visible');
            Effect.Fade($('overlay'), {
                duration: 0.3,
                from: 0.3,
                to: 0,
                afterFinish: function() {$('overlay').remove(); }
            });            
            
        });
    }
}



function fixIE() {
    $$('select.address-select').invoke('observe', 'change', function() {
        Scroller.updateAll();
        this.up('.box').down('.button-set').toggleClassName('fix-ie');
    });
}


function showDiscountBox() {  
    var discountOpener =  $$('.discount-codes a')[0];
    if(discountOpener) {
        discountOpener.observe('click', function(event){
            this.up().hide().next('p').show();  
            Event.stop(event);   
        });   
    }
}

function checkAccept() {
    var buyButtons = $$('.checkout-types a');
    if(buyButtons) {
        buyButtons.invoke('observe', 'click', function(event) {
            var acceptCheckbox = $$('.checkout-agreements input[type=checkbox]')[0];
            if(acceptCheckbox && !acceptCheckbox.checked) {
                $$('.shopping-cart-totals .validation-advice')[0].show()
                Event.stop(event);
            }
        });
    }
}








