var Typewriter = {
  
  CHAR_WIDTH : 8,     // in pixels
  PAGE_PADDING : 40,  // 20 left and 20 right
  LINE_HEIGHT : 17,
  
  
  initialize : function() {
    this.element = $(document.body).down('.text');
    get('.the_page').observe('dblclick', this.adjustPage.bind(this));
    this.element.observe('keyup', function(e){ this._boundLazySave.setLazy(1000); }.bind(this));
    this.element.observe('paste', this.checkForPaste.bind(this));
    document.observe('mousewheel', this.mouseScroll.bind(this));
    
    this._boundLazySave = this.lazySave.bind(this);
  },
  
  
  loadPage : function(page) {
    // Save the old page before switchin'
    if (this.page) this.lazySave();
    this.page = page;
    var top = this.page.get('page_position');
    this.element.setStyle({top : top + 'px'});
    this.element.value = this.page.get('text');
    if (ok) Setting.get('active_page').set('value', page.id).save();
    if (ok) page.save();
    
    get('.really_button').setStyle({opacity:0});
    $(document.body).select('.menu_page').each(function(el) {
      el.removeClassName('active');
    });
    if (ok) $('menu_page_' + page.id).addClassName('active');
    
    this.element.focus.bind(this.element).defer();
  },
  
  
  adjustPage : function(e) {
    var top = parseInt(this.element.getStyle('top'), 10);
    var y = $(e).pointerY();
    var desired = window.innerHeight / 2.5;
    desired = desired - y;
    var moveTo = top + desired;
    new Effect.Move(this.element, {x : 0, y : moveTo, mode : 'absolute', 
                    duration : 0.35, transition : Effect.Transitions.sinoidal});
    this.setPagePosition(moveTo);
  },
  
  
  mouseScroll : function(e) {
    if (Menu.visible || Dock.visible) return;
    var top = parseInt(this.element.getStyle('top'), 10);
    top = top + (e.wheelDelta / 100);
    var height = window.innerHeight * 0.95;
    if (top > height) top = height;
    this.element.setStyle({top : top + 'px'});
    this.setPagePosition(top);
  },
  
  
  setPagePosition : function(num) {
    this.page.set('page_position', num);
    this._boundLazySave.setLazy(1000);
  },
  
  
  checkForPaste : function(e) {
    var later = function() { this.element.scrollTop = 0; }.bind(this);
    later.defer();
  },
    
  
  lazySave : function(e) {
    if (!ok) return;
    var text = this.element.value;
    this.page.saveText(text);
  }
};