//AJAX

/*Funções GERAIS
******************************************************/



function addEvent(obj, evType, fn)
{
    if (obj.addEventListener)
    {
        obj.addEventListener(evType, fn, true);
    }
    if (obj.attachEvent)
    {
        obj.attachEvent("on" + evType, fn);
    }
}

function $O(string){
	return document.getElementById(string);
}

function $V(string){
	return document.getElementById(string).value;
}


function valor_radio(objeto){
	
		
	for(i=0;i<objeto.length;i++){
		if(objeto[i].checked){
			break;
		}
	}
	return objeto[i].value;
}

function valor_radio_novo(string){
	
	objeto=document.all[string];
	
	for(i=0;i<objeto.length;i++){
		if(objeto[i].checked){
			break;
		}
	}
	return objeto[i].value;
}


function marca_radio(objeto,valor){
	
	for(i=0;i<objeto.length;i++){
		if(objeto[i].value==valor){
			objeto[i].checked=true;
		}
	}

}

function desmarca_radio(objeto){
	
	for(i=0;i<objeto.length;i++){
		objeto[i].checked=false;
	}

}

function valida_preenchido(string,mensagem){
	if($V(string)==""){
		if(mensagem.length>0){
			alert(mensagem);
		}
		return false
	}else{
		return true;
	}
}



function valida_multi_select(string,mensagem){

	multiplo=$O(string);
	conta=multiplo.options.length;
	
	selecionado=false;
	
	for(j=0;j<conta;j++){
		if(multiplo.options[j].selected){
			selecionado=true;
		}
	}

	if(!selecionado){
		alert(mensagem);
		return false;
		
	}else{
		
		return true;
		
	}
	
}




function valida_radio(objeto){

	selecionado=false;
	for(i=0;objeto[i]!=null;i++){
		if(objeto[i].checked){
			selecionado=true;
		}
	}

	if(selecionado==true){
		return true;
	}else{
		return false;
	}

}

function valida_radio_novo(string){

	alert(document.element);

	objeto=document.all[string];

	selecionado=false;
	for(i=0;objeto[i]!=null;i++){
		if(objeto[i].checked){
			selecionado=true;
		}
	}

	if(selecionado==true){
		return true;
	}else{
		return false;
	}

}

function valida_checkbox(string){

	selecionado=false;
	for(i=0;$O(string + i)!=null;i++){
		if($O(string + i).checked){
			selecionado=true;
		}
	}

	if(selecionado==true){
		return true;
	}else{
		return false;
	}

}



function troca_campo(quant_carac,objeto,troca){
	trocando=$O(troca);
	if(objeto.value.length>=quant_carac){
		trocando.focus();
	}
}



function currencyFormat(campo, milSep, decSep, e) { 

	fld=document.getElementById(campo);

	var whichCode = "";
	var sep = 0; 
	var key = ''; 
	var i = j = 0; 
	var len = len2 = 0; 
	var strCheck = '0123456789'; 
	var aux = aux2 = ''; 
	if(window.event) // IE
	{
		whichCode = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		whichCode = e.which
	}
	//alert(whichCode);
	//alert(e.keyCode);
	if (whichCode == 13 || whichCode == 0 || whichCode == 8) return true; // Enter 
	key = String.fromCharCode(whichCode); // Get key value from key code 
	if (strCheck.indexOf(key) == -1) return false; // Not a valid key 
	len = fld.value.length; 
	for(i = 0; i < len; i++) 
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; 
		aux = ''; 
	for(; i < len; i++) 
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); 
	aux += key; 
	len = aux.length; 
	if (len == 0) fld.value = ''; 
	if (len == 1) fld.value = '0'+ decSep + '0' + aux; 
	if (len == 2) fld.value = '0'+ decSep + aux; 
	if (len > 2) { 
	aux2 = ''; 
	for (j = 0, i = len - 3; i >= 0; i--) { 
	if (j == 3) { 
	aux2 += milSep; 
	j = 0; 
	} 
	aux2 += aux.charAt(i); 
	j++; 
	} 
	fld.value = ''; 
	len2 = aux2.length; 
	for (i = len2 - 1; i >= 0; i--) 
	fld.value += aux2.charAt(i); 
	fld.value += decSep + aux.substr(len - 2, len); 
	} 
	return false; 
}





//*************************************
//FUNÇÕES PARA VALIDAÇÃO DE FORMULÁRIOS
//*************************************


function validaEmail(id, mensagem_texto)
{
	var item_form = $O(id);
	var er = /^[A-Za-z0-9_.-]+@([A-Za-z0-9_]+\.)+[A-Za-z]{2,4}(\.[A-Za-z]{2})?$/;
	if (er.test(item_form.value))
	{
		return true;
	}
	else
	{
		alert(mensagem_texto);
		item_form.focus();
		return false;
	}
}


