//###########################################################################
// This file is part of the Reddynote web application at reddynote.com. All
// code and content is (c) 2006+ by Andreas Neuhaus of Pridago GmbH. No
// usage or distribution is allowed without direct permission of the author.
//---------------------------------------------------------------------------

jQuery(function ($) {
  // Automatic browser upgrade warning via browser-update.org
  if (document.location.protocol == 'http:')
    $.getScript('http://browser-update.org/update.js')

  // Workaround for missing Array#indexOf in IE
  if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
      for (var i=0; i<this.length; i++)
        if (this[i] == obj)
          return i;
      return -1;
    }
  }

  // Helper for executing code now and after an Ajax load
  jQuery.afterAjaxAndNow = function (name, callback) {
    $(document).bind('ajaxComplete.' + name, callback);
    callback();
  };

  //
  // Flash messages
  //
  window.flashMessage = function (type, text) {
    if (type && text) {
      $('#flash').attr('class', type).find('.message').html(text);
      $('#flash').clearQueue();
      // Highlight message if it's already visible
      $('#flash:visible .message').each(function () {
        var origColor = $(this).css('color');
        $(this).animate({ color: '#ffff00' }, 200).animate({ color: origColor }, 600);
      });
      // Fade in message if invisible
      $('#flash:hidden').fadeIn('slow');
      // Auto-fade non-error message after some time
      if (type != 'error')
        $('#flash').delay(7000).fadeOut('slow');
      // Make sure the user can see the flash message by scrolling to the top of the page
      window.scrollTo(0, 0);
    } else {
      $('#flash:visible').fadeOut('slow');
    }
  };

  // Auto-fade static non-error message after some time
  $('#flash[class!=error]:visible').delay(7000).fadeOut('slow');

  //
  // Lightbox
  //
  $('a.lightbox').live('click.lightbox', function (event) {
    event.preventDefault();
    var id = this.id ? this.id + '_dialog' : null;
    var href = this.href;
    var title = this.title || $(this).text();
    $('<div/>').attr('id', id).appendTo('body').dialog({
      close: function (event, ui) {
        $(this).remove();
      },
      height: 33 + 10 + 475,
      modal: true,
      open: function (event, ui) {
        $('<div class="spinner"></div>').prependTo(this);
        $(this).load(href);
      },
      resizable: false,
      title: title,
      width: 28 + 10 + 720
    });
  });

  //
  // Autofocus
  //
  $.afterAjaxAndNow('autofocus', function () {
    $('input[autofocus],textarea[autofocus]').first().focus();
  });
});
