var ContactUs_Sending = false;

function ContactUs_Send () {
	if (ContactUs_Sending || !ContactUs_Verify_All())
		return;

	ContactUs_Sending = true;
	ContactUs_StateChange();
	
	ContactUs_Send_Request();
}

function ContactUs_Verify_Name () {
	$('name').value = $('name').value.trim();
	var name_failed = ($('name').value.length == 0);
	$('v_name').style.color = (name_failed ? 'red' : '');
	return !name_failed;
}

function ContactUs_Verify_Email () {
	$('email').value = $('email').value.trim();
	var email_failed = (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($('email').value));
	$('v_email').style.color = (email_failed ? 'red' : '');
	return !email_failed;
}

function ContactUs_Verify_Comments () {
	$('comments').value = $('comments').value.trim();
	var comments_failed = ($('comments').value.length == 0);
	$('v_comments').style.color = (comments_failed ? 'red' : '');
	return !comments_failed;
}

function ContactUs_Verify_All () {
	var fail = !ContactUs_Verify_Name();
	fail = !ContactUs_Verify_Email() || fail;
	fail = !ContactUs_Verify_Comments() || fail;
	return !fail;
}

function ContactUs_StateChange() {
	$('name').disabled = ContactUs_Sending;
	$('email').disabled = ContactUs_Sending;
	$('phone').disabled = ContactUs_Sending;
	$('company').disabled = ContactUs_Sending;
	$('comments').disabled = ContactUs_Sending;
	$('btnSend').src = '/images/' + (ContactUs_Sending ? 'contactus_send_d.gif' : 'contactus_send.gif');
	$('btnSend').style.cursor = (ContactUs_Sending ? '' : 'pointer');
}

function ContactUs_Send_Request () {
	new Ajax.Request('/ajax/contact.php', {
			method: 'post',
			parameters: {
				name:		$('name').value,
				email:		$('email').value,
				phone:		$('phone').value,
				company:	$('company').value,
				comments:	$('comments').value
			},
			requestHeaders: {Accept: 'application/json'},
			onFailure: function () {
				alert('There was an issue while processing your request.\n\nPlease try again later.');
				ContactUs_Sending = false;
				ContactUs_StateChange();
			},
			onSuccess: function (transport) {
				var requestFailed = false;
				try {
					json = transport.responseText.evalJSON();
				} catch (e) {
					requestFailed = true;
				}
				
				if (requestFailed) {
					alert('There was an issue while processing your request.\n\nPlease try again later.');
					ContactUs_Sending = false;
					ContactUs_StateChange();
				} else {
					if (json.success) {
						ContactUs_Send_Request_Succcess();
					} else {
						ContactUs_Verify();
						if (json.message) {
							alert(json.message);
						} else {
							alert('There was an issue while processing your request.\n\nPlease try again later.');
						}
						ContactUs_Sending = false;
						ContactUs_StateChange();
					}
				}
			}
		}
	);
}

function ContactUs_Send_Request_Succcess () {
	new Effect.Fade('contactus-body-content');
	new Effect.Appear('contactus-body-thankyou', {queue: 'end'});
}