// funcoes genericas
function AdicionaProdutoAoPedido( selector ){        
	var table = $( selector );        
	if( ! table.get(0) ) return false;
	var tr = table.find('tr.produto:last').clone();
		tr.html( tr.html().replace( /produto\[\d+\]/g , 'produto['+ ( table.find('tr.produto').length*1 + 1) +']') );
	tr.insertAfter( table.find( 'tr.produto:last' ) );
		tr.find( 'td > *' ).each(function(){
			if( this.nodeName == 'INPUT' ) $(this).val('');
			else if( this.nodeName == 'SELECT' ) $(this).find('option:first').attr('selected','selected');
		});            
	return false;
};

function ExcluirLinha( selector , node ){
	var table, total_pedido;
	table        = $( selector );
	total_pedido = 0
	
	if( ! table.get(0) || table.find('tr.produto').length <= 1 ) return false;
	$( node ).parent().parent().remove();

	$( 'input[name*="[total]"]' ).each(function(){
		total_pedido += $( this ).val().replace( '.' , '' ).replace( ',' , '.' )*1;        
	});

	$( '#total_pedido' ).val(  number_format( total_pedido , 2 , ',' , '.')  );
};

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 testa_browser(){
	if ( document.all ) {  
		return true;
	} else if (document.getElementById){  
		alert('Este recurso só pode ser acessado pelo Internet Explorer');
		return false;
	} 
}

function fale_voip(){
	if(testa_browser() == true){
		window.open('http://www.unodistribuidora.com.br/phone/index.php','popup1','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=380,height=420,left=0,top=0');
	}	
}

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}$/;
	ex = /^\d{1,3}(\.\d{3})*\,\d{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
	  }
   }
}

function contaCaracteres(limite,nome_formulario,campo_contado) {
	//onKeyUp='contaCaracteres(500,this);'
	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)-1);
	ano1=datainicial.substr(6,4);
	dia2=datafinal.substr(0,2);
	mes2=(datafinal.substr(3,2)-1);
	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;
}

function setCheckboxes(the_form, the_checkboxes, do_check){
    /**
	 * 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
	 */
	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.toLowerCase()+".xml";
			break;
			case "traz_cidades":
				arquivo="includes/cidades_"+valor.toLowerCase()+".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 Clientes_do_contratante(valor,o_que) {
	ajax = try_ajax();
	//se tiver suporte ajax
	if(ajax) {
		document.forms[0].id_cliente.options.length = 1;
		idOpcao  = document.getElementById("selec_cliente");
		
		//arquivo xml
		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_Clientes_do_contratante(ajax.responseXML);
					Dados_do_cliente(0,0);
				}
				else {
					//caso não seja um arquivo XML emite a mensagem abaixo
					idOpcao.innerHTML = "--Nenhum cliente cadastrado para esse contratante--";
					Dados_do_cliente(0,0);
				}
			}
		}
		//passa o código do estado escolhido
		var params = "grupo="+valor+"&traz="+o_que;
		ajax.send(params);
	}
}
	
function processXML_Clientes_do_contratante(obj){
	//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;
			var habilitado=  item.getElementsByTagName("habilitado")[0].firstChild.nodeValue;
	
			idOpcao.innerHTML = "--Selecione o cliente--";
			
			//cria um novo option dinamicamente
			var novo = document.createElement("option");
			//atribui um ID a esse elemento
			novo.setAttribute("id", "selec_cliente");
			if(habilitado==0)
			novo.setAttribute("style", "background-color:#eee");
			//atribui um valor
			novo.value = codigo;
			//atribui um texto
			novo.text  = descricao;
			//finalmente adiciona o novo elemento
			document.forms[0].id_cliente.options.add(novo);				
		}
	}else {
		//caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Nenhum cliente cadastrado para esse contratante--";
	}	  
}

