// variabili globali
var mem_win = new Array();

// aggiunge il supporto al PopUp
if (!document.getElementById('pop_up_class')) {
        
	var s = document.createElement("script");
      
	s.setAttribute("id", "pop_up_class");
	s.setAttribute("type", "text/javascript");
	s.setAttribute("src", "/script/popup/source/PopUpClass.js");
      
	document.getElementsByTagName("head")[0].appendChild(s);
       
}

	// aggiunge il supporto al drag and drop
	var script_drag = document.getElementById('drag_script');

	if (!script_drag) {
        
		var src = "/script/drag/" + "drag.js";

		/* cerca se c'è uno script con src uguale a drag.js,
			se non esiste lo crea */
		var scripts = document.getElementsByTagName("script");
		var i = -1;
		if (scripts.length > 0) {
			for (i = 0; i < scripts.length; i++) {
				if (scripts[i].getAttribute("src") == src) 
					break;
			}
		}

		if ( i == scripts.length ) {

			var script_node = document.createElement("script");

			script_node.setAttribute("id", "drag_script");
			script_node.setAttribute("type", "text/javascript");
			script_node.setAttribute("src", src );
      
			document.getElementsByTagName("head")[0].appendChild(script_node);
			
		}
		else if ( i >= 0 ) {
			scripts[i].setAttribute("id", "drag_script");
		}
       
	}


function findPos(obj) {
	
	var curleft = curtop = 0;

	// If the browser supports offsetParent we proceed.
	if (obj.offsetParent) {

	// Every time we find a new object, we add its offsetLeft and offsetTop to curleft and curtop.
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);

	}
	// Finally, when the while loop has quit, 
	// we return an array with the calculated coordinates to whichever script asked for it.
	return [curleft,curtop];
	
}

function createMenuItem(menu_cont, button, depth) {
        
	// depth è la profondità della chiamata
	if (!depth) { depth = 1;}
        var n_id = button.getAttribute("id");

        var figli = button.childNodes;
        
	var s = document.createElement("div");
        s.setAttribute("id", n_id);
        s.setAttribute("class", "win_menu");
        s.setAttribute("onmouseover", "menuMouseover(event)");
        // per IE
        s.style.className = "win_menu";
        s.onmouseover = "menuMouseover(event)";
                
        for (var i=0; i<figli.length;i++) {
                
                if (figli[i].tagName == "item") {
                        
                        var item = figli[i];
                        var caption = item.getAttribute("caption");
                        var a = document.createElement("a");
                        a.setAttribute("class", "menuItem");
                        // per IE
                        a.style.className = "menuItem";
                        
                        if (item.getElementsByTagName("item").length > 0) {
                                
				depth++;
                                var sId = item.getAttribute("id");
				if (!sId) {
					sId = depth + "_" + i;
					item.setAttribute("id", sId);
				} 

                                a.setAttribute("onmouseover", "menuItemMouseover(event, '" + sId + "');");
                                a.onmouseover="menuItemMouseover(event, '" + sId + "');";
                                                
                                var span = document.createElement("span");
                                span.setAttribute("class", "menuItemText");
                                span.appendChild(document.createTextNode(caption));
                                a.appendChild(span);
                        
                                span = document.createElement("span");
                                span.setAttribute("class", "menuItemArrow");
                                span.appendChild(document.createTextNode("&#9654;"));
                                
                                a.appendChild(span);
                                createMenuItem(menu_cont, item, depth);
                        
                        }
                        else {
				var la_azione = item.getAttribute("azione");
				var la_query = item.getAttribute("query");
				var i_param = item.getAttribute("param");
				if (la_azione) {
					var chiamata = "callA('" + la_azione + "'";
					if (la_query) {
						chiamata += ",'" + la_query + "'";
					}
					if (i_param) {
						chiamata += ",'" + i_param + "'";
					}
					chiamata += ")";
		                        a.setAttribute("onclick", chiamata);
				}
				else {
		                        a.setAttribute("href", item.getAttribute("href"));
				}
                                a.appendChild(document.createTextNode(caption));
                        }
                        
                        s.appendChild(a);
                }
        
        }

        menu_cont.appendChild(s);

}

function Comando (_azione, _query, _param) {
        
        this.azione = _azione;
        this.query  = _query;
        this.param  = _param;

}

