var componentDivIndex = new Array();
var componentLinkIndex = new Array();
var componentStackingOrder = new Array();
var widgetMaxHeight=500;
var closedWidgetHeight=22;
var widgetPadding=2;

function toggleWidget(currentTarget) {
	
	//alert(evt.currentTarget.id);	
	if (currentTarget.className!="component_toggle") return;
	//trova l'id nell'array
	var numeroarray=null;
	for(var k=0; k< componentLinkIndex.length; k++) {
		if (componentLinkIndex[k]==currentTarget.id) {
			numeroarray=k;
		}
	}
	if (numeroarray==null) return;
	//alert(numeroarray);
	elementoRoot = document.getElementById(componentDivIndex[numeroarray]);
	//alert(componentDivIndex[numeroarray]);
	if (elementoRoot.className=="component_open") {
		elementoRoot.className="component_closed";
	} else if (elementoRoot.className=="component_closed") {
		elementoRoot.className="component_open";
		widgetBringToFront(numeroarray);
	}

	//calcoliamo la lista delle altezze
	widgetFixHeights();
	return false; //Non ricarica la pagina
}

function widgetFixHeights() {return;
	
	var actualHeight = 0;
	for ( var i=0; i<componentStackingOrder.length; i++) {

		var elementoRoot = document.getElementById( componentDivIndex[componentStackingOrder[i]] );
		var altezza = widgetNodeHeightCalculator(elementoRoot);

		if (elementoRoot.className=="component_open") {
			if (altezza+actualHeight>widgetMaxHeight-((componentStackingOrder.length-i-1)*(closedWidgetHeight+widgetPadding)) ) {
				elementoRoot.className="component_closed";
				altezza = closedWidgetHeight;//widgetNodeHeightCalculator(elementoRoot);
			}
		} else {
			altezza = closedWidgetHeight;
		}
		//alert(widgetMaxHeight-((componentStackingOrder.length-i-1)*26));
		actualHeight+=altezza+2;
	}
	widgetSaveStack();
	widgetSaveComponentStatus();
}

function widgetNotify() {
	var links = document.links;
	for(var i = 0; i < links.length; i++) {
		if (links[i].className == "component_toggle") {
			parentComponent = widgetDOMTraversalComponent(links[i]);
			if ( parentComponent != null && parentComponent.getAttribute("notify") == "auto" && parentComponent.className=="component_closed" ) toggleWidget(links[i]);
			
			if ( parentComponent != null && parentComponent.getAttribute("notify") == "disabled" && parentComponent.className=="component_open" ) toggleWidget(links[i]);
			
			if ( parentComponent != null && parentComponent.getAttribute("notify") == "disabled" ) {
				links[i].onclick = function () { };
				
				widgetGrayOut( parentComponent );
			}
			
		}
	}
}

function widgetGrayOut(node) {
	if (node==null) return null;
	//node.style.color="#666666";
	//if (node.className=="component_open" || node.className=="component_closed") return node;
	if (node.tagName=="TD" || node.tagName=="A") {
		node.style.color="#BBBBBB";
		
	}
	var children = node.childNodes;
	for (var i=0; i<children.length; i++) {
		widgetGrayOut(children[i]);
		//alert(i);
	}
	
}


function widgetSaveComponentStatus() {
	
	var statusVector = new Array();
	
	for (var i=0; i<componentDivIndex.length; i++) {
		elementoRoot = document.getElementById( componentDivIndex[i] );
		if (elementoRoot.className=="component_open") {
			statusVector.push("o");
		} else if (elementoRoot.className=="component_closed") {
			statusVector.push("c");
		}
	}
	setCookie("widgetStatus", statusVector.join("."), 60);
}

