// Define the validstatechange event...

(function( $ ){
 		
	var testvalidity = function(target, e){
		
		
		target = $(target);

		var currentstate = target.data("validstate.currentstate");
		var newstate = target.isValid();
		
		//Store current validstate
		target.data("validstate.currentstate", newstate);
		
		if( currentstate != newstate){
			//Raise event
			target.triggerHandler( "validstatechange" );
		}
			
	}
	
	// ------------------------------------------------------ //
	// ------------------------------------------------------ //
 
 
	// Define our special event:
	$.event.special.validstatechange = {
 
		// This method gets called the first time this event
		// is bound to THIS particular element. It will be
		// called once and ONLY once for EACH element.
		setup: function( eventData, namespaces ){
			// Bind events
 			var target = $(this);
			target.data( "validstate.change", target.isValid() );
			
			target.bind( "input keyup change blur", function(e){testvalidity( target, e);} );
			//$( ":input[type=checkbox]", target).bind( "click", function(e){testvalidity( target, e);} );
			
			
			// Return void as we don't want jQuery to use the
			// native event binding on this element.
			return;
		},
 
		// This method gets called when this event us unbound
		// from THIS particular element.
		teardown: function( namespaces ){
			
			// Remove bound events.
			
			
			// Return void as we don't want jQuery to use the
			// native event binding on this element.
			return;
		}
 
 
	};
 
})( jQuery );



//Custom properties
jQuery.fn.extend({
	
	isValid: function(markinvalidfields) {

		var $this = $(this);

		var valid = true;
		
		if( $this.is(":input") ){
			var e = $this.get(0);
			if(markinvalidfields)H5F.checkField(e);
			return e.validity.valid;
		}

		$(":input:not([type=button], [type=submit])", $this).each( function(){
			
			if(markinvalidfields)H5F.checkField(this);
			if(this.validity && !this.validity.valid) valid = false;
		});

		return valid;
	}
	
});



// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};
