<?php
/*=======================================================================
 *
 * motivationcounter.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/inc_calendar.inc.php");
include_once ("../include/html.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "f_business_volume", "f_password", "f_year", "f_month", "f_hqId", "f_sel_hq_id", "viewMode"));


// Parameters
$f_business_volume = str_replace (",", ".", $f_business_volume);
$listOfAmounts = "";
if ($f_hqId == "") : $f_hqId = $hq_id; endif;

$parMotivationCounterViewmodeBusinessVolume = getParameterValue("0", "MOTIVATIONCOUNTER_VIEWMODE_BUSINESS_VOL", "0");
if ($parMotivationCounterViewmodeBusinessVolume == "") : $parMotivationCounterViewmodeBusinessVolume = "0"; endif;

// Selected headquarters regarding the multiple headquarters view
if ($f_sel_hq_id == "") : $f_sel_hq_id = getColVectorFromDB2ArrayByClause("mandatorheadquarters AS mdhq, headquarters AS hq", "hq.hq_id", "mdhq.md_id = '" . $md_id . "' AND mdhq.hq_id = hq.hq_id", "", "hq.hq_mnemonic", ""); endif;
if (count($f_sel_hq_id) == 0) : array_push($f_sel_hq_id, $hq_id); endif;

// Current number of headquarters
$numOfSelHq = getCountOfTable("headquarters");

// Mode of view (single headquarters only or all headquarters)
if (!isset($viewMode) || $viewMode == "") : $viewMode = "0"; endif;
$viewMode_0 = "";
$viewMode_1 = "";
if ($viewMode == "0") : $viewMode_0 = "checked"; endif;
if ($viewMode == "1") : $viewMode_1 = "checked"; endif;


/* 
// Nach Mitarbeiter gesplittet
SELECT 
    count(jb.jb_id) AS count_jobs, 
    SUM(jb.jb_totalprice) as business_volume, 
    jb.emp_id
  FROM 
    job AS jb 
  WHERE 
    jb.jb_status = '2' AND 
    jb.hq_id IN (2) AND 
    (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND 
    jb.jb_finishtime >= '2010-01-01 00:00:00' AND 
    jb.jb_finishtime <= '2010-01-31 23:59:59' 
  GROUP BY jb.emp_id 
  ORDER BY emp_id
*/

function htmlDivLineSpacerBlack ($height = "10px", $width = "", $clear = "") {
	global $constMenuBackground;
	if ($width == "") : $width = "100%"; endif;
  return "<div style=\"width:" . $width . "; height:" . $height . ";" . ($clear != "" ? "clear:" . $clear . ";" : "") . " background: #000000\"> </div>";
}

// Gets checkboxes with headquarters
function getSelectionHeadquartersCheckboxes($f_sel_hq_id, $numOfSelHq) {
  $phpHeadquartersOut = "";
	if ($numOfSelHq != "" && is_numeric($numOfSelHq) && $numOfSelHq > 0) :
     $phpHeadquartersOut .= "<div style=\"color:#8888FF;\">";
     $phpHeadquartersOut .=   addCheckboxesFromTable("f_sel_hq_id","headquarters","hq_id","hq_mnemonic","hq_mnemonic","",$f_sel_hq_id, "&nbsp;&nbsp;&nbsp;","");
     $phpHeadquartersOut .= "</div>";
     $phpHeadquartersOut .= htmlDivLineSpacerBlack("10px");
     $phpHeadquartersOut .= defineButtonType10(getLngt("Alle"), "f_hq_sel_check_all", "hqSelectionCheckAll(" . $numOfSelHq . ");", "50px");
     $phpHeadquartersOut .= htmlDivLineSpacerBlack("5px");
     $phpHeadquartersOut .= defineButtonType10(getLngt("Keine"), "f_hq_sel_uncheck_all", "hqSelectionUncheckAll(" . $numOfSelHq . ");", "50px");
     $phpHeadquartersOut .= htmlDivLineSpacerBlack("5px");
     $phpHeadquartersOut .= defineButtonType10(getLngt("Aktualisieren"), "f_hq_sel_submit", "finishPage('');", "100px");
     $phpHeadquartersOut .= htmlDivLineSpacerBlack("10px", "", "left");
  endif;
  return $phpHeadquartersOut;
}

