/*!

 * jQuery Placeholder Plugin

 *

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

 * Licensed under the MIT license

 */

if(jQuery) // Check if jQuery is loaded

{

  (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');



        // 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);

          }

        };



        // Adding placeholded class name

        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);

      });

    };

  })(jQuery);

}
