<?php
	//Ensure no caching
	header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	header("Pragma: no-cache"); // HTTP/1.0
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

?><!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, width=device-width, viewport-fit=cover" />
		<meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="mobile-web-app-capable" content="yes">
		
	    
	    <link rel="apple-touch-icon" href="medimage-icons/apple-icon-152x152.png" />	
		<link rel="apple-touch-icon" sizes="128x128" href="icon.png">	
		<link rel="icon" type="image/x-icon" href="medimage-icons/favicon-16x16.png" />
		
		<!--<link rel="icon" href="favicon.ico">-->
		<link rel="apple-touch-icon" sizes="57x57" href="medimage-icons/apple-icon-57x57.png">
		<link rel="apple-touch-icon" sizes="60x60" href="medimage-icons/apple-icon-60x60.png">
		<link rel="apple-touch-icon" sizes="72x72" href="medimage-icons/apple-icon-72x72.png">
		<link rel="apple-touch-icon" sizes="76x76" href="medimage-icons/apple-icon-76x76.png">
		<link rel="apple-touch-icon" sizes="114x114" href="medimage-icons/apple-icon-114x114.png">
		<link rel="apple-touch-icon" sizes="120x120" href="medimage-icons/apple-icon-120x120.png">
		<link rel="apple-touch-icon" sizes="144x144" href="medimage-icons/apple-icon-144x144.png">
		<link rel="apple-touch-icon" sizes="152x152" href="medimage-icons/apple-icon-152x152.png">
		<link rel="apple-touch-icon" sizes="180x180" href="medimage-icons/apple-icon-180x180.png">
		<link rel="icon" type="image/png" sizes="192x192"  href="medimage-icons/android-icon-192x192.png">
		<link rel="icon" type="image/png" sizes="48x48" href="medimage-icons/windows-icon-48x48.png">
		<link rel="icon" type="image/png" sizes="32x32" href="medimage-icons/favicon-32x32.png">
		<link rel="icon" type="image/png" sizes="96x96" href="medimage-icons/favicon-96x96.png">
		<link rel="icon" type="image/png" sizes="16x16" href="medimage-icons/favicon-16x16.png">
		<link rel="icon" type="image/png" sizes="256x256" href="medimage-icons/windows-icon-256x256.png">
		<link rel="icon" type="image/png" sizes="24x24" href="medimage-icons/windows-icon-24x24.png">
		<link rel="manifest" href="medimage-icons/manifest.json">
		<meta name="msapplication-TileColor" content="#ffffff">
		<meta name="msapplication-TileImage" content="medimage-icons/ms-icon-144x144.png">
		<meta name="theme-color" content="#ffffff">
	    
	        <meta http-equiv="Content-Security-Policy" content="style-src 'self' 'unsafe-inline'; media-src * blob; img-src 'self' data:; connect-src * data:;">
	     
		<link rel="stylesheet" href="css/onsenui.css"/>
		<link rel="stylesheet" href="css/onsen-css-components-purple-theme.css">
    	
    	<link rel="stylesheet" type="text/css" href="css/ionicons/css/ionicons.css">
    	<link rel="stylesheet" type="text/css" href="css/material-design-iconic-font/css/material-design-iconic-font.css">
    	<noscript>Sorry, 'JavaScript' is disabled in your browser. Please enabled JavaScript in your browser to be able to operate the MedImage app.</noscript>
    	
    	<script>
    		//Run these cookie checks before any other .js scripts are included, and may fail
    		//But keep the functionality up-to-date with index.js versions of the same functions
    	
    		
    		    function myTrim(x)
				{
					return x.replace(/^\s+|\s+$/gm,'');
				}

				function getCookie(cname)
				{	
					if(document && document.cookie) {
						var name = cname + "=";
						var ca = document.cookie.split(';');
						for(var i=0; i<ca.length; i++)
						{
							var c = myTrim(decodeURIComponent(ca[i]));// ie8 didn't support .trim();
							if (c.indexOf(name)==0) return c.substring(name.length,c.length);
						}
					}
					return "";
				}


				function cookieOffset()
				{
				  //Should output: Thu,31-Dec-2020 00:00:00 GMT
				  var cdate = new Date;
				  var expirydate=new Date();
				  expirydate.setTime(expirydate.getTime()+(365*3*60*60*24*1000));	//3 years, although 2 years may be the limit on some browsers
				  var write = expirydate.toGMTString();
				  
				  return write;
				}
								
    		    
				function localStorageGetItem(mykey) {
				
					return getCookie(mykey);	
				}
	
	
    
				function localStorageSetItem(mykey, value) {
										
					//Now set the cookie locally
					document.cookie = mykey + '=' + encodeURIComponent(value) + '; path=/; SameSite=Strict; expires=' + cookieOffset() + ';';		//Note: strict means cookies only used by this site
										
					if(mykey !== "currentPhotoId") {		//We don't want to call the server every time we take a photo. It doesn't matter if
														//this gets reset on an iPhone, as it is just a current count. The 7-day cookies should be fine.
						var data = {};	
						data.name = mykey;
						data.value = value;
					
						
						//And start a server-side setting of the cookie via an http response. Important for iPhones.
						if(window.jQuery) {			//Note: the first time we run this, to do the checking of whether the cookies are working,
															//jQuery won't have been defined. We can skip the secondary setting of the cookies in this case, anyway.
							
							jQuery.ajax({
									url: "cook/set-cookie.php",
									data: data,
									method:"POST",
									cache:false,
									crossDomain: false,
									global: false,
									error: function(err) {
										console.error(err);
									},
									success: function(data) {
										console.log(data);
									},
									complete:function(){
										console.log("Request finished.");
									}
							});
						}
					}
				}
				
				function localStorageRemoveItem(mykey) {
    	 			document.cookie = mykey + '=; SameSite=Strict; expires=Thu, 01 Jan 1970 00:00:00 GMT';  
				}
    
				function localStorageClear() {
					//Note: this won't remove different paths
					var c = document.cookie.split("; ");
			 		for (i in c) {
			  			document.cookie =/^[^=]+/.exec(c[i])[0]+"=; SameSite=Strict; expires=Thu, 01 Jan 1970 00:00:00 GMT"; 
			  		}  

				}
    	
    	
    		
    		   function reportStorage(storageWorking) {
    		   		
    		   		if(storageWorking === false) {
    		   	
						alert("Warning: Your browser needs '1st party cookies' to be enabled to be able to remember the MedImage Server connections between visits. How to do this differs per browser, but look under your browser's Privacy Settings to correct this. You may also try a different browser.");  
					}
    		   }
    	
			   function checkLocalStorageEnabled() {
					//Checks if local storage, currently cookie-based, existings and is working
					
					try {
				 		localStorageSetItem("ce", "exists");
				 		//Wait for a fraction of a second
				 						 		
				 		setTimeout(function() {
				 			try {
						 		var item = localStorageGetItem("ce");
								
								if(!item) {
									reportStorage(false);
									return false;
								} else {
									if(item === "exists") {
										reportStorage(true);
										return true;
									} else {
										//Stored connections not being held correctly
										reportStorage(false);
										return false;
									}
								}
							} catch(err) {
								reportStorage(false);
								return false;
							}
						}, 10);
					} catch(err) {
						reportStorage(false);
						return false;
					}
				
				}
				
				
				//Check if local storage exists, and provide a warning if not
				setTimeout(function() {
					checkLocalStorageEnabled();
				}, 50);
				
			
    	</script>
      	<script src="js/onsenui.js"></script>
    	<script src="js/jquery-3.4.0.js"></script>
    	
    	<!-- Live atomjump cdn -->
	<script src='https://frontcdn.atomjump.com/tesseract-worker/node_modules/tesseract.js/dist/tesseract.min.js'></script>
    	
    	
		<script>
		
	      // This event fires when the keyboard will hide
			window.addEventListener('native.keyboardshow', keyboardShowHandler);



			function keyboardShowHandler(e){
				//$("body").addClass("keyboardOn");
				var deviceHeight = window.innerHeight;
				var keyboardHeight = e.keyboardHeight;
				var deviceHeightAdjusted = deviceHeight - keyboardHeight;//device height adjusted
				deviceHeightAdjusted = deviceHeightAdjusted < 0 ? (deviceHeightAdjusted * -1) : deviceHeightAdjusted;//only positive number
				document.getElementById('page').style.height = deviceHeightAdjusted + 'px';//set page height
				document.getElementById('page').setAttribute('keyBoardHeight', keyboardHeight);//save keyboard height
			}

			// This event fires when the keyboard will show
			window.addEventListener('native.keyboardhide', keyboardHideHandler);

			function keyboardHideHandler(e){
				   setTimeout(function () {
						document.getElementById('page').style.height = 100 + '%';//device  100% height
					}, 100);
			}
			
			
			function checkPlatform() {
				var platform = "Desktop";	//Assume this to begin with
				
				var isiOSLike = navigator.platform.match(/(iPhone|iPod|iPad)/i) ? true:false;				
				if(isiOSLike) platform = "iOS";
				if(navigator.platform === 'MacIntel' && typeof navigator.standalone !== "undefined") platform = "iOS";	//See https://stackoverflow.com/questions/57765958/how-to-detect-ipad-and-ipad-os-version-in-ios-13-and-up
				
				var userAgent = navigator.userAgent.toLowerCase();
				var android = userAgent.indexOf("android") > -1;
				if(android) platform = "Android";
						
				return platform;

			}
			
			
			var platformGuideIndex = {
				"iOS": "ios-guide",
				"Android": "android-guide",
				"Desktop": "desktop-guide"           
			};
			
			var platformButtonIndex = {
				"iOS": "ios-button",
				"Android": "android-button",
				"Desktop": "desktop-button"           
			};
			
			function selectGuide(detectedPlatform) {
			
				//Show the relevant text block
				jQuery("#" + platformGuideIndex[detectedPlatform]).toggle();
				if(detectedPlatform != "iOS") {
					$('#ios-guide').hide(); 
				}
				if(detectedPlatform != "Android") {
					$('#android-guide').hide(); 
				}
				if(detectedPlatform != "Desktop") {
					$('#desktop-guide').hide();
				}
			
				if(jQuery("#" + platformButtonIndex[detectedPlatform]).hasClass("highlighted")) {
					jQuery("#" + platformButtonIndex[detectedPlatform]).removeClass("highlighted");
				} else {
					jQuery("#" + platformButtonIndex[detectedPlatform]).addClass("highlighted");
				}
				
				if(detectedPlatform != "iOS") {
					$('#ios-button').removeClass("highlighted");
				}
				if(detectedPlatform != "Android") {
					$('#android-button').removeClass("highlighted"); 
				}
				if(detectedPlatform != "Desktop") {
					$('#desktop-button').removeClass("highlighted");
				}
				
				
				
			}
			
			function showDefaultPlatform() {
				//Decide on active class based on platform used:
				$('#ios-guide').hide(); 
				$('#android-guide').hide(); 
				$('#desktop-guide').hide();
				$('#ios-button').removeClass("highlighted");
				$('#android-button').removeClass("highlighted"); 
				$('#desktop-button').removeClass("highlighted");
				
				if($('#add-to-home').is(":hidden")) {
					$('#add-to-home').show(); 
					$('#install-box-background').show();
					var detectedPlatform = checkPlatform();
			
					selectGuide(detectedPlatform);
				} else {
					//Leave everything unhighlighted
					$('#add-to-home').hide(); 
					$('#install-box-background').hide();
				}
				
				
				
				return false;
			}
			
			
			function introBeta() {
				if(confirm("'ID scanning' is one of the features in the new MedImage Beta App. Would you like to try the Beta out now?  (Note: you can use both apps at the same time, but you will need a fresh 4-digit pairing code for the Beta)")) {
					//window.location.href = "https://medimage-app-beta.atomjump.com/";
					window.open("https://medimage-app-beta.atomjump.com/",null, "width=900,height=700");	//,"_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=yes, width=900, height=700"
				}
				return false;
			}
			
		</script>

        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>MedImage</title>
    </head>
    <body>
    	<style><item name="android:windowTranslucentStatus">true</item></style> <!-- Ensure clicking inside box scrolls down -->
    	<ons-navigator>
         <ons-page>
	        
	        
	        <div id="camera-popup" style="display:none;">
					<!-- https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API/Taking_still_photos -->
					<div class="contentarea">
					 
					  <div class="camera">
						 <video id="video" playsinline>Video stream not available.</video>
						 <!--<button id="startbutton">Take photo</button>-->
						 <ons-fab style="z-index: 1400; background-color: #ddd; color: black;" id="startbutton" position="bottom center">
				   		<ons-icon icon="md-local-see" ></ons-icon>
				 		 </ons-fab>
					  </div>
					  <canvas id="cam-canvas"> </canvas>
					  
					</div>
					
					
					<div id="confirm-photo" style="display:none;">
						<div class="output">
						 <img id="photo" alt="The screen capture will appear in this box." style="display: none;"/>
					   </div>
					   
					   <div>
					   	<div style="width:50%; float: left;"><ons-button modifier="large" style="z-index: 1400; padding: 10px; background-color: #ddd; color: black;" id="retry-button"><ons-icon icon="md-undo" ></ons-icon>&nbsp;&nbsp;Retry</ons-button></div><div style="width:50%; float: right;"><ons-button modifier="large" style="z-index: 1400; padding: 10px; background-color: #ddd; color: black;" id="confirm-button"><ons-icon icon="md-thumb-up" ></ons-icon>&nbsp;&nbsp;Confirm</ons-button></div>
					 		 </div>
					</div>
          </div>
	        
		    <ons-fab style="z-index: 800;" position="bottom right" onclick="app.openSettings();">
		      <ons-icon icon="md-menu" ></ons-icon>
		    </ons-fab>
		    
		    <ons-fab style="z-index: 800;" position="bottom left" onclick="showDefaultPlatform();">
		      <ons-icon icon="md-bookmark" ></ons-icon>
		    </ons-fab>
		    
		    
	
 
        <p style="text-align:center;">
             <span class="big-text" onclick="navigator.notification.alert('Enter a patient or image ID, which names the image folder. The second word names the image file. The [ID] button allows you to snap a photo and detect an ID in English.', function(){}, 'Optional');">Image ID <small >(e.g. NHI) <ons-icon icon="ion-ios-help" size="20px" fixed-width="true"></small><br/></span><input id="id-entered" type="text" size="9" class="resizedTextbox" value=""><span id="waiting-icon" style="display: none;"><img src="img/ajax-loader.gif" width="28" height="28" style="position: relative; top: 6px; margin-left: 12px;"></span><span class="fakefile-scan"><input class="file" type="file" id="scan-button" accept="image/jpeg" capture="camera"></span>
        </p>
					

 		<div style="text-align:center;">
            <span id="currentPC"  class="pc-text"></span>
        </div>
        <div id="mainButtonDiv" class="fakefile">
        		<!-- https://www.w3.org/TR/html-media-capture/   Was image/jpeg -->
       		<input class="file" type="file" id="mypic" accept="image/jpeg" capture="environment">
       		<!-- For future improvement: you can add accept: accept="image/jpeg, application/pdf" on an option. This allows pdf uploads (though it
       		currently calls it xyz.jpg.pdf) However, each photo gives you a choice of using the camera or the file manager, so it is a slower interface)
       		Worth putting on an option though!
       		-->
       </div>
       
 
        <div style="text-align:center;">
            <span id="notify" class="notify-text" style="padding-left:4px; padding-right:4px;"></span>
            &nbsp;<span id="status" class="notify-text"></span>
            <br/><br/><span id="cancel-trans" class="cancel-text"></span>
            <br/><span id="general-warning" class="cancel-text"></span>
        </div>
        
        <!--Was in here - needed still?: <br/>-->
        
        
       <div id="install-box-background" style="display: none;">
        	<div id="install-box" >
        
        		
				<div id="add-to-home" style="display:none;">
					<small>Add app to your Homescreen <span style="float: right;"><a href="javascript:" onclick="return showDefaultPlatform();" ><ons-icon size="30px" style="color: black;" icon="md-close"></ons-icon></a></span><br/><a id="ios-button" class='button' style='margin:4px;' onclick="return selectGuide('iOS');" href='javascript:'>iOS</a>&nbsp;<a id="android-button" class='button' style='margin:4px;' onclick="return selectGuide('Android');" href='javascript:'>Android</a>&nbsp;<a id="desktop-button" class='button' style='margin:4px;' onclick="return selectGuide('Desktop');" href='javascript:'>Desktop</a></small><br/><br/>
				</div>
				
				<div id="ios-guide" style="display:none;">Tap <img src="img/safari-add.png" width="25" height="30">, usually along the bottom of the screen, then swipe up, and tap 'Add to Home Screen'. <a href="#ios-more-info" onclick="$('#ios-more-info').toggle();">More Info</a><br/><br/>
					<div id="ios-more-info" style="display:none;">
						<small><strong>Troubleshooting:</strong> if you don't see the 'Add to Home Screen' option, scroll to the bottom and tap 'Edit Actions', then tap 'Add' next to the 'Add to Home Screen'. After that, try again.</small> Or see <a href="https://support.apple.com/en-nz/guide/iphone/iph42ab2f3a7/ios#iph4f9a47bbc" target="_blank">Apple's Guide</a><br/><br/>								
						
					</div>
				</div>
				
				<div id="android-guide" style="display:none;">Tap the <img src="img/chrome-menu.png"width="20" height="20"> in the top right corner of the screen, and then choose 'Add to Home Screen'. <a href="#android-more-info" onclick="$('#android-more-info').toggle();">More Info</a><br/><br/>
					<div id="android-more-info" style="display:none;">
						<small><strong>Troubleshooting:</strong> If you cannot see the 3-dot menu, you may be in another app's internal browser. Run the browser app directly (e.g. Chrome or Firefox Fennec), and then open the MedImage app address from there.</small> Or see <a href="https://www.wikihow.com/Set-a-Bookmark-Shortcut-in-Your-Home-Screen-on-Android" target="_blank">More Tips</a><br/><br/>								
						
					</div>
				</div>
				
				<div id="desktop-guide" style="display:none;">Click the <img src="img/firefox-drag-desktop.png"> or <img src="img/chrome-desktop-drag.png"> or <img src="img/lock.png"> style icon in the address bar, to the left of the address, and depending on the browser, drag this onto your desktop. <a href="https://www.hellotech.com/guide/for/how-to-create-a-desktop-shortcut-to-a-website">More Details</a><br/><br/>In Edge on Windows, use <img src="img/edge-menu.png" width="30" height="20"> > "Apps" > "Install this site as an app".<br/>
				</div>

        	</div>
        </div>
		
		
        <div id="settings-popup" style="display:none;">
        	<div id="inner-popup">
        		
        		<span class="big-text">Settings</span><br/><br/>
        		
        		<ons-fab position="top right" onclick="app.closeSettings(); ">
		      		<ons-icon icon="md-close" ></ons-icon>
		    	</ons-fab>
        		
        		
        		<div id="settings"></div>
        		<p>
        			<ons-button style="background-color: #7c5599; color: white;" modifier="large" onclick="app.newServer();">Add a New PC</ons-button>
	        	</p>
	        	
	        	 <ons-list>
					<ons-list-item>
					  <div class="center">
						ID writes a folder <a onclick="idWritesAFolderHelp(); return false;"><ons-icon style="color: #892f83;" icon="ion-ios-help" size="20px" fixed-width="true"></a>
					  </div>
					  <div class="right">
						<ons-switch style="color: #7c5599;" id="always-create-folder" checked></ons-switch>
					  </div>
					</ons-list-item>
					<ons-list-item>
					  <div class="center">
						ID scan pattern search <a onclick="$('#pattern-match-help').toggle(); return false;"><ons-icon style="color: #892f83;" icon="ion-ios-help" size="20px" fixed-width="true"></a>
					  	<div id="pattern-match-help" style="display: none;">
					  		<br/><b>Advanced:</b> The ID scanning will detect text in the photo, and then search for a pattern in this text. By default a New Zealand NHI pattern is expected, [a-zA-Z][a-zA-Z][a-zA-Z]\d\d\d\d, which finds 3 lower or upper case characters followed by 4 digits e.g. NHI1234, but you can modify this to suit your own IDs. You will need to create a 'regular expression' and more info on these is available here: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet" target="_blank">Regular Expression Cheat Sheet</a>
					  	</div>
					  </div>
					  <div class="right">
					  	<a style="color: #892f83;" href="javascript:" onclick="$('#pattern-match').toggle(); $('#pattern-match-opts').toggle(); $('#pattern-match-help').hide(); return false;">Edit</a>&nbsp;&nbsp;<input style="display: none;" oninput="app.setPattern(); return false;" id="pattern-match" type="text" size="9" class="resizedTextbox" value="[a-zA-Z][a-zA-Z][a-zA-Z]\d\d[a-zA-Z0-9][a-zA-Z0-9]">
					  </div>
					</ons-list-item>
					<ons-list-item id="pattern-match-opts" style="display: none;">
						 <div class="right">
						    <select onchange="patternMatchSet(this.value); return false;">
						    	<option value="user">User</option>
								<option value="[a-zA-Z][a-zA-Z][a-zA-Z]\d\d\d\d">New Zealand NHID (Pre-2024)</option>	
								<option value="[a-zA-Z][a-zA-Z][a-zA-Z]\d\d[a-zA-Z0-9][a-zA-Z0-9]">New Zealand NHID (All)</option>
							</select>
						</div>
					</ons-list-item>
					
					
					<ons-list-item>
					  <div class="center">
						Camera <a onclick="cameraHelp(); return false;"><ons-icon style="color: #892f83;" icon="ion-ios-help" size="20px" fixed-width="true"></a>
					  </div>
					  <div class="right">
						<select id="video-source" onchange="cameraHelp(this.value, true); app.changeCamInterface(this.value); app.setDefaultCamera(); return false;">
							<option value="environment" selected="selected">Back-facing</option>	
							<option value="user">Front-facing</option>	
						</select>
					  </div>
					</ons-list-item>
					
					<ons-list-item>
						<div class="right">
								<a class="small-text" target="_blank" href="http://medimage.co.nz/guide/#professional">Version: 2.6.1<a/>
						</div>
					</ons-list-item>
				  </ons-list>
	        	
	        	
				<p>
					<a class="small-text" href="javascript" onclick="return app.factoryReset();">Reset Factory Settings</a>
					
				</p>
				<p>
					<a style="color: #888;" class="small-text" href="javascript:" onclick="$('#show-my-data-options').toggle();">My Data <ons-icon icon='md-cloud-download'></ons-icon></a>
				</p>
				<div id="show-my-data-options" style="display: none;">
					<p>
						<a style="color: white; background-color: #7c5599;" class="small-text button" href="javascript:" onclick="$('#import-my-data').hide(); return app.showMyData();">View <ons-icon icon='md-cloud-download'></ons-icon></a>  <a style="color: white; background-color: #7c5599;" class="small-text button" href="javascript:" onclick="$('#import-my-data').show(); $('#show-my-data').hide();">Import <ons-icon icon='md-cloud-upload'></ons-icon></a>
					</p>
					
					
					<p id="import-my-data" style="text-align:center; display: none;">
						<span class="small-text">Please paste your "Raw Data" below</span><br/><textarea style="padding:5px;" id="import-raw-data" rows="4" cols="40"></textarea><br/><span class="small-text">Export this data from 'Settings' > 'My Data' > 'View'</span>
					
						<br/><br/>
						<ons-button style="background-color: #7c5599; color: white;" modifier="large--cta" onclick="app.importCookies(); return false;"><ons-icon icon='md-cloud-upload'></ons-icon>&nbsp;&nbsp;Import Personal Data</ons-button>
					</p>
					
					<p id="show-my-data" style="display: none; background-color: rgb(238, 238, 238); opacity: 1.0; padding: 10px; padding-bottom: 100px; width:100%;">
						<span class="small-text" style="color: #555;">Your MedImage app data is stored in your local browser's 'cookies' for up to 2 years, and is annually refreshed if the app is being used. You can copy and paste this central app data into a local file, which can then be imported with the 'Import' option above, to either refresh this device, or create a new secondary device.
						<br/><br/>Please store any data here in a <b>secure location</b>.<br/></span><br/>
						<b>Raw Data:</b><br/><textarea id="raw-data" rows="4" cols="40"></textarea><br/><br/>
						<b>Readable Version:</b><br/><textarea id="human-data" rows="4" cols="40"></textarea><br/><br/>
						<b>Images Stored:</b><br/><span id="stored-image-description" class="small-text" style="color: #555;"></span><br/><a id="stored-image-link" href="" download="medimage-photo.jpg"><img id="stored-image" src="" width="90%"></a>
					</p>
				</div>
			</div>
        </div>
        
        <!-- See https://ourcodeworld.com/articles/read/322/how-to-convert-a-base64-image-into-a-image-file-and-upload-it-with-an-asynchronous-form-using-jquery -->
        
          
        
        
        <img style="display: none;" id="myImage">
		
		<form id="photo-sending-frm" method="post" action="/replaced-dynamically-with-medimage-server-path/">
		</form>

        <style>
        input.file {
			position: relative;
			text-align: right;
			-moz-opacity:0 ;
			filter:alpha(opacity: 0);
			opacity: 0;
			z-index: 1002;
			width: 300px; 
			height: 300px;
			
			margin-left: auto; 
			margin-right: auto;
			margin-bottom:10px;
			margin-top:6px;
		}
		
		
		

		.fakefile {
			position: relative;
			z-index: 1000;
			width: 300px; 
			height: 300px;
			background: url('img/logo@2x.png') no-repeat center center fixed;
			-webkit-background-size: cover;
      		-moz-background-size: cover;
      		-o-background-size: cover;
      		background-size: cover;
      		background-attachment:scroll;
  			
  			margin-left: auto; 
			margin-right: auto;
			margin-bottom:10px;
			margin-top:6px;
		}
		
		
		#scan-button {
			position: relative;
			text-align: right;
			-moz-opacity:0 ;
			filter:alpha(opacity: 0);
			opacity: 0;
			z-index: 1002;
			width: 40px; 
			height: 40px;
		}
		
		.fakefile-scan {
			position: relative;
			z-index: 1000;
			top: -10px;
			margin-left: 10px;
			width: 40px; 
			height: 40px;
			background: url('img/id-link.png') no-repeat center center fixed;
			-webkit-background-size: cover;
      		-moz-background-size: cover;
      		-o-background-size: cover;
      		background-size: cover;
      		background-attachment:scroll;
      	display: inline-block;	
		}
		

        </style>
        
        <!-- Cache these icons now for later dynamic use. These are hidden via their opacity -->
        <ons-icon style="vertical-align: middle; color:#f7afbb; filter:alpha(opacity: 0); opacity: 0; -moz-opacity:0;" size="30px" icon="fa-close"></ons-icon>
        <ons-icon style="vertical-align: middle; color:#DDD; filter:alpha(opacity: 0); opacity: 0; -moz-opacity:0;" size="20px" spin icon="fa-spinner"></ons-icon>
        
       <canvas id="standard-cam-canvas" style="display: none;"></canvas>	<! -- Should be style="display: none;" but can use display: block for testing OCR-->
       <div id="output-text"></div>
       
       <!-- From above:
      	        <div id="camera-popup" style="display:none;">
					<div class="contentarea">
					 
					  <div class="camera">
						 <video id="video">Video stream not available.</video>
						 <ons-fab style="z-index: 1400; background-color: #ddd; color: black;" id="startbutton" position="bottom center">
				   		<ons-icon icon="md-local-see" ></ons-icon>
				 		 </ons-fab>
					  </div>
					  <canvas id="cam-canvas"> </canvas>
					  
					</div>
					
					<div id="confirm-photo" style="display:none;">
						<div class="output">
						 <img id="photo" alt="The screen capture will appear in this box." style="display: none;"/>
					   </div>
					   
					   <div>
					   	<div style="width:50%; float: left;"><ons-button modifier="large" style="z-index: 1400; padding: 10px; background-color: #ddd; color: black;" id="retry-button"><ons-icon icon="md-undo" ></ons-icon>&nbsp;&nbsp;Retry</ons-button></div><div style="width:50%; float: right;"><ons-button modifier="large" style="z-index: 1400; padding: 10px; background-color: #ddd; color: black;" id="confirm-button"><ons-icon icon="md-thumb-up" ></ons-icon>&nbsp;&nbsp;Confirm</ons-button></div>
					 		 </div>
					</div>
          </div>
          -->

		<style>
		#video {
		  position: relative;
		  left: 0px;
		  top: 0px;
		  width: 100%; 
		  height: 100%;
		  object-fit: fill;
		}

		#photo {
		  width: 100%; 
		  height: 100%;  
		  object-fit: fill;
		  
		  position: relative;
		  left: 0px;
		  top: 0px;
		  	
		}

		#cam-canvas {
		  display: none;
		}

		.camera {		
		  width: 100%;  			
		  display: inline-block;	
		}

		.output {
		  width: 100%; 		
		  display: inline-block;	
		  vertical-align: top;
		}

		#startbutton {

		  background-color: rgb(0 150 0 / 50%);
		  border: 1px solid rgb(255 255 255 / 70%);
		  box-shadow: 0px 0px 1px 2px rgb(0 0 0 / 20%);
		  font-size: 14px;
		  font-family: "Lucida Grande", "Arial", sans-serif;
		  color: rgb(255 255 255 / 100%);
		}

		.contentarea {
		  font-size: 16px;
		  font-family: "Lucida Grande", "Arial", sans-serif;
		  width: 100%;  
		  z-index: 1410;   /* Slightly above camera-popup */
		}
		</style>

		<script>
			//https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API/Taking_still_photos#demo
		  const width = 2448; //This is a common size (4:3 aspect ratio: 3264 x 2448 pixels (8 megapixels) as of 2023. Or 16:9 aspect ratio: 4128 x 2322 pixels (9.6 megapixels)
		  								//TODO: allow user to edit this chosen resolution
		  let height = 0; // This will be computed based on the input stream

		  // |streaming| indicates whether or not we're currently streaming
		  // video from the camera. Obviously, we start at false.

		  let streaming = false;

		  // The various HTML elements we need to configure or control. These
		  // will be set by the startup() function.

		  let video = null;
		  let canvas = null;
		  let photo = null;
		  let startbutton = null;
		  var globDataURL = null;

		  function showViewLiveResultButton() {
			 if (window.self !== window.top) {
				// Ensure that if our document is in a frame, we get the user
				// to first open it in its own tab or window. Otherwise, it
				// won't be able to request permission for camera access.
				document.querySelector(".contentarea").remove();
				const button = document.createElement("button");
				button.textContent = "View live result of the example code above";
				document.body.append(button);
				button.addEventListener("click", () => window.open(location.href));
				return true;
			 }
			 return false;
		  }
		  
		  function erroredCam(err) {
		  		  alert("Sorry, we could not access the specific camera lens, at this time. We will default back to the system default camera, but please try again later as there can be various reasons, which can change.  System error: " + err);	
				  clearphoto();		
				  jQuery("#camera-popup").hide();		//Hide camera panel
				  jQuery("#confirm-photo").hide();		//Hide confirmation screen
				  glbThis.changeCamInterface("environment");		//Change the selected lens to the default system one.
		  
		  }

		  function changeCam(cam) {
		  		navigator.mediaDevices.getUserMedia({ video: { deviceId: cam }, audio: false })
				.then((stream) => {
				  video.srcObject = stream;
				  video.onloadedmetadata = (event) => {
				  	video.play();				  
				  };
				})
				.catch((err) => {
				  console.error(`An error occurred: ${err}`);
				  erroredCam(err);
				});
		  
		  }
		  
		  function initCam(cam) {
		  
		  		 if (showViewLiveResultButton()) {
					return;
				 }
				 video = document.getElementById("video");
				 canvas = document.getElementById("cam-canvas");
				 photo = document.getElementById("photo");
				 startbutton = document.getElementById("startbutton");

				 navigator.mediaDevices.getUserMedia({ video: { deviceId: cam }, audio: false })		
					.then((stream) => {
					  video.srcObject = stream;
					  video.onloadedmetadata = (event) => {
					  	video.play();				  
					  };
					})
					.catch((err) => {
					  console.error(`An error occurred: ${err}`);
					  erroredCam(err);
					});

				 video.addEventListener(
					"canplay",
					(ev) => {
					  if (!streaming) {
						 height = Math.floor(video.videoHeight / (video.videoWidth / width));

						 // Firefox currently has a bug where the height can't be read from
						 // the video, so we will make assumptions if this happens.

						 if (isNaN(height)) {
							height = Math.floor(width / (4 / 3));
						 }

						 video.setAttribute("width", width);
						 video.setAttribute("height", height);
						 
						 photo.setAttribute("width", width);
						 photo.setAttribute("height", height);
						 
						 canvas.setAttribute("width", width);
						 canvas.setAttribute("height", height);
						 streaming = true;
					  }
					},
					false,
				 );

				 startbutton.addEventListener(
					"click",
					(ev) => {
					  takepicture();
					  ev.preventDefault();
					},
					false,
				 );

				 clearphoto();
		  
		  		return;
		  }

		  function startupCam(cam) {
		  		if(app.firstTimeMediaCam == true) {
					initCam(cam);
					app.firstTimeMediaCam = false;
				} else {
					//Do nothing - camera is already running
				}
		  
		  	 jQuery("#camera-popup").show();
		  	 jQuery("#photo").hide();
		  	 jQuery("#confirm-photo").hide();
			 jQuery(".contentarea").show();
		  	 
		  	 //restart the streams, if necessary
		  	 if(video && video.srcObject) {
			  	 video.srcObject.getTracks().forEach(function(track) {
					  	track.enabled = true;
					 });
			}
		  	 
		  	 return;
		  }
		  


		  // Fill the photo with an indication that none has been
		  // captured.

		  function clearphoto() {
			 const context = canvas.getContext("2d");
			 context.fillStyle = "#AAA";
			 context.fillRect(0, 0, canvas.width, canvas.height);

			 var data = canvas.toDataURL("image/jpg");		//Was image/png
			 photo.setAttribute("src", data);
		  }

		  // Capture a photo by fetching the current contents of the video
		  // and drawing it into a canvas, then converting that to a PNG
		  // format data URL. By drawing it on an offscreen canvas and then
		  // drawing that to the screen, we can change its size and/or apply
		  // other changes before drawing it.
			
		  function captureFrame() {
	
				const context = canvas.getContext("2d");
			 	if (width && height) {
					canvas.width = width;
					canvas.height = height;
					context.drawImage(video, 0, 0, width, height);
					
					globDataURL = canvas.toDataURL("image/jpeg", 0.95);  //was image/png
					photo.setAttribute("src", globDataURL);
					
					return globDataURL;
				} else {
					clearphoto();
			 	}
		  
		  }


		  function takepicture() {
		  
		  	  //See https://www.dynamsoft.com/codepool/take-high-resolution-photo-in-the-browser.html
		  	  if ("ImageCapture" in window) {
			  try {
					const track = video.srcObject.getVideoTracks()[0];		//getTracks?
			
					
					let imageCapture = new ImageCapture(track);
					try { 			
						
						const photoSettings = (width && height) ? {
						  imageWidth: width,
						  imageHeight: height
						} : null;
					
						
					
					 imageCapture
						 .takePhoto(photoSettings)
						 .then((blob) => {
						 	
							console.log("Took photo:", blob);
						
							var objectURL = URL.createObjectURL(blob);
							
							
							
							photo.src = objectURL;		//A smaller visual screen-sized preview
							photo.onload = function(){
							  
								const context = canvas.getContext("2d");
								canvas.width = width;
								canvas.height = height;
								context.drawImage(photo, 0, 0, width, height);
											
								
								 // Save image as a data URL
								 globDataURL = canvas.toDataURL("image/jpeg", 0.95);
								
								//Show the photo
								jQuery("#photo").show();
			
								//Get agreement from user first
								jQuery("#confirm-photo").show();
								jQuery(".contentarea").hide();
							  
							};
							
							
							
							
							
							
						})		//End of imageCapture.then
							
							
					
							
					} catch(error) {
							console.error("takePhoto() error: ", error);
				   };
					
					
					
					
				 } catch(e) {
					globDataURL = captureFrame();
				 }
			  } else{
				 globDataURL = captureFrame();
			  }
			  
		  	
		  
			 if (width && height) {

				jQuery("#photo").show();
				
				//Get agreement from user first
				jQuery("#confirm-photo").show();
				jQuery(".contentarea").hide();
				
			 } else {
				clearphoto();
			 }
		  }
		  
		  function confirmPicture() {
				app.bigButton(globDataURL);  //Send data to MedImage Server
				jQuery("#camera-popup").hide();		//Hide camera panel
				jQuery("#confirm-photo").hide();		//Hide confirmation screen
				
				 //Stop the stream
				 if(video && video.srcObject) {
				  	 video.srcObject.getTracks().forEach(function(track) {
					  	track.enabled = false;
					 });
				}
		  
		  }
		  
		  
			</script>
       
       
       <script>
       	 	function cameraHelp(camId, silentInit) {
 				if(camId && camId != "") {
 					switch(camId) {
 						case "environment":
 							//No need to comment on this option
 						break;
 						
 						case "user":
 							alert("Changing this default camera option to 'front-facing' will only work on some devices and browsers. In some Android or iPhones you can also toggle the front/back camera with the 'rotating arrows' button to the right of the main photo-taking button, or select the 0.5 1x 2x zoom options to specify a lens, or use the 'macro' mode, for a close-up lense.");
 						break;

						case "initspecific":
							if(silentInit == true) {
								//no need to display this time
							} else {
								alert("You should now have new, specific, camera lenses listed in the Change Camera selection dropdown box.  Please select your preferred option there.");
							}
						break; 
 						
 						default:
 							//This is some specific camera lens
 							alert("Changing this default camera option to a specific camera lens will only work on some devices and browsers, and is still experimental. Note: You can use the default 'back-facing' option for a generic system camera.");
 						
 						break;
 					}
 				} else { 				
 					alert("Changing this default camera option will only work on some devices and browsers. 'Back-facing' uses the system-default camera. In some system-default cameras (on Android or iPhones) you can also toggle the front/back camera with the 'rotating arrows' button to the right of the main photo-taking button, or select the 0.5 1x 2x zoom options to specify a lens, or use the 'macro' mode, for a close-up lense.");
 				}
 			}
 			
 			function idWritesAFolderHelp() {
 				alert("When switched on, this option will write a new folder in the PC's target folder with the name of the first word entered in the 'Image ID' field. When this is off, all photos go into a single folder, and their filename includes the first word entered.");
 			}
 			
 			
 			//From https://github.com/jasonlee86cn/New-Zealand-NHI-validator/blob/main/New%20Zealand%20NHI%20validator.htm
 			function isLetter(str) {
			  return str.length === 1 && str.match(/[a-z]/i);
			}
 			
 			
 			
 			

			function patternMatchSet(pattern) {
				if(pattern && pattern != "user") {
					$('#pattern-match').val(pattern);
					app.setPattern();
				} else {
					$('#pattern-match').val("");
					app.setPattern();
				}
			}
			
			function preFillPatternMatch() {
				var pattern = $('#pattern-match').val();
				//Loop through to see if the pattern is a match, and set that option as the value
				jQuery('#pattern-match-opts option').each(function(i){
					if($(this).val() === pattern) {
						//$('#pattern-match-opts').val(pattern).trigger("change");	
						//alert("Selected: " + pattern);		//TESTING
						//$("#pattern-match-opts option[value='" + pattern + "']").prop('selected', true); 
						$(this).prop('selected', true); 
					} 				
				})
				
				//Default to 'user'
				setTimeout(function() {
					 if ($("#pattern-match-opts")[0].selectedIndex <= 0) {
					 	//Select the user one
		            	$("#pattern-match-opts option[value=user]").prop('selected', true); 
		        	}
		        }, 2000);
					
				
			}
			
			
 			function formatNHINumber(nhi) {
 			
		 		/*
		 			NHI official 2024 standard available here:
 					https://www.tewhatuora.govt.nz/publications/hiso-100462024-consumer-health-identity-standard
 					https://nhi-ig.hip-uat.digital.health.nz/ComplianceTestingImportantInformation.html#extra-tests-for-new-nhi-number-format
		 		
		 			Expected results:
		 			alert("'ZXE24NV':" + formatNHINumber('ZXE24NV')); 		//true
		 			alert("'ZUA48EH':" + formatNHINumber('ZUA48EH')); 		//true
		 			alert("'ZUT01RG':" + formatNHINumber('ZUT01RG')); 		//true
		 			alert("'WLD9413':" + formatNHINumber('WLD9413'));		//true
		 			alert("'zsc21tn':" + formatNHINumber('zsc21tn'));		//true
		 			alert("'zzZ0044':" + formatNHINumber('zzZ0044'));		//false
		 			alert("'ZZZ00AA':" + formatNHINumber('ZZZ00AA'));		//false
		 			alert("'zvb97xq':" + formatNHINumber('zvb97xq'));		//true
		 			alert("'ZZZ0016':" + formatNHINumber('ZZZ0016'));		//true
		 			alert("'ZZZ00AC':" + formatNHINumber('ZZZ00AC'));		//true
		 			alert("'ZZZ0044':" + formatNHINumber('ZZZ0044'));		//false
		 			alert("'ZVU27KE':" + formatNHINumber('ZVU27KE'));		//true
		 			alert("'ZAA7860':" + formatNHINumber('ZAA7860'));		//true
		 			
		 			Test photos:
		 			
		 			
		 			
		 			
		 			
		 			ZXE24NV			(true)
		 			
		 			
		 			
		 			
		 			                                               WLD9413			(true)
		 			
		 			
		 			
		 			
		 			BBZ11AA			(false)
		 			
		 			
		 			
		 			
		 			
		 			
		 			
		 		*/
		 		
				if ((!(typeof nhi === 'string')) || (nhi.length !== 7)) {
					return false;
				}
				
				//Force upper-case
				nhi = nhi.toUpperCase();

				var alphabetConversionTable = {
					'A': 1,  'B': 2, 'C': 3, 'D': 4, 'E': 5,
					'F': 6, 'G': 7, 'H': 8, 'J': 9, 'K': 10,
					'L': 11, 'M': 12, 'N': 13, 'P': 14, 'Q': 15,
					'R': 16, 'S': 17, 'T': 18, 'U': 19, 'V': 20,
					'W': 21, 'X': 22, 'Y': 23, 'Z': 24
				}
				

				var sum = 0;
				sum += alphabetConversionTable[nhi[0]] * 7;
				sum += alphabetConversionTable[nhi[1]] * 6;
				sum += alphabetConversionTable[nhi[2]] * 5;
				sum += (parseInt(nhi[3])) * 4;
				sum += (parseInt(nhi[4])) * 3;

				if (!(alphabetConversionTable[nhi[0]]) || !(alphabetConversionTable[nhi[1]]) || !(alphabetConversionTable[nhi[2]])) {
					return false; 
				}

				if (!isLetter(nhi[5])) { 
					//An old format NHI e.g. ABC1234		
					sum += (parseInt(nhi[5])) * 2;
				} else {
					//A new format NHI number e.g. ABC12DE
					if((isLetter(nhi[5])) && (alphabetConversionTable[nhi[5]])) { 
						sum += alphabetConversionTable[nhi[5]] * 2;
					} else {
						return false; 
					}
				}

				if (!isLetter(nhi[6])) { 
					var remainder = sum % 11;
					var checkDigit = 11 - remainder;
					if (checkDigit == 11) {
						return false; 
					}
					if (checkDigit == 10) {
						checkDigit = 0; 
					}
					return checkDigit === parseInt(nhi[6]);
				} else {
					if (isLetter(nhi[6])) { 
						var remainder = sum % 23;  //Get 0-22
						var leftOver = 23 - remainder;
						
						if(leftOver == 0) return false;
						return (alphabetConversionTable[nhi[6]] === leftOver);
					}
				}

				return false;
			}
 			

 			


 			
 			function processPattern(ocrText)
 			{
 				//Take an OCR matched string e.g.
 				/*
 					Page Tasks inbox |
					SVU0053 Ma
					English He

					Fr v5 |

 				*/
 				
 				//Some special-case New Zealand patterns
 				
 				var nzNHIDPatterns = [ "[a-zA-Z][a-zA-Z][a-zA-Z]\\d\\d\\d\\d", 			//Original app setting, for old (pre 2024 format) NHID numbers only
 											"[a-zA-Z][a-zA-Z][a-zA-Z]\\d\\d[a-zA-Z0-9][a-zA-Z0-9]" ];		//New app settings
 				var nznhid = false;
 				if($('#pattern-match').val() == nzNHIDPatterns[0]) {
 						if(confirm("Warning: you are currently scanning for the old New Zealand NHID format (pre-2024). Do you want to change to search both the new and old formats? (Recommended)")) {
 								$('#pattern-match').val(nzNHIDPatterns[1]);
 								app.setPattern(); 
 								$('#pattern-match-opts').val(nzNHIDPatterns[1]).trigger("change");
 								jQuery('#pattern-match-opts option').each(function(i){
									if($(this).val() === nzNHIDPatterns[1]) {
										$(this).prop('selected', true); 
									} 				
								})
 						}
 				}
 				
 				 				
 				//and locate the pattern. For NZ NHIDs we are looking for the 'SVU0058'
 				//Then put the pattern into the input box - or display an error icon.
 				//var regex = /([a-zA-Z][a-zA-Z][a-zA-Z]\d\d\d\d)/g;
 				var regex = new RegExp("(" + $('#pattern-match').val() + ")", "g");
 				var searchResults = ocrText.match(regex);
 				
 				//var searchResults = []; searchResults[0] = "ZXE24NV";		//TESTING, REMOVE
 				if(searchResults) {
 					
 					for(var cnt = 0; cnt< nzNHIDPatterns.length; cnt++) {
 						if($('#pattern-match').val() === nzNHIDPatterns[cnt]) {
 							nznhid = true;
 						}
 					}
 					
 					
 				
 					if(searchResults.length == 1) {
 						//Only one result
 						var finalResult = searchResults[0];					
 						
 					} else {
 						//Multiple results - currently use the 1st
 						var finalResult = searchResults[0];
 					}
 					
 					if(nznhid == true) {
 						finalResult = finalResult.toUpperCase();	//Upper case any letters
 					}
 					
 					//Set the text box
 					$("#id-entered").val(finalResult);
 					
 					//Special case for New Zealand users
 					
 					if(nznhid == true) {
						//An NZ NHID
						if(formatNHINumber(finalResult) == true) {
							//A valid NZ-based NHID
							$("#id-entered").css('backgroundColor', "#0F0");
							setTimeout(function() {
								$("#id-entered").css('backgroundColor', "white");
							}, 2000);
							app.notify("Scanning completed.");	
						} else {
							//Not a valid NHID
							$("#id-entered").css('backgroundColor', "#F00");
							setTimeout(function() {
								$("#id-entered").css('backgroundColor', "white");
							}, 2000);
							app.notify("Scanning completed. Warning: the NHI is not valid.");
						}
					} else {
							app.notify("Scanning completed.");
					}
 					
 				} else {
 					var maxQuoteLen = 100;
 					if(ocrText.length > maxQuoteLen) {
 						var ocrQuoteText = ocrText.substring(0, maxQuoteLen) + "...";
 					} else {
 						var ocrQuoteText = ocrText; 					
					}
 					alert("Sorry no ID was detected in the text below, please try again. Detected: \n\"" + ocrQuoteText + "\"");
 					app.notify("Scanning completed.");
 				}
 				
 				
 			}
			
			// Area to fit image into, in pixels.
			// The image will be proportionally resized to fit within this area.
			var areaWidth = 768, areaHeight = 1024;
			
			
			$('#scan-button').on('change', function(e) {
				if ('' === this.value) { return; }
				var file = e.target.files[0], reader = new FileReader();
				reader.onload = function() {
					var $img = $('<img>', {src:this.result})
					.on('load', function() {
						var srcWidth = this.naturalWidth, srcHeight = this.naturalHeight;
						var ratio = Math.min(areaWidth / srcWidth, areaHeight / srcHeight);
						var width = srcWidth*ratio, height = srcHeight*ratio;
						var canvas = document.querySelector('#standard-cam-canvas');
						canvas.width = width; canvas.height = height;
						var ctx = canvas.getContext('2d');

						if (srcWidth < width && srcHeight < height) {
							// Enlarge the image: no inbetween-steps needed:
							ctx.drawImage(this, 0, 0, width, height);			
						}
						else {
							// Shrink the image: inbetween-steps make it look smooth:
							var oc = document.createElement('canvas');
							var octx = oc.getContext('2d');
							var cur = {
								width: Math.round(srcWidth/2), height: Math.round(srcHeight/2)
							};
							oc.width = cur.width;
							oc.height = cur.height;
							octx.drawImage(this, 0, 0, cur.width, cur.height);

							while (cur.width / 2 > width) {
								octx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, cur.width/2, cur.height/2);
								cur = {
									width: Math.round(cur.width/2), height: Math.round(cur.height/2)
								};
							}
							ctx.filter = "blur(1px)";		//Blur it - particularly useful for removing screen-shot pixel stuff
							ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);
						}
					
					
						var dataUrl = canvas.toDataURL(file.type);
						
						//Show the processing graphic
						$(".fakefile-scan").hide();
						$("#waiting-icon").show();
						
						
						
						
						//OCR scanning
						var scanning = true;
						setTimeout(function() { 
								//Default back to a failure after four seconds
								$("#waiting-icon").hide();
						  		$(".fakefile-scan").show();
						  		
						  		if(scanning == true) {
						  			//Handle an error case
						  			app.notify("Sorry detection is taking too long. You can try again, and try to adjust the distance from the text and/or the lighting, or enter the ID manually.");
						  		}
						 }, 4000);
						 
						 app.notify("Starting scanning...");
						(async () => {
						  const worker = await Tesseract.createWorker('eng', { psm: 8 }, {
						  	workerPath: 'https://frontcdn.atomjump.com/tesseract-worker/node_modules/tesseract.js/dist/worker.min.js',
  							langPath: 'https://frontcdn.atomjump.com/tesseract-languages/',
  							corePath: 'https://frontcdn.atomjump.com/tesseract-worker/node_modules/tesseract.js-core'
						  } );		//Different mode numbers 'psm' options are available here: https://muthu.co/all-tesseract-ocr-options/
						  const ret = await worker.recognize(dataUrl);		//, {	rectangle: { top: 250, left: 150, width: 618, height: 474 } Using a rectangle in the center of the image to clip too much info - although this could be confusing?
						  console.log(ret.data.text);
						  
						  //alert(ret.data.text);
						  scanning = false;
						  processPattern(ret.data.text);
						  
						  await worker.terminate();
						})();
						
					});
				};
				reader.readAsDataURL(file);
				this.value = '';
			});
 			
      
        //Note: this is repeated when you change camera in app.changeCamInterface
		  var input = document.getElementById('mypic'); 	//Was: mypic document.querySelector('input[type=file]');
		  input.onchange = function () {
			var file = input.files[0];
			drawOnCanvas(file, input.id);   
		  };
		 
		 
		  function drawOnCanvas(file, thisId) {
			
			var reader = new FileReader();
			reader.onload = function (e) {
			  
			  //Click the big button and pass in the image data as jpeg
           switch(thisId) {
           	case "mypic": 
           	  var dataURL = e.target.result,		
           	  c = document.querySelector('#standard-cam-canvas'), 
			  	  ctx = c.getContext('2d'),
			  	  img = new Image();
			  
			  	  //This line is not necessary - but would be used if you are drawing the image: img.src = dataURL;
			  
			  
           	  img.onload = function() {
					c.width = img.width;
					c.height = img.height;
					ctx.drawImage(img, 0, 0);
				  };
           	
              //Pass in the user's photo data
              app.bigButton(dataURL);
           	 break;
           	 
           	case "scan-button":
           		//Handled in the jquery onchange event above.
           	break;
           }
			  
			};
		 
			reader.readAsDataURL(file);
			
		  }
		  
		
     		

 

		 
		 

       </script>
       
       

        
        
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/pub/index-2-5-2.js"></script> <!-- Update number for new version to prevent caching -->
        <script type="text/javascript">
         
          
          ons.ready(function() {	   
                     
                     
            //TODO: may need these events after jquery has loaded?
			  	jQuery('#confirm-button').click(function() {
			  		confirmPicture();		  	
			  	});

				jQuery('#retry-button').click(function() {
			  		jQuery(".contentarea").show();	
			  		jQuery("#confirm-photo").hide();  	
			  	});
                       	
	        
	        	//Global databases
			  	var idbSupported = false;		//Whether we can store photos in an indexeddb database within this browser, or not
			  	app.idbSupported = false;
			  	var sendCacheRam = [];			//If we cannot use an indexeddb database within this browser, store photos temporarily in RAM memory
			  	app.medImageSendCacheDb = {};
			 
			 
			  	//document.addEventListener("DOMContentLoaded", function(){
			  	//Set up the indexedDb database
				if("indexedDB" in window) {
					idbSupported = true;
					app.idbSupported = true;
				} 
				
				if(idbSupported == true) {
					//Seem to have support for indexDB
					app.medImageSendCacheDb = indexedDB.open("sendCache");
					
				} else {
					alert("Sorry, additional storage is not supported, and unsent photos will not be remembered when you revisit this app.");
					app.medImageSendCacheDb = {};
					
				}

				app.medImageSendCacheDb.onupgradeneeded = function() {
				  // The database did not previously exist, so create object stores and indexes.
				  app.medImageSendCacheDb = app.medImageSendCacheDb.result;
				  var store = app.medImageSendCacheDb.createObjectStore("images", {keyPath: "imageId"});
			  
				};

				
				app.medImageSendCacheDb.onsuccess = function() {
				  	app.medImageSendCacheDb = this.result;
				  	

				  
				  	// Init code here
        			app.initialize();
				};
		
		
				//End of db setup
		
	        
	    });
	     
	     
	   
	     
	     
	     
        var mySwitch = document.getElementById("always-create-folder");
        
        if(checkPlatform() === "iOS") {
        	//On iOS we are going to register the change when you click the Close button, or some other button.
		} else {
			//Every other browser platform supports this correctly
			mySwitch.addEventListener('change', function() {	
				app.saveIdInput(document.getElementById("always-create-folder").checked);
			});
			
		}
		
		
          
		</script>
		
		
		
          
          
     </ons-page>
     
     
    </ons-navigator>  
    </body>
</html>
