var validationOn= true;
var ignoreValidation = false;
var datevalid=true;
var checkFieldsFrom;
var checkFieldsTo;
var isValid = true;
var topLayer = "creditAddress";	
var declarationDate = new Date();
var focusField;

function doFocus2()
{
	focusField.focus();
}

function doFocus(oField)
{
	if (typeof(oField.tabName) != "undefined")
	{
		//force the section to be displayed
		parent.Working.doTabClick(parent.Working[oField.tabName]);
	}
	focusField = oField;
	setTimeout("doFocus2()",100);
}

function doFormExpiredPass()
{
	if (ValidateFormExpired(ExpiredPass))
	{
		parent.Menu.setTitle("Wait_Expired_Password");
		parent.Working.ExpiredPass.submit();
		parent.Working.ExpiredPass.reset();
	}
}

function ValidateFormExpired(theForm)
{
	return validateLayer("ExpiredPass");
}

function doFormNewPassword()
{
	if (ValidateFormNewPass(NewPassword))
	{
		parent.Menu.setTitle("Wait_Change_Password");
		parent.Working.NewPassword.submit();
		parent.Working.NewPassword.reset();
	}
}

function ValidateFormNewPass(theForm)
{
	return validateLayer("NewPassword");
}

function doFormLogon()
{
	if (ValidateFormLO(LogonRequest))
	{
		LogonRequest.btnLogon.disabled = true;
		LogonRequest.submit();
		LogonRequest.reset();
	}
}

function ValidateFormLO(theForm)
{
	var nData;
	
	isValid=validateLayer("Logon");

	return (isValid);
}

function showLayer( newTop )
{
	if (newTop == "consumer")
	{
		topLayer = "consumerAddress";
	}

    // Display the new layer
	window.scrollTo(0,0);
	document.all(topLayer).className = "cardHide";
	document.all(newTop).className = "cardShow";
	topLayer = newTop;
}


// Stop beep from Logon - USER ID, GROUP ID and Password fields when pressing Enter
function filterKey()
{
	return window.event.keyCode != 13;
}

var g_oCheckField;
var g_oNextField;
function doCheck(oField,oNext)
{
	if (typeof(oField) == "object")
	{
		g_oCheckField = oField;
		g_oNextField = oNext;
		setTimeout("doCheck2()",0);
	}
}

function doCheck2()
{
	if (g_oCheckField.value.length == g_oCheckField.maxLength
	 && typeof(g_oNextField) == "object")
		g_oNextField.focus();
}

function autoTabNumber(oField,oNext)
{
	var key = window.event.keyCode;
	if (key >= 48 && key <= 57)
	{
		doCheck(oField,oNext);
		return true;
	}
	return false;
}

function autoTabField(oField,oNext)
{
	if (window.event.keyCode >= 32)
	{
		doCheck(oField,oNext);
	}
	return true;
}

function inputLatin()
{
	var key = window.event.keyCode;
	if (key >=32 && key <= 126)
	{
		window.event.returnValue = true;
	}
	else
	{
		window.event.returnValue = false;
	}
	return window.event.returnValue;
}

function inputNumber()
{
	var key = window.event.keyCode;
	if (key >=48 && key <= 57)
	{
		window.event.returnValue = true;
	}
	else
	{
		window.event.returnValue = false;
	}
	return window.event.returnValue;
}

function inputNegativeNumber()
{
	var key = window.event.keyCode;
	if (key==45)
	{
		window.event.returnValue = true;
	}
	else if (key >=48 && key <= 57)
	{
		window.event.returnValue = true;
	}
	else
	{
		window.event.returnValue = false;
	}
	return window.event.returnValue;
}

function KeyPressCheck(theForm)
{
	var keyCode;
	
	keyCode = window.event.keyCode;

	if (keyCode == 13 && wValue("FLG_ENTER") == "Submit" )
	{
		switch (theForm.name)
		{
			case "LogonRequest":
				doFormLogon();
				break;

			case "ConsumerEnquiry":
				isValid=ConsumerEnquiryAction('Submit');
				return (isValid);
				break;

			case "CreditEnquiry":
				isValid=CreditEnquiryAction('Submit');
				return (isValid);
				break;

			case "ManagerEnquiry":
				isValid=ManagerEnquiryAction('Submit');
				return (isValid);
				break;

			case "CEUSearch":
				isValid=CEUSearchValidation();
				return (isValid);
				break;

			case "CEU":
				isValid=CEUUpdateValidation();
				return (isValid);
				break;
			case "ExpiredPass":
				doFormExpiredPass();
				break;
			case "NewPassword":
				doFormNewPassword();
				break;
		}
	}
	return window.event.returnValue;
}


