
var errorsValidationMandatory = "{0} is mandatory.";
var errorsValidationInteger = "Invalid integer for {0}";
var errorsValidationDecimal = "Invalid number for {0}";
var errorsValidationRange = "Valid range for {0} is from {1} to {2}";
var errorsValidationTimeRange = "Valid time range is from {0} to {1}";
var errorsValidationTimestamp = "Invalid timestamp";
var errorsValidationDate = "Invalid date";
var errorsValidationTime = "Invalid time";
var errorsValidationTextArea = "Reach maximum range";
var errorsValidationEmail = "Invalid email format";
var errorsValidationMinimumSelection = "At least one record must be selected";
var errorsValidationGreaterThanZero = "{0} cannot be empty and must be greater than 0";
var alertDeleteRecord = "Are you sure you want to delete this record?";
var errorsDoesNotMatch = "{0} does not match {1}";
var errorsEitherOneMarketMustBeEntered = "Please select market from dropdown list or enter Other Market field"
var errorsExceedMaxPage = "This document only allows 2 pages of data. \n Please remove a few lines from {0} and try again."
var errorsExceedMaxRow = "The data you have keyed in has exceeded the page length.\n Please remove a few lines from {0} and try again."
var errorsExceedMaxTemplate = "Template can not be saved. Total templates saved has reached the limit"
var errorsCannotBeRepeated = "{0} cannot be repeated.";

var alertRejectRecord = "Are you sure you want to reject this application?";
var alertDeleteAllRejectedRecord = "Are you sure you want to delete all rejected applications";
var alertSaveChanges = "Save record?";



function isNetscape() {
  if (navigator.appName.indexOf('Netscape') != -1) {
    return true;
  }
  return false;
}

function formatText(text) {
  returnValue = text;
  for (i = 1; i < arguments.length; i++) {
    pattern = "\\{" + (i-1) + "\\}";
    returnValue = returnValue.replace(new RegExp(pattern), arguments[i]);
  }
  return returnValue;
}

function toNumeric(val, frac) {
  var decimalPoint = val.indexOf('.');
  if (decimalPoint == -1) {
    intPart = val;
    decimalPart = "";
  }
  else {
    intPart = val.substr(0, decimalPoint);
    decimalPart = val.substr(decimalPoint+1);
  }
  if (frac == 0) {
  	return intPart;
  }
  // Substract the decimal part based on the input fraction
  if (decimalPart.length > frac) {
    decimalPart = decimalPart.substr(0, frac);
  }
  // Place zero as decimal points
  for (var i = decimalPart.length; i < frac; i++) {
    decimalPart = decimalPart + "0";
  }
  return intPart + "." + decimalPart;
}

function isNotEmpty(obj, objName) {
	if (obj.value == '') {
		obj.focus();
		alert(formatText(errorsValidationMandatory, objName));
		return false;
	} else {
		return true;
	}
}

// Check for all required field in form.
function isAllNotEmpty(thisArray) {
	empty = false;
	errorMsg = "";
  	for (iArray=0; iArray < thisArray.length; iArray++) {
    	if ((thisArray[iArray][0]).value == "") {
	  		if (!empty) {
	  			empty = true;
	  		}
	  		errorMsg = errorMsg + formatText(errorsValidationMandatory, thisArray[iArray][1]) + "\n";
    	}
  	}
  	if (empty) {
	 	alert(errorMsg); 	
 	}
  	return !empty;
}

function isAllSelected(thisArray){

	empty = false;
	errorMsg = "";
  	for (iArray=0; iArray < thisArray.length; iArray++) {
    	if ((thisArray[iArray][0]).selectedIndex <= 0) {
	  		if (!empty) {
	  			empty = true;
	  		}
	  		errorMsg = errorMsg + formatText(errorsValidationMandatory, thisArray[iArray][1]) + "\n";
    	} 
  	}
  	if (empty) {
	 	alert(errorMsg); 	
 	}
  	return !empty;
}

/*
 * function: validate a decimal array field
 * parameter: thisArray - array where index
 *            	0 - element object,
 *            	1 - element name,
 *            	2 - minimum value, '' means ignore
 *            	3 - maximum value, '' means ignore
 *            	4 - length of field
 *            	5 - the number of decimal places
 * return: true if integer is within range and length; false otherwise
 */
