// JavaScript Document
// These functions check if data entered in the fields of a form are in acceptable form.

var fieldColorOriginal = '#FFFFFF';
var fieldColorError = '#EBFFFF';
var ALPH = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
var NUM = "0123456789 ";
var ALPH_NUM = ALPH + NUM;
var NUM_H = NUM + "-";
var NUM_S = NUM + " ";
var NUM_P = NUM + ".";
var NUM_HS = NUM + "- ";
var NUM_TIME = NUM + ":.";
var DATE = NUM + "/";
var NUM_ID = ALPH + NUM + "- ";
var NAME = "!@#$%^&*()_+=/|[]{};:\?<>`~\\\"";
var STREET = "!@$%^&*()_+=/|[]{};:\?<>`~\\\"";
var SPECIAL_CHAR = "!@#$%^&*()_+=/|[]{};:\'?.,<>`~\\\" ";
var EMAIL = ALPH + NUM + ".@-_";
var FILE_NAME = ALPH + NUM + "-_:. /\\()' ";
var FILE_DIR = "\"<>\'|/*?";
var TEXT = "\\\"<>";
var NAME2 = ALPH + NUM + "' .-,()";
var STREET2 = ALPH + NUM + "#'.,- ";
var USERNAME = ALPH + NUM;

// Check numeric data. Return false if data contains any non-numeric characters.
function isDataValid(fieldList, charListName){	
	var invalidFields = new Array() ;	
	var itemCount = 0;
	var charList = getCharList(charListName);
	
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){
		var val = getValue(fieldList[i]);
		
		if (!includesValidChar(val, charList)){
			invalidFields[itemCount] = fieldList[i] ;
			itemCount = itemCount + 1 ;
		}
	}

	if (invalidFields.length > 0){			
		paintFieldColor(invalidFields, fieldColorError) ;
		return false ;	
	}
	return true ;
}

// Get a char list for a given list name.
function getCharList(name){
	if(name == "NUM") return NUM;
	if(name == "NUM_H") return NUM_H;
	if(name == "NUM_S") return NUM_S
	if(name == "NUM_P") return NUM_P
	if(name == "NUM_HS") return NUM_HS;
	if(name == "NUM_ID") return NUM_ID;
	if(name == "NUM_TIME") return NUM_TIME;
	if(name == "ALPH_NUM") return ALPH_NUM;
	if(name == "DATE") return DATE;
	if(name == "NAME") return NAME;
	if(name == "STREET") return STREET;
	if(name == "ALPH") return ALPH;
	if(name == "SPECIAL_CHAR") return SPECIAL_CHAR;
	if(name == "EMAIL") return EMAIL;
	if(name == "FILE_NAME") return FILE_NAME;
	if(name == "FILE_DIR") return FILE_DIR;
	if(name == "TEXT") return TEXT;
	if(name == "NAME2") return NAME2;
	if(name == "STREET2") return STREET2;
	if(name == "USERNAME") return USERNAME;
}

// Check blank fields. Return false if there're one or more empty fields.
function checkRequiredFields (fieldList){	
	var invalidFields = new Array() ;
	var itemCount = 0;	
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){
		var val = getValue(fieldList[i]) ;

		// Check if field has no value		
		if (val == null || val.length == 0 || val == "0" || val == "AllFiltersOff"){	
			invalidFields[itemCount] = fieldList[i] ;	
			itemCount = itemCount + 1 ;	
		}
	}	
	if (invalidFields.length > 0){			
		paintFieldColor(invalidFields, fieldColorError) ;	
		return false ;	
	}	
	return true ;
}

// Check whitespaces. Return false if a field contains only white spaces.
function checkWhitespace (fieldList){	
	var invalidFields = new Array() ;	
	var itemCount = 0;		
	var whatspace = " " ;		
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){
		var whiteSpaceCount = 0 ;			
		var data = getValue(fieldList[i]);	
		
		for (pos=0; pos<data.length; pos++){			
			var c = data.charAt(pos);				
			if (whatspace.indexOf(c) == 0) {				
				whiteSpaceCount = whiteSpaceCount + 1 ;			
			}
		}		
		if (data.length > 0){		
			if (data.length == whiteSpaceCount){
				invalidFields[itemCount] = fieldList[i] ;
				itemCount = itemCount + 1 ;			
			}
		}		
	}
	
	if (invalidFields.length > 0){	
		paintFieldColor(invalidFields, fieldColorError) ;
		return false ;	
	}
	return true ;
}

