//TODO: this is all / or mostly global stuff for admin and public site
//	if there's public-only form stuff, move it into a separate sheet so admin doesn't inherit it
//	maybe rename this _forms or even merge it into _global or something


//	to do late-binding of datepicker callbacks, just define an element here with a key equal to the id of the form input
var dateCallbacks = {};

$(document).ready(function(){
	$("input,select,textarea").focus(
		function()
		{
			$("div.formField").removeClass("active");
			$(this).parents("div.formField").addClass("active");
		}
	);
	$("div.formField div.error").each(
		function()
		{
			$(this).parents("div.formField").addClass("error");
		}
	);
	$("img.requiredField").each(
		function()
		{
			$(this).parents("div.formField").find("input").addClass("required");
			$(this).parents("div.formField").find("select").addClass("required");
			$(this).parents("div.formField").find("textarea").addClass("required");
		}
	);
	
	//	get focus on the login box
	$("#loginBox input.username").each(
		function ()
		{
			this.focus ();
		}
	);
	
	//	date pickers
	var calendarSource = "/static/default/graphics/calendar.gif";
	var transparentSource = "/static/default/graphics/transparent.gif";
	if ($("img.calendarImageTemplate.hidden").size () > 0)
	{
		calendarSource = $("img.calendarImageTemplate.hidden").eq(0).attr("src");
	}
	if ($("img.transparentImageTemplate.hidden").size () > 0)
	{
		transparentSource = $("img.transparentImageTemplate.hidden").eq(0).attr("src");
	}
	var datePickerOptions = {
		dateFormat:'m/d/y',
		showOn:'both',
		buttonImageOnly:true,
		onSelect:function(dateText)
		{
			datePicked(this,dateText);
		}
	};
	
	$("input.datePicker").each 
	(
		function ()
		{
			if ($(this).hasClass("noIcon"))
			{
				
				datePickerOptions.buttonImage = transparentSource;
				datePickerOptions.buttonText = '';
			}
			else
			{
				datePickerOptions.buttonImage = calendarSource;
				datePickerOptions.buttonText = "click to select a date";			
			}
			$(this).datepicker(datePickerOptions);
		}
	);
	
	//	color pickers
	$("div.colorPicker").each(
		function ()
		{
			var controlSelect = "#" + extractID ($(this).attr("id"));
			$(this).farbtastic(controlSelect);
		}
	);
	
	$("input.causesValidation,img.causesValidation,a.causesValidation").click
	(
		function ()
		{
			return ll_generic_form_validate ($(this).hasClass ("skipRequired"));
		}
	);
	
	$("#radio_storedPayment").click(
		function ()
		{
			if ($(this).attr("checked"))
			{
				hide($("#newPaymentInfo"));
			}
		}
	);
	$("#radio_newPayment").click(
		function ()
		{
			if ($(this).attr("checked"))
			{
				show($("#newPaymentInfo"));
			}
		}
	);

	//	paypal submit button
	$("#startExpressCheckoutButton").click (
		function ()
		{
			var agreed = $("#chkAgreeToTerms").attr("checked");
			if (!agreed && $("#chkAgreeToTerms").length)
			{
				alert ('You must agree to the terms before you can continue.');
				return false;
			}
			$("#startExpressCheckoutAgree").attr("value",agreed ? 1 : 0);
			$("#startExpressCheckoutForm").submit ();
			return false;
		}
	);	
});

/*
*	skipRequired is just a hack so we can have multiple forms on one page
*	and still validate the numeric fields without one form submission getting angry about
*	empty fields that actually belong to another form... (note that they might all be part
*	of the same <form>, but visually presented as separate views via JS... see PaymentActions)
*		The correct answer is 'Validation Groups'
*/
function ll_generic_form_validate (skipRequired)
{
	var emptyFields = emptyRequiredFields ();
	var numberFields = badNumericFields ();
	var message = "";	

	if (emptyFields.length > 0 && !skipRequired)
	{
		message += "Please be sure to fill in the following required fields: \n";
		for (var i = 0; i < emptyFields.length; i++)
		{
			message += "  > " + emptyFields[i] + "\n";
		}
		message += "\n\n";
	}
	
	if (numberFields.length > 0)
	{
		message += "The following fields require numeric values: \n";
		for (var i = 0; i < numberFields.length; i++)
		{
			message += "  > " + numberFields[i] + "\n";
		}
		message += "\n\n";
	}
	
	if (message == "")
	{
		return true;
	}
	else
	{
		alert (message);
		return false;
	}
}

//	get an array of the required fields that have been left empty
function emptyRequiredFields ()
{
	var badFields = [];
	var badFieldCount = 0;
	
	$("input.paymentTerms").each(
		function ()
		{
			if (!this.checked)
			{
				badFields[badFieldCount++] = "You must agree to the payment terms.";
			}
		}
	);	
	
	$(":input.required").each(
		function(){
			if	((!$(this).hasClass("checkbox") && $(this).attr("value") == "") || ($(this).hasClass("checkbox") && !this.checked))
			{
				var pmtFields = {"Billing Address" : 1,"Credit Card Number" : 1,"Security Code" : 1};
				var fieldName = getFieldName(this);
				if ($("#radio_storedPayment").attr("checked") && pmtFields[fieldName])
				{
					return;
				}
				if (indexOf (fieldName,badFields) == -1)
				{
					badFields[badFieldCount++] = fieldName;
				}
			}
		}
	);
	
	return badFields;
}

function badNumericFields ()
{
	var badFields = [];
	var reMoney = /^[0-9\$\.]*$/;
	var reNumber = /^\d*$/;
	
	//	fields that allow $ and .
	validateFieldsByRegExp ("input.fee,input.amountInput,input.paymentRequest", reMoney, badFields);
	
	//	pure numeric fields
	validateFieldsByRegExp ("input.AreaCode,input.Prefix,input.LastFour,#input_CardNumber,#input_SecurityCode", reNumber, badFields);
	
	return badFields;
}

/*
*	make sure all fields matching the given selector have values that match rePattern
*	if they don't work, append their field name to the badFields array
*/
function validateFieldsByRegExp (sSelector, rePattern, badFields)
{
	var badFieldCount = badFields.length;
	$(sSelector).each (
		function ()
		{
			var val = $(this).attr("value")
			if (!val.match (rePattern))
			{
				var fieldName = getFieldName(this);
				if (indexOf (fieldName,badFields) == -1)
				{
					badFields[badFieldCount++] = fieldName;
				}
			}
		}
	);
	return badFields;
}

//	generic callback for datepickers. If it's a single date picker, value is the date. If a range, value is an array
//	with 'from' in position 0 and 'to' in position 1
function datePicked(element,value)
{
	var id = $(element).attr("id");
	callback = dateCallbacks[id];
	if (callback)
	{
		callback(value);
	}
}

function checkMatchingFields(idOne,idTwo)
{
	return ($("#" + idOne).val() == $("#" + idTwo).val());
}

function getFieldName(objElement)
{
	var labelText = $(objElement).parents("div.formField").find("label").html();
	if (labelText)
	{
		var nextTag = labelText.indexOf("<");
		if (nextTag != -1)
		{
			labelText = labelText.substr(0,nextTag);
		}
	}
	else
	{
		var jqObj = $(objElement);
		if (jqObj.hasClass("fee") || jqObj.hasClass("paymentRequest") || jqObj.hasClass ("amountInput"))
		{
			labelText = "All Dollar Amounts";
		}
	}
	return labelText.trim ();
}
