/*

Metodi per facilitare la gestione DOM

*/


cmsjs=new Object();
cmsjs.onloadArray=new Array();
cmsjs.addOnLoad =function(func) {
	cmsjs.onloadArray[cmsjs.onloadArray.length]=func;
}
cmsjs.onload =function() {
	var i,maxi=cmsjs.onloadArray.length;
	for (i=0;i<maxi;i++) {
		try {
			cmsjs.onloadArray[i]();
		} catch (err) {
			if (cmsjs.debug) alert('Eccezione: alla funzione n '+i+' '+err);
		}
		finally {

		}
	}
}


cmsjs.imgPreload=new Array();
cmsjs.preloadImage=function(src) {
	var image=document.createElement("IMG");
	image.setAttribute('src',src);
	this.imgPreload[this.imgPreload.length]=image;
}


cmsjs.fileExtension=function (path) {
	var ext='';
	var index=path.lastIndexOf('.');

	if (index>0) {
		ext=path.substring(index+1);
		ext=ext.toLocaleLowerCase();
	}

	return ext;

}

cmsjs.fileName=function(path) {
	var name='';
	var index=path.lastIndexOf('/');

	if (index>0) {
		name=path.substring(index+1);
	}

	return name;

}

cmsjs.isImage=function(src) {
	var ext=cmsjs.fileExtension(src).toLowerCase();
	switch (ext) {
		case "jpg":
		case "jpeg":
		case "gif":
		case "png":
			return true;
			break;

		default:
		return false;
		break;

	}
}

cmsjs.stripDomain=function(url) {
	index=url.indexOf('//');
	if (index>0) index=url.indexOf('/',index+2);
	else index=url.indexOf('/',index);
	if (index>0) url=url.substr(index);
	return url;

}




var dom=new Object();
	dom.ELEMENT_NODE = 1;
	dom.ATTRIBUTE_NODE = 2;
	dom.TEXT_NODE = 3;
	dom.CDATA_SECTION_NODE = 4;
	dom.ENTITY_REFERENCE_NODE = 5;
	dom.ENTITY_NODE = 6;
	dom.PROCESSING_INSTRUCTION_NODE = 7;
	dom.COMMENT_NODE = 8;
	dom.DOCUMENT_NODE = 9;
	dom.DOCUMENT_TYPE_NODE = 10;
	dom.DOCUMENT_FRAGMENT_NODE = 11;
	dom.NOTATION_NODE = 12;
cmsjs.dom=dom;

DOM=dom;




var dati=new Object();
dati.html=new Object();






if (window.addEventListener) {
	window.addEventListener('load',cmsjs.onload,false);
} else if (window.attachEvent) {
	window.attachEvent('onload',cmsjs.onload);
}

// window.onload=cmsjs.onload;


var selected=new Object();
selected.background=null;
selected.border=null;
selected.src=null;
selected.element=null;
selected.sign=null;

selected.select=function(source) {
	var element=this.element;
	if (element!=null) {

		// disattiva l'elemento precedente
		element.style.border=this.border;
		element.style.background=this.background;
		if (element.tagName=="IMG") {
			element.width+=2;
			element.height+=2;
		}
	}


	if (source===element) {
		// Disattiva il medesimo elemento appena cliccato
		this.border=null;
		this.background=null;
		this.element=null;
		cmsjs.wyeditor.hide();

		return true;
	}


	// Attiva l'elemento appena cliccato
	this.element=source;
	this.border=source.style.border;
	this.background=source.style.background;
	if (source.tagName=="IMG") {
		source.width-=2;
		source.height-=2;
	}
	source.style.border='1px dashed orange';
	source.style.background='yellow';

	cmsjs.wyeditor.hide();


}

selected.cancel=function () {
	var element=this.element;
	if (element!=null) {
		element.parentNode.removeChild(element);
		this.element=null;
	}

}

dati.selected=selected;
cmsjs.dati=dati;





function asyncUpload(input,iframeId,action,params,notifyFunction) {

	var doc=document;
	var pipe=cmsjs.pipe;


	if (trim(input.value).length==0) {
		notifyFunction(null,null);
		alert('Premere il pulsante sfoglia, quindi scegliere un allegato.');
		return false;
	}

	var fileName=input.value;
	var ext='';
	var index=fileName.lastIndexOf('.');
	if (index>=0) ext=fileName.substring(index+1);
	ext=ext.toLocaleLowerCase();
	switch (ext) {
		case 'gif':
		case 'jpeg':
		case 'jpg':
		case 'png':
			break;

		case 'pdf':
		case 'doc':
		case 'zip':
			break;

		default:
			notifyFunction(null,null);
			alert('Gli allegati di tipo '+ext+', prima del caricamento,\ndevono essere zippati (posti all\'interno di un files zip)');
			return false;

	}


	pipe.staticIframeUpload(input,iframeId,notifyFunction);
	return true;
}


