/*
 * Protótipo da função trim(), para tirar espaços em branco de um string.
 */
String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ''); }

/**
 *
 */
function bloquearAlfa()
{	
	if (event.keyCode < 47 || event.keyCode > 57) {
		event.keyCode = 0;
		return false;
	} else {
		if (event.keyCode == 47) {
			event.keyCode = 0;
			return false;
		}
	}
}

/*
 * Valida se um endereço de e-mail passado como parâmetro é válido.
 */
function validarEmail(pDsEmail)
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(pDsEmail)) {
		return true;
	}

	return false;	
}

/**
 *
 */
function validarCPF(pNrCPF)
{
	pNrCPF = pNrCPF.replace('.', '');
	pNrCPF = pNrCPF.replace('.', '');
	pNrCPF = pNrCPF.replace('.', '');
	pNrCPF = pNrCPF.replace('-', '');
	pNrCPF = pNrCPF.replace('-', '');
	pNrCPF = pNrCPF.replace('-', '');

	if ( pNrCPF.length != 11 || pNrCPF == "00000000000" || pNrCPF == "11111111111" ||
	     pNrCPF == "22222222222" || pNrCPF == "33333333333" || pNrCPF == "44444444444" ||
	     pNrCPF == "55555555555" || pNrCPF == "66666666666" || pNrCPF == "77777777777" ||
	     pNrCPF == "88888888888" || pNrCPF == "99999999999" ) {
		return false;
	}

	soma = 0;
	for (i = 0; i < 9; i ++) {
		soma += parseInt(pNrCPF.charAt(i)) * (10 - i);
	}
	
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11) {
		resto = 0;
	}
	
	if (resto != parseInt(pNrCPF.charAt(9))) {
		return false;
	}
	
	soma = 0;
	for (i = 0; i < 10; i ++) {
		soma += parseInt(pNrCPF.charAt(i)) * (11 - i);
	}
	
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11) {
		resto = 0;
	}
	
	if (resto != parseInt(pNrCPF.charAt(10))) {
		return false;
	}
	
	return true;
}

/**
 *
 */
function validarCampo(pCampo, pNome)
{
	if (pCampo) {
		if (pCampo.value.trim() == '') {
			alert('O campo "' + pNome + '" deve ser preenchido!');
			pCampo.focus();
			return (false);
		}
	}
	
	return (true);
}

/**
 *
 */
function validarOpcao(pCampo, pNome)
{
	if (pCampo) {
		if (pCampo.selectedIndex == 0) {
			alert('É obrigatória a seleção em ' + pNome + '!');
			pCampo.focus();
			return (false);
		}
	}

	return (true);
}

/**
 *
 */
function validarCheck(pCampo, pNome)
{
	var bSelecionado = false;

	for (var i = 0; i < pCampo.length; i++) {
		if (pCampo[i].checked) {
			bSelecionado = true;
		}
	}	

	if (!bSelecionado) {
		alert('É obrigatória a seleção em ' + pNome + '!');
		return (false);
	}

	return (true);
}

/**
 *
 */
function validarNumero(pCampo, pNome)
{
	if (isNaN(pCampo.value) || pCampo.value.length == 0) {
		alert('O conteúdo do campo ' + pNome + ' deve ser numérico!');
		pCampo.focus();
		pCampo.select();
		return (false);
	}

	return (true);
}

/**
 *
 */
function validarData(pCampo, pNome)
{
	var array_data = new Array;
	var ExpReg = new RegExp('(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}');

	array_data = pCampo.value.split('/');
	bErro = false;
	if (pCampo.value.search(ExpReg) == -1) {
		bErro = true;
	} else {
		if (((array_data[1] == 4) || (array_data[1] == 6) || (array_data[1] == 9) || (array_data[1] == 11)) && ( array_data[0] > 30)) {
			bErro = true;
		} else {
			if (array_data[1] == 2) {
				if ((array_data[0] > 28) && ((array_data[2] % 4) != 0)) {
					bErro = true;
				}

				if ((array_data[0] > 29 ) && ((array_data[2] % 4) == 0)) {
					bErro = true;
				}
			}
		}
	}

	if (bErro) {
		alert('O campo ' + pNome + ' contém uma data inválida!');
		pCampo.focus();
		return (false);
	}

	return (true);
}

