function isEmpty(fld) {
    var error = false;
 
    if (fld.length == 0) {
       
        error = true;
    } else {
        error = false;
    }
    return error;  
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function isPostcode(fld) {
    //var postcodeFilter = /([0-9]){4}\s{1}([A-Z]){2}/ ;
	 var error =false;
    var stripped = fld.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld == "") {
        error = true;       
    } else if (isNaN(parseInt(stripped))) {
        error = true;        
    } else if (!(stripped.length <= 6 && stripped.length >= 6)) {
      	error = true;      
    }
    return error;
}
   
function isEmail(fld) {
    var error=false;
    var tfld = trim(fld);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld == "") {        
        error = true
    } else if (!emailFilter.test(tfld)) {         
        error =true;
    } else if (fld.match(illegalChars)) {
        error = true;
    } else {
       error = false;
    }
    return error;
}

function isPhone(fld) {
    var error =false;
    var stripped = fld.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld == "") {
        error = true;       
    } else if (isNaN(parseInt(stripped))) {
        error = true;        
    } else if (!(stripped.length <= 14 && stripped.length >= 10)) {
      	error = true;      
    }
    return error;
}

function isEmptyMultipleChoice(field) {
	var error = false;
	var fieldValue = field.find('option:selected').html();
	if (fieldValue == "") {
		error = true;
		
	}

	return error;
}



	function validate(fieldsToCheck){
		var formContainsErrors = false;
		for(var i=0; i < fieldsToCheck.length; i++){
			var field = fieldsToCheck[i].field;
			var validation = fieldsToCheck[i].validation;
			error = false;
			if(validation  == "isEmpty"){				
				var error = (isEmpty(field.val())) ? true : false;
			}
			if(validation  == "isEmail"){
				var error = (isEmail(field.val())) ? true : false;
			}
			if(validation  == "isPhone"){
				var error = (isPhone(field.val())) ? true : false;
			}
			if(validation  == "isPostcode"){
				var error = (isPostcode(field.val())) ? true : false;
			}
			if(validation  == "isEmptyMultipleChoice"){
				var error = isEmptyMultipleChoice(field);
				
			}
			if(error){		
				field.addClass("wrong");
				formContainsErrors = true;
			}else{
				field.removeClass("wrong");
			}
		}
		
		return formContainsErrors;
	}
