// funcoes genericas

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());

	if(HORA_INTEIRA==true)
		return Math.ceil(dif / hora);
	else
		return dif / minuto;
}
function troca_fundo(campo,classe){
	if(classe=='')
	campo.className='cor_meio';
	else
	campo.className=classe;
}
function confirma_se_numero(num){
	ex = /^([0-9]+)$/
	if(ex.test(num))
		return true;
	else
		return false;
}
function valida_email(email){
	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){
	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){
	ex = /^([0-1]\d|2[0-3]):[0-5]\d$/;
	if( ex.test(hora))
		return true;
	else
		return false;
}
function valida_cep(cep){
	ex = /^[0-9]{5}-[0-9]{3}$/
	if( ex.test(cep))
		return true;
	else
		return false;
}
function valida_moeda(moeda){
	ex = /^([0-9]+),[0-9]{2}$/
	if( ex.test(moeda))
		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 confirmacao(msg){
	var agree = confirm(msg);
	if(agree)
		return true;
	else
		return false;
}
function confirma_excluir(id){
	if (confirmacao("Tem certeza que deseja apagar esta ordem de serviço?") == true)
		window.location.href = "realizar.php?id="+id+"&executar=apagar";
}
function ed(id){
	window.location.href = "edita.php?id="+id;
}
function io(id){
	window.location.href = "imprime_os.php?id="+id;
}
function vi(id){
	window.location.href = "visualizar.php?id="+id;
}

function setFocus()	{
	if(document.login.codigo != null){
		if (document.login.codigo.value == "") 
			document.login.codigo.focus();
		else{
			if (document.login.usuario.value == "")
				document.login.usuario.focus();
			else
				document.login.senha.focus();
		}
	}else{
		if (document.login.usuario.value == "")
			document.login.usuario.focus();
		else
			document.login.senha.focus();
	}
}
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){
	if (campo.value == "Digite aqui sua mensagem.") {
		campo.value = "";
	}
}
function show_defeito(info){
	document.getElementById(info).style.display='block';
}
function hide_defeito(info){
	document.getElementById(info).style.display='none';
}

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 imprime(){
	window.print();
}
function addFav(url,title){
    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;
        }
    } else {
        elts.checked        = do_check;
    }

    return true;
}
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=500, height=445,top=100,left=100,resizable=1,status=0,menubar=0,scrollbars=1');
}
function abrir_produtos_os(id){	
	window.open("produtos.php?id="+id,'popProdutos', 'width=754, height=350,top=100,left=100,resizable=1,status=0,menubar=0,scrollbars=1' );
}
function pinta_cor(formulario,campo,cor){
	campo = eval ( "formulario."+campo+";");
	campo.value=cor;
	campo.style.backgroundColor = cor;
}

function try_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;
			}
		}
	}
	return ajax;
}


function Dados(valor,o_que, marcado) {
	ajax = try_ajax();	
	//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

		switch(o_que){
			case "traz_classes":
				arquivo="../gera_xml.php";
			break;
			case "traz_cidades_cad":
				arquivo="../includes/cidades_"+valor+".xml";
			break;
			case "traz_cidades":
				arquivo="includes/cidades_"+valor+".xml";
			break;
			case "traz_estados":
				arquivo="includes/estados.xml";
			break;
			default:
				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--";
	}	  
}


function Dados_do_cliente(valor,marcado) {	
	ajax = try_ajax();
	//se tiver suporte ajax
	if(ajax) {
		var cod = document.forms[0].codigo_cliente;
		var cli = document.forms[0].cliente;
		var end = document.forms[0].endereco;
		var tel = document.forms[0].telefone;
		var bai = document.forms[0].bairro;
		var ema = document.forms[0].email;
		var cont = document.forms[0].contato;
		var grupo = document.forms[0].grupo;
		var est_r = document.forms[0].estado_reserva;
		var cid_r = document.forms[0].cidade_reserva;
		arquivo="xml_dados_clientes.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) {
				if (cod != null) cod.value = "Carregando...";   
				if (cli != null) cli.value = "Carregando...";   
				if (end != null) end.value = "Carregando...";   
				if (tel != null) tel.value = "Carregando...";   
				if (bai != null) bai.value = "Carregando...";   
				if (ema != null) ema.value = "Carregando...";
				if (cont != null) cont.value = "Carregando...";
			}
			//após ser processado - chama função processXML que vai varrer os dados
			if(ajax.readyState == 4 ) {
				if(ajax.responseXML) {
					processXML_clientes(ajax.responseXML,marcado);
				}else{
					if (cod != null){
						cod.value = '';
						cod.readOnly=false;
					}
					if (cli != null){
						cli.value = '';
						cli.readOnly=false;
					}
					if (end != null){
						end.value = '';
						end.readOnly=false;
					}
					if (tel != null){
						tel.value = '';
						tel.readOnly=false;
					}
					if (bai != null){
						bai.value = '';
						bai.readOnly=false;
					}
					if (ema != null){
						ema.value = '';
						ema.readOnly=false;
					}
					if (cont != null){
						cont.value = '';
						cont.readOnly=false;
					}
					if (est_r != null){
						est_r.value = '';
						
					}
					if (cid_r != null){
						cid_r.value = '';
						
					}
					if (grupo != null){
						if (grupo.type == 'text'){
							grupo.value = '';
							document.forms[0].subgrupo.value='';
						}else{
							grupo.options[0].selected=true;
							Dados(0,'traz_cidades',0);
							grupo.removeAttribute("disabled");
							document.forms[0].subgrupo.removeAttribute("disabled");
						}
					}
				}
			}
		}
		//passa o código do estado escolhido
		var params = "id_cliente="+valor;
		ajax.send(params);
	}
}
	