function valida_telefone(ddd,numero,mensagem){

	var item_ddd = $O(ddd);
	var item_numero = $O(numero);
	var er = /\d/;


	if(item_ddd.value.length!=2 || !er.test(item_ddd.value)){
		alert("Você precisa preencher o DDD corretamente");
		item_ddd.focus();
		return false;
		
	}else{
		
		if((item_numero.value.length<6 || item_ddd.value.length>8) || !er.test(item_numero.value)){
			alert("Número de telefone inválido");
			item_numero.focus();
			return false;
			
		}
	
	}
	
	return true;

}


function valida_hora(hora,minuto){
	if((!isNaN(hora) && hora>=0 && hora<=23) && (!isNaN(hora) && minuto>=0 && minuto<=59)){
		return true;
	}else{
		return false;
	}
}


function valida_data(dia,mes,ano)
{
	hoje = new Date();
	anoAtual = hoje.getFullYear();
	resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano >= 1900));
	if(mes==2)
	{
		if((ano%4==0 && !(dia>0 && dia<30)) || (ano%4!=0 && !(dia>0 && dia<29)))
		{
			return false;
		}
	}
	if((mes==4 || mes==6 || mes==9  || mes==11) && dia==31){
		return false;
	}
	if (!resultado) {
		
		return false;
		
	}else{
		
		return true;
		
	}
	
}




function validaCNPJ(campo) {
	CNPJ = campo;
	if (CNPJ.length < 14){
		alert("É necessarios preencher corretamente o numero do CNPJ!");
		return false
	}
	
	var nonNumbers = /^\D$/;

	if (nonNumbers.test(CNPJ)){
		alert("A verificacao de CNPJ suporta apenas numeros!");
		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])){
		alert("Digito verificador com problema!");
		return false
	}
	return true;
}



function validacpf(campo){ 

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

	var d1 = 0; 
	
	for (i = 0; i < 9; i++){ 
		d1 += c.charAt(i)*(10-i);
	} 
	
	if (d1 == 0){
		alert("CPF Inválido")
		return false; 
	} 
  
	d1 = 11 - (d1 % 11); 
  
	if (d1 > 9) d1 = 0; 
  
	if (dv.charAt(0) != d1){
		alert("CPF Inválido")
		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){ 
		alert("CPF Inválido");
		return false; 
	} 
  
	return true; 
  
}



function somente_numero(x){
	
	/*var keynum;
	var keychar;
	var numcheck;
	if(window.event) // IE
	{
		keynum = e.keyCode;
		alert('IE '+keynum);
	}
	else if(e.which) // Netscape/Firefox/Opera
	{		
		keynum = e.which;
		alert('Fire '+keynum);
	}*/	
	//alert(keynum);
	
    if(navigator.appName=='Microsoft Internet Explorer'){
       var y=x.keyCode;
    }
    else if(navigator.appName=='Netscape')
    {
       var y=x.which;
    }	
	
	if(y>=48 && y<=57 || y==8 || y==0)
	{
       return true;
    } 
    else 
    {
       return false;
    }		
}

function somente_inteiro(e){
	
	var keynum;
	var keychar;
	var numcheck;
	if(window.event) // IE
	{
	keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
	keynum = e.which
	}
	keychar = String.fromCharCode(keynum)
	numcheck = /^\d$/
	return numcheck.test(keychar);	
	
}