// Check email formatting. Return false if incorrect.
function checkEmailFormat(fieldList){ 		
	var invalidFields = new Array() ;	
	var itemCount = 0;		
	paintFieldColor(fieldList, fieldColorOriginal);	
	for (i=0; i<fieldList.length; i++){		
		var val = getValue(fieldList[i]);
	
		if (!isEmail(val)){	
			invalidFields[itemCount] = fieldList[i] ;	
			itemCount++;	
		}	
	}
	
	if(invalidFields.length > 0){	
		paintFieldColor(invalidFields, fieldColorError) ;
		return false ;	
	}
	return true ;
}

// Check format of email address
function isEmail(address){    
	// Email address must contain at least one character before at sign(@).
    	var i = 1;
    	var sLength = address.length;	
	var charList = getCharList("EMAIL");

	// Check if all the characters are 1 byte characters.
	for(var e=0; e < sLength; e++){
		if(address.charAt(e).length > 1) return false;
	}

    	// look for special characters except dot(.), underscore(_) and at mark (@)
    	if(!includesValidChar(address, charList)) return false;	

	if(countOccurenceOfChar(address, '@') > 1) return false;	

    	// look for at mark (@)
    	while ((i < sLength) && (address.charAt(i) != "@")) i++;    	

    	if ((i >= sLength) || (address.charAt(i) != "@")) return false;
    	else i += 2;    

    	// look for dot (.)
    	while ((i < sLength) && (address.charAt(i) != ".")) i++;    

	// there must be at least one character after the dot (.)
    	if ((i >= sLength - 2) || (address.charAt(i) != ".")) return false;
	else return true;	
}

// Check format of number incl. minimum length. Return false if incorrect.
function checkNumberFormat(fieldList, charListName, minLength){
	var invalidFields = new Array();
	var itemCount = 0;	
	var charList = getCharList(charListName);
	
	paintFieldColor(fieldList, fieldColorOriginal);	

	for (i=0; i < fieldList.length; i++){
		var val = getValue(fieldList[i]);

		// First check if the number has at least 3 digits.	
		if(val.length >= minLength){
			// Then check if the number contains valid numbers.	
			if(!includesValidChar(val, charList)){
				invalidFields[itemCount] = fieldList[i];
				itemCount++;		
			}			
		}else{
			invalidFields[itemCount] = fieldList[i];	
			itemCount++;
		}							
	}
		
	if(invalidFields.length > 0){				
		paintFieldColor(invalidFields, fieldColorError) ;
		return false ;
	}			
	return true ;
}

// Check numeric data. Return false if data contains any non-numeric characters.
function checkNumericData (fieldList, charListName){	
	var invalidFields = new Array() ;	
	var itemCount = 0;	
	var charList = getCharList(charListName); 
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){	
		var val = getValue(fieldList[i]);
		
		if (!includesValidChar(val, charList)){		
			invalidFields[itemCount] = fieldList[i] ;
			itemCount = itemCount + 1 ;	
		}	
	}

	if (invalidFields.length > 0){			
		paintFieldColor(invalidFields, fieldColorError) ;
		return false ;	
	}
	return true ;
}

// Check alphabetic data. Return false if data contains any illegal special characters.
function checkAlphabetData (fieldList, charListName){	
	var invalidFields = new Array() ;	
	var itemCount = 0;
	var charList = getCharList(charListName);
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){	
		var val = getValue(fieldList[i]);	
					
		if (includesInvalidChar(val, charList) || includesNumeric(val)){
			invalidFields[itemCount] = fieldList[i] ;
			itemCount = itemCount + 1 ;
		}	
	}
	
	if (invalidFields.length > 0){		
		paintFieldColor(invalidFields, fieldColorError) ;	
		return false ;	
	}		
	
	return true ;
}

