/**
 * @file common.error.js
 * @note performs standard error checking on given forms and submits error messages to given error div
 */

/**
 * DetectFormErrors
 * @author 	dhowe
 * @date		04.04.11
 * @note		Runs error detection on any fields in the form with specific classes
 *					Given: form - ID of the given form to check again
 * 					Given: errorcontainer - ID of the given container div to drop errors into
 * 					".required" 	- strlen > 0
 *					".email" 			- has an @
 *					".password"		-	more than 6 characters
 *					Then dumps any error messages into given errorcontainer ID
 */
function DetectFormErrors(form, errorcontainer)
{
	// Loop over all inputs in the form and detect any errors
	var errors = 0;
	var errormsgs = [];
	var inputs = $("#"+form).find(":input").each(function()
	{
		// Ignore buttons
		if ($(this).attr("type") != "submit" && $(this).attr("type") != "button")
		{
			// Find the label for this input and its value
			var value = $(this).val();
			var label = $("label[for='" + $(this).attr('id') + "']").text().replace(":", "");
			
            // console.log($("label[for='" + $(this).attr('id') + "']"));
			
			// HANDLE ERRORS BASED ON CLASS
			// -- Required Field
			if ($(this).hasClass("required"))
			{
				if (value.length == 0)
				{
					errors += 1;
					errormsgs[errormsgs.length] = label + " is a required field.";
				}
			}
			// -- Email Field
			if ($(this).hasClass("email"))
			{
				if (value.search("@") == -1)
				{
					errors += 1;
					errormsgs[errormsgs.length] = label + " must be a valid email address.";
				}
			}
			// -- Password Field
			if ($(this).hasClass("password"))
			{
				if (value.length < 6)
				{
					errors += 1;
					errormsgs[errormsgs.length] = label + " must have at least 6 characters in length.";
				}
			}
		}
	});

	if (errors > 0)
	{
		// Display the errors and don't submit the form
		var html = "";
		var i;

		html += "<ul>";
		for (i = 0; i < errormsgs.length; i++)
		{
			html += "<li>" + errormsgs[i] + "</li>";
		}
		html += "</ul>";

		$("#"+errorcontainer).css("display", "");
		$(".success").css("display", "none"); // Hide any previous success messages
		$("#"+errorcontainer+"_errors").html(html);

		 return false;
	}
	else
	{
	    $("#"+errorcontainer).hide();
		return true;
	}
}

