<?php
/*=======================================================================
 *
 * inc_job.inc.php
 *
 * Autor: Marc Vollmann
 *
 *
 =======================================================================*/   


include_once ("../include/mcglobal.inc.php");
include_once ("../include/services_func.inc.php");
include_once ("../include/image.inc.php");
include_once ("../include/inc_group.inc.php");
include_once ("../include/inc_dbdata.inc.php");



// Returns an array with job IDs searched for jb.jb_id, tr.tr_commission_no and gdc.gdc_content with gdc.gdc_gen_fieldname = 'info_0'
function searchJobs ($searchItem) {
	 $retArray = array();
   if ($searchItem != "") :
      if (substr($searchItem,-2) == "/1" || substr($searchItem,-2) == "/2") :
         array_push($retArray, getJobIdSearchOutput($searchItem));
      else :
         $tmpId = getJobIdSearchOutput($searchItem . "/1");
         if ($tmpId != "" && is_numeric($tmpId) && strlen($tmpId) < 9) :
            array_push($retArray, $tmpId);
         endif;
         $tmpId = getJobIdSearchOutput($searchItem . "/2");
         if ($tmpId != "" && is_numeric($tmpId) && strlen($tmpId) < 9) :
            array_push($retArray, $tmpId);
         endif;
      endif;
      // Check commission no
      $tmpArray = getColVectorFromDB2ArrayByClause("tour", "jb_id", "tr_commission_no = '" . $searchItem . "'", "", "", "");
      if (count($tmpArray) > 0) :
         $retArray = array_merge($retArray, $tmpArray);
      endif;
      // Check GDC
      $tmpArray = getColVectorFromDB2ArrayByClause("genericdatacontainer", "gdc_obj_id", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_search' AND gdc_content = '" . $searchItem . "'", "", "", "");
      if (count($tmpArray) > 0) :
         $retArray = array_merge($retArray, $tmpArray);
      endif;
      $tmpArray = getColVectorFromDB2ArrayByClause("genericdatacontainer", "gdc_obj_id", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_0' AND gdc_content = '" . $searchItem . "'", "", "", "");
      if (count($tmpArray) > 0) :
         $retArray = array_merge($retArray, $tmpArray);
      endif;
   endif;
   return $retArray;
}

// Gets last (youngest) job ID
function getLastJob ($objId, $objType = "cs", $noStorno = "1", $specialClause = "") {
  $retVal = "";
  if ($objId != "" && is_numeric($objId)) :
     $whereClause = "";
     if ($objType == "cmp.cs" || $objType == "cmp") : 
        $objId = getFieldValueFromId("customer", "cmp_id", $objId, "cs_id");
        $objType = "cs";
     endif;
     if ($objType == "cmp.cr") : 
        $objId = getFieldValueFromId("courier", "cmp_id", $objId, "cr_id");
        $objType = "cr";
     endif;
     if ($objType == "cs") :
        $cscIdArray = getColVectorFromDB2ArrayByClause("costcenter", "csc_id", "cs_id = '" . $objId . "'", "", "", "");
        if (count($cscIdArray) > 0) :
           $whereClause = " csc_id_payer IN (" . implode(",",$cscIdArray) . ") ";
        endif;
     endif;
     if ($objType == "csc") : 
        $whereClause = " csc_id_payer = '" . $objId . "' ";
     endif;
     if ($objType == "cr") : 
        $whereClause = " cr_id = '" . $objId . "' ";
     endif;
     if ($noStorno == "1") :
        $whereClause .= " AND (isnull(jb_storno) OR jb_storno = '0' OR jb_storno = '1') ";
     endif;
     if ($specialClause != "") :
        $whereClause .= " AND " . $specialClause;
     endif;
     $retVal = getOneStmt("SELECT jb_id FROM job WHERE " . $whereClause . " ORDER BY jb_id DESC LIMIT 0,1", "jb_id");
  endif;
  return $retVal;
}

// Gets the total weight of all articles of a job
function getTratTotalweight ($jbId, $trSort = "") {
  global $db, $PHP_SELF;
  $retVal = 0;
  if ($jbId != "" && is_numeric($jbId)) :
     // Get data from the job
     $whereClause = "";
     if ($trSort != "" && is_numeric($trSort)) : $whereClause .= " AND trat.tr_sort = '" . $trSort . "' "; endif;
     $sqlquery = "SELECT SUM(trat.trat_weight) AS weight FROM tourarticle AS trat WHERE trat.jb_id = '" . $jbId . "'" . $whereClause;
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           if ($row["weight"] != "" && $row["weight"] != "0") :
              $retVal = $row["weight"];
           endif;
     endwhile;
     $result->free();
  endif;
  return $retVal;
}

// Gets the sum of packing pieces of all articles of a job
function getTratPackingPieces ($jbId, $trSort = "") {
  global $db, $PHP_SELF;
  $retVal = 0;
  if ($jbId != "" && is_numeric($jbId)) :
     // Get data from the job
     $whereClause = "";
     if ($trSort != "" && is_numeric($trSort)) : $whereClause .= " AND trat.tr_sort = '" . $trSort . "' "; endif;
     $sqlquery = "SELECT SUM(trat.trat_packingpieces) AS packingpieces FROM tourarticle AS trat WHERE trat.jb_id = '" . $jbId . "'" . $whereClause;
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           if ($row["packingpieces"] != "" && $row["packingpieces"] != "0") :
              $retVal = $row["packingpieces"];
           endif;
     endwhile;
     $result->free();
  endif;
  return $retVal;
}

// Gets customer group
function getCustomerGroupIdFromJob ($jbId, $cscId = "", $cscFieldMode = "") {
  global $db, $PHP_SELF;
  $retVal = "";
  if ($jbId != "" && is_numeric($jbId) && $cscId == "") :
     $cscField = "csc_id_related";
     if ($cscFieldMode == "1") :
        $cscField = "csc_id_payer";
     endif;
     $cscId = getFieldValueFromId("job", "jb_id", $jbId, $cscField);  // Get the requested costcenter ID of the job
  endif;
  if ($cscId != "" && is_numeric($cscId)) :
     $csId = getFieldValueFromId("costcenter", "csc_id", $cscId, "cs_id");  // Get "cs_id" of the related costcenter
     $grpStr = getFieldValueFromId("customer", "cs_id", $csId, "cs_group");  // Get (static) group of the customer
     if ($grpStr != "") :
        $grpArray = spliti(",", $grpStr);
        $retVal = $grpArray[1];  // Because of first sign of $tmpGrpStr is "," take array element with index "1" (and not "0")
     endif;
  endif;
  return $retVal;
}

// Gets associated articles of a special station of a job in "tourarticle"
function getTratArticles ($jbId, $trSort = "", $specialWhereClause = "") {
  global $db, $PHP_SELF;
  $retArray = array();
  if ($jbId != "" && is_numeric($jbId)) :
     $whereClause = "";
     if ($trSort != "" && is_numeric($trSort)) : $whereClause .= " AND trat.tr_sort = '" . $trSort . "' "; endif;
     if ($specialWhereClause != "") : $whereClause .= " AND " . $specialWhereClause . " "; endif;
     /* Article has to exist in table "article"
     $sqlquery = "SELECT trat.trat_id, trat.tr_id, trat.at_id, trat.trat_quantity, trat.trat_price, trat.trat_sort, trat.trat_packingpieces, trat.trat_weight, trat.trat_int_serialno, trat.trat_serialno, trat.trat_state, trat.trat_remark, at.at_name, at.at_description"
               . "  FROM article AS at, tourarticle AS trat"
               . "  WHERE trat.jb_id = '" . $jbId . "' AND trat.at_id = at.at_id" . $whereClause
               . "  ORDER BY trat.tr_sort, trat.trat_sort";
     */
     // ATTENTION: Data from "tourarticle" ONLY, MAPPING trat.trat_serialno => trat.trat_name, trat.trat_remark => trat.trat_description !!!!
     $sqlquery = "SELECT trat.trat_id, trat.tr_id, trat.at_id, trat.trat_quantity, trat.trat_price, trat.trat_sort, trat.trat_packingpieces, trat.trat_weight, trat.trat_int_serialno, trat.trat_serialno, trat.trat_state, trat.trat_remark,"
               . "       trat.trat_serialno, trat.trat_name, trat.trat_remark AS trat_description" 
               . "  FROM tourarticle AS trat"
               . "  WHERE trat.jb_id = '" . $jbId . "'" . $whereClause
               . "  ORDER BY trat.tr_sort, trat.trat_sort";
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $retArray[] = array($row["at_id"], $row["trat_quantity"], $row["trat_sort"], $row["trat_packingpieces"], $row["trat_serialno"], $row["trat_state"], $row["trat_remark"], $row["trat_price"], $row["trat_name"], $row["trat_description"], $row["trat_weight"], $row["trat_id"], $row["tr_id"], $row["trat_int_serialno"]);
     endwhile;
     $result->free();     
  endif;
  return $retArray;
}

// Gets associated articles of a special station of a job in "tourarticle"
function getValueOfGoodsOfTratArticles ($atArray, $cDateTime, $grpId, $csId, $mtSort = "", $mode = 0) {
  global $db, $PHP_SELF;
  $retVal = 0;
  if ($atArray != "" && is_array($atArray)) :
     $atArrayLen = count($atArray);
     for ($i = 0; $i < $atArrayLen; $i++) :
         // Try to get price from "articleprice" for this article
         $tmpAtPrice = "";
         $atId = $atArray[$i][0];
         $tratQuantity = $atArray[$i][1];
         if ($mtSort != "") :
            if ($csId != "") :
               $tmpAtPrice = getArticleServiceValues($atId, $cDateTime, "", $csId, $mtSort, $mode);     // Check for article SPECIAL price of the SPECIAL customer
            endif;
            if (($tmpAtPrice == "" || $tmpAtPrice == 0) && $grpId == "") :
               $tmpAtPrice = getArticleServiceValues($atId, $cDateTime, $grpId, "", $mtSort, $mode);    // Check for article SPECIAL group price
            endif;
         endif;
         if (($tmpAtPrice == "" || $tmpAtPrice == 0) && $csId != "") :
            $tmpAtPrice = getArticleServiceValues($atId, $cDateTime, "", $csId, "", 0);                 // Check for article STANDARD price of the SPECIAL customer
         endif;
         if (($tmpAtPrice == "" || $tmpAtPrice == 0) && $grpId != "") :
            $tmpAtPrice = getArticleServiceValues($atId, $cDateTime, $grpId, "", "", "", 0);            // Check for article STANDARD group price
         endif;
         if ($tmpAtPrice != "" && is_numeric($tmpAtPrice)) :
            if ($tratQuantity != "" && is_numeric($tratQuantity)) :
               $tmpAtPrice *= $tratQuantity;
            endif;
            $retVal += $tmpAtPrice;
         endif;
     endfor;
  endif;
  return $retVal;
}

// Gets output of tourarticle data for a sepecified job
function getOutputJobTratArticleData ($jb_id, $noTitle = "", $noHeadline = "", $noSummation = "", $noDefaultCols = "", $trSort = "") {
  global $db, $PHP_SELF;
  global $hq_id;
  $retVal = "";
  if ($jb_id != "" && is_numeric($jb_id)) :
    $outputTourarticle = "";
    if ($trSort == "") : $trSort = "2"; endif;
    $tratArray = getTratArticles($jb_id, $trSort);
    $tratArrayLen = count($tratArray);
    if ($tratArrayLen > 0) :
       if ($noTitle == "") :
          $outputTourarticle .= "<span class=\"f10bp1\"><b>" . getLngt("Artikel") . "</b></span><br>";
       endif;

       // Parameter for displaying scan events
       $parOutputArticleScanEvents = getParameterValue("0", "MASK_JOBDETAILS_ARTICLE_SCAN_EVENTS", $hq_id);
       if ($parOutputArticleScanEvents == "") : $parOutputArticleScanEvents = getParameterValue("0", "MASK_JOBDETAILS_ARTICLE_SCAN_EVENTS", "0"); endif;

       // Headline
       if ($noHeadline == "") :
          $parOutputArticlesHeadline = getParameterValue("0", "MASK_JOBDETAILS_ARTICLE_HEADLINE", $hq_id);
          if ($parOutputArticlesHeadline == "") : $parOutputArticlesHeadline = getParameterValue("0", "MASK_JOBDETAILS_ARTICLE_HEADLINE", "0"); endif;
          if ($parOutputArticlesHeadline == "") : 
             $parOutputArticlesHeadline = getLngt("ID,Menge,Sortierung,Packstücke,Seriennummer,Status,Bemerkung,Preis,Nummer,Artikelbeschreibung,Gewicht");
          endif;
          if ($parOutputArticleScanEvents == "1") : $parOutputArticlesHeadline .= ",Auslieferstatus"; endif;
          $parOutputArticlesHeadlineArray = spliti(",", $parOutputArticlesHeadline);
       endif;

       // Body with articles
       $parOutputArticles = getParameterValue("0", "MASK_JOBDETAILS_ARTICLES", $hq_id);
       if ($parOutputArticles == "") : $parOutputArticles = getParameterValue("0", "MASK_JOBDETAILS_ARTICLES", "0"); endif;
       if ($parOutputArticles == "" && $noDefaultCols == "") : 
          $parOutputArticles = "9,8,1,10,3,7";  // Default cols (at_description, at_name, trat_quantity, trat_weight, trat_packingpieces, trat_price)
       endif;
       if ($parOutputArticleScanEvents == "1") : 
          if ($parOutputArticles != "") : $parOutputArticles .= ","; endif;
          $parOutputArticles .= "4,99";
       endif;
       $parOutputArticlesArray = spliti(",", $parOutputArticles);
       $parOutputArticlesArrayLen = count($parOutputArticlesArray);

       $outputTourarticle .= "<table>";
       // Output headline
       if ($noHeadline == "") :
          // $outputTourarticle .= "<tr><td><b>" . getLngt("Artikelbeschreibung") . "&nbsp;</b></td><td><b>" . getLngt("Nummer") . "&nbsp;</b></td><td><b>" . getLngt("Menge") . "&nbsp;</b></td><td><b>" . getLngt("Gewicht") . "&nbsp;</b></td><td><b>" . getLngt("Packstücke") . "&nbsp;</b></td><td><b>" . getLngt("Preis") . "&nbsp;</b></td></tr>";
          $outputTourarticle .= "<tr>";
          for ($j = 0; $j < $parOutputArticlesArrayLen; $j++) :
              $tmpVal = $parOutputArticlesArray[$j];  // !!!!
              $outputTourarticle .= "<td><b>" . getLngt($parOutputArticlesHeadlineArray[$tmpVal]) . "&nbsp;</b></td>";
          endfor;
          $outputTourarticle .= "</tr>";
       endif;

       // Output body with articles
       $sumOfTratPackingPieces = 0;
       $sumOfTratWeight = 0;
       $sumOfTratPrice = 0;
       for ($i = 0; $i < $tratArrayLen; $i++) :
           $outputTourarticle .= "<tr>";
           /* STATIC OUTPUT
           $outputTourarticle .= "<td>" . substr($tratArray[$i][9], 0, 50) . "&nbsp;</td>";                                    // at_description
           $outputTourarticle .= "<td>" . $tratArray[$i][8] . "</td>";                                                         // at_name
           $outputTourarticle .= "<td align=\"center\">" . $tratArray[$i][1] . "</td>";                                        // trat_quantity
           $outputTourarticle .= "<td align=\"right\">" . number_format(round($tratArray[$i][10], 2), 2, ",", ".") . "</td>";  // trat_weight
           $outputTourarticle .= "<td align=\"center\">" . $tratArray[$i][3] . "</td>";                                        // trat_packingpieces
           $outputTourarticle .= "<td align=\"right\">" . number_format(round($tratArray[$i][7], 2), 2, ",", ".") . "</td>";   // trat_price
           */
           for ($j = 0; $j < $parOutputArticlesArrayLen; $j++) :
               $tmpVal = $parOutputArticlesArray[$j];
               if ($tmpVal != "") :
                  if ($tmpVal == "9") :
                     $outputTourarticle .= "<td>" . substr($tratArray[$i][$tmpVal], 0, 50) . "&nbsp;</td>";
                  elseif ($tmpVal == "8") :
                     $outputTourarticle .= "<td>" . $tratArray[$i][$tmpVal] . "</td>";
                  elseif ($tmpVal == "7" || $tmpVal == "10") :
                     $outputTourarticle .= "<td align=\"right\">" . number_format(round($tratArray[$i][$tmpVal], 2), 2, ",", ".") . "</td>";
                  elseif ($tmpVal == "99") :
                     $tratpState = getFieldValueFromId("tourarticleprocess", "trat_id", $tratArray[$i][11], "tratp_state");
                     // $outputTourarticle .= "<td>" . ($tratpState == "1" ? getLngt("OK") : getLngt("Nicht&nbsp;OK")) . "</td>";
                     // $outputTourarticle .= "<td>" . ($tratpState == "1" ? "&nbsp;&nbsp;" . getLngt("OK") : "") . "</td>";
                  else :
                     $outputTourarticle .= "<td align=\"center\">" . $tratArray[$i][$tmpVal] . "</td>";
                  endif;
               endif;
           endfor;
           $outputTourarticle .= "</tr>";
           
           $sumOfTratPackingPieces += $tratArray[$i][3];
           $sumOfTratPrice += $tratArray[$i][7];
           $sumOfTratWeight += $tratArray[$i][10];
       endfor;
       if ($noSummation == "") :
          $outputTourarticle .= "<tr>";
          $outputTourarticle .= "<td colspan=\"2\"><b>" . getLngt("Gesamtanzahl Packstücke") . "&nbsp;:&nbsp;" . $sumOfTratPackingPieces . "</b></td>";
          $outputTourarticle .= "<td colspan=\"4\" align=\"right\"><b>" . getLngt("Gesamtwarenwert") . "&nbsp;:&nbsp;" . number_format(round($sumOfTratPrice, 2), 2, ",", ".") . "</b></td>";
          $outputTourarticle .= "</tr>";
          $outputTourarticle .= "<tr>";
          $outputTourarticle .= "<td colspan=\"2\"><b>" . getLngt("Gesamtgewicht") . "&nbsp;:&nbsp;" . number_format(round($sumOfTratWeight,2), 2, ",", ".") . "</b></td>";
          $outputTourarticle .= "</tr>";
          // Check for additional article info in GDC
          $gdcContentJbAddedInfo = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jb_id . "' AND gdc_gen_fieldname = 'jb_addinfo'");
          if ($gdcContentJbAddedInfo) :
             $outputTourarticle .= "<tr>";
             $outputTourarticle .= "<td colspan=\"6\"><br><br><b>" . nl2br($gdcContentJbAddedInfo) . "</b></td>";
             $outputTourarticle .= "</tr>";
          endif;
       endif;
       $outputTourarticle .= "</table>";
       $outputTourarticle .= "<br>";
    endif;
    $retVal = $outputTourarticle;
  endif;
  return $retVal;
}

// Gets calculator entries of a special station of a job in "jobcalculator"
function getCalculatorData ($jbId, $trSort = "", $indexValue = "", $mode = "") {
  global $db, $PHP_SELF;
  $retArray = array();
  if ($jbId != "" && is_numeric($jbId)) :
     $whereClause = "";
     if ($trSort != "" && is_numeric($trSort)) : $whereClause .= " AND jbc.tr_sort = '" . $trSort . "' "; endif;
     $sqlquery = "SELECT jbc.srv_name, jbc.jbc_totalprice, jbc.jbc_amount, jbc.jbc_price, jbc.srv_id, jbc.srvt_name"
               . "  FROM jobcalculator AS jbc"
               . "  WHERE jbc.jb_id = '" . $jbId . "'" . $whereClause
               . "  ORDER BY jbc.jb_id, jbc.tr_sort, jbc.srv_name";
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $count = 0;
     while ($row = $result->fetch_assoc()):
           if ($indexValue == "" || (is_numeric($indexValue) && $indexValue == $count)) :
              if ($mode == "1") :
                 $retArray["srv_name"] = $row["srv_name"];
                 $retArray["jbc_totalprice"] = $row["jbc_totalprice"];
                 $retArray["jbc_amount"] = $row["jbc_amount"];
                 $retArray["jbc_price"] = $row["jbc_price"];
                 $retArray["srv_id"] = $row["srv_id"];
                 $retArray["srvt_name"] = $row["srvt_name"];
              else :
                 $retArray[] = array($row["srv_name"], $row["jbc_totalprice"], $row["jbc_amount"], $row["jbc_price"], $row["srv_id"], $row["srvt_name"]);
              endif;
           endif;
           $count++;
     endwhile;
     $result->free();     
  endif;
  return $retArray;
}

// Gets calculator price
function getCalculatorPrice ($calcArray, $mode = 0) {
  global $db, $PHP_SELF;
  $retVal = 0;
  if ($calcArray != "" && is_array($calcArray)) :
     $calcArrayLen = count($calcArray);
     for ($i = 0; $i < $calcArrayLen; $i++) :
         // Get price for this calculator entry
         $jbcTotalprice = $calcArray[$i][1];
         $retVal += $jbcTotalprice;
     endfor;
  endif;
  return $retVal;
}

// Gets all price entries of a special job in "jobprice"
function getJobPriceData ($jbId, $mtSort = "", $indexValue = "", $mode = "") {
  global $db, $PHP_SELF;
  $retArray = array();
  if ($jbId != "" && is_numeric($jbId)) :
     $whereClause = "";
     if ($mtSort != "" && is_numeric($mtSort)) : $whereClause .= " AND jbprc.mt_sort = '" . $mtSort . "' "; endif;

     $sqlquery = "SELECT jbprc.mt_sort, mt.mt_value, mt.mt_mapped_value, jbprc.jbprc_price, jbprc.jbprc_remark, jbprc.jbprc_reference"
               . "  FROM jobprice AS jbprc, metatype AS mt"
               . "  WHERE jbprc.jb_id = '" . $jbId . "'" . $whereClause . " AND jbprc.mt_sort = mt.mt_sort AND mt.mt_type = 'job_price'"
               . "  ORDER BY jbprc.jb_id, jbprc.mt_sort";
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $count = 0;
     while ($row = $result->fetch_assoc()):
           if ($indexValue == "" || (is_numeric($indexValue) && $indexValue == $count)) :
              if ($mode == "1") :
                 $retArray["mt_sort"] = $row["mt_sort"];
                 $retArray["mt_value"] = $row["mt_value"];
                 $retArray["mt_mapped_value"] = $row["mt_mapped_value"];
                 $retArray["jbprc_price"] = $row["jbprc_price"];
                 $retArray["jbprc_remark"] = $row["jbprc_remark"];
                 $retArray["jbprc_reference"] = $row["jbprc_reference"];
              else :
                 $retArray[] = array($row["mt_sort"], $row["mt_value"], $row["mt_mapped_value"], $row["jbprc_price"], $row["jbprc_remark"], $row["jbprc_reference"]);
              endif;
           endif;
           $count++;
     endwhile;
     $result->free();     
  endif;
  return $retArray;
}

// Gets output of the job ID regarding the global mode of usage
function getJobIdOutput ($jbId, $jbIdParent = "") {
  global $db, $PHP_SELF, $globalParUseRelatedCustomer;
  $retOut = "";
  if ($jbId != "" && is_numeric($jbId)) :
     // Get global mode of usage
     if ($globalParUseRelatedCustomer == "") :
        $globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");
     endif;
     // Output of the job ID
     $retOut = $jbId;
     if ($globalParUseRelatedCustomer == "1") : 
        if ($jbIdParent == "" || !is_numeric($jbIdParent)) :
           $jbIdParent = getFieldValueFromId("job", "jb_id", $jbId, "jb_id_parent");
        endif;
        $retOut = $jbId . "/1";
        if ($jbIdParent != "" && $jbIdParent > 0) :
           $retOut = $jbIdParent . "/2";
        endif;
     endif;
  endif;
  return $retOut;
}

// Gets output of the job ID on the disposition drag bar
// (E.g. "20123" => "2"."<br>")
function getJobIdDragBarOutput ($jbIdOut, $stringLen = "", $delimiter = "<br>", $fontSize = "7", $fontCol = "blue") {
  $retOut = "";
  $jbIdOut = trim($jbIdOut);
  if ($stringLen != "" && is_numeric($stringLen)) :
     $jbIdOut = substr($jbIdOut,0,$stringLen);
  endif;
  if ($jbIdOut != "") :
     $retOut .= "<span style=\"font-size:" . $fontSize . "pt; color:" . $fontCol . "\">";
     $jbIdOutLen = strlen($jbIdOut);
     for ($j = 0; $j < $jbIdOutLen; $j++) :
         $retOut .= substr($jbIdOut,$j,1) . $delimiter;
     endfor;
     $retOut .= "</span>";
  endif;
  return $retOut;
}


// Gets real job number regarding the search item
function getJobIdSearchOutput ($searchItem) {
  global $db, $PHP_SELF, $globalParUseRelatedCustomer;
  $searchItem = trim($searchItem);
  if ($searchItem != "") :
     // Get global mode of usage
     if ($globalParUseRelatedCustomer == "") :
        $globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");
     endif;
     if ($globalParUseRelatedCustomer == "1") :
        if (substr($searchItem,-2) == "/1") :
           $searchItem = substr($searchItem,0,-2);
        endif;
        if (substr($searchItem,-2) == "/2") :
           $searchItem = substr($searchItem,0,-2);
           if (is_numeric($searchItem)) :
              $searchItem = getFieldValueFromId("job", "jb_id_parent", $searchItem, "jb_id");
           endif;
        endif;
     endif;
  endif;
  $retVal = $searchItem;
  return $retVal;
}


// Gets parent cascade level
function getJobParentCascadeLevel ($jbId, $retLevel = 0) {
	if ($jbId != "" && is_numeric($jbId)) :
     $jbIdParent = getFieldValueFromId("job", "jb_id", $jbId, "jb_id_parent");
     if ($jbIdParent != "" && $jbIdParent > 0) :
        $retLevel = getJobParentCascadeLevel($jbId, ($retLevel + 1));
     endif;
  endif;
  return $retLevel;
}


// Get an array of timeunit chunks according to parameters
// E.g. getNumericChunksBySplit(120, 48) => array(48,48,24)
function getNumericChunksBySplit ($value, $chunkLength) {
	global $hq_id;
  $retArray = array();
  if ($value != "" && is_numeric($value) && $chunkLength != "" && is_numeric($chunkLength)) :
     $count = floor($value / $chunkLength);
     for ($i = 0; $i <= $count; $i++) :
         if ($value > $chunkLength) :
            $retArray[$i] = $chunkLength;
            $value -= $chunkLength;
         elseif ($value == $chunkLength) :
            $retArray[$i] = $value;
            break;
         else :
            $retArray[$i] = $value;
         endif;
     endfor;
  endif;
  return $retArray;
}


// Check job having more time units than the defined maximum from parameter of the related customer
// Returns an array. If jb_timeunits of the job e.g. equals 116 than the array will be filled with:
// Day 0 <=> Day of the begin of the job <=> retArray[0] = 48 (e.g. $csRelatedMaxTimeunitsService = 48)
// Day 1 <=> Day of the begin of the job <=> retArray[1] = 48 (e.g. $csRelatedMaxTimeunitsService = 48)
// Day 2 <=> Day of the begin of the job <=> retArray[2] = 20 (rest of example with 116)
function getMultipleDayJobTimeUnitsPerDay ($jbId, $csId = "") {
	global $hq_id;
  $retArray = array();
  if ($jbId != "" && is_numeric($jbId)) :
     // Get related customer if needed
     if ($csId == "" || $csId == "0") :
        $cscIdRelated = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_related");
        $csId = getFieldValueFromId("costcenter", "csc_id", $cscIdRelated, "cs_id");
     endif;
     // Get number of maximum timeunits of the whole day
     // $numOfTimeUnitsOfTheSelectedDay = getNumOfTimeUnitsBetweenInterval($csId);
     // Get number of time units of the related customer        
     $csRelatedMaxTimeunitsService = getObjectBasedParameterValue("JB_SERVICE_INSTALLAION_MAX_TIMEUNITS", $csId, $hq_id);
     if ($csRelatedMaxTimeunitsService == "") : $csRelatedMaxTimeunitsService = 48; endif;  // Standard fallback
     // Get number of time units of the current job
     $jbTimeunits = getFieldValueFromId("job", "jb_id", $jbId, "jb_timeunits");
     if ($jbTimeunits != "" && is_numeric($jbTimeunits)) :
        $retArray = getNumericChunksBySplit($jbTimeunits, $csRelatedMaxTimeunitsService);
     endif;
  endif;
  return $retArray;
}


// If job is an installation job AND at least one child job does exist, then the current job is a multiple day job
/*
function isMultipleDayJob ($jbId, $csId = "") {
  $retVal = "0";
  if ($jbId != "" && is_numeric($jbId)) :
     // Get service of the job
     $jbService = getFieldValueFromId("job", "jb_id", $jbId, "jb_service");
     if (($jbService & 2) == 2) :
        // Get child ID
        $jbIdChild = getFieldValueFromId("job", "jb_id_parent", $jbId, "jb_id");
        if ($jbIdChild != "" && is_numeric($jbIdChild)) :
           $retVal = "1";
        endif;
     endif;
  endif;
  return $retVal;
}
*/


// Check job having more time units than the defined maximum from parameter of the related customer
function isMultipleDayJob ($jbId, $csId = "") {
	global $hq_id;
  $retVal = "0";
  if ($jbId != "" && is_numeric($jbId)) :
     // Get service of the job
     // $jbService = getFieldValueFromId("job", "jb_id", $jbId, "jb_service");
     // if (($jbService & 2) == 2) :
        // [1.] Check for current representation in FDS being a job for multiple days
        $dayArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "LEFT(vhd_timeslot,10) AS day", "jb_id = '" . $jbId . "'", "", "", "DISTINCT");
        $dayArrayLen = count($dayArray);
        if ($dayArrayLen >= 2) :
           $retVal = "1";
        endif;

        // [2.] Check for time units being a job for multiple days
        if ($retVal == "0") :
           $daysWithJobTimeUnitsArray = getMultipleDayJobTimeUnitsPerDay($jbId, $csId);
           $daysWithJobTimeUnitsArrayLen = count($daysWithJobTimeUnitsArray);
           if ($daysWithJobTimeUnitsArrayLen > 1) :
              // The array has more than one element and thefore the job involves more days
              $retVal = "1";
           endif;
        endif;
     // endif;
  endif;
  return $retVal;
}