/**
 *
 */
function validarCEP(pCampo, pNome)
{
	var ExpReg = new RegExp('^[0-9]{5}-[0-9]{3}$');

	if (pCampo.value.search(ExpReg) == -1) {
		alert('O campo ' + pNome + ' contém um CEP inválido!');
		pCampo.focus();
		return (false);
	}

	return (true);
}

/**
 * Troca os marcadores da visão
 */
function swapTwisties(expandir, colapsar)
{
	for (var i in document.images) {
		if (i != 'length') {
			var imagem = document.images[i].src;

			if (imagem != null) {
				if (imagem.indexOf(expandir) != -1) {
	  				document.images[i].setAttribute('src', '/agritech/imagens/mais.gif');
  					document.images[i].setAttribute('width', 12);
  					document.images[i].setAttribute('height', 12);
  				}
  			
	  			if (imagem.indexOf(colapsar) != -1) {
  					document.images[i].setAttribute('src', '/agritech/imagens/menos.gif');
  					document.images[i].setAttribute('width', 12);
  					document.images[i].setAttribute('height', 12); 
	  			}
			}
		}
	}
}

/**
 *
 */
function mostrarCadastro(pExibir)
{
	document.getElementById('spnTelefones').style.display = 'none';
	document.getElementById('spnQuadro').style.display = 'none';	
	document.getElementById(pExibir).style.display = 'block';
}

/**
 *
 */
function mostrarSubCadastro(pExibir)
{
	document.getElementById('spnAdministracao').style.display = 'none';
	document.getElementById('spnVendas').style.display = 'none';
	document.getElementById('spnPecas').style.display = 'none';
	document.getElementById('spnAT').style.display = 'none';
	
	if (pExibir != '') {
		document.getElementById(pExibir).style.display = 'block';
	}
}

/*
 * Recebe uma string (moeda) e retorna um inteiro
 */
function StrToInt(str)
{
	var aux = "";

	if (str == '') {
		return 0;
	}

	aux = str.replace('.','');
	aux = aux.replace('R$','');
	aux = aux.replace(',','.');
	aux = aux.replace(' ','');
	
	return eval(aux);
}

/*
 * Validar somente a entrada de digitos numéricos 
 */
function validarEntradaNumero(campo, decimais, evento)
{  
	var whichCode = (window.Event) ? evento.which : evento.keyCode;	
	var permitidos = decimais ? '0123456789,' : '0123456789';

	key = String.fromCharCode(whichCode);

	if (parseInt(whichCode) < 32){
		return true;
	}
	
	if (permitidos.indexOf(key) < 0) {
		return false;
	}
	
	if (key == ',') {
		if (campo.value.indexOf(',') > -1) {
			return false;
		}
	}
	
	return true;
}

/**
 *
 */
function abrirJanela(url, id, iwidth, iheight)
{
	var sURL = url;
	var frm = document.forms[0];

	if (document.getElementById('SESSION_ID')) {
		sURL += '&SESSIONID=' + document.getElementById('SESSION_ID').value;
	}

	window.open(sURL, id, 'resizable=yes,menubar=no,directories=no,location=no,status=yes,scrollbars=yes,width=' + iwidth + ',height=' + iheight + ',top=30,left=30');
}

/**
 *
 */
function abrirPopup(arquivo, largura, altura, pScroll)
{
	alturaTela = (screen != null ? screen.availHeight : 600);
	larguraTela = (screen != null ? screen.availWidth : 800);
	
	ntop = (alturaTela - altura) / 2;
	nleft = (larguraTela - largura) / 2;

	window.open(arquivo, 'popup_' + (new Date()).getSeconds(), 'width=' + largura + ',height=' + altura + ',status=no,menubar=no,locationbar=no,top=' + ntop + ',left=' + nleft + (pScroll == true ? ',scrollbars=yes' : ''));
}

