// Javascript for the questions form on the main page, backend in questions.cgi

// Are we awaiting ajax response?
// used to prevent double submits
var gSubmitting = 0;

$(function() {
	// Document ready function
	$("form[name=questions]").submit(handleSubmit);
	
	//
	$("form[name=questions] textarea").focus(focusClearText);
});

// Clears inner text and unbinds the event
function focusClearText()
{
	if ($(this).is('textarea'))
		$(this).val("");
	else
		$(this).val("");
	$(this).unbind('focus', focusClearText);
}

// When someone attempts to submit questions form
function handleSubmit()
{
	if (gSubmitting)
		return; // Already processing a submission
	
	gSubmitting = 1;
	var datamap = new Object();
	datamap["ajax"] = true;
	var fields = $(this).find("select,input,textarea");
	for (var i = 0; i < fields.length; i++)
	{
		var field = fields.eq(i).attr("name");
		datamap[field] = getFieldValue(field);
	}

	$.post("/solutions/includes/questions.cgi", datamap, submitCallback, "json");
	return false;
}

// Called when a submit to the backend completes
function submitCallback(data, textStatus)
{
	gSubmitting = 0;

	$("span.QuestionError").html("");
	$("#errors").html("");
	
	if (data["result"] == "error")
	{
		$("#errors").html("The following errors occurred:\n");
		for (x in data["errors"])
			$("#error_" + x).html(data["errors"][x]);
	}
	else
	{
		// Success
		$("#questionFormThankYou").toggle().html("Thank you for your submission!");
		$(".questionFormContent").slideUp();
	}
}

// Gets the value for an arbitrary form field
function getFieldValue(fname)
{
	var eles = $('[name='+fname+']');
	if (!eles.length) return "";
	if (eles.is("select"))
	{
		var ret = eles.find("option:selected").val();
		return (ret == "Select") ? "" : ret;
	}
	if (eles.is("[type=radio]") || eles.is("[type=checkbox]"))
	{
		var ret = eles.filter(":checked");
		return (ret.length) ? ret.val() : "";
	}
	return eles.val();
}

