/*
<!-- -->
<!-- The copyright in the work that is PublicAccess is the exclusive -->
<!-- property of CAPS Solutions Ltd, and its respective copyright owners, and is -->
<!-- protected under United Kingdom copyright law and other international copyright -->
<!-- treaties and conventions. 
<!-- © 2005. CAPS Solutions Ltd and its licensor(s). All rights reserved. -->
*/

/*
	validate.jsxtrain5
	PA client-side data validation functions
	adapted from core UFWEB validate.js
	dependant on utility.js
*/

//***********************************************************************************
// Validates form data prior to submit
//***********************************************************************************
function validateFormData (f){

//alert('hi in validate form');
	if (!validateAllFormFields(f))
		return false;
	//alert('hi in validate form 2');
	if (window.validateFormDataSpecific){
		if (!validateFormDataSpecific())
			return false;
	}
	
	// validation succeeded - return true and submit
	return true;
}



//***********************************************************************************
// Validates search form data and submits form
//***********************************************************************************
function validateAndSubmitSearchForm(f, elBtn) {
	
	 var bValidated = false;
	 	
	 //check for specific verify function in scope
	 if(window.verify){
		 if (verify(f)) {
	   	    bValidated = true;
		 }else{
			return false;
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
	  } else bValidated = validateFormData(f);
		
	 if (bValidated == true){
		  elBtn.disabled = true;
		  f.submit();
		  return true;
	 
	 }else 
	 	return false;
}

//***********************************************************************************
// checks that all fields contain valid data for the field type
//***********************************************************************************
function checkAllFieldTypes(f){
	
	var arFormEls = f.elements;
	var iElCount = arFormEls.length;
	var arBadFormEls = new Array();
		
	for (var i=0; i < iElCount; i++){

		if (!checkFieldType(arFormEls[i]) && arFormEls[i].value != ''){
			arBadFormEls[arBadFormEls.length] = arFormEls[i];
		}
	}
	
	if (arBadFormEls.length > 0){
		
		var msg; 
		var szFormatTxt;
		var desc, descValue, fieldtype, fieldtypeValue;
  		msg = "Error: the following fields contain invalid values:\n\n";
  		arrLength = arBadFormEls.length;
  		for (var i=0; i< arrLength; i++){
			

			
			desc = getAttributeFromElement(arBadFormEls[i],"desc").value;
			fieldtype = getAttributeFromElement(arBadFormEls[i],"fieldtype").value;
			
			if (desc!=null)
  			{
  				descValue=desc.value;
  			}
  			else
  			{
	  			descValue="";
  			}
  			
  			if (fieldtype!=null)
  			{
  				fieldtypeValue=fieldtype.value;
  			}
  			else
  			{
  				fieldtypeValue="";
  			}
  			
  			szFormatTxt=getFormatText(fieldtypeValue);
			
  			msg += (i + 1) + '. ' + descValue + ' (must be of type ' + fieldtypeValue + ' ' + szFormatTxt + ')\n';
  		}
		msg += '\nPlease complete all fields correctly before saving the record.';
		
		alert(msg);
		return false;
		
	}else{
		return true;
	}
	
}

//***********************************************************************************
// gets some help text to tell the user how to format a particular data type
//***********************************************************************************
function getFormatText(szFieldType){
	
	var szFormat;
	switch (szFieldType){
	
		case szcFIELDTYPE_DATE:
			szFormat='DD/MM/YYYY'
			break;
			
			
		case szcFIELDTYPE_TIME:
			szFormat='HH24:MM:SS';
			break;	
		
		case szcFIELDTYPE_SHORTTIME:
			szFormat='HH24:MM';
			break;
		
		case szcFIELDTYPE_HOURSMINUTES:
			szFormat='HH.MM';
			break;
			
		default:
			szFormat = '';
			break;
	}
	
	return szFormat;
}

//***********************************************************************************
// Checks that field has appropriate format and data type
//***********************************************************************************
function checkFieldType(el){
	
	var fieldtype;
	var bFoundFieldTypeAttribute=false;
	var elementAttribute;
	var i=0;
	
	fieldtype = getAttributeFromElement(el,"fieldtype");
	
	if (fieldtype!=null) //fieldtype attribute found in element
	{
		switch (fieldtype.value){
			
			// only use dates in PA
			case szcFIELDTYPE_DATE:
				return isFieldValidDate(el);
				break;
			
			case szcFIELDTYPE_PHONENUMBER:
				return isFieldValidTelephoneNumber(el);
				break;
				
			case szcFIELDTYPE_EMAIL:
				return isFieldValidEmailAddress(el);
				break;
		
		
			default:
				return true;
				break;
		}
	}
	else return true;
}

//***********************************************************************************
// validates validity of date and format of datefield
//***********************************************************************************
function isFieldValidDate(el){
	
	var szDateVal = el.value;
	var iLen = szDateVal.length;
	
	// return if zero length - if field is required trap error elsewhere
	if(0 == iLen)
		return true;

	
	var ar_szDateParts = szDateVal.split('/');
	
	// check that 3 elements are present
	if (ar_szDateParts.length != 3){
		return false;
	}

	// check for 2-digit mask on all values
	if (ar_szDateParts[0].length < 2 || ar_szDateParts[1].length < 2 || ar_szDateParts[2].length < 4){
		return false;
	}
	
	// check that the numeric values are within real date ranges	
	var d = atoi(ar_szDateParts[0]);
	var m = atoi(ar_szDateParts[1]);
	var y = atoi(ar_szDateParts[2]);
	
	// check that values are valid
	if(y < 1601 || y > 4500 || m < 1 || m > 12 || d < 1 || d > getMonthDayCount(m,y))
		return false;
	
	// all ok
	return true;
}

//***********************************************************************************
// validates a numeric field
//***********************************************************************************
function isFieldValidNumber(el){
	
	 var pVal = el.value;

	 if (!isNaN(el.decplaces))
	 	return isValidDecimalNumber(pVal, el.decplaces);
	 else
		return isNumber(pVal);
}

//***********************************************************************************
// Checks that all fields with the required attribute set to true are completed
//***********************************************************************************
function checkRequiredFields(f){

	var arrMissingFields = new Array();
	var arrLength = 0;
 	var iElCnt = f.elements.length
 	var required, desc, descValue="";
  	
	//check "required" attributes
  	for (var j=0; j < iElCnt; j++){
			
		desc = getAttributeFromElement(f.elements[j],"desc");
		required = getAttributeFromElement(f.elements[j],"required");	
		
  		if (required!=null && required.value)
  		{
  			if (required.value == "true" || required.value==true)
  			{	
  				if (desc!=null)
  				{
  					descValue = desc.value;
  				}
				else
				{
					descValue="";
				}
		  		
  				if (!ForceEntry(f.elements[j]))
  				{
					// add this field id to the list of missing fields
  					arrLength = arrMissingFields.length;
  					if (arrLength > 0)
  					{
						arrMissingFields[arrLength] = descValue;
					}
					else
					{
						arrMissingFields[0] = descValue;
					}
  				}
  			}
  		}
  	}

      	
  	if (arrMissingFields.length > 0){
  		var msg; 
  		msg = "Error: the following required fields are missing:\n\n";
  		arrLength = arrMissingFields.length;
  		for (var i=0; i< arrLength; i++){
  			msg += (i + 1) + '. ' + arrMissingFields[i] + '\n';
  		}
		msg += '\nPlease complete all required fields before saving the record.';
		alert(msg);
  		return false;
  	
  	}
	return true;

}


//***********************************************************************************
//***********************************************************************************
function validateAllFormFields(f){
	
	var arrMissingFields = new Array();
	var arBadFormEls = new Array();
	
	var arrLength = 0;
	
	var msg; 
	
 	var iElCnt = f.elements.length
 	
 	var desc, descValue="";
 	var required, fieldtype, fieldtypeValue="";

  	for (var j=0; j < iElCnt; j++){
		
		desc = getAttributeFromElement(f.elements[j],"desc");
		required = getAttributeFromElement(f.elements[j],"required");
		
		//required fields
		if (required!=null && required.value)
		{	
			if (required.value == "true" || required.value==true)
  			{	
  				if (desc!=null)
  				{
  					descValue=desc.value;
  				}
  				else
  				{
  					descValue="";
  				}
	  			
  				if (!ForceEntry(f.elements[j]))
  				{
					// add this field id to the list of missing fields
  					arrLength = arrMissingFields.length;
  					if (arrLength > 0)
  					{
						arrMissingFields[arrLength] = descValue;
					}
					else
					{
						arrMissingFields[0] = descValue;
					}
  				}
  			}
  		}
		
		// check field type
		if (!checkFieldType(f.elements[j]) && f.elements[j].value != '')
			arBadFormEls[arBadFormEls.length] = f.elements[j];
	

  	}//end loop through all form fields
	
	
	//prepare error messages
	if (arrMissingFields.length > 0){
  		msg = "Error: the following required fields are missing:\n\n";
  		arrLength = arrMissingFields.length;
  		for (var i=0; i< arrLength; i++){
  			msg += (i + 1) + '. ' + arrMissingFields[i] + '\n';
  		}
		msg += '\nPlease complete all required fields before saving the record.\n\n';
		alert(msg);
		return false;
  	}
	
	if (arBadFormEls.length > 0){
		var szFormatTxt;
  		msg = "Error: the following fields contain invalid values:\n\n";
  		arrLength = arBadFormEls.length;
  		

		
  		
		for (var i=0; i< arrLength; i++){
		
		  	desc = getAttributeFromElement(arBadFormEls[i],"desc");
			fieldtype = getAttributeFromElement(arBadFormEls[i],"fieldtype");
  		
  		  	if (desc!=null)
  			{
  				descValue=desc.value;
  			}
  			else
  			{
	  			descValue="";
  			}
  			
  			if (fieldtype!=null)
  			{
  				fieldtypeValue=fieldtype.value;
  			}
  			else
  			{
  				fieldtypeValue="";
  			}
			
			szFormatTxt=getFormatText(fieldtypeValue);
			
  			msg += (i + 1) + '. ' + descValue + ' (must be of type ' + fieldtypeValue + ' ' + szFormatTxt + ')\n';
  		}
		msg += '\nPlease complete all fields correctly before saving the record.';
		
		alert(msg);
		return false;
		
	}

	//all fields are validated - return true
	return true;

}


//***********************************************************************************
// Checks to see if a required field is blank (empty or whitespace only)
//***********************************************************************************
function ForceEntry(objField){
	var strField = new String(objField.value);

	if (isWhitespace(strField)) {
		return false;
	}
	return true;
}


//***********************************************************************************
// enforces maxlength attribute for <textarea> elements
//***********************************************************************************
function enforceTextAreaMaxLength(elTextArea){
	
	var iMaxLen = elTextArea.maxlength;
	var iNumChars = elTextArea.innerText.length + 1;
	
	if (iNumChars > iMaxLen){
		cancelBubble=true;
		window.event.returnValue =false;
	}
}

//***********************************************************************************
// validates the format of a telephone number
// raises a message box if has < 11 characters (minus whitespace and hyphens)
// or if contains non-numeric characters (except hyphens)
//  taken from ufweb validate.js
//***********************************************************************************
function isFieldValidTelephoneNumber(elFld){
	
	var szFailReason;
	var szTelNum = elFld.value;
	var szTelNumChar;
	var i;
	
	// ignore if nothing entered
	if (szTelNum=='')
	{
		return true;
	}

	//strip out all permissable non-numeric characters
	szTelNum=szTelNum.split('-').join('');
	szTelNum=szTelNum.split(' ').join('');
	szTelNum=szTelNum.split(')').join('');
	szTelNum=szTelNum.split('(').join('');
	
	if (!isNumber(szTelNum))
	{
		szFailReason = 'The telephone number entered contains non-numeric characters.  Verify that this is a valid telephone number.';
		return false;
	}	

	
	// checks that the telephone number has at least 11 characters
	if (szTelNum.length < 11){
		szFailReason = 'The telephone number entered is less than 11 characters in length.  Verify that this is a valid telephone number.';
		return false;
	}
	
	// all ok
	return true;
	
}

//***********************************************************************************
// validates the format of an email address - incomplete.
//***********************************************************************************
function isFieldValidEmailAddress(elFld){
   
   var szEmail = elFld.value;
   var bValid = true;
	
	// ignore if nothing entered
	if (szEmail==''){
		return true;
	}

	// check length
	if (szEmail.length < 5){
		// a@b.c should be the shortest an address could be
		bValid = false;
	}
	
	// check characters
	
	// at least one @ and . is required
    if(-1 == szEmail.indexOf("@") || -1 == szEmail.indexOf(".")) { 
       bValid = false;
    }
	
	// invalid characters are , # ! and " "
    if(-1 != szEmail.indexOf(",") || -1 != szEmail.indexOf("#") || -1 != szEmail.indexOf("!") || -1 != szEmail.indexOf(" ")) { 
        bValid = false;
	}

	// check for domain name after the @
    if(szEmail.length == (szEmail.indexOf("@")+1) ) {
        bValid = false;
    }

    return bValid;
}