// Returns the statement to get the statistic of the sum of all jobs according to a specified datetime interval
// ONE HEADQUARTERS
function getCumulatedJobData ($fromDatetime, $toDatetime, $hqIds = "", $retMode = "0", $whereClause = "", $orderByClause = "") {
  global $db, $PHP_SELF;
	$retVal = "";

  if ($fromDatetime != "" && $toDatetime != "") :
     $whereClauseHq = "";
     if ($hqIds != "") : $whereClauseHq = " AND jb.hq_id IN (" . $hqIds . ") "; endif;
     if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
     if ($orderByClause == "") : $orderByClause = "count_jobs"; endif;

     // Exclude jobs for special customers
     $whereClauseExcludedCustomers = getParameterValue("0", "MOTIVATIONCOUNTER_EXCLUDED_CS", "0");
     $whereClauseExcludedCustomers = trim($whereClauseExcludedCustomers);
     if ($whereClauseExcludedCustomers != "") :
        $tmpArray = spliti(",", $whereClauseExcludedCustomers);
        $whereClauseExcludedCustomers = " AND cs.cs_eid NOT IN ('" . implode("','", $tmpArray) . "')";
     endif;
/*
     $sqlquery = "SELECT count(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) as business_volume" .
                 " FROM job AS jb" .
                 " WHERE jb.jb_status = '2' " . $whereClauseHq . " AND " .
                 "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND" .
                 "       jb.jb_finishtime >= '" . $fromDatetime . "' AND" .
                 "       jb.jb_finishtime <= '" . $toDatetime . "'" . $whereClause .
                 " ORDER BY " . $orderByClause;
*/
     $sqlquery = "SELECT count(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) as business_volume" .
                 " FROM job AS jb, costcenter AS csc, customer AS cs" .
                 " WHERE jb.jb_status = '2' " . $whereClauseHq . " AND " .
                 "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND" .
                 "       jb.jb_finishtime >= '" . $fromDatetime . "' AND" .
                 "       jb.jb_finishtime <= '" . $toDatetime . "' AND" . 
                 "       jb.csc_id_payer = csc.csc_id AND" .
                 "       csc.cs_id = cs.cs_id" . $whereClauseExcludedCustomers . $whereClause .
                 " ORDER BY " . $orderByClause;

     if ($retMode == "0") : return $sqlquery; endif;

     // Execute statement
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $count_jobs = $row["count_jobs"];
           $business_volume = $row["business_volume"];
     endwhile;
     $result->free();

     if ($retMode == "1") : $retVal = array($count_jobs, $business_volume); endif;
     if ($retMode == "2") : $retVal = $count_jobs; endif;
     if ($retMode == "3") : $retVal = round($business_volume, 2); endif;
  endif;

  return $retVal;
}

// Returns the statement to get the statistic of the sum of all jobs according to a specified datetime interval
function getCumulatedJobDataMultiHeadquarters ($fromDatetime, $toDatetime, $whereClause = "", $orderByClause = "", $excludedHQs, $f_sel_hq_id) {
	global $db, $PHP_SELF;
	$retVal = "";

  if ($fromDatetime != "" && $toDatetime != "") :
     $whereClauseHq = "";
     if ($excludedHQs != "") : $whereClauseHq = " AND jb.hq_id NOT IN (" . $excludedHQs . ") "; endif;
     if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
     if ($orderByClause == "") : $orderByClause = "count_jobs"; endif;
     
     // Exclude jobs for special customers
     $whereClauseExcludedCustomers = getParameterValue("0", "MOTIVATIONCOUNTER_EXCLUDED_CS", "0");
     $whereClauseExcludedCustomers = trim($whereClauseExcludedCustomers);
     if ($whereClauseExcludedCustomers != "") :
        $tmpArray = spliti(",", $whereClauseExcludedCustomers);
        $whereClauseExcludedCustomers = " AND cs.cs_eid NOT IN ('" . implode("','", $tmpArray) . "')";
     endif;
/*
     $sqlquery = "SELECT count(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) as business_volume, hq.hq_id, hq.hq_mnemonic" .
                 " FROM job AS jb, headquarters AS hq" .
                 " WHERE jb.jb_status = '2'" . $whereClauseHq . " AND " .
                 "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND" .
                 "       jb.jb_finishtime >= '" . $fromDatetime . "' AND" .
                 "       jb.jb_finishtime <= '" . $toDatetime . "'" . $whereClause . " AND" .
                 "       jb.hq_id = hq.hq_id" .
                 " GROUP BY jb.hq_id" .
                 " ORDER BY " . $orderByClause;
*/
     $sqlquery = "SELECT count(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) as business_volume, hq.hq_id, hq.hq_mnemonic" .
                 " FROM job AS jb, headquarters AS hq, costcenter AS csc, customer AS cs" .
                 " WHERE jb.jb_status = '2' AND" . 
                 "       jb.hq_id IN " . getSQLMandatorArray($f_sel_hq_id) . " AND" .
                 "       jb.hq_id = hq.hq_id" . $whereClauseHq . " AND " .
                 "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND" .
                 "       jb.jb_finishtime >= '" . $fromDatetime . "' AND" .
                 "       jb.jb_finishtime <= '" . $toDatetime . "' AND" .
                 "       jb.csc_id_payer = csc.csc_id AND" .
                 "       csc.cs_id = cs.cs_id" . $whereClauseExcludedCustomers . $whereClause .
                 " GROUP BY hq.hq_id" .
                 " ORDER BY " . $orderByClause;

     // Execute statement
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $hq_mnemonic = array();
     $count_jobs = array();
     $business_volume = array();
     while ($row = $result->fetch_assoc()):
           $hq_mnemonic[$row["hq_id"]] = $row["hq_mnemonic"];
           $count_jobs[$row["hq_id"]] = $row["count_jobs"];
           $business_volume[$row["hq_id"]] = $row["business_volume"];
     endwhile;
     $result->free();

     $retVal = array($hq_mnemonic, $count_jobs, $business_volume);
  endif;

  return $retVal;
}


