// javascript regular expressions for pattern checking
// must have a 4.0 browser
// expect a global ns4/ie4, otherwise, don't call these functions
// and let the server handle the type checking

// types array, no need to create anew each time
// add as many as you need
// currently, types can be function pointers that take one argument
// or re's

var focus2 = true;

var types = new Array();
types["w"] = /\w/;	//word
types["w1"] = /\w+/;	//word
types["d"] = /^\d*$/;
types["d1"] = /^\d+$/;
types["file"] = /\w/;
types["date"] = _is_date;
types["null_date"] = _is_null_date;
types["email"] = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
types["state"] = _is_state;
types["password"] = _check_password;
types["password_verify"] = _check_password_verify;
//separate match from password_verify if the need arises
types["match"] = _check_password_verify;
types["ccard_type"] = _check_credit_card_type;
types["ccard"] = _check_credit_card_num;
types["phone"] = /\w+/;
types["and"] = _all_or_nothing;
types["or"] = _any;

function TypeChecker () {
    this.check_value = _check_value;
    this.check_form = _check_form;
}

function _all_or_nothing(vals) {
		var countTruth = 0;
		var countFalse = 0;
		for (i=0;i<vals.length;i++) {
			if (vals[i] != '') {
				countTruth++;
			} else {
				countFalse++;
			}
		}
		return ((countTruth==0) || (countFalse==0));
}

function _any(vals) {
		var toReturn = (vals[0]!='');
		for (i=0;i<vals.length;i++) {
			toReturn = toReturn || (vals[i]!='');
		}
		return toReturn;
}

function _check_password(val) {
	return (val.length > 4);
}

function _check_credit_card_type(vals) {
	//expects vals to be array of 2, first element is card type, 2nd element is ccard num
	var cardType=vals[0].toString();
	var cardNumber=vals[1].toString();
  
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "Mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "Visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "AmericanExpress":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;

      default:
        prefixRegExp = /^$/;
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  return isValid;
}

function _check_credit_card_num(val) {

		var cardNumber = val;
		
		var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
	
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
      {
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    return(checkSumTotal % 10 == 0);

}

function _check_password_verify(vals) {
x=vals[0].toString();
y=vals[1].toString();
	if (x == y) {
		return(true);
	} else { 
		return(false);
	}
}

function _is_state(val){
	return ((val.length >= 1) && (val.length <=2) );
}

function _is_date (val) {
    return Date.parse(val);
}

function _is_null_date (val) {
    if (val == "") {
	return true;
    } else {
	return Date.parse(val);
    }
}

function _check_value (vals, typ) {
	if (vals.length > 1) {
		return types[typ](vals);
	} else {
		var qq = new String(val);
		switch (typeof(types[typ])) {
	    case "undefined":
		return false;
	    case "object":
		return qq.match(types[typ]);
	    case "function":
		return types[typ](qq);
	    default:
		return false;
    }
	}
}


// this function expects to be passed
// an array of arrays of field names and expected types
// it will alert use and return true/false
// so the form knows whether or not to submit
// each sub array is in the form: new Array("field_name", "field_type", "error message"[, boolean ignore_empty_value]);
function _check_form (frm, fields) {
    var i, val, field, j;
    for(i=0; i<fields.length; i++) {
	val = "";
	
	strFieldnames = fields[i][0];
	fieldnames = strFieldnames.split("|");
	
	vals = new Array();
	
	has_val=0;
	for(m=0; m<fieldnames.length; m++) {
		//aryField[m] = frm[fieldnames[m]];

		vals[m] = new String(_get_val(frm[fieldnames[m]]));
		if(vals[m].length>0)
			has_val=1;
	}	
	if(fields[i][3] && !has_val) //skip if we are accepting empty values for this field
		continue;	

	if (! this.check_value(vals, fields[i][1])) {
	    alert(fields[i][2]);
	    if (focus2) { frm[fieldnames[0]].focus() }
	    return false;
	}
    }
    return true;
}


function _get_val(field) {
    // first we catch radio buttons
	if (!field.type) {  // it's a radio or checkbox group
	    if (field.length > 0) {
			if (field[0].type.match(/radio/i)) {
				focus2 = false;
				val = ""; // was val = null;
				for(j=0; j<field.length; j++) {
					if (field[j].checked) {
						val = field[j].value;
					}
				}
			}
	    }
	} else if (field.type.match(/select/i)) {
	    val = new String(field.options[field.selectedIndex].value);
	} else if ((field.type.match(/text/)) || (field.type.match(/password/))) {
	    val = new String(field.value);
	} else if (field.type.match(/file/)) {
	    val = new String(field.value);
	} else if (field.type.match(/radio/)) {
	    val = new String(field.value);
		//alert(val);
	} else if (field.type.match(/checkbox/)) { 
         val = ""; 
          if (field.checked) {
               val = new String(field.value);
          }
	}
	return val;
	
}























