/***************************************************************************************************

Purpose:		Perform validation checks on what users have entered into text fields

Created By:		Simon Cadd		14 Mar 2000

Change History:	Duncan Atkins	29 May 2001
				Added the function ValidateDecimal
				
				Skermode		05 Mar 2004
				Updated function ValidateDecimal to validate currency
				
				Paul Bromilow	30 Mar 2004
				Prevalidates input and makes the background red when an error
				
				Jason Jones		21 Jan 2005
				Added ValidateNumberWithDecimalPlaceControl function
				
				Ian Hunt		17 Feb 2005
				ValidateNumberWithDecimalPlaceControl now removes unnecessary decimal points

				Alex Moses		21 Mar 2007		Version 2
				Added InputFocus and InputBlur as written by John Goodall (plus markMissing by me)
				ValidateText now optionally allows us to specify whether we want symbolic characters

****************************************************************************************************/


function Validate (oTextBox, strTextToValidate, bAlphas, bNumerics)
{
	var bValid = true;
	var strValidChars = '';
	var intTextCount = 0;
	var intValidCharsCount = 0;
	var strMessage = '';
	var mychar;
	
	if (bAlphas == 'true') {
		strValidChars = strValidChars + "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ@,.-'&():/% _";
	}
	
	if (bNumerics == 'true') {
		strValidChars = strValidChars + "0123456789";
	}
	
	for (intTextCount = 0; intTextCount < strTextToValidate.length; intTextCount++) {
		mychar = strTextToValidate.charAt(intTextCount);
		for (intValidCharsCount = 0; intValidCharsCount < strValidChars.length; intValidCharsCount++)
			if (mychar == strValidChars.charAt (intValidCharsCount))
				break;
			if (intValidCharsCount == strValidChars.length)
			{
				bValid = false;
				break;
			}
	}
		
	if (bValid == false) {
		if ((bAlphas == 'true') && (bNumerics != 'true')) {
			strMessage = 'please only type letters';
		}
		else if ((bAlphas != 'true') && (bNumerics == 'true')) {
			strMessage = 'please only type numbers';
		} else {
			strMessage = 'please only type letters and numbers';
		}

		// Set background colour
		oTextBox.style.backgroundColor='#ffdddd'; // set colour	
		alert('Invalid Input, ' + strMessage + ' , please try again');
		oTextBox.focus();

		// Return a false state
		return false;
	} else {
		// Clear background colour as it is fine
		oTextBox.style.backgroundColor=''; // clear colour

		// Return a true state
		return true;
	}
	
}


function ValidateText (strTextToValidate, bAlphas, bNumerics, bSymbols)
{
	var bValid = true;
	var strValidChars = '';
	var intTextCount = 0;
	var intValidCharsCount = 0;
	var mychar;
	// If the third parameter is missing, emulate old version which allowed symbols with alphas
	if (bSymbols==null) bSymbols = bAlphas;

	if (bAlphas) // Allows space
	{
		strValidChars = strValidChars + "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ ";
	}

	if (bNumerics)
	{
		strValidChars = strValidChars + "0123456789";
		// if first character is  + or - then strip from test string
		if (strTextToValidate.charAt(0) == '-' || strTextToValidate.charAt(0) == '+')
		{
			strTextToValidate = strTextToValidate.substring(1);
		}
	}

	if (bSymbols)
	{
		strValidChars = strValidChars + "@,.-'&():/%_";
	}

	if (bAlphas || bNumerics || bSymbols)
		for (intTextCount = 0; intTextCount < strTextToValidate.length; intTextCount++)
		{
			mychar = strTextToValidate.charAt(intTextCount);
			for (intValidCharsCount = 0; intValidCharsCount < strValidChars.length; intValidCharsCount++)
				if (mychar == strValidChars.charAt (intValidCharsCount))
					break;
				if (intValidCharsCount == strValidChars.length)
				{
					bValid = false;
					break;
				}
				
		}		

	return bValid;
}


function ValidateDecimal (strDecimalToValidate,strIsCurrency)
{
	var bValid = true;
	var strValidChars = "0123456789.";
	var numDecimalCount = 0;
	var numValidCharsCount = 0;
	var strChar;
	var numDecimalPoints = 0;
	var bTooManyDP = false;


	if (strIsCurrency && strDecimalToValidate.charAt(0) == '-')
	{
		strDecimalToValidate = strDecimalToValidate.substring(1,strDecimalToValidate.length)
	}

	for (numDecimalCount = 0; numDecimalCount < strDecimalToValidate.length; numDecimalCount++)
	{
		strchar = strDecimalToValidate.charAt(numDecimalCount);
		if (strchar == '.')
		{
			numDecimalPoints++ 
			if (numDecimalCount < strDecimalToValidate.length-3)
			{
				bTooManyDP = true;
			}
		}
		for (numValidCharsCount = 0; numValidCharsCount < strValidChars.length; numValidCharsCount++)						
			if (strchar == strValidChars.charAt(numValidCharsCount))
				break;
			if (numValidCharsCount == strValidChars.length)
			{
				bValid = false;
				break;
			}
			
	}		

	if (numDecimalPoints > 1 && strIsCurrency)
	{
		bValid = false;
	}
	if (bTooManyDP && strIsCurrency)
	{
		bValid = false;
	}	
	if (bValid == false)
	{			
		return false;
	}
	else
	{
	return true;
	}	
}