// Set color of the difference amount
function getColorOfAmount ($percentValue) {
  $colorOfBalanceDue = "#FF0000";
  if ($percentValue >= 100) : 
     $colorOfBalanceDue = "#00FF00";
  elseif ($percentValue < 10) : 
     $colorOfBalanceDue = "#FF2200";
  elseif ($percentValue >= 10 && $percentValue < 20) : 
     $colorOfBalanceDue = "#FF5500";
  elseif ($percentValue >= 20 && $percentValue < 30) :
     $colorOfBalanceDue = "#FF9900";
  elseif ($percentValue >= 30 && $percentValue < 40) : 
     $colorOfBalanceDue = "#FFCC00";
  elseif ($percentValue >= 40 && $percentValue < 50) : 
     $colorOfBalanceDue = "#FFFF00";
  elseif ($percentValue >= 50 && $percentValue < 60) : 
     $colorOfBalanceDue = "#CCFF00";
  elseif ($percentValue >= 60 && $percentValue < 70) : 
     $colorOfBalanceDue = "#99FF00";
  elseif ($percentValue >= 70 && $percentValue < 80) : 
     $colorOfBalanceDue = "#55FF00";
  elseif ($percentValue >= 80 && $percentValue < 90) : 
     $colorOfBalanceDue = "#22FF00";
  elseif ($percentValue >= 90 && $percentValue < 100) : 
     $colorOfBalanceDue = "#00FF00";
  endif;
  return $colorOfBalanceDue;
};


