// JavaScript Document for forms validations

/*******************************************

shira,
* create a string check for name type fields
* implement returnToField()

********************************************/

/* called from a JS function, commits focus and select to requested field and returns false */
function returnToField(currField){
	currField.focus();
	try{
		currField.select();				// this is in 'try' for when refers to select objects
	}catch(e){}
	return false;
}

/* checks validation of a requested string using a regular expression object */
function checkInvalidChar(string,reg){
	if(!string.match(reg)){
		return true;
	}
	return false;
}

/* validats number fierlds */
function isNumber(fieldVal, minVal, maxVal, decLength){
	// Returns one of the following values:
	// 0 = all ok
	// 1 = invalid characters
	// 2 = not in range - too little
	// 3 = not in range - too much
	// 4 = to many decimal points
	// 5 = decimal value to long
	if(minVal > -1){														// if minus allowed
		if(decLength == 0){													// if no decimal allowed
			if(checkInvalidChar(fieldVal,"^[0-9]+$")){
				return 1;
			}
		}else{																// if decimal allowed
			if(checkInvalidChar(fieldVal,"^[0-9.]+$")){
				return 1;
			}
		}
	}else{																	// if no minus allowed
		if(decLength == 0){													// if no decimal allowed
			if(checkInvalidChar(fieldVal,"^[0-9-]+$")){
				return 1;
			}
		}else{																// if decimal allowed
			if(checkInvalidChar(fieldVal,"^[0-9.-]+$")){
				return 1;
			}
		}
	}
	if((minVal != null) && (maxVal != null)){					// if both minimum and maximum defined
		if(fieldVal < minVal){
			return 2;
		}else if(fieldVal > maxVal){
			return 3;
		}
	}else if((minVal != null) && (maxVal == null)){				// if only minimum defined
		if(fieldVal < minVal){
			return 2;
		}
	}else if((minVal == null) && (maxVal != null)){				// if only maximum defined
		if(fieldVal > maxVal){
			return 3;
		}
	}
	if(decLength != 0){
		regEx = /./i;
		var hasDec = fieldVal.search(regEx);
		if(hasDec != -1){										// if page called with specified anchor
			var splitNumber = fieldVal.split(".");
			if(splitNumber.length > 2){							// if more then 1 decimal point
				return 4;
			}else if(splitNumber[1] != undefined){
				if(splitNumber[1].length > decLength){			// if too many digits after deciaml points
					return 5;
				}
			}
		}
	}
	return 0;
}

/* checks validation of an email string using a regular expression object */
function checkEmail(emailValue){
	pattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)";
	emailValue = trim(emailValue);											// trim() is the next function, not a method
	if(-1 == emailValue.search(pattern)){
		return false;
	}else{
		return true;
	}
}

