var msg ='', quebralinha = '', nodeBorder = '', nodeBack='#FFFF33', x=-1, countNode=0;

function addTableIrmao(){
    
	var i, x=0;
    var td = document.getElementById('table_irmao');
	var div = document.createElement('div');
	td.appendChild(div);
	for(i=0; i<td.childNodes.length; i++){
		if(td.childNodes[i].tagName == 'DIV'){
		     x = i;	 
		}
	}
	td.childNodes[x].innerHTML = document.getElementById('table_irmao_orginal').innerHTML; 
	addEventsLink();
}

function removeTableIrmao(e){
	if (window.event) {
        target = window.event.srcElement;
    } else if (e) {
        target = e.target;
    } else return;
	
	confirmValue = confirm('Tem certeza que quer excluir?');
	if(confirmValue){
	   target.parentNode.parentNode.removeChild(target.parentNode);	
	}
	else{
		
	}
}

function addEventsLink(){
	objA = document.getElementsByTagName('a');
	for(i=0; i<objA.length; i++){
		if(objA[i].id == 'remover_irmao'){
			addEvent(objA[i], 'click', removeTableIrmao);
		}
	}
}


function addEventForms(){
	var i;
	addEventsLink();
	objforms = document.getElementsByTagName('form');
	for(i=0; i< objforms.length; i++ ){
		addEvent(objforms[i], 'submit', validateForms);
		for(y=0; y<objforms[i].length; y++){
			nodeInput = objforms[i].elements[y];
			if(nodeInput.name == 'cod_cpf_mae'){
				addEvent(nodeInput, 'keyup', mascaraEnet2);
				addEvent(nodeInput, 'blur', veficaCpfAuterado);
			}
			else if (nodeInput.name == 'cod_cpf_pai'){
				addEvent(nodeInput, 'blur', veficaCpfAuterado);
			}
		}
	}
}


function addEventFilhosCpf(){
	var i;
	objforms = document.getElementsByTagName('form');
	for(i=0; i< objforms.length; i++ ){
		for(y=0; y<objforms[i].length; y++){
			nodeInput = objforms[i].elements[y];
			if(/^cod_cpf_irmao/.test(nodeInput.name)){
				addEvent(nodeInput, 'blur', veficaCpfAuterado);
			}
    	}
	}
}




function validaCNPJ(objNode) 
{
	
	CNPJ = objNode.value;
	
	if (CNPJ.length < 18) {
		msg += "\n - É necessarios preencher corretamente o numero do CNPJ!";
		nodeStyleError(objNode);
		return false;
	}
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		msg += "\n - É necessarios preencher corretamente o numero do CNPJ!";
		nodeStyleError(objNode);
		return false;
	}
	//substituir os caracteres que nao sao numeros
	if(document.layers && parseInt(navigator.appVersion) == 4){
	x = CNPJ.substring(0,2);
	x += CNPJ.substring(3,6);
	x += CNPJ.substring(7,10);
	x += CNPJ.substring(11,15);
	x += CNPJ.substring(16,18);
	CNPJ = x;
	} else {
	CNPJ = CNPJ.replace(".","");
	CNPJ = CNPJ.replace(".","");
	CNPJ = CNPJ.replace("-","");
	CNPJ = CNPJ.replace("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)){
		msg += "\n - A verificacao de CNPJ suporta apenas números!";
		nodeStyleError(objNode);
		return false;
	}
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
	a[i] = CNPJ.charAt(i);
	b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
	b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		msg +="\n - Digito verificador com problema!";
		nodeStyleError(objNode);
		
		return false;
	
	}
	
	
	return true;
}

function validaEmail(objNode){
	
	var email = objNode.value;
	var invalid;
	invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
	
	// verifica se o email é válido
	if (email.length == 0)	
		{
				msg+='\n- E-mail inválido! ';
				nodeStyleError(objNode);
			return false;	
		}
			

	if (invalid.test(email) == false) 
		{
		// caso o teste falhe, para mudar a cor do texto na caixa, mude na linha abaixo
			msg+='\n- E-mail inválido !';
			nodeStyleError(objNode);
		  return (false); 
		}		
			 
	return true;
		   
}

