
var MAX_COMMENT_LENGTH = 1000;
var sPaymentType = null;

$(function()
{
	$('input.PaymentType').click(function(e)
	{		
		/* set the GLOBAL var paymentType
		 */
		sPaymentType = $(this).val();
	
		/* highlight current type
		 */
		$('input.CurrentPaymentType').removeClass('CurrentPaymentType');
		$('#subTotal' + sPaymentType).addClass('CurrentPaymentType');
		
		/* highlight submit button
		 */
		$('#apply').addClass('HL');
	
	
		adjustTotal();
	});
	
	$('#membershipForm').submit(function()
	{
		adjustTotal();
		return validate();
	});
});


/** ****************************************************************
 * adjustTotal(f)
 *
 * Add donation amount to the subtotal and update total field.
 * Called from onchange event of PaymentType radio inputs, passing
 * the value, which is string that can be used to find the corresponding
 * subtotal.
 * If called from the onchange of the donation input, the total may not be
 * set if none of the PaymentType radio inputs is set.
 * Same for the onsubmit: this will be caught in the function checkForm()
 *
 * Dependant on Simon Wilson's getElementsByClassName(), which
 * is in the linked util.js file.
 *
 * @returns void
 **/
function adjustTotal()
{
	//return null;
	//var subtotal = roundCents(parseFloat(oForm.total.value));
	
	var fDonation = roundCents(parseFloat($('#donation').val()));              /* deal with donation first */

	$('#donation').val((fDonation > 0) ? formatDecimal(fDonation) : '');    /* don't want '0.00' showing up */
/*	
	if (null == sPaymentType)                                                  // sum total 
	{
		var aPaymentTypes = document.getElementsByClassName(Array('input'), 'PaymentType');
		
		for (var i = 0; i < aPaymentTypes.length; i++)
		{
			if (aPaymentTypes[i].checked)                                        // may not be any set!
			{
				//setPaymentType(oForm, aPaymentTypes[i].value);
				break;
			}
		}
	}
*/
	if (sPaymentType)
	{
		var fSubtotal = roundCents(parseFloat($('#subtotal_' + sPaymentType).val()));
		$('#total').val(formatDecimal(roundCents(fSubtotal + fDonation)));
	}
	return true;
	
	function roundCents(fVal)                 // round to nearest cent
	{
		if (isNaN(fVal)) return 0;
		return Math.round(fVal * 100) / 100;
	}
	
	function formatDecimal(sVal)
	{
		var s = new String(sVal);            // format the output
		var decimal = s.indexOf('.');

		if (-1 == decimal)                     // whole number
		{
			s += '.00';
		}
		else if ((s.length - 2) == decimal)    // needs a trailing zero
		{
			s += '0';
		}
		return s;
	}
}



/** ****************************************************************
 *
 **/
function validate()
{
	$('#comments').val($('#comments').val().substr(0, MAX_COMMENT_LENGTH));

	var bChecked = false;
/*
	var aMemberTypes = oForm.member_type;
	
	for (var i = 0; i < aMemberTypes.length; i++)
	{
		if (aMemberTypes[i].checked)
		{
			bChecked = true;
			break;
		}
	}
	
	if (!bChecked)
	{
		alert('Please select a member type');
		return false;
	}
*/	
	var sUserName = $('#name').val();
	
	if (!isString(sUserName))
	{
		alert('Please enter your full name');
		return false;
	}
	
	var sAddress1 = $('#address_1').val();
	
	if (!isString(sAddress1))
	{
		alert('Please enter your street address');
		return false;
	}
	
	var sCity = $('#city').val();
	
	if (!isString(sCity))
	{
		alert('Please enter your city');
		return false;
	}
	
	var sProvince = $('#province').val();
	
	if (!isString(sProvince) || sProvince.length != 2)
	{
		alert('Please enter province');
		return false;
	}
	
	var sPostalCode = $('#postal_code').val();
	
	if (!isPostalCode(sPostalCode))
	{
		alert('Please enter postal code');
		return false;
	}
	
	var sTelephone = $('#telephone_1').val();
	
	if (!isString(sTelephone) || sTelephone.length < 7)
	{
		alert('Please enter at least one telephone number');
		return false;
	}
	
	bChecked = false;
	
	$('.PaymentType').each(function(i)
	{
		if ($(this).is(':checked')) 
		{
			bChecked = true;
			return false;
		}
	});

	if (!bChecked)
	{
		alert('Please select a payment method');
		return false;
	}
	
	
	var fTotal = parseFloat($('#total').val());

	if (isNaN(fTotal) || fTotal <= 0)
	{
		alert('Please enter the total payable');
		return false;
	}
	
	return true;
}


/** ****************************************************************
 * checks that input is at least one visible character
 *
 * @param string sVal string to be checked
 * @returns boolean success
 **/
function isString(sVal)
{
	return (sVal.match(/^[ ]?\S+/));
}


/** ****************************************************************
 * checks for well-formed Canadian postal code
 *
 * @param string sVal the code to be checked
 * @returns boolean success
 **/
function isPostalCode(sVal)
{
	return sVal.match(/^\S{1}\d{1}\S{1}[ ]?\d{1}\S{1}\d{1}$/);
}

/**
 * request new CAPTCHA image
 *
 * @param	object	f	the form
 * @param	string	path	the path to make the request to
 *
 **/
function newCaptchaImage(f, path)
{	
	var post_str = 'captcha_new_request=1';
	
	/* get all elements & values
	 */
	/*
	for (var i = 0; i < f.elements.length; i++)
	{
		if (!f.elements[i].name) continue;
		
		post_str += '&' + f.elements[i].name + '=' + encodeURIComponent(f.elements[i].value);		
	}
	*/
	makePOSTRequest(path, post_str, replaceCaptchaImage);
}



/**
 * Replace CAPTCHA image for a form
 **/
function replaceCaptchaImage()
{
	if (!http_request) return false;
	
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			/* HTML elements
			 */
			result = http_request.responseText;
			
			/* get the fieldset with the captcha elements
			 */
			 
			/*
			var captcha_controls = document.getElementById('captcha_controls');
			
			var new_node = document.createElement('span');

			new_node.innerHTML = result;
			captcha_controls.parentNode.replaceChild(new_node, captcha_controls);
			*/
			
			var captcha_image = document.getElementById('captcha_image');
			captcha_image.id = 'foo';
			
			var new_image = new Image();
			new_image.src = result;
			new_image.id = 'captcha_image';
			captcha_image.parentNode.replaceChild(new_image, captcha_image);

			return true;
		}
		else
		{
			alert('There was a problem with the request.');
			return false;
		}
	}
}

/**
 *
 **/
function makePOSTRequest(url, parameters, readystate_callback)
{
	http_request = false;
	
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType)
		{
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	}
	else if (window.ActiveXObject)
	{
		try
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{

			}
		}
	}
	if (!http_request)
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange = readystate_callback;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}


function alertHTTPRequestContents()
{
	if (!http_request) return false;
	
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			result = http_request.responseText;
			//document.getElementById('myspan').innerHTML = result;
			return true;
		}
		else
		{
			alert('There was a problem with the request.');
			return false;
		}
	}
}
