Function.prototype.bind = function(scope) {
  var _function = this;
  
  return function() { return _function.apply(scope, arguments); }
}

function BarcodeScanner(endPoint) {
  if (endPoint) {
    this.endPoint = endPoint;
  }

  this.init();
}

BarcodeScanner.prototype = {
  endPoint: "http://localhost/barcodes/scan/",
  inputTime: 500,
  value: "",
  enabled: true,
  timer: {
    id: null,
    active: false,
    delay: 100,
    msecs: null,
    start: function() {
      if (this.msecs == 0) {
			  this.stop();
      }	else {
        window.status = this.msecs;
        this.msecs -= this.delay;
        this.active = true;
        this.id = window.setTimeout(this.start.bind(this), this.delay);
  		}
    },
    stop: function() {
      if(this.active) {
        clearTimeout(this.id);
      }

      this.active = false;
    }
  },
  init: function() {
    this.timer.msecs = this.inputTime;
    document.onkeydown = this.listener.bind(this);
  },
  listener: function(ev) {
    if (!ev) { //for IE
			ev = window.event;
		}
    
		if(this.enabled) {
			if(!this.timer.active) {
				this.timer.start();
      }
				
			// If return
			if(ev.keyCode==13) {
        $.getJSON(this.endPoint + this.value, 
            function(data) {
              if (data.redirect) {
                window.location = data.redirect;
              }
            });

				this.timer.stop();
        this.timer.msecs = this.inputTime;
        this.value = "";
			} else {
				var charCode = (ev.charCode) ? ev.charCode : ev.keyCode;
        // Get visible characters only.
        // http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
        var valid = false;
        if (charCode >= 48 && charCode <= 90) { // 0-9 a-z (case doesn't matter)
          valid = true;
        } else if (charCode >= 96 && charCode <= 111) { // 0-9 (numpad) + - / * .
          valid = true;
        } else if (charCode >= 186 && charCode <= 222) { // ; = , - . / ` { \ } '
          valid = true;
        }

        if (valid) {
          this.value += String.fromCharCode(charCode);
        }
			}
		}
  }
};

