var myRequest = null;

function CreateXmlHttpReq(handler) {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch(e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xmlhttp.onreadystatechange = handler;
return xmlhttp;
}

function myHandler() {

if (myRequest.readyState == 4 && myRequest.status == 200) {
e = document.getElementById("articoli");
e.innerHTML = myRequest.responseText;
}
}

function dettagliEvento(cod) {
 var app='art_x_gruppo.php?cod_Gruppo='+cod+'&rand='+escape(Math.random());

myRequest = CreateXmlHttpReq(myHandler);
myRequest.open("GET",app);
myRequest.send(null);
}

function getDati(query,dest){
 	var app='getdati.php?query='+query+'&dest='+dest+'&rand='+escape(Math.random());
	myRequest = CreateXmlHttpReq(stampaDati);
	myRequest.open("GET",app);
	myRequest.send(null);
}



function stampaDati(){
  if (myRequest.readyState == 4 && myRequest.status == 200) {
    app=myRequest.responseText.split("SEPDEST");
		//alert(myRequest.responseText);
		e = document.getElementById(app[1]);
    e.value = app[0];
  }
}





function getCampi(tabella){
	//alert(tabella);
 	var app='getCampi.php?tabella='+tabella+'&rand='+escape(Math.random());
	myRequest = CreateXmlHttpReq(stampaCampi);
	myRequest.open("GET",app);
	myRequest.send(null);

}



function stampaCampi(){
  if (myRequest.readyState == 4 && myRequest.status == 200) {
 		a=document.getElementById("campo_valore");
		e=document.getElementById("ext_chiave");
    o=document.getElementById("campo_testo");
		e.options.length=0;
    a.options.length=0;
    o.options.length=0;
    if(myRequest.responseText!="VUOTO"){
  		app=myRequest.responseText.split("SEPCAMPO");
  		//alert(myRequest.responseText);
      for(i=0;i<app.length;i++){
    		e.options[i]=new Option(app[i],app[i]);
    		a.options[i]=new Option(app[i],app[i]);
    		o.options[i]=new Option(app[i],app[i]);
  		}
 		}else{
			e.options[0]=new Option("Nessuno","-1");
			a.options[0]=new Option("Nessuno","-1");
			o.options[0]=new Option("Nessuno","-1");

		}
		e.selectedIndex=0;
		a.selectedIndex=0;
		o.selectedIndex=0;
  }
}





function getInfo(query,valore){
	param=query[0];
	for(i=1;i<query.length;i++){
		param+="@"+query[i];
	}
	//alert(param);
 	var app='getinfo.php?query='+param+'&codice='+valore+'&rand='+escape(Math.random());
	//alert(app);
	myRequest = CreateXmlHttpReq(stampaInfo);
	myRequest.open("GET",app);
	myRequest.send(null);
}


function stampaInfo(){
	var vett=new Array();
  if (myRequest.readyState == 4 && myRequest.status == 200) {
 		//alert(myRequest.responseText);
		err=myRequest.responseText.split("SEPERR");
		dip=err[1].split("SEPDIP");
		//alert("err="+err[0]+"  "+err[1]);
		for(i=0;i<(dip.length-1);i++){ 		
 		app=dip[i].split("SEPCAMPO");
		//alert(app[0]+"  "+app[1]+"  "+app[2]);
  		dest=document.getElementById(app[0]);
  		tipotag=app[1];
  		if(tipotag!="select"){
  			//alert("gsgfs"+app[0]+' '+app[1]+' '+app[2]+' '+app[3]);
  			//alert(dest.id);
			if(app[2]!=undefined){
  				dest.value=app[3];
  			}else{
  				dest.value="";
  			}		
  		}else{ 		
  			dest.options.length=0;
    		dest.options[0]=new Option("          ",-7);
			k=1;
  			for(j=2;j<app.length;j=j+2){
      		dest.options[k]=new Option(app[j+1],app[j]);
      		k++;
    		}
  			dest.selectedIndex=0;
//			alert(dest.id);
			vett[vett.length]=dest;
//			dest.onchange();
    	}
    }
	if(vett.length){
		for(i=0;i<vett.length;i++){
			vett[i].onchange();
		}
	}
	}
}





function stampaInfo2(){
  if (myRequest.readyState == 4 && myRequest.status == 200) {
 		//alert(myRequest.responseText);
		err=myRequest.responseText.split("SEPERR");
		dip=err[1].split("SEPDIP");
		//alert("err="+err[0]+"  "+err[1]);
		for(i=0;i<(dip.length-1);i++){ 		
			app=dip[i].split("SEPCAMPO");
			dest=document.getElementById(app[0]);
			tipotag=app[1];
			if(tipotag!="select"){
				//alert("gsgfs"+app[0]+' '+app[1]+' '+app[2]+' '+app[3]);
				//alert(dest.id);
				if(app[2]!=undefined){
					dest.value=app[3];
				}else{
					dest.value="";
				}		
			}else{ 		
				alert(0);
				dest.selectedIndex=0;
				dest.options.length=0;
				dest.options[0]=new Option("          ",-7);
				k=1;
				for(j=2;j<app.length;j=j+2){
					dest.options[k]=new Option(app[j+1],app[j]);
					k++;
				}
				dest.selectedIndex=0;
	//			alert(dest.id);
	//			dest.onchange();
			}
    	}
	}
}









function switchcampo(valore,campi){
	
	for(i=0;i<campi.length;i++){
		var app=campi[i].substr((campi[i].length-1),(campi[i].length-1));
		//alert(app);
		if(app==valore){
			document.getElementById(campi[i]).style.display='';
		}else{
			document.getElementById(campi[i]).style.display='none';
		}
	}
	for(i=0;i<campi.length;i++){
		var app=campi[i].substr((campi[i].length-1),(campi[i].length-1));
		//alert(app);
		if(app==valore){
			document.getElementById(campi[i]).onchange();
		}
	}
	if(valore=='-7'){
		document.getElementById(campi[0]).style.display='';
		document.getElementById(campi[0]).onchange();
	}
}


/*if(this.value=="C"){
app=document.getElementById("MITT_DEST_C").style.display="block";
document.getElementById("MITT_DEST_F").style.display="none";
document.getElementById("MITT_DEST_C").onchange();
}else{
app=document.getElementById("MITT_DEST_F").style.display="block";
document.getElementById("MITT_DEST_C").style.display="none";
app=document.getElementById("MITT_DEST_F").onchange();
}


getDati("select Indirizzo from fornitore where Cod_fornitore="+this.options[this.options.selectedIndex].value,"DESTINAZIONE");*/






var BACKUP=new Array();
var DOVE='art';
var QUERY="";
var ARTICOLI=new Array();
var LISTADDT=new Array();
				
function init_doc(){

BACKUP['doc']="";
BACKUP['art']="";
/*var app='gestore_AddArt.php?rand='+escape(Math.random());
myRequest = CreateXmlHttpReq(stampaArt);
myRequest.open("GET",app);
myRequest.send(null);
*/
//alert(BACKUP['doc']);

}




function azzeraCol(idcol){
	var i=0;
	while(document.getElementById(idcol+"_"+i)){
		document.getElementById(idcol+"_"+i).innerHTML="0";
		i++;
	}
}



function switchDoc(flag,param,numrighe,stampa){
		var origine='doc';
		var dest='art';	 		
		if(DOVE=='art'){
			//salva_articoli();
//			alert(BACKUP['doc']);
			BACKUP['art']=document.getElementById('CORPO_DOC').innerHTML;
			//document.getElementById('CORPO_DOC').innerHTML=BACKUP['doc'];
			//creaEventoHeader("onchange");
			var num=0;
			if(param!='init'){
				num=selArt(param);
				document.getElementById('HEADER_DOC').style.display='';
				document.getElementById('FOOTER_DOC').style.display='';			
				document.getElementById('div_esegui').style.display='';
				creaEventoFooter("onblur");
			}else{
				if(numrighe!=""){
					num=numrighe;
				}
			}
			switch(flag){
				case 'Art':
					myRequest = CreateXmlHttpReq(stampaListinoArt);
				break;
				case 'Ddt':
					myRequest = CreateXmlHttpReq(stampaDdt);
					//totaliRighe('doc');	
				break;
				default:
				break;
			}
			//totaliRighe('doc');

//			alert("numtuple="+num);
			DOVE='doc';
			var app='gestore_Add'+flag+'.php?query=LISTINO&numtuple='+num+'&tipodoc='+document.getElementById('TIPO_DOCUMENTO').value+'&stampa='+stampa;
			//alert(app);
			app+='&rand='+escape(Math.random());
			myRequest.open("GET",app);
			myRequest.send(null);
		}else{
			//alert(document.getElementById('HTML_DOCUMENTO').textContent);
			switch(flag){
				case 'Art':
					listinoArticoli();
					myRequest = CreateXmlHttpReq(stampaArt);
				break;
				case 'Ddt':
					listinoDdt();
					myRequest = CreateXmlHttpReq(stampaDdt);					
				break;
				default:
				break;
			}
//			alert(QUERY);
			BACKUP['doc']=document.getElementById('CORPO_DOC').innerHTML;
			document.getElementById('HEADER_DOC').style.display='none';
			document.getElementById('FOOTER_DOC').style.display='none';			
			document.getElementById('div_esegui').style.display='none';
			DOVE='art';
			var app='gestore_Add'+flag+'.php?cod='+document.getElementById('DESTINATARIO').value+'&query='+QUERY+'&tipodoc='+document.getElementById('TIPO_DOCUMENTO').value+'&stampa='+stampa;
			if(param!=""){
				app+="&"+param;
			}
			//alert(app);
			app+='&rand='+escape(Math.random());
			myRequest.open("GET",app);
			myRequest.send(null);
    	
		}	 		
}


var ATTESA=0;
function stampaListinoArt(){
	if (myRequest.readyState == 4 && myRequest.status == 200) {
// 		alert("handler");
 		document.getElementById('CORPO_DOC').innerHTML=myRequest.responseText;
		insArt();
				if(document.getElementById('totaleriga_0')){
					totaliRighe('doc');
				}
		ATTESA=0;
		//$("#PROVAMODALE").dialog("destroy").remove();
	}else{
		if(!ATTESA){
			//alert(1);
			//$("<div id='PROVAMODALE'></div>").load("sincronizza.php?rand="+escape(Math.random()),{},function(a,b,c){}).dialog({modal:true,position:"center",width:80,height:55,maxWidth:1000,maxHeight:1000,overlay:{opacity:0.5,background: "black"}});
			document.getElementById('CORPO_DOC').innerHTML="<img src='images/loader.gif'/>";
			ATTESA=1;
		}
	}


}




function stampaArt(){
  //alert(myRequest.responseText);
	if (myRequest.readyState == 4 && myRequest.status == 200) {
 		
		// alert(myRequest.responseText);
		//BACKUP['art']=myRequest.responseText;
// 		document.getElementById('HTML_DOCUMENTO').innerHTML=myRequest.responseText;
		 		document.getElementById('CORPO_DOC').innerHTML=myRequest.responseText;
				filtroArt();
	
		ATTESA=0;
		//$("#PROVAMODALE").dialog("destroy").remove();
	}else{
		if(!ATTESA){
			//alert(1);
			//$("<div id='PROVAMODALE'></div>").load("sincronizza.php?rand="+escape(Math.random()),{},function(a,b,c){}).dialog({modal:true,position:"center",width:80,height:55,maxWidth:1000,maxHeight:1000,overlay:{opacity:0.5,background: "black"}});
			document.getElementById('CORPO_DOC').innerHTML="<img src='images/loader.gif'/>";
			ATTESA=1;
		}
	}

}


function stampaArt2(){
  //alert(myRequest.responseText);
	if (myRequest.readyState == 4 && myRequest.status == 200) {
 		
		// alert(myRequest.responseText);
		//BACKUP['art']=myRequest.responseText;
 		document.getElementById('HTML_DOCUMENTO').innerHTML=myRequest.responseText;
	}
}

function aggiungiArt(indice){
	var tabella=document.getElementById('ELENCO_ARTICOLI');
	var riga=new Array();
	//alert(indice+' '+tabella.rows[indice].cells[0].innerHTML+'  '+tabella.rows[indice].cells.length);
	for(i=0;i<tabella.rows[indice].cells.length-1;i++){
		riga[i]=tabella.rows[indice].cells[i].innerHTML;
		//alert(tabella.rows[indice].cells[i].innerHTML+' '+riga[i]);
  	if(i==3){
  		var app=riga[i].split("value=");
    	app=app[1].split(" ");
    	riga[i]=app[0];
    	//alert(riga[i]);
    }
	}
	switchDoc();
	tabella=document.getElementById('ELENCO_DOC');
	var indice=cercaRiga(riga[0]);
	if(!indice){
  	var newriga=tabella.insertRow(-1);
  	for(i=0;i<riga.length;i++){
  		//alert(riga[i]);
    	var newcol=newriga.insertCell(i);
    	newcol.innerHTML=riga[i];
  	}
  }else{
		//alert(cercaRiga(riga[0]));
		tabella.rows[indice].cells[3].innerHTML=parseInt(tabella.rows[indice].cells[3].innerHTML)+parseInt(riga[3]);
	}
 	var tot=document.getElementById('TOTALE');
 	if(tot){
 		tot.value=calcolaTotale();
 		tot.onchange();
 	}	
 	var tot=document.getElementById('TOT_PRODOTTI');
 	tot.value=scaricaGiacenza();
}




function cercaRiga(chiave){

var tabella=document.getElementById('ELENCO_DOC');
var i=0,c=0;;
while(i<tabella.rows.length && !c){
	if(tabella.rows[i].cells[0].innerHTML==chiave){
		c=1;
	}else{
		i++;
	}
}
return c*i;
}




function aggiungiArt_prova(indice){
	var tabella=document.getElementById('ELENCO_ARTICOLI');
	var riga=new Array();
	for(i=0;i<tabella.rows[indice].cells.length-1;i++){
		riga[i]=tabella.rows[indice].cells[i].innerHTML;
	}
	switchDoc();
	tabella=document.getElementById('ins_tab');
	var newriga="<tr class=\"firstcolor\" onmouseover=\"this.className=mousecolor\" onmouseout=\"this.className=firstcolor\">";
	var newriga2="<tr></tr>";
	for(i=0;i<riga.length;i++){
  	newriga+="<td valign=top class=sx>"+riga[i]+"</td>";
	}
	newriga+="</tr>";
	tabella.innerHTML+=newriga2;
	alert(tabella.innerHTML);
}




function calcolaTotale_old(){

	var tabella=document.getElementById('ELENCO_DOC');
	var tot=0.0;
	
	for(i=1;i<tabella.rows.length;i++){
		var app=tabella.rows[i].cells[3].innerHTML.split("value=");
		var app2=app[1].split(" ");
		//alert(app2[0]+' piu   '+app2[1]+' piu '+tabella.rows[i].cells[4].innerHTML);
		//alert(app[0]+' piu '+tabella.rows[i].cells[4].innerHTML);
		tot+=(app2[0])*(tabella.rows[i].cells[4].innerHTML);
	}
	//alert(tot);
	return tot;
}





function calcolaTotale(){

	var tabella=document.getElementById('ELENCO_DOC');
	var tot=0.0;
	
	for(i=1;i<tabella.rows.length;i++){
		tot+=(tabella.rows[i].cells[3].innerHTML)*(tabella.rows[i].cells[4].innerHTML);
	}
	//alert(tot);
	return tot;
}



function scaricaGiacenza(){

	var tabella=document.getElementById('ELENCO_DOC');
	var tot=0;
	
	for(i=1;i<tabella.rows.length;i++){
		//var app=tabella.rows[i].cells[3].innerHTML;
		tot+=parseInt(tabella.rows[i].cells[3].innerHTML);
	}
	//alert("TOTALE PRODOTTI "+tot);
return tot;
}







/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//FUNZIONI PER INVENTARIO



function calcolaTotRiga(indice,flag){
	//alert(document.getElementById("Prezzo-Iva_"+indice).innerHTML);
		//alert(document.getElementById("Giacenza_"+indice).value);
//		alert(flag);
	var app=0;
	var app2=0;
	/*if(flag=='doc'){
		app2=parseFloat(document.getElementById("Prezzo+Iva_"+indice).innerHTML);
	}else{
		app2=parseFloat(document.getElementById("Costo+Iva_"+indice).innerHTML);	
	}*/
	
	if(flag=='doc'){
		if(document.getElementById("valorec_"+indice)){
			app2=parseFloat(document.getElementById("valorec_"+indice).value);
		}else{
			app2=parseFloat(document.getElementById("Costo+Iva_"+indice).innerHTML);	
		}
		app=parseFloat(document.getElementById("Giacenza_"+indice).innerHTML);
		
	}else if(flag=='inv'){
		if(document.getElementById("valore_Giacenza_"+indice)){
		app=parseFloat(document.getElementById("valore_Giacenza_"+indice).value);
		}else{
		app=parseFloat(document.getElementById("Giacenza_"+indice).innerHTML);
		}
		app2=parseFloat(document.getElementById("Costo+Iva_"+indice).innerHTML);
	}else{
		app=parseFloat(document.getElementById("Giacenza_"+indice).innerHTML);
		app2=parseFloat(document.getElementById("Costo+Iva_"+indice).innerHTML);
	}
	/*if(flag!='inv'){
	//	alert(document.getElementById("Giacenza_"+indice).innerHTML);
		app=parseFloat(document.getElementById("Giacenza_"+indice).innerHTML);
	}*/	
//	alert(app+'   '+app2);
		//alert(app);
	return parseFloat(document.getElementById("totaleriga_"+indice).innerHTML=(app*app2)+' &euro;');

}


function totaliRighe(flag){
//	alert(2);
	i=0;
	totale=0.0;
	while(document.getElementById("riga_"+i) && document.getElementById("totaleriga_"+i)){
		if(document.getElementById("riga_"+i).style.display!='none'){
			totale+=calcolaTotRiga(i,flag);
			arrotonda("totaleriga_",i);
		}
		i++;
	}
	if(flag=='inv' || flag=='listainv' || flag=='doc'){
		document.getElementById("totalelenco").innerHTML=totale;
		arrotonda("totalelenco","");
		document.getElementById("totalelenco").innerHTML="<b>Tot:</b>"+document.getElementById("totalelenco").innerHTML+' &euro;';
		//alert(document.getElementById("totalelenco").innerHTML);
//		document.getElementById("totalelenco").innerHTML
	}
	return totale;
}


function totaleConsumato(){
	i=0;
	totale=0;
	while(document.getElementById("riga_"+i)){
		if(document.getElementById("riga_"+i).style.display!='none'){
			totale+=calcolaConsumatoRiga(i);
			//arrotonda("totaleriga_",i);
		}
		i++;
	}
	
}

function valoreAssoluto(num){
	return ((num>=0)*num)+((num<0)*(-1*num));
}

function calcolaConsumatoRiga(indice){
	ris=0.0;
	if(document.getElementById("riga_"+indice)){
		ris=valoreAssoluto(parseInt(document.getElementById("Consumato_"+indice).value))-(parseInt(document.getElementById("Pasti_"+indice).value)*parseFloat(document.getElementById("Grammi_"+indice).value));
//alert(ris);
ris=-1*ris;
//alert(document.getElementById("Caricato_"+indice).type);
if(document.getElementById("Caricato_"+indice).type!="text"){
	var perc=((100*valoreAssoluto(ris))/parseInt(document.getElementById("Caricato_"+indice).innerHTML));
}else{
	var perc=((100*valoreAssoluto(ris))/parseInt(document.getElementById("Caricato_"+indice).value));	
}
//document.getElementById("totaleriga_"+indice).innerHTML=ris+" ("+perc+"%)";
document.getElementById("totaleriga_"+indice).innerHTML=perc;
arrotonda("totaleriga_",indice);
var app=document.getElementById("totaleriga_"+indice).innerHTML;
document.getElementById("totaleriga_"+indice).innerHTML=ris+" ("+app+"%)";
	}
	return ris;
}


function numArticoli(){
	var ris=0;
	var i=0;
	while(document.getElementById("riga_"+i)){
		if(document.getElementById("riga_"+i).style.display!='none'){
			ris++;
		}
		i++;
	}
//	alert(ris);
	return ris;
}


function numPezzi(){
	var ris=0;
	var i=0;
	while(document.getElementById("riga_"+i)){
		if(document.getElementById("riga_"+i).style.display!='none'){
			ris+=parseInt(document.getElementById("Giacenza_"+i).innerHTML);
		}
		i++;
	}
	return ris;
}


function confInventario_old(){

if(document.getElementById("Cod_articolo_0")){
	ris=document.getElementById("Cod_articolo_0").innerHTML+"SEPCAMPO"+document.getElementById("Giacenza_0").value+"SEPCAMPO"+document.getElementById("Costo+Iva_0").innerHTML;
	i=1;
	while(document.getElementById("Cod_articolo_"+i)){
			ris+="SEPRIGA"+document.getElementById("Cod_articolo_"+i).innerHTML+"SEPCAMPO"+document.getElementById("Giacenza_"+i).value+"SEPCAMPO"+document.getElementById("Costo+Iva_"+i).innerHTML;
			i++;
	}
	document.getElementById("listaelem").value=ris;
}
	
}




function confInventario(){
var ris=FILTRI[0][0];
for(k=1;k<FILTRI[0].length-2;k++){
	ris+="SEPCAMPO"+FILTRI[0][k];
}

for(i=1;i<FILTRI.length;i++){
	ris+="SEPRIGA"+FILTRI[i][0];
	for(j=1;j<FILTRI[i].length-2;j++){
		ris+="SEPCAMPO"+FILTRI[i][j];
	}
}

document.getElementById("listaelem").value=ris;
	//alert(document.getElementById("listaelem").value);

}

function switch_campo2(indice){
	var app=document.getElementById("Giacenza_"+indice).innerHTML;
	document.getElementById("Giacenza_"+indice).innerHTML="<input type='text' id='valore_Giacenza_"+indice+"' value='"+app+"' onblur=chiudiInputIndex('"+indice+"');totaliRighe('doc');>";
}


function check_giacenza(indice){
	//alert(document.getElementById("Giacenza_"+indice).getAttribute('Giacenza')+"   "+document.getElementById("valore_Giacenza_"+indice).value);
	//alert(document.getElementById("Giacenza_"+indice).getAttribute('Giacenza'));
if(document.getElementById('STATO_DOCUMENTO').value=='EMESSO'){
	if(parseInt(document.getElementById("Giacenza_"+indice).getAttribute('Giacenza'))<parseInt(document.getElementById("valore_Giacenza_"+indice).value)){
		return false;
	}else{
		return true;
	}
}else{
	return true;
}

}



function stampaErrGiacenza(){
	alert('La quantità selezionata è maggiore di quella disponibile in magazzino !!!')
}


function switch_campo(indice,ncol){
//	document.getElementById('STATO_DOCUMENTO').value="RICEVUTO";
	var app=document.getElementById("Giacenza_"+indice).innerHTML;
	
	if(ncol==2){
		var app2=document.getElementById("Costo+Iva_"+indice).innerHTML;
		document.getElementById("Costo+Iva_"+indice).innerHTML="<input type='text' id='valorec_"+indice+"' value='"+app2+"'  onblur=chiudiInputIndex('"+indice+"','1');chiudiInputIndex('"+indice+"','2');totaliRighe('doc');creaEventoFooter('onblur');>";
		document.getElementById("Giacenza_"+indice).innerHTML="<input type='text' id='valoreg_"+indice+"' value='"+app+"'  onblur=if(check_giacenza('"+indice+"')){chiudiInputIndex('"+indice+"','1');totaliRighe('doc');}else{chiudiInputIndex('"+indice+"','1');stampaErrGiacenza();}creaEventoFooter('onblur');>";
	}else{
//		document.getElementById("Giacenza_"+indice).innerHTML="<input type='text' id='valore_Giacenza_"+indice+"' value='"+app+"'  onblur=if(check_giacenza('"+indice+"')){chiudiInputIndex('"+indice+"','1');FILTRI[cercaArtFiltri(document.getElementById('Cod_articolo_"+indice+"').innerHTML)][3]=this.value;totaliRighe('doc');}else{chiudiInputIndex('"+indice+"','1');stampaErrGiacenza();}creaEventoFooter('onblur');>";
			document.getElementById("Giacenza_"+indice).innerHTML="<input type='text' id='valore_Giacenza_"+indice+"' value='"+app+"'  onblur=FILTRI[cercaArtFiltri(document.getElementById('Cod_articolo_"+indice+"').innerHTML)][3]=this.value;chiudiInputIndex('"+indice+"','1');totaliRighe('doc');creaEventoFooter('onblur');>";

	
	}
	/*if(document.getElementById("TIPO_DOCUMENTO")){
		
	}else{
		document.getElementById(idcol+"_"+indice).innerHTML="<input type='text' id='valoreg_"+indice+"' value='"+app+"'  onblur=if(check_giacenza('"+indice+"')){chiudiInputIndex('"+indice+"','"+idcol+"');totaliRighe('doc');}else{chiudiInputIndex('"+indice+"','"+idcol+"');stampaErr"+idcol+"();}creaEventoFooter('onblur');>";	
	}*/
	
	
	
	//document.getElementById("Giacenza_"+indice).innerHTML="<input type='text' id='valoreg_"+indice+"' value='"+app+"' onblur=alert(document.getElementById('Giacenza_"+indice+"').Giacenza);>";
}




function chiudiInput(ncol){

	i=0;
	while(document.getElementById("riga_"+i)){
		if(document.getElementById("valore_Giacenza_"+i)){
			chiudiInputIndex(i,1);
		}
		if(ncol==2){
			if(document.getElementById("valorec_"+i)){
				chiudiInputIndex(i,2);
			}
		}
		i++;
	}
	
}



function chiudiInputIndex(indice,ncol){
	
	if(ncol==1){
		if(document.getElementById("valore_Giacenza_"+indice)){
			var app=document.getElementById("valore_Giacenza_"+indice).value;
			if(check_giacenza(indice)){
				if(isNaN(parseInt(app))){
					app=0;
				}
				document.getElementById("Giacenza_"+indice).innerHTML=parseInt(app);
			}else{
		//		alert(document.getElementById("Giacenza_"+indice).getAttribute("Giacenza"));
				document.getElementById("Giacenza_"+indice).innerHTML=document.getElementById("Giacenza_"+indice).getAttribute("Giacenza");
			}
		}
	}
	if(ncol==2){
		var app=document.getElementById("valorec_"+indice).value;
		if(!isNaN(app)){
			document.getElementById("Costo+Iva_"+indice).innerHTML=app;
		}else{
			alert('Prezzo non valido!!!');	
			document.getElementById("Costo+Iva_"+indice).innerHTML=0;
		}
	}
}




function nameToIndex(idgrid,nome){
	var tab=jQuery(idgrid);
	var col=tab.getGridParam("colModel");
	var i=0;
	var c=-1;
	while(i<col.length && c==-1){
	//alert(col[i].name);
		if(col[i].name==nome){
			c=i;
		}
		i++;
	}
	return c;
}



function creaQueryArt(){
	//alert(1);
	
	var ris="";
	if(document.getElementById("TABELENCOART")){
		var tab=jQuery("#TABELENCOART");
		var righe=tab.getDataIDs();
		var campi=tab.getGridParam("campiDB");
		var i=0;
		for(i=0;i<righe.length;i++){
			ris+="SEPART";
			var j=1;
			ris+=tab.getCell(righe[i],nameToIndex("#TABELENCOART",campi[0]));
			for(j=1;j<campi.length;j++){
				ris+="@"+tab.getCell(righe[i],nameToIndex("#TABELENCOART",campi[j]));
			}
		}
	}
	document.getElementById("QUERY_ARTICOLI").value=ris;	
	//alert(document.getElementById("QUERY_ARTICOLI").value);
	return true;
}


function creaQueryArt_old(){
	chiudiInput();
	//alert(1);
	i=0;
	var c=0;
	var ris="";
	var campo="Costo+Iva_";
	if(document.getElementById("TIPO_DOCUMENTO").value!="ordine"){
		while(document.getElementById("riga_"+i)){
			if(document.getElementById("riga_"+i).style.display!='none'){
				ris+="SEPART"+document.getElementById("Cod_articolo_"+i).innerHTML+"@"+document.getElementById("Giacenza_"+i).innerHTML+"@"+document.getElementById("Costo+Iva_"+i).innerHTML;
				c=1;
			}
			i++;
		}
	}else{
		while(document.getElementById("riga_"+i)){
			if(document.getElementById("riga_"+i).style.display!='none'){
				ris+="SEPART"+document.getElementById("Cod_articolo_"+i).innerHTML+"@"+document.getElementById("Giacenza_"+i).innerHTML+"@"+document.getElementById("Disavanzo_"+i).innerHTML+"@"+document.getElementById("Caricato_"+i).innerHTML;
				c=1;
			}
			i++;
		}
	}
	document.getElementById("QUERY_ARTICOLI").value=ris;	
//alert(document.getElementById("QUERY_ARTICOLI").value);

if(c){
		return true;
	}else{
		alert("Nessun articolo presente nel documento !!!");
		return false;	
	}
}



function validaDest(){
	var c1=true;
	var c2=true;
	var c3=true;
	var c4=true;
	var priorita=document.getElementById('CAMPO_PRIORITA').value;
	var allegato=document.getElementById('ALLEGATO_DOCUMENTI').value;
	if(document.getElementById(priorita)){
		if(document.getElementById(priorita).value=='-7'){
			c1=false;
			alert("Scegliere un "+priorita+" !!!");
		}
	}
	if(allegato!=""){
		if(document.getElementById('ELENCO_DDT').value=='-7'){
			c2=false;
			alert("Scegliere un documento di riferimento !!!");
		}
	}
	var nump=$("#TABELENCOART").getDataIDs();
	if(!(nump.length>0)){
		c3=false;
		alert("Aggiungere almeno un articolo !!!");
	}
	if(document.getElementById("TIPO_PAGAMENTO")){
		if(document.getElementById("TIPO_PAGAMENTO").value=='-7'){
			c4=false;
			alert("Scegliere un tipologia di pagamento !!!");
		}
	}
	return c1 && c2 && c3 && c4;	
}


function validaDest_christianeunaMERDA(){
	if(document.getElementById('DESTINATARIO').value!='-7' && document.getElementById('CONSEGNA').value!='-7'){
		return true;
	}else if(document.getElementById('DESTINATARIO').value=='-7'){
		alert("Scegliere un impianto di destinazione !!!");
		return false;
	}else if(document.getElementById('CONSEGNA').value=='-7'){
		alert("Scegliere un punto di consegna!!!");
		return false;
	}
	
}



function creaEventoFooter(evento){
	var app=document.getElementsByTagName("input");
	for(var i=0;i<app.length;i++){
		if(app[i].getAttribute("contenitore")=="FOOTER"){
			//alert(app[i].id);
			eval("document.getElementById(app[i].id)."+evento+"();");
//			document.getElementById("TOT_PRODOTTI").onblur();
		}
	}

}

function creaEventoHeader(evento){
	var app=document.getElementsByTagName("input");
	for(var i=0;i<app.length;i++){
		if(app[i].getAttribute("contenitore")=="HEADER"){
			//alert(app[i].id);
			eval("document.getElementById(app[i].id)."+evento+"();");
//			document.getElementById("TOT_PRODOTTI").onblur();
		}
	}

}


function dselall(flag){
 var i=0;
 while(document.getElementById('riga_'+i)){
  if(document.getElementById('riga_'+i).style.display!='none'){
   if(flag=='sel'){
    document.getElementById('check_'+i).checked=true;
   }else{
    document.getElementById('check_'+i).checked=false;
   }
   	document.getElementById('check_'+i).onchange();
  }
  i++;
 }
}



function insArt(){
/*var app=0;
	for(var i=0;i<ARTICOLI.length;i++){
		app=cercaArticolo(ARTICOLI[i]);
		if(app>=0){
			document.getElementById("riga_"+app).style.display='';
		}
	}*/
		for(i=0;i<ARTICOLI.length;i++){
			for(j=0;j<ETICHETTE.length;j++){
				//alert(ETICHETTE[j]);
				var app="";
				app+=ETICHETTE[j];
				var ris=app.split(",");
				//alert(ris[0]+" aaaa "+ris[1]);
				if(document.getElementById(ris[1]+"_"+i)){
				document.getElementById(ris[1]+"_"+i).innerHTML=FILTRI[ARTICOLI[i]][j];
				}
			}
		}
	
}






function selArt(param){
	if(param!='torna'){
		ARTICOLI=new Array();
		for(i=0;i<FILTRI.length;i++){
			if(FILTRI[i][FILTRI[i].length-1] ||	FILTRI[i][FILTRI[i].length-2]){
				FILTRI[i][FILTRI[i].length-2]=true;		
				ARTICOLI[ARTICOLI.length]=i;			
			}
			FILTRI[i][FILTRI[i].length-1]=false;
			
		}
	}
	return ARTICOLI.length;
}

var ARTXDDT=new Array();


function selDdt(){
	 var i=0;
	 document.getElementById("APPOGGIO").innerHTML=BACKUP['doc'];
	 while(document.getElementById('riga_art_'+i)){
		if(document.getElementById('check_'+i).checked){
			if(document.getElementById("LISTA_DOCUMENTI").value!=""){
				document.getElementById("LISTA_DOCUMENTI").value+="@"+document.getElementById("Cod_Ddt_art_"+i).innerHTML;
			}else{
				document.getElementById("LISTA_DOCUMENTI").value=document.getElementById("Cod_Ddt_art_"+i).innerHTML;				
			}
			insDdt(document.getElementById("Cod_Ddt_art_"+i).innerHTML);
			document.getElementById('check_'+i).checked=false;
			document.getElementById('riga_art_'+i).style.display='none';
		}
		i++;
	 }
	 BACKUP['doc']=document.getElementById("APPOGGIO").innerHTML;
	 document.getElementById("APPOGGIO").innerHTML="";
	 //alert(document.getElementById("LISTA_DOCUMENTI").value);
}



function insDdt(coddoc){
	var app=-1;
	//alert("dim vet"+ARTXDDT[coddoc].length);
	for(i=0;i<ARTXDDT[coddoc].length;i=i+2){
		//alert("cod doc= "+coddoc+" codart= "+ARTXDDT[coddoc][i]+" QTA= "+ARTXDDT[coddoc][i+1]);
		app=cercaArticolo(ARTXDDT[coddoc][i]);
		if(app>=0){
			//alert("indice= "+app);
			if(document.getElementById('riga_'+app).style.display=='none'){
				document.getElementById('riga_'+app).style.display='';
				document.getElementById('Giacenza_'+app).innerHTML=parseInt(ARTXDDT[coddoc][i+1]);
			}else{
document.getElementById('Giacenza_'+app).innerHTML=parseInt(document.getElementById('Giacenza_'+app).innerHTML)+parseInt(ARTXDDT[coddoc][i+1]);
			}
		}
	}
}



function azzeraDocDdt(){
	 var i=0;
//	 alert("prima "+document.getElementById('LISTA_DOCUMENTI').value);
	while(document.getElementById('riga_'+i)){
		if(document.getElementById('riga_'+i).style.display!='none'){
			document.getElementById('riga_'+i).style.display='none';
			document.getElementById('Giacenza_'+i).innerHTML='0';
		}
		i++;
	 }
	 document.getElementById('LISTA_DOCUMENTI').value=""
	// alert("dopo "+document.getElementById('LISTA_DOCUMENTI').value);
}



function esisteDdt(nome){
  var c=false;
  for(var i in ARTXDDT){
		if(i==nome){
  		c=true;
  	}
  }
  return c;
}






function setDdt(chiave,valore1,valore2){
//alert(1);
if(!esisteDdt(chiave)){
		ARTXDDT[chiave]=new Array();
		ARTXDDT[chiave][0]=valore1;
		ARTXDDT[chiave][1]=valore2;
	}else{
		ARTXDDT[chiave][ARTXDDT[chiave].length]=valore1;
		ARTXDDT[chiave][ARTXDDT[chiave].length]=valore2;
	}
	
}

function stampaDdt(){
	if (myRequest.readyState == 4 && myRequest.status == 200) {

		if(document.getElementById('CORPO_DOC_LISTA')){
 			document.getElementById('CORPO_DOC_LISTA').innerHTML=myRequest.responseText;
		}else{
			document.getElementById('CORPO_DOC').innerHTML=myRequest.responseText;
		}
		if(document.getElementById('totaleriga_0')){
			totaliRighe('doc');
		}
		$(function(){
		$('.date-pick').datePicker({clickInput:false, startDate:'01/01/1900' })
	});
					
				
		  	
		//alert(document.getElementById('evento_as').onclick);
		//document.getElementById('evento_as').click();

	}
	
}



function selData(){
listinoDdt();
var param="";
if(document.getElementById('TIPO_DOCUMENTO').value=="ordine"){
	param="ordine";
}else{
	param=document.getElementById('DESTINATARIO').value;
}
var app='gestore_AddDdt.php?cod='+param+'&query='+QUERY+'&datain='+document.getElementById("datada").value+'&datafi='+document.getElementById("dataa").value+'&flag_data=1&tipodoc='+document.getElementById('TIPO_DOCUMENTO').value;
			//alert(app);
			app+='&rand='+escape(Math.random());
			myRequest = CreateXmlHttpReq(stampaDdt);
			myRequest.open("GET",app);
			myRequest.send(null);
	
}








function cercaArticolo(cod){
	var i=0;
	var ris=-1;
	c=1;
	while(document.getElementById('riga_'+i) && c){
		//alert(document.getElementById('Cod_articolo_'+i).innerHTML+"  "+cod);
		if(document.getElementById('Cod_articolo_'+i).innerHTML==cod){
			//alert(1);
			ris=i;
			c=0;
		}else{
			//alert(0);
			i++;
		}
	}
	return ris;
}



function cancArt(cod){
	
}



function listinoDdt(){
	QUERY=document.getElementById("LISTA_DOCUMENTI").value;
}





function listinoArticoli(){
	var i=0;
	var ris=-1;
	c=1;
	QUERY="";
	while(document.getElementById('riga_'+i)){
		if(document.getElementById('riga_'+i).style.display!='none'){
			QUERY+="@"+document.getElementById('Cod_articolo_'+i).innerHTML;
		}
		i++;
	}
}







function cancArticolo(indice){
	document.getElementById("riga_"+indice).style.display="none";
	if(document.getElementById("TIPO_DOCUMENTO").value=="fattura"){
		totaliRighe('doc');
	}
	creaEventoFooter("onblur");
	FILTRI[cercaArtFiltri(document.getElementById("Cod_articolo_"+indice).innerHTML)][FILTRI[0].length-1]=false;
	FILTRI[cercaArtFiltri(document.getElementById("Cod_articolo_"+indice).innerHTML)][FILTRI[0].length-2]=false;	
}


function arrotonda(campo,num){
	
	var app="aSEP"+document.getElementById(campo+num).innerHTML;
	var app2=app.split('.');
	var app3=app2;
	if(app2.length>1){
		app2=app2[1].substring(0,2);
		app=app3[0].split('SEP');
		document.getElementById(campo+num).innerHTML=app[1]+"."+app2;
	}
}


var RIGALIBERA=0;

function salvaIndice(riga){
	RIGALIBERA=riga;
}


function ins_riga(){
	document.getElementById("riga_"+RIGALIBERA).style.display='';
	RIGALIBERA++;
}



var VETTORE_DIP=new Array(new Array("a","a"));
var CONTATORE=0;






function backupDOC(){
	//alert("handler");
	if (myRequest2.readyState == 4 && myRequest2.status == 200) {
		//alert(myRequest2.responseText);
		//return;
		ris=myRequest2.responseText;
		app=ris.split("SEPERR");
		doc=app[1];
		tuple=doc.split("SEPCOL");
		var i=0;
		for(i=0;i<tuple.length;i++){
			campo=tuple[i].split("SEPCAMPO");
			tag=document.getElementById(campo[0]);
			if(tag){
				//alert(campo[0]+" => "+tag.type);
				if(tag.type=="select-one"){
						document.getElementById(campo[0]).options.selectedIndex=cercaSelect(campo[0],campo[1]);
						//alert(campo[0]);
						$("#"+campo[0]).trigger("change");
						//document.getElementById(campo[0]).onchange();
				}else{
					tag.value=campo[1];
				}
			}else{
				//alert('nobuono');
			}
		}
		ordinaDataDoc();
	}else{
		//alert("nobuono");
	}
}






function backupDOC_old(){
	if (myRequest2.readyState == 4 && myRequest2.status == 200) {
		//alert(myRequest.responseText);
		ris=myRequest2.responseText;
		app=ris.split("SEPERR");
		doc=app[2];
		tuple=doc.split("SEPCOL");
		//alert(doc);
		for(i=0;i<tuple.length;i++){
			campo=tuple[i].split("SEPCAMPO");
			//alert(campo[0]+"  "+campo[1]);
			tag=document.getElementById(campo[0]);
			if(tag){
				if(tag.type=="select-one"){
					//alert(campo[0]+"  "+tag.type);
					if(tag.getAttribute("priorita")=="ok"){
						VETTORE_DIP[0][0]=campo[0];
						VETTORE_DIP[0][1]=campo[1];
					}else{
						app=VETTORE_DIP.length;
						VETTORE_DIP[app]=new Array();
						VETTORE_DIP[app][0]=campo[0];				
						VETTORE_DIP[app][1]=campo[1];				
					}
					/*tag.options.selectedIndex=cercaSelect(campo[0],campo[1]);
					tag.onchange();*/
				}else{
					tag.value=campo[1];
				}
			}
		}
		document.getElementById(VETTORE_DIP[0][0]).options.selectedIndex=cercaSelect(VETTORE_DIP[0][0],VETTORE_DIP[0][1]);
		document.getElementById(VETTORE_DIP[0][0]).onchange();
//pause(4000);
	window.showModalDialog("sincronizza.php","","dialogHeight:1px,dialogWidth:1px,dialogHide:yes");
		for(var CONTATORE=1;CONTATORE<VETTORE_DIP.length;CONTATORE++){
			//alert(vett[j][0]+"  "+vett[j][1]);
document.getElementById(VETTORE_DIP[CONTATORE][0]).options.selectedIndex=cercaSelect(VETTORE_DIP[CONTATORE][0],VETTORE_DIP[CONTATORE][1])
//setTimeout("cercaSelect()",2000*CONTATORE,VETTORE_DIP[CONTATORE][0],VETTORE_DIP[CONTATORE][1]);
			//document.getElementById(vett[j][0]).options.selectedIndex=cercaSelect(vett[j][0],vett[j][1]);
			//setTimeout("document.getElementById(VETTORE_DIP[CONTATORE][0]).onchange()",5000*CONTATORE);
			document.getElementById(VETTORE_DIP[CONTATORE][0]).onchange();
		}
	}
	ordinaDataDoc();
}








function pausecomp(millis){
	alert(millis);
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); } 
	while(curDate-date < millis);
}


