<?php
/*=======================================================================
 *
 * scan_events.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

include_once("../include/auth.inc.php");
include_once("../include/inc_scan_events.inc.php");

//$dl = $_GET["dl"];
$jb_id = isset($_GET["jb_id"]) ? $_GET["jb_id"] : 0;

$min_es_date = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
$max_es_date = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));

$f_min_es_date = isset($_GET["from"]) ? $_GET["from"] : (isset($_POST["f_min_es_date"]) ? $_POST["f_min_es_date"] : "");
$f_max_es_date = isset($_GET["to"]) ? $_GET["to"] : (isset($_POST["f_max_es_date"]) ? $_POST["f_max_es_date"] : "");
if (trim($f_min_es_date) == ""):
  $f_min_es_date = $min_es_date;
else:
  $f_min_es_date = sqlDate($f_min_es_date);
endif;
if (trim($f_max_es_date) == ""):
  $f_max_es_date = $max_es_date;
else:
  $f_max_es_date = sqlDate($f_max_es_date);
endif;

$f_search_value = isset($_POST["f_search_value"]) ? trim($_POST["f_search_value"]) : "";
$f_open = isset($_POST["f_open"]) ? $_POST["f_open"] : "";
$f_disp = isset($_POST["f_disp"]) ? $_POST["f_disp"] : "";
$f_taken = isset($_POST["f_taken"]) ? $_POST["f_taken"] : "";
$f_finished = isset($_POST["f_finished"]) ? $_POST["f_finished"] : "";
$f_mode = isset($_POST["f_mode"][0]) ? $_POST["f_mode"][0] : "";
$f_no_OS = isset($_POST["f_no_OS"]) ? $_POST["f_no_OS"] : "";
$f_formsubmit = isset($_POST["f_formsubmit"]) ? $_POST["f_formsubmit"] : "";

$dates = array(
  $f_min_es_date,
  $f_max_es_date
);

if ($f_formsubmit == "Senden")
  echo "Das wäre jetzt gesendet worden";

writeLog_order_status("___________________________________________________________________________________");
if ($f_search_value != "" && $jb_id == 0):
  $jb_id = "";
  $sql_query = "SELECT jb_id FROM job WHERE jb_id = '" . $f_search_value . "'";
  $res = exec_query($sql_query);
  while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $jb_id .= $row['jb_id'] . ",";
  endwhile;
  mysql_free_result($res);
  if (substr($f_search_value, 0, 2) == "HA" || $f_no_OS == "") { // nur wenn nach Shipment-Nummen ("HA...") oder auch nach OS-Aufträgen gesucht wird
    $sql_query = "SELECT jb_id FROM tour WHERE tr_commission_no = '" . $f_search_value . "'";
    $res = exec_query($sql_query);
    while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
      $jb_id .= $row['jb_id'] . ",";
    endwhile;
    mysql_free_result($res);
  }
  if (substr($f_search_value, 0, 2) != "HA") { // Nur Ordernummern (also ohne 'HA' am Anfang) werden in 'info_%' gespeichert
    $sql_query = "SELECT gdc_obj_id FROM genericdatacontainer WHERE gdc_gen_fieldname LIKE 'info_%' AND gdc_content = '" . $f_search_value . "'";
    $res = exec_query($sql_query);
    while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
      $jb_id .= $row['gdc_obj_id'] . ",";
    endwhile;
    mysql_free_result($res);
  }

  if ($jb_id != "") {
    $jb_id .= $jb_id;
    $jb_id = substr($jb_id, 0, -1);
    $f_mode = "1";
  } else {
    $f_mode = "";
  }
endif;

if ($f_mode != "") {
  check_pickup_and_arr_tour($jb_id);
  $content = getScanEventsHtml($jb_id, $dates, false, $f_mode, $f_no_OS);
} else {
  $f_mode = "1";
  $f_no_OS = "1";
}
/**************************************************************************************************************************************************/
// HTML-Output

?>

