
var vSummary;
var name = "";
var address = "";
var phone = "";
var email = "";
function resetErrors(){
	vSummary = "";
	document.getElementById('nameError').style.visibility = 'hidden';
	document.getElementById('zipError').style.visibility = 'hidden';
	document.getElementById('phoneError').style.visibility = 'hidden';
	document.getElementById('emailError').style.visibility = 'hidden';
	document.getElementById('validationSummary').style.display = 'none';
}

function showErrorSummary(){
	document.getElementById('validationSummary').innerHTML = vSummary;
    document.getElementById('validationSummary').style.display = 'block';
}
function showError(element){
	document.getElementById(element).style.visibility = 'visible';
}

function checkName(val){
    if (val == "" || val == null) {
        showError('nameError');
        vSummary += "Name is required. <br />";
        return false;
    }
    else {
        return true;
    }
}

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

function validateForm(form){
    resetErrors();
	name = trim(form.txtName.value);
	phone = trim(form.txtPhone.value);
	email = trim(form.txtEmail.value);
	zip = trim(form.txtZip.value);
	
    if (!checkName(name)) {
        showErrorSummary();
        return false;
    }
	else if ((phone == "" || phone == null) && (email == "" || email == null) ) {
		showError('emailError');
		showError('phoneError');
        vSummary += "Email or phone number is required. <br />";
		showErrorSummary()
        return false;
    }
	else if (!(phone == "" || phone == null) && !checkPhone(phone)){
        showErrorSummary();
		return false;
	}
	else if (!(email == "" || email == null) && !checkEmail(email)){
		showErrorSummary();
		return false;
	}
	else if((phone != "") && (email != "")){
		if (!checkEmail(email)) {
			showErrorSummary();
			return false;
		}
		if (!checkPhone(phone)) {
			showErrorSummary();
			return false;
		}
	}
	else if (zip != ""){
		if(!checkZip(zip)){
			showErrorSummary();
			return false;
		}
	}
	
}

function checkPhone(val){	
    // Check for correct phone number
	phoneRe = /^[2-9]\d{2}-\d{3}-\d{4}$/;
    rePhoneNumber = new RegExp(/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/);
    if (!phoneRe.test(val)) {
        vSummary += "Phone Number Must Be Entered As: 555-555-1234. <br />";
		showError('phoneError');
		return false;
    }
	else return true;
}

function checkEmail(val){	
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(pattern.test(val)){         
		return true;   
    }else{   
		vSummary += "Email address is invalid. <br />";
		showError('emailError');
		return false; 
    }
}

function checkZip(val){	
    var pattern=/^\d{5}/;
    if(pattern.test(val)){         
		return true;   
    }else{   
		vSummary += "Zip code is invalid. <br />";
		return false; 
    }
}