function sincronizza(){
	window.showModalDialog("sincronizza.php","","dialogHeight:1px,dialogLeft:-1,dialogTop:-1,dialogWidth:1px,dialogHide:1");
}


function vuoto(){}

function aspetta(){
	for(i=0;i<1000000;i++){
		a=(23*5646*i)/101;
	}

}

var myRequest2=null;
function ripristinaDOC(codice,doc){
	//alert(codice+"   "+doc);
 	var app='getCampiDoc.php?codice='+codice+'&documento='+doc+'&rand='+escape(Math.random());
	myRequest2 = CreateXmlHttpReq(backupDOC);
	myRequest2.open("GET",app);
	myRequest2.send(null);
}




function cercaSelect(id,valore){
	
	if(document.getElementById(id)){
		var app=document.getElementById(id);
		if(app.type=="select-one"){
			var i=0;
			var c=-1;
	//aspetta();
		while((i<document.getElementById(id).options.length) && (c==-1)){
					if(document.getElementById(id).options[i].value==valore){
						c=i;
						document.getElementById(id).options[i].selectedIndex=i;
					}
					i++;
				}
				return c;
		}else{
			//alert("nobuono!");
			return -1;
		}
	}else{
		//alert("nobuono!");
		return -1;
	}
}


function setCampoPr(){
	var app=document.getElementsByTagName("*");
	var c=1;
	var numcampi=app.length;
	var i=0;
	while(c && i<numcampi){
		if(app[i].id!=""){
			if(document.getElementById(app[i].id)){
				if(document.getElementById(app[i].id).getAttribute("priorita")=="ok"){
					document.getElementById("CAMPO_PRIORITA").value=app[i].id;			
					c=0;
					//alert(app[i].id);
				}
			}
		}
		i++;
	}
}




