/*** validation.js
 * V0.1 
 * 23/6/2011
 * Code for validating forms and other form related functions
**/

	/** Validation settings **/
	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 = "";
	
	//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);
	}	
	
	function validateMe() {
		field_valid=true;
		
		//if this is a required field validate it
		if($(this).hasClass("required")) {	
		//alert($(this).get(0).tagName+" : "+$(this).attr("type"));
			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
			switch(validation_type) {
				case "alert" :
					if(!field_valid)
						alert_str += validation_text_array[form_name][$(this).attr("name")]+"\n";
					break;
				case "dialog" :
					if(!field_valid)
						alert_str += validation_text_array[form_name][$(this).attr("name")]+"<br />";
					break;
				case "label" :
					if(!field_valid)
						$("label[for='"+$(this).attr("name")+"']").html(validation_text_array[form_name][$(this).attr("name")]);
					else
						$("label[for='"+$(this).attr("name")+"']").html("");
					break;
				case "div" :
					if(!field_valid)
						$("div[id='"+$(this).attr("name")+"']").html(validation_text_array[form_name][$(this).attr("name")]);
					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"));
	 	
	 	});
	}							 
});


/** Return true if a specific checkbox is checked **/
function isChecked(chkbx) {
	var checked = $("input[name='"+chkbx+"']:checked").length; 
	if (checked == 0) 
	{ 
	return false; 
	} 
	else 
	{ 
	return true; 
	} 
} 

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;
}



function isDate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false

if (!validformat.test(input))
	return false;
else{ //Detailed check for valid date ranges

var monthfield=input.split("/")[0]
var dayfield=input.split("/")[1]
var yearfield=input.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
return false;
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}

/******************************************* OLD CODE ****************************************/


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");
}
}


function submitForm(theform){
	$("#"+theform).submit();
}


//check that all fields with classname 'required' are filled in
function validateForm(formname, classname, check_default){
if(!classname) classname="required";
var elems=eval("document."+formname+".elements"); 
var valid=true;
var alert_text = "Please fill in the highlighted fields.";
var radio = true;
var checkbox = true;
var email=true;



for(var i=0;i<elems.length;i++){
	if(elems[i].className.indexOf(classname)>=0){
	switch(elems[i].type) {
			case "text" :
				if(elems[i].name=='email_address'){
					if(!isEmail(elems[i].value)){
						elems[i].style.backgroundColor="#FE938D";
						valid=false;
						email = false;
					}
					else
						elems[i].style.backgroundColor="#f3f8fa";
					
				}
			case "textarea" :
			case "password" :
				if( (elems[i].value=="")  || ((check_default) && (elems[i].value==elems[i].defaultValue))){
					valid=false;
					elems[i].style.backgroundColor="#FE938D";
				}
					else
						elems[i].style.backgroundColor="#f3f8fa";
				break;
			case "select-one" :
				if(elems[i].value==''){
					//alert("Please select an option from the dropdowns");
					elems[i].style.backgroundColor="#FE938D";
					valid=false;
				}
					else
						elems[i].style.backgroundColor="#f3f8fa";
				break;
			case "radio" :
				if(!isSelected(formname, elems[i].name)){
						elems[i].style.backgroundColor="#FE938D";
						radio = false;
						valid=false;
					
				}
				break;
			case "checkbox" :
				if(!isChecked(formname, elems[i].name)){
						elems[i].style.backgroundColor="#FE938D";
						checkbox=false;
						valid=false;
				}
				break;
		}
		//if(!valid){
		//	return valid;
		//}
	}
}
if(!radio)
	alert_text += "\nPlease tick all required radio buttons";
if(!checkbox)
	alert_text += "\nPlease tick all required checkboxes";
if(!email)
	alert_text += "\nPlease enter a genuine email address";
	
if(!valid)
	alert(alert_text);
	
return valid;
}




function isEmail(str){
	if((str.indexOf('@')==-1)||(str.indexOf('.')==-1)){
		//alert("Invalid email address");
		return false;
	}
	else
		return true;
}
/*** This validation function checks that an email address contains both '@' and '.' **/
function validateEmailAddress(email_address){
var email = document.getElementById(email_address).value;
	if((email.indexOf('@')==-1)||(email.indexOf('.')==-1)){
		//alert("Invalid email address");
		return false;
	}
	else
		return true;
}

//Check that two fields have the same values, useful for password changes etc
function validateSame(type, retype){
if(document.getElementById(type).value == document.getElementById(retype).value)
	return true;
else{
	return false;
}
}

//Check if this element is an array
function isArray(obj) {
	if(!obj) { 
	return false;
	}
	try{ if((NodeList!="undefined") && (obj instanceof NodeList)) return true;} catch(e) {}
	try{ if((HTMLCollection!="undefined") && (obj instanceof HTMLCollection)) return true;} catch(e) {}

	if(!obj.constructor){ 
	return false;
	}
	if(!obj.constructor.indexOf) { 
	return false;
	}
return (obj.constructor.indexOf("Array") != -1);
}