<html>
<head>
<title>&Uuml;bersicht der Scan-Events</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
<!--
.verysmall
{ font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 2pt; font-weight: normal; padding: 0px}
-->
</style>
<script src="../js/jquery.js"></script>
<script type="text/javascript">
<!--

//var usr_name = '<?php echo $javascript_usr_name; ?>';

function popupWindow(url,title,config) {
  popup = window.open(url,title,config);
}

function ajaxRequestGet(url, data) {
  $.ajax({
     type: "GET",
     url: url,
     data: data,
     async: false,
     cache: false,
     success: function(msg){eval(msg);}
  });
}

function edit_event(sequence_no, lfd, bo_id, event_no, modeno, jb_id, jb_incoming_date) {
  var val = '';

  if (modeno == 0 && lfd != "set_status") {
    var datumzeit = document.getElementsByName(sequence_no + "_" + lfd)[0].value.split(" ");
    var datum = gueltigesDatum(datumzeit[0]);
    var zeit = gueltigeZeit(document.getElementsByName(sequence_no + "_" + lfd)[0].value.substr(datum.length));
    if (datum == "0" || zeit == "0") {
      alert("Falsche Datums-/Zeitangabe");
      return;
    }    
    val = sql_date(datum + " " + zeit);

//alert (sql2isodate(val) + " " + sql2isodate(jb_incoming_date));
    if (Date.parse(sql2isodate(val)) < Date.parse(sql2isodate(jb_incoming_date))) {
      alert("Falsche Datums-/Zeitangabe:\n\n" +
        "Das eingegebene Datum \"" + datum + " " + zeit + "\" liegt vor dem Eingangsdatum.");
      return;
    }
  } else if (modeno == 1 || lfd == "set_status") {
  	val = document.getElementsByName(sequence_no + "_" + lfd + "_select")[0].options[document.getElementsByName(sequence_no + "_" + lfd + "_select")[0].selectedIndex].value;
    if (lfd == "set_status") {
      if (!confirm("                Shipment Status \"" + document.getElementsByName(sequence_no + "_" + lfd + "_select")[0].options[document.getElementsByName(sequence_no + "_" + lfd + "_select")[0].selectedIndex].text + "\" setzen?\n\n" +
                   "Diese Aktion kann nicht rückgängig gemacht werden!")) {
        document.getElementsByName(sequence_no + "_" + lfd + "_select")[0].options.selectedIndex = 0;
        return;
      }
    }
  } else if (modeno == 2) {
    if (!confirm("                         Scan-Event löschen?\n\n" +
                 "Diese Aktion kann nicht rückgängig gemacht werden!"))
    return;
  }
//alert('sequence_no=' + sequence_no + '&event_no=' + event_no + "&val=" + val + "&bo_id=" + bo_id + "&mode=" + modeno + "&jb_id=" + jb_id);
  ajaxRequestGet('../include/ajaxReqScanEvent.php', 'sequence_no=' + sequence_no + '&event_no=' + event_no + "&val=" +
    val + "&bo_id=" + bo_id + "&mode=" + modeno + "&jb_id=" + jb_id);
  update_rows(sequence_no, retValue1, "eventTable");
  update_rows('', retValue2, "eventTableInternal");
}

function sql_date(local_date) {
  return local_date.substr(6, 4) + "-" + local_date.substr(3, 2) + "-" + local_date.substr(0, 2) + " " + local_date.substr(11, 5) + ':' + pad2(Math.floor(Math.random() * 60));
}

function pad2(n){
  return ("0" + n).slice(-2);
}

function sql2isodate(sql_date) {
  return sql_date.substr(0, 10) + "T" + sql_date.substr(11, 8);
}