// Gets sales tax rate for a special job
function getSalesTaxFactor ($jb_id) {
  global $db, $PHP_SELF;
  $taxFactor = 1.19;  // Init
  if ($jb_id != "" && is_numeric($jb_id)) :
     // Get tax value associated to the job
     $jbTxId = getFieldValueFromId("job", "jb_id", $jb_id, "jb_sales_tax_rate");
     if ($jbTxId != "" && $jbTxId != 0) :
        $jbTxValue = getFieldValueFromId("tax", "tx_id", $jbTxId, "tx_value");
        if ($jbTxValue != "" && is_numeric($jbTxValue)) :
           $taxFactor = 1 + ($jbTxValue / 100);
        endif;
     endif;
  endif;
  return $taxFactor;
}


// Gets output of jobcalculator data for a sepecified job
function getOutputJobCalculatorData ($jb_id, $noTitle = "") {
  global $db, $PHP_SELF;
  $retVal = "";
  if ($jb_id != "" && is_numeric($jb_id)) :
     // Get tax value assotiated to the job
     $taxFactor = getSalesTaxFactor($jb_id);
     
     $jbcArray = getCalculatorData($jb_id, "2");
     $jbcArrayLen = count($jbcArray);
     if ($jbcArrayLen > 0) :
        if ($noTitle == "") :
           $outputJobcalculator .= "<span class=\"f10bp1\"><b>" . getLngt("Rechnungsposten") . "</b></span><br>";
        endif;
        $outputJobcalculator .= "<table>";
        $outputJobcalculator .= "<tr><td><b>" . getLngt("Posten") . "&nbsp;</b></td><td><b>" . getLngt("Anzahl") . "&nbsp;</b></td><td><b>" . getLngt("Preis") . "&nbsp;</b></td><td><b>" . getLngt("Gesamtpreis") . "&nbsp;</b></td></tr>";
        $sumOfJbcTotalprice = 0;
        for ($i = 0; $i < $jbcArrayLen; $i++) :
            $outputJobcalculator .= "<tr>";
 	          $outputJobcalculator .= "<td>" . substr($jbcArray[$i][0], 0, 50) . "</td>";                                         // jbc.srv_name
            $outputJobcalculator .= "<td>" . $jbcArray[$i][2] . "</td>";                                                        // jbc.jbc_amount
            $outputJobcalculator .= "<td align=\"right\">" . number_format(round(($jbcArray[$i][3] * $taxFactor), 2), 2, ",", ".") . "</td>";  // jbc.jbc_price
            $outputJobcalculator .= "<td align=\"right\">" . number_format(round(($jbcArray[$i][1] * $taxFactor), 2), 2, ",", ".") . "</td>";  // jbc.jbc_totalprice
            $outputJobcalculator .= "</tr>";
     
            $sumOfJbcTotalprice += $jbcArray[$i][1];
        endfor;
        $outputJobcalculator .= "<tr>";
        $outputJobcalculator .= "<td colspan=\"4\" align=\"right\"><b>" . getLngt("Gesamt") . "&nbsp;:&nbsp;" . number_format(round(($sumOfJbcTotalprice * $taxFactor), 2), 2, ",", ".") . "</b></td>";
        $outputJobcalculator .= "</tr>";
        $outputJobcalculator .= "</table>";
        $outputJobcalculator .= "<br>";
     endif;
     $retVal = $outputJobcalculator;
  endif;
  return $retVal;
}