function ConsumerEnquiryAction(Action)
{
	isValid=true;

	isValid=validateLayer("consumer");

	if (isValid == true)
	{	
		parent.Menu.setTitle("Wait_Send");
		CreditEnquiry.submit();
		CreditEnquiry.reset();
	}
	else
	{
		return (false);
	}
}

function CreditEnquiryAction(Action)
{
	isValid=true;

	isValid=validateLayer("credit");
			
	if (isValid == true)
	{	
		parent.Menu.setTitle("Wait_Send");
		CreditEnquiry.submit();
		CreditEnquiry.reset();
	}
	else
	{
		return (false);
	}

}

function ManagerEnquiryAction(Action)
{
	isValid=true;

	isValid=validateLayer("manager");
			
	if (isValid == true)
	{	
		parent.Menu.setTitle("Wait_Send");
		CreditEnquiry.submit();
		CreditEnquiry.reset();
	}
	else
	{
		return (false);
	}

}
function validateLayer(strCurrentForm)
{

	if (validationOn == false)
	{
		return (true);
	}

	var nData;
	var strFieldName;
	var formRequest;
	var nSecondSep;
	var strFieldForm;
	var isValid = true;

    // LOGON FORM
	if ( strCurrentForm == "Logon" )
	{	
		formRequest = document.forms("LogonRequest") ;
		checkFieldsFrom=0;
		checkFieldsTo=3;
	}

    // EXPIRED PASSWORD
	if ( strCurrentForm == "ExpiredPass" )
	{
		formRequest = document.forms("ExpiredPass") ;
		isValid = PasswordsMatch();
		checkFieldsFrom=0;
		checkFieldsTo=2;
	}

    // NEW PASSWORD
	if ( strCurrentForm == "NewPassword" )
	{
		formRequest = document.forms("NewPassword") ;
		isValid = PasswordsMatch();
		checkFieldsFrom=0;
		checkFieldsTo=2;
	}

    // CAIS EMEREGNCY UPDATE	
	if ( strCurrentForm == "CEU" )
	{	
		formRequest = document.forms("CEU") ;
		checkFieldsFrom=8;
		checkFieldsTo=29;
		isValid=CAISEUVal();
	}


    // 	CAISEU SEARCH
	//there is no specific validation for this - just lengths and data types and mandatory
	if ( strCurrentForm == "CEUSearch" )
	{	
		formRequest = document.forms("CEUSearch") ;
		checkFieldsFrom=0;
		checkFieldsTo=2;
	}


	
//////////////////////////////////////////////////////////////////////////////
////    Credit Enquiry form
///////////////////////////////////////////////////////////////////////////////

	if ( strCurrentForm == "credit" )
	{	
		formRequest = document.forms("CreditEnquiry") ;		

		isValid=true;
		checkFieldsFrom=0;
		checkFieldsTo=formRequest.elements.length - 1;
		
		isValid = creditApplication();
		if (isValid==false)
		{
			return(false);
		}

		isValid=CredEnquiryConsumerInfo();
		if (isValid==false)
		{
			return(false);
		}

		isValid = CEAddress();
		if (isValid==false)
		{
			return(false);
		}

	}

//////////////////////////////////////////////////////////////////////////////
////    Consumer Enquiry form
///////////////////////////////////////////////////////////////////////////////
	if ( strCurrentForm == "consumer" )
	{	
		formRequest = document.forms("CreditEnquiry");		
		isValid=true;

		checkFieldsFrom=0;
		checkFieldsTo=formRequest.elements.length - 1;
	
		isValid = creditApplication();
		if (isValid==false)
		{
			return(false);
		}

		isValid=CredEnquiryConsumerInfo();
		if (isValid==false)
		{
			return(false);
		}

		isValid = CEAddress();
		if (isValid==false)
		{
			return(false);
		}

	}

//////////////////////////////////////////////////////////////////////////////
////    Manager Enquiry form
///////////////////////////////////////////////////////////////////////////////
	if ( strCurrentForm == "manager" )
	{	
		formRequest = document.forms("CreditEnquiry") ;		

		isValid=true;
		checkFieldsFrom=0;
		checkFieldsTo=formRequest.elements.length - 1;
		
		isValid = creditApplication();
		if (isValid==false)
		{
			return(false);
		}

		isValid=CredEnquiryConsumerInfo();
		if (isValid==false)
		{
			return(false);
		}

		isValid = CEAddress();
		if (isValid==false)
		{
			return(false);
		}

	}

	if ( false != isValid )
	{
		var nData;
		for(nData = checkFieldsFrom; nData <= checkFieldsTo; nData++)
		{
			// Check if we got something with an error
			if (CheckField(formRequest.elements[nData]) == false)
			{
				return (false);
			}
		}
		return (true);
	}
	
	return (false);
}

