/*
 * jQuery MaskLabel plugin v1.0
 * File Date: 6/3/2009
 *
 * Copyright (c) 2009 Jim Salyer
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

$.fn.extend({
  maskLabel: function(locals)
  {
    // create global properties from combo of defaults and parameters
    var globals = {
      css: {
        color: "#ccc"
      },
      text: "Enter Text Here"
    };
    $.extend(globals, locals);
    
    // loop through given elements, while returning them to preserve JQuery chain
    return $(this).each(function()
    {
      // get the current element in the loop and make sure it's a text input
      var el = $(this);
      if (!/input|textarea/i.test(el.get(0).tagName.toLowerCase()) || !/text|textarea/i.test(new String(el.attr("type")).toLowerCase())) return true;
      
      // set the input's style to the given one while backing up the old one 
      var backup = {};
      for (var rule in globals.css)
      {
        backup[rule] = el.css(rule);
        el.css(rule, globals.css[rule]);
      }
      el.data("maskLabel_css", backup);
     
      // set the element's initial value and event handlers
      el.addClass("maskLabel").val(globals.text).focus(function()
      {
        // when the element gets focus and it's still masked, unmask it for input by the user
        if (el.val() == globals.text)
        {
          el.css(backup);
          el.val("");
        }
      }).blur(function()
      {
        // when the element is blurred and doesn't contain a value, reset it to it's masked state
        if (el.val() == "")
        {
          el.css(globals.css);
          el.val(globals.text);
        }
      });
      
      // make sure the mask text isn't left in the input when the input's form is submitted
      $(el.get(0).form).submit(function()
      {
        if (el.val() == globals.text) el.val("");
      }).get(0).onreset = function()
      {
        var el = $(this);
        setTimeout(function()
        {
          $(".maskLabel", el).blur();
        }, 10);
      };
    });
  }
});