<?php

	#$time_start = microtime(true);
	$copyCustData=copyCustomerData();
	
	$custLogo=false;
	$custHtmlTxt=false;
	
	if(is_array($copyCustData) && count($copyCustData) == 2 ){
			if($copyCustData[0] != false)$custLogo=$copyCustData[0];
			if($copyCustData[1] != false)$custHtmlTxt=$copyCustData[1];
	}
	

	#$time_end = microtime(true);
	#$execution_time = $time_end - $time_start;
	
	if(isset($_GET['kennung'])) $kennung=$_GET['kennung'];
	else $kennung=false;
		
		switch ($kennung) {
			case "1024x600": $requestResolution="1024x600"; break;
			case "1024x768": $requestResolution="1024x768"; break;
			case "1280x800": $requestResolution="1280x800"; break;
			case "handy": $requestResolution="handy"; break;
			case "tablet": $requestResolution="tablet"; break;
			
			default: $requestResolution=false;	
			
		}
		
		
			#  session wird hier gelöscht, die Resolution wieder gesetzt, restliche Session werden im login.php gesetzt.
		if(!isset($_SESSION)){session_start();}
		if (!isset($_SESSION['print_start'])){$_SESSION['print_start'] = false;}
		
		if(isset($_SESSION['requested_resolution'])) unset($_SESSION['requested_resolution']);

		if($requestResolution != false){
			if(!isset($_SESSION)){session_start();	}
			$_SESSION['requested_resolution']=$requestResolution;
		}
	
	require_once("config/connect.php");
	require_once("config/pageConfig.php");	
	
	define('NUMLETTERPAD_ENABLER', 'ja');		//   'ja'
	define('NUMLETTERPAD_DELAY', '900');
	
	if(defined('GASTRO_VERSION') && strtolower(GASTRO_VERSION)=='ja' ) $pageTarget="tische.php";
	else $pageTarget="kassieren.php";
	if (isset($_REQUEST['bildschirm'])) $pageTarget="kuechenbildschirm_anzeigen.php?bildschirm=".$_REQUEST['bildschirm'];
	
	date_default_timezone_set('Europe/Vienna');
	
	
	require_once("include/upgrade.php");
	
	$checkLicensing=check_base_licensing();
	$checkLicensVerified=checkLicenseLastVerify('indexPage', false);
		# return oder -> $licVersion, $baseL, $userL, $gutscheinModul, $kassabuchModul, $lieferscheinModul
	if($checkLicensing[0] == false || $checkLicensing[1] == false || $checkLicensing[2] == false) {
		$lizenseWarning="<p style='font-size:1.5em; color:#e90808; font-weight:bold; margin:0; padding:0; line-height:1em;'>Unlizenzierte </p>";
	}
	else if($checkLicensVerified[1] != ''){
			$lizenseWarning=$checkLicensVerified[1];
	}
	else $lizenseWarning=false;

	
	function copyCustomerData(){
			$custDir="C:\sitpos\custdata\\";
			$custDirTarget= __DIR__ ."\kundendaten\\";
			$copyMsg="";
			$copyError=0;
			$copyCont=false;
			$logoPath=false;
			$htmlContPath=false;
			//echo $custDir."<br>";
			//echo $custDirTarget."<br>";
			//echo $custDir."<br>";
			if(is_dir($custDir) && is_dir($custDirTarget)){
				$custDirCont=scandir($custDir, 1);
				
				if(is_array($custDirCont)){
					$copyCont=0;
					$logoImg=false;
					for($i=0; $i < sizeof($custDirCont); $i++){
						$fType=strtolower(pathinfo($custDirCont[$i], PATHINFO_EXTENSION ));
						$fName=strtolower(pathinfo($custDirCont[$i], PATHINFO_FILENAME));
;						
						if($fType == 'jpg' || $fType == 'jpeg' || $fType == 'png' || $fType == 'gif' || 
									$fType == 'html' || $fType == 'txt') {
						
							$doCopy=copy($custDir.$fName.".".$fType, $custDirTarget.$fName.".".$fType);
							
							if(($fType == 'jpg' || $fType == 'jpeg' || $fType == 'png' || $fType == 'gif') && $fName== 'logo'){
								$logoPath='kundendaten/'.$fName.".".$fType;
							}
							else if($fType == 'html' && $fName == 'startseite'){
								$htmlContPath=file_get_contents('kundendaten/'.$fName.'.'.$fType);
							}
						}
					}
				}
				return array($logoPath, $htmlContPath);	
			}
			
			else return false;
				
		}
	
	
	
	


