// JS Common, modified functions to be used in magnolia pages
// Most of the functions of the original common.js are too hard-coded to work with a cms, so we rewrote them.

/**
 * Adds the target="_blank" to all link with class "externalLink".
 * This trick with the class is required to generate a valid xhtml, because the target attribute has been deprecated. 
 */
function initExternalLink() {
  $$('a.externalLink').each( function(link) {
    link.target = "_blank";
  });
}


/**
 * Adds all the events needed to handle accordions in a magnolia page.
 * Unfortunately there is NO div container for the accordion, so everything is done computing ids... 
 * @return void
 */
function accordionMagnoliaPage() {

	// Collecting accordion elements and closing only the ones setted by cms.
	$$('.accordionContent').each(function(e) {
        if (e.getProperty('id')) {
        	var accordionId = e.getProperty('id').split('accordion_')[1];
        	if (accordionId) {
                var controller = $('trig_' + accordionId);
                // Magnolia sets the initial class for each element.
                if (controller && controller.hasClass('exp')) {
        		   // Class "exp" states that the element is collapsed and will expand on click
                   eval("_acc_" + accordionId + " = new Fx.Slide('accordion_"+accordionId+"');");
                   eval("_acc_" + accordionId + ".hide();");
                };
            	if (controller && controller.hasClass('coll')) {
         		   // Class "coll" states that the element is expanded and will collapse on click
            	   eval("_acc_" + accordionId + " = new Fx.Slide('accordion_"+accordionId+"');");
                   eval("_acc_" + accordionId + ".show();");
            	};
        	};
        };
    });
    
    $$('a.exp', 'a.coll').each(function(e) {
    	var accordionId = e.getProperty('id').split('trig_')[1];

        e.addEvent('focus', function() {
            this.blur();
        });      

        e.addEvent('click', function() {
            if (this.hasClass('exp')) {
                // Expand
            	this.removeClass('exp');
                this.addClass('coll');
                eval("_acc_" + accordionId + ".cancel();");
                eval("_acc_" + accordionId + ".slideIn();");
            } else {
                // Collapse
            	this.removeClass('coll');
                this.addClass('exp');
                eval("_acc_"+accordionId+".cancel();");
                eval("_acc_"+accordionId+".slideOut();");
            };
            var controlAll = $('trigAllAccordion_' + accordionId.split('_')[0]);
            if (controlAll) {
                var countCollapsedElements = 0;
                // Count the collapsed elements in the current paragraph (collapsed has class exp)
                $$('a.exp').each(function(e) {
                	if (e.getProperty('id') && (accordionId.split('_')[0] == e.getProperty('id').split('_')[1])) {
                		countCollapsedElements++;
                	};
                });
                if (countCollapsedElements > 0)  {
                    // When all of them are closed propose the expand all
                	controlAll.removeClass('collAll');
                    controlAll.addClass('expAll');
                    controlAll.setProperty('title', btn_collExp_expand);
                    controlAll.innerHTML = btn_collExp_expand;
                } else if (countCollapsedElements == 0) {
                    // When all of them are opened propose the collapse all
                    controlAll.removeClass('expAll');
                    controlAll.addClass('collAll');
                    controlAll.setProperty('title', btn_collExp_collapse);
                    controlAll.innerHTML = btn_collExp_collapse;
                };
            };
        });
    });
    $$('.accordionContent').each(function(e) {
        e.getParent().addClass('mooDiv');
    });

    $$('.btn_collExp').addEvent('focus', function() {
        this.blur();
    });

    // Expand all or collapse all.
    $$('.btn_collExp').addEvent('click', function() {
        if (this.hasClass('expAll')) {
        	this.removeClass('expAll');
        	this.addClass('collAll');
        	this.setProperty('title', btn_collExp_collapse);
        	this.innerHTML = btn_collExp_collapse;
        	if (this.getProperty('id')) {
        		// Each expand should operate ONLY on the accordion elements of the same group. 
        		var paragraphName = this.getProperty('id').split('trigAllAccordion_')[1];
                $$('.accordionContent').each(function(e) {
                	var accordionId = e.getProperty('id').split('_');
                	if (accordionId && (accordionId[1] == paragraphName)) {
                		eval("_acc_" + accordionId[1] + '_' + accordionId[2] + ".cancel();");
                        eval("_acc_" + accordionId[1] + '_' + accordionId[2] + ".slideIn();");
                        $('trig_' + accordionId[1] + '_' + accordionId[2]).removeClass('exp');
                        $('trig_' + accordionId[1] + '_' + accordionId[2]).addClass('coll');
                	};
                });
        	};
        } else {
        	this.removeClass('collAll');
        	this.addClass('expAll');
        	this.setProperty('title', btn_collExp_expand);
        	this.innerHTML = btn_collExp_expand;
        	if (this.getProperty('id')) {
        		var paragraphName = this.getProperty('id').split('trigAllAccordion_')[1];
                $$('.accordionContent').each(function(e) {
                	var accordionId = e.getProperty('id').split('_');
                	if (accordionId && (accordionId[1] == paragraphName)) {
                		eval("_acc_" + accordionId[1] + '_' + accordionId[2] + ".cancel();");
                        eval("_acc_" + accordionId[1] + '_' + accordionId[2] + ".slideOut();");
                        $('trig_' + accordionId[1] + '_' + accordionId[2]).removeClass('coll');
                        $('trig_' + accordionId[1] + '_' + accordionId[2]).addClass('exp');
                	};
                });
        	};
        };
        return false;
    });
}