function Queque()  {
        
        this.current_win = -1;
        this.old_win = -1;
        this.last_win = -1;
        
        this.comandi = new Array();        
        
        this.Add = function(azione, query, param) {

		if (this.old_win == this.current_win) {
                	this.last_win++;
        	        this.comandi[this.last_win] = new Comando(azione, query, param);
	                this.current_win = this.last_win;
		}

                this.old_win = this.current_win;

        };
             
        this.Azione = function() {
                return (this.comandi[this.current_win]).azione;
        };
        this.Query = function() {
                return (this.comandi[this.current_win]).query;
        };
        this.Param = function() {
                return (this.comandi[this.current_win]).param;
        };
}


function getBrowser() {

	appCodeName = navigator.appCodeName; //	Nome in codice del browser (es. Mozilla)
	appName = navigator.appName;	// 	Nome del browser (es. Netscape o Microsoft Internet Explorer)
	appVersion = navigator.appVersion;	// 	Versione del browser (es. 3.0 o 4.0)
	userAgent = navigator.userAgent;	// 	Titolo completo del browser. (es. Mozilla/4.0)
	platform = navigator.platform;	// 	Sistema operativo dell'utente (es. WIN32)


	if (appName.indexOf("Netscape")!=-1) {
		appName="NS";
	}
	else if (appName.indexOf("Microsoft")!=-1) {
		appName="MSIE";
	}
	else if (appName.indexOf("Opera")!=-1) {
		appName="Opera";
	}

	return (appName);

}

