/**
 * @author Barraq
 *
 * Beautiful Forms
 *  
 *  A simple set of functions to remove form labels and place their
 *  description inside the form field
 *
 *  Source:
 *    http://ennuidesign.com/blog/Beautiful+Forms+with+JavaScript/
 */

(function($) {
  
  /**
   * Plugin definition
   */
  $.fn.prettyForm = function(options) {
  	debug(this);
 
 		// build main options before element iteration
 		var opts = $.extend({}, $.fn.prettyForm.defaults, options);
 		
 		// iterate and reformat each matched element
 		return this.each(function() {
   		$form = $(this);
   		
   		$("label[for]", $form ).filter(opts.labelFilter).each( function() { 
   			var label = $(this);
   			var labelVal = $(label).html();
        var id = label.attr( 'for' );
        
        if ( id != '' ) {
        	var field = $("#"+id, $form );
         	 
         	$(field).attr("value", labelVal);
         	$(field).attr("default", labelVal);
        	
        	if( $(field).attr("type") != 'checkbox' && $(field).attr("type") != 'radio' ) {
        		$(label).hide();
        	}
        	
        	$(field).focus( function() { textFocus(this);	});
        	$(field).blur( function() { textBlur(this);	});
      	}
   		});
 		});
  };
  
  /**
   * private function for debugging
   */
  function debug($obj) {
 		if (window.console && window.console.log) {
   		window.console.log("prettyForm selection count: " + $obj.size());
   	}
  };
  
  /**
   * private function
   */
  function textFocus(input) {
  	if( $.fn.prettyForm.isDefault(input) ) {
    	$(input).attr("value", '');
  	} else {
    	return false;
  	}
	}

	/**
   * private function
   */
	function textBlur(input) {
	  if( $(input).val() == '' ) {
	    $(input).attr("value", $(input).attr("default") );
	  } else {
	    return false;
	  }
	}
  
  $.fn.prettyForm.reset = function(input) {
  	$(input).attr("value", $(input).attr("default"));
  }
  
  $.fn.prettyForm.isDefault = function(input) {
  	return $(input).attr("default") == $(input).val() ? true : false;
  }
  
  $.fn.prettyForm.isTextValid = function(input) {
  	return (!$.fn.prettyForm.isDefault(input) && ($(input).val() != '') );
  }
  
  $.fn.prettyForm.isEmailValid = function(input) {
  	var emailReg = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if( $.fn.prettyForm.isDefault(input) ) {
			return false;
		} else if( !emailReg.test($(input).val()) ) {
			return false
		}
		
		return true;
  }
  
  /**
   * plugin defaults
   */
  $.fn.prettyForm.defaults = {
  	labelFilter: 	'label'
  };

})(jQuery);