var pipe=new Object();
// pipe.rcmenu=cmsjs.dati.rcmenu;
pipe.channels=new Object();
pipe.channels.counter=0;

pipe.loading=new Image(150,150);
pipe.loading.src='/cms/sys/ico/loading.gif';




pipe.prepareChannel=function(input,action,display,notifyFunction) {
	var idChannel='pipe'+this.channels.counter++;
	var doc=input.ownerDocument;

	// loading
	/*
	 commentato per test

	var inode=doc.importNode(this.loading,true);
	display.appendChild(inode);
	*/


	var iframe=doc.createElement('iframe');
	iframe.setAttribute('name',idChannel);
	if (!cmsjs.debug) iframe.style.display='none';
	doc.body.appendChild(iframe);





	var f=new AsyncForm(action,doc,notifyFunction);
	f.node.setAttribute('target',idChannel);
	f.data.iframe=iframe;
	f.data.input=input;
	pipe.channels[idChannel]=f;

	inode=doc.importNode(input,true);



	f.node.appendChild(inode);
	f.node.style.display='none';
	f.addParam('pipeid',idChannel);
	if (cmsjs.debug) alert('invio del file '+inode.value);


	doc.body.appendChild(f.node);



	return f;
}


pipe.uploaded=function(src,width,height,idChannel) {

	var aform=this.channels[idChannel];
	/*
	 commentato per test
	var display=form.data.display;
	var sign=display.firstChild;
	var img=display.ownerDocument.createElement("IMG");
	*/
	var ext='';
	var index=src.lastIndexOf('.');

	if (index>=0) {
		ext=src.substring(index+1);
		ext=ext.toLocaleLowerCase();
	}



	switch (ext) {
		case 'gif':
		case 'jpg':
		case 'jpeg':
		case 'png':
			var img=aform.data.input.ownerDocument.createElement("IMG");
			// img.setAttribute("width",width);
			// img.setAttribute("height",height);
			img.cmsdata=new Object();
			img.cmsdata.aform=aform;

			// var img=new Image(width,height);
			// img.src=src;

			img.onload=function(){
				var data=this.cmsdata.aform.data;

				if (cmsjs.debug) alert('... simulazione di connessione lenta:'+this.src+'\npremere un tasto per continuare ...');
				data.input.value='';
				// if (!cmsjs.debug) data.iframe.parentNode.removeChild(data.iframe);
				// this.cmsdata.aform.node.parentNode.removeChild(this.cmsdata.aform.node);
				this.cmsdata.aform.completed(this.src);

			};

			img.onerror=function(){pipe.onerror(idChannel);};
			img.onabort=function(){pipe.onerror(idChannel);};
			img.setAttribute("src",src);

			break;

		default:
			var data=aform.data;
			if (cmsjs.debug) alert('... simulazione di connessione lenta:'+this.src+'\npremere un tasto per continuare ...');
			data.input.value='';
			aform.completed(src);
			break;



	} // switch



}

pipe.staticIframeUpload=function(input,iframeId, notifyFunction) {
	var idChannel=iframeId;
	var doc=input.ownerDocument;
	var iframe=document.getElementById(idChannel);

	var form=input.form;

	var aform=new SimpleAsyncForm(form,iframe,notifyFunction);
	aform.data.iframe=iframe;
	aform.data.input=input;


	pipe.channels[idChannel]=aform;


	form.pipeid.value=idChannel;
	form.submit();
	return true;

}






function SimpleAsyncForm(form, iframe, notifyFunction) {
	this.data=new Object();
	this.data.iframe=iframe;
	this.data.oldTarget=form.target;
	this.node=form;

	if (notifyFunction) {
		this.sent=notifyFunction;
	}

	this.reset=function() {
			this.node.reset();
	}

	this.completed=function(obj) {
		try {
			if (cmsjs.debug) alert('Modulo inviato con successo.');
			if (this.sent) this.sent(obj,true);
		} catch (err) {
			if (cmsjs.debug) alert('Eccezione:'+err);
		}
		finally {

		}
	}


	this.interrupted=function(obj) {
		try {
			if (this.sent) this.sent(obj,false);
			if (cmsjs.debug) alert('Errore:invio NON riuscito.');
		} catch (err) {
			if (cmsjs.debug) alert('Eccezione su interrupted():'+err);
		}
		finally {

		}

	}

}


pipe.completed=function(code,idChannel) {
	var aform=this.channels[idChannel];
	if (aform) {
		var mittente=aform.data.mittente;
		if (mittente) {
			if (mittente.completed) mittente.completed(code);
		}
	}
	// alert('pipe.complete()');
}