/**
 * Adds events on the slider box.
 * @return void
 */
function promoMagnoliaSlider() {
    $$('.promoBoxStatic').each(function(e) {
        e.removeClass('promoBoxStatic');
        e.addClass('promoBox');
        var idPromo = e.getProperty('id').split('promoBox_')[1];
        eval("var _slid" + idPromo + " = createSlider($('promoWrapper_" + idPromo + "'));");
        eval('var current' + idPromo + ' = 1;');
        e.getElements('.controlBox a').each(function(a) {
        	a.addEvent('click', function(ev) {
		    	ev.preventDefault();
		    	ev.stop();
		        eval("_slid" + idPromo + ".toElement($('promo" + idPromo + "_' + this.innerHTML));");
		        eval("current" + idPromo + " = parseInt(this.innerHTML);");
		        e.getElements('.controlBox a').each(function(inner) {
		        	inner.removeClass('selected');
		        });
		        this.addClass('selected');
		        return false;
        	});
        });
        
        e.getElements('a.trigger').each(function(e) {
            e.addEvent('focus', function() { this.blur(); })
        });
        e.getElements('.controlBox a').each(function(e) {
            e.addEvent('focus', function() { this.blur(); })
        });
        e.getElements('a.trigger.slideLeft').each(function(a) {
        	a.addEvent('click', function(ev) {
            	ev.preventDefault();
            	ev.stop();
            	var controls = e.getElements('.controlBox a');
            	if (controls && controls.length > 1) {
            		controls.each(function(inner) {
	                	inner.removeClass('selected');
	                });
	                if (eval("current" + idPromo) > 1) {
	                    // There are elements to shift.
	                	eval("current" + idPromo + "--;");
	                } else {
	                    // First element, so go to the last.
	                	eval("current" + idPromo + " = " + controls.length + ";");
	                };
	                controls[eval("current" + idPromo + "-1")].addClass('selected');
	                eval("_slid" + idPromo).toElement($("promo" + idPromo + "_" + eval("current" + idPromo)));
            	};
                return false;
            });
        });
        e.getElements('a.trigger.slideRight').each(function(a) {
        	a.addEvent('click', function(ev) {
            	ev.preventDefault();
            	ev.stop();
            	var controls = e.getElements('.controlBox a');
            	if (controls && controls.length > 1) {
            		controls.each(function(inner) {
	                	inner.removeClass('selected');
	                });
	                if (eval("current" + idPromo) < controls.length) {
	                    // There are elements to shift.
	                	eval("current" + idPromo + "++;");
	                } else {
	                    // First element, so go to the last.
	                	eval("current" + idPromo + " = 1;");
	                };
	                controls[eval("current" + idPromo + "-1")].addClass('selected');
	                eval("_slid" + idPromo).toElement($("promo" + idPromo + "_" + eval("current" + idPromo)));
            	};
                return false;
            });
        });

        function createSlider(e) {
            var _slider = new Fx.Scroll(e, {
                offset: {
                    'x': 0,
                    'y': 0
                },
                wait: false,
                duration: 800,
                wheelStops: false,
                onStart: function(element) {
               	    var parentFound = element;
               	    while (((parentFound = parentFound.getParent()) != null) && (!parentFound.hasClass('promoBox')));
               	    if (parentFound && parentFound.getElement('.controlBox')) { 
               	    	parentFound.getElement('.controlBox').set('tween', {duration:150});
                      	parentFound.getElement('.controlBox').fade('out');
               	    };
                },
                onComplete: function(element) {
               	    var parentFound = element;
               	    while (((parentFound = parentFound.getParent()) != null) && (!parentFound.hasClass('promoBox')));
               	    if (parentFound && parentFound.getElement('.controlBox')) {
               	    	parentFound.getElement('.controlBox').set('tween', {duration:150});
               	    	parentFound.getElement('.controlBox').fade('in');
               	    };
                }

            });
            return _slider;
        }
    });
}

/**
 * Adds all the necessary events to handle multiple tab containers in page.
 * Handles both the special tabs for product page and the generic tab container.
 * @return void
 */