$nameOfMonths = array("Jan.", "Feb.", "März", "April", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez.", );

$currentYear  = getDateTime("year");
$currentMonth = getDateTime("month");
$currentDay   = getDateTime("day");

$nameOfCurrentMonth = $nameOfMonths[($currentMonth - 1)];

$fromDatetime = $currentYear . "-" . $currentMonth . "-01 00:00:00";
$toDatetime   = $currentYear . "-" . $currentMonth . "-" . $currentDay . " 23:59:59";


$parMotivationCounterPreviousMonth = "";
if ($currentDay < 10) :
   $parMotivationCounterPreviousMonth = getParameterValue("0", "MOTIVATIONCOUNTER_PREVIOUS_MONTH", "0");
   if ($viewMode == "1") : $parMotivationCounterPreviousMonth = ""; endif;   // Disable if multi headquarters view
   if ($parMotivationCounterPreviousMonth == "1") :
   
      $firstDayOfLastMonth = date("Ym", mktime(0,0,0,date("m")-1,1,date("Y")));
      $lastMonth = substr($firstDayOfLastMonth, 4, 2);
      $yearOfLastMonth = substr($firstDayOfLastMonth, 0, 4);
      $lastDayOfLastMonth = $calMonthDays[($lastMonth - 1)];
      
      $nameOfLastMonth = $nameOfMonths[($lastMonth - 1)];
   
      $fromDatetimeLastMonth = $yearOfLastMonth . "-" . $lastMonth . "-01 00:00:00";
      $toDatetimeLastMonth   = $yearOfLastMonth . "-" . $lastMonth . "-" . $lastDayOfLastMonth . " 23:59:59";
   endif;
endif;


// *** STORE DATA BEGIN ***
if ($f_act == "storeAmount") :
   // Check for password
   $parMotivationcounterPassword = getParameterValue("0", "MOTIVATIONCOUNTER_PASSWORD", $f_hqId);
   if ($parMotivationcounterPassword != "" && $parMotivationcounterPassword == $f_password) :
      // Check for selected year and month
      if ($f_year != "" && $f_month != "") :
         $f_month = pad($f_month, 2);
         // Check for not overwriting months before
         if ($f_year . $f_month >= $currentYear . $currentMonth) :
            if ($f_business_volume != "" && is_numeric($f_business_volume)) :
               $parKey = "MOTIVATIONCOUNTER_" . $f_year . "_" . $f_month;
               if (existsEntry("parameter",array("par_key",$parKey,"emp_id","0","hq_id",$f_hqId))) :
                  updateStmt("parameter", "emp_id", "0", array("par_value", $f_business_volume), " par_key = '" . $parKey . "' AND hq_id = '" . $f_hqId . "'");
               else:
                  insertStmt("parameter", array("par_key", $parKey, "emp_id", "0", "par_value", $f_business_volume, "hq_id", $f_hqId));
               endif;
               $f_year = "";
               $f_month = "";
            else :
               $statusMessage = "Sie müssen bitte auch einen Betrag eingeben!";
            endif;
         else :
            $statusMessage = "Ältere Monate dürfen nicht überschrieben werden!";
         endif;
      endif;
   else :
      $statusMessage = "Das Passwort ist nicht korrekt!";
   endif;
endif;

if ($f_act == "listAmounts") :
   // Check for password
   $parMotivationcounterPassword = getParameterValue("0", "MOTIVATIONCOUNTER_PASSWORD", $hq_id);
   if ($parMotivationcounterPassword != "" && $parMotivationcounterPassword == $f_password) :
      // Get all parameters "MOTIVATIONCOUNTER_YYYY_mm" in database for the current headquarters
      $sqlquery = "SELECT par.par_key, par.par_value FROM parameter AS par"
                . " WHERE par.par_key LIKE 'MOTIVATIONCOUNTER_2%' AND"
                . "       par.hq_id = '". $hq_id . "' AND"
                . "       par.emp_id = '0'"
                . " ORDER BY par.par_key";
                
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      $insertFlag = TRUE;
      while ($row = $result->fetch_assoc()):
            $listOfAmounts .= "<tr>\n";
            $listOfAmounts .= "<td align=\"center\">" . substr($row["par_key"], 18, 4) . "</td>\n";   // Year extracted out of par_key
            $listOfAmounts .= "<td align=\"center\">" . substr($row["par_key"], 23, 2) . "</td>\n";   // Month extracted out of par_key
            $listOfAmounts .= "<td align=\"right\">" . number_format($row["par_value"], 2, ",", ".") . "</td>\n";                        
            $listOfAmounts .= "</tr>\n";
      endwhile;
      if ($listOfAmounts != "") :
         $listOfAmounts = "<div style=\"width:100%; padding: 0px; margin: 0px; border: 0px; outline: 0px; text-align:center; vertical-align:middle;\"><br><br><table border=\"0\" align=\"center\">\n" .
                          "<tr><td align=\"center\">&nbsp;<b>Jahr</b>&nbsp;</td><td align=\"center\">&nbsp;<b>Monat</b>&nbsp;</td><td align=\"center\">&nbsp;<b>Soll</b>&nbsp;</td></tr>\n" .
                          $listOfAmounts .
                          "</table></div>\n";
      endif;
      $result->free();
   else :
      $statusMessage = "Das Passwort ist nicht korrekt!";
   endif;
endif;
// *** STORE DATA END ***


// Check for output mode for only one headquarters or for all headquarters with exceptions
// If parameter is defined, only this specified mode will be used. Otherwise the selected viewmode by the user will be used
$parMotivationCounterMode = getParameterValue("0", "MOTIVATIONCOUNTER_MODE", "0");
if ($parMotivationCounterMode == "") : $parMotivationCounterMode = $viewMode; endif;
if ($parMotivationCounterMode == "") : $parMotivationCounterMode = "0"; endif;

if ($parMotivationCounterMode != "1") :
   // SINGLE HEADQUARTERS

   // Get values of the LAST MONTH if requested
   if ($parMotivationCounterPreviousMonth == "1") :
      $businessVolumeLastMonth = getCumulatedJobData($fromDatetimeLastMonth, $toDatetimeLastMonth, $hq_id, "3", "", "");
      $businessVolumeLastMonthOut = number_format($businessVolumeLastMonth, 2, ",", ".");
      
      $parBusinessVolumeLastMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $yearOfLastMonth . "_" . $lastMonth, $hq_id);
      if ($parBusinessVolumeLastMonth == "") : $parBusinessVolumeLastMonth = 0; endif;
      $parBusinessVolumeLastMonth = round($parBusinessVolumeLastMonth, 2);
      $parBusinessVolumeLastMonthOut = number_format($parBusinessVolumeLastMonth, 2, ",", ".");
      
      // Difference amount
      $balanceDueLastMonth = ($parBusinessVolumeLastMonth - $businessVolumeLastMonth);
      $balanceDueLastMonth = round($balanceDueLastMonth,2);
      if ($balanceDueLastMonth < 0) :
         $balanceDueLastMonth = $balanceDueLastMonth * (-1);
         $balanceDueLastMonthOut = number_format($balanceDueLastMonth, 2, ",", ".");
         $balanceDueLastMonthOut = "+&nbsp;" . $balanceDueLastMonthOut;
      else :
         $balanceDueLastMonthOut = number_format($balanceDueLastMonth, 2, ",", ".");
      endif;
      
      // Percent value
      $percentValueLastMonth = 0;
      $colorOfBalanceDueLastMonth = getColorOfAmount ($percentValueLastMonth);
      $percentValueLastMonthOut = "";
      if ($parBusinessVolumeLastMonth != "0") :
         $percentValueLastMonth = (($businessVolumeLastMonth / $parBusinessVolumeLastMonth) * 100);   
         $percentValueLastMonth = round($percentValueLastMonth, 2);
         $colorOfBalanceDueLastMonth = getColorOfAmount ($percentValueLastMonth);
         $percentValueLastMonthOut = "<div style=\"color:" . $colorOfBalanceDueLastMonth . "; font-size:10pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;\">" .
                            "[&nbsp;" . number_format($percentValueLastMonth, 2, ",", ".") . "&nbsp;%&nbsp;erreicht&nbsp;]" .
                            "</div>";
      endif;
      
      // Percent value bar
      $tmpPercentValue = round(($percentValueLastMonth * 4),0);
      $tmpPercentValue2 = (400 - $tmpPercentValue);
      $percentValueBarLastMonthOut .= "<img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\">";
      $percentValueBarLastMonthOut .= "<img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\">";
   endif;


   // Get values of the CURRENT MONTH

   // Get business volume of the current month done by finished jobs
   $businessVolume = getCumulatedJobData($fromDatetime, $toDatetime, $hq_id, "3", "", "");
   $businessVolumeOut = number_format($businessVolume, 2, ",", ".");

   // Get presetting set by leader
   $parBusinessVolumeCurrentMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $currentYear . "_" . $currentMonth, $hq_id);
   if ($parBusinessVolumeCurrentMonth == "") : $parBusinessVolumeCurrentMonth = 0; endif;
   $parBusinessVolumeCurrentMonth = round($parBusinessVolumeCurrentMonth, 2);
   $parBusinessVolumeCurrentMonthOut = number_format($parBusinessVolumeCurrentMonth, 2, ",", ".");

   // Difference amount
   $balanceDue = ($parBusinessVolumeCurrentMonth - $businessVolume);
   $balanceDue = round($balanceDue,2);
   if ($balanceDue < 0) :
      $balanceDue = $balanceDue * (-1);
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
      $balanceDueOut = "+&nbsp;" . $balanceDueOut;
   else :
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
   endif;

   // Percent value
   $percentValue = 0;
   $colorOfBalanceDue = getColorOfAmount ($percentValue);
   $percentValueOut = "";
   if ($parBusinessVolumeCurrentMonth != "0") :
      $percentValue = (($businessVolume / $parBusinessVolumeCurrentMonth) * 100);   
      $percentValue = round($percentValue,2);
      $colorOfBalanceDue = getColorOfAmount ($percentValue);
      $percentValueOut = "<div style=\"color:" . $colorOfBalanceDue . "; font-size:10pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;\">" .
                         "[&nbsp;" . number_format($percentValue, 2, ",", ".") . "&nbsp;%&nbsp;erreicht&nbsp;]" .
                         "</div>";
   endif;

   // Percent value bar
   $tmpPercentValue = round(($percentValue * 4),0);
   $tmpPercentValue2 = (400 - $tmpPercentValue);
   $percentValueBarOut .= "<img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\">";
   $percentValueBarOut .= "<img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\">";