/* changes the string to the correct phone number format and returns error code when number is invalid */
/* returns: */
/* -1 - bad number. check dialing code. */
/* -2 - bad number. not enough digits. */
/* newPhoneStr - if all ok */
function isPhone(phoneStr){ 
	var newPhoneStr = '';													// will hold "clean"number
	for(var c=0; c<phoneStr.length; c++){
		if(/^\d+$/.test(phoneStr.substr(c,1))){								// if current character is a digit
			newPhoneStr += phoneStr.substr(c,1);							// "passes" the numebr to the new var
		}
	}
	if((newPhoneStr.substr(0,1) != '1') && (newPhoneStr.substr(0,1) != '0')){	// if first digit is not 0 or 1
		return -1;
	}
	if(newPhoneStr.substr(0,1) == '0'){	
		if((newPhoneStr.substr(1,1) == '1')){								// if 2nd number is 1
			return -1;
		}
		switch(newPhoneStr.substr(1,1)){
			case '2': case '3': case '4': case '8': case '9' :case '':	
				if(newPhoneStr.length < 9){									// count at least 9 characters
					return -2;
				}
				newPhoneStr = newPhoneStr.substr(0,2) + '-' + newPhoneStr.substr(2,newPhoneStr.length);	//add hyphen after 2 digits
			break;
			case '5':	
				switch(newPhoneStr.substr(2,1)){
					case '1':case '3':case '5':case '6':case '8':case '9':	// check if not: 050 052 054 057
						return -1;
					break;
					case '0':case '2':case '4':case '7':
						if(newPhoneStr.length < 10){						// count at least 10 characters
							return -2;
						}
					break;
				}
				newPhoneStr = newPhoneStr.substr(0,3)+'-'+newPhoneStr.substr(3,newPhoneStr.length);	//add hyphen after 3 digits
			break;
			case '7':	
				switch(newPhoneStr.substr(2,1)){
					case '0':case '1':case '3':case '5':case '6':case '8':case '9':	// check if not: 072 077 074
						return -1;
					break;
					case '2':case '7':case '4':case '':
						if(newPhoneStr.length < 10){						// count at least 10 characters
							return -2;
						}
					break;
				}
				newPhoneStr = newPhoneStr.substr(0,3) + '-' + newPhoneStr.substr(3,newPhoneStr.length);	//add hyphen after 3 digits
			break;
			case '0':
											// if abroad - dont let
				return -1;
			break;
		}
	}else{		
													// if first digit is 1
		if((newPhoneStr.substr(1,3)!='700')&&(newPhoneStr.substr(1,3)!='800')){	// if doesn't fit toll-free code
			return -1;
		}
		if(newPhoneStr.length < 10){										// count at least 9 characters
			return -1;
		}
		newPhoneStr = newPhoneStr.substr(0,4) + '-' + newPhoneStr.substr(4,newPhoneStr.length);	//add hyphen after 4 digits
	}
	return newPhoneStr;
}

function trim(str){
	return str.replace(/^\s+/,'');
}

/* email validator - checks if the email address is valid, displays error and retunrs boolean value */
function validateEmail(emailStr){
	/* Tells the rest of the function whether or not to verify that the address ends 
	in a two-letter country or well-known TLD. 1 means check it, 0 means don't. */
	var checkTLD = 1;
	/* List of known TLDs that an e-mail address must end with. */
	var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	/* Pattern used to check if the entered e-mail address fits the user@domain format. 
	It also is used to separate the username from the domain. */
	var emailPat = /^(.+)@(.+)$/;
	/* String pattern for matching all special characters. We don't want to allow special 
	characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	/* String range of characters allowed in a username or domainname. It really states which chars aren't allowed.*/
	var validChars = "\[^\\s" + specialChars + "\]";
	/* String pattern, applies if the "user" is a quoted string (in which case, there are no rules about which characters 
	are allowed and which aren't; anything goes). E.g. "jiminy cricket"@disney.com is a legal e-mail address. */
	var quotedUser = "(\"[^\"]*\")";
	/* Pattern applies for domains that are IPs, rather than symbolic names. E.g. joe@[123.124.233.4] is a legal e-mail address. 
	NOTE: The square brackets are required. */
	var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	/* String represents an atom (basically a series of non-special characters.) */
	var atom = validChars + '+';
	/* String represents one word in the typical username. For example, in john.doe@somewhere.com, 
	john and doe are words. Basically, a word is either an atom or quoted string. */
	var word = "(" + atom + "|" + quotedUser + ")";
	/* Pattern describes the structure of the user */
	var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
	/* Pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */
	var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Start checking if the supplied address is valid: */
	
	/* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */
	var matchArray = emailStr.match(emailPat);
	if(matchArray == null){
		/* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */
		alertMsg(5, '?? ???????: @ ??????');							// Email address seems incorrect (check @ and .'s)
		return false;
	}
	var user = matchArray[1];
	var domain = matchArray[2];
	/* Check that only basic ASCII characters are in the strings (0-127). */
	for(i=0; i< user.length; i++){
		if(user.charCodeAt(i) > 127){
			alertMsg(5, '?? ?? ??????');								// Ths email's username contains invalid characters
			return false;
		}
	}
	for(i=0; i< domain.length; i++){
		if(domain.charCodeAt(i) > 127){
			alertMsg(5, '?? ???? ??????');								// Ths email's domain name contains invalid characters
			return false;
		}
	}
	/* if "user" is valid */
	if(user.match(userPat) == null){
		alertMsg(5, '?? ?? ??????');									// The email's username doesn't seem to be valid
		return false;
	}
	/* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */
	var IPArray = domain.match(ipDomainPat);
	if(IPArray != null){
		// this is an IP address
		for(var i=1; i<=4; i++){
			if(IPArray[i] > 255){
				alertMsg(5, '?? ????? ???????? ????????');				// email's Destination IP address is invalid
				return false;
			}
		}
		return true;
	}
	/* Domain is symbolic name. Check if it's valid. */
	var atomPat = new RegExp("^" + atom + "$");
	var domArr = domain.split(".");
	var len = domArr.length;
	for(i=0; i<len; i++){
		if(domArr[i].search(atomPat) == -1){
			alertMsg(5, '?? ?? ?????');									// email's The domain name does not seem to be valid.
			return false;
		}
	}
	/* ake sure that the domain ends in a known top-level domain (like com, edu, gov) or a two-letter word, 
	representing country (uk, nl), and that there's a hostname preceding the domain or country. */
	if(checkTLD && domArr[domArr.length-1].length != 2 && domArr[domArr.length-1].search(knownDomsPat) == -1){
		alertMsg(5, '????? ?????? ???? ?? ????? ???? ?????? ?????');	// email's address must end in a well-known domain or two letter country.
		return false;
	}
	/* Make sure there's a host name preceding the domain. */
	if(len < 2){
		alertMsg(5, '???? ?? ???? ????');								// email's address is missing a hostname
		return false;
	}
	// email is valid
	return true;
}

