// if you need to pass anything to Interface,
// remove this part and put it in the page
Event.observe(document, 'dom:loaded', function() {
  window.interface = new Interface();
});

Interface = Class.create({
  initialize: function() {
    this.drawPage();
  },

  drawPage: function() {
    this.renderBackground('background', 1024, 989, true);
    this.makeHelperInputs();
    this.autoHideFlashMessages(10);
    this.navigation = new Navigation('navigation_root');
    Event.observe(window, 'resize', function() {
      this.renderBackground('background', 1024, 989, true);
    }.bind(this));
  },

  renderBackground: function(background, imageWidth, imageHeight, center) {
    background = $(background);

    var backgroundImage = $('background_image');
    var imageRatio = imageWidth / imageHeight;
    var bodyDimensions = document.viewport.getDimensions();
    var bodyRatio = bodyDimensions.width / bodyDimensions.height;
    var height;
    
    var width = height = 0;
    if (imageRatio <= bodyRatio) {
      width = bodyDimensions.width;
      height = bodyDimensions.width / imageRatio;
    } else {
      height = bodyDimensions.height;
      width = bodyDimensions.height * imageRatio;
    }

    background.setStyle({height: bodyDimensions.height + 'px'});
    backgroundImage.setStyle({
      position: 'absolute',
      top: ((center) ? (-(height - bodyDimensions.height) / 2) : '0') + 'px',
      left: ((center) ? (-(width - bodyDimensions.width) / 2) : '0') + 'px',
      width: width + 'px',
      height: height + 'px'
    });
  },

  makeHelperInputs: function() {
    $$('input.helper').each(function(input) {
      if (!input.title) return;

      var form = input.up('form');
      form.observe('submit', function() { if (input.value == input.title) input.value = ''; });

      if (!input.value) input.value = input.title;
      else input.removeClassName('helper');

      input.observe('focus', function() {
        if (input.value == input.title) {
          input.value = '';
          input.removeClassName('helper');
        }
      });

      input.observe('blur', function() {
        if (!input.value) {
          input.value = input.title;
          input.addClassName('helper');
        }
      });
    });
  },

  autoHideFlashMessages: function(delay) {
    // will auto hide flash messages
    var flashMessagesElement = $('flash_messages');
    if (flashMessagesElement && !flashMessagesElement.down('.error')) {
      setTimeout(function() { new Effect.BlindUp(flashMessagesElement); }, delay * 1000);
    }
  }
});

Object.extend(Interface,{
  TWEEN_SPEED: .3,
  DEBUG: function(msg) {
    console.debug(msg);
  }
});