Browse Source

initial upload

Toby Chui 6 years ago
parent
commit
112603ad4d
38 changed files with 6545 additions and 0 deletions
  1. 10 0
      GetMemoMax.php
  2. 1 0
      Memo/0.txt
  3. 1 0
      Memo/1.txt
  4. 1 0
      Memo/2.txt
  5. 33 0
      StickMemo.php
  6. 210 0
      display.php
  7. 38 0
      download.php
  8. 96 0
      file.php
  9. 202 0
      img.php
  10. BIN
      img/Thumbs.db
  11. BIN
      img/cube.png
  12. BIN
      img/noimg.png
  13. 124 0
      index.php
  14. 28 0
      jquery.qrcode.min.js
  15. 279 0
      js/alignpat.js
  16. 111 0
      js/bitmat.js
  17. 203 0
      js/bmparser.js
  18. 117 0
      js/datablock.js
  19. 336 0
      js/databr.js
  20. 207 0
      js/datamask.js
  21. 95 0
      js/decoder.js
  22. 413 0
      js/detector.js
  23. 58 0
      js/errorlevel.js
  24. 651 0
      js/findpat.js
  25. 104 0
      js/formatinf.js
  26. 117 0
      js/gf256.js
  27. 230 0
      js/gf256poly.js
  28. 152 0
      js/grid.js
  29. 455 0
      js/qrcode.js
  30. 178 0
      js/rsdecoder.js
  31. 261 0
      js/version.js
  32. 218 0
      rx.php
  33. 0 0
      tocas.css
  34. 1424 0
      tocas.js
  35. 179 0
      upload.php
  36. BIN
      uploads/Thumbs.db
  37. BIN
      uploads/p1.zip
  38. 13 0
      urlfix.js

+ 10 - 0
GetMemoMax.php

@@ -0,0 +1,10 @@
+<?php
+$max = 0;
+	foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+		if ($fileInfo->isDot()) continue;
+		$current = pathinfo($fileInfo->getFilename())['filename'];
+		if (!is_numeric($current)) continue;
+		if ($current > $max) $max = $current;
+	}
+echo json_encode($max);
+?>

+ 1 - 0
Memo/0.txt

@@ -0,0 +1 @@
+48656c6c6f20576f726c64210a57656c636f6d6520746f2074686520494d5553204c61626f7261746f7279206f6e6c696e6520736572766963657320736974652e0a0a546f2075736520746869732073657276696365732c20796f75206861766520746f206f70656e20746869732075726c20696e2051522d436f646520666f726d20696620796f7520617265207573696e6720736d6172742064657669636573206c696b6520736d6172742070686f6e65206f72207461626c6574732e0a0a4f72206f74686572776973652c20696620796f752077616e7420746f206f70656e2061207370656369616c204d656d6f207769746820676976656e206964206e756d6265722c20706c6561736520757365207468652052582066756e6374696f6e206f6e20746f702e

+ 1 - 0
Memo/1.txt

@@ -0,0 +1 @@
+48656c6c6f20576f726c6421205468697320697320746865206669727374206d6573736167652073656e6420746f20517569636b53656e64206166746572207468652073797374656d2072657365742e

+ 1 - 0
Memo/2.txt

@@ -0,0 +1 @@
+646174613a66696c652f70312e7a6970

+ 33 - 0
StickMemo.php

@@ -0,0 +1,33 @@
+<?php
+$memodir = "Memo/";
+if(isset($_POST['content']) !== False){
+    $content = $_POST['content'];
+	$content = bin2hex($content);
+}
+$max = 0;
+	foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+		if ($fileInfo->isDot()) continue;
+		$current = pathinfo($fileInfo->getFilename())['filename'];
+		if (!is_numeric($current)) continue;
+		if ($current > $max) $max = $current;
+	}
+	
+//Check if the number of files exceed the max
+if ($max > 1000){
+	foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+			$current = pathinfo($fileInfo->getFilename())['filename'];
+			if (!is_numeric($current)) continue;
+			if ((int)$current != 0){
+				unlink('Memo/' . $current . ".txt");
+			}
+	}
+	$max = 0;
+}
+
+$filename = (int)$max + 1;
+$myfile = fopen($memodir . $filename . ".txt", "w") or die("Unable to open file!");
+$txt = $content;
+fwrite($myfile, $txt);
+fclose($myfile);
+echo $filename;
+?>

+ 210 - 0
display.php

@@ -0,0 +1,210 @@
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<head>
+<title>QuickSend</title>
+<link rel="stylesheet" href="tocas.css">
+
+</head>
+<body>
+<div class="ts inverted heading fluid slate" style="background-color:#2c2835;color:white;">
+    <span class="large header">Quick Send System</span>
+    <span class="description">Send data between mobile and laptops.<br> Powered by IMUS Laboratory</span>
+    <div class="ts bottom attached tabbed menu" style="color:white;">
+        <a class="item" href="index.php" style="color:#9d9ca3;">Send</a>
+        <a class="item" href="rx.php" style="color:#9d9ca3;">Receive</a>
+        <a class="item" href="img.php" style="color:#9d9ca3;">Image</a>
+        <a class="item" href="file.php" style="color:#9d9ca3;">Files</a>
+		<a class="active item">Display</a>
+    </div>
+</div>
+
+<div class="ts container">
+<br><br>
+
+<div class="ts stackable grid">
+    <div class="four wide column" align="center">
+	<div id="output"></div>
+	<div class="ts small statistic">
+    <div class="label">QuickSend ID</div>
+    <div class="value" id="sid"><?php
+		if (isset($_GET['id']) !== False){
+			echo '<script>var sid = parseInt("' . $_GET['id'] . '");</script>';
+			echo $_GET['id'];
+			$id = $_GET['id'];
+		}else{
+			//No input ids
+			echo '<script>var sid = parseInt("0");</script>';
+			echo 0;
+			$id = 0;
+		}
+	?></div>
+	</div>
+	</div>
+    <div class="twelve wide column">
+	<div class="ts fluid input" style="height:250px">
+    <?php
+		$memodir = "Memo/";
+		$dataType = "TEXT";
+		if (file_exists($memodir . $id.".txt")){
+			$myfile = fopen($memodir . $id.".txt", "r") or die("Unable to open file!");
+			$content = hex2bin(fread($myfile,filesize($memodir . $id.".txt")));
+			fclose($myfile);
+			$filetrue = true;
+			//Process the different filetype
+			if (strpos($content, "data:image/") !== False && strpos($content, ";base64,") !== False){
+				//This is an image encoded in base64
+				echo "<img class='ts centered image' src='" . $content . "'> ";
+				echo '<a class="ts bottom right attached label" href="'.$content.'" target="_blank">View Raw</a>';
+				echo '</img>';
+				$dataType = "IMAGE";
+			}else if (strpos($content, "data:file/") !== False){
+				$filename = str_replace("data:file/","uploads/",$content);
+				echo '<div class="ts fluid segment">';
+				echo '<div class="ts fluid steps">
+						<div class="step">
+							<div class="content">
+								<div class="title">Click the button below to download your file</div>
+								<div class="description">Please beware that we have the permission to remove your file anytime.</div>
+							</div>
+						</div>
+					</div><br>';
+				echo '<a href="'.$filename.'" class="ts basic fluid button" download>Download</a>';
+				echo '</div>';
+				$dataType = "FILE";
+			
+			}else{
+				echo '<textarea id="textholder" placeholder="Text to be sent via QRcode.">';
+				echo $content;
+				echo '</textarea>';
+				$dataType = "TEXT";
+			}
+		}else{
+			$filetrue = false;
+			echo 'The specified Memo ID cannot be find in the database. Are you sure you entered the correct QuickSend id?';
+			
+		}
+	?>
+	<?php
+		if ($filetrue == true){
+			echo '<script>var file_exists = true;</script>';
+		}else{
+			echo '<script>var file_exists = false;</script>';
+		}
+	?>
+	</div><br><br>
+	<div class="ts container" align="right"><?php
+		if($dataType == "TEXT"){
+			echo '<button class="ts tiny basic button" onclick="action()">Open / Search</button>';
+			echo '<button class="ts tiny basic button" onclick="copy()">Copy to Clipboard</button>';
+		}
+	?>
+	</div>
+	</div>
+</div>
+
+</div>
+
+<div style="position: fixed;
+    z-index: 100; 
+    bottom: 0; 
+    left: 0;
+    width: 100%;
+	background-color:#2c2835;
+	color:white;">
+<div class="ts container">
+<img class="ts tiny right floated image" src="img/cube.png"></img>
+</div>
+<div align="left" class="ts container">
+<br>
+CopyRight IMUS Laboratory 2018, All right reserved.
+</div>
+</div>
+
+<div id="notifybar" class="ts active bottom right snackbar" style="display:none;z-index: 101;">
+    <div class="content" style="z-index: 102;">
+        Your message has been copied into the clipboard.
+    </div>
+</div>
+
+<br><br><br><br>
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
+<script type="text/javascript" src="jquery.qrcode.min.js"></script>
+<script>
+jQuery(function(){
+	if (file_exists == true){
+		jQuery('#output').qrcode("http://imuslab.com/qs/display.php?id=" + sid);
+	}else{
+		jQuery('#output').qrcode("NOT FOUND");
+	}
+})
+function copyToClipboard(elem) {
+	  // create hidden text element, if it doesn't already exist
+    var targetId = "_hiddenCopyText_";
+    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
+    var origSelectionStart, origSelectionEnd;
+    if (isInput) {
+        // can just use the original source element for the selection and copy
+        target = elem;
+        origSelectionStart = elem.selectionStart;
+        origSelectionEnd = elem.selectionEnd;
+    } else {
+        // must use a temporary form element for the selection and copy
+        target = document.getElementById(targetId);
+        if (!target) {
+            var target = document.createElement("textarea");
+            target.style.position = "absolute";
+            target.style.left = "-9999px";
+            target.style.top = "0";
+            target.id = targetId;
+            document.body.appendChild(target);
+        }
+        target.textContent = elem.textContent;
+    }
+    // select the content
+    var currentFocus = document.activeElement;
+    target.focus();
+    target.setSelectionRange(0, target.value.length);
+    
+    // copy the selection
+    var succeed;
+    try {
+    	  succeed = document.execCommand("copy");
+    } catch(e) {
+        succeed = false;
+    }
+    // restore original focus
+    if (currentFocus && typeof currentFocus.focus === "function") {
+        currentFocus.focus();
+    }
+    
+    if (isInput) {
+        // restore prior selection
+        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
+    } else {
+        // clear temporary content
+        target.textContent = "";
+    }
+    return succeed;
+}
+
+function copy(){
+	copyToClipboard(document.getElementById("textholder"));
+	$("#notifybar").fadeIn('slow').delay(3000).fadeOut('slow');
+}
+
+function action(){
+	var content = $('#textholder').val();
+	//alert(content);
+	if (content.substr(0, 4).includes("http") || content.substr(0, 11).includes("data:image/")){
+		//It is a url to be open
+		window.open(content,"_blank");
+	}else{
+		//It is a normal text to be searched
+		content = content.replace(" ","+");
+		window.open("https://www.google.com.hk/?#safe=off&q=" + content,"_blank");
+	}
+}
+
+</script>
+</body>
+</html>

+ 38 - 0
download.php

@@ -0,0 +1,38 @@
+<?php
+//downloading script for QuickSend desktop application
+if (isset($_GET['VB_download']) && $_GET['VB_download'] == "true" && isset($_GET['id']) && $_GET['id'] != ""){
+	$id = $_GET['id'];
+	$memodir = "Memo/";
+		$dataType = "TEXT";
+		if (file_exists($memodir . $id.".txt")){
+			$myfile = fopen($memodir . $id.".txt", "r") or die("Unable to open file!");
+			$content = hex2bin(fread($myfile,filesize($memodir . $id.".txt")));
+			fclose($myfile);
+			$filetrue = true;
+			//Process the different filetype
+			if (strpos($content, "data:image/") !== False && strpos($content, ";base64,") !== False){
+				//This is an image encoded in base64, throw back to client to handle
+				echo "<img src='" .$content . "'></img>";
+			}else if (strpos($content, "data:file/") !== False){
+				$filename = str_replace("data:file/","uploads/",$content);
+				if (file_exists($filename) == true){
+					echo "FILE:" . $filename;
+				}else{
+					echo '410 GONE';
+				}
+				
+			
+			}else{
+				echo "TEXT:" .$content;
+			}
+		}else{
+			$filetrue = false;
+			echo '404 NOTFOUND';
+			
+		}
+}else{
+	echo 'Invalid operation.';
+	exit(0);
+}
+
+?>

+ 96 - 0
file.php

@@ -0,0 +1,96 @@
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<head>
+<title>Quick Send</title>
+<link rel="stylesheet" href="tocas.css">
+<script type="text/javascript" src="urlfix.js"></script>
+</head>
+<body>
+<?php
+	if (isset($_GET['rx']) && $_GET['rx'] != ""){
+		header("Location: display.php?id=" . $_GET['rx']);
+		die();
+	}
+?>
+<div class="ts inverted heading fluid slate" style="background-color:#2c2835;color:white;">
+    <span class="large header">Quick Send System</span>
+    <span class="description">Send data between mobile and laptops.<br> Powered by IMUS Laboratory</span>
+    <div class="ts bottom attached tabbed menu" style="color:white;">
+        <a class="item" href="index.php" style="color:#9d9ca3;">Send</a>
+        <a class="item" href="rx.php" style="color:#9d9ca3;">Receive</a>
+        <a class="item" href="img.php" style="color:#9d9ca3;">Image</a>
+        <a class="active item" href="file.php">Files</a>
+    </div>
+</div>
+
+<div class="ts container">
+<br><br>
+<div class="ts stackable grid">
+    <div class="four wide column" align="center">
+		<div id="output"></div>
+		<div class="ts small statistic">
+			<div class="label">QuickSend ID</div>
+			<div class="value" id="sid"><?php
+			$max = 0;
+			foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+				if ($fileInfo->isDot()) continue;
+				$current = pathinfo($fileInfo->getFilename())['filename'];
+				if (!is_numeric($current)) continue;
+				if ($current > $max) $max = $current;
+			}
+			echo $max+1;
+			?></div>
+		</div>
+	</div>
+    <div class="twelve wide column">
+		<form action="upload.php" method="post" enctype="multipart/form-data">
+			<input class="ts basic fluid button" type="file" name="fileToUpload" id="fileToUpload"><br><br>
+			<input class="ts basic fluid button" type="submit" value="Generate QR-Code" name="submit">
+		</form>
+		<br>
+	</div>
+</div>
+
+<br><br><br><br><br><br>
+<div style="position: fixed;
+    z-index: 100; 
+    bottom: 0; 
+    left: 0;
+    width: 100%;
+	background-color:#2c2835;
+	color:white;">
+<div class="ts container">
+<img class="ts tiny right floated image" src="img/cube.png"></img>
+</div>
+<div align="left" class="ts container">
+<br>
+CopyRight IMUS Laboratory 2018, All right reserved.
+</div>
+</div>
+
+</div>
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
+<script type="text/javascript" src="jquery.qrcode.min.js"></script>
+<script>
+jQuery(function(){
+	jQuery('#output').qrcode("Hello World");
+})
+
+function senddata(){
+	textarea = $('#textholder').val();
+    $.ajax({
+        type: "POST",
+        url: "StickMemo.php",
+        data:{ content: textarea }, 
+        success: function(data){
+            //alert(data);
+			$("#output").empty();
+			jQuery('#output').qrcode("http://imuslab.com/qs/display.php?id=" + data);
+			$("#sid").html(data);
+        }
+    })
+	
+}
+</script>
+</body>
+</html>

+ 202 - 0
img.php

@@ -0,0 +1,202 @@
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<head>
+<title>QuickSend Image</title>
+<link rel="stylesheet" href="tocas.css">
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
+<script type="text/javascript" src="jquery.qrcode.min.js"></script>
+</head>
+
+<body>
+<div class="ts inverted heading fluid slate" style="background-color:#2c2835;color:white;">
+    <span class="large header">Quick Send System</span>
+    <span class="description">Send data between mobile and laptops.<br> Powered by IMUS Laboratory</span>
+    <div class="ts bottom attached tabbed menu" style="color:white;">
+        <a class="item" href="index.php" style="color:#9d9ca3;">Send</a>
+        <a class="item" href="rx.php" style="color:#9d9ca3;">Receive</a>
+        <a class="active item" href="img.php">Image</a>
+        <a class="item" href="file.php" style="color:#9d9ca3;">Files</a>
+    </div>
+</div>
+<br><br>
+<div class="ts container">
+<div class="ts stackable centered grid">
+	 <div class="six wide column" align="center" style="overflow:hidden;">
+		<div class="ts fluid steps">
+			<div class="step">
+				<div class="content">
+					<div class="title">Step 1</div>
+					<div class="description">Select your image to send</div>
+				</div>
+			</div>
+		</div>
+	 
+		<input class="ts button" id="inp" type='file' style="width:100%;"><br>
+		<button class="ts basic fluid negative button" onclick="clearselection()">Clear</button>
+		<div class="ts narrow container" style="">
+			<p id="b64"></p>
+			<img id="img" src='img/noimg.png' height="150">
+		</div>
+		
+	 </div>
+	 <div class="five wide column" align="center">
+	 <div class="ts fluid steps">
+			<div class="step">
+				<div class="content">
+					<div class="title">Step 2</div>
+					<div class="description">Generate the sender QR Code</div>
+				</div>
+			</div>
+		</div>
+	 
+		<div class="ts inverted segment">
+			<div class="ts tiny inverted statistics">
+				<div class="statistic">
+					<div class="value" id="width">N/A</div>
+					<div class="label">Image Width</div>
+				</div>
+				<div class="statistic">
+					<div class="value" id="height">N/A</div>
+					<div class="label">Image Height</div>
+				</div>
+				<div class="statistic">
+					<div class="value" id="size">N/A</div>
+					<div class="label">Storage Size</div>
+				</div>
+			</div>
+		</div>
+		<button class="ts basic fluid button" onclick="senddata()">Generate QR Code</button>
+	 
+	 </div>
+	 <div class="five wide column" align="center">
+		<div class="ts fluid steps">
+			<div class="step">
+				<div class="content">
+					<div class="title">Step 3</div>
+					<div class="description">Use the QR Code to receive the image.</div>
+				</div>
+			</div>
+		</div>
+		
+		<div id="output"></div>
+		<div class="ts small statistic">
+		<div class="label">QuickSend ID</div>
+		<div class="value" id="sid"><?php
+		$max = 0;
+		foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+			if ($fileInfo->isDot()) continue;
+			$current = pathinfo($fileInfo->getFilename())['filename'];
+			if (!is_numeric($current)) continue;
+			if ($current > $max) $max = $current;
+		}
+		echo $max+1;
+		?></div>
+		</div>
+	 </div>
+
+</div>
+<div class="ts fluid input" style="display:none;">
+    <div class="ts input" style="width: 100%;height:250px">
+    <textarea id="base64" placeholder="Encoded Base64 Content..."></textarea>
+	</div>
+</div>
+<div class="ts segment">
+	<div class="ts grid" align="center">
+		<div class="six wide column">
+		
+		</div>
+		<div class="ten wide column">
+		
+		
+		
+		</div>
+	</div>
+</div>
+<br><br><br><br><br><br>
+
+
+<div style="position: fixed;
+    z-index: 100; 
+    bottom: 0; 
+    left: 0;
+    width: 100%;
+	background-color:#2c2835;
+	color:white;">
+<div class="ts container">
+<img class="ts tiny right floated image" src="img/cube.png"></img>
+</div>
+<div align="left" class="ts container">
+<br>
+CopyRight IMUS Laboratory 2018, All right reserved.
+</div>
+</div>
+<script>
+
+function clearselection(){
+	$("#base64").val('');
+	document.getElementById("img").src       = 'img/noimg.png';
+	$("#inp").val("");
+	$("#width").text("Null");
+	$("#height").text("Null");
+	$("#size").text("Null");
+}
+
+function bytesToSize(bytes) {
+   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
+   if (bytes == 0) return '0 Byte';
+   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
+   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
+};
+
+function readFile() {
+  
+  if (this.files && this.files[0]) {
+    
+    var FR= new FileReader();
+    
+    FR.addEventListener("load", function(e) {
+      document.getElementById("img").src       = e.target.result;
+      $("#base64").val(e.target.result);
+	  var i = new Image();
+	  i.src = document.getElementById("img").src;
+	  i.onload = function(){
+	  console.log(i.width);
+	  $("#width").text(i.width + "px");
+	  console.log(i.height);
+	  $("#height").text(i.height+ "px");
+	  $("#size").text(bytesToSize(encodeURI(e.target.result).split(/%..|./).length - 1));
+	  }
+    }); 
+    
+    FR.readAsDataURL( this.files[0] );
+  }
+  
+}
+
+jQuery(function(){
+	jQuery('#output').qrcode("Hello World");
+})
+
+function senddata(){
+	textarea = $('#base64').val();
+	if (textarea != ""){
+    $.ajax({
+        type: "POST",
+        url: "StickMemo.php",
+        data:{ content: textarea }, 
+        success: function(data){
+            //alert(data);
+			$("#output").empty();
+			jQuery('#output').qrcode("http://imuslab.com/qs/display.php?id=" + data);
+			$("#sid").html(data);
+        }
+    })
+	
+
+	}}
+
+
+document.getElementById("inp").addEventListener("change", readFile);
+</script>
+</body>
+</html>

BIN
img/Thumbs.db


BIN
img/cube.png


BIN
img/noimg.png


+ 124 - 0
index.php

@@ -0,0 +1,124 @@
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<head>
+<title>Quick Send</title>
+<link rel="stylesheet" href="tocas.css">
+<script type="text/javascript" src="urlfix.js"></script>
+</head>
+<body>
+<?php
+	if (isset($_GET['rx']) && $_GET['rx'] != ""){
+		header("Location: display.php?id=" . $_GET['rx']);
+		die();
+	}
+?>
+<div class="ts inverted heading fluid slate" style="background-color:#2c2835;color:white;">
+    <span class="large header">Quick Send System</span>
+    <span class="description">Send data between mobile and laptops.<br> Powered by IMUS Laboratory</span>
+    <div class="ts bottom attached tabbed menu" style="color:white;">
+        <a class="active item" href="index.php">Send</a>
+        <a class="item" href="rx.php" style="color:#9d9ca3;">Receive</a>
+        <a class="item" href="img.php" style="color:#9d9ca3;">Image</a>
+        <a class="item" href="file.php" style="color:#9d9ca3;">Files</a>
+    </div>
+</div>
+
+<div class="ts container">
+<br><br>
+<div class="ts stackable grid">
+    <div class="four wide column" align="center">
+		<div id="output"></div>
+		<div class="ts small statistic">
+			<div class="label">QuickSend ID</div>
+			<div class="value" id="sid"><?php
+			$max = 0;
+			foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+				if ($fileInfo->isDot()) continue;
+				$current = pathinfo($fileInfo->getFilename())['filename'];
+				if (!is_numeric($current)) continue;
+				if ($current > $max) $max = $current;
+			}
+			echo $max+1;
+			?></div>
+		</div>
+	</div>
+    <div class="twelve wide column">
+		<div class="ts fluid input" style="height:250px">
+		<textarea id="textholder" placeholder="Text to be sent via QRcode."></textarea>
+		</div><br><br>
+		<div class="ts container" align="right">
+		<button class="ts tiny basic button" onclick="senddata()">Generate QR-Code</button>
+		</div>
+	</div>
+</div>
+<div class="ts horizontal divider">Latest QuickSend code</div>
+<div class="ts stackable fluid horizontal list">
+			<?php
+			$max = 0;
+			foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+				if ($fileInfo->isDot()) continue;
+				$current = pathinfo($fileInfo->getFilename())['filename'];
+				if (!is_numeric($current)) continue;
+				if ($current > $max) $max = $current;
+			}
+			$number = 10;
+			if ($max < 10){
+				$number = $max;
+			}
+			for( $i = 0; $i <= $number; $i++){
+				echo "<div class='ts label'><a class='item' onCLick='rx(" . ($max - $i) . ");'>QSCODE#" . ($max - $i) . "</a></div>";
+			}
+			?>
+</div>
+<br><br><br><br><br><br>
+<div style="position: fixed;
+    z-index: 100; 
+    bottom: 0; 
+    left: 0;
+    width: 100%;
+	background-color:#2c2835;
+	color:white;">
+<div class="ts container">
+<img class="ts tiny right floated image" src="img/cube.png"></img>
+</div>
+<div align="left" class="ts container">
+<br>
+CopyRight IMUS Laboratory 2018, All right reserved.
+</div>
+</div>
+
+</div>
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
+<script type="text/javascript" src="jquery.qrcode.min.js"></script>
+<script>
+jQuery(function(){
+	jQuery('#output').qrcode("Hello World");
+})
+
+function senddata(){
+	textarea = $('#textholder').val();
+    $.ajax({
+        type: "POST",
+        url: "StickMemo.php",
+        data:{ content: textarea }, 
+        success: function(data){
+            //alert(data);
+			$("#output").empty();
+			jQuery('#output').qrcode("http://imuslab.com/qs/display.php?id=" + data);
+			$("#sid").html(data);
+        }
+    })
+	
+}
+
+$(document).ready(function(){
+	
+});
+
+function rx(id){
+	top.location.href = "http://imuslab.com/qs/display.php?id=" + id;
+}
+
+</script>
+</body>
+</html>

