﻿
var subjDefault = 'Please include your policy number, if available';

function validateForm() {
	var hold;

    // NAME
    hold = document.frmComments.txtName;
    if(isBlanks(hold.value)) {
        alert('Please enter your name')
        hold.focus();
        return false;
    }
    
    // PHONE
    hold = document.frmComments.txtPhone;
    if(isBlanks(hold.value)) {
        alert('Please provide a phone number');
        hold.focus();
        return false;
    }
    
	// EMAIL
	hold = document.frmComments.txtEmail.value;
	if(!isBlanks(hold)) {
	    if(hold.indexOf('@') == -1 || hold.indexOf('.') == -1) {
	        alert('Invalid email address');
	        document.frmComments.txtEmail.select();
	        return false;
	    }
	}
	
	// SUBJECT
	hold = document.frmComments.txtSubject.value;
	if(isBlanks(hold) || hold.toLowerCase() == subjDefault.toLowerCase()) {
		alert('You must enter a subject');
		document.frmComments.txtSubject.focus();
		return false;
	}
	
	// MATH QUIZ
	hold = document.frmComments.txtAnswer.value
	if(isBlanks(hold)) {
	    alert('Please answer the simple Math Quiz, which is intended to prevent\nsubmissions from automated email systems (spam)');
	    document.frmComments.txtAnswer.focus();
	    return false;
	}
	else {
	    var ans = document.frmComments.hidAnswer.value
	    if(hold != ans) {
	        alert('You\'re answer to the math quiz was incorrect');
	        document.frmComments.txtAnswer.select();
	        return false;
	    }
	}
	
			
	// COMMENTS
	hold = document.frmComments.txtComments.value;
	if(isBlanks(hold)) {
	    alert('You must enter your comments');
		document.frmComments.txtComments.select();
		return false;
	}
	
	return true;
}

function applyDefault(elem, val) {
  if(elem.value.length == 0) {
    elem.value = val;
    elem.style.color = '#777';
  
    elem.onfocus = function() {
      if(this.value.toLowerCase() == val.toLowerCase()) {
        this.style.color = '#000';
        this.value = '';
      }
    }
  
    elem.onblur = function() {
      if(isBlanks(this.value)) {
        this.style.color = '#777';
        this.value = val;
      }
    }
  }
}

function isBlanks(val) {
	for(var i = 0; i < val.length; i++) {
		var c = val.charAt(i);
		if((c != ' ') && (c != '\n') && (c != ''))
		    return false;
	}
	return true;
}

window.onload = function() {
  var subj = document.getElementById('txtSubject');
  var name = document.getElementById('txtName');
  
  name.focus();
  applyDefault(subj, subjDefault)
}