function nonNull(s) {
    return ((s != null) && (s.length > 0));
}
function TrimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

function specialChar(val){
	if(val.indexOf("'")!=-1){
	     return "'";
	 }
	 if(val.indexOf("&")!=-1){
	      return "&";
	  }
	   if(val.indexOf("%")!=-1){
	         return "%";
	  }
	  if(val.indexOf("?")!=-1){
	       return "?";
	  }
	  if(val.indexOf("#")!=-1){
	         return "#";
	  }
	  if(val.indexOf("\"")!=-1){
	       return "\"";
	  }
	 if(val.indexOf("/")!=-1){
	         return "/";
	    }
	 
  	return "ok";
}
function checkFileName(val){
   if(val.indexOf("\\")!=-1){
	       return "\\";
	  }
	return  specialChar(val);
	
	
}

function getFieldValue(widget) {

    var value = null;

    if (widget.type) {

        var type = widget.type;

        if ((type == "text") || (type == "password") || (type == "textarea")) {

            value = widget.value;

        } else if ((type == "select-one") || (type == "select")) {

            if (widget.selectedIndex != -1) {
                value = widget.options[widget.selectedIndex].value;
            }

        } else if (widget.value) {
            value = widget.value;
        } else {
            value = null;
        }

    } else if (widget.length) {

       // for widget with length we only return the first value checked

        for (var i = 0; i < widget.length; i++) {
            var w = widget[i];
            if (w.type && (w.type == "radio") && w.checked) {
                value = w.value;
                break;
            }
        }
    }

    return value;
}

function fieldIsEmpty(widget) {
    return (!nonNull(getFieldValue(widget)));
}

function requireField(widget,message) {
    if (fieldIsEmpty(widget)) {
        if (widget.focus) widget.focus();
        alert(message);
        return false;
    } else
        return true;
}

//replace all the specified characters in a string
function removeAllChar(str, c) {

    if (str == null) return null;
    if (str.length != 0) {
        var strAr = str.split(c);
        return strAr.join("");
    } else {
        return "";
    }
    
}


//check a widget value is an integer
function validInteger(widget) {

    var value = getFieldValue(widget);
    return isInteger(value);
}

// check a string pattern is an interger
function isInteger(value) {
    if (value == null || value.length == 0) return false;
    var re = /^\d+$/;
    return re.test(value);
}

function validFloat(widget) {
    var value = getFieldValue(widget);
    return isFloat(value);
}

//check if a string pattern is a float
function isFloat(value) {

    if (value == null || value.length == 0)
        return false;
    var re1 = /^\d+(\.\d*)?$/;
    var re2 = /^\.\d+$/;
    return (re1.test(value) || re2.test(value));
}

//check a widgt value is a valid currency pattern
function validCurrency(widget) {

    var value = getFieldValue(widget);
    if (value == null || value.length == 0) return false;
    var cleanValue = null;
    if (value.charAt(0) == '$') {
        cleanValue = value.substring(1, value.length);
    } else if (value.lastIndexOf('$') != -1) {
        cleanValue = value.substring(0, value.lastIndexOf('$'));
    } else {
        cleanValue = value;
    }
    return (isFloat(removeAllChar(cleanValue, ',')));
}

//check a widget value is a valid percentage pattern
function validPercentage(widget) {
	
    var value = getFieldValue(widget);
    if (value == null)
	return false;
    var re1 = /^\d+%$/;
    var re2 = /^\d+(\.\d{0,5})?%$/;
    var re3 = /^\.\d{1,5}%$/;
    var re4 = /^\d{1,3}(,\d{3})+(\.\d{0,5})?%$/;
    return (re1.test(value) || re2.test(value) || re3.test(value) || re4.test(value));
}

function isIntOrNull(widget, message) {

    if (!fieldIsEmpty(widget)) {
	if (!validInteger(widget)) {
	    alert(message);
	    widget.focus();
	    return false;
	}
    }

    return true;

}

