Event.observe(window, 'load', function() {
  	Event.observe('contactform', 'submit', processOrder);
});


function processOrder(eventid){
	eventid.stop();
	
	var reason = "";
	reason += validateEmail($('email'));
	reason += validatePhone($('phone'));
	reason += validateEmpty($('name'), "Name");
	reason += validateEmpty($('type'), "Question Type");	
	reason += validateEmpty($('message'), "Message");	
	
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
	} else {
		var myNewAjax = new Ajax.Request('/contact/process.php', { method: 'post', parameters: Form.serialize('contactform')
			, onSuccess: function (originalResponse) {
			JSONresponse = originalResponse.responseJSON;
			location.href=JSONresponse.statusURL;
			}
		});	

	}
}

function validateEmpty(fld,theinfo) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "--  " + theinfo + " is empty.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

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

}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "--  Email address is empty.\n";
    } else if (!emailFilter.test(tfld)) {
        fld.style.background = 'Yellow';
        error = "-- Email address is invalid.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "-- Email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    
   if (fld.value == "") {
        error = "--  Phone number.\n";
        fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "-- Phone number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "-- Phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    }
    return error;
}
