// Requires Prototype JavaScript framework, version 1.4+ 
Form.Validator = Class.create();
Form.Validator.prototype = {
	initialize: function(form_id, submit_button_id, fields) {
		// Setup the form.
		this.form = $(form_id);
		this.form.onsubmit = Form.Validator.makeSubmitFunction(fields, this);
		
		// Setup validators on the elements.
		this.fields = fields;
		this.elements = Form.getElements(this.form);
		this.valid = new Object();
		for ( var i = 0; i < this.elements.length; i++ ) {
			var field = this.fields[this.elements[i].id];
			if ( field ) {
				var input = $(this.elements[i].id);
				input.onfocus = Form.Validator.makeFocusFunction(field[0], field[1]);
				input.onblur = Form.Validator.makeBlurFunction(field[0], field[1]);
				input.onblur();
				this.valid[this.elements[i].id] = false;
			}
		}

		// Hook up the submit button.
//		this.submitButton = $(submit_button_id);
//		this.submitButton.disabled = true;
	}
};

Form.Validator.makeSubmitFunction = function(fields, thisValidator) {
	return function(x) {
		for ( var i in thisValidator.fields ) {
			var field = $(i);
			var fieldValidator = $(thisValidator.fields[i]);
			if ( field.value == fieldValidator[1] ) { field.value = ''; }
		}
		return true;
	};
}

Form.Validator.makeFocusFunction = function(regex, defaultValue) {
	return function(x) {
		if ( this.value == defaultValue ) {
			this.value = '';
			this.style.color = '';
		}
		return true;
	};
};

Form.Validator.makeBlurFunction = function(regex, defaultValue) {
	return function(x) {
		if ( this.value == '' || this.value == defaultValue ) {
			this.value = defaultValue;
			this.style.color = '#bbb';
		}
		return true;
	};
};

function toggleCheckbox(id) {
	var cb = $(id);
	cb.checked = !cb.checked;
}

function checkState(element) {
	(element.value == 'USA')
		? $('state').show()
		: $('state').hide();
}

function removeInvite(id) {
	new Ajax.Updater('selector', '/gathering/invites?uninvite='+id, {asynchronous:true, evalScripts:true});
	$(id).show();
}

function checkboxByName(form_name, state) {
	Form.getElements(document.forms[form_name]).each(function(el){el.checked=state;});
}

function checkboxInvertByName(form_name) {
	Form.getElements(document.forms[form_name]).each(function(el){el.checked=!el.checked;});
}

function submitTagForm(form, url) {
	new Ajax.Updater('drop_friend', url, {
		evalScripts:true,
		parameters:Form.serialize(form),
		onLoading:function(req){$('new_tag_spinner').show();},
		onComplete:function(req){$('new_tag_spinner').hide();}
	});
	new Ajax.Updater('filter_tags_outer', '/person/filtertags', {
		evalScripts:true,
		asynchronous:true
	});
	return false;
}