// Gets output of jobcalculator data for a sepecified job
function getOutputJobPriceData ($jb_id, $noTitle = "", $showZeroPrice = "") {
  global $db, $PHP_SELF;
  $retVal = "";
  if ($jb_id != "" && is_numeric($jb_id)) :
     // Get tax value assotiated to the job
     $taxFactor = getSalesTaxFactor($jb_id);
     $jbprcArray = getJobPriceData($jb_id);
     $jbprcArrayLen = count($jbprcArray);
     if ($jbprcArrayLen > 0) :
        if ($noTitle == "") :
           $outputJobcalculator .= "<span class=\"f10bp1\"><b>" . getLngt("Beträge zum Auftrag") . "</b></span><br>";
        endif;
        $outputJobcalculator .= "<table>";
        $outputJobcalculator .= "<tr><td><b>" . getLngt("Preiskategorie") . "&nbsp;</b></td><td><b>" . getLngt("Service") . "&nbsp;</b></td><td><b>" . getLngt("Preis") . "&nbsp;</b></td></tr>";
        $sumOfjbprcTotalprice = 0;
        $remMtSort = $jbprcArray[0][0];
        for ($i = 0; $i < $jbprcArrayLen; $i++) :
            if ($jbprcArray[$i][3] != 0 || $showZeroPrice != "") :

               if ($remMtSort != $jbprcArray[$i][0]) :
                  $outputJobcalculator .= "<tr><td colspan=\"2\" align=\"right\">" . getLngt("Summe") . "</td><td align=\"right\"><b>" . number_format(round(($sumOfjbprcTotalprice * $taxFactor), 2), 2, ",", ".") . "</b></td></tr>";
                  $remMtSort = $jbprcArray[$i][0];
                  $sumOfjbprcTotalprice = 0;
               endif;

               $outputJobcalculator .= "<tr>";
               $outputJobcalculator .= "<td>" . $jbprcArray[$i][2] . "</td>";  // mt.mt_mapped_value
               $outputJobcalculator .= "<td>" . $jbprcArray[$i][4] . "</td>";  // jbprc.jbprc_remark
               $outputJobcalculator .= "<td align=\"right\">" . number_format(round(($jbprcArray[$i][3] * $taxFactor), 2), 2, ",", ".") . "</td>";  // jbprc.jbprc_price
               $outputJobcalculator .= "</tr>";

               $sumOfjbprcTotalprice += $jbprcArray[$i][3];
            endif;
        endfor;
        $outputJobcalculator .= "<tr><td colspan=\"2\" align=\"right\">" . getLngt("Summe") . "</td><td align=\"right\"><b>" . number_format(round(($sumOfjbprcTotalprice * $taxFactor), 2), 2, ",", ".") . "</b></td></tr>";

        // $outputJobcalculator .= "<tr>";
        // $outputJobcalculator .= "<td colspan=\"4\" align=\"right\"><b>" . getLngt("Gesamt") . "&nbsp;:&nbsp;" . number_format(round(($sumOfjbprcTotalprice * $taxFactor), 2), 2, ",", ".") . "</b></td>";
        // $outputJobcalculator .= "</tr>";
        $outputJobcalculator .= "</table>";
        $outputJobcalculator .= "<br>";
     endif;
     $retVal = $outputJobcalculator;
  endif;
  return $retVal;
}


