// funcao necessaria ao mm_validadeform
// v4.01
function MM_findObj( n, d ) { 
  var p,i,x;  
  
  if(!d)
	  d=document; 
  
  if((p=n.indexOf("?"))>0&&parent.frames.length) 
  {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p);
  }
  
  if(!(x=d[n])&&d.all) 
	  x=d.all[n]; 
  
  for (i=0;!x&&i<d.forms.length;i++) 
	  x=d.forms[i][n];
  
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
	  x=MM_findObj(n,d.layers[i].document);
  
  if(!x && d.getElementById) 
	  x=d.getElementById(n);
  
  return x;
}


// validacao do formulario - usado em alterar dados
function validateForm() 
{
	// argumentos da função
	var temp_args = validateForm.arguments;
	var total_args = temp_args.length;
	var args = new Array();
	
	// array copy necessario já que arguments fica bugado
	for (i = 0; i < (temp_args.length ); i++ ) 
	{
		args[i] = temp_args[i];		
	}
	
	var i, p, q, nm, test, num, min, max, errors = '';
	var l = args.length;
   var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	
	
	for (i = 0; i < (args.length - 2); i += 4) 
	{
		test = args[i + 2];
		var sIdCampo = args[i].split(":");
		val  = MM_findObj(sIdCampo[0]);
		
		if (val) {
			
			nm = '[' + args[i + 3] + ']';
			
			
			if ((val = val.value) != "") 
			{
								
				if (test.indexOf('isEmail') != -1) {
					if (!regEmail.test(val)) 
					{
						//pega mensagem de erro caso houver
						if (!(sIdCampo[1] == null)) 
						{
						   errors += '- '+sIdCampo[1]+'\n';	
				      }
						else
						{
						   errors += '- ' + nm + ' deve conter um endereço de e-mail.\n';	
						}
						
					}
					
				} else if (test.indexOf('isDate') != -1) {
					if (!ValidaData(val)) {
						errors += '- ' + nm + ' deve conter uma data.\n';
					}
				} else if (test.indexOf('isChecked') != -1) {
					if (!ValidaInputSelecionado(args[i])) {
						errors += '- ' + nm + ' devem ser selecionados.\n';
					}
				} else if (test.indexOf('isCPF') != -1) {
					if (!ValidaCPF(val)) {
						errors += '- ' + nm + ' deve conter um CPF.\n';
					}
				} else if (test.indexOf('isCNPJ') != -1) {
					if (!ValidaCNPJ(val)) {
						errors += '- ' + nm + ' deve conter um CNPJ.\n';
					}
				} else if (test.indexOf('isCEP') != -1) {
					if (!ValidaCEP(val)) {
						errors += '- ' + nm + ' deve conter um CEP.\n';
					}
				} else if (test.indexOf('isEqual') != -1) {
					
					campo2 = MM_findObj(test.substr(test.indexOf('(') + 1, test
							.indexOf(',')
							- test.indexOf('(') - 1));
					
					val2 = campo2.value;
					
					nm2  = test.substr(test.indexOf(',') + 1, test.indexOf(')')
							- test.indexOf(',') - 1);
					
					if (val != val2) {
                  //pega mensagem de erro caso houver
                  if(!(sIdCampo[1]==null))
                  {
                     errors += '- '+sIdCampo[1]+'\n';
                  }
                  else
                  {
                     errors+='- '+nm+' deve ser igual a ['+nm2+'].\n';
                  }
					}
					
				} 
				else if (test.indexOf('notIsEqual')!=-1) {
               campo2 = MM_findObj( test.substr(test.indexOf('(')+1,test.indexOf(',')-test.indexOf('(')-1) );
               val2 = campo2.value;
               nm2 = test.substr(test.indexOf(',')+1,test.indexOf(')')-test.indexOf(',')-1);
               
               if ( val == val2 ) {
                  //pega mensagem de erro caso houver
                  if(!(sIdCampo[1]==null))
                  {
                     errors += '- '+sIdCampo[1]+'\n';
                  }
                  else
                  {
                     errors+='- '+nm+' não pode ser igual a ['+nm2+'].\n';
                  }                 
               }              
            }
				
				else if (test != 'R') {
					
					if (val.indexOf(',') != -1) {
						val = val.substr(0, val.indexOf(',')) + '.'
								+ val.substr(val.indexOf(',') + 1, 2);
					}
					
					num = parseFloat(val);
					
					if (isNaN(val)) {
						errors += '- ' + nm + ' deve conter um número.\n';
					}
					
					if (test.indexOf('inRange') != -1) {
						
						p 	= test.indexOf(':');
						min = test.substring(8, p);
						max = test.substring(p + 1);
						
						if (num < min || max < num) {
							errors += '- ' + nm
									+ ' deve conter um número entre ' + min
									+ ' e ' + max + '.\n';
						}
					}
				}
				
			} 
			else if (test.indexOf('isEqual') != -1) {
				
				campo2 = MM_findObj(test.substr(test.indexOf('(') + 1, test
						.indexOf(',')
						- test.indexOf('(') - 1));
				
				val2 = campo2.value;
				
				nm2  = test.substr(test.indexOf(',') + 1, test.indexOf(')')
						- test.indexOf(',') - 1);
				
				if (val != val2) 
				{
	            //pega mensagem de erro caso houver
	            if(!(sIdCampo[1]==null))
	            {
	               errors += '- '+sIdCampo[1]+'\n';
	            }
	            else
	            {
	               errors += '- ' + nm + ' deve ser igual a [' + nm2 + '].\n';
	            }  					
				}
				
			} 
			else if (test.charAt(0) == 'R') {
				errors += '- ' + nm + ' é necessário.\n';
         } 
			else if ((val=val.value)!="")
         {

         }
			
		} else {
			// Caso o objeto não exista ainda(utilizado com campos incluidos
			// posteriormente a criação da página pelo ajax, mas que são
			// obrigatórios)
			nm = '[' + args[i + 3] + ']';
			errors += '- ' + nm + ' é necessário.\n';
		}
	}
	
	if (errors) 
	{
		alert('Valores inválidos:\n' + errors);
	}
	
	
	document.returnValue = (errors == '');
	// para testes document.returnValue = false;
	
}

