// 
//  application.js
//  
//  Copyright 2011 Osborne Brook Partnership Limited. All rights reserved.
// 

// ======================
// = Our namespace is OB.
// ======================
 
var OB = {};

OB.showMessages = function() {
  $('#messages').fadeIn();
  $(document).one('click', function(){
    OB.hideMessages();
  });
  $(document).one('keydown', function(){
    OB.hideMessages();
  });
};

OB.hideMessages = function(animate) {
  animate = animate == undefined ? true : animate
  if (animate) {
    $('#messages').fadeOut();
  } else {
    $('#messages').hide();
  }
};

OB.message = function(message_text) {
  $('#messages').remove();
  $('body').prepend('<div id="messages"><ul>' + message_text + '</ul></div>');
  OB.showMessages();
}

OB.fadeRemove = function(element){
  $(element).animate({opacity: 0}, 'fast').animate({width: 0, height: 0}, function(){
    $(this).remove();
  });
};

OB.fadeRemoveTR = function(element){
  $(element).find('td').animate({
    opacity: 0
  }, 'fast', function(){
    $(this).html('');
  }).slideUp('fast', function(){
    $(this).remove();
  });
};

OB.scrollPageTo = function(element){
  $('html,body').animate({ scrollTop: $(element).offset().top }, { duration: 'slow', easing: 'swing'});
};

OB.initPlaceholder = function() {
  if ($.browser.webkit) return false;

  $('input[placeholder]').each(function(index) {
    var target = $(this);
    
    if (! $.trim(target.val())) {
      $(target).addClass('placeholder');
      $(target).val($(target).attr('placeholder'));
    }
 
    $(target).focus(function() {
      if ($(this).val() == $(this).attr('placeholder')) {
        $(this).removeClass('placeholder');
        $(this).val('');
      }
    });

    $(target).blur(function() {
      if ($.trim($(this).val()) == '' ) {
        $(this).addClass('placeholder');
        $(this).val( $(this).attr('placeholder') );
      }
    });
  });
  
  // The form shouldn't send the placeholder text as the value
  // TODO: write back the labels after submit
  $('form').submit(function(){
    $(this).find('input[placeholder]').each(function(index) {
      var target = $(this);
      if ($(target).val() == $(target).attr('placeholder')) {
        $(target).val('');
      }
    });
  });
};

