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

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

  if (methodParameters) {
      this.methodParameters = "/" + methodParameters;
  }

  this.init();
}

BarcodeScanner.prototype = {
  endPoint: "http://localhost/barcodes/scan/",
  methodParameters: "",
  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();
        } else {
            // If return
            if(ev.keyCode==13) {
                $.getJSON(this.endPoint + this.value + this.methodParameters, 
                    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);
                }
            }
        }
    }
  }
};