function update_rows(sequence_no, new_rows_html, tableName) {
//alert(new_rows_html);
  var new_rows = new_rows_html.split("</tr><tr>");
  var newTbody = "";
  var cur_sequence_no = "";
//alert(new_rows[0])  ;
//alert(new_rows[1])  ;
  if (new_rows.length > 0) {
//    new_rows[0] = new_rows[0].substr(4);
    var myTable = document.getElementsByName(tableName)[0];
    var myTbody = myTable.getElementsByTagName("tbody")[0];
    var myRows = myTbody.getElementsByTagName("tr");
    if (tableName == 'eventTableInternal') {
      newTbody +=  "<tr>" + myRows[0].innerHTML + "</tr>";
    }
    var done = false;
    for(var i = 0; i < myRows.length; i++) {
      var myColumns = myRows[i].getElementsByTagName("td");
      if (typeof myColumns[1] !== 'undefined') {
      	if (myColumns[1].innerHTML != "")
      	  cur_sequence_no = myColumns[1].innerHTML;
        if (myColumns[1].innerHTML == sequence_no || (tableName == 'eventTableInternal' && !done)) {
          var j_start = 2;
          var new_rows_length = new_rows.length - 1;
          if (tableName == 'eventTableInternal') {
            var j_start = 0;
            new_rows_length = new_rows.length;
          }
          for (var j = j_start; j < new_rows_length; j++) {
//alert(new_rows[j]);
            newTbody +=  "<tr>" + new_rows[j] + "</tr>";
          }
          done = true;
   	    } else {
   	    	if (cur_sequence_no != sequence_no && tableName != 'eventTableInternal')
            newTbody += "<tr>" + myRows[i].innerHTML + "</tr>";
 	    	}
      } else {
        newTbody += "<tr>" + myRows[i].innerHTML + "</tr>";
      }
//alert(newTbody);
    }
    myTbody.innerHTML = newTbody;
  }
}

function disable_submit(id_tag) {
  document.getElementById(id_tag).disabled = true;
  document.getElementById(id_tag).style.background = '#CCCCCC';
  document.getElementById(id_tag).style.color = '#808080';
}

function check_submit1() {
  disable_submit('formsubmit1');
}

function check_submit2() { 
  var save_style_background = document.getElementById('formsubmit2').style.background;
  var save_style_color = document.getElementById('formsubmit2').style.color;
  
  disable_submit('formsubmit2');
  if (confirm("                Scan-Events an IKEA senden?\n\n" +
              "Diese Aktion kann nicht rückgängig gemacht werden!")) {
    document.getElementsByName('f_formsubmit')[0].value = "Senden";
    document.scan_events.submit();
  } else {
    document.getElementById('formsubmit2').disabled = false;
    document.getElementById('formsubmit2').style.background = save_style_background;
    document.getElementById('formsubmit2').style.color = save_style_color;
  }
}

// Quelle: http://aktuell.de.selfhtml.org/artikel/javascript/datumueberpruefen/
function gueltigesDatum (datum)
{
    //(Schritt 1) Fehlerbehandlung
 if (!datum) return false;
 datum=datum.toString();

    //(Schritt 2) Aufspaltung des Datums
 datum=datum.split(".");
 if (datum.length!=3) return false;

    //(Schritt 3) Entfernung der fuehrenden Nullen und Anpassung des Monats

 datum[0]=parseInt(datum[0],10);
 datum[1]=parseInt(datum[1],10)-1;

    //(Schritt 4) Behandlung Jahr nur zweistellig
 if (datum[2].length==2) datum[2]="20"+datum[2];

    //(Schritt 5) Erzeugung eines neuen Dateobjektes
 var kontrolldatum=new Date(datum[2],datum[1],datum[0]);

    //(Schritt 6) Vergleich, ob das eingegebene Datum gleich dem JS-Datum ist
 if (kontrolldatum.getDate()==datum[0] && kontrolldatum.getMonth()==datum[1] && kontrolldatum.getFullYear()==datum[2])
     return pad(datum[0]) + "." + pad(datum[1]+1) + "." + datum[2];
 else return "0";
}