function CheckField( fieldTest )
{
	var strName;
	var strType;
	var strRequired;
	var bValidType;
	var strSize;
	var nSize;
	var valTest;

    // Display the value of the field
	//if(!(fieldTest.value == null || fieldTest.value == "<undefined>" || fieldTest.value ==  ""))
    //    doAlert(fieldTest.value);

	// Get the name of the field
	strName = fieldTest.validation;

    // Check if we need to validate this field
    if(strName == null || strName == "<undefined>" || strName == "")
        return (true);


	////////////////////////////////////////////////////////////
	// First validation: check if the field is required or not
	// 
	strRequired = strName.substring(1,2);

	if(strRequired == "r")
	{
		// Check for null information 
		if(fieldTest.value == null || fieldTest.value == "<undefined>" || fieldTest.value ==  "")
		{
			// Message for required information 
			DisplayErrorMessage(null,1,0,fieldTest);
			return false;
		}
	}


	////////////////////////////////////////////////////////////
	// Second validation: Check for the minimun size
	//

	// Check if we have information or not
	if(fieldTest.value == null || fieldTest.value == "<undefined>" || fieldTest.value ==  "")
	{
		// We have null data
	}
	else	
	{
		// We do not have null data
		strSize = strName.substring(2,4);
		nSize = parseInt(strSize,10);	// Convert the information to numbers

		// Check the minimun size
		if(nSize > 1)
		{
			// Check the size
			if(nSize > fieldTest.value.length)
			{
				DisplayErrorMessage(strName.substring(0,1), 0,nSize,fieldTest);	// Too short
				return false;
			}
		}

		////////////////////////////////////////////////////////////
		// Third validation: Check for the correct characters
		//

		// Check for the type of field
		strType = strName.substring(0,1);

		// Call the correct function for each type of validation
		if(strType == "a")		// All characters are valid
		{
			bValidType = true;
		}
		else if(strType == "n")		// Numeric validation
		{
			bValidType = ValidNumber( fieldTest );
		}
		else if(strType == "d")		// Date validation
		{
			bValidType = ValidDate( fieldTest.value );
		}
		else if(strType == "c")		// Currency validation
		{
			bValidType = ValidCurrency( fieldTest );
		}
		else if(strType == "z")		// negative numeric
		{
			bValidType = ValidNegativeNumber( fieldTest );
		}
		else if(strType == "l")		// Latin validation
		{
			bValidType = ValidLatin( fieldTest );
		}
		else
		{
			bValidType = true;
		}

		////////////////////////////////////////////
		// Check for the validation 
		//
		if(bValidType == false)
		{
			DisplayErrorMessage(strType,0,0,fieldTest);
			return (false);
		}

	}


	// We are assuming everithing is ok
	return (true);
}

function DisplayErrorMessage(errType,errRequired,errSize,fieldTest)
{

    	var strForm;
	var strField;
	var strNameField;
	var nIndex;

	// Get the name of the field that we are going to display in the screen
	if(fieldTest.fieldName != null)
		
		strField = fieldTest.fieldName;
			
	else
	{
		// Get the name of the field from the field itself
		strNameField = fieldTest.name;

		nIndex = strNameField.lastIndexOf("_");
	        strForm = strNameField.substring(0,nIndex);

	        strField = strNameField.substring(nIndex+1,strNameField.length);

		if (trim(strField.length ==0))
		{
			strField=strNameField;
		}
	}

	if(errRequired == 1)
	{
		doAlert(wEmbed(ERR_NO_DATA,strField));
	}

	// Check the sizes
	else if(errSize != 0)
	{
		if ( errType == "n")
		{
			doAlert(wEmbed(ERR_NOT_ENOUGH_DIGITS,errSize,strField));
		}
		else
		{
			doAlert(wEmbed(ERR_NOT_ENOUGH_CHARS,errSize,strField));
		}

	}

	///////////////////////////////////////////////////////
	// Check the Errors type 
	//

	// Dates
	else if(errType == "d")
	{
		doAlert(wEmbed(ERR_INVALID_DATE,strField));
	}

	// Currency
	else if(errType == "c")
	{
		doAlert(wEmbed(ERR_INVALID_AMOUNT,strField));
	}

	// Numbers
	//dl added for negative entries for caiseu
	else if(errType == "n" || errType == "z")
	{
		doAlert(wEmbed(ERR_TEXT_NUMBER_IN_NUMERIC,strField));
	}

	// Date parts
	else if(errType == "D")
	{
		doAlert(wEmbed(ERR_INVALID_DAY,strField));
	}
	else if(errType == "M")
	{
		doAlert(wEmbed(ERR_INVALID_MONTH,strField));
	}
	else if(errType == "Y")
	{
		doAlert(wEmbed(ERR_INVALID_YEAR,strField));
	}

	// Latin
	else if(errType == "l")
	{
		doAlert(wEmbed(ERR_NON_LATIN_TEXT,strField));
	}

	if (!fieldTest.disabled)
	{
		doFocus(fieldTest);
	}
}