function processXML (xml, param) {

    
	var id_nodo = "msg_nodo";
	var parent_node = "body";
	var position = "absolute";
	var drag = false;
	var base_style = false;

	var pos_x = "", pos_y = "";

	var i;
	var str;
	
	if (param) {
		var coppie = param.split(";");
		for (i=0; i < coppie.length; i++) {
			var coppia = coppie[i].split(":");
			var nome = coppia[0];
			var valore = coppia[1];
			switch (nome) {
				case "id_nodo" : 	
					id_nodo = valore;
					break;
				case "parent" : 	
					parent_node = valore;
					break;
				case "position" : 	
					position = valore;
					break;
				case "drag" : 	
					drag = (valore=="yes") || (valore=="si") || (valore=="true");
					break;
				case "style" : 	
					base_style = !((valore=="no") || (valore=="false"));
					break;
				case "x" : 	
					pos_x = valore;
					break;
				case "y" : 	
					pos_y = valore;
					break;
			}
		}	
	}
	
	// imposta stili esterni se ci sono   
	var link = xml.getElementsByTagName("link");

	for (i = 0; i < link.length; i++) {		
      		
		var id_link = link[i].getAttribute("id");

		var link_obj = document.getElementById(id_link);
    
		if (link_obj) { 
      
			// lo stile non esiste allora inseriscilo
			var link_node = document.createElement('link');
      
		        link_node.setAttribute('id', link[i].getAttribute("id"));
		        link_node.setAttribute('rel', 'stylesheet');
		        link_node.setAttribute('type', 'text/css');
	        	link_node.setAttribute('href', link[i].getAttribute("href"));
      
		        document.getElementsByTagName("head")[0].appendChild(link_node);

		}
	}

	// imposta script esterni se ci sono   
	var script = xml.getElementsByTagName("script");

	for (i = 0; i < script.length; i++) {		
      		
		var id_script = script[i].getAttribute("id");

		var script_obj = document.getElementById(id_script);
    
		if (!script_obj) { 
			// lo script non esiste allora inseriscilo
			var script_node = document.createElement('script');
      
		        script_node.setAttribute('id', script[i].getAttribute("id"));
		        script_node.setAttribute('type', script[i].getAttribute("type"));
	        	script_node.setAttribute('src', script[i].getAttribute("src"));
      
		        document.getElementsByTagName("body")[0].appendChild(script_node);

		}
	}

	// gli stili online che possono sovrascrivere quelli di default
	if (xml.getElementsByTagName("style")) {

		var style = xml.getElementsByTagName("style")[0];

		if (style) 
		{

			var cont;
			if (style.childNodes) {
				cont =  style.childNodes[0].nodeValue;}
			else {cont = "";}
			// il tag style esiste, allora prosegui
     		
			var id_style = style.getAttribute("id");
			var style_obj = document.getElementById(id_style);
    
			if (!style_obj) { 

				// inseriscilo
				var s = document.createElement("style");
				s.setAttribute("id", id_style);
				s.setAttribute("type", "text/css");

				document.getElementsByTagName("head")[0].appendChild(s);

				if (s.styleSheet) {		// IE
					s.styleSheet.cssText = cont;
				}
				else {
					var css_text_node_loc = document.createTextNode(cont);
					s.appendChild(css_text_node_loc);
				}

			}
		}

	} 


	var menu = xml.getElementsByTagName("menu");
	var menu_cont = document.createElement("div");
        
	// imposta il menu se esiste
	if (menu.length > 0) {
        
		// aggiunge il supporto ai menu
		if (!document.getElementById('menu_class')) {
        
			var m = document.createElement("script");
      
			m.setAttribute("id", "menu_class");
			m.setAttribute("type", "text/javascript");
			m.setAttribute("src", "/script/menu/menu.js");
      
			document.getElementsByTagName("head")[0].appendChild(m);
       
		}
        
		var main_menu = document.createElement("div");
		var item_menu = document.createElement("items");
		var f;
        
		main_menu.setAttribute("class", "menuBar");                   
		main_menu.style.className = "menuBar";        // per IE
        
		var buttons = menu[0].getElementsByTagName("barra");
        
		for (i = 0; i < buttons.length; i++) {
                
			var button = buttons[i];
			var n_id = button.getAttribute("id");
			
			if (!n_id) {
				n_id = "1_" + i;
				button.setAttribute("id", n_id);
			} 
                        
			var n_caption = button.getAttribute("caption");
                
			var n_button = document.createElement("a");
                
			n_button.setAttribute("class", "menuButton");                   
			n_button.style.className = "menuButton";        // per IE
                
			if (button.getElementsByTagName("item").length > 0) {

				n_button.setAttribute("onclick", "return buttonClick(event, '" + n_id + "');");                   
				n_button.setAttribute("onmouseover", "return buttonMouseover(event, '" + n_id + "');");                   
                        
				n_button.onclick = "return buttonClick(event, '" + n_id + "');";
				n_button.onmouseover = "return buttonMouseover(event, '" + n_id + "');";

				n_button.appendChild(document.createTextNode(n_caption));
                
				createMenuItem(menu_cont, button, 1);

			}
			else {
				
				var la_azione = button.getAttribute("azione");
				var la_query = button.getAttribute("query");
				var i_param = button.getAttribute("param");
				if (la_azione) {
					
					var chiamata = "callA('" + la_azione + "'";
					
					if (la_query) {
						chiamata += ",'" + la_query + "'";
					}
					if (i_param) {
						chiamata += ",'" + i_param + "'";
					}
					
					chiamata += ")";
					n_button.setAttribute("onclick", chiamata);
				
				}
				else {
		                        n_button.setAttribute("href", button.getAttribute("href"));
				}

				n_button.appendChild(document.createTextNode(n_caption));
			}

			main_menu.appendChild(n_button);
        
		}
        
		menu_cont.appendChild(main_menu);
        
		// inverte main_menu
		var _menu = document.createElement("div");
		var c_m = menu_cont.childNodes;
                
		for (i = c_m.length -1; i >=0; i--) {
			_menu.appendChild(c_m[i]);}
                
			menu_cont = _menu;
        }


        var p = new PopUp(id_nodo);

		var dat = xml.getElementsByTagName("data")[0];

		if (dat.getAttribute("style")) {
			p.style = dat.getAttribute("style");
		}

		var childs;
		var obj_header = xml.getElementsByTagName("header");
		if (obj_header.length > 0) {

	        // il nodo header

		childs = obj_header[0].childNodes;

		str = "";

		for (i = 0; i < childs.length; i++) {
			str += printXML (childs[i]);}
			p.Header(str);

        }        // fine header
    
    
		var obj_corpo = xml.getElementsByTagName("corpo");
		
		if (obj_corpo.length > 0) {


			var body_style = obj_corpo[0].getAttribute("style");
			if (body_style != "") {
//			p.body_style = body_style;
			}


			childs = obj_corpo[0].childNodes;
			str = printXML(menu_cont);

			for (i = 0; i < childs.length; i++) {
				str += printXML (childs[i]);}

			p.Body(str);

		}
   

		
		var obj_footer = xml.getElementsByTagName("footer");
		if (obj_footer.length > 0) {

 
			var footer_style = obj_footer[0].getAttribute("style");
			if (footer_style) {
 //     			msg_footer.style.cssText = footer_style;
			}

	        

                // inserisce i pulsanti di navigazione
			var btn_cont  = document.createElement('span');
/*

                
			var prev_btn  = document.createElement('input');
			prev_btn.setAttribute("value", "&lt;&lt;");
			prev_btn.type =  "button";
			prev_btn.setAttribute('id', "prev_btn");
	
			btn_cont.appendChild(prev_btn);
                
                
			var next_btn  = document.createElement('input');
			next_btn.setAttribute('type', 'button');
			next_btn.setAttribute('value', '&gt;&gt;');
			next_btn.setAttribute('id', 'next_btn');
                
			btn_cont.appendChild(next_btn);
	        
			btn_cont.style.cssText = "float:<;padding:0 3px";
       
*/		

			str = printXML(btn_cont);

			childs = obj_footer[0].childNodes;

			for (i = 0; i < childs.length; i++) {
				str += printXML (childs[i]);}


			p.Footer(str);

		}        // fine footer
    

		if (position == "absolute") {
			p.position = position;
			if ( pos_x == "" )
	        	p.left = "100" + 'px';
	        else
	        	p.left = pos_x + 'px';
			if ( pos_y == "" )
	        	p.top  = "100" + 'px';
	        else
	        	p.top = pos_y + 'px';
        }
        else {
			p.position = position;
        }            
 
        p.load_base_style  = base_style;
        

	p.create(parent_node);

	// solo dopo che è stato creato il pop_up posso aggiungere
	// gli eventi ai bottoni di navigazione
	// questo è dovuto alla procedure printXML
	// che non 
	
/*
	if (obj_footer.length > 0) {
                
		var the_nodo = id_nodo;
		document.getElementById("prev_btn").onclick = function () {

			mem_win[the_nodo].current_win--;
                        
			var _azione = mem_win[the_nodo].Azione();
			var _query_string = mem_win[the_nodo].Query();
			var _param = mem_win[the_nodo].Param();
               
			callA (_azione, _query_string, _param);
                
		};
                
		document.getElementById("next_btn").onclick = function () {
                        
			mem_win[the_nodo].current_win++;
                        
			var _azione = mem_win[the_nodo].Azione();
			var _query_string = mem_win[the_nodo].Query();
			var _param = mem_win[the_nodo].Param();
                        
			callA (_azione, _query_string, _param);
                
		};

		if (mem_win[id_nodo].current_win < 1) {
			
			document.getElementById("prev_btn").disabled = true;
		
		}

		if (mem_win[id_nodo].current_win >= mem_win[id_nodo].last_win) {
				document.getElementById("next_btn").disabled = true;
		}

	}
*/

}

