if (window.location.hostname.substr(0, 3) != "www")
	window.location = "http://www." + window.location.hostname + window.location.pathname;

$(document).ready(function(){
	initContactForm();
});

$.fn.clearFields = function(){
	$(this).find(".clearme").each(function(){
		if ($(this).val() === $(this).get(0).defaultValue)
			$(this).val("");
	});
};

$.fn.defaultFields = function(){
	$(this).find(".clearme").each(function(){
		if ($(this).val() == "")
			$(this).val($(this).get(0).defaultValue);
	});
};

$.fn.clearOnFocus = function(){
	return this
		.focus(function(){
			var v = $(this).val();
			$(this).val( v === this.defaultValue ? '' : v );
		})
		.blur(function(){
			var v = $(this).val();
			$(this).val( v.match(/^\s+$|^$/) ? this.defaultValue : v );
		});
};

$.fn.validate = function(){
	$(this).find(".required").removeClass("formError");
	var errCount = 0;
	$(this).find(".required").each(function(){
		if ($(this).val() === $(this).get(0).defaultValue || $(this).val() == "")
		{
			$(this).addClass("formError");
			errCount++;
		}
	});
	if (errCount > 0)
	{
		$(".msg").text("Please correct the highlighted fields above and try again.").show();
		return false;
	}
	return true;
}

function initContactForm(){
	$(".contactform").show().ajaxStart(function(){$(this).hide();});
	$(".clearme").clearOnFocus();
	$("#sendingMsg").ajaxStart(function(){$(this).show();});
	$("#sendingMsg").ajaxComplete(function(){$(this).hide()});
	$("#submit").click(function() {
		$(".msg").hide();
		if ($("#contactform").validate())
		{
			$("#contactform").clearFields();
			var dataString = "";
			var fields = $("#contactform :input").not("#submit").serializeArray();
			jQuery.each(fields, function(i, field){
				if (field.value != "")
				{
					if (dataString != "")
						dataString = dataString + "&";
					dataString = dataString + field.name + "=" + field.value;
				}
			});
			$.ajax({
			   type: "POST",
			   url: "/webformmailer.php",
			   data: dataString,
			   success: function(){
				   $(".msg").text("Your message was sent. Thank you.").show();
				   return false;
			   },
			   error: function(){
				   $(".msg").text("There was an error sending your message. Please try again.").show();
				   $(".contactform").show();
				   $("#contactform").defaultFields();
				   return false;
			   }
			 });
		}
		else
			return false;
	});
}
