/* formValidation.js
An automatic form validation tool.

Reads attributes of <input> fields to determine how to validate.

Usage: validate(dom_element_id, options)
Setup: Input type keys off of the <input> 'name' field. eg.
	<input name='emailAddress'> 
will validate an email address.

emailAddress: text@text.text
tempC: integer between 0 and 100
*/

var validator = {
	"tempC": function(val) {
		return ( (val>=0) && (val<=100) )
	},

	"emailAddress": function(val) {
		return val.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)
	}	
}

function preValidate() {
	// validate input fields when they are changed
	$(':input').each( function() {
		validate(this)
		var validateFunc = function() {
			validate(this)
			if (this.type != 'radio') {
				$(this).siblings(':radio').attr('checked',true)
			}
		}
		$(this)
			.change(validateFunc)
			.keyup(validateFunc)
	})

	// Make sure everything's valid when the user clicks 'submit'
	$(':submit').click( function() {
		if (!validateAll()) {
			alert('Please verify all field are filled out correctly.')
			return false
		}
	})

	// Create tooltips
	$(':text, textarea').each( function() {
		if (this.title) {
			$(this).after( 
				$("<span></span>")
					.addClass('tooltip')
					.css('display', 'none')
					.append("<img src='../shared/images/leftbracket.png />")
					.append("<span class='rounded_big'><div>"+this.title+"</div></span>")
			)
			$(this).focus( function() {
				$(this).next('.tooltip').css('display','')
			})
			$(this).blur( function() {
				$(this).next('.tooltip').css('display','none')
			})
		}
	})
}

function validate(element) {
	var valid = true

	if (validator[element.name]) {
		valid = validator[element.name](element.value)
	}

	if (valid) {
		$(element).css('border-color', '')
	} else {
		$(element).css('border-color', 'red')
	}
	return valid
}

function validateAll() {
	var valid = true
	$(':input').each( function() {
		if (!validate(this)) valid = false
	})
	return valid
}
