<?php
/****************************************************************************************
SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV

Version 0.9.9

Copyright (C) 2006-2009  Sylvain FATOME
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; 
either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program
(in the directory docs); 
if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 
Boston, MA  02110-1301, USA.

Contact : galawa@free.fr

Web : http://smitst.homelinux.com
****************************************************************************************/

// Vérification des tentatives de hack
$pos=strpos($_SERVER['PHP_SELF'],"inc.php");
if ($pos===FALSE)
	$ok_inc=TRUE;
else
	$ok_inc=FALSE;
if ($ok_inc==FALSE) header("Location: ../index.php");

/**********************************************/
/* Fonctions pour les accès aux interventions */
/* et fichiers rattachés                      */
/**********************************************/

/** Indices **/

// Vérification du nombre d'indices contrats
function nb_ind()
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rexist = "SELECT * FROM `" .TBIND;
	$rs2 = mysql_query($rexist) or die(mysql_error());
	$nbexist = mysql_num_rows($rs2);
	mysql_free_result($rs2);
	mysql_close($conn2);

	return $nbexist;
}

// Lecture d'un enregistrement indice contrat
function lit_enr_ind($code,$open=TRUE)
{
	if ($open==TRUE)
	{
		$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	$rech2 = "SELECT * FROM " .TBIND. " WHERE ind_code = '$code'";
	$rs2 = mysql_query($rech2)or die(mysql_error());
	if ($row2 = mysql_fetch_array($rs2))
	{
	}
	mysql_free_result($rs2);
	
	if ($open==TRUE)
		mysql_close($conn2);
	
	return $row2;
}

// Vérifie si un indice est modifiable
// Non, si déjà utilisé  :
//     dans une intervention
function ind_modifiable($code,$open)
{
	$used=FALSE;
	if ($open==TRUE)
	{
		$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}

	// Dans une intervention
	$rech2 = "SELECT * FROM " .TBINTH. " WHERE inth_codeind = '$code'";
	$rs2 = mysql_query($rech2)or die(mysql_error());
	if (mysql_num_rows($rs2)>0)
		$used=TRUE;

	mysql_free_result($rs2);
	if ($open==TRUE)
		mysql_close($conn2);
	
	return !$used;
}




/** Interventions **/

// Lecture d'un enregistrement intervention
function lit_enr_int($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rech2 = "SELECT * FROM `" .TBINT. "` WHERE `int_code` = '$code'";
	$rs2 = mysql_query($rech2)or die(mysql_error());
	if ($row2 = mysql_fetch_array($rs2))
	{
	}
	mysql_free_result($rs2);
	mysql_close($conn2);
	
	return $row2;
}

// Vérification si intervention close ou pas
function int_closed($code,$open)
{
	$closed=FALSE;
	if ($open==TRUE)
	{
		$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	$rexist2 = "SELECT int_datefin FROM `" .TBINT. "` WHERE `int_code` = '$code'";
	$rs2 = mysql_query($rexist2) or die(mysql_error());
	if (mysql_num_rows($rs2) <> 0)
	{
		if ($row2 = mysql_fetch_array($rs2))
		{
			extract ($row2);
			if ($int_datefin<>"0000-00-00")
				$closed = TRUE;
		}
	}
	mysql_free_result($rs2);
	if ($open==TRUE)
		mysql_close($conn2);
	
	return $closed;
}

// Vérification de la présence d'une agence/opérateur/technicien en tant 
// que code de création d'une fiche intervention
function exist_in_int_codecrea($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rexist = "SELECT * FROM `" .TBINT. "` WHERE `int_codecrea` = '$code'";
	$rs2 = mysql_query($rexist) or die(mysql_error());
	if (mysql_num_rows($rs2) <> 0)
		$exist = TRUE;
	else
		$exist = FALSE;
	mysql_free_result($rs2);
	mysql_close($conn2);
	
	return $exist;
}

// Crée une chaîne qui contient la liste des problèmes rattachés à une intervention
function cree_str_lstpbm_int($ci)
{
	$lstpbm = "";
	
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rech2 = "SELECT rpbm_id FROM `" .TBRPBM. "` WHERE `rpbm_codeint`= '".$ci."' ORDER BY `rpbm_datecrea`";
	$rs2 = mysql_query($rech2) or die(mysql_error());
	while ($row2 = mysql_fetch_assoc($rs2)) 
	{
		extract($row2);
		$lstpbm .= $rpbm_id."-";
	}
	mysql_free_result($rs2);
	mysql_close($conn2);
	if ($lstpbm!="")
		$lstpbm = substr($lstpbm,0,strlen($lstpbm)-1);
	
	return $lstpbm;
}

// Crée le texte des matériels (intervention) sur la base de la string des problèmes choisis
function cree_txt_matos_int($lstpbm)
{
	$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$txtmatos="";
	$tab_lstpbm=explode("-",$lstpbm);
	
	if (count($tab_lstpbm>0))
	{
		for($i=0; $i<count($tab_lstpbm); $i++)
		{
			$rech = "SELECT * FROM `" .TBRPBM. "` WHERE `rpbm_id`= '".$tab_lstpbm[$i]."'";
			$rs = mysql_query($rech) or die(mysql_error());
			if (mysql_num_rows($rs) == 1) // Il ne peut y avoir qu'un seul résultat
			{
				if ($row = mysql_fetch_array($rs))
				{
					extract ($row);
					$rech2="";
					switch ($rpbm_typrel)
					{
						// C'est une licence
						case 1 :
							$rech2 = "SELECT * FROM `" .TBRLIC. "` WHERE `rlic_code`= '".$rpbm_coderlp."'";
							break;
							
						// C'est du matériel
						case 2 :
							$rech2 = "SELECT * FROM `" .TBRPDT. "` WHERE `rpdt_code`= '".$rpbm_coderlp."'";
							break;
							
						default :
							break;
					}
					if ($rech2<>"")
					{
						$txtmatos_titre="";
						$txtmatos_corps1="";
						$txtmatos_pied="";
						$rs2 = mysql_query($rech2) or die(mysql_error());
						if ($row2 = mysql_fetch_array($rs2))
						{
							extract ($row2);
							
							switch ($rpbm_typrel)
							{
								// C'est une licence
								case 1 :
									$txtmatos_titre ="---- DETAIL LICENCE CONCERNEE PAR LE PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
									$rech3 = "SELECT * FROM ".TBMQUE." WHERE `mque_code` = '".$rlic_codema."'";
									$rs3 = mysql_query($rech3) or die(mysql_error());
									if ($row3 = mysql_fetch_array($rs3))
									{
										extract ($row3);
									}
									$txtmatos_corps1 .= "Relevé ".$rlic_code." : ".$mque_ste." ".$rlic_modele." ".$rlic_version;
									mysql_free_result($rs3);
									break;

								// C'est du matériel
								case 2 :
									$txtmatos_titre ="---- DETAIL MATERIEL CONCERNE PAR LE PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
									$rech3 = "SELECT * FROM ".TBRPCAT." WHERE `rpcat_code` = '".$rpdt_codecat."'";
									$rs3 = mysql_query($rech3) or die(mysql_error());
									if ($row3 = mysql_fetch_array($rs3))
									{
										extract ($row3);
									}
									$rech3 = "SELECT * FROM ".TBMQUE." WHERE `mque_code` = '".$rpdt_codema."'";
									$rs3 = mysql_query($rech3) or die(mysql_error());
									if ($row3 = mysql_fetch_array($rs3))
									{
										extract ($row3);
									}
									$txtmatos_corps1 = "Relevé ".$rpdt_code." : ".$rpcat_desc." / ".$mque_ste." ".$rpdt_modele." (".$rpdt_codep.")";
									mysql_free_result($rs3);
									break;
									
								default :
									break;
							}
							
							switch ($rpbm_typrel)
							{
								// C'est une licence
								case 1 :
									$txtmatos_pied = "---- FIN LICENCE CONCERNEE PAR LE PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
									break;
									
								// C'est du matériel
								case 2 :
									$txtmatos_pied = "---- FIN MATERIEL CONCERNEE PAR LE PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
									break;
									
								default :
									break;
							}
							$txtmatos.=$txtmatos_titre."%%".$txtmatos_corps1."%%".$txtmatos_pied."%%%%";
						}
						mysql_free_result($rs2);
					}
				}
			}
			mysql_free_result($rs);
		}
	}
	mysql_close($conn);
	
	if ($txtmatos!="")
		$txtmatos = substr($txtmatos,0,strlen($txtmatos)-4);
	return $txtmatos;
}


// Crée le texte des problèmes (intervention) sur la base de la string des problèmes choisis
function cree_txt_pbm_int($lstpbm)
{
	$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$txtpbm="";
	$tab_lstpbm=explode("-",$lstpbm);
	
	if (count($tab_lstpbm>0))
	{
		for($i=0; $i<count($tab_lstpbm); $i++)
		{
			$rech = "SELECT * FROM `" .TBRPBM. "` WHERE `rpbm_id`= '".$tab_lstpbm[$i]."'";
			$rs = mysql_query($rech) or die(mysql_error());
			if (mysql_num_rows($rs) == 1) // Il ne peut y avoir qu'un seul résultat
			{
				if ($row = mysql_fetch_array($rs))
				{
					extract ($row);
					$rech2="";
					switch ($rpbm_typrel)
					{
						// C'est une licence
						case 1 :
							$rech2 = "SELECT * FROM `" .TBRLIC. "` WHERE `rlic_code`= '".$rpbm_coderlp."'";
							break;
							
						// C'est du matériel
						case 2 :
							$rech2 = "SELECT * FROM `" .TBRPDT. "` WHERE `rpdt_code`= '".$rpbm_coderlp."'";
							break;
							
						default :
							break;
					}
					if ($rech2<>"")
					{
						$txtpbm_titre="";
						$txtpbm_corps1="";
						$txtpbm_corps1="";
						$txtpbm_pied="";
						$rs2 = mysql_query($rech2) or die(mysql_error());
						if ($row2 = mysql_fetch_array($rs2))
						{
							extract ($row2);
							
							$txtpbm_titre ="---- DETAIL PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
							$saut = chr(13).chr(10);
							$txtpbm_corps1 = ereg_replace($saut,"%%",htmlspecialchars_decode($rpbm_pbm));
							$txtpbm_corps2 = "Signalé par ".$rpbm_signale.", le ".formatedate($rpbm_datecrea);
							$txtpbm_pied = "---- FIN PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";

							$txtpbm.=$txtpbm_titre."%%".$txtpbm_corps1."%%".$txtpbm_corps2."%%".$txtpbm_pied."%%%%";
						}
						mysql_free_result($rs2);
					}
				}
			}
			mysql_free_result($rs);
		}
	}
	mysql_close($conn);
	
	if ($txtpbm!="")
		$txtpbm = substr($txtpbm,0,strlen($txtpbm)-4);
	return $txtpbm;
}

// Crée le texte des travaux effectués (intervention) sur la base de la string des problèmes choisis
function cree_txt_fait_int($lstpbm)
{
	$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$txtfait="";
	$tab_lstpbm=explode("-",$lstpbm);
	
	if (count($tab_lstpbm>0))
	{
		for($i=0; $i<count($tab_lstpbm); $i++)
		{
			$rech = "SELECT * FROM `" .TBRPBM. "` WHERE `rpbm_id`= '".$tab_lstpbm[$i]."'";
			$rs = mysql_query($rech) or die(mysql_error());
			if (mysql_num_rows($rs) == 1) // Il ne peut y avoir qu'un seul résultat
			{
				if ($row = mysql_fetch_array($rs))
				{
					extract ($row);

					if (trim($rpbm_fait)<>"")
					{
						$txtfait_titre ="---- TRAVAIL EFFECTUE SUR PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
						$saut = chr(13).chr(10);
						$txtfait_corps = ereg_replace($saut,"%%",htmlspecialchars_decode($rpbm_fait));
						$txtfait_pied = "---- FIN TRAVAIL EFFECTUE SUR PROBLEME N°".sprintf("%'010s",$rpbm_id)." ----";
						$txtfait.=$txtfait_titre."%%".$txtfait_corps."%%".$txtfait_pied."%%%%";
					}
				}
			}
			mysql_free_result($rs);
		}
	}
	mysql_close($conn);
	
	if ($txtfait!="")
		$txtfait = substr($txtfait,0,strlen($txtfait)-4);
	return $txtfait;
}

/** Détails Horaires **/

// Vérification de la présence d'une intervention dans un historique contrat client
function exist_int_in_coclh($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rexist = "SELECT * FROM `" .TBCOCLH. "` WHERE `coclh_codeint` = '$code'";
	$rs2 = mysql_query($rexist) or die(mysql_error());
	if (mysql_num_rows($rs2) <> 0)
		$exist = TRUE;
	else
		$exist = FALSE;
	mysql_free_result($rs2);
	mysql_close($conn2);

	return $exist;
}

// Nombre de détail horaire pour une intervention
function nb_inth($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rech2 = "SELECT * FROM `" .TBINTH. "` WHERE `inth_codeint` = '$code'";
	$rs2 = mysql_query($rech2)or die(mysql_error());
	$nbexist = mysql_num_rows($rs2);
	mysql_free_result($rs2);
	mysql_close($conn2);
	
	return $nbexist;
}

// Lecture d'un enregistrement détail horaire intervention
function lit_enr_inth($id)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rech2 = "SELECT * FROM `" .TBINTH. "` WHERE `inth_id` = '$id'";
	$rs2 = mysql_query($rech2)or die(mysql_error());
	if ($row2 = mysql_fetch_array($rs2))
	{
	}
	mysql_free_result($rs2);
	mysql_close($conn2);
	
	return $row2;
}

// Donne le temps complet travaillé sur une intervention
function tps_travaille_int($codeint,$open)
{
	$tps=0;
	if ($open==TRUE)
	{
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	
	// Récupération total travaillé
	$rech = "SELECT * FROM `" .TBINTH. "` WHERE `inth_codeint`= '".$codeint."'";
	$rs = mysql_query($rech) or die(mysql_error());
	if (mysql_num_rows($rs) <> 0)
	{
		while ($row = mysql_fetch_assoc($rs)) 
		{         
			$ind_coeff=1;
			if ($row["inth_codeind"]<>"-1")
			{
				$row2=lit_enr_ind($row["inth_codeind"],FALSE);
				if (is_array($row2))
					extract($row2);
			}
			$tps = $tps + (diff_time_sec($row["inth_heurea"],$row["inth_heured"])*$ind_coeff);
		}
	}

	mysql_free_result($rs);
	if ($open==TRUE)
	{
		mysql_close($conn);
	}
	
	return $tps;
}

// Donne le temps réellement compté au client sur une intervention
function tps_retenu_int($codeint,$open)
{
	$tps=0;
	if ($open==TRUE)
	{
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	
	// Récupération total travaillé
	$rech = "SELECT * FROM `" .TBINTH. "` WHERE `inth_codeint`= '".$codeint."' AND `inth_offert`= 0";
	$rs = mysql_query($rech) or die(mysql_error());
	if (mysql_num_rows($rs) <> 0)
	{
		while ($row = mysql_fetch_assoc($rs)) 
		{         
			$ind_coeff=1;
			if ($row["inth_codeind"]<>"-1")
			{
				$row2=lit_enr_ind($row["inth_codeind"],FALSE);
				if (is_array($row2))
					extract($row2);
			}
			$tps = $tps + (diff_time_sec($row["inth_heurea"],$row["inth_heured"])*$ind_coeff);
		}
	}

	mysql_free_result($rs);
	if ($open==TRUE)
	{
		mysql_close($conn);
	}
	
	return $tps;
}

// Donne le temps offert sur une intervention
function tps_offert_int($codeint,$open)
{
	$tps=0;
	if ($open==TRUE)
	{
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	
	// Récupération total travaillé
	$rech = "SELECT * FROM `" .TBINTH. "` WHERE `inth_codeint`= '".$codeint."' AND `inth_offert`= 1";
	$rs = mysql_query($rech) or die(mysql_error());
	if (mysql_num_rows($rs) <> 0)
	{
		while ($row = mysql_fetch_assoc($rs)) 
		{         
			$ind_coeff=1;
			if ($row["inth_codeind"]<>"-1")
			{
				$row2=lit_enr_ind($row["inth_codeind"],FALSE);
				if (is_array($row2))
					extract($row2);
			}
			$tps = $tps + (diff_time_sec($row["inth_heurea"],$row["inth_heured"])*$ind_coeff);
		}
	}

	mysql_free_result($rs);
	if ($open==TRUE)
	{
		mysql_close($conn);
	}
	
	return $tps;
}

// Calcule le prix de revient d'une intervention
function px_revient_int($codeint,$open)
{
	$pr=0;
	if ($open==TRUE)
	{
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	
	// Récupération prix de revient pour le travail effectué (inclus offert)
	$rech = "SELECT * FROM `" .TBINTH. "` WHERE `inth_codeint`= '".$codeint."'";
	$rs = mysql_query($rech) or die(mysql_error());
	if (mysql_num_rows($rs) <> 0)
	{
		while ($row = mysql_fetch_assoc($rs)) 
		{
			extract($row);    
			$cout_site=0;
			$tps = diff_time_sec($inth_heurea,$inth_heured); // Temps passé sur site
			$cout_aller=0;
			$tpsa = diff_time_sec($inth_aheured,$inth_aheuref); // Temps pour aller
			$cout_retour=0;
			$tpsr = diff_time_sec($inth_rheured,$inth_rheuref); // Temps pour retour
			// Calcul du coût de déplacement
			// On récupère le prix de revient du technicien en fonction de la date
			$rech2 = "SELECT tecpr_couth FROM `" .TBTECPR. "` WHERE `tecpr_date` <= '$inth_date' AND `tecpr_codetec` = '".$inth_codetec."' ORDER BY tecpr_date DESC";
			$rs2 = mysql_query($rech2)or die(mysql_error());
			if ($row2 = mysql_fetch_array($rs2))
			{
				extract($row2);
				// ... Aller
				$rech3 = "SELECT * FROM `" .TBMT. "` WHERE `mt_code` = '$inth_acodemt'";
				$rs3 = mysql_query($rech3)or die(mysql_error());
				if ($row3 = mysql_fetch_array($rs3))
				{
					extract($row3);
					if ($mt_coutk>0) // C'est un coût interne
						$cout_aller=$inth_akm*$mt_coutk; // Montant "kilométrique" aller
					else // C'est sous-traité
					{
						// Coût forfaitaire
						if ($mt_coutas==0) // A saisir ?
							$cout_aller=$mt_coutf; // Oui : Montant forfaitaire pour l'aller
						else
							$cout_aller=$inth_acd; // Non : Montant saisi pour l'aller
						// Coût kilométrique
						if ($mt_kmill==0) // Pas illimité : on calcule (sinon on ne fait rien)
						{
							$diff_km=$inth_akm-$mt_kmi;
							if ($diff_km>0)
								$cout_aller=$cout_aller+($mt_kms*$diff_km);
						}
					}
					$cout_aller=$cout_aller+$mt_coutc+$inth_afrais; // Rajout des frais supplémentaires
					
					if ($mt_tpsdi==0) // Le temps de déplacement n'est pas inclus : on calcul (sinon on ne fait rien)
						$cout_aller=$cout_aller+round((($tecpr_couth/3600)*$tpsa)*100)/100;
				}
				// ...Sur site
				$cout_site=round((($tecpr_couth/3600)*$tps)*100)/100;
				// ... Retour
				$rech3 = "SELECT * FROM `" .TBMT. "` WHERE `mt_code` = '$inth_rcodemt'";
				$rs3 = mysql_query($rech3)or die(mysql_error());
				if ($row3 = mysql_fetch_array($rs3))
				{
					extract($row3);
					if ($mt_coutk>0) // C'est un coût interne
						$cout_retour=$inth_rkm*$mt_coutk; // Montant "kilométrique" retour
					else // C'est sous-traité
					{
						// Coût forfaitaire
						if ($mt_coutas==0) // A saisir ?
							$cout_retour=$mt_coutf; // Oui : Montant forfaitaire pour le retour
						else
							$cout_retour=$inth_rcd; // Non : Montant saisi pour le retour
						// Coût kilométrique
						if ($mt_kmill==0) // Pas illimité : on calcule (sinon on ne fait rien)
						{
							$diff_km=$inth_rkm-$mt_kmi;
							if ($diff_km>0)
								$cout_retour=$cout_retour+($mt_kms*$diff_km);
						}
					}
					$cout_retour=$cout_retour+$mt_coutc+$inth_rfrais; // Rajout des frais supplémentaires
					
					if ($mt_tpsdi==0) // Le temps de déplacement n'est pas inclus : on calcul (sinon on ne fait rien)
						$cout_retour=$cout_retour+round((($tecpr_couth/3600)*$tpsr)*100)/100;
				}
				$pr=$pr+$cout_site+$cout_aller+$cout_retour;
			}
		}
	}

	mysql_free_result($rs);
	if ($open==TRUE)
	{
		mysql_close($conn);
	}
	
	return $pr;
}

// Donne la chaîne des techniciens traitants sur une intervention
// Les clients ne voient pas le détail des agences
function str_tec_traitants_int($codeint,$open)
{
	global
		$_SESSION;
	$str="";
	if ($open==TRUE)
	{
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	
	$rech = "SELECT DISTINCT inth_codetec FROM `" .TBINTH. "` WHERE `inth_codeint`= '".$codeint."'";
	$rs = mysql_query($rech) or die(mysql_error());
	if (mysql_num_rows($rs) <> 0)
	{
		while ($row = mysql_fetch_assoc($rs)) 
		{
			$rech2 = "SELECT tec_nom, tec_prenom,tec_codeage FROM `" .TBTEC. "` WHERE `tec_code`= '".$row["inth_codetec"]."' ORDER BY tec_nom";
			$rs2 = mysql_query($rech2) or die(mysql_error());
			if (mysql_num_rows($rs2) <> 0)
			{
				if ($row2 = mysql_fetch_assoc($rs2))
					$str .= $row2["tec_nom"]." ".$row2["tec_prenom"];
				if ($_SESSION["niv_log"]<>1)
					$str.=" (".$row2["tec_codeage"].")";
				$str.=", ";
			}
			mysql_free_result($rs2);
		}
	}
	if ($str!="")
		$str = substr($str,0,strlen($str)-2).".";
	mysql_free_result($rs);
	if ($open==TRUE)
	{
		mysql_close($conn);
	}
	
	return $str;
}

/** Produits & Taxes dans interventions **/

// Vérification du nombre d'articles dans une fiche intervention
function nb_art_in_int($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rexist = "SELECT * FROM `" .TBPDTI. "` WHERE `pdti_codeint` = '$code'";
	$rs2 = mysql_query($rexist) or die(mysql_error());
	$nbexist = mysql_num_rows($rs2);
	mysql_free_result($rs2);
	mysql_close($conn2);

	return $nbexist;
}

// Vérification du nombre de taxes dans une fiche intervention
function nb_tpf_in_int($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rexist = "SELECT * FROM `" .TBTPFI. "` WHERE `tpfi_codeint` = '$code'";
	$rs2 = mysql_query($rexist) or die(mysql_error());
	$nbexist = mysql_num_rows($rs2);
	mysql_free_result($rs2);
	mysql_close($conn2);

	return $nbexist;
}

// Création du code Javascript pour affichage des articles de l'intervention
function cre_js_pdti($td,$code,$acpte,$from)
{
	global
		$lang,
		$txt_ent_lst_clic;
		
	echo "<script language=\"javascript\">\n";
	echo "function updatint() {\n";
	echo "var myid = ".$from."document.getElementById(\"detpdti\");\n";
	echo "myid.innerHTML = '';\n";

	if ((nb_art_in_int($code)>0) OR (nb_tpf_in_int($code)>0))
	{
		// Variables de calcul
		$totalintHT = 0; // Total HT de l'intervention
		$totalintTTC = 0; // Total TTC de l'intervention
		$totalTTCpdt= 0; // Total TTC des produits (sans les taxes) de l'intervention
		$totalgenHT = 0; // Total général (avec les taxes globales) HT de l'intervention
		$totalgenTTC = 0; // Total général (avec les taxes globales) TTC de l'intervention
		
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);

		// Type de facturation
		$factTTC=TRUE;
		
		$rech = "SELECT int_codecli FROM ".TBINT." WHERE int_code='".$code."'";
		$rs = mysql_query($rech) or die(mysql_error());
			
		if ($row = mysql_fetch_assoc($rs))
		{
			extract($row);
			$rech2 = "SELECT cli_modfact FROM ".TBCLI." WHERE cli_code='".$int_codecli."'";
			$rs2 = mysql_query($rech2) or die(mysql_error());
				
			if ($row2 = mysql_fetch_assoc($rs2))
			{
				extract($row2);
				if (($cli_modfact=="0") OR ($cli_modfact=="2"))
					$factTTC=FALSE;
			}
		}

		// *** Affichage de la table
		$str_html = "<table class=\"Ltable\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";     

		// Création entête
		$str_html.="<th>";
		$str_html.="Code";
		$str_html.="</th>";
		
		$str_html.="<th>";
		$str_html.="Désignation";
		$str_html.="</th>";

		$str_html.="<th>";
		if ($factTTC==TRUE)
			$txt= "PU TTC";
		else
			$txt= "PU HT";
		$str_html.=$txt;
		$str_html.="</th>";

		$str_html.="<th>";
		$str_html.="Qté";
		$str_html.="</th>";

		$str_html.="<th>";
		if ($factTTC==TRUE)
			$txt= "Total TTC";
		else
			$txt= "Total HT";
		$str_html.=$txt;
		$str_html.="</th>";

		$str_html.="<th>";
		$str_html.="TVA";
		$str_html.="</th>";

		if ($td=="edit")
		{
			$str_html.="<th>";
			$str_html.=$txt_ent_lst_clic;
			$str_html.="</th>";
		}

		// Lignes des articles
		$rech = "SELECT * FROM ".TBPDTI." WHERE pdti_codeint='".$code."' ORDER BY pdti_id";
		$rs = mysql_query($rech) or die(mysql_error());
			
		$i = 0;
		
		while ($row = mysql_fetch_assoc($rs))
		{
			extract($row);
			   
			// Couleurs alternées
			if($i%2 == 0)  
			   $str_html.="<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter1'\" class=\"TRalter1\">";
			else
			   $str_html.="<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter2'\" class=\"TRalter2\">";

			// Code produit
			$str_html.="<td class=\"tdlst\" valign=\"top\">";
			$str_html.=$pdti_codepdt;
			$str_html.="</td>";
	
			if ($pdti_frompdt<>"") // C'est une taxe rattachée à un produit
				$rech2 = "SELECT tpf_desc,tpf_typmt FROM ".TBTPF." WHERE tpf_code='".$pdti_codepdt."'";
			else // C'est un produit
				$rech2 = "SELECT pdt_des,pdt_codepdtu FROM ".TBPDT." WHERE pdt_code='".$pdti_codepdt."'";
			$rs2 = mysql_query($rech2) or die(mysql_error());
			if ($row2 = mysql_fetch_assoc($rs2)) 
				extract($row2);
			
			// Désignation
			if ($pdti_frompdt<>"")
				$txt=$tpf_desc;
			else
			{
				$txt=$pdt_des;
				$desart=$pdt_des;
			}
			$str_html.="<td class=\"tdlst\" valign=\"top\">";
			$str_html.=$txt;
			// Commentaire en cas de taxe parafiscale
			if ($pdti_frompdt<>"")
			{
				$str_html.="<div class=\"annot_moy_it\">";
				$txt=" Sur ".$desart;
				$str_html.=$txt;
				$str_html.="</div>";
			}

			// Affichage ligne(s) du numéro de série
			if (trim($pdti_ns) <> "")
			{
				$ligne_cesure = cesuretxt_tab($pdti_ns,100);
				foreach ($ligne_cesure as $index_ligne=>$ligne)
				{
					$ligne = str_replace('"','\"',$ligne);
					$str_html.="<div class=\"annot_moy_it\">";
					if ($index_ligne==0)
						$txt="N/S : ";
					else
						$txt="";
					$str_html.=$txt.$ligne;
					$str_html.="</div>";
				}
			}
			// Affichage ligne(s) du commentaire
			if (trim($pdti_texte) <> "")
			{
				$ligne_cesure = cesuretxt_tab($pdti_texte,100);
				foreach ($ligne_cesure as $index_ligne=>$ligne)
				{
					$ligne = str_replace('"','\"',$ligne);
					$str_html.="<div class=\"annot_moy_it\">";
					$str_html.=$ligne;
					$str_html.="</div>";
				}
			}
			$str_html.="</td>";
	
			// Prix
			// On récupère la TVA du produit
			$rech2 = "SELECT tva_tx FROM ".TBTVA." WHERE tva_code='".$pdti_codetva."'";
			$rs2 = mysql_query($rech2) or die(mysql_error());
			
			if ($row2 = mysql_fetch_assoc($rs2)) 
				extract($row2);
				
			$txtva=$tva_tx/100;
			$puht=round($pdti_puttc/(1+$txtva),2);

			if ($factTTC==TRUE)
				$txt= $pdti_puttc.$lang['symbole_monnaie_txt'];
			else
				$txt= format_num($puht,2).$lang['symbole_monnaie_txt'];

			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"right\">";
			$str_html.=$txt;
			$str_html.="</td>";
	
			// Quantité
			$rech2 = "SELECT pdtu_abr FROM ".TBPDTU." WHERE pdtu_code='".$pdt_codepdtu."'";
			$rs2 = mysql_query($rech2) or die(mysql_error());
			
			if ($row2 = mysql_fetch_assoc($rs2)) 
				extract($row2);

			$txt= $pdti_qte;
			if ($pdti_frompdt=="")
				$txt.= " ".$pdtu_abr;

			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"right\">";
			$str_html.=$txt;
			$str_html.="</td>";

			// Total ligne
			if ($factTTC==TRUE)
			{
				$totalligneTTC = $pdti_puttc*$pdti_qte;
				$totalligneHT = round($totalligneTTC/(1+$txtva),2);
				$txt=format_num($totalligneTTC,2).$lang['symbole_monnaie_txt'];
			}
			else
			{
				$totalligneHT = round($puht*$pdti_qte,2);
				$totalligneTTC = round($totalligneHT*(1+$txtva),2);
				$txt=format_num($totalligneHT,2).$lang['symbole_monnaie_txt'];
			}
			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"right\">";
			$str_html.=$txt;
			$str_html.="</td>";
	
			// Taux TVA
			$txt=format_num($tva_tx,2)."%";
			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"center\">";
			$str_html.=$txt;
			$str_html.="</td>";

			if ($td == "edit")
			{
				$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"center\">";
				if  ($pdti_frompdt=="")
				{
					$urleditart = "pdti_maj.php?td=edit&ci=".$pdti_codeint."&ca=".$pdti_codepdt;
					$str_html.="<a href=\"javascript:;\" onclick=\"fensaisie('".$urleditart."',700,500,'status=no,scrollbars=yes,menubar=no,statusbar=no,location=no,locationbar=no')\")>";
					$str_html.="<img src=\"../img/edit.png\" border=\"0\" align=\"absmiddle\" title=\"Modifier la ligne article\"></a>";
					$str_html.=" ";
					//echo "mycurrent_link.onclick = function() {fensaisie('".$urleditart."',700,500,'status=no,scrollbars=no,menubar=no,statusbar=no,location=no,locationbar=no');};\n";
					$urldelart = "pdti_maj.php?td=del&ci=".$pdti_codeint."&ca=".$pdti_codepdt;
					$str_html.="<a href=\"javascript:;\" onclick=\"fensaisie('".$urldelart."',700,500,'status=no,scrollbars=yes,menubar=no,statusbar=no,location=no,locationbar=no')\")>";
					$str_html.="<img src=\"../img/del.png\" border=\"0\" align=\"absmiddle\" title=\"Supprimer la ligne article\"></a>";
				}
				else
					$str_html.=" ";
				$str_html.="</td>";
			}

			$totalintHT = $totalintHT+$totalligneHT;
			$totalintTTC = $totalintTTC+$totalligneTTC;

			if ($pdti_frompdt=="")
				$totalTTCpdt = $totalTTCpdt+$totalligneTTC;

			$str_html.="</tr>";		
			$i++;
		}  

		$totalgenHT = $totalintHT;
		$totalgenTTC = $totalintTTC;

		// Lignes des taxes globales
		$rech = "SELECT * FROM ".TBTPFI." WHERE tpfi_codeint='".$code."' ORDER BY tpfi_id";
		$rs = mysql_query($rech) or die(mysql_error());
			
		while ($row = mysql_fetch_assoc($rs))
		{
			extract($row);
			   
			// Couleurs alternées
			if($i%2 == 0)  
			   $str_html.="<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter4'\" class=\"TRalter4\">";
			else
			   $str_html.="<tr onmouseover=\"this.className='TRsel'\" onmouseout=\"this.className='TRalter5'\" class=\"TRalter5\">";

			// Code taxe
			$str_html.="<td class=\"tdlst\" valign=\"top\">";
			$str_html.=$tpfi_codetpf;
			$str_html.="</td>";
	
			$rech2 = "SELECT tpf_desc,tpf_typmt,tpf_pour,tpf_basepour FROM ".TBTPF." WHERE tpf_code='".$tpfi_codetpf."'";
			$rs2 = mysql_query($rech2) or die(mysql_error());
			if ($row2 = mysql_fetch_assoc($rs2)) 
				extract($row2);
			
			// Désignation
			$str_html.="<td class=\"tdlst\" valign=\"top\">";
			$str_html.=$tpf_desc;

			// Commentaire en cas de taxe globale par pourcentage
			if ($tpf_pour==TRUE)
			{
				$str_html.="<div class=\"annot_moy_it\">";
				$txt=" Sur ".format_num($tpfi_valeur,2)."% du total des articles";
				if ($tpf_basepour==TRUE)
					 $txt.=" avec les taxes.";
				else
					 $txt.=" sans les taxes.";
				$str_html.=$txt;
				$str_html.="</div>";
			}

			// Affichage ligne(s) du commentaire
			if (trim($tpfi_texte) <> "")
			{
				$ligne_cesure = cesuretxt_tab($tpfi_texte,100);
				foreach ($ligne_cesure as $index_ligne=>$ligne)
				{
					$ligne = str_replace('"','\"',$ligne);
					$str_html.="<div class=\"annot_moy_it\">";
					$str_html.=$ligne;
					$str_html.="</div>";
				}
			}
			$str_html.="</td>";
	
			// Prix
			// On récupère la TVA de la taxe
			$rech2 = "SELECT tva_tx FROM ".TBTVA." WHERE tva_code='".$tpfi_codetva."'";
			$rs2 = mysql_query($rech2) or die(mysql_error());
			
			if ($row2 = mysql_fetch_assoc($rs2)) 
				extract($row2);
				
			$txtva=$tva_tx/100;
			$puttc=0;
			switch ($tpf_pour)
			{
				// Calcul normal
				case "0" :
					$puttc=$tpfi_valeur;
					break;
				// Pourcentage du total articles
				case "1" :
					if ($tpf_basepour==TRUE)
						$puttc=round($totalintTTC*($tpfi_valeur/100),2);
					else
						$puttc=round($totalTTCpdt*($tpfi_valeur/100),2);
					break;
			}
			$puht=round($puttc/(1+$txtva),2);

			if ($factTTC==TRUE)
				$txt= $puttc.$lang['symbole_monnaie_txt'];
			else
				$txt= format_num($puht,2).$lang['symbole_monnaie_txt'];
			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"right\">";
			$str_html.=$txt;
			$str_html.="</td>";
	
			// Quantité
			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"right\">";
			$str_html.=$tpfi_qte;
			$str_html.="</td>";

	
			// Total ligne
			if ($factTTC==TRUE)
			{
				$totalligneTTC = round($puttc*$tpfi_qte,2);
				$totalligneHT = round($totalligneTTC/(1+$txtva),2);
				$txt=format_num($totalligneTTC,2).$lang['symbole_monnaie_txt'];
			}
			else
			{
				$totalligneHT = round($puht*$tpfi_qte,2);
				$totalligneTTC = round($totalligneHT*(1+$txtva),2);
				$txt=format_num($totalligneHT,2).$lang['symbole_monnaie_txt'];
			}
			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"right\">";
			$str_html.=$txt;
			$str_html.="</td>";
	
			// Taux TVA
			$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"center\">";
			$str_html.=format_num($tva_tx,2)."%";
			$str_html.="</td>";

			if ($td == "edit")
			{
				$str_html.="<td class=\"tdlst\" valign=\"top\" align=\"center\">";
				$urledittpf = "tpfi_maj.php?td=edit&ci=".$tpfi_codeint."&tpf=".$tpfi_codetpf;
				$str_html.="<a href=\"javascript:;\" onclick=\"fensaisie('".$urledittpf."',700,500,'status=no,scrollbars=yes,menubar=no,statusbar=no,location=no,locationbar=no')\")>";
				$str_html.="<img src=\"../img/edit.png\" border=\"0\" align=\"absmiddle\" title=\"Modifier la ligne taxe\"></a>";
				$str_html.=" ";
				$urldeltpf = "tpfi_maj.php?td=del&ci=".$tpfi_codeint."&tpf=".$tpfi_codetpf;
				$str_html.="<a href=\"javascript:;\" onclick=\"fensaisie('".$urldeltpf."',700,500,'status=no,scrollbars=yes,menubar=no,statusbar=no,location=no,locationbar=no')\")>";
				$str_html.="<img src=\"../img/del.png\" border=\"0\" align=\"absmiddle\" title=\"Supprimer la ligne taxe\"></a>";
				$str_html.="</td>";
			}
	
			$totalgenHT = $totalgenHT+$totalligneHT;
			$totalgenTTC = $totalgenTTC+$totalligneTTC;
			
			$str_html.="</tr>";
			
			$i++;
		}  
	
		mysql_close($conn);

		// Pied de liste

		// Total HT
		// Couleurs alternées
	   $str_html.="<tr class=\"TRalter3\">";

		for ($j=0;$j<3;$j++)
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}

		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.="Total HT :";
		$str_html.="</td>";

		$txt = format_num($totalgenHT,2,'.','').$lang['symbole_monnaie_txt'];
		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.=$txt;
		$str_html.="</td>";

		$str_html.="<td class=\"tdlst\">";
		$str_html.="&nbsp;";
		$str_html.="</td>";

		if ($td == "edit")
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}	
	
		$str_html.="</tr>";
		$i++;
			
		// Total TVA
		$str_html.="<tr class=\"TRalter3\">";

		for ($j=0;$j<3;$j++)
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}

		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.="TVA :";
		$str_html.="</td>";

		$totalTVA=$totalgenTTC-$totalgenHT;
		$txt = format_num($totalTVA,2,'.','').$lang['symbole_monnaie_txt'];
		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.=$txt;
		$str_html.="</td>";

		$str_html.="<td class=\"tdlst\">";
		$str_html.="&nbsp;";
		$str_html.="</td>";

		if ($td == "edit")
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}	
		
		$str_html.="</tr>";
		$i++;
			
		// Total TTC
	   $str_html.="<tr class=\"TRalter3\">";

		for ($j=0;$j<3;$j++)
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}

		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.="Total TTC :";
		$str_html.="</td>";

		$txt = format_num($totalgenTTC,2,'.','').$lang['symbole_monnaie_txt'];
		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.=$txt;
		$str_html.="</td>";

		$str_html.="<td class=\"tdlst\">";
		$str_html.="&nbsp;";
		$str_html.="</td>";

		if ($td == "edit")
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}	

		$str_html.="</tr>";
		$i++;
			
		// Acompte
	   $str_html.="<tr class=\"TRalter3\">";

		for ($j=0;$j<3;$j++)
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}

		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.="Acompte :";
		$str_html.="</td>";

		if ($acpte<>0)
			$txt = "-".format_num($acpte,2,'.','').$lang['symbole_monnaie_txt'];
		else
			$txt = "&nbsp;";
		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.=$txt;
		$str_html.="</td>";

		if ($acpte<>0)
			$txt = "TTC";
		else
			$txt = "&nbsp;";
		$str_html.="<td class=\"tdlst\">";
		$str_html.=$txt;
		$str_html.="</td>";

		if ($td == "edit")
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}	

		$str_html.="</tr>";
		$i++;
			
		// Net à payer
		$str_html.="<tr class=\"TRalter3\">";
		for ($j=0;$j<3;$j++)
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}

		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.="Net à payer :";
		$str_html.="</td>";

		$txt = format_num(($totalgenTTC-$acpte),2,'.','').$lang['symbole_monnaie_txt'];
		$str_html.="<td class=\"tdlst\" align=\"right\">";
		$str_html.=$txt;
		$str_html.="</td>";

		$str_html.="<td class=\"tdlst\">";
		$str_html.="TTC";
		$str_html.="</td>";

		if ($td == "edit")
		{
			$str_html.="<td class=\"tdlst\">";
			$str_html.="&nbsp;";
			$str_html.="</td>";
		}	

		$str_html.="</tr>";
		$i++;
			
		// Fermeture de la table
		$str_html.="</table>";

		// MAJ de l'id
		echo "var str_html = '".addslashes($str_html)."';\n";
		echo "myid.innerHTML=str_html;\n";

		// MAJ champ du total intervention
		$totalgen=$totalintTTC-$acpte;
		echo $from."document.int_maj.totalint.value=\"".$totalgen."\";\n";
	}
	else
	{
		// MAJ champ du total intervention (0)
		echo $from."document.int_maj.totalint.value=\"0\";\n";
	}
	echo "}\n";
	
	echo "</script>\n";
}