function setNavDoc(){
	if(document.getElementById("torna_doc")){
		document.getElementById("torna_doc").innerHTML="<a href=\"javascript:setEsegui('form1','torna','','','1','');\"><img src=\"immagini/indietro.png\"> Torna</a>";
	}
}




function ordinaDataDoc(){
	var old=document.getElementById("DATA").value;
	var nuova=old.split("/");
	nuova=nuova[2]+"/"+nuova[1]+"/"+nuova[0];
	//alert(nuova);
	document.getElementById("DATA").value=nuova;
}



/*----------------------FUNZIONI FORM ARTICOLO----------------------------*/



function calcolaCostoIva(id_iva,id_valore){
	var tag=document.getElementById(id_iva);
	var aliquota=parseFloat(tag.options[tag.options.selectedIndex].getAttribute("ali"));
	if(document.getElementById(id_valore).value==""){
		document.getElementById(id_valore).value=0;
	}
	var costo=parseFloat(document.getElementById(id_valore).value);	
	costo+=(((costo*aliquota)/100));
	return costo;
	//document.getElementById(id_valore).value=costo;
}

function impostaForn(){
	var tag=document.getElementById("forn");
	var ali=parseFloat(tag.options[tag.options.selectedIndex].getAttribute("ali"));
	var flag=true;
	if(tag.value!=-1){
		flag=false;
		document.getElementById("COSTO_PIU").value=calcolaCostoIva("forn","COSTO_MENO");
		/*var costo=parseFloat(document.getElementById("COSTO_MENO").value);	
		costo+=(((costo*ali)/100));
		document.getElementById("COSTO_PIU").value=costo;
		*/
	}else{
		document.getElementById("COSTO_PIU").value=0;
		document.getElementById("COSTO_MENO").value=0;
		document.getElementById("DATA_ULT_ACQ").value="";
	}
	document.getElementById("COSTO_PIU").disabled=flag;
	document.getElementById("COSTO_MENO").disabled=flag;
	document.getElementById("DATA_ULT_ACQ").disabled=flag;
}





function stampaGuida(pagina){
	$("<div id='PROVAMODALE'></div>").load(pagina+"?async=1",{},function(a,b,c){/*alert(a);*/}).dialog({modal:true,position:"center",width:800,height:430,maxWidth:1000,maxHeight:1000,overlay:{opacity:0.5,background: "black"}});
}





function eliminaCodSel(id,gestore){
	var tab=jQuery(id);
	var righe_or=tab.getGridParam("selarrrow");
	var ris="";
	var i=0;
	if(righe_or.length>0){
		for(i=0;i<righe_or.length;i++){
			ris+=righe_or[i]+"SEPCOD";
		}
		//alert(ris);
		setEsegui('form1',gestore,"multicanc",'cod_Articolo='+ris,'1','1');
	}else{
		alert("Nessun elemento selezionato !!!");
	}
}

