(function(){ // Do everything in this one anonymous function
  // When the document finishes loading, call init()
  if (window.addEventListener) 
    window.addEventListener("load", init, false);
  else 
    if (window.attachEvent) 
      window.attachEvent("onload", init);
  
  // Define event handlers for any forms and form elements that need them.
  function init(){
    // Loop through all forms in the document
    for (var i = 0; i < document.forms.length; i++) {
      var f = document.forms[i]; // the form we're working on now
      // Assume, for now, that this form does not need any validation
      var needsValidation = false;
      
      // Now loop through the elements in our form
      for (j = 0; j < f.elements.length; j++) {
        var e = f.elements[j]; // the element we're working on
        // We're only interested in <input type="text"> textfields
        if (e.type != "text" && e.type != "password") 
          continue;
        
        // See if it has attributes that require validation
        var pattern = e.getAttribute("pattern");
        // We could use e.hasAttribute() but IE doesn't support it
        var required = e.getAttribute("required") != null;
        
        // Required is just a shortcut for a simple pattern
        if (required && !pattern) {
          pattern = "\\S";
          e.setAttribute("pattern", pattern);
        }
        
        // If this element requires validation,
        if (pattern) {
          // validate the element each time it changes
          e.onchange = validateOnChange;
          // validate the element each time blur
          //e.onblur = validateOnBlur;
          // Remember to add an onsubmit handler to this form
          needsValidation = true;
        }
      }
      
      // If at least one of the form elements needed validation,
      // we also need an onsubmit event handler for the form
      if (needsValidation) 
        f.onsubmit = validateOnSubmit;
    }
  }
  
  // This function is the onchange event handler for textfields that 
  // require validation.  Remember that we converted the required attribute
  // to a pattern attribute in init().
  
  
  
  // This function is the onchange event handler for textfields that 
  // require validation.  Remember that we converted the required attribute
  // to a pattern attribute in init().
  function validateOnChange(){
    var textfield = this; // the textfield
    var pattern = textfield.getAttribute("pattern"); // the pattern
    var required = textfield.getAttribute("required"); // the required
    var value = this.value; // the user's input
    if (required != "true" && value.length == 0) {
      textfield.className = "";
      return;
    }
    
    
    // Verify defined patterns
    if (pattern == "cep") {
      pattern = "\\d{2}\\.?\\d{3}-?\\d{3}";
    }
    else 
      if (pattern == "email") 
        pattern = "[\\w\\-]+@[\\w\\-]+?\\.[0-9a-zA-Z]{2,6}";
      else 
        if (pattern == "data" || pattern == "shortdata") {
        
          var date = new Date();
          date = parseDate(textfield.value);
          
          if (date == null) {
            textfield.className = "invalid";
            
          }
          else {
            if (pattern == "shortdata") 
              textfield.value = formatDate(date, "dd/MM/yy");
            else 
              textfield.value = formatDate(date, "dd/MM/yyyy");
            textfield.className = "valid";
          }
          return;
        }
        else 
          if (pattern == "hora") 
            pattern = "\\d{1,2}\:\\d{2}";
          else 
            if (pattern == "telefone") {
            
              var digits = value.replace(/[^0-9]/ig, ''); /* extract digits only */
              if (!digits) {
                textfield.className = "invalid";
                return;
              }
              
              var len = digits.length
              
              if (len < 9 || len > 12) {
                textfield.className = "invalid";
                return;
              }
              
              textfield.value = digits.substring(0, 2) + '-' + digits.substring(2, len - 4)
              
              textfield.value += '.' + digits.substring(len - 4, len);
              
              textfield.className = "valid";
              
              return;
              
            }
            else 
              if (pattern == "cpf") {
              
                var digits = value.replace(/[^0-9]/ig, ''); /* extract digits only */
                if (!digits) {
                  textfield.className = "invalid";
                  return;
                }
                
                if (!isCpf(value)) {
                  textfield.className = "invalid";
                  return;
                }
                
                textfield.value = formatCpfCnpj(value, null, false);
                textfield.className = "valid";
                
                return;
                
              }
              else 
                if (pattern == "cnpj") {
                
                  var digits = value.replace(/[^0-9]/ig, ''); /* extract digits only */
                  if (!digits) {
                    textfield.className = "invalid";
                    return;
                  }
                  
                  if (!isCnpj(value)) {
                    textfield.className = "invalid";
                    return;
                  }
                  
                  textfield.value = formatCpfCnpj(value, null, true);
                  textfield.className = "valid";
                  
                  return;
                  
                } else if (pattern == "empresa_parceira") {
                  
                  if (textfield.value.length == 0 && textfield.getAttribute("disabled") != "") {
                    textfield.className = "invalid"
                    return
                  }
                  
                  var script_name = '/cadastros/empresas/parceiras'
                  var params = {
                    'nome': textfield.value.substring(22,100)
                  }
                  jQuery.get(script_name, params, function(emp){
                    if (emp.length > 0) 
                      if (emp[0].value == textfield.value) {
                        textfield.className = "valid"
                        return
                      }
                    textfield.className = "invalid"
                  }, 'json')
                  return;
                } else if (pattern == "usuarios") {
                  
                  if (textfield.value.length == 0 && textfield.getAttribute("disabled") != "") {
                    textfield.className = "invalid"
                    return
                  }
                  
                  var script_name = '/cadastros/usuarios/autocomplete'
                  var params = {
                    'nome': textfield.value
                  }
                  jQuery.get(script_name, params, function(emp){
                    if (emp.length > 0) 
                      if (emp[0].value == textfield.value) {
                        textfield.className = "valid"
                        return
                      }
                    textfield.className = "invalid"
                  }, 'json')
                  return;
                }
  
    
    // If the value does not match the pattern set the class to "invalid".
    if (value.search(pattern) == -1) 
      textfield.className = "invalid";
    else 
      textfield.className = "valid";
    
  }
  
  // This function is the onsubmit event handler for any form that 
  // requires validation.
  function validateOnSubmit(){
    // When the form is submitted, we revalidate all the fields in the
    // form and then check their classNames to see if they are invalid.
    // If any of those fields are invalid, display an alert and prevent
    // form submission.
    var invalid = false; // Start by assuming everything is valid
    // Loop through all form elements
    for (var i = 0; i < this.elements.length; i++) {
      var e = this.elements[i];
      // If the element is a text field and has our onchange handler
      if ((e.type == "text" || e.type == "password") && e.onchange == validateOnChange) {
        e.onchange(); // Invoke the handler to re-validate
        // If validation fails for the element, it fails for the form
        if (e.className == "invalid") 
          invalid = true;
      }
    }
    
    // If the form is invalid, alert user and block submission
    if (invalid) {
      alert("O cadastro está incompleto ou com preenchimento incorreto.\n" +
      "Favor corrigir os campos marcados antes de salvar.");
      return false;
    }
  }
  
})();

