/**
 * @version		$Id$
 * @package		Hotproperty
 * @subpackage	Javascript
 * @copyright	(C) 2008 Mosets Consulting
 * @url			http://www.mosets.com/
 */

var MosetsFormValidator = JFormValidator.extend({
	/**
	 * Function to attach a MosetsFormValidator object to a form
	 * 
	 * Overload JFormValidator.attachToForm to automatically check a form when it is submited
	 *
	 */
	attachToForm: function(form)
	{
		// On submitting form, just return the validate value
		form.onsubmit = function(){return document.formvalidator.isValid(form);};
		
		// Iterate through the form object and attach the validate method to all input fields.
		$A(form.elements).each(function(el){
			el = $(el);
			if ((el.getTag() == 'input' || el.getTag() == 'button') && el.getProperty('type') == 'submit') {
				if (el.hasClass('validate')) {
					el.onclick = function(){return document.formvalidator.isValid(this.form);};
				}
			} else {
				el.addEvent('blur', function(){return document.formvalidator.validate(this);});
			}
		});
	},
	
	/**
	 * Function to validate form elements
	 * 
	 * Overload JFormValidator.isValid to not check disabled elements
	 *
	 */
	isValid: function(form)
	{
		var valid = true;

		// Validate form fields
		for (var i=0;i < form.elements.length; i++) {
				if (!form.elements[i].disabled && this.validate(form.elements[i]) == false) {	// Don't check disabled elements
				valid = false;
			}
		}

		// Run custom form validators if present
		$A(this.custom).each(function(validator){
			if (validator.exec() != true) {
				valid = false;
			}
		});

		return valid;
	}
});

document.formvalidator = null;
Window.onDomReady(function(){
	document.formvalidator = new MosetsFormValidator();
	
	// A custom handler to validate a list of items separated with '|'
	document.formvalidator.setHandler('pipelist', function(value){
		regex=/^[^\|]+(\|[^\|]+)*$/;
		return regex.test(value);
	});
});