/*********************************************************************************
 * Validates the specified 'theAmount' for a percentage value
 ********************************************************************************/
function isValidPercentage(theAmount) {
	//Matches theAmount to the specified regular expression without the currency but with decimals
	//Valid values are: 1.2 or 1.23 or 234.5 BUT NOT 998864846841.65
	if (theAmount.match(/^(\d{1,3})(\.\d{1,2})$/)) {
		return true;
	}
	//Matches theAmount to the specified regular expression without the currency without decimals
	//Valid values are: 1 or 23 or 998 BUT NOT 9867868678
	if (theAmount.match(/^(\d{1,3})$/)) {
		return true;
	}
	return false;
}

/*********************************************************************************
 * Validates the specified 'theAmount' for an amount value
 ********************************************************************************/
function isValidAmount(theAmount) {
	if (isValidPositiveAmount(theAmount)) {
		return true;
	}
	//Matches theAmount to the specified regular expression without the currency but with decimals
	//Valid values are: -1.23 or -23.45 or -998864846841.65 or -0.1
	if (theAmount.match(/^(\-\d{1})+(\.\d{1,2})$/)) {
		return true;
	}
	//Matches theAmount to the specified regular expression without the currency but with decimals
	//Valid values are: -.23 or -.4
	if (theAmount.match(/^(\-)+(\.\d{1,2})$/)) {
		return true;
	}
	//Matches theAmount to the specified regular expression without the currency without decimals
	//Valid values are: -1 or -23 or -998864846841
	if (theAmount.match(/^(\-\d{1})+(\d{1})*(\d{1})*$/)) {
		return true;
	}
	return false;
}

/*********************************************************************************
 * Validates the specified 'theAmount' for a positive amount value
 ********************************************************************************/
function isValidPositiveAmount(theAmount) {
	//Matches theAmount to the specified regular expression without the currency but with decimals
	//Valid values are: 1.23 or 23.45 or 998864846841.65 or 0.1
	if (theAmount.match(/^(\d{1})+(\.\d{1,2})$/)) {
		return true;
	}
	//Matches theAmount to the specified regular expression without the currency but with decimals
	//Valid values are: .2 or .45 
	if (theAmount.match(/^(\.\d{1,2})$/)) {
		return true;
	}
	//Matches theAmount to the specified regular expression without the currency without decimals
	//Valid values are: 1 or 23 or 998864846841
	if (theAmount.match(/^(\d{1})+(\d{1})*(\d{1})*$/)) {
		return true;
	}
	return false;
}

/*********************************************************************************
 * Validates the specified 'theAmount' for a positive amount value based on the
 * format for the specified 'currencyValues'
 * currencyValues: [groupSeparatorPOS][groupSeparator][decimalSeparator][precision]
 ********************************************************************************/
function isValidPositiveAmountForCurrency(theAmount, currencyValues) {
	var groupSeparatorPOS = currencyValues[0];
	var groupSeparator = currencyValues[1];
	var decimalSeparator = currencyValues[2];
	var precision = currencyValues[3];
	
	//If the result was true we don't need to continue with validation
	if (isValidPositiveAmount(theAmount)) {
		return true;
	}
	//Matches theAmount to the Regular Expression for the CurrencyFormat.
	//example:
	// groupSeparatorPOS = 3| groupSeparator = ,| decimalSeparator = .| precision = 2
	// which translates to a regular expression of: /^(\d{1,3})(\,\d{3})*(\.\d{2})$/g
	// and for this expression valid amounts are: 1.99 or 0.10 or 123.45 or 1,234.00 or 1,900,654,567,456.55
	dExp = new RegExp("^(\\d{1," + groupSeparatorPOS + "})(\\" + groupSeparator + "\\d{" + groupSeparatorPOS + "})*(\\" + decimalSeparator + "\\d{" + precision + "})$");
	if (theAmount.match(dExp)) {
		return true;
	}
	// Similar to the previous one, except it ignores the 'cents'
	// Valid amounts are: 1 or 0 or 1,234 or 1,900,654,567,456
	exp = new RegExp("^(\\d{1," + groupSeparatorPOS + "})(\\" + groupSeparator + "\\d{" + groupSeparatorPOS + "})*$");
	if (theAmount.match(exp)) {
		return true;
	}
	return false;
}

/*********************************************************************************
 * Validates the specified 'theAmount' for an amount value based on the
 * format for the specified 'currencyValues'
 * currencyValues: [groupSeparatorPOS][groupSeparator][decimalSeparator][precision]
 ********************************************************************************/