// Check if a file name contains any illegal characters.
function isLeagalFileName(fName){	
	
	var i = 0 ;
	var charList = getCharList("FILE_NAME");
	
	for (i = 0; i < fName.length; i++){		
		var cha = fName.charAt(i);	
		if (charList.indexOf(cha) == -1){
			return false;			
			break ;
		}	
	}	
	return true;
}

// Check if a file path is valid.
function isLeagalFilePath(dirPath){	
	
	var i = 0 ;
	var charList = getCharList("FILE_DIR");
	
	for (i = 0; i < dirPath.length; i++){		
		var cha = dirPath.charAt(i);	
		if (charList.indexOf(cha) >= 0){
			return false;			
			break ;
		}	
	}	
	return true;
}

// Check if values are under given max number
function isUnderMaxNum(fieldList, max){

	var result = true;
	var itemCount = 0;
	var invalidFields = new Array() ;
	
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){
		var val = getValue(fieldList[i]);

		if (val > max){			
			invalidFields[itemCount] = fieldList[i] ;						
			itemCount ++;					
		}
	}

	if (invalidFields.length > 0){	
		
		paintFieldColor(invalidFields, fieldColorError) ;			
		return false ;				
	}	
	return result;
}

	// Check if values are above given min number
function isAboveMinNum(fieldList, min){

	var result = true;
	var itemCount = 0;
	var invalidFields = new Array() ;
	
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){
		var val = getValue(fieldList[i]);

		if (val < min){			
			invalidFields[itemCount] = fieldList[i] ;						
			itemCount ++;					
		}
	}

	if (invalidFields.length > 0){			
		paintFieldColor(invalidFields, fieldColorError) ;			
		return false ;				
	}	
	return result;
}

// Check if the credit card expiration date is valid
function checkCreditCardExpDate(field, max){

	var result = true;	
	var val = getValue(field);
	var len = val.length;
	var month = "";
	var year = "";
	var today = new Date();

	paintFieldColor(new Array(field), fieldColorOriginal);

	if(len > 5) result = false;

	month = val.substr(0,2);
	if(!isNumber(month)) result = false;

	year = val.substr(3,5);
	if(!isNumber(year)) result = false;

	if(month > 12 || month < 1){
	 	result = false;
	}
	
	year = new Number(year);
	currentYear = new Number(today.getYear().toString().substr(2,4));
	maxYear = today.getFullYear() + max;
	maxYear = new Number(maxYear.toString().substr(2,4)); 

	if(year > maxYear || year < currentYear) result = false;

	if(!result) paintFieldColor(new Array(field), fieldColorError) ;
	return result;

}

function isNumber(val){
	
	var charList = getCharList("NUM");

	if(val == "") return false;
		
	var i = 0 ;
	for (i = 0; i < val.length; i++){
		var cha = val.charAt(i);

		if (charList.indexOf(cha) == -1){
			return false ;
			break ;
		}			
	}
	return true;
}

function isAlphabet(val){
	
	var charList = getCharList("ALPH");

	if(val == "") return false;
		
	var i = 0 ;
	for (i = 0; i < val.length; i++){
		var cha = val.charAt(i);

		if (charList.indexOf(cha) == -1){
			return false ;
			break ;
		}			
	}
	return true;
}

// Check alphabetic data. Return false if data contains any illegal special characters.
function checkAlphaNumericData(fieldList, charListName){
	var invalidFields = new Array() ;	var itemCount = 0;
	var charList = getCharList(charListName);
	paintFieldColor(fieldList, fieldColorOriginal);
	for (i=0; i<fieldList.length; i++){	
		var val = getValue(fieldList[i]);	
					
		if (includesInvalidChar(val, charList)){						
			invalidFields[itemCount] = fieldList[i] ;						
			itemCount = itemCount + 1 ;					
		}	
	}
	
	if (invalidFields.length > 0){			
		paintFieldColor(invalidFields, fieldColorError) ;		
		return false ;	
	}

	return true ;
}

// Compare start & end dates. Return false if the start date is later than the end date	
function compareStartEndDates(date1Field, date2Field){

	startDate = new Date();
	endDate = new Date();

	if(date1Field != "") startDate = new Date(getElement(date1Field).value);
	if(date2Field != "") endDate = new Date(getElement(date2Field).value);
	
	if(startDate >= endDate) return false;
	
	return true;
}

