(function($){

	var formAction,
		action = 'action', disabledName = 'disabled', send = 'Send', sending = 'Sending...', checked = 'checked',
		errgood = 'errorbox-good', errbad = 'errorbox-bad', inputselect='input,button,textarea,select',
		required = 'ss-required-asterisk',
		subbtn, theform, other;

	$(function(){
		var states = $('#entry_6');
		var emptstate = $('<option/>');
		emptstate.insertBefore(states.children()[0]);
		emptstate.attr('selected','selected');
		subbtn = $('button#submitButton');
		theform = $('form#contactForm');
		other=$('input#otherinput');

		formAction = theform.attr(action);
		theform.attr(action,'').submit(function(){return false;});
		$('input#other_option_check').change(
				function(){
					if($(this).attr(checked))
						other.attr(disabledName,'').focus();
					else
						other.attr(disabledName,disabledName);
				});
		subbtn.click(submitForm);
	});

	var whiteSpace = new RegExp("^\\s*$");

	function checkForm()
	{
		var good = true;//, inp = 'input';
		$('.'+errbad).removeClass().addClass(errgood);
		$('tr', theform).filter(function(){
				return $('span', this).is('.'+required) && $(inputselect, this).length > 0;
			}).each(function(){
				if($(inputselect, this).val().match(whiteSpace))
				{
					good = false;
					$('.'+errgood,this).removeClass().addClass(errbad);
				}
			});

		if(!good)
			return false;
		
		return true;
	}

	function enableForm()
	{
		$(inputselect).attr(disabledName, '');
		subbtn.text(send);
	}

	function submitForm()
	{
		if(!checkForm())
			return;

		var postData = theform.serialize();

		subbtn.text(sending);
		$(inputselect).attr(disabledName,disabledName);

		$.ajax({
			 url: '/transport/remote?url='+formAction+'&method=post',
			 contentType: 'text/plain',
			 data: postData,
			 type: 'POST',
			 error: function(req, status, err){
				 alert('There was an error while trying to send your message.  Please try again in a moment.');
				 enableForm();
			 },
			 success: function(data, status){
				 alert('Thank you for contacting us.\n We will get in touch with you shortly.');
				 enableForm();
				 $('input[type!=checkbox],textarea').each(function(i){$(this).val('');});
				 $('input[type=checkbox]').each(function(i){$(this).attr(checked,'');});
			 }
		});
	}
	
})(jQuery);