+ 28 - 0
jquery.qrcode.min.js

@@ -0,0 +1,28 @@
+(function(r){r.fn.qrcode=function(h){var s;function u(a){this.mode=s;this.data=a}function o(a,c){this.typeNumber=a;this.errorCorrectLevel=c;this.modules=null;this.moduleCount=0;this.dataCache=null;this.dataList=[]}function q(a,c){if(void 0==a.length)throw Error(a.length+"/"+c);for(var d=0;d<a.length&&0==a[d];)d++;this.num=Array(a.length-d+c);for(var b=0;b<a.length-d;b++)this.num[b]=a[b+d]}function p(a,c){this.totalCount=a;this.dataCount=c}function t(){this.buffer=[];this.length=0}u.prototype={getLength:function(){return this.data.length},
+write:function(a){for(var c=0;c<this.data.length;c++)a.put(this.data.charCodeAt(c),8)}};o.prototype={addData:function(a){this.dataList.push(new u(a));this.dataCache=null},isDark:function(a,c){if(0>a||this.moduleCount<=a||0>c||this.moduleCount<=c)throw Error(a+","+c);return this.modules[a][c]},getModuleCount:function(){return this.moduleCount},make:function(){if(1>this.typeNumber){for(var a=1,a=1;40>a;a++){for(var c=p.getRSBlocks(a,this.errorCorrectLevel),d=new t,b=0,e=0;e<c.length;e++)b+=c[e].dataCount;
+for(e=0;e<this.dataList.length;e++)c=this.dataList[e],d.put(c.mode,4),d.put(c.getLength(),j.getLengthInBits(c.mode,a)),c.write(d);if(d.getLengthInBits()<=8*b)break}this.typeNumber=a}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17;this.modules=Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=Array(this.moduleCount);for(var b=0;b<this.moduleCount;b++)this.modules[d][b]=null}this.setupPositionProbePattern(0,0);this.setupPositionProbePattern(this.moduleCount-
+7,0);this.setupPositionProbePattern(0,this.moduleCount-7);this.setupPositionAdjustPattern();this.setupTimingPattern();this.setupTypeInfo(a,c);7<=this.typeNumber&&this.setupTypeNumber(a);null==this.dataCache&&(this.dataCache=o.createData(this.typeNumber,this.errorCorrectLevel,this.dataList));this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,c){for(var d=-1;7>=d;d++)if(!(-1>=a+d||this.moduleCount<=a+d))for(var b=-1;7>=b;b++)-1>=c+b||this.moduleCount<=c+b||(this.modules[a+d][c+b]=
+0<=d&&6>=d&&(0==b||6==b)||0<=b&&6>=b&&(0==d||6==d)||2<=d&&4>=d&&2<=b&&4>=b?!0:!1)},getBestMaskPattern:function(){for(var a=0,c=0,d=0;8>d;d++){this.makeImpl(!0,d);var b=j.getLostPoint(this);if(0==d||a>b)a=b,c=d}return c},createMovieClip:function(a,c,d){a=a.createEmptyMovieClip(c,d);this.make();for(c=0;c<this.modules.length;c++)for(var d=1*c,b=0;b<this.modules[c].length;b++){var e=1*b;this.modules[c][b]&&(a.beginFill(0,100),a.moveTo(e,d),a.lineTo(e+1,d),a.lineTo(e+1,d+1),a.lineTo(e,d+1),a.endFill())}return a},
+setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(a=8;a<this.moduleCount-8;a++)null==this.modules[6][a]&&(this.modules[6][a]=0==a%2)},setupPositionAdjustPattern:function(){for(var a=j.getPatternPosition(this.typeNumber),c=0;c<a.length;c++)for(var d=0;d<a.length;d++){var b=a[c],e=a[d];if(null==this.modules[b][e])for(var f=-2;2>=f;f++)for(var i=-2;2>=i;i++)this.modules[b+f][e+i]=-2==f||2==f||-2==i||2==i||0==f&&0==i?!0:!1}},setupTypeNumber:function(a){for(var c=
+j.getBCHTypeNumber(this.typeNumber),d=0;18>d;d++){var b=!a&&1==(c>>d&1);this.modules[Math.floor(d/3)][d%3+this.moduleCount-8-3]=b}for(d=0;18>d;d++)b=!a&&1==(c>>d&1),this.modules[d%3+this.moduleCount-8-3][Math.floor(d/3)]=b},setupTypeInfo:function(a,c){for(var d=j.getBCHTypeInfo(this.errorCorrectLevel<<3|c),b=0;15>b;b++){var e=!a&&1==(d>>b&1);6>b?this.modules[b][8]=e:8>b?this.modules[b+1][8]=e:this.modules[this.moduleCount-15+b][8]=e}for(b=0;15>b;b++)e=!a&&1==(d>>b&1),8>b?this.modules[8][this.moduleCount-
+b-1]=e:9>b?this.modules[8][15-b-1+1]=e:this.modules[8][15-b-1]=e;this.modules[this.moduleCount-8][8]=!a},mapData:function(a,c){for(var d=-1,b=this.moduleCount-1,e=7,f=0,i=this.moduleCount-1;0<i;i-=2)for(6==i&&i--;;){for(var g=0;2>g;g++)if(null==this.modules[b][i-g]){var n=!1;f<a.length&&(n=1==(a[f]>>>e&1));j.getMask(c,b,i-g)&&(n=!n);this.modules[b][i-g]=n;e--; -1==e&&(f++,e=7)}b+=d;if(0>b||this.moduleCount<=b){b-=d;d=-d;break}}}};o.PAD0=236;o.PAD1=17;o.createData=function(a,c,d){for(var c=p.getRSBlocks(a,
+c),b=new t,e=0;e<d.length;e++){var f=d[e];b.put(f.mode,4);b.put(f.getLength(),j.getLengthInBits(f.mode,a));f.write(b)}for(e=a=0;e<c.length;e++)a+=c[e].dataCount;if(b.getLengthInBits()>8*a)throw Error("code length overflow. ("+b.getLengthInBits()+">"+8*a+")");for(b.getLengthInBits()+4<=8*a&&b.put(0,4);0!=b.getLengthInBits()%8;)b.putBit(!1);for(;!(b.getLengthInBits()>=8*a);){b.put(o.PAD0,8);if(b.getLengthInBits()>=8*a)break;b.put(o.PAD1,8)}return o.createBytes(b,c)};o.createBytes=function(a,c){for(var d=
+0,b=0,e=0,f=Array(c.length),i=Array(c.length),g=0;g<c.length;g++){var n=c[g].dataCount,h=c[g].totalCount-n,b=Math.max(b,n),e=Math.max(e,h);f[g]=Array(n);for(var k=0;k<f[g].length;k++)f[g][k]=255&a.buffer[k+d];d+=n;k=j.getErrorCorrectPolynomial(h);n=(new q(f[g],k.getLength()-1)).mod(k);i[g]=Array(k.getLength()-1);for(k=0;k<i[g].length;k++)h=k+n.getLength()-i[g].length,i[g][k]=0<=h?n.get(h):0}for(k=g=0;k<c.length;k++)g+=c[k].totalCount;d=Array(g);for(k=n=0;k<b;k++)for(g=0;g<c.length;g++)k<f[g].length&&
+(d[n++]=f[g][k]);for(k=0;k<e;k++)for(g=0;g<c.length;g++)k<i[g].length&&(d[n++]=i[g][k]);return d};s=4;for(var j={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,
+78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var c=a<<10;0<=j.getBCHDigit(c)-j.getBCHDigit(j.G15);)c^=j.G15<<j.getBCHDigit(c)-j.getBCHDigit(j.G15);return(a<<10|c)^j.G15_MASK},getBCHTypeNumber:function(a){for(var c=a<<12;0<=j.getBCHDigit(c)-
+j.getBCHDigit(j.G18);)c^=j.G18<<j.getBCHDigit(c)-j.getBCHDigit(j.G18);return a<<12|c},getBCHDigit:function(a){for(var c=0;0!=a;)c++,a>>>=1;return c},getPatternPosition:function(a){return j.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,c,d){switch(a){case 0:return 0==(c+d)%2;case 1:return 0==c%2;case 2:return 0==d%3;case 3:return 0==(c+d)%3;case 4:return 0==(Math.floor(c/2)+Math.floor(d/3))%2;case 5:return 0==c*d%2+c*d%3;case 6:return 0==(c*d%2+c*d%3)%2;case 7:return 0==(c*d%3+(c+d)%2)%2;default:throw Error("bad maskPattern:"+
+a);}},getErrorCorrectPolynomial:function(a){for(var c=new q([1],0),d=0;d<a;d++)c=c.multiply(new q([1,l.gexp(d)],0));return c},getLengthInBits:function(a,c){if(1<=c&&10>c)switch(a){case 1:return 10;case 2:return 9;case s:return 8;case 8:return 8;default:throw Error("mode:"+a);}else if(27>c)switch(a){case 1:return 12;case 2:return 11;case s:return 16;case 8:return 10;default:throw Error("mode:"+a);}else if(41>c)switch(a){case 1:return 14;case 2:return 13;case s:return 16;case 8:return 12;default:throw Error("mode:"+
+a);}else throw Error("type:"+c);},getLostPoint:function(a){for(var c=a.getModuleCount(),d=0,b=0;b<c;b++)for(var e=0;e<c;e++){for(var f=0,i=a.isDark(b,e),g=-1;1>=g;g++)if(!(0>b+g||c<=b+g))for(var h=-1;1>=h;h++)0>e+h||c<=e+h||0==g&&0==h||i==a.isDark(b+g,e+h)&&f++;5<f&&(d+=3+f-5)}for(b=0;b<c-1;b++)for(e=0;e<c-1;e++)if(f=0,a.isDark(b,e)&&f++,a.isDark(b+1,e)&&f++,a.isDark(b,e+1)&&f++,a.isDark(b+1,e+1)&&f++,0==f||4==f)d+=3;for(b=0;b<c;b++)for(e=0;e<c-6;e++)a.isDark(b,e)&&!a.isDark(b,e+1)&&a.isDark(b,e+
+2)&&a.isDark(b,e+3)&&a.isDark(b,e+4)&&!a.isDark(b,e+5)&&a.isDark(b,e+6)&&(d+=40);for(e=0;e<c;e++)for(b=0;b<c-6;b++)a.isDark(b,e)&&!a.isDark(b+1,e)&&a.isDark(b+2,e)&&a.isDark(b+3,e)&&a.isDark(b+4,e)&&!a.isDark(b+5,e)&&a.isDark(b+6,e)&&(d+=40);for(e=f=0;e<c;e++)for(b=0;b<c;b++)a.isDark(b,e)&&f++;a=Math.abs(100*f/c/c-50)/5;return d+10*a}},l={glog:function(a){if(1>a)throw Error("glog("+a+")");return l.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;256<=a;)a-=255;return l.EXP_TABLE[a]},EXP_TABLE:Array(256),
+LOG_TABLE:Array(256)},m=0;8>m;m++)l.EXP_TABLE[m]=1<<m;for(m=8;256>m;m++)l.EXP_TABLE[m]=l.EXP_TABLE[m-4]^l.EXP_TABLE[m-5]^l.EXP_TABLE[m-6]^l.EXP_TABLE[m-8];for(m=0;255>m;m++)l.LOG_TABLE[l.EXP_TABLE[m]]=m;q.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var c=Array(this.getLength()+a.getLength()-1),d=0;d<this.getLength();d++)for(var b=0;b<a.getLength();b++)c[d+b]^=l.gexp(l.glog(this.get(d))+l.glog(a.get(b)));return new q(c,0)},mod:function(a){if(0>
+this.getLength()-a.getLength())return this;for(var c=l.glog(this.get(0))-l.glog(a.get(0)),d=Array(this.getLength()),b=0;b<this.getLength();b++)d[b]=this.get(b);for(b=0;b<a.getLength();b++)d[b]^=l.gexp(l.glog(a.get(b))+c);return(new q(d,0)).mod(a)}};p.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],
+[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,
+116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,
+43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,
+3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,
+55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,
+45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];p.getRSBlocks=function(a,c){var d=p.getRsBlockTable(a,c);if(void 0==d)throw Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+c);for(var b=d.length/3,e=[],f=0;f<b;f++)for(var h=d[3*f+0],g=d[3*f+1],j=d[3*f+2],l=0;l<h;l++)e.push(new p(g,j));return e};p.getRsBlockTable=function(a,c){switch(c){case 1:return p.RS_BLOCK_TABLE[4*(a-1)+0];case 0:return p.RS_BLOCK_TABLE[4*(a-1)+1];case 3:return p.RS_BLOCK_TABLE[4*
+(a-1)+2];case 2:return p.RS_BLOCK_TABLE[4*(a-1)+3]}};t.prototype={get:function(a){return 1==(this.buffer[Math.floor(a/8)]>>>7-a%8&1)},put:function(a,c){for(var d=0;d<c;d++)this.putBit(1==(a>>>c-d-1&1))},getLengthInBits:function(){return this.length},putBit:function(a){var c=Math.floor(this.length/8);this.buffer.length<=c&&this.buffer.push(0);a&&(this.buffer[c]|=128>>>this.length%8);this.length++}};"string"===typeof h&&(h={text:h});h=r.extend({},{render:"canvas",width:256,height:256,typeNumber:-1,
+correctLevel:2,background:"#ffffff",foreground:"#000000"},h);return this.each(function(){var a;if("canvas"==h.render){a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();var c=document.createElement("canvas");c.width=h.width;c.height=h.height;for(var d=c.getContext("2d"),b=h.width/a.getModuleCount(),e=h.height/a.getModuleCount(),f=0;f<a.getModuleCount();f++)for(var i=0;i<a.getModuleCount();i++){d.fillStyle=a.isDark(f,i)?h.foreground:h.background;var g=Math.ceil((i+1)*b)-Math.floor(i*b),
+j=Math.ceil((f+1)*b)-Math.floor(f*b);d.fillRect(Math.round(i*b),Math.round(f*e),g,j)}}else{a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();c=r("<table></table>").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e<a.getModuleCount();e++){f=r("<tr></tr>").css("height",b+"px").appendTo(c);for(i=0;i<a.getModuleCount();i++)r("<td></td>").css("width",
+d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;jQuery(a).appendTo(this)})}})(jQuery);

+ 279 - 0
js/alignpat.js

@@ -0,0 +1,279 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function AlignmentPattern(posX, posY,  estimatedModuleSize)
+{
+	this.x=posX;
+	this.y=posY;
+	this.count = 1;
+	this.estimatedModuleSize = estimatedModuleSize;
+	
+	this.__defineGetter__("EstimatedModuleSize", function()
+	{
+		return this.estimatedModuleSize;
+	}); 
+	this.__defineGetter__("Count", function()
+	{
+		return this.count;
+	});
+	this.__defineGetter__("X", function()
+	{
+		return Math.floor(this.x);
+	});
+	this.__defineGetter__("Y", function()
+	{
+		return Math.floor(this.y);
+	});
+	this.incrementCount = function()
+	{
+		this.count++;
+	}
+	this.aboutEquals=function( moduleSize,  i,  j)
+		{
+			if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize)
+			{
+				var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
+				return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0;
+			}
+			return false;
+		}
+	
+}
+
+function AlignmentPatternFinder( image,  startX,  startY,  width,  height,  moduleSize,  resultPointCallback)
+{
+	this.image = image;
+	this.possibleCenters = new Array();
+	this.startX = startX;
+	this.startY = startY;
+	this.width = width;
+	this.height = height;
+	this.moduleSize = moduleSize;
+	this.crossCheckStateCount = new Array(0,0,0);
+	this.resultPointCallback = resultPointCallback;
+	
+	this.centerFromEnd=function(stateCount,  end)
+		{
+			return  (end - stateCount[2]) - stateCount[1] / 2.0;
+		}
+	this.foundPatternCross = function(stateCount)
+		{
+			var moduleSize = this.moduleSize;
+			var maxVariance = moduleSize / 2.0;
+			for (var i = 0; i < 3; i++)
+			{
+				if (Math.abs(moduleSize - stateCount[i]) >= maxVariance)
+				{
+					return false;
+				}
+			}
+			return true;
+		}
+
+	this.crossCheckVertical=function( startI,  centerJ,  maxCount,  originalStateCountTotal)
+		{
+			var image = this.image;
+			
+			var maxI = qrcode.height;
+			var stateCount = this.crossCheckStateCount;
+			stateCount[0] = 0;
+			stateCount[1] = 0;
+			stateCount[2] = 0;
+			
+			// Start counting up from center
+			var i = startI;
+			while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount)
+			{
+				stateCount[1]++;
+				i--;
+			}
+			// If already too many modules in this state or ran off the edge:
+			if (i < 0 || stateCount[1] > maxCount)
+			{
+				return NaN;
+			}
+			while (i >= 0 && !image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount)
+			{
+				stateCount[0]++;
+				i--;
+			}
+			if (stateCount[0] > maxCount)
+			{
+				return NaN;
+			}
+			
+			// Now also count down from center
+			i = startI + 1;
+			while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount)
+			{
+				stateCount[1]++;
+				i++;
+			}
+			if (i == maxI || stateCount[1] > maxCount)
+			{
+				return NaN;
+			}
+			while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[2] <= maxCount)
+			{
+				stateCount[2]++;
+				i++;
+			}
+			if (stateCount[2] > maxCount)
+			{
+				return NaN;
+			}
+			
+			var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
+			if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
+			{
+				return NaN;
+			}
+			
+			return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN;
+		}
+		
+	this.handlePossibleCenter=function( stateCount,  i,  j)
+		{
+			var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
+			var centerJ = this.centerFromEnd(stateCount, j);
+			var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal);
+			if (!isNaN(centerI))
+			{
+				var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0;
+				var max = this.possibleCenters.length;
+				for (var index = 0; index < max; index++)
+				{
+					var center =  this.possibleCenters[index];
+					// Look for about the same center and module size:
+					if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
+					{
+						return new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
+					}
+				}
+				// Hadn't found this before; save it
+				var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
+				this.possibleCenters.push(point);
+				if (this.resultPointCallback != null)
+				{
+					this.resultPointCallback.foundPossibleResultPoint(point);
+				}
+			}
+			return null;
+		}
+		
+	this.find = function()
+	{
+			var startX = this.startX;
+			var height = this.height;
+			var maxJ = startX + width;
+			var middleI = startY + (height >> 1);
+			// We are looking for black/white/black modules in 1:1:1 ratio;
+			// this tracks the number of black/white/black modules seen so far
+			var stateCount = new Array(0,0,0);
+			for (var iGen = 0; iGen < height; iGen++)
+			{
+				// Search from middle outwards
+				var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1));
+				stateCount[0] = 0;
+				stateCount[1] = 0;
+				stateCount[2] = 0;
+				var j = startX;
+				// Burn off leading white pixels before anything else; if we start in the middle of
+				// a white run, it doesn't make sense to count its length, since we don't know if the
+				// white run continued to the left of the start point
+				while (j < maxJ && !image[j + qrcode.width* i])
+				{
+					j++;
+				}
+				var currentState = 0;
+				while (j < maxJ)
+				{
+					if (image[j + i*qrcode.width])
+					{
+						// Black pixel
+						if (currentState == 1)
+						{
+							// Counting black pixels
+							stateCount[currentState]++;
+						}
+						else
+						{
+							// Counting white pixels
+							if (currentState == 2)
+							{
+								// A winner?
+								if (this.foundPatternCross(stateCount))
+								{
+									// Yes
+									var confirmed = this.handlePossibleCenter(stateCount, i, j);
+									if (confirmed != null)
+									{
+										return confirmed;
+									}
+								}
+								stateCount[0] = stateCount[2];
+								stateCount[1] = 1;
+								stateCount[2] = 0;
+								currentState = 1;
+							}
+							else
+							{
+								stateCount[++currentState]++;
+							}
+						}
+					}
+					else
+					{
+						// White pixel
+						if (currentState == 1)
+						{
+							// Counting black pixels
+							currentState++;
+						}
+						stateCount[currentState]++;
+					}
+					j++;
+				}
+				if (this.foundPatternCross(stateCount))
+				{
+					var confirmed = this.handlePossibleCenter(stateCount, i, maxJ);
+					if (confirmed != null)
+					{
+						return confirmed;
+					}
+				}
+			}
+			
+			// Hmm, nothing we saw was observed and confirmed twice. If we had
+			// any guess at all, return it.
+			if (!(this.possibleCenters.length == 0))
+			{
+				return  this.possibleCenters[0];
+			}
+			
+			throw "Couldn't find enough alignment patterns";
+		}
+	
+}

+ 111 - 0
js/bitmat.js

@@ -0,0 +1,111 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function BitMatrix( width,  height)
+{
+	if(!height)
+		height=width;
+	if (width < 1 || height < 1)
+	{
+		throw "Both dimensions must be greater than 0";
+	}
+	this.width = width;
+	this.height = height;
+	var rowSize = width >> 5;
+	if ((width & 0x1f) != 0)
+	{
+		rowSize++;
+	}
+	this.rowSize = rowSize;
+	this.bits = new Array(rowSize * height);
+	for(var i=0;i<this.bits.length;i++)
+		this.bits[i]=0;
+	
+	this.__defineGetter__("Width", function()
+	{
+		return this.width;
+	});
+	this.__defineGetter__("Height", function()
+	{
+		return this.height;
+	});
+	this.__defineGetter__("Dimension", function()
+	{
+		if (this.width != this.height)
+		{
+			throw "Can't call getDimension() on a non-square matrix";
+		}
+		return this.width;
+	});
+	
+	this.get_Renamed=function( x,  y)
+		{
+			var offset = y * this.rowSize + (x >> 5);
+			return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0;
+		}
+	this.set_Renamed=function( x,  y)
+		{
+			var offset = y * this.rowSize + (x >> 5);
+			this.bits[offset] |= 1 << (x & 0x1f);
+		}
+	this.flip=function( x,  y)
+		{
+			var offset = y * this.rowSize + (x >> 5);
+			this.bits[offset] ^= 1 << (x & 0x1f);
+		}
+	this.clear=function()
+		{
+			var max = this.bits.length;
+			for (var i = 0; i < max; i++)
+			{
+				this.bits[i] = 0;
+			}
+		}
+	this.setRegion=function( left,  top,  width,  height)
+		{
+			if (top < 0 || left < 0)
+			{
+				throw "Left and top must be nonnegative";
+			}
+			if (height < 1 || width < 1)
+			{
+				throw "Height and width must be at least 1";
+			}
+			var right = left + width;
+			var bottom = top + height;
+			if (bottom > this.height || right > this.width)
+			{
+				throw "The region must fit inside the matrix";
+			}
+			for (var y = top; y < bottom; y++)
+			{
+				var offset = y * this.rowSize;
+				for (var x = left; x < right; x++)
+				{
+					this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f);
+				}
+			}
+		}
+}

