$(function() {
	$('.error').hide();
	
	$(".button").click(function() {
		// validate and process form
		// first hide any error messages
		$('.error').hide();
		
		var name = $("input#name").val();
		if (name == "") {
			$("label#name_error").show();
			$("input#name").focus();
			return false;
		}
		
		var email = $("input#email").val();
		var at="@";
		var dot=".";
		var lat=email.indexOf(at);
		var lstr=email.length;
		var ldot=email.indexOf(dot);
		if (email.indexOf(at)==-1){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		}
		if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lstr){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		}
		if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		}
		 if (email.indexOf(at,(lat+1))!=-1){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		 }
		 if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		 }
		 if (email.indexOf(dot,(lat+2))==-1){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		 }
		 if (email.indexOf(" ")!=-1){
			$("label#email_error").show();
			$("input#email").focus();
			return false;
		 }
		
		var zip = $("input#zip").val();
		var valid = "0123456789-";
		var hyphencount = 0;	
		if (zip.length!=5 && zip.length!=10) {
			$("label#zip_error").show();
			$("input#zip").focus();
			return false;
		}
		for (var i=0; i < zip.length; i++) {
			temp = "" + zip.substring(i, i+1);
			if (temp == "-") hyphencount++;
			if (valid.indexOf(temp) == "-1") {
				$("label#zip_error").show();
				$("input#zip").focus();
				return false;
			}
			if ((hyphencount > 1) || ((zip.length==10) && ""+zip.charAt(5)!="-")) {
				$("label#zip_error").show();
				$("input#zip").focus();
				return false;
			}
		}
		
		var hear_about_us = $("input#hear_about_us").val();
		
		var dataString = 'name='+ name + '&email=' + email + '&zip=' + zip + '&hear_about_us=' + hear_about_us;
	//	var id = parseInt(new Date().getTime().toString().substring(0, 10));
		$.ajax({
			type: "POST",
			url: "form-process.php",
			data: dataString,
			success: function() {
				$('#submit').html("<p>Your free video download has begun</p>")
				.animate({opacity: 1.0}, 3000)
				.fadeOut(500);
				//location.href="/video.php?id="+id;
				location.href="/video.php";
				$('#video_link').html("<a href=\"/video.php\">If your download did not start, please click here to download.</a>");
			}
		});
		return false;
	});
});