function ValidLatin( testField )
{
	var checkStr = testField.value;
	var allValid = true;
	for (var i = 0; i < checkStr.length; i++)
	{
		var ch = checkStr.charCodeAt(i);
		if (ch < 32 || ch > 126)
		{
			allValid = false;
			break;
		}
	}
	return (allValid);
}

function ValidNumber( testField )
{
	var checkOK = "0123456789";
	var checkStr = testField.value;
	var allValid = true;

	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		{
			if (ch == checkOK.charAt(j))
				break;
		}

		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
	}

	// Return the value
	return (allValid);
}


function ValidNegativeNumber( testField )
{

var result = testField.value.indexOf("-")
if (result !=-1)
	{
	var test = testField.value.substr(result+1,testField.value.length)
	result = test.indexOf("-")
	if (result !=-1)
		{
		return (false);
		}
	}



	var checkOK = "0123456789-";
	var checkStr = testField.value;
	var allValid = true;

	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		{
			if (ch == checkOK.charAt(j))
				break;
		}

		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
	}

	// Return the value
	return (allValid);

}


function ValidDate(dateField)
{
	var strDate = trim(dateField);
	var delimiters = "/-.";

	var dayStr = "";
	var monStr = "";
	var yearStr = "";
	var numSeps = delimiters.length;
	var i = 0;

	//test with each separator
	for (i = 0; i < numSeps; i++)
	{
		var sep = delimiters.charAt(i);
		var firstSep = strDate.indexOf(sep);
		var lastSep = strDate.lastIndexOf(sep);
		if(firstSep != lastSep) //no seps gives -1,-1, one sep gives n,n.
		{
			dayStr = strDate.substring(0,firstSep);
			monStr = strDate.substring(firstSep+1, lastSep);
			yearStr = strDate.substring(lastSep+1);
		}
	}

    var lenDay = dayStr.length;
	var lenMon = monStr.length;
	var lenYear = yearStr.length;

    if( ( lenDay != 2 ) || ( lenMon != 2 ) || ( lenYear != 4 ) )
	{
	    return false;
	}

	// extract day, month and year
	var nDay   = parseInt(dayStr,10);
	var nMonth = parseInt(monStr,10);
	var nYear  = parseInt(yearStr,10);

	if(isNaN(nDay) || isNaN(nMonth) || isNaN(nYear))
	{
		return false;
	}
	
	// validate year, month, day values
	if (strDate.length == 6) {
		nYear += (nYear <  30) ? 2000 : 1900;
	}
	//if (nYear < 1900) return false;
	if (nMonth < 1 || nMonth > 12) return false;
	if (nDay < 1 || nDay > 31) return false;
	if (nDay > 30 && (nMonth == 4 || nMonth == 6 || nMonth == 9 || nMonth == 11))
		return false;
	if (nMonth == 2 && nDay > 29) return false;
	if (nMonth == 2 && nDay > 28 && !isLeap(nYear)) return false;
	// construct "ccyymmdd" string
	var strDate = nYear + "";
	if (nMonth < 10) strDate += "0" + nMonth; else strDate += nMonth; 
	if (nDay   < 10) strDate += "0" + nDay;   else strDate += nDay;
	return strDate; 
}

function isLeap(nYear)
{
	allValid = false;

	// if the year is not divisible by 4 it is not a leap year
	if( nYear.valueOf() % 4 == 0 )
		allValid = true;

	// if the year is divisible by 100 it is not a leap year...
	if( nYear.valueOf() % 100 == 0 )
		allValid = false;

	// ...unless it is divisible by 400
	if( nYear.valueOf() % 400 == 0 )
		allValid = true;

	return allValid;
}