+ 203 - 0
js/bmparser.js

@@ -0,0 +1,203 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function BitMatrixParser(bitMatrix)
+{
+	var dimension = bitMatrix.Dimension;
+	if (dimension < 21 || (dimension & 0x03) != 1)
+	{
+		throw "Error BitMatrixParser";
+	}
+	this.bitMatrix = bitMatrix;
+	this.parsedVersion = null;
+	this.parsedFormatInfo = null;
+	
+	this.copyBit=function( i,  j,  versionBits)
+	{
+		return this.bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1;
+	}
+	
+	this.readFormatInformation=function()
+	{
+			if (this.parsedFormatInfo != null)
+			{
+				return this.parsedFormatInfo;
+			}
+			
+			// Read top-left format info bits
+			var formatInfoBits = 0;
+			for (var i = 0; i < 6; i++)
+			{
+				formatInfoBits = this.copyBit(i, 8, formatInfoBits);
+			}
+			// .. and skip a bit in the timing pattern ...
+			formatInfoBits = this.copyBit(7, 8, formatInfoBits);
+			formatInfoBits = this.copyBit(8, 8, formatInfoBits);
+			formatInfoBits = this.copyBit(8, 7, formatInfoBits);
+			// .. and skip a bit in the timing pattern ...
+			for (var j = 5; j >= 0; j--)
+			{
+				formatInfoBits = this.copyBit(8, j, formatInfoBits);
+			}
+			
+			this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits);
+			if (this.parsedFormatInfo != null)
+			{
+				return this.parsedFormatInfo;
+			}
+			
+			// Hmm, failed. Try the top-right/bottom-left pattern
+			var dimension = this.bitMatrix.Dimension;
+			formatInfoBits = 0;
+			var iMin = dimension - 8;
+			for (var i = dimension - 1; i >= iMin; i--)
+			{
+				formatInfoBits = this.copyBit(i, 8, formatInfoBits);
+			}
+			for (var j = dimension - 7; j < dimension; j++)
+			{
+				formatInfoBits = this.copyBit(8, j, formatInfoBits);
+			}
+			
+			this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits);
+			if (this.parsedFormatInfo != null)
+			{
+				return this.parsedFormatInfo;
+			}
+			throw "Error readFormatInformation";	
+	}
+	this.readVersion=function()
+		{
+			
+			if (this.parsedVersion != null)
+			{
+				return this.parsedVersion;
+			}
+			
+			var dimension = this.bitMatrix.Dimension;
+			
+			var provisionalVersion = (dimension - 17) >> 2;
+			if (provisionalVersion <= 6)
+			{
+				return Version.getVersionForNumber(provisionalVersion);
+			}
+			
+			// Read top-right version info: 3 wide by 6 tall
+			var versionBits = 0;
+			var ijMin = dimension - 11;
+			for (var j = 5; j >= 0; j--)
+			{
+				for (var i = dimension - 9; i >= ijMin; i--)
+				{
+					versionBits = this.copyBit(i, j, versionBits);
+				}
+			}
+			
+			this.parsedVersion = Version.decodeVersionInformation(versionBits);
+			if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension)
+			{
+				return this.parsedVersion;
+			}
+			
+			// Hmm, failed. Try bottom left: 6 wide by 3 tall
+			versionBits = 0;
+			for (var i = 5; i >= 0; i--)
+			{
+				for (var j = dimension - 9; j >= ijMin; j--)
+				{
+					versionBits = this.copyBit(i, j, versionBits);
+				}
+			}
+			
+			this.parsedVersion = Version.decodeVersionInformation(versionBits);
+			if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension)
+			{
+				return this.parsedVersion;
+			}
+			throw "Error readVersion";
+		}
+	this.readCodewords=function()
+		{
+			
+			var formatInfo = this.readFormatInformation();
+			var version = this.readVersion();
+			
+			// Get the data mask for the format used in this QR Code. This will exclude
+			// some bits from reading as we wind through the bit matrix.
+			var dataMask = DataMask.forReference( formatInfo.DataMask);
+			var dimension = this.bitMatrix.Dimension;
+			dataMask.unmaskBitMatrix(this.bitMatrix, dimension);
+			
+			var functionPattern = version.buildFunctionPattern();
+			
+			var readingUp = true;
+			var result = new Array(version.TotalCodewords);
+			var resultOffset = 0;
+			var currentByte = 0;
+			var bitsRead = 0;
+			// Read columns in pairs, from right to left
+			for (var j = dimension - 1; j > 0; j -= 2)
+			{
+				if (j == 6)
+				{
+					// Skip whole column with vertical alignment pattern;
+					// saves time and makes the other code proceed more cleanly
+					j--;
+				}
+				// Read alternatingly from bottom to top then top to bottom
+				for (var count = 0; count < dimension; count++)
+				{
+					var i = readingUp?dimension - 1 - count:count;
+					for (var col = 0; col < 2; col++)
+					{
+						// Ignore bits covered by the function pattern
+						if (!functionPattern.get_Renamed(j - col, i))
+						{
+							// Read a bit
+							bitsRead++;
+							currentByte <<= 1;
+							if (this.bitMatrix.get_Renamed(j - col, i))
+							{
+								currentByte |= 1;
+							}
+							// If we've made a whole byte, save it off
+							if (bitsRead == 8)
+							{
+								result[resultOffset++] =  currentByte;
+								bitsRead = 0;
+								currentByte = 0;
+							}
+						}
+					}
+				}
+				readingUp ^= true; // readingUp = !readingUp; // switch directions
+			}
+			if (resultOffset != version.TotalCodewords)
+			{
+				throw "Error readCodewords";
+			}
+			return result;
+		}
+}

+ 117 - 0
js/datablock.js

@@ -0,0 +1,117 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function DataBlock(numDataCodewords,  codewords)
+{
+	this.numDataCodewords = numDataCodewords;
+	this.codewords = codewords;
+	
+	this.__defineGetter__("NumDataCodewords", function()
+	{
+		return this.numDataCodewords;
+	});
+	this.__defineGetter__("Codewords", function()
+	{
+		return this.codewords;
+	});
+}	
+	
+DataBlock.getDataBlocks=function(rawCodewords,  version,  ecLevel)
+{
+	
+	if (rawCodewords.length != version.TotalCodewords)
+	{
+		throw "ArgumentException";
+	}
+	
+	// Figure out the number and size of data blocks used by this version and
+	// error correction level
+	var ecBlocks = version.getECBlocksForLevel(ecLevel);
+	
+	// First count the total number of data blocks
+	var totalBlocks = 0;
+	var ecBlockArray = ecBlocks.getECBlocks();
+	for (var i = 0; i < ecBlockArray.length; i++)
+	{
+		totalBlocks += ecBlockArray[i].Count;
+	}
+	
+	// Now establish DataBlocks of the appropriate size and number of data codewords
+	var result = new Array(totalBlocks);
+	var numResultBlocks = 0;
+	for (var j = 0; j < ecBlockArray.length; j++)
+	{
+		var ecBlock = ecBlockArray[j];
+		for (var i = 0; i < ecBlock.Count; i++)
+		{
+			var numDataCodewords = ecBlock.DataCodewords;
+			var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords;
+			result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords));
+		}
+	}
+	
+	// All blocks have the same amount of data, except that the last n
+	// (where n may be 0) have 1 more byte. Figure out where these start.
+	var shorterBlocksTotalCodewords = result[0].codewords.length;
+	var longerBlocksStartAt = result.length - 1;
+	while (longerBlocksStartAt >= 0)
+	{
+		var numCodewords = result[longerBlocksStartAt].codewords.length;
+		if (numCodewords == shorterBlocksTotalCodewords)
+		{
+			break;
+		}
+		longerBlocksStartAt--;
+	}
+	longerBlocksStartAt++;
+	
+	var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock;
+	// The last elements of result may be 1 element longer;
+	// first fill out as many elements as all of them have
+	var rawCodewordsOffset = 0;
+	for (var i = 0; i < shorterBlocksNumDataCodewords; i++)
+	{
+		for (var j = 0; j < numResultBlocks; j++)
+		{
+			result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
+		}
+	}
+	// Fill out the last data block in the longer ones
+	for (var j = longerBlocksStartAt; j < numResultBlocks; j++)
+	{
+		result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++];
+	}
+	// Now add in error correction blocks
+	var max = result[0].codewords.length;
+	for (var i = shorterBlocksNumDataCodewords; i < max; i++)
+	{
+		for (var j = 0; j < numResultBlocks; j++)
+		{
+			var iOffset = j < longerBlocksStartAt?i:i + 1;
+			result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
+		}
+	}
+	return result;
+}

+ 336 - 0
js/databr.js

@@ -0,0 +1,336 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function QRCodeDataBlockReader(blocks,  version,  numErrorCorrectionCode)
+{
+	this.blockPointer = 0;
+	this.bitPointer = 7;
+	this.dataLength = 0;
+	this.blocks = blocks;
+	this.numErrorCorrectionCode = numErrorCorrectionCode;
+	if (version <= 9)
+		this.dataLengthMode = 0;
+	else if (version >= 10 && version <= 26)
+		this.dataLengthMode = 1;
+	else if (version >= 27 && version <= 40)
+		this.dataLengthMode = 2;
+		
+	this.getNextBits = function( numBits)
+		{			
+			var bits = 0;
+			if (numBits < this.bitPointer + 1)
+			{
+				// next word fits into current data block
+				var mask = 0;
+				for (var i = 0; i < numBits; i++)
+				{
+					mask += (1 << i);
+				}
+				mask <<= (this.bitPointer - numBits + 1);
+				
+				bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1);
+				this.bitPointer -= numBits;
+				return bits;
+			}
+			else if (numBits < this.bitPointer + 1 + 8)
+			{
+				// next word crosses 2 data blocks
+				var mask1 = 0;
+				for (var i = 0; i < this.bitPointer + 1; i++)
+				{
+					mask1 += (1 << i);
+				}
+				bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1));
+                this.blockPointer++;
+				bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1))));
+				
+				this.bitPointer = this.bitPointer - numBits % 8;
+				if (this.bitPointer < 0)
+				{
+					this.bitPointer = 8 + this.bitPointer;
+				}
+				return bits;
+			}
+			else if (numBits < this.bitPointer + 1 + 16)
+			{
+				// next word crosses 3 data blocks
+				var mask1 = 0; // mask of first block
+				var mask3 = 0; // mask of 3rd block
+				//bitPointer + 1 : number of bits of the 1st block
+				//8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks)
+				//numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block 
+				for (var i = 0; i < this.bitPointer + 1; i++)
+				{
+					mask1 += (1 << i);
+				}
+				var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1));
+				this.blockPointer++;
+				
+				var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8));
+				this.blockPointer++;
+				
+				for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++)
+				{
+					mask3 += (1 << i);
+				}
+				mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8));
+				var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8)));
+				
+				bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock;
+				this.bitPointer = this.bitPointer - (numBits - 8) % 8;
+				if (this.bitPointer < 0)
+				{
+					this.bitPointer = 8 + this.bitPointer;
+				}
+				return bits;
+			}
+			else
+			{
+				return 0;
+			}
+		}
+	this.NextMode=function()
+	{
+		if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2))
+			return 0;
+		else
+			return this.getNextBits(4);
+	}
+	this.getDataLength=function( modeIndicator)
+		{
+			var index = 0;
+			while (true)
+			{
+				if ((modeIndicator >> index) == 1)
+					break;
+				index++;
+			}
+			
+			return this.getNextBits(qrcode.sizeOfDataLengthInfo[this.dataLengthMode][index]);
+		}
+	this.getRomanAndFigureString=function( dataLength)
+		{
+			var length = dataLength;
+			var intData = 0;
+			var strData = "";
+			var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':');
+			do 
+			{
+				if (length > 1)
+				{
+					intData = this.getNextBits(11);
+					var firstLetter = Math.floor(intData / 45);
+					var secondLetter = intData % 45;
+					strData += tableRomanAndFigure[firstLetter];
+					strData += tableRomanAndFigure[secondLetter];
+					length -= 2;
+				}
+				else if (length == 1)
+				{
+					intData = this.getNextBits(6);
+					strData += tableRomanAndFigure[intData];
+					length -= 1;
+				}
+			}
+			while (length > 0);
+			
+			return strData;
+		}
+	this.getFigureString=function( dataLength)
+		{
+			var length = dataLength;
+			var intData = 0;
+			var strData = "";
+			do 
+			{
+				if (length >= 3)
+				{
+					intData = this.getNextBits(10);
+					if (intData < 100)
+						strData += "0";
+					if (intData < 10)
+						strData += "0";
+					length -= 3;
+				}
+				else if (length == 2)
+				{
+					intData = this.getNextBits(7);
+					if (intData < 10)
+						strData += "0";
+					length -= 2;
+				}
+				else if (length == 1)
+				{
+					intData = this.getNextBits(4);
+					length -= 1;
+				}
+				strData += intData;
+			}
+			while (length > 0);
+			
+			return strData;
+		}
+	this.get8bitByteArray=function( dataLength)
+		{
+			var length = dataLength;
+			var intData = 0;
+			var output = new Array();
+			
+			do 
+			{
+				intData = this.getNextBits(8);
+				output.push( intData);
+				length--;
+			}
+			while (length > 0);
+			return output;
+		}
+    this.getKanjiString=function( dataLength)
+		{
+			var length = dataLength;
+			var intData = 0;
+			var unicodeString = "";
+			do 
+			{
+				intData = this.getNextBits(13);
+				var lowerByte = intData % 0xC0;
+				var higherByte = intData / 0xC0;
+				
+				var tempWord = (higherByte << 8) + lowerByte;
+				var shiftjisWord = 0;
+				if (tempWord + 0x8140 <= 0x9FFC)
+				{
+					// between 8140 - 9FFC on Shift_JIS character set
+					shiftjisWord = tempWord + 0x8140;
+				}
+				else
+				{
+					// between E040 - EBBF on Shift_JIS character set
+					shiftjisWord = tempWord + 0xC140;
+				}
+				
+				//var tempByte = new Array(0,0);
+				//tempByte[0] = (sbyte) (shiftjisWord >> 8);
+				//tempByte[1] = (sbyte) (shiftjisWord & 0xFF);
+				//unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte)));
+                unicodeString += String.fromCharCode(shiftjisWord);
+				length--;
+			}
+			while (length > 0);
+			
+			
+			return unicodeString;
+		}
+
+	this.parseECIValue = function ()
+	{
+		var intData = 0;
+		var firstByte = this.getNextBits(8);
+		if ((firstByte & 0x80) == 0) {
+			intData = firstByte & 0x7F;
+		}
+		if ((firstByte & 0xC0) == 0x80) {
+			// two bytes
+			var secondByte = this.getNextBits(8);
+			intData = ((firstByte & 0x3F) << 8) | secondByte;
+		}
+		if ((firstByte & 0xE0) == 0xC0) {
+			// three bytes
+			var secondThirdBytes = this.getNextBits(8);;
+			intData = ((firstByte & 0x1F) << 16) | secondThirdBytes;
+		}
+		return intData;
+	}
+
+	this.__defineGetter__("DataByte", function()
+	{
+		var output = new Array();
+		var MODE_NUMBER = 1;
+	    var MODE_ROMAN_AND_NUMBER = 2;
+	    var MODE_8BIT_BYTE = 4;
+		var MODE_ECI = 7;
+	    var MODE_KANJI = 8;
+		do 
+					{
+						var mode = this.NextMode();
+						//canvas.println("mode: " + mode);
+						if (mode == 0)
+						{
+							if (output.length > 0)
+								break;
+							else
+								throw "Empty data block";
+						}
+						if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI && mode != MODE_ECI)
+						{
+							throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")";
+						}
+
+						if(mode == MODE_ECI)
+						{
+							var temp_sbyteArray3 = this.parseECIValue();
+							//output.push(temp_sbyteArray3);
+						}
+						else
+						{
+
+							var dataLength = this.getDataLength(mode);
+							if (dataLength < 1)
+								throw "Invalid data length: " + dataLength;
+							switch (mode)
+							{
+								
+								case MODE_NUMBER: 
+									var temp_str = this.getFigureString(dataLength);
+									var ta = new Array(temp_str.length);
+									for(var j=0;j<temp_str.length;j++)
+										ta[j]=temp_str.charCodeAt(j);
+									output.push(ta);
+									break;
+								
+								case MODE_ROMAN_AND_NUMBER: 
+									var temp_str = this.getRomanAndFigureString(dataLength);
+									var ta = new Array(temp_str.length);
+									for(var j=0;j<temp_str.length;j++)
+										ta[j]=temp_str.charCodeAt(j);
+									output.push(ta );
+									break;
+								
+								case MODE_8BIT_BYTE: 
+									var temp_sbyteArray3 = this.get8bitByteArray(dataLength);
+									output.push(temp_sbyteArray3);
+									break;
+								
+								case MODE_KANJI: 
+									var temp_str = this.getKanjiString(dataLength);
+									output.push(temp_str);
+									break;
+							}
+						}
+					}
+					while (true);
+		return output;
+	});
+}

+ 207 - 0
js/datamask.js

@@ -0,0 +1,207 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+var DataMask = {};
+
+DataMask.forReference = function(reference)
+{
+	if (reference < 0 || reference > 7)
+	{
+		throw "System.ArgumentException";
+	}
+	return DataMask.DATA_MASKS[reference];
+}
+
+function DataMask000()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		return ((i + j) & 0x01) == 0;
+	}
+}
+
+function DataMask001()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		return (i & 0x01) == 0;
+	}
+}
+
+function DataMask010()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		return j % 3 == 0;
+	}
+}
+
+function DataMask011()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		return (i + j) % 3 == 0;
+	}
+}
+
+function DataMask100()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		return (((URShift(i, 1)) + (j / 3)) & 0x01) == 0;
+	}
+}
+
+function DataMask101()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		var temp = i * j;
+		return (temp & 0x01) + (temp % 3) == 0;
+	}
+}
+
+function DataMask110()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		var temp = i * j;
+		return (((temp & 0x01) + (temp % 3)) & 0x01) == 0;
+	}
+}
+function DataMask111()
+{
+	this.unmaskBitMatrix=function(bits,  dimension)
+	{
+		for (var i = 0; i < dimension; i++)
+		{
+			for (var j = 0; j < dimension; j++)
+			{
+				if (this.isMasked(i, j))
+				{
+					bits.flip(j, i);
+				}
+			}
+		}
+	}
+	this.isMasked=function( i,  j)
+	{
+		return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0;
+	}
+}
+
+DataMask.DATA_MASKS = new Array(new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111());
+

+ 95 - 0
js/decoder.js

@@ -0,0 +1,95 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+var Decoder={};
+Decoder.rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD);
+
+Decoder.correctErrors=function( codewordBytes,  numDataCodewords)
+{
+	var numCodewords = codewordBytes.length;
+	// First read into an array of ints
+	var codewordsInts = new Array(numCodewords);
+	for (var i = 0; i < numCodewords; i++)
+	{
+		codewordsInts[i] = codewordBytes[i] & 0xFF;
+	}
+	var numECCodewords = codewordBytes.length - numDataCodewords;
+	try
+	{
+		Decoder.rsDecoder.decode(codewordsInts, numECCodewords);
+		//var corrector = new ReedSolomon(codewordsInts, numECCodewords);
+		//corrector.correct();
+	}
+	catch ( rse)
+	{
+		throw rse;
+	}
+	// Copy back into array of bytes -- only need to worry about the bytes that were data
+	// We don't care about errors in the error-correction codewords
+	for (var i = 0; i < numDataCodewords; i++)
+	{
+		codewordBytes[i] =  codewordsInts[i];
+	}
+}
+
+Decoder.decode=function(bits)
+{
+	var parser = new BitMatrixParser(bits);
+	var version = parser.readVersion();
+	var ecLevel = parser.readFormatInformation().ErrorCorrectionLevel;
+	
+	// Read codewords
+	var codewords = parser.readCodewords();
+
+	// Separate into data blocks
+	var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel);
+	
+	// Count total number of data bytes
+	var totalBytes = 0;
+	for (var i = 0; i < dataBlocks.length; i++)
+	{
+		totalBytes += dataBlocks[i].NumDataCodewords;
+	}
+	var resultBytes = new Array(totalBytes);
+	var resultOffset = 0;
+	
+	// Error-correct and copy data blocks together into a stream of bytes
+	for (var j = 0; j < dataBlocks.length; j++)
+	{
+		var dataBlock = dataBlocks[j];
+		var codewordBytes = dataBlock.Codewords;
+		var numDataCodewords = dataBlock.NumDataCodewords;
+		Decoder.correctErrors(codewordBytes, numDataCodewords);
+		for (var i = 0; i < numDataCodewords; i++)
+		{
+			resultBytes[resultOffset++] = codewordBytes[i];
+		}
+	}
+	
+	// Decode the contents of that stream of bytes
+	var reader = new QRCodeDataBlockReader(resultBytes, version.VersionNumber, ecLevel.Bits);
+	return reader;
+	//return DecodedBitStreamParser.decode(resultBytes, version, ecLevel);
+}

+ 413 - 0
js/detector.js