function gueltigeZeit (zeit)
{
    //(Schritt 1) Fehlerbehandlung
 if (!zeit) return false;
 zeit=zeit.toString();

    //(Schritt 2) Aufspaltung der Zeit
 zeit=zeit.split(":");
 if (zeit.length!=2) return false;

    //(Schritt 3) Entfernung der fuehrenden Nullen
 zeit[0]=parseInt(zeit[0],10);
 zeit[1]=parseInt(zeit[1],10);
 
 if ((zeit[0] >= 0 && zeit[0] <= 23) && (zeit[1] >= 0 && zeit[1] <= 59))
   return pad(zeit[0]) + ":" +  pad(zeit[1]);
 else 
   return "0";
}

function pad(number) {
  if (number<=99) { number = ("0"+number).slice(-2); }
  return number;
}

function content_loaded() {
<?php if ($f_mode == "") echo "//  disable_submit('formsubmit2');\n"; ?>
}

document.addEventListener("DOMContentLoaded", content_loaded, false);

-->
</script>
</head>
<body>
  <table border="0" width="100%" cellspacing="0" cellpadding="0" vspace="<?php echo ($jb_id != 0) ? "10" : "0"; ?>" hspace="0">
    <tr>
      <td>
        &nbsp;
      </td>
      <td align="center">
        <table border="0" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
<?php if ($jb_id != 0 && $f_search_value == "") echo "<!--\n"; ?>
          <tr>
          	<td align="center"> <div class="f12bp1_blue">
              <br>
              &Uuml;bersicht der Scan-Events<br>
            <br></div>
        <form name="scan_events" action="scan_events.php" method="post"><div class="f10bp1_blue">
    <input type="radio" name="f_mode[]" value="0"<?php if ($f_mode == "0") echo " checked"; ?>>Eingangs-/
    <input type="radio" name="f_mode[]" value="1"<?php if ($f_mode == "1") echo " checked"; ?>>Ausf&uuml;hrungsdatum ab:&nbsp;
    <input name="f_min_es_date" type="text" size="9" maxlength="10" class="input"
      value="<?php echo ($f_min_es_date != "" ? formDate($f_min_es_date) : "") ?>">&nbsp;
    bis:&nbsp;
    <input name="f_max_es_date" type="text" size="9" maxlength="10" class="input"
      value="<?php echo ($f_max_es_date != "" ? formDate($f_max_es_date) : "") ?>">&nbsp;
    (<input type="checkbox" name="f_no_OS" value="1"<?php if ($f_no_OS == "1") echo " checked"; ?>>ohne Montagen&nbsp;)&nbsp;
    oder Suche: <input name="f_search_value" type="text" size="10" maxlength="11" class="input" value="<?php echo $f_search_value ?>">&nbsp;
    <input type="submit" id="formsubmit1" name="formsubmit1" size="2" value="Anzeigen" class="submit" onclick="check_submit1()"><br><br>
<!--
    <input type="button" id="formsubmit2" name="formsubmit2" size="2" value="Senden" class="submit" onclick="check_submit2()"><br><br>
      <input type="checkbox" name="f_open" value="1"<?php if ($f_open == "1") echo " checked"; ?>>UN-Dispo&nbsp;
      <input type="checkbox" name="f_disp" value="1"<?php if ($f_disp == "1") echo " checked"; ?>>Disposition&nbsp;
      <input type="checkbox" name="f_taken" value="1"<?php if ($f_taken == "1") echo " checked"; ?>>angenommen&nbsp;
      <input type="checkbox" name="f_finished" value="1"<?php if ($f_finished == "1") echo " checked"; ?>>erledigt<br><br>
-->
  <input type="hidden" name="f_open" value="1">
  <input type="hidden" name="f_disp" value="1">
  <input type="hidden" name="f_taken" value="1">
  <input type="hidden" name="f_finished" value="1">
  <input type="hidden" name="f_formsubmit" value="Anzeigen">
      </div>
        </form>              
            </td>
          </tr>
<?php if ($jb_id != 0 && $f_search_value == "") echo "-->\n"; ?>
          <tr>
          	<td align="center">
              <?php echo $content;?>
            </td>
          </tr>
        </table>
      </td>
      <td>
        &nbsp;
      </td>
    </tr>
  </table>
</body>
</html>
