// Variables globales
var xmlHttpRequest;

// Appel d'une page générant un fichier XML 
function chargeXml(url,pstrListe,pstrCombo)	{	

		if (window.XMLHttpRequest) 	{
			xmlHttpRequest = new XMLHttpRequest();
		}
		else if (window.ActiveXObject) 	{
			xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlHttpRequest.open("GET", url, true);
		xmlHttpRequest.onreadystatechange = function () {processRequestChange(pstrListe,pstrCombo);}
		xmlHttpRequest.send(null);
	
}


// Callback appelé lors du changement de statut de la requête HTTP
function processRequestChange(pstrListe,pstrCombo) {

	if (xmlHttpRequest.readyState == 4)	{
		if(xmlHttpRequest.status == 200) {
			if (xmlHttpRequest.responseXML.xml || navigator.appName != "Microsoft Internet Explorer") {
        switch (pstrListe)
				{
					// setTimeout pour supprimer l'effet de clignotement
					case 'ilots' :	
						setTimeout("afficheXmlDataIlots();", 0);
						// Redimensionnement éventuel de la zone d'affichage						
						setTimeout("fixeTableHeight('tabilots');", 0);
						break;
					
					case 'parcelles' :
						setTimeout("afficheXmlDataParcelles();", 0);	
						setTimeout("fixeTableHeight('tabparcelles');", 0);	
						break;
	
					case 'parcellesdetsol' :
						setTimeout("afficheXmlDataParcellesDetSol();", 0);	
						// Redimensionnement éventuel de la zone d'affichage
						setTimeout("fixeTableHeight('tabparcellesdetsol');", 0);	
						break;	
						
					case 'valide' :
						setTimeout("afficheXmlDataValidation();", 0);
						break;

					case 'validecalcul' :
						setTimeout("afficheXmlDataValideCalcul();", 0);
						break;
						
					case 'synthese'	:
						setTimeout("afficheXmlDataSynthese();", 0);
						setTimeout("fixeTableHeight('tabsynth');", 0);	
						break;
						
					case 'combo' :
						setTimeout("afficheXmlCombo('"+pstrCombo+"');", 0);						
						break;

					case 'combocult' :
						setTimeout("afficheXmlComboCult('"+pstrCombo+"');", 0);						
						break;
						
					case 'saisie' :
					break;
					
					case '170kg':
          	setTimeout("afficheXml170kg();", 0);
					break;

				}
			}
			// Le document XML est incorrect (erreur lors de la génération)
			else {
				document.getElementById("msgretour").className="erreur";
				document.getElementById("msgretour").innerHTML= "Erreur serveur : Impossible d'afficher la liste.";
				document.getElementById("msgretour").title=xmlHttpRequest.responseText;
			}
		}
		else  {
			alert("Erreur "+ xmlHttpRequest.status +" : "+ xmlHttpRequest.statusText);
		}
		document.getElementById("statusZone").style.visibility = 'hidden';
		
	}
	else {
		document.getElementById("statusZone").style.visibility = 'visible';
	}
	}
	
	
// Effacement des lignes d'un tableau sauf la 1ere (entête)
function videTable(pstrTableId) {

  var objTable = document.getElementById(pstrTableId);
	
  document.getElementById("msgbas").innerHTML=" ";
 
  while (objTable.rows.length > 1)
  	{
      objTable.deleteRow(objTable.rows.length -1);
    }
    
}

// Affichage initial de liste, sans tri
function afficheListe(pstrColTri,pstrListe,pstrParam) {

	// Redimensionnement de la zone selon l'espace d'affichage
	document.getElementById("zone_tableau").style.height=(document.body.offsetHeight-findPosY(document.getElementById("zone_tableau"))-38);
	
	// Masquage du tableau
	document.getElementById("zone_tableau").style.visibility = 'hidden';

	// Affichage du sablier
	document.getElementById("statusZone").style.visibility = 'visible';
	
	
	var file = "/www/ppf/get"+pstrListe+".php?format=xml"+pstrParam;
	chargeXml(file,pstrListe);
	//window.open(file,'getListe');
	//alert(pstrParam);

}

// Affichage trié de la liste
function triListe(pstrColTri,pstrListe,pstrParam) {
	
	// Affichage du sablier
	document.getElementById("statusZone").style.visibility = 'visible';
		
    var file = "/www/ppf/get"+pstrListe+".php?format=xml&coltri="+pstrColTri+pstrParam;
        
    chargeXml(file,pstrListe);
}


// Ajout d'une ligne à une table
function ajoutLigneTable(pstrTableId, ptabLigne) {
	var objTable = document.getElementById(pstrTableId);
	var intLastRow = objTable.rows.length;
	var objRow = objTable.insertRow(intLastRow);
		
	if (objTable.rows.length != 1) {
		// Pour alterner la couleur des lignes
		if (objTable.rows[intLastRow-1].className=="d0") {
			objRow.className = "d1";
		}
		else {
			objRow.className = "d0";
		}
	}
	else {
		objRow.className = "d0";
	}
	
	
	tabobjCell = new Array ();
		
	for (i=0; i<ptabLigne.length; i++) {
		tabobjCell[i] = objRow.insertCell(i);
		tabobjCell[i].appendChild(ptabLigne[i]);
	} 		
}

function afficheXmlDataValidation() {
	
	var statut = xmlHttpRequest.responseXML.getElementsByTagName("statut")[0].firstChild.nodeValue;
	var message = xmlHttpRequest.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
	var messagetech = xmlHttpRequest.responseXML.getElementsByTagName("messagetech")[0].firstChild.nodeValue;
	switch (statut) {
		
		// Erreur technique
		case '-1':
			document.getElementById("msgretour").className="erreur";
			document.getElementById("msgretour").innerHTML= "Erreur serveur : " + message;
			document.getElementById("msgretour").title=messagetech;
			break;
		
		// Erreur utilisateur
		case '0':
			document.getElementById("msgretour").className="erreur";
			document.getElementById("msgretour").innerHTML=message;
			break;
		
		// Succès	
		case '1':
			document.getElementById("msgretour").className="succes";
			document.getElementById("msgretour").innerHTML=message;
			break;
	}
}

function imprimeliste(pstrTitre, pstrObjListe) {
	var intXPos = (screen.width-240) / 2;
	var intYPos = (screen.height-80) / 2;
	window.open('/www/ppf/imprimeliste.php?liste='+pstrObjListe+'&titre='+pstrTitre,'Impression', 'directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=240,height=80,left='+intXPos+',top='+intYPos);
}

function popup(pstrUrl) {
	var intXPos = (screen.width-240) / 2;
	var intYPos = (screen.height-80) / 2;
	window.open(pstrUrl,'Impression', 'directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=240,height=80,left='+intXPos+',top='+intYPos);
}

function ouvreferme(pinStrId) {
	if (document.getElementById(pinStrId).style.display=='block') {
		document.getElementById(pinStrId).style.display='none';
	}
	else {
		document.getElementById(pinStrId).style.display='block';
	}
}


function afficheXmlCombo(pstrCombo){			
	var items = xmlHttpRequest.responseXML.getElementsByTagName("ligne");

	videCombo(pstrCombo);

	var objcombo=document.getElementById(pstrCombo);
	
	
	if (items.length > 0) {				
		
		for (var i=0; i<items.length; i++) {
			var node = items[i];
			
			objOptionNode=document.createElement("option");
			objOptionNode.value = node.getElementsByTagName("id")[0].firstChild.nodeValue;
						
			objOptionNode.appendChild(document.createTextNode(node.getElementsByTagName("valeur")[0].firstChild.nodeValue));			
			objcombo.appendChild(objOptionNode);

		}
	}
}

// Effacement des lignes d'un tableau sauf la 1ere (entête)
function videCombo(pstrComboId) {

	var objcombo=document.getElementById(pstrComboId);
	var taille = objcombo.length;
	
	for (i=0; i < taille; i++) {
		objcombo.options.remove(0);
	}
}

// fonction utile pour fixepopup
function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

// fonction utile pour fixepopup
function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

//trouve la position X et Y et se positionne dessus pour gestion ouvreferme d'une popup de 350px de haut
function fixepopup(pobjLien, pStrPopup) {	
	document.getElementById(pStrPopup).style.left=findPosX(pobjLien);
	document.getElementById(pStrPopup).style.top=findPosY(pobjLien);

	//alert(document.getElementById(pStrPopup).style.width);
	
	intDiff = findPosY(pobjLien)+350 - document.body.scrollTop;
	
	if (intDiff > document.body.clientHeight) {
		document.getElementById(pStrPopup).style.top = findPosY(pobjLien)-350;
	}
}

// Redimensionnement de la zone d'affichage d'un tableau
function fixeTableHeight(pstrTableau) {

	if (document.getElementById(pstrTableau).offsetHeight < document.getElementById("zone_tableau").offsetHeight) {	
		document.getElementById("zone_tableau").style.height = document.getElementById(pstrTableau).offsetHeight;
	}
	
	// Affichage du tableau
	document.getElementById("zone_tableau").style.visibility = 'visible';
	
}

/*
    Copyright Robert Nyman, http://www.robertnyman.com
    Free to use if this text is included
*/
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}