// Check date format.
function checkDate(fieldList, dFormat){	

	var invalidFields = new Array() ;
	var itemCount = 0;	

	paintFieldColor(fieldList, fieldColorOriginal);

	for (i=0; i<fieldList.length; i++){	
		var val = getValue(fieldList[i]);

		if (!isDate(val, dFormat)){		
			invalidFields[itemCount] = fieldList[i] ;
			itemCount = itemCount + 1 ;	
		}	
	}

	if (invalidFields.length > 0){			
		paintFieldColor(invalidFields, fieldColorError) ;
		return false ;	
	}
	return true ;
}


// Compare two dates passed in as string. Return false if date 1 is the same as or later than date 2.
function compareDatesAsString(d1, d2){
	
	date1 = new Date(d1);
	date2 = new Date(d2);
	
	if(date1 >= date2) return false;
	
	return true;
}

// Compare start date and current date. Return false if the start date is earlier than the current date	
function compareStartCurrentDates(date1){
	startDate = "";
	currentDate = new Date();

	if(date1 != "") startDate = new Date(document.getElementById(date1).value);

	if(currentDate > startDate) return false;
	
	return true;
}

// Count the occurenece of a char in a string.
function countOccurenceOfChar(element, cha){	
	var i = 0;
	var occurence = 0;

	while (i < element.length){
		if (element.charAt(i) == cha) occurence++;
		i++;
	}
	return occurence;		
}

// Returns true if the string passed in includes numeric characters.
function includesNumeric(element){	
	var i = 0;
	var charList = getCharList("NUM");

		for (i = 0; i < element.length; i++){
		var cha = element.charAt(i);
		if (charList.indexOf(cha) >= 0){
			return true ;
			break ;
		}		
	}
	return false;
}

// Returns true if the string passed in only includes valid characters.
function includesValidChar(element, charList){	
	var i = 0 ;

	for (i = 0; i < element.length; i++){
		var cha = element.charAt(i);

	if (charList.indexOf(cha) == -1){		

			return false ;
			break ;
		}		
	}
	return true;
}

// Returns true if the string passed in includes invalid characters.
function includesInvalidChar(element, charList){
	var i = 0 ;
	for (i = 0; i < element.length; i++){		
		var cha = element.charAt(i);
	
		if (charList.indexOf(cha) >= 0){
			return true ;			
			break ;
		}	
	}
	return false;
}

// Replace special characters with 7-BIT ASCII characters. This method can accept 
// only one field name at a time.
function replaceSpecialCharByCode(val){
	var output = "";

	for (i = 0; i < val.length; i++){	
		var c = val.charAt(i);
		output = output + convertSpecialCharToCode(c);		
	}		
	return output;
}


// Replace 7-BIT ASCII codes to special characters. This method can accept 
// only one field name at a time.
function replaceCodeBySpecialChar(val){
	var output = "";	
	var valLength = val.length;


	for (i = 0; i < valLength; i++){

		var cha = val.charAt(i);		
		var code = ""; 	
		if (cha == "&"){
			while(i < valLength & val.charAt(i) != ';'){
				code = code + val.charAt(i);					
				i++;	
			}
			if (i <= valLength && val.charAt(i) == ';'){				
				code = code + val.charAt(i);				
			}		
			output = output + convertCodeToSpecialChar(code);			
		} else {
			output = output + cha;					
		}

	}
	return output;
}

// Convert special characters to 7-BIT Printable ASCII Characters.
function convertSpecialCharToCode(cha){		
	if (cha == '!') return "&#33;";
	if (cha == '@') return "&#64;";
	if (cha == '#') return "&#35;";
	if (cha == '$') return "&#36;";
	if (cha == '%') return "&#37;"
	if (cha == '^') return "&#94;";
	if (cha == '&') return "&#38;";
	if (cha == '*') return "&#42;";
	if (cha == '(') return "&#40;";
	if (cha == ')') return "&#41;";
	if (cha == '_') return "&#95;";
	if (cha == '+') return "&#43;";
	if (cha == '-') return "&#45;";
	if (cha == '=') return "&#61;";
	if (cha == '/') return "&#47;";
	if (cha == '|') return "&#124;";
	if (cha == '[') return "&#91;";
	if (cha == ']') return "&#93;";
	if (cha == '{') return "&#123;";
	if (cha == '}') return "&#125;";
	if (cha == ';') return "&#59;";
	if (cha == ':') return "&#58;";
	if (cha == '\'') return "&#39;";
	if (cha == '?') return "&#63;";
	if (cha == '.') return "&#46;";
	if (cha == ',') return "&#44;";
	if (cha == '<') return "&#60;";
	if (cha == '>') return "&#62;";
	if (cha == '`') return "&#96;";
	if (cha == '~') return "&#126;";
	if (cha == '\\') return "&#92;";
	if (cha == '"') return "&#34;";
	else return cha;
}