else :
   // MULTI HEADQUARTERS

   // Get business volume of the current month done by finished jobs
   $multiArray = getCumulatedJobDataMultiHeadquarters($fromDatetime, $toDatetime, "", "", "203", $f_sel_hq_id);

   $hqMnemonicArray = $multiArray[0];
   $countJobsArray = $multiArray[1];
   $businessVolumeArray = $multiArray[2];

   // Business volume of the current headquarters
   $businessVolume = round($businessVolumeArray[$hq_id], 2);
   $businessVolumeOut = number_format($businessVolumeArray[$hq_id], 2, ",", ".");

   $parBusinessVolumeCurrentMonthArray = array();
   $percentValueArray = array();
   $outArray = array();

   $parBusinessVolumeCallingHqCurrentMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $currentYear . "_" . $currentMonth, $hq_id);
   if ($parBusinessVolumeCallingHqCurrentMonth == "") : $parBusinessVolumeCallingHqCurrentMonth = 0; endif;
   
   // Look for the own headquarters business volume before entering the loop to have an offset for displaying the bars only
   $parBusinessVolumeCurrentMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $currentYear . "_" . $currentMonth, $hq_id);
   if ($parBusinessVolumeCurrentMonth == "") : $parBusinessVolumeCurrentMonth = 0; endif;
   $parBusinessVolumeCurrentMonth = round($parBusinessVolumeCurrentMonth, 2);
   $percentOffsetValueOfOwnHq = 0;
   if ($parBusinessVolumeCurrentMonth != 0) :
      $percentOffsetValueOfOwnHq = (($businessVolumeArray[$hq_id] / $parBusinessVolumeCurrentMonth) * 100);
      $percentOffsetValueOfOwnHq = round($percentOffsetValueOfOwnHq, 2);
   endif;

   $tmpKeys = array_keys($businessVolumeArray);   // Headquarters IDs
   $tmpKeysLen = count($tmpKeys);
   for ($i = 0; $i < $tmpKeysLen; $i++) :
       $currHqId = $tmpKeys[$i];

       // Get presetting set by leader
       $parBusinessVolumeCurrentMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $currentYear . "_" . $currentMonth, $currHqId);
       if ($parBusinessVolumeCurrentMonth == "") : $parBusinessVolumeCurrentMonth = 0; endif;
       $parBusinessVolumeCurrentMonthArray[$currHqId] = round($parBusinessVolumeCurrentMonth, 2);

       // Percent value
       $percentValue = 0;
       if ($parBusinessVolumeCurrentMonth != 0) :
          // Percent value for fulfilling the target (balance due) of each headquarters
          $percentValue = (($businessVolumeArray[$currHqId] / $parBusinessVolumeCurrentMonth) * 100);   
          $percentValue = round($percentValue,2);

          // Percent value for comparison between the own headquarters regarding to the others using the business volumes
          $percentValueDelta = ((($businessVolumeArray[$currHqId] / $businessVolumeArray[$hq_id]) * 100) - 100);
          $percentValueDelta = round($percentValueDelta,2);

          // Percent value for absolute(!) comparison between the own headquarters regarding to the others
          $percentValueDeltaAbsolute = ((($businessVolumeArray[$hq_id] - $businessVolumeArray[$currHqId]) / $businessVolumeArray[$currHqId]) * 100);
          $percentValueDeltaAbsolute = round($percentValueDeltaAbsolute,2);
          
          // Percent value for relative(!) comparison between the own headquarters regarding to the others (=> better way to compare...)
          $percentValueDeltaRelative = 0;
          if ($parBusinessVolumeCallingHqCurrentMonth != "") :
             $percentValueDeltaRelative = ((($businessVolumeArray[$hq_id] / $parBusinessVolumeCallingHqCurrentMonth) * 100) - (($businessVolumeArray[$currHqId] / $parBusinessVolumeCurrentMonth) * 100));
             $percentValueDeltaRelative = round($percentValueDeltaRelative,2);
          endif;
       endif;
       if ($currHqId == $hq_id) :
          $colorOfBalanceDue = getColorOfAmount($percentValue);
          $parBusinessVolumeCurrentMonthOut = number_format($parBusinessVolumeCurrentMonth, 2, ",", ".");
       endif;

       // Percent value bar
       $tmpPercentValue = round(($percentValue * 4),0);
       $tmpPercentValue2 = (400 - $tmpPercentValue);
       // Percent value bar
       $tmpPercentValueDelta = $tmpPercentValue * ($businessVolumeArray[$currHqId] / $businessVolumeArray[$hq_id]);
       $tmpPercentValueDelta2 = (400 - $tmpPercentValueDelta);

       // Percent value bar for absolute comparison
       /*
       $tmppercentValueDeltaAbsolute = ($percentValueDeltaAbsolute / 15);   // Only for scaling the output
       $tmppercentValueDeltaAbsolute = round(($tmppercentValueDeltaAbsolute * 4),0);
       $tmppercentValueDeltaAbsolutePre = 200;
       $tmppercentValueDeltaAbsolutePost = 200;
       $outPercentBarImage = "spacer_green.jpg";
       if ($tmppercentValueDeltaAbsolute >= 0) :
          $tmppercentValueDeltaAbsolutePost -= $tmppercentValueDeltaAbsolute;
       else :
          $tmppercentValueDeltaAbsolute = abs($tmppercentValueDeltaAbsolute);
          $tmppercentValueDeltaAbsolutePre -= $tmppercentValueDeltaAbsolute;
          $outPercentBarImage = "spacer_red.jpg";
       endif;
       */

       // Percent value bar for relative comparison
       /*
       $tmpPercentValueDeltaRelative = round(($percentValueDeltaRelative * 4),0);
       $tmpPercentValueDeltaRelative2 = (400 - $tmpPercentValueDeltaRelative);
       */

       /*
       $outArray[$currHqId] = "<tr><td style=\"color:#00FF00\">" . $hqMnemonicArray[$currHqId] . "&nbsp;&nbsp;&nbsp;</td><td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\">" .
                              "<img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\"></td>" .
                              "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format($percentValue, 2, ",", ".") . "&nbsp;%</td></tr>\n";
       */
       $outArray[$currHqId]  = "<tr>\n";
       $outArray[$currHqId] .= "<td style=\"color:#00FF00\">" . $hqMnemonicArray[$currHqId] . "&nbsp;&nbsp;&nbsp;</td>\n";

       // Output bar for percent value
       // $outArray[$currHqId] .= "<td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\"><img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\"></td>\n";

       // Output bar for percent value of the comparison of the business volumes
       if ($currHqId == $hq_id) :
          $outArray[$currHqId] .= "<td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValueDelta . "\"><img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValueDelta2 . "\"></td>\n";
       else :
          $outArray[$currHqId] .= "<td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValueDelta . "\"><img src=\"../images/spacer_black.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValueDelta2 . "\"></td>\n";
       endif;

       // Output bar for percent value of absolute comparison
       /*
       if ($currHqId == $hq_id) :
          $outArray[$currHqId] .= "<td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\"><img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\"></td>\n";
       else :
          // $outArray[$currHqId] .= "<td><img src=\"../images/spacer_darkgrey.jpg\" border=\"0\" height=\"20\" width=\"" . $tmppercentValueDeltaAbsolutePre . "\"><img src=\"../images/" . $outPercentBarImage . "\" border=\"0\" height=\"20\" width=\"" . $tmppercentValueDeltaAbsolute . "\"><img src=\"../images/spacer_darkgrey.jpg\" border=\"0\" height=\"20\" width=\"" . $tmppercentValueDeltaAbsolutePost . "\"></td>\n";
          $outArray[$currHqId] .= "<td><img src=\"../images/spacer_black.jpg\" border=\"0\" height=\"20\" width=\"" . $tmppercentValueDeltaAbsolutePre . "\"><img src=\"../images/" . $outPercentBarImage . "\" border=\"0\" height=\"20\" width=\"" . $tmppercentValueDeltaAbsolute . "\"><img src=\"../images/spacer_black.jpg\" border=\"0\" height=\"20\" width=\"" . $tmppercentValueDeltaAbsolutePost . "\"></td>\n";
       endif;
       */

       // Output bar for percent value of relative comparison
       /*
       if ($currHqId == $hq_id) :
          $outArray[$currHqId] .= "<td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\"><img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\"></td>\n";
       else :
          $outArray[$currHqId] .= "<td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValueDeltaRelative . "\"><img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValueDeltaRelative2 . "\"></td>\n";
       endif;
       */

       // The current business volume
       if ($parMotivationCounterViewmodeBusinessVolume == "0") :
          $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format($businessVolumeArray[$currHqId], 2, ",", ".") . "&nbsp;€</td>\n";
       endif;

       // The debit of the month (balance due)
       // $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;[" . number_format($parBusinessVolumeCurrentMonth, 2, ",", ".") . "&nbsp;€]</td>\n";

       // Percent value for comparison between the headquarters regarding the business volumes
       if ($currHqId == $hq_id) :
          $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;&nbsp;</td>\n";
       else :
          $textColor = "color:#00FF00;";
          if ($percentValueDelta < 0) : $textColor = "color:#FF0000;"; endif;
          $outArray[$currHqId] .= "<td style=\"" . $textColor . " text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format(($percentValueDelta), 2, ",", ".") . "&nbsp;%</td>\n";
       endif;

       // Percent value for absolute(!) comparison between the headquarters
       /*
       if ($currHqId == $hq_id) :
          $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;&nbsp;</td>\n";
       else :
          $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format(($percentValueDeltaAbsolute), 2, ",", ".") . "&nbsp;%</td>\n";
       endif;
       */

       // Percent value for relative(!) comparison between the headquarters
       /*
       if ($currHqId == $hq_id) :
          $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format($percentValue, 2, ",", ".") . "&nbsp;%</td>\n";
       else :
          $outArray[$currHqId] .= "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format(($percentValueDeltaRelative), 2, ",", ".") . "&nbsp;%</td>\n";
       endif;
       */

       $outArray[$currHqId] .= "</tr>\n";
   endfor;

   // Sort and output of all bars
   $percentValueBarOut .= "<table align=\"center\">";
   $percentValueBarOut .= $outArray[$hq_id];
   $percentValueBarOut .= "<tr><td colspan=\"3\"><&nbsp;></td></tr>";
   for ($i = 0; $i < $tmpKeysLen; $i++) :
       $currHqId = $tmpKeys[$i];
       if ($currHqId != $hq_id) :
          $percentValueBarOut .= $outArray[$currHqId];
       endif;
   endfor;
   $percentValueBarOut .= "</table>";
   
   // Output of the percent value of the own headquarters
   $colorOfBalanceDue = getColorOfAmount ($percentValue);
   $percentValueOut = "";
   if ($parBusinessVolumeCurrentMonthArray[$hq_id] != "0") :
      $percentValue = (($businessVolume / $parBusinessVolumeCurrentMonthArray[$hq_id]) * 100);   
      $percentValue = round($percentValue,2);
      $colorOfBalanceDue = getColorOfAmount ($percentValue);
      $percentValueOut = "<div style=\"color:" . $colorOfBalanceDue . "; font-size:40pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;\">" . number_format($percentValue, 2, ",", ".") . "&nbsp;%</div>";
   endif;

   // Difference amount
   $balanceDue = ($parBusinessVolumeCurrentMonthArray[$hq_id] - $businessVolume);
   $balanceDue = round($balanceDue,2);
   if ($balanceDue < 0) :
      $balanceDue = $balanceDue * (-1);
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
      $balanceDueOut = "+&nbsp;" . $balanceDueOut;
   else :
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
   endif;
