$(document).ready(function () {

  $("body").off("click", "#getBauteile");
  $("select").off('change');


  $("body").on("change", "select.aw", function() {
    var typToShow = $(this).val();
    if ( typToShow === "none" ) { 
    resetTable();
      return;
    }

    console.log( "Zeige Bauteile des Typs " + typToShow + " an ...");
    var arr = $.parseJSON(DB.getBauteile(typToShow));
    resetTable();
    getBauteile(arr);
  });

	$("body").on("click", "#getBauteile", function() {
		resetTable();
		getBauteile();
		$("#results").tablesorter();
	});

});

function resetTable() { $("#results").html("<thead><tr id=\"resultsHead\"><th>TXLCode</th><th>status</th><th>Abf-Dat</th><th>Mess-Dat</th><th>Rau-Dat</th><th>Lief-Dat</th><th>Lieferbox</th><th>Ofen</th><th>SchottOrderNr</th></tr></thead><tbody></tbody>"); }

function getBauteile(arr) { 
  
  
  $.each(arr, function(idx, ele){
  	var abfDate = ele.Abformdatum.split(" ");
  	var messDate = ele.Messdatum.split(" ");
  	var rauDate = ele.Rauheitsdatum.split(" ");
		var liefDate = ele.Lieferdatum
    var row = "";
		if ( abfDate[0] === "0000-00-00" ) { abfDate[0] = "-/-"; }
		if ( messDate[0] === "0000-00-00" ) { messDate[0] = "-/-"; }
		if ( rauDate[0] === "0000-00-00" ) { rauDate[0] = "-/-"; }
		if ( liefDate === "0000-00-00" ) { liefDate = "-/-"; }
  	
  	$tr = $('<tr id="SQLrow_' + ele.id + '">').append(
  		$('<td>').text(ele.TXLCode),
  		$('<td>').text(ele.status),
  		$('<td>').text(abfDate[0]),
  		$('<td>').text(messDate[0]),
  		$('<td>').text(rauDate[0]),
  		$('<td>').text(liefDate),
  		$('<td>').text(ele.Lieferbox),
  		$('<td>').text(ele.Ofen),
  		$('<td>').text(ele.SchottOrderNr)
  	).appendTo('#results');
  });
}