// Création du code Javascript pour affichage des reports contrats
function cre_js_coded($td,$ncli,$nco,$duree,$dureeoff,$from)
{
	echo "<script language=\"javascript\">\n";
	
	echo "function updatcoded() {\n";
	echo "var myid = ".$from."document.getElementById(\"lsttded\");\n";
	echo 'if (myid) {';
		echo "myid.innerHTML = '';\n";
	
		if (trim($nco)<>"")
		{
			// On se connecte a la base
			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			// On recupere les infos sur le contrat en cours
			$rech = "SELECT * FROM ".TBCOCL." WHERE cocl_code='".$nco."'";
			$rs = mysql_query($rech) or die(mysql_error());
			if ($row = mysql_fetch_array($rs))
			{
				extract($row);
			}
			$soldemini=soldes_reel_contrat($nco,FALSE);
			if ($soldemini<0)
			{
				echo 'option = '.$from.'document.createElement("option");';
				echo 'option.setAttribute("value","");';
				echo 'option.innerHTML ="-- Faites votre choix --";';
				echo 'myid.appendChild(option);';
		
				echo 'option = '.$from.'document.createElement("option");';
				echo 'option.setAttribute("value","-2");';
				echo 'option.innerHTML ="Pas de déduction";';
				echo 'myid.appendChild(option);';
			
				// On recupere les infos sur le contrat en cours
				$rnum="";
				$tab = array();
				if (trim($cocl_rnum)=="")
				{
					if ($cocl_renauto==TRUE)
					{
						echo 'option = '.$from.'document.createElement("option");';
						echo 'option.setAttribute("value","-1");';
						echo 'option.innerHTML ="Déduction sur renouvellement (automatique)";';
						echo 'myid.appendChild(option);';
					}
				}
				else
				{
					echo 'option = '.$from.'document.createElement("option");';
					echo 'option.setAttribute("value","-1");';
					echo 'option.innerHTML ="Déduction sur renouvellement ('.$cocl_rnum.')";';
					echo 'myid.appendChild(option);';
					$rnum=$cocl_rnum;
				}
					
				// On récupère les enregistrements
				$rech = "SELECT * FROM ".TBCOCL." WHERE cocl_code<>'".$nco."' AND cocl_codecli='".$ncli."'";
				$rech.= " AND cocl_typh=1 AND (cocl_datef>=".date("Y-m-d")." OR cocl_datef='0000-00-00')";
				$rech.= " AND cocl_datefin='0000-00-00'";
				$rech.= " ORDER BY cocl_code";
				$rs = mysql_query($rech) or die(mysql_error());
				// On cree le resultat
				while($row = mysql_fetch_array($rs))
				{
					extract($row);
					if ($rnum<>$cocl_code)
					{
						// On ne prend que les contrats ayant plus de temps dispo que le temps minimum nécessaire
						// pour le contrat choisi
						$solde_reel=soldes_reel_contrat($cocl_code,FALSE);
						if ($solde_reel>=$soldemini)
						{
							$rech2 = "SELECT * FROM " .TBCO. " WHERE co_code = '".$cocl_codeco."'";
							$rs2 = mysql_query($rech2) or die(mysql_error());
							if ($row2 = mysql_fetch_array($rs2))
							{
								extract($row2);
								if ($cocl_delai <> 0)
									$txt_cocl = $cocl_code." - ".$co_nom." (".$cocl_delai."h";
								else
									$txt_cocl = $cocl_code." - ".$co_nom." (Pas de délai";
								if ($cocl_datef<>"0000-00-00")
								{
									$split = split("-",$cocl_datef);
									$annee = $split[0];
									$mois = $split[1];
									$jour = $split[2];
									$txt_cocl.=", ".$txt_div_ech." "."$jour"."/"."$mois"."/"."$annee";
								}
								else
									$txt_cocl.=", ".$txt_div_ssech." ";
								$txt_cocl.=", solde réel ".heure_to_hhmm(sec_heure($solde_reel,3,TRUE));
								if ($cocl_datesig<>"0000-00-00")
									$txt_cocl.=", Signé";
								else
									$txt_cocl.=", Non signé";
								$txt_cocl.=")";
							}
							$result[] = $cocl_code."=".$txt_cocl;
							echo 'option = '.$from.'document.createElement("option");';
							echo 'option.setAttribute("value","'.$cocl_code.'");';
							echo 'option.innerHTML ="'.$txt_cocl.'";';
							echo 'myid.appendChild(option);';
						}
					}
				}
			}
			else
			{
				echo 'option = '.$from.'document.createElement("option");';
				echo 'option.setAttribute("value","0");';
				echo 'option.innerHTML ="Solde '.$nco.' suffisant";';
				echo 'myid.appendChild(option);';
			}		
			mysql_close();
		}
	echo "}\n";
	echo "}\n";
	
	echo "</script>\n";
}