function ValidateNumberWithDecimalPlaceControl(poControl, pnumDecimalPlaces)
{

	/*
		This function will chop off any extraneous numbers after a predefined decimal place limit
		It does not round the decimal portion (currently)
		
		eg: input - 345.678 
			called with 	pnumDecimalPlaces = -1 returns 345.678
			called with 	pnumDecimalPlaces = 0 returns 345
			called with 	pnumDecimalPlaces = 2 returns 345.67
			called with 	pnumDecimalPlaces = 4 returns 345.678			
	*/
	
	var strNumber = new String(poControl.value);
	var strWholeNumberPortion = new String();
	var strDecimalPortion = new String();
	var re = new RegExp("[-+]?([0-9]*)(\.)?([0-9]+)?","ig");
	
	if (isNaN(strNumber))
	{
		poControl.style.backgroundColor='#ffdddd'; // set colour	
		alert('This is not a valid value for this numeric field, please try again');
		poControl.focus();
		return false;
	}
	else
	{
		//exec the regular expression		
		re.exec(strNumber);
		
		//$1 will now contain the whole number part and $3 will contain the decimal part
		strWholeNumberPortion = RegExp.$1;
		strDecimalPortion = RegExp.$3;
		
		//What limitation is placed on the decimal portion
		switch (pnumDecimalPlaces)
		{
			case -1 :
				//return everything
				if (strDecimalPortion.length ==0) 
				{
					poControl.value = strWholeNumberPortion;
				}
				else
				{
					poControl.value = strWholeNumberPortion + '.' + strDecimalPortion;
				}
				break;
			case 0 :
				poControl.value = strWholeNumberPortion;
				break;
			default :
				strDecimalPortion = strDecimalPortion.substring(0,pnumDecimalPlaces);
				poControl.value = strWholeNumberPortion + '.' + strDecimalPortion;
		}
		
		// Remove '.'
		if (poControl.value.substr(poControl.value.length - 1) == '.')
			poControl.value = poControl.value.substr(0, poControl.value.length - 1);
		
		// Clear background colour as it is fine
		poControl.style.backgroundColor=''; // clear colour
		return true;
	}
	
}


function InputFocus (pstrID, pstrBackground, pintMaxLength)
{
	var oInput;

	if (document.getElementById) // Browser supports DHTML through the W3C DOM-2
	{
		oInput = document.getElementById(pstrID)

		if (oInput.value == pstrBackground) {
			oInput.value = '';
			if (pintMaxLength)
				oInput.maxLength = pintMaxLength;
		}
			
		oInput.style.color = '#000';
	}
}


function InputBlur (pstrID, pstrBackground, pbMaxLength)
{
	var oInput;

	if (document.getElementById) // Browser supports DHTML through the W3C DOM-2
	{
		oInput = document.getElementById(pstrID)

		if (oInput.value == '')
		{
			if (pbMaxLength && oInput.maxLength < pstrBackground.length)
				oInput.maxLength = pstrBackground.length;
			oInput.value = pstrBackground;
			oInput.style.color = '#B1B1B1';
		}
	}
}


function markMissing(poLabel, pbMissing)
{
	var strErrClass = ' missingfield';
	var oErrorRegExp = new RegExp(strErrClass + '$');
	var bMarked = (poLabel.className.search(oErrorRegExp) > -1);

	if (pbMissing && !bMarked) // need to mark
	{
		poLabel.className = poLabel.className + strErrClass;
	}
	else if (!pbMissing && bMarked) // need to unmark
	{
		poLabel.className = poLabel.className.replace(oErrorRegExp);
	}
}


function cancelKeyboardPaste(event, pstrFormName, pstrInputName)
{
	if (browserName!='IE') // IE simply needs attribute onpaste="return false"
	{
		with (event) {
			if ((shiftKey && keyCode == 45) ||	// Shift+Insert (Firefox/Opera)
				(ctrlKey && keyCode == 86) ||	// Control+V (Opera)
				(ctrlKey && charCode == 118) ||	// Control+V (Firefox)
				(metaKey && charCode == 118))	// Command+V (Safari)				
			{
				// Since mouse clicks are too complicated to track, advise user why we have disabled this key combination
				alert('Pasting is discouraged because a typing error might\nbe compounded and cause problems in the future.');
				setTimeout('clearInputValue(\'' + pstrFormName + '\', \'' + pstrInputName + '\')', 1);
			}
			
		}
	}
}


function clearInputValue(pstrFormName, pstrInputName)
{
	document.forms[pstrFormName].elements[pstrInputName].value= '';
}