function isAllDecimal(thisArray){
	empty = false;
	errorMsg = "";
  	for (iArray=0; iArray < thisArray.length; iArray++) {
	  	var s = "";
		var min = thisArray[iArray][2];
		var max = thisArray[iArray][3];
		var len = thisArray[iArray][4];
		var frac = thisArray[iArray][5];

		if ((thisArray[iArray][0]).value != "") {
   			if (isNaN((thisArray[iArray][0]).value)) {
   				if (!empty) {
	  				empty = true;
		  		}
      			errorMsg = errorMsg + formatText(errorsValidationDecimal, thisArray[iArray][1]) + "\n";
    		} else {
	    		limit = "";
    			for (iLen = 0; iLen < len-frac; iLen++) {
      				limit = limit + "9";
    			}
	    		if (frac > 0) {
    	  			limit = limit + ".";
      				for (iLen = 0; iLen < frac; iLen++) {
        				limit = limit + "9";
      				}
    			}
    			if (isNaN(parseFloat(min, 10))) min = parseFloat(limit, 10) * -1;
    			if (isNaN(parseFloat(max, 10))) max = parseFloat(limit, 10);
    			if ((parseFloat((thisArray[iArray][0]).value, 10) < min) || (parseFloat((thisArray[iArray][0]).value, 10) > max)) {
    				if (!empty) {
		  				empty = true;
			  		}	
    				errorMsg = errorMsg + formatText(errorsValidationRange, thisArray[iArray][1], min, max) + "\n";
    			} else {
    				(thisArray[iArray][0]).value = toNumeric((thisArray[iArray][0]).value, frac);
    			}	
  			}
		}  
  	}
  	if (empty) {
	 	alert(errorMsg); 	
 	}
  	return !empty;
}

/*
 * function: validate an integer field
 * parameter: obj - control
 *            min - minimum value, '' means ignore
 *            max - maximum value, '' means ignore
 *            len - length of field
 * return: true if integer is within range and length; false otherwise
 */
function validateInteger(obj, objName, min, max, len) {
  var maxInteger, minInteger;
  if (obj.value != "") {
    limit = "";
    for (i = 0; i < len; i++) {
      limit = limit + "9";
    }
    if (isNaN(parseInt(min, 10))) {
      min = parseInt(limit, 10) * -1;
    }
    if (isNaN(parseInt(max, 10))) {
      max = parseInt(limit, 10);
    }

    var p = new Number(obj.value);
    if (isNaN(p) == true) {
      if (!isNetscape()) {
      	obj.select();
      	obj.focus();
      }	 
      alert(formatText(errorsValidationInteger, objName));
      return false;
    } else if ((parseInt(obj.value, 10) < min) || (parseInt(obj.value, 10) > max)) {
      if (!isNetscape()) {
        obj.select();
        obj.focus();
      }	
      alert(formatText(errorsValidationRange, objName, min, max));
      return false;
    }
    obj.value = toNumeric(obj.value, 0);
  }
  return true;
}

/*
 * function: validate a decimal field
 * parameter: c - control
 *            min - minimum value, '' means ignore
 *            max - maximum value, '' means ignore
 *            len - length of field
 *            frac - the number of decimal places
 * return: true if integer is within range and length; false otherwise
 */
function validateDecimal(obj, objName, min, max, len, frac) {
  var s = "";
  if (obj.value != "") {
    if (isNaN(obj.value)) {
      obj.select();
      obj.focus();
      alert(formatText(errorsValidationDecimal, objName));
      return false;
    }
    limit = "";
    for (i = 0; i < len-frac; i++) {
      limit = limit + "9";
    }
    if (frac > 0) {
      limit = limit + ".";
      for (i = 0; i < frac; i++) {
        limit = limit + "9";
      }
    }
    if (isNaN(parseFloat(min, 10))) min = parseFloat(limit, 10) * -1;
    if (isNaN(parseFloat(max, 10))) max = parseFloat(limit, 10);
    if ((parseFloat(obj.value, 10) < min) || (parseFloat(obj.value, 10) > max)) {
      obj.select();
      obj.focus();
      alert(formatText(errorsValidationRange, objName, min, max));
      return false;
    }
    obj.value = toNumeric(obj.value, frac);
  }
  
  return true;
}

function isGreaterThanZero(formElement,message) {
	if (formElement.value <= 0) {
      	alert(formatText(errorsValidationGreaterThanZero, message));
      	formElement.focus();
      	return false;
    }
    else
    	return true;
}

function isSameOrGreaterThanZero(formElement,message) {
	if (formElement.value < 0) {
      	alert(formatText(errorsValidationGreaterThanZero, message));
      	formElement.focus();
      	return false;
    }
    else
    	return true;
}

