// JavaScript Document
//validate contest form entries
//classified_validate.js

function formValidator(){
	// Make quick references to our fields
	var name = document.getElementById('name');
	var address = document.getElementById('address');
	var email = document.getElementById('email');
	var phone = document.getElementById('phone');
	var ad_category = document.getElementById('ad_category');
	var adcopy = document.getElementById('adcopy');
	
	// Check each input in the order that it appears in the form!
	if(isEmpty(name, "Please enter your name")){
		if(isEmpty(address, "Please enter a valid address")){
				if(isEmpty(email, "Please enter an email address, if you do not wish to display this information in the ad, please deselect the appropriate checkbox")){
						if(emailValidator(email, "Please enter a valid email address, if you do not wish to display this information in the ad, please deselect the appropriate checkbox")){
							if(isEmpty(phone, "Please enter a valid telephone number, if you do not wish to display this information in the ad, please deselect the appropriate checkbox")){
								if(isEmpty(ad_category, "Please enter a valid category")){
					if(lengthRestriction(adcopy, 2, 255)){
							return true;
					}
				}
			}
		}
	}
	
   }

}

	return false;
	
}

function isEmpty(elem, helperMsg){
	if(elem.value == ""){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}

function isNumeric(elem, helperMsg){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isAlphanumeric(elem, helperMsg){
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function lengthRestriction(elem, min, max){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <= max){
		return true;
	}else{
		alert("Sorry, you ad is too long. Ad text should be between" +min+ " and " +max+ " characters in length");
		elem.focus();
		return false;
	}
}

function madeSelection(elem, helperMsg){
	if(elem.value == "Please Choose"){
		alert(helperMsg);
		elem.focus();
		return false;
	}else{
		return true;
	}
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+\']+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
