// JS Common

window.addEvent('domready', function() {
    setFs('getFromCookie');
    styleInputs();
    styleRadios();
    styleChecks();
    
    $$('ul.secondLevel li:first-child a').each(function(e) {
		e.addClass('firstChild');
	});
    
	$$('.areaPersonaleBtn').addEvent('click', function(){
		$$('#datiAreaPersonale').tween('visibility', ['hidden', 'visible']);
	});
	$$('.btn_login_close').addEvent('click', function(){
		$$('#datiAreaPersonale').tween('visibility', ['visible', 'hidden']);
	});
    
});

function autoBlur(){
	$$('a').each( function(e) { e.addEvent('focus', function() { this.blur(); }); });
}


function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

var fs = { 'min': '12px', 'mid': '13px', 'max': '14px' } // body font-size parameters

function styleInputs() {
    allTextInps = $$('.text');
    for (var i = 0; i < allTextInps.length; i++) {
        allTextInps[i].addEvent("focus", function() {
            this.className += ' focused';
            if (this.className.match('error_inp')) {
                removeClass('error_inp', this);
                var errBoxSelect = $$('.errorbox')[0];
                if (errBoxSelect) {
                    errBoxSelect.style.display = 'none';
                    var errorid = 'error'+(errBoxSelect.id.substr(errBoxSelect.id.length-1));
                    $(errorid).style.display = 'none';
                }
            }
        });
        allTextInps[i].addEvent("blur", function() {
            removeClass('focused', this);
        });
    }
    allSubInps = document.getElementsByTagName('input');
    for (var i = 0; i < allSubInps.length; i++) {
        if (allSubInps[i].type == 'submit') {
            allSubInps[i].onmouseover = function() { this.className += ' active'; }
            allSubInps[i].onmouseout = function() { removeClass('active',this); }
        }
    }
}

function styleRadios() {
    allRadioInps = $$('.radio');
	var basePath = '..';
	if ($defined(document.getElementById('magnoliaContextPathID'))) {
		basePath = document.getElementById('magnoliaContextPathID').value;
	}
    for (var i = 0; i < allRadioInps.length; i++) {
		
		/*  Imposto il background dei radioButton personalizzati */
		allRadioInps[i].parentNode.style.background ='url(' + basePath + '/genialloyd/img/radio_noBack.gif) no-repeat top left';
		allRadioInps[i].parentNode.style.paddingLeft = 35+'px';
		
        if (allRadioInps[i].parentNode.tagName == 'LABEL') {
            if (navigator.userAgent.match('MSIE') != null) {
                allRadioInps[i].parentNode.onmousedown = function( e ) {
                	e = e || event;
                    if (e['srcElement'] && e['srcElement'].tagName != 'A') {
                        allLabels = this.parentNode.getElementsByTagName('label');
                        for (var j = 0; j < allLabels.length; j++) {
                            //allLabels[j].style.background = 'transparent url(img/radio.jpg) no-repeat top left';
                            allLabels[j].className = 'normal';
                        }
                        //this.style.background = '#e7ebf0 url(img/radio_on.jpg) no-repeat top left';
                        this.className = 'selected';
                        var errSelect = getElementsByClassName(this.parentNode, 'div', 'error')[0];
                        if (errSelect) {
                            errSelect.style.display = 'none';
                        }
                    }
                }
            } else {
                allRadioInps[i].parentNode.onmousedown = function( event ) {
                    if (event && event.target.tagName != 'A') {
                        allLabels = this.parentNode.getElementsByTagName('label');
                        for (var j = 0; j < allLabels.length; j++) {
                            //allLabels[j].style.background = 'transparent url(img/radio.jpg) no-repeat top left';
                            allLabels[j].className = 'normal';
                        }
                        //this.style.background = '#e7ebf0 url(img/radio_on.jpg) no-repeat top left';
                        this.className = 'selected';
                        var errSelect = getElementsByClassName(this.parentNode, 'div', 'error')[0];
                        if (errSelect) {
                            errSelect.style.display = 'none';
                        }
                    }
                }
            }
            
			allRadioInps[i].parentNode.onmouseover = function() {
                if (!this.getElementsByTagName('input')[0].checked) {
                    if (!this.className.match('error')) {
                        this.className += ' hover';
                        //this.style.background = '#e7ebf0 url(img/radio_hover.jpg) no-repeat top left';
                    } else {
                        this.className += ' err_hover';
                        //this.style.background = '#e7ebf0 url(img/radio_err_hover.jpg) no-repeat top left';
                    }
                }
            }
			
            allRadioInps[i].parentNode.onmouseout = function() {
                if (!this.getElementsByTagName('input')[0].checked) {
                    if (!this.className.match('error') && !this.className.match('selected')) {
                        removeClass('hover', this);
                    } else {
                        removeClass('err_hover', this);
                        //this.style.background = 'transparent url(img/radio_err.jpg) no-repeat top left';
                    }
                }
            }
            if (allRadioInps[i].checked) {
                //allRadioInps[i].parentNode.style.background = '#e7ebf0 url(img/radio_on.jpg) no-repeat top left';
                allRadioInps[i].parentNode.className = 'selected';
            }
        }            
    }
}

