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() {
    //fix for IE png transparency bug
    pngFix();

    //dropdown menu in ie6
    startList();

    //put labels into text input values
    labelToInput();
    
    //tabs switching
    tabs();

    //marking clicked element as 'active'    
    markActive();
    
    //toggle details of product in cart
    toggleDetails();

    //rollover effect for text buttons
    btnHover();
    
    //rollover effect for image buttons (with images preloading)
    btnImgHover();
    
    //rollover effect on checkout headers
    checkoutHover();
    
});

window.onload = function() {
    //modal window with products list
   modalWindow();
   //lightboxes();
}
function popupImg(sHref,iW,iH) {
    var win=window.open('', 'gallery', 'width='+iW+',height='+iH+',left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes');
    var sDocument='<html><body style="padding:0;margin:0">';
    sDocument+='<img height="'+iH+'" width="'+iW+'" src="'+sHref+'"/>';
    sDocument+='</body></html>';
    win.document.write(sDocument);
}
function lightboxes() {
    var oContainer=$('programme-products-steps');
    if(!oContainer)
            return;
      var aImages=oContainer.select('a.lightbox');
            //aLightBoxes=new Array();
            for(var i=0,j=aImages.length;i<j;i++) {
               aImages[i].onclick=function() {
                   popWin(this.href, 'gallery', 'width=300,height=300,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;
               }
            }
}
function pngFix() {

    if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6)) {
        var toFix = $$('.pngfix, .header-nav li li');
        for (var i=0;i<toFix.length; i++) {
            var bgImg = toFix[i].getStyle('backgroundImage');
    			if(bgImg.indexOf(".png")!=-1){
    			    var iebg;
    			    if(bgImg.indexOf('url("')!=-1) 
    				    iebg = bgImg.split('url("')[1].split('")')[0];
    				else
    				    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 startList() {
    if (document.all && document.getElementById) {
        var navRoots = $$('.header-nav > ul');

        for (j=0; j<navRoots.length; j++) {
            navRoot = navRoots[j];
            lis = navRoot.childNodes;
            for (i=0; i<lis.length; i++) {
                node = lis[i];

                if (node.nodeName=="LI") {
                    Event.observe(node, "mouseover",function() {
                        toggleMenu(this, true);
                        Element.extend(this);
                        var ulChild = this.down('ul');
                        if(ulChild) {
                            var ulwidth = this.down('ul').getWidth() - 24;
                            this.select('li a').invoke('setStyle', {width: ulwidth + 'px'});
                        }
                    });
                    Event.observe(node, "mouseout",function() {
                        toggleMenu(this, false);
                    });
                }
        }
        }
    }
}




function labelToInput() {
    var labels = $$('.labelvalue');
    if(labels)
    	labels.each(function(elem){								
			elem.hide();	
			var txt = elem.innerHTML;
			var chpsTxt = elem.next('input.input-text'); //$(elem.readAttribute('for')); 

			chpsTxt.value = txt;
			chpsTxt.observe('focus', function(e){if(e.target.value == txt) e.target.value = ''});
			chpsTxt.observe('blur', function(e){if(e.target.value == '') e.target.value = txt});
    	});
}



function tabs() {
    $$('.tabs-nav').each(function(tabNav){
        tabNav.adjacent('.tab-item').invoke('hide');

        tabNav.select('a').each(function(tabLink) {
            if(tabLink.hasClassName('active'))
                $(tabLink.readAttribute('href').replace('#', '')).show();

            tabLink.observe('click', function(event){
                var parentUL = this.parentNode.parentNode;
                parentUL.select('a').invoke('removeClassName', 'active');
                this.addClassName('active');

                parentUL.adjacent('.tab-item').invoke('hide');
                $(this.readAttribute('href').replace('#', '')).show();

                event.stop();
            });
        });

    });
}



function markActive() {
        var elements = $$('.more-views ul a');
        elements.each(function(el) {
        el.observe('click', function(){
            elements.invoke('removeClassName', 'active');
            this.addClassName('active');
        });
    });
}



function toggleDetails() {
    $$('.data-table .attributes-col  span.toggle').invoke('observe', 'click', function() {
        this.up().next('.product-contents').toggle();
        this.toggleClassName('up');
    });
}


function goToNext(elem) { 
    Element.extend(elem);
    var activeLi = elem.up('li');
    var nextLi = activeLi.next('li');
    activeLi.removeClassName('active');
    nextLi.addClassName('active');
    
    nextLi.previousSiblings().invoke('addClassName', 'previous-step');
}


function goToPrev() {
    var steps = $('programme-products-steps');
    if(steps) {
        Element.extend(steps);
        //var heads = steps.select('li .head');
        var heads = $$('.head');
        for(i=0; i<heads.length; i++) {
        //Element.extend(heads[i]);
        heads[i].observe('click', function() {
            var currentLi =  this.up('li');
            if(currentLi.hasClassName('previous-step')) {
                currentLi.nextSiblings().invoke('removeClassName', 'previous-step').invoke('removeClassName', 'active');
                currentLi.removeClassName('previous-step').addClassName('active');
            }
        });
        }
    }
}



function btnHover() {
    $$('button.form-button-alt, button.form-button, .balance-form input.input-submit, .btn-type, .programmes-ask input.input-submit, .cart-box .button-set a ')
        .invoke('observe', 'mouseover', function() {
            //this.addClassName('btn-hover');
            this.setStyle({backgroundColor: '#3a3a3a'});
        }) 
        .invoke('observe', 'mouseout', function() {
            this.setStyle({backgroundColor: '#58ac25'});
        });          
}


function btnImgHover() { 

    var buttons = $$('.home-intro .join a img, .add-to-holder button img, .cart-box .last-product .widget-btn img, #shopping-cart-table tbody td.last img, .checkout-types li img, .custom-programme .submit-button-set button img, .kitchendiet-choice .col-2 .button-set img, .client-choice .col-2 img, #options_program img.close-modal, #review-buttons-container input, .personal-steps .bottom-buttons .right img');

    for(var i=0, images=[]; i<buttons.length; i++) {
        var newSrc = buttons[i].src.replace('.png', '-on.png');
        var j;
        var check = false;
        for(j=0; j<images.length; j++) {
            if(images[j].src == newSrc) {
                check = true;
                break;
            }
        }
        if(!check) {
            images.push(new Image());
            images.last().src = newSrc;
        }
    }

    for(var i=0; i<images.length; i++) {
        images[i].onload = function() {
            for(j=0; j<buttons.length; j++) {
                origSrc = this.src.replace('-on', '');
                if(buttons[j].src == origSrc) {
                    if(buttons[j].parentNode.nodeName == 'BUTTON') {
                        Element.extend(buttons[j].parentNode);
                        buttons[j].parentNode.observe('mouseover', function(){
                            childImg = this.down('img');
                            childImg.src = childImg.src.replace('.png', '-on.png');
                        });
                        buttons[j].parentNode.observe('mouseout', function(){
                            childImg = this.down('img');
                            childImg.src = childImg.src.replace('-on', '');
                        });
                    } 
                    else {
                        buttons[j].observe('mouseover', function(){
                            this.src = this.src.replace('.png', '-on.png');
                        });
                        buttons[j].observe('mouseout', function(){
                            this.src = this.src.replace('-on', '');
                        });
                    }
                }
            }
        }
    }
}



function checkoutHover() {
    $$('#checkoutSteps li.allow .head').invoke('observe', 'mouseover', function(){
        this.addClassName('head-hover');
    }).invoke('observe', 'mouseout', function(){
        this.removeClassName('head-hover');
    });
}


function modalWindow() {
    var modalWindowBox = $('options_program');
    if(modalWindowBox) {
        var modal = new Control.Modal(modalWindowBox,{  
            overlayOpacity: 0.75,  
            className: 'modal',  
            fade: true,
            iframeshim: false,
            beforeOpen: function() {
                if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6))
                    $$('select').invoke('setStyle', {visibility: 'hidden'});
            },
            afterOpen: function() {
            if(!$('scroll-innerBox-1'))
                Scroller.setAll();
            },          
            afterClose: function() {
                if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6))
                    setTimeout(function() {$$('select').invoke('setStyle', {visibility: 'visible'})}, 250);
                setTimeout(function() {$$('iframe').invoke('hide');}, 500);
            }
        });  
   
        var opener = $('show-list');
        if(opener)    
            opener.observe('click', function(event) {
                modal.open();
                Event.stop(event);
            });
        
        var closer = modalWindowBox.down('.close-modal');
        if(closer) {
            closer.observe('click', function(){
                modal.close();
            });
        }
    }
}


Validation.addAllThese([
    ['validate-zip-international', 'Please enter a valid zip code.', function(v) {

            //return Validation.get('IsEmpty').test(v) || /(^[A-z0-9]{2,10}([\s]{0,1}|[\-]{0,1})[A-z0-9]{2,10}$)/.test(v);
            return Validation.get('IsEmpty').test(v) || /(^\d{5}$)/.test(v);
            }],
    ['validate-telephone-no', 'Please enter a valid phone number without spaces.', function(v) {

            //return Validation.get('IsEmpty').test(v) || /(^[A-z0-9]{2,10}([\s]{0,1}|[\-]{0,1})[A-z0-9]{2,10}$)/.test(v);
            return Validation.get('IsEmpty').test(v) || /(^\d{10}$)/.test(v);
            }]
]

);
