var mascara = '##.###.###/####-##';

function formata(numeros) {
  var pos = 0;
  var resultado = '';
  for (var i = 0; i < mascara.length && pos < numeros.length; i++) {
    if (mascara.charAt(i) == '#') {
      resultado += numeros.charAt(pos++);
    } else {
      resultado += mascara.charAt(i);
    }
  }
  return resultado;
}

function extraiNumeros(campo) {
  var numeros = '';
  for (var i = 0; i < campo.length; i++) {
    if (campo.charAt(i).match(/[0-9]/)) {
      numeros += campo.charAt(i);
    }
  }
  return numeros;
}

document.observe('dom:loaded', function() {
  $$('.cnpj').each(function(el){
    //92.411.245/0001-20
    el.maxLength = mascara.length;
    $(el).observe("keyup", function(e) {
      el.value = formata(extraiNumeros(el.value));
    });
  });

  $$('.numeric').each(function(el) {
    $(el).observe("keyup", function(e) {
      el.value = extraiNumeros(el.value);
    });
  });

  var errors = $$('.fieldWithErrors input');

  if(errors.length > 0)
    errors[0].focus();
  else
    $('company_contact_name').focus();

  $('company_form').observe('submit', function(e){
    $('company_submit').disable();
    return true;
  });
});
