/*!

 * jQuery Placeholder Plugin

 *

 * Copyright (c) 2011 Dmitriy Kubyshkin (http://kubyshkin.ru)

 * Licensed under the MIT license

 */



(function($) { // Making $ accessible even in noConflict

  jQuery.fn.placeholder = function(options){

    var options = jQuery.extend({

      className: "placeholded"

    },options);



    return $(this).each(function(){

      var hold = $(this);

      var text = this.defaultValue;

      var form = hold.closest('form');

      

      // Support for html5 placeholder attribute

      if(hold.attr('placeholder'))

      {

        text = hold.attr('placeholder');

        // We don't want native support

        hold.removeAttr('placeholder');

      }



      // If there's no default value then there's nothing to do here

      if(!text) return;



      // Function to clear input value

      var clearValue = function(){

        if(hold.hasClass(options.className))

        {

          hold.val("");

          hold.removeClass(options.className);

        }

      };



      // Function to restore default value if field is empty

      var restoreValue = function(){

        if(hold.val() == "")

        {

          hold.val(text);

          hold.addClass(options.className);

        }

      };



      // We need to remove default values before we submit

      form.submit(function(){

        clearValue();

        // But if submitting failed for example if other event

        // handler prevented default submit behavior then we need

        // to put placeholders back into the form

        setTimeout(restoreValue); 

      });



      // On focus we clear placeholded value

      hold.focus(clearValue);



      // On blur we put it back if field is empty

      hold.blur(restoreValue);

      

      // Clear placeholder values upon page reload

    	$(window).bind('unload', clearValue);

      

      // That may not be true if we have both placeholder and value attributes

      if(hold.val() == text)

      {

        // Adding placeholded class name

        hold.addClass(options.className);

      }

      

      // Necessary for html5 placeholder

      restoreValue();

    });

  };

})(jQuery);
