	<link rel="stylesheet" href="sITeditor/jquery/jquery-ui.min.css">
	<link type="text/css" rel="stylesheet" href="sITeditor/jquery/jquery-ui-timepicker-addon.css" />
	<link rel="stylesheet" href="sITeditor/jquery/tablesorter-master/css/theme.blue.css">
	<script src="sITeditor/jquery/jscolor.js"></script>
	<script src="sITeditor/jquery/jquery-3.3.1.min.js"></script>
	<script src="sITeditor/jquery/jquery-ui.min.js"></script>
	<script src="sITeditor/jquery/jquery-ui-timepicker-addon.js"></script>
	
	<script src="sITeditor/jquery/tablesorter-master/js/jquery.tablesorter.js"></script>
	<script src="sITeditor/jquery/tablesorter-master/js/jquery.tablesorter.widgets.js"></script>
	<script src="sITeditor/jquery/tablesorter-master/js/widgets/widget-math.js"></script>
	<script src="sITeditor/jquery/export-table/tableHTMLExport.js"></script>
	<script src="sITeditor/jquery/export-table/jspdf.min.js"></script>
	<script src="sITeditor/jquery/export-table/jspdf.plugin.autotable.js"></script>

	<script>
	// das ist die funktion iframe_dialog - 
	function open_iframe(php_file, save_enabled=false, tr_id=false) {
		//var wHeight = $(document).height();
		var wHeight =window.innerHeight;
        var dHeight = wHeight * 0.8;
		
		document.getElementById("iframe_dialog_iframe").style.display="";
		document.getElementById("iframe_dialog_iframe").src = php_file;
		
		if (save_enabled)
		{
			var buttons={
						"Cancel": function () {
							$(this).dialog("close");
							$("#edit_line").empty();
							location.reload();
						},
						"Save": function () {
								var iframe=$("#iframe_dialog_iframe").contents();
								
								// Wenn es eine class validatior_invalid gibt, dann soll die Form nicht abgesendet werden
								// ist nur bei autoedit notwendig - sonst eigentlich unnötig
								var input_required=iframe.find(".validator_invalid");
								//alert(input_required);
								if(input_required.val() == undefined)
								{
									iframe.find("#edit_line_form").submit();
									
									diag=$(this);
									setTimeout(function()
									{ 
										
										diag.dialog("close");
										//location.reload();
										
										//alert("hello");
									}, 500);
								}
							}											

			}
		}
		else
		{
			var buttons={
				"Cancel": function () 
				{
					$(this).dialog("close");
					$("#edit_line").empty();
					//location.reload();
					// Hier wird die Zeile neu geladen, weil ansonsten flackert das beim Reload
					reload_tr(tr_id);
					$(".tablesorter").trigger("update");
				}
			}
		}
		
		$( "#iframe_dialog" ).dialog({
							height: dHeight,
							width: "80%",
							buttons: buttons,
							// keinen X button zum closen anzeigen
							open: function(event, ui) {
								$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
							}
						});
		
	}
	</script>
<?php
	
require_once(__DIR__."/sITeditor_global_functions.php");
	
echo '<div id="iframe_dialog" width=80% style="width:80%; height:80%; display:none">
<iframe id="iframe_dialog_iframe" src="" frameborder="0" style="display:none; width:100%; height:100%"></iframe>
</div>';
	