// Output of sign image out of a given sign vector
function getSignImageFromVectordata ($signVectorData, $mode = "") {
  $retData = "";
  if ($signVectorData != "") :
     $rawCoord = splitRawCoordinates ($signVectorData);
     $maxCoord = checkMaxCoordinates($rawCoord);

     if ($mode == "1") :
        // Output for mail
        $tmpSignPath = "../temp/signs/";
        if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;                   
        $imgFilename = $tmpSignPath . md5(rand(0,10000)) . ".png";
        $im = createSignImage($rawCoord);
        imagepng ($im, $imgFilename);

        $retData = "<img src=\"" . $imgFilename . "\" border=\"0\" height=\"" . $maxCoord[1] . "\" width=\"" . $maxCoord[0] . "\">";
     else :
        // Output for web page
        $retData = "<img src=\"../include/image_create.php?signVectorData=" . $signVectorData . "\" border=\"0\" height=\"" . $maxCoord[1] . "\" width=\"" . $maxCoord[0] . "\">";
     endif;
  endif;
  return $retData;
}


// Gets output of article acceptance data for a sepecified job
function getOutputArticleAcceptanceData ($jb_id, $noTitle = "") {
  global $db, $PHP_SELF;
  $retVal = "";
  if ($jb_id != "" && is_numeric($jb_id)) :

     $outputData = "";
     $dataArray = getColVectorFromDB2ArrayByClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jb_id . "' AND gdc_gen_fieldname = 'article_acceptance'", "", "gdc_content", "");
     $dataArrayLen = count($dataArray);
     if ($dataArrayLen > 0) :
        if ($noTitle == "") :
           $outputData .= "<span class=\"f10bp1\"><b>" . getLngt("Gefahrenübergänge") . "</b></span><br>";
        endif;
        $outputData .= "<table>";
        $outputData .= "<tr><td><b>" . getLngt("Scan-Zeitpunkt") . "&nbsp;</b></td><td><b>" . getLngt("Verantwortlicher") . "&nbsp;</b></td><td><b>" . getLngt("Scan-Code") . "&nbsp;</b></td><td><b>" . getLngt("Unterschrift") . "&nbsp;</b></td></tr>";
        for ($i = 0; $i < $dataArrayLen; $i++) :
            $contentString = trim($dataArray[$i]);            
            if ($contentString != "") :
               $contentString = str_replace("|", "-,-", $dataArray[$i]);
               if (!(strpos($contentString, "-,-") === FALSE)) :
                  $contentArray = spliti("-,-",$contentString);
               endif;
               $outputData .= "<tr>";
               $tmpTime = $contentArray[0];
               $tmpTime = substr($tmpTime,6,2) . "." . substr($tmpTime,4,2) . "." . substr($tmpTime,0,4) . " " . substr($tmpTime,8,2) . ":" . substr($tmpTime,10,2) . ":" . substr($tmpTime,12,2);
               $outputData .= "<td>" . $tmpTime . "</td>";  // Scan time
               $tmpUsrId = $contentArray[1];
               $tmpUserData = "";
               if ($tmpUsrId != "" && is_numeric($tmpUsrId) && $tmpUsrId > 0) :
                  $tmpUserData = getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_name") . ", &nbsp;" . getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_firstname");
               endif;
               $outputData .= "<td>" . $tmpUserData . "</td>";  // User data
               $outputData .= "<td>" . $contentArray[3] . "</td>";  // Scan code
               $outputData .= "<td>" . getSignImageFromVectordata($contentArray[2]) . "</td>";  // Sign image data
               $outputData .= "</tr>";
            endif;
        endfor;
        $outputData .= "</table>";
     endif;
     $retVal = $outputData;
  endif;
  return $retVal;
}


// Gets associated payments (of a special station) of a job in "jobpayment"
function getPaymentsReceived ($jbId, $trSort = "") {
  global $db, $PHP_SELF;
  $retArray = array();
  if ($jbId != "" && is_numeric($jbId)) :
     $whereClause = "";
     if ($trSort != "" && is_numeric($trSort)) : $whereClause .= " AND jbp.tr_sort = '" . $trSort . "' "; endif;
     $sqlquery = "SELECT jbp.tr_sort, jbp.csc_id, jbp.jbp_mode, jbp.jbp_price, jbp.jbp_bookingtime, jbp.jbp_export_time, jbp.jbp_counter, jbp.jbp_id, jbp.jb_id, jbp.jbpc_id, jbp.jbp_tan"
               . "  FROM jobpayment AS jbp"
               . "  WHERE jbp.jb_id = '" . $jbId . "'" . $whereClause
               . "  ORDER BY jbp.jbp_bookingtime, jbp.jbp_export_time";
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $retArray[] = array($row["tr_sort"], $row["csc_id"], $row["jbp_mode"], $row["jbp_price"], $row["jbp_bookingtime"], $row["jbp_export_time"], $row["jbp_counter"], $row["jbp_id"], $row["jb_id"], $row["jbpc_id"], $row["jbp_tan"]);
     endwhile;
     $result->free();     
  endif;
  return $retArray;
}


// Gets sum of associated payments (of a special station) of a job in "jobpayment"
function getSumOfPaymentsReceived ($jbId, $trSort = "") {
  global $db, $PHP_SELF;
  $retVal = 0;
  if ($jbId != "" && is_numeric($jbId)) :
     $paymentsReceived = getPaymentsReceived($jbId, $trSort);
     $paymentsReceivedLen = count($paymentsReceived);
     for ($i = 0; $i < $paymentsReceivedLen; $i++) :
         $retVal += $paymentsReceived[$i][3];
     endfor;
  endif;
  return $retVal;
}


// Gets open volume of a single job. Payments will be compared with the total volume required
// Returns net or gross value
function getOpenPaymentValue ($jbId, $trSort = "", $grossValue = "") {
  global $db, $PHP_SELF;
  $retVal = "";
  if ($jbId != "" && is_numeric($jbId)) :
     $paymentsReceived = getSumOfPaymentsReceived($jbId, $trSort);
     $jbTotalPrice = getFieldValueFromId("job", "jb_id", $jbId, "jb_totalprice");
     if ($paymentsReceived != "" && is_numeric($paymentsReceived) && $jbTotalPrice != "" && is_numeric($jbTotalPrice)) :
        $retVal = $jbTotalPrice - $paymentsReceived;
        if ($grossValue == "1") :
           $taxFactor = getSalesTaxFactor($jbId);
           $retVal *= $taxFactor;
        endif;
        $retVal = round($retVal,2);
     endif;
  endif;
  return $retVal;
}


// Gets daytime interval (e.g. daytime = "0" => "08:00 - 12:00")
function getDaytimeTimeInterval ($timeStamp, $csId) {
	$retVal = "";
	if ($timeStamp != "" && $csId != "" && is_numeric($csId)) :
     $daytimeTimeInterval = metatypeGetMappedValues("day_time", "", $csId, "cs", "1");
     $daytimeTimeIntervalLen = count($daytimeTimeInterval);
     $currDay = substr($timeStamp,0,10);
     $currTime = substr($timeStamp,11);
     $dayTime = 0;
     for ($k = 0; $k < $daytimeTimeIntervalLen; $k++) :
         if ($daytimeTimeInterval[$k][0] <= $currTime && $currTime < $daytimeTimeInterval[$k][1]) :
             $dayTime = $k;
             break;
         endif;
     endfor;
     // Get mapped value of the day time (clock time)
     $retVal = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "' AND mt_sort = '" . $dayTime . "'");
  endif;
  return $retVal;
}

// Gets daytime interval for a special job (e.g. daytime = "0" => "08:00 - 12:00")
function getJobDaytimeTimeInterval($timeStamp, $originaldaytimeText, $csId, $jbId) {
	$retVal = "";
	if (($timeStamp != "" || $jbId != "") && $csId != "" && is_numeric($csId)) :
	   if ($jbId != "") :
	      $timeStamp = getFieldValueFromId("job", "jb_id", $jbId, "jb_ordertime");
	      $originaldaytimeText = getFieldValueFromId("job", "jb_id", $jbId, "jb_freetext_1");
	   endif;
	   if (substr($timeStamp,-8) == "00:00:01") :
	      $retVal = $originaldaytimeText;
	   else :
	      $retVal = getDaytimeTimeInterval($timeStamp, $csId);
	   endif;
  endif;
  return $retVal;
}

// Gets computed time interval from timestamp
function getComputedTimeInterval ($timeStamp, $csId, $minusOffsetInSec = "", $plusOffsetInSec = "") {
  $retArray = array();
  if ($timeStamp != "" && $csId != "" && is_numeric($csId)) :
     if ($minusOffsetInSec == "" || !is_numeric($minusOffsetInSec)) : $minusOffsetInSec = 7200; endif;
     if ($plusOffsetInSec == "" || !is_numeric($plusOffsetInSec)) : $plusOffsetInSec = 7200; endif;
  
     // Get earlies clock time to start the interval
     $dayTimeMappedValues = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "", "", "mt_sort", "");
     $mtDaytimeMappedValue = getFieldValueFromClause("metatype", "mt_mapped_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "' AND mt_sort = '0'");
     $mtDaytimeMinHour = substr($mtDaytimeMappedValue,0,2);
  
     $tmpHourFrom = substr($timeStamp,11,2);
     $jbUnixtimestamp = strtotime($timeStamp);
     $intervalStart = date("H:i", $jbUnixtimestamp - $minusOffsetInSec);
     $intervalEnd = date("H:i", $jbUnixtimestamp + $plusOffsetInSec);

     // Check for beginning of the work time of the day                     
     if (substr($intervalStart,0,2) < $mtDaytimeMinHour) :
        $intervalStart = $mtDaytimeMinHour . ":00";
     endif;

     $retArray = array($intervalStart, $intervalEnd);
  endif;
  return $retArray;
}

// Get standard ECO service colour
function getDispositionStandardColours ($ecoService) {
	global $parInstallationServiceArray, $parInstallationServiceArrayLen, $parDeliveryServiceArray, $parDeliveryServiceArrayLen, $serviceColourArray, $serviceColourArrayLen;
  if (($ecoService & 2) == 2) :
     $ecoBgCol = "background-color: #55BB55;";  // Init "Installation"
     if ($serviceColourArrayLen > 0 && $parInstallationServiceArrayLen > 0) :
        for ($j = 0; $j < $parInstallationServiceArrayLen; $j++) :
            $tmpService = $parInstallationServiceArray[$j];
            if (is_numeric($tmpService) && $serviceColourArray[$tmpService] != "") :
               $decNumForService = pow(2,$tmpService);
               if (($ecoService & $decNumForService) == $decNumForService) :
                  $ecoBgCol = "background-color: " . $serviceColourArray[$tmpService] . ";";  // E.g. "Küchen"
                  break;
               endif;
            endif;
        endfor;
     endif;
  else :
     $ecoBgCol = "background-color: #88BB88;";  // Init "Delivery"
     if ($serviceColourArrayLen > 0 && $parDeliveryServiceArrayLen > 0) :
        for ($j = 0; $j < $parDeliveryServiceArrayLen; $j++) :
            $tmpService = $parDeliveryServiceArray[$j];
            if (is_numeric($tmpService) && $serviceColourArray[$tmpService] != "") :
               $decNumForService = pow(2,$tmpService);
               if (($ecoService & $decNumForService) == $decNumForService) :
                  $ecoBgCol = "background-color: " . $serviceColourArray[$tmpService] . ";";  // E.g. "Küchen"
                  break;
               endif;
            endif;
        endfor;
     endif;
  endif;
  return $ecoBgCol;
}

// Gets open volume of a single job. Payments will be compared with the total volume required
// Returns net or gross value
function getManualEventsHtml ($jbId) {
  global $db, $PHP_SELF;
  $retVal = "";
  if ($jbId != "" && is_numeric($jbId)) :
     // Get predecessor job
     $jbPredecessor = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_storno' AND gdc_obj_id = '" . $jbId . "'");
     if ($jbPredecessor != "" && is_numeric($jbPredecessor)) :
        $jbCurrentEvents = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_events' AND gdc_obj_id = '" . $jbPredecessor . "'");
        if ($jbCurrentEvents != "") :
           $retVal = str_replace(",", "<br>", $jbCurrentEvents);
        endif;
     endif;
  endif;
  return $retVal;
}

