// funcoes genericas
jQuery(function($){
	// formata os campos do agendamento de consultas
	$("#data_preferencial").mask("99/99/9999");
	$("#nascimento").mask("99/99/9999");
	$("#fone_residencial").mask("(99) 9999-9999");
	$("#fone_comercial").mask("(99) 9999-9999");
	$("#fone_celular").mask("(99) 9999-9999");
	$("#horario_preferencial").mask("99:99");
});
function calcula_horas(h1,h2){
	// variáveis auxiliares
	var minuto = 60000; 
	var hora = minuto * 60;
	var dt1 = new Date();
	var dt2 = new Date();

	// ajusta o horario de cada objeto Date
	dt1.setHours(h1.substr(0,2));
	dt1.setMinutes(h1.substr(3,2));
	dt1.setSeconds(0);
	dt2.setHours(h2.substr(0,2));
	dt2.setMinutes(h2.substr(3,2));
	dt2.setSeconds(0);
	
	var dif = Math.abs(dt2.getTime() - dt1.getTime());
	return Math.ceil(dif / hora);
}

function troca_fundo(campo,classe){
	if(classe=='')
	campo.className='cor_meio';
	else
	campo.className=classe;
//	alert(campo.className);
}

function valida_email(email){
	//expressão regular...
	ex = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	if ( ex.test(email) ) {
		return true;
	} else {
		return false;
	}
}

function valida_data(data){
	//expressao regular...
	ex = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
	if( ex.test(data)){
		return true;
	}else{
		return false;
	}
}

function valida_hora(hora){
	//expressao regular...
	ex = /^([0-1]\d|2[0-3]):[0-5]\d$/;
	if( ex.test(hora)){
		return true;
	}else{
		return false;
	}
}
function valida_cep(cep){
	//expressao regular...
	ex = /^[0-9]{5}-[0-9]{3}$/
	if( ex.test(cep)){
		return true;
	}else{
		return false;
	}	
}

function openImg(url) {
   window.open(url,'Imagem','toolbar=0,menubar=0,location=0,resizable=1,scrollbars=1,width=50,height=50,left=0,top=0');
}

function valida_moeda(moeda){
	//expressao regular...
	ex = /^([0-9]+),[0-9]{2}$/
	if( ex.test(moeda)){
		return true;
	}else{
		return false;
	}	
}


function confirmacao(msg){
	var agree = confirm(msg);
	if(agree)
		return true;
	else
		return false;
}

function setFocus()	{
	if (document.login.usuario.value == "") {
		document.login.usuario.focus();
	} else {
		document.login.senha.focus();
	}
}

// verifica se é um numero inteiro
function confirma_se_numero(num){
	ex = /^([0-9]+)$/
	if(ex.test(num)){
		return true;
	}else{
		return false;
	}			
}

function seleciona_campos(valor_campo) {
	for (var i = 0; i < document.forms[0].subgrupo.length; i++) {
	  if(document.forms[0].subgrupo.options[i].value == valor_campo){
		  document.forms[0].subgrupo.options[i].selected=true
	  }
   }
}

//onKeyUp='contaCaracteres(500,this);'
function contaCaracteres(limite,nome_formulario,campo_contado) {
	intCaracteres = limite - campo_contado.value.length;
	if (intCaracteres > 0) {
		eval("document."+nome_formulario+".caracteres_restantes.value = "+intCaracteres+";");
		return true;
	} else {
		eval("document."+nome_formulario+".caracteres_restantes.value = "+0+";");
		campo_contado.value = campo_contado.value.substr(0,limite);
	return false;
	}
}

function limpa_campo(campo,texto_default){
	if (campo.value == texto_default)
		campo.value = "";
}

function abre(qual){	
	if(document.getElementById(qual).style.display=="none"){		
		document.getElementById(qual).style.display="block";
		document.getElementById("sinal_"+qual).innerHTML="<img src=\"imagens/icn_rec_servico.gif\" border=\"0\" alt=\"Abrir\" title=\"expandir\" width=\"11\" height=\"11\">";		
	}else{
		document.getElementById(qual).style.display="none";
		document.getElementById("sinal_"+qual).innerHTML="<img src=\"imagens/icn_exp_servico.gif\" border=\"0\" alt=\"Fechar\" title=\"expandir\" width=\"11\" height=\"11\">";		
	}
}

