/* CORRETTO BUG PRIMO LIVELLO */
var timerID;
var levelFind = false;
var levelToStart = 0;
var is_visible = 'yes';
var idSelected = '';
var image_path = '/images/';
var path_url = "/index.php";
var path_spacer = '/images/spacer.gif';
var path_freccia_down = '/images/freccia_menu_down.gif';
var path_freccia_right = '/images/freccia_menu_right.gif';
var borderCol = "#FFFFFF";
var width = 240;
var height = 20;
var style = 'horizontal'; //valori possibili -> vertical, horizontal, select, table
var dMap = false;
var backgroundColorOver = new Array("#435475", "#FFBC00", "#FFBC00", '#FFBC00'); //colore quando sono su una cella
var backgroundColor = new Array("#9BA6BD", "#7B879E", "#9BA6BD", '#F0F1F6'); // colore primo livello, secondo livello e terzo livello
var styleColor = new Array("menuprimo", "menusecondo", "menuterzo", "menuquarto"); // style primo livello, style secondo livello, style terzo livello
var styleSelected = new Array('menustyleselected1','menustyleselected2','menustyleselected3','menustyleselected3','menustyleselected3','menustyleselected3','menustyleselected3');

function getAbsX(elt){
 return (elt.x) ? elt.x : getAbsPos(elt,"Left");
}

function getAbsY(elt){
 return (elt.y) ? elt.y : getAbsPos(elt,"Top");
}

function getAbsPos(elt,which){
	iPos = 0;
	while (elt != null){
		iPos += elt["offset" + which];
		elt = elt.offsetParent;
	} 
	
	return iPos;
}

function Is(){
	var agent = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
	this.minor = parseFloat(navigator.appVersion);
	this.ns = ((agent.indexOf('mozilla')!= -1) && ((agent.indexOf('spoofer')== -1) && (agent.indexOf('compatible')== -1)));
	this.ns4 = (this.ns && (this.major == 4));
	this.ns6 = (this.ns && (this.major >= 5));
	this.ie = (agent.indexOf("msie")!= -1);
	this.ie4 = (this.ie && (this.major == 4) && (agent.indexOf("msie 5.")== -1));
	this.ie5 = (this.ie && (this.major >= 4)&& (agent.indexOf("msie 5.")!=-1));
}

function aaa(anim){ 
	var is = new Is();
	if(is.ns6){
		xPos = document.images[anim].offsetLeft
	}
	
	else if(document.getElementById){
			myObject = document.getElementById(anim)
			xPos = getAbsX(myObject)
		}else if(document.layers){
					var doc =eval('document.'+anim)
					myObject = doc
					xPos = getAbsX(myObject)
				}else if (document.all) {
							var doc =eval('document.all.'+anim)
							myObject=doc
							xPos = getAbsX(myObject)
						}  

	return(xPos);
}

function str_replace(what, wwhat, where){
	re = eval("/"+ what + "/gi")
	return where.replace(re, wwhat);
}

// Node object
function Node(id, fatherId, name, url, isOpen) {
	this.id = id;
	this.fatherId = fatherId;
	this.name = name;
	this.url = url;
	//this.other = other;
	this.level = 0;
	this.isOpen = isOpen || false;
	this.lastChild = false;
	this.hasChildren = false;
	
	//alert(this.name + '---' + this.isOpen)
};

//Tree object
function Tree(objName, width, height, style, indent, home, overEffects) {
	this.config = {
		viewHome		: home || false,
		useCookies		: true,
		useStatusText	: true,
		closeSameLevel	: true,
		width			: width || 200,
		height			: height || 25,
		indent			: indent || false,
		style			: style || 'vertical',
		top				: top || 0,
		left			: left || 0,
		overEffects		: overEffects				
	}
	
	this.obj = objName;
	this.Nodes = [];
	this.Indent = [];
	this.principalNode = [];
};

// Outputs the tree to the page
Tree.prototype.toString = function() {
	for (n=0; n<this.Nodes.length; n++){
		this.findChildren(this.Nodes[n]);
	}
	var str = '';
	
	
	
	if (document.getElementById) {
		str += this.addNode(this.Nodes[0]);
	} else str += 'Browser not supported.';
	
	//prompt('',str);
	return str;
};

// Creates the tree structure
Tree.prototype.addNode = function(pNode) {
	var str = '';
	var n=0;
	
	for (n; n<this.Nodes.length; n++) {
		var cn = this.Nodes[n];
		
		if (this.Nodes[n].fatherId == pNode.id) {
			
			//if (cn.hasChildren && !cn.isOpen && this.config.useCookies) cn.isOpen = this.isOp(cn.id);
			
			str += this.node(cn,n);
			
			
			
			if (cn.lastChild) break;
		}
	}
	return str;
};