pipe.onerror=function(idChannel) {
	if (cmsjs.debug) alert('pipe::onError()');
	var aform=this.channels[idChannel];

	var data=aform.data;
	/* commentato per test
	var display=data.display;
	display.removeChild(display.firstChild);
	*/
	// if (!cmsjs.debug) data.iframe.parentNode.removeChild(data.iframe);
	data.input.value='';
	aform.interrupted(null);
	// img.cmsdata.aform.node.parentNode.removeChild(img.cmsdata.aform.node);
}





function AsyncForm(action, doc, notifyFunction) {
	// Utilizzata da prepareChannel
	if (!action) action='elemento.php';
	this.pipe=pipe;
	this.data=new Object();
	if (doc===undefined) doc=document;
	var node=document.createElement('form');
	node.setAttribute('action',action);
	node.setAttribute('method','post');
	node.setAttribute('name','pipe-form');
	node.encoding='multipart/form-data';
	this.node=node;

	if (notifyFunction) this.sent=notifyFunction;


	this.reset=function() {
		this.node.reset();
	}

	this.addParam=function (nome, valore)  {
		var input=this.node.ownerDocument.createElement('input');
		input.setAttribute("type","hidden");
		input.setAttribute("name",nome);
		input.setAttribute("value",valore);
		this.node.appendChild(input);
	}

	this.submit=function () {
		var body=this.node.ownerDocument.body;
		if (!body && cmsjs.debug) alert('AsyncForm.submit():body nullo.');
		this.pipe.mittente=this;
		body.appendChild(this.node);
		this.node.submit();
	}


	this.completed=function(img) {
		try {
			if (this.sent) this.sent(img,true);
			if (cmsjs.debug) alert('Form inviata con successo.');

		} catch (err) {
			if (cmsjs.debug) alert('Eccezione:'+err);
		}
		finally {
			this.node.parentNode.removeChild(this.node);


		}

	}

	this.interrupted=function(img) {
		try {
			this.form.reset();
			if (this.sent) this.sent(img,false);
			if (cmsjs.debug) alert('Errore:invio NON riuscito.');

		} catch (err) {
			if (cmsjs.debug) alert('Eccezione su interrupted():'+err);
		}
		finally {
			this.node.parentNode.removeChild(this.node);
		}

	}

} // AsyncForm



function prepareForm(action) {
	var formObject=new AsyncForm(action);
	return formObject;
}


pipe.prepareForm=prepareForm;



pipe.submit=function(form) {
	var nodo=cmsjs.dati.selected.element;
	var span;

	cmsjs.dati.form=form;
	metodo=form.mtd.value;


	switch (metodo) {
		case 'img':

			// Posiziona l'immagine loading su cmsjsdati.selected.sign;
			// alla conferma dal server pipe.uploaded questa viene
			// rimpiazzata dall'immagine appena caricata

			var inode=nodo.ownerDocument.importNode(pipe.loading,true);
			nodo.appendChild(inode);
			cmsjs.dati.selected.sign=inode;
			break;

		case 'html':
			cmsjs.wyeditor.salva();

			// alert('invio dati html...(' + html.substr(0,10)+')');
			break;


	}




	return true;
} // submit();


cmsjs.pipe=pipe;


function rightClic(e,posx,posy) {

	var selected=cmsjs.dati.selected.element;
	if (selected==null) {
		var wyeditor=cmsjs.wyeditor;
		wyeditor.showMetaEditor();
		wyeditor.metaTag.keywords.value=cmsjs.template.keywords.node.getAttribute('value');
		wyeditor.metaTag.description.value=cmsjs.template.description.node.getAttribute('value');

		wyeditor.setPosition(posx,posy);
		wyeditor.show();

		return;
	}


	var i,maxi=selected.childNodes.length;
	var isText=false;
	for (i=0;i<maxi;i++) if (!(selected.childNodes[i].nodeType==3)) break;
	if (i==maxi && maxi!=0) {
		// clic su un nodo testo
		isText=true;
	}

	var wyeditor=cmsjs.wyeditor;
	if (!wyeditor) alert('wyeditor nullo');
	var id=selected.id;
	var id_pagina=cmsjs.template.pkvalue;

	if (!id) // alert('wyeditor.id nullo.');
	if (!id_pagina) alert('wyeditor.id_pagina nullo.');
	wyeditor.id=id;
	wyeditor.id_pagina=id_pagina;

	/*
	var rcmenu=cmsjs.dati.rcmenu;
	var menu=rcmenu.node;

	var span=menu.getElementsByTagName("SPAN")[0];

	spazzaNodo(span);

	var doc=selected.ownerDocument;
	var testo=doc.createTextNode('Clic su elemento ' + selected.nodeName+ ' ('+posx +','+posy+')');
	span.appendChild(testo);

	rcmenu.form.reset();
	if (isText) rcmenu.modificaTesto(selected);
	else rcmenu.aggiungiTesto(selected);





	var node=rcmenu.node;

	node.style.visibility='hidden';
	node.style.display='';
	*/
	/*
	var w1=node.clientWidth;
	var w2=doc.body.clientWidth;
	var maxLeft=(w2-w1);
	var nleft=((posx>maxLeft)?maxLeft:posx);
	if (nleft<0) nleft=0;
	menu.style.left=nleft+'px';



	menu.style.top=posy+'px';
	node.style.visibility='visible';
	alert('rcmenu:x='+nleft+' y='+ posy);
	*/

	wyeditor.showContentEditor();
	wyeditor.setPosition(posx, posy);
	wyeditor.show();


	wyeditor.iframe.contentDocument.body.innerHTML=selected.innerHTML;

}


