/*----------------------------------------------------------------------
  Adiciona a função de validação checkForm() a todos os formulários
  encontrados na página. Esta função será incluida no arquivo por
  meio do evento window.onload
----------------------------------------------------------------------*/
function attachFormHandlers() {
  if (!document.getElementsByTagName) return;
  if (document.getElementsByTagName('form')) {
    var objForms = document.getElementsByTagName('form');
    for( var i = 0, objForm; objForm = objForms[i]; i++ ) {
      objForm.onsubmit = function(){return checkForm(this);}
    }
  }
}

/*----------------------------------------------------------------------
  Como existem vários tipos de controles, cada um com suas
  particularidades, dividimos o processamento por tipo e delegamos
  a tarefa da validação em si a outras funções.
----------------------------------------------------------------------*/
var globalForm;
var globalMsg = new Array();
var hazardChars = /[\"\'<>\/]/;

function checkForm(form){
  globalForm = form;
  var elNode, valid;
  var message = '';
  var validateIt = true;
  var frmFields = globalForm.getElementsByTagName('*');
  for( var i = 0, frmField; frmField = frmFields[i]; i++ ) {
    var classes = frmField.className.split(' ');
    for( var j = 0, theclass; theclass = classes[j]; j++ ) {
      if (theclass == 'null'){
        validateIt = false;
      }
    }
    if (validateIt == true) {
      var elNode = frmField.nodeName;
      switch(elNode){
      case 'SELECT':
        valid = checkSelect(frmField);
        break;
      case 'TEXTAREA':
        valid = checkTextarea(frmField);
        break;
      case 'INPUT':
        valid = checkInput(frmField);
        break;
      default:
        valid = true;
      }
      if (valid == false){
        var label = (frmField.title)?frmField.title:frmField.name.toTitleCase();
        globalMsg.push(label);
      }
    }
    validateIt = true;
  }
  if (globalMsg.length > 0) {
    globalMsg.formatAndShow();
    return false;
  } else {
    return true;
  }
}

/*----------------------------------------------------------------------
  Cada tipo de input é validado de uma forma específica
----------------------------------------------------------------------*/
function checkInput(field){
  var elType = field.type;
  var msg;
  switch(elType){
  case 'radio':
    return checkRadio(field);
    break;
  case 'checkbox':
    return checkCheckbox(field);
    break;
  case 'text':
    return checkTextField(field);
    break;
  case 'file':
    field.className += ' string';
    return checkTextField(field);
    break;
  case 'password':
    return checkPassword(field);
    break;
  default:
    return true;
    break;
  }
  return true;
}

/*----------------------------------------------------------------------
  Checa se algum item do SELECT foi selecionado
----------------------------------------------------------------------*/
function checkSelect(field){
  return (field.value != null && field.value != '' && field.value != '-1');
}

/*----------------------------------------------------------------------
  TEXTAREAs só não podem ser vazias
----------------------------------------------------------------------*/
function checkTextarea(field){
  return (field.value != null && field.value != '' && !field.value.match(hazardChars));
}

/*----------------------------------------------------------------------
    Radio buttons precisam ser verificados de uma maneira específica,
    pois não são um elemento apenas, e sim vários elementos com o mesmo
    'name'.
----------------------------------------------------------------------*/
function checkRadio(field){
  var inputs = globalForm.getElementsByTagName('input');
  for( var i = 0, input; input = inputs[i]; i++ ) {
    if (input.name == field.name){
      if(input.checked == true){
        return true;
      }
    }
  }
  return false;
}

/*----------------------------------------------------------------------
    O comentário da função checkRadio() se aplica também aqui.
----------------------------------------------------------------------*/
function checkCheckbox(field){
  var inputs = globalForm.getElementsByTagName('input');
  for( var i = 0, input; input = inputs[i]; i++ ) {
    if (input.name == field.name){
      if(input.checked == true){
        return true;
      }
    }
  }
  return false;
}

/*----------------------------------------------------------------------
    caso haja comparação de senha compara os dois campos
----------------------------------------------------------------------*/
function checkPassword(field){
  var valid;
  var elClasses = field.className.split(' ');
  for( var i = 0, elClass; elClass = elClasses[i]; i++ ) {
    switch (elClass){
      case 'senha':
        valid = IsNotEmpty (field.value);
        break;
      case 'comp_senha':
        valid = comparePasswords (field.value, document.getElementById('pass_senha').value);
        break;
    }
  }
  if (valid == false){
    return false;
  }
  return true;
}

function comparePasswords(v,c){
  if (IsNotEmpty(v) && IsNotEmpty(c)) {
    if (v == c) { return true; } else { return false; }
  } else { return false; }
}

/*----------------------------------------------------------------------
  Campos de texto serão validados com base em suas classes,
  que dizem que tipo de valor se espera encontrar.
----------------------------------------------------------------------*/
function checkTextField(field){
  var valid;
  var elClasses = field.className.split(' ');
  for( var i = 0, elClass; elClass = elClasses[i]; i++ ) {
    switch (elClass){
      case 'string':
        valid = isString (field.value.replace(/^\s*|\s*$/g, ''));
        break;
      case 'number':
        valid = isNumber (field.value);
        break;
      case 'money':
        valid = isMoney (field.value);
        break;
      case 'name':
        valid =  isName (field.value);
        break;
      case 'email':
        valid = isEmail (field.value);
        break;
      case 'url':
        valid = isUrl (field.value);
        break;
      case 'date':
        valid = isDate (field.value);
        break;
      case 'niver':
        valid = isDate (field.value, true);
        break;
      case 'cpf':
        valid = isCpf (field.value);
        break;
      case 'cnpj':
        valid = isCnpj (field.value);
        break;
      case 'rg':
        valid = isRg (field.value);
        break;
      case 'cep':
        valid = isCep (field.value);
        break;
      /*case 'senha':
        valid = isSenha (field.value, field.value);
        break;*/
      case 'tel':
        valid = isTel (field.value);
        break;
    }
  }
  if (valid == false){
    return false;
  }
  return true;
}

/*----------------------------------------------------------------------
  Funções de validação
----------------------------------------------------------------------*/
function isString(v){
  return (typeof v == 'string' && v != '' && isNaN(v) && !v.match(hazardChars));
}

function isNumber(v){
  return (!isNaN(v) && v != '');
}

function isMoney(v){
  return (v.match(/^([0-9]{1,3}\.?)+\,[0-9]{2}$/));
}

function isEmail(v){
  var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
  return (v != '' && objRE.test(v));
}

function isUrl(v){
  return (v.match(/^(ht|f)tp\:\/\/[a-zd][a-zd-]{1,64}(\.[a-zd][a-zd-]{2,64})*\.[a-z]{2,4}.+$/));
}

function isDate(date, b) {
  if (date==null) return false;
  arrDdate = date.split('/');
  dia = arrDdate[0]; mes = arrDdate[1]; ano = arrDdate[2]
  if (
    ( isNaN(parseInt(dia)) || isNaN(parseInt(mes)) || isNaN(parseInt(ano)) ) ||
    (ano < 1900 || ano > 2200) || 
    (mes < 1 || mes > 12) || 
    (dia < 1 || dia > 31) || 
    (mes == 2 && dia > 28 && (ano % 4 != 0)) || 
    (mes == 2 && dia > 29 && (ano % 4 == 0)) || 
    (dia > 30 && (mes == 4 || mes == 6 || mes == 9 || mes== 11))
  ) { 
    return false;
    } else {
    if (b){
      data = new Date (ano,mes,dia);
      dateInicio = new Date(1900,01,01);
      dateFim = new Date(2200,01,01);
      if(data<dateInicio || data>dateFim) return false;
    }
    return true;
  }
}

function isCpf(v){
  var s=null;
  var r=null;
  for( var i = 0, digit; digit = v[i]; i++ ) {
    if (isNaN(digit)){
      v = v.replace(digit, '');
    }
  }
  if(v.length !=11 || v.match(/1{11}|2{11}|3{11}|4{11}|5{11}|6{11}|7{11}|8{11}|9{11}|0{11}/))return false;
  s=0;
  for(var i=0;i<9;i++)s+=parseInt(v.charAt(i))*(10-i);r=11-(s%11);
  if(r==10||r==11)r=0;
  if(r!=parseInt(v.charAt(9)))return false;
  s=0;
  for(var i=0;i<10;i++)s+=parseInt(v.charAt(i))*(11-i);
  r=11-(s%11);
  if(r==10||r==11)r=0;
  if(r!=parseInt(v.charAt(10)))return false;
  return true;
}

function isCnpj(v){
  var dig1=0;
  var dig2=0;
  var x;
  var Mult1='543298765432';
  var Mult2='6543298765432';
  for( var i = 0, digit; digit = v[i]; i++ ) {
    if (isNaN(digit)){
      v = v.replace(digit, '');
    }
  }
  for(x=0;x<=11;x++){
    dig1=dig1+(parseInt(v.slice(x,x+1))*parseInt(Mult1.slice(x,x+1)));
  }
  for(x=0;x<=12;x++){
  dig2=dig2+(parseInt(v.slice(x, x+1))*parseInt(Mult2.slice(x,x+1)));
  }
  dig1=(dig1*10)%11;dig2=(dig2*10)%11;
  if(dig1==10){
    dig1=0;
  }
  if(dig2==10){
    dig2=0;
  }
  if(dig1!=parseInt(v.slice(12, 13))){
    return false;
  }else{
    if(dig2!=parseInt(v.slice(13, 14))){
      return false;
    }else{
      return true;
  }
  }
}

function isRg(v){
  for( var i = 0, digit; digit = v[i]; i++ ) {
    if (isNaN(digit)){
      v = v.replace(digit, '');
    }
  }
  return (v.match(/[0-9xX]{9}/));
}

function isCep(v) {
  for( var i = 0, digit; digit = v[i]; i++ ) {
    if (isNaN(digit)){
      v = v.replace(digit, '');
    }
  }
  if (v.length < 8) return false;
  return (v.match(/[0-9]{8}/));
}

function isTel(v) {
  for( var i = 0, digit; digit = v[i]; i++ ) {
    if (isNaN(digit)){
      v = v.replace(digit, '');
    }
  }
  if (v.length < 11) {
    return (v.match(/\d{7,11}/));
  } else {
    return false
  }
}
function IsNotEmpty(v) {
  if ((v.length==0) || (v==null) || (v == '')) {
    return false;
  }  else { return true; }
}
Array.prototype.formatAndShow = function(){
  var msg = "Os campos:\n\n";
  for (var i=0; i<this.length; i++){
    msg += ' * ' + this[i] + "\n";
  }
  msg += "\nEstão preenchidos de forma incorreta.\n\nPor favor, verifique se os dados\nestão corretamente preenchidos\ne envie novamente.";
  alert(msg);
  globalMsg = Array();
}

String.prototype.toTitleCase = function ()
{
  //lowercase the whole string
  var ls = this.toLowerCase();
  //turn it into an array by splitting at spaces
  var la = ls.split(" ");
  var firstLetter;
  //loop through word array
  for (var i = 0; i < la.length; i++)
  {
    //uppercase the first letter
    firstLetter = la[i].charAt(0).toUpperCase();
    //replace first letter with uppercase version
    la[i] = la[i].replace(la[i].charAt(0), firstLetter);
  }
  //rejoin words and return the new string
  return la.join(" ");
}

/*----------------------------------------------------------------------
  Adiciona a checagem ao documento, tomando o cuidado de não perder
  funções previamente adicionadas.
----------------------------------------------------------------------*/

/*var oldOnload = window.onload;

if (typeof(window.onload) != "function"){
  window.onload = attachFormHandlers;
} else {
  window.onload = function(){
    oldOnload();
    attachFormHandlers();
  }
}*/


function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

addEvent(window, 'load', attachFormHandlers);