@@ -0,0 +1,413 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function PerspectiveTransform( a11,  a21,  a31,  a12,  a22,  a32,  a13,  a23,  a33)
+{
+	this.a11 = a11;
+	this.a12 = a12;
+	this.a13 = a13;
+	this.a21 = a21;
+	this.a22 = a22;
+	this.a23 = a23;
+	this.a31 = a31;
+	this.a32 = a32;
+	this.a33 = a33;
+	this.transformPoints1=function( points)
+		{
+			var max = points.length;
+			var a11 = this.a11;
+			var a12 = this.a12;
+			var a13 = this.a13;
+			var a21 = this.a21;
+			var a22 = this.a22;
+			var a23 = this.a23;
+			var a31 = this.a31;
+			var a32 = this.a32;
+			var a33 = this.a33;
+			for (var i = 0; i < max; i += 2)
+			{
+				var x = points[i];
+				var y = points[i + 1];
+				var denominator = a13 * x + a23 * y + a33;
+				points[i] = (a11 * x + a21 * y + a31) / denominator;
+				points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
+			}
+		}
+	this. transformPoints2=function(xValues, yValues)
+		{
+			var n = xValues.length;
+			for (var i = 0; i < n; i++)
+			{
+				var x = xValues[i];
+				var y = yValues[i];
+				var denominator = this.a13 * x + this.a23 * y + this.a33;
+				xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator;
+				yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator;
+			}
+		}
+
+	this.buildAdjoint=function()
+		{
+			// Adjoint is the transpose of the cofactor matrix:
+			return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21);
+		}
+	this.times=function( other)
+		{
+			return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33);
+		}
+
+}
+
+PerspectiveTransform.quadrilateralToQuadrilateral=function( x0,  y0,  x1,  y1,  x2,  y2,  x3,  y3,  x0p,  y0p,  x1p,  y1p,  x2p,  y2p,  x3p,  y3p)
+{
+	
+	var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
+	var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
+	return sToQ.times(qToS);
+}
+
+PerspectiveTransform.squareToQuadrilateral=function( x0,  y0,  x1,  y1,  x2,  y2,  x3,  y3)
+{
+	var dy2 = y3 - y2;
+	var dy3 = y0 - y1 + y2 - y3;
+	if (dy2 == 0.0 && dy3 == 0.0)
+	{
+		return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0);
+	}
+	else
+	{
+		var dx1 = x1 - x2;
+		var dx2 = x3 - x2;
+		var dx3 = x0 - x1 + x2 - x3;
+		var dy1 = y1 - y2;
+		var denominator = dx1 * dy2 - dx2 * dy1;
+		var a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
+		var a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
+		return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0);
+	}
+}
+
+PerspectiveTransform.quadrilateralToSquare=function( x0,  y0,  x1,  y1,  x2,  y2,  x3,  y3)
+{
+	// Here, the adjoint serves as the inverse:
+	return this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();
+}
+
+function DetectorResult(bits,  points)
+{
+	this.bits = bits;
+	this.points = points;
+}
+
+
+function Detector(image)
+{
+	this.image=image;
+	this.resultPointCallback = null;
+	
+	this.sizeOfBlackWhiteBlackRun=function( fromX,  fromY,  toX,  toY)
+		{
+			// Mild variant of Bresenham's algorithm;
+			// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
+			var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
+			if (steep)
+			{
+				var temp = fromX;
+				fromX = fromY;
+				fromY = temp;
+				temp = toX;
+				toX = toY;
+				toY = temp;
+			}
+			
+			var dx = Math.abs(toX - fromX);
+			var dy = Math.abs(toY - fromY);
+			var error = - dx >> 1;
+			var ystep = fromY < toY?1:- 1;
+			var xstep = fromX < toX?1:- 1;
+			var state = 0; // In black pixels, looking for white, first or second time
+			for (var x = fromX, y = fromY; x != toX; x += xstep)
+			{
+				
+				var realX = steep?y:x;
+				var realY = steep?x:y;
+				if (state == 1)
+				{
+					// In white pixels, looking for black
+					if (this.image[realX + realY*qrcode.width])
+					{
+						state++;
+					}
+				}
+				else
+				{
+					if (!this.image[realX + realY*qrcode.width])
+					{
+						state++;
+					}
+				}
+				
+				if (state == 3)
+				{
+					// Found black, white, black, and stumbled back onto white; done
+					var diffX = x - fromX;
+					var diffY = y - fromY;
+					return  Math.sqrt( (diffX * diffX + diffY * diffY));
+				}
+				error += dy;
+				if (error > 0)
+				{
+					if (y == toY)
+					{
+						break;
+					}
+					y += ystep;
+					error -= dx;
+				}
+			}
+			var diffX2 = toX - fromX;
+			var diffY2 = toY - fromY;
+			return  Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2));
+		}
+
+	
+	this.sizeOfBlackWhiteBlackRunBothWays=function( fromX,  fromY,  toX,  toY)
+		{
+			
+			var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
+			
+			// Now count other way -- don't run off image though of course
+			var scale = 1.0;
+			var otherToX = fromX - (toX - fromX);
+			if (otherToX < 0)
+			{
+				scale =  fromX /  (fromX - otherToX);
+				otherToX = 0;
+			}
+			else if (otherToX >= qrcode.width)
+			{
+				scale =  (qrcode.width - 1 - fromX) /  (otherToX - fromX);
+				otherToX = qrcode.width - 1;
+			}
+			var otherToY = Math.floor (fromY - (toY - fromY) * scale);
+			
+			scale = 1.0;
+			if (otherToY < 0)
+			{
+				scale =  fromY /  (fromY - otherToY);
+				otherToY = 0;
+			}
+			else if (otherToY >= qrcode.height)
+			{
+				scale =  (qrcode.height - 1 - fromY) /  (otherToY - fromY);
+				otherToY = qrcode.height - 1;
+			}
+			otherToX = Math.floor (fromX + (otherToX - fromX) * scale);
+			
+			result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
+			return result - 1.0; // -1 because we counted the middle pixel twice
+		}
+		
+
+	
+	this.calculateModuleSizeOneWay=function( pattern,  otherPattern)
+		{
+			var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y));
+			var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y));
+			if (isNaN(moduleSizeEst1))
+			{
+				return moduleSizeEst2 / 7.0;
+			}
+			if (isNaN(moduleSizeEst2))
+			{
+				return moduleSizeEst1 / 7.0;
+			}
+			// Average them, and divide by 7 since we've counted the width of 3 black modules,
+			// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
+			return (moduleSizeEst1 + moduleSizeEst2) / 14.0;
+		}
+
+	
+	this.calculateModuleSize=function( topLeft,  topRight,  bottomLeft)
+		{
+			// Take the average
+			return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0;
+		}
+
+	this.distance=function( pattern1,  pattern2)
+	{
+		var xDiff = pattern1.X - pattern2.X;
+		var yDiff = pattern1.Y - pattern2.Y;
+		return  Math.sqrt( (xDiff * xDiff + yDiff * yDiff));
+	}
+	this.computeDimension=function( topLeft,  topRight,  bottomLeft,  moduleSize)
+		{
+			
+			var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize);
+			var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize);
+			var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
+			switch (dimension & 0x03)
+			{
+				
+				// mod 4
+				case 0: 
+					dimension++;
+					break;
+					// 1? do nothing
+				
+				case 2: 
+					dimension--;
+					break;
+				
+				case 3: 
+					throw "Error";
+				}
+			return dimension;
+		}
+
+	this.findAlignmentInRegion=function( overallEstModuleSize,  estAlignmentX,  estAlignmentY,  allowanceFactor)
+		{
+			// Look for an alignment pattern (3 modules in size) around where it
+			// should be
+			var allowance = Math.floor (allowanceFactor * overallEstModuleSize);
+			var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
+			var alignmentAreaRightX = Math.min(qrcode.width - 1, estAlignmentX + allowance);
+			if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3)
+			{
+				throw "Error";
+			}
+			
+			var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
+			var alignmentAreaBottomY = Math.min(qrcode.height - 1, estAlignmentY + allowance);
+			
+			var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback);
+			return alignmentFinder.find();
+		}
+		
+	this.createTransform=function( topLeft,  topRight,  bottomLeft, alignmentPattern, dimension)
+		{
+			var dimMinusThree =  dimension - 3.5;
+			var bottomRightX;
+			var bottomRightY;
+			var sourceBottomRightX;
+			var sourceBottomRightY;
+			if (alignmentPattern != null)
+			{
+				bottomRightX = alignmentPattern.X;
+				bottomRightY = alignmentPattern.Y;
+				sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0;
+			}
+			else
+			{
+				// Don't have an alignment pattern, just make up the bottom-right point
+				bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X;
+				bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y;
+				sourceBottomRightX = sourceBottomRightY = dimMinusThree;
+			}
+			
+			var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y);
+			
+			return transform;
+		}		
+	
+	this.sampleGrid=function( image,  transform,  dimension)
+		{
+			
+			var sampler = GridSampler;
+			return sampler.sampleGrid3(image, dimension, transform);
+		}
+	
+	this.processFinderPatternInfo = function( info)
+		{
+			
+			var topLeft = info.TopLeft;
+			var topRight = info.TopRight;
+			var bottomLeft = info.BottomLeft;
+			
+			var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft);
+			if (moduleSize < 1.0)
+			{
+				throw "Error";
+			}
+			var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize);
+			var provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
+			var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7;
+			
+			var alignmentPattern = null;
+			// Anything above version 1 has an alignment pattern
+			if (provisionalVersion.AlignmentPatternCenters.length > 0)
+			{
+				
+				// Guess where a "bottom right" finder pattern would have been
+				var bottomRightX = topRight.X - topLeft.X + bottomLeft.X;
+				var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y;
+				
+				// Estimate that alignment pattern is closer by 3 modules
+				// from "bottom right" to known top left location
+				var correctionToTopLeft = 1.0 - 3.0 /  modulesBetweenFPCenters;
+				var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X));
+				var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y));
+				
+				// Kind of arbitrary -- expand search radius before giving up
+				for (var i = 4; i <= 16; i <<= 1)
+				{
+					//try
+					//{
+						alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY,  i);
+						break;
+					//}
+					//catch (re)
+					//{
+						// try next round
+					//}
+				}
+				// If we didn't find alignment pattern... well try anyway without it
+			}
+			
+			var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
+			
+			var bits = this.sampleGrid(this.image, transform, dimension);
+			
+			var points;
+			if (alignmentPattern == null)
+			{
+				points = new Array(bottomLeft, topLeft, topRight);
+			}
+			else
+			{
+				points = new Array(bottomLeft, topLeft, topRight, alignmentPattern);
+			}
+			return new DetectorResult(bits, points);
+		}
+		
+
+	
+	this.detect=function()
+	{
+		var info =  new FinderPatternFinder().findFinderPattern(this.image);
+			
+		return this.processFinderPatternInfo(info); 
+	}
+}

+ 58 - 0
js/errorlevel.js

@@ -0,0 +1,58 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function ErrorCorrectionLevel(ordinal,  bits, name)
+{
+	this.ordinal_Renamed_Field = ordinal;
+	this.bits = bits;
+	this.name = name;
+	this.__defineGetter__("Bits", function()
+	{
+		return this.bits;
+	});
+	this.__defineGetter__("Name", function()
+	{
+		return this.name;
+	});
+	this.ordinal=function()
+	{
+		return this.ordinal_Renamed_Field;
+	}
+}
+
+ErrorCorrectionLevel.forBits=function( bits)
+{
+	if (bits < 0 || bits >= FOR_BITS.length)
+	{
+		throw "ArgumentException";
+	}
+	return FOR_BITS[bits];
+}
+
+var L = new ErrorCorrectionLevel(0, 0x01, "L");
+var M = new ErrorCorrectionLevel(1, 0x00, "M");
+var Q = new ErrorCorrectionLevel(2, 0x03, "Q");
+var H = new ErrorCorrectionLevel(3, 0x02, "H");
+var FOR_BITS = new Array( M, L, H, Q);

+ 651 - 0
js/findpat.js

@@ -0,0 +1,651 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+var MIN_SKIP = 3;
+var MAX_MODULES = 57;
+var INTEGER_MATH_SHIFT = 8;
+var CENTER_QUORUM = 2;
+
+qrcode.orderBestPatterns=function(patterns)
+		{
+			
+			function distance( pattern1,  pattern2)
+			{
+				var xDiff = pattern1.X - pattern2.X;
+				var yDiff = pattern1.Y - pattern2.Y;
+				return  Math.sqrt( (xDiff * xDiff + yDiff * yDiff));
+			}
+			
+			/// <summary> Returns the z component of the cross product between vectors BC and BA.</summary>
+			function crossProductZ( pointA,  pointB,  pointC)
+			{
+				var bX = pointB.x;
+				var bY = pointB.y;
+				return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
+			}
+
+			
+			// Find distances between pattern centers
+			var zeroOneDistance = distance(patterns[0], patterns[1]);
+			var oneTwoDistance = distance(patterns[1], patterns[2]);
+			var zeroTwoDistance = distance(patterns[0], patterns[2]);
+			
+			var pointA, pointB, pointC;
+			// Assume one closest to other two is B; A and C will just be guesses at first
+			if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance)
+			{
+				pointB = patterns[0];
+				pointA = patterns[1];
+				pointC = patterns[2];
+			}
+			else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance)
+			{
+				pointB = patterns[1];
+				pointA = patterns[0];
+				pointC = patterns[2];
+			}
+			else
+			{
+				pointB = patterns[2];
+				pointA = patterns[0];
+				pointC = patterns[1];
+			}
+			
+			// Use cross product to figure out whether A and C are correct or flipped.
+			// This asks whether BC x BA has a positive z component, which is the arrangement
+			// we want for A, B, C. If it's negative, then we've got it flipped around and
+			// should swap A and C.
+			if (crossProductZ(pointA, pointB, pointC) < 0.0)
+			{
+				var temp = pointA;
+				pointA = pointC;
+				pointC = temp;
+			}
+			
+			patterns[0] = pointA;
+			patterns[1] = pointB;
+			patterns[2] = pointC;
+		}
+
+
+function FinderPattern(posX, posY,  estimatedModuleSize)
+{
+	this.x=posX;
+	this.y=posY;
+	this.count = 1;
+	this.estimatedModuleSize = estimatedModuleSize;
+	
+	this.__defineGetter__("EstimatedModuleSize", function()
+	{
+		return this.estimatedModuleSize;
+	}); 
+	this.__defineGetter__("Count", function()
+	{
+		return this.count;
+	});
+	this.__defineGetter__("X", function()
+	{
+		return this.x;
+	});
+	this.__defineGetter__("Y", function()
+	{
+		return this.y;
+	});
+	this.incrementCount = function()
+	{
+		this.count++;
+	}
+	this.aboutEquals=function( moduleSize,  i,  j)
+		{
+			if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize)
+			{
+				var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
+				return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0;
+			}
+			return false;
+		}
+	
+}
+
+function FinderPatternInfo(patternCenters)
+{
+	this.bottomLeft = patternCenters[0];
+	this.topLeft = patternCenters[1];
+	this.topRight = patternCenters[2];
+	this.__defineGetter__("BottomLeft", function()
+	{
+		return this.bottomLeft;
+	}); 
+	this.__defineGetter__("TopLeft", function()
+	{
+		return this.topLeft;
+	}); 
+	this.__defineGetter__("TopRight", function()
+	{
+		return this.topRight;
+	}); 
+}
+
+function FinderPatternFinder()
+{
+	this.image=null;
+	this.possibleCenters = [];
+	this.hasSkipped = false;
+	this.crossCheckStateCount = new Array(0,0,0,0,0);
+	this.resultPointCallback = null;
+	
+	this.__defineGetter__("CrossCheckStateCount", function()
+	{
+		this.crossCheckStateCount[0] = 0;
+		this.crossCheckStateCount[1] = 0;
+		this.crossCheckStateCount[2] = 0;
+		this.crossCheckStateCount[3] = 0;
+		this.crossCheckStateCount[4] = 0;
+		return this.crossCheckStateCount;
+	}); 
+	
+	this.foundPatternCross=function( stateCount)
+		{
+			var totalModuleSize = 0;
+			for (var i = 0; i < 5; i++)
+			{
+				var count = stateCount[i];
+				if (count == 0)
+				{
+					return false;
+				}
+				totalModuleSize += count;
+			}
+			if (totalModuleSize < 7)
+			{
+				return false;
+			}
+			var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7);
+			var maxVariance = Math.floor(moduleSize / 2);
+			// Allow less than 50% variance from 1-1-3-1-1 proportions
+			return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
+		}
+	this.centerFromEnd=function( stateCount,  end)
+		{
+			return  (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0;
+		}
+	this.crossCheckVertical=function( startI,  centerJ,  maxCount,  originalStateCountTotal)
+		{
+			var image = this.image;
+			
+			var maxI = qrcode.height;
+			var stateCount = this.CrossCheckStateCount;
+			
+			// Start counting up from center
+			var i = startI;
+			while (i >= 0 && image[centerJ + i*qrcode.width])
+			{
+				stateCount[2]++;
+				i--;
+			}
+			if (i < 0)
+			{
+				return NaN;
+			}
+			while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount)
+			{
+				stateCount[1]++;
+				i--;
+			}
+			// If already too many modules in this state or ran off the edge:
+			if (i < 0 || stateCount[1] > maxCount)
+			{
+				return NaN;
+			}
+			while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount)
+			{
+				stateCount[0]++;
+				i--;
+			}
+			if (stateCount[0] > maxCount)
+			{
+				return NaN;
+			}
+			
+			// Now also count down from center
+			i = startI + 1;
+			while (i < maxI && image[centerJ +i*qrcode.width])
+			{
+				stateCount[2]++;
+				i++;
+			}
+			if (i == maxI)
+			{
+				return NaN;
+			}
+			while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount)
+			{
+				stateCount[3]++;
+				i++;
+			}
+			if (i == maxI || stateCount[3] >= maxCount)
+			{
+				return NaN;
+			}
+			while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount)
+			{
+				stateCount[4]++;
+				i++;
+			}
+			if (stateCount[4] >= maxCount)
+			{
+				return NaN;
+			}
+			
+			// If we found a finder-pattern-like section, but its size is more than 40% different than
+			// the original, assume it's a false positive
+			var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+			if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
+			{
+				return NaN;
+			}
+			
+			return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN;
+		}
+	this.crossCheckHorizontal=function( startJ,  centerI,  maxCount, originalStateCountTotal)
+		{
+			var image = this.image;
+			
+			var maxJ = qrcode.width;
+			var stateCount = this.CrossCheckStateCount;
+			
+			var j = startJ;
+			while (j >= 0 && image[j+ centerI*qrcode.width])
+			{
+				stateCount[2]++;
+				j--;
+			}
+			if (j < 0)
+			{
+				return NaN;
+			}
+			while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount)
+			{
+				stateCount[1]++;
+				j--;
+			}
+			if (j < 0 || stateCount[1] > maxCount)
+			{
+				return NaN;
+			}
+			while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount)
+			{
+				stateCount[0]++;
+				j--;
+			}
+			if (stateCount[0] > maxCount)
+			{
+				return NaN;
+			}
+			
+			j = startJ + 1;
+			while (j < maxJ && image[j+ centerI*qrcode.width])
+			{
+				stateCount[2]++;
+				j++;
+			}
+			if (j == maxJ)
+			{
+				return NaN;
+			}
+			while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount)
+			{
+				stateCount[3]++;
+				j++;
+			}
+			if (j == maxJ || stateCount[3] >= maxCount)
+			{
+				return NaN;
+			}
+			while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount)
+			{
+				stateCount[4]++;
+				j++;
+			}
+			if (stateCount[4] >= maxCount)
+			{
+				return NaN;
+			}
+			
+			// If we found a finder-pattern-like section, but its size is significantly different than
+			// the original, assume it's a false positive
+			var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+			if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
+			{
+				return NaN;
+			}
+			
+			return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN;
+		}
+	this.handlePossibleCenter=function( stateCount,  i,  j)
+		{
+			var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+			var centerJ = this.centerFromEnd(stateCount, j); //float
+			var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float
+			if (!isNaN(centerI))
+			{
+				// Re-cross check
+				centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal);
+				if (!isNaN(centerJ))
+				{
+					var estimatedModuleSize =   stateCountTotal / 7.0;
+					var found = false;
+					var max = this.possibleCenters.length;
+					for (var index = 0; index < max; index++)
+					{
+						var center = this.possibleCenters[index];
+						// Look for about the same center and module size:
+						if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
+						{
+							center.incrementCount();
+							found = true;
+							break;
+						}
+					}
+					if (!found)
+					{
+						var point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
+						this.possibleCenters.push(point);
+						if (this.resultPointCallback != null)
+						{
+							this.resultPointCallback.foundPossibleResultPoint(point);
+						}
+					}
+					return true;
+				}
+			}
+			return false;
+		}
+		
+	this.selectBestPatterns=function()
+		{
+			
+			var startSize = this.possibleCenters.length;
+			if (startSize < 3)
+			{
+				// Couldn't find enough finder patterns
+				throw "Couldn't find enough finder patterns (found " + startSize + ")"
+			}
+			
+			// Filter outlier possibilities whose module size is too different
+			if (startSize > 3)
+			{
+				// But we can only afford to do so if we have at least 4 possibilities to choose from
+				var totalModuleSize = 0.0;
+                var square = 0.0;
+				for (var i = 0; i < startSize; i++)
+				{
+					//totalModuleSize +=  this.possibleCenters[i].EstimatedModuleSize;
+                    var	centerValue=this.possibleCenters[i].EstimatedModuleSize;
+					totalModuleSize += centerValue;
+					square += (centerValue * centerValue);
+				}
+				var average = totalModuleSize /  startSize;
+                this.possibleCenters.sort(function(center1,center2) {
+				      var dA=Math.abs(center2.EstimatedModuleSize - average);
+				      var dB=Math.abs(center1.EstimatedModuleSize - average);
+				      if (dA < dB) {
+				    	  return (-1);
+				      } else if (dA == dB) {
+				    	  return 0;
+				      } else {
+				    	  return 1;
+				      }
+					});
+
+				var stdDev = Math.sqrt(square / startSize - average * average);
+				var limit = Math.max(0.2 * average, stdDev);
+				//for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++)
+				for (var i = this.possibleCenters.length - 1; i >= 0 ; i--)
+				{
+					var pattern =  this.possibleCenters[i];
+					//if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average)
+                    if (Math.abs(pattern.EstimatedModuleSize - average) > limit)
+					{
+						//this.possibleCenters.remove(i);
+						this.possibleCenters.splice(i,1);
+						//i--;
+					}
+				}
+			}
+			
+			if (this.possibleCenters.length > 3)
+			{
+				// Throw away all but those first size candidate points we found.
+				this.possibleCenters.sort(function(a, b){
+					if (a.count > b.count){return -1;}
+					if (a.count < b.count){return 1;}
+					return 0;
+				});
+			}
+			
+			return new Array( this.possibleCenters[0],  this.possibleCenters[1],  this.possibleCenters[2]);
+		}
+		
+	this.findRowSkip=function()
+		{
+			var max = this.possibleCenters.length;
+			if (max <= 1)
+			{
+				return 0;
+			}
+			var firstConfirmedCenter = null;
+			for (var i = 0; i < max; i++)
+			{
+				var center =  this.possibleCenters[i];
+				if (center.Count >= CENTER_QUORUM)
+				{
+					if (firstConfirmedCenter == null)
+					{
+						firstConfirmedCenter = center;
+					}
+					else
+					{
+						// We have two confirmed centers
+						// How far down can we skip before resuming looking for the next
+						// pattern? In the worst case, only the difference between the
+						// difference in the x / y coordinates of the two centers.
+						// This is the case where you find top left last.
+						this.hasSkipped = true;
+						return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2);
+					}
+				}
+			}
+			return 0;
+		}
+	
+	this.haveMultiplyConfirmedCenters=function()
+		{
+			var confirmedCount = 0;
+			var totalModuleSize = 0.0;
+			var max = this.possibleCenters.length;
+			for (var i = 0; i < max; i++)
+			{
+				var pattern =  this.possibleCenters[i];
+				if (pattern.Count >= CENTER_QUORUM)
+				{
+					confirmedCount++;
+					totalModuleSize += pattern.EstimatedModuleSize;
+				}
+			}
+			if (confirmedCount < 3)
+			{
+				return false;
+			}
+			// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
+			// and that we need to keep looking. We detect this by asking if the estimated module sizes
+			// vary too much. We arbitrarily say that when the total deviation from average exceeds
+			// 5% of the total module size estimates, it's too much.
+			var average = totalModuleSize / max;
+			var totalDeviation = 0.0;
+			for (var i = 0; i < max; i++)
+			{
+				pattern = this.possibleCenters[i];
+				totalDeviation += Math.abs(pattern.EstimatedModuleSize - average);
+			}
+			return totalDeviation <= 0.05 * totalModuleSize;
+		}
+		
+	this.findFinderPattern = function(image){
+		var tryHarder = false;
+		this.image=image;
+		var maxI = qrcode.height;
+		var maxJ = qrcode.width;
+		var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES));
+		if (iSkip < MIN_SKIP || tryHarder)
+		{
+				iSkip = MIN_SKIP;
+		}
+		
+		var done = false;
+		var stateCount = new Array(5);
+		for (var i = iSkip - 1; i < maxI && !done; i += iSkip)
+		{
+			// Get a row of black/white values
+			stateCount[0] = 0;
+			stateCount[1] = 0;
+			stateCount[2] = 0;
+			stateCount[3] = 0;
+			stateCount[4] = 0;
+			var currentState = 0;
+			for (var j = 0; j < maxJ; j++)
+			{
+				if (image[j+i*qrcode.width] )
+				{
+					// Black pixel
+					if ((currentState & 1) == 1)
+					{
+						// Counting white pixels
+						currentState++;
+					}
+					stateCount[currentState]++;
+				}
+				else
+				{
+					// White pixel
+					if ((currentState & 1) == 0)
+					{
+						// Counting black pixels
+						if (currentState == 4)
+						{
+							// A winner?
+							if (this.foundPatternCross(stateCount))
+							{
+								// Yes
+								var confirmed = this.handlePossibleCenter(stateCount, i, j);
+								if (confirmed)
+								{
+									// Start examining every other line. Checking each line turned out to be too
+									// expensive and didn't improve performance.
+									iSkip = 2;
+									if (this.hasSkipped)
+									{
+										done = this.haveMultiplyConfirmedCenters();
+									}
+									else
+									{
+										var rowSkip = this.findRowSkip();
+										if (rowSkip > stateCount[2])
+										{
+											// Skip rows between row of lower confirmed center
+											// and top of presumed third confirmed center
+											// but back up a bit to get a full chance of detecting
+											// it, entire width of center of finder pattern
+											
+											// Skip by rowSkip, but back off by stateCount[2] (size of last center
+											// of pattern we saw) to be conservative, and also back off by iSkip which
+											// is about to be re-added
+											i += rowSkip - stateCount[2] - iSkip;
+											j = maxJ - 1;
+										}
+									}
+								}
+								else
+								{
+									// Advance to next black pixel
+									do 
+									{
+										j++;
+									}
+									while (j < maxJ && !image[j + i*qrcode.width]);
+									j--; // back up to that last white pixel
+								}
+								// Clear state to start looking again
+								currentState = 0;
+								stateCount[0] = 0;
+								stateCount[1] = 0;
+								stateCount[2] = 0;
+								stateCount[3] = 0;
+								stateCount[4] = 0;
+							}
+							else
+							{
+								// No, shift counts back by two
+								stateCount[0] = stateCount[2];
+								stateCount[1] = stateCount[3];
+								stateCount[2] = stateCount[4];
+								stateCount[3] = 1;
+								stateCount[4] = 0;
+								currentState = 3;
+							}
+						}
+						else
+						{
+							stateCount[++currentState]++;
+						}
+					}
+					else
+					{
+						// Counting white pixels
+						stateCount[currentState]++;
+					}
+				}
+			}
+			if (this.foundPatternCross(stateCount))
+			{
+				var confirmed = this.handlePossibleCenter(stateCount, i, maxJ);
+				if (confirmed)
+				{
+					iSkip = stateCount[0];
+					if (this.hasSkipped)
+					{
+						// Found a third one
+						done = this.haveMultiplyConfirmedCenters();
+					}
+				}
+			}
+		}
+		
+		var patternInfo = this.selectBestPatterns();
+		qrcode.orderBestPatterns(patternInfo);
+		
+		return new FinderPatternInfo(patternInfo);
+	};
+}