function Dados_do_cliente(valor,marcado) {
	if(valor==0){
		nao_envia=true;
		document.getElementById('bt_submit').onclick='';
	}else{
		nao_envia=false;
		document.getElementById('bt_submit').onclick=function(){alert('Por favor aguarde carregar os dados do cliente')};
	}
	
	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 grupo          = document.forms[0].grupo;
		var est_r          = document.forms[0].estado_reserva;
		var cid_r          = document.forms[0].cidade_reserva;
		var contato        = document.forms[0].contato;
		var contato_select = document.forms[0].contato_select;
		var email          = document.forms[0].email;
		var celular        = document.forms[0].celular;
		var habilitado     = document.forms[0].cliente_habilitado;
				
		if( contato_select ) $( contato_select ).remove();
		
		$( '<input type="text" name="contato" value="" style="width: 400px;" onblur="fundo_branco(this);">' ).insertAfter( contato );
		$( contato ).remove();
		
		email.value = '';
		
		if( celular ){
			$( celular ).parent().parent().remove();
		}
		
		
		
		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...";   
			}

			//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{
					habilitado.value = ''; //LISTA NEGRA DE CLIENTES
					$('.autoriza_os').hide();
					$('#os_autorizada_login').val('');
					$('#os_autorizada_senha').val('');
					
					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 (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 grupo   = document.forms[0].grupo;
	var est_r   = document.forms[0].estado_reserva;
	var cid_r   = document.forms[0].cidade_reserva;	
	var contato = document.forms[0].contato;	
	var hab     = document.forms[0].cliente_habilitado;	
	

	
	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 estado	  =  item.getElementsByTagName("estado")[0].firstChild.nodeValue;
			var cidade    =  item.getElementsByTagName("cidade")[0].firstChild.nodeValue;
			var contatos  =  item.getElementsByTagName("contato");
			var habilitado=  item.getElementsByTagName("habilitado")[0].firstChild.nodeValue;
			
			
			if(habilitado==' ')
				habilitado='';
			if(habilitado==0)
				$('.autoriza_os').show();
			else{
				$('.autoriza_os').hide();
				$('#os_autorizada_login').val('');
				$('#os_autorizada_senha').val('');
			}
			hab.value = habilitado;
				
			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 (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 (contatos.length > 0){				
				
				$( '<input name="contato" type="hidden" /><select onchange="Dados_do_contato( this.value )" onblur="fundo_branco(this);" style="width: 400px;" name="contato_select"><option value="0">--Selecione uma das opções abaixo--</option></select>' ).insertAfter( contato );
				$( contato ).remove();
				
				for( var i = 0 ; i < contatos.length ; i++ ){
					var item = contatos[i];
					//contéudo dos campos no arquivo XML
					var contato_id      =  item.getElementsByTagName("contato_id"     )[0].firstChild.nodeValue;
					var contato_nome    =  item.getElementsByTagName("contato_nome"   )[0].firstChild.nodeValue;
					var contato_email   =  item.getElementsByTagName("contato_email"  )[0].firstChild.nodeValue;
					var contato_celular =  item.getElementsByTagName("contato_celular")[0].firstChild.nodeValue;
					
					//cria um novo option dinamicamente
					var novo = document.createElement("option");
					//atribui um valor
					novo.value = 'var dados = { "contato_id" : "'+contato_id+'" , "contato_nome" : "' + contato_nome + '" , "contato_email" : "' + contato_email + '", "contato_celular" : "' + contato_celular + '" };';
					//atribui um texto
					novo.text  = contato_nome;
					//finalmente adiciona o novo elemento
					document.forms[0].contato_select.options.add(novo);
				}
			}
		}
		if(marcado != 0)
			seleciona_campos(marcado);
			
		nao_envia=true;
		document.getElementById('bt_submit').onclick='';
	}else {
		//caso o XML volte vazio, printa a mensagem abaixo
		hab.value = '';
		$('#os_autorizada_login').val('');
		$('#os_autorizada_senha').val('');
		$('.autoriza_os').hide();
		
		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 (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");
			}
		}
	}	  
}

function Dados_do_contato( contato_dados ){
	eval( contato_dados ); 
		
	if( document.forms[0].celular ){
		$( document.forms[0].celular ).parent().parent().remove();
	}
	
	jQuery( '<tr><td class="td_esquerda">Celular:</td><td><input type="text" onblur="fundo_branco(this);" style="width: 400px;" value="" name="celular" /></td></tr>' ).insertAfter( $( document.forms[0].email ).parent().parent() );
	
	var contato  = document.forms[0].contato.value = dados.contato_nome;
	var telefone = document.forms[0].celular.value = dados.contato_celular;
	var email    = document.forms[0].email.value    = dados.contato_email;
};

function disableSelection(target){
//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
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"
}

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';	}");
}