function setTabsInMagnoliaPage(){
	// Generic tabs
	$$('div.tabCont').each(function(elTab) {
		elTab.removeClass('noJS');
		elTab.getElements('div.tabHeadCont a').each(function(e) {
			e.addEvent('focus', function() { this.blur(); })
			e.addEvent('click', function(ev) {
				ev.stop();
				ev.preventDefault();
				var curLink = this;
				var curInd;
				elTab.getElements('div.tabHeadCont a').each(function(elem, i) {
    				if (elem == curLink) { curInd = i; }
    				elem.removeClass('currentTab');
    			});
				this.addClass('currentTab');
       	    	elTab.getElements('div.innerTabCont').each(function(elem, i) {
    				elem.removeClass('showTab');
    				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';
	                    };
	                });
	            };
			});
		});
	});
	
	// Specific tabs for product page, slightly different html.
	$$('dl.productDlTabs').each(function(elTab) {
		elTab.removeClass('noJS');
		elTab.addClass('tabs');
		elTab.getElements('dt a').each(function(e) {
			e.addEvent('focus', function() { this.blur(); })
			e.addEvent('click', function(ev) {
				ev.stop();
				ev.preventDefault();
				var curLink = this;
				var curInd;
      	    	elTab.getElements('dt a').each(function(elem, i) {
    				if (elem == curLink) { curInd = i; }
    				elem.removeClass('current');
    			});
				this.addClass('current');
       	    	elTab.getElements('dd').each(function(elem, i) {
    				elem.removeClass('current');
    				if(curInd == i) {
    					elem.addClass('current');
    				};
    			});
			});
		});
	});
}

/**
 * Generic function to reset and hide some divs in two pages. 
 * This handles the "tabbed-icon-content" and "partner" paragraphs, if they are in page.
 * This also replaces the "contentManager" function adding the corresponding events.
 * @return void
 */
function setTabbedIconMagnoliaPage() {
    // This is for the "tabbed-icon-content" paragraphs.
	$$('div.img_links').each(function(elem) {
		elem.getElements('a').each(function(a) {
			a.addEvent('focus', function() { this.blur(); });
			// Adding click event on all links in the head
			a.addEvent('click', function(ev) {
				ev.stop();
				ev.preventDefault();
				var divID = this.getProperty('id').split('link_')[1];
				if (divID != currentID) {
					elem.getElements('a').each(function(a) {
					    a.removeClass('current');
						var curDiv = $('id_' + a.getProperty('id').split('link_')[1]);
						if (curDiv) {
							curDiv.setStyle('display', 'none');
							curDiv.setStyle('direction', 'rtl');
							curDiv.getElement('div.tab_title').setStyle('direction', 'rtl');
						};
					});
					var newDiv = $('id_' + divID);
					if (newDiv) {
						newDiv.setStyle('display', 'inline');
						newDiv.setStyle('direction', 'ltr');
						newDiv.getElement('div.tab_title').setStyle('direction', 'ltr');
					};
					this.addClass('current');
					currentID = divID;
				};
			});
		});
    });
	$$('descriptionCont div.roundCont').each(function(elem) {
		elem.setStyle('display', 'none');
	});
	if (currentID != '') {
		var link = $$('a.link_'+currentID);
		if (link && (link.length == 1)) { link[0].addClass('current'); };
		if ($('id_' + currentID)) { $('id_' + currentID).setStyle('display', 'inline'); };
	};
	
    // This is for the "partner" paragraphs.
	$$('div.elenco_partner').each(function(elem) {
		elem.getElements('a').each(function(a) {
			a.addEvent('focus', function(){ this.blur(); });
			// Adding events for all div links in the container.
			a.addEvent('click', function(ev) {
				ev.stop();
				ev.preventDefault();
				var divID = this.getProperty('id').split('p_')[1];
				if (divID != currentID) {
					elem.getElements('a').each(function(a) {
					    a.removeClass('current');
					    if ($('s_' + a.getProperty('id').split('p_')[1])) {
					    	$('s_' + a.getProperty('id').split('p_')[1]).setStyle('display', 'none')
					    };
					});
					if ($('p_' + divID)) { $('p_' + divID).addClass('current'); };
					if ($('s_' + divID)) {$('s_' + divID).setStyle('display', 'inline'); };
					currentID = divID;
				};
			});
		});
		elem.getElements('schede_partner div.scheda_partner').each(function(elemP) {
			elemP.setStyle('display', 'none');
		});
    });
	if (currentID != '') {
		var link = $$('a.p_'+currentID);
		if (link && (link.length == 1)) { link[0].setStyle('display', 'inline'); };
		if ($('s_' + currentID)) { $('s_' + currentID).setStyle('display', 'inline'); };
	};
}