endif;

// Output
if ($f_year == "") : $f_year = $currentYear; endif;
if ($f_month == "") : $f_month = $currentMonth; endif;
?>


<html>
<head>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css"> 

<script type="text/javascript">

var refreshStatus = 1;
var statusMessage = "<?php echo $statusMessage ?>";

function displayStatusMessage() {
 if (statusMessage != "") {
    alert(statusMessage);
 }
};

function startReload() {  
  if (refreshStatus == 1) {
     // self.location.reload();
     document.forms[0].submit();
  }
}

function startTimeout() {  
  self.setTimeout("startReload()", 180000);
}

function finishPage(f_act) {
	document.forms[0].f_act.value = f_act;
  document.forms[0].submit();
}

function hqSelectionCheckAll(numOfSelHq) {
  for (i = 0; i < numOfSelHq; i++) {
	  document.getElementsByName('f_sel_hq_id[]')[i].checked = true;
	}
}

function hqSelectionUncheckAll(numOfSelHq) {
  for (i = 0; i < numOfSelHq; i++) {
  	if (document.getElementsByName('f_sel_hq_id[]')[i].value != '<?php echo $hq_id; ?>') {
	     document.getElementsByName('f_sel_hq_id[]')[i].checked = false;
	  }
  }
}
</script>
</head>