function myMouseHandler(e) {
	if (!e) e = window.event;

	var source;
	if (e.target) source = e.target;
	else if (e.srcElement) source = e.srcElement;
	if (source.nodeType==DOM.TEXT_NODE) source=source.parentNode;



	// Determina se rightClic e dove
	var rightclick;
	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);

	if (rightclick)	return true;


	var id,node=source,cc=0;

	// Esclude gli eventi proventienti da rcmenu
	while (node!=null && cc <100) {
		if (node.getAttribute) id=node.getAttribute('id');
		else { id=null;}

		switch (id) {
			case 'wyeditor':

				return true;
				break;

			default:


		}
		node=node.parentNode;
		if (node==document) break;
		cc++;
	}


	cmsjs.dati.selected.select(source);


}



function varDump(obj) {
	var p,t='';

	for (p in obj) t+=p+'\n';

	alert(t);

}

function myMouseMove(e,handle) {
	var source;
	if (!e) e = window.event;
	if (e.target) source = e.target;
	else if (e.srcElement) source = e.srcElement;
	e.cms_source=source;

	var posx = 0;
	var posy = 0;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}



	var x=handle.style.left;
	var y=handle.style.top;

	var mm=cmsjs.dati.mousemove;
	var diffx;

	var node=cmsjs.wyeditor.iframe;
	if (!mm.startx)  {
		mm.startx=posx;
		mm.starty=posy;
		mm.startWidth=parseInt(node.style.width);
		mm.startHeight=parseInt(node.style.height);
		//window.parent.status+=' startx='+mm.startx;
	} else {
		diffx=posx-mm.startx;
		diffy=posy-mm.starty;

		node.style.width=mm.startWidth+diffx+'px';
		node.style.height=mm.startHeight+diffy+'px';
	}


	// cmsjs.wyeditor.position(posx, posy);

}


function myOnContextMenu(e, originalHandler) {
	var source;
	if (!e) e = window.event;
	if (e.target) source = e.target;
	else if (e.srcElement) source = e.srcElement;
	e.cms_source=source;


	if (e.ctrlKey) return true;

	// defeat Safari bug
	 if (source.nodeType == DOM.TEXT_NODE) source = source.parentNode;


	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);

	if (rightclick)	 {
		var posx = e.clientX;
		var posy = e.clientY;

		/*
			posx, posy assoluti
		if (e.pageX || e.pageY) 	{
			// old firefox
			posx = e.pageX;
			posy = e.pageY;
		} else if (e.clientX || e.clientY) 	{
			posx = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}
		*/



		window.parent.status+='x:='+posx+' y:='+posy;

		rightClic(e, posx, posy, originalHandler);


	}


	if (e.preventDefault) e.preventDefault();

	return false;
}



function cancelBubble(e) {
	if (e && e.stopPropagation) {
		e.stopPropagation();
		// e.preventDefault();
	} else {
		e=window.event;
		e.cancelBubble = true;
	}

	if (e.preventDefault) e.preventDefault();

}


function myOnKeyPress(e) {

	// Gestore eventi tastiera
	e=e||window.event;
	var source=e.target || e.srcElement;
	if (source.tagName!="HTML") return true;

	var keyunicode=e.charCode || e.keyCode;

	var selected=cmsjs.dati.selected;
	var element=selected.element;


	switch (keyunicode) {
		case 37:
			// sx
			var prev=prevSiblingNode(element);
			if (prev!=null) selected.select(prev);

			break;

		case 38:
			// su
			window.status='alto';
			break;

		case 39:
			// dx
			var next=nextSiblingNode(element);
			if (next!=null) selected.select(next);
			break;


		case 40:
			// giu'
			window.status='basso';

			break;

		case 46:
			// canc
			if (selected) selected.cancel();

			break;

		case 113:
			// f2


		default:
		window.status+=keyunicode;

	}

	return true;
}