function zeige_kapitel($tabelle, $konfiguration, $id, $name, $aktuelles_kapitel=0)
{
	$chapter_delete_string="";
	if (array_key_exists('delete', $konfiguration['chapter']))
	{
		$chapter_delete=$konfiguration['chapter']['delete'];
		if ($chapter_delete)
			$chapter_delete_string="<img onclick='delete_chapter(\"".$id."\")' src='sITeditor/images/sIT_delete.png'>";
	}
	
	$chapter_edit_string="";
	if (array_key_exists('edit', $konfiguration['chapter']))
	{
		$chapter_edit_php=$konfiguration['chapter']['edit'];
		// utf8_decode - ansonsten geht das §§ irgendwie nicht
		$chapter_edit_php=utf8_decode($chapter_edit_php);
		$chapter_edit_php=str_replace('§§id§§', $id, $chapter_edit_php );
		//echo "<br>".$chapter_edit_php. "ID:".$id;
		$chapter_edit_string="<img onclick='open_iframe(\"".$chapter_edit_php."\", true)' src='sITeditor/images/sIT_edit.png'>";
	}
	
	// Zeige die ID an
	echo "<tr  id='row-".$tabelle."_".$id."chapter'>";
	echo "<th>$chapter_delete_string $chapter_edit_string $aktuelles_kapitel : $name </th>";
	foreach ($konfiguration['fields'] as $feld)
	{
		$math="";
		if (in_array('table_list', $feld['view_options']))
		{
			// Wenn col Summe angezeigt werden soll
			if (array_key_exists('calculation', $feld))
			{
				$math='data-math="above-sum"';
			}
			$css=get_css_for_field($feld, 'css_table_list');
			echo "<th $math id='footer_".$tabelle."_".$feld['feldname']."' $css >";
			echo "</th>";
		}
	}
	echo "</tr>";
}

