/* Javascript Helpers */

/* 
 * Barcode Scanner
 *
 * Variables used to detect the barcode scanner
 */

	var inputted_string = "";
	var input_time = 500;

	var scanner_enabled = false;
	var book_scanning_enabled = false;
	var student_scanning_enabled = false;

	var book_barcode_min_length = 9;
	var book_scan_url = "";

	var student_id_barcode_length = 8;
	var student_id_scan_url = "";
	var student_id_scan_url_append = "/";

	// Timer variables
	var msecs = input_time;
	var timer_id = null;
	var timer_running = false;
	var delay = 100; // msec

/* 
 * Enables support for book barcode scanning
 *
 */

	function barcode_scanner_book(url)
	{
		scanner_enabled = true;
		book_scanning_enabled = true;
		book_scan_url = url;
	}

/* 
 * Enables support for student_id barcode scanning
 *
 */

	function barcode_scanner_student(url,url_append)
	{
		scanner_enabled = true;
		student_scanning_enabled = true;
		student_id_scan_url = url;
		student_id_scan_url_append = url_append;
	}

/* 
 * Start the timer window when input will be accepted
 *
 */
	
	function timer_start()
	{
	    if (msecs==0)
			timer_stop();
		else
		{
			window.status = msecs;
			msecs = msecs - delay;
			timer_running = true;
			timer_id = window.setTimeout("timer_start()", delay)
		}
	}

/* 
 * Stops the input window
 *
 */

	function timer_stop()
	{
		if(timer_running)
			clearTimeout(timer_id);
		timer_running = false;
		inputted_string = "";
		msecs = input_time;
	}

/* 
 * Set up the key listener and respond to various actions
 *
 */

	function keyListener(e)
	{
		if(!e)
		{
			//for IE
			e = window.event;
		}
		if(scanner_enabled)
		{			
			if(!timer_running)
				timer_start();
				
			// If return
			if(e.keyCode==13)
			{
				// Check is this a book barcode?
				if(book_scanning_enabled && inputted_string.length >= book_barcode_min_length)
				{
					document.getElementById('barcode_main_page').style.display='none';
					document.getElementById('barcode_scan_message').style.display='';
					window.location = book_scan_url + inputted_string + "/";
					scanner_enabled = false;
				}

				// Check is this a book barcode?
				if(student_scanning_enabled && inputted_string.length == student_id_barcode_length)
				{
					document.getElementById('barcode_main_page').style.display='none';
					document.getElementById('barcode_scan_student_message').style.display='';
					window.location = student_id_scan_url + inputted_string + student_id_scan_url_append;
					scanner_enabled = false;
				}

				inputted_string = "";
				timer_stop();
			}
			else
			{
				var charCode = (e.charCode) ? e.charCode : e.keyCode;
				inputted_string += String.fromCharCode(charCode);
			}
		}
	}

/* 
 * Link the event handler to the page
 *
 */

	document.onkeydown = keyListener; 
	
