
/**
 * Enables an input field in the structure <input type="text" class="hint" alt="text for hint" />
 * to display a helpful text such as 'enter search term here'
 * Note: It can be used for textarea, but alt attribute is not valid.
 *
 * Usage :
 *   jQuery('input.hint').hint( { 'hintColor' : 'red' , 'valueColor' : 'blue' } );
 *
 * @TODO: - hintSource "label:for": move label text to corresponding input
 *        - hintSource "label:wrap": move label text to child input
 *        - store hint text to jQuery data assigned to current jQuery object
 * 
 * @author Dieter Raber <raber at h2a dot lu>
 * @author Pierrot Evrard <evrard at h2a dot lu>
 * @param  settings object Options to overwrite
 * @return jQuery object
 */
jQuery.fn.hint = function( settings ) {
  /* Initialize options */
  var options = {
    hintCallback  : function( inputDom ){ jQuery(inputDom).addClass( 'hinted' ) },
    unhintCallback : function( inputDom ){ jQuery(inputDom).removeClass( 'hinted' ) },
    hintSource : 'alt',
    clearLabel : false,
    addTitle : true
  };
  jQuery.extend( options , settings || {} );

  /* Real job */
  this.each( function() {
    /* Clear label functionnality */
    if(options.clearLabel && this.parentNode.tagName == 'LABEL') {
      var childNodes = this.parentNode.childNodes;
      for(var i = 0; i < childNodes.length; i++) {
        if(childNodes[i].nodeType == 3) {// = text node
          this.parentNode.removeChild(childNodes[i])
        }
      }    
    }
    /* Create reference to itself (used when bind submit event to form) */
    var thisRef = jQuery(this);
    /* Initialize hint */
    if(!this.value || this.value == thisRef.attr( options.hintSource )) {
      this.value = thisRef.attr( options.hintSource );
      if(options.addTitle) {
        this.title = this.value;
      }
      options.hintCallback( this );
    }
    /* Bind events */
    thisRef.focus(function() {
      if(this.value == thisRef.attr( options.hintSource )) {
        this.value = '';
        options.unhintCallback( this );
      }
    })
    .blur(function() {
      if(this.value == thisRef.attr( options.hintSource ) || !this.value) {
        this.value = thisRef.attr( options.hintSource );
        options.hintCallback( this );
      }
    })
    .parents('form').submit(function() {
      if(thisRef.attr( 'value' ) == thisRef.attr( options.hintSource )) {
        thisRef.attr( 'value' , '' );
      }
    });

  });
  return this;
};