function styleChecks() {
    $$('label.check').each(function(e) {
        removeClass('check', e);
        e.className += ' styledCheck';
        (e.getElementsByTagName('input')[0].checked) ? e.className += ' labChecked' : void(0);
        e.addEvent('click', function() {
        	if (!(this.className.contains('labDisabled'))) {
	            if (this.getElementsByTagName('input')[0].checked) {
	                removeClass('labChecked', this);
	                this.getElementsByTagName('input')[0].checked = null;
	            } else {
	                this.className += ' labChecked';
	                this.getElementsByTagName('input')[0].checked = true;
	            }
            }
            return false;
        });
    });
}

function setFs(a) {
    var fontsz = 0;
    if (a == 'getFromCookie') {
        if (Cookie.read('genialloyd_font_size')) {
            fontsz = Cookie.read('genialloyd_font_size');
            document.body.style.fontSize = fs[fontsz];
            ($$('.'+fontsz)[0]) ? $$('.'+fontsz)[0].style.textDecoration = 'none' : void(0);
            /*if ($$('.menu')[0]) {
                fontsz = fs[fontsz];
                if (parseInt(fontsz.substr(0,2))-2 >= 11) {
                    if(navigator.userAgent.match('Safari') && parseInt(fontsz.substr(0,2))-2 == 11) {
                        $$('.menu')[0].style.marginLeft = '-10.5em';
                    } else if (navigator.userAgent.match('Safari') && parseInt(fontsz.substr(0,2))-2 == 12) {
                        $$('.menu')[0].style.marginLeft = '-14em';
                    } else { $$('.menu')[0].style.marginLeft = '-12.65em'; }
                } else { 
                    if(navigator.userAgent.match('Safari')) {
                        $$('.menu')[0].style.marginLeft = '-10.2em';
                    } else { $$('.menu')[0].style.marginLeft = '-10.3em'; }
                }
            }*/
        } else { ($$('.min')[0]) ? $$('.min')[0].style.textDecoration = 'none' : void(0); }
    } else if(a.className) {
        $$('.charResize a').each(function(item) {
            item.style.textDecoration = 'underline';
        });
        a.blur();
        a.style.textDecoration = 'none';
        fontsz = fs[a.className];
        document.body.style.fontSize = fontsz;
        /*if ($$('.menu')[0]) {
            if (parseInt(fontsz.substr(0,2))-2 >= 11) {
                if(navigator.userAgent.match('Safari') && parseInt(fontsz.substr(0,2))-2 == 11) {
                    $$('.menu')[0].style.marginLeft = '-10.5em';
                } else if (navigator.userAgent.match('Safari') && parseInt(fontsz.substr(0,2))-2 == 12) {
                    $$('.menu')[0].style.marginLeft = '-14em';
                } else { $$('.menu')[0].style.marginLeft = '-12.65em'; }
            } else { 
                if(navigator.userAgent.match('Safari')) {
                    $$('.menu')[0].style.marginLeft = '-10.2em';
                } else { $$('.menu')[0].style.marginLeft = '-10.3em'; }
            }
        }*/
        Cookie.write('genialloyd_font_size', a.className, { duration: 365 });
    }
    return false;
}

function removeClass(classe, el) {
  var re = new RegExp("(\\b|^)" + classe + "(\\b|$)", "gi");
  if (re.test(el.className)) {
        el.className = el.className.replace(re, '');
        return true;
  }
  return false;
}

function replaceClass(classe, classe2, el) {
  var re = new RegExp("(\\b|^)" + classe + "(\\b|$)", "gi");
  if (re.test(el.className)) {
        el.className = el.className.replace(re, classe2);
        return true;
  }
  return false;
}