/**
*
*/
function novajanela(titulo, altura, largura, link)
{
	var conteudo = "<html>";
	conteudo += "<head>";
	conteudo += "<style type='text/css'>";
	conteudo += "body {";
	conteudo += "margin: 0px 0px;";
	conteudo += "padding: 0px 0px;";
	conteudo += "}";
	conteudo += "</style>";
	conteudo +="<title>" + titulo + "</title>";
	conteudo +="</head>"; 
	conteudo +="<body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>";
	conteudo += "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0' width='"+ largura +"' height='"+ altura +"'><param name=movie value='"+ link+ "'><param name=quality value=high><embed src='"+ link +"' width='"+ largura + "' height='"+ altura +"' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash'></embed></object>";	
	conteudo +="</body>";
	conteudo +="</html>";
 	lkwin = window.open("","lkwin","top=25,left=50,width=" + largura + ",height="+ altura +",scrollbars=no");
	lkwin.document.write(conteudo);
}

/**
 * Funções utilizadas nos formulários
 */
function editar() 
{
	if (!botaoClicado) {
		var frm = document.forms[0];

		iPos = window.location.href.indexOf('?', 1);
		url = window.location.href.substring(0, iPos);
		window.location.href = url + '?EditDocument&SESSIONID=' + document.getElementById('SESSION_ID').value;
		botaoClicado = true;
	}
}

/**
 *
 */
function excluir()
{
	if (!botaoClicado && confirm('Confirma a exclusão do registro?')) {
		botaoClicado = true;

    	document.getElementById('Acao').value = 'EXCLUIR';
		document.forms[0].submit();
	}
}

/**
 *
 */
function novo(pURL, id, iwidth, iheight)
{
	var frm = document.forms[0];

	lURL = pURL + '&SESSIONID=' + document.getElementById('SESSION_ID').value;
	abrirJanela(lURL, id, iwidth, iheight);
}

/**
 *
 */
function fechar()
{  
  try {
		window.opener.location.reload();
	} catch(e) {
	}	
	window.close();
}

/**
 *
 */
function pesquisar(pURL)
{
	lURL = pURL + '&SESSIONID=' + document.getElementById('SESSION_ID').value;
	lURL = lURL.replace('//', '/');
	window.open(lURL, '_pesq', 'resizable=no,menubar=no,directories=no,status=yes,scrollbars=no,width=553,height=200,top=30,left=30');
}

/**
 *
 */
function submeterPesquisa(sDBPath, sView, sPalavra, sSessionID, bMesmaJanela)
{
	var sURL;
	var sQuery = (sPalavra != '') ? '+*' + sPalavra + '*+' : '';
	
	if (sQuery.length > 0) {
 		sURL = '/' + sDBPath + '/' + sView + '?SearchView&Query=(' + sQuery + ')&View=' + sView + '&SESSIONID=' + sSessionID;
		sURL = sURL.replace('//', '/');

		if (bMesmaJanela) {
			window.location.href = sURL;
		} else {
			opener.location.href = sURL;
			window.close();
		}
	}
	
	return false;
}

/**
 *
 */
function excluirSelecionados()
{	
	
  if (document.forms[0].check) {
    var check = document.forms[0].check;
  } else {
    alert('Não há documentos selecionados para excluir!');
    return false;
  }
  
  var checados = obterChecados(check);
	
	if (checados == '') {
		alert('Não há documentos selecionados para excluir!');
		return false;
	}

	if (!botaoClicado && confirm("Confirma a remoção dos documentos?")) {
		var sView = document.forms[0].View.value;
		
		iPos = window.location.href.indexOf('nsf', 1);
		url = window.location.href.substring(0, iPos + 3);
		window.location.href = url + '/removerDOCS?OpenAgent&IDS=' + checados + '&VIEW=' + sView + '&SESSIONID=' + document.getElementById('SESSION_ID').value;
		botaoClicado = true;
	}
}

