/*
  author:
    perlnamehoge@gmail.com
  example:
    $(function () {
      $( ".hoge" ).fillinMsg( "message", "#AAAAAA", "black" );
    });
  method:
    fillinMsg
          -> ( fillin-message, fillin-message-color, default-message-color )
*/

(function ($) {
   var colorToHex = function (c) {
       if ( !Array.prototype["map"] )
          Array.prototype.map = function (iter) {
                for ( var i = 0, len = this.length, res = []; i < len; i++ )
                    res[i] = iter.call(null,this[i],i);
                return res;
          }
       return /^rgb/.test(c) ? "#" + c.match(/\d+/g).map(function (v) {
                  v = parseInt(v);
                  return ( (v >> 4 ? '' : 0) + v.toString(16) ).toUpperCase();
              }).join("") : c.toUpperCase();
   }
   $.fn.fillinMsg = function (msg,msg_color,default_color) {
       var msg_color = msg_color || "#AAAAAA", default_color = default_color || "black";
       return $( this ).each(function () {
          /*
            set event(focus and blur) handler to input form.
          */
          $( this ).focus(function () {
            if ( $( this ).attr("value") == msg && colorToHex( $( this ).css("color") ) == msg_color.toUpperCase() )
               $( this ).val("").css("color", default_color.toUpperCase())
          }).blur(function () {
               if ( $( this ).val() == "" )
                  $( this ).val(msg).css("color", msg_color.toUpperCase());
          });
          /*
            set message if target form is empty.
          */
          if ( $( this ).val() == "" )
             $( this ).val( msg ).css("color", msg_color.toUpperCase());
          /*
            attach clear event handler to form.
          */
          $.clearSubmitAction.apply(this);
       });
   }
   $.clearSubmitAction = function () {
       var self   = $( this ),
           parent = $( this ).parent();
       while ( parent ) {
             parent.each(function (i,t) {
                 if ( t.tagName == "FORM" ) {
                    parent.submit(function () {
                       self.focus();
                    });
                    parent = null;
                 } else if ( t.tagName == "HTML" || t.tagName == "BODY" || !t.tagName ) {
                    parent = null;
                 } else {
                    parent = parent.parent();
                 }
             });
       }
   }
})(jQuery);