/* 
 * Gerasimos Chatzidamianos
 * &copy; copyright 2011
 */

(function( $ ){

  var methods = {
     init : function(options) {
       return this.each(function(){

            var $this = $(this);
            $this.data('clearText', {
               target : $this,
               ov : $this.val()
           });
            // If options exist, lets merge them
            // with our default settings
            $this.bind('focusin.clearText', methods.focusin);
            $this.bind('focusout.clearText', methods.focusout);
            $this.closest('form').bind('submit.clearText',{elm: $this}, methods.submit);
       });
     },
     destroy : function( ) {
        return this.each(function(){
            var $this = $(this);
            var data=$this.data('clearText');
            // Namespacing FTW
            $this.unbind('.clearText');
            data.clearText.remove();
            $this.removeData('clearText');
        });
     },
     focusin : function() {
         var $this = $(this);
         if($this.val()==$this.data('clearText').ov)
            $this.val('');
     },
     focusout: function() {
         var $this = $(this);
         if($this.val()=="")
            $this.val($this.data('clearText').ov);
     },
     submit: function(event) {
         // Get element that needs to be cleared prior to submission
         var elm=event.data.elm;
         if(elm.val()==elm.data('clearText').ov)
            elm.val('');
         return true;
     },
     reset: function() {
         this.each(function(){
             var $this = $(this);
             if($this.val()=='')
                $this.val($this.data('clearText').ov);
         });
     }
  };

  $.fn.clearText = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.clearText' );
    }

  };

})( jQuery );