/*

Tipos de valida??o utiliz?veis:

R -> Simplesmente valida (? obrigat?rio qualquer tipo de valor)
isEmail -> O valor do campo deve ser um e-mail v?lido (n?o pode ser vazio)
isRange -> Deve conter um n?mero entre min e max definidos
isNumber -> Deve conter um n?mero
isDate -> Deve conter uma data no formato 'dd/mm/aaaa'
isCPF -> Deve conter um CPF v?lido
isCNPJ -> Deve conter um CNPJ v?lido
isCEP -> Deve conter um CEP v?lido (99999-999)

*/

//****************************   DATA   **********************************************
function MascaraData(campo, key) { // Esta fun??o coloca as barras da data automaticamente no onKeyPress

	tecla = new Array();
	tecla[47] = '/';
	tecla[48] = '0';
	tecla[49] = '1';
	tecla[50] = '2';
	tecla[51] = '3';
	tecla[52] = '4';
	tecla[53] = '5';
	tecla[54] = '6';
	tecla[55] = '7';
	tecla[56] = '8';
	tecla[57] = '9';

	input = document.getElementById(campo);
	if ((key < 47 || key > 57) && (key != 13)) {
		return false;
	}

	if ( (key != 47) && (input.value.length == 2 || input.value.length == 5) ) {
		input.value += tecla[47];
	}

}
//Esta função verifica se existe um elemento do tipo input checkado dentro de uma div
function ValidaInputSelecionado( divId )
{
	//pega a div
	var div = document.getElementById(divId);

	
	//pega os elementos(inputs) dentro da div
	var checks = div.getElementsByTagName('input');
	
	//Para cara elemento adiquirido
	for (i=0;i<checks.length;i++){
		//se for do tipo checkbox
		if (checks[i].type == 'checkbox' && checks[i].checked==true ) {
			//achou um chekado então está ok
			return true;
		}
	}
	
   return false;	
}

function ValidaData( valor ){ // Esta fun??o verifica se o valor ? uma data v?lida
  if (valor == '') {
  	return false;
  }
  barras = valor.split("/");
  if (barras.length == 3){
     dia = barras[0];
     mes = barras[1];
     ano = barras[2];
     resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano >= 1800));
     if (!resultado) {
       return false;
     }
  } else {
     return false;
  }
  return true;
}