+ 104 - 0
js/formatinf.js

@@ -0,0 +1,104 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+var FORMAT_INFO_MASK_QR = 0x5412;
+var FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F));
+var BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4);
+
+
+function FormatInformation(formatInfo)
+{
+	this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03);
+	this.dataMask =  (formatInfo & 0x07);
+
+	this.__defineGetter__("ErrorCorrectionLevel", function()
+	{
+		return this.errorCorrectionLevel;
+	});
+	this.__defineGetter__("DataMask", function()
+	{
+		return this.dataMask;
+	});
+	this.GetHashCode=function()
+	{
+		return (this.errorCorrectionLevel.ordinal() << 3) |  this.dataMask;
+	}
+	this.Equals=function( o)
+	{
+		var other =  o;
+		return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask;
+	}
+}
+
+FormatInformation.numBitsDiffering=function( a,  b)
+{
+	a ^= b; // a now has a 1 bit exactly where its bit differs with b's
+	// Count bits set quickly with a series of lookups:
+	return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)];
+}
+
+FormatInformation.decodeFormatInformation=function( maskedFormatInfo)
+{
+	var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo);
+	if (formatInfo != null)
+	{
+		return formatInfo;
+	}
+	// Should return null, but, some QR codes apparently
+	// do not mask this info. Try again by actually masking the pattern
+	// first
+	return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR);
+}
+FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo)
+{
+	// Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
+	var bestDifference = 0xffffffff;
+	var bestFormatInfo = 0;
+	for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++)
+	{
+		var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i];
+		var targetInfo = decodeInfo[0];
+		if (targetInfo == maskedFormatInfo)
+		{
+			// Found an exact match
+			return new FormatInformation(decodeInfo[1]);
+		}
+		var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo);
+		if (bitsDifference < bestDifference)
+		{
+			bestFormatInfo = decodeInfo[1];
+			bestDifference = bitsDifference;
+		}
+	}
+	// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
+	// differing means we found a match
+	if (bestDifference <= 3)
+	{
+		return new FormatInformation(bestFormatInfo);
+	}
+	return null;
+}
+
+		

+ 117 - 0
js/gf256.js

@@ -0,0 +1,117 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function GF256( primitive)
+{
+	this.expTable = new Array(256);
+	this.logTable = new Array(256);
+	var x = 1;
+	for (var i = 0; i < 256; i++)
+	{
+		this.expTable[i] = x;
+		x <<= 1; // x = x * 2; we're assuming the generator alpha is 2
+		if (x >= 0x100)
+		{
+			x ^= primitive;
+		}
+	}
+	for (var i = 0; i < 255; i++)
+	{
+		this.logTable[this.expTable[i]] = i;
+	}
+	// logTable[0] == 0 but this should never be used
+	var at0=new Array(1);at0[0]=0;
+	this.zero = new GF256Poly(this, new Array(at0));
+	var at1=new Array(1);at1[0]=1;
+	this.one = new GF256Poly(this, new Array(at1));
+	
+	this.__defineGetter__("Zero", function()
+	{
+		return this.zero;
+	});
+	this.__defineGetter__("One", function()
+	{
+		return this.one;
+	});
+	this.buildMonomial=function( degree,  coefficient)
+		{
+			if (degree < 0)
+			{
+				throw "System.ArgumentException";
+			}
+			if (coefficient == 0)
+			{
+				return this.zero;
+			}
+			var coefficients = new Array(degree + 1);
+			for(var i=0;i<coefficients.length;i++)coefficients[i]=0;
+			coefficients[0] = coefficient;
+			return new GF256Poly(this, coefficients);
+		}
+	this.exp=function( a)
+		{
+			return this.expTable[a];
+		}
+	this.log=function( a)
+		{
+			if (a == 0)
+			{
+				throw "System.ArgumentException";
+			}
+			return this.logTable[a];
+		}
+	this.inverse=function( a)
+		{
+			if (a == 0)
+			{
+				throw "System.ArithmeticException";
+			}
+			return this.expTable[255 - this.logTable[a]];
+		}
+	this.multiply=function( a,  b)
+		{
+			if (a == 0 || b == 0)
+			{
+				return 0;
+			}
+			if (a == 1)
+			{
+				return b;
+			}
+			if (b == 1)
+			{
+				return a;
+			}
+			return this.expTable[(this.logTable[a] + this.logTable[b]) % 255];
+		}		
+}
+
+GF256.QR_CODE_FIELD = new GF256(0x011D);
+GF256.DATA_MATRIX_FIELD = new GF256(0x012D);
+
+GF256.addOrSubtract=function( a,  b)
+{
+	return a ^ b;
+}

+ 230 - 0
js/gf256poly.js

@@ -0,0 +1,230 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function GF256Poly(field,  coefficients)
+{
+	if (coefficients == null || coefficients.length == 0)
+	{
+		throw "System.ArgumentException";
+	}
+	this.field = field;
+	var coefficientsLength = coefficients.length;
+	if (coefficientsLength > 1 && coefficients[0] == 0)
+	{
+		// Leading term must be non-zero for anything except the constant polynomial "0"
+		var firstNonZero = 1;
+		while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0)
+		{
+			firstNonZero++;
+		}
+		if (firstNonZero == coefficientsLength)
+		{
+			this.coefficients = field.Zero.coefficients;
+		}
+		else
+		{
+			this.coefficients = new Array(coefficientsLength - firstNonZero);
+			for(var i=0;i<this.coefficients.length;i++)this.coefficients[i]=0;
+			//Array.Copy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length);
+			for(var ci=0;ci<this.coefficients.length;ci++)this.coefficients[ci]=coefficients[firstNonZero+ci];
+		}
+	}
+	else
+	{
+		this.coefficients = coefficients;
+	}
+	
+	this.__defineGetter__("Zero", function()
+	{
+		return this.coefficients[0] == 0;
+	});
+	this.__defineGetter__("Degree", function()
+	{
+		return this.coefficients.length - 1;
+	});
+	this.__defineGetter__("Coefficients", function()
+	{
+		return this.coefficients;
+	});
+	
+	this.getCoefficient=function( degree)
+	{
+		return this.coefficients[this.coefficients.length - 1 - degree];
+	}
+	
+	this.evaluateAt=function( a)
+	{
+		if (a == 0)
+		{
+			// Just return the x^0 coefficient
+			return this.getCoefficient(0);
+		}
+		var size = this.coefficients.length;
+		if (a == 1)
+		{
+			// Just the sum of the coefficients
+			var result = 0;
+			for (var i = 0; i < size; i++)
+			{
+				result = GF256.addOrSubtract(result, this.coefficients[i]);
+			}
+			return result;
+		}
+		var result2 = this.coefficients[0];
+		for (var i = 1; i < size; i++)
+		{
+			result2 = GF256.addOrSubtract(this.field.multiply(a, result2), this.coefficients[i]);
+		}
+		return result2;
+	}
+	
+	this.addOrSubtract=function( other)
+		{
+			if (this.field != other.field)
+			{
+				throw "GF256Polys do not have same GF256 field";
+			}
+			if (this.Zero)
+			{
+				return other;
+			}
+			if (other.Zero)
+			{
+				return this;
+			}
+			
+			var smallerCoefficients = this.coefficients;
+			var largerCoefficients = other.coefficients;
+			if (smallerCoefficients.length > largerCoefficients.length)
+			{
+				var temp = smallerCoefficients;
+				smallerCoefficients = largerCoefficients;
+				largerCoefficients = temp;
+			}
+			var sumDiff = new Array(largerCoefficients.length);
+			var lengthDiff = largerCoefficients.length - smallerCoefficients.length;
+			// Copy high-order terms only found in higher-degree polynomial's coefficients
+			//Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
+			for(var ci=0;ci<lengthDiff;ci++)sumDiff[ci]=largerCoefficients[ci];
+			
+			for (var i = lengthDiff; i < largerCoefficients.length; i++)
+			{
+				sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
+			}
+			
+			return new GF256Poly(field, sumDiff);
+	}
+	this.multiply1=function( other)
+		{
+			if (this.field!=other.field)
+			{
+				throw "GF256Polys do not have same GF256 field";
+			}
+			if (this.Zero || other.Zero)
+			{
+				return this.field.Zero;
+			}
+			var aCoefficients = this.coefficients;
+			var aLength = aCoefficients.length;
+			var bCoefficients = other.coefficients;
+			var bLength = bCoefficients.length;
+			var product = new Array(aLength + bLength - 1);
+			for (var i = 0; i < aLength; i++)
+			{
+				var aCoeff = aCoefficients[i];
+				for (var j = 0; j < bLength; j++)
+				{
+					product[i + j] = GF256.addOrSubtract(product[i + j], this.field.multiply(aCoeff, bCoefficients[j]));
+				}
+			}
+			return new GF256Poly(this.field, product);
+		}
+	this.multiply2=function( scalar)
+		{
+			if (scalar == 0)
+			{
+				return this.field.Zero;
+			}
+			if (scalar == 1)
+			{
+				return this;
+			}
+			var size = this.coefficients.length;
+			var product = new Array(size);
+			for (var i = 0; i < size; i++)
+			{
+				product[i] = this.field.multiply(this.coefficients[i], scalar);
+			}
+			return new GF256Poly(this.field, product);
+		}
+	this.multiplyByMonomial=function( degree,  coefficient)
+		{
+			if (degree < 0)
+			{
+				throw "System.ArgumentException";
+			}
+			if (coefficient == 0)
+			{
+				return this.field.Zero;
+			}
+			var size = this.coefficients.length;
+			var product = new Array(size + degree);
+			for(var i=0;i<product.length;i++)product[i]=0;
+			for (var i = 0; i < size; i++)
+			{
+				product[i] = this.field.multiply(this.coefficients[i], coefficient);
+			}
+			return new GF256Poly(this.field, product);
+		}
+	this.divide=function( other)
+		{
+			if (this.field!=other.field)
+			{
+				throw "GF256Polys do not have same GF256 field";
+			}
+			if (other.Zero)
+			{
+				throw "Divide by 0";
+			}
+			
+			var quotient = this.field.Zero;
+			var remainder = this;
+			
+			var denominatorLeadingTerm = other.getCoefficient(other.Degree);
+			var inverseDenominatorLeadingTerm = this.field.inverse(denominatorLeadingTerm);
+			
+			while (remainder.Degree >= other.Degree && !remainder.Zero)
+			{
+				var degreeDifference = remainder.Degree - other.Degree;
+				var scale = this.field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm);
+				var term = other.multiplyByMonomial(degreeDifference, scale);
+				var iterationQuotient = this.field.buildMonomial(degreeDifference, scale);
+				quotient = quotient.addOrSubtract(iterationQuotient);
+				remainder = remainder.addOrSubtract(term);
+			}
+			
+			return new Array(quotient, remainder);
+		}
+}

+ 152 - 0
js/grid.js

@@ -0,0 +1,152 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+var GridSampler = {};
+
+GridSampler.checkAndNudgePoints=function( image,  points)
+		{
+			var width = qrcode.width;
+			var height = qrcode.height;
+			// Check and nudge points from start until we see some that are OK:
+			var nudged = true;
+			for (var offset = 0; offset < points.length && nudged; offset += 2)
+			{
+				var x = Math.floor (points[offset]);
+				var y = Math.floor( points[offset + 1]);
+				if (x < - 1 || x > width || y < - 1 || y > height)
+				{
+					throw "Error.checkAndNudgePoints ";
+				}
+				nudged = false;
+				if (x == - 1)
+				{
+					points[offset] = 0.0;
+					nudged = true;
+				}
+				else if (x == width)
+				{
+					points[offset] = width - 1;
+					nudged = true;
+				}
+				if (y == - 1)
+				{
+					points[offset + 1] = 0.0;
+					nudged = true;
+				}
+				else if (y == height)
+				{
+					points[offset + 1] = height - 1;
+					nudged = true;
+				}
+			}
+			// Check and nudge points from end:
+			nudged = true;
+			for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2)
+			{
+				var x = Math.floor( points[offset]);
+				var y = Math.floor( points[offset + 1]);
+				if (x < - 1 || x > width || y < - 1 || y > height)
+				{
+					throw "Error.checkAndNudgePoints ";
+				}
+				nudged = false;
+				if (x == - 1)
+				{
+					points[offset] = 0.0;
+					nudged = true;
+				}
+				else if (x == width)
+				{
+					points[offset] = width - 1;
+					nudged = true;
+				}
+				if (y == - 1)
+				{
+					points[offset + 1] = 0.0;
+					nudged = true;
+				}
+				else if (y == height)
+				{
+					points[offset + 1] = height - 1;
+					nudged = true;
+				}
+			}
+		}
+	
+
+
+GridSampler.sampleGrid3=function( image,  dimension,  transform)
+		{
+			var bits = new BitMatrix(dimension);
+			var points = new Array(dimension << 1);
+			for (var y = 0; y < dimension; y++)
+			{
+				var max = points.length;
+				var iValue =  y + 0.5;
+				for (var x = 0; x < max; x += 2)
+				{
+					points[x] =  (x >> 1) + 0.5;
+					points[x + 1] = iValue;
+				}
+				transform.transformPoints1(points);
+				// Quick check to see if points transformed to something inside the image;
+				// sufficient to check the endpoints
+				GridSampler.checkAndNudgePoints(image, points);
+				try
+				{
+					for (var x = 0; x < max; x += 2)
+					{
+						//var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4);
+                        var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])];
+						//qrcode.imagedata.data[xpoint] = bit?255:0;
+						//qrcode.imagedata.data[xpoint+1] = bit?255:0;
+						//qrcode.imagedata.data[xpoint+2] = 0;
+						//qrcode.imagedata.data[xpoint+3] = 255;
+						//bits[x >> 1][ y]=bit;
+						if(bit)
+							bits.set_Renamed(x >> 1, y);
+					}
+				}
+				catch ( aioobe)
+				{
+					// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
+					// transform gets "twisted" such that it maps a straight line of points to a set of points
+					// whose endpoints are in bounds, but others are not. There is probably some mathematical
+					// way to detect this about the transformation that I don't know yet.
+					// This results in an ugly runtime exception despite our clever checks above -- can't have
+					// that. We could check each point's coordinates but that feels duplicative. We settle for
+					// catching and wrapping ArrayIndexOutOfBoundsException.
+					throw "Error.checkAndNudgePoints";
+				}
+			}
+			return bits;
+		}
+
+GridSampler.sampleGridx=function( image,  dimension,  p1ToX,  p1ToY,  p2ToX,  p2ToY,  p3ToX,  p3ToY,  p4ToX,  p4ToY,  p1FromX,  p1FromY,  p2FromX,  p2FromY,  p3FromX,  p3FromY,  p4FromX,  p4FromY)
+{
+	var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
+			
+	return GridSampler.sampleGrid3(image, dimension, transform);
+}

+ 455 - 0
js/qrcode.js

@@ -0,0 +1,455 @@
+/*
+   Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info)
+   
+   Licensed 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.
+*/
+
+
+var qrcode = {};
+qrcode.imagedata = null;
+qrcode.width = 0;
+qrcode.height = 0;
+qrcode.qrCodeSymbol = null;
+qrcode.debug = false;
+qrcode.maxImgSize = 1024*1024;
+
+qrcode.sizeOfDataLengthInfo =  [  [ 10, 9, 8, 8 ],  [ 12, 11, 16, 10 ],  [ 14, 13, 16, 12 ] ];
+
+qrcode.callback = null;
+
+qrcode.vidSuccess = function (stream) 
+{
+    qrcode.localstream = stream;
+    if(qrcode.webkit)
+        qrcode.video.src = window.webkitURL.createObjectURL(stream);
+    else
+    if(qrcode.moz)
+    {
+        qrcode.video.mozSrcObject = stream;
+        qrcode.video.play();
+    }
+    else
+        qrcode.video.src = stream;
+    
+    qrcode.gUM=true;
+    
+    qrcode.canvas_qr2 = document.createElement('canvas');
+    qrcode.canvas_qr2.id = "qr-canvas";
+    qrcode.qrcontext2 = qrcode.canvas_qr2.getContext('2d');
+    qrcode.canvas_qr2.width = qrcode.video.videoWidth;
+    qrcode.canvas_qr2.height = qrcode.video.videoHeight;
+    setTimeout(qrcode.captureToCanvas, 500);
+}
+        
+qrcode.vidError = function(error)
+{
+    qrcode.gUM=false;
+    return;
+}
+
+qrcode.captureToCanvas = function()
+{
+    if(qrcode.gUM)
+    {
+        try{
+            if(qrcode.video.videoWidth == 0)
+            {
+                setTimeout(qrcode.captureToCanvas, 500);
+                return;
+            }
+            else
+            {
+                qrcode.canvas_qr2.width = qrcode.video.videoWidth;
+                qrcode.canvas_qr2.height = qrcode.video.videoHeight;
+            }
+            qrcode.qrcontext2.drawImage(qrcode.video,0,0);
+            try{
+                qrcode.decode();
+            }
+            catch(e){       
+                console.log(e);
+                setTimeout(qrcode.captureToCanvas, 500);
+            };
+        }
+        catch(e){       
+                console.log(e);
+                setTimeout(qrcode.captureToCanvas, 500);
+        };
+    }
+}
+
+qrcode.setWebcam = function(videoId)
+{
+    var n=navigator;
+    qrcode.video=document.getElementById(videoId);
+
+    var options = true;
+    if(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices)
+    {
+        try{
+            navigator.mediaDevices.enumerateDevices()
+            .then(function(devices) {
+              devices.forEach(function(device) {
+                console.log("deb1");
+                if (device.kind === 'videoinput') {
+                  if(device.label.toLowerCase().search("back") >-1)
+                    options=[{'sourceId': device.deviceId}] ;
+                }
+                console.log(device.kind + ": " + device.label +
+                            " id = " + device.deviceId);
+              });
+            })
+            
+        }
+        catch(e)
+        {
+            console.log(e);
+        }
+    }
+    else{
+        console.log("no navigator.mediaDevices.enumerateDevices" );
+    }
+    
+    if(n.getUserMedia)
+        n.getUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
+    else
+    if(n.webkitGetUserMedia)
+    {
+        qrcode.webkit=true;
+        n.webkitGetUserMedia({video:options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
+    }
+    else
+    if(n.mozGetUserMedia)
+    {
+        qrcode.moz=true;
+        n.mozGetUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
+    }
+}
+
+qrcode.decode = function(src){
+    
+    if(arguments.length==0)
+    {
+        if(qrcode.canvas_qr2)
+        {
+            var canvas_qr = qrcode.canvas_qr2;
+            var context = qrcode.qrcontext2;
+        }	
+        else
+        {
+            var canvas_qr = document.getElementById("qr-canvas");
+            var context = canvas_qr.getContext('2d');
+        }
+        qrcode.width = canvas_qr.width;
+        qrcode.height = canvas_qr.height;
+        qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height);
+        qrcode.result = qrcode.process(context);
+        if(qrcode.callback!=null)
+            qrcode.callback(qrcode.result);
+        return qrcode.result;
+    }
+    else
+    {
+        var image = new Image();
+        image.crossOrigin = "Anonymous";
+        image.onload=function(){
+            //var canvas_qr = document.getElementById("qr-canvas");
+            var canvas_out = document.getElementById("out-canvas");
+            if(canvas_out!=null)
+            {
+                var outctx = canvas_out.getContext('2d');
+                outctx.clearRect(0, 0, 320, 240);
+                outctx.drawImage(image, 0, 0, 320, 240);
+            }
+
+            var canvas_qr = document.createElement('canvas');
+            var context = canvas_qr.getContext('2d');
+            var nheight = image.height;
+            var nwidth = image.width;
+            if(image.width*image.height>qrcode.maxImgSize)
+            {
+                var ir = image.width / image.height;
+                nheight = Math.sqrt(qrcode.maxImgSize/ir);
+                nwidth=ir*nheight;
+            }
+
+            canvas_qr.width = nwidth;
+            canvas_qr.height = nheight;
+            
+            context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height );
+            qrcode.width = canvas_qr.width;
+            qrcode.height = canvas_qr.height;
+            try{
+                qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height);
+            }catch(e){
+                qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!";
+                if(qrcode.callback!=null)
+                    qrcode.callback(qrcode.result);
+                return;
+            }
+            
+            try
+            {
+                qrcode.result = qrcode.process(context);
+            }
+            catch(e)
+            {
+                console.log(e);
+                qrcode.result = "error decoding QR Code";
+            }
+            if(qrcode.callback!=null)
+                qrcode.callback(qrcode.result);
+        }
+        image.onerror = function ()
+        {
+            if(qrcode.callback!=null) 
+                qrcode.callback("Failed to load the image");
+        }
+        image.src = src;
+    }
+}
+
+qrcode.isUrl = function(s)
+{
+    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
+    return regexp.test(s);
+}
+
+qrcode.decode_url = function (s)
+{
+  var escaped = "";
+  try{
+    escaped = escape( s );
+  }
+  catch(e)
+  {
+    console.log(e);
+    escaped = s;
+  }
+  var ret = "";
+  try{
+    ret = decodeURIComponent( escaped );
+  }
+  catch(e)
+  {
+    console.log(e);
+    ret = escaped;
+  }
+  return ret;
+}
+
+qrcode.decode_utf8 = function ( s )
+{
+    if(qrcode.isUrl(s))
+        return qrcode.decode_url(s);
+    else
+        return s;
+}
+
+qrcode.process = function(ctx){
+    
+    var start = new Date().getTime();
+
+    var image = qrcode.grayScaleToBitmap(qrcode.grayscale());
+    //var image = qrcode.binarize(128);
+    
+    if(qrcode.debug)
+    {
+        for (var y = 0; y < qrcode.height; y++)
+        {
+            for (var x = 0; x < qrcode.width; x++)
+            {
+                var point = (x * 4) + (y * qrcode.width * 4);
+                qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0;
+                qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0;
+                qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0;
+            }
+        }
+        ctx.putImageData(qrcode.imagedata, 0, 0);
+    }
+    
+    //var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image);
+    
+    var detector = new Detector(image);
+
+    var qRCodeMatrix = detector.detect();
+    
+    if(qrcode.debug)
+    {
+        for (var y = 0; y < qRCodeMatrix.bits.Height; y++)
+        {
+            for (var x = 0; x < qRCodeMatrix.bits.Width; x++)
+            {
+                var point = (x * 4*2) + (y*2 * qrcode.width * 4);
+                qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
+                qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
+                qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0;
+            }
+        }
+        ctx.putImageData(qrcode.imagedata, 0, 0);
+    }
+    
+    
+    var reader = Decoder.decode(qRCodeMatrix.bits);
+    var data = reader.DataByte;
+    var str="";
+    for(var i=0;i<data.length;i++)
+    {
+        for(var j=0;j<data[i].length;j++)
+            str+=String.fromCharCode(data[i][j]);
+    }
+    
+    var end = new Date().getTime();
+    var time = end - start;
+    console.log(time);
+    
+    return qrcode.decode_utf8(str);
+    //alert("Time:" + time + " Code: "+str);
+}
+
+qrcode.getPixel = function(x,y){
+    if (qrcode.width < x) {
+        throw "point error";
+    }
+    if (qrcode.height < y) {
+        throw "point error";
+    }
+    var point = (x * 4) + (y * qrcode.width * 4);
+    var p = (qrcode.imagedata.data[point]*33 + qrcode.imagedata.data[point + 1]*34 + qrcode.imagedata.data[point + 2]*33)/100;
+    return p;
+}
+
+qrcode.binarize = function(th){
+    var ret = new Array(qrcode.width*qrcode.height);
+    for (var y = 0; y < qrcode.height; y++)
+    {
+        for (var x = 0; x < qrcode.width; x++)
+        {
+            var gray = qrcode.getPixel(x, y);
+            
+            ret[x+y*qrcode.width] = gray<=th?true:false;
+        }
+    }
+    return ret;
+}
+
+qrcode.getMiddleBrightnessPerArea=function(image)
+{
+    var numSqrtArea = 4;
+    //obtain middle brightness((min + max) / 2) per area
+    var areaWidth = Math.floor(qrcode.width / numSqrtArea);
+    var areaHeight = Math.floor(qrcode.height / numSqrtArea);
+    var minmax = new Array(numSqrtArea);
+    for (var i = 0; i < numSqrtArea; i++)
+    {
+        minmax[i] = new Array(numSqrtArea);
+        for (var i2 = 0; i2 < numSqrtArea; i2++)
+        {
+            minmax[i][i2] = new Array(0,0);
+        }
+    }
+    for (var ay = 0; ay < numSqrtArea; ay++)
+    {
+        for (var ax = 0; ax < numSqrtArea; ax++)
+        {
+            minmax[ax][ay][0] = 0xFF;
+            for (var dy = 0; dy < areaHeight; dy++)
+            {
+                for (var dx = 0; dx < areaWidth; dx++)
+                {
+                    var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*qrcode.width];
+                    if (target < minmax[ax][ay][0])
+                        minmax[ax][ay][0] = target;
+                    if (target > minmax[ax][ay][1])
+                        minmax[ax][ay][1] = target;
+                }
+            }
+            //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
+        }
+    }
+    var middle = new Array(numSqrtArea);
+    for (var i3 = 0; i3 < numSqrtArea; i3++)
+    {
+        middle[i3] = new Array(numSqrtArea);
+    }
+    for (var ay = 0; ay < numSqrtArea; ay++)
+    {
+        for (var ax = 0; ax < numSqrtArea; ax++)
+        {
+            middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2);
+            //Console.out.print(middle[ax][ay] + ",");
+        }
+        //Console.out.println("");
+    }
+    //Console.out.println("");
+    
+    return middle;
+}
+
+qrcode.grayScaleToBitmap=function(grayScale)
+{
+    var middle = qrcode.getMiddleBrightnessPerArea(grayScale);
+    var sqrtNumArea = middle.length;
+    var areaWidth = Math.floor(qrcode.width / sqrtNumArea);
+    var areaHeight = Math.floor(qrcode.height / sqrtNumArea);
+
+    var buff = new ArrayBuffer(qrcode.width*qrcode.height);
+    var bitmap = new Uint8Array(buff);
+
+    //var bitmap = new Array(qrcode.height*qrcode.width);
+    
+    for (var ay = 0; ay < sqrtNumArea; ay++)
+    {
+        for (var ax = 0; ax < sqrtNumArea; ax++)
+        {
+            for (var dy = 0; dy < areaHeight; dy++)
+            {
+                for (var dx = 0; dx < areaWidth; dx++)
+                {
+                    bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false;
+                }
+            }
+        }
+    }
+    return bitmap;
+}
+
+qrcode.grayscale = function()
+{
+    var buff = new ArrayBuffer(qrcode.width*qrcode.height);
+    var ret = new Uint8Array(buff);
+    //var ret = new Array(qrcode.width*qrcode.height);
+    
+    for (var y = 0; y < qrcode.height; y++)
+    {
+        for (var x = 0; x < qrcode.width; x++)
+        {
+            var gray = qrcode.getPixel(x, y);
+            
+            ret[x+y*qrcode.width] = gray;
+        }
+    }
+    return ret;
+}
+
+
+
+
+function URShift( number,  bits)
+{
+    if (number >= 0)
+        return number >> bits;
+    else
+        return (number >> bits) + (2 << ~bits);
+}
+

