/**
 * Virtual keyboard;
 */
var Keyboard = Class.create();
Keyboard.prototype = {
  _config: {
    'renderTo': '',
    'buttons': [
      {
        'title': '1',
        'value': '1',
        'class': 'keyboard-std-button'
      }
    ],
    'input': '',
    'class': 'keyboard'
  },
  
  initialize: function ( _cfg ) {
    this.applyConfig(_cfg);
  },

  applyConfig: function (_cfg) {
    if ( !_cfg ) {
      return;
    }

    this.destroy();
    this._config = _cfg;

    this.render();
  },

  render: function() {
    if ( !this._config.renderTo || !this._config.buttons ) {
      return;
    }

    var renderTo = $(this._config.renderTo);
    var input = $(this._config.input);
    renderTo.addClassName(this._config['class']);
    this._config.buttons.each(
      function ( _button ) {
        var div = $(document.createElement('div'));
        renderTo.appendChild(div);

        _button['class'] = _button['class'] ? _button['class'] : 'keyboard-std-button';
        div.addClassName(_button['class']);
        if ( _button['style'] ) {
          div.setStyle(_button['style']);
        }
        div.update(_button.title ? _button.title : _button.value);
        div.setOpacity(0.5);

        //Эффекты при наведении мышкой;
        div.observe('mouseover', function () {
          this.setOpacity(1);
        });
        div.observe('mouseout', function () {
          this.setOpacity(0.5);
          //new Effect.Opacity(this, { from: 1, to: 0.5, duration: 0.5 });
        });
        //При нажатии мышкой;
        div.observe('mousedown', function () {
          this.addClassName(_button['class'] + '-down');
        });
        div.observe('mouseup', function () {
          this.removeClassName(_button['class'] + '-down');
        });
        div.observe('click', function () {
          input.focus();
          input.value += _button.value;
        });

        if ( _button['break'] ) {
          var div = $(document.createElement('div'));
          renderTo.appendChild(div);
          div.addClassName('keyboard-std-break');
        }
      }
    );
  },

  destroy: function () {
    if ( !this._config.renderTo ) {
      return;
    }

    var buttons = $(this._config.renderTo).childElements();
    if ( !buttons ) {
      return;
    }

    buttons.each(Element.remove);
  }
}