function isFloatOrNull(widget, message) {

    if (!fieldIsEmpty(widget)) {
	if (!validFloat(widget)) {
	    alert(message);
	    widget.focus();
	    return false;
	}
    }

    return true;

}

function getNumber(widget) {
    var value = getFieldValue(widget);
    if (nonNull(value)) {
        var number = parseInt(value,10);
        return number;
    }
    return Number.NaN;
}

function getFloatNumber(widget) {
    var value = getFieldValue(widget);
    if (nonNull(value)) {
        var number = parseFloat(value);
        return number;
    }
    return Number.NaN;
}

function isEqual(widget1, widget2, message) {
    var value1 = getFieldValue(widget1);
    var value2 = getFieldValue(widget2);
    if (value1 == value2)
        return true;
    alert(message);
    return false;
}

function validDate(month_w, day_w, year_w) {
  if (fieldIsEmpty(month_w) && fieldIsEmpty(day_w) && fieldIsEmpty(year_w))
	return true;
  return requiredDate(month_w, day_w, year_w);

}

function validateAddress(street, city, state, province, zip, country) {
  if (fieldIsEmpty(street) && fieldIsEmpty(city) && (fieldIsEmpty(state)|| fieldIsEmpty(province)) && fieldIsEmpty(zip) && fieldIsEmpty(country))
      return true;
  else if (!fieldIsEmpty(street) && !fieldIsEmpty(city) && (!fieldIsEmpty(state) || !fieldIsEmpty(province)) && !fieldIsEmpty(zip) && !fieldIsEmpty(country))
      return true;

}


function requiredDate(month_w, day_w, year_w) {
  if (!(validInteger(month_w) && validInteger(day_w) && validInteger(year_w)))
  	return false;
  var month = getNumber(month_w);
  var year = getNumber(year_w);
  var day = getNumber(day_w);
  if (month > -1 && month < 13 && day > 0 && day < 32 && year > 1900 && year < 2200)
     return true;
  return false;
}


function requiredFullDate(full_date) {

  if(full_date.value=='')
     return false;

  return true;

}


function isDateEmpty( month_w, day_w, year_w) {
  if( fieldIsEmpty( month_w) ||
      fieldIsEmpty( day_w) ||
      fieldIsEmpty( year_w) ) {
      return true;
  } else
     return false;
}


function validatePhoneDigits(phone) {
	 var count=0;
		 var c;
		 if(fieldIsEmpty(phone))
			return true;
	     else{
		   	for(i=0;i<phone.value.length;i++){
				c =phone.value.charAt(i);
				if(c>='0' && c<='9')
					count++;
			
			}
			if(count==10)
				return 	true;
			else
				return false;
	 }

}

function validateNumericMix(inputval,num) {
	 var count=0;
		 var c;
		 if(fieldIsEmpty(inputval))
			return true;
	     else{
		   	for(i=0;i<inputval.value.length;i++){
				c =inputval.value.charAt(i);
				if(c>='0' && c<='9')
					count++;
			
			}
			if(count==num)
				return 	true;
			else
				return false;
	 }

}

function isNumber(v) {
	  
		 var c;
			 
		 if(fieldIsEmpty(v))
			return true;
		 else{
		   	for(i=0;i<v.value.length;i++){
				c =v.value.charAt(i);
				if(c<'0' || c>'9')
					return false;
			
			}
			 
	 }
	return true;
}
function isEmpty(v){
     var c;
	
		for(i=0;i<v.length;i++){
				c =v.charAt(i);
				if(c !=' ')
				   return false;
		  
	    }
	return true;

}
function checkNumeric(v) {
	  
		 var c;
	
		for(i=0;i<v.length;i++){
				c =v.charAt(i);
				if((c<'0' || c>'9') && c !='.' && c !=',' && c !='$' && c!='%' && c!='-')
					return false;
		  
	    }
	return true;
}
function checkPercentage(v) {
	  
		 var c;
	
		for(i=0;i<v.length;i++){
				c =v.charAt(i);
				if((c<'0' || c>'9') && c !='.' )
					return false;
		  
	    }
	return true;
}
function transform(v) {
	  
		 var c;
		 var result="";
		for(i=0;i<v.length;i++){
			c =v.charAt(i);
			if((c>='0' && c<='9') || c =='.'  )
				result+=c;				 
		  
	    }
	return result;
}