?>

<!doctype html>

<head>
	<meta charset="utf-8">
	<title>SITPOS</title>
	<?php echo META_DATA_INDEX; ?>
	<meta name="mobile-web-app-capable" content="yes">
	<style type="text/css">
		<?php include 'include/main.css'; 
			if($requestResolution == 'handy' || $requestResolution == 'tablet')  include 'include/mobile.css'; 
		?>
		
		
	</style>
	
	<?php 
		if($targetVersion==true || $resultContent == true){
			$logonDisable='disabled'; 
			?>
				<style type="text/css" > .logonButton{ opacity:.5; cursor:not-allowed; } 
										.logonButton:hover { background: -moz-linear-gradient(top,  #faa51a,  #f47a20); }
										.userButDiv { max-height:33%; overflow-y:hidden;			}
				</style>
			<?php
		}
		else $logonDisable='';
		
	
	
	?>

<script>
	function user_login(userId, pwdFunction){
		
	//	if(pwdFunction=='oopen'){  window.location.replace("kassieren.php");  }
	
	if ( pwdFunction == 'getIpFiled'){
			cclearErrorDiv();
			$(".logonButton").css({ "display":"none"	});
			loginWin="<input type='password' id='loginField' placeholder='Passwort' onfocus=\"cclearErrorDiv()\" /><input type='text' id='loginTmpField' /><button id='userLoginButton' class=' button orange loginButton' onclick=\"user_login('"+userId+"', 'readIpField')\" >Login</button><button id='userLoginButton' class=' button orange loginButton' onclick=\"user_login('', 'cCancel')\" >Abbrechen</button><div class='cclear'></div>";
			$("#loginDiv").html(loginWin);	
			$("#loginDiv, #loginOperationsDiv").css({'display':'block'});
			$('#loginField').focus();
		}
		else if ( pwdFunction == 'readIpField' || pwdFunction == 'nnone' || pwdFunction == 'autologin' ){
			if(pwdFunction == 'readIpField') userPwd=$('#loginField').val();
			else if(pwdFunction == 'autologin') userPwd=pwdFunction;
			else if(pwdFunction == 'nnone') userPwd="nnone";
			
			xmlhttp=GetXmlHttpObject();
			xmlhttp.open("POST", "user_login.php", false);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			sendCont="functionKey=logOn&userPwd="+userPwd+"&userId="+userId+"&pwdFunction="+pwdFunction;
			
			xmlhttp.send(sendCont);
			resp=xmlhttp.responseText;
			
			if( resp.toLowerCase().indexOf('error') >= 0){
				$('#errorDiv').html(resp); 
				$('#loginField').val("");
				setTimeout(function(){ $("#errorDiv").html(''); }, 3000);
			
			}
			
			
			else if (resp.toLowerCase().indexOf('success') >= 0){ 
			//	openIndexSelectDialog('selectPrinter', 'Auwahl vom mobilden Drucker', '', 'indexLoginDiv');
			
				window.location.replace("<?php echo $pageTarget; ?>"); }
			
			else {
				$('#errorDiv').html('Login Error !!!');
				$('#loginField').val("");
				setTimeout(function(){ $("#errorDiv").html(''); }, 3000);
			}
			
			
			
		}
		
		else if(pwdFunction == 'cCancel'){
			cclearErrorDiv();
			$("#loginDiv, #loginOperationsDiv").css({'display':'none'});
			$(".logonButton").css({ "display":"block"	});
			
		}
	}
	function cclearErrorDiv(){ $('#errorDiv').html(""); }
	

		   $(window).keypress(function(e) {
				var key = e.which;												// pressed Key wird inizialisiert
				if(key == 13){													// wenn enter
					getLastEnter=$("#autologinChecker").html();					// schaun wir uns die letzten gespeicherten zeichen an, ist ein div, da schriebt der browser nie rein, input könnte sein wenn focus
					logCode="out";												// mit out wird der vom Kellnerschloss kommende code beendet. 16 zeichen vor "out" ist der kellner KEY.s
					nx = getLastEnter.lastIndexOf(logCode);						// finde position of out im eingabestring
					if(nx >= 16 ){												//  wenn vor out kein 16 zeichen langer code steht ist es ungültig
						startPos=nx-16;											//  user code (Kellnerschloss Key) beginnt 16 zeichen vor "out"
						userCode=getLastEnter.substring(startPos, nx); 			//  schneiden den Key aus dem String						
						user_login(userCode, 'autologin' );						// wir übergeben hir anstelle der userID den kellnerschlosscode
						//	alert(getLastEnter+" / "+nx+" usercode: "+userCode+" usercodeLength: "+userCode.length);	
						$("#autologinChecker").html('');									// setzen das hidden textfeld auf leer
						return false;							
					}
					logCode="_";												// mit out wird der vom Kellnerschloss kommende code beendet. 16 zeichen vor "out" ist der kellner KEY.s
					nx = getLastEnter.lastIndexOf(logCode);						// finde position of out im eingabestring
					if(nx >= 16 ){												//  wenn vor out kein 16 zeichen langer code steht ist es ungültig
						startPos=nx-16;											//  user code (Kellnerschloss Key) beginnt 16 zeichen vor "out"
						userCode=getLastEnter.substring(startPos, nx); 			//  schneiden den Key aus dem String						
						user_login(userCode, 'autologin' );						// wir übergeben hir anstelle der userID den kellnerschlosscode
						//	alert(getLastEnter+" / "+nx+" usercode: "+userCode+" usercodeLength: "+userCode.length);	
						$("#autologinChecker").html('');									// setzen das hidden textfeld auf leer
						return false;							
					}
				}
			   else {															// irgend ein anderer keycode/character als "enter" keypress		
				var res = String.fromCharCode(key);							// wandeln den keycode in string um
				var tmpX=$("#autologinChecker").html();							// holen uns die letzten einträge aus dem selbst erstellten BUFFER, mitschreiber
				if(tmpX.length > 50){
					cPosA=tmpX.length-50;
					tmpX=tmpX.substr(cPosA, 50);							// limitieren die länge wie viel wir mitschreiben, wir müssen vorne wegschneiden
				}											
				var newVal= tmpX+res;											// fügen den aus dem feld geholten string mit dem neu hinzugekommen character zusammen
				$("#autologinChecker").html(newVal); 							// schreiben es wieder in das feld
			  }
		   });
		
			
	
	$(document).keypress(function(e) {
		if(e.which == 13 && $("#loginDiv").css("visibility") == 'visible') {
			$( "#userLoginButton" ).click();
		}
	});
		
	var clickCount=0;
	var padArray = new Array('V');
	
	
	var clicks = 0, timer = null;

		
			$(function(){
				$(".indexNumPadKey").on("click", function(e){
					var namPadDelay = $("#numpadDelayField").val();
					clicks++;
					
					var currId=$(this).attr('id');
					if(currId=='padCe'){
						$("#loginField").val("");
						clicks = 0; 
						return false;
					}
					else if(currId=='padC'){
						$("#loginField").val($("#loginField").val().slice(0, -1));
						clicks = 0; 
						return false;
					}
					else if(currId=='padEnter'){
						clicks = 0; 
						$( "#userLoginButton" ).click();
						return false;
					}
					
					dataArray=$(this).val().split('-|-');
					if(dataArray[1]== ''){
						padOp=dataArray[0];
						$("#loginTmpField").val(padOp);
						setTimeout(function(){ $("#loginTmpField").val(''); }, 1000);
						tmpIp=$("#loginField").val();
						pwdVal=tmpIp+padOp;
						$("#loginField").val(pwdVal);
						clicks = 0; 
					}
					else {
						setTimeout(function() {
							if(clicks==1){ padOp=dataArray[0];}		// regarding the amound of clicks, the relvant value will be taken from the array !
							else if(clicks==2){	padOp=dataArray[1];}
							else if(clicks==3){padOp=dataArray[2];}
							else if(clicks==4){padOp=dataArray[3];}
							else {
								clicks = 0; 						// if amound of clicks more than 4 break function
								return false;
							}
							$("#loginTmpField").val(padOp);
							setTimeout(function(){ $("#loginTmpField").val(''); }, 1000);	// shows the last input for 1 second in the tmp field
							tmpIp=$("#loginField").val();		// read out the currently value of the pwd field
							pwdVal=tmpIp+padOp;					// add the last inserted character to the read out val
							$("#loginField").val(pwdVal);		// write back the added value to the pawd field
							clicks = 0; 
						}, namPadDelay);
					}
				})
				.on("dblclick", function(e){
					e.preventDefault();  //cancel system double-click event
				});
			});
			
			
	function openIndexSelectDialog(callFrom=false, boxTitle, dialogContent=false, wrappEr=false){
		if(wrappEr == false){ wrappEr='wrapper';   }
		wrapHeight=$("#"+wrappEr).height();	
		dialogCssClass='generalDialogBox';
		buttonTxtLeft="Bestätigen";
		buttonTxtRight="Abbrechen";
		mminHeight=150;
		wwidth=600;
		pPosition="center";
		atPosition="center";
		
		if(callFrom == 'selectPrinter'){
			htmlContent='schau ma amoiiiiiiii';
		
		}
		
		$("#generalIndexDialog").html(htmlContent);
		$("#generalIndexDialog").dialog({

		});
	
	}
	
		
	/*         kp AJAX request 
	---------------------------------------------------------*/
	
	function GetXmlHttpObject(){
		if (window.XMLHttpRequest){return new XMLHttpRequest();}
		else if (window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP");}
    return null;
    }
	
	
	
</script>

</head>

<body>
	<div type="text" id="autologinChecker" ></div>	
	
	<div id="generalIndexDialog" ></div>
	
<?php
	

	function extendedNumPad(){
		$padArray=array(array('CE', '', '', '', 'padCe', ''), array('C', '', '', '', 'padC', ''), array('*', '', '', '', 'padMulti', ''), array('7', 's', 't', 'u', 'pad7', ''), 
						array('8', 'v', 'w', 'x', 'pad8', ''), array('9', 'y', 'z', '-', 'pad9', ''), array('4', 'j', 'k', 'l', 'pad4', ''), array('5', 'm', 'n', 'o', 'pad5', ''), 
						array('6', 'p', 'q', 'r', 'pad6', ''), array('1', 'a', 'b', 'c', 'pad1', ''), array('2', 'd', 'e', 'f', 'pad2', ''), array('3', 'g', 'h', 'i', 'pad3', ''), 
						array('0', '', '', '', 'pad0', ''), array('.', '', '', '', 'padPt', ''), array('Enter', '', '', '', 'padEnter', ''), 
		);
		
		
		
		$padOp="";
		for($i=0; $i < sizeof($padArray); $i++){
			if($padArray[$i][4]=='padCe' || $padArray[$i][4]=='padEnter' || $padArray[$i][4]=='padC') $classAd='_2'; 
			else if($padArray[$i][4]=='padMulti')$classAd='_3'; 
			else $classAd='';
	
			if(!defined('LOGIN_NUMMERNFELD_ERWEITERT') || LOGIN_NUMMERNFELD_ERWEITERT != 'ja' ){ 
				$padArray[$i][1] =''; $padArray[$i][2] =''; $padArray[$i][3] ='';
				$keyClass=' numPadNumberCenterDiv';
			}
			else $keyClass=' ';
			
			$padOp.="<button id='".$padArray[$i][4]."' class='indexNumPadKey floatL orange' 
						value='".$padArray[$i][0]."-|-".$padArray[$i][1]."-|-".$padArray[$i][2]."-|-".$padArray[$i][3]."' >							
							<div class='numPadNumberDiv".$classAd.$keyClass."' >".$padArray[$i][0]."</div>
							<div class='numPadLetterDiv'>".$padArray[$i][1].$padArray[$i][2].$padArray[$i][3]."</div>
				</button>";
			if($padArray[$i][4] == 'padMulti' || $padArray[$i][4] == 'pad9' || $padArray[$i][4] == 'pad6' || $padArray[$i][4] == 'pad3')$padOp.="<div class='cclear'></div>  ";
		
		}
			$padOp.="<div class='cclear'></div>";
		
		return $padOp;
	
	}
	
	if(isset($_SESSION['requested_resolution'])) $resSession=$_SESSION['requested_resolution'];
	else $resSession=false;
	
	
	if(preg_replace('/Version\s/', '', SITPOS_VERSION) != APPLICATION_VERSION) $displayVersion = "<strong>".SITPOS_VERSION." / ".APPLICATION_VERSION."</srong>";
	else $displayVersion=SITPOS_VERSION;
	
	$macAdr=getMacAddresses();
	
	$displayVersion .= " / ".$macAdr[0];
	if($custLogo!=false){
		$kassaLogo="src='".$custLogo."' style='margin:0 auto; display:block; max-height:100px;'";
	}
	else $kassaLogo=" class='indexLogo' src='images/sITposLogoWeb_.png'";

	echo '<div id="indexHeaderDiv" class="username" >
				<div style="width:100%; height:100%;"><img '.$kassaLogo.' /></div>
				<h2>'.$lizenseWarning."sITpos ".$displayVersion.'</h2>
				<h2><a href="https://start.teamviewer.com/device/" target="blank">Remote Support</a></h2>
			</div>'; 
	if($custHtmlTxt!=false) $xTraSytle="style='height:290px; overflow:auto;'";
	else $xTraSytle="";
	echo "<div id='indexLoginDiv' class='username' ".$xTraSytle."   >			
			<div class='userButDiv'>";
	
	$checkAusblCol = (mysql_num_rows(mysql_query("SHOW COLUMNS FROM benutzer LIKE 'ausblenden' "))) ? true : false;
	$addWhere="";
	if($checkAusblCol!==false){
		$addWhere="WHERE ausblenden = 0";
	}
		
	$sql="SELECT id, name, passwort FROM benutzer ".$addWhere." ";
	$sql_user = mysql_query($sql);
		if (! $sql_user)
		{
			echo "SQL Fehler: " . mysql_error();
			exit(1);
		}
		while ($row_user=mysql_fetch_assoc($sql_user))
		{
			$userId=$row_user['id'];
			if (isset($row_user['passwort']) && $row_user['passwort'] == true){
				$indic=" * ";
				$pwd=$row_user['passwort'];
				$pwdFunction='getIpFiled';
			}
			else {
				$indic="";
				$pwdFunction='nnone';

			}
			echo "<input type='button' ".$logonDisable."  class='button_kp logonButton floatL button_login orange' value='".$row_user['name']." ".$indic."' 
						onclick=\"user_login('".$userId."', '".$pwdFunction."')\" />";
			
			
		}
			echo "<div class='cclear'></div>
					</div>
				<div id='loginDiv'></div>
				<input type='hidden' id='numpadDelayField' value='".LOGIN_NUMMERNFELD_ERWEITERT_TRIMER."' />
				<div id='loginOperationsDiv'>
					<div id='errorDiv'></div>	
					<div id='logonNumberPad' >".extendedNumPad()."</div>
				</div>";
		$z="";
		for($i=0; $i<100; $i++){
			$z.=$i." - <br />";
		}
		
		echo "<div id='upgradeIxDiv' >
	
		".$ugForm."
		
		".$resultForm."
		".$resultMessage."
	
			</div>";
		
		
	
	echo '</div>';
	if($custHtmlTxt!=false){
		echo "<div class='indexCustomizeTxt' >".$custHtmlTxt."</div>";
	}

	/*
	// check foxit.exe
	exec("tasklist | findstr /i foxitreader.exe", $get_exe, $retval_exec);
	
	if ( $retval_exec )
	{

		if ($_SESSION['print_start'] == false)
		{
			$printer = mysql_fetch_array(mysql_query("SELECT win_drucker_name, drucker_margin_pdf, druckbreite, zoom_factor 
												FROM drucker WHERE LOWER(ist_rechnungsdrucker) = 'ja' "));
			if ($printer['druckbreite'] == true && $printer['druckbreite'] > 35) $bonWidth = $printer['druckbreite'];
			else $bonWidth = preg_replace('/[^\d]/', '', AUSDRUCK_GESAMTE_BREITE);
			
			$drucker = $printer[0];
			if(defined('PRINTER_ANSTEUERUNG') && PRINTER_ANSTEUERUNG == 'foxit'){
					$command='"C:\sitpos\FoxitReaderPortable\App\Foxit Reader\foxitreader.exe" /t "C:\sitpos\FoxitReaderPortable\App\blank.pdf" "'.$drucker.'" ';
					file_put_contents('kpcheckit.txt', "\n".basename( __FILE__)." / ". __LINE__ ."   seiteDrucken ansteuerung Foxit: ".PRINTER_ANSTEUERUNG."\n".$command, FILE_APPEND);
					exec($command, $output, $error_code);
					$_SESSION['print_start'] = true;
			}
		}

	}
	*/

?>
	<div style="display:block; height:22px; width:25%; border:none; position:relative; margin: 10px auto;"; >
		<button class="button orange" style="width:100%; padding:5px 0;" onclick='window.open("", "_self", "");window.close();return false;'>Fenster schlie&szlig;en</button>
		
	</div>
</body>
</html>