var scanValue = "";
var scanStarted = false;
var controller = "";
var firstChar = true;
var keepAllChars = false;
var process = true;
var ignoreNextEnterKey = false;

if (typeof(entering) == "undefined") {
    var entering = "";
}

if (typeof(submitForm) == "undefined") {
    var submitForm = "";
}

if (typeof(scanDisabled) == "undefined") {

    document.onkeydown = function getcode(e) {
        var keynum;
        var keychar;

        if (window.event) // IE
        {
            keynum = event.keyCode;
        }
        else if (e.which) // Netscape/Firefox/Opera
        {
            keynum = e.which;
        }

        keychar = String.fromCharCode(keynum)

        // They are using the scanner to enter information into a form
        // don't change the page
        if (scanStarted && entering.indexOf(keychar) != -1 && firstChar) {
            process = false;
        }

        if (scanStarted && keychar == 'U' && firstChar && process) {
            controller = 'unit';
            firstChar = false;
            return false;
        }

        if (scanStarted && keychar == 'L' && firstChar && process) {
            controller = 'workOrder';
            firstChar = false;
            keepAllChars = true;
        }

        if (scanStarted && keychar == 'Q' && firstChar && process) {
            controller = 'quote';
            firstChar = false;
            return false;
        }

        if (scanStarted && keychar == 'P' && firstChar && process) {
            controller = 'purchaseOrder';
            firstChar = false;
            return false;
        }

        // Ignore the enter key at the end of a scan
        if (keynum == 13 && ignoreNextEnterKey) {
            ignoreNextEnterKey = false;
            return false;
        }

        if (keynum == 119) {
            if (scanStarted) {
                if (process) {
                    ignoreNextEnterKey = true;
                    var displayUrl = "/" + controller + "/scan/" + scanValue;
                    scanStarted = false;
                    window.location = displayUrl;
                } else if (submitForm.length > 0) {
                    document.forms[submitForm].submit();
                }
            } else {
                //alert("Scan started");
                process = true;
                scanStarted = true;
                return false;
            }
        }

        if (scanStarted && process) {
            if ((scanStarted && (keynum >= 48 && keynum <= 57)) || (keepAllChars && ((keynum >= 48 && keynum <= 57) || (keynum >= 65 && keynum <= 90)))) {
                scanValue += keychar;
                return false;
            }
        } else {
            return true;
        }
    }
}