function isValidAmountForCurrency(theAmount, currencyValues) {
	var groupSeparatorPOS = currencyValues[0];
	var groupSeparator = currencyValues[1];
	var decimalSeparator = currencyValues[2];
	var precision = currencyValues[3];
	//If the result was true we don't need to continue with validation
	if (isValidPositiveAmountForCurrency(theAmount, currencyValues)) {
		return true;
	}
	//Matches theAmount to the Regular Expression for the CurrencyFormat.
	//example:
	// groupSeparatorPOS = 3| groupSeparator = ,| decimalSeparator = .| precision = 2
	// which translates to a regular expression of: /^(\d{1,3})(\,\d{3})*(\.\d{2})$/g
	// and for this expression valid amounts are: -1.99 or -0.10 or -123.45 or -1,234.00 or -1,900,654,567,456.55
	dExp = new RegExp("^(\\-\\d{1," + groupSeparatorPOS + "})(\\" + groupSeparator + "\\d{" + groupSeparatorPOS + "})*(\\" + decimalSeparator + "\\d{" + precision + "})$");
	if (theAmount.match(dExp)) {
		return true;
	}
	// Similar to the previous one, except it ignores the 'cents'
	// Valid amounts are: -1 or -0 or -1,234 or -1,900,654,567,456
	exp = new RegExp("^(\\-\\d{1," + groupSeparatorPOS + "})(\\" + groupSeparator + "\\d{" + groupSeparatorPOS + "})*$");
	if (theAmount.match(exp)) {
		return true;
	}
	return false;
}

/*********************************************************************************
 * Format Message for parameter localisation purposes - takes a String and Array 
 ********************************************************************************/
function format(message, params) {
	for (i=0; i < params.length; i++) {
		var search = "{" + i + "}";
		var index = message.indexOf(search);
		if (index != -1) {
			var pre = message.substring(0, index);
			var post = message.substring(index + search.length);
			message = pre.substring(0, index) + params[i] + post;
		}
	}
	return message;
}

// VALIDATE OPERATOR_CODE
function validate_operatorCode(channelIdentifier, operatorCodes){
	//opCodesArray = new Array('2782', '2783'); 
	var result = false;
	for(var i=0; i < opCodesArray.length;i++ ){
		if( channelIdentifier.indexOf(opCodesArray[i]) == 0 ) { 
		  result = true;
		  break;
		}
	}
   return result; 
}

// VALIDATE MANDATORY PHONECODE
function validate_mandatory_phone_code(phoneCode, phoneNumber){

   code = trim_string(phoneCode);
   number = trim_string(phoneNumber);

   if(code == "" && number != ""){
      return false;
   }

   return true;
}

// VALIDATE MANDATORY PHONENUMBER
function validate_mandatory_phone_number(phoneCode, phoneNumber){

   code = trim_string(phoneCode);
   number = trim_string(phoneNumber);

   if(code != "" && number == ""){
      return false;
   }

   return true;
}

   
// VALIDATE PHONE
function validate_phone(phoneCode, phoneNumber){
   code = trim_string(phoneCode);
   number = trim_string(phoneNumber);

   if(code == "" && number == ""){
      return true;
   }

   if(code == "" || number == ""){
      return false;
   }
   if( ! validate_phone_code(code)){
      return false;
   }
   if( ! validate_phone_number(number)){
      return false;
   }

   return true;
}
// VALIDATE PHONE CODE
function validate_phone_code(phoneCode){
   code = trim_string(phoneCode);

   if(code == ""){
      return true;
   }

	if( ! validate_numeric(code)){
      return false;
   }
	
	
   // Check that the code starts with a 0
   if(code.substring(0,1) != "0"){
      return false;
   }
   
	  
   // Check that the code length is a min of 2 and max of 10
   if(! validate_length(code, 2, 10)){
   	return false;
   }	

   return true;
}
// VALIDATE PHONE NUMBER
function validate_phone_number(phoneNumber){
   number = trim_string(phoneNumber);

   if(number == ""){
      return true;
   }

   if( ! validate_numeric(number)){
      return false;
   }

   // Check that the code length is a min of 2 and max of 10
   if(! validate_length(number, 2, 20)){
   	return false;
   }	

   return true;
}

// VALIDATE ADDRESS
function validate_address(addressText, addressCode)
{
   addr = trim_string(addressText);
   postalCode = trim_string(addressCode);
   if( (postalCode == "") && (addr == "") ){
      return true;
   }
   if( (postalCode == "") || (addr == "") ){
      return false;
   }
   return true;
}