/**
 *
 */
function abrirLink(pLink)
{
	window.location = pLink + '&SESSIONID=' + document.getElementById('SESSION_ID').value;
}

/**
 *
 */
function inverterSelecao(pCampo)
{
	if (pCampo.length) {
		for (var i = 0; i < pCampo.length; i++) {
			pCampo[i].checked = !pCampo[i].checked;
		}
	} else {
		pCampo.checked = !pCampo.checked;
	}
}

/**
 *
 */
function marcarTodos(pCampo, pEstado)
{
	if (pCampo.length) {
		for (var i = 0; i < pCampo.length; i++) {
			pCampo[i].checked = pEstado;
			pCampo[i].disabled = pEstado;
		}
	} else {
		pCampo.checked = pEstado;
		pCampo.disabled = pEstado;
	}
}

/**
 *
 */
function obterChecados(checks)
{
	var listaValores = '';	
    		
	if (checks.length) {
		for (var i = 0; i < checks.length; i++) {
			if (checks[i].checked && checks[i].value != '') {
				if (listaValores == '') {
					listaValores += checks[i].value;
				} else {
					listaValores += ';' + checks[i].value;
				}
			}
		}
	} else {
		if (checks.checked) {
			listaValores = checks.value;
		}
	}

	return (listaValores);
}

/**
 *
 */
function formata(s)
{
	return s.replace(/\n/g, '<br>');
}

/**
 * Segura a barra de id pNome no topo da pagina a uma distancia de pTopo do topo da página
 */  
function seguraBarra(pNome, pTopo)
{
  var y, offset;
  var y1 = pTopo;
  (document.getElementById) ? dom = true : dom = false;

  if (dom && !document.all) {
  	if (document.getElementById(pNome)) {
  		y = window.pageYOffset;
  		offset = (window.innerHeight - (window.innerHeight - y1));
  	
  		if (y > pTopo) {
			offset -= pTopo;
		} else {
			if (y <= pTopo) {
				offset -= y;
			}
		}
  	
  		document.getElementById(pNome).style.top = y + offset;
  	}
  }
  
  if (document.layers) {
  	if (document.layers[pNome]) {
  		y = window.pageYOffset;
  		offset = (window.innerHeight - (window.innerHeight - y1));
  	
  		if (y > pTopo) {
			offset -= pTopo;
		} else {
			if (y <= pTopo) {
				offset -= y;
			}
		}
  	
  		document.layers[pNome].top = y + offset;
  	}
  }
  
  if (document.all) {
  	if (document.all[pNome]) {
  		y = document.body.scrollTop;
  		offset = (document.body.clientHeight - (document.body.clientHeight - y1));
  	
  		if (y > pTopo) {
			offset -= pTopo;
		} else {
			if (y <= pTopo) {
				offset -= y;
			}
		}
  	
  		document.all[pNome].style.top = y + offset;
  	}
  }
  
  window.setTimeout('seguraBarra(\'' + pNome + '\', ' + pTopo + ')', 10);
}

/**
 * Substitui a mensagem de exclusão dos anexos em ingles por uma em portugues
 */ 
function msgExcluirAnexo()
{  
	msg = document.getElementsByTagName('b');  
	msg = msg[msg.length - 1];  
  
	if (!msg) {
		return;
	}
  
	if (msg.innerHTML == 'Mark attachments for deletion') {
	    /*
		 * Substitui a mensagem
	     */     
		msg.innerHTML = '<br><font class="descricao">Marque os anexos que deseja excluir e clique em salvar</font>';
    
	    /*
		 * Tira a linha horizontal
	     */     
		hr = document.getElementsByTagName('hr');    
	    hr[hr.length - 1].style.display = 'none';
    
	    /*
		 * Troca a imagem dos links e coloca os estilos
	     */     
		links = document.getElementsByTagName('a');    
	    for (i = 0; i < links.length; i++) {            
			if (links[i].innerHTML.search('/icons/fileatt.gif') >= 0) {        
				links[i].target = '_blank';
		        links[i].innerHTML = '<img src="/imagens/anexo.gif" border="0" title="Clique para ver o anexo" /><br />';
				links[i+1].target = '_blank';
		        links[i+1].innerHTML = '<font class="descricao">' + links[i+1].innerHTML + '</font>';
			}
		}
    
	    /*
		 * Tira a borda dos checks
	     */     
		checks = document.getElementsByTagName('input');    
	    for (i = 0; i < checks.length; i++) {
			if (checks[i].type == 'checkbox') {
				checks[i].style.border = '0px';      
			}
		}
    
	    /*
		 * Mostra o div com os anexos
	     */    
		document.getElementById('msgAnexo').style.display = 'block'; 
	}
}