function accordionPage(e) {
    var a;
    try { 
        e.contains(1);
        a = e;
    }
    catch(er) {
        a = new Array();
        a.push(e);
    }
    $$('.accordionContent').each(function(e,i) {
        e.id = 'accordion_'+i;
        if (a.contains(i)) {
            eval("_acc_"+i+" = new Fx.Slide('accordion_"+i+"');");
        } else {
            eval("_acc_"+i+" = new Fx.Slide('accordion_"+i+"').hide();");
        }
    });
    
    $$('.exp').each(function(e,i) {
        if (a.contains(i)) {
            e.className = 'coll';
        }
        e.id = 'trig_'+i;

        e.addEvent('focus', function() {
            this.blur();
        });      

        e.addEvent('click', function() {
            if (this.className == 'exp') {
                this.className = 'coll';
                eval("_acc_"+this.id.split('trig_')[1]+".cancel();");
                eval("_acc_"+this.id.split('trig_')[1]+".slideIn();");
            } else {
                this.className = 'exp';
                eval("_acc_"+this.id.split('trig_')[1]+".cancel();");
                eval("_acc_"+this.id.split('trig_')[1]+".slideOut();");
            }
            if ($$('a.coll').length == 0 && $$('.btn_collExp')[0]) {
                replaceClass('collAll', 'expAll', $$('.btn_collExp')[0]);
                $$('.btn_collExp')[0].innerHTML = btn_collExp_expand;
				$$('.btn_collExp')[0].title = btn_collExp_expand;
            } else if ($$('a.coll').length == $$('.accordionContent').length && $$('.btn_collExp')[0]) {
                replaceClass('expAll', 'collAll', $$('.btn_collExp')[0]);
                $$('.btn_collExp')[0].innerHTML = btn_collExp_collapse;
				$$('.btn_collExp')[0].title = btn_collExp_collapse;
            }
        });
    });
    $$('.accordionContent').each(function(e,i) {
        e.parentNode.className = 'mooDiv';
    });

    $$('.btn_collExp').addEvent('focus', function() {
        this.blur();
    });

    $$('.btn_collExp').addEvent('click', function() {
        if (this.className.match('expAll')) {
            replaceClass('expAll', 'collAll', this);
            $$('.btn_collExp')[0].innerHTML = btn_collExp_collapse;
			$$('.btn_collExp')[0].title = btn_collExp_collapse;
            $$('.accordionContent').each(function(e,i) {
                eval("_acc_"+i+".cancel();");
            });
            $$('.accordionContent').each(function(e,i) {
                eval("_acc_"+i+".slideIn();");
            });
            $$('.exp').each(function(e,i) {
                replaceClass('exp', 'coll', e);
            });
        } else {
            replaceClass('collAll', 'expAll', this);
            $$('.btn_collExp')[0].innerHTML = btn_collExp_expand;
			$$('.btn_collExp')[0].title = btn_collExp_expand;
            $$('.accordionContent').each(function(e,i) {
                eval("_acc_"+i+".cancel();");
            });
            $$('.accordionContent').each(function(e,i) {
                eval("_acc_"+i+".slideOut();");
            });
            $$('.coll').each(function(e,i) {
                replaceClass('coll', 'exp', e);
            });
        }
        return false;
    });
}

function expandAll() {
	replaceClass('expAll', 'collAll', $$('.btn_collExp'));
	$$('.btn_collExp')[0].innerHTML = btn_collExp_collapse;
	$$('.btn_collExp')[0].title = btn_collExp_collapse;
	$$('.accordionContent').each(function(e,i) {
		eval("_acc_"+i+".cancel();");
	});
	$$('.accordionContent').each(function(e,i) {
		eval("_acc_"+i+".slideIn();");
	});
	$$('.exp').each(function(e,i) {
		replaceClass('exp', 'coll', e);
	});
}

