/*** validation.js
 * V0.2
 * Handles mupltiple forms on a page
 * 21/09/2011
 *
 * V0.1 
 * 23/6/2011
 * Code for validating forms and other form related functions
 *
 * Copyright Diligence Group ltd 2011
**/

	//Set up global variables
	var validation_type = "alert";
	var validation_time = "submit";
	var invalid_class = "invalid";

	var field_valid = true;
	var valid=true;
	var validation_confirmed=false;
	var alert_str = "";
	var form_name = "";
	var ok = false;
	
		//Bind the appropriate handler to inputs on the page
	
		
		alert_str = "";
		$("form").submit(function(e) {
			valid=true;
			alert_str = "";
			form_name = $(this).attr('name');
			if(!validation_confirmed) {
				e.preventDefault();
				$("form[name='"+form_name+"'] input, form[name='"+form_name+"'] select, form[name='"+form_name+"'] textarea").each(validateMe);
				
				if(valid) {
					validation_confirmed = true;
					$(this).submit();
					
					return true;
				}
				else{
					switch(validation_type) {
						case "alert" :
							alert(alert_str);
							break;
						case "dialog" :
							$("#alert_dialog_str").html(alert_str);
							$("#alert_dialog").dialog("open");
							break;
					}
					return false;
				}
			}	
			else
				{
				return true;
				}
		});
			
	
	if(validation_time!="submit"){
		
		$("input,select,textarea").bind(validation_time, validateMe);
	}	
	
	/** The validation function
	 * This runs for each field in the form that requires validation
	**/
function validateMe() {
		field_valid=true;
		var msg = "";
		//if this is a required field validate it
		if($(this).hasClass("required")) {	
			switch($(this).get(0).tagName) {
				case "SELECT" :	
				case "TEXTAREA" :
					field_valid = $(this).attr("value")!='';
					break;
				default :
		
					break;
			}
			
			if(field_valid) {
				switch($(this).attr("type")) {
					case "text" :
					case "textarea" :
					case "password" :
						
						//first check that the field has a value
						field_valid = $(this).attr("value")!="";
						//if it does and there are other checks to do, carry them out now
						if((field_valid) && ($(this).hasClass("email")))
							field_valid = isEmail($(this).attr("value"));
						if((field_valid) && ($(this).hasClass("date")))
							field_valid = isDate($(this).attr("value"));
						if((field_valid) && ($(this).hasClass("telephone")))
							field_valid = isTelephone($(this).attr("value"));					
						if((field_valid) && ($(this).hasClass("match")))
							field_valid = ($(this).attr("value") == $("input[name='"+$(this).attr("rel")+"']").attr("value"));					
						break;
					case "select-one" :
					case "select-multiple" :
						field_valid = $(this).attr("value")!='';
						break;
					case "radio" :
						field_valid = isSelected($(this).attr("name"));			
						break;
					case "checkbox" :
						field_valid = isChecked($(this).attr("name"));
						break;
				}	
			}
			
			
			//Display the appropriate message where required
			if((typeof validation_text_array == "object") && (validation_text_array[form_name]) && (validation_text_array[form_name][$(this).attr("name")]!="")) {
				msg = validation_text_array[form_name][$(this).attr("name")];
			}
			else {
				msg = $(this).attr("title");
			}
			
			switch(validation_type) {
				case "alert" :
					if(!field_valid)
						alert_str += msg+"\n";
					break;
				case "dialog" :
					if(!field_valid)
						alert_str += msg+"<br />";
					break;
				case "label" :
					if(!field_valid)
						$("label[for='"+$(this).attr("name")+"']").html(msg);
					else
						$("label[for='"+$(this).attr("name")+"']").html("");
					break;
				case "div" :
					if(!field_valid)
						$("div[id='"+$(this).attr("name")+"']").html(msg);
					else
						$("div[id='"+$(this).attr("name")+"']").html("")
					break;
			}
			
			if((!field_valid) && (invalid_class)){
				$(this).addClass(invalid_class);
				}
			else if((field_valid) && (invalid_class))
				$(this).removeClass(invalid_class);
		}
		
		if(!field_valid) valid = false;
		//return field_valid;
	}



/** Copying data between fields eg delivery address -> billing address **/
$("#copy_data").change(function() {
	 if(this.checked) {
	 
	 	$("input[id^='target']").each(function() {
	 		arr = $(this).attr("id").split("_");
	 		$(this).attr("value", $("#source_"+arr[1]).attr("value"));
	 	
	 	});
	}							 
});



/** Validate single and multiple checkboxes by name **/
function isChecked(chkbx) {
	var checked = $("input[name='"+chkbx+"']:checked").length; 
	if (checked == 0) 
	{ 
	return false; 
	} 
	else 
	{ 
	return true; 
	} 
} 

/** Validate single and multiple radio buttons by name **/
function isSelected(chkbx) {
	var checked = $("input[name='"+chkbx+"']:checked").length; 
		if (checked == 0) 
	{ 
	return false; 
	} 
	else 
	{ 
	return true; 
	} 
} 

/** Telephone numbers should consist of ()-+ and between 10-14 digits**/
function isTelephone(str) {
	var test = "-+() ";
	var digits = "1234567890";
	var myvalid=false;
	var mycount=0;
	for(i=0;i<str.length;i++) {
		if((test.indexOf(str.charAt(i))==-1) && (digits.indexOf(str.charAt(i))==-1)) return false;
		if(digits.indexOf(str.charAt(i))>-1) mycount++;
	}
	if((mycount<10) || (mycount>14)) return false;
	return true;
}



/** isEmail()
 * Returns true if given string is a valid email address
**/
function isEmail(str){
	if((str.indexOf('@')==-1)||(str.indexOf('.')==-1)){
		//alert("Invalid email address");
		return false;
	}
	else
		return true;
}


/** isMaxLength()
 * Puts an alert on textareas when maxmimum entry length is reached
**/
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength){
		obj.value=obj.value.substring(0,mlength)
		alert("Maximum character length of "+mlength+" reached");
	}
}


/** submitForm()
 * Allows submission and validation of forms by a normal link
 **/
function submitForm(theform){
	//if(validate) ok = validateForm(theform);
	 eval("document."+theform+".submit()");
}


/** 
* Copying data between fields eg delivery address -> billing address 
* Runs when a checkbox with id 'copy_data' is ticked
* Copies data from fields with id=source_xxx to id=target_xxx
**/
$("#copy_data").change(function() {
	 if(this.checked) {
	 
	 	$("input[id^='target']").each(function() {
	 		arr = $(this).attr("id").split("_");
	 		$(this).attr("value", $("#source_"+arr[1]).attr("value"));
	 	
	 	});
	}							 
});