// Création du code Javascript pour affichage des contacts clients
function cre_js_ddeurs($ncli,$idsite,$from)
{
	echo "<script language=\"javascript\">\n";
	
	echo "function updatddeurs() {\n";
	echo "var myid = ".$from."document.getElementById(\"ddeur\");\n";
	echo 'if (myid) {';
		echo "myid.innerHTML = '';\n";
	
		if (trim($ncli)<>"")
		{
			echo 'option = '.$from.'document.createElement("option");';
			echo 'option.setAttribute("value","");';
			echo 'option.innerHTML ="-- Choisissez un  contact --";';
			echo 'myid.appendChild(option);';

			// On se connecte a la base
			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);

			// Données client
			$rech = "SELECT * FROM ".TBCLI." WHERE `cli_code` = '".$ncli."'";
			$rs = mysql_query($rech) or die(mysql_error());
			if (mysql_num_rows($rs) <> 0)
			{
				if ($resultat = mysql_fetch_array($rs)) 
				{
					extract($resultat);
					$txt_ccli = $cli_nom." ".$cli_prenom." (Contact principal";
					$txt_ccli.= " - ".$cli_telf.")";
					echo 'option = '.$from.'document.createElement("option");';
					echo 'option.setAttribute("value","-1");';
					echo 'option.innerHTML ="'.$txt_ccli.'";';
					echo 'myid.appendChild(option);';
				}
			}

			// Données site client
			if (trim($idsite)<>"")
			{
				if (intval($idsite)>0)
				{
					$rech = "SELECT * FROM `" .TBSCLI. "` WHERE `scli_id` = '$idsite'";
					$rs = mysql_query($rech)or die(mysql_error());
					if ($resultat = mysql_fetch_array($rs)) 
					{
						extract($resultat);
						$txt_ccli = $scli_rnom." ".$scli_rprenom." (Contact site";
						$txt_ccli.= " - ".$scli_telf.")";
						echo 'option = '.$from.'document.createElement("option");';
						echo 'option.setAttribute("value","0");';
						echo 'option.innerHTML ="'.$txt_ccli.'";';
						echo 'myid.appendChild(option);';
					}
					mysql_free_result($rs);
				}
			}
			// Filtre sur client
			$rech = "SELECT * FROM ".TBCCLI." WHERE `ccli_codecli` = '".$ncli."' ORDER BY ccli_nom";
			$rs = mysql_query($rech) or die(mysql_error());
			if (mysql_num_rows($rs) <> 0)
			{
				while ($resultat = mysql_fetch_array($rs)) 
				{
					extract($resultat);
	
					$txt_ccli = $ccli_nom." ".$ccli_prenom;
					$row2=lit_enr_fonc($ccli_codefonc,FALSE);
					if (is_array($row2))
					{
						extract($row2);
						$txt_fonc=$fonc_desc;
					}
					else
						$txt_fonc=$ccli_codefonc;
					$txt_ccli.=" (".$txt_fonc;
					$txt_ccli.= " - ".$ccli_telf.")";
					echo 'option = '.$from.'document.createElement("option");';
					echo 'option.setAttribute("value","0");';
					echo 'option.innerHTML ="'.$txt_ccli.'";';
					echo 'myid.appendChild(option);';
				}
			}		
			mysql_close();
		}
	echo "}\n";
	echo "}\n";
	
	echo "</script>\n";
}