// VALIDATE NUMERIC
function validate_numeric(number)
{
	i = 0;
	ch = "";

	while (i < number.length)
	{
		ch = number.charAt(i);
		if (ch < "0" || ch > "9")
		{
			return false;
		}

		i++;
	}

	return true;
}

//FOR CHECKING WHETHER A TXT_STRING CONTAINS A NUMBER
	function containsNumber(stringTxt) {
		i = 0;
		ch = "";
		while (i < stringTxt.length)	{
			ch = stringTxt.charAt(i);
			if (ch == "0" || ch == "1" ||
					ch == "2" || ch == "3" ||
					ch == "4" || ch == "5" ||
					ch == "6" || ch == "7" ||
					ch == "8" || ch == "9"){
				return true;
			}
			i++;
		}
		return false;
	}

// VALIDATE STRING - 'Dummy' method for use with F3 message data-type validation
function validate_string(string) 
{
	return true;
}

function validate_field(string) 
{
	i = 0;
	ch = "";
	while ( i < string.length) 
	{
		ch = string.charAt(i);
		if (ch == "'") {
			return false;
		}
		i++;
	}
	return true;
}


// Validate Amount
function validate_amount(number)	{
	i = 0;
	ch = "";
	decimalCounter = 0;
	periodCounter = 0;
	validateCents = false;

	//SM Robinson - 05-05-2003
	//remove first char if it is '-' to evaluate the number normally
	if (number.charAt(0) == "-") {
		//number = number.substring(1);
		return false; //remove this line if -ve amounts are allowed
	}

	while (i < number.length) {
		ch = number.charAt(i);
		if (validateCents){
				decimalCounter++;
		}
		if (ch < '0' || ch > '9') {
				if (ch != ".") {
					return false;
				} else {
					validateCents = true;
				}
				if(ch == "."){
					periodCounter++;
				}
				if(periodCounter > 1){
					return false;
				}
		}
		if(decimalCounter > 2){
			return false;
		}
		i++;
	}

	return true;
}

// Validate Percentage
function validate_percentage(number, decimalCount)
{
	i = 0;
	ch = "";
	decimalCounter =0;
	periodCounter = 0;
	validateCents = "No";

	//SM Robinson - Added 14-11-2000
	if (number < 0) {
	  return false;
	}

	
	while (i < number.length) 
	{
		ch = number.charAt(i);	

		if (validateCents == "Yes"){
		    decimalCounter++;
		}    
		if (ch < "0" || ch > "9"){
		    if(ch != "."){
			return false;
		    }
		    else {
		    	validateCents = "Yes";
		    }
		    if(ch == "."){
			periodCounter++;
		    }
         	    if(periodCounter > 1){
		        return false;
		    }    
		}
		if(decimalCounter > decimalCount){
		    return false;
		}    
		i++;
	}

	return true;
}


// TRIM STRING
function trim_string(instr)
{
   i = 0;
   ch = "";
   string = "";
	
   if (instr != ""){
      	
      while (i < instr.length){
         ch = instr.substring(i, i+1);	

         if (ch != " " && ch != "\n" && ch != "\r"){
            break;
         }

         i++;
      }
      string = instr.substring(i);				

      i = string.length;
      while (i > 0){
         ch = string.substring(i-1,i);	

         if (ch != " " && ch != "\n" && ch != "\r"){
            break;
         }

         i--;
      }
      string = string.substring(0, i);				
   }	

   return string;
}

// REMOVE SPACES
function remove_spaces(instr)
{
   i = 0;
   ch = "";
   string = "";
	
   if (instr != ""){
      i = 0;

      while (i < instr.length){
         ch = instr.substring(i,i+1);	

         if (ch != " "){
            string = string + ch;	
         }

         i++;
      }
   }	

   return string;
}

// TRIM THE LEADING AND TRAILING SPACES OF THE STRING - FWalters - Modified 14-3-2002
function trimString (str) {
  while (str.charAt(0) == ' ')
    str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
    str = str.substring(0, str.length - 1);
  return str;
}