// Check for activation of survey functionality on PDA
function checkJobForSurvey ($jbId, $category = "15", $gdcOpEnabled = "1") {
  global $db, $PHP_SELF, $hq_id, $usr_id;

  $retBool = false;
  $debug = false;
  
  // Check survey is enabled
  $parJobTriggerSurveyEnabled = getParameterValue("0", "JOB_SURVEY_TRIGGER_ENABLED", $hq_id);
  if ($parJobTriggerSurveyEnabled == "") : $parJobTriggerSurveyEnabled = getParameterValue("0", "JOB_SURVEY_TRIGGER_ENABLED", "0"); endif;

  if ($parJobTriggerSurveyEnabled == "1" || $gdcOpEnabled != "1") :
     if ($jbId != "" && is_numeric($jbId)) :
        if ($debug) : echo "<h2>jbId : " . $jbId . "</h2><br>"; endif;

        $jbStatus = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
        if ($jbStatus == "0" || $jbStatus == "1" || $gdcOpEnabled != "1") :

           // Get object IDs for categogy "survey"
           $sqlquery = "SELECT DISTINCT mtfv.mtfv_id"
                        . " FROM metafieldvalue AS mtfv, metafieldcategorykey AS mtfck, metafieldkey AS mtfk"
                        . " WHERE mtfv.mtfck_id = mtfck.mtfck_id      AND"
                        . "       mtfck.mtfc_id = '" . $category . "' AND"
                        . "       mtfck.mtfk_id = mtfk.mtfk_id";

           $result = $db->query($sqlquery);
           if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

           $objIdArray = array();
           while ($row = $result->fetch_assoc()):
                 $objIdArray[] = $row["mtfv_id"];
           endwhile;
           $result->free();

           // Iterate survey trigger configurations
           // If at least one trigger does match then return "true"
           $objIdArrayLen = count($objIdArray);
           if ($objIdArrayLen > 0) :

              $objValues = array();

              for ($i = 0; $i < $objIdArrayLen; $i++) :

                  if ($debug) : echo "<h3>[----" . $i . "----]</h3><br>"; endif;
                  $currObjId = $objIdArray[$i];

                  $sqlquery = "SELECT mtfv.mtfck_id, mtfv.mtfv_id, mtfv.mtfv_value, mtfk.mtfk_type, mtfk.mtfk_id"
                               . " FROM metafieldvalue AS mtfv, metafieldcategorykey AS mtfck, metafieldkey AS mtfk"
                               . " WHERE mtfv.mtfv_id = " . $currObjId . " AND"
                               . "       mtfck.mtfc_id = '" . $category . "' AND"
                               . "       mtfk.mtfk_id = mtfck.mtfk_id AND "
                               . "       mtfv.mtfck_id = mtfck.mtfck_id"
                               . " ORDER BY mtfv.mtfv_id, mtfck.mtfck_sort";
              
                  $result = $db->query($sqlquery);
                  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

                  while ($row = $result->fetch_assoc()):
                        if ($debug) : echo $row["mtfk_type"] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; endif;
                        $objValues[$currObjId][$row["mtfk_type"]] = $row["mtfv_value"];
                        if ($debug) : echo $objValues[$currObjId][$row["mtfk_type"]] . "<br>"; endif;
                  endwhile;
                  $result->free();

                  $doContinue = true;
                  if ($doContinue) :

                     // [1.] Check date interval
                     if ($doContinue) :
                        if ($debug) : echo "<br>[1.] Check date interval<br>"; endif;
                        $dateBegin = $objValues[$currObjId]["date_begin"];
                        $dateEnd   = $objValues[$currObjId]["date_end"];
                        if ($debug) : echo "dateBeginPRE : " . $dateBegin . "<br>"; endif;
                        if ($debug) : echo "dateEndPRE : " . $dateEnd . "<br>"; endif;
                        if ($dateBegin != "" || $dateEnd != "") :
                           $dateBegin = substr($dateBegin,6,4) . "-" . substr($dateBegin,3,2) . "-" . substr($dateBegin,0,2);
                           $dateEnd = substr($dateEnd,6,4) . "-" . substr($dateEnd,3,2) . "-" . substr($dateEnd,0,2);
                           if ($debug) : echo "dateBegin : " . $dateBegin . "<br>"; endif;
                           if ($debug) : echo "dateEnd : " . $dateEnd . "<br>"; endif;
                           // $currentDay = getDateTime("3");   // "Y-m-d" (today)
                           $jobDay = getFieldValueFromId("job", "jb_id", $jbId, "jb_ordertime");  // "Y-m-d" (Ordertime of the job)
                           $jobDay = substr($jobDay,0,10);
                           if ($debug) : echo "jobDay : " . $jobDay . "<br>"; endif;
                           if (($dateBegin != "" && $jobDay < $dateBegin) || ($dateEnd != "" && $jobDay > $dateEnd)) :
                              $doContinue = false;  // Date does not match date interval
                              if ($debug) : echo "<br>DATE DOES NOT MATCH INTERVAL! => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // [2.] Check HQ trigger being empy OR hq_id of the job being in current trigger headquarters list
                     if ($doContinue) :
                        if ($debug) : echo "<br>[2.] Check HQ trigger being empy OR hq_id of the job being in current trigger headquarters list<br>"; endif;
                        if ($objValues[$currObjId]["checkboxes_hq"] != "") :
                           $jbHqId = getFieldValueFromId("job", "jb_id", $jbId, "hq_id");  // Get hq_id of the job
                           if ($debug) : echo "jbHqId : " . $jbHqId . "<br>"; endif;
                           $tmpHqIdArray = spliti(",", $objValues[$currObjId]["checkboxes_hq"]);
                           $j = array_search($jbHqId, $tmpHqIdArray);
                           if ($j === FALSE) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>NOT FOUND! =>  => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // [3.] Check single customer
                     if ($doContinue) :
                        if ($debug) : echo "<br>[3.] Check single customer<br>"; endif;
                        $csEid = $objValues[$currObjId]["button:cs:cs_eid"];
                        if ($csEid != "") :
                           if ($debug) : echo "csEid : " . $csEid . "<br>"; endif;
                           $jbCscIdPayer = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_payer");
                           $jbCsIdPayer = getFieldValueFromId("costcenter", "csc_id", $jbCscIdPayer, "cs_id");
                           $jbCsEidPayer = getFieldValueFromId("customer", "cs_id", $jbCsIdPayer, "cs_eid");
                           if ($debug) : echo "jbCsEidPayer : " . $jbCsEidPayer . "<br>"; endif;
                           if ($jbCsEidPayer != $csEid) :
                              // $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>SINGLE CUSTOMER DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                              // [3.(a)] Check meta customer
                              if ($debug) : echo "<br>[3.] Check meta customer<br>"; endif;
                              // Get meta customer
                              $jbCsIdParent = getFieldValueFromId("customer", "cs_id", $jbCsIdPayer, "cs_id_parent");
                              $jbCsEidParent = "";
                              if ($jbCsIdParent != "" && is_numeric($jbCsIdParent) && $jbCsIdParent > 0) :
                                 $jbCsEidParent = getFieldValueFromId("customer", "cs_id", $jbCsIdParent, "cs_eid");
                              endif;
                              if ($debug) : echo "jbCsEidParent : " . $jbCsEidParent . "<br>"; endif;
                              if ($jbCsEidParent != $csEid) :
                                 $doContinue = false;  // Not found, trigger does not match
                                 if ($debug) : echo "<br>META CUSTOMER DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                              endif;
                           endif;
                        endif;
                     endif;

                     // [3.(a)] Check meta customer
                     /*
                     if ($doContinue) :
                        if ($debug) : echo "<br>[3.] Check meta customer<br>"; endif;
                        $csEid = $objValues[$currObjId]["button:cs:cs_eid"];
                        if ($csEid != "" && $doCheckMetaCustomer) :
                           if ($debug) : echo "csEid : " . $csEid . "<br>"; endif;
                           $jbCscIdPayer = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_payer");
                           $jbCsIdPayer = getFieldValueFromId("costcenter", "csc_id", $jbCscIdPayer, "cs_id");
                           // Get meta customer
                           $jbCsIdParent = getFieldValueFromId("customer", "cs_id", $jbCsIdPayer, "cs_id_parent");
                           $jbCsEidParent = "";
                           if ($jbCsIdParent != "" && is_numeric($jbCsIdParent) && $jbCsIdParent > 0) :
                              $jbCsEidParent = getFieldValueFromId("customer", "cs_id", $jbCsIdParent, "cs_eid");
                           endif;
                           if ($debug) : echo "jbCsEidParent : " . $jbCsEidParent . "<br>"; endif;
                           if ($jbCsEidParent != $csEid) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>META CUSTOMER DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;
                     */

                     // [4.] Check single courier
                     if ($doContinue) :
                        if ($debug) : echo "<br>[4.] Check single courier<br>"; endif;
                        $crEid = $objValues[$currObjId]["button:cr:cr_eid"];
                        if ($crEid != "") :
                           if ($debug) : echo "crEid : " . $crEid . "<br>"; endif;
                           $jbCrId = getFieldValueFromId("job", "jb_id", $jbId, "cr_id");
                           $jbCrEid = getFieldValueFromId("courier", "cr_id", $jbCrId, "cr_eid");
                           if ($debug) : echo "jbCrEid : " . $jbCrEid . "<br>"; endif;
                           if ($jbCrEid != $crEid) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>SINGLE COURIER DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // [5.] Check single couriervehicle
                     if ($doContinue) :
                        if ($debug) : echo "<br>[5.] Check single couriervehicle<br>"; endif;
                        $crvhSid = $objValues[$currObjId]["select:crvh:crvh_sid"];
                        if ($crvhSid != "") :
                           if ($debug) : echo "crvhSid : " . $crvhSid . "<br>"; endif;
                           $jbCrSid = getFieldValueFromId("job", "jb_id", $jbId, "cr_sid");
                           if ($debug) : echo "jbCrSid : " . $jbCrSid . "<br>"; endif;
                           if ($jbCrSid != $crvhSid) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>SINGLE COURIERVEHICLE DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // [6.] Check couriervehicle class
                     if ($doContinue) :
                        if ($debug) : echo "<br>[6.] Check couriervehicle class<br>"; endif;
                        $vhtId = $objValues[$currObjId]["select:vht"];
                        if ($vhtId != "") :
                           if ($debug) : echo "vhtId : " . $vhtId . "<br>"; endif;
                           // $jbVhtIdReal = getFieldValueFromId("job", "jb_id", $jbId, "vht_id_real");
                           $jbVhtId = getFieldValueFromId("job", "jb_id", $jbId, "vht_id");
                           // if ($debug) : echo "jbVhtIdReal : " . $jbVhtIdReal . "<br>"; endif;
                           if ($debug) : echo "jbVhtId : " . $jbVhtId . "<br>"; endif;
                           // if ($jbVhtIdReal != $vhtId) :
                           if ($jbVhtId != $vhtId) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>VEHICLE CLASS DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // [7.] Check customer group
                     if ($doContinue) :
                        if ($debug) : echo "<br>[7.] Check customer group<br>"; endif;
                        $csGrpID = $objValues[$currObjId]["select:grp"];
                        if ($csGrpID != "") :
                           if ($debug) : echo "csGrpID : " . $csGrpID . "<br>"; endif;
                           // Get customer ID of the current job
                           $jbCscIdPayer = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_payer");
                           $jbCsIdPayer = getFieldValueFromId("costcenter", "csc_id", $jbCscIdPayer, "cs_id");
                           // Get members of the (customer) group
                           $csGroupMemberIds = getGroupMemberIDs(array($csGrpID), "cs");
                           // Check customer of the job being member of the specified (customer) group
                           $j = array_search($jbCsIdPayer, $csGroupMemberIds);
                           if ($j === FALSE) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>CUSTOMER NOT IN SPECIFIED GROUP! => CHECK NEXT TRIGGER!!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // [8.] Check branch
                     if ($doContinue) :
                        $brId = $objValues[$currObjId]["select:br"];
                        if ($brId != "") :
                           if ($debug) : echo "brId : " . $brId . "<br>"; endif;
                           $jbCscIdPayer = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_payer");
                           $jbCsIdPayer = getFieldValueFromId("costcenter", "csc_id", $jbCscIdPayer, "cs_id");
                           $jbCmpIdPayer = getFieldValueFromId("customer", "cs_id", $jbCsIdPayer, "cmp_id");
                           $jbBrIdPayer = getFieldValueFromId("company", "cmp_id", $jbCsIdPayer, "br_id");
                           if ($debug) : echo "$jbBrIdPayer : " . $jbBrIdPayer . "<br>"; endif;
                           if ($jbBrIdPayer != $brId) :
                              $doContinue = false;  // Not found, trigger does not match
                              if ($debug) : echo "<br>BRANCH DOES NOT MATCH! => CHECK NEXT TRIGGER!<br>"; endif;
                           endif;
                        endif;
                     endif;

                     // If $doContinue == "true" at this place then all checks are matched for the 
                     // current trigger (object) and therefore condition is green to display survey in PDA !!!!
                     if ($doContinue) :
                        if ($debug) : echo "<br>TRIGGER FOUND!!!!!!!!!!!!!!!!!!!!!!!!!! => BREAK!<br>"; endif;
                        $retBool = true;
                        break;
                     endif;
                     if ($debug) : echo "--------------------------------------------------------------------------------<br><br>"; endif;                     
                  endif;
              endfor;
           endif;
        endif;
     endif;

     // if (!$debug) :
     if ($gdcOpEnabled == "1") :
        $gdcContent = "0";
        $logTriggerNo = "";
        if ($retBool) :
           $gdcContent = "1";
           $logTriggerNo = $currObjId;  // Last object ID before breaking the loop
        endif;
        if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","jb_pda_survey","gdc_obj_id",$jbId))) :
           updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $gdcContent, "gdc_context", ""),"gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'jb_pda_survey'");
        else :
           insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "jb_pda_survey", "gdc_content", $gdcContent, "gdc_context", ""));
        endif;

        // Write logdata into log database
        if ($retBool) :  // Remove check for "$retBool" to get negative cases, too!
           writeToLogDB("134",$hq_id,$jbId,$usr_id,$jbCrId,$jbCrSid,$jbCsIdPayer,"STATE=" . ($retBool ? "YES" : "NO") . "|MTFV_ID=" . $logTriggerNo);
        endif;
     endif;
     // endif;
  endif;
  return $retBool;
}