// Convert 7-BIT Printable ASCII characters to special characters.
function convertCodeToSpecialChar(code){		
	if (code == "&#33;") return '!';
	if (code == "&#64;") return '@';
	if (code == "&#35;") return '#';
	if (code == "&#36;") return '$';
	if (code == "&#37;") return '%';
	if (code == "&#94;") return '^';
	if (code == "&#38;") return '&';
	if (code == "&#42;") return '*';
	if (code == "&#40;") return '(';
	if (code == "&#41;") return ')';
	if (code == "&#95;") return '_';
	if (code == "&#43;") return '+';
	if (code == "&#45;") return '-';
	if (code == "&#61;") return '=';
	if (code == "&#47;") return '/';
	if (code == "&#124;") return '|';
	if (code == "&#91;") return '[';
	if (code == "&#93;") return ']';
	if (code == "&#123;") return '{';
	if (code == "&#125;") return '}';
	if (code == "&#59;") return ';';
	if (code == "&#58;") return ':';
	if (code == "&#39;") return '\'';
	if (code == "&#63;") return '?';
	if (code == "&#46;") return '.';
	if (code == "&#44;") return ',';
	if (code == "&#60;") return '<';
	if (code == "&#62;") return '>';
	if (code == "&#96;") return '`';
	if (code == "&#126;") return '~';
	if (code == "&#92;") return '\\';
	if (code == "&#34;") return '\"';
	else return code;
}

// Get entered data from a field.
function getValue(element){
	val = "-1";
	if(getFieldElement(element)){
		val = getFieldElement(element).value;
	}
	return val;
}

// Set background colour property of a field
function setFieldColor (element, color){
	if(getFieldElement(element)){
		getFieldElement(element).style.background=color; 
	}
}

// Colour background of fields that have error.
function paintFieldColor (element, color){
	for (i=0; i<element.length; i++){			
		setFieldColor(element[i], color) ;	
	}	
	setFocus(element[0]) ;
}

// Set cursor focus on a field.
function setFocus (fieldName){
	if(getFieldElement(fieldName)){
		field = getFieldElement(fieldName);
		field.focus();
	}
}

// Get field element
function getFieldElement(fieldName){
	fieldElement = "";
	if(document.getElementById(fieldName)){
		fieldElement = document.getElementById(fieldName);
	}
	return fieldElement;
}

// Jumpt to a section of the page.
function jumpToField(fieldName){
	window.location = "#" + fieldName;
}

// Find left position of an element on the page.
function findPosX(obj){
    	var curleft = 0;
    	if(obj.offsetParent)
        	while(1) 
        	{
	        curleft += obj.offsetLeft;
        	if(!obj.offsetParent)
	        break;
        	obj = obj.offsetParent;
        }
	else if(obj.x)
        curleft += obj.x;
    	return curleft;
}

// Find top position of an element on the page.
function findPosY(obj){
    	var curtop = 0;
    	if(obj.offsetParent)
        	while(1){
          		curtop += obj.offsetTop;
          		if(!obj.offsetParent)
            		break;
          		obj = obj.offsetParent;
       	}
	else if(obj.y) curtop += obj.y;
    	return curtop;
}

// Set the color of background of fields with error
function setFieldColorError(color){	
	if(color != "") fieldColorError = color;
}

// Show error message. Always return false.
function showErrorMsg(msg){	
	if(msg == ""){
		msg = "Error occurred.";
	}else{	
		alert(msg);
	}	
	return false;
}