/* Personal ID validator - checks if the paersonal id is valid, displays error and retunrs boolean value */
function validateId(personalId){							// personalId - string
	var isValidId = false;
	while(personalId.length < 9){
		personalId = '0' + personalId;
	}
	if(personalId == '000000000'){
		isValidId = false;									// personal id is invalid
	}else{
		var tot = 0;
		for(var i=0; i<8; i++){
			var x = (((i%2)+1)*personalId.charAt(i));
			if(x > 9){
				x = x.toString();
				x = parseInt(x.charAt(0))+parseInt(x.charAt(1))
			}
			tot += x;
		}
		if((tot + parseInt(personalId.charAt(8)))%10 == 0){
			isValidId = true;								// personal id is valid
		}else{
			isValidId = false;								// personal id is invalid
		}
	}
	if(isValidId){											// return confirmation
		return true;
	}else{													// display error and return 
		alertMsg(6, '');
		return false;
	}
}

function isRegularPhoneNumber(val)

{           

 

    if(val == null)

        return false;

        

            var ret = (/^05[0,2,4,7,9]-{0,1}\d{7}$/.test(val) || 
		/^0[2,3,4,8,9]-{0,1}\d{7}$/.test(val) || 
		/^1-{0,1}[7,8]00-{0,1}\d{6}$/.test(val) ||
		/^077-{0,1}\d{7}$/.test(val)||
		/^07[2,4,6,7]-{0,1}\d{7}$/.test(val)||
		/^07[8]-{0,1}[4,8]-{0,1}\d{7}$/.test(val)||
		/^07[3]-{0,1}[2,7]-{0,1}\d{6}$/.test(val)||
		/^01[3,4,8]-{0,1}\d{7}$/.test(val)||
		/^153-{0,1}[2,3,4,8,9]-{0,1}\d{7}$/.test(val) ||
		/^1515[0,2,4,7]-{0,1}\d{7}$/.test(val));


            if(ret==false)
               
                return false;

      return true;       

}



