//================================================================
//		Java script functions and routines for Lean UK
//		Author:		Stephen Lewis
//
//		   Date		Changes
//		28 Oct 04	Original
//		21 Jun 05	Menu preview
// 	19 Oct 05	form validation
//===============================================================


//-----------------------------------------------
//	Add Events
//	where:	elm		= Element
//				evType	= Event Type
//				fn			= Function name
//-----------------------------------------------
function addEvent(elm, evType, fn) 
{

  // cross-browser event handling for IE5+, NS6 and Mozilla 
  if (elm.addEventListener)
  	 { 
    elm.addEventListener(evType, fn, false); 
    return true; 
	 }
	 else if (elm.attachEvent) 
	 	{
    	var r = elm.attachEvent('on' + evType, fn); 
    	return r; 
		}
		else
			{
    		elm['on' + evType] = fn;
  			}
}

//------------------------------------------
//	checkValid:	Validate field
//------------------------------------------
function checkValid(e) 
{
 	// Check for broweser support
   var target = window.event ? window.event.srcElement : e ? e.target : null;
   if (!target) return;

   var errorMessage = handleValidity(target);
   var errorDisplay = document.getElementById('error_' + target.name);

	// Check: invalid with error field
	if (errorMessage && errorDisplay) 
	{
		errorDisplay.innerHTML = errorMessage;
		errorDisplay.style.color = 'red';
    }
	// check: invalid with no error field	
	if (errorMessage && !errorDisplay) 
	{
 		alert( errorMessage );
    }
	
	// check: valid and error field (Clear error field)
    if (!errorMessage && errorDisplay) 
	{
		errorDisplay.innerHTML = '';
		errorDisplay.style.color = 'black';
    }
}

//---------------------------------------------------------
// handleValidty: Validate field against Regular expression
//		Params:	field		- field to validate
//		Returns:	null if Valid else error message
//---------------------------------------------------------
function handleValidity(field) 
{
	var classCheck

	// Check for required field	
	// Note:	The class contains the RegExp to validate for
	//			and may be preceded by 'Required ', ie Required Email
	
	
	if (field.className.substr(0,8) == 'Required')
	{
		//alert (field.name);
		// Check for textbox content
		if ( field.type == 'text')
		{
   	        if (!field.value) 
		    {
          	    return 'Required field';
    	    }
    	}
    	
        if ( field.type == 'checkbox')
	    {
            if (!field.checked) 
		    {
          	    return 'Please Tick';
    	    }
	    }
	
		// Store the name of the RegExp to look up (removing Required)
		classCheck = field.className.substr(9, field.className.length - 9) ;
	}
	else
	{
		// Check for content
		if (!field.value) 
		{
			return null;
    	}
		
		// store name of regexp to look up
		classCheck = field.className;
	}

	// Check for validation class 
	if (!classCheck)
	{
		// no validation requested
		return null;
	}

	// Get regular expression for field		
	var regExpression = validationSet[classCheck]['regexp'];

	// alert('Field: ' + field.value + ' RegExp: ' + regExpression );
   
	if (!field.value.match(regExpression)) 
	{
		// Error - Return error message
		return validationSet[classCheck]['error'];
    }
	else
	{
		// Valid - Return NULL  
		return null;
    }
}

//------------------------------------------
//	checkValidSubmit on Submit button event
//------------------------------------------
function checkValidSubmit(e) 
{

	// check browser support
   var frm = window.event ? window.event.srcElement : e ? e.target : null;
   
   if (!frm) return;

   var errorText = '';		// Error message(s)

	// check for function support by browser
	if (!document.getElementsByTagName)
   	return;

	// Get all the form input fields	
	var inputFields = document.getElementsByTagName('input');

	// Loop through all input fields on form
	for (var i = 0; i < inputFields.length-1; i++ )
	{ 
				
		// Check for Validation ...
		// The class name contains name of Reg.Exp validation to be performed
		if (inputFields[i].className) 
		{
			var errorMessage = handleValidity(inputFields[i]);
			var errorDisplay = document.getElementById('error_' + inputFields[i].name);

			// Check: invalid with error field
			if (errorMessage && errorDisplay) 
 			{
				//alert( 'error - ' + inputFields[i].id );
				errorDisplay.innerHTML = errorMessage;
				errorDisplay.style.color = 'red';
				//alert( errorMessage );
   			}
		
			// check: valid and error field (Clear error field)
			if (!errorMessage && errorDisplay) 
 			{
				//alert( 'no error - Id:' + inputFields[i].id + ' Name: ' + inputFields[i].name + ' Display:' + errorDisplay );
				errorDisplay.innerHTML = '';
				errorDisplay.style.color = 'black';
   			}
			
			// Store error
			if (errorMessage)
			{
				if ( inputFields[i].id == 'mb-bjhku-bjhku')
				{
					errorText += 'Email address - ' + errorMessage + '\n';
				}
	         	else
				{
					errorText += inputFields[i].id + ' - ' + errorMessage + '\n';
				}
         	}
		} // if className ...
	} // for loop i ...


	//alert( 'Before Submit:' + errorText );

	// any errors ?     
	if (errorText.length > 0) 
	{
		alert('________________________________\n' +
		      '\n Please enter required information ...\n' + 
			  '________________________________\n\n' +
					errorText + '\n');
    
		frm.submitAllowed = false;
      	
		// Stop propagation ...
      	if (e && e.stopPropagation && e.preventDefault) 
		{
       		e.stopPropagation();
   			e.preventDefault();
		}
      	if (window.event) 
		{
        	window.event.cancelBubble = true;
        	window.event.returnValue = false;
        	return false;
      	}
    }
	else
	{
      	frm.submitAllowed = true;
    }
}


//------------------------------------------------------
//	Add event listeners based on type of fields
//------------------------------------------------------
function addListeners()
{

	// check for function support by browser
	if (!document.getElementById)
   	return;

	// check for function support by browser
	if (!document.getElementsByTagName)
   	return;	

	// Add Blur event for Form fields	
	var inputFields;
	
	inputFields = document.getElementsByTagName('input');

	// Loop through all input fields on form
	for (var i = 0; i < inputFields.length-1; i++ )
	{ 
		
		// Check for Validation ...
		// The class name contains name of Reg.Exp validation to be performed
		if (inputFields[i].className) 
		{
			// Required field so add event handler 
			addEvent(inputFields[i], 'blur', checkValid, false);
		}

		// Add submit validation
	 	if (!inputFields[i].form.validateSubmit) 
		{
			// Add Submit event
			addEvent(inputFields[i].form, 'submit', checkValidSubmit, false);
			if (this.submitAllowed)
			{
         		inputFields[i].form.onsubmit = this.submitAllowed; // Safari
			}
         	inputFields[i].form.validateSubmit = true;
		}
		
		} // for i
}


// set the Window onLoad event ...
addEvent(window, 'load', addListeners);