// Creates the node icon, url and text
Tree.prototype.node = function(node, nodeId) {
	var str = '';
	var bgcolor;
	this.findLevel(node);
	
	bgcolor = backgroundColor[node.level];
	css = (node.id==idSelected)?styleSelected[node.level]:styleColor[node.level];
	display = (node.level == 0)?'':'none';
	
	//alert(node.name + '---' + node.isOpen)
	
	if(node.level == 0){
		this.principalNode.push(this.obj + nodeId);
		left = left + this.config.width - 1;
	}
	
	var positioning = '';
	if(this.config.style == 'horizontal' && node.level == 0) positioning = 'position:absolute; top:' + top + 'px; left:' + left + 'px;';
	
	if(node.level == 0) str += '<div id="' + this.obj + nodeId + '" style="width:' + this.config.width + 'px; display:'+display+';'+positioning+'">';
	
	str += '<table width="' + this.config.width + '" cellspacing="0" cellpadding="0" border="0" bgcolor="'+bgcolor +'">';
	str += '<tr>';
	
	width = this.config.width - 1;
	
	if(node.level == 0 && node.hasChildren){
		link = ' href="javascript:' + this.obj + '.o(' + nodeId + ');"';
	}else{
		re = /^\d+$/
		//se sono solo caratteri numerici costruisco il link sennò metto direttamente la url
		if(re.test(node.url)) link = ' href="' + path_url + '?sid=' + node.url + '"';
			else if(node.url.indexOf("openWin") >= 0) link = ' href="' + node.url + '"';
			else link = ' href="' + node.url + '"';
		
		//if(node.url.indexOf("http://") >= 0) link += ' target="_blank"';
	}
	
	str += '<td width="1" bgcolor="' +borderCol+ '"><img src="' +path_spacer+ '" height="1"></td>';
	str += '<td id="td' + nodeId + '" width="' + width + '" height="' + this.config.height + '"';
	if(node.level == 0) str += ' align="center"';
		//else  str += ' style="padding-left:5px; padding-right:5px"';
		//else  str += ' style="padding:0px 5px 2px 5px"';
		else if(this.config.indent) str += ' style="padding-top:0px; padding-left:' + (5+((node.level-1)*10)) + 'px; padding-bottom:2px; padding-right:5px"';
	str += '>';
	
	

	str += '<a';
	if(this.config.overEffects){
		if(node.level == 0) str += ' onclick="setBgColor(\'' + nodeId + '\' ,\'' + node.level + '\'); " onmouseover="canceltimeout()" onmouseout="timeout()"';
			else  str += ' onmouseover="setBgColor(\'' + nodeId + '\' ,\'' + node.level + '\'); canceltimeout()" onmouseout="resetBgColor(\'' + nodeId + '\' ,\'' + node.level + '\'); timeout()"';
	}
	str += ' id="s' + this.obj + nodeId + '" class="' + css + '" ' + link + '>';

	str +=  node.name;
	
	str += '</a>';
	str += '</td>';
	str += '<td width="1" bgcolor="' +borderCol+ '"><img src="' +path_spacer+ '" height="1"></td>';
	str += '</tr>';
	str += '<tr><td colspan="3" height="1" bgcolor="' +borderCol+ '"><img src="' +path_spacer+ '" height="1"></td></tr>';
	str += '</table>';
	
	if (node.hasChildren) {
		str += '<div id="d' + this.obj + nodeId + '" style="display:' + ((node.level == 0) ? 'none' : '') + ';  width:' + this.config.width + 'px">';
		str += this.addNode(node);
		str += '</div>\n';
	}
	
	if(node.level == 0)
		str += '</div>\n';
	
	this.Indent.pop();
	return str;
};


// [Cookie]
Tree.prototype.isOp = function(id) {
	var io = this.getCookie('co' + this.obj).split('.');
	for (var n=0; n<io.length; n++)
		if (io[n] == id) return true;
	return false;
};

// [Cookie] Clears a cookie
Tree.prototype.clearCookie = function() {
	var now = new Date();
	var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
	this.setCookie('co'+this.obj, 'cookieValue', yesterday);
	this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};

// [Cookie] Sets value in a cookie
Tree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
};

// [Cookie] Gets a value from a cookie
Tree.prototype.getCookie = function(cookieName) {
	var cookieValue = '';
	var posName = document.cookie.indexOf(escape(cookieName) + '=');
	if (posName != -1) {
		var posValue = posName + (escape(cookieName) + '=').length;
		var endPos = document.cookie.indexOf(';', posValue);
		if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
		else cookieValue = unescape(document.cookie.substring(posValue));
	}
	return (cookieValue);
};

// [Cookie] Returns ids of open nodes as a string
Tree.prototype.updateCookie = function() {
	var str = '';
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].isOpen) {
			if (str) str += '.';
			str += this.Nodes[n].id;
		}
	}
	this.setCookie('co' + this.obj, str);
};




// Adds a new node
Tree.prototype.add = function(id, fatherId, name, url, isOpen) {
	this.Nodes[this.Nodes.length] = new Node(id, fatherId, name, url, isOpen);
};

// Checks if a node has any children and if it is the last sibling
Tree.prototype.findChildren = function(node) {
	var lastId;
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].fatherId == node.id) node.hasChildren = true;
		if (this.Nodes[n].fatherId == node.fatherId) lastId = this.Nodes[n].id;
	}
	if(lastId==node.id) node.lastChild = true;
};