function ValidPostcode(postcodeField)
{
	var strPostcode = trim(postcodeField);

	if (strPostcode.length ==0)
	{
		return (true)
	}

	var delimiters = "-";
	var digits = "0123456789";
	var s;


	if (delimiters.indexOf(strPostcode.charAt(2)) >= 0)
	{
		//remove that hyphen if there is one
		strPostcode = strPostcode.substr(0,2) + strPostcode.substr(3)
	}

	//now check for numeric only

	for (var i = 0; i < strPostcode.length; i++) 
	{
		if (digits.indexOf(strPostcode.charAt(i)) < 0)
		{	
			return (false);
		}
	}
	
	//we want 5 and only 5
	if (strPostcode.length != 5)
	{
		return (false);
	}	

	return (true);
}

function trimLeft(myVal)
{
	var myStr = myVal + "";
	while (myStr.length > 0 && myStr.charAt(0) == " ")
		myStr = myStr.substr(1);
	return myStr;
}

function trimRight(myVal)
{
	var myStr = myVal + "";
	while (myStr.length > 0 && myStr.charAt(myStr.length-1) == " ")
		myStr = myStr.substr(0,myStr.length-1);
	return myStr;
}

function trimBoth(myVal)
{
	return trimLeft(trimRight(myVal));
}

function trimAll(myVal)
{
	var myStr = myVal + "";
	var re = / /g;
	return myStr.replace(re,"");
}

function trim(myVal)
{
	return trimLeft(trimRight(myVal));
}

function GetTodaysDate()
{
	var Today = new Date();

	var year = Today.getFullYear(); // getYear() returns 70-99 for 1900s, 2000+ or 100+ for 2000s (depending on the documentation you read!)
	if (year < 2000) 
		year += 1900;

	var month = Today.getMonth() + 1;
	if (month < 10)		
		month = "0" + month;
	
	var day = Today.getDate();
	if (day < 10) 
		day = "0" + day;
	
	var strResult;
	    
    strResult = "" + year;
    strResult += month;
    strResult += day;
    return strResult;
}

function convertYMD(sDate)
{
	var strResult;

	var nDay = sDate.substr(0,2);
	var nMonth = sDate.substr(2,2);
	var nYear = sDate.substr(4,4);

	/// output as YYYYMMDD so we can compare on it
	strResult = "" + nYear;
	strResult = strResult.concat(nMonth);
	strResult = strResult.concat("" + nDay);
	
	return strResult;
}

//checks if a date is valid and if > todays date 
//it will return an error if the date is in the past
//MSD 02-12-99
function ValidPresentDate(testField)
{
	var dateValid = true;
	//0 is a valid and correct date
	//1 is a invalid date
	//2 is a valid but incorrect date 
	var dateValidAndCorrect = 0;

	//first of all do we have a valid date string
	dateValid = ValidDate(testField);
	if (dateValid)
	{
		//now compare it against the system date
		var presentDate = new Date();

		if (declarationDate.getYear() == presentDate.getYear())
		{
			if (declarationDate.getMonth() == presentDate.getMonth())
			{
				if (declarationDate.getDate() > presentDate.getDate())
					dateValidAndCorrect = 0;
				else dateValidAndCorrect = 2;
			}
			else 
			{
				if (declarationDate.getMonth() > presentDate.getMonth())
					dateValidAndCorrect = 0;
				else dateValidAndCorrect = 2;
			}
		}
		else
		{
			if (declarationDate.getYear() >= presentDate.getYear())
				dateValidAndCorrect = 0;
			else dateValidAndCorrect = 2;
		}
	}
	else
	{
		dateValidAndCorrect = 1;
	}

	return (dateValidAndCorrect);
}

function validateDateParts(oForm,sID)
{
	var oD = oForm[sID+"D"];
	var sD = trim(oD.value);
	var oM = oForm[sID+"M"];
	var sM = trim(oM.value);
	var oY = oForm[sID+"Y"];
	var sY = trim(oY.value);
	if (sD != "" || sM != "" || sY != "")
	{
		var nD = parseInt(sD,10);
		if (isNaN(nD) || nD < 1 || nD > 31)
		{
			DisplayErrorMessage("D",0,0,oD)
			return false;
		}
		var nM = parseInt(sM,10);
		if (isNaN(nM) || nM < 1 || nM > 12)
		{
			DisplayErrorMessage("M",0,0,oM)
			return false;
		}
		var nY = parseInt(sY,10);
		if (isNaN(nY) || nY < 1300 || nY > 2500)
		{
			DisplayErrorMessage("Y",0,0,oY)
			return false;
		}
	}
	return true;
}