//****************************   CPF   **********************************************
function ValidaCPF( valor ){
	if ( isNaN(valor) || valor.length != 11 ) {
		return false;
	}

	if ( valor == '00000000000' || valor == '11111111111' || valor == '22222222222' ||
		 valor == '33333333333' || valor == '44444444444' || valor == '55555555555' ||
		 valor == '66666666666' || valor == '77777777777' || valor == '88888888888' ||
		 valor == '99999999999' ) {
		return false;
	}

	var i;
	var c = valor.substr(0,9);
	var dv = valor.substr(9,2);
	var d1 = 0;

	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(10-i);
	}
	if (d1 == 0){
		return false;
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) {
		d1 = 0;
	}
	if (dv.charAt(0) != d1) {
		return false;
	}
	d1 *= 2;
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) {
		d1 = 0;
	}
	if (dv.charAt(1) != d1) {
		return false;
	}

	return true;
}

//****************************   CNPJ   **********************************************
function ValidaCNPJ( valor ){

	var i;
	var c = valor.substr(0,12);
	var dv = valor.substr(12,2);
	var d1 = 0;

	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
	if (d1 == 0) {
		return false;
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) {
		d1 = 0;
	}
	if (dv.charAt(0) != d1){
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) {
		d1 = 0;
	}
	if (dv.charAt(1) != d1){
		return false;
	}

	return true;
}

//****************************   CEP   **********************************************
function MascaraCEP (campo, key){

	tecla = new Array();
	tecla[45] = '-';
	tecla[48] = '0';
	tecla[49] = '1';
	tecla[50] = '2';
	tecla[51] = '3';
	tecla[52] = '4';
	tecla[53] = '5';
	tecla[54] = '6';
	tecla[55] = '7';
	tecla[56] = '8';
	tecla[57] = '9';

	input = document.getElementById(campo);
	if ((key < 48 || key > 57) && (key != 13) && (key != 45)) {
		return false;
	}

	if ( (key != 45) && (input.value.length == 5) ) {
		input.value += tecla[45];
	}

}

function ValidaCEP( valor ){
	if ( isNaN(valor) ) {
		return false;
	}

	if ( valor.length != 8 ) {
		return false;
	}

	return true;
}

function data_barras(campo, key) {

	tecla = new Array();
	tecla[47] = '/';
	tecla[48] = '0';
	tecla[49] = '1';
	tecla[50] = '2';
	tecla[51] = '3';
	tecla[52] = '4';
	tecla[53] = '5';
	tecla[54] = '6';
	tecla[55] = '7';
	tecla[56] = '8';
	tecla[57] = '9';

	input = document.getElementById(campo);
	if ((key < 47 || key > 57) && (key != 13)) {
		return false;
	}

	if ( (key != 47) && (input.value.length == 2 || input.value.length == 5) ) {
		input.value += tecla[47];
	}
	return true;
}

function getBoxDesc(objPost){
    return objPost.options[objPost.selectedIndex].text;
}

function getData(objPost,campos) {
   
    if (objPost.value == '') {
        return false;
    }

    for (c=0;c<campos.length;c++){
        if ((campos[c].value.length != 0 || campos[c].value.length != 1) && campos[c].value != '0') {
            return false;
        }
    }

    if (!document.getElementById('UM_wCEP')) {
	    var div = document.createElement('div');
	        div.id = 'UM_wCEP';
	        div.innerHTML = 'Pesquisando CEP! Aguarde...';
	        div.style.width = '50%';
	        div.style.height = '100%';
	        objPost.offsetParent.appendChild(div);
    }

    var i = objPost.form;
        var link = window.location.href;
        var posicao = window.location.href.indexOf('&id_focus=');

        if (posicao > 0) {
           link = window.location.href.substr(0, posicao);
        }

        i.action = link+'&id_focus='+objPost.id+'#'+objPost.id;
        i.submit();
        return true;
}

function reloadCEP(objPost) {
    
    objPost.form.ds_estado.value = '';
    objPost.form.ds_cidade.value= '';

     if (!document.getElementById('UM_wCEP')) {
        var div = document.createElement('div');
            div.id = 'UM_wCEP';
            div.innerHTML = 'Pesquisando CEP! Aguarde...';
            div.style.width = '50%';
            div.style.height = '100%';
            objPost.offsetParent.appendChild(div);
    }

    objPost.form.cd_municipio.value = 0;
    objPost.form.ds_estado.value = 0;
    objPost.form.action = window.location.href + '';
    objPost.form.submit();
    return true;
}

function checkCEP(objPost,ObjAct) {
    if (!document.getElementById('WM_cCEP')) {
        var div           = document.createElement('div');
            div.id        = 'WM_cCEP';
            div.innerHTML = '<a href="#" onclick="reloadCEP(document.forms[0].ds_cep)">Buscar Endereço</a>';
            objPost.offsetParent.appendChild(div);
    }
    return true;
}

