<?php
/**
 * Copyright (C) DairyWindow 2019
 * admin@dairywindow.nz
 */

	/* (C) DairyWindow 2012-2017 */

	$tickbox = "tick";
	$notickbox = "notick";
	$output = "";
	$number_of_ticks = 0;
	$spacing = 6;
	$limitarray = array('limitID'=>0);

	$sdarray = array();

	if(isset($_POST['confirm'])){
		//redirect to tests page
		header("HTTP/1.1 303 See Other");
		if(isset($_POST['extra'])) header("Location: test.php?t=".$_POST['extra']);
		else header("Location: test.php");
	}

	function callback1($m) {
		return string_to_math($m[1]);
	}
	function callback2($n, $m) {
		$o = $m[0];
		$m[0] = ' ';
		$m = trim($m);
		return $o=='+' ? $n + $m : ($o=='-' ? $n-$m : ($o=='*' ? $n*$m : $n/$m));
	}
	//Stolen from http://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions
	function string_to_math($s){
		while ($s != ($t = preg_replace_callback('/\(([^()]*)\)/','callback1', $s))) $s= $t;
		preg_match_all('![-+/*].*?[\d.]+!', "+$s", $m);
		return array_reduce($m[0], 'callback2');
	}

	if(!function_exists('stats_standard_deviation')) {
		//http://php.net/manual/en/function.stats-standard-deviation.php
		/**
		 * This user-land implementation follows the implementation quite strictly;
		 * it does not attempt to improve the code or algorithm in any way. It will
		 * raise a warning if you have fewer than 2 values in your array, just like
		 * the extension does (although as an E_USER_WARNING, not E_WARNING).
		 *
		 * @param array $a
		 * @param bool $sample [optional] Defaults to false
		 * @return float|bool The standard deviation or false on error.
		 */
		function stats_standard_deviation(array $a, $sample = false) {
			$n = count($a);
			if ($n===0) {
				trigger_error("The array has zero elements", E_USER_WARNING);
				return false;
			}
			if ($sample && $n===1) {
				trigger_error("The array has only 1 element", E_USER_WARNING);
				return false;
			}
			$mean = array_sum($a) / $n;
			$carry = 0.0;
			foreach ($a as $val) {
				$d = ((double) $val) - $mean;
				$carry += $d * $d;
			};
			if ($sample) {
			   --$n;
			}
			return sqrt($carry / $n);
		}
	}

	require "inc/connect.php";

	if(in_array($_SESSION['userSite'], array(4,7,8))) $odl = true;
	else $odl = false;

	if(isset($_POST['download']) && isset($_GET['r'])){ //output to CSV

		header('Content-Type: text/csv; charset=utf-8');

		$cypherID = clean($_GET['r']);
		$sql="
			Select
				dw_cypher.cypherText,
				dw_cypher.cypherOrderID,
				dw_cypher.cypherManuDate,
				dw_spec.specText,
				dw_location.locationText,
				dw_unit.unitText,
				dw_group.groupText,
				dw_test.testText,
				dw_result.resultFriendly
			From
				dw_result Left Join
				dw_unit
					On dw_result.resultUnit = dw_unit.unitID Left Join
				dw_test
					On dw_result.resultTest = dw_test.testID Left Join
				dw_location
					On dw_unit.unitLocation = dw_location.locationID Left Join
				dw_cypher
					On dw_unit.unitCypher = dw_cypher.cypherID Left Join
				dw_spec
					On dw_cypher.cypherSpec = dw_spec.specID Left Join
				dw_group
					On dw_test.testGroup = dw_group.groupID
			Where
				dw_cypher.cypherID = ? And
				dw_unit.unitActive = 1 And
				dw_group.groupActive = 1 And
				dw_test.testActive = 1 And
				dw_location.locationActive = 1 And
				dw_spec.specActive = 1
			Order By
				dw_cypher.cypherManuDate,
				dw_spec.specOrder,
				dw_group.groupOrder,
				dw_test.testOrder,
				LPad(dw_unit.unitText,20,0),
				dw_location.locationOrder
		";
		if(!$resultquery = mysqli_prepared_query($link, $sql, "i", array($cypherID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$resultarray = $resultquery[0];

		header('Content-Disposition: attachment; filename='.$resultarray['cypherText'].' '.$resultarray['cypherOrderID'].' '.$resultarray['specText'].'.csv');

		$fp = fopen('php://output', 'w'); //direct output to browser
		fputcsv($fp, array(
			'Cypher',
			'Batch/Order',
			'Date',
			'Product',
			'Location',
			'Sample',
			'Group',
			'Test',
			'Result',
		));

		foreach($resultquery as $resultarray){
			if(is_array($resultarray)) fputcsv($fp, $resultarray);
		}

		fclose($fp);
		exit();
	}

	if(isset($_POST['spreadsheet']) && isset($_GET['r']) && isset($_GET['f'])){
		header('Content-Type: text/csv; charset=utf-8');

		$unitsql="
			Select
				dw_unit.unitID,
				dw_unit.unitText,
				dw_spec.specText,
				dw_cypher.cypherText,
				dw_location.locationText
			From
				dw_unit Left Join
				dw_cypher
					On dw_unit.unitCypher = dw_cypher.cypherID Left Join
				dw_location
					On dw_unit.unitLocation = dw_location.locationID Left Join
				dw_spec
					On dw_cypher.cypherSpec = dw_spec.specID
			Where
				dw_cypher.cypherID = ? And
				dw_cypher.cypherSite = ? And
				dw_spec.specSite = ? And
				dw_spec.specActive = 1 And
				dw_cypher.cypherActive = 1 And
				dw_location.locationActive = 1 And
				dw_unit.unitActive = 1
			Order By
				Case dw_unit.unitText
					When 'F' Then 1
					When 'M' Then 2
					When 'L' Then 3
					Else 4
				End,
				Field(dw_unit.unitText, 'F', 'M', 'L', 'Comp', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2', 'Composite'),
				LPad(dw_unit.unitText,20,0),
				dw_location.locationOrder,
				dw_location.locationText
		";
		if(!$unitquery = mysqli_prepared_query($link, $unitsql, "iii", array($_GET['r'], $_SESSION['userSite'], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $unitsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$unitarray = $unitquery[0];

		header("Content-Disposition: attachment; filename=".$unitarray['cypherText']." ".$unitarray['specText'].".csv");

		$fp = fopen('php://output', 'w'); //direct output to browser

		//csv header
		$filearray = array();
		$filearray[] = " "; //group
		$filearray[] = " "; //test
		//if(!$unitquery = mysqli_prepared_query($link, $unitsql)) reporterror(get_error(), $unitsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		foreach($unitquery as $unitarray){
			$filearray[] = $unitarray['locationText'];
		}
		fputcsv($fp, $filearray);

		$filearray = array();
		$filearray[] = " "; //group
		$filearray[] = " "; //test
		foreach($unitquery as $unitarray){
			$filearray[] = $unitarray['unitText'];
		}
		fputcsv($fp, $filearray);

		$testsql="
			# get all the tests on the form
			Select
				dw_group.groupID,
				dw_group.groupText,
				dw_test.testID,
				dw_test.testText
			From
				dw_test Right Join
				dw_sub
					On dw_sub.subTest = dw_test.testID Left Join
				dw_form
					On dw_sub.subForm = dw_form.formID Left Join
				dw_group
					On dw_test.testGroup = dw_group.groupID
			Where
				dw_form.formID = ? And
				dw_group.groupActive = 1 And
				dw_group.groupSite = ? And
				dw_test.testActive = 1 And
				dw_test.testSite = ?
			Order By
				dw_group.groupOrder,
				dw_test.testOrder
		";
		if(!$testquery = mysqli_prepared_query($link, $testsql, "iii", array($_GET['f'], $_SESSION['userSite'], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $testsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		foreach($testquery as $testarray){

			$filearray = array();
			$filearray[] = $testarray['groupText'];
			$filearray[] = $testarray['testText'];

			//get units
			foreach($unitquery as $unitarray){

				$resultsql="
					# get result (if any)
					Select
						dw_result.resultFriendly
					From
						dw_result
					Where
						dw_result.resultTest = ? And
						dw_result.resultUnit = ?
				";
				if(!$resultquery = mysqli_prepared_query($link, $resultsql, "ii", array($testarray['testID'], $unitarray['unitID']), __FILE__, __LINE__)) reporterror(get_error(), $resultsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				$resultarray = $resultquery[0];
				$filearray[] = $resultarray['resultFriendly'];

			}
			fputcsv($fp, $filearray);
		}

		fclose($fp);
		exit();
	}

	if(isset($_POST['report'])){
		require('inc/pdf/tfpdf.php'); //allows utf-8, whereas /fpdf.php is windows-1252

		$subcontracted_text = "Ø";
		$accredited_text = "¤";

		$width["Extra" ] =  5;
		$width["Test"  ] = 55;
		$width["Method"] = 95;
		$width["Units" ] = 15;
		$width["Result"] = 20;
		//                190

		$width["Test2"     ] = 40;
		$width["Code"      ] = 55;
		$width["Lab name"  ] = 40;
		$width["Accredited"] = 20;
		$width["Authorised"] = 20;
		$width["Date"      ] = 15;
		//                    190

		if(isset($_GET['r']) && $_GET['r']!="") $cypher = clean($_GET['r']);
		else $cypher = 0;

		$is_accredited = false;

		class PDF extends tFPDF{
			// Page header
			function Header(){
				global $link;
				$this->AddFont('DejaVu','','DejaVuSans.ttf',true);
				$this->AddFont('DejaVu','B','DejaVuSans-Bold.ttf',true);
				$this->AddFont('DejaVu','I','DejaVuSans-Oblique.ttf',true);
				$this->AddFont('DejaVu','BI','DejaVuSans-BoldOblique.ttf',true);
				if(isset($_GET['r']) && $_GET['r']!="") $cypher = clean($_GET['r']);
				else $cypher = 0;

				if($this->PageNo()==1){
					$this->Image('images/cow_pdf.jpg',10,10,10);
					$this->Image("images/".$_SESSION['userSite']."/company_logo_pdf.jpg",170,10,10);
					$this->SetFont('DejaVu','',8);
					$x= $this->GetX(); $y= $this->GetY();
					$this->SetXY(150,17);
					$this->CellFitScale(50,8,"Address: ".$_SESSION['postal_addr1'],'',0,'C');
					$this->SetXY(150,20);
					$this->CellFitScale(50,8,"Email: ".$_SESSION['userEmail'],'',0,'C');
					$this->SetXY(150,23);
					$this->CellFitScale(50,8,"Phone number: ".$_SESSION['phone'],'',0,'C');
					$this->SetXY($x, $y);

					$this->SetFont('DejaVu','B',15);
					$this->Cell(60,10,'');//gap
					$this->Write(10,"Certificate of Analysis\n");
					$this->SetFont('DejaVu','B',10);

					$sql="
						Select
							dw_cypher.cypherText,
							dw_cypher.cypherOrderID,
							dw_cypher.cypherNotesFP,
							dw_cypher.cypherManuDate,
							dw_cypher.cypherExpiryDate,
							dw_spec.specText,
							dw_spec.specShortDesc
						From
							dw_cypher Inner Join
							dw_spec
								On dw_cypher.cypherSpec = dw_spec.specID
						Where
							dw_cypher.cypherID = ?
					";
					if(!$qry = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$array = $qry[0];

					$this->Write(8,"Cypher: ");
					$this->SetFont('DejaVu','',10);
					$this->Write(8, $array['cypherText']);
					$this->SetX(190/2);
					$this->SetFont('DejaVu','B',10);
					$this->Write(8,"Batch: ");
					$this->SetFont('DejaVu','',10);
					$this->Write(8, $array['cypherOrderID']."\n");

					if($array['cypherNotesFP']!=""){
						$this->SetFont('DejaVu','B',10);
						$this->Write(8,"Notes: ");
						$this->SetFont('DejaVu','',10);
						$this->Write(8, $array['cypherNotesFP']."\n");
					}

					$this->SetFont('DejaVu','B',10);
					$this->Write(8,"Manufacture date: ");
					$this->SetFont('DejaVu','',10);
					$this->Write(8,date('d/m/Y',strtotime($array['cypherManuDate'])));
					$this->SetX(190/2);
					$this->SetFont('DejaVu','B',10);
					$this->Write(8,"Expiry date: ");
					$this->SetFont('DejaVu','',10);
					$this->Write(8,date('d/m/Y',strtotime($array['cypherExpiryDate']))."\n");

					$this->SetFont('DejaVu','B',10);
					$this->Write(8,"Product: ");
					$this->SetFont('DejaVu','',10);
					$this->Write(8, $array['specText']);
					$this->SetX(190/2);
					$this->SetFont('DejaVu','B',10);
					$this->Write(8,"Description: ");
					$this->SetFont('DejaVu','',10);
					$this->Write(8, $array['specShortDesc']."\n");

				}else{
					$this->SetFont('DejaVu','BI',8);
					$this->Cell(190/2,5,'Reference: '.$cypher,'B');
					$this->Cell(190/2,5,'Report issued: '.date('d/m/y'),'B',1,'R');
					$this->ln(1);
				}
			}

			// Page footer
			function Footer(){
				$this->AddFont('DejaVu','I','DejaVuSans-Oblique.ttf',true);
				// Position at 1.5 cm from bottom
				$this->SetY(-15);
				// DejaVu italic 8
				$this->SetFont('DejaVu','I',8);
				// Page number
				$this->Cell(0,10,'Page '.$this->PageNo().' of {nb}',0,0,'C');
			}
			
			//Cell with horizontal scaling if text is too wide
      function CellFit($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $scale=false, $force=true){
        //Get string width
        $str_width= $this->GetStringWidth($txt);

        //Calculate ratio to fit cell
        if($w==0) $w = $this->w-$this->rMargin-$this->x;
        if($str_width==0) $ratio = ($w-$this->cMargin*2);
        else $ratio = ($w-$this->cMargin*2)/$str_width;

        $fit = ($ratio < 1 || ($ratio > 1 && $force));
        if ($fit){
          if ($scale)	{
            //Calculate horizontal scaling
            $horiz_scale= $ratio*100.0;
            //Set horizontal scaling
            $this->_out(sprintf('BT %.2F Tz ET', $horiz_scale));
          }else{
            //Calculate character spacing in points
            $char_space=($w-$this->cMargin*2-$str_width)/max($this->MBGetStringLength($txt)-1, 1)*$this->k;
            //Set character spacing
            $this->_out(sprintf('BT %.2F Tc ET', $char_space));
          }
          //Override user alignment (since text will fill up cell)
          $align='';
        }

        //Pass on to Cell method
        $this->Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);

        //Reset character spacing/horizontal scaling
        if($fit) $this->_out('BT '.($scale ? '100 Tz' : '0 Tc').' ET');
      }

      //Cell with horizontal scaling only if necessary
      function CellFitScale($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
          $this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, true, false);
      }

      //Cell with horizontal scaling always
      function CellFitScaleForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
          $this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, true, true);
      }

      //Cell with character spacing only if necessary
      function CellFitSpace($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
          $this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, false, false);
      }

      //Cell with character spacing always
      function CellFitSpaceForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
          //Same as calling CellFit directly
          $this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, false, true);
      }

      //Patch to also work with CJK double-byte text
      function MBGetStringLength($s){
        if($this->CurrentFont['type']=='Type0'){
          $len = 0;
          $nbbytes = strlen($s);
          for ($i = 0; $i < $nbbytes; $i++){
            if (ord($s[$i])<128)
              $len++;
            else{
              $len++;
              $i++;
            }
          }
          return $len;
        }
        else return strlen($s);
      }
			
		}
		
		// Instanciation of inherited class
		$pdf = new PDF();
		$pdf->AliasNbPages();
		$pdf->AddPage();
		$pdf->AddFont('DejaVu','','DejaVuSans.ttf',true);
		$pdf->AddFont('DejaVu','B','DejaVuSans-Bold.ttf',true);
		$pdf->AddFont('DejaVu','I','DejaVuSans-Oblique.ttf',true);
		$pdf->AddFont('DejaVu','BI','DejaVuSans-BoldOblique.ttf',true);

		$pdf->SetFillColor(222,222,222); //grey
		$pdf->SetFont('DejaVu','B',10);
		$pdf->CellFitScale($width["Extra" ],8,"",'TLB');
		$pdf->CellFitScale($width["Test"  ],8,"Test",'TB');
		$pdf->CellFitScale($width["Method"],8,"Method",'TB');
		$pdf->CellFitScale($width["Units" ],8,"Units",'TB');
		$pdf->CellFitScale($width["Result"],8,"Result",'TBR',1);

		$pdf->SetFillColor(255,255,255); //white
		$pdf->SetFont('DejaVu','',8);

		$sql="
			# get units from cypher
			Select
				dw_unit.unitID,
				dw_unit.unitText,
				dw_location.locationText
			From
				dw_unit Left Join
				dw_location
					On dw_unit.unitLocation = dw_location.locationID
			Where
				dw_unit.unitCypher = ?
			Order By
				Case dw_unit.unitText When 'F' Then 1 When 'M' Then 2 When 'L' Then 3 Else 4
				End,
				Field(dw_unit.unitText, 'F', 'M', 'L', 'Comp', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2', 'Composite'),
				LPad(dw_unit.unitText, 20, 0)
		";
		if(!$qry = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		foreach($qry as $array){
			$sql="
				Select
					dw_result.resultFriendly,
					dw_result.resultModDate,
					dw_unit.unitText,
					dw_location.locationText,
					dw_cypher.cypherText,
					dw_spec.specText,
					dw_test.testID,
					dw_test.testText,
					dw_test.testTextCOA,
					dw_test.testCode,
					dw_test.testMethod,
					dw_test.testUnits,
					dw_test.testAccredited,
					dw_group.groupText,
					dw_test.testLabName
				From
					dw_result Inner Join
					dw_unit On dw_result.resultUnit = dw_unit.unitID Inner Join
					dw_test On dw_result.resultTest = dw_test.testID Inner Join
					dw_location On dw_unit.unitLocation = dw_location.locationID Inner Join
					dw_cypher On dw_unit.unitCypher = dw_cypher.cypherID Inner Join
					dw_spec On dw_cypher.cypherSpec = dw_spec.specID Inner Join
					dw_group On dw_test.testGroup = dw_group.groupID
				Where
					dw_unit.unitID = ?
				Order By
					dw_group.groupOrder,
					dw_test.testOrder,
					dw_result.resultModDate DESC
			";
			if(!$qry2 = mysqli_prepared_query($link, $sql, "i", array($array['unitID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$spacing = 6;
			if(mysqli_prepared_num_rows($qry2)>0){ //dont show empty units
				$prevTestID = 0;
				$pdf->SetFont('DejaVu','B',10);
				$pdf->Write(9, $array['unitText']." ");
				$pdf->SetFont('DejaVu','',10);
				$pdf->Write(9, $array['locationText']."\n");
				$pdf->SetFont('DejaVu','',8);
				foreach($qry2 as $array2){
					$extra = "";
					if($array2['testID']!= $prevTestID){

						if($array2['testAccredited']!=1) $extra .= $accredited_text;
						else $is_accredited = true;
						if($array2['testLabName']!="") $extra .= $subcontracted_text;
						$pdf->CellFitScale($width["Extra" ], $spacing, $extra,'B');

						$pdf->CellFitScale($width["Test"  ], $spacing,clean($array2['testTextCOA'   ]),'B');
						$pdf->CellFitScale($width["Method"], $spacing,clean($array2['testMethod'    ]),'B');
						$pdf->CellFitScale($width["Units" ], $spacing,      $array2['testUnits'     ] ,'B');
						$pdf->CellFitScale($width["Result"], $spacing,      $array2['resultFriendly'] ,'B',1);
					}
					$prevTestID = $array2['testID'];
				}
			}
		}
		$pdf->SetTextColor(0,0,255);//blue
		$pdf->CellFitScale(190, $spacing,"Tests marked with '".$accredited_text."' are not under the scope of IANZ accreditation. Tests marked with '".$subcontracted_text."' are subcontracted to an external laboratory",'',1,'C');
		$pdf->SetTextColor(0);//black

		$pdf->AddPage();

		$pdf->SetFont('DejaVu','B',12);
		$pdf->CellFitScale(190,8,'Test summary','',1,'C');
		$pdf->SetFont('DejaVu','B',10);
		$pdf->CellFitScale($width["Test2"],8,'Test');
		$pdf->CellFitScale($width["Code"],8,'Code');
		$pdf->CellFitScale($width["Lab name"],8,'Lab name');
		$pdf->CellFitScale($width["Accredited"],8,'Accredited',0,0,'C');
		$pdf->CellFitScale($width["Authorised"],8,'Authorised');
		$pdf->CellFitScale($width["Date"],8,'Date','',1);
		$pdf->SetFont('DejaVu','',8);
		
		$sql="
			Select
				dw_test.testText,
				dw_test.testCode,
				dw_test.testMethod,
				dw_test.testUnits,
				dw_test.testLabName,
				dw_test.testAccredited,
				dw_user.userName,
				dw_user.userSignature,
				dw_resultrelease.releaseDate
			From
				dw_result Left Join
				dw_unit On dw_result.resultUnit = dw_unit.unitID Left Join
				dw_test On dw_result.resultTest = dw_test.testID Left Join
				dw_group On dw_test.testGroup = dw_group.groupID Left Join
				dw_cypher On dw_unit.unitCypher = dw_cypher.cypherID Left Join
				dw_resultrelease On dw_cypher.cypherID = dw_resultrelease.releaseCypher And
					dw_test.testID = dw_resultrelease.releaseTest Left Join
				dw_user On dw_resultrelease.releaseUser = dw_user.userID
			Where
				dw_cypher.cypherID = ?
			Group By
				dw_test.testID,
				dw_user.userName,
				dw_user.userSignature,
				dw_resultrelease.releaseDate
			Order By
				dw_group.groupOrder,
				dw_test.testOrder,
				dw_test.testText
		";
		if(!$qry3 = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$spacing = 7;
		foreach($qry3 as $array3){
			$pdf->CellFitScale($width["Test2"], $spacing,clean($array3['testText']),0,0,'',1);
			$pdf->CellFitScale($width["Code"], $spacing, $array3['testCode'],0,0,'',1);
			if($array3['testLabName']==""){
				$pdf->CellFitScale($width["Lab name"], $spacing, $_SESSION['comp_name']." Laboratory",0,0,'',1);
			}else{
				$pdf->CellFitScale($width["Lab name"], $spacing, $array3['testLabName'],0,0,'',1);
			}
			if($array3['testAccredited']==1) $accredited = "Yes";
			else $accredited = "No";
			$pdf->CellFitScale($width["Accredited"], $spacing, $accredited,0,0,'C',1);
			if(!empty($array3['releaseDate']) && !empty($array3['userSignature'])){
				if(file_exists("images/sigs/".$array3['userSignature'])) $image = "images/sigs/".$array3['userSignature'];
				else $image = "images/".$_SESSION['userSite']."/company_logo_pdf.jpg";
				$pdf->CellFitScale($width["Authorised"], $spacing, $pdf->Image($image, $pdf->GetX(), $pdf->GetY(),null, $spacing));
				$pdf->CellFitScale($width["Date"], $spacing,date('d/m/y',strtotime($array3['releaseDate'])),'',1);
			}else{
				$pdf->CellFitScale($width["Authorised"], $spacing," ");
				$pdf->CellFitScale($width["Date"], $spacing,"",'',1);
			}
		}

		if($is_accredited){
			$pdf->Line(10, $pdf->GetY(), 200, $pdf->GetY());

			//ianz logos
			$x=10;
			$y= $pdf->GetY()+5;
			foreach(scandir("images/".$_SESSION['userSite']) as $image){
				//files will only show if they are named using this convention: IANZxxxxxx.jpg
				$name = explode(".", $image);
				if(isset($name[0]) && isset($name[1]) && strtoupper(substr($name[0],0,4))=='IANZ' && $name[1]=='jpg'){ //has trouble with png's and transparency
					$pdf->Image("images/".$_SESSION['userSite']."/".$image, $x, $y,50);
					$x+=70;
					if($x>200){
						$x=10;
						$y+=20;
					}
				}
			}

			$pdf->SetY($pdf->GetY()+35);
			$pdf->CellFitScale(190,8,"All tests reported herein have been performed in accordance with the laboratories scope of accreditation, unless otherwise specified.",0,1,'C');
			$pdf->SetFont('DejaVu','B',10);
			$pdf->CellFitScale(190,8, $_SESSION['comp_name_long']." is a Recognised Laboratory under the Ministry of Primary Industries Recognised Laboratory Program.",0,1,'C');
		}

		$pdf->Output();
		exit();
	}

	require "inc/fade.php";
	require "inc/enteroos.php";

	$title = "Results";
	require "inc/head.php";
	$menu = "results";
	require "inc/menu.php";

	if($_SESSION['userLevel'] <= $_SESSION['results_results_delete']) $allowdelete = true;
	else $allowdelete = false;
	if($_SESSION['userLevel'] <= $_SESSION['results_results_add']) $readonlystatus = '';
	else $readonlystatus = 'readonly';

	if($debug) showdebug();
	require "inc/texttonumber.php";
	require "inc/numbertotext.php";

	if(isset($_GET['f']) && $_GET['f']!='') $formid = $_GET['f'];
	else $formid = 0;

	$tabindex = 2;
	$specstyle = 1;

	if((isset($_GET['r']) && $_GET['r']!="") || (isset($_POST['cypherid']) && $_POST['cypherid']!='' && $_POST['cypherid']!=0)){
		//cypherid is set if the use has just added a new cypher from inc/calendar.php
		if(isset($_GET['r']) && $_GET['r']!="") $r = clean($_GET['r']);
		if(isset($_POST['cypherid']) && $_POST['cypherid']!='' && $_POST['cypherid']!=0) $r = clean($_POST['cypherid']);
		$sql="
			# r is set, get date from cypherid for c
			Select
				dw_cypher.cypherManuDate,
				dw_cypher.cypherOrderID,
				dw_cypher.cypherText,
				dw_spec.specText,
				dw_spec.specStyle,
				dw_cypher.cypherNotesFP
			From
				dw_spec Right Join
				dw_cypher
					On dw_spec.specID = dw_cypher.cypherSpec
			Where
				dw_cypher.cypherID = ? And
				dw_cypher.cypherSite = ?
		";
		if(!$cypherquery = mysqli_prepared_query($link, $sql, "ii", array($r, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$cypherid = $r;
		if(mysqli_prepared_num_rows($cypherquery)>0){
			$cypherarray = $cypherquery[0];
			$c = $cypherarray['cypherManuDate'];
			$specstyle = $cypherarray['specStyle'];
		}else{
			$c = date('Y-m-d');
		}
	}else{
		$cypherid = 0;
		if(isset($_GET['c']) && $_GET['c']!="") $c = $_GET['c'];
		else $c = date('Y-m-d');
	}

	if(isset($_POST['save']) && ((isset($_POST['new_sample']) && $_POST['new_sample']=='') || !isset($_POST['new_sample']))){
		foreach($_POST as $key => $value){
			if($key[0]=='u'){ //new result
				$newkey = explode('t', $key);
				$unitID = substr($newkey[0],1); //minus 1st character (u)
				$testID = $newkey[1];

				if($debug){
					echo "
						value: ".$value."<br>
						unitID: ".$unitID."<br>
						testID: ".$testID."<br>
					";
				}

				if($value!='' && $value!='0'){

					$value = str_replace(',','', $value); //remove commas
					$value = str_replace('()','', $value); //remove brackets
					$sql="
						# get existing result (for comparison), if it exists
						Select
							dw_result.resultID,
							dw_result.resultFriendly
						From
							dw_result
						Where
							dw_result.resultUnit = ? And
							dw_result.resultTest = ?
						Order By
							dw_result.resultModDate Desc
						Limit 1
					";
					if(!$resultquery = mysqli_prepared_query($link, $sql, "ii", array($unitID, $testID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$resultarray = $resultquery[0];
					if(mysqli_prepared_num_rows($resultquery)==0 || strtolower($resultarray['resultFriendly'])!=strtolower($value)){
						if(empty($value) || $value==='()'){
							if($debug) echo "Result '".$value."' NOT inserted";
						}else{
							$value = str_replace('&lt;','<',$value);
							$value = str_replace('&gt;','>',$value);
							if(substr($value,0,1)==".") $value = "0".$value; // if someone enters .1 convert to 0.1
							if(empty($resultNotes)) $resultNotes = 'Manual entry';
							//insert new result
							$sql="# insert new result (not calc)
								INSERT INTO dw_result         (resultFriendly, resultUnit, resultTest,  resultNotes, resultModUser, resultModDate)
								VALUES                        (      ?       ,       ?   ,       ?   ,        ?    ,       ?      ,     now()    )";
							$params =                       '      s               i           i            s            i                      ';
							$values =                  array(    $value    ,   $unitID ,   $testID , $resultNotes, $_SESSION['userID']         ) ;
							if(!savesql($link, $sql, $params, $values, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							enteroos($value, $unitID, $testID, $_SESSION['userSite']);
							if($debug) echo "Result ".$value." inserted";
						}
					}else{
						//result already exists
						if($debug) echo "Result already exists: Unit ".$unitID.", test ".$testID.", result ".$resultarray['resultFriendly'].", rID ".$resultarray['resultID'];
					}
				}else{
					if($debug) echo "value is blank or zero, may be a calculation?<br>";
					$sql="
						Select
						  dw_calc.calcText1,
						  dw_calc.calcTest1,
						  dw_calc.calcText2,
						  dw_calc.calcTest2,
						  dw_calc.calcText3,
						  dw_calc.calcTest3,
						  dw_calc.calcText4,
						  dw_calc.calcTest4,
						  dw_calc.calcText5
						From
						  dw_calc Right Join
						  dw_test On dw_test.testCalc = dw_calc.calcID
						Where
						  dw_test.testID = ? And
						  dw_calc.calcID != 0
					";
					if(!$calcquery = mysqli_prepared_query($link, $sql, "i", array($testID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if($debug) echo '<br>';
					$calc_numrows = mysqli_prepared_num_rows($calcquery);
					if($calc_numrows>0){
						if($debug) echo 'calc_numrows>0<br>';
						$calcarray = $calcquery[0];

						$string = "";

						$sql="
							Select testText, testFormat, testRound
							From dw_test
							Where testSite = ? And testID = ?
						";
						if(!$calctquery = mysqli_prepared_query($link, $sql, "ii", array($_SESSION['userSite'], $testID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						$calcTest   = $calctquery[0];
						$testText   = clean($calcTest['testText']);
						$testFormat = $calcTest['testFormat'];
						$testRound  = $calcTest['testRound'];

						//now to get results for each test
						$resultavg = array();
						$calc = true;
						for($i=1; $i<=4; $i++){
							if($calcarray['calcTest'.$i]!='' && $calcarray['calcTest'.$i]!=null && $calcarray['calcTest'.$i]!=0){
								$sql="
									# get result for each test
									Select
										dw_result.resultFriendly,
										dw_test.testFormat,
										dw_test.testRound
									From
										dw_result Left Join
										dw_test
											On dw_result.resultTest = dw_test.testID Left Join
										dw_unit
											On dw_result.resultUnit = dw_unit.unitID
									Where
										dw_result.resultTest = ? And
										dw_test.testSite = ? And
										dw_test.testActive = 1 And
										dw_unit.unitCypher = ? And
										dw_unit.unitActive = 1
									Order By
										dw_result.resultModDate Desc
								";
								if(!$resultquery = mysqli_prepared_query($link, $sql, "iii", array($calcarray['calcTest'.$i], $_SESSION['userSite'], $r), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								if(mysqli_prepared_num_rows($resultquery)>0){
									$sum = 0;
									$count = 0;
									foreach($resultquery as $result){
										$sum += $result['resultFriendly'];
										$last_result = $result['resultFriendly'];
										$count++;
									}
									if($count > 0) $avg = $sum/$count;
									else $avg = 0;
									if($debug) echo $avg;
									$resultavg[$i] = texttonumber($avg, $result['testFormat']);
								}else{
									$resultavg[$i] = "";
									if($debug) echo "<br>null";
									$missing_test = $calcarray['calcTest'.$i];
									$calc = false;
								}
							}else{
								$resultavg[$i] = "";
								if($debug) echo "<br>calcTest".$i." is blank";
							}
						}

						/*
							[calcText1] => (
							[calcTest1] => 1894
							[calcText2] => /((100-
							[calcTest2] => 1893
							[calcText3] => )-
							[calcTest3] => 1892
							[calcText4] => ))*100
							[calcTest4] => 0
							[calcText5] =>
						*/

						$string = $calcarray['calcText1']; //is allowed to be blank
						if(isset($resultavg[1])){
							$string .= round($resultavg[1],2);
							if($calcarray['calcText2']!="" && $calcarray['calcText2']!=null){
								$string.=$calcarray['calcText2'];
								if(isset($resultavg[2]) && $resultavg[2]!=""){
									$string .= round($resultavg[2],2);
									if($calcarray['calcText3']!="" && $calcarray['calcText3']!=null){
										$string .= $calcarray['calcText3'];
										if(isset($resultavg[3]) && $resultavg[3]!=""){
											$string .= round($resultavg[3],2);
											if($calcarray['calcText4']!="" && $calcarray['calcText4']!=null){
												$string .= $calcarray['calcText4'];
												if(isset($resultavg[4]) && $resultavg[4]!=""){
													$string .= round($resultavg[4],2);
													if($calcarray['calcText4']!="" && $calcarray['calcText4']!=null){
														$string .= $calcarray['calcText5'];
													};
												};
											};
										};
									};
								};
							};
						};

						if($debug) echo "<br>string:".$string;

						if($string!="" && $string!="0000" && $calc){

							$string = trim($string);

							$average = str_replace(",","",numbertotext(string_to_math($string), $testFormat, $testRound)); //string_to_math is usually a very bad idea. USE SPARINGLY!
							if($debug){
								echo "<br><pre>string:'".$string."'</pre>";
								echo "<br><pre>testID:'".$testID."'</pre>";
								echo "<br><pre>string_to_math:'".string_to_math($string)."'</pre>";
								echo "<br><pre>testFormat:'".$testFormat."'</pre>";
								echo "<br><pre>testRound:'".$testRound."'</pre>";
								echo "<br><pre>average:'".$average."'</pre>";
								//die();
							}
							//see if result exists. if it does, overwrite it (dont want to add a new one each time), if it doesnt exist, add it

							$sql="
								Select
								  resultID,
								  resultFriendly
								From
								  dw_result
								Where
								  resultUnit = ? And
								  resultTest = ?
								Order By
								  resultModDate Desc
								Limit 1
							";
							if(!$result2query = mysqli_prepared_query($link, $sql, "ii", array($unitID, $testID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							if(mysqli_prepared_num_rows($result2query)>0){
								$results = $result2query[0];
								$sql="
									# result exists, update it
									Update dw_result Set
									  resultFriendly = ?,
									  resultNotes    = ?,
									  resultModUser  = ?,
									  resultModDate  = now()
									Where
									  resultID       = ? And
									  resultTest     = ?
								";
								if(!savesql($link, $sql, "ssiii", array($average, $string, $_SESSION['userID'], $results['resultID'], $testID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}else{
								$average = str_replace('&lt;','<',$average);
								$average = str_replace('&gt;','>',$average);
								if(substr($average,0,1)==".") $average = "0".$average; // if someone enters .1 convert to 0.1
								$sql="
									# no result exists, add it (calc)
									Insert Into dw_result         (resultFriendly, resultUnit, resultTest, resultNotes, resultModUser, resultModDate)
									Values                        (      ?       ,       ?   ,       ?   ,       ?    ,       ?      ,     now()    )";
								$types  =                       '      s               i           i           s            i                      ';
								$values =                  array(   $average   ,   $unitID ,   $testID ,   $string  , $_SESSION['userID']         ) ;
								if(!savesql($link, $sql, $types, $values, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								enteroos($average, $unitID, $testID, $_SESSION['userSite']);
							}
						}else{
							//Could not calculate due to missing test result
							if(isset($missing_test)){
								$sql="
									# get missing test for calc
									Select
										testText
									From
										dw_test
									Where
										testID = ?
								";
								if(!$testquery = mysqli_prepared_query($link, $sql, "i", array($missing_test), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								$missing_array = $testquery[0];

								$message['type'] = "error";
								if($debug) $message['text'] = "Could not calculate ".$testText."[".$testID."] due to missing ".$missing_array['testText']."[".$missing_test."] results";
								else $message['text'] = "Could not calculate ".$testText." due to missing ".$missing_array['testText']." results";
							}
						}
					}else{
						//if result is 0, enter it
						if($debug) echo "Not a calculation (calc_numrows<=0)<br>";
						$sql="# get existing result (for comparison), if it exists
							Select
								dw_result.resultFriendly
							From
								dw_result
							Where
								dw_result.resultUnit = ? And
								dw_result.resultTest = ?
							Order By
								dw_result.resultModDate Desc
							Limit 1
						";
						if(!$resultquery = mysqli_prepared_query($link, $sql, "ii", array($unitID, $testID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						$resultarray = $resultquery[0];
						if(strtolower($resultarray['resultFriendly'])!=strtolower($value)){
							//insert new result
							$value = str_replace('&lt;','<',$value);
							$value = str_replace('&gt;','>',$value);
							if(substr($value,0,1)==".") $value = "0".$value; // if someone enters .1 convert to 0.1
							$resultNotes = 'Zero';
							$sql="# insert new result (zero)
								INSERT INTO dw_result        (resultFriendly, resultUnit, resultTest,  resultNotes, resultModUser, resultModDate)
								VALUES                       (      ?       ,       ?   ,       ?   ,        ?    ,       ?      ,     now()    )";
							$types  =                      '      s               i           i            s            i                      ';
							$values =                 array(    $value    ,   $unitID ,   $testID , $resultNotes, $_SESSION['userID']         ) ;

							if(!savesql($link, $sql, $types, $values, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							enteroos($value, $unitID, $testID, $_SESSION['userSite']);

							//$message['type'] = "error";
							//$message['text'] = "You tried to enter a result of zero, but this is currently not allowed. If you really meant to do this, please contact the administrator";
							//email('shaun@dairywindow.nz', 'Zero result', $_SESSION['userFirst'].' entered a zero result on site '.$_SESSION['userSite'].' URL: '.$_SERVER['REQUEST_URI']);

						}//else result already exists
					}
				}
			}
		}
	}

	if(isset($_POST['resultID']) && $_POST['resultID']!='' && $allowdelete){
		$resultID = clean($_POST['resultID']);
		$sql="
			DELETE FROM dw_result
			WHERE resultID = ?
			LIMIT 1
		";
		if(!savesql($link, $sql, "i", array($resultID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
	}

	if(isset($_POST['new_sample']) && $_POST['new_sample']!='' && isset($_POST['new_location']) && isset($_GET['r']) && $_GET['r']!='' && $_SESSION['userLevel']<= $_SESSION['admin_unit_add']){
		$new_sample   = clean($_POST['new_sample'  ]);
		$new_location = clean($_POST['new_location']);
		$new_cypher   = clean($_GET[ 'r'           ]);
		$sql="
			INSERT INTO dw_unit          ( unitCypher,   unitText ,  unitLocation, unitActive, unitModUser, unitModDate)
			VALUES                       (     ?     ,       ?    ,      ?       ,     1     ,     ?      ,    now()   )
		";
		if(!savesql($link, $sql, "isii", array($new_cypher, $new_sample, $new_location,        $_SESSION['userID']          ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
	}

	echo "<div id='main' class='panel-group' aria-multiselectable='true' >
		<div id='topDIV'>
			<h1 class='text-center'>
				<span class='hidden-print'>".$title."</span>";
			if($cypherid!=0 && isset($cypherarray)){
					echo "<span class='hidden-print'> for </span>";
					switch($_SESSION['cypherorbatch']){
						case 0:
							echo $cypherarray['cypherText'];
							break;
						case 1:
							echo $cypherarray['cypherOrderID'];
							break;
						default:
							echo $cypherarray['cypherText'].' '.$cypherarray['cypherOrderID'];
					}
					echo " ".$cypherarray['specText'];
				}
			if(!empty($_GET['r'])){
				echo "<span class='pull-right no-print'><input type='checkbox' id='watching' data-toggle='toggle' data-on='Watching' data-off='Not watching' data-size='small' value='1'></span>";
				//see if the cypher is in the watch list
				$sql='
					Select
						subID
					From
						dw_subscribe
					Where
						subCypher = ? And
						subUser = ?';
				if(!$qry = mysqli_prepared_query($link, $sql, 'ii', array($cypherid, $_SESSION['userID']), __FILE__,__LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__, array($cypherid, $_SESSION['userID']));
				if(mysqli_prepared_num_rows($qry)>0){
					echo '<script>
						$(function(){
							$("#watching").bootstrapToggle();
							$("#watching").bootstrapToggle("on");
						});
					</script>';
				}else{
					echo '<script>
						$(function(){
							$("#watching").bootstrapToggle();
							$("#watching").bootstrapToggle("off");
						});
					</script>';
				}
				echo '<script>
					//watching onchange event handler
					$(function(){
						$("#watching").change(function(){
							//console.log("#watching has changed");
							if($(this).prop("checked")){
								//insert
								//console.log("#watching is checked");
								$.post("ajax/update_watch.php", {
									cypher: '.$cypherid.',
									user: '.$_SESSION['userID'].',
									action: "insert"
								}).done(function(data){
									alert(data);
								});
							}else{
								//delete
								//console.log("#watching is not checked");
								$.post("ajax/update_watch.php", {
									cypher: '.$cypherid.',
									user: '.$_SESSION['userID'].',
									action: "delete"
								}).done(function(data){
									alert(data);
								});
							}
						});
					});
				</script>';
			}
			echo "</h1>";
		if(isset($cypherarray) && $cypherarray['cypherNotesFP']!="") echo "<h2 class='text-center'>".$cypherarray['cypherNotesFP']."</h2>";
	echo "</div><div class='container-fluid'>";
	require "inc/calendar.php";
	echo "<div class='col-md-9' role='main'>";
	//echo "<input type='"; if($debug) echo "text"; else echo "hidden"; echo "' id='changed' value='false'>";
	if($cypherid!=0){

		$sql="# get all units
			SELECT
			  dw_location.locationID,
			  dw_location.locationText,
			  dw_unit.unitID,
			  dw_unit.unitText,
			  dw_user.userFirst,
			  dw_user.userLast,
			  dw_unit.unitModDate
			FROM
			  dw_unit LEFT JOIN
			  dw_cypher ON dw_cypher.cypherID = dw_unit.unitCypher LEFT JOIN
			  dw_location ON dw_location.locationID = dw_unit.unitLocation LEFT JOIN
			  dw_user ON dw_user.userID = dw_unit.unitModUser
			WHERE
				dw_unit.unitActive = 1 AND
			  dw_location.locationActive = 1 And
			  dw_cypher.cypherID = ? AND
			  dw_cypher.cypherSite = ?
			GROUP BY
			  dw_unit.unitID
			ORDER BY
			  dw_location.locationOrder,
			  dw_location.locationText,
			  CASE dw_unit.unitText
			    WHEN 'F' THEN 1
			    WHEN 'M' THEN 2
			    WHEN 'L' THEN 3
			    ELSE 4
			  END,
			  Field(dw_unit.unitText, 'F', 'M', 'L', 'Comp', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2', 'Composite'),
			  LPad(dw_unit.unitText, 20, 0)
		";
		$types = 'ii';
		$params = array($cypherid, $_SESSION['userSite']);
		if(!$unitquery = mysqli_prepared_query($link, $sql, $types, $params, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		if($debug) echo '<br>';
		$numunits = mysqli_prepared_num_rows($unitquery);

		if(isset($_GET['f']) && $_GET['f']!=0){
			$sql = "# Get tests
			(
				# Get tests from submission form
				Select
					dw_group.groupID,
					dw_group.groupText,
					dw_group.groupOrder,
					
					dw_test.testID,
					dw_test.testText,
					dw_test.testFormat,
					dw_test.testRound,
					dw_test.testCalc,
					dw_test.testStdev,
					dw_test.testShowAvg,
					dw_test.testGroup,
					dw_test.testOrder,
					
					dw_spec.specID
				From
					(dw_spec Right Join
					((dw_group Right Join
					dw_test On dw_group.groupID = dw_test.testGroup) Right Join
					dw_sub
						On dw_test.testID = dw_sub.subTest)
						On dw_spec.specID = dw_sub.subSpec) Right Join
					dw_cypher On dw_spec.specID = dw_cypher.cypherSpec
				Where
					dw_sub.subForm     = ? And
					dw_cypher.cypherID = ? And
					dw_test.testSite   = ?
				Group By
					dw_test.testID,
					dw_spec.specID
				Order By
					dw_group.groupOrder,
					dw_group.groupText,
					dw_test.testOrder,
					dw_test.testText
			)Union Distinct(
				# Get tests from pre-existing results
				Select
					dw_group.groupID,
					dw_group.groupText,
					dw_group.groupOrder,
					
					dw_test.testID,
					dw_test.testText,
					dw_test.testFormat,
					dw_test.testRound,
					dw_test.testCalc,
					dw_test.testStdev,
					dw_test.testShowAvg,
					dw_test.testGroup,
					dw_test.testOrder,
					
					dw_spec.specID
				From
					dw_spec    Right Join
					(dw_cypher Right Join
					(dw_unit   Right Join
					(dw_group  Right Join
					(dw_test   Right Join
					dw_result
						On dw_test.testID     = dw_result.resultTest)
						On dw_group.groupID   = dw_test.testGroup)
						On dw_unit.unitID     = dw_result.resultUnit)
						On dw_cypher.cypherID = dw_unit.unitCypher)
						On dw_spec.specID     = dw_cypher.cypherSpec
				Where
					dw_group.groupActive = 1 And
					dw_test.testActive   = 1 And
					dw_spec.specActive   = 1 And
					dw_cypher.cypherID   = ? And
					dw_cypher.cypherSite = ?
				Group By
					dw_test.testID,
					dw_spec.specID
				Order By
					dw_group.groupOrder,
					dw_group.groupText,
					dw_test.testOrder,
					dw_test.testText
			)
			Order By
				groupOrder,
				groupText,
				testOrder,
				testText
			";
			$types = 'iiiii';
			$array = array($formid, $cypherid, $_SESSION['userSite'], $cypherid, $_SESSION['userSite']);
		}else{
			$sql = "
				# Get tests from pre-existing results
				Select
					dw_group.groupID,
					dw_group.groupText,
					dw_test.testID,
					dw_test.testText,
					dw_test.testFormat,
					dw_test.testRound,
					dw_test.testCalc,
					dw_test.testStdev,
					dw_test.testShowAvg,
					dw_test.testGroup,
					dw_cypher.cypherSpec as specID
				From
				  dw_result
					LEFT JOIN dw_unit ON dw_unit.unitID = dw_result.resultUnit
					LEFT JOIN dw_test ON dw_test.testID = dw_result.resultTest
					LEFT JOIN dw_cypher ON dw_cypher.cypherID = dw_unit.unitCypher
					LEFT JOIN dw_group ON dw_group.groupID = dw_test.testGroup
				Where
					dw_test.testActive   = 1 And
					dw_unit.unitActive   = 1 And
					dw_cypher.cypherID   = ? And
					dw_cypher.cypherSite = ?
				Group By
					dw_test.testID
				Order By
					dw_group.groupOrder,
					dw_group.groupText,
					dw_test.testOrder,
					dw_test.testText
			";
			$types = 'ii';
			$array = array($cypherid, $_SESSION['userSite']);
		}
		if(!$testquery = mysqli_prepared_query($link, $sql, $types, $array, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

		//if($numunits>0){
			if($debug) echo 'specstyle:'.$specstyle.'<br>';
			echo "<form method='post' id='mainform'><table class='table table-striped table-condensed table-bordered sorttable' id='table'><thead>";
			if($specstyle==1 || $specstyle=='1' || $specstyle==4 || $specstyle=='4'){
				// Final Product or Ingredients

				foreach($unitquery as $unitarray){
					$units[$unitarray['unitID']]['unitText'    ] = $unitarray['unitText'    ];
					$units[$unitarray['unitID']]['locationID'  ] = $unitarray['locationID'  ];
					$units[$unitarray['unitID']]['locationText'] = $unitarray['locationText'];
					$units[$unitarray['unitID']]['userFirst'   ] = $unitarray['userFirst'   ];
					$units[$unitarray['unitID']]['userLast'    ] = $unitarray['userLast'    ];
					$units[$unitarray['unitID']]['unitModDate' ] = $unitarray['unitModDate' ];
				}

				echo "<tr><th class='hidden-print'>Group</th><th>Test</th>";
				foreach($units as $unitkey => $unitvalue){
					echo "<th data-toggle='tooltip' title='".$unitvalue['userFirst']." ".$unitvalue['userLast'][0]." ".date('j/n/y',strtotime($unitvalue['unitModDate']))."' data-container='body' class='text-center' >".$unitvalue['locationText']."<br>".$unitvalue['unitText'];
					if($debug) echo " <small>[".$unitkey."]</small>";
					echo "<span class='hidden' id='u".$unitkey."'>".$unitarray['unitText']."</span>";
					echo "<span class='hidden' id='l".$unitkey."'>".$unitarray['locationText']."</span>";
					echo "</th>";
				}
				echo "<th class='avg'>Average<span class='hidden-print'><br><a href='cypher.php?u=".$cypherid."'>Add sample</a></span></th><th style='text-align:center'>Limits</th>";
				if($_SESSION['userSite']==4) echo "<th>CoV</th>";
				echo "<th class='hidden-print'>Released</th></tr></thead>";

				$unitlist = array_column($units, 'unitText'); //this creates a new array containing the unit texts (used for searching for frequencies)
				$hascomp = false;
				foreach($unitlist as $unit){
					if(in_array($unit, array('Comp', 'comp', 'Composite', 'composite', 'Comp1', 'comp1', 'Comp 1', 'comp 1', 'Comp2', 'comp2', 'Comp 2', 'comp 2'))) $hascomp = true;
				}

				$end_unit = count($units)-1; //last unit
				if($debug){
					echo "<small>end_unit:".$end_unit."</small>&nbsp;";
					if($hascomp) echo "<small>hascomp:true</small>";
					else echo "<small>hascomp:false</small>";
				}

				foreach($testquery as $testarray){ //rows (tests)
					/*
					if(
						!isset($testarray['testID']) ||
						$testarray['testID']=="" ||
						$testarray['testID']==null
					){
						$testarray['testID']=0; //Warning: Cannot use a scalar value as an array
					}
					*/
					$sql="
						# check relaese status
						Select releaseID
						From dw_resultrelease
						Where
							releaseCypher = ? And
							releaseTest = ?
					";
					if(!$releasequery = mysqli_prepared_query($link, $sql, "ii", array($cypherid, $testarray['testID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if(mysqli_prepared_num_rows($releasequery)>0) $result_final = "readonly";
					else $result_final = "";

					$sql="
						# get limits
						Select
							limitID,
							limitLow,
							limitHigh,
							limitLowParent,
							limitHighParent,
							limitLowAnz,
							limitHighAnz,
							limitLowDbp,
							limitHighDbp,
							limitLowGb,
							limitHighGb
						From
							dw_limit
						Where
							limitTest      = ? And
							limitSpec      = ? And
							limitLocation  = ? And
							limitDateFrom <= ? And
							limitDateTo   >= ?
						Order By
							limitModReason Desc
						Limit 1
					";
					if($debug){
						echo $sql.' '.$testarray['testID'].' '.$testarray['specID'].' '.$unitvalue['locationID'].' '.$c;
					}
					if(!$limitquery = mysqli_prepared_query($link, $sql, "iiiss", array($testarray['testID'], $testarray['specID'], $unitvalue['locationID'], $c, $c), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if($debug) echo 'rows:'.mysqli_prepared_num_rows($limitquery);
					if(mysqli_prepared_num_rows($limitquery)>0){
						$limitarray = $limitquery[0];

						$limitLow  = numbertotext($limitarray['limitLow' ], $testarray['testFormat'], $testarray['testRound']);
						$limitHigh = numbertotext($limitarray['limitHigh'], $testarray['testFormat'], $testarray['testRound']);

						if($limitarray['limitLow']!=null && $limitarray['limitLow']==$limitarray['limitHigh']) $limits = $limitLow;
						else{
							if($limitarray['limitLow']!=null && $limitarray['limitLow']==0){
								//try to stop displaying limits as '<B', otherwise the browser gets confused and thinks it's supposed to be bold XD
								if($limitarray['limitHigh']!=null && $testarray['testFormat']==4 || $testarray['testFormat']=='4') $limits = "Less than ".$limitHigh;
								else{
									if($limitarray['limitHigh']!=null && $limitHigh[0]=="<") $limits = $limitHigh;
									else $limits = "&lt;".$limitHigh;
								}
							}else{
								if($limitarray['limitLow']==null && $limitarray['limitHigh']==null) $limits = numbertotext($limitarray['limitLowParent'], $testarray['testFormat'], $testarray['testRound'])."-".numbertotext($limitarray['limitHighParent'], $testarray['testFormat'], $testarray['testRound']);
								else{
									if($limitarray['limitLow']==null || $limitarray['limitLow']==0){
										if($limitHigh[0] == '<') $limits = $limitHigh;
										else $limits = "&lt;".$limitHigh;
									}else $limits = $limitLow."-".$limitHigh;
								}
							}
						}
					}else{
						$limits="&#x221e;"; //infinity
						//if($debug) $limits.=$unitvalue['locationID'];
						$limitarray = array('limitID'=>0);
					}

					echo "<tr><td style='padding: 0px 10px 0px 10px;' class='hidden-print'>".$testarray['groupText']."</td><td style='padding: 0px 10px 0px 10px;white-space:nowrap;'>".clean($testarray['testText']);
					if($debug) echo " <small>[".$testarray['testID']."]</small>";
					if($testarray['testCalc']!='0' && $testarray['testCalc']!=0){
						$sql='# get calc data
						Select
						  dw_calc.calcText1,
						  dw_test1.testText As calcTest1,
						  dw_calc.calcText2,
						  dw_test2.testText As calcTest2,
						  dw_calc.calcText3,
						  dw_test3.testText As calcTest3,
						  dw_calc.calcText4,
						  dw_test4.testText As calcTest4,
						  dw_calc.calcText5  
						From
						  dw_calc Left Join
						  dw_test dw_test1 On dw_test1.testID = dw_calc.calcTest1 Left Join
						  dw_test dw_test2 On dw_test2.testID = dw_calc.calcTest2 Left Join
						  dw_test dw_test3 On dw_test3.testID = dw_calc.calcTest3 Left Join
						  dw_test dw_test4 On dw_test4.testID = dw_calc.calcTest4
						Where
							calcID = ?';
						if(!$qry = mysqli_prepared_query($link, $sql, "i", array($testarray['testCalc']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						$title = '';
						if(!empty($qry[0]['calcText1'])) $title .= $qry[0]['calcText1'];
						if(!empty($qry[0]['calcTest1'])) $title .= $qry[0]['calcTest1'];
						if(!empty($qry[0]['calcText2'])) $title .= $qry[0]['calcText2'];
						if(!empty($qry[0]['calcTest2'])) $title .= $qry[0]['calcTest2'];
						if(!empty($qry[0]['calcText3'])) $title .= $qry[0]['calcText3'];
						if(!empty($qry[0]['calcTest3'])) $title .= $qry[0]['calcTest3'];
						if(!empty($qry[0]['calcText4'])) $title .= $qry[0]['calcText4'];
						if(!empty($qry[0]['calcTest4'])) $title .= $qry[0]['calcTest4'];
						if(!empty($qry[0]['calcText5'])) $title .= $qry[0]['calcText5'];
						echo "&nbsp;<span data-toggle='tooltip' title='".$title."' class='glyphicon glyphicon-info-sign' aria-hidden='true' ></span>";
					}

					//if($limits=="&#x221e;" || $limits=='') echo "&nbsp;<a href='limit.php'><span style='color:orange;'><span data-toggle='tooltip' title='No test limits set up for this test' class='glyphicon glyphicon-exclamation-sign has-warning' aria-hidden='true' ></span></span></a>";
					$sql="
						# get frequency
						Select
							dw_sub.subFreq
						From
							dw_sub
						Where
							dw_sub.subTest = ? And
							dw_sub.subSpec = ? And
							dw_sub.subForm = ?
					";
					if(!$qry = mysqli_prepared_query($link, $sql, "iii", array($testarray['testID'], $testarray['specID'], $formid), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$array = $qry[0];
					$freq = $array['subFreq'];
					if($debug) echo "<small>Freq:".$freq."</small>";
					if($testarray['testID'] < 10) $testarray['testID'] = '0' . $testarray['testID'];
					echo "<span class='hidden' id='tk".$testarray['testID']."'>".$testarray['testText']."</span>";

					echo "</td>";

					$sum=0; $count=0; $col=0;

					foreach($units as $unitkey => $unitvalue){ //unit cols

						$required = false;
						if($freq!=""){
							if($hascomp==true){
								switch($freq){
									case 1: //comp only
										if($col==$end_unit){
											$required = true;
										}
										break;
									case 2: //even
										if($col%2==0 && $col!= $end_unit){
											$required = true;
										}
										break;
									case 3: //first, mid, last
										if($col==0){
											$required = true;
										}
										else if($col==floor(($end_unit-1)/2)){
											$required = true;
										}
										else if($col==($end_unit-1)){
											$required = true;
										}
										break;
									case 4: // first, mid, last, comp
										if($col==0){
											$required = true;
										}
										else if($col==floor($end_unit/2)){
											$required = true;
										}
										else if($col==($end_unit-1)){
											$required = true;
										}
										else if($col==$end_unit){
											$required = true;
										}
										break;
									case 5: // all units, not comp
										if($col!= $end_unit) $required = true; // Comp
										break;
									case 6: // all units, plus comp
										$required = true;
										break;
									case 7: // first only
										if($col==0){
											$required = true;
										}
										break;
									case 8: // last only
										if($col==($end_unit-1)){
											$required = true;
										}
										break;
									case 9: // first, last
										if($col==0){
											$required = true;
										}
										else if($col==($end_unit-1)){
											$required = true;
										}
										break;
									case 10: // Tier 1
										if($col>=0 && $col<=4){
											$required = true;
										}
										break;
									case 11: // first, comp
										if($col==0){
											$required = true;
										}
										else if($col==$end_unit){
											$required = true;
										}
										break;
									case 12: // Tier 2 (composites)
										if(stristr($colnits[$col],"Comp")){
											$required = true;
										}
										break;
									case 13: // Tier 3
										if($col>=5 && $col<=13){
											$required = true;
										}
										break;
									case 14: //odd
										if($col%2!=0 && $col!= $end_unit){
											$required = true;
										}
										break;
									default:
										//reporterror('Error with frequency. Comp is true, Frequency is '.$freqs[$testarray['testID']], $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										if(isset($freq) && $freq!="" && $freq!=0){
											$sql="
												Select
													dw_frequency.freqAlgorithm
												From
													dw_frequency
												Where
													dw_frequency.freqID = ?
											";
											if(!$freq_query = mysqli_prepared_query($link, $sql, "i", array($freq), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
											$freq_row = $freq_query[0];
											$freq_array = explode(',', $freq_row['freqAlgorithm']);
											if(in_array($col, $freq_array)){
												$required = true;
											}
										}
								}
							}else{
								//no composite sample
								switch($freq){
									case 1: //comp only
										break;
									case 2: //even
										if($col%2==0){
											$required = true;
										}
										break;
									case 3: // first, mid, last
										if($col==0){
											$required = true;
										}
										else if($col==floor($end_unit/2)){
											$required = true;
										}
										else if($col==$end_unit){
											$required = true;
										}
										break;
									case 4: // first, mid, last, comp
										if($col==0){
											$required = true;
										}
										else if($col==floor($end_unit/2)){
											$required = true;
										}
										else if($col==$end_unit){
											$required = true;
										}
										break;
									case 5: // all units, not comp
										//or
									case 6: // all units, plus comp
										$required = true;
										break;
									case 7: // first only
										if($col==0){
											$required = true;
										}
										break;
									case 8: // last only
										if($col==$end_unit){
											$required = true;
										}
										break;
									case 9: // first, last
										if($col==0){
											$required = true;
										}
										else if($col==$end_unit){
											$required = true;
										}
										break;
									case 10: // Tier 1
										if($col>=0 && $col<=4){
											$required = true;
										}
										break;
									case 11: // first, comp
										if($col==0){
											$required = true;
										}
										break;
									case 12: // Tier 2 (composites)
										break;
									case 13: // Tier 3
										if($col>=5 && $col<=13){
											$required = true;
										}
										break;
									case 14: //odd
										if($col%2!=0){
											$required = true;
										}
										break;
									default:
										//reporterror('Error with frequency. Comp is false, Frequency is '.$freqs[$testarray['testID']], $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										if(isset($freq) && $freq!="" && $freq!=0){
											$sql="
												Select
													dw_frequency.freqAlgorithm
												From
													dw_frequency
												Where
													dw_frequency.freqID = ?
											";
											if(!$freq_query = mysqli_prepared_query($link, $sql, "i", array($freq), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
											$freq_row = $freq_query[0];
											$freq_array = explode(',', $freq_row['freqAlgorithm']);
											if(in_array($col, $freq_array)){
												$required = true;
											}
										}
								}
							}
						}

						$unit_padded = str_pad($unitkey, 2, "0", STR_PAD_LEFT);
						$test_padded = str_pad($testarray['testID'], 2, "0", STR_PAD_LEFT);

						$sql="
							# get result
							Select
								dw_result.resultID,
								dw_result.resultFriendly,
								dw_result.resultReference,
								dw_result.resultModDate,
								dw_result.resultNotes,
								dw_user_mod.userFirst As userFirst_mod,
								dw_user_mod.userLast As userLast_mod,
								dw_user_tested.userFirst As userFirst_tested,
								dw_user_tested.userLast As userLast_tested
							From
								dw_user dw_user_mod Right Join
								dw_result              On dw_user_mod.userID         = dw_result.resultModUser Left Join
								dw_user dw_user_tested On dw_result.resultTestedUser = dw_user_tested.userID
							Where
								dw_result.resultUnit = ? And
								dw_result.resultTest = ?
							Order By
								dw_result.resultModDate Desc
							Limit 2
						";
						if(!$resultquery = mysqli_prepared_query($link, $sql, 'ii', array($unitkey, $testarray['testID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						if($debug) echo "<br>";
						if(mysqli_prepared_num_rows($resultquery)>0){
							//result exists, final product
							$resultarray = $resultquery[0];

							if($debug) echo "<td class='text-center' title='".$sql."'>";
							else echo "<td class='text-center' >";

							$limittext = "";
							$oos = false;
							if($limits!="&#x221e;"){
								if(
									(isset($limitarray['limitLow'      ]) && $limitarray['limitLow'      ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) < $limitarray['limitLow'      ]) ||
									(isset($limitarray['limitLowParent']) && $limitarray['limitLowParent']!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) < $limitarray['limitLowParent']) ||
									(isset($limitarray['limitLowAnz'   ]) && $limitarray['limitLowAnz'   ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) < $limitarray['limitLowAnz'   ]) ||
									(isset($limitarray['limitLowDbp'   ]) && $limitarray['limitLowDbp'   ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) < $limitarray['limitLowDbp'   ]) ||
									(isset($limitarray['limitLowGb'    ]) && $limitarray['limitLowGb'    ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) < $limitarray['limitLowGb'    ])
								){
									$limittext = "<strong>Result too low!</strong><br>";
									$oos = true;
								}
								if(
									(isset($limitarray['limitHigh'      ]) && $limitarray['limitHigh'      ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) > $limitarray['limitHigh'       ]) ||
									(isset($limitarray['limitHighParent']) && $limitarray['limitHighParent']!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) > $limitarray['limitHighPatrent']) ||
									(isset($limitarray['limitHighAnz'   ]) && $limitarray['limitHighAnz'   ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) > $limitarray['limitHighAnz'    ]) ||
									(isset($limitarray['limitHighDbp'   ]) && $limitarray['limitHighDbp'   ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) > $limitarray['limitHighDbp'    ]) ||
									(isset($limitarray['limitHighGb'    ]) && $limitarray['limitHighGb'    ]!=null && texttonumber($resultarray['resultFriendly'], $testarray['testFormat']) > $limitarray['limitHighGb'     ])
								){
									$limittext = "<strong>Result too high!</strong><br>";
									$oos = true;
								}
							}

							$popover = "title='";
							if(mysqli_prepared_num_rows($resultquery)>1) $popover .= "<small>Original result: ".$resultquery[1]['resultFriendly']."</small><br>This r";
							else $popover .= "R";
							$popover .= "esult: ".$resultarray['resultFriendly']."' data-content=\"";
							if($allowdelete) $popover .= "<span class='hidden-print'><a href='#' data-toggle='modal' data-target='#confirmDelete' onclick='updatedeleteprompt(".$resultarray['resultID'].");' >Delete this result</a></span><br>";
							$popover .= "
								<span class='hidden-print'><a href='trends.php?p=".$testarray['specID']."&l=".$unitvalue['locationID']."&g=".$testarray['groupID']."&t=".$testarray['testID']."'>View ".substr(clean($testarray['testText']),0,20)." trend</a></span><br>
								<span class='nobr'>".$limittext."<a href='limit.php?s=".$testarray['specID']."&l=".$limitarray['limitID']."'>Limits: ".$limits."</a></span><br>";
								if(!empty($resultarray['resultReference'])) $popover.="<span class='nobr'>Reference: ".$resultarray['resultReference']."</span><br>";
								if(!empty($resultarray['userFirst_tested'])) $popover.="<span class='nobr'>Tested by: ".$resultarray['userFirst_tested'].' '.$resultarray['userLast_tested'][0]."</span><br>";
								$popover.="<span class='nobr'>Entered by: ".$resultarray['userFirst_mod'].' '.$resultarray['userLast_mod'][0]."</span><br>
								<span class='nobr'>Date: ".date('j/n/y G:i',strtotime($resultarray['resultModDate']))."</span>";
							//if($resultarray['resultNotes']!='' && $resultarray['resultNotes']!=null){
								$popover .= "<br><span class='italic' ";
								if(strlen($resultarray['resultNotes'])>22){
									$popover .= "title='".$resultarray['resultNotes']."' >".substr($resultarray['resultNotes'],0,22)."&hellip;";
								}else{
									$popover .= ">".$resultarray['resultNotes'];
								}
								$popover .= "</span>";
							//}
							$popover .= "\" data-toggle='popover' data-html=true data-container='body' data-trigger='click' data-placement='left' onclick='hideallpopovers();' ";

							if($oos) $popover .= "style='background-color:orange;' ";

							if($debug){
								//echo "<span>Unit:".$unitkey." Test:".$testarray['testID']."</span>";
								echo "<small>[".$resultarray['resultID']."]</small>";
							}

							echo "<span class='visible-print-inline'>".$resultarray['resultFriendly'];
							if($oos) echo "<span class='glyphicon glyphicon-exclamation-sign'></span>";
							echo "</span><span class='hidden-print'>";

							echo "<span style='display:none;' class='raw'>".$resultarray['resultFriendly']."</span>";

							$css = "form-control fp has-result result_input";
							if(mysqli_prepared_num_rows($resultquery)>1) $css.=" retest";

							switch($testarray['testFormat']){
								case 1: //count
								case '1':
									$cellvalue = clean($resultarray['resultFriendly']);
									if(substr($cellvalue, -6)==='000000')   $cellvalue = substr($cellvalue, 0, strlen($cellvalue)-6).',000,000';
									else if(substr($cellvalue, -3)==='000') $cellvalue = substr($cellvalue, 0, strlen($cellvalue)-3).',000';
									echo "<input ".$popover." tabindex='".$tabindex."' type='text' class='".$css." no-padding format1 input-sm test".$testarray['testID']."' id='u".$unit_padded.'t'.$test_padded."' value='".$cellvalue."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",1);' ".$result_final." >";
									break;
								case 2: //abs/pres
								case '2':
									echo "
										<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding input-sm format2 test".$testarray['testID']."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",2);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option></option><option value='Absent' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,3)=='abs' || $resultarray['resultFriendly'][0]=='<') echo "selected ";
											echo ">Absent</option><option value='Present' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,4)=='pres') echo "selected ";
											echo ">Present</option>
										</select>
									";
									break;
								case 3: //number
								case '3':
									if(is_numeric($resultarray['resultFriendly']) || empty($resultarray['resultFriendly'])){
										if(isset($resultarray['resultFriendly']) && $resultarray['resultFriendly']!="" && $resultarray['resultFriendly']!=null) $cellvalue = number_format(trim($resultarray['resultFriendly']), $testarray['testRound'], ".", '');
										else $cellvalue = "";

										echo "<input ".$popover." type='number' ";
										//get the step from testRound
										$step = "0.";
										for ($i = 0; $i < $testarray['testRound']; $i++) $step .= "0";
										$step = substr($step, 0, (strlen($step)-1));
										$step .= "1";
										echo "step='".$step."' class='".$css." no-padding input-sm format3 test".$testarray['testID']."' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".$cellvalue."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",3);' ".$result_final." >";
									}else{
										if(
											stristr($resultarray['resultFriendly'], '<') ||
											stristr($resultarray['resultFriendly'], '>')
										){
											//should be format 1
											$cellvalue = $resultarray['resultFriendly'];
											$sql='# Update test format to count
												Update dw_test
												Set testFormat = 1
												Where testID = ?
											';
											$types  = 'i';
											$values = array($testarray['testID']);
											if(!savesql($link, $sql, $types, $values, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
											else{
												$message['type'] = "ok";
												$message['text'] = "The test <strong>format</strong> for ".$testarray['groupText']." ".$testarray['testText']." was not correct. The format was 'number' but the result '".$resultarray['resultFriendly']."' contains non-numeric characters (a less than or greater than sign), so I have changed the test format of the test to 'Count' for you.";
											}
										}else{
											$cellvalue = -1; //test format is wrong
											//reporterror("Test format is incorrect. Currently number format, but '".$resultarray['resultFriendly']."' is not a number", "Group: ".$testarray['testGroup'].", Test: ".$testarray['testText']." [".$testarray['testID']."]", $_SERVER['REQUEST_URI'], __FILE__, __LINE__, "", False);
											$message['type'] = "warning";
											$message['text'] = "The test <strong>format</strong> for ".$testarray['groupText']." ".$testarray['testText']." is not correct. Currently the format is 'number' but the result '".$resultarray['resultFriendly']."' contains non-numeric characters. Results will show as -1 until this is fixed. Would you like to go to the <strong>tests page</strong> now?";
											$message['extra'] = $testarray['testID'];
										}
										echo "<input ".$popover." type='text' class='".$css." no-padding input-sm format3 test".$testarray['testID']."' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".$cellvalue."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",3);' ".$result_final." >";
									}

									break;
								case 4: //letter
								case '4':
									echo "<input ".$popover." type='text' class='".$css." no-padding input-sm format4 test".$testarray['testID']."' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".clean($resultarray['resultFriendly'])."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",4);' ".$result_final." >";
									break;
								case 5: //pass/fail
								case '5':
									echo "
										<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding input-sm format5 test".$testarray['testID']."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",5);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option></option><option value='Pass' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,4)=='pass') echo "selected ";
											echo ">Pass</option><option value='Fail' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,4)=='fail') echo "selected ";
											echo ">Fail</option>
										</select>
									";
									break;
								case 6: //detected/not detected
								case '6':
									echo "
										<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding input-sm format6 test".$testarray['testID']."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",6);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option></option><option value='Detected' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,3)=='det') echo "selected ";
											echo ">Detected</option><option value='Not detected' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,3)=='not' || strtolower($resultarray['resultFriendly'])=='nd' || strtolower(substr($resultarray['resultFriendly'],0,2))=='no' || substr($resultarray['resultFriendly'],0,1)=='<') echo "selected ";
											echo ">Not detected</option>
										</select>
									";
									break;
								case 7: //text
								case '7':
									echo "<input ".$popover." type='text' class='".$css." no-padding input-sm format7 test".$testarray['testID']."' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".clean($resultarray['resultFriendly'])."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",7);' ".$result_final." >";
									break;
								case 8: //typ/atyp
								case '8':
									echo "
										<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding input-sm format8 test".$testarray['testID']."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",8);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option></option><option value='Typical' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,3)== 'typ') echo "selected ";
											echo ">Typical</option><option value='Atypical' ";
												if(substr(strtolower($resultarray['resultFriendly']),0,4)=='atyp') echo "selected ";
											echo ">Atypical</option>
										</select>
									";
									break;
								case 9:
								case "9":
								echo "<input ".$popover." type='text' class='".$css." no-padding input-sm format9 test".$testarray['testID']."' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".clean($resultarray['resultFriendly'])."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",9);' ".$result_final." >";
									break;
								default:
									if(!empty($testarray['testFormat'])) reporterror('Unknown testFormat "'.$testarray['testFormat'].'"', 'none', $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}

							echo "</span>";

							echo "</td>";
							$sum+=texttonumber($resultarray['resultFriendly'], $testarray['testFormat']);
							$last_result = $resultarray['resultFriendly'];
							$sdarray[$testarray['testID']][] = texttonumber($resultarray['resultFriendly'], $testarray['testFormat']); //add result to std dev array
							$count++;
						}else{
							//no result, final product
							echo "<td ><span class='visible-print-inline fp no-result' style='text-align: left;'>";
							if($required) echo "*"; else echo "&nbsp;";
							echo "</span><span class='hidden-print";
							if($required) echo " blue";
							echo "'>";
							$css='form-control fp no-result';

							switch($testarray['testFormat']){
								case 1: //count
								case '1':
									echo "<input type='text' "; if($required && $odl) echo "value='()' "; echo "class='".$css." no-padding input-sm format1 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",1);' ".$result_final." >";
									break;
								case 2: //abs/pres
								case '2':
									echo "
										<select tabindex='".$tabindex."' class='".$css." no-padding input-sm format2 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",2);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option>"; if($required && $odl) echo "()"; echo "</option><option value='Absent' >Absent</option><option value='Present'>Present</option>
										</select>
									";
									break;
								case 3: //number
								case '3':
									echo "<input type='number' ";
									if($required && $odl) echo "value='' ";
									//get the step from testRound
									$step = "0.";
									for ($i = 0; $i < $testarray['testRound']; $i++) $step .= "0";
									$step = substr($step, 0, (strlen($step)-1));
									$step .= "1";
									echo "step='".$step."' class='".$css." no-padding input-sm format3 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",3);' ".$result_final." >";
									break;
								case 4: //letter
								case '4':
									echo "<input type='text' "; if($required && $odl) echo "value='()' "; echo "class='".$css." no-padding input-sm format4 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",4);' ".$result_final." >";
									break;
								case 5: //pass/fail
								case '5':
									echo "
										<select tabindex='".$tabindex."' class='".$css." no-padding input-sm format5 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",5);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option>"; if($required && $odl) echo "()"; echo "</option><option value='Pass'>Pass</option><option value='Fail'>Fail</option>
										</select>
									";
									break;
								case 6: //detected/not detected
								case '6':
									echo "
										<select tabindex='".$tabindex."' class='".$css." no-padding input-sm format6 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",6);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option>"; if($required && $odl) echo "()"; echo "</option><option value='Detected'>Detected</option><option value='Not detected'>Not detected</option>
										</select>
									";
									break;
								case 7: //text
								case '7':
									echo "<input type='text' "; if($required && $odl) echo "value='()' "; echo "class='".$css." no-padding input-sm format7 test".$testarray['testID'].""; if($required) echo " blue"; echo "' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",7);' ".$result_final." >";
									break;
								case 8: //typ/atyp
								case '8':
									echo "
										<select tabindex='".$tabindex."' class='".$css." no-padding input-sm format8 test".$testarray['testID']." result_input"; if($required) echo " blue"; echo "' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly') echo "disabled"; echo " onchange='createnewcell(".$unit_padded.",".$test_padded.",8);' ";
										if($result_final=="readonly") echo "disabled";
										echo " >
											<option>"; if($required && $odl) echo "()"; echo "</option><option value='Typical' >Typical</option><option value='Atypical'>Atypical</option>
										</select>
									";
									break;
								case 9:
								case "9":
								echo "<input type='text' "; if($required && $odl) echo "value='()' "; echo "class='".$css." no-padding input-sm format9 test".$testarray['testID'].""; if($required) echo " blue"; echo "' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",9);' ".$result_final." >";
									break;
								default:
									if(!empty($testarray['testFormat'])) reporterror('Unknown testFormat "'.$testarray['testFormat'].'"', 'none', $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}
							$tabindex++;
							echo "</span></td>";
							$sdarray[$testarray['testID']][] = null;
						}
						$col++;
					}

					if($count==0) $average = $sum;
					else $average = $sum/$count;
					if($count==0) echo "<td style='color:orange; padding: 0px 10px 0px 10px;' class='avg fp'><span data-toggle='tooltip' title='No ".$testarray['testText']." results' class='glyphicon glyphicon-exclamation-sign has-warning' aria-hidden='true'></span></td>";
					else{
						echo "<td class='avg fp' >";
						if($testarray['testShowAvg']==1){
							echo "<strong>";
							if($count==1) echo $last_result;
							else echo numbertotext($average, $testarray['testFormat'], $testarray['testRound']);
							if($testarray['testStdev']==1 || $testarray['testStdev']=='1') echo " ± ".number_format(stats_standard_deviation($sdarray[$testarray['testID']]), $testarray['testRound'], '.', ',');
							echo "</strong>";
						}else{
							echo "<!-- Not showing avg because testShowAvg = 0 -->";
						}
						echo "</td>";
					}
					echo "<td class='avg' >".$limits;
					if($limits=="&#x221e;" || $limits=='') echo "&nbsp;<a href='limit.php'><span style='color:orange;'><span data-toggle='tooltip' title='No test limits set up for this test' class='glyphicon glyphicon-exclamation-sign has-warning' aria-hidden='true' ></span></span></a>";
					echo "</td>";

					//cov
					if($_SESSION['userSite']==4){
						if($testarray['testShowAvg']==1 && $testarray['testStdev']==1){
							$sd = stats_standard_deviation($sdarray[$testarray['testID']]);
							if($sd === 0 || $sd === '0' || $average === 0 || $average === '0'){
								$cov = 0;
							}else{
								$cov = (1 + 1 / 4 * $count) * ($sd / $average);
							}
							echo "<td class='avg' ";
							if($cov > 10) echo "style='background-color:orange;' ";
							echo "><span title='(1+1/4*".$count.")*(".$sd."/".$average.")'>" . number_format($cov,2) . "</span></td>";
						}else{
							echo "<td><!-- no cov --></td>";
						}
					}

					echo "
						<td class='hidden-print'><!-- released -->
							<input class='form-control fp' type='checkbox' ";
							if($result_final=="readonly"){
								echo "checked ";
								if($_SESSION['userRelease']!='1' && $_SESSION['userLevel']!=1) echo "disabled ";
							}
							echo "data-toggle='toggle' data-size='small' data-on='Final' data-off='Interim' data-onstyle='success' id='r".$cypherid."t".$testarray['testID']."' >
							<script>
								$('#r".$cypherid."t".$testarray['testID']."').change(function() {
									if(this.checked) { ";
										if($_SESSION['userRelease']=='1') echo "
											//alert('unchecked -> checked');
											$.post( 'ajax/update_release.php', { r:".$cypherid.", t:".$testarray['testID'].", v:1, u:".$_SESSION['userID']." })
											.done(function( data ) {
												if(data!='') alert( data );
											});
											$('.test".$testarray['testID']."').attr('readonly', true);
										";
									echo "}else{";
										if($_SESSION['userLevel']=='1') echo "
											//alert('checked -> unchecked');
											$.post( 'ajax/update_release.php', { r:".$cypherid.", t:".$testarray['testID'].", v:0, u:".$_SESSION['userID']." })
											.done(function( data ) {
												if(data!='') alert( data );
											});
											$('.test".$testarray['testID']."').attr('readonly', false);
										";
										echo "
									}
								});
							</script>
						</td>
					</tr>";
				}
				echo "</tbody><tfoot class='fp'><tr class='hidden-print'>
					<td>";
					$sql="
						Select
							dw_group.groupID,
							dw_group.groupText
						From
							dw_group
						Where
							dw_group.groupSite = ?
						Order By
							dw_group.groupOrder,
							dw_group.groupText
					";
					if(!$groupquery = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					echo "
						<select class='form-control fp' onchange='update_tests();' id='newgroup'>
							<option disabled selected ></option>";

							foreach($groupquery as $grouparray){
								echo "<option value='".$grouparray['groupID']."' ";
								if(isset($_POST['newgroup']) && $_POST['newgroup']==$grouparray['groupID']) echo "selected ";
								echo ">".$grouparray['groupText']."</option>";
							}
							echo "
						</select>
					</td>
					<td>
						<select class='form-control' id='tests' onchange='update_text_boxes();' >
							<!-- Tests will go here. Populated by get_tests.php (which is called by results.js:update_tests()) -->
						</select>
					</td>";
				foreach($units as $unitkey => $unitvalue){
					echo "<td ><input type='text' id='u".$unitkey."t0' step='any' class='form-control new-unit' onkeydown='checkKey();' onchange='createnewcell(".$unitkey.",0,1);' ></td>";
				}
				echo "</tr>";
			}else{
				// In Process or Swabs
				echo "<tr><th>Location</th><th>Sample</th>";
				//if(mysqli_prepared_num_rows($testquery)>0){

					$result_final = array();
					foreach($testquery as $testarray){
						$tests[$testarray['testID']]['groupText'  ] = $testarray['groupText'  ];
						$tests[$testarray['testID']]['testText'   ] = $testarray['testText'   ];
						$tests[$testarray['testID']]['testID'     ] = $testarray['testID'     ];
						$tests[$testarray['testID']]['specID'     ] = $testarray['specID'     ];
						$tests[$testarray['testID']]['testFormat' ] = $testarray['testFormat' ];
						$tests[$testarray['testID']]['testRound'  ] = $testarray['testRound'  ];
						$tests[$testarray['testID']]['testStdev'  ] = $testarray['testStdev'  ];
						$tests[$testarray['testID']]['testShowAvg'] = $testarray['testShowAvg'];
						$tests[$testarray['testID']]['testGroup'  ] = $testarray['testGroup'  ];

						$sql="
							# check relaese status
							Select releaseID
							From dw_resultrelease
							Where
								releaseCypher = ? And
								releaseTest = ?
						";
						if(!$releasequery = mysqli_prepared_query($link, $sql, "ii", array($cypherid, $testarray['testID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						if(mysqli_prepared_num_rows($releasequery)>0) $result_final[$testarray['testID']] = "disabled";
						else $result_final[$testarray['testID']] = "";
					}

					foreach($tests as $testkey => $testvalue){
						echo "<th class='text-center'>".$testvalue['groupText']."<br>".clean($testvalue['testText']);
						if($debug) echo " <small>[".$testkey."]</small>";
						if($testarray['testCalc']!='0' && $testarray['testCalc']!=0) echo "&nbsp;<span data-toggle='tooltip' title='Calculated field' class='glyphicon glyphicon-info-sign' aria-hidden='true' ></span>";
						if($testkey < 10) $testkey = '0' . $testkey;
						echo "<span class='hidden' id='tk".$testkey."'>".clean($testvalue['testText'])."</span>";
						echo "</th>";
					}

					//add new test
					echo "<th class='text-center new-test ip'>";
					$sql='
					Select
					  dw_group.groupText,
					  dw_test.testID,
					  dw_test.testText
					From
					  dw_group Right Join
					  dw_test On dw_test.testGroup = dw_group.groupID
					Where
						dw_test.testSite = ? And 
						dw_test.testActive = 1
					Order By
					  dw_group.groupOrder,
					  dw_test.testOrder,
					  dw_test.testText';
					if(!$query = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					echo "<select name='new_test' id='tests' class='form-control input-sm ip' ><option value='0'>New test</option>";
					$group = array();
					foreach($query as $row){
						$group[$row['groupText']][] = $row;
					}
					foreach ($group as $key => $values) {
						echo "<optgroup label='".$key."'>";
						foreach ($values as $value) {
							echo "<option value='".$value['testID']."'>".$value['testText'];
							if($debug) echo " <small>[".$value['testID']."]</small>";
							echo "</option>";
						}
						echo "</optgroup>";
					}
					echo "</select>";
					echo "</th></tr></thead>";

					//results
					foreach($unitquery as $unitarray){

						//limits
						$sql="
							# get limits, for exclamation mark
							Select
								dw_limit.limitLow,
								dw_limit.limitHigh
							From
								dw_limit
							Where
								dw_limit.limitSpec      = ? And
								dw_limit.limitLocation  = ? And
								dw_limit.limitDateFrom <= ? And
								dw_limit.limitDateTo   >= ?
							Order By
								dw_limit.limitModReason Desc
							Limit 1
						";
						$params = array($testvalue['specID'], $unitarray['locationID'], $c, $c);
						if(!$limitquery = mysqli_prepared_query($link, $sql, "iiss", $params, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						//echo "specID:".$params[1]." locationID:".$params[2]." sql: ".sprintf(str_replace('?', '"%s"', $sql), ...$params)." rows:".mysqli_prepared_num_rows($limitquery)." query:".print_r($limitquery,true);
						if(mysqli_prepared_num_rows($limitquery)>0){
							$limitarray = $limitquery[0];
							if($limitarray['limitLow']==$limitarray['limitHigh']) $limits=numbertotext($limitarray['limitLow'], $testvalue['testFormat'], $testvalue['testRound']);
							else{
								if($limitarray['limitLow']==0){
									//try to stop displaying limits as '<B', otherwise the browser gets confused and thinks it's supposed to be bold
									if($testvalue['testFormat']==4 || $testvalue['testFormat']=='4') $limits="Less than ".numbertotext($limitarray['limitHigh'], $testvalue['testFormat'], $testvalue['testRound']);
									else $limits="&lt;".numbertotext($limitarray['limitHigh'], $testvalue['testFormat'], $testvalue['testRound']);
								}else $limits = numbertotext($limitarray['limitLow'], $testvalue['testFormat'], $testvalue['testRound'])."-".numbertotext($limitarray['limitHigh'], $testvalue['testFormat'], $testvalue['testRound']);
							}
						}else $limits="&#x221e;"; //infinity

						//location
						echo "<tr class='ip'><td style='padding: 0px 10px 0px 10px;'>".$unitarray['locationText'];
						if($debug) echo " <small>[".$unitarray['locationID']."]</small>";
						if($limits=="&#x221e;" || $limits=='') echo "&nbsp;<a href='limit.php'><span style='color:orange;'><span data-toggle='tooltip' title='No limits set up for this location' class='glyphicon glyphicon-exclamation-sign has-warning' aria-hidden='true' ></span></span></a>";
						//unit (time)
						echo "</td><td style='padding: 0px 10px 0px 10px;'>".$unitarray['unitText'];
						if($debug) echo " <small>[".$unitarray['unitID']."]</small>";
						echo "<span class='hidden' id='u".$unitarray['unitID']."'>".$unitarray['unitText']."</span>";
						echo "<span class='hidden' id='l".$unitarray['unitID']."'>".$unitarray['locationText']."</span>";
						echo "</td>";

						//results
						foreach($tests as $testkey => $testarray){

							$sql="
								# get limits
								Select
									dw_limit.limitID,
									dw_limit.limitLow,
									dw_limit.limitHigh
								From
									dw_limit
								Where
									dw_limit.limitTest      = ? And
									dw_limit.limitSpec      = ? And
									dw_limit.limitLocation  = ? And
									dw_limit.limitDateFrom <= ? And
									dw_limit.limitDateTo   >= ?
								Order By
									dw_limit.limitModReason Desc
								Limit 1
							";
							$params = array($testkey, $testvalue['specID'], $unitarray['locationID'], $c, $c);
							if(!$limitquery = mysqli_prepared_query($link, $sql, "iiiss", $params, __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							if(mysqli_prepared_num_rows($limitquery)>0){
								$limitarray = $limitquery[0];
								if($limitarray['limitLow']==$limitarray['limitHigh']) $limits=numbertotext($limitarray['limitLow'], $testvalue['testFormat'], $testvalue['testRound']);
								else{
									if($limitarray['limitLow']==0){
										//try to stop displaying limits as '<B', otherwise the browser gets confused and thinks it's supposed to be bold
										if($testvalue['testFormat']==4 || $testvalue['testFormat']=='4') $limits="Less than ".numbertotext($limitarray['limitHigh'], $testvalue['testFormat'], $testvalue['testRound']);
										else $limits="&lt;".numbertotext($limitarray['limitHigh'], $testvalue['testFormat'], $testvalue['testRound']);
									}else $limits = numbertotext($limitarray['limitLow'], $testvalue['testFormat'], $testvalue['testRound'])."-".numbertotext($limitarray['limitHigh'], $testvalue['testFormat'], $testvalue['testRound']);
								}
							}else $limits="&#x221e;"; //infinity

							if(!isset($limitarray['limitID'])){
								$limitarray['limitID'] = null;
							}

							$sql="
								# get result
								Select
									dw_result.resultID,
									dw_result.resultFriendly,
									dw_result.resultReference,
									dw_result.resultModDate,
									dw_result.resultNotes,
									dw_user_mod.userFirst    As userFirst_mod,
									dw_user_mod.userLast     As userLast_mod,
									dw_user_tested.userFirst As userFirst_tested,
									dw_user_tested.userLast  As userLast_tested
								From
									dw_user dw_user_mod Right Join
									dw_result              On dw_user_mod.userID         = dw_result.resultModUser Left Join
									dw_unit                On dw_result.resultUnit       = dw_unit.unitID          Left Join
									dw_user dw_user_tested On dw_result.resultTestedUser = dw_user_tested.userID
								Where
									dw_result.resultUnit = ? And
									dw_result.resultTest = ? And
									dw_unit.unitLocation = ?
								Order By
									dw_result.resultModDate Desc
								Limit 2
							";

							if(!$resultquery = mysqli_prepared_query($link, $sql, "iii", array($unitarray['unitID'], $testkey, $unitarray['locationID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							if($debug) echo "<br>";
							$resultquery_numrows = mysqli_prepared_num_rows($resultquery);
							if($resultquery_numrows > 0){
								//ip, has result
								$resultarray = $resultquery[0];
								if($debug) echo "<td style='text-align:center;width:100px;' title='".$sql."'>";
								else echo "<td style='text-align:center;width:100px;'>";
								$limittext = "";
								$oos = false;
								if($limits!="&#x221e;"){ //infinity
									if(texttonumber($resultarray['resultFriendly'], $testarray['testFormat'])<$limitarray['limitLow' ]){ $limittext = "<strong>Result too low!</strong><br>";  $oos=true; }
									if(texttonumber($resultarray['resultFriendly'], $testarray['testFormat'])>$limitarray['limitHigh']){ $limittext = "<strong>Result too high!</strong><br>"; $oos=true; }
								}

								$sdarray[$testkey][] = texttonumber($resultarray['resultFriendly'], $testarray['testFormat']); //add result to std dev array

								$popover = "onclick='hideallpopovers();' title='";
								if($resultquery_numrows > 1) $popover .= "<small>Original result: ".$resultquery[0]['resultFriendly']."</small><br>This r";
								else $popover .= "R";
								$popover .= "esult: ".$resultarray['resultFriendly']."' data-content=\"";
								if($allowdelete) $popover .= "<span class='nobr'><a href='#' data-toggle='modal' data-target='#confirmDelete' onclick='updatedeleteprompt(".$resultarray['resultID'].");' >Delete this result</a></span><br>";
								$popover .= "
									<span class='nobr'><a href='trends.php?t=".$testkey."'>View ".substr($testarray['testText'],0,20)." trend</a></span><br>
									<span class='nobr'>".$limittext."<a href='limit.php?s=".$testvalue['specID']."&l=".$limitarray['limitID']."'>Limits: ".$limits."</a></span><br>";
									if(!empty($resultarray['resultReference'])) $popover.="<span class='nobr'>Reference: ".$resultarray['resultReference']."</span><br>";
									if(!empty($resultarray['userFirst_tested'])) $popover.="<span class='nobr'>Tested by: ".$resultarray['userFirst_tested'].' '.$resultarray['userLast_tested'][0]."</span><br>";
									$popover.="<span class='nobr'>Entered by: ".$resultarray['userFirst_mod'].' '.$resultarray['userLast_mod'][0]."</span><br>
									<span class='nobr'>Date: ".date('j/n/y G:i',strtotime($resultarray['resultModDate']))."</span><br>
									<span class='italic' ";
									if(strlen($resultarray['resultNotes'])>22){
										$popover .= "title='".$resultarray['resultNotes']."' >".substr($resultarray['resultNotes'],0,22)."&hellip;";
									}else{
										$popover .= ">".$resultarray['resultNotes'];
									}
									$popover .= "</span>
									\" data-toggle='popover' data-html=true data-container='body' data-trigger='click' data-placement='left' ";

								if($oos) $popover .= "style='background-color:orange;' ";

								if($debug){
									//echo "<span>Unit:".$unitarray['unitID']." Test:".$testkey."</span>";
									echo "<small>[".$resultarray['resultID']."]</small>";
								}

								$unit_padded = str_pad($unitarray['unitID'], 2, "0", STR_PAD_LEFT);
								$test_padded = str_pad($testkey, 2, "0", STR_PAD_LEFT);

								echo "<span class='visible-print-inline'>".str_replace(',,',',', $resultarray['resultFriendly']);
								if($oos) echo "<span class='glyphicon glyphicon-exclamation-sign'></span>";
								echo "</span><span class='hidden-print'>";

								$css = 'form-control result_input ip has-result';
								if($resultquery_numrows > 1) $css .= ' retest';

								switch($testarray['testFormat']){
									case 1: //count
									case '1':
										$cellvalue=clean($resultarray['resultFriendly']);
										if(substr($cellvalue, -6)=="000000") $cellvalue = substr($cellvalue, 0, strlen($cellvalue)-6).",000,000";
										else if(substr($cellvalue, -3)=="000") $cellvalue = substr($cellvalue, 0, strlen($cellvalue)-3).",000";
										echo "<input ".$popover." tabindex='".$tabindex."' type='text' class='".$css." no-padding format1' id='u".$unit_padded.'t'.$test_padded."' value='".$cellvalue."' ".$readonlystatus." ".$result_final[$testkey]." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' >";
										break;
									case 2: //abs/pres
									case '2':
										echo "
											<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding format2' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " >
												<option></option><option value='Absent' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,3)=='abs' ) echo "selected ";
												echo ">Absent</option><option value='Present' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,4)=='pres') echo "selected ";
												echo ">Present</option>
											</select>
										";
										break;
									case 3: //number
									case '3':
										echo "<input ".$popover." type='number' ";
										//get the step from testRound
										$step = "0.";
										for ($i = 0; $i < $testarray['testRound']; $i++) $step .= "0";
										$step = substr($step, 0, (strlen($step)-1));
										$step .= "1";

										if(is_numeric($resultarray['resultFriendly']) || empty($resultarray['resultFriendly'])){
											if(isset($resultarray['resultFriendly']) && $resultarray['resultFriendly']!="" && $resultarray['resultFriendly']!=null) $cellvalue = number_format(trim($resultarray['resultFriendly']), $testarray['testRound'], ".", '');
											else $cellvalue = "";
										}else{
											$cellvalue = -1; //test format is wrong
											//reporterror("Test format is incorrect. Currently number format, but '".$resultarray['resultFriendly']."' is not a number", "Group: ".$testarray['testGroup'].", Test: ".$testarray['testText']." [".$testarray['testID']."]", $_SERVER['REQUEST_URI'], __FILE__, __LINE__, "", False);
											$message['type']="warning";
											$message['text']="The test <strong>format</strong> for ".$testarray['groupText']." ".$testarray['testText']." is not correct. Currently the format is 'number' but '".$resultarray['resultFriendly']."' contains non-numeric characters. Results will show as -1 until this is fixed. Would you like to go to the <strong>tests page</strong> now?";
										}
										echo "step='".$step."' class='".$css." no-padding format3' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".$cellvalue."' ".$readonlystatus." ".$result_final[$testkey]." onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' >";
										break;
									case 4: //letter
									case '4':
										echo "<input ".$popover." type='text' class='".$css." no-padding format4' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".clean($resultarray['resultFriendly'])."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " >";
										break;
									case 5: //pass/fail
									case '5':
										echo "
											<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding format5' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " >
												<option></option><option value='Pass' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,4)=='pass') echo "selected ";
												echo ">Pass</option><option value='Fail' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,4)=='fail') echo "selected ";
												echo ">Fail</option>
											</select>
										";
										break;
									case 6: //detected/not detected
									case '6':
										echo "
											<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding format6' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " >
												<option></option><option value='Detected' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,3)=='det') echo "selected ";
												echo ">Detected</option><option value='Not detected' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,3)=='not' || strtolower($resultarray['resultFriendly'])=='nd' || strtolower(substr($resultarray['resultFriendly'],0,2))=='no') echo "selected ";
												echo ">Not detected</option>
											</select>
										";
										break;
									case 7: //text
									case '7':
										echo "<input ".$popover." type='text' class='".$css." no-padding format7' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".clean($resultarray['resultFriendly'])."' ".$readonlystatus." ".$result_final[$testkey]." >";
										break;
									case 8: //typ/atyp
									case '8':
										echo "
											<select ".$popover." tabindex='".$tabindex."' class='".$css." no-padding format8' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " >
												<option></option><option value='Typical' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,3)=='typ') echo "selected ";
												echo ">Typical</option><option value='Atypical' ";
													if(substr(strtolower($resultarray['resultFriendly']),0,4)=='atyp') echo "selected ";
												echo ">Atypical</option>
											</select>
										";
										break;
									case 9:
									case "9":
										echo "<input ".$popover." type='text' class='".$css." no-padding format9' tabindex='".$tabindex."' id='u".$unit_padded.'t'.$test_padded."' value='".clean($resultarray['resultFriendly'])."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " >";
										break;
									default:
										if(!empty($testarray['testFormat'])) reporterror('Unknown testFormat "'.$testarray['testFormat'].'"', 'none', $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								}
								//echo $resultarray['resultFriendly'];
								echo "</span>";
								echo "</td>";

							}else{
								//no result

								echo "<td class='ip no-result'>";

								$css='form-control';
								if(!empty($_GET['f'])) $css .= ' blue';

								echo "<span class='visible-print-inline'>&nbsp;</span><span class='hidden-print'>";
								$unit_padded = str_pad($unitarray['unitID'], 2, "0", STR_PAD_LEFT);
								$test_padded = str_pad($testkey, 2, "0", STR_PAD_LEFT);

								switch($testarray['testFormat']){
									case 1: //count
									case '1':
										echo "<input type='text' class='".$css." no-padding result_input ip no-result' tabindex='".$tabindex."' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." ".$result_final[$testkey]." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' value='()' >";
										break;
									case 2: //abs/pres
									case '2':
										echo "
											<select tabindex='".$tabindex."' class='".$css." no-padding result_input ip no-result' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' >
												<option>()</option><option value='Absent' >Absent</option><option value='Present'>Present</option>
											</select>
										";
										break;
									case 3: //number
									case '3':
										echo "<input type='number' ";
										//get the step from testRound
										$step = "0.";
										for ($i = 0; $i < $testarray['testRound']; $i++) $step .= "0";
										$step = substr($step, 0, (strlen($step)-1));
										$step .= "1";
										echo "step='".$step."' class='".$css." no-padding result_input ip no-result' tabindex='".$tabindex."' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." ".$result_final[$testkey]." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' value='' >";
										break;
									case 4: //letter
									case '4':
										echo "<input type='text' class='".$css." no-padding result_input ip no-result' tabindex='".$tabindex."' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." ".$result_final[$testkey]." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' value='()' >";
										break;
									case 5: //pass/fail
									case '5':
										echo "
											<select tabindex='".$tabindex."' class='".$css." no-padding result_input ip no-result' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' >
												<option>()</option><option value='Pass'>Pass</option><option value='Fail'>Fail</option>
											</select>
										";
										break;
									case 6: //detected/not detected
									case '6':
										echo "
											<select tabindex='".$tabindex."' class='".$css." no-padding result_input ip no-result' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' >
												<option>()</option><option value='Detected'>Detected</option><option value='Not detected'>Not detected</option>
											</select>
										";
										break;
									case 7: //text
									case '7':
										echo "<input type='text' class='".$css." no-padding result_input ip no-result' tabindex='".$tabindex."' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." ".$result_final[$testkey]." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' value='()' >";
										break;
									case 8: //typ/atyp
									case '8':
										echo "
											<select tabindex='".$tabindex."' class='".$css." no-padding result_input ip no-result' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' "; if($readonlystatus=='readonly' || $result_final[$testkey]=='disabled') echo "disabled"; echo " onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' >
												<option>()</option><option value='Typical' >Typical</option><option value='Atypical'>Atypical</option>
											</select>
										";
										break;
									case 9:
									case "9":
										echo "<input type='text' class='".$css." no-padding result_input ip no-result' tabindex='".$tabindex."' name='u".$unit_padded.'t'.$test_padded."' id='u".$unit_padded.'t'.$test_padded."' ".$readonlystatus." ".$result_final[$testkey]." onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",".$test_padded.",".$testarray['testFormat'].");' value='()' >";
										break;
									default:
										if(!empty($testarray['testFormat'])) reporterror('Unknown testFormat "'.$testarray['testFormat'].'"', 'none', $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								}
								$tabindex++;
								echo "</span></td>";
							}
						}
						echo "<td><input type='text' id='u".$unit_padded."t0' class='form-control no-padding result_input ip no-result' onkeydown='checkKey();' onchange='createnewcell(".$unit_padded.",0,0);'></td>";
						echo "</tr>";
					}

					echo '</tbody><tfoot class="ip">';

					//avg & std dev
					echo "<tr class='ip'><td colspan='2'><strong>Average</strong></td>";
					foreach($tests as $testkey => $testarray){
						echo "<td class='avg'>";
						if($testarray['testShowAvg']==1){
							echo "<strong>";
							$sum = 0;
							$count = 0;
							if(isset($sdarray) && isset($sdarray[$testkey])){
								foreach($sdarray[$testkey] as $result){
									$sum += $result;
									//$last_result = $result;
									$count++;
								}
							}

							//this is to stop division by zero errors
							$show = true;
							switch($count){
								case 0:
									$result = 0;
									$show = false;
									break;
								case 1:
									$result = $sum;
									$show = true;
									break;
								default:
									$result = $sum / $count;
									$show = true;
							}

							if($show){
								echo numbertotext(number_format($result, $testarray['testRound'], '.', ''), $testarray['testFormat'], $testarray['testRound']);
								echo '<!-- x:n2t('.number_format($result, $testarray['testRound'], '.', '').', '.$testarray['testFormat'].', '.$testarray['testRound'].') -->';
								if($testarray['testStdev']==1 || $testarray['testStdev']=='1') echo " ± ".number_format(stats_standard_deviation($sdarray[$testkey]), $testarray['testRound'], '.', ',');
							}else{
								echo '<!-- no results to show -->';
							}
							/*
							switch($count){
								case 0:
									echo numbertotext(number_format(0, $testarray['testRound'], '.', ''), $testarray['testFormat'], $testarray['testRound']);
									echo '<!-- 0:n2t('.number_format(0, $testarray['testRound'], '.', '').', '.$testarray['testFormat'].', '.$testarray['testRound'].') -->';
									break;
								case 1:
									//echo numbertotext(number_format($sum, $testarray['testRound'], '.', ','), $testarray['testFormat'], $testarray['testRound']);
									echo '<!-- 1:'.$last_result.' -->';
									echo $last_result;
									break;
								default:
									echo numbertotext(number_format($sum/$count, $testarray['testRound'], '.', ''), $testarray['testFormat'], $testarray['testRound']);
									echo '<!-- x:n2t('.number_format($sum/$count, $testarray['testRound'], '.', '').', '.$testarray['testFormat'].', '.$testarray['testRound'].') -->';
									if($testarray['testStdev']==1 || $testarray['testStdev']=='1') echo " ± ".number_format(stats_standard_deviation($sdarray[$testkey]), $testarray['testRound'], '.', ',');
							}
							*/
							echo "</strong>";
						}else{
							echo "<!-- testShowAvg=0 -->";
						}
						echo "</td>";
					}
					echo "</tr>";

					//prod release
					echo "<tr class='ip'><td colspan='2'><strong>Released</strong></td>";
					foreach($tests as $testkey => $testarray){
						echo "<td class='avg'>";

						echo "
							<input class='form-control ip' type='checkbox' ";
						if($result_final[$testarray['testID']]=="readonly"){
							echo "checked ";
							if($_SESSION['userRelease']!='1' && $_SESSION['userLevel']!=1) echo "disabled ";
						}
						echo "data-toggle='toggle' data-size='small' data-on='Final' data-off='Interim' data-onstyle='success' id='r".$cypherid."t".$testarray['testID']."' >
							<script>
								";
									$sql='# get release status
										Select
											releaseID
										From
											dw_resultrelease
										Where
											releaseCypher = ? And
											releaseTest = ?';
									if(!$releasequery = mysqli_prepared_query($link, $sql, "ii", array($cypherid, $testarray['testID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
									if(mysqli_prepared_num_rows($releasequery) > 0){
										echo "$(function(){ $('#r".$cypherid."t".$testarray['testID']."').bootstrapToggle('on'); });";
									}
								echo "
								//click event handler
								$('#r".$cypherid."t".$testarray['testID']."').change(function() {
									if(this.checked) { ";
										if($_SESSION['userRelease']=='1') echo "
											//alert('unchecked -> checked');
											$.post( 'ajax/update_release.php', { r:".$cypherid.", t:".$testarray['testID'].", v:1, u:".$_SESSION['userID']." })
											.done(function( data ) {
												if(data!='') alert( data );
											});
											$('.test".$testarray['testID']."').attr('readonly', true);
										";
									echo "}else{";
										if($_SESSION['userLevel']=='1') echo "
											//alert('checked -> unchecked');
											$.post( 'ajax/update_release.php', { r:".$cypherid.", t:".$testarray['testID'].", v:0, u:".$_SESSION['userID']." })
											.done(function( data ) {
												if(data!='') alert( data );
											});
											$('.test".$testarray['testID']."').attr('readonly', false);
										";
										echo "
									}
								});
							</script>
						</td>";
					}
					echo "</tr>";

					echo "<tr class='hidden-print'><td>";
					$loc_sql="
						# get locations
						Select
							dw_locgroup.locGroupText,
							dw_location.locationID,
							dw_location.locationText
						From
							dw_locgroup Right Join
							dw_location
								On dw_locgroup.locGroupID = dw_location.locationGroup
						Where
							dw_location.locationSite = ? And
							dw_location.locationActive = 1
						Order By
							dw_locgroup.locGroupOrder,
							dw_location.locationOrder,
							dw_location.locationText
					";
					if(!$loc_query = mysqli_prepared_query($link, $loc_sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $loc_sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					echo "<select name='new_location' id='new_location' class='form-control input-sm ip'>";
					$group = array();
					foreach($loc_query as $row){
						$group[$row['locGroupText']][] = $row;
					}
					foreach ($group as $key => $values) {
						echo "<optgroup label='".$key."'>";
						foreach ($values as $value) {
							echo "<option value='".$value['locationID']."'";
								if(isset($_POST['new_location']) && $_POST['new_location']==$value['locationID']) echo " selected";
								echo ">".$value['locationText'];
								if($debug) echo " <small>[".$value['locationID']."]</small>";
							echo "</option>";
						}
						echo "</optgroup>";
					}
					echo "</select>";

					if($_SESSION['userLevel']<= $_SESSION['admin_unit_add']){
						echo "</td><td><input type='text' class='form-control input-sm' id='new_sample' name='new_sample' placeholder='New sample' >";
						time_input('new_sample');
						echo "</td>";
						foreach($tests as $testkey => $testvalue){
							echo '<td><input type="text" name="u0t'.$testkey.'" id="u0t'.$testkey.'" class="form-control new-unit input-sm" onkeydown="checkKey();" onchange="createnewcell();" ></td>'; //new results box, need to get test
						}
						echo "</tr>";
					}
				//}else echo "No results. Please choose a sub form from the dropdown underneath the calendar";
			}
			echo "</tfoot></table>
			<div class='text-center hidden-print'>
			<div id='newresults' ";
			if(!$debug) echo "style='display:none;'";
			echo ">New results go here:</div>
				<!-- <input type='submit' class='btn btn-default btn-primary' name='save' value='Save'> -->
				<input type='hidden' name='save' value='Save'>
				<a id='savebtn' class='btn btn-default btn-primary' href='#' role='button' onclick=\"submitform();\" ><span class='glyphicon glyphicon-save' aria-hidden='true'></span>&nbsp;Save</a>
			</div></form>";
		}else echo "There are no samples present. <a href='cypher.php?u=".$cypherid."'>Add a sample</a>"; //beware of spaces here!
	//}else{
	//	echo "Please choose a cypher/batch from under the calendar";
	//}
?>
</div>

<div class="modal fade" id="confirmDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
				<h4 class="modal-title" id="myModalLabel"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>&nbsp;Confirm delete</h4>
			</div>
			<div class="modal-body" id='deletebody'>Are you sure you want to <strong>permanently delete</strong> this test result? This action cannot be undone</div>
			<div class="modal-footer">
				<form method="post">
					<input type='hidden' name='resultID' id='resultID' value=''>
					<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
					<button type="submit" class="btn btn-primary" name="delresult">Yes</button>
				</form>
			</div>
		</div>
	</div>
</div>

<script src="js/results.js?v=2.6"><!-- Include JS specific to results.php (this file) --></script>
<script src="js/responsive-calendar.js?v=2.1"><!-- for calendar --></script>

</div></div>
<?php require "inc/footer.php"; ?>
