function KeyboardBuffer() {
    var self = {}; //Instance of keyboardbuffer
    self.buffer = []; //Buffer containing pressed keys
    self.activeWindow = {}; //Poitner to function containing the handle scanned values function

    //Push on buffer
    self.push = function (char) {
        //alert('walalalalala');
        //        console.log('adding char: ' + char);
        self.buffer.push(char);
    }

    //set buffer data
    self.set = function (data) {
        self.buffer = [];
        if (defined(data)) {
            if (data.length > 0) {
                for (i = 0; i < data.length; i++) {
                    self.buffer.push(data[i]);
                }
            }
        }
    }

    self.append = function (data) {
        //        console.log('adding value: ' + data);
        if (defined(data)) {
            if (data.length > 0) {
                for (i = 0; i < data.length; i++) {
                    self.buffer.push(data[i]);
                }
            }
            else {
                self.buffer = [];
            }
        }
    }

    //Get values in buffer in a string
    self.val = function () {
        var bufferData = self.buffer.join('');
        self.buffer = [];
        return bufferData;
    }

    self.keyup = (function (e) {
        if (e.keyCode == 8) {
            self.buffer.pop();
            //
        }
    });

    self.keypressed = function (e) {
        var dc = String.fromCharCode(e.which);
        //        console.log("Active element is : " + document.activeElement);   
        //        console.log('keycode: ' + e.keyCode);
        if (e.keyCode == 13) {
            var barcodeText = self.val();
            debugLogWrite(barcodeText);
            self.buffer = [];
            if (defined(self.activeWindow)) {
                self.activeWindow.handleScannedValues(barcodeText.trim());
            }
            return;
        }
        if (e.keyCode == 8) {
            self.buffer.pop();
            debugLogWrite(self.buffer.join(''));
        }
        else {
            self.push(dc);
            //            console.log('Stack had the following value pushed : ' + dc + "  [" + self.buffer.join("") +  "]");
            debugLogWrite(self.buffer.join(''));
            if (defined(barcodeText)) {
            }
        }
    }
    $(document).on('blur', "input", function (e) {
        self.set(this.value); // If user blurs the input, then set the value in the buffer
    });
    $(document).on('click', document, function (e) {
        self.buffer = [];
    });
    return self;
}

///// Main /////

var keyboardbuffer = KeyboardBuffer();