function salvaDoc(doc,saveIdContent) {
	if (saveIdContent===undefined) saveIdContent=true;
	if (!doc) doc=document;
	var doctype=doc.childNodes[0];

	/*
	var head=doc.childNodes[1].childNodes[0];
	var body=doc.childNodes[1].childNodes[1];
	var headSource=salvaNodo(head);
	var bodySource=salvaNodo(body);
	*/
	// var form=document.forms['doc'];
	// form.sorgente.value=headSource+bodySource;
	// form.submit();


	return salvaNodo(doc, saveIdContent);
}



function salvaNodo(nodo,saveIdContent) {
	switch (nodo.nodeType) {
		case  1:
		case  9:
		case 10:
			// Elemento
			var i,maxi;
			var testo='';
			var attributo,attributi;
			var skipContent=false;


			if (nodo.tagName) {
				testo='<'+nodo.tagName.toLowerCase();

				// codifica gli attributi
				attributi=nodo.attributes;
				if (attributi) {
					maxi=attributi.length;
					for (i=0;i<maxi;i++) {
						attributo=nodo.attributes[i];
						// if (attributo.name.toLowerCase()!='style')
						testo+=' '+attributo.name+'="'+attributo.value+'"';
					}
				}

				testo+='>' ;
			}


			if (!saveIdContent && nodo.getAttribute) {

				// evita di salvare il contenuto dei nodi template
				var id=nodo.getAttribute('id');

				if (id && id.toLowerCase().indexOf('cms:')==0) {
					skipContent=true;
					testo+='<cms>'+id+'</cms>';
				}
			}

			if (!skipContent) {
				var figli=nodo.childNodes;
				var testoFiglio;
				maxi=figli.length;
				for (i=0;i<maxi;i++) {
					testoFiglio=salvaNodo(figli[i],saveIdContent);
					testo+=testoFiglio;
				}
			}

			if (nodo.tagName) {
				testo+='</'+nodo.tagName+'>' ;
			}
			return testo;
			break;

		case 3:
			// nodo testo
			var text=nodo.nodeValue;
			return text;
			break;

		case 8:
			return '<!--'+nodo.nodeValue+'-->';
			// commento
			break;

		default:
		alert(nodo.nodeType +':tipo sconosciuto');
		break;

	}

}

function html2js(nodo, nomeVar,nx) {
	switch (nodo.nodeType) {
		case 1:
			// Elemento
			var i,maxi;
			var attrubuto;

			var code='var '+nomeVar+nx+'=d.createElement(\''+nodo.tagName+'\');\n';


			var nodoFiglio;

			maxi=nodo.attributes.length;
			for (i=0;i<maxi;i++) {
				attributo=nodo.attributes[i];
				if (attributo.name.toLowerCase!='style') code+=nomeVar+nx+'.setAttribute(\''+attributo.name+'\',"'+attributo.value+'");\n';
			}


			if (nx>1) code+=nomeVar+(nx-1)+'.appendChild('+nomeVar+nx+');\n';

			 // ricorsione sui figli
			var figli=nodo.childNodes;
			maxi=figli.length;
			for (i=0;i<maxi;i++) {
				nodoFiglio=html2js(figli[i],nomeVar,nx+1);

				if (nodoFiglio.length>0) {
					code+=nodoFiglio;
					// code+=nomeVar+nx+'.appendChild('+nomeVar+(nx+1)+');\n';
				}

			}


			return code;
			break;

		case 3:
			// nodo testo
			var textContent=nodo.nodeValue;
			var code;
			if (trim(textContent).length>0) {
				code=nomeVar+nx+'=d.createTextNode(\''+textContent+'\');';
				if (nx>1) code+=nomeVar+(nx-1)+'.appendChild('+nomeVar+nx+');\n';

			} else code='';


			return code;
			break;

		case 8:
			return '';
			return '<!--'+nodo.nodeValue+'-->';
			// commento
			break;

		default:
		break;

	}

}

function trim(s) {
	var c,s2='';
	var maxi=s.length;
	for (i=0;i<maxi;i++) {
		c=s.substr(i,1);
		switch (c) {
			case '\n':
			case '\t':
			case ' ':
				break;
			default:
				s2=s.substr(i);
				i=maxi;
		}
	}

	maxi=s2.length;

	for (i=maxi-1;i>=0;i--) {
		c=s2.substr(i,1);

		switch (c) {
			case '\n':
			case '\t':
			case ' ':
				break;
			default:
				s2=s2.substr(0,i+1);
				i=-1;
		}
	}



	return s2;

}


