/*
  cp_formValidate.js
  Forms data validation
  Version 1.1
  Copyright (C) 2006 by Cinematica Producciones Ltda.
  Created: 20061115
  Last update: 20061208

  Falta:
    - Validar Url
*/

// Trim
String.prototype.trim = function() {
  return(this.replace(/(^\s*)|(\s*$)/g, ""));
};

// Object Validate
function oValidate(szName, szValidation, szError) {
  this.szName = szName;
  this.szValidation = szValidation;
  this.szError = szError;

  this.toString = function() { return(this.szName + "|" + this.szValidation + "|" + this.szError); }
  return(this);
}

// Return true if a date components are ok
function isDateOk(iYear, iMonth, iDay) {
  var iNewYear, iNewMonth, iNewDay;
  var aDate = new Date();
  aDate.setFullYear(iYear);
  aDate.setMonth(iMonth - 1);
  aDate.setDate(iDay);
  iNewYear = aDate.getFullYear();
  iNewMonth = aDate.getMonth() + 1;
  iNewDay = aDate.getDate();
  return((iYear == iNewYear) && (iMonth == iNewMonth) && (iDay == iNewDay));
}

// Return true if the eMail address is ok
/*
function isEMailOk(szEMail) {
  var eMailExp = '^([a-z_0-9]{1,})@([a-z_0-9]{1,})([.]{1})([a-z_0-9]{1,})$';
  return(szEMail == szEMail.match(new RegExp(eMailExp, "gi")));
}
*/

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function isEMailOk(str) {
  var at = "@";
  var dot = ".";
  var lat = str.indexOf(at);
  var lstr = str.length;
  var ldot = str.indexOf(dot);
  if(str.indexOf(at) == -1)
    return(false);
  if(str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr)
    return(false);
  if(str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr)
    return(false);
  if(str.indexOf(at,(lat+1)) != -1)
    return(false);
  if(str.substring(lat-1, lat) == dot || str.substring(lat+1, lat+2) == dot)
    return(false);
  if(str.indexOf(dot, (lat+2)) == -1)
    return(false);
  if(str.indexOf(" ") != -1)
    return(false);
  return(true);
}

/*
  Validation types:

  NE: Not empty
  MS: Must select
  NM: Numeric (a valid not empty number)
  DT: Valid date
  NR: Numeric Range: 0,1000 // not implemented yet: | >100 | <40 | !0
  EM: eMail address
  // not implemented yet: UR: URL
*/

// Validate a form
function frm_validate(oForm, aFields) {
/*
  var aFields = new Array(
    new oValidate("txtNumero", "NR,10,100", "Debe ser un número válido entre 10 y 100!"),
    new oValidate("txtFecha", "DT", "Debe ingresar una fecha válida en la forma YYYYMMDD!"),
    new oValidate("txtArea", "NE", "Debe ingresar algún tipo de comentario!"),
    new oValidate("txtPassword", "NE", "Debe ingresar el password!"),
    new oValidate("cbCheckBox", "MS", "Debe seleccionar al menos una opción!"),
    new oValidate("lstList", "MS", "Debe seleccionar por lo menos un elemento de la lista!")
  );
*/

  var bOk = true;
  if(aFields == null)
    return(bOk);

  for(var iField = 0; iField < aFields.length; iField++) {
    var oValid = aFields[iField];
    var oField = null;
    var szValue = "";
    var szValidate = oValid.szValidation.substr(0, 2);

    // MS: Must select
    if(szValidate == "MS") {
      oField = eval("oForm." + oValid.szName);
      if(oField.length) { // multiple
        // Must be at least one checked or selected
        var bSelected = false;
        for(var iItem = 0; iItem < oField.length; iItem++) {
          if((oField[iItem].checked || oField[iItem].selected) && (oField[iItem].value != "")) {
            bSelected = true;
            break;
          }
        }
        if(!bSelected) {
          bOk = false;
          alert("ERROR: " + oValid.szError);
          // Focus con control or at the first item
          if(oField.focus)
            oField.focus();
          else if(oField[0].focus)
            oField[0].focus();
        }
      }
    }
    else {
      // Take direct value
      oField = eval("oForm." + oValid.szName);
      szValue = oField.value.trim();
      var bValidValue = true;
      // NE: Not empty
      if(szValidate == "NE")
        bValidValue = (szValue != "");
      // NM: Numeric
      else if(szValidate == "NM")
        bValidValue = (szValue != "" && !isNaN(szValue));
      // DT: Date yyyymmdd
      else if(szValidate == "DT")
        bValidValue = (szValue != "" && szValue.length == 8 && isDateOk(szValue.substr(0, 4), szValue.substr(4, 2), szValue.substr(6, 2)));
      // EM: eMail
      else if(szValidate == "EM")
        bValidValue = isEMailOk(szValue);
      // NR: Numeric Range
      else if(szValidate == "NR") {
        var aData = oValid.szValidation.split(",");
        var iFrom = aData[1] * 1.0;
        var iTo = aData[2] * 1.0;
        var iValue = szValue * 1.0;
        bValidValue = (iValue >= aData[1] && iValue <= aData[2]);
      }
      if(!bValidValue) {
        bOk = false;
        alert("ERROR: " + oValid.szError);
        if(oField.focus)
          oField.focus();
      }
    }
    if(!bOk)
      break;
  }
  return(bOk);
}

// Control the number of input characters into a text area
function limitChars(ctrlName, maxChars) {
  var len = ctrlName.value.length;
  if(len > maxChars) {
    var txt = ctrlName.value;
    ctrlName.value = txt.substr(0, maxChars);
    return false;
  }
  return true;
}
