$(function() {

    // These first three lines of code compensate for Javascript being turned on and off. 
    // It simply changes the submit input field from a type of "submit" to a type of "button".
    var paraTag = $('input#submit').parent('li');
    $(paraTag).children('input').remove();
    $(paraTag).append('<input type="button" name="submit" id="submit" value="Sign-up" />');

	// initialise jquery validation plugin
	$("#signupform").validate({
	
		// optional debug to console - uncomment to use
		// debug: true,
	
		// start patched validate file code for custom showing/hiding of error codes to allow animation effects: http://plugins.jquery.com/node/7271
		showError: function(error) {
    		error.slideDown();
  		},
  		hideError: function(error) {
    		error.slideUp();
  		},
  		// end patched code
	
		// define required fields
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		
		// define error messages			
		messages: {
			email: {
				required: "Please enter a valid email address"
			}
		},
		
		
		//custom error placement of validation error (uncomment as needed):
		errorPlacement: function(error, element) {
    	//error.insertBefore( element );
    	//error.appendTo( element.parent().next() );
    	//error.appendTo(label.insertAfter( element ));
    	error.insertAfter('.submit');
		},
		

		// submit handler for validate plugin
		submitHandler: function() {
		
			// disable submit button
			$('button.submit').attr('disabled', 'disabled');
			
			// hide submit button
			$('button.submit').hide();					
			
			// display loading icon		
			$('.loadericon').show();
		
			// setup variables
			var email = $("#email").val();


			// send email with message (this was useful: http://blog.themeforest.net/tutorials/how-to-create-a-contact-form-using-php-and-ajax/)
			$.ajax({
				type: "POST",
				url: "bin/signup_process.php",
				data: 'email=' + email
			});	


			// Add email address to addtomailchimp list script
			$.ajax({
				type: "POST",
				url: "bin/addtomailchimp.php",
				data: 'email=' + email,
					
				// display success message after send
				success: function() {
				
					// fade out loading icon
				 	$('.loadericon').fadeOut('fast');
				 	
				 	// animate contact form to close
					$('#signupform').fadeOut('slow', function() {
				    	//show the success message
				    	$('#send_success').fadeIn('slow');
				  	}); 
	    		}
			});
			
			// re-enable submit button
			$('button.submit').removeAttr('disabled');
			
			// prevent button's usual action
			return false;
	    }
	});		
});