function rispostaHttp (http, param) {


	var id_nodo = "msg_nodo";
	var parent_node = "body";

	if (param) {
		var coppie = param.split(";");
		for (var i=0; i < coppie.length; i++) {
			var coppia = coppie[i].split(":");
			var nome = coppia[0];
			var valore = coppia[1];
			switch (nome) {
				case "id_nodo" : 	
					id_nodo = valore;
					break;
				case "parent" : 	
					parent_node = valore;
					break;
			}
		}	
	}
	
	var doc;
	if (http.readyState >= 4) { 

		if(http.status == 200) {

			var cType = http.getResponseHeader("Content-Type");

			if (cType.indexOf('text/xml') != -1) {

				// XML response
				xml = http.responseXML;
				if ( xml.getElementsByTagName("data").length > 0 ) {
					processXML(xml, param);
				}
			
				// controlla se ci sono output
				var results = xml.getElementsByTagName ( "result" );
				for (i = 0; i < results.length; i++) {		

					var id_result = results[i].getAttribute("id");
					var id_value  = results[i].getAttribute("value");

					var el = document.getElementById ( id_result ) ;

					if ( el ) {
						if ( id_value )
							el.value = id_value;
						else {
							el.innerHTML = ''
							for (var child = results[i].firstChild; child; child=child.nextSibling) { 
								el.innerHTML+=printXML(child);
							}
						}
					}
						
				}
			
				var old_child = document.getElementById(id_nodo);
				if (old_child) {
					// riabilita tutte le caselle di input e select
					var btn = old_child.getElementsByTagName("input");
					for (i=0; i< btn.length; i++) {
						btn[i].disabled = false;	
					}
					btn = old_child.getElementsByTagName("select");
					for (i=0; i< btn.length; i++) {
						btn[i].disabled = false;	
					}
				}

			} else if (cType.indexOf('text/html') != -1) {
				// text esponse
				doc = document.getElementById(parent_node);
				doc.innerHTML = http.responseText;
			} else if (cType.indexOf('text/plain') != -1) {
				// plain text response
				processText(id_nodo);
				doc = document.getElementById('msg_body');
		        doc.innerHTML = http.responseText;
			} else if (cType.indexOf('none') != -1) {
				// nessuna risposta è richiesta
 
				var old_child = document.getElementById(id_nodo);
				if (old_child) {
					// riabilita tutte le caselle di input e select
					var btn = old_child.getElementsByTagName("input");
					for (i=0; i< btn.length; i++) {
						btn[i].disabled = false;	
					}
					btn = old_child.getElementsByTagName("select");
					for (i=0; i< btn.length; i++) {
						btn[i].disabled = false;	
					}
				}

				
			} else {
				// per default considera text/plain
				processText(id_nodo);
				doc = document.getElementById('msg_body');
		        doc.innerHTML = http.responseText;
			}
		}
		else  {alert("Errore " + http.status);}
	}

}

