<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.0
 *
 * Copyright (C) 2006-2014  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://smi.no-ip.org
 ****************************************************************************************/


// 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 fichiers Location */
/**************************************************/

// Contrats de location

/**
 * Lecture d'un enregistrement contrat
 *
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_coloc($code, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBCOLOC . "` WHERE `coloc_code` = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification du nombre de contrats de location
 *
 * @param bool $open
 * @return null
 */
function nb_coloc($open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBCOLOC . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Vérification du nombre de contrats de location sur un client
 * Filtre sur niveau et sur code agence/donneur d'ordre
 *
 * @param $client
 * @param $level
 * @param $codead
 * @param bool $open
 * @return null
 */
function nb_coloc_cli($client, $level, $codead, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBCOLOC . "` WHERE `coloc_codecli` = '" . $db->escape($client) . "'";
    if (trim($codead) <> "") {
        if (($level == 3) OR ($level == 4))
            $rexist .= " AND `coloc_codeage` = '" . $db->escape($codead) . "'";
    }
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Vérification du nombre de contrats de location sur un technicien
 * Filtre sur type client
 *
 * @param $client
 * @param $typcli
 * @param bool $open
 * @return null
 */
function nb_coloc_tec($client, $typcli, $open = TRUE)
{
    global
    $db;


    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBCOLOC . "` WHERE `coloc_codecli` = '" . $db->escape($client) . "'";
    $rexist .= " AND `coloc_typcli` = '" . $db->escape($typcli) . "'";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

// Produits à louer

/**
 * Nombre d'articles
 *
 * @param bool $open
 * @return null
 */
function nb_pdtloc($open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTLOC . "`";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Nombre d'articles dans un contrat de location
 *
 * @param $coloc
 * @param bool $open
 * @return null
 */
function nb_pdtloc_in_coloc($coloc, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTL . "` WHERE `pdtl_codecoloc` = '" . $db->escape($coloc) . "'";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Vérifie si tous les produits d'un contrat sont revenus
 *
 * @param $coloc
 * @param bool $open
 * @return bool
 */
function all_pdtloc_ret_in_coloc($coloc, $open = TRUE)
{
    global
    $db;
    $all = TRUE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTL . "` WHERE `pdtl_codecoloc` = '" . $db->escape($coloc) . "' AND `pdtl_dateret` = '0000-00-00'";
    $nbexist = $db->get_var($rexist);
    if ($nbexist > 0)
        $all = FALSE;
    if ($open == TRUE)
        $db->disconnect();

    return $all;
}

/**
 * Retourne la dernière date de retour pour les produits d'un contrat donné
 *
 * @param $coloc
 * @param bool $open
 * @return string
 */
function lastdate_ret_in_coloc($coloc, $open = TRUE)
{
    global
    $db;
    $lastdate = "";
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT MAX(pdtl_dateret) AS lastdate FROM `" . TBPDTL . "` WHERE `pdtl_codecoloc` = '" . $db->escape($coloc) . "'";
    $row = $db->get_row($rexist, ARRAY_A);
    if ($row)
        extract($row);
    if ($open == TRUE)
        $db->disconnect();
    return $lastdate;
}

/**
 * Clôt un contrat de location à une date donnée
 *
 * @param $coloc
 * @param $dateclos
 * @param bool $open
 */
function clot_coloc($coloc, $dateclos, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech = "UPDATE `" . TBCOLOC;
    $rech .= "` SET `coloc_dateclos`='" . $dateclos . "'";
    $rech .= " WHERE `coloc_code` = '" . $db->escape($coloc) . "'";
    $db->query($rech);
    if ($open == TRUE)
        $db->disconnect();
}

/**
 * Lecture d'un enregistrement produit
 *
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_pdtloc($code, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDTLOC . "` WHERE `pdtloc_code` = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification de la présence d'un article dans une fiche location
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_pdt_in_coloc($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTL . "` WHERE `pdtl_codecoloc` = '" . $db->escape($code) . "'";
    $nbexist = $db->get_var($rexist);
    if ($nbexist <> 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Lit un article dans une fiche location
 *
 * @param $codep
 * @param $codel
 * @param bool $open
 * @return array|null
 */
function lit_enr_pdt_in_coloc($codep, $codel, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDTL . "` WHERE `pdtl_codepdtloc` = '" . $db->escape($codep) . "' AND `pdtl_codecoloc` = '" . $db->escape($codel) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification de la présence d'un produit dans une fiche location non close
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_pdt_in_coloc_ouv($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*)FROM `" . TBPDTL . "`, `" . TBCOLOC . "`";
    $rech2 .= " WHERE (" . TBPDTL . ".pdtl_codepdtloc = '" . $db->escape($code) . "' AND " . TBPDTL . ".pdtl_codecoloc = " . TBCOLOC . ".coloc_code AND " . TBCOLOC . ".coloc_datefin = '0000-00-00')";
    $nbexist = $db->get_var($rech2);
    if ($nbexist <> 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Vérification si un produit est à remettre dans une fiche location non close
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_adep_in_coloc_ouv($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*)FROM `" . TBPDTL . "`, `" . TBCOLOC . "`";
    $rech2 .= " WHERE (" . TBPDTL . ".pdtl_codepdtloc = '" . $db->escape($code) . "'";
    $rech2 .= " AND " . TBPDTL . ".pdtl_datedep = '0000-00-00' AND " . TBPDTL . ".pdtl_codecoloc = " . TBCOLOC . ".coloc_code AND " . TBCOLOC . ".coloc_datefin = '0000-00-00')";
    $nbexist = $db->get_var($rech2);
    if ($nbexist <> 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Vérification si un produit est à retourner dans une fiche location non close
 *
 * @param $code
 * @param bool $open
 * @return bool
 */
function exist_aret_in_coloc_ouv($code, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*)FROM `" . TBPDTL . "`, `" . TBCOLOC . "`";
    $rech2 .= " WHERE (" . TBPDTL . ".pdtl_codepdtloc = '" . $db->escape($code) . "'";
    $rech2 .= " AND " . TBPDTL . ".pdtl_dateret = '0000-00-00' AND " . TBPDTL . ".pdtl_codecoloc = " . TBCOLOC . ".coloc_code AND " . TBCOLOC . ".coloc_datefin = '0000-00-00')";
    $nbexist = $db->get_var($rech2);
    if ($nbexist <> 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}


/**
 * Création du code Javascript pour affichage des barèmes dans une fiche article à louer
 *
 * @param $id_html
 * @param $td
 * @param $code
 * @param string $from
 * @param bool $open
 */
function cre_html_barloc($id_html, $td, $code, $from = '', $open = TRUE)
{
    global
    $db,
    $lng_tjouri_abr,
    $lng_tduree,
    $non_oui,
    $_SESSION;

    // Création de la chaine HTML
    $str_html = '';

    if (nb_barloc_in_pdtloc($code) > 0) {
        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        // *** 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 .= _("Désignation");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Période");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Validité");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Pu HT");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("TVA");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Pu TTC");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Actif");
        $str_html .= "</th>";

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

        // Lignes du tableau
        $rech = "SELECT * FROM `" . TBBARLOC . "` WHERE barloc_codepdtloc='" . $db->escape($code) . "' ORDER BY `barloc_des`";
        $rows = $db->get_results($rech, ARRAY_A);

        $i = 0;

        if ($rows) {
            foreach ($rows as $row) {
                $row = encode_str($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\">";

                // Désignation
                $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                $str_html .= $row["barloc_des"];

                // Assurance (texte)
                if ($row["barloc_mtass"] <> 0) {
                    $txt = _("Assurance");
                    if ($row["barloc_assobl"] == 1)
                        $txt .= ' '._("obligatoire");
                    else
                        $txt .= ' ' . _("facultative");
                    $str_html .= "<div class=\"annot_moy_it\" align=\"right\">";
                    $str_html .= $txt;
                    $str_html .= "</div>";
                }

                $str_html .= "</td>";

                // période
                $rech2 = "SELECT * FROM `" . TBPERLOC . "` WHERE perloc_code='" . $row["barloc_codeperloc"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);

                // Affichage détail de la période
                //...Plage de démarrage de la location
                $txt = _("Plage début") . " :";
                if ($perloc_jourd1 <> -1)
                    $txt .= " " . $lng_tjouri_abr[$perloc_jourd1] . " - " . $lng_tjouri_abr[$perloc_jourd2];
                else
                    $txt .= " " . _("Indifférent");
                $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                $str_html .= $txt;

                //...Durée
                $txt = " (" . _("sur une durée de") . " " . $perloc_nduree . " " . $lng_tduree[$perloc_tduree] . ")";
                $str_html .= "<span class=\"annot_moy_it\">";
                $str_html .= $txt;
                $str_html .= "</span>";

                $str_html .= "</td>";

                // Validité
                if (datetolocal($row["barloc_dateval2"]) == "")
                    $txt = _("Depuis le") . " " . datetolocal($row["barloc_dateval1"]);
                else
                    $txt = _("Du") . " " . $row["barloc_dateval1"] . " " . _("au") . " " . $row["barloc_dateval2"];
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                $str_html .= $txt;
                $str_html .= "</td>";

                // PU HT
                $txt = full_num_format($row["barloc_pvht"], '', '', TRUE,'',FALSE);
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
                $str_html .= $txt;

                // Assurance (HT)
                if ($row["barloc_mtass"] <> 0) {
                    //... Montant
                    $txt = full_num_format($row["barloc_mtass"], '', '', TRUE,'',FALSE);
                    $str_html .= "<div class=\"annot_moy_it\">";
                    $str_html .= $txt;
                    $str_html .= "</div>";
                }
                $str_html .= "</td>";

                // TVA
                $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $row["barloc_codetva"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txtva = $tva_tx / 100;
                $puttc = round(($row["barloc_pvht"] * (1 + $txtva)) * 100) / 100;
                $txt = full_num_format($tva_tx) . "%";

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

                // Assurance (TVA)
                if ($row["barloc_mtass"] <> 0) {
                    //... Taux
                    $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $row["barloc_codetvaass"] . "'";
                    $row2 = $db->get_row($rech2, ARRAY_A);
                    if ($row2)
                        extract($row2);
                    $txt = full_num_format($tva_tx) . "%";
                    $txtvaass = $tva_tx / 100;
                    $mtassttc = round(($row["barloc_mtass"] * (1 + $txtvaass)) * 100) / 100;
                    $str_html .= "<div class=\"annot_moy_it\">";
                    $str_html .= $txt;
                    $str_html .= "</div>";
                }
                $str_html .= "</td>";

                // PU TTC
                $txt = full_num_format($puttc, '', '', TRUE,'',FALSE);
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"right\">";
                $str_html .= $txt;


                // Assurance (TTC)
                if ($row["barloc_mtass"] <> 0) {
                    //... Montant
                    $txt = full_num_format($mtassttc, '', '', TRUE,'',FALSE);
                    $str_html .= "<div class=\"annot_moy_it\">";
                    $str_html .= $txt;
                    $str_html .= "</div>";
                }
                $str_html .= "</td>";

                // Actif
                $txt = $non_oui[$row["barloc_actif"]];
                $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\">";
                    $urleditbarloc = "barloc_maj.php?td=edit&cp=" . $row["barloc_codepdtloc"] . "&pl=" . $row["barloc_codeperloc"];
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urleditbarloc."','barloc_edit_".$row["barloc_id"]."',900,550,'yes')\")>";
                    $str_html .= "<img src=\"../img/edit.png\" border=\"0\" align=\"absmiddle\" title=\"" . _("Edition") . "\"></a>";
                    $str_html .= " ";

                    $urldelbarloc = "barloc_maj.php?td=del&cp=" . $row["barloc_codepdtloc"] . "&pl=" . $row["barloc_codeperloc"];
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldelbarloc."','barloc_del_".$row["barloc_id"]."',900,550,'yes')\")>";
                    $str_html .= "<img src=\"../img/del.png\" border=\"0\" align=\"absmiddle\" title=\"" . _("Supprimer le barème") . "\"></a>";
                    $str_html .= " ";
                    $str_html .= "</td>";
                }
                $str_html .= "</tr>";
                $i++;

            }
        }

        if ($open == TRUE)
            $db->disconnect();

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

    }

    echo 'function tbbarloc() {';
    echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
    echo $from . "$('#".$id_html."').html('" . str_replace("'", "\'", $str_html) . "');";
    echo '}';
    echo '}';
}

/**
 * Création du code Javascript pour affichage des tarifs consommables dans une fiche article à louer
 *
 * @param $ntcons
 * @param $id_html
 * @param $td
 * @param $ibl
 * @param string $from
 * @param bool $open
 */
function cre_html_tarcons($ntcons, $id_html, $td, $ibl, $from = '', $open = TRUE)
{
    global
    $db,
    $_SESSION;

    // Création de la chaine HTML
    $str_html = '';

    $nb_tarcons = nb_tarcons_in_barloc($ibl, intval($ntcons));
    $infini = exist_infini_tcons_id($ibl, intval($ntcons), TRUE);

    if ($nb_tarcons > 0) {
        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        // *** 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 .= _("Depuis (qté)");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Jusqu'à (qté)");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("PU HT");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("TVA");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("PU TTC");
        $str_html .= "</th>";

        $str_html .= "<th>";
        if ($td == "edit")
            $str_html .= _("Cliquer");
        else
            $str_html .= " ";
        $str_html .= "</th>";

        // Récupération données du barème
        $rech2 = "SELECT * FROM `" . TBBARLOC . "` WHERE barloc_id='" . $ibl . "'";
        $row2 = $db->get_row($rech2, ARRAY_A);
        if ($row2)
            extract($row2);

        // Lignes du tableau
        $rech = "SELECT * FROM `" . TBBARLOCTC . "` WHERE barloctc_idbarloc='" . $ibl . "' AND barloctc_ncons='1' ORDER BY `barloctc_min`";
        $rows = $db->get_results($rech, ARRAY_A);

        $i = 0;

        if ($rows) {
            foreach ($rows as $row) {
                $row = encode_str($row);
                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\">";

                // Depuis
                $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                $str_html .= $barloctc_min;
                $str_html .= "</td>";

                // Jusqu'à
                $txt = $barloctc_max;
                if (intval($barloctc_max) == 0)
                    $txt = _("infini");
                $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                $str_html .= $txt;
                $str_html .= "</td>";

                // PU HT
                $txt = full_num_format($barloctc_pvht, '', '', TRUE,'',FALSE);
                $str_html .= "<td class=\"TDnumberD\" valign=\"top\">";
                $str_html .= $txt;
                $str_html .= "</td>";

                // TVA
                $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $barloc_tvacons.intval($ntcons) . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txtva = $tva_tx / 100;
                $puttc = round(($barloctc_pvht * (1 + $txtva)) * 100) / 100;
                $txt = full_num_format($tva_tx) . "%";
                $str_html .= "<td class=\"TDnumberD\" valign=\"top\">";
                $str_html .= $txt;
                $str_html .= "</td>";

                // PU TTC
                $txt = full_num_format($puttc, '', '', TRUE,'',FALSE);
                $str_html .= "<td class=\"TDnumberD\" valign=\"top\">";
                $str_html .= $txt;
                $str_html .= "</td>";

                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                if (($td == "edit") AND ($nb_tarcons == ($i + 1))) {
                    $str_html .= "<a href=\"javascript:;\" onclick=\"fen_barloc('edit','" . $ibl . "','" . $barloctc_id . "','".intval($ntcons)."');\")>";
                    $str_html .= "<img src=\"../img/edit.png\" border=\"0\" align=\"absmiddle\" title=\""._("Modifier")."\"></a>";
                    $str_html .= " ";

                    $str_html .= "<a href=\"javascript:;\" onclick=\"fen_barloc('del','" . $ibl . "','" . $barloctc_id . "','".intval($ntcons)."');\")>";
                    $str_html .= "<img src=\"../img/del.png\" border=\"0\" align=\"absmiddle\" title=\""._("Supprimer")."\"></a>";
                    $str_html .= " ";
                } else
                    $str_html .= " ";
                $str_html .= "</td>";

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

            $db->disconnect();

            // Fermeture de la table
            $str_html .= "</table>";
        }
        if ($open == TRUE)
            $db->disconnect();
    }

    echo 'function tbtarcons'.intval($ntcons).'() {';
    echo 'if ((' . $from . '$("#' . $id_html.intval($ntcons). '").length) > 0) {';
    echo $from . "$('#" . $id_html.intval($ntcons). "').html('" . str_replace("'", "\'", $str_html) . "');";
    echo '}';
    // MAJ de nextmin et de addtc
    switch (intval($ntcons))
    {
        case 1 :
            $qconsi = $barloc_qconsi1;
            break;
        case 2 :
            $qconsi = $barloc_qconsi2;
            break;

    }

    echo $from.'$("#nextmin'.intval($ntcons).'").val("'.next_min_tcons($ibl, $qconsi, intval($ntcons), TRUE).'");';
    if ($infini == TRUE)
        echo $from.'$("#addtc'.intval($ntcons).'").hide();';
    else
        echo $from.'$("#addtc'.intval($ntcons).'").show();';

    echo '}';
}

/**
 * Vérification de la disponibilité d'un produit sur une période donnée
 *
 * @param $code
 * @param $dated
 * @param $heured
 * @param $datef
 * @param $heuref
 * @param bool $open
 * @return bool
 */
function pdtloc_dispo($code, $dated, $heured, $datef, $heuref, $open = TRUE)
{
    global
    $db;
    $dispo = TRUE;
    $ts1 = getTimeStamp($dated . ' ' . $heured);
    $ts2 = getTimeStamp($datef . ' ' . $heuref);
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDTL . "` WHERE `pdtl_codepdtloc` = '" . $db->escape($code) . "'";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if ($rows2) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $tspdtldeb = getTimeStamp(datetolocal($pdtl_datedeb) . ' ' . $pdtl_heuredeb);
            $tspdtlfin = getTimeStamp(datetolocal($pdtl_datefin) . ' ' . $pdtl_heurefin);
            // Date de début entre une date de début de location et une date de fin de location
            if (($tspdtldeb <= $ts1) AND ($ts1 <= $tspdtlfin)) {
                $dispo = FALSE;
                break;
            }
            // Date de fin entre une date de début de location et une date de fin de location
            if (($tspdtldeb <= $ts2) AND ($ts2 <= $tspdtlfin)) {
                $dispo = FALSE;
                break;
            }
            // Plage de date de location entre la date de début et la date de fin
            if (($ts1 <= $tspdtldeb) AND ($tspdtlfin <= $ts2))
                if ((comp_date(datetomysql($dated), $pdtl_datedeb) == TRUE) AND (comp_date($pdtl_datefin, datetomysql($datef)) == TRUE)) {
                    $dispo = FALSE;
                    break;
                }
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $dispo;
}

/**
 * Calcule le montant des consos HT sur un retour de location, à partir de l'id du barème utilisé et les 2 indexes
 *
 * @param $idbarloc
 * @param $diffidx1
 * @param $diffidx2
 * @param bool $open
 * @return int
 */
function calcul_consloc($idbarloc, $diffidx1, $diffidx2, $open = TRUE)
{
    global
    $db;
    $totconso1 = 0;
    $totconso2 = 0;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

    // Calcul pour le premier consommable
    if (intval($diffidx1) > 0) {
        // On recherche dans le barème des consommables
        // ... Il y a une fourchette de valeurs ?
        $rech2 = "SELECT * FROM `" . TBBARLOCTC . "` WHERE barloctc_idbarloc<=" . $idbarloc . " AND barloctc_ncons=1 AND barloctc_min<=" . $diffidx1 . " AND barloctc_max<=" . $diffidx1;
        $rows2 = $db->get_results($rech2, ARRAY_A);
        if (count($rows2) == 1) {
            extract($rows2[0]);
            $totconso1 = $diffidx1 * $barloctc_pvht;
        } else // ... Il y a une fourchette "nb unités dépassées - infini" ?
        {
            $rech2 = "SELECT * FROM `" . TBBARLOCTC . "` WHERE barloctc_idbarloc<=" . $idbarloc . " AND barloctc_ncons=1 AND barloctc_min<=" . $diffidx1 . " AND barloctc_max=0";
            $rows2 = $db->get_results($rech2, ARRAY_A);
            if (count($rows2) == 1) {
                extract($rows2[0]);
                $totconso1 = $diffidx1 * $barloctc_pvht;
            }
        }
    }

    // Calcul pour le second consommable
    if (intval($diffidx2) > 0) {
        // On recherche dans le barème des consommables
        // ... Il y a une fourchette de valeurs ?
        $rech2 = "SELECT * FROM `" . TBBARLOCTC . "` WHERE barloctc_idbarloc<=" . $idbarloc . " AND barloctc_ncons=2 AND barloctc_min<=" . $diffidx2 . " AND barloctc_max<=" . $diffidx2;
        $rows2 = $db->get_results($rech2, ARRAY_A);
        if (count($rows2) == 1) {
            extract($rows2[0]);
            $totconso2 = $diffidx2 * $barloctc_pvht;
        } else // ... Il y a une fourchette "nb unités dépassées - infini" ?
        {
            $rech2 = "SELECT * FROM `" . TBBARLOCTC . "` WHERE barloctc_idbarloc<=" . $idbarloc . " AND barloctc_ncons=2 AND barloctc_min<=" . $diffidx2 . " AND barloctc_max=0";
            $rows2 = $db->get_results($rech2, ARRAY_A);
            if (count($rows2) == 1) {
                extract($rows2[0]);
                $totconso2 = $diffidx1 * $barloctc_pvht;
            }
        }
    }

    $totconsos = $totconso1 + $totconso2;

    if ($open == TRUE)
        $db->disconnect();
    return $totconsos;
}


/**
 * @param $id_html
 * @param $td
 * @param $tab_bl
 * @param $tab_pl
 * @param $tab_cl
 * @param $from
 * @param bool $open
 */
function cre_html_pdtlbl($id_html, $td, $tab_bl, $tab_pl, $tab_cl, $from, $open = TRUE)
{
    global
    $db,
    $_SESSION;

    // Création de la chaine HTML
    $str_html = '';

    if (count($tab_bl) > 0) {
        // *** 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 .= _("Désignation");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Quantité");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Total HT");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Mt TVA");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Total TTC");
        $str_html .= "</th>";

        if (($td == "edit") OR ($td == "add") OR ($td == "ret")) {
            $str_html .= "<th>";
            $str_html .= _("Cliquer");
            $str_html .= "</th>";
        }

        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        for ($i = 0; $i < count($tab_bl); $i++) {
            $qte = $tab_bl[$i]["qte"];

            // Récupération enregistrement barème location
            if ($tab_bl[$i]["idbarloc"] <> 0) {
                $rech2 = "SELECT * FROM `" . TBBARLOC . "` WHERE barloc_id='" . $tab_bl[$i]["idbarloc"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
            } else {
                $barloc_des = _("Prêt de matériel sur").' ' . $qte . ' '._("jour(s)");
            }

            // 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\">";

            // Désignation
            $txt_des = $barloc_des . " "._("inclus caution");
            if ($tab_bl[$i]["avecass"] == 1)
                $txt_des .= ' ' ._("et assurance");
            else
                $txt_des .= ', '._("sans assurance");
            $txt_des .= ")";
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $txt_des;

            if ($tab_bl[$i]["qconsi1"] > 0) {
                $rech2 = "SELECT * FROM `" . TBPDTU . "` WHERE pdtu_code='" . $tab_bl[$i]["pdtuconsi1"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txt = _("Inclus").' ' . $qte . ' ' ._("forfait(s)").' ' . $tab_bl[$i]["qconsi1"] . ' ' . strtolower($pdtu_abr);
                $str_html .= "<div class=\"annot_moy_it\" valign=\"top\" align=\"right\">";
                $str_html .= $txt;
                $str_html .= "</div>";
            }
            if ($tab_bl[$i]["qconsi2"] > 0) {
                $rech2 = "SELECT * FROM `" . TBPDTU . "` WHERE pdtu_code='" . $tab_bl[$i]["pdtuconsi2"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txt = _("Inclus").' '  . $qte . ' '._("forfait(s)").' ' . $tab_bl[$i]["qconsi2"] . ' ' . strtolower($pdtu_abr);
                $str_html .= "<div class=\"annot_moy_it\" valign=\"top\" align=\"right\">";
                $str_html .= $txt;
                $str_html .= "</div>";
            }
            $str_html .= "</td>";

            // Quantité
            $txt = full_num_format($tab_bl[$i]["qte"], '', '', FALSE, '', FALSE);
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Calculs divers
            //... Montant location
            $pvht = $tab_bl[$i]["pvht"];
            $tothtloc = round(($qte * $pvht) * 100) / 100;
            $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $tab_bl[$i]["codetva"] . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            $txtva = $tva_tx / 100;
            $totttcloc = round(($tothtloc * (1 + $txtva)) * 100) / 100;
            $tottvaloc = $totttcloc - $tothtloc;
            //... Caution
            $pvht = $tab_bl[$i]["caution"];
            $tothtcaut = round($pvht * 100) / 100;
            $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $tab_bl[$i]["tvacaut"] . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            $txtva = $tva_tx / 100;
            $totttccaut = round(($tothtcaut * (1 + $txtva)) * 100) / 100;
            $tottvacaut = $totttccaut - $tothtcaut;
            //... Assurance
            $tothtass = 0;
            $totttcass = 0;
            $tottvaass = 0;
            if ($tab_bl[$i]["avecass"] == 1) {
                $pvht = $tab_bl[$i]["mtass"];
                $tothtass = round(($qte * $pvht) * 100) / 100;
                $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $tab_bl[$i]["codetvaass"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txtva = $tva_tx / 100;
                $totttcass = round(($tothtass * (1 + $txtva)) * 100) / 100;
                $tottvaass = $totttcass - $tothtass;
            }
            //...Consommables
            $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $tab_bl[$i]["codetva"] . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            $txtva = $tva_tx / 100;
            //... Consommable 1
            $pvht = $tab_bl[$i]["puconsi1"];
            $tothtcons1 = round(($qte * $pvht) * 100) / 100;
            $totttccons1 = round(($tothtcons1 * (1 + $txtva)) * 100) / 100;
            $tottvacons1 = $totttccons1 - $tothtcons1;
            //... Consommable 2
            $pvht = $tab_bl[$i]["puconsi2"];
            $tothtcons2 = round(($qte * $pvht) * 100) / 100;
            $totttccons2 = round(($tothtcons2 * (1 + $txtva)) * 100) / 100;
            $tottvacons2 = $totttccons2 - $tothtcons2;

            // Affichages
            // Total HT
            $totbarht = $tothtloc + $tothtcaut + $tothtass + $tothtcons1 + $tothtcons2;
            $txt = full_num_format($totbarht, '', '', TRUE,'',FALSE);
            $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // Mt TVA
            $totbartva = $tottvaloc + $tottvacaut + $tottvaass + $tottvacons1 + $tottvacons2;
            $txt = full_num_format($totbartva, '', '', TRUE,'',FALSE);
            $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            // total TTC
            $totbarttc = $totttcloc + $totttccaut + $totttcass + $totttccons1 + $totttccons2;
            $txt = full_num_format($totbarttc, '', '', TRUE,'',FALSE);
            $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            if (($td == "add") OR ($td == "edit")) {
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                $urleditbarloc = "pdtlbl_maj.php?td=edit&cl=" . $tab_bl[$i]["codecoloc"] . "&ca=" . $tab_bl[$i]["codeart"];
                $urleditbarloc .= "&dd=" . $tab_bl[$i]["dd"] . "&hd=" . $tab_bl[$i]["hd"] . "&df=" . $tab_bl[$i]["df"] . "&hf=" . $tab_bl[$i]["hf"];
                // $str_html .= cre_falselnk_img('', 'pdtlbl_edit_'.$tab_bl[$i]["id"], 'span', '', _("Edition"), 'lnkpop', $urleditbarloc, '../img/edit.png', 800 , 500, true);
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urleditbarloc."','pdtlbl_edit_".$tab_bl[$i]["id"]."',800,500,'yes')\")>";
                $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                $str_html .= " ";

                $urldelbarloc = "pdtlbl_maj.php?td=del&cl=" . $tab_bl[$i]["codecoloc"] . "&ca=" . $tab_bl[$i]["codeart"];
                $urldelbarloc .= "&dd=" . $tab_bl[$i]["dd"] . "&hd=" . $tab_bl[$i]["hd"] . "&df=" . $tab_bl[$i]["df"] . "&hf=" . $tab_bl[$i]["hf"];
                // $str_html .= cre_falselnk_img('', 'pdtlbl_del_'.$tab_bl[$i]["id"], 'span', '', _("Suppression"), 'lnkpop', $urldelbarloc, '../img/del.png', 800 , 500, true);
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldelbarloc."','pdtlbl_del_".$tab_bl[$i]["id"]."',800,500,'yes')\")>";
                $str_html .= '<img src="../img/del.png" border="0" align="absmiddle" title="' . _("Suppression") . '"></a>';
                $str_html .= "</td>";
            }
            if ($td == "ret") {
                $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                $str_html .= " ";
                $str_html .= "</td>";
            }

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

        // On affiche les pénalités s'il y en a et si on est en mode retour ou visualisation
        $i++;
        $penht = 0;
        $pentva = 0;
        $penttc = 0;
        if (($td == "ret") OR ($td == "view")) {
            if (count($tab_pl) > 0) {
                // Si "-1" on est ou sans pénalité, ou pénalité offerte
                if ($tab_pl[0]["codepen"] <> "-1") {
                    // Calculs divers
                    //... Montant pénalité
                    $penht = $tab_pl[0]["valeur"];
                    $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $tab_pl[0]["tva"] . "'";
                    $row2 = $db->get_row($rech2, ARRAY_A);
                    if ($row2)
                        extract($row2);
                    $txtva = $tva_tx / 100;
                    $penttc = round(($penht * (1 + $txtva)) * 100) / 100;
                    $pentva = $penttc - $penht;

                    if ($tab_pl[0]["valeur"] <> 0) // On affiche que si pénalité non nulle
                    {
                        // 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\">";

                        // Désignation
                        $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                        $str_html .= _("Pénalité sur retard");
                        $str_html .= "</td>";

                        // Quantité
                        $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                        $str_html .= "1.00";
                        $str_html .= "</td>";

                        // Total HT
                        $txt = full_num_format($penht, '', '', TRUE,'',FALSE);
                        $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
                        $str_html .= $txt;
                        $str_html .= "</td>";

                        // Mt TVA
                        $txt = full_num_format($pentva, '', '', TRUE,'',FALSE);
                        $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
                        $str_html .= $txt;
                        $str_html .= "</td>";

                        // total TTC
                        $txt = full_num_format($penttc, '', '', TRUE,'',FALSE);
                        $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
                        $str_html .= $txt;
                        $str_html .= "</td>";

                        // Icône de suppression de pénalité
                        if ($td == "ret") {

                            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                            $str_html .= "<a href=\"javascript:;\" onclick=\"fen_rloc('ret','pen_del_".$tab_pl[$i]['id']."',700,500);\")>";
                            $str_html .= "<img src=\"../img/del.png\" border=\"0\" align=\"absmiddle\" title=\""._("Supprimer la pénalité")."\"></a>";
                            $str_html .= "</td>";
                        }
                        $str_html .= "</tr>";
                    }
                }
            }
        }

        // On affiche le montant des consommables s'il y en a et si on est en mode retour ou visualisation
        $i++;
        $consht = 0;
        $constva = 0;
        $consttc = 0;
        if (($td == "ret") OR ($td == "view")) {
            if (count($tab_cl) > 0) {
                // Calculs divers
                //... Montant pénalité
                $consht = $tab_cl[0]["valeur"];
                $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $tab_cl[0]["tva"] . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txtva = $tva_tx / 100;
                $consttc = round(($consht * (1 + $txtva)) * 100) / 100;
                $constva = $consttc - $consht;

                if ($tab_cl[0]["valeur"] <> 0) // On affiche que si montant non nul
                {
                    // 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\">";

                    // Désignation
                    $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                    $str_html .= _("Consommables en sus");
                    $str_html .= "</td>";

                    // Quantité
                    $str_html .= "<td class=\"tdlst\" valign=\"top\">";
                    $str_html .= "1.00";
                    $str_html .= "</td>";

                    // Total HT
                    $txt = full_num_format($consht, '', '', TRUE,'',FALSE);
                    $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
                    $str_html .= $txt;
                    $str_html .= "</td>";

                    // Mt TVA
                    $txt = full_num_format($constva, '', '', TRUE,'',FALSE);
                    $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
                    $str_html .= $txt;
                    $str_html .= "</td>";

                    // Total TTC
                    $txt = full_num_format($consttc, '', '', TRUE,'',FALSE);
                    $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
                    $str_html .= $txt;
                    $str_html .= "</td>";

                    // Icône de suppression de consommables
                    if ($td == "ret") {
                        $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
                        $str_html .= "<a href=\"javascript:;\" onclick=\"fen_cons_rloc('del');\")>";
                        $str_html .= "<img src=\"../img/del.png\" border=\"0\" align=\"absmiddle\" title=\""._("Supprimer le montant consommables")."\"></a>";
                        $str_html .= "</td>";
                    }
                    $str_html .= "</tr>";
                }
            }
        }

        if ($open == TRUE)
            $db->disconnect();

        // Totaux généraux
        $str_html .= "<tr>";

        // 1ère cellule
        $str_html .= "<td class=\"annot_gras_it\" valign=\"top\" align=\"right\">";
        $str_html .= _("Total Général");
        $str_html .= "</td>";

        // 2nde cellule
        $str_html .= "<td class=\"annot_gras_it\" valign=\"top\" align=\"right\">";
        $str_html .= " ";
        $str_html .= "</td>";

        // Total général HT
        $txt = full_num_format(($totbarht + $penht + $consht), '', '', TRUE,'',FALSE);
        $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        // Mt général TVA
        $txt = full_num_format(($totbartva + $pentva + $constva), '', '', TRUE,'',FALSE);
        $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        // total général TTC
        $txt = full_num_format(($totbarttc + $penttc + $consttc), '', '', TRUE,'',FALSE);
        $str_html .= "<td class=\"TDnumberD\" valign=\"top\" align=\"center\">";
        $str_html .= $txt;
        $str_html .= "</td>";

        // 6ème cellule
        if (($td == "edit") OR ($td == "add") OR ($td == "ret")) {
            $str_html .= "<td valign=\"top\" align=\"center\">";
            $str_html .= " ";
            $str_html .= "</td>";
        }

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

        echo 'function tbpbarloc() {';
        echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
        echo $from . "$('#".$id_html."').html('" . str_replace("'", "\'", $str_html) . "');";
        echo '}';
        // Mises à jour boutons & liens
        // Lien ajout de barème
        echo $from . "$('#addbarloc').hide();";
        // Bouton d'enregistrement
        echo $from . "$('#enr').attr('class','bton_std');";
        echo $from . "$('#enr').val('"._("Valider")."');";
        echo $from . "$('#enr').attr('disabled',false);";
        echo '}';
    } else {
        echo 'function tbpbarloc() {';
        echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
        echo $from . "$('#".$id_html."').html('" . str_replace("'", "\'", $str_html) . "');";
        echo '}';
        // Mises à jour boutons & liens
        // Lien ajout de barème
        echo $from . "$('#addbarloc').show();";
        // Bouton d'enregistrement
        echo $from . "$('#enr').attr('class','bton_fmarr_dis');";
        echo $from . "$('#enr').val('"._("Pour valider, merci de choisir au moins un barême")."');";
        echo $from . "$('#enr').attr('disabled',true);";
        echo '}';
    }
}

/**
 * Création du code Javascript pour affichage des produits dans un contrat location
 *
 * @param $id_html
 * @param $td
 * @param $code
 * @param $from
 * @param bool $open
 */
function cre_html_pdtincloc($id_html, $td, $code, $from, $open = TRUE)
{
    global
    $db,
    $_SESSION;

    // Création de la chaine HTML
    $str_html = '';

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

    $rech = "SELECT * FROM `" . TBPDTL . "` WHERE pdtl_codecoloc='" . $db->escape($code) . "' ORDER BY `pdtl_codepdtloc`";
    $rows = $db->get_results($rech, ARRAY_A);

    if (($rows) AND (count($rows) > 0)) {
        // Type de facturation
        $factTTC = TRUE;

        $rech2 = "SELECT coloc_codecli,coloc_typcli FROM `" . TBCOLOC . "` WHERE coloc_code='" . $db->escape($code) . "'";
        $row2 = $db->get_row($rech2, ARRAY_A);
        if ($row2) {
            extract($row2);

            switch ($coloc_typcli) {
                case 0 :
                    $rech3 = "SELECT cli_modfact FROM `" . TBCLI . "` WHERE cli_code='" . $coloc_codecli . "'";
                    $row3 = $db->get_row($rech3, ARRAY_A);

                    if ($row3) {
                        extract($row3);
                        if (($cli_modfact == "0") OR ($cli_modfact == "2"))
                            $factTTC = FALSE;
                    }
                    break;
                case 1 :
                case 3 :
                    $factTTC = FALSE;
                    break;
            }
        }

        // *** 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 .= _("Désignation");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Du");
        $str_html .= "</th>";

        $str_html .= "<th>";
        $str_html .= _("Au");
        $str_html .= "</th>";

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

        $str_html .= "<th>";
        if ($td == "edit")
            $str_html .= _("Cliquer");
        else
            $str_html .= " ";
        $str_html .= "</th>";

        // Lignes du tableau
        $i = 0;

        foreach ($rows as $row) {
            $row = encode_str($row);
            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\">";

            // Désignation
            $rech2 = "SELECT pdtloc_des FROM `" . TBPDTLOC . "` WHERE pdtloc_code='" . $pdtl_codepdtloc . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);

            // Récupération enregistrement barème location du produit dans ce contrat
            $rech2 = "SELECT * FROM `" . TBPDTLBL . "` WHERE pdtlbl_idpdtl='" . $pdtl_id . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            if ($pdtlbl_idbarloc == 0)
                $pdtloc_des .= ' ('._("prêt").')';

            // Désignation
            $str_html .= "<td class=\"tdlst\" valign=\"top\">";
            $str_html .= $pdtloc_des;

            if (datetolocal($pdtl_datedep) <> "") {
                $str_html .= " ";
                $str_html .= "<img src=\"../img/sorti.png\" border=\"0\" align=\"absmiddle\" title=\"" . _("Produit livré le"). " " . datetolocal($pdtl_datedep) . "\"></a>";
            }
            if (datetolocal($pdtl_dateret) <> "") {
                $str_html .= " ";
                $str_html .= "<img src=\"../img/revenu.png\" border=\"0\" align=\"absmiddle\" title=\"" . _("Produit rendu le"). "  " . datetolocal($pdtl_dateret) . "\"></a>";
            }
            $str_html .= "</td>";

            // Du
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            $str_html .= datetolocal($pdtl_datedeb) . " (" . substr($pdtl_heuredeb, 0, 5) . ")";
            $str_html .= "</td>";

            // Au
            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            $str_html .= datetolocal($pdtl_datefin) . " (" . substr($pdtl_heurefin, 0, 5) . ")";
            $str_html .= "</td>";

            $qte = $pdtlbl_qte;

            // Calculs divers
            //... Montant location
            $pvht = $pdtlbl_pvht;
            $tothtloc = round(($qte * $pvht) * 100) / 100;
            $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $pdtlbl_codetva . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            $txtva = $tva_tx / 100;
            $totttcloc = round(($tothtloc * (1 + $txtva)) * 100) / 100;
            $tottvaloc = $totttcloc - $tothtloc;
            //... Caution
            $pvht = $pdtlbl_caution;
            $tothtcaut = round($pvht * 100) / 100;
            $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $pdtlbl_tvacaut . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            $txtva = $tva_tx / 100;
            $totttccaut = round(($tothtcaut * (1 + $txtva)) * 100) / 100;
            $tottvacaut = $totttccaut - $tothtcaut;
            //... Assurance
            $tothtass = 0;
            $totttcass = 0;
            $tottvaass = 0;
            if ($pdtlbl_avecass == 1) {
                $pvht = $pdtlbl_mtass;
                $tothtass = round(($qte * $pvht) * 100) / 100;
                $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $pdtlbl_codetvaass . "'";
                $row2 = $db->get_row($rech2, ARRAY_A);
                if ($row2)
                    extract($row2);
                $txtva = $tva_tx / 100;
                $totttcass = round(($tothtass * (1 + $txtva)) * 100) / 100;
                $tottvaass = $totttcass - $tothtass;
            }
            //...Consommables
            $rech2 = "SELECT * FROM `" . TBTVA . "` WHERE tva_code='" . $pdtlbl_codetva . "'";
            $row2 = $db->get_row($rech2, ARRAY_A);
            if ($row2)
                extract($row2);
            $txtva = $tva_tx / 100;
            //... Consommable 1
            $pvht = $pdtlbl_puconsi1;
            $tothtcons1 = round(($qte * $pvht) * 100) / 100;
            $totttccons1 = round(($tothtcons1 * (1 + $txtva)) * 100) / 100;
            $tottvacons1 = $totttccons1 - $tothtcons1;
            //... Consommable 2
            $pvht = $pdtlbl_puconsi2;
            $tothtcons2 = round(($qte * $pvht) * 100) / 100;
            $totttccons2 = round(($tothtcons2 * (1 + $txtva)) * 100) / 100;
            $tottvacons2 = $totttccons2 - $tothtcons2;

            // Total
            if ($factTTC == TRUE)
                $txt = full_num_format(($totttcloc + $totttccaut + $totttcass + $totttccons1 + $totttccons2), '', '', TRUE,'',FALSE);
            else
                $txt = full_num_format(($tothtloc + $tothtcaut + $tothtass + $tothtcons1 + $tothtcons2), '', '', TRUE,'',FALSE);
            $str_html .= "<td class=\"TDnumberD\" valign=\"top\">";
            $str_html .= $txt;
            $str_html .= "</td>";

            $str_html .= "<td class=\"tdlst\" valign=\"top\" align=\"center\">";
            if ($td == "edit") {
                if ((datetolocal($pdtl_datedep) == "") AND (datetolocal($pdtl_dateret) == "")) {
                    $urleditpdtl = "pdtl_maj.php?td=edit&cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    $urleditpdtl .= "&dd=" . datetolocal($pdtl_datedeb) . "&hd=" . substr($pdtl_heuredeb, 0, 5);
                    $urleditpdtl .= "&df=" . datetolocal($pdtl_datefin) . "&hf=" . substr($pdtl_heurefin, 0, 5);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urleditpdtl."','pdtl_edit_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/edit.png" border="0" align="absmiddle" title="' . _("Edition") . '"></a>';
                    $str_html .= " ";
                }

                if (datetolocal($pdtl_datedep) == "") {
                    $urldeppdtl = "pdtl_maj.php?td=dep&cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    $urldeppdtl .= "&dd=" . datetolocal($pdtl_datedeb) . "&hd=" . substr($pdtl_heuredeb, 0, 5);
                    $urldeppdtl .= "&df=" . datetolocal($pdtl_datefin) . "&hf=" . substr($pdtl_heurefin, 0, 5);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldeppdtl."','pdtl_dep_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/depart.png" border="0" align="absmiddle" title="' . _("Livrer") . '"></a>';
                    $str_html .= " ";
                }

                if ((datetolocal($pdtl_datedep) <> "") AND (datetolocal($pdtl_dateret) == "")) {
                    $urlretpdtl = "pdtl_maj.php?td=ret&cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    $urlretpdtl .= "&dd=" . datetolocal($pdtl_datedeb) . "&hd=" . substr($pdtl_heuredeb, 0, 5);
                    $urlretpdtl .= "&df=" . datetolocal($pdtl_datefin) . "&hf=" . substr($pdtl_heurefin, 0, 5);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urlretpdtl."','pdtl_ret_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/retour.png" border="0" align="absmiddle" title="' . _("Retour") . '"></a>';
                    $str_html .= " ";
                }

                if ((datetolocal($pdtl_datedep) <> "") AND (datetolocal($pdtl_dateret) <> "")) {
                    $urldetpdtl = "pdtl_maj.php?td=view&cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    $urldetpdtl .= "&dd=" . datetolocal($pdtl_datedeb) . "&hd=" . substr($pdtl_heuredeb, 0, 5);
                    $urldetpdtl .= "&df=" . datetolocal($pdtl_datefin) . "&hf=" . substr($pdtl_heurefin, 0, 5);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldetpdtl."','pdtl_det_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/eye.png" border="0" align="absmiddle" title="' . _("Visualisation") . '"></a>';
                    $str_html .= " ";
                }

                if ($_SESSION["niv_log"] <> 1) {
                    $urlprtart = "pdtldr_pdf.php?cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    // $str_html .= cre_falselnk_img('', 'pdtldr_prn_'.$pdtl_id, 'span', 'center', _("Imprimer"), 'lnkpop', $urlprtart, '../img/print.png',0,0,true);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urlprtart."','pdtldr_prn_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/print.png" border="0" align="absmiddle" title="' . _("Imprimer") . '"></a>';
                    $str_html .= " ";
                }

                if ((datetolocal($pdtl_datedep) == "") AND (datetolocal($pdtl_dateret) == "")) {
                    $urldelpdtl = "pdtl_maj.php?td=del&cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    $urldelpdtl .= "&dd=" . datetolocal($pdtl_datedeb) . "&hd=" . substr($pdtl_heuredeb, 0, 5);
                    $urldelpdtl .= "&df=" . datetolocal($pdtl_datefin) . "&hf=" . substr($pdtl_heurefin, 0, 5);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldelpdtl."','pdtl_del_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/del.png" border="0" align="absmiddle" title="' . _("Suppressionr") . '"></a>';
                }
            } else {
                $urldetpdtl = "pdtl_maj.php?td=view&cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                $urldetpdtl .= "&dd=" . datetolocal($pdtl_datedeb) . "&hd=" . substr($pdtl_heuredeb, 0, 5);
                $urldetpdtl .= "&df=" . datetolocal($pdtl_datefin) . "&hf=" . substr($pdtl_heurefin, 0, 5);
                $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urldetpdtl."','pdtl_det_".$pdtl_id."',900,700,'yes')\")>";
                $str_html .= '<img src="../img/eye.png" border="0" align="absmiddle" title="' . _("Visualisation") . '"></a>';
                $str_html .= " ";

                if ($_SESSION["niv_log"] <> 1) {
                    $urlprtart = "pdtldr_pdf.php?cl=" . $pdtl_codecoloc . "&ca=" . $pdtl_codepdtloc;
                    // $str_html .= cre_falselnk_img('', 'pdtldr_prn_'.$pdtl_id, 'span', 'center', _("Imprimer"), 'lnkpop', $urlprtart, '../img/print.png',0,0,true);
                    $str_html .= "<a href=\"javascript:;\" onclick=\"init_new_window('".$urlprtart."','pdtldr_prn_".$pdtl_id."',900,700,'yes')\")>";
                    $str_html .= '<img src="../img/print.png" border="0" align="absmiddle" title="' . _("Imprimer") . '"></a>';
                }
            }
            $str_html .= "</td>";

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

        if ($open == TRUE)
            $db->disconnect();

        echo 'function pdtincloc() {';
        echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
        echo $from . "$('#" . $id_html . "').html('" . str_replace("'", "\'", $str_html) . "');";
        echo '}';
        // Mises à jour boutons & liens
        echo $from . "$('#affsel').show();";
        echo $from . "$('#affchxdd').hide();";
        echo $from . "$('#affchxdf').hide();";
        echo $from . "$('#enr').attr('class','bton_std');";
        echo $from . "$('#enr').val('" . _("Valider") . "');";
        echo $from . "$('#enr').attr('disabled',false);";
        echo $from . "$('#enrimp').attr('class','bton_std');";
        echo $from . "$('#enrimp').attr('disabled',false);";
        echo '}';
    } else {
        echo 'function pdtincloc() {';
        echo 'if ((' . $from . '$("#' . $id_html . '").length) > 0) {';
        echo $from . "$('#" . $id_html . "').html('" . str_replace("'", "\'", $str_html) . "');";
        echo '}';
        if ($td <> "add") {
            // Mises à jour boutons & liens
            echo $from . "$('#affsel').hide();";
            echo $from . "$('#affchxdd').show();";
            echo $from . "$('#affchxdf').show();";
            echo $from . "$('#enr').attr('class','bton_fmarr_dis');";
            echo $from . "$('#enr').val('" . _("Pour valider, merci de choisir au moins un barême") . "');";
            echo $from . "$('#enr').attr('disabled',true);";
            echo $from . "$('#enrimp').attr('class','bton_fmarr_dis');";
            echo $from . "$('#enrimp').attr('disabled',true);";
        }
        echo '}';
    }

}

// Barèmes

/**
 * Donne le nombre de barèmes dans une fiche article à louer
 *
 * @param $codep
 * @param bool $open
 * @return null
 */
function nb_barloc_in_pdtloc($codep, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*) FROM `" . TBBARLOC . "` WHERE `barloc_codepdtloc` = '" . $db->escape($codep) . "'";
    $nbbarloc = $db->get_var($rech2);
    if ($open == TRUE)
        $db->disconnect();

    return $nbbarloc;
}

/**
 * Donne le nombre de tarifs consommables dans un barème donné et un numéro de consommable donné
 *
 * @param $idbl
 * @param $ncons
 * @param bool $open
 * @return null
 */
function nb_tarcons_in_barloc($idbl, $ncons, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*) FROM `" . TBBARLOCTC . "` WHERE `barloctc_idbarloc` = '$idbl' AND `barloctc_ncons` = '" . $db->escape($ncons) . "'";
    $nbtarcons = $db->get_var($rech2);
    if ($open == TRUE)
        $db->disconnect();

    return $nbtarcons;
}

/**
 * Donne le dernier id d'un tarif consommable dans un barème donné et un numéro de consommable donné
 *
 * @param $idbl
 * @param $ncons
 * @param bool $open
 * @return int
 */
function last_id_tarcons_in_barloc($idbl, $ncons, $open = TRUE)
{
    global
    $db;
    $idtc = 0;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT barloctc_id FROM `" . TBBARLOCTC . "` WHERE `barloctc_idbarloc` = '$idbl' AND `barloctc_ncons` = '" . $db->escape($ncons) . "' ORDER BY `barloctc_min` DESC";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($row2) {
        extract($row2);
        $idtc = $barloctc_id;
    }
    if ($open == TRUE)
        $db->disconnect();

    return $idtc;
}

/**
 * Vérifie si un tarif consommable possède un maximum "infini", pour un numéro de consommable donné
 *
 * @param $idbl
 * @param $ncons
 * @param bool $open
 * @return bool
 */
function exist_infini_tcons_id($idbl, $ncons, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*) FROM `" . TBBARLOCTC . "` WHERE `barloctc_idbarloc` = '" . $idbl . "' AND `barloctc_max` = '0' AND `barloctc_ncons` = '$ncons'";
    $nbres = $db->get_var($rech2);
    if ($nbres > 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Lecture d'un enregistrement barème, par son id
 *
 * @param $id
 * @param bool $open
 * @return array|null
 */
function lit_enr_barloc_id($id, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBBARLOC . "` WHERE `barloc_id` = '$id'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Lecture d'un enregistrement tarif consommables, par son id
 *
 * @param $id
 * @param bool $open
 * @return array|null
 */
function lit_enr_tcons_id($id, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBBARLOCTC . "` WHERE `barloctc_id` = '$id'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Lecture d'un enregistrement barème, pour un barème et un produit donnés
 *
 * @param $codepl
 * @param $codep
 * @param bool $open
 * @return array|null
 */
function lit_enr_barloc_in_pdtloc($codepl, $codep, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBBARLOC . "` WHERE `barloc_codeperloc` = '" . $db->escape($codepl) . "' AND `barloc_codepdtloc` = '" . $db->escape($codep) . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}

/**
 * Vérification de la présence d'un barème location dans une fiche location
 *
 * @param $idbl
 * @param bool $open
 * @return bool
 */
function exist_barloc_in_coloc($idbl, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT COUNT(*) FROM `" . TBPDTLBL . "`";
    $rech2 .= " WHERE " . TBPDTLBL . ".pdtlbl_idbarloc = '" . $idbl . "'";
    $nbres = $db->get_var($rech2);
    if ($nbres <> 0)
        $exist = TRUE;
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Vérification de la présence d'un barème location dans une fiche location non close
 *
 * @param $idbl
 * @param bool $open
 * @return bool
 */
function exist_barloc_in_coloc_ouv($idbl, $open = TRUE)
{
    global
    $db;
    $exist = FALSE;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT " . TBPDTL . ".pdtl_codecoloc FROM `" . TBPDTL . "`, `" . TBPDTLBL . "`";
    $rech2 .= " WHERE " . TBPDTLBL . ".pdtlbl_idbarloc = '" . $idbl . "'";
    $rech2 .= " AND " . TBPDTLBL . ".pdtlbl_idpdtl = " . TBPDTL . ".pdtl_id";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if (($rows2) AND (count($rows2) <> 0)) {
        foreach ($rows2 as $row2) {
            extract($row2);
            $rech3 = "SELECT " . TBCOLOC . ".coloc_code FROM `" . TBCOLOC . "`";
            $rech3 .= " WHERE " . TBCOLOC . ".coloc_code = '" . $pdtl_codecoloc . "'";
            $rech3 .= " AND " . TBCOLOC . ".coloc_datefin = '0000-00-00'";
            $row3 = $db->get_row($rech3, ARRAY_A);
            if ($row3) {
                $exist = TRUE;
                break;
            }
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $exist;
}

/**
 * Retourne le prochain minimum à appliquer sur un tarif consommables
 *
 * @param $idbl
 * @param $qconsi
 * @param $ncons
 * @param bool $open
 * @return mixed
 */
function next_min_tcons($idbl, $qconsi, $ncons, $open = TRUE)
{
    global
    $db;
    $nextmin = $qconsi + 1;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT MAX(" . TBBARLOCTC . ".barloctc_max) AS maximum FROM `" . TBBARLOCTC . "`";
    $rech2 .= " WHERE " . TBBARLOCTC . ".barloctc_idbarloc = '" . $idbl . "' AND " . TBBARLOCTC . ".barloctc_ncons = '" . $ncons . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($row2) {
        extract($row2);
        if ($maximum <> NULL)
            $nextmin = $maximum + 1;
    }
    if ($open == TRUE)
        $db->disconnect();

    return $nextmin;
}

/**
 * Retourne la quantité de secondes couvertes par un barème pour un produit en location
 *
 * @param $idbl
 * @param bool $open
 * @return int
 */
function nbsc_in_barloc_barloc($idbl, $open = TRUE)
{
    global
    $db;
    $nbs = 0;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT barloc_codeperloc FROM `" . TBBARLOC . "`";
    $rech2 .= " WHERE " . TBBARLOC . ".barloc_id = '" . $idbl . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($row2) {
        extract($row2);
        // On récupère les valeurs nombre et secondes de la périodicité
        $rech3 = "SELECT perloc_nduree,perloc_tduree FROM `" . TBPERLOC . "`";
        $rech3 .= " WHERE " . TBPERLOC . ".perloc_code = '" . $barloc_codeperloc . "'";
        $row3 = $db->get_row($rech3, ARRAY_A);
        if ($row3) {
            extract($row3);
            $nbs = $perloc_nduree * $perloc_tduree;
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $nbs;
}

/**
 * Retourne la quantité de secondes déjà couvertes par des barèmes pour un produit en location
 * Dans un contrat de location donné
 *
 * @param $codecl
 * @param $codep
 * @param bool $open
 * @return int
 */
function nbs_barloc_in_pdtloc($codecl, $codep, $open = TRUE)
{
    global
    $db;
    $nbs = 0;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    // On récupère l'ID du produit dans le contrat
    $rech2 = "SELECT pdtl_id FROM `" . TBPDTL . "`";
    $rech2 .= " WHERE " . TBPDTL . ".pdtl_codecoloc = '" . $codecl . "' AND " . TBPDTL . ".pdtl_codepdtloc = '" . $codep . "'";
    $row2 = $db->get_row($rech2, ARRAY_A);
    if ($row2) {
        extract($row2);
        /** On récupère le total secondes couvertes **/

        // On récupère l'ID du barème de location
        $rech3 = "SELECT pdtlbl_idbarloc FROM `" . TBPDTLBL . "`";
        $rech3 .= " WHERE " . TBPDTLBL . ".pdtlbl_idpdtl = '" . $pdtl_id . "'";
        $rows3 = $db->get_results($rech3, ARRAY_A);
        if (($rows3) AND (count($rows3) > 0)) {
            foreach ($rows3 as $row3) {
                extract($row3);
                // On récupère le code périodicité du barème de location
                $rech4 = "SELECT barloc_codeperloc FROM `" . TBBARLOC . "`";
                $rech4 .= " WHERE " . TBBARLOC . ".barloc_id = '" . $pdtl_idbarloc . "'";
                $row4 = $db->get_row($rech4, ARRAY_A);
                if ($row4) {
                    extract($row4);
                    // On récupère les valeurs nombre et secondes de la périodicité
                    $rech5 = "SELECT perloc_nduree,perloc_tduree FROM `" . TBPERLOC . "`";
                    $rech5 .= " WHERE " . TBPERLOC . ".perloc_code = '" . $barloc_codeperloc . "'";
                    $row5 = $db->get_row($rech5, ARRAY_A);
                    if ($row5) {
                        extract($row5);
                        $nbs = $nbs + ($pdtlbl_qte * $perloc_nduree * $perloc_tduree);
                    }
                }
            }
        }
    }
    if ($open == TRUE)
        $db->disconnect();

    return $nbs;
}

/** Produits à louer : réparations
 * @param $codepdtloc
 * @param bool $open
 * @return null
 */

// Nombre de réparations
function nb_pdtlocr($codepdtloc, $open = TRUE)
{
    global
    $db;

    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT COUNT(*) FROM `" . TBPDTLOCR . "`";
    if ($codepdtloc <> "")
        $rexist .= " WHERE  `pdtlocr_codepdtloc` = '" . $db->escape($codepdtloc) . "'";
    $nbexist = $db->get_var($rexist);
    if ($open == TRUE)
        $db->disconnect();

    return $nbexist;
}

/**
 * Prix de revient des réparations pour un produit de location donné
 *
 * @param $codepdtloc
 * @param bool $open
 * @return float|int
 */
function px_revient_pdtlocr($codepdtloc, $open = TRUE)
{
    global
    $db;
    $cout_rep = 0;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rech2 = "SELECT * FROM `" . TBPDTLOCR . "`";
    $rech2 .= " WHERE  `pdtlocr_codepdtloc` = '" . $db->escape($codepdtloc) . "'";
    $rows2 = $db->get_results($rech2, ARRAY_A);
    if (($rows2) AND (count($rows2) > 0)) {
        foreach ($rows2 as $row2) {
            extract($row2);
            // On récupère le prix de revient du technicien en fonction de la date
            $rech3 = "SELECT tecpr_couth FROM `" . TBTECPR . "` WHERE `tecpr_date` <= '$pdtlocr_date' AND `tecpr_codetec` = '" . $pdtlocr_codetec . "' ORDER BY tecpr_date DESC";
            $row3 = $db->get_row($rech3, ARRAY_A);
            if ($row3) {
                extract($row3);
                $cout_rep += (round((($tecpr_couth / 3600) * $pdtlocr_durees) * 100) / 100);
            }

            $cout_rep+= $pdtlocr_mtp;
        }
    }
    if ($open == TRUE)
        $db->disconnect();
    return $cout_rep;
}

/**
 * Lecture d'une réparation
 *
 * @param $id
 * @param $code
 * @param bool $open
 * @return array|null
 */
function lit_enr_pdtlocr_id_in_pdtloc($id, $code, $open = TRUE)
{
    global
    $db;
    if ($open == TRUE)
        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
    $rexist = "SELECT * FROM `" . TBPDTLOCR . "` WHERE `pdtlocr_id` = '$id' AND `pdtlocr_codepdtloc` = '" . $db->escape($code) . "'";
    $row2 = $db->get_row($rexist, ARRAY_A);
    if ($open == TRUE)
        $db->disconnect();

    return $row2;
}
?>