// Cancel a special job
/*
function cancelJob ($jb_id_cancellation, $jb_storno_costs = "2") {
	global $db;
	global $usr_id, $hq_id;
  if ($jb_id_cancellation != "" && is_numeric($jb_id_cancellation) && existsEntry("job",array("jb_id",$jb_id_cancellation))) :
  
     if ($jb_storno_costs != "1" && $jb_storno_costs != "2") : 
        $jb_storno_costs = "2"; 
     endif;

     $currentTime = getDateTime("0");
     
     // Check headquarters to be set and get current job data (jb_status and cr_id of the job to be cancelled)
     $hqId = $hq_id;
     if ($hqId == "") :
        $hqId = getFieldValueFromId("job","jb_id",$jb_id_cancellation,"hq_id");
     endif;
     $jbStatus = getFieldValueFromId("job","jb_id",$jb_id_cancellation,"jb_status");
     $crId = getFieldValueFromId("job","jb_id",$jb_id_cancellation,"cr_id");
     $crIdOrder = getFieldValueFromId("job","jb_id",$jb_id_cancellation,"cr_id_order");
     
     $jbStatusString = " (jb_status = '8' OR jb_status = '9' OR jb_status = '0' OR jb_status = '1') ";
     if (is_numeric($jb_status)) : $jbStatusString = "jb_status = '" . $jb_status . "'"; endif;
     
     $res = updateStmt("job", "jb_id", $jb_id_cancellation, 
                       array("jb_storno", $jb_storno_costs, "usr_id_storno", $usr_id, "jb_status" , "2", "jb_finishtime", $currentTime), 
                       "(" . $jbStatusString . " AND (isnull(jb_storno) OR jb_storno = '0'))");

     if ($db->affected_rows > 0) :

        // Insert PDA command to remove job (take cr_id/cr_id_order before changing)
        if ($crId != "" && $crId != "0") :
           insertPDACommand($hq_id, $crId, "3", "1", $jb_id_cancellation, $currentTime, ""); 
           insertPDACommand($hq_id, $crId, "8", "1", $jb_id_cancellation, $currentTime, ""); 
        endif;
        if ($crIdOrder != "" && $crIdOrder != "0" && $crIdOrder != $crId) :
           insertPDACommand($hq_id, $crIdOrder, "3", "1", $jb_id_cancellation, $currentTime, ""); 
           insertPDACommand($hq_id, $crIdOrder, "8", "1", $jb_id_cancellation, $currentTime, ""); 
        endif;

        // Check for storno-job has a standing order
        $jbPermanent = getFieldValueFromId("job","jb_id",$jb_id_cancellation,"jb_permanent");

        if ($jbPermanent != "" && $jbPermanent > "0") :
           // Check for the continued existence of the standing order rule
           if ($jb_storno_rhythm == "2") :
              // Update row for termnination of the standing order
              updateStmt("job", "jb_id", $jb_id_cancellation, array("jb_permanent", "0"));
           endif;
        endif;

        // Remove payment entry/entries from table "jobpayment" for the job if not being exported
        $removedFromJbp = false;
        if ($jb_storno_jbp_id != "" && is_numeric($jb_storno_jbp_id)) :
           // Remove ALL payments if NOT be exported
           deleteStmt("jobpayment","jb_id = '" . $jb_id_cancellation . "' AND (jbpc_id = '' OR jbpc_id = '0')");
           // Check for removal
           $jbpcJbId = getFieldValueFromId("jobpayment","jbp_id",$jb_storno_jbp_id,"jb_id");
           if ($jbpcJbId == "") :
              $removedFromJbp = true;
              $statusMessage = getLngt("ACHTUNG: Die Einnahmenbuchung dieses stornierten Auftrags wurde gelöscht, da noch KEIN Export stattfand!");
           else :
              $statusMessage = getLngt("ACHTUNG: Die Einnahmenbuchung dieses stornierten Auftrags wurde schon exportiert und kann deshalb NICHT gelöscht werden!");
           endif;
        endif;

        // Remove reservation entry from table "vehicledisposition" if FDS is enabled
        $removedFromFDS = false;
        if ($fastDispositionStructureEnabled == "1") :
           $removedFromFDS = removeAssocCrvhJb($jb_id_cancellation);
        endif;

        // Storno "addmont" job
        $gdcContentIdAddMon = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_id_addmont' AND gdc_obj_id = '" . $jb_id_cancellation . "'");
        if ($gdcContentIdAddMon != "" && is_numeric($gdcContentIdAddMon)) :
           updateStmt("job", "jb_id", $gdcContentIdAddMon, array("jb_storno", "2", "jb_status", "2", "jb_incomplete", "1", "jb_finishtime", $currentTime));
        endif;

        // Write logdata into log database
        writeToLogDB("10",$hq_id,$jb_id_cancellation,$currentSessionUsrId,"","","","COSTS=" . ($jb_storno_costs == "1" ? "YES" : "NO") . "|JBP_REMOVAL=" . ($removedFromJbp ? "YES" : "NO") . "|FDS_REMOVAL=" . ($removedFromFDS ? "YES" : "NO"));
     
        // Call for generation of a new job with negative invoice data      
        if ($globalParUseRelatedCustomer != "1") :
           copy_job($jb_id_cancellation, $jb_storno_costs, $jbStatus, true);
        endif;
     endif;
  endif;   
}
*/

function addmontEdit($jb_id, $jb_paymenttype) {
  global $db;
//echo "$jb_id, $jb_paymenttype<br>\n";
  $jb_addmont = str_replace(",", ".", $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_addmont'"));
//echo "$jb_addmont<br>\n";

//  if ($jb_addmont > 0):
    $csc_id_related = $db->getOne("SELECT csc_id_related FROM job WHERE jb_id = $jb_id");
    $hq_id = $db->getOne("SELECT hq_id FROM job WHERE jb_id = $jb_id");
    $csId = $db->getOne("SELECT cs_id FROM costcenter WHERE csc_id = $csc_id_related");  
 
    include_once ("../include/inc_mtf_func.inc.php");
    $hqId = "0";

    $jbp_tan = '';
    // wenn aus dem order_request, dann Zahlart OShappy
    if ($db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'acquisitiontime'") != ""):
      $jbp_tan = $jb_paymenttype;
      $jb_paymenttype = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'payment_type' AND mt_value = 'OS happy'");
    endif;

// SAMS-Preise berücksichtigen!
    $category = "20";
    $category_cr = "30";
    if ($db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_service_job'") == 1):
      $category = "40";
      $category_cr = "40";
//      $jb_paymenttype = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'payment_type' AND mt_objtype = 'grp' AND mt_objid = '$hq_id' AND mt_value = 'Serviceaufträge'");
      $jb_paymenttype = 15;
      // wenn aus dem order_request, dann Zahlart OSsad
      if ($db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'acquisitiontime'") != "")
        $jb_paymenttype = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'payment_type' AND mt_value = 'OS sad'");
    endif;

    $result = getMtfFunctionResult($hqId, $csId, $category, "ident_0001", $jb_addmont);
    if (is_array($result))
      $result = $result[0];
    $result = ($result * $jb_addmont) / 1.19;
    $result_crArr = getMtfFunctionResult($hqId, $csId, $category_cr, "ident_0001", $jb_addmont);
    if (is_array($result_crArr)):
      $result_cr = $result_crArr[0];
      if ($hq_id == 1020)
        $result_cr = $result_crArr[0] - $result_crArr[1];
    endif;
    $result_cr = ($result_cr * $jb_addmont) / 1.19;

//    // Fuhrlohn-Provisionss?tze Altona (CR_PROV_17093) in Prozent f?r SAP-Debitoren 69900 (Lieferungen), 69901 (Montagen) und 69902 (Küchenmontagen)
//    $serviceKueMont = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'KU'");
//    $jb_service_num_mont = $db->getOne("SELECT jb_service FROM job WHERE jb_id = $jb_id");
//    $jb_service_arr_mont = mcConvertNum2Sel($jb_service_num_mont);
//    $prov_idx_mont = 1;
//    if (in_array($serviceKueMont, $jb_service_arr_mont)):
//      $prov_idx_mont = 2;
//    endif;
//    $cr_prov_mont = 0;
//    $cr_provArr = array_filter(explode(",", getParameterValue("0", "CR_PROV_" . $csId, $hqId)));
//    if (count($cr_provArr) == 3):
//      $cr_prov_mont = $cr_provArr[$prov_idx_mont] / 100;
//    endif;
//    $result_cr = ($result_cr * (1 - $cr_prov_mont));

//    $jb_subtotalprice = $db->getOne("SELECT jb_subtotalprice FROM job WHERE jb_id = $jb_id");
//    $jb_cr_subprice = $db->getOne("SELECT jb_cr_subprice FROM job WHERE jb_id = $jb_id");
//    $jb_totalprice = $jb_subtotalprice + $result;
//    $jb_cr_price = $jb_cr_subprice + $result_cr;

////echo("'$category, $category_cr, $result, $result_cr'\n");
//    updateStmt("job", "jb_id", $jb_id, array("jb_fixprice", $jb_totalprice, "jb_totalprice", $jb_totalprice, "jb_cr_price", $jb_cr_price, "jb_incomplete", 0));
//    $jbp_id = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jbp_id'");
//    updateStmt("jobpayment", "jbp_id", $jbp_id, array("jbp_mode", $jb_paymenttype, "jbp_price", $result, "jbp_bookingtime", date("Y-m-d H:i:s")));
//    updateStmt("jobcalculator", "jb_id", $jb_id, array("jbc_amount", $jb_addmont, "jbc_price", ($result / $jb_addmont), "jbc_totalprice", $result), "srvt_name = 'ident_9999:par_01'");    
////  endif;

  $jb_id_addmont = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_id_addmont'");
  if ($jb_id_addmont == ""):
    include_once("../include/copy_job.inc.php");
    $jb_id_addmont = copy_job_flat($jb_id, $jb_id_addmont);
    insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_id_addmont", "gdc_content", $jb_id_addmont, "gdc_context", ""));
    insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id_addmont, "gdc_gen_fieldname", "jb_id_addmont_parent", "gdc_content", $jb_id, "gdc_context", ""));
//    if ($hq_id != 1020)
//      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id_addmont, "gdc_gen_fieldname", "hide", "gdc_content", "", "gdc_context", ""));
    if ($jb_paymenttype == 15)
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id_addmont, "gdc_gen_fieldname", "jb_service_job", "gdc_content", "1", "gdc_context", ""));
  endif;
  updateStmt("job", "jb_id", $jb_id_addmont, array("jb_id_parent", 0, "jb_fixprice", $result, "jb_totalprice", $result, "jb_subtotalprice", $result, "jb_cr_price", $result_cr, "jb_cr_subprice", $result_cr, "jb_incomplete", 0, "jb_status", 2));
  // ohne jb_finishtime kein Export: jb_finishtime updaten wenn NULL (d.h. vom "Elternauftrag" kopierte jb_finishtime ist NULL weil noch nicht erledigt; kann nur passieren, wenn Auftrag manuell abgeschlossen wird)
  updateStmt("job", "jb_id", $jb_id_addmont, array("jb_finishtime", date("Y-m-d H:i:s")), "jb_finishtime IS NULL");  
  updateStmt("job", "jb_id", $jb_id_addmont, array("jb_finishtime", date("Y-m-d H:i:s")), "jb_finishtime = '0000-00-00 00:00'");  
  updateStmt("tourservice", "jb_id", $jb_id_addmont, array("trs_price", $result));
  
  $jbp_id = $db->getOne("SELECT jbp_id FROM jobpayment WHERE jb_id = $jb_id_addmont");
  if ($jbp_id == ""):
    insertStmt("jobpayment", array("jb_id", $jb_id_addmont, "tr_sort", 2, "csc_id", $csc_id_related, "jbp_mode", $jb_paymenttype, "jbp_price", $result, "jbp_tan", $jbp_tan, "jbp_bookingtime", date("Y-m-d H:i:s"), "jbp_counter", "0"));
  else:
    updateStmt("jobpayment", "jbp_id", $jbp_id, array("jbp_mode", $jb_paymenttype, "jbp_price", $result, "jbp_tan", $jbp_tan, "jbp_bookingtime", date("Y-m-d H:i:s")));
  endif;
  updateStmt("jobcalculator", "jb_id", $jb_id, array("jbc_amount", $jb_addmont, "jbc_price", ($result / $jb_addmont), "jbc_totalprice", $result), "srvt_name = 'ident_9999:par_01'");    

}