+ 178 - 0
js/rsdecoder.js

@@ -0,0 +1,178 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+function ReedSolomonDecoder(field)
+{
+	this.field = field;
+	this.decode=function(received,  twoS)
+	{
+			var poly = new GF256Poly(this.field, received);
+			var syndromeCoefficients = new Array(twoS);
+			for(var i=0;i<syndromeCoefficients.length;i++)syndromeCoefficients[i]=0;
+			var dataMatrix = false;//this.field.Equals(GF256.DATA_MATRIX_FIELD);
+			var noError = true;
+			for (var i = 0; i < twoS; i++)
+			{
+				// Thanks to sanfordsquires for this fix:
+				var evalu = poly.evaluateAt(this.field.exp(dataMatrix?i + 1:i));
+				syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalu;
+				if (evalu != 0)
+				{
+					noError = false;
+				}
+			}
+			if (noError)
+			{
+				return ;
+			}
+			var syndrome = new GF256Poly(this.field, syndromeCoefficients);
+			var sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(twoS, 1), syndrome, twoS);
+			var sigma = sigmaOmega[0];
+			var omega = sigmaOmega[1];
+			var errorLocations = this.findErrorLocations(sigma);
+			var errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations, dataMatrix);
+			for (var i = 0; i < errorLocations.length; i++)
+			{
+				var position = received.length - 1 - this.field.log(errorLocations[i]);
+				if (position < 0)
+				{
+					throw "ReedSolomonException Bad error location";
+				}
+				received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]);
+			}
+	}
+	
+	this.runEuclideanAlgorithm=function( a,  b,  R)
+		{
+			// Assume a's degree is >= b's
+			if (a.Degree < b.Degree)
+			{
+				var temp = a;
+				a = b;
+				b = temp;
+			}
+			
+			var rLast = a;
+			var r = b;
+			var sLast = this.field.One;
+			var s = this.field.Zero;
+			var tLast = this.field.Zero;
+			var t = this.field.One;
+			
+			// Run Euclidean algorithm until r's degree is less than R/2
+			while (r.Degree >= Math.floor(R / 2))
+			{
+				var rLastLast = rLast;
+				var sLastLast = sLast;
+				var tLastLast = tLast;
+				rLast = r;
+				sLast = s;
+				tLast = t;
+				
+				// Divide rLastLast by rLast, with quotient in q and remainder in r
+				if (rLast.Zero)
+				{
+					// Oops, Euclidean algorithm already terminated?
+					throw "r_{i-1} was zero";
+				}
+				r = rLastLast;
+				var q = this.field.Zero;
+				var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree);
+				var dltInverse = this.field.inverse(denominatorLeadingTerm);
+				while (r.Degree >= rLast.Degree && !r.Zero)
+				{
+					var degreeDiff = r.Degree - rLast.Degree;
+					var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse);
+					q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale));
+					r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
+					//r.EXE();
+				}
+				
+				s = q.multiply1(sLast).addOrSubtract(sLastLast);
+				t = q.multiply1(tLast).addOrSubtract(tLastLast);
+			}
+			
+			var sigmaTildeAtZero = t.getCoefficient(0);
+			if (sigmaTildeAtZero == 0)
+			{
+				throw "ReedSolomonException sigmaTilde(0) was zero";
+			}
+			
+			var inverse = this.field.inverse(sigmaTildeAtZero);
+			var sigma = t.multiply2(inverse);
+			var omega = r.multiply2(inverse);
+			return new Array(sigma, omega);
+		}
+	this.findErrorLocations=function( errorLocator)
+		{
+			// This is a direct application of Chien's search
+			var numErrors = errorLocator.Degree;
+			if (numErrors == 1)
+			{
+				// shortcut
+				return new Array(errorLocator.getCoefficient(1));
+			}
+			var result = new Array(numErrors);
+			var e = 0;
+			for (var i = 1; i < 256 && e < numErrors; i++)
+			{
+				if (errorLocator.evaluateAt(i) == 0)
+				{
+					result[e] = this.field.inverse(i);
+					e++;
+				}
+			}
+			if (e != numErrors)
+			{
+				throw "Error locator degree does not match number of roots";
+			}
+			return result;
+		}
+	this.findErrorMagnitudes=function( errorEvaluator,  errorLocations,  dataMatrix)
+		{
+			// This is directly applying Forney's Formula
+			var s = errorLocations.length;
+			var result = new Array(s);
+			for (var i = 0; i < s; i++)
+			{
+				var xiInverse = this.field.inverse(errorLocations[i]);
+				var denominator = 1;
+				for (var j = 0; j < s; j++)
+				{
+					if (i != j)
+					{
+						denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse)));
+					}
+				}
+				result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator));
+				// Thanks to sanfordsquires for this fix:
+				if (dataMatrix)
+				{
+					result[i] = this.field.multiply(result[i], xiInverse);
+				}
+			}
+			return result;
+		}
+}

+ 261 - 0
js/version.js

@@ -0,0 +1,261 @@
+/*
+  Ported to JavaScript by Lazar Laszlo 2011 
+  
+  lazarsoft@gmail.com, www.lazarsoft.info
+  
+*/
+
+/*
+*
+* Copyright 2007 ZXing authors
+*
+* Licensed 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.
+*/
+
+
+
+function ECB(count,  dataCodewords)
+{
+	this.count = count;
+	this.dataCodewords = dataCodewords;
+	
+	this.__defineGetter__("Count", function()
+	{
+		return this.count;
+	});
+	this.__defineGetter__("DataCodewords", function()
+	{
+		return this.dataCodewords;
+	});
+}
+
+function ECBlocks( ecCodewordsPerBlock,  ecBlocks1,  ecBlocks2)
+{
+	this.ecCodewordsPerBlock = ecCodewordsPerBlock;
+	if(ecBlocks2)
+		this.ecBlocks = new Array(ecBlocks1, ecBlocks2);
+	else
+		this.ecBlocks = new Array(ecBlocks1);
+	
+	this.__defineGetter__("ECCodewordsPerBlock", function()
+	{
+		return this.ecCodewordsPerBlock;
+	});
+	
+	this.__defineGetter__("TotalECCodewords", function()
+	{
+		return  this.ecCodewordsPerBlock * this.NumBlocks;
+	});
+	
+	this.__defineGetter__("NumBlocks", function()
+	{
+		var total = 0;
+		for (var i = 0; i < this.ecBlocks.length; i++)
+		{
+			total += this.ecBlocks[i].length;
+		}
+		return total;
+	});
+	
+	this.getECBlocks=function()
+			{
+				return this.ecBlocks;
+			}
+}
+
+function Version( versionNumber,  alignmentPatternCenters,  ecBlocks1,  ecBlocks2,  ecBlocks3,  ecBlocks4)
+{
+	this.versionNumber = versionNumber;
+	this.alignmentPatternCenters = alignmentPatternCenters;
+	this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4);
+	
+	var total = 0;
+	var ecCodewords = ecBlocks1.ECCodewordsPerBlock;
+	var ecbArray = ecBlocks1.getECBlocks();
+	for (var i = 0; i < ecbArray.length; i++)
+	{
+		var ecBlock = ecbArray[i];
+		total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords);
+	}
+	this.totalCodewords = total;
+	
+	this.__defineGetter__("VersionNumber", function()
+	{
+		return  this.versionNumber;
+	});
+	
+	this.__defineGetter__("AlignmentPatternCenters", function()
+	{
+		return  this.alignmentPatternCenters;
+	});
+	this.__defineGetter__("TotalCodewords", function()
+	{
+		return  this.totalCodewords;
+	});
+	this.__defineGetter__("DimensionForVersion", function()
+	{
+		return  17 + 4 * this.versionNumber;
+	});
+	
+	this.buildFunctionPattern=function()
+		{
+			var dimension = this.DimensionForVersion;
+			var bitMatrix = new BitMatrix(dimension);
+			
+			// Top left finder pattern + separator + format
+			bitMatrix.setRegion(0, 0, 9, 9);
+			// Top right finder pattern + separator + format
+			bitMatrix.setRegion(dimension - 8, 0, 8, 9);
+			// Bottom left finder pattern + separator + format
+			bitMatrix.setRegion(0, dimension - 8, 9, 8);
+			
+			// Alignment patterns
+			var max = this.alignmentPatternCenters.length;
+			for (var x = 0; x < max; x++)
+			{
+				var i = this.alignmentPatternCenters[x] - 2;
+				for (var y = 0; y < max; y++)
+				{
+					if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0))
+					{
+						// No alignment patterns near the three finder paterns
+						continue;
+					}
+					bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5);
+				}
+			}
+			
+			// Vertical timing pattern
+			bitMatrix.setRegion(6, 9, 1, dimension - 17);
+			// Horizontal timing pattern
+			bitMatrix.setRegion(9, 6, dimension - 17, 1);
+			
+			if (this.versionNumber > 6)
+			{
+				// Version info, top right
+				bitMatrix.setRegion(dimension - 11, 0, 3, 6);
+				// Version info, bottom left
+				bitMatrix.setRegion(0, dimension - 11, 6, 3);
+			}
+			
+			return bitMatrix;
+		}
+	this.getECBlocksForLevel=function( ecLevel)
+	{
+		return this.ecBlocks[ecLevel.ordinal()];
+	}
+}
+
+Version.VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69);
+
+Version.VERSIONS = buildVersions();
+
+Version.getVersionForNumber=function( versionNumber)
+{
+	if (versionNumber < 1 || versionNumber > 40)
+	{
+		throw "ArgumentException";
+	}
+	return Version.VERSIONS[versionNumber - 1];
+}
+
+Version.getProvisionalVersionForDimension=function(dimension)
+{
+	if (dimension % 4 != 1)
+	{
+		throw "Error getProvisionalVersionForDimension";
+	}
+	try
+	{
+		return Version.getVersionForNumber((dimension - 17) >> 2);
+	}
+	catch ( iae)
+	{
+		throw "Error getVersionForNumber";
+	}
+}
+
+Version.decodeVersionInformation=function( versionBits)
+{
+	var bestDifference = 0xffffffff;
+	var bestVersion = 0;
+	for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++)
+	{
+		var targetVersion = Version.VERSION_DECODE_INFO[i];
+		// Do the version info bits match exactly? done.
+		if (targetVersion == versionBits)
+		{
+			return this.getVersionForNumber(i + 7);
+		}
+		// Otherwise see if this is the closest to a real version info bit string
+		// we have seen so far
+		var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion);
+		if (bitsDifference < bestDifference)
+		{
+			bestVersion = i + 7;
+			bestDifference = bitsDifference;
+		}
+	}
+	// We can tolerate up to 3 bits of error since no two version info codewords will
+	// differ in less than 4 bits.
+	if (bestDifference <= 3)
+	{
+		return this.getVersionForNumber(bestVersion);
+	}
+	// If we didn't find a close enough match, fail
+	return null;
+}
+
+function buildVersions()
+{
+	return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), 
+	new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), 
+	new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), 
+	new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), 
+	new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), 
+	new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), 
+	new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), 
+	new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), 
+	new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), 
+	new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), 
+	new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), 
+	new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), 
+	new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), 
+	new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), 
+	new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), 
+	new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), 
+	new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), 
+	new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), 
+	new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), 
+	new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), 
+	new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), 
+	new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), 
+	new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), 
+	new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), 
+	new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), 
+	new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), 
+	new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), 		new ECB(28, 16))),
+	new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), 
+	new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), 
+	new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), 
+	new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), 
+	new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), 
+	new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), 
+	new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), 
+	new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), 
+	new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), 
+	new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), 
+	new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), 
+	new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), 
+	new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16))));
+}

+ 218 - 0
rx.php

@@ -0,0 +1,218 @@
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<head>
+<title>QuickSend RX</title>
+<link rel="stylesheet" href="tocas.css">
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
+<script type="text/javascript" src="js/grid.js"></script>
+<script type="text/javascript" src="js/version.js"></script>
+<script type="text/javascript" src="js/detector.js"></script>
+<script type="text/javascript" src="js/formatinf.js"></script>
+<script type="text/javascript" src="js/errorlevel.js"></script>
+<script type="text/javascript" src="js/bitmat.js"></script>
+<script type="text/javascript" src="js/datablock.js"></script>
+<script type="text/javascript" src="js/bmparser.js"></script>
+<script type="text/javascript" src="js/datamask.js"></script>
+<script type="text/javascript" src="js/rsdecoder.js"></script>
+<script type="text/javascript" src="js/gf256poly.js"></script>
+<script type="text/javascript" src="js/gf256.js"></script>
+<script type="text/javascript" src="js/decoder.js"></script>
+<script type="text/javascript" src="js/qrcode.js"></script>
+<script type="text/javascript" src="js/findpat.js"></script>
+<script type="text/javascript" src="js/alignpat.js"></script>
+<script type="text/javascript" src="js/databr.js"></script>
+
+<script type="text/javascript">
+function qdecode(){
+	var result = qrcode.decode();
+	if (result.includes("imuslab.com")){
+		window.location.replace(result);
+	}else{
+		alert(result);
+	}
+}
+</script>
+
+</head>
+
+<body>
+<div class="ts inverted heading fluid slate" style="background-color:#2c2835;color:white;">
+    <span class="large header">Quick Send System</span>
+    <span class="description">Send data between mobile and laptops.<br> Powered by IMUS Laboratory</span>
+    <div class="ts bottom attached tabbed menu" style="color:white;">
+        <a class="item" href="index.php" style="color:#9d9ca3;">Send</a>
+        <a class="active item" href="rx.php">Receive</a>
+        <a class="item" href="img.php" style="color:#9d9ca3;">Image</a>
+        <a class="item" href="file.php" style="color:#9d9ca3;">Files</a>
+    </div>
+</div>
+<div class="ts container">
+<br><br>
+<div class="ts stackable grid">
+    <div class="four wide column" align="center">
+		<h4>QuickSend ID</h4>
+		<div class="ts fluid input">
+			<input type="text" id="mid" placeholder="Memo ID" style="width:100%;">
+		</div>
+		<button id="viewbtn"class="ts basic fluid button" onclick="manual_redirect();" >View</button>
+		<div class="ts tiny statistic" onClick="cloneCode();">
+			<div class="label">Latest QSCode Number</div>
+			<div class="value" id="lcode"><?php
+			$max = 0;
+			foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+				if ($fileInfo->isDot()) continue;
+				$current = pathinfo($fileInfo->getFilename())['filename'];
+				if (!is_numeric($current)) continue;
+				if ($current > $max) $max = $current;
+			}
+			echo $max;
+			?></div>
+		</div>
+		
+	</div>
+    <div class="twelve wide column">
+		<h4>QR-Code ID</h4>
+			<form>
+				<div>
+					<input class="ts button" type="file" accept="image/*" id="file-input" capture="camera">
+				</div>
+			</form>
+		<canvas id="qr-canvas" width="256px" height="256px" style="display:none;"></canvas>
+		<canvas id="preview-canvas" width="256px" height="256px"></canvas>
+		<div class="ts container" align="right">
+			<button class="ts basic button" onclick="qdecode()">Decode</button>
+		</div>
+	</div>
+</div>
+
+
+<br><br><br><br><br><br>
+
+
+<div style="position: fixed;
+    z-index: 100; 
+    bottom: 0; 
+    left: 0;
+    width: 100%;
+	background-color:#2c2835;
+	color:white;">
+<div class="ts container">
+<img class="ts tiny right floated image" src="img/cube.png"></img>
+</div>
+<div align="left" class="ts container">
+<br>
+CopyRight IMUS Laboratory 2018, All right reserved.
+</div>
+</div>
+
+
+</div>
+<script>
+$("#viewbtn").keyup(function(event) {
+    if (event.keyCode == 13) {
+        manual_redirect();
+    }
+});
+
+function resizeCanvasImage(img, canvas, maxWidth, maxHeight) {
+    var imgWidth = img.width, 
+        imgHeight = img.height;
+
+    var ratio = 1, ratio1 = 1, ratio2 = 1;
+    ratio1 = maxWidth / imgWidth;
+    ratio2 = maxHeight / imgHeight;
+
+    // Use the smallest ratio that the image best fit into the maxWidth x maxHeight box.
+    if (ratio1 < ratio2) {
+        ratio = ratio1;
+    }
+    else {
+        ratio = ratio2;
+    }
+
+    var canvasContext = canvas.getContext("2d");
+    var canvasCopy = document.createElement("canvas");
+    var copyContext = canvasCopy.getContext("2d");
+    var canvasCopy2 = document.createElement("canvas");
+    var copyContext2 = canvasCopy2.getContext("2d");
+    canvasCopy.width = imgWidth;
+    canvasCopy.height = imgHeight;  
+    copyContext.drawImage(img, 0, 0);
+
+    // init
+    canvasCopy2.width = imgWidth;
+    canvasCopy2.height = imgHeight;        
+    copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);
+
+
+    var rounds = 2;
+    var roundRatio = ratio * rounds;
+    for (var i = 1; i <= rounds; i++) {
+        console.log("Step: "+i);
+
+        // tmp
+        canvasCopy.width = imgWidth * roundRatio / i;
+        canvasCopy.height = imgHeight * roundRatio / i;
+
+        copyContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvasCopy.width, canvasCopy.height);
+
+        // copy back
+        canvasCopy2.width = imgWidth * roundRatio / i;
+        canvasCopy2.height = imgHeight * roundRatio / i;
+        copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);
+
+    } // end for
+
+
+    // copy back to canvas
+    canvas.width = imgWidth * roundRatio / rounds;
+    canvas.height = imgHeight * roundRatio / rounds;
+    canvasContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvas.width, canvas.height);
+
+
+}
+
+
+$(function() {
+    $('#file-input').change(function(e) {
+        var file = e.target.files[0],
+            imageType = /image.*/;
+
+        if (!file.type.match(imageType))
+            return;
+
+        var reader = new FileReader();
+        reader.onload = fileOnload;
+        reader.readAsDataURL(file);
+    });
+
+    function fileOnload(e) {
+        var $img = $('<img>', { src: e.target.result });
+        $img.load(function() {
+            var canvas = $('#qr-canvas')[0];
+            var context = canvas.getContext('2d');
+
+            canvas.width = this.naturalWidth;
+            canvas.height = this.naturalHeight;
+            context.drawImage(this, 0, 0);
+			//grab the context from your destination canvas
+			var pcanvas = $('#preview-canvas')[0];
+			var destCtx = pcanvas.getContext('2d');
+			//call its drawImage() function passing it the source canvas directly
+			destCtx.drawImage(canvas, 0, 0, 256, 256 * this.height / this.width);
+        });
+    }
+});
+
+function manual_redirect(){
+	var id = $("#mid").val();
+	window.location.replace("http://imuslab.com/qs/display.php?id=" + id);
+}
+
+function cloneCode(){
+	$("#mid").val($("#lcode").html());
+}
+
+</script>
+</body>
+</html>

