function clearSampleInput (event) {
	event.target.value = '';
	$(event.target).removeClass('form_sampleinput');
}
function setFormControlSampleInput (controlSelector, sampleInput) {
	$(controlSelector).addClass('form_sampleinput').one('focus',clearSampleInput).get(0).value = sampleInput;
}


var validators = {
	email: function (value) {
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   if(reg.test(value) == false) {
	      return 'Invalid e-mail address';
	   }
	   return null;
   },
	password: function (value) {
		if (value.length < 5) return 'Must be at least 5 characters long.';
		if (value.length > 20) return 'Cannot be longer than 20 characters.';
	   return null;
   },
	name: function (value) {
		if (value.length > 30) return 'Cannot be longer than 30 characters.';
	   return null;
   },
	title: function (value) {
		
		if (value.length > 255) return 'Cannot be longer than 255 characters.';
	   return null;
   },
	urlpart: function (value) {
		
		if (value.length > 24) return 'Cannot be longer than 24 characters.';
		value = value.toLowerCase();
		var re = /^[0-9a-z_ ]+$/;
		if (!value.match(re)) {
			return "Can only contain simple letters, numbers and underscores.";
		}
	   return null;
   },
   exist: function (value) {
   		if (value.length == 0) return 'Required'
   		return null;
   }
};




function doSuccess(o) {
	setTimeout("doSuccess2('"+o.id+"')", 100);
}
function doSuccess2(id) {
	$('#' + id + '_div').removeClass("error");
	$('#' + id + '_div').addClass("success");
	$('#' + id + '_si').html('<span class=formsuccessmark>&#10003;</span>');
	$('#' + id + '_msg').html("");
	$('#' + id + '_msg').css('display','none');
	$('#' + id + '_hos').css('display','none');
}

function doError(o,m) {
      $('#' + o.id + '_div').removeClass("success");
      $('#' + o.id + '_si').html("");
      $('#' + o.id + '_hos').css('display','inline');

	// message is hidden until form is first submitted
	if (m) {
		$('#' + o.id + '_msg').html('<span class=formfailuremark>!</span>'+m);
	}

	if (o.form.firstSubmitAttempted) {
	  $('#' + o.id + '_msg').css('display','block');
      $('#' + o.id + '_div').addClass("error");
	}
	else {
	  $('#' + o.id + '_msg').css('display','none');
	}
 }
 

function validateAndSubmitForm (form) {
	if (!form.firstSubmitAttempted) {
		form.firstSubmitAttempted = 1;

		form.fieldsToValidateInThisForm.each(function(){
			if (this.needsValidationOnSubmit) {
				validateFormField(this);
			}
		});
	}

	return checkWhetherFormIsValid(form);
}

// check whether the form (as a whole) is valid and enable/disable the submit 
// button appropriately
function checkWhetherFormIsValid (form) {
	var submitControl = $('#' + form.id + ' :submit').get(0);
	var wholeFormIsValid = true;
	$(submitControl.form.fieldsToValidateInThisForm).each(function() {
		if (!this.valid) {
			wholeFormIsValid = false;
		}
	});
	
	return wholeFormIsValid;
}


function formFieldIsEmpty (formField) {
	if (formField.value == '') return true;
	
	// richtext validation disabled
	if (formField.validatetype == 'richtext') return false;
	
	return false;
}

function validateFormField (formField) {
	if (formField.validatetype == 'submit') return;
	if (formField.id == '') {
		console.log('validateFormField: form field '+formField.name+' has no id; cannot validate');
		return;
	}
	var validateFunction = validators[formField.validatetype];
	if (!(validateFunction)) { 
		// This is no longer considered an error condition.  Not
		// all validatetypes have a validator function (some are just used
		// for switching which form controls to render.)
		return true;
	}

	var validValueBeforeCheck = formField.valid;
	if (formFieldIsEmpty(formField)) {
		if (formField.isoptional) {
			doSuccess(formField);
			formField.valid = true;
		}
		else {
			doError(formField, 'Required field');
			formField.valid = false;
		}
	}
	else {
		var response = validateFunction(formField.value);
		if (response == null) {
			doSuccess(formField);
			formField.valid = true;
		}
		else {
			doError(formField, response);
			formField.valid = false;
		}
	}
	if (formField.form.firstSubmitAttempted) {
		formField.needsValidationOnSubmit = false;
	}
	if (formField.valid != validValueBeforeCheck) {
		checkWhetherFormIsValid(formField.form);
	}
	return formField.valid;
}


function initFormValidation () {
	
	$('input[validatetype],textarea[validatetype]').each(function() {
		var validatetype = this.attributes['validatetype'].value;
		if (validatetype == 'submit') {
			var submitControl = this;
			var form = submitControl.form;
			if (form.id == '') {
				console.log('initFormValidation: missing form id; cannot enable form validation');
				return;
			}

			
			if (form.formValidationInitialized) return;
			form.formValidationInitialized = 1;
		
			submitControl.valid = true;
			submitControl.needsValidationOnSubmit = false;
			form.fieldsToValidateInThisForm = $('#' + form.id + ' input[validatetype],#' + form.id + ' textarea[validatetype]');
			$(form).bind('submit',function(event) { return validateAndSubmitForm(form); });
		}
		else {
			var isoptional = false;
			if (this.attributes['optional'] && (this.attributes['optional'].value=='true')) isoptional = true;
			this.validatetype = validatetype;
			
			

			// richtext validation disabled (need to integrate with TinyMCE)
			if (validatetype == 'richtext') this.valid = true;
			else if (!formFieldIsEmpty(this)) this.valid = true;
			else this.valid = isoptional;
			this.needsValidationOnSubmit = true;
			
			this.isoptional = isoptional;
			if (isoptional) {
				$('#'+this.id+'_hos').append(' (optional)');
			}
			
			if (validatetype != 'richtext') {
				$(this).bind('change', function() {
					validateFormField(this); 
				});
			}
		}
	});
}