function mk_jb_tourdata($jb_id) {
  global $db;

  $jb_tourdata1 = "";
  $jb_tourdata2 = "";
  $jb_tourdata3 = "";
  $sqlquery = "SELECT ad_zipcode, ad_city, ad_country FROM address, tour WHERE jb_id = " . $jb_id . " AND address.ad_id = tour.ad_id ORDER BY tr_sort";
  $res = $db->query($sqlquery);
  if (DB::isError($res)) die ("$PHP_SELF: " . $res->getMessage());
  while ($row = $res->fetch_assoc()):
    $jb_tourdata1 .= ($jb_tourdata1 == "" ? "" : ";") . $row['ad_zipcode'];
    $jb_tourdata2 .= ($jb_tourdata2 == "" ? "" : ";") . $row['ad_city'];
    $jb_tourdata3 .= ($jb_tourdata3 == "" ? "" : ";") . $row['ad_country'];
  endwhile;
  $res->free();
  updateStmt("job", "jb_id", $jb_id, array("jb_tourdata", $jb_tourdata1 . "|" . $jb_tourdata2 . "|" . $jb_tourdata3));
}

function getJobsByLocating($gpsLong, $gpsLat, $radius = 50) {
  global $db;

  //https://rechneronline.de/erdradius/
  $r_equator = 6378.137;  // Radius am Äquator in km
  $r_poles   = 6356.752;  // Radius an den Polen in km
  $r_local = sqrt(
    (pow(pow($r_equator, 2) * cos(deg2rad($gpsLat)), 2)
   + pow(pow($r_poles, 2)   * sin(deg2rad($gpsLat)), 2)) /
    (pow($r_equator * cos(deg2rad($gpsLat)), 2)
   + pow($r_poles   * sin(deg2rad($gpsLat)), 2))
  );

  $sqlquery = "SELECT job.jb_id, gc_lat, gc_long, tr_comp, ad_zipcode, ad_city, ad_street, tr_hsno " .
    "FROM job, tour, address, geocode " .
    "WHERE job.jb_id = tour.jb_id AND address.ad_id = tour.ad_id AND tour.tr_id = gc_obj_id AND tour.tr_sort = 1 AND gc_obj_type = 'tr' AND jb_status = 9 AND " .
    "  ACOS(" .
    "    SIN(RADIANS(" . $gpsLat . ")) * SIN(RADIANS(gc_lat)) +" .
    "    COS(RADIANS(" . $gpsLat . ")) * COS(RADIANS(gc_lat)) *" .
    "    COS(RADIANS(gc_long) - RADIANS(" . $gpsLong . "))" .
    "  ) * " . $r_local . " <= " . $radius;
  $retArr = array();
  $res = $db->query($sqlquery);
  if (DB::isError($res)) die ("$PHP_SELF: " . $res->getMessage());
  while ($row = $res->fetch_assoc()):
    $retArr[] = array($row["jb_id"], $row["gc_lat"], $row["gc_long"], $row["tr_comp"],
      $row["ad_street"], $row["tr_hsno"], $row["ad_zipcode"], $row["ad_city"],
      round(acos(
        sin(deg2rad($gpsLat)) * sin(deg2rad($row['gc_lat'])) +
        cos(deg2rad($gpsLat)) * cos(deg2rad($row['gc_lat'])) *
        cos(deg2rad($row['gc_long']) - deg2rad($gpsLong))
      ) * $r_local, 1));
  endwhile;
  $res->free();

  return($retArr);
};

/*
function addmontEdit($jb_id, $jb_paymenttype) {
  global $db;
//echo "$jb_id, $jb_paymenttype<br>\n";
  $jb_addmont = str_replace(",", ".", $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_addmont'"));
//echo "$jb_addmont<br>\n";

  if ($jb_addmont > 0):
    $jb_id_addmont = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_id_addmont'");
//echo "$jb_id_addmont<br>\n";
//    if ($jb_id_addmont == "")
//      $jb_id_addmont = $jb_id;
    $csc_id_related = $db->getOne("SELECT csc_id_related FROM job WHERE jb_id = $jb_id_addmont");
    $csId = $db->getOne("SELECT cs_id FROM costcenter WHERE csc_id = $csc_id_related");  
 
    include_once ("../include/inc_mtf_func.inc.php");
    $hqId = "0";

// SAMS-Preise berücksichtigen!
    $category = "20";
    $category_cr = "30";
    if ($db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_service_job'") == 1):
      $category = "40";
      $category_cr = "40";
      $jb_paymenttype = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'payment_type' AND mt_objtype = 'grp' AND mt_objid = '$hq_id' AND mt_value = 'Serviceaufträge'");
    endif;

    $result = round((getMtfFunctionResult($hqId, $csId, $category, "ident_0001", $jb_addmont) * $jb_addmont) / 1.19, 2);
    $result_cr = round((getMtfFunctionResult($hqId, $csId, $category_cr, "ident_0001", $jb_addmont) * $jb_addmont) / 1.19, 2);
//echo("'$category, $category_cr, $result, $result_cr'\n");
    updateStmt("job", "jb_id", $jb_id_addmont, array("jb_fixprice", $result, "jb_totalprice", $result, "jb_cr_price", $result_cr, "jb_cr_subprice", $result_cr, "jb_incomplete", 0, "jb_status", 2, "jb_finishtime", date("Y-m-d H:i:s")));
    deleteStmt("jobpayment", "jb_id = $jb_id_addmont");
    insertStmt("jobpayment", array("jb_id", $jb_id_addmont, "tr_sort", 2, "csc_id", $csc_id_related, "jbp_mode", $jb_paymenttype, "jbp_price", $result, "jbp_bookingtime", date("Y-m-d H:i:s"), "jbp_counter", "0"));
  endif;
}
*/


// Gets internal remark items
function getJobInternalRemarkItems ($jbId, $mode = "", $trId = "") {
	$retStr = "";
	$retArray = array();
	$retJsStr = "";

	if ($jbId != "" && is_numeric($jbId)) :	
	   // Get tour IDs by jbId
	   $trIdArray = getColVectorFromDB2ArrayByClause("tour", "tr_id", "jb_id = '" . $jbId . "'", "", "tr_sort", "");	
	   $trIdArrayLen = count($trIdArray);

     // Get vector of metatype items regarding internal remark cases
     $mtIntRemItem = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'internal_remark' AND mt_objtype = '' AND mt_objid = '0'", "mt_sort", "mt_sort", "");
     $mtIntRemItemLen = count($mtIntRemItem);
     // Put metatype data into javascript array
     for ($mt = 0; $mt < $mtIntRemItemLen; $mt++) :
         $retJsStr .= "mtIntRemItems[" . $mt . "] = '" . $mtIntRemItem[$mt] . "';\n";
         for ($i = 0; $i < $trIdArrayLen; $i++) :
             $retJsStr .= "  trIntRemItemTexts[" . $trIdArray[$i] . "] = new Array();\n";
         endfor;
     endfor;

     // Get existing markers regarding internal remark
     $gdcIntRemItem = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'int_rem_item'");
     $gdcIntRemItemArr = getKeyValueArrayFromString($gdcIntRemItem);
     if ($mode == "1") :
        $retArray = $gdcIntRemItemArr;
     endif;
     $gdcIntRemItemKeysArr = array_keys($gdcIntRemItemArr);
     $gdcIntRemItemKeysArrLen = count($gdcIntRemItemKeysArr);
     // ATTENTION: View source code to understand.... ;-)
     // E.g.: 6535260=2,9|6535261=5|....
     for ($i = 0; $i < $trIdArrayLen; $i++) :
         mcArrIsSet($trIdArray, $i);
         $gdcIntRemItemArr[$trIdArray[$i]] = mcArrIsSet($gdcIntRemItemArr, $trIdArray[$i]);         
         if ($gdcIntRemItemArr[$trIdArray[$i]] != "") :
            $tmpArr = explode(",", $gdcIntRemItemArr[$trIdArray[$i]]);  // Explode "0,9", "5", .... and set metatype texts
            $tmpArrLen = count($tmpArr);
            if ($mode == "2" && $trId == $trIdArray[$i]) :
               $retStr .= "<br>";
            endif;
            for ($t = 0; $t < $tmpArrLen; $t++) :
                // trIntRemItemTexts[6535260][2] = mtIntRemItems[2] <=> Text for mt_sort = 2
                // trIntRemItemTexts[6535260][9] = mtIntRemItems[9] <=> Text for mt_sort = 9
                // trIntRemItemTexts[6535261][5] = mtIntRemItems[5] <=> Text for mt_sort = 5
                // ....
                // $retJsStr .= "trIntRemItemTexts[" . $gdcIntRemItemKeysArr[$g] . "][" . $tmpArr[$t] . "] = '" . $mtIntRemItem[$tmpArr[$t]] . "';\n";
                $retJsStr .= "trIntRemItemTexts[" . $trIdArray[$i] . "][" . $tmpArr[$t] . "] = '" . $mtIntRemItem[$tmpArr[$t]] . "';\n";
            
                // Get active items for the requested station only (!!!!)
                if ($mode == "2" && $trId == $trIdArray[$i]) :
                   $retStr .= $mtIntRemItem[$tmpArr[$t]] . "<br>";
                endif;
            endfor;
         endif;
         if ($mode == "2" && $trId == $trIdArray[$i]) :
             $retStr .= "<br><b>";
             $retStr .= getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'tr_int_rem'");
             $retStr .= "</b><br>";
         endif;
     endfor;
     $retJsStr .= "\n\n";
  endif;

  if ($mode == "1") :
     return $retArray;
  elseif ($mode == "2") :
     return $retStr;
  else :
     return $retJsStr;
  endif;
}

