Ext.keyboard = Ext.extend(Ext.Panel, {
  layout: 'card',
  cls: 'keyboard',
  activeItem: 0,
  target: '',
  width: 471,
  height: 168,
  border: false,
  constructor: function(config){
        Ext.keyboard.superclass.constructor.apply(this, arguments);
        var lKeyboard = [['q','w','e','r','t','y','u','i','o','p'],['a','s','d','f','g','h','j','k','l'],['up','z','x','c','v','b','n','m','bspace'],['.?123','space','return']];
        var uKeyboard = [['Q','W','E','R','T','Y','U','I','O','P'],['A','S','D','F','G','H','J','K','L'],['up','Z','X','C','V','B','N','M','bspace'],['.?123','space','return']];
        var sKeyboard = [['1','2','3','4','5','6','7','8','9','0'],['-','/',':',';','*','+','$','&','@','"'],['up','.',',','?','!',"'",'bspace'],['ABC','space','return']];
        this.add(this.buildKeyboard(this,lKeyboard));
        this.add(this.buildKeyboard(this,uKeyboard));
        this.add(this.buildKeyboard(this,sKeyboard));
  },
  listeners: {
    blur: function(){
      if (this.target != ''){
        target = Ext.getCmp(this.target);                     
        if (Ext.isIE){
          //TODO: Unset focus
        } else {
          target.validateBlur = function(){return true;};
        }
      }
    }
  },
  insertLetter: function(target,letter){
    obj = document.getElementById(target.id);
    
    if (obj.selectionStart){
      startPos = obj.selectionStart;
      endPos = obj.selectionEnd;
      target.el.dom.value = (target.el.dom.value.substring(0,startPos) + letter + target.el.dom.value.substring(endPos));
      target.focus(); 
      obj.selectionEnd = startPos+1;
      obj.selectionStart = startPos+1;
    } 
    else {
      newValue = target.el.dom.value + letter;
      target.focus(); 
      target.el.dom.value = newValue;   
    }       
  },
  backSpace: function (target){
    obj = document.getElementById(target.id);
    if (obj.selectionStart){
      startPos = obj.selectionStart;
      endPos = obj.selectionEnd;
      if (startPos == endPos){
        target.el.dom.value = (target.el.dom.value.substring(0,startPos-1) +target.el.dom.value.substring(endPos));              
      } else{
        target.el.dom.value = (target.el.dom.value.substring(0,startPos) + target.el.dom.value.substring(endPos));
      }
      target.focus();
      if(startPos==endPos){ 
        obj.selectionEnd = startPos-1;
        obj.selectionStart = startPos-1;
      } else{
        obj.selectionEnd = startPos;
        obj.selectionStart = startPos;
      }
    } 
    else {         //If the browser is not Firefox
      target.el.dom.value = (target.el.dom.value.substring(0,target.el.dom.value.length-1));  //Delete one Chacter from the field
    }
  },  
  //-------------------------------------------------------------------------------------------------//
  //Function: buildKeyboard -------------------------------------------------------------------------//
  //Description: Takes a 2 dimensional array with each 2nd dimension representing a keyboard row-----//
  //   Each row is an array containing strings representing each button -----------------------------//
  //Return: Returns a panel containing each row for a keyboard --------------------------------------//
  //-------------------------------------------------------------------------------------------------//
  buildKeyboard: function(keyPanel, keyboard){
    var tempPanel = new Ext.Panel({border: false});
    for (mykeys in keyboard){
      if (typeof(keyboard[mykeys]) != 'function') {
        var tempPanelRow = new Ext.Panel({border: false, cls: 'keyrow', bodyStyle: 'margin-top: 3px; margin-bottom: 3px;'});
       if (keyboard[mykeys].length == 9 && mykeys == 1){
          tempPanelRow.bodyStyle += 'margin-left: 18px;';
        } 
        for (akey in keyboard[mykeys]){                                                                                                    
          if (typeof(keyboard[mykeys][akey]) != 'function') {
            var buttonWidth = 41;
            var buttonClass = 'keyboardbuttons';
            var buttonText = keyboard[mykeys][akey];
            var buttonIconClass = '';
            keySpaceArray = ['.?123', 85, 'ABC', 85, 'space', 283,'return', 85, 'up', 55, 'bspace', 55, '.', 60, ',', 60, '?', 60, '!', 60, "'", 60];      //Array with buttonnames next to their widths (Exceptions only)
            if (keySpaceArray.indexOf(keyboard[mykeys][akey]) != -1){                                    // Checks to see if the current button is in the array, if it is it sets the width
              buttonWidth =  keySpaceArray[keySpaceArray.indexOf(keyboard[mykeys][akey])+1];                                              
            } 
            if (keyboard[mykeys][akey] == 'up' || keyboard[mykeys][akey] == 'bspace'){                   //Set the class to handle the margins and icons
              buttonClass = 'keyboard' + keyboard[mykeys][akey];
              buttonIconClass = 'keyboardicon' + keyboard[mykeys][akey];
              buttonText = ""; 
            }                                                                                                                           
            tempPanelRow.add(                                                                            //Add the button to the panel
                  {                                                                   
                    xtype: 'button',
                    text: buttonText,
                    cls: buttonClass,
                    iconCls: buttonIconClass,
                    width: buttonWidth,
                    buttonName: keyboard[mykeys][akey],
                    height: 35,
                    handler: function(btn){
                      if (keyPanel.target != ''){
                        target = Ext.getCmp(keyPanel.target); 
                        target.validateBlur = function(){return false;};
                        target.focus();                                       
                        switch(btn.buttonName){
                          case '.?123':
                            keyPanel.layout.setActiveItem(2);
                            break;
                          case 'up':
                            firstLetter = keyPanel.layout.activeItem.items.items[0].items.items[0].text; //Get the first chacter on the keyboard
                            if(firstLetter == 'q'){ keyPanel.layout.setActiveItem(1);}                   //Change to uppercase letters if the keyboard is lowercase
                            else if(firstLetter == 'Q'){ keyPanel.layout.setActiveItem(0); }             //Change to lowercase letters if the keyboard is uppercase
                            break;
                          case 'ABC':
                            keyPanel.layout.setActiveItem(0);                                            //Change to lowercase letters
                            break;
                          case 'bspace':
                            keyPanel.backSpace(target);
                            break;
                           case 'space':
                            keyPanel.insertLetter(target,' ');                                                             
                            break;
                           case 'return':
                            //Do something here
                            break;                                                             
                          default:
                            keyPanel.insertLetter(target,btn.text);                                                           
                            break;
                        }
                        
                        if (target.dqTask) {   
                          target.dqTask.delay(target.queryDelay);  //Cause dropdown with filtering
                        }
                      } 
                    }
                  }
            );
          }
        }
        tempPanel.add(tempPanelRow);
        
      }
    }
     
    return tempPanel;
  }
});
Ext.ComponentMgr.registerType('keyboard', Ext.keyboard);