function somente_letra(e){
	
	var keynum;
	var keychar;
	var numcheck;
	if(window.event) // IE
	{
	keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
	keynum = e.which
	}
	keychar = String.fromCharCode(keynum)
	numcheck = /^\d|[+*&¨%$#@!"'-\/\\;:]$/
	return !numcheck.test(keychar);	
	
}



/*Funções de controle de TABELA
******************************************************/
function insere_linha(coluna,objeto,adicional){

	var alvo = document.getElementById(objeto);
	var linha = document.createElement("TR");
	linha.style.cssText = 'background:#ffffff;text-align:center;';
	//linha.setAttribute("bgcolor","#ffffff");
	if(adicional!=""){
		linha.innerHTML=adicional;
	}
	alvo.appendChild(linha);

	var contagem=coluna.length;

	for(i=0;i<contagem;i++){
		var campo = document.createElement("TD");
		campo.innerHTML = coluna[i];
		linha.appendChild(campo);
	}

	linha.appendChild(campo); 

}


function deleta_linha(objeto,div){
	
	coluna=objeto.parentNode.parentNode;
	//alert(coluna.rowIndex);
	var alvo = document.getElementById(div);
	alvo.deleteRow(coluna.rowIndex);

}




function valida_historico(){
	
	
	if(!valida_preenchido("texto_hist","O campo comentário deverá ser preenchido.")){
		$O("texto_hist").focus();
		return false;
	}
	
	if(!valida_radio(document.historico_ajax.confidencial_hist)){
		alert("Você deve selecionar uma opção para confidencial");
		$O("confidencial_hist1").focus();
		return false;
	}
	
	incluir_historico();
	
	return false;
	
}



// montar text para formulario de pesquisa familiar
function insere_txtFilho(id,idDestino){

	var destino =$O(idDestino);
	destino.innerHTML =""; // limpa a div de destinos 
	
	var campo = $O(id);
	var valor = campo.value;
	
	//
	if($O('idadePai').value!="" && $O('idadeMae').value!="" ){
		var con="5";
	}else{
		if ($O('idadePai').value!="" || $O('idadeMae').value!=""){
			var con="6";
		}else{
			alert('Digite a idade do Pai ou da Mãe');
			return false;
		}
	}
	// verefica se o pai ou a mae esta preenchido
	if(valor<=eval(con)){ 
		//cria os objetos na div destino	
		var i;
		for (i=1; i<= valor; i++){
		
			var label=document.createElement("strong");
			label.name="myidname";
	        label.innerHTML=i+" - Filho : ";
			destino.appendChild(label);
		
			var pname=document.createElement("input");
			pname.type="text";
			pname.size="2";
			pname.maxlength="2";
			pname.name = "filho"+i;
			pname.id = "filho"+i;
			pname.setAttribute("onkeypress", "return somente_numero(event)");
			pname.setAttribute("onblur", "buscaPrecoPlano('formInd','valorMinimo','precoPlanoFami.php')");
			destino.appendChild(pname);
			
			var br=document.createElement("br");
			destino.appendChild(br);		
		}
	}else{
		alert('Quantidade de vidas excedidas, o limite de vida esperado é de até '+ con + ' vidas');
	}
}






// url_encode version 1.0  
function url_encode(str) {  
    var hex_chars = "0123456789ABCDEF";  
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
    var n, strCode, hex1, hex2, strEncode = "";  

    for(n = 0; n < str.length; n++) {  
        if (noEncode.test(str.charAt(n))) {  
            strEncode += str.charAt(n);  
        } else {  
            strCode = str.charCodeAt(n);  
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
            hex2 = hex_chars.charAt(strCode % 16);  
            strEncode += "%" + (hex1 + hex2);  
        }  
    }  
    return strEncode;  
}  

// url_decode version 1.0  
function url_decode(str) {  
    var n, strCode, strDecode = "";  

    for (n = 0; n < str.length; n++) {  
        if (str.charAt(n) == "%") {  
            strCode = str.charAt(n + 1) + str.charAt(n + 2);  
            strDecode += String.fromCharCode(parseInt(strCode, 16));  
            n += 2;  
        } else {  
            strDecode += str.charAt(n);  
        }  
    }  
    return strDecode;  
}



fecha=false;
function fechaAnima(como,id,tempo){
	
	objeto = document.getElementById(id);

	if(como=="tempo"){
		if(!fecha){
			tempoFecha=setTimeout("fechaAnima('tempo','"+ id +"',"+ tempo +")",tempo);
			fecha=true;
		}else{
			objeto.style.display="none";
		}
	}else if(como=="agora"){
		objeto.style.display="none";
	}
}

//Função para o Editor 

function baseTiny ( campo , raizInclude )
{
	tinyMCE.init({
			mode : "exact",
			elements : campo,
			theme : "advanced",
			language : "pt_br",	
			plugins : "table,advhr,searchreplace",
			theme_advanced_buttons2_add_before: "cut,copy,paste,pastetext,separator,search,replace,separator",
			theme_advanced_buttons3_add_before : "tablecontrols,separator",
			theme_advanced_buttons4 : "code",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_path_location : "bottom",
			content_css : raizInclude + "editor.css",
			extended_valid_elements : "hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
			external_link_list_url : "example_link_list.js",
			external_image_list_url : "example_image_list.js",
			flash_external_list_url : "example_flash_list.js",
			media_external_list_url : "example_media_list.js",
			template_external_list_url : "example_template_list.js",
			theme_advanced_resize_horizontal : false,
			theme_advanced_resizing : false,
			nonbreaking_force_tab : true,
			apply_source_formatting : true,
			template_replace_values : {
				username : "Jack Black",
				staffid : "991234"
			}
		});
}



addEvent(window, "load", init);