function isAllGreaterThanZero(thisArray){
	empty = false;
	errorMsg = "";
  	for (iArray=0; iArray < thisArray.length; iArray++) {
    	if ((thisArray[iArray][0]).value <= 0) {
	  		if (!empty) {
	  			empty = true;
	  		}
	  		errorMsg = errorMsg + formatText(errorsValidationGreaterThanZero, thisArray[iArray][1]) + "\n";
    	} 
  	}
  	if (empty) {
	 	alert(errorMsg); 	
 	}
  	return !empty;
}

function mustSelect(formElement,message){
	
	if(formElement.selectedIndex <= 0){
		errorMsg = formatText(errorsValidationMandatory, message);
		alert(errorMsg);
		formElement.focus();
		return false;
	}
	else
		return true;
}

function checkRadio(formElement,message){
	var count;
	var flag;
	flag = 0;
	for (count=0; count < 2; count++){
   		if(formElement[count].checked == true){
       		flag = 1;
			return true;
       	}
	}
    	
	if (flag == 0){	
       	alert(message);   
		formElement[0].focus();     	
       	return false;
   	} 
}

function checkFormat(formElement, format, message) {
	found = formElement.value.match(format);
	if (found != null) {	
		alert(message);
		formElement.focus();
		return false;
	}
	else 
		return true;
} 		
	
function isNumeric(formElement,message){
	if (!checkFormat(formElement, /[^0-9]/, message))
		return false;
	else if (isNaN(formElement.value)) {
		alert(message);
		formElement.focus();
		return false;
	}	
	else 
		return true;
}

function isEmail(formElement){
	var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
	var matchArray = formElement.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
//        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailStr)){
	if (matchArray == null) {        
		alert(errorsValidationEmail);
		formElement.focus();
		return false;
	} else
		return true;
}

function isMinimumCheck(formElement,minimum){
	count = 0;
	if (formElement.length > 1) {
		for (i = 0; i < formElement.length; i++) {
			if(formElement[i].checked == true) {
				count++;
			}	
		}
	} else {
		if (formElement.checked == true) {
			count++;
		}
	}	
	if (count < minimum) {
		alert(errorsValidationMinimumSelection);
		return false;
	} else
		return true;
}

var splitIndex = 0;
var splitArray = new Array();

function textareaKeys(formElement, maxlimit, maxrowlimit) {
  if (formElement.value.length > maxlimit) { // if too long, trim it
    formElement.value = formElement.value.substring(0, maxlimit);
    return false;		
  } else if (maxrowlimit > 0) {
  	split(formElement.value, '\n');
  	oldSplitIndex = splitIndex;
    while (splitIndex > maxrowlimit) {
		formElement.value = formElement.value.substring(0, formElement.value.length - 3);
		split(formElement.value, '\n');
    }
    
    if (oldSplitIndex > maxrowlimit) {
    	return false;
    }
  }  
  return true;
}


function splits(string,text) {
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return;
    if (i == -1) {
        splitArray[splitIndex++] = string;
        return;
    }
    splitArray[splitIndex++] = string.substring(0,i);
    if (i+txtLength < strLength)
        splits(string.substring(i+txtLength,strLength),text);
    return;
}

function split(string,text) {
    splitIndex = 0;
    splits(string,text);
}

function confirmDelete() {
  if (confirm(alertDeleteRecord)) {
	  return true;
  }
  else {
      return false;
  }
}

function confirmReject() {
  if (confirm(alertRejectRecord)) {
	  return true;
  }
  else {
      return false;
  }
}

function confirmDeleteAllRejectedApp() {
  if (confirm(alertDeleteAllRejectedRecord)) {
	  return true;
  }
  else {
      return false;
  }
}

function confirmSave() {
  if (confirm(alertSaveChanges)) {
	  return true;
  }
  else {
      return false;
  }
}

function MatchingValidation(param1, param2, msg1, msg2) {
	
	if (param1.value != param2.value)	{
		alert(formatText(errorsDoesNotMatch, msg1, msg2));
		return false;
	}
	else {
		return true;
	}
}

function getTextareaRow(formElement, oneRowLimit) {
	trimBlankLine(formElement);
	split(formElement.value, '\n');
  	num = splitIndex;	
  	for (var i = 0; i < splitIndex; i++) {
		while (splitArray[i].length > oneRowLimit) {
			splitArray[i] = splitArray[i].substring(oneRowLimit, splitArray[i].length);
			num = num + 1;
		}  		
    }
    return num;
}

function trimBlankLine(formElement) {
	var theEnd = formElement.value.substring(formElement.value.length - 2, formElement.value.length - 1);
	if (theEnd == '\r') {
		while(theEnd == '\r') {
			formElement.value = formElement.value.substring(0, formElement.value.length - 2);
			theEnd = formElement.value.substring(formElement.value.length - 2, formElement.value.length - 1);
		}	
	}
	return true;
}