function jsType(x){
	var coString;
	var tipo=typeof(x);

	switch (tipo){
		case 'object':{
			if (x==null) {tipo='null';}
			else {
				coString=x.constructor.toString();
				if (coString==Array.toString()) {tipo='array';}
				else if (coString==Date.toString()) {tipo='date';}
				else if (coString==Number.toString()) {tipo='Number';}
				else if (coString==Boolean.toString()) {tipo='Boolean';}
				else if (coString==String.toString()) {tipo='String';}
				else tipo='object';
			}
			break;
		} // case object
	}
	return tipo;
}


function nextSiblingNode(node) {
	vicino=null;
	if (node!=null) {
		vicino=node.nextSibling;
		while (vicino!=null) {
			if (vicino.nodeType==1) return vicino;
			vicino=vicino.nextSibling;
		}
	}


}


function prevSiblingNode(node) {
	vicino=null;
	if (node!=null) {
		vicino=node.previousSibling;
		while (vicino!=null) {
			if (vicino.nodeType==1) return vicino;
			vicino=vicino.previousSibling;
		}
	}


}



function isDefined(x){
	var flag=true;

	switch (typeof(x)){
		case 'undefined':
			flag=false;
			break;

		case 'object':
			if (x==null) flag=false;
		break;

		case 'string':
			if (x=='') flag=false;
	}
	//var flag=((typeof(oggetto)!='undefined') && oggetto!=null && oggetto!=0 && oggetto!='');
	return flag;
}

function structGet(struttura,chiave){
	var sottoStruttura=null;
	if (isDefined(struttura) && struttura[chiave]) sottoStruttura=struttura[chiave];
	return sottoStruttura;
}

function conteggioChiavi(struttura){
	var i=0;
	for (chiave in struttura) i++;
	return i;
}

function spazzaNodo(nodo){
	if (isDefined(nodo)) if (nodo.hasChildNodes) while (nodo.hasChildNodes()) nodo.removeChild(nodo.firstChild);
}



function appendFirstChild(nodeToAppend, toNode) {
	var childNodes=toNode.childNodes;
	if (childNodes.length==0) toNode.appendChild(nodeToAppend);
	else {
		toNode.insertBefore(nodeToAppend, childNodes[0]);
	}

}


/*
function figliSelezionati(nodo,nome){
	var figli,figlio;
	var selezionati=null;
	var i,ultimo;
	if (isDefined(nodo)){
		figli=nodo.getElementsByTagName('input');
		selezionati = new Array();

		if (figli!=null && figli!=''){
			ultimo=figli.length;
			for (i=0;i<ultimo;i++){
				figlio=figli[i];
				switch (figlio.getAttribute('type')){
					case 'checkbox':{
							if (figlio.getAttribute('name')==nome){
								if (figlio.checked) selezionati[selezionati.length]=figlio;
							}

							break;
					} // case checkbox
					default:;
				}
			} // for i=0;
		} // if figli!=null
	} // if isDefined
	return selezionati;
}
*/

/*
	Individua un nodo figlio che abbia un attributo 'name' con
	valore uguale al parametro 'nome' indicato. Il parametro numero
	indica quale figlio, nel caso ce ne fossero più di uno.
*/

function figlioConNome(nodo,nome,numero){
	if (!isDefined(nodo)) nodo=null;
	if (!isDefined(nome)) nome=null;
	if (!isDefined(numero)) numero=1;

	nome=nome.toLowerCase();

	var ilFiglio=null;
	var figli,figlio,figlioN=0;
	var i=0,ultimo=0;
	var valore=null;

	if (nodo!=null){
		if (nodo.length){
			figli=nodo;
		}
		if (nodo.hasChildNodes) figli=nodo.childNodes;

		ultimo=figli.length;
		if (nome!=null){
			for (i=0;i<ultimo;i++){
				figlio=figli[i];
				if (figlio.nodeType==1){
					valore=figlio.getAttribute('name');
					if (valore!=null && valore.toLowerCase()==nome){
						figlioN++;
						if (figlioN==numero){
							ilFiglio=figlio;
							break;
						}
					} // se il figlio ha il nome corrispondente

					// controlla anche i sottonodi
					if (figlio.hasChildNodes()){
						figlio=figlioConNome(figlio,nome,numero-figlioN);
						if (figlio!=null) {
							ilFiglio=figlio;
							break;
						}
					}
				} // solo per nodi standard
			} // per ogni figlio
		} // se è stato fornito un nome
	} // if nodo != null

	return ilFiglio;
}


/*

Restituisce tutti i nodi figlio aventi un attributo 'name' con valore uguale
al parametro nome passato alla funzione

es.

<form>
	<table>
		<tr><td><input type="checkbox" name="id_articolo" value="..."/></td></tr>
		...
		<tr><td><input type="submit" onClick="figliConNome(this.form,'id_articolo')"/></td></tr>
	</table>
</form>



*/