function addFav(url,title){
//    var url   = "http://www.dcavalo.com";
//    var title = "Dcavalo - Sua loja na internet";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

function diferenca_entre_datas(datainicial,datafinal){
	dia1=datainicial.substr(0,2);
	mes1=datainicial.substr(3,2);
	ano1=datainicial.substr(6,4);
	dia2=datafinal.substr(0,2);
	mes2=datafinal.substr(3,2);
	ano2=datafinal.substr(6,4);
	
	objinicial=new Date(ano1,mes1,dia1);
	objfinal=new Date(ano2,mes2,dia2);

	diff= objfinal - objinicial;

	nrodias= diff / 86400000;
	return nrodias;
}

/**
 * Checks/unchecks all checkboxes
 *
 * @param   string   the form name
 * @param   atring   the name of the array with the checlboxes
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always true
 */
function setCheckboxes(the_form, the_checkboxes, do_check)
{
    var elts      = (the_checkboxes != '')
                  ? document.forms[the_form].elements[the_checkboxes + '[]']
                  : document.forms[the_form].elements;
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked        = do_check;
    } // end if... else

    return true;
} // end of the 'setCheckboxes()' function

function abrir_popup_impressao(opcao,id){	
	window.open("versao_impressao.php?opcao="+opcao+"&id="+id,'popImpressao', 'width=800, height=600,top=100,left=100,resizable=1,status=0,menubar=1,scrollbars=1');
}

function abrir_popup_enviar_amigo(opcao,id){	
	window.open("enviar_amigo.php?opcao="+opcao+"&id="+id,'popImpressao' , 'width=450, height=470,top=100,left=100,resizable=1,status=0,menubar=0,scrollbars=1');
}
		
// ajax para cidades
function Dados(valor,o_que, marcado) {
	//verifica se o browser tem suporte a ajax
	try {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			}
			catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				ajax = null;
			}
		}
	}
	
	//se tiver suporte ajax
	if(ajax) {
		//deixa apenas o elemento 1 no option, os outros são excluídos
		document.forms[0].subgrupo.options.length = 1;

		idOpcao  = document.getElementById("opcoes");
		//arquivo xml
		if (o_que == "traz_classes" || o_que == "traz_cidades_cad"){
			arquivo="../gera_xml.php";
		}else{
			arquivo="gera_xml.php";
		}
		ajax.open("POST", arquivo, true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		
		ajax.onreadystatechange = function() {
			//enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
				idOpcao.innerHTML = "Carregando...";   
			}
			//após ser processado - chama função processXML que vai varrer os dados
			if(ajax.readyState == 4 ) {
				if(ajax.responseXML) {				   
					processXML(ajax.responseXML,marcado);
				}
				else {
				//caso não seja um arquivo XML emite a mensagem abaixo
				idOpcao.innerHTML = "--Primeiro selecione uma opção acima--";
				}
			}
		}
		//passa o código do estado escolhido
		var params = "grupo="+valor+"&traz="+o_que;
		ajax.send(params);
	}
}
	
function processXML(obj,marcado){
	//pega a tag cidade
	var dataArray   = obj.getElementsByTagName("subgrupo");
	
	//total de elementos contidos na tag cidade
	if(dataArray.length > 0) {
		//percorre o arquivo XML paara extrair os dados
		for(var i = 0 ; i < dataArray.length ; i++) {
			var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
	
			idOpcao.innerHTML = "--Selecione uma das opções abaixo--";
	
			//cria um novo option dinamicamente
			var novo = document.createElement("option");
			//atribui um ID a esse elemento
			novo.setAttribute("id", "opcoes");
			//atribui um valor
			novo.value = codigo;
			//atribui um texto
			novo.text  = descricao;
			//finalmente adiciona o novo elemento
			document.forms[0].subgrupo.options.add(novo);
		}
		if(marcado != 0){
			seleciona_campos(marcado);
		}
	}
	else {
		//caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Selecione outra opção acima--";
	}	  
}
// fim ajax para cidades

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
	target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
	target.style.MozUserSelect="none"
else //All other route (ie: Opera)
	target.onmousedown=function(){return false}
target.style.cursor = "default"
}

//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"


function bloqueia_clique_direito(){
	var isNS = (navigator.appName == "Netscape") ? 1 : 0;
	var EnableRightClick = 0;
	if(isNS)
	document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
	function mischandler(){
	if(EnableRightClick==1){ return true; }
	else {return false; }
	}
	function mousehandler(e){
	if(EnableRightClick==1){ return true; }
	var myevent = (isNS) ? e : event;
	var eventbutton = (isNS) ? myevent.which : myevent.button;
	if((eventbutton==2)||(eventbutton==3)) return false;
	}
	function keyhandler(e) {
	var myevent = (isNS) ? e : window.event;
	if (myevent.keyCode==96)
	EnableRightClick = 1;
	return;
	}
	document.oncontextmenu = mischandler;
	document.onkeypress = keyhandler;
	document.onmousedown = mousehandler;
	document.onmouseup = mousehandler;
}