function validaCPF(objNode)	
{
	cpf = objNode.value	
	cpf = cpf.replace(".","");
	cpf = cpf.replace(".","");
	cpf = cpf.replace("-","");
	cpf = cpf.replace("/","");
	
	var i;
	var c = cpf.substr(0,9);
	var dv = cpf.substr(9,2);
	var d1 = 0;
	
	if (cpf == '11111111111')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
	if (cpf == '22222222222')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}

	if (cpf == '33333333333')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}

	if (cpf == '44444444444')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}

	if (cpf == '55555555555')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}

	if (cpf == '66666666666')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
	if (cpf == '77777777777')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
	if (cpf == '88888888888')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
	if (cpf == '99999999999')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
	if (cpf == '00000000000')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
	if (cpf == '01234567890')
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
		
	
	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)
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		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)
	{
		msg+='\n - CPF inválido !';
		nodeStyleError(objNode);
		return false;
	}
        return true;
}

function  validaCEP(cep)
{
	if (cep.length < 8) 
		{
			msg+='\n CEP inválido !';
			return false; 
		}
		
	return true;
	
}		

function veficaCpfAuterado(e){
	if (window.event) {
        target = window.event.srcElement;
    } else if (e) {
        target = e.target;
    } else return;
	
    if(target.name == 'cod_cpf_mae'){	
	  if(document.form1.cpf_mae_tmp.value != target.value){
          document.form1.id_mae.value = '';		
	  }
	}
	else if(target.name == 'cod_cpf_pai'){
		if(document.form1.cpf_pai_tmp.value != target.value){
         document.form1.id_pai.value = '';		
	    }
	}
	else if(/^cod_cpf_irmao/.test(target.name)) {
		 arr = target.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('input');
		 zerarIdIrmao = false;
		 for(i=0; i< arr.length; i++){
		 	if(arr[i].name == 'cpf_irmao_tmp[]'){
				if(target.value != arr[i].value){
					zerarIdIrmao = true;
				}
			}
			else if(/^id_irmao/.test(arr[i].name)){
			   if(zerarIdIrmao){
				    arr[i].value = '';
				}	
			}
		 }
	}  
}

function validateForms(e){
	
	if (window.event) {
        target = window.event.srcElement;
    } else if (e) {
        target = e.target;
    } else return;
	
	msg = '';
	x = -1;
	
	for(countNode=0; countNode<target.length; countNode++ ){
	   objNode = target.elements[countNode];
	   if(nodeBorder != ''){
	      objNode.style.borderColor = ''; 	
	   } 
	   else{
	      objNode.style.backgroundColor = '';
	   }
	   if(objNode.getAttribute('mensagem') && objNode.disabled == false){
	   	   if(objNode.type == 'text' || objNode.type == 'textarea' || objNode.type =='password'){
		   	  
			   if(objNode.name == "cod_cnpj")
		   		{
				    validaCNPJ(objNode);   
		   		}
		   		else if(objNode.name == "cod_email")
		   		{
					 validaEmail(objNode);
		   		}
		   		else if(objNode.name == "cod_cpf")
		   		{
					validaCPF(objNode)
		   		}
				else 
				{
			  		validateInputText(objNode);
				}
			  			  
		   }
		   else if(objNode.type == 'select-one' || objNode.type == 'select' || objNode.type == 'select-multiple'){
		   	   validateSelect(objNode);
		   }
		   
		  
		   
	   }	
	}
    if(msg != ''){	
	   alert(msg);
	   if(x!=-1){
		  target.elements[x].focus();
	   }
	     if (e && e.preventDefault) e.preventDefault(); // DOM style
           return false;
    }
}

