function refreshWordle() {
	
	var container = $("#flash");
	
	if ($("#iwant-flash").length == 1) {
		container = $("#iwant-flash");
	}
	
	var html = container.html();
	container.html(html);	
};

$(function() {

	var form = $("#i-want-submit");
	var error_wrapper = '<div id="form_error">Please check your submission:<ul></ul></div>';
	var error_message = "";
	
	$(form).submit(function(e) {
		
		// Remove the error box if it exists
		var error_box; 
		
		error_box = $("#form_error");
		
		// Get the form values
		var name = $('input[name="fields[name]"]').val();
		var word = $('input[name="fields[word]"]').val();
		
		// Check the form values
		if(name == "" || word == "") {
			
			// Add the error box
			if (error_box.length < 1) {
				$(this).before($(error_wrapper));
			}
			
			error_box = $("#form_error");
			$(error_box).hide().fadeIn();
			
			error_message = (name == "") ? "<li>- 'Name' is missing</li>" : ""; 
			error_message += (word == "") ? "<li>- 'What you want' is missing</li>" : ""; 
			
			// Show the error message
			$("ul", error_box).html(error_message);
			
			return false;
		
		} else {
		
			
		
		}
		
		$(error_box).fadeOut();
		
		// Otherwise submit the form via AJAX
		$.ajax({
			type: "POST",
			data: "fields[name]="+name+"&fields[word]="+word+"&action[add-wordle-word]=true",
			url: "/i-want/submit/",
			dataType: "text",
			success: function(data) {
				$("#thanks").remove();
				$("a#more-wordle, a#refresh-wordle").unbind("click");
				$(form).fadeOut(function() {
					
						// Show a thank you message
						$(this).after($('<div id="thanks"><p>Thank you for your submission. <a id="more-wordle" href="#">Want something else?</a></p><p class="more black" style="margin-left:0;"><a href="#" id="refresh-wordle">Refresh the tag cloud</a></p></div>').hide().fadeIn());
						
						// Add on onclick event to the more link
						$("a#more-wordle, a#refresh-wordle").click(function(e) {
							refreshWordle();
							$("#thanks").fadeOut(function() {
								
								// reset the form value
								$('input[name="fields[name]"]').val("");
								$('input[name="fields[word]"]').val("");
								
								// Fade the form back in
								$(form).fadeIn();
								
							});
						
							e.preventDefault();
						
					});
			
				});
					
			}
			
		});
		
		e.preventDefault();
	
	}); 
	
	
});