// Author: Charl van Niekerk <charlvn@charlvn.com>
// Copyright: Copyright (c) 2010 Charl van Niekerk.
// Last Modified: 2010-06-17
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

// Wrap our code in a self-calling closure to isolate scope.
(function() {
 // If the current value of the input is empty, insert the placeholder.
 function populate() {
  var input = jQuery(this);
  if (input.val() == "") {
   input.val(input.attr("placeholder"));
  }
 };

 // If the current value of the input is the placeholder, empty it.
 function depopulate() {
  var input = jQuery(this);
  if (input.val() == input.attr("placeholder")) {
   input.val("");
  }
 };

 // Execute as soon as the document is fully loaded.
 jQuery(function() {
  var inputs = jQuery("input[type=text]");

  // Initially, populate the placeholder values.
  inputs.each(populate);

  // When an input receives focus, clear the placeholder value if used.
  inputs.focus(depopulate);

  // When an empty input loses focus, reinsert the placeholder value.
  inputs.blur(populate);

  // Before a form is submitted back, clear the placeholder values as necessary.
  jQuery("form").submit(function() {
   jQuery("input[type=text]", this).each(depopulate);
  });
 });
})();

