//FUNÇÃO BUSCAS------------------------------------------------------------------------------------------------------------------
function ajax(url){
req = null;
// Procura por um objeto nativo (Mozilla/Safari)
if (window.XMLHttpRequest)
	{
	req = new XMLHttpRequest();
	req.onreadystatechange = processReqChange;
	req.open("GET",url,true);
	req.send(null);
	}
// Procura por uma verso ActiveX (IE)
else if (window.ActiveXObject)
	{
	req = new ActiveXObject("Microsoft.XMLHTTP");
	if (req)
		{
		req.onreadystatechange = processReqChange;
		req.open("GET",url,true);
		req.send();
		}
	}
	}
function processReqChange()
	{
	// apenas quando o estado for "completado"
	if (req.readyState == 4)
	{
	// apenas se o servidor retornar "OK"
	if (req.status ==200)
		{
		// procura pela div id="pagina" e insere o conteudo
		// retornado nela, como texto HTML
		document.getElementById('pagina').innerHTML = req.responseText;
	}
else
	{
	alert("Houve um problema ao obter os dados:n" + req.statusText);
	}}}
	
function BuscaProdutoNomeProdutos(valor)
	{
	url="buscas/busca_produto_nome_produtos.php?valor="+valor;
	ajax(url);
	}
function BuscaProdutoCodigoProdutos(valor)
	{
	url="buscas/busca_produto_codigo_produtos.php?valor="+valor;
	ajax(url);
	}	