//calcul l'azote produit en kg pour chaque ligne de "170kg d'azote" suite a la modif d'un effectif moyen
//puis mise a jour total categorie et total azote final

function fcalculAzoteProduit(pintCategorie,pintIdCalcul,pintEffectif, pintKgazote, pintIdParent, pbooConnBase) {
	if (typeof pbooConnBase == "undefined"){
		pbooConnBase = true;
	}
	//sauvegarde des valeurs des elements avant prise en compte modif effectif
	var intTotLigne=document.getElementById(pintIdCalcul).innerHTML;
	var intTotCategorie=document.getElementById("total"+pintCategorie).innerHTML;
	var intTotLigneParent;

	// Modification de la catégorie parente si besoin
	if (pintIdParent != 0)  {
		
		//intSepPos = document.getElementById("effmoyen"+pintIdParent).value.indexOf("/");
		//if (intSepPos != -1) {
			//var intEffMoyenParentTotal = document.getElementById("effmoyen"+pintIdParent).value.substring(intSepPos+2,document.getElementById("effmoyen"+pintIdParent).value.length);
			var intEffMoyenParentTotal = document.getElementById("effmoyen"+pintIdParent).value;
		//}
		//else {
		//	var intEffMoyenParentTotal = document.getElementById("effmoyen"+pintIdParent).value;
		//}

		// Calcul du total des sous-catégories
		var intEffMoyenParent = intEffMoyenParentTotal;
		//alert(getElementsByAttribute(document.body, "input", "pereid", pintIdParent).length);
		
		// Si on a une connexion à la base de données, les données sont contrôlées par celle existante en base
		if(pbooConnBase){
			for (i=0; i<getElementsByAttribute(document.body, "input", "pereid", pintIdParent).length; i++) {
				intEffMoyenParent = intEffMoyenParent - getElementsByAttribute(document.body, "input", "pereid", pintIdParent)[i].value;
			}
		
	    // Cas où l'effectif saisi dépasse le total
			if (intEffMoyenParent < 0) {
				pintEffectif = intEffMoyenParentTotal;
				//document.getElementById("souseffmoyen"+pintIdParent).value = pintEffectif;
	      		document.getElementById("effmoyen"+pintIdCalcul).value = eval(document.getElementById("effmoyen"+pintIdCalcul).value + intEffMoyenParent);
				intEffMoyenParent = 0;
			}
			
		//si on a pas de connexion, les données sont calculées par rapport à la saisie
		}else{
			var intTmpFils = 0;
			if (intEffMoyenParent == ""){
					intEffMoyenParent = 0;
				}
				else{
					intEffMoyenParent = parseInt(intEffMoyenParent);
			}
			for (i=0; i<getElementsByAttribute(document.body, "input", "pereid", pintIdParent).length; i++) {
				var fils = parseInt(getElementsByAttribute(document.body, "input", "pereid", pintIdParent)[i].value);
				if( isNaN(fils) ){
					fils = 0;
				}
				
				intEffMoyenParent = intEffMoyenParent - fils;
				intTmpFils = intTmpFils + fils;
			}
			if(intEffMoyenParent <= 0){
				intEffMoyenParent = "" ;
			}
			
			if(intEffMoyenParent > 0){
				intTmpTotal = intTmpFils + intEffMoyenParent
			}else{
				intTmpTotal = intTmpFils;
			}
			if( (intTmpTotal > intEffMoyenParent) && (intTmpFils = 0) ){
				intEffMoyenParentTotal = intTmpTotal;
			}
		}
		// Affectation à la nouvelle valeur
		document.getElementById("souseffmoyen"+pintIdParent).value = intEffMoyenParent;
		document.getElementById("effmoyen"+pintIdParent).value = intEffMoyenParentTotal;
	}

	// Affichage des sommes apres modif effectif
	var intCalculLigne=(pintKgazote * pintEffectif);
	intCalculLigne=Math.round(intCalculLigne * 100)/100;
	document.getElementById(pintIdCalcul).innerHTML=intCalculLigne;
	//alert('pintIdCalcul ' +pintIdCalcul);
	//alert('intTotCategorie ' + intTotCategorie);
	//alert('intTotLigne ' + intTotLigne);
	//alert('intCalculLigne ' + intCalculLigne);
	
	// Calcul du sous-total pour la catégorie
	var intCalculCategorie=intTotCategorie-intTotLigne+intCalculLigne;
	intCalculCategorie=Math.round(intCalculCategorie * 100)/100;
	document.getElementById("total"+pintCategorie).innerHTML=intCalculCategorie;

	// Mise à jour de l'azote produit pour la catégorie parente si elle existe
	if (pintIdParent != 0) {
		intTotLigneParent=document.getElementById(pintIdParent).innerHTML;
		//alert('intTotLigneParent ' + intTotLigneParent);
		var intKgazoteParent = document.getElementById("kgazote"+pintIdParent).innerHTML;
		var intCalculParent = intKgazoteParent * intEffMoyenParent;
		document.getElementById(pintIdParent).innerHTML = Math.round(intCalculParent * 100)/100;
		
		intCalculCategorie=intCalculCategorie-intTotLigneParent+intCalculParent;
		intCalculCategorie=Math.round(intCalculCategorie * 100)/100;
		document.getElementById("total"+pintCategorie).innerHTML=intCalculCategorie;
		
		//alert('document.getElementById(pintIdParent).innerHTML ' + document.getElementById(pintIdParent).innerHTML);
	}
	
	// Calcul éventuel du total complet de l'azote produit par les animaux
	if (document.getElementById("totalazoteproduit")) {
		var intTotalproduit=document.getElementById("totalazoteproduit").value;
		intTotalproduit=intTotalproduit-intTotLigne+intCalculLigne;
		intTotalproduit=Math.round(intTotalproduit * 100)/100;
		document.getElementById("totalazoteproduit").value=intTotalproduit;
		fcalculOpt2();
	}
	
}