// Sets internal remark items
function setJobInternalRemarkItems ($trId, $itemValues) {
	$retVal = "NOK";
	if ($trId != "" && is_numeric($trId)) :
	   // if ($itemValues != "") :
	      $jbId = getFieldValueFromId("tour", "tr_id", $trId, "jb_id");
	      if ($jbId != "") :
	         $gdcIntRemItem = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'int_rem_item'");
           $gdcIntRemItemArr = getKeyValueArrayFromString($gdcIntRemItem);
           $gdcIntRemItemArr[$trId] = $itemValues;
           $gdcStrToStore = getStringFromKeyValueArray($gdcIntRemItemArr);
           if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","int_rem_item","gdc_obj_id",$jbId))) :
              updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $gdcStrToStore),"gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'int_rem_item' AND gdc_context = '" . "" . "'");
              $retVal = "OK";
           else :
              insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "int_rem_item", "gdc_content", $gdcStrToStore, "gdc_context", ""));
              $retVal = "OK";
           endif;
	      endif;
	   // endif;
	endif;
	return $retVal;
}

// Sets internal remark items
function setTourInternalRemark ($trId, $remarkText) {
	$retVal = "NOK";
	if ($trId != "" && is_numeric($trId)) :
     if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_gen_fieldname","tr_int_rem","gdc_obj_id",$trId))) :
        updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", $remarkText),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'tr_int_rem'");
        $retVal = "OK";
     else :
        $jbId = getFieldValueFromId("tour", "tr_id", $trId, "jb_id");
        insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "tr_int_rem", "gdc_content", $remarkText, "gdc_context", $jbId));
        $retVal = "OK";
     endif;
	endif;
	return $retVal;
}

// Proof of delivery by photo
function getStationPhotos ($trId, $f_act = "mailsend", $parPodPath = "") {
	global $hq_id;
	$out = "";
	if ($parPodPath == "") :
     // Get path for proof of delivery photo
     $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", $hq_id);
     if ($parPodPath == "") : $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", "0"); endif;
  endif;
  if ($parPodPath != "") :
     // Generate photos
     if ($f_act != "export") :
        global $jbMailAttachements;
        if (!isset($jbMailAttachements) || !is_array($jbMailAttachements)) :
           $jbMailAttachements = array();
        endif;
        $jbMailAttachementsLen = count($jbMailAttachements);
        // Check existence in "pic"
        $podPhotoFilenames = getImagesFromPic($trId, $parPodPath);
        $podPhotoFilenamesLen = count($podPhotoFilenames);
        if ($podPhotoFilenamesLen == 0) :
           // Check existence in "b2b_objects"
           $podPhotoFilenames = getImagesFromB2bObjects($trId, $parPodPath);
           $podPhotoFilenamesLen = count($podPhotoFilenames);
        endif;
        for ($p = 0; $p < $podPhotoFilenamesLen; $p++) :
            if ($podPhotoFilenames[$p] != "") :
               if (file_exists($parPodPath . $podPhotoFilenames[$p])) :
                  if ($f_act == "mailsend") :
                     // $out = "<img src=\"" . $parPodPath . $podPhotoFilenames[$p] . "\" border=\"0\" height=\"100\" width=\"100\">&nbsp;";
                     if (file_exists($parPodPath . "pht_" . $podPhotoFilenames[$p])) :
                        unlink($parPodPath . "pht_" . $podPhotoFilenames[$p]);
                     endif;
                     $im = imagecreatefromjpeg($parPodPath . $podPhotoFilenames[$p]);
                     if ($im) :
                        if (imagejpeg($im, $parPodPath . "pht_" . $podPhotoFilenames[$p])) :
                           $out .= "<img src=\"" . $parPodPath . "pht_" . $podPhotoFilenames[$p] . "\" border=\"0\" height=\"100\" width=\"100\">&nbsp;";
                        endif;
                     endif;

                     // Attach each photo to the mail (!!!!)
                     $jbMailAttachements[($p + $jbMailAttachementsLen)][0] = $parPodPath . $podPhotoFilenames[$p];
                     $jbMailAttachements[($p + $jbMailAttachementsLen)][1] = $podPhotoFilenames[$p];
                  else :
                     $out .= "<a href=\"javascript:openImageViewer('" . $podPhotoFilenames[$p] . "','800','600','" . $parPodPath . "');\"><img src=\"" . $parPodPath . $podPhotoFilenames[$p] . "\" border=\"" . "0" . "\" height=\"100\" width=\"100\"></a>&nbsp;";
                  endif;
               endif;
            endif;
        endfor;
     endif;
  endif;
  return $out;
}
?>


<?php
/*

*******************************************
* Structure of the arrays of a single job *
*******************************************

Array
(
    [job] => Array
        (
            [jb_id] => 17
            [csc_id] => 1
            [vht_id] => 2
            [vht_id_real] => 0
            [csc_id_payer] => 2
            [jb_payment] => 0
            [jb_outlay] => 0
            [jb_weight] => 0
            [jb_ordertime] => 2013-10-29 07:30:00
            [jb_reserv] => 1
            [jb_permanent] => 
            [jb_permanent2] => 0000000
            [jp_permenddat] => 
            [jb_specials] => 
            [cr_id] => 0
            [cr_sid] => 
            [cr_id_order] => 0
            [cr_id_permanent] => 
            [jb_cr_filter] => 
            [jb_cr_filter_opt] => 
            [jb_waitstorno] => 0
            [jb_waittime] => 
            [jb_taketime] => 0000-00-00 00:00:00
            [jb_tourname] => 
            [jb_status] => 9
            [jb_type] => 0
            [jb_incomplete] => 0
            [jb_storno] => 
            [jb_finishtime] => 0000-00-00 00:00:00
            [jb_warningtime] => 
            [emp_id] => 18098
            [jb_fixprice] => 159.7900
            [jb_serviceprice] => 0.0000
            [jb_totalprice] => 0.0000
            [jb_cr_price] => 0.0000
            [jb_cr_subprice] => 0.0000
            [jb_id_parent] => 0
            [jb_booktime] => 0000-00-00 00:00:00
            [jb_export_time] => 
            [jb_postage] => 0.00
            [jb_modify] => 2013-11-06 13:41:54
            [jb_longhaul] => 0
            [jb_dispoinfo] => 
            [jb_offer] => 0
            [jb_subtotalprice] => 0.0000
            [jb_markup] => 0.00
            [csc_id_related] => 1
            [jb_timeunits] => 5
            [jb_service] => 2
        )

    [tour] => Array
        (
            [1] => Array
                (
                    [ad_id] => 432206
                    [tr_sort] => 1
                    [tr_comp] => Firma
                    [tr_comp2] => 
                    [tr_hsno] => 132-134
                    [tr_remark] => 
                    [tr_person] => 
                    [tr_phone] => 
                    [csc_id] => 4
                    [tr_km_extra] => 0
                    [tr_srv_extra] => 0
                    [tr_status] => 0
                    [tr_sign] => 
                    [tr_signname] => 
                    [tr_ware_from_to] => 0
                    [tr_finishtime] => 
                    [tr_commission_no] => 
                    [ad_street] => Rothenbaumchaussee
                    [ad_zipcode] => 20149
                    [ad_city] => Hamburg
                    [ad_country] => DE
                    [ad_modify] => 2013-08-15 13:16:25
                )

            [2] => Array
                (
                    [ad_id] => 432207
                    [tr_sort] => 2
                    [tr_comp] => dort
                    [tr_comp2] => 
                    [tr_hsno] => 1
                    [tr_remark] => <br>Bezahlart:1<br>Voucher:RE123456789<br>------------------------<br>FA INV<br>FA2 INV<br>FA INV<br>FA2 INV<br>Adresse:<br>Rechnungsstr. 111<br>22844 Rechnungsstadt<br>Frau Rechnung<br>040 12345678<br>rechnung@rechnung.de<br>Rechnungsbemerkung<br>------------------------<br>WARE AUSLIEFERN<br>NR.: AT1234567<br>Sofa XYZ<br>STK.: 1<br>PREIS: 1.299<br>WGRP: 1100<br>GEWICHT: 70<br>LxBxHxP: 2,5x1,2x0,9x4<br>------------------------<br>WARE RETOURE<br>Altes Sofa<br>STK.: 1<br>GEWICHT: 80<br>LxBxHxP: 2x1x1x3
                    [tr_person] => 
                    [tr_phone] => 
                    [csc_id] => 4
                    [tr_km_extra] => 0
                    [tr_srv_extra] => 0
                    [tr_status] => 0
                    [tr_sign] => A0,38;0,37;1,43;2,45;3,48;4,51;6,54;8,57;10,60;13,62;15,64;23,61;23,59;24,57;24,55;23,53;23,51;22,50;21,50;20,50;17,59;18,61;19,62;19,63;20,64;22,63;23,62;24,62;26,61;36,57;38,57;40,58;41,60;42,61;42,62;42,64;42,65;40,66;31,65;28,63;26,61;24,59;22,58;21,57;20,56;21,56;22,57;39,63;43,63;47,62;51,60;54,57;57,54;59,51;62,48;63,45;65,36;65,35;64,36;63,36;62,38;61,40;59,42;58,43;56,45;45,46;42,44;39,42;37,39;35,36;33,34;31,32;30,31;33,34;35,36;37,38;40,39;43,40;46,41;50,41;53,40;57,38;72,27;74,26;75,24;76,24;76,25;76,27;75,29;74,31;63,46;61,48;59,50;58,51;58,52;57,52;57,51;58,50;58,49;68,31;71,27;74,23;78,19;81,15;84,11;86,8;88,5;90,3;92,0
                    [tr_signname] => 
                    [tr_ware_from_to] => 1
                    [tr_finishtime] => 
                    [tr_commission_no] => 147258369
                    [ad_street] => Hugh-Greene-Weg und noch der Weg daneben
                    [ad_zipcode] => 22529
                    [ad_city] => Hamburg
                    [ad_country] => DE
                    [ad_modify] => 2013-09-04 15:07:16
                )

        )

    [tourservice] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [csc_id] => 1
                            [tr_sort] => 0
                            [srv_id] => 0
                            [trs_srv_name] => Grundpreis
                            [srvt_id] => 0
                            [trs_srvt_name] => PKW
                            [trs_price] => 0.0000
                            [trs_discount] => 0.0000
                        )

                    [1] => Array
                        (
                            [csc_id] => 1
                            [tr_sort] => 0
                            [srv_id] => 0
                            [trs_srv_name] => PLZ 20149 nach PLZ 22529
                            [srvt_id] => 0
                            [trs_srvt_name] => 
                            [trs_price] => 0.0000
                            [trs_discount] => 0.0000
                        )

                )

        )

    [tourarticle] => Array
        (
            [2] => Array
                (
                    [0] => Array
                        (
                            [trat_id] => 100
                            [tr_sort] => 2
                            [trat_sort] => 1
                            [at_id] => 65996
                            [trat_quantity] => 2
                            [trat_price] => 899.00
                            [trat_packingpieces] => 6
                            [trat_serialno] => 
                            [trat_state] => 0
                            [trat_remark] => Sofa-Mon.
                            [trat_createtime] => 0000-00-00 00:00:00
                            [trat_modify] => 2013-11-05 18:04:05
                            [at_eid] => AT100001
                            [at_name] => 00103135
                            [at_match] => IKEA
                            [at_description] => IKEA STHLM SO 3,5 GAMMELBO HBR
                            [at_barcode] => 00103135
                            [at_bundlequantity] => 1
                            [at_bundlecode] => 
                            [at_stk_itemquantity] => 1
                            [at_stk_areaquantity] => 1
                            [at_serialno] => 0
                            [at_totalweight] => 94.0000
                            [at_packingpieces] => 2
                            [at_timeunits] => 2
                        )

                    [1] => Array
                        (
                            [trat_id] => 101
                            [tr_sort] => 2
                            [trat_sort] => 2
                            [at_id] => 65997
                            [trat_quantity] => 3
                            [trat_packingpieces] => 12
                            [trat_serialno] => 
                            [trat_state] => 0
                            [trat_remark] => 
                            [trat_createtime] => 0000-00-00 00:00:00
                            [trat_modify] => 2013-11-05 18:04:10
                            [at_eid] => AT100002
                            [at_name] => 00118146
                            [at_match] => IKEA
                            [at_description] => KARLSTAD RÉCAGEST WEIPO
                            [at_barcode] => 00118146
                            [at_bundlequantity] => 1
                            [at_bundlecode] => 
                            [at_stk_itemquantity] => 1
                            [at_stk_areaquantity] => 1
                            [at_serialno] => 0
                            [at_totalweight] => 34.4000
                            [at_packingpieces] => 1
                            [at_timeunits] => 3
                        )

                )

        )

)


*/
?>
