function warning_require(field, hide) {
	if(hide === true) {
		jQuery("#label-"+field).hide();
	} else {
		jQuery("#label-"+field).show();
		jQuery.jGrowl("Please enter a " + field + " before submitting.");
	}
}
/* This is from the iFrame's perspective: I really really hate jQuery for making
 * me try it this way.
 */
function iFrameOnLoadHandler() {
	/* We retrieve the information in the iFrame, which is where the target
	 * response is, then process it into a JSON object.
	 */
	var iFrame = document.getElementById("formSubmissioniFrame").contentWindow.document.body;
	var responseText = iFrame.innerHTML;
	var response = jQuery.evalJSON(responseText);
	/* We properly look at the responses, so that we can tell if the person has
	 * been naughty or nice, and fill their stockings appropriately.
	 */
	if(response.errno == 0) {
		jQuery.jGrowl("Submission complete.");
		jQuery(".blog-box1").html("<h3>Bug submitted.  Thank you for your report.  We will look into the matter and contact you if we need additional information.</h3>");
		var forms = jQuery("#title-form, #bug-form, #description-form");
		for(var i = 0; i < forms.length; i++) {
			forms[i].reset();
		}
		//window.location.reload();
	} else {
		jQuery.jGrowl("Server responded with: \n" + response.errmsg);
		window.location.reload();
	}

	// Refresh the captcha image
	jQuery("captcha-image").attr("src", "about:blank").attr("src", "/share/captcha-basic.php");
}
/* Form submission handler.
 */
function bug_submission(event) {
	/* The list of fields to fetch, as well as the data
	 * to send to the server.
	 */
	var data = {"title": "",
	             "category": "",
	             "email": "",
	             "url": "",
	             "time": "",
	             "browser": "",
	             "version": "",
	             "os": "",
	             "description": "",
	             "captcha": "",
	             "image": ""};
	        
	var prevent = false;     
	for(var key in data) {
		data[key] = jQuery("#input-" + key).val();
		if(data[key] == "" && key != "image") {
			prevent = true;
			warning_require(key);		// Shows the require text
		} else {
			warning_require(key, true);	// Hides the required text, if it's displayed
		}
	}

	/* Now, if we have filled in all the fields except for image, we are free to proceed
	 * with submission of the bug to the server.  We'll create an iframe, add the data
	 * to that, and then trigger the submission of the form.
	 */
	if(!prevent) {
		jQuery("#main-content").append("<iframe id=\"formSubmissioniFrame\" name=\"formSubmissioniFrame\" onload=\"iFrameOnLoadHandler()\" />");
		jQuery("#formSubmissioniFrame").hide();
		/* For some reason, jQuery is making us go the long way around and do this
		 * by hand.  There MUST be an easier way to get this done, but I couldn't
		 * tell you what it was.
		 */
		jQuery("#main-content").append("<form action=\"/a/bugs.api\" method=\"post\" id=\"formsubmission\" enctype=\"multipart/form-data\" target=\"formSubmissioniFrame\" />");
		/* This will populate the individual fields of the form in the hidden
		 * iFrame.
		 */
		for(var key in data) {
			if(key === "description")
				jQuery("#formsubmission").append('<textarea name="description">' + data[key] + '</textarea>').attr("name", "key");
			else if(key !== "image")
				jQuery("#formsubmission").append('<input type="text" name="' + key + '" value="' + data[key] + '" />');
			else
				jQuery("input[name='ssimage']").clone().appendTo("#formsubmission");
		}
		jQuery("#formsubmission").append('<input type="hidden" name="action" value="submit" />');
		/* Now we add the hidden form to the page, and we have to copy the value of the file
		 * submission separately, since JavaScript disallows an input[@type=file] box to be
		 * filled programmatically.
		 */
		jQuery("#formsubmission").hide();
		/* Now, we bind to the load of the iFrame for after we are done the actual
		 * transfer of the data.
		 */
		//document.getElementById("formSubmissioniFrame").contentDocument.onload = 
		/* And, lastly, we actually try to submit the form... heaven help us!
		 */
		jQuery("#formsubmission")[0].submit();//.each(function() { this.submit(); });


	}
	
	/* Whether or not we submitted we definitely don't want to experience a page refresh.
	 * That would just stink, wouldn't it?
	 */
	event.preventDefault();
	return false;
}

/* First order of business is to hide the bug DIV until it's used
 * and to attach a listener onto the bug search form so that we
 * can call some JSON when the time comes.
 */
jQuery(document).ready(function() {
	/* It would look kinda funny if this was visible before
	 * there was any data in it, so I'm going to hide it until
	 * such a time as that.
	 */
	jQuery("#bug-div").hide();
	// Same with warnings
	jQuery(".required-warning").hide();
	// And the image upload box
	jQuery("#image").hide();
	
	/* We're going to slightly mess around with this one.
	 */
	jQuery("#screenshot").css("cursor", "pointer").click(function(event) {
		$("#image").show();
	});
	
	/* A listener for when people submit a search for bugs.
	 * We'll call the server, and then show some results.
	 * TODO: Make links out of the titles or the <tr>'s after
	 * I have written a details page.
	 */
	jQuery("#bug-search-form").submit(function(event) {
		searchString = jQuery("#bugs-search-input").val()
		jQuery.getJSON("/a/bugs.api?action=search", 
				{ 'searchString': searchString },
				function(data) {
					if(data.errno !== 0) {
						jQuery("#bug-div-content h2").text(data.errmsg);
					}
					jQuery.each(data.bugs, function(i, item) {
						jQuery("table.bug-tb tbody").append("<tr class=\""+item.status+"\" >"
							+ "<td>" + item.title + "</td><td>" + item.status + "</td></tr>");
					});
					jQuery("#bug-div-content h2").text(data.results + " bugs found.");
					// This has been hidden - so we need to unhide it, if so
					jQuery("#bug-div").show("slow");
		
					/* We want the table to be sortable by the client. We
					 * love jQuery for things like this!
					 */
					jQuery("#bug-tb").tablesorter();

				});
		
		// This stops the form from submitting, refreshing the page, and us losing our data and results
		event.preventDefault();
		return false;
	});
	
	/* Since the submission form is actually broken into 3 different forms, we need to capture
	 * the submission from any of the three.  If it weren't for the restrictions of
	 * XHTML, we'd be all good here, but that would screw up our display in many browsers that
	 * want compliant code.  We will warn the users if they need to fill in more information.
	 */
	jQuery("#title-form").submit(bug_submission);
	jQuery("#bug-form").submit(bug_submission);
	jQuery("#description-form").submit(bug_submission);
	
	
	/* This will make sure the above method gets called.
	 */
	jQuery("#input-submit").click(function(event) {
		bug_submission(event);
	});
});