<body style="background:#777777; padding: 0px; margin: 0px; <div></div>border: 0px" onLoad="startTimeout();displayStatusMessage();">

  <form action="../tools/motivationcounter_neutral.php" method="post">

    <input type="hidden" name="f_act" value="">

    <?php 
      if ($parMotivationCounterMode == "0") :
         if ($parMotivationCounterPreviousMonth == "1") :
            echo htmlDivLineSpacerBlack("100px");
         else :
            echo htmlDivLineSpacerBlack("250px");
         endif;
      else : 
         echo htmlDivLineSpacerBlack("50px");
      endif; 
    ?>

    
    <?php if ($parMotivationCounterPreviousMonth == "1") : ?>
      <div style="width:100%; <?php if ($parMotivationCounterMode == "0") : echo "height:100px;"; endif; ?> padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
      	<?php if ($viewMode == "0" || ($viewMode == "1" && $parMotivationCounterViewmodeBusinessVolume == "0")) : ?>
          <div style="color:<?php echo $colorOfBalanceDueLastMonth ?>; font-size:40pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;">
           <span style="font-family: Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px; vertical-align:middle; color: #7777FF;"><?php echo $nameOfLastMonth ?>:</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $balanceDueLastMonthOut ?>&nbsp;€         
          </div>
          <?php echo htmlDivLineSpacerBlack("50px"); ?>
        <?php endif; ?>
        
        <?php echo $percentValueLastMonthOut ?>
        <?php echo htmlDivLineSpacerBlack("10px"); ?>
      
        <?php echo $percentValueBarLastMonthOut ?>
      </div>
      
      <?php echo htmlDivLineSpacerBlack("100px"); ?>
    
      <div style="width:100%; height:100px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
        <span style="font-family: Arial, Helvetica, sans-serif; font-size: 14pt; font-weight: normal; padding: 1px; color: #7777FF;">SOLL:&nbsp;&nbsp;&nbsp;<?php echo $parBusinessVolumeLastMonthOut ?>&nbsp;€</span>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span style="font-family: Arial, Helvetica, sans-serif; font-size: 14pt; font-weight: normal; padding: 1px; color: #7777FF;">IST:&nbsp;&nbsp;&nbsp;<?php echo $businessVolumeLastMonthOut ?>&nbsp;€</span>
      </div>
    
      <?php echo htmlDivLineSpacerBlack("100px"); ?>      
    <?php endif; ?>
    
    <div style="width:100%; <?php if ($parMotivationCounterMode == "0") : echo "height:100px;"; endif; ?> padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
    	<?php if ($viewMode == "0" || ($viewMode == "1" && $parMotivationCounterViewmodeBusinessVolume == "0")) : ?>
        <div style="color:<?php echo $colorOfBalanceDue ?>; font-size:40pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;">
        	<?php if ($parMotivationCounterPreviousMonth == "1") : echo "<span style=\"font-family: Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px; vertical-align:middle; color: #7777FF;\">" . $nameOfCurrentMonth . ":</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; endif; ?><?php echo $balanceDueOut ?>&nbsp;€
        </div>
        <?php echo htmlDivLineSpacerBlack("50px"); ?>
      <?php endif; ?>
      
      <?php echo $percentValueOut ?>
      <?php echo htmlDivLineSpacerBlack("10px"); ?>
    
      <?php echo $percentValueBarOut ?>
    </div>

    <?php 
      if ($parMotivationCounterPreviousMonth == "1") :
         echo htmlDivLineSpacerBlack("100px");
      else :
         echo htmlDivLineSpacerBlack("300px");
      endif;
    ?>

    <?php if ($viewMode == "0" || ($viewMode == "1" && $parMotivationCounterViewmodeBusinessVolume == "0")) : ?>
      <div style="width:100%; height:100px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
        <span style="font-family: Arial, Helvetica, sans-serif; font-size: 14pt; font-weight: normal; padding: 1px; color: #7777FF;">SOLL:&nbsp;&nbsp;&nbsp;<?php echo $parBusinessVolumeCurrentMonthOut ?>&nbsp;€</span>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span style="font-family: Arial, Helvetica, sans-serif; font-size: 14pt; font-weight: normal; padding: 1px; color: #7777FF;">IST:&nbsp;&nbsp;&nbsp;<?php echo $businessVolumeOut ?>&nbsp;€</span>
      </div>
    <?php endif; ?>
    
    <?php echo htmlDivLineSpacerBlack("20px"); ?>
    
    <div style="width:100%; height:50px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
    	<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px; color: #BBBBBB;">
        <input type="radio" name="viewMode" value="0" <?php echo $viewMode_0 ?> onChange="javascript:finishPage('')"> <?php echo getLngt("Nur die eigene Niederlassung") ?>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <input type="radio" name="viewMode" value="1" <?php echo $viewMode_1 ?> onChange="javascript:finishPage('')"> <?php echo getLngt("Alle Niederlassungen") ?>
      </span>
    </div>
    
    <?php echo htmlDivLineSpacerBlack("20px", "", "left"); ?>
    
    <?php 
      if ($viewMode == "1") :
    ?>
         <div style="width:100%; height:50px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
           <?php echo getSelectionHeadquartersCheckboxes($f_sel_hq_id, $numOfSelHq); ?>
         </div>
    <?php 
      endif;
    ?>
    
    <div style="width:100%; height:400px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background-image:url(../images/motivationcounterfade.png);">
    </div>

    <div style="width:100%; padding: 0px; margin: 0px; border: 0px; outline: 0px; text-align:center; vertical-align:middle;">
    	<select name="f_hqId"><?php echo addOptionsFromTable("headquarters","hq_id","hq_mnemonic","hq_id","",$f_hqId); ?></select>
    	&nbsp;&nbsp;
      <select name="f_year"><?php echo addOptionsFromRange($currentYear,$currentYear + 1,$f_year,"") ?></select>
      &nbsp;&nbsp;
      <select name="f_month"><?php echo addOptionsFromRange(1,12,$f_month,"") ?></select>
      &nbsp;&nbsp;
      Betrag:<input class="f8np1" type="text" name="f_business_volume" value="" size="15">
      (<a href="javascript:finishPage('listAmounts');">Liste</a>)
      &nbsp;&nbsp;
      Passwort:&nbsp;<input class="f8np1" type="password" name="f_password" value="" size="15">
      &nbsp;&nbsp;
      <a href="javascript:finishPage('storeAmount');">Speichern</a>
    </div>

    <?php echo $listOfAmounts ?>
</form>

</body>

</html>