function promoSlider() {
    
    $$('.promoBoxStatic').each(function(e, i) {

        window.addEvent('domready', function() {
            replaceClass('promoBoxStatic','promoBox', e);
            eval('var pInd'+i+' = 1;');
            eval("var _slid"+i+" = createSlider('promoWrapper'+"+i+");");
            
            $$('#promoBox'+i+' .controlBox a').addEvent('click', function() {
                this.blur();
                eval("_slid"+i+".toElement('promo"+i+"_'+this.innerHTML);");
                eval("pInd"+i+" = parseInt(this.innerHTML);");
                $$('#promoBox'+i+' .controlBox a').each(function(e) {
                    removeClass('selected', e);
                });
                this.className += ' selected';
                return false;
            });
            
            $$('#promoBox'+i+' a.trigger').each(function(e) {
                e.addEvent('focus', function() { this.blur(); })
            });
            $$('#promoBox'+i+' .controlBox a').each(function(e) {
                e.addEvent('focus', function() { this.blur(); })
            });
            
            $$('#promoBox'+i+' a.trigger').addEvent('click', function() {
                if (this.getElementsByTagName('img')[0].title == 'Successivo' && eval("pInd"+i) < 3) {
                    eval("pInd"+i+"++;");
                    $$('#promoBox'+i+' .controlBox a').each(function(e) {
                        removeClass('selected', e);
                    });
                    $$('#promoBox'+i+' .controlBox a')[eval("pInd"+i+"-1")].className += ' selected';
                    eval("_slid"+i).toElement(eval("'promo"+i+"_'+"+"pInd"+i));
                } else if (this.getElementsByTagName('img')[0].title == 'Precedente' && eval("pInd"+i) > 1) {
                    eval("pInd"+i+"--;");
                    $$('#promoBox'+i+' .controlBox a').each(function(e) {
                        removeClass('selected', e);
                    });
                    $$('#promoBox'+i+' .controlBox a')[eval("pInd"+i+"-1")].className += ' selected';
                    eval("_slid"+i).toElement(eval("'promo"+i+"_'+"+"pInd"+i));
                }
                return false;
            });
        });
        
        function createSlider(e) {
            var _slider = new Fx.Scroll(e, {
                offset: {
                    'x': 0,
                    'y': 0
                },
                wait: false,
                duration: 800,
                wheelStops: false,
                onStart: function(a) {
                    var pd = a.id.charAt(a.id.length-1);
                    $$('.controlBox')[pd].set('tween', {duration:150});
                    $$('.controlBox')[pd].fade('out');
                },
                onComplete: function(a) {
                    var pd = a.id.charAt(a.id.length-1);
                    $$('.controlBox')[pd].set('tween', {duration:150});
                    $$('.controlBox')[pd].fade('in');
                }

            });
            return _slider;
        }
        
    });
}

function setTabsInPage(){
	$$('div.tabCont').each(function(el) {
		removeClass('noJS',el);
	});

	$$('div.tabHeadCont a').each(function(e) {
		e.addEvent('focus', function() { this.blur(); })
		e.addEvent('click', function() {
			var curLink = this;
			var curInd;
			this.parentNode.parentNode.parentNode.parentNode.getElements('a').each(function(elem,i) {
				if (elem == curLink) { curInd = i; }
				removeClass('currentTab',elem);
			});
			this.className = 'currentTab';
			var curContainer = this.parentNode.parentNode.parentNode.parentNode;
			curContainer.getElements('div.innerTabCont').each(function(elem,i) {
				removeClass('showTab',elem);
				if(curInd == i) {
					elem.addClass('showTab');
				}
				if (elem.style.direction == 'ltr') { 
					elem.style.direction = '';
					elem.style.direction = 'ltr';
				} else {
					elem.style.direction = 'ltr';
				}
			});
            if (navigator.userAgent.match('MSIE')) {
                $$('.showTab a.exp', '.showTab a.coll').each(function(el) {
                    if (el.style.direction == 'ltr') { 
                        el.style.direction = '';
                        el.style.direction = 'ltr';
                    } else {
                        el.style.direction = 'ltr';
                    }
                });
            }
		});
	});
}

//patch moodalbox mootools
Request.HTML.implement({
 
        processHTML: function(text){
            var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
            text = (match) ? match[1] : text;
            
            var container = new Element('div');
            
            return $try(function(){
                var root = '<root>' + text + '</root>', doc;
                if (Browser.Engine.trident){
                    doc = new ActiveXObject('Microsoft.XMLDOM');
                    doc.async = false;
                    doc.loadXML(root);
                } else {
                    doc = new DOMParser().parseFromString(root, 'text/xhtml');
                }
                root = doc.getElementsByTagName('root')[0];
                for (var i = 0, k = root.childNodes.length; i < k; i++){
                    var child = Element.clone(root.childNodes[i], true, true);
                    if (child) container.grab(child);
                }
                return container;
            }) || container.set('html', text);
        }
    
    });