File diff suppressed because it is too large
+ 0 - 0
tocas.css


+ 1424 - 0
tocas.js

@@ -0,0 +1,1424 @@
+// Generated by CoffeeScript 2.0.0-beta4
+(function() {
+  // 主要的選擇器函式。
+  var ts;
+
+  ts = function(selector, context) {
+    var nodes, ref, tag;
+    nodes = [];
+    // 如果選擇器是文字,但是是標籤(如:`<div>`)就建立新的元素
+    if (typeof selector === 'string' && selector[0] === '<') {
+      tag = selector.match(/<(.*)\/>|<(.*)>/);
+      nodes = [document.createElement((ref = tag[1]) != null ? ref : tag[2])];
+    // 如果選擇器是一般的文字,就選取元素。
+    } else if (typeof selector === 'string' && context === void 0) {
+      document.querySelectorAll(selector).forEach(function(element) {
+        return nodes.push(element);
+      });
+    // 如果選擇器有上下文選擇器,就透過選擇器找出上下文元素。
+    } else if (typeof context === 'string') {
+      nodes = ts(selector).find(context).toArray();
+    // 如果選擇器是 NodeList 就轉換成元素陣列然後取出來接著繼續。
+    } else if (selector instanceof NodeList) {
+      selector.forEach(function(element) {
+        return nodes.push(element);
+      });
+    // 如果選擇器是陣列,就當作是元素陣列,取出來然後繼續。
+    // 或傳入的是一個選擇器,就取出裡面的元素然後繼續。
+    } else if (Array.isArray(selector) || (selector != null ? selector.isSelector : void 0) === true) {
+      nodes = nodes.concat(selector);
+      selector = selector.selector;
+      context = selector != null ? selector.context : void 0;
+    // 如果是單個 DOM 元素,就放入選擇器然後繼續。
+    } else if (selector instanceof HTMLElement || selector instanceof HTMLDocument || selector instanceof HTMLBodyElement || selector === window) {
+      nodes = [selector];
+    }
+    // 保存目前的選擇器文字與上下文選擇器文字。
+    nodes.selector = typeof selector === 'string' ? selector : null;
+    nodes.context = typeof context === 'string' ? context : null;
+    // 將自訂的選擇器方法插入到節點陣列中,這樣才能夠串連使用。
+    Object.defineProperties(nodes, ts.fn);
+    // 將節點陣列標註為是選擇器,這樣才能判斷傳入的是不是我們自己的選擇器。
+    Object.defineProperty(nodes, 'isSelector', {
+      value: true
+    });
+    return nodes;
+  };
+
+  // 註冊到視窗上。
+  window.ts = ts;
+
+  // 函式鏈。
+  ts.fn = {};
+
+  // 輔助函式。
+  ts.helper = {};
+
+  // 事件輔助函式。
+  ts.helper.eventAlias = function(event) {
+    var alias, pair;
+    pair = event.split('.');
+    alias = pair[1] !== void 0 ? `.${pair[1]}` : '';
+    switch (false) {
+      case pair.indexOf('animationend') === -1:
+        return `webkitAnimationEnd${alias} mozAnimationEnd${alias} MSAnimationEnd${alias} oanimationend${alias} animationend${alias}`;
+      case pair.indexOf('transitionend') === -1:
+        return `webkitTransitionEnd${alias} mozTransitionEnd${alias} oTransitionEnd${alias} msTransitionEnd${alias} transitionend${alias}`;
+      default:
+        return event;
+    }
+  };
+
+  // 是否為物件。
+  ts.isPlainObject = function(object) {
+    return Object.prototype.toString.call(object) === '[object Object]';
+  };
+
+  // 是否為可觸控裝置。
+  ts.isTouchDevice = function() {
+    return 'ontouchstart' in window || navigator.maxTouchPoints;
+  };
+
+  // 延展物件的函式,與 ES 的 `...` 不同之處在於 extend 並不會替換掉整個子物件,而會以補插的方式執行。
+  // https://gomakethings.com/vanilla-javascript-version-of-jquery-extend/
+  ts.extend = function() {
+    var deep, extended, i, length, merge, obj;
+    extended = {};
+    deep = true;
+    i = 0;
+    length = arguments.length;
+    if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') {
+      deep = arguments[0];
+      i++;
+    }
+    merge = function(obj) {
+      var prop;
+      for (prop in obj) {
+        if (Object.prototype.hasOwnProperty.call(obj, prop)) {
+          if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
+            extended[prop] = ts.extend(true, extended[prop], obj[prop]);
+          } else {
+            extended[prop] = obj[prop];
+          }
+        }
+      }
+    };
+    while (i < length) {
+      obj = arguments[i];
+      merge(obj);
+      i++;
+    }
+    return extended;
+  };
+
+  // 建立元素
+  ts.createElement = (html) => {
+    var div;
+    div = document.createElement('div');
+    div.innerHTML = html.trim();
+    return div.firstChild;
+  };
+
+  // 註冊 Tocas 模塊
+  ts.register = ({NAME, MODULE_NAMESPACE, Settings}, starter) => {
+    return ts.fn[NAME] = {
+      value: function(parameters) {
+        var $allModules, consoleText, errorHeaderCSS, headerCSS, messageCSS, methodInvoked, query, queryArguments, returnedValue;
+        $allModules = ts(this);
+        query = arguments[0];
+        queryArguments = [].slice.call(arguments, 1);
+        methodInvoked = typeof query === 'string';
+        returnedValue = void 0;
+        consoleText = (args) => {
+          //currentdate = new Date();
+          //datetime = "#{currentdate.getFullYear()}/#{(currentdate.getMonth()+1)}/#{currentdate.getDate()}/@#{currentdate.getHours()}:#{currentdate.getMinutes()}:#{currentdate.getSeconds()}"
+          return `%c${NAME}%c ${args[0]}`;
+        };
+        headerCSS = "background   : #EEE;\ncolor        : #5A5A5A;\nfont-size    : 1em;\npadding      : 8px 8px;\nline-height  : 5px;\nmargin       : 5px 0 5px 0;\nborder-radius: 1000em;";
+        errorHeaderCSS = `${headerCSS}\nbackground: #CE5F58;\ncolor: #FFF;`;
+        messageCSS = "font-weight: bold;";
+        $allModules.each(function(_, index) {
+          var $this, debug, element, error, initialize, instance, instantiate, invoke, module, observeChanges, settings;
+          $this = ts(this);
+          element = this;
+          instance = $this.data(MODULE_NAMESPACE);
+          settings = ts.isPlainObject(parameters) ? ts.extend(Settings, parameters) : ts.extend(Settings);
+          debug = function() {
+            if (!settings.debug || settings.silent) {
+              return;
+            }
+            return console.info.call(console, consoleText(arguments), headerCSS, messageCSS, "\n", ...Array.prototype.slice.call(arguments).slice(1));
+          };
+          error = function() {
+            if (settings.silent) {
+              return;
+            }
+            error = Function.prototype.bind.call(console.error, console, consoleText(arguments), errorHeaderCSS, messageCSS);
+            return error.apply(console, Array.prototype.slice.call(arguments, 1));
+          };
+          instantiate = () => {
+            module.instantiate();
+            instance = module;
+            return $this.data(MODULE_NAMESPACE, instance);
+          };
+          initialize = () => {
+            module.initialize();
+            if (settings.observeChanges) {
+              observeChanges();
+            }
+            return instantiate();
+          };
+          observeChanges = () => {
+            var observer;
+            if (!'MutationObserver' in window) {
+              debug('找不到樹狀結構變更觀測者,略過結構監聽動作', element);
+              return;
+            }
+            observer = new MutationObserver((mutations) => {
+              //debug 'DOM 樹狀結構已變更,更新快取資料'
+              return module.refresh();
+            });
+            return observer.observe(element, {
+              childList: true,
+              subtree: true
+            });
+          };
+          //debug '已設置 DOM 樹狀結構異動觀察者', observer
+          invoke = (query, passedArguments, context) => {
+            var camelCaseValue, depth, found, j, len, maxDepth, object, response, value;
+            object = instance;
+            maxDepth = void 0;
+            found = void 0;
+            response = void 0;
+            passedArguments = passedArguments || queryArguments;
+            context = element || context;
+            if (typeof query === 'string' && object !== void 0) {
+              query = query.split(/[\. ]/);
+              maxDepth = query.length - 1;
+              for (depth = j = 0, len = query.length; j < len; depth = ++j) {
+                value = query[depth];
+                camelCaseValue = query;
+                if (depth !== maxDepth) {
+                  camelCaseValue = value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1);
+                }
+                switch (false) {
+                  case !(ts.isPlainObject(object[camelCaseValue]) && depth !== maxDepth):
+                    object = object[camelCaseValue];
+                    break;
+                  case object[camelCaseValue] === void 0:
+                    found = object[camelCaseValue];
+                    break;
+                  case !(ts.isPlainObject(object[value]) && depth !== maxDepth):
+                    object = object[value];
+                    break;
+                  case object[value] === void 0:
+                    found = object[value];
+                    break;
+                  default:
+                    error('欲呼叫的方法並不存在', query);
+                    break;
+                }
+              }
+            }
+            switch (false) {
+              case typeof found !== 'function':
+                response = found.apply(context, passedArguments);
+                break;
+              case found === void 0:
+                response = found;
+            }
+            switch (false) {
+              case response !== $allModules:
+                returnedValue = $allModules;
+                break;
+              default:
+                returnedValue = response;
+            }
+            return found;
+          };
+          module = starter({$allModules, $this, element, debug, settings, instance, index});
+          if (methodInvoked) {
+            if (instance === void 0) {
+              initialize();
+            }
+            return invoke(query);
+          } else {
+            if (instance !== void 0) {
+              invoke('destroy');
+            }
+            return initialize();
+          }
+        });
+        if (returnedValue !== void 0) {
+          return returnedValue;
+        } else {
+          return $allModules;
+        }
+      }
+    };
+  };
+
+  // Get
+
+  // 取得選擇器內的指定元素,並且回傳一個 DOM 元素而非選擇器。
+  ts.fn.get = {
+    value: function(index = 0) {
+      return this[index];
+    }
+  };
+
+  // ToArray
+
+  // 將選擇器轉換成帶有節點的一般陣列。
+  ts.fn.toArray = {
+    value: function() {
+      var array;
+      array = [];
+      this.forEach(function(element) {
+        return array.push(element);
+      });
+      return array;
+    }
+  };
+
+  // Each
+
+  // 遍歷整個選擇器陣列。
+  ts.fn.each = {
+    value: function(callback) {
+      this.forEach(function(element, index) {
+        return callback.call(element, element, index);
+      });
+      return this;
+    }
+  };
+
+  // CollectSwap
+
+  // 將收集到的元素替換掉目前選擇器內的所有元素。
+  ts.fn.collectSwap = {
+    value: function(callback) {
+      var collection, newSelector;
+      collection = [];
+      this.each(function(element, index) {
+        var result;
+        result = callback.call(element, element, index);
+        if (result === void 0 || result === null) {
+          return;
+        }
+        if (result instanceof NodeList) {
+          return result.forEach(function(el) {
+            return collection.push(el);
+          });
+        } else if (Array.isArray(result)) {
+          return collection = collection.concat(result);
+        } else {
+          if (collection.indexOf(result) === -1) {
+            return collection.push(result);
+          }
+        }
+      });
+      // 透過 Set 型態移除重複的節點。
+      collection = new Set(collection);
+      // 然後將 Set 轉換成陣列,建立新的選擇器。
+      newSelector = ts([...collection]);
+      // 保存選擇器之前的所有節點。
+      Object.defineProperty(newSelector, 'prevObject', {
+        value: this
+      });
+      // 回傳這個新的選擇器。
+      return newSelector;
+    }
+  };
+
+  // Eq
+
+  // 取得選擇器的指定元素,然後繼續回傳僅帶有該元素的選擇器。
+  ts.fn.eq = {
+    value: function(index) {
+      return ts(this.get(index));
+    }
+  };
+
+  // Parent
+
+  // 回傳元素的父元素選擇器。
+  ts.fn.parent = {
+    value: function() {
+      return this.collectSwap(function() {
+        return this.parentNode;
+      });
+    }
+  };
+
+  // Closest
+
+  // 回傳最接近指定的父元素選擇器。
+  ts.fn.closest = {
+    value: function(selector) {
+      return this.collectSwap(function() {
+        return this.closest(selector);
+      });
+    }
+  };
+
+  // Find
+
+  // 在目前元素中搜尋指定元素並回傳其選擇器。
+  ts.fn.find = {
+    value: function(selector) {
+      return this.collectSwap(function() {
+        return this.querySelectorAll(selector);
+      });
+    }
+  };
+
+  // Insert Before
+
+  // 將選擇器元素安插在指定元素前。
+  ts.fn.insertBefore = {
+    value: function(target) {
+      return this.each(function() {
+        return ts(target).each((element) => {
+          return element.parentNode.insertBefore(this, element);
+        });
+      });
+    }
+  };
+
+  // Insert After
+
+  // 將選擇器元素安插在指定元素後。
+  ts.fn.insertAfter = {
+    value: function(target) {
+      return this.each(function() {
+        return ts(target).each((element) => {
+          return element.parentNode.insertBefore(this, element.nextSibling);
+        });
+      });
+    }
+  };
+
+  // Wrap
+
+  // 將元素用指定元素包覆起來。
+  ts.fn.wrap = {
+    value: function(element) {
+      return this.each(function() {
+        if (this.nextSibling) {
+          this.parentNode.insertBefore(element, this.nextSibling);
+        } else {
+          this.parentNode.appendChild(element);
+        }
+        return element.appendChild(this);
+      });
+    }
+  };
+
+  // Clone
+
+  // 複製元素。
+  ts.fn.clone = {
+    value: function() {
+      return this.collectSwap(function() {
+        return this.cloneNode(true);
+      });
+    }
+  };
+
+  // Append
+
+  // 將元素插入在目前選擇器元素的內部最後面。
+  ts.fn.append = {
+    value: function(element) {
+      var shouldClone;
+      shouldClone = this.length !== 1;
+      if (element.isSelector !== void 0) {
+        return this.each(function() {
+          return element.each((e) => {
+            return this.appendChild(shouldClone ? e.cloneNode(true) : e);
+          });
+        });
+      } else if (typeof element === 'string') {
+        return this.each(function() {
+          return this.insertAdjacentHTML('beforeend', element);
+        });
+      } else {
+        return this.each(function() {
+          return this.appendChild(shouldClone ? element.cloneNode(true) : element);
+        });
+      }
+    }
+  };
+
+  // AppendTo
+
+  // 將目前選擇器元素插入到指定元素的內部最後面。
+  ts.fn.appendTo = {
+    value: function(selector) {
+      return this.each(function() {
+        return ts(selector).append(this);
+      });
+    }
+  };
+
+  // Prepend
+
+  // 將元素插入在目前選擇器元素的內部最前面。
+  ts.fn.prepend = {
+    value: function(element) {
+      var shouldClone;
+      shouldClone = this.length !== 1;
+      if (element.isSelector !== void 0) {
+        return this.each(function() {
+          return element.each((e) => {
+            return this.prepend(shouldClone ? e.cloneNode(true) : e);
+          });
+        });
+      } else if (typeof element === 'string') {
+        return this.each(function() {
+          return this.insertAdjacentHTML('afterbegin', element);
+        });
+      } else {
+        return this.each(function() {
+          return this.prepend(shouldClone ? element.cloneNode(true) : element);
+        });
+      }
+    }
+  };
+
+  // PrependTo
+
+  // 將目前選擇器元素插入到指定元素的內部最前面。
+  ts.fn.prependTo = {
+    value: function(selector) {
+      return this.each(function() {
+        return ts(selector).prepend(this);
+      });
+    }
+  };
+
+  // Remove
+
+  // 將選擇器元素從頁面上中移除。
+  ts.fn.remove = {
+    value: function() {
+      return this.each(function() {
+        var ref;
+        return (ref = this.parentNode) != null ? ref.removeChild(this) : void 0;
+      });
+    }
+  };
+
+  // Is
+
+  // 選擇一些元素,然後用來比對目前的選擇器元素是否在這群當中。
+  ts.fn.is = {
+    value: function(selector) {
+      var compareElements, isInElements;
+      compareElements = document.querySelectorAll(selector);
+      isInElements = false;
+      this.each(function() {
+        return compareElements.forEach(function(compareElement) {
+          if (this === compareElement) {
+            return isInElements = true;
+          }
+        }, this);
+      });
+      return isInElements;
+    }
+  };
+
+  // Contains
+
+  // 是否擁有指定子元素。
+  ts.fn.contains = {
+    value: function(selector) {
+      var ref;
+      return (ref = this.get(0)) != null ? ref.contains(ts(selector).get()) : void 0;
+    }
+  };
+
+  // Not
+
+  // 將指定元素從選擇器中剔除。
+  ts.fn.not = {
+    value: function(selector) {
+      return ts(this.toArray().filter((element) => {
+        return ts(selector).indexOf(element) === -1;
+      }));
+    }
+  };
+
+  // Slice
+
+  // 替元素陣列進行切分。
+  ts.fn.slice = {
+    value: function(from, to) {
+      return ts(this.toArray().slice(from, to));
+    }
+  };
+
+  // Children
+
+  // 取得容器裡的第一層子節點。
+  ts.fn.children = {
+    value: function(selector) {
+      return this.collectSwap(function() {
+        return this.querySelectorAll(selector != null ? `:scope > ${selector}` : ':scope > *');
+      });
+    }
+  };
+
+  // Replace With
+
+  // 將元素替換為指定選擇器元素。
+  ts.fn.replaceWith = {
+    value: function(selector) {
+      var element;
+      element = ts(selector).get();
+      return this.each(function() {
+        return this.replaceWith(element);
+      });
+    }
+  };
+
+  // Last
+
+  // 選擇器中的最後一個元素。
+  ts.fn.last = {
+    value: function() {
+      return this.eq(this.length - 1);
+    }
+  };
+
+  // Next
+
+  // 下一個元素。
+  ts.fn.next = {
+    value: function() {
+      return this.collectSwap(function() {
+        return this.nextElementSibling;
+      });
+    }
+  };
+
+  // Prev
+
+  // 上一個元素。
+  ts.fn.prev = {
+    value: function() {
+      return this.collectSwap(function() {
+        return this.previousElementSibling;
+      });
+    }
+  };
+
+  // NextAll
+
+  // 這個元素之後的所有同階層元素。
+  ts.fn.nextAll = {
+    value: function(selector) {
+      return this.collectSwap(function() {
+        var $children, $parent, $self, index;
+        $self = ts(this);
+        $parent = $self.parent();
+        $children = selector != null ? $parent.find(`:scope > ${selector}`) : $parent.find(':scope > *');
+        index = $self.index();
+        return $children.slice(index + 1);
+      });
+    }
+  };
+
+  // PrevAll
+
+  // 這個元素之前的所有同階層元素。
+  ts.fn.prevAll = {
+    value: function(selector) {
+      return this.collectSwap(function() {
+        var $children, $parent, $self, index;
+        $self = ts(this);
+        $parent = $self.parent();
+        $children = selector != null ? $parent.find(`:scope > ${selector}`) : $parent.find(':scope > *');
+        index = $self.index();
+        return $children.slice(0, index);
+      });
+    }
+  };
+
+  // AddBack
+
+  // 在目前的選擇器節點陣列中加上先前選擇的所有節點。
+  ts.fn.addBack = {
+    value: function() {
+      if (this.prevObject) {
+        this.prevObject.toArray().forEach((element) => {
+          return this.push(element);
+        });
+      }
+      return this;
+    }
+  };
+
+  // Index
+
+  // 該元素在容器內的索引。
+  ts.fn.index = {
+    value: function() {
+      var index, node;
+      node = this.get(0);
+      index = 0;
+      if (node == null) {
+        return -1;
+      }
+      while ((node = node.previousElementSibling)) {
+        index++;
+      }
+      return index;
+    }
+  };
+
+  // Attr
+
+  // 取得或是建立新的標籤到目前的選擇器元素。
+  ts.fn.attr = {
+    value: function(name, value) {
+      var ref;
+      // 如果有 value 就設置簡單鍵值資料。
+      if (value !== void 0) {
+        return this.each(function() {
+          return this.setAttribute(name, value);
+        });
+      // 如果傳入的是物件就設置多重資料。
+      } else if (typeof name === 'object') {
+        return this.each(function() {
+          var key, results;
+          results = [];
+          for (key in name) {
+            results.push(this.setAttribute(key, name[key]));
+          }
+          return results;
+        });
+      } else {
+        return (ref = this.get()) != null ? ref.getAttribute(name) : void 0;
+      }
+    }
+  };
+
+  // RemoveAttr
+
+  // 移除目前選擇器元素的指定標籤。
+  ts.fn.removeAttr = {
+    value: function(name) {
+      return this.each(function() {
+        return this.removeAttribute(name);
+      });
+    }
+  };
+
+  // AddClass
+
+  // 在目前選擇器元素插入新的樣式類別名稱。
+  ts.fn.addClass = {
+    value: function(names) {
+      var name, newNames;
+      if (typeof names === 'object') {
+        newNames = '';
+        for (name in names) {
+          if (names[name] === true) {
+            newNames += ` ${name}`;
+          }
+        }
+        names = newNames;
+      } else {
+        names = Array.prototype.slice.call(arguments).join(' ');
+      }
+      return this.each(function() {
+        return DOMTokenList.prototype.add.apply(this.classList, names.split(' ').filter(Boolean));
+      });
+    }
+  };
+
+  // RemoveClass
+
+  // 移除目前選擇器元素的指定樣式類別。
+  ts.fn.removeClass = {
+    value: function(names) {
+      var name, newNames;
+      if (typeof names === 'object') {
+        newNames = '';
+        for (name in names) {
+          if (names[name] === true) {
+            newNames += ` ${name}`;
+          }
+        }
+        names = newNames;
+      } else {
+        names = Array.prototype.slice.call(arguments).join(' ');
+      }
+      //console.log @
+      return this.each(function() {
+        return DOMTokenList.prototype.remove.apply(this.classList, names.split(' ').filter(Boolean));
+      });
+    }
+  };
+
+  // ToggleClass
+
+  // 切換目前選擇器元素的樣式。
+  ts.fn.toggleClass = {
+    value: function(names) {
+      return this.each(function() {
+        return names.split(' ').forEach(function(name) {
+          return this.classList.toggle(name);
+        }, this);
+      });
+    }
+  };
+
+  // HasClass
+
+  // 回傳選擇器元素是否帶有指定樣式類別,是布林值。
+  ts.fn.hasClass = {
+    value: function(name) {
+      var ref;
+      return (ref = this.get(0)) != null ? ref.classList.contains(name) : void 0;
+    }
+  };
+
+  // CSS
+
+  // 將選擇器元素套用指定的 CSS 樣式。
+  ts.fn.css = {
+    value: function(name, value) {
+      var key;
+      // 有 name 也有 value 就設置樣式。
+      if (typeof name === 'string' && value !== void 0) {
+        return this.each(function() {
+          return this.style[name] = value;
+        });
+      // 有 name 但沒有 value 就取得樣式。
+      } else if (typeof name === 'string' && value === void 0) {
+        if (this.get() != null) {
+          return document.defaultView.getComputedStyle(this.get(), null).getPropertyValue(name);
+        } else {
+          return null;
+        }
+      // 有 name 但他是 object,就設置多重樣式。
+      } else if (typeof name === 'object') {
+        for (key in name) {
+          this.each(function() {
+            return this.style[key] = name[key];
+          });
+        }
+        return this;
+      }
+    }
+  };
+
+  // Rect
+
+  // 回傳選擇器元素的渲染形狀。
+  ts.fn.rect = {
+    value: function() {
+      var ref;
+      return (ref = this.get(0)) != null ? ref.getBoundingClientRect() : void 0;
+    }
+  };
+
+  // On
+
+  // 綁定並註冊一個事件監聽器。
+  ts.fn.on = {
+    value: function() {
+      var data, events, handler, options, selector;
+      switch (arguments.length) {
+        // Event 與 Handler。
+        case 2:
+          events = arguments[0];
+          handler = arguments[1];
+          break;
+        // Event 與 Selector 與 Handler。
+        // Event 與 Data 與 Handler。
+        // Event 與 Handler 與 Options。
+        case 3:
+          events = arguments[0];
+          handler = arguments[2];
+          switch (typeof arguments[1]) {
+            case "string":
+              selector = arguments[1];
+              break;
+            case "function":
+              handler = arguments[1];
+              options = arguments[2];
+              break;
+            default:
+              data = arguments[1];
+          }
+          break;
+        // Event 與 Selector 與 Data 與 Handler。
+        // Event 與 Selector 與 Handler 與 Options。
+        case 4:
+          events = arguments[0];
+          selector = arguments[1];
+          handler = arguments[3];
+          switch (typeof arguments[2]) {
+            case "function":
+              handler = arguments[2];
+              options = arguments[3];
+              break;
+            default:
+              data = arguments[2];
+          }
+          break;
+        // Event 與 Selector 與 Data 與 Handler 與 Options。
+        case 5:
+          events = arguments[0];
+          selector = arguments[1];
+          data = arguments[2];
+          handler = arguments[3];
+          options = arguments[4];
+      }
+      events = ts.helper.eventAlias(events);
+      // $events.click =
+      // {
+      //     anonymous: [
+      //         {
+      //             once    : true,
+      //             selector: ".button",
+      //             data    : {},
+      //             func    : func()
+      //         }
+      //     ]
+      //     alias1: [
+      //         {
+      //             once    : true,
+      //             selector: ".button",
+      //             data    : {},
+      //             func    : func()
+      //         }
+      //    ]
+      // }
+      return this.each(function() {
+        if (this.addEventListener === void 0) {
+          return;
+        }
+        if (this.$events === void 0) {
+          this.$events = {};
+        }
+        return events.split(' ').forEach(function(eventName) {
+          var event, eventAlias, hasAlias;
+          event = eventName.split('.');
+          // 透過事件的「event.alias」取得「點」後面的別名。
+          hasAlias = event.length > 1;
+          eventName = event[0];
+          eventAlias = hasAlias ? event[1] : null;
+          // 如果事件還沒在這個物件內產生過,就初始化一個事件結構。
+          if (this.$events[eventName] === void 0) {
+            this.$events[eventName] = {
+              anonymous: []
+            };
+            // 然後建立一個管理多個事件的事件管理處理程式。
+            this.addEventListener(eventName, function(event) {
+              var alias, calledAlias, closest, context, hasArgs, index, ref, ref1, ref2, results, single;
+              // 是否有自訂參數。
+              hasArgs = ((ref = event.detail) != null ? (ref1 = ref.args) != null ? ref1.length : void 0 : void 0) > 0;
+              // 是否有呼叫事件別名。
+              calledAlias = (ref2 = event.detail) != null ? ref2.alias : void 0;
+              // 如果該事件已經被移除則停止後續的反應。
+              if (this.$events[eventName] === void 0) {
+                return;
+              }
+              results = [];
+              // 將被觸發的事件裡面的所有處理程式全部呼叫一次。
+              for (alias in this.$events[eventName]) {
+                if (calledAlias && calledAlias !== alias) {
+                  continue;
+                }
+                index = this.$events[eventName][alias].length;
+                results.push((function() {
+                  var results1;
+                  results1 = [];
+                  while (index--) {
+                    if (this.$events[eventName] === void 0) {
+                      continue;
+                    }
+                    if (this.$events[eventName][alias] === void 0) {
+                      continue;
+                    }
+                    single = this.$events[eventName][alias][index];
+                    // 設置事件的上下文。
+                    context = this;
+                    // 如果這個事件有選擇器的話,則使用該選擇器為主。
+                    if (single.selector !== void 0) {
+                      selector = single.selector;
+                      closest = ts(event.target).closest(selector);
+                      // 如果找不到指定選擇棄的元素,就不要觸發此事件。
+                      if (closest.length === 0) {
+                        continue;
+                      } else {
+                        // 替換上下文為選擇器元素。
+                        context = closest.get();
+                      }
+                    }
+                    // 將事件預資料放入事件中供處理函式取得。
+                    event.data = single.data;
+                    if (hasArgs) {
+                      single.func.call(context, event, ...event.detail.args);
+                    } else {
+                      single.func.call(context, event);
+                    }
+                    // 如果這個程式只能被呼叫一次就在處理程式呼叫後移除。
+                    if (single.once === true) {
+                      results1.push(this.$events[eventName][alias].splice(index, 1));
+                    } else {
+                      results1.push(void 0);
+                    }
+                  }
+                  return results1;
+                }).call(this));
+              }
+              return results;
+            });
+          }
+          // 將新的事件處理程式註冊到事件清單中。
+          // 如果有別名,就不要推送到匿名陣列中,我們替這個別名另開物件。
+          if (hasAlias) {
+            if (this.$events[eventName][eventAlias] === void 0) {
+              this.$events[eventName][eventAlias] = [];
+            }
+            return this.$events[eventName][eventAlias].push({
+              func: handler,
+              selector: selector,
+              data: data,
+              once: options != null ? options.once : void 0
+            });
+          } else {
+            // 如果沒有,就照常推進匿名陣列中。
+            return this.$events[eventName].anonymous.push({
+              func: handler,
+              selector: selector,
+              data: data,
+              once: options != null ? options.once : void 0
+            });
+          }
+        }, this);
+      });
+    }
+  };
+
+  // One
+
+  // 綁定一次性的事件監聽器,當被觸發之後就會被移除。
+  ts.fn.one = {
+    value: function(events, handler) {
+      events = ts.helper.eventAlias(events);
+      return this.each(function() {
+        return ts(this).on(events, handler, {
+          once: true
+        });
+      });
+    }
+  };
+
+  // Off
+
+  // 註銷事件監聽器。
+  ts.fn.off = {
+    value: function(events, handler) {
+      events = ts.helper.eventAlias(events);
+      return this.each(function() {
+        if (this.$events === void 0) {
+          return;
+        }
+        return events.split(' ').forEach((eventName) => {
+          var alias, aliasName, event, hasAlias, isAlias, results;
+          // 將事件名稱由中間的「.」切成兩半。
+          event = eventName.split('.');
+          // 如果事件開頭是「.」符號,表示這是個別名,不是事件名稱。
+          isAlias = eventName[0] === '.';
+          // 如果事件分切後有兩個項目,表示這個事件有別名。
+          hasAlias = event.length === 2 && event[0] !== '';
+          if (hasAlias || isAlias) {
+            // 如果有別名的話,取得別名。
+            aliasName = event[1];
+          }
+          // 如果此事件不是只有別名的話,取得事件名稱。
+          eventName = !isAlias ? event[0] : void 0;
+          switch (false) {
+            // 當有指定監聽函式時。
+            case !(handler !== void 0 && this.$events[eventName] !== void 0):
+              return this.$events[eventName].anonymous.forEach((item, index) => {
+                if (handler === item.func) {
+                  return this.$events[eventName].anonymous.splice(index, 1);
+                }
+              });
+            // 當本事件名稱不僅是別名時。
+            case !(!isAlias && hasAlias && this.$events[eventName] !== void 0):
+              // 移除指定事件的別名監聽函式。
+              return delete this.$events[eventName][aliasName];
+            // 當僅有指定別名時。
+            case !(isAlias && !hasAlias):
+              results = [];
+              // 移除所有與此別名有關的事件監聽器。
+              for (event in this.$events) {
+                results.push((function() {
+                  var results1;
+                  results1 = [];
+                  for (alias in this.$events[event]) {
+                    if (aliasName === alias) {
+                      results1.push(delete this.$events[event][aliasName]);
+                    } else {
+                      results1.push(void 0);
+                    }
+                  }
+                  return results1;
+                }).call(this));
+              }
+              return results;
+              break;
+            // 當僅有指定事件名稱時。
+            case this.$events[eventName] === void 0:
+              // 清空該事件的所有事件監聽器。
+              return delete this.$events[eventName];
+          }
+        }, this);
+      });
+    }
+  };
+
+  // Trigger
+
+  // 觸發指定事件。
+  ts.fn.trigger = {
+    value: function(events) {
+      var customArguments;
+      events = ts.helper.eventAlias(events);
+      customArguments = [].slice.call(arguments, 1);
+      return this.each(function() {
+        return events.split(' ').forEach((eventName) => {
+          var alias, event, name;
+          event = eventName.split('.');
+          name = event[0];
+          alias = event.length > 1 ? event[1] : null;
+          event = new CustomEvent(name, {
+            detail: {
+              args: customArguments,
+              alias: alias
+            }
+          });
+          return this.dispatchEvent(event);
+        });
+      });
+    }
+  };
+
+  // Emulate
+
+  // 在指定的秒數過後觸發指定事件,若已被觸發則不再次觸發。
+  // 這能用以強迫讓某個事件發生。
+  ts.fn.emulate = {
+    value: function(event, duration) {
+      return this.each(function() {
+        var called;
+        called = false;
+        ts(this).one(event, function() {
+          return called = true;
+        });
+        return setTimeout(() => {
+          if (!called) {
+            return ts(this).trigger(event);
+          }
+        }, duration);
+      });
+    }
+  };
+
+  // Text
+
+  // 變更或取得選擇器元素的內容文字。
+  ts.fn.text = {
+    value: function(text) {
+      var ref;
+      if (text !== void 0) {
+        return this.each(function() {
+          return this.innerText = text;
+        });
+      } else {
+        return (ref = this.get()) != null ? ref.innerText : void 0;
+      }
+    }
+  };
+
+  // Val
+
+  // 變更或取得選擇器元素的值。
+  ts.fn.val = {
+    value: function(value) {
+      var ref;
+      if (value !== void 0) {
+        return this.each(function() {
+          return this.value = value;
+        });
+      } else {
+        return (ref = this.get()) != null ? ref.value : void 0;
+      }
+    }
+  };
+
+  // HTML
+
+  // 變更或取得選擇器元素的 HTML。
+  ts.fn.html = {
+    value: function(html) {
+      var ref;
+      if (html !== void 0) {
+        return this.each(function() {
+          return this.innerHTML = html;
+        });
+      } else {
+        return (ref = this.get()) != null ? ref.innerHTML : void 0;
+      }
+    }
+  };
+
+  // Empty
+
+  // 將選擇器元素的內容清除,例如值或文字。
+  ts.fn.empty = {
+    value: function() {
+      return this.each(function() {
+        if (this.value !== void 0) {
+          this.value = null;
+        }
+        if (this.innerHTML !== void 0) {
+          this.innerHTML = null;
+        }
+        if (this.innerText !== void 0) {
+          return this.innerText = null;
+        }
+      });
+    }
+  };
+
+  // Prop
+
+  // 變更或取得選擇器元素的屬性,例如 `.src`、`.width`。
+  ts.fn.prop = {
+    value: function(name, value) {
+      var key, ref;
+      // 有 name 也有 value 就設置屬性。
+      if (typeof name === 'string' && value !== void 0) {
+        return this.each(function() {
+          return this[name] = value;
+        });
+      // 有 name 但沒有 value 就取得屬性。
+      } else if (typeof name === 'string' && value === void 0) {
+        return (ref = this.get()) != null ? ref[name] : void 0;
+      // 有 name 但他是 object,就設置多重屬性。
+      } else if (typeof name === 'object') {
+        for (key in name) {
+          this.each(function() {
+            return this[key] = name[key];
+          });
+        }
+        return this;
+      }
+    }
+  };
+
+  // Data
+
+  // 在選擇器元素中存放資料,類似 Attr 但頁面不可見。
+  ts.fn.data = {
+    value: function(name, value) {
+      var key, ref, ref1;
+      // 有 name 也有 value 就設置資料。
+      if (typeof name === 'string' && value !== void 0) {
+        return this.each(function() {
+          if (this.$data === void 0) {
+            this.$data = {};
+          }
+          return this.$data[name] = value;
+        });
+      // 有 name 但沒有 value 就取得資料。
+      } else if (typeof name === 'string' && value === void 0) {
+        return (ref = this.get()) != null ? (ref1 = ref.$data) != null ? ref1[name] : void 0 : void 0;
+      // 有 name 但他是 object,就設置多重樣式。
+      } else if (typeof name === 'object') {
+        for (key in name) {
+          this.each(function() {
+            if (this.$data === void 0) {
+              this.$data = {};
+            }
+            return this.$data[key] = name[key];
+          });
+        }
+        return this;
+      }
+    }
+  };
+
+  // Remove Data
+
+  // 移除指定的資料。
+  ts.fn.removeData = {
+    value: function(name) {
+      return this.each(function() {
+        if (this.$data[name] != null) {
+          return delete this.$data[name];
+        }
+      });
+    }
+  };
+
+  // Has Timer
+
+  // 確認是否有指定的計時器。
+  ts.fn.hasTimer = {
+    value: function(name) {
+      var ref, ref1;
+      return ((ref = this.get(0)) != null ? (ref1 = ref.$timers) != null ? ref1[name] : void 0 : void 0) != null;
+    }
+  };
+
+  // Get Timer
+
+  // 取得計時器內容。
+  ts.fn.getTimer = {
+    value: function(name) {
+      var ref, ref1;
+      return (ref = this.get(0)) != null ? (ref1 = ref.$timers) != null ? ref1[name] : void 0 : void 0;
+    }
+  };
+
+  // Set Timer
+
+  // 設置一個新的計時器。
+  ts.fn.setTimer = {
+    value: function(options) {
+      options = Object.assign({}, {
+        name: '',
+        callback: function() {},
+        interval: 0,
+        looping: false,
+        visible: false
+      }, options);
+      return this.each(function() {
+        var timer;
+        if (this.$timers === void 0) {
+          this.$timers = {};
+        }
+        if (this.$timers[options.name] !== void 0) {
+          clearInterval(this.$timers[options.name].timer);
+        }
+        timer = () => {
+          var ref;
+          // 當設置有說明,頁面不可見的時候就不要繼續計時。
+          if (options.visible && document.hidden) {
+            return;
+          }
+          // 替計時器加上 10 毫秒。
+          this.$timers[options.name].passed += 10;
+          // 如果計時器的經過時間還不到使用者設定的時間
+          // 就返回而不要繼續執行。
+          if (this.$timers[options.name].passed < options.interval) {
+            return;
+          }
+          // 呼叫回呼函式。
+          options.callback();
+          // 如果要循環的話,就在計時器執行後重設時間即可。
+          if (options.looping) {
+            return this.$timers[options.name].passed = 0;
+          } else {
+            // 不然就移除計時器資訊。
+            return clearInterval((ref = this.$timers[options.name]) != null ? ref.timer : void 0);
+          }
+        };
+        // 移除在 DOM 元素內的這個計時器物件。
+        //delete @$timers[options.name]
+
+        // 在此元素內初始化計時器物件。
+        return this.$timers[options.name] = {
+          timer: setInterval(timer, 10),
+          passed: 0,
+          callback: options.callback,
+          interval: options.interval,
+          looping: options.looping,
+          visible: options.visible,
+          initializer: timer,
+          paused: false
+        };
+      });
+    }
+  };
+
+  // Pause Timer
+
+  // 暫停一個計時器。
+  ts.fn.pauseTimer = {
+    value: function(name) {
+      return this.each(function() {
+        var ref;
+        if (((ref = this.$timers) != null ? ref[name] : void 0) == null) {
+          return;
+        }
+        // 清除計數計時器達到暫停效果。
+        clearInterval(this.$timers[name].timer);
+        // 表示暫停。
+        return this.$timers[name].paused = true;
+      });
+    }
+  };
+
+  // Play Timer
+
+  // 重啟一個計時器。
+  ts.fn.playTimer = {
+    value: function(name) {
+      return this.each(function() {
+        var ref;
+        if (((ref = this.$timers) != null ? ref[name] : void 0) == null) {
+          return;
+        }
+        if (!this.$timers[name].paused) {
+          return;
+        }
+        // 重新初始化計數計時器來達到繼續的效果。
+        this.$timers[name].timer = setInterval(this.$timers[name].initializer, 10);
+        // 表示重新啟動。
+        return this.$timers[name].paused = false;
+      });
+    }
+  };
+
+  // Remove Timer
+
+  // 移除一個計時器。
+  ts.fn.removeTimer = {
+    value: function(name) {
+      return this.each(function() {
+        var ref;
+        if (((ref = this.$timers) != null ? ref[name] : void 0) == null) {
+          return;
+        }
+        // 清除計數計時器。
+        clearInterval(this.$timers[name].timer);
+        // 移除在 DOM 元素內的計時器物件。
+        return delete this.$timers[name];
+      });
+    }
+  };
+
+  // Repaint
+
+  // 讓瀏覽器重繪元素。
+  ts.fn.repaint = {
+    value: function() {
+      return this.each(function() {
+        return void(this.offsetHeight);
+      });
+    }
+  };
+
+}).call(this);