function BuscaClienteNomeClientes(valor)
	{
	url="buscas/busca_cliente_nome_clientes.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteCPFClientes(valor)
	{
	url="buscas/busca_cliente_cpf_clientes.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteCNPJClientes(valor)
	{
	url="buscas/busca_cliente_cnpj_clientes.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteNome(valor)
	{
	url="buscas/busca_cliente_nome.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteCPF(valor)
	{
	url="buscas/busca_cliente_cpf.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteCNPJ(valor)
	{
	url="buscas/busca_cliente_cnpj.php?valor="+valor;
	ajax(url);
	}
	function BuscaClienteNomeVenda(valor)
	{
	url="buscas/busca_cliente_nome_venda.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteCPFVenda(valor)
	{
	url="buscas/busca_cliente_cpf_venda.php?valor="+valor;
	ajax(url);
	}
function BuscaClienteCNPJVenda(valor)
	{
	url="buscas/busca_cliente_cnpj_venda.php?valor="+valor;
	ajax(url);
	}
function BuscaProdutoCodigo(valor)
	{
	url="buscas/busca_produto_codigo.php?valor="+valor;
	ajax(url);
	}
function GravaProdutoLocacao(valor)
	{ 
	url="insert/grava_locacao.php?valor="+valor;
	ajax(url);
	}
function GravaProdutoVenda(valor)
	{ 
	url="insert/grava_venda.php?valor="+valor;
	ajax(url);
	}
function BuscaFornecedorNomeEntrada(valor)
	{
	url="modulos/entrada_estoque/search_fornecedor_nome.php?valor="+valor;
	ajax(url);
	}
function BuscaFornecedorCPFEntrada(valor)
	{
	url="modulos/entrada_estoque/search_fornecedor_cpf.php?valor="+valor;
	ajax(url);
	}
function BuscaFornecedorCNPJEntrada(valor)
	{
	url="modulos/entrada_estoque/search_fornecedor_cnpj.php?valor="+valor;
	ajax(url);
	}
function GravaProdutoEntrada(valor)
	{ 
	url="modulos/entrada_estoque/grava_produto_entrada.php?valor="+valor;
	ajax(url);
	}	
//POP UP---------------------------------------------------------------------------------------------------
function Operacoes(URL) {
   var width = 800;
   var height = 600;
   var left = 99;
   var top = 99;
   window.open(URL,'estornos', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
}
//ACEITA SOMENTE NUMEROS
function apenasNum(e){
var tecla=(window.event)?event.keyCode:e.which;
if (tecla > 47 && tecla < 58) return true;
else {
if (tecla != 8) return false;
else return true;
}
}
//PULA CAMPOS---------------------------------------------------------------------------------------------------------------------------------------
function exibeValor(nomeCampo, lenCampo, controle)
{
	if ((nomeCampo.value.length == lenCampo) && (checarTabulacao))
	{	
		var i=0;
		for (i=0; i<document.forms[0].elements.length; i++)
		{
			if (document.forms[0].elements[i].name == nomeCampo.name)
			{
				while ((i+1) < document.forms[0].elements.length)
				{
					if (document.forms[0].elements[i+1].type != "hidden")
					{
						document.forms[0].elements[i+1].focus();
						break;
					}
					i++;
				}
				checarTabulacao=false;
				break;
			}
		}
	}
}
	
function stopTabCheck(nomeCampo)
{checarTabulacao=false;}

function startTabCheck()
{checarTabulacao=true;}
//FORMATAÇÃO DE CAMPOS------------------------------------------------------------------------------------------------------------------------------
function MascarasFormatacao(mascara, documento){
  var i = documento.value.length;
  var saida = mascara.substring(0,1);
  var texto = mascara.substring(i)
  
  if (texto.substring(0,1) != saida){
	documento.value += texto.substring(0,1);
  }
  
}
// FUNÇÃO CONVERTE MAIUSCULA-----------------------------------------------------------------------------------------------------------------------
function ConverteMaiuscula(event) {
    var keynum;

    // IE
    if (window.event) {
        keynum = event.keyCode;
    }
    // Netscape/Firefox/Opera
    else if (event.which) {
        keynum = event.which;
    }

    if ((keynum >= 97 && keynum <= 122) || (keynum >= 224 && keynum <= 255)) {
        // converte de acordo com o valor decimal da tecla na tabela ascii    
        keynum = keynum - 32;
        
        // IE
        if (window.event) {
            window.event.keyCode = keynum;
        }
        // firefox e outros que usam o Gecko
        else if (event.which) {
            var newEvent = document.createEvent("KeyEvents");
            newEvent.initKeyEvent("keypress", true, true, document.defaultView,
                        event.ctrlKey, event.altKey, event.shiftKey,
                        event.metaKey, 0, keynum);
            event.preventDefault();
            event.target.dispatchEvent(newEvent);
        }
    }
    
    return true;
}
//FUNÇÃO CAPS LUCK ------------------------------------------------------------------------------------------------------------------------------
function checar_caps_lock(ev) {
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
	if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
		document.getElementById('aviso_caps_lock').style.visibility = 'visible';
	}
	else {
		document.getElementById('aviso_caps_lock').style.visibility = 'hidden';
	}
}

//FORMATA MOEDA ----------------------------------------------------------------------------------------------------------------------------------
function formatar(src, mask)
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var caract = new RegExp(/^[0-9\b]+$/i);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
  {
        src.value += texto.substring(0,1);
  }

    var kCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    var caract = new RegExp(/^[0-9\b]+$/i);
    var caract = caract.test(String.fromCharCode(kCode));

    if(!caract){
        return false;
    }
}
documentall = document.all;
/*
* funo para formatao de valores monetrios retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "" + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency  false, retorna o valor sem apenas com os nmeros. Se  true, os dois ltimos caracteres so considerados as
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){
		/* Elimina os zeros  esquerda
		* a varivel  <i> passa a ser a localizao do primeiro caractere aps os zeros e
		* val2 contm os caracteres (descontando os zeros  esquerda)
		*/

		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;

		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;

		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;

	}
	else{
			/* currency  false: retornamos os valores COM os zeros  esquerda,
			* sem considerar os ltimos 2 algarismos como casas decimais
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}
	return val3;
	}
}


function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatao aps o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {
/*
Previne a ao padro nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente aps o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa funo basicamente altera o  backspace nos input com mscara reais para os navegadores IE e opera.
O IE no detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do cdigo.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessrio para o opera
	obj.value += y;

	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra funo no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ao padro nos navegadores. No estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o cdigo da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave invlida

/*
Concatenamos ao value o keycode de key, se esse for um nmero
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da funo to somente move o cursor para o final no opera. Atualmente no existe como mov-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}
function clica(id,iderro){
document.getElementById(id).style.background = '';
document.getElementById(iderro).style.display = 'none';
}

function clica2(iderro){
document.getElementById(iderro).style.display = 'none';
}

function clica3(id){
document.getElementById(id).style.display = 'none';
}

function clica4(id){
document.getElementById(id).style.display = '';
}

function clica5(id){
document.getElementById(id).style.background = '';
}

function valida_1(nform){
if (nform.nome.value == ""){
document.getElementById('nome').style.background = '#fcc';
document.getElementById('erro1').style.display = '';
return false
}
if (nform.porcentagem.value == ""){
document.getElementById('porcentagem').style.background = '#fcc';
document.getElementById('erro2').style.display = '';
return false
}
}

function valida_2(nform){
if (nform.codigo.value == ""){
document.getElementById('codigo').style.background = '#fcc';
document.getElementById('erro3').style.display = '';
return false
}
if (nform.produto.value == ""){
document.getElementById('produto').style.background = '#fcc';
document.getElementById('erro4').style.display = '';
return false
}
if (nform.quantidade.value == ""){
document.getElementById('quantidade').style.background = '#fcc';
document.getElementById('erro5').style.display = '';
return false
}
if (nform.preco.value == ""){
document.getElementById('preco').style.background = '#fcc';
document.getElementById('erro6').style.display = '';
return false
}
}

function valida_3(nform) {
	marcado = -1
	for (i=0; i<nform.opcao.length; i++) {
		if (nform.opcao[i].checked) {
			marcado = i
		}
	}
	
	if (marcado == -1) {
		document.getElementById('erro7').style.display = '';
		return false;
	} else {
		window.open('','produtos','resizable=no,height=550,width=680,toolbar=yes,location=no,directories=no,fullscreen=no,menubar=no,scrollbars=yes,status=yes')
		closeMessage()
	} 
		return true;
}

function valida_4(nform){
if (nform.vendedor.value == ""){
document.getElementById('vendedor').style.background = '#fcc';
document.getElementById('erro8').style.display = '';
return false
}
if (nform.porcentagem.value == ""){
document.getElementById('porcentagem').style.background = '#fcc';
document.getElementById('erro9').style.display = '';
return false
}
}

function valida_5(nform){
if (nform.produto.value == ""){
document.getElementById('produto').style.background = '#fcc';
return false
}
if (nform.quantidade.value == "0"){
document.getElementById('quantidade').style.background = '#fcc';
return false
}
if (nform.preco.value == ""){
document.getElementById('preco').style.background = '#fcc';
return false
}
}

function visualiza(idd)
{
var abre = 'vendas_imprimir.php?id='+idd;
window.open(abre,'venda','resizable=no,height=550,width=680,toolbar=yes,location=no,directories=no,fullscreen=no,menubar=no,scrollbars=yes,status=yes');
}

function visualizar(idd)
{
var abre = 'vendas_imprimir.php?id='+idd;
window.open(abre,'venda','resizable=no,height=550,width=680,toolbar=yes,location=no,directories=no,fullscreen=no,menubar=no,scrollbars=yes,status=yes');
closeMessage()
}


function seleciona(valor){
var quebra=valor.split('::');
document.f10.porcentagem.value = quebra[1];
}

function selecionar(valor){

var quebra=valor.split('::');
if (valor == ""){
document.f12.custo.value = '';
} else {
document.f12.custo.value = 'CUSTO: R$ '+quebra[4];
}

document.getElementById('quantidade').style.background = '';
document.getElementById('preco').style.background = '';

var c=document.getElementById("quantidade")
while(c.options.length>0)c.options[0]=null

if (quebra[3]==0){
c.options[c.options.length]=new Option([0],[0])
} else {
for(var i=1;i<=quebra[3];i++){
c.options[c.options.length]=new Option([i],[i])
}
}

}

function confirma() {
if (confirm("Confirma Remover o tem?"))
{
return true;
}
else
return false;
}