function callA (azione, query_string, param) {
    
	if (!param) {param = "";} 
	if (!query_string) {query_string = "";} 
        
	var id_nodo = "msg_nodo";
	var id_form = "";	// da usare se la query string è
				// prelevata da un form
				// in questo caso query_string è vuota o contiene query aggiuntive
	var parent_node="body";
	var i;
	var nome;
	var valore;
	if (param) {
		var coppie = param.split(";");
		for (i=0; i < coppie.length; i++) {
			var coppia = coppie[i].split(":");
			nome = coppia[0];
			valore = coppia[1];
			switch (nome) {
				case "id_nodo" : 	
					id_nodo = valore;
					break;
				case "id_form" : 	
					id_form = valore;
					break;
				case "parent" : 	
					parent_node = valore;
					break;
			}
		}	
	}
 
	var old_child = document.getElementById(id_nodo);
	if ( old_child && parent_node == "body" ) {
		// disabilita tutte le caselle di input e select
		// per simulare una attesa dal server
		var btn = old_child.getElementsByTagName("input");
		for (i=0; i< btn.length; i++) {
				btn[i].disabled = true;	
		}
		btn = old_child.getElementsByTagName("select");
		for (i=0; i< btn.length; i++) {
				btn[i].disabled = true;	
		}
	}

	var http ;

	if(window.XMLHttpRequest)  {
		http = new XMLHttpRequest();
	}
	else {
		if(window.ActiveXObject) {
			try {
				http = new ActiveXObject("Msml2.XMLHTTP");
			}
			catch(err1) {
				try {
				            http = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(err2) {
					alert("Attenzione il suo browser non supporta le nuove tecnologie usate in questo sito.");
					return false;
				}
			}
		}
    	}

	http.open("POST", azione, true);
      
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      
	http.onreadystatechange = function () {
		rispostaHttp (http, param); 
	};

	if (id_form != "") {
		if (query_string != "") {
			query_string += "&";
		}
		var frm = document.getElementById(id_form);
		if (frm) {
		        var num = frm.elements.length;
                        for (i=0; i < num; i++) {
                                nome = frm.elements[i].name;
                                if (nome) { 
                                        valore = encodeURIComponent(frm.elements[i].value);
                                        var tipo = frm.elements[i].type;
                                        if (tipo == "radio") {
                                                if (frm.elements[i].checked) {
                                                        query_string += nome + "=" + valore + "&";
						}
                                        }
                                        else if (tipo == "checkbox") {
                                                if (frm.elements[i].checked) {
                                                        query_string += nome + "=" + valore + "&";
						}
                                        }
                                        else
                                                { query_string += nome + "=" + valore + "&";}
                                }
                        }
                }
 	}
/*        
        // memorizza la chiamata
        if (!mem_win[id_nodo]) {
                mem_win[id_nodo] = new Queque ();
        }
        
        mem_win[id_nodo].Add(azione, query_string, param);
*/
//alert(query_string);
        http.send(query_string);
  
}
    

function processText (id_nodo) {

	var p = new PopUp(id_nodo);
   
	p.create("", "header", "body", "footer");
    
}


// stampa l'xml ricorsivamente
// curEl = il noto attuale
    
function printXML (curEl)
{
    
	var loc_print = "";
  
	var tagName;
	var i;
    
	if (curEl) {
    
		tagName = curEl.tagName;
		
		if (tagName) {
			tag = "<" + curEl.tagName ;
			var attr = curEl.attributes;
			
			for (i = 0; i < attr.length; i++) {
				var nome = attr[i].nodeName;
				var valore = curEl.getAttribute(nome);
				if (valore) {
					tag += " " + nome + "=\"" + valore + "\""; }
			}
			
			tag += ">";
		}  
		else
			{ tag = curEl.nodeValue; }
    
		loc_print += tag;

		var curElChild = curEl.childNodes;
    
		for (i = 0; i < curElChild.length; i++) {
        	        // attraversamento ricorsivo dei figli
        		loc_print += printXML(curElChild[i]);
		}
 
		// chiude il tag
		if (tagName) {
	        	loc_print += "</" + tagName + ">";
		}

	}
  
  
	return loc_print;
}  
