//
// $Id:$
//
// HP Velotechnik Website
// Prospektanfrage Javascript form validation functions
// (C) 2009 Pieter Hollants <pieter@hollants.com>
//

// Clear any displayed errors
function clearerror()
{
	$$('.labels').each(function(label) {
		label.style.color="#000000";
	});
	$$('.errmsgs').each(function(errmsg) {
		errmsg.hide();
	});
        var form = $("requestform");
	$(form["submitbutton"]).disabled = false;	
}

// Validate the form's data
function validateform()
{
        var form = $("requestform");

	if ($F(form["customer_name"]).length < 2 || $F(form["customer_name"]).length > 40)
		return "customer_name";

	if ($F(form["customer_street"]).length < 2 || $F(form["customer_street"]).length > 40)
		return "customer_street";

	if (!$F(form["customer_zip"]).match(/^[A-Za-z0-9 \-\/]{3,8}$/))
		return "customer_zip";

	if ($F(form["customer_place"]).length < 2 || $F(form["customer_place"]).length > 40)
		return "customer_place";

	if ($F(form["customer_phone"]).length > 0 && !$F(form["customer_phone"]).match(/^[0-9 \+\-\(\)]{3,}$/))
		return "customer_phone";

	if ($F(form["customer_email"]).length > 0 && !$F(form["customer_email"]).match(/^[^ ]+@[^ ]+\.[^ ]+/))
		return "customer_email";

	return null;
}

// Triggered whenever the form is changed, permanently validates the data
function formchange()
{
        var form = $("requestform");

	clearerror();
	error = validateform();
	if (error)
	{
		$(form["submitbutton"]).disabled = true;
		$$("th#label_" + error)[0].style.color="#ff0000";
		if ($(form[error]).value.length > 0)
		{
			// Workaround for old Internet Explorer versions
			if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))                      
			        ieversion=new Number(RegExp.$1);
			else
			        ieversion=0;

			if (ieversion == 7)
				$$("tr#errmsg_" + error)[0].style.display = "block";
			else
				$$("tr#errmsg_" + error)[0].style.display = "table-row";
		}
	}
}

// Stuff to be done when document has loaded completely
Event.observe(window, 'load', function()
{
        var form;

	// Perform initial validation
	formchange();

	// Attach call to our callback function whenever the input fields change
	if (form = $("requestform"))
	{
		["customer_name", "customer_street", "customer_zip", "customer_place",
		 "customer_phone", "customer_email"].each(function(element) {
			Element.observe(form[element], "change", formchange);
		});
	}
});

