/**
 * Notice management jquery plugin for ma-residence.fr
 * @author rmouillard
 *
 * How to use:
 *
 * Init plugin (required once in the page and prior to other plugin uses)
 * > jQuery.notice.init();
 *
 * Display flash messages defined by the server (errors or notices)
 * > jQuery.notice.show();
 *
 * Display a message
 * > jQuery.notice.display('My awesome message','notice');
 *
 * Display an error
 * > jQuery.notice.display('My no so awesome error','error');
 *
 * 
 */

 jQuery.notice = {
  /**
   * Init notice plugin
   */
  init: function()
  {
    // Dom elements used by plugin
    noticeElement = jQuery("div.alert");
    wrapperElement = jQuery("div.wrapper", noticeElement);
    this.initTextElement();
    defaultDisplayTime = 5000;
    extendedDisplayTime = defaultDisplayTime * 2;

    // Bind close action to close link
    jQuery('a.close', noticeElement).click(function(e)
    {
      e.preventDefault();
      jQuery.notice.close();
    });
  },
  initTextElement: function()
  {
    noticeTextElement = jQuery('p', "div.alert");
  },

  /**
   * Show the current notice if there is something to show
   * To define a message, use display function
   **/
  show: function()
  {
    if(noticeTextElement.html() && noticeTextElement.html().length > 0)
    {
      noticeElement.slideDown();
      if(noticeElement.hasClass('extended'))
      {
        displayTime = extendedDisplayTime;
      }
      else
      {
        displayTime = defaultDisplayTime;
      }

      setTimeout(function()
      {
        jQuery.notice.close();
      }, displayTime);
    }
  },

  /**
   * Display a notice
   *
   * @param message message to display
   * @param type type of message (notice or error)
   */
  display: function(message, type)
  {
    if(! noticeTextElement.length)
    {
      wrapperElement.append('<p></p>');
      this.initTextElement();
    }

    noticeTextElement.html(message);

    // Add the right class according to the type
    if(type != 'error')
    {
      noticeElement.removeClass('error');
      noticeElement.addClass('notice');
    }
    else
    {
      noticeElement.removeClass('notice');
      noticeElement.addClass('error');
    }

    // slide notice panel
    this.show();

  },

  /**
   * Close the notice panel with an animation
   */
  close: function()
  {
    noticeElement.slideUp("slow", function () {
      noticeElement.hide();
    });
  },

  /**
   * Hide the notice panel (no animation)
   */
  hide: function()
  {
    noticeElement.hide();
  }
};