//  Funktion macht die übersicht Tabelle
//	Type:	text 			.... Der Text wird einfach ausgegeben, so wie er in der DB steht
//			array_lookup 	.... Schaut die Werte in einem Array nach und gibt den Wert ausgegeben
//									'array'		=> array ('0' => 'Nein','1' => 'Ja'	)
//	functions:	D			.... delete
function sIT_editor_tabelle($konfiguration, $id=false)
{
	$tabelle=$konfiguration['table'];

	if (isset($konfiguration['functions']['autoedit']) && $konfiguration['functions']['autoedit'])
	{
		echo "<script>
			$(document).ready (function ()
			{
			edit_line_dialog('".$id."', false, false);
			})
			</script>";
	}
	else
	{
		if (array_key_exists('chapter', $konfiguration))
		{
			$chapter_anzeigen=true;
			$chapter_table=$konfiguration['chapter']['table'];
			$chapter_id=$konfiguration['chapter']['id'];
			$chapter_view=$konfiguration['chapter']['view'];
			$chapter_number=$konfiguration['chapter']['number'];
		}
		else $chapter_anzeigen=false;
		
		$konfiguration=sIT_editor_view_user_search_filter($konfiguration);
		
		if (isset($konfiguration['functions']['download_csv']) && $konfiguration['functions']['download_csv'])
		{
			echo '<button id="download_csv" class="button orange" onclick="download_table_csv()" style="margin-top: 10px; margin-left: 20px;" >CSV Export</button>';
		}
		if (isset($konfiguration['functions']['download_pdf']) && $konfiguration['functions']['download_pdf'])
		{
			echo '<button id="download_pdf" class="button orange" onclick="download_table_pdf()" style="margin-top: 10px; margin-left: 20px;" >PDF Export</button>';
		}
		//<button id="download_pdf" class="button orange" onclick="download_table_pdf();" style="margin-top: 10px; margin-left: 20px;" >PDF Export</button>
		//<br><br><br>
	
		echo "<table id='sITtable_".$tabelle."' class='tablesorter sITtable_uebersicht'>";
		echo "<thead>";
		echo "<tr >";
		// Functions column
		$css="";
			if (array_key_exists('css', $konfiguration['functions']))
			{
				$css='style="'.$konfiguration['functions']['css'].'"';
			}
		echo "<th class='sorter-false' $css>";
		if (isset($konfiguration['functions']['add']) )
		{	// Nur wenn add auf false gesetzt ist, dann nicht anzeigen
			if ($konfiguration['functions']['add']!==false)	echo "<button onclick='edit_line_dialog(\"\")'>Add</button>";
		}
		else // Wenn add nicht gesetzt ist, dann auch anzeigen
		{	 // RFR: geändert am 09.04.2020
			//echo "<button onclick='edit_line_dialog(\"\")'>Add</button>";
		}
		echo "</th>";
		foreach ($konfiguration['fields'] as $feld)
		{
			if (in_array('table_list', $feld['view_options']))
			{
				$css=get_css_for_field($feld, 'css_table_list');
				$filter=get_tablesorter_default_filter_for_field($feld);
				echo "<th $css $filter>";
				echo $feld['header'];
				echo "</th>";
			}
		}
		echo "</tr>";
		echo "</thead>";

		// Footer wegen math
		echo "<tfoot>";
		echo "<tr>";
		// Functions column

		echo "<th>";
		echo "</th>";
		foreach ($konfiguration['fields'] as $feld)
		{
			$math="";
			if (in_array('table_list', $feld['view_options']))
			{
				// Wenn col Summe angezeigt werden soll
				if (array_key_exists('calculation', $feld))
				{
					$math='data-math="col-sum"';
				}
				$css=get_css_for_field($feld, 'css_table_list');
				echo "<th $math id='footer_".$tabelle."_".$feld['feldname']."' $css >";
				echo "</th>";
			}
		}
		echo "</tr>";
		echo "</tfoot>";
		
		echo "<tbody>";
		$kapitel=1;
		$orderby="";
		if (array_key_exists('orderby', $konfiguration))
		{
			$orderby=$konfiguration['orderby'];
		}
				
		$filter = get_filter($konfiguration);
		$user_search_filter = get_user_search_filter($konfiguration);
		//echo $filter . $user_search_filter;
		$sql="SELECT * from $tabelle $filter $user_search_filter $orderby";
		log_to_file("Anzeigen des Table: ".$sql);
		//echo $sql;
		$Q1=mysql_query($sql);
		if (! $Q1) echo "Fehler: ".mysql_error();
		$aktuelles_kapitel=0;
		while ($row=mysql_fetch_assoc($Q1))
		{
			$key=$konfiguration['key'];
			if ($chapter_anzeigen) 
			{
				// Wenn es ein neues Kapitel ist, dann anzeigen
				while ($aktuelles_kapitel<$row[$chapter_number]) 
				{
					//echo("Vor erstem Produkt :".$row['kapitel']." ".$aktuelles_kapitel);
					$sql2="SELECT $chapter_id, $chapter_view from $chapter_table $filter AND $chapter_number=$aktuelles_kapitel";
					//echo $sql2;
					$Q2=mysql_query($sql2);
					if (mysql_num_rows($Q2)>0)
					{
						while ($row2=mysql_fetch_assoc($Q2))
						{
							$angebot_kapitel_id=$row2[$chapter_id];
							zeige_kapitel($tabelle, $konfiguration, $angebot_kapitel_id, $row2[$chapter_view], $aktuelles_kapitel );
						}		
					}
					$aktuelles_kapitel++;
				}

				// Falls sich das Kapitel geändert hat, dann das Kapitel anzeigen
				if ($aktuelles_kapitel!=$row[$chapter_number]) 
				{
					$sql2="SELECT $chapter_id, $chapter_view from $chapter_table $filter AND $chapter_number=$kapitel";
					//echo $sql2;
					$Q2=mysql_query($sql2);
					$row2=mysql_fetch_assoc($Q2);
					$angebot_kapitel_id=$row2[$chapter_id];
					if ($chapter_anzeigen) zeige_kapitel($tabelle, $konfiguration, $angebot_kapitel_id, $row2[$chapter_view], $aktuelles_kapitel );
					$aktuelles_kapitel++;
				}
			}
			
			zeige_datenzeile_an($tabelle, $row, $key, $konfiguration);
		}
		
		if ($chapter_anzeigen)
		{
			// jetzt die letzte Zeile anzeigen bzw. erstellen
			$sql2="SELECT $chapter_id, $chapter_view, $chapter_number from $chapter_table $filter AND $chapter_number>=$aktuelles_kapitel ORDER by $chapter_number";
			//echo $sql2;
			$Q2=mysql_query($sql2);
			if (mysql_num_rows($Q2)>0)
			{
				while ($row2=mysql_fetch_assoc($Q2))
				{
					$angebot_kapitel_id=$row2[$chapter_id];
					if ($chapter_anzeigen) zeige_kapitel($tabelle, $konfiguration, $angebot_kapitel_id, $row2[$chapter_view],$row2[$chapter_number] );
				}		
			}
			// ansonsten neuen anlegen - zuerst höchste ID raussuchen
			else 
			{
				$sql="SELECT MAX($chapter_number) as max_kapitel FROM $chapter_table $filter";
				$Q1=mysql_query($sql);
				$row=mysql_fetch_assoc($Q1);
				$max_kapitel_id=$row['max_kapitel'];
				$max_kapitel_id++;
				// das where aus dem Filter rausschneiden, weil dort steht die Angebot ID drinnnen
				$where_setzen=str_replace("WHERE ", "", $filter);
				$sql3="INSERT INTO $chapter_table SET $chapter_number=$max_kapitel_id, $where_setzen";
				// Ende neues Kapitel einfügen
				mysql_query($sql3);
				//echo $sql3;
				//echo "Kein letztes Kapitel $max_kapitel_id";
				 zeige_kapitel($tabelle, $konfiguration, $max_kapitel_id, "", $max_kapitel_id );
			}
		}
		// Das hier ist für eine Zwischensumme
		//echo '<tr><th></th><th data-math="above-sum">above-sum</th></tr>';
		echo "</tbody>";
		
		echo "</table>";
		
		//sIT_javascript_feld($key, $row, $konfiguration['fields']['dummy1']);


	}
	echo '
	<div id="edit_line" title="Edit">
	  
	</div>';

	echo '<script>
	$( document ).ready(function() {
		//console.log( "ready!" );
		var $table = $("#sITtable_'.$tabelle.'");
							$table.tablesorter({
								theme : "blue",
								widthFixed : false,
								widgets: ["filter", "zebra", "resizable", "stickyHeaders", "math" ],
								//debug: true,
								widgetOptions : {
									resizable: true,
									filter_columnFilters: true,
									filter_searchDelay : 300,
									filter_saveFilters : true,
									math_data     : "math",
									math_event    : "recalculate",
								}
							});
	});
	
	// Submitted eine Form ohne reload - damit es nicht flackert!!
	function submitForm(form, successFn)
	{
		if (form.getAttribute("id")!="" || form.getAttribute("id")!=null){
			var id = form.getAttribute("id");
		} else {
			console.log("Form id attribute was not set; the form cannot be serialized");
		}
		
		$.ajax({
			type: form.method,
			url: form.action,
			data: $(form).serializeArray(),
			dataType: "json",
			success: successFn,
			//error: errorFn(data)
		});
	}
	
	//hier wird das Modal zum editieren aufgemacht
	function edit_line_dialog(key, copy_line = false, show_dialog=true, tr_id=false)
	{
		konfiguration=\''.urlencode(json_encode($konfiguration)).'\';
		$.ajax({
			url: "sITeditor/sITeditor_ajax_functions.php", 
			method : "POST",
			data : { funktion: "sIT_edit_line", key : key, konfiguration : konfiguration , copy_line: copy_line},
			success: function(result)
			{	
				$("#edit_line").append(result);
				
					
			}
		  });
  
		if (show_dialog)
		{
			$(document).ready( function ()
			{
			$( "#edit_line" ).dialog({
				//height: "auto",
				width: "80%",
				modal: true,
				position: ({
				   my: "top",
				   at: "top",
				   of: window
				}),
				resizable: true,
				autoResize: true, 
				closeOnEscape: false,
				dialogClass: "no-close",
				buttons: {
					"Save": function () {
						// Form nur submitten, wenn alle Felder ausgefüllt sind!
						if (validate_form()==false)
						{
							alert ("Error - please fill out all required fields");
							return(false);
						}
						else 
						{
							//$("form").submit();	
							//var formElement = document.getElementById("edit_line_form");
							//hier wird das letzte Form auf der Seite submitted 
							var formElement = document.forms[document.forms.length-1];
							submitForm(formElement, function() {
								console.log("Form submitted");
							});
							setTimeout(function()
							{
								
								$("#edit_line").empty();
								//$(this).dialog("close");
								$("#edit_line").dialog("close");
								reload_tr(tr_id);
							}, 500);
						}
						//reload_tr(tr_id);
					},
					"Cancel": function () {
						$(this).dialog("close");
						$("#edit_line").empty();
						
					}
				},
				// keinen X button zum closen anzeigen
				open: function(event, ui) {
					$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
				}
			});
			});
		}

		setTimeout(function() {
		$(".datepicker").datepicker({ dateFormat: "yy-mm-dd" });
		},1000);

	}
	
	// Entweder view oder delete wird hier aufgerufen - wenn delete_enabled dann delete Button anzeigen
	function view_line(key, delete_enabled = false)
	{
		//alert(key);
		konfiguration=\''.urlencode(json_encode($konfiguration)).'\';
		$.ajax({
			url: "sITeditor/sITeditor_ajax_functions.php", 
			data : { funktion: "view_line", key : key, konfiguration : konfiguration },
			method : "POST",
			success: function(result)
			{	
				//$("#edit_line").html(result);
				$("#edit_line").append(result);
				
					
			}
		  });
  
		// Wenn es ein delete ist, dann den delete Button anzeigen, ansonsten nur cancel, weil dann ist es view
		if (delete_enabled)
		{
			var buttons = {
			"Delete": function () {
									konfiguration=\''.urlencode(json_encode($konfiguration)).'\';
									$.ajax({
										url: "sITeditor/sITeditor_ajax_functions.php", 
										data : { funktion: "delete_line", key : key, konfiguration : konfiguration },
										method : "POST",
										success: function(result)
										{	
											//$("#edit_line").html(result);
											//$("#edit_line").append(result);
											$("#edit_line").dialog("close");
											$("#edit_line").empty();
											location.reload(); 
											
												
										}
									  });
								},
								"Cancel": function () {
									$(this).dialog("close");
									$("#edit_line").empty();
								}
			};
		}
		else
		{
			var buttons = {
						"Cancel": function () {
									$(this).dialog("close");
									$("#edit_line").empty();
								}
			};
		}
		
		$( "#edit_line" ).dialog({
							height: 300,
							width: "80%",
							modal: true,
                            resizable: true,
							dialogClass: "no-close",
							buttons: buttons
						});

						setTimeout(function() {
						$(".datepicker").datepicker({ 
							dateFormat: "yy-mm-dd",
							onSelect: function(){
									  $(this).change();
							 }
							});
						},1000);

	}
	
	//löschen
	function confirm_delete_line(key)
	{
		//alert(key);
		konfiguration=\''.urlencode(json_encode($konfiguration)).'\';
		$.ajax({
			url: "sITeditor/sITeditor_ajax_functions.php", 
			data : { funktion: "delete_line", key : key, konfiguration : konfiguration },
			method : "POST",
			success: function(result)
			{	
				//$("#edit_line").html(result);
				$("#edit_line").append(result);
				
					
			}
		  });
	}
	
	function delete_chapter(key)
	{
		//alert(key);
		konfiguration=\''.urlencode(json_encode($konfiguration)).'\';
		$.ajax({
			url: "sITeditor/sITeditor_ajax_functions.php", 
			data : { funktion: "delete_chapter", key : key, konfiguration : konfiguration },
			method : "POST",
			success: function(result)
			{	
				//$("#edit_line").html(result);
				//$("#edit_line").append(result);
				location.reload(); 
					
			}
		  });
	}
	</script>';

	
	
	echo '<script>
	
	function run_ajax(php_file) {
		$.ajax({
                url: php_file,
                dataType: "text",
                type: "post",
                contentType: "application/x-www-form-urlencoded",
                data: $(this).serialize(),
                success: function( data){
					$("#iframe_dialog").html(data);
                    //alert(data);
					//location.reload(); 
                }
            });
	
		var wHeight =window.innerHeight;
        var dHeight = wHeight * 0.8;
		
		var buttons={
							"Cancel": function () {
								$(this).dialog("close");
								$("#edit_line").empty();
								location.reload();
							}
		}	
		$( "#iframe_dialog" ).dialog({
								height: dHeight,
								width: "80%",
								buttons: buttons,
								// keinen X button zum closen anzeigen
								open: function(event, ui) {
									$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
								}
							});
		
	}
	
	function reload_tr(id)
	{
		//alert (id);

		konfiguration=\''.urlencode(json_encode($konfiguration)).'\';
		$.ajax({
			url: "sITeditor/sITeditor_ajax_functions.php", 
			data : { funktion: "zeige_eine_einzelne_datenzeile_an_ajax", id : id, konfiguration : konfiguration },
			method : "POST",
			success: function(result)
			{	
				//$("#sITtable_vk_angebot").append(result);
				if (id==false)
				{
					//alert(result);
					$("table tbody").prepend(result);
				}
				else $("#"+id).replaceWith(result);
				//alert(result);
				$(".tablesorter").trigger("update");
				//console.log(JSON.stringify(result));
			}
		  });
	}
	
	
	
	</script>';
	
	// und jetzt die javascripts einfügen
	echo '<script>
			$(document).ready (function ()
			{';
			$javascript="";
			if (array_key_exists('javascript', $konfiguration))
			{
				$javascript=$konfiguration['javascript'];
			}
			echo $javascript;
			
			// ein update auf die Tabelle machen, wenn mit javascript was eingefügt wurde, damit math neu rechnet
			echo '$("#sITtable_'.$tabelle.'").trigger("update");';
	echo '}); 
	';
	
	echo 'function download_table_csv()
	{
		// A4 Hochformat
		$("#sITtable_'.$tabelle.'").tableHTMLExport({
			
		  // csv, txt, json, pdf
		  type: "csv",

		  // file name
		  filename:"'.$tabelle.'.csv",
		  
		    // for csv
		  separator: ";",
		  newline: "\r\n",
		  trimContent: false,
		  quoteFields: false,

		  // CSS selector(s)
		  ignoreColumns: "",
		  ignoreRows: ".tablesorter-ignoreRow",
						
		  // your html table has html content?
		  htmlContent: false,
		  
		  // debug
		  consoleLog: true
		  
		});
	}
	
	function download_table_pdf()
	{
		// A4 Hochformat
		document.getElementById("sITtable_'.$tabelle.'").style.fontSize ="5px";
		var doc = new jsPDF("p", "mm", [297, 210]);
		doc.setFontSize(8);
		
		doc.autoTable({html: "#sITtable_'.$tabelle.'",
		        tableWidth: 200,
				styles: {overflow: "linebreak",  minCellWidth: 20, 
						cellPadding: 0.5, fontSize: number = 8}
		
				});
		doc.save("'.$tabelle.'");
	}
	</script>';
}


					
?>
<script>
// Funktion schneidet aus einem Feld gewisse Zeichen weg (default alle NICHT Ziffern wegnschneiden)
function regexp_zeichen_abschneiden(elem, regex=/[^\\d]/)
{
	wert=$(elem).val();
	//var re = new RegExp(regex,"g");
	//alert (wert);
	//wert=wert.replace(/[^\d]/,'');
	wert=wert.replace(regex,'');
	//wert=wert.replace(re,'');
	//alert(wert);
	$(elem).val(wert);
}
	
function validate_input_required(elem) 
{
	var input=elem;
	var is_name=input.val();
	if(is_name){
		input.removeClass('validator_invalid');
		input.addClass('validator_valid');
		}
	else{
		input.removeClass('validator_valid').addClass('validator_invalid');
	}
}

function validate_input_float(elem) 
{
	console.log(elem);
	var input=elem;
	var is_name=input.val();
	if(is_name)
	{
		if(! isNaN(is_name)){
			input.removeClass('validator_invalid');
			input.addClass('validator_valid');
		}
		else{
			input.removeClass('validator_valid').addClass('validator_invalid');
		}
	}	
	else{
		input.removeClass('validator_valid').addClass('validator_invalid');
	}
}

function check_alle_validation_fields()
{
	$(".validator_invalid").each(
	function()
	{
		//alert($(this).val);
		validate_input_required($(this));
	});
	$(".validator_valid").each(
	function()
	{
		validate_input_required($(this));
	});
}
// Checkt ob ein Formular richtig ist
// wenn es eine Klasse validator_invalid gibt, dann sind nicht alle Felder befüllt
function validate_form()
{
	check_alle_validation_fields();
	
	//alert(document.querySelector('.validator_invalid'));
	if (document.querySelector('.validator_invalid') !== null)
	{
		return (false);
	}
	else return (true);
	//if ($(".validator_invalid")[0])
	
}

</script>

