$(function() {

	// load the modal window
	$('a.modal').click(function(){

		// scroll to top
		$('html, body').animate({scrollTop:0}, 'fast');

		// before showing the modal window, reset the form incase of previous use.
		$('.success, .signerror').hide();
		$('form#contactForm').show();
		
		// Reset all the default values in the form fields
		$('#signUpname').val('');
		$('#signUpemail').val('');

		//show the mask and contact divs
		$('#mask').show().fadeTo('', 0.7);
		$('div#signbox').fadeIn();

		// stop the modal link from doing its default action
		return false;
	});

	// close the modal window is close div or mask div are clicked.
	$('div#close, div#mask').click(function() {
		$('div#signbox, div#mask').stop().fadeOut('slow');

	});

	$('#contactForm input').focus(function() {
		$(this).val(' ');
	});
	
	$('#contactForm textarea').focus(function() {
        $(this).val('');
    });

	// when the Submit button is clicked...
	$('#signUpButton').click(function() {
	$('.signerror').hide().remove();
		//Inputed Strings
		var subscribername = $('#signUpname').val(),
			subscriberemail = $('#signUpemail').val();
		
	
		//Error Count
		var error_count;
		
		//Regex Strings
		var username_regex = /^[a-z0-9_-]{3,16}$/,
			email_regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
		
			//Test Username
			if(!username_regex.test(subscribername)) {
				$('#signUpname').after('<span class="signerror"> Enter your name</span>');
				error_count += 1;
			}
			
			//Test Email
			if(!email_regex.test(subscriberemail)) {
				$('#signUpemail').after('<span class="signerror"> Enter correct email</span>');
				error_count += 1;
			}
			error_count = 0;
			//Blank Comment?
			//if(comment == '') {
			//	$('#sign_header').after('<p>No Comment was entered!</p>');
			//	error_count += 1;
			//}
			
			//No Errors?
			if(error_count === 0) {
				$.ajax({
					type: "post",
					url: "inc/mailsubscriber.php",
					data: "name=" + subscribername + "&email=" + subscriberemail,
					error: function() {
						$('.signerror').hide();
						$('#sendError').slideDown('slow');
					},
					success: function (data) {
						
						if( data == "x" ){
							$('.signerror').show();
						}else{
							$('.signerror').hide();
							$('.success').html(data);
							$('.success').slideDown('slow');
							$('form#contactForm').fadeOut('slow');
						}
						
					}

				});	
			}
			
			else {
                $('.signerror').show();
            }
			
		return false;
	});
	
});
