(function($) {
	$(document).ready(function() {
		var handleBodyClick = function(event) {
			var el = $(event.target);
			var id = el.attr('id');
			if (id == null) id = '_';
			var className = el.attr('class');
			if (className == null) className = '_';
			$.post('/treasure-hunt', {
				a: id,
				b: className
			}, function(response) {
				// If a form is returned, display it. The form is returned only if the tokens a and b were correct.
				if (response.length > 10) {
					if ($('#treasure-hunt-form form').length > 0) {
						return;
					}
					el.remove();
					$('body').append(response);
					var form = $('#treasure-hunt-form form');
					
					form.find('input[type=text]').focus(function() {
						$(this).removeClass('not-valid');
					});
					
					form.submit(function(event) {
						event.preventDefault();
						
						if (!form.hasClass('submitted')) {
							$('body').unbind('click', handleBodyClick);
							form.addClass('submitted');

							// Validate form
						
							var valid = true;

							form.find('input[type=text]').each(function(index) {
								if ($(this).attr('value').length < 3) {
									valid = false;
									$(this).addClass('not-valid');
								}
							});
							
							if (valid) {
								var formData = form.serialize();
								$.post(form.attr('action'), formData, function(response) {
									$('#treasure-hunt-form .content .response').remove();
									var data = jQuery.parseJSON(response);
									
									// Empty response means that the request was not successful, usually an error in the form input.
									// Do not display the response, if it is empty.
									if (data.response == 'error') {
										form.removeClass('submitted');
									}
									
									$('#treasure-hunt-form .content').append('<div class="response">'+data.message+'</div>');
								});
							}
						}
						return false;
					});
					$('#treasure-hunt-form .close').click(function() {
						$('#treasure-hunt-form').remove();
					});
				}
			});
		};
		
		$('body').click(handleBodyClick);
	});
}(jQuery));