/**
 * Volta uma posição no histórico do navegador
 */ 
function voltar()
{    
	history.go(-1);
}

/*
 * Seleciona a opção da combo pCombo com o valor pValor
 */ 
function selecionarOpcao(pValor, pCombo)
{  
  for (var i = 0; i < pCombo.options.length; i++) {
    if (pCombo.options[i].value == pValor) {
      pCombo.selectedIndex = i;
      return;
    }
  }
}

/*
 * Valida caracteres não permitidos de um campo
 */
function validarTexto(pTexto)
{
	if (pTexto == '') {
		return false;
	}
	return true;
}

/**
 * Pesquisa de linhas de produto no site
 */
function buscarLinha(sPath)
{
	var frm = window.document.frmBuscaRapida;
	var sValor = '', sCategoria = '', sLinha = '';
	
	if (frm.buscaRapida.selectedIndex == 0) {
		alert('Selecione a linha desejada!');
		frm.buscaRapida.focus();
		return false;
	}
	
	sValor = frm.buscaRapida[frm.buscaRapida.selectedIndex].value;
	sCategoria = sValor.substring(0, sValor.indexOf('|'));
	sLinha = sValor.substring(sValor.indexOf('|') + 1, sValor.length);
	
	window.open('/' + sPath + '/Template?ReadForm&SECAO=Produtos&CATEGORIA=' + sCategoria + '&LINHA=' + sLinha, '_self');
}

/*
 * Volta para o documento pai (requer campo docParent com ID do documento pai)
 */
function voltarNivel(pView)
{
	if (!botaoClicado) {
		botaoClicado = true;

		iPos = window.location.href.indexOf('nsf', 1);
		url = window.location.href.substring(0, iPos + 3);
		abrirJanela(url + '/' + pView + '/' + document.getElementById('docParent').value + '?OpenDocument', '_self', 800, 600);
	}
}

/*
 *
 */
function removerAcentos(pCampo)
{
   var Acentos = 'áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇ';
   var Traducao = 'aaaaaAAAAeeEEiIoooOOOuuUUcC';
   var Carac, Posic;
   var TempLog = '';

   for (var i = 0; i < pCampo.length; i++) {
		Carac = pCampo.charAt(i);
		Posic = Acentos.indexOf(Carac);

		if (Posic > -1) {
			TempLog += Traducao.charAt(Posic);
		} else {
			TempLog += pCampo.charAt(i);
		}
	}

	return (TempLog);
}

/*
 * Mostra ou esconde o submenu dos produtos
 */
function meSubmenu(pNomeObjeto) {

    // Obtem o ul
    var ulProdutos = document.getElementById(pNomeObjeto);
    
    // Verifica se está sendo mostrado
    if (ulProdutos.style.display == 'none'){
        ulProdutos.style.display = '';
    } else {
        ulProdutos.style.display = 'none';
    }
} 

/**
 * Mostra  ou esconde os links para outros websites
 */
function mostraSelect(pNomeDIVSelect) {
	var lSelect;
	lSelect = document.getElementById(pNomeDIVSelect);
	if (lSelect.style.display == 'none') {
		lSelect.style.display = 'block';
		return true;	
	}
	if (lSelect.style.display == 'block') {
		lSelect.style.display = 'none';
		return true;
	}
}
