function checkEmail(str) {
	var at = "@", dot = ".", lat = str.indexOf(at), lstr = str.length, returnValue = true;

	if (str.indexOf(at) === -1) {
		returnValue = false;
	}

	if (str.indexOf(at) === -1 || str.indexOf(at) === 0 || str.indexOf(at) === lstr) {
		returnValue = false;
	}

	if (str.indexOf(dot) === -1 || str.indexOf(dot) === 0 || str.indexOf(dot) === lstr) {
		returnValue = false;
	}

	if (str.indexOf(at, (lat + 1)) !== -1) {
		returnValue = false;
	}

	if (str.substring(lat - 1, lat) === dot || str.substring(lat + 1, lat + 2) === dot) {
		returnValue = false;
	}

	if (str.indexOf(dot, (lat + 2)) === -1) {
		returnValue = false;
	}

	if (str.indexOf(" ") !== -1) {
		returnValue = false;
	}

	return returnValue;
}

function requestPage(url, parameters, onComplete) {
	var http_request = false;

	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (ex) {}
		}
	}

	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = function () {
		if (http_request.readyState === 4) {
			onComplete(http_request.status, http_request.responseText);
		}
	};
	http_request.open('GET', url + parameters, true);
	http_request.send(null);
}

$(function () {
	$('.emailError').hide();

	function subscribeComplete(status, text) {
		if (status === 200) {
			$('#signUp').fadeOut(750, function () {
				$('#signUp').html("<div id='message'></div>");
				$('#message').html("<br /><p>We will be in touch soon.</p>");
				$('#signUp').fadeIn(750, function () {});
			});           
		} else if (status === 501) {
			$("label#email_signed").show();
			$("input#email").focus();
		} else if (status === 500) {
			$("label#email_domain_error").show();
			$("input#email").focus();
		}
	}

	$("#submit_btn").click(function () {
		var name = $("input#name").val(), email = $("input#email").val(), dataString;

		$('.emailError').hide();

		if (name === "") {
			$("label#name_error").show();
			$("input#name").focus();
			return false;
		}

		if (email === "") {
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		}
		
		if (checkEmail(email) === false) {
			$("label#email_domain_error").show();
			$("input#email").focus();
			return false;
		}
		
		dataString = 'name=' + name + '&email=' + email;

		requestPage('/umbraco/subscribe.aspx', '?' + dataString, subscribeComplete);

		return false;
	});
});
