/*-----------------------------
 * Module: Glowie WebDev Form Validator
 * Author: Ben Wynn <answer@glowie.com>
 * Version: 0.3
 * Date: Sun Nov 17 07:31:10 EST 2002
 * Copyright 2002.  All rights reserved, worldwide.
 */

function gwdFindObj(name) {
  var elem = new Object;
  if (document.getElementById) {
  	elem.obj = document.getElementById(name);
	elem.style = document.getElementById(name).style;
  } else if (document.all) {
	elem.obj = document.all[name];
	elem.style = document.all[name].style;
  } else if (document.layers) {
   	elem.obj = document.layers[name];
   	elem.style = document.layers[name];
  }
  
  return elem;
}

/* generic error reporting function. */
/* FIXME: has an error if fieldObj isn't visible, etc. */ 
function gwdFVDoError(fieldObj, errMsg) {
  alert("Form Validator:\n"+errMsg);
  if (fieldObj.focus) {
    fieldObj.focus();
  }
  return false;
}

/* FIXME: dear god this function needs work. */  
function gwdFVCheckEmailSub( emailStr ) {

var checkTLD=1;
var knownDomsPat=/^(COM|NET|ORG|EDU|INT|MIL|GOV|ARPA|BIZ|AERO|NAME|COOP|INFO|PRO|MUSEUM|com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
		alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Ths username contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Ths domain name contains invalid characters.");
			return false;
		}
	}

	if (user.match(userPat)==null) {
		alert("The username doesn't seem to be valid.");
		return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {

		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}
 
	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) {
			alert("The domain name does not seem to be valid.");
			return false;
		}
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	    domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	if (len<2) {
		alert("This address is missing a hostname!");
		return false;
	}
	return true;
}

function gwdFVCheckEmail(fieldObj, fieldName)
{

	if (! (gwdFVCheckString(fieldObj, fieldName) && gwdFVCheckEmailSub(fieldObj.value)) ) {
		//alert(msgAlert); // alert is already done by the tests.
		fieldObj.focus();
		return false;
	}
	return true;
}
  
function gwdFVCheckString(fieldObj, fieldName)
{
  //alert("Checking String Value: "+ theElem.value);
  if (fieldObj.value == "") {
    return gwdFVDoError(fieldObj, "Please enter a value for the "+fieldName+" field.");
  }
  return true;
}

/* gwdFVCheckNumeric: type is a bit-flag, codes are as follows:
  0 = valid number, should it exist.
  1 = number is mandatory
  2 = number must be at least the minimum
  3 = mandatory minimum
  4 = number cannot exceed the maximum
  5 = mandatory maximum
  6 = between min and max
  7 = mandatory between min and max
  8 = stringwise character check
  9 = mandatory character check
 16 = all checks?
*/  
function gwdFVCheckNumeric(fieldObj, fieldName, type, min, max)
{
  var ckStr = fieldObj.value;
  
  //alert("field: "+fieldName+"\ncheck type: "+type+"\nmin:"+min+"\n max: "+max);

  if (type & 0x01) {
    /* this field is mandatory.  make sure *something* is there */
    if (ckStr == "") {
      return gwdFVDoError(fieldObj, "Please fill in the "+fieldName+" field.");
    }
  } else {
    /* not mandatory, just return true if it's empty */
    if (ckStr == "") {
      return true;
    }
  }

  /* min and max checks */
  if ( (type & 0x02) || (type & 0x04) || (type == 0) ) {
    var ckNum = parseFloat(ckStr);
    //alert("the "+fieldName+" field is currently: "+ckNum);
    if (! isFinite(ckNum)) {
      return gwdFVDoError(fieldObj, "Please enter a Number in the "+fieldName+" field.");
    }

    /* set the number to what we know it to be, instead of what they typed in */
    if (fieldObj.type == "text") fieldObj.value = ckNum.toString();
    
    if (type & 0x02) {
      if (ckNum < min) {
        return gwdFVDoError(fieldObj, "The "+fieldName+" field is too low.\n (minimum is "+min+")");
      }
    }
  
    if (type & 0x04) {
      if (ckNum > max) {
        return gwdFVDoError(fieldObj, "The "+fieldName+" field is too high.\n (maximum is "+max+")");
      }
    }
  }
  
  
  
  if (type & 0x08) {
    alert("check type four is on (unh...)"+fieldName);
    var checkOK = "0123456789-.";

    /* FIXME: check for leading '-' and one only. */
    /* FIXME: check for only one '.' */

    for (i = 0;  i < ckStr.length;  i++)  {
      ch = ckStr.charAt(i);
      if (ckOK.indexOf(ch) == -1) {
        return gwdDoAlert(fieldObj, "Please only enter \""+checkOK+"\" in field "+fieldName);
      }
    }
  }

  //alert("well, i guess the check worked"+fieldName);
  /* well, i guess everything worked okay */  
  return true;
}

function gwdFVCheckRadio(fieldObj, fieldName)
{
  	var numSelected = 0;
  	var i;
	for (i = 0;  i < fieldObj.length;  i++) {
		if (fieldObj[i].checked)
			numSelected++;
	}
	if (numSelected < 1)  {
		return gwdFVDoError(fieldObj[0], "Please select one of the "+fieldName+" options.");
	}
	
	return true; 
}

/* make sure between min and max items are selected */
/* a minimum of zero implies non-mandatory field. */
function gwdFVCheckSelect(fieldObj, fieldName, min, max)
{

  /* shortcut if they havn't selected anything at all */
  if ((min > 0) && fieldObj.selectedIndex < 0)  {
    return gwdFVDoError(fieldObj, "Please select one of the "+fieldName+" options.");
  }

  var numSelected = 0;
  var i;
  for (i = 0;  i < fieldObj.length;  i++)  {
    if (fieldObj.options[i].selected)
        numSelected++;
  }
  if (numSelected < min)  {
    return gwdFVDoError(fieldObj, "Please select at least "+min+" of the "+fieldName+" options.");
  }
  if (numSelected > max) {
    return gwdFVDoError(fieldObj, "Please select no more than "+max+" of the "+fieldName+" options.");
  }

  return true;
}