+ 179 - 0
upload.php

@@ -0,0 +1,179 @@
+<?php
+$target_dir = "uploads/";
+if (isset($_GET['VB_upload']) && $_GET['VB_upload'] == "true"){
+	$target_file = $target_dir . basename($_FILES["file"]["name"]);
+	$_FILES["fileToUpload"] = $_FILES["file"];
+}else{
+	$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
+}
+$uploadOk = 1;
+$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
+$filename = "";
+$displayMsg = "";
+$jsonReply = false;
+//Check if it is a program request or not
+if (isset($_GET['json']) && $_GET['json'] == "true"){
+	$jsonReply = true;
+}
+// Check if file already exists
+if (file_exists($target_file)) {
+    //echo "Sorry, file already exists.";
+    $uploadOk = 0;
+}
+// Check file size
+if ($_FILES["fileToUpload"]["size"] > 25000000) {
+    //echo "Sorry, your file is too large.";
+    $uploadOk = 0;
+}
+// Allow certain file formats
+if($imageFileType == "php") {
+    $uploadOk = 0;
+}
+// Check if $uploadOk is set to 0 by an error
+if ($uploadOk == 0) {
+    //echo "Sorry, your file was not uploaded.";
+// if everything is ok, try to upload file
+	$displayMsg = "Sorry, your file was not uploaded. (Maybe file already exists / Not allowed format / file larger than 25MB)";
+} else {
+    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
+        //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
+		$filename =  $_FILES["fileToUpload"]["name"];
+		$displayMsg = "Done.";
+    } else {
+		$displayMsg = "Sorry, there was an error uploading your file.";
+        //echo "Sorry, there was an error uploading your file.";
+    }
+}
+
+if ($filename != ""){
+	//DONE
+	$memodir = "Memo/";
+	$content = "data:file/" . $filename;
+	$content = bin2hex($content);
+	$max = 0;
+		foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+			if ($fileInfo->isDot()) continue;
+			$current = pathinfo($fileInfo->getFilename())['filename'];
+			if (!is_numeric($current)) continue;
+			if ($current > $max) $max = $current;
+		}
+		
+	//Check if the number of files exceed the max
+	if ($max > 1000){
+		foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+				$current = pathinfo($fileInfo->getFilename())['filename'];
+				if (!is_numeric($current)) continue;
+				if ((int)$current != 0){
+					unlink('Memo/' . $current . ".txt");
+				}
+		}
+		$max = 0;
+	}
+	
+	$filename = (int)$max + 1;
+	$myfile = fopen($memodir . $filename . ".txt", "w") or die("Unable to open file!");
+	$txt = $content;
+	fwrite($myfile, $txt);
+	fclose($myfile);
+	//echo $filename;
+	
+	if ($jsonReply == true){
+		if ($uploadOk == 0){
+			header('Content-Type: application/json');
+			echo json_encode(-1);
+		}else{
+			header('Content-Type: application/json');
+			echo json_encode($filename);
+		}
+		exit();
+	}
+}else{
+	if ($jsonReply == true){
+		if ($uploadOk == 0){
+			echo json_encode("Sorry, your file was not uploaded. (Maybe file already exists / Not allowed format / file larger than 25MB)");
+		}
+		exit();
+	}
+}
+?>
+<html>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<head>
+<title>Quick Send</title>
+<link rel="stylesheet" href="tocas.css">
+<script type="text/javascript" src="urlfix.js"></script>
+</head>
+<body>
+<?php
+	if (isset($_GET['rx']) && $_GET['rx'] != ""){
+		header("Location: display.php?id=" . $_GET['rx']);
+		die();
+	}
+?>
+<div class="ts inverted heading fluid slate" style="background-color:#2c2835;color:white;">
+    <span class="large header">Quick Send System</span>
+    <span class="description">Send data between mobile and laptops.<br> Powered by IMUS Laboratory</span>
+    <div class="ts bottom attached tabbed menu" style="color:white;">
+        <a class="item" href="index.php" style="color:#9d9ca3;">Send</a>
+        <a class="item" href="rx.php" style="color:#9d9ca3;">Receive</a>
+        <a class="item" href="img.php" style="color:#9d9ca3;">Image</a>
+        <a class="active item" href="file.php">Files</a>
+    </div>
+</div>
+
+<div class="ts container">
+<br><br>
+<div class="ts stackable grid">
+    <div class="four wide column" align="center">
+		<div id="output"></div>
+		<div class="ts small statistic">
+			<div class="label">QuickSend ID</div>
+			<div class="value" id="sid"><?php
+			$max = 0;
+			foreach (new DirectoryIterator('Memo/') as $fileInfo) {
+				if ($fileInfo->isDot()) continue;
+				$current = pathinfo($fileInfo->getFilename())['filename'];
+				if (!is_numeric($current)) continue;
+				if ($current > $max) $max = $current;
+			}
+			echo $max;
+			?></div>
+		</div>
+	</div>
+    <div class="twelve wide column">
+		<h2 class="ts header"><?php echo $displayMsg;?></h2><br>
+		<a href="file.php" class="ts basic button">Upload Next File</a>
+		<br>
+	</div>
+</div>
+
+<br><br><br><br><br><br>
+<div style="position: fixed;
+    z-index: 100; 
+    bottom: 0; 
+    left: 0;
+    width: 100%;
+	background-color:#2c2835;
+	color:white;">
+<div class="ts container">
+<img class="ts tiny right floated image" src="img/cube.png"></img>
+</div>
+<div align="left" class="ts container">
+<br>
+CopyRight IMUS Laboratory 2018, All right reserved.
+</div>
+</div>
+
+</div>
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
+<script type="text/javascript" src="jquery.qrcode.min.js"></script>
+<script>
+var data = <?php echo $max;?>;
+jQuery(function(){
+	jQuery('#output').qrcode("http://imuslab.com/qs/display.php?id=" + data);
+})
+
+
+</script>
+</body>
+</html>

BIN
uploads/Thumbs.db


BIN
uploads/p1.zip


+ 13 - 0
urlfix.js

@@ -0,0 +1,13 @@
+//IMUS url redirect system for website under iframe and redirected subdomains using javascript.
+console.log("IMUS urlfix.js working in process...");
+var dirshort = "qs";
+var url = (window.location != window.parent.location)
+            ? document.referrer
+            : document.location.href;
+if (url.includes("/" + dirshort + "/") == false){ 
+//Switch to sub-domain system
+console.log("Subdomain system not found. Coverting to subdomain system.");
+top.window.location.href = "http://" + dirshort + ".imuslab.com";
+}else{
+console.log("Handling by subdomain redirection system. DONE");	
+}

Some files were not shown because too many files changed in this diff