/** Suivi de facturation **/

// Lecture d'un enregistrement suivi de facturation intervention
function lit_enr_intf($code,$open)
{
	if ($open==TRUE)
	{
		$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	$rech2 = "SELECT * FROM `" .TBINTF. "` WHERE `intf_codeint` = '$code'";
	$rs2 = mysql_query($rech2)or die(mysql_error());
	if ($row2 = mysql_fetch_array($rs2))
	{
	}
	mysql_free_result($rs2);
	if ($open==TRUE)
		mysql_close($conn2);
	
	return $row2;
}

// Vérification de la présence d'un suivi facturation pour une intervention
function exist_intf_int($code)
{
	$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
	mysql_select_db(DBNAME);
	$rexist = "SELECT * FROM `" .TBINTF. "` WHERE `intf_codeint` = '$code'";
	$rs2 = mysql_query($rexist) or die(mysql_error());
	if (mysql_num_rows($rs2) <> 0)
		$exist = TRUE;
	else
		$exist = FALSE;
	mysql_free_result($rs2);
	mysql_close($conn2);
	
	return $exist;
}

// Nombre de facturates pour une intervention
function nb_intf_int($code,$open)
{
	$n=0;
	if ($open==TRUE)
	{
		$conn2 = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
	}
	$rexist = "SELECT * FROM `" .TBINTF. "` WHERE `intf_codeint` = '$code'";
	$rs2 = mysql_query($rexist) or die(mysql_error());
	$nb=mysql_num_rows($rs2);
	mysql_free_result($rs2);
	if ($open==TRUE)
		mysql_close($conn2);
	
	return $nb;
}


?>