Tree.prototype.findLevel = function(node) {
	node.level = this.Indent.length;
	(node.lastChild) ? this.Indent.push(0) : this.Indent.push(1);
};

Tree.prototype.indent = function(node,spacer) {
	var str = '';
	for (var n=0; n<node.level; n++) str += spacer;
	return str;
};

// Toggle Open
Tree.prototype.o = function(id) {
	var cn = this.Nodes[id];
	
	this.closeMenuNoThis(id);
	
	if(cn.isOpen){
		resetBgColor(id,0)
		this.nodeStatus(false, id)
		cn.isOpen = false;
	}else{
		setBgColor(id,0)
		this.closeLevel(this.Nodes[id]);
		this.nodeStatus(true, id);
		cn.isOpen = true;
	}
	
	
	
	//if(!cn.isOpen) this.closeAllChildren(this.Nodes[id]);
	//timeout();
};

// Open or close all nodes
Tree.prototype.oAll = function(status) {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].hasChildren && this.Nodes[n].fatherId != 0) {
			this.nodeStatus(status, n)
			this.Nodes[n].isOpen = status;
		}
	}
};

// Open/close all nodes
Tree.prototype.openAll = function() {
	this.oAll(true);
};
Tree.prototype.closeAll = function() {
	this.oAll(false);
};


Tree.prototype.closeMenu = function() {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].fatherId == 1) {
			resetBgColor(n,0)
			this.nodeStatus(false, n)
			this.Nodes[n].isOpen = false;
		}
	}
};

Tree.prototype.closeMenuNoThis = function(id) {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].fatherId == 1) {
			resetBgColor(n,0)
			if(n != id){
				this.nodeStatus(false, n)
				this.Nodes[n].isOpen = false;
			}
		}
	}
};


// Change the status of a node(open or closed)
Tree.prototype.nodeStatus = function(status, id) {
	eDiv = document.getElementById('d' + this.obj + id);
	//alert(eDiv.style.display);
	if(eDiv) eDiv.style.display = (status) ? 'block': 'none';
};

// Closes all nodes on the same level as certain node
Tree.prototype.closeLevel = function(node) {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].fatherId == node.fatherId && this.Nodes[n].id != node.id && this.Nodes[n].hasChildren) {
			this.nodeStatus(false, n);
			this.Nodes[n].isOpen = false;
			//this.closeAllChildren(this.Nodes[n]);
		}
	}
}

Tree.prototype.closeAllChildren = function(node) {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].fatherId == node.id && this.Nodes[n].hasChildren) {
			if (this.Nodes[n].isOpen) this.nodeStatus(false, n);
			this.Nodes[n].isOpen = false;
			this.closeAllChildren(this.Nodes[n]);
		}
	}
}

// Returns the selected node
Tree.prototype.getSelected = function() {
	var sn = this.getCookie('cs' + this.obj);
	return (sn) ? sn : null;
};

// Change stylesheet to a specific node
Tree.prototype.changeStyleNode = function(nId, style) {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].id == nId) {
			nId = n;
			break;
		}
	}
	
	if(document.getElementById("td" + nId))
		document.getElementById("td" + nId).className = style;
}

// Opens the tree to a specific node
Tree.prototype.openTo = function(nId) {
	for (var n=0; n<this.Nodes.length; n++) {
		if (this.Nodes[n].id == nId) {
			nId = n;
			break;
		}
	}
	
	
	var cn = this.Nodes[nId];
	if (cn.fatherId == 0) return;
	
	css = styleSelected[cn.level-1];
	if(document.getElementById("s" + this.obj + nId))
		document.getElementById("s" + this.obj + nId).className = css;
	
	if(cn.hasChildren){
		this.o(nId);
		cn.isOpen = true;
		this.nodeStatus(true, nId);
	}
	
	this.openTo(cn.fatherId);
};


// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
};
if (!Array.prototype.pop) {
	Array.prototype.pop = function array_pop() {
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
};


function WoR(){
	var top = getAbsPos(document.images['layerMenu'],"Top");
	var left = getAbsPos(document.images['layerMenu'],"Left") - 1;
	
	for(i=0;i<d.principalNode.length;i++){
		document.getElementById(d.principalNode[i]).style.top = top;
		document.getElementById(d.principalNode[i]).style.left = (left + (width * i));
		
	}
}

function canceltimeout(){
	if(timerID) clearTimeout(timerID);
}

function timeout(){
	timerID = setTimeout("d.closeMenu()",3000);
}

function setBgColor(id,level){
	nId = fatherNode;
	for (var n=0; n<d.Nodes.length; n++) {
		if (d.Nodes[n].id == nId) {
			nId = n;
			break;
		}
	}
	if(id != nId) document.getElementById("td" + id).style.background = backgroundColorOver[level];
}

function resetBgColor(id,level){
	nId = fatherNode;
	for (var n=0; n<d.Nodes.length; n++) {
		if (d.Nodes[n].id == nId) {
			nId = n;
			break;
		}
	}
	if(id != nId) document.getElementById("td" + id).style.background = backgroundColor[level];
}
