/************************************************

	Groups - dsvalidate

	/includes/js/jquery/dsvalidate.js

	Copyright © DailyStrength, 2008.
	
	This file is meant to extend the jquery validator plugin, adding support for ds-specific remote validation.

***/

// Adding validation method : dsremote
jQuery.validator.addMethod("dsremote", function dsremote_callback(value, element, method) { 	
	
	// init value cache
	if(this.valueCache[method] !== undefined) {
		vCache = this.valueCache[method];
	} else {
		vCache = this.valueCache[method] = {};
	}
	
	// return cached value if we got it
	if( vCache[value] !== undefined ) {
		return vCache[value];
	}
	else {
		// otherwise phone it in
		ds_remote_api_jq( method, value, { 
			success: function(o) { 
				var url_available = JSON.parse(o);
				var el_id = $(element).attr('id');
				var form_id = $(element).parents("form").eq(0).attr('id');
				vCache[value] = url_available=="true";
				jQuery.validator.get(form_id).element("#"+el_id);
			}, 
			failure: function(o) { }
		}); 
	}
	return true;
	
}, "" );

// Adding validator storage
jQuery.extend(jQuery.validator, {
	validators: {},
	store: function(form_id, validator) {
		return this.validators[form_id] = validator;
	},
	get: function(form_id) {
		return this.validators[form_id];
	}
});

// Creating new dsvalidation function
jQuery.extend(jQuery.fn, {
	dsvalidate: function( options ) {
		return jQuery.validator.store(this.attr('id'), this.validate( options ));
	}
});