function figliConNome(nodo,valoreNome,nomeFigli,array) {
	/*
	es figliConNome(nodo,'id_articolo[]','input')
	trova tutti i discendenti di nodo che si chiamino
	input ed abbiano l'attributo nome uguale a 'id_articolo[]'
	il parametro array viene utilizzato internamente.

	Il parametro nomeFigli non è obbligatorio
	*/

	valoreNome=valoreNome.toLowerCase();
	if (nomeFigli) nomeFigli=nomeFigli.toLowerCase();
	var figliIndividuati;
	if (array) figliIndividuati=array;
	else figliIndividuati=new Array();
	var figli,maxi,i;

	if (nodo && nodo.hasChildNodes){
		figli=nodo.childNodes;
		maxi=figli.length;
		for (i=0;i<maxi;i++){
			figlio=figli[i];
			if (figlio.nodeType!=cmsjs.dom.ELEMENT_NODE) {continue;}
			if (nomeFigli) if (figlio.tagName.toLowerCase()!=nomeFigli) {continue;}

			valore=figlio.getAttribute('name');
			if (valore && valore.toLowerCase()==valoreNome) {
				figliIndividuati.push(figlio);



			} // se il figlio corrisponde
			else {
				// alert(' ricorsione su ' + figlio.tagName+ ' con nome='+valore);
				// richiama ricorsivamente la funzione sui sottonodi
				figliConNome(figlio,valoreNome,nomeFigli,figliIndividuati);

			}
		} // per ogni figlio
	} // if nodo != null

	return figliIndividuati;

}

/*
 sostituita dalla precedente che consente di specificare anche il tipo dei figli
function figliConNome(nodo,nome){
	var ilNome=nome.toLowerCase();

	var figliIndividuati=new Array();
	var contatore=0;
	var figli,figlio;
	var i=0,maxi=0;
	var valore=null;

	if (nodo && nodo.hasChildNodes){
		figli=nodo.childNodes;
		maxi=figli.length;
		for (i=0;i<maxi;i++){
			figlio=figli[i];
			if (figlio.nodeType==cmsjs.dom.ELEMENT_NODE){
				valore=figlio.getAttribute('name');
				if (valore && valore.toLowerCase()==ilNome) {
					figliIndividuati[contatore]=figlio;
					contatore+=1;
				} // se il figlio corrisponde
				else {
					// richiama ricorsivamente la funzione sui sottonodi
					if (figlio.hasChildNodes()) {
						var nipoti=figliConNome(figlio,ilNome);
						// Aggiunge i risultati
						var j,maxj=nipoti.length;
						for (j=0;j<maxj;j++) {
							figliIndividuati[contatore]=nipoti[j];
							contatore+=1;
						}
					}
				}
			} // solo per nodi standard
		} // per ogni figlio
	} // if nodo != null

	return figliIndividuati;
}
*/

function padreConTag(nodo, tag) {
	tag=tag.toLowerCase();

	for (padre=nodo.parentNode;padre!==null;padre=padre.parentNode) {
		if (padre.tagName.toLowerCase()==tag)	return padre;
	}
	return null;
}

function figliConTag(nodo,tag){
	if (!isDefined(nodo)) nodo=null;
	if (!isDefined(tag)) tag=null;

	var figli=new Array();

	if (nodo!=null) figli=nodo.getElementsByTagName(tag)

	if (figli.length==0) return null;
	else return figli;
}



function figliConAttributo(nodo,attributo,valore,parziale){
	if (!isDefined(nodo)) nodo=null;
	if (!isDefined(attributo)) attributo=null;
	if (!isDefined(valore)) valore=null;
	if (!isDefined(parziale)) parziale=false;


	var selezionati=new Array();
	var figli,figlio,sottoNodiSelezionati,test;
	var i,j,ultimo,ultimo2;


	attributo=attributo.toLowerCase();

	if (nodo!=null){
		if (attributo!=null){
			if (nodo.length){
				figli=nodo;
			}
			if (nodo.hasChildNodes) figli=nodo.childNodes;

			ultimo=figli.length;

			for (i=0;i<ultimo;i++){
				figlio=figli[i];
				if (figlio.nodeType==1){
					//alert('esame del nodo ' + figlio.tagName);
					test=figlio.getAttribute(attributo);
					if (isDefined(test)){
						if (parziale) {
							if (test.indexOf(valore)>=0) selezionati[selezionati.length]=figlio;
						} else {

							if (test.toLowerCase()==valore){
								selezionati[selezionati.length]=figlio;
							} // se il valore dell'attributo corrisponde
						}
					} // se è definito l'attributo specificato

					// controlla anche i sottonodi
					if (figlio.hasChildNodes()){
						//alert('scansione dei figli di ' + figlio.tagName);
						sottoNodiSelezionati=figliConAttributo(figlio,attributo,valore,parziale);
						if (sottoNodiSelezionati!=null) {
							ultimo2=sottoNodiSelezionati.length;
							for (j=0;j<ultimo2;j++){
								selezionati[selezionati.length]=sottoNodiSelezionati[j];
							} // per ogni sottoNodo selezionato
						} // se esistono sottonodi selezionati
						//alert('fine della scansione dei figli di ' + figlio.tagName);
					}  // se il nodo ha figli
					//alert('fine esame del nodo ' + figlio.tagName);
				} // se il nodo è standard
			} // per ogni figlio

		} // se è stato specificato un tag
	} // if nodo != null

	return selezionati;
}