//fonction de calcul 170kg azote / Import-Export d'azote organique
function fcalculOpt2() {

	if (document.getElementById("sortant").value==""){
		intSortant=0;
	}else{
		intSortant=eval(document.getElementById("sortant").value);
	}

	if (document.getElementById("totalazoteproduit").value==""){
		intTotalproduit=0;
	}else{
		intTotalproduit=document.getElementById("totalazoteproduit").value;
	}


	if (document.getElementById("entrant")){
		//nous sommes dans un departement autre que 54

		if (document.getElementById("entrant").value==""){
			intEntrant=0;
		}else{
			intEntrant=document.getElementById("entrant").value;
		}


		intTotalOpt2=(eval(intTotalproduit)+eval(intEntrant))-intSortant;

	}else{
		//nous sommes dans le departement 54
		if (document.getElementById("entrant_1").value==""){
			intEntrant1=0;
		}else{
			intEntrant1=document.getElementById("entrant_1").value;
		}

		if (document.getElementById("entrant_2").value==""){
			intEntrant2=0;
		}else{
			intEntrant2=document.getElementById("entrant_2").value;
		}

		if (document.getElementById("entrant_3").value==""){
			intEntrant3=0;
		}else{
			intEntrant3=document.getElementById("entrant_3").value;
		}

		intTotalOpt2=(eval(intTotalproduit)+eval(intEntrant1)+eval(intEntrant2)+eval(intEntrant3))-intSortant;
	}
	document.getElementById("TotalOpt2").value=intTotalOpt2;

	//Calcul Total final Azote Organique par ha
	if (document.getElementById("TOT_AZOTE")){
		var intSE=document.getElementById("SE").value;
		if (intSE==0){
			intTotal=0;
		}else{
		intTotal=Math.round((intTotalOpt2/intSE)*100)/100;
		}
		document.getElementById("TOT_AZOTE").value=intTotal; 
	}
}

