$(document).ready( function() {
	$("#signupDialog").dialog( {
		bgiframe :true,
		height :650,
		width :600,
		resizable: false,
		modal :true,
		autoOpen :false,
		buttons : {
			'Free Instant Access!' : function() {
				newsLetterSignUp();
			}//,
			//Cancel : function() {
				//$("#signupDialog").dialog('close');
			//}
		}
	});
	$("#signupDialog").bind("keypress", function(e) {
		  if (e.keyCode == 13) {
			  newsLetterSignUp();
			  return false;
		  }
		});
	$("#signupButton").bind("mouseenter mouseleave", function(e){
        $(this).toggleClass("ui-state-hover");
    });

})

window.onload = function() {
	$('[name=email]').val('');
	$('[name=first_name]').val('');
	$("#container").css("visibility", "visible");
}

showNewsletterForm = function() {
	$("#signupDialog").dialog('open');
}

newsLetterSignUp = function() {
	email = $('[name=email]').val();
	first_name = $('[name=first_name]').val();
	type = $('input[name=newsletterType]:checked').val(); 
	

	if ((email == null) || (email == "")) {
		updateMsg("Please enter an email address.")
	} else {
		if(validateEmail(email)) {
			response = submitEmail(email, first_name, type);
		} else {
			updateMsg("Please enter a valid email address (e.g. user@example.com) with no spaces.");
		}
	}
}

submitEmail = function(email, first_name, type) {
	//$.get("http://localhost/keithyork/ajax/newsletterSubmit.php",  { email: email, first_name: first_name, type: type},
	$.get("http://keithyork.com/ajax/newsletterSubmit.php", { email: email, first_name: first_name, type: type},
			  function(data){
			    updateMsg(data);
			    window.setTimeout(function() {
			    	$("#signupDialog").dialog('close');
			    	updateMsg("");
			    	$('[name=email]').val('');
			    	$('[name=first_name]').val('');
			    	}, 1500);
	});
}

updateMsg = function(msg){
	$("#msgSpace").html(msg);
}

validateEmail = function(str) {

	var at = "@"
	var dot = "."
	var lat = str.indexOf(at)
	var lstr = str.length
	var ldot = str.indexOf(dot)
	if (str.indexOf(at) == -1) {
		return false
	}

	if (str.indexOf(at) == -1 || str.indexOf(at) == 0
			|| str.indexOf(at) == lstr) {
		return false
	}

	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0
			|| str.indexOf(dot) == lstr) {
		return false
	}

	if (str.indexOf(at, (lat + 1)) != -1) {
		return false
	}

	if (str.substring(lat - 1, lat) == dot
			|| str.substring(lat + 1, lat + 2) == dot) {
		return false
	}

	if (str.indexOf(dot, (lat + 2)) == -1) {
		return false
	}

	if (str.indexOf(" ") != -1) {
		return false
	}

	return true
}