// VALIDATE DATE - E Silver - Modified 20-09-2000
function validate_date(dateStr){
	dateString = dateStr;
	slashIndex = dateString.indexOf('/');
	day = dateString.substring(0, slashIndex);
	if( ! validate_numeric(day)){
		return false;
  }
	dateString = dateString.substring(slashIndex + 1);
	slashIndex = dateString.indexOf('/');
	month = dateString.substring(0, slashIndex) - 1;
	if( ! validate_numeric(dateString.substring(0, slashIndex))){
		return false;
	}
	dateString = dateString.substring(slashIndex + 1);
	slashIndex = dateString.indexOf('/');
	year = dateString;
	if(year.length != 4){
		return false;
	}
	dt = new Date(year, month, day);
	testYear = "1850";
	testDateValue = (new Date(testYear, month, day)).valueOf();
	if ((dt - testDateValue) <= 0) {
		return false;
	}
	if( month != dt.getMonth() ){
		//alert("month=" + month + ",getMonth()=" + dt.getMonth());
		return false;
	}else{
		return true;
	}
}
//VALIDATE TIME  Ronel - 17-09-2003
function isValidTime(timeStr) {
// Checks if time is in HH:MM:SS format. (24HH)

	var timePat = /^(\d{2}):(\d{2}):(\d{2})$/;
	var matchArray = timeStr.match(timePat);

	if (matchArray == null) {
		//alert("Time is not in a valid format.");
		return false;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[3];

	if (second=="") { second = null; }
	if (hour < 0  || hour > 23) {
		//alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
		return false;
	}

	if (minute<0 || minute > 59) {
		//alert ("Minute must be between 0 and 59.");
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		//alert ("Second must be between 0 and 59.");
		return false;
	}
	return true;
}

//  End -->


// VALIDATE CREDIT CARD EXPIRY DATE FORMAT- SM Robinson - Modified 14/02/2001
function validate_expiry_date_format(dateString){

	//check there is a '/' in the string:
	if (dateString.indexOf("/") < 0) {
		return false;
	}
	dateArray = dateString.split("/");
	//check that the length of each is correct
	for (i = 0; i < dateArray.length; i++) {
		if (dateArray[i].length != 2) {
			return false;
		}
		if (!validate_numeric(dateArray[i])) {
			return false;
		}
	}
	//check for leading zero on month, and remove it (parseInt recognises leading zeros as octal).
	if (dateArray[0].indexOf("0") == 0) {
		dateArray[0] = dateArray[0].substring(1);
	}	
	month = parseInt(dateArray[0]) - 1;
	year = parseInt(dateArray[1]);

	//Note: Javascript takes the month as and integer from 0 to 11
	if (month > 11 || month < 0) {
		return false;
	}
	if (year < 0) {
		return false;
	}

	fullYear = "20" + dateArray[1];
	date = new Date(fullYear, month, 1);
	if( month != date.getMonth() ){
		return false;
	}
	return true;
}
//*********************************************************************************************
// VALIDATE CREDIT CARD EXPIRY DATE - F Walters - Modified 28/08/2001
function validate_expiry_date(dateString){

	dataArray = dateString.split("/");	
   	expiryDate = new Date(dataArray[1],dataArray[0],1,1,1,1,1);
	expiryMonth = expiryDate.getMonth();
	expiryYear = expiryDate.getYear()+2000;
	
	// get date (today)	
	dateNow = new Date();
	monthNow = dateNow.getMonth()+1;
	yearNow = dateNow.getYear();
	
	//logic
	if(yearNow > expiryYear){
		return false;
	} 	
	if(yearNow == expiryYear){
		if(monthNow > expiryMonth){
			return false;
		}	
	}	
	return true;	
}
//*********************************************************************************************
// VALIDATE LENGTH
function validate_length(text, min, max)
{
   if(text.length < min || text.length > max){
      return false;
   }
   return true;
}


//*********************************************************************************************
// VALIDATE SHORTNAME
function validate_shortname(shortname)
{
	i = 0;
	ch = "";

	while (i < shortname.length)
	{
		ch = shortname.charAt(i);
		if (ch == "<" || ch == ">")
		{
			return false;
		}

		i++;
	}

	return true;
}

//*********************************************************************************************
// VALIDATE SHORTNAME & DESCRIPTION FOR INVALID CHARACTERS
// EB 11/08/2004
function validate_ForInvalidCharacters(text)
{
	var invalids = ";!@#$%^&*()_+|=\\/<>=?{}[].-,'\""
	for(i = 0; i < invalids.length; i++) {
		if(text.indexOf(invalids.charAt(i)) >= 0 ) {
			return false;
    }
	}
	return true;
}

function validate_ForEmailInvalidCharacters(text)
{
	var invalids = ";!#$%^&*()+|=\\/<>=?{}[],'\" "
	for(i = 0; i < invalids.length; i++) {
		if(text.indexOf(invalids.charAt(i)) >= 0 ) {
			return false;
    }
	}
	return true;
}

//Makes sure that the correct number of decimals appear after the decimal seperator
//wvdv 27/10/2003
function check_precision_length(number, currencyValues){
	var decimalSeparator = currencyValues[2];
	var precision = currencyValues[3];
	var decPos = number.indexOf(decimalSeparator);
	decPos++;
	var dec = number.substring(decPos);
	var preDec = number.substring(0,decPos);
	while(dec.length < precision){
		dec += '0';
	}
	return preDec+dec;
}

function getSystemName() {
	return "Pilot";
}
//*********************************************************************************************
// VALIDATE SOUTH AFRICAN ID NUMBER
// 

function isValidBirthDateForSaId(idNumber,dateOfBirth){
	
	var idYearOfBirth = parseInt(idNumber.substr(0,2));
	var idMonthOfBirth = parseInt(idNumber.substr(2,2));
	var idDayOfBirth = parseInt(idNumber.substr(4,2));
	
	var dobYear = parseInt(dateOfBirth.substr(8, 2));
	var dobMonth = parseInt(dateOfBirth.substr(3, 2));
	var dobDay = parseInt(dateOfBirth.substr(0, 2));

	if ( (idYearOfBirth!=dobYear) || 
			(idMonthOfBirth!=dobMonth) || 
			(idDayOfBirth!=dobDay) ){
		return false;
	}
	return true;
}

function isValidGenderForSaId(idNumber,gender){
var genderIndicator = parseInt(idNumber.substring(6,10));

	  if(gender == 1 && genderIndicator < 5000){ 
		  return false;     
	  }
	  if(gender == 2 && genderIndicator > 4999){    
	      return false;    
	  }
	  return true;
}

function isValidSaId(idNumber){

var idExcludingLastDigit = idNumber.substring(0, idNumber.length - 1);
var lastDigitOfID = idNumber.substring(idNumber.length - 1, idNumber.length);
var getOptionalDigit = parseInt(idNumber.substring(11,12));
var getCitizenshipDigit = parseInt(idNumber.substring(10,11));
var sumOfOddDigits = 0;

//Step 1
for(i = 1; i <= 12; i = i + 2){
    sumOfOddDigits = sumOfOddDigits + parseInt(idExcludingLastDigit.substring(i - 1, i));
}

// Step 2

var newString = "";
var evenDigitField = 0;
for(i = 2; i <= 12; i = i + 2){
      evenDigitField = idExcludingLastDigit.substring(i - 1, i);
      newString = newString.concat(evenDigitField);
}
var productOfNewString = (newString) * 2 ;

// Step 3

var productOfEvenDigitsAsString = productOfNewString.toString();
var sumOfproductOfEvenDigits = 0;

for(i = 0; i < productOfEvenDigitsAsString.length; ++i){
     sumOfproductOfEvenDigits = sumOfproductOfEvenDigits + parseInt(productOfEvenDigitsAsString.substring(i, i + 1));
} 
// Step 4
var sum = sumOfOddDigits + sumOfproductOfEvenDigits;
//Step 5

var sumAsString = sum.toString();
var lastDigit = sumAsString.substring(sumAsString.length - 1);
var checkDigit = (10 - parseInt(lastDigit));
var stringCheckBit = checkDigit.toString();

// If the result is 2 digits, the last digit is used to compare against the last number in the identity number. If the answer differs, the identity number is invalid
checkDigit = stringCheckBit.substring(stringCheckBit.length - 1);

	if((isNaN(idNumber))){
		return false;
	}
	if(idNumber.length !=13){
		return false;
	}
	
	if(checkDigit != lastDigitOfID){
		return false;
	}	
	if(getOptionalDigit != 8 && getOptionalDigit != 9){
		return false;
	}
	if(getCitizenshipDigit != 0 && getCitizenshipDigit != 1){
		return false;
	}
	
	// If the result is 2 digits, the last digit is used to compare against the last number in the identity number. If the answer differs, the identity number is invalid
	/*if(stringCheckBit.length == 2){
		alert(stringCheckBit.length);
      	checkDigit = stringCheckBit.substring(stringCheckBit.length - 1);						
		if(checkDigit != lastDigitOfID){
			return false;
       	}
	} */
		
    return true;
}

