(function($, Drupal, window, document, undefined) {

  Drupal.sitetheme = Drupal.sitetheme || {};

  /*
   * Initialize placeholder functionality on a text based input element.
   * this in the function is the DOM Element.
   */
  Drupal.sitetheme.initPlaceholder = function() {
    var element = $(this),
        text = element.attr('placeholder');
    var addPlaceholder = function() {
      if (!element.val() || element.val() === text) {
        element.val(text).addClass('placeholder-text');
      }
    };
    var removePlaceholder = function() {
      if (element.val() === text) {
        element.val('').removeClass('placeholder-text');
      }
    };

    addPlaceholder();

    element.focus(removePlaceholder)
      .blur(addPlaceholder);

    element.closest('form').submit(removePlaceholder)
      .bind('reset', function() {
        // When the reset event fires the form reset has not actually
        // happened. We use a timeout so we can add the placeholder
        // after the reset happens.
        setTimeout(addPlaceholder, 50);
      });
  };

  /*
   * Make placeholder function in browsers that do not naticely support it.
   */
  Drupal.behaviors.sitetheme = {
    attach: function(context, settings) {
      // Detect placeholder support.
      var SUPPORTED = 'placeholder' in document.createElement('input');
      if (SUPPORTED || !$(context).find(':input[placeholder]').length) {
        // If the browser natively supports placeholder or it is not used in
        // a page return as there is nothing to do.
        return;
      }
      $(context).find(':input[placeholder]').each(Drupal.sitetheme.initPlaceholder);
    }
  };

})(jQuery, Drupal, this, this.document);;