function validatePhone1(phone) {
   if(fieldIsEmpty(phone))
       return true;
   else if (phone.value.length >= 13)
       return true;
   else if (phone.value == "()-") {
       phone.value ="";	
       return true;
   }		
   else
      return false;
}

function validatePhone(phone) {
	 var count=0;
	 var c;
	 if(fieldIsEmpty(phone))
		return true;
     else{
	   	for(i=0;i<phone.value.length;i++){
			c =phone.value.charAt(i);
			if(c>='0' && c<='9')
				count++;
		
		}
		if(count==10)
			return 	true;
		else
			return false;
	 }

}
function isDateNull( month_w, day_w, year_w) {
  if( fieldIsEmpty( month_w) && 
      fieldIsEmpty( day_w) && 
      fieldIsEmpty( year_w) ) {
      return true;
  } else
     return false;
}

function requireDate( month_w, day_w, year_w, message) {
  if( isDateEmpty( month_w, day_w, year_w)) {
      alert( message);
      if (month_w.focus) month_w.focus();
      return false;
  } else 
    return true;
}    

function emailCheck (emailStr) {
    /* The following pattern is 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=/^(.+)@(.+)$/
    /* The following string represents the pattern for matching all special
       characters.  We don't want to allow special characters in the address. 
       These characters include ( ) < > @ , ; : \ " . [ ]    */
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    /* The following string represents the range of characters allowed in a 
       username or domainname.  It really states which chars aren't allowed. */
    var validChars="\[^\\s" + specialChars + "\]"
    /* The following 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="(\"[^\"]*\")"
    /* The following pattern applies for domains that are IP addresses,
       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})\]$/
    /* The following string represents an atom (basically a series of
       non-special characters.) */
    var atom=validChars + '+'
    /* The following 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 + ")"
    // The following pattern describes the structure of the user
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
    /* The following pattern describes the structure of a normal symbolic
       domain, as opposed to ipDomainPat, shown above. */
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


    /* Finally, let's start trying to figure out 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. */
            alert("Email address seems incorrect (check @ and .'s)")
            return false
    }
    var user=matchArray[1]
    var domain=matchArray[2]

    // See if "user" is valid 
    if (user.match(userPat)==null) {
        // user is not valid
        alert("The 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) {
                    alert("Destination IP address is invalid!")
                    return false
                }
        }
        return true
    }

    // Domain is symbolic name
    var domainArray=domain.match(domainPat)
    if (domainArray==null) {
            alert("The domain name doesn't seem to be valid.")
        return false
    }

    /* domain name seems valid, but now make sure that it ends in a
       three-letter word (like com, edu, gov) or a two-letter word,
       representing country (uk, nl), and that there's a hostname preceding 
       the domain or country. */

    /* Now we need to break up the domain to get a count of how many atoms
       it consists of. */
    var atomPat=new RegExp(atom,"g")
    var domArr=domain.match(atomPat)
    var len=domArr.length
    if (domArr[domArr.length-1].length<2 || 
        domArr[domArr.length-1].length>3) {
       // the address must end in a two letter or three letter word.
       alert("The address must end in a three-letter domain, or two letter country.")
       return false
    }

    // Make sure there's a host name preceding the domain.
    if (len<2) {
       var errStr="This address is missing a hostname!"
       alert(errStr)
       return false
    }

    // If we've gotten this far, everything's valid!
    return true;
}