function widgetLoadComponentStatus() {
	var statusCookie = getCookie("widgetStatus");
	if ( statusCookie == null ) return false;
	var cookieArray = statusCookie.split(".");
	if (cookieArray.length!=componentDivIndex.length) dataValid = false;
	for (var i=0; i<componentDivIndex.length; i++) {
		elementoRoot = document.getElementById( componentDivIndex[i] );
		if (cookieArray[i]=="o") {
			//elementoRoot.className="component_open";
		} else if (cookieArray[i]=="c") {
			elementoRoot.className="component_closed";
		}
	}
}

function widgetLoadStack() {
	var stackCookie = getCookie("widgetStack");
	if (stackCookie==null) return false;
	
	var tempStack = new Array();
	var cookieArray = stackCookie.split(".");
	var dataValid=true;
	
	if (cookieArray.length!=componentStackingOrder.length) dataValid = false;
	
	for (var i=0; i<cookieArray.length; i++) {
		var valore = cookieArray[i];
		//controlliamo esista e non sia stato inserito
		if (!arrayExists(componentStackingOrder,valore) || arrayExists(cookieArray,valore)) dataValid = false;
		tempStack.push(valore);
	}
	
	if (dataValid) componentStackingOrder=tempStack;
	
}

function arrayExists(arr,val) {
	var esiste=false;
	for (var i=0; i<arr.length; i++) {
		if ( arr[i]==val) esiste=true;	
	}
	return esiste;
}

function widgetSaveStack() {
	setCookie("widgetStack", componentStackingOrder.join("."), 60);
}

function widgetBringToFront( numeroarray ) {
	if ( numeroarray>=componentDivIndex.length ) return false;
	var tempArray = new Array();
	tempArray.push( numeroarray );
	for (var i=0; i<componentStackingOrder.length; i++) {
		if ( componentStackingOrder[ i ] != numeroarray ) tempArray.push(componentStackingOrder[ i ]);
	}
	componentStackingOrder = tempArray;
}

function widgetDOMTraversalComponent(node) {
	if (node==null) return null;
	if (node.className=="component_open" || node.className=="component_closed") return node;
	return widgetDOMTraversalComponent(node.parentNode);
}

function widgetNodeHeightCalculator(node) {
	if (node==null) return null;
	//Trovo childnodes
	var altezza = 0;
	var ndList = node.childNodes; 
	//itero memorizzando le altezze
	for (var i=0; i<ndList.length; i++) {
		var classNameNodo = ndList[i].className;
		if (classNameNodo=="laterale_header") {
			altezza+=ndList[i].clientHeight;
		} else if (classNameNodo=="laterale_content") {
			altezza+=ndList[i].clientHeight;
		} else if (classNameNodo=="laterale_footer") {
			altezza+=ndList[i].clientHeight;
		}
	}
	return altezza;
}

function setupWidgets() {
	//percorre i link
	var links = document.links;
	var stackingOrder = 0;
	for(var i = 0; i < links.length; i++) {
		//controlla se la class è quella desiderata
		if (links[i].className == "component_toggle") {
			//elemento trovato, setta l'id dell'elemento
			links[i].id="component_toggle_"+i;
			//alert(links[i].id);
			//trova il parent
			parentComponent = widgetDOMTraversalComponent(links[i]);
			widgetHeight = widgetNodeHeightCalculator(parentComponent);
			//se trovato setta il suo ID
			
			if ( parentComponent != null && widgetHeight!=null ) {
				parentComponent.id = "widget_root_"+i;
				//Setta il callback
				links[i].onclick = function () { return toggleWidget(this) };
				//Memorizza l'id nell'array link
				componentLinkIndex.push(links[i].id);
				componentDivIndex.push(parentComponent.id);
				componentStackingOrder.push( stackingOrder++ ); //default
			}
		}
	}
	
	//load stacking order
	widgetLoadStack();
	widgetLoadComponentStatus();
	
	//redim components
	widgetFixHeights();
	
	widgetNotify();
	
}

//Utility per i cookie
function setCookie(c_name,value,expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie  =c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return null;
}

// Appende loadevent in modo non distruttivo...
function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}
addLoadEvent(setupWidgets);
