/*
 * JQUERY OWNS YOUR FACE
 * 
 * Passing variables to the individual validation functions can probably be removed with proper jQuery use.
 * Oh and did I mention this is as dynamic as my gogogadget cock? 
 */

/*
* Onload
*/
window.onload = attachFormHandlers;

/*
 * Globals
 */
// Input defaults
var defaults = [];
	defaults['name'] 	= "Name *";
	defaults['company'] = "Company Name *";
	defaults['email'] 	= "Email *";
	defaults['tel'] 	= "Telephone *";
	defaults['message'] = "Enter your message here...";
// Error messages	
var errors = [];
	errors['required']= "Required field";
	errors['email'] 	= "Please enter a valid email address";
	errors['tel'] 	= "Please enter a valid UK phone number";
// Input regexp
var email_reg = /^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/;
var tel_reg = /^0[127]\d{9}$/;
// Valid marker image
var valid_img = '<img src="http://www.glossopbsg.com/images/uploads/tick.gif" border="0" />';


/*
 * Event listeners
 */
function attachFormHandlers() {
	// Input listeners
	$('input[type=text]').each(
		function(){
			// onFocus: Clear default
			$(this).focus(
				function(){clearDefault(this);}
			);
			// onBlur: Validate / set default
			$(this).blur(
				function(){
					setDefault(this);
					return validateThis(this);
				}
			);
		}
	);

	// Textarea listeners
	$('textarea').each(
		function(){
			$(this).focus(
					function(){clearDefault(this);}
				);
			$(this).blur(
				function(){
					setDefault(this);
					return validateThis(this);
				}
			);
		}
	);
	
	// Onsubmit listener
	$('form').submit(
		function(){
			return validate();
		}
	);
}

/*
 * Validate all
 */
function validateAll() {
	// Input listeners
	$('input[type=text]').each(
		function(){
			return validateThis(this);
		}
	);

	// Textarea listeners
	$('textarea').each(
		function(){
			return validateThis(this);
		}
	);
}


/*
 * Validation routing
 */
function validateThis(obj) {
	// Retrieve params
	var val 		= obj.value; 				//get value inside of input field
	var rules 		= obj.className.split(' '); // get all the rules from the input box classname
	var id			= obj.id;					// object id - for checking defaults
	var required 	= rules[1]; 				// determines if field is required or not
	var type		= rules[2];					// field type
    
    // Determine validation to run
    switch(type) {
	    case "email":
	    	validateEmail(id,val);
	    	break;
	    case "tel":
	    	validateTel(id,val);
	    	break;
	    default:
	    	validateRequired(id,val);
	    	break;
    }
}

/*
 * Required generic field
 */
function validateRequired(id,val) {
	if(val == "" || val == defaults[id]) {
		$("#"+id+"_err").html(errors['required']);
		$("#"+id+"_msg").html("");
	}
	else {
		$("#"+id+"_err").html("");
		$("#"+id+"_msg").html(valid_img);
	}
}	

/*
 * Email field
 */
function validateEmail(id,val,target) {
	if(val.match(email_reg)) {
		$("#"+id+"_err").html("");
		$("#"+id+"_msg").html(valid_img);
	}
	else {
		$("#"+id+"_err").html(errors[id]);
		$("#"+id+"_msg").html("");
	}	
}

/*
 * Tel field
 */
function validateTel(id,val,target) {
val = val.replace(/\s+/g,'');
	if(val.match(tel_reg)) {
		$("#"+id+"_err").html("");
		$("#"+id+"_msg").html(valid_img);
	}
	else{
		$("#"+id+"_err").html(errors[id]);
		$("#"+id+"_msg").html("");
	}
}

/*
 * Onsubmit validate
 */
function validate() {
	// Errors var
	var errors = 0;
	
	// Validate all values - prevents a fresh form being submit
	validateAll();
	
	// Loop through error message elements
	$(".err").each(
		function(){
			// Colorise and prevent submit as necessary
			if($(this).html() !== "") {
				errors++;
				$(this).css("color","#ff0000");
			}else{$(this).css("color","#000");}
		}
	)
	
	// Final check
	// Prevent submit with errors
	if(errors > 0) {
		// Show message
		alert("Please make sure all fields are properly completed. Errors are marked in red!");
		// Stop submit
		return false;
	}
	// Submit without errors
	else {
		return true;
	}
}

/*
 * Clear default
 */
function clearDefault(obj){
	if(obj.value == defaults[obj.id]){
		obj.value = "";
	}
}

/*
 * Set default
 */
function setDefault(obj){
	if(obj.value == ""){
		obj.value = defaults[obj.id];
	}
}