$(document).ready(function() {
	ContactForm.init();
});

var ContactForm = {
	// Binds events to the form, overriding defaults
	init : function() {
		$('.content .contact input[type="submit"]').click(function() {
			ContactForm.submit();
			return false;
		});
		
		$('.content .contact textarea').bind('keyup blur', function() {
			ContactForm.limit();
		});
	},
	
	// Clear the form
	clear : function() {
		$('form')[0].reset();
	},
	
	// Submit the form via AJAX
	submit : function() {
		$.ajax({
			type : 'POST',
			url : 'http://www.irythia.com/mailer.php',
			data : {
				name : $('.content .contact input[name="name"]').val(),
				email : $('.content .contact input[name="email"]').val(),
				message : $('.content .contact textarea[name="message"]').val(),
			},
			success : function(data) {
				ContactForm.parse(data);
			},
			error : function() {
			},
		});
	},
	
	// Parse results
	parse : function(data) {
		var obj = $.parseJSON(data);
		
		if (obj["submit"] == true) {
			ContactForm.showSuccess();
		}
		else {
			ContactForm.showFail(obj);
		}
	},
	
	// Display successful message
	showSuccess : function() {
		ContactForm.clear();
	},
	
	// Display error message (obj contains various keys and values
	// to determine specific errors)
	showFail : function(obj) {
		alert('There was a problem in delivering your message. Please ensure that all fields have been entered correctly and try again.');
	},
	
	// Interactive character limit display
	limit : function() {
		var length = $('.content .contact textarea').val().length;
		var remaining = 1000 - length;
		
		var result = '' + remaining + ' character(s) remaining';
		$('.content .contact .limit').text(result);
	},
}