function validateInputText(objInput){
	if(objInput.value == ''){
		nodeStyleError(objInput);
		if(msg.indexOf(objInput.getAttribute('mensagem')) == -1){
		   msg +=  quebralinha + objInput.getAttribute('mensagem');
		   quebralinha = '\n';
		} 
		x = (x == -1)?countNode:x;
	}
	return;
}

function nodeStyleError(obj){
	if(nodeBorder != ''){
	    obj.style.borderColor = nodeBorder; 	
	} 
	else{
		obj.style.backgroundColor = nodeBack;
	}
	return;
}


function validateSelect(obj){
	var i, sel=false;
	for(i=0; i< obj.options.length; i++){
	  if(obj.options[i].selected && obj.options[i].value !=''){
	   	sel = true;
	  }	
	}
	if(sel){
		return;
	}
	else{
		nodeStyleError(obj);
		if(msg.indexOf(obj.getAttribute('mensagem')) == -1){
		  msg +=  quebralinha + obj.getAttribute('mensagem');
		  quebralinha = '\n';
		} 
		x = (x == -1)?countNode:x;
		return;
	}
}

function getDadosCliente(idmae){
	
	
	var ajaxMae = new ajax;
	ajaxMae.setParams('acao', 'getDadosCliente', 'id_cliente', idmae);
	ajaxMae.returnXML = true;
	ajaxMae.sendLoad('cliente_engine.php', '', setDados, 'POST');
}

function setDados(xmlDadosMae){
	//document.getElementById('debug').innerHTML = '';
	
	alert(xmlDadosMae);
	
	var itemsMae =  xmlDadosMae.getElementsByTagName('item');


	
	var id_estado = '';
	var id_cidades = '';
	for(var i=0; i<itemsMae.length; i++){
		nodeMae = itemsMae[i];
		if(document.getElementById(nodeMae.getAttribute('nodeName')).name == 'id_estados'){
		    id_estado = nodeMae.getAttribute('value');
			setOption(document.getElementById(nodeMae.getAttribute('nodeName')),id_estado); 	
		}else if(document.getElementById(nodeMae.getAttribute('nodeName')).name == 'id_cidades')
		{
			
			 id_cidades = nodeMae.getAttribute('value'); 
			 Atualiza(id_estado, id_cidades);
			 
			 
		}
		else
		{
		  document.getElementById(nodeMae.getAttribute('nodeName')).value = nodeMae.getAttribute('value');
		} 
		//document.getElementById('debug').innerHTML += nodeMae.getAttribute('nodeName') + '= '+ nodeMae.getAttribute('value') 	 +'<br />';
	}
  
}

function setOption(objSelect, value){
     
   for(var i=0; i<objSelect.options.length; i++){
	   optionNode = objSelect.options[i];
	   if(optionNode.value == value){
	   	  optionNode.selected = true;
	   }  	
	}
}

function getDadosFilhos(idMae, idFilho){
	
	if(idMae == ''){
		return;
	}
	var ajaxFilhos = new ajax;
	
	idsIrmao = document.getElementsByName('id_irmao[]');
	idIrmao = '(-1';
	for(i=0; i<idsIrmao.length; i++){
		if(idsIrmao[i].value){
	      idIrmao += ', ' + idsIrmao[i].value; 		
		}
	}
	idIrmao += ' )'; 
	
    var visual = document.forms[0].visual.value;	
	
	ajaxFilhos.setParams('acao', 'get_dados_filhos', 'id_cliente', idMae, 'id_filho', idFilho);
	ajaxFilhos.setParams('id_irmaos', idIrmao, 'visual', visual);
	ajaxFilhos.sendLoad('../sistemas/cadastro/cliente_engine.php', '', setDadosFilhos, 'POST');
}

function setDadosFilhos(dados){
	document.getElementById('table_irmao').innerHTML +=  dados;
	addEventsLink();
	addEventFilhosCpf();
	document.body.style.cursor = '';
	
}