function processXML_clientes(obj,marcado){
	/***VARIAVEIS PARA NAO PRECISAR DIGITAR TODO O NOME DO CAMPO DO FORMULARIO  E TESTES*****/
	var cod = document.forms[0].codigo_cliente;
	var cli = document.forms[0].cliente;
	var end = document.forms[0].endereco;
	var tel = document.forms[0].telefone;
	var bai = document.forms[0].bairro;
	var ema = document.forms[0].email;
	var cont = document.forms[0].contato;
	var grupo = document.forms[0].grupo;
	var est_r = document.forms[0].estado_reserva;
	var cid_r = document.forms[0].cidade_reserva;	
	var dataArray   = obj.getElementsByTagName("grupo");
	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_cliente")[0].firstChild.nodeValue;
			var nome	  =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
			var telefone  =  item.getElementsByTagName("telefone")[0].firstChild.nodeValue;
			var bairro 	  =  item.getElementsByTagName("bairro")[0].firstChild.nodeValue;
			var endereco  =  item.getElementsByTagName("endereco")[0].firstChild.nodeValue;
			var email	  =  item.getElementsByTagName("email")[0].firstChild.nodeValue;
			var contato	  =  item.getElementsByTagName("contato")[0].firstChild.nodeValue;
			var estado	  =  item.getElementsByTagName("estado")[0].firstChild.nodeValue;
			var cidade    =  item.getElementsByTagName("cidade")[0].firstChild.nodeValue;
			
			if (cod != null){
				if(codigo==' ')
					codigo='';
				cod.value = codigo;
				cod.readOnly=true;
			}
			if (cli != null){
				if(nome==' ')
					nome='';
				cli.value = nome;
				cli.readOnly=true;
			}
			if (end != null){
				if(endereco==' ')
					endereco='';
				end.value = endereco;
				end.readOnly=true;
			}
			if (tel != null){
				if(telefone==' ')
					telefone='';
				tel.value = telefone;
				tel.readOnly=true;
			}
			if (bai != null){
				if(bairro==' ')
					bairro='';
				bai.value = bairro;
				bai.readOnly=true;
			}
			if (ema != null){
				if(email==' ')
					email='';
				ema.value = email;
				ema.readOnly=true;
			}
			
			if (cont != null){
				if(contato==' ')
					contato='';
				cont.value = contato;
			}
			
			if (est_r != null)
				est_r.value = estado;
			
			if (cid_r != null)
				cid_r.value = cidade;
			
			if (grupo != null){
				if (grupo.type == 'text'){
					grupo.value = estado.toUpperCase();
					PegaCidadePeloCodigo( estado , cidade , function( t ){
						document.forms[0].subgrupo.value=t;
					});					
				}else{
					grupo.value = estado;
					Dados(estado,'traz_cidades',cidade);
					grupo.setAttribute("disabled","disabled");
					document.forms[0].subgrupo.setAttribute("disabled","disabled");
				}
			}
		}
		if(marcado != 0)
			seleciona_campos(marcado);
	}else {
		//caso o XML volte vazio, printa a mensagem abaixo
		if (cod != null){
			cod.value = '';
			cod.readOnly=false;
		}

		if (cli != null){
			cli.value = '';
			cli.readOnly=false;
		}
		if (end != null){
			end.value = '';
			end.readOnly=false;
		}
		if (tel != null){
			tel.value = '';
			tel.readOnly=false;
		}
		if (bai != null){
			bai.value = '';
			bai.readOnly=false;
		}
		if (ema != null){
			ema.value = '';
			ema.readOnly=false;
		}
		if (cont != null)
			cont.value = '';

		if (est_r != null)
			est_r.value = '';
			
		if (cid_r != null)
			cid_r.value = '';
		
		if (grupo != null){
			if (grupo.type == 'text'){
				grupo.value = '';
				document.forms[0].subgrupo.value = '';
			}else{
				grupo.options[0].selected=true;
				Dados(0,'traz_cidades',0);
				grupo.removeAttribute("disabled");
				document.forms[0].subgrupo.removeAttribute("disabled");
			}
		}
	}	  
}



/***********************************************
* 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;
}
function mostra_div_opcao_os(ID_CHECK){
	eval("	if(document.getElementById('div_"+ID_CHECK+"')!=null){		if(document.getElementById('chec_"+ID_CHECK+"').checked==true)			document.getElementById('div_"+ID_CHECK+"').style.display='block';		else document.getElementById('div_"+ID_CHECK+"').style.display='none';	}");
}