function discendentiConTag(nodo,tag){
	if (!isDefined(nodo)) nodo=null;
	if (!isDefined(tag)) tag=null;

	var selezionati=new Array();
	var figli,figlio,sottoNodiSelezionati,valore;
	var i,j,ultimo,ultimo2;


	tag=tag.toLowerCase();

	if (nodo!=null){
		if (tag!=null){
			figli=nodo.childNodes;
			ultimo=figli.length;

			for (i=0;i<ultimo;i++){
				figlio=figli[i];
				if (figlio.nodeType==1){
					//alert('esame del nodo ' + figlio.tagName);
					test=figlio.tagName;

					if (isDefined(test)){
						if (test.toLowerCase()==tag){
							selezionati[selezionati.length]=figlio;
						} // se il nome corrisponde
					} // se il tag ha un nome

					// controlla anche i sottonodi
					if (figlio.hasChildNodes()){
						//alert('scansione dei figli di ' + figlio.tagName);
						sottoNodiSelezionati=figliConTag(figlio,tag);
						if (sottoNodiSelezionati!=null) {
							ultimo2=sottoNodiSelezionati.length;
							for (j=0;j<ultimo2;j++){
								selezionati[selezionati.length]=sottoNodiSelezionati[j];
							} // per ogni sottoNodo selezionato
						} // se esistono sottonodi selezionati
						//alert('fine della scansione dei figli di ' + figlio.tagName);
					}  // se il nodo ha figli
					//alert('fine esame del nodo ' + figlio.tagName);
				} // se il nodo è standard
			} // per ogni figlio

		} // se è stato specificato un tag
	} // if nodo != null
	if (selezionati.length==0) return null;
	else return selezionati;
}

function creaModulo(nome){
	var modulo=document.createElement('FORM');

	if (isDefined(nome)){
		modulo.setAttribute('name',nome);
	}
	return modulo;
}


function creaRiga(nCelle){
	if (!isDefined(nCelle)) nCelle=0;

	var riga,cella;

	riga=document.createElement('TR');
	for (i=0;i<nCelle;i++){
		cella=document.createElement('TD');
		riga.appendChild(cella);
	}
	return riga;
}

function creaTabella(nRighe,nCelle, border, altro){
	var tabella,riga,cella,thead,tbody,tfoot;
	var i,j=0;


	if (!nRighe) nRighe=0;
	if (!nCelle) nCelle=0;

	tabella=document.createElement('TABLE');
	tabella.setAttribute('border',border);

	for (i=0;i<nRighe;i++){
		riga=tabella.insertRow(0);
		for (j=0;j<nCelle;j++){
			cella=riga.insertCell(0);
		}
	}

	if (nRighe && altro!=null){
		thead=tabella.createTHead();
		tfoot=tabella.createTFoot();
	}

	return tabella;

}

function creaInput(tipo){
	if (!isDefined(tipo)) tipo='testo';
	tipo=tipo.toLowerCase();

	var campo=null;
	var nParametri=arguments.length;

	switch(tipo){
		case 'testo':{
			campo=document.createElement('INPUT');
			campo.setAttribute('type','text');
			if (nParametri>1) campo.setAttribute('name',arguments[1]);
			if (nParametri>2) campo.setAttribute('value',arguments[2]);
			break;
		}
	}

	return campo;
}

function deepCopy(x){
	var copia;
	var fx,chiave,i,ultimo;

	switch (typeof(x)){
		case 'object':
			switch (jsType(x)){
				case 'null':copia=null;break;
				case 'object':
					copia=new Object();
					for (chiave in x) copia[chiave]=deepCopy(x[chiave]);
				break;
				// object
				case 'array':
					copia=new Array();
					ultimo=x.length;
					for (i=0;i<ultimo;i++){
						copia[i]=deepCopy(x[i]);
					}
				break;
				default :
					fx=x.constructor;
					copia=fx(x.valueOf());

			} // switch jsType(object)
		break;
		default:copia=x;
	} // switch typeof
return copia;

}