//fonction de verification de la saisie de chiffres positifs uniquements
function fVerifcar(e){	
	if(e.keyCode < 46 || e.keyCode == 47 || e.keyCode > 57 ) e.returnValue = false;
	if(e.which < 46 || e.which == 47 || e.which > 57) return false;
}

function valide170kg() {
   // Constituation de la chaine de paramètres de validation
   strurl = "/www/170kg/valide170kg.php?";
   
	var arrobjInputs = document.getElementsByTagName("INPUT");

 	for(i=0; i<arrobjInputs.length; i++) {
      if (arrobjInputs[i].name != '') {
         strurl = strurl + arrobjInputs[i].name + "=" + arrobjInputs[i].value + "&";
      }
   }
   chargeXml(strurl,"170kg");
}


function afficheXml170kg() {
		// Affichage des pavés selon le résultat
    document.getElementById("pbilan").style.visibility="visible";
    if (document.getElementById("TOT_AZOTE").value <= 170)
    {
		 document.getElementById("bilan_ok").style.display="block";
     document.getElementById("bilan_ko").style.display="none";
		}
		else {
      document.getElementById("bilan_ko").style.display="block";
		 document.getElementById("bilan_ok").style.display="none";
		}

  	// Mise à jour de la valeur
	 document.getElementById("bilan_ok_niveau").innerHTML = "D'après les informations connues votre niveau d'azote organique par ha est de : " + document.getElementById("TOT_AZOTE").value;
	 document.getElementById("bilan_ko_niveau").innerHTML = "D'après les informations connues votre niveau d'azote organique par ha est de : " + document.getElementById("TOT_AZOTE").value;
	 // Scrolling de la page jusqu'en bas (pavé de résultat)
		window.scrollBy(0,200);

}
