/*
	Algumas das funções usadas na página solicitacaopp.php dependem de variáveis definidas na própia página.
	Essas variáveis são definidas lá pois dependem do PHP para definí-las, ou seja, seu valor inicial varia.
*/
var col = 255;
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
var arrInput = new Array(0);
var arrInputValue = new Array(0);
var etapa = '';
var navegador = navigator.userAgent.toLowerCase();
var xmlhttp;

function fadein()
{
	document.getElementById("fade").style.color="rgb(" + col + "," + col + "," + col + ")";
	col-=3;
	if(col>0) setTimeout('fadein()', 50);
	else setTimeout('fadeout()', (255 / 3)* 100);
}

function fadeout()
{
	document.getElementById("fade").style.color="rgb(" + col + "," + col + "," + col + ")";
	col+=3;
	if(col<255) setTimeout('fadeout()', 50);
}

function focusativacao()
{
	alterasenha.senha.focus();
	alterasenha.senha.select();
}

function focussenhaemail()
{
	senhaemail.email.focus();
	senhaemail.email.select();
}

function focusopcoesnome()
{
	alteranome.nome.focus();
	alteranome.nome.select();
}

function focusopcoessenha()
{
	alterasenha.atual.focus();
	alterasenha.atual.select();
}

function focuslogon(erroemail)
{
	if (erroemail == true)
	{
		logon.logonemail.focus();
		logon.logonemail.select();
	}
	else
	{
		if (logon.logonemail.value == '')
		{
			logon.logonemail.focus();
			logon.logonemail.select();
		}
		else
		{
			logon.logonsenha.focus();
			logon.logonsenha.select();
		}
	}
}

function alteraemail(email, marcar)
{
	if (marcar == true && senhaemail.email.value != email)
		senhaemail.email.value = email;
	else if (marcar == false && senhaemail.email.value == email)
		senhaemail.email.value = '';
}

function alteraemail2(email)
{
	if (senhaemail.elements[2].checked == true)
		senhaemail.elements[3].checked = true;
}

function focuscliente()
{
	cadastrousuario.email.focus();
	cadastrousuario.email.select();
}

function focuscadastrousuarios()
{
	cadastrousuarios.codigo.focus();
	cadastrousuarios.codigo.select();
}

function numeros()
{
	var keypress = window.event.keyCode;
	if ((keypress != 13 && keypress < 48) || keypress > 57 )
		return false;
	else
		return true;
}

function autotab(input,len, e)
{
	function containsElement(arr, ele)
	{
		var found = false, index = 0;
		while(!found && index < arr.length)
		{
			if(arr[index] == ele)
				found = true;
			else
				index++;
		}
		return found;
	}
	
	function getIndex(input)
	{
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
		{
			if (input.form[i] == input)
				index = i;
			else
				i++;
		}
		return index;
	}
	
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode))
	{
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
	return true;
}

function popup(vUrl,vName,vPosFimX,vPosFimY)
{
	vPosIniX=((screen.availWidth/2)-(vPosFimX/2));
	vPosIniY=((screen.availHeight/2)-(vPosFimY/2));
	window.open(vUrl,vName,'toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=yes,resizable=yes,top='+vPosIniY+',left='+vPosIniX+',width='+vPosFimX+',height='+vPosFimY+'');
}

function validadataDMAHM(DIA, MES, ANO, HORA, MINUTO)
{
	validacao = true;
	dia_mes = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	strlendata = DIA.length + MES.length + ANO.length + HORA.length + MINUTO.length;

	if (ANO != '' && ((ANO > 9999) || (ANO < 1900))) validacao = false;
	if (MES != '' && ((MES > 12) || (MES < 01) || (MES.length < 2))) validacao = false;
	if (DIA != '' && ((DIA > 31) || (DIA < 01) || (DIA.length < 2))) validacao = false;
	if (HORA != '' && ((HORA > 23) || (HORA < 00) || (HORA.length < 2))) validacao = false;
	if (MINUTO != '' && ((MINUTO > 59) || (MINUTO < 00) || (MINUTO.length < 2))) validacao = false;
	if (((DIA == 29 && MES == 2) && ((ANO % 4) != 0)) ||
		((dia_mes[MES - 1] < DIA) && (DIA != 29))) validacao = false;
	if (strlendata < 12) validacao = false;
	
	if (!validacao)
		return validacao;
	else
		return DIA + '/' + MES + '/' + ANO + ' ' + HORA + ':' + MINUTO;
}

function verificaradio(radiogroup)
{
	var valor = '';
	for(var j = 0 ; j < radiogroup.length ; ++j)
	{
		if(radiogroup[j].checked)
		{
			valor = radiogroup[j].value;
			break;
		}
	}
	return valor;
}

	function fs()
	{
		var quando = verificaradio(document.solicitacaopp.quando);
		var clientesolicitante = '';
		if (document.solicitacaopp.clientesolicitante.type != 'hidden')
			clientesolicitante = verificaradio(document.solicitacaopp.clientesolicitante);
		else
			clientesolicitante = document.solicitacaopp.clientesolicitante.value;
		
		var dados = new Array(clientesolicitante, quando, document.solicitacaopp.tipoencomenda.value, 
					document.solicitacaopp.tiposervico.value, document.solicitacaopp.expresso.value);
		for (n = 0; n < dados.length; n++)
		{
			if (dados[n] == '')
			{
				alert(clientesolicitante);
				return false;
			}
		}
		return true;
	}
	
function findasolicitacaopp()
{
	// validando a data e hora para execução
	var data = validadataDMAHM(
			document.solicitacaopp.data0.value, 
			document.solicitacaopp.data1.value, 
			document.solicitacaopp.data2.value, 
			document.solicitacaopp.hora0.value,
			document.solicitacaopp.hora1.value);
	if (!data && document.solicitacaopp.quando[1].checked)
	{
		alert(msg4);
		return false;
	}
	// validando o restante da solicitação
	if (fs())
		document.solicitacaopp.submit();
	else
		alert(msg5);
}

function verificaroteiro()
{
	var prosseguir = true;
	if(document.solicitacaopp.etapa.value >= 3)
	{
		if(document.solicitacaopp.retorno[1].checked &&	document.solicitacaopp.descricaoretorno.value == '')
			prosseguir = false;
		else
			prosseguir = true;
	}

	if (
		prosseguir &&
		document.solicitacaopp.uf.value != '' &&
		document.solicitacaopp.municipio.value != '' &&
		document.solicitacaopp.bairro.value != '' &&
		document.solicitacaopp.endereco.value != '' &&
		document.solicitacaopp.contato.value != '' &&
		document.solicitacaopp.observacoes.value != ''
	)
		prosseguir = true;
	else
		prosseguir = false;

	if (prosseguir)
		return true;
	else
	{
		alert(msg5);
		return false;
	}
}

function addroteiro()
{
	if(verificaroteiro())
		document.solicitacaopp.submit();
}

function findaroteiro()
{
	if(verificaroteiro())
	{
		document.solicitacaopp.etapa.value = 0;
		document.solicitacaopp.submit();
	}
}

function cancelachat(caminho, id, confirma, fecha)
{
	var motivo = '';
	if (id != 0)
	{
		if (confirma == 'true')
		{
			if (confirm('O chat será encerrado e a solicitação será cancelada. Deseja confirmar?'))
			{
				motivo = prompt('Qual o motivo do cancelamento da solicitação?','');
				
				if (motivo != null)
					document.location = caminho + 'principal.php?modo=cancelasolicitacao&solicitacaopp=' + id + '&motivo=' + motivo + '&fecha=' + fecha;
			}
		}
		else
			document.location = caminho + 'principal.php?modo=cancelasolicitacao&solicitacaopp=' + id + '&motivo=' + motivo + '&fecha=' + fecha;
	}
	else
		document.location = caminho + 'principal.php?fecha=' + fecha;
}

function cancelachat2(id, confirma)
{
	var motivo = '';
	if (confirma == 'true')
		var texto = 'O chat será encerrado e a solicitação será cancelada. Deseja confirmar?';
	else
		var texto = 'Deseja realmente encerrar o chat?';
	if (confirm(texto))
	{
		if (confirma == 'true')
		{
			motivo = prompt('Qual o motivo do cancelamento da solicitação?','');
			
			if (motivo != '' && motivo != null)
				document.location = 'listaatendimento.php?modo=cancelasolicitacao&solicitacaopp=' + id + '&motivo=' + motivo;
			else if(motivo != null)
				alert(msg6);
		}
		else
			document.location = 'listaatendimento.php?modo=cancelasolicitacao&solicitacaopp=' + id;
	}
}

function iniciachat()
{
	parent.location = 'chat.php?mensagem=chat';
}

function sematendente()
{
	parent.location = 'principal.php?mensagem=atendentechat';
}

function opcoes(opcao)
{
	switch (opcao)
	{
		/* desativado após mudanças do funcionamento da solicitação de serviços PP
		case 1:
			document.exibirservicos.tipoinicial.value = 'solicitapp';
		break; */
		case 2:
			document.exibirservicos.tipoinicial.value = 'porfatura';
		break;
		case 3:
			document.exibirservicos.tipoinicial.value = 'todas';
			document.exibirservicos.tipo.value = 'pontoaponto';
		break;
		case 4:
			document.exibirservicos.tipoinicial.value = 'todas';
			document.exibirservicos.tipo.value = 'especializadas';
		break;
		case 5:
			document.exibirservicos.tipoinicial.value = 'avancada';
			document.exibirservicos.tipo.value = 'pontoaponto';
		break;
		case 6:
			document.exibirservicos.tipoinicial.value = 'avancada';
			document.exibirservicos.tipo.value = 'especializadas';
		break;
		case 7:
			document.exibirservicos.tipoinicial.value = 'tracking';
			document.exibirservicos.tipo.value = 'especializadas';
		break;
	}
	document.exibirservicos.submit();
}

var timerID = 0;
var tStart  = null;

/*******************************************************
	Timer para página de espera do chat para usuário
*******************************************************/
function UpdateTimer()
{
	if(timerID)
	{
		clearTimeout(timerID);
		clockID  = 0;
	}
	
	if(!tStart)
		tStart   = new Date();
	
	var   tDate = new Date();
	var   tDiff = tDate.getTime() - tStart.getTime();
	
	tDate.setTime(tDiff);
		
	var minutes = tDate.getMinutes();
	var seconds = tDate.getSeconds();
	if (seconds < 10)
		seconds = '0' + seconds;
		
	document.timer.tempo.value = minutes + ":" + seconds;
	  
	timerID = setTimeout("ut()", 1000);
}

function ut()
{
	timerID = setTimeout("UpdateTimer()", 0);
}
	
function StartTimer()
{
   tStart = new Date();
   document.timer.tempo.value = "0:00";
   timerID  = setTimeout("UpdateTimer()", 1000);
}
/*******************************************************
	Fim
*******************************************************/
/*******************************************************
	Timer para página com lista de usuários a atender
*******************************************************/
function UpdateTimer2()
{
	window.frames['verificaatendimento'].location.reload();
	timerID = setTimeout("ut2()", 10 * 1000);
}

function ut2()
{
	timerID = setTimeout("UpdateTimer2()", 0);
}
	
function StartTimer2()
{
	timerID  = setTimeout("UpdateTimer2()", 10 * 1000);
}
/*******************************************************
	Fim
*******************************************************/

/*******************************************************
	Timer para página do chat
*******************************************************/
function UpdateTimer3()
{
	window.frames['verifica'].location.reload();
	  
	timerID = setTimeout("ut3()", 10 * 1000);
}

function ut3()
{
	timerID = setTimeout("UpdateTimer3()", 0);
}
	
function StartTimer3()
{
   timerID  = setTimeout("UpdateTimer3()", 10 * 1000);
}
/*******************************************************
	Fim
*******************************************************/

function calculasobra(campo) 
{
	var campo1 = document.solicitacaopp.observacoes;
	var campo2 = document.solicitacaopp.descricaoretorno;
	var contador = document.solicitacaopp.contador;
	var maxlimit = 244; // 255 (total) - 11 (' Retornar: ')
	// corta o texto se for muito longo
	if ((campo1.value.length + campo2.value.length) > maxlimit)
	{
		if(campo == campo1)
		{
			campo1.value = campo1.value.substring(0, (maxlimit - campo2.value.length));
		}
		else if(campo == campo2)
		{
			campo2.value = campo2.value.substring(0, (maxlimit - campo1.value.length));
		}
	}
	contador.value = maxlimit - (campo1.value.length + campo2.value.length);
}

function montapedidocadastro(empresa) 
{
	var antigo, pessoa;
	
	if (document.pedidocadastro.antigo[0].checked)
	{
		antigo = 'sim';
	}
	else if (document.pedidocadastro.antigo[1].checked)
	{
		antigo = 'nao';
	}

	if (document.pedidocadastro.pessoa[0].checked)
	{
		pessoa = 'fisica';
	}
	else if (document.pedidocadastro.pessoa[1].checked)
	{
		pessoa = 'juridica';
	}

	if (antigo && pessoa)
	{
		document.location = 'pedidocadastro.php?antigo=' + antigo + '&pessoa=' + pessoa + '&empresa=' + empresa;
	}
}

function voltalistaatendimento()
{
	document.location = 'listaatendimento.php?naoredireciona=true';
}

function wait()
{
	top.document.getElementById('opaco').style.visibility = 'visible';
}

function done()
{
	top.document.getElementById('opaco').style.visibility = 'hidden';
}

function atualiza()
{
	wait();
	window.frames['verificaatendimento'].location.reload();
}

// quando atendente clica em mudar status, antes de confirmar
function status1()
{
	wait();
	document.getElementById('menustatus').style.visibility = 'visible';
	window.frames['verificaatendimento'].location.reload();	
	
	top.menustatus = true;
}

// quando realmente fica disponível
function status2()
{
	wait();
	window.frames['mudastatus'].location = 'status.php?status=0';
}

// quando realmente fica indisponível
function status3()
{
	wait();
	window.frames['mudastatus'].location = 'status.php?status=1';
}

// quando desiste de ficar indisponível
function status4()
{
	document.getElementById('menustatus').style.visibility = 'hidden';
	
	menustatus = false;
}

// quando a página carrega e deve mostrar o status atual
function status5(stt)
{
	if (stt == 0)
	{
		top.document.getElementById('status').innerHTML = '<span style="color:#00CC00; font-weight:bold;">Dispon&iacute;vel</span> (<a href="javascript:status1();">mudar</a>)';
	}
	else if (stt == 1)
	{
		top.document.getElementById('menustatus').style.visibility = 'hidden';
		top.document.getElementById('status').innerHTML = '<span style="color:#CC0000; font-weight:bold;">Indispon&iacute;vel</span> (<a href="javascript:status2();">mudar</a>)';
		
		top.menustatus = false;
	}
	done();
}

// atualiza a informação da página listaatendimento.php com os atendimentos pendentes e em aberto
function display()
{
	top.window.frames['verifica2'].document.getElementById('conteudo').innerHTML = top.window.frames['verificaatendimento'].document.getElementById('verifica2').innerHTML;
	top.window.frames['verifica3'].document.getElementById('conteudo').innerHTML = top.window.frames['verificaatendimento'].document.getElementById('verifica3').innerHTML;
	display2();
}

// atualiza os clientes que estão cadastrando serviços e os demais atendentes disponíveis
function display2()
{
	if(top.menustatus == true)
	{
		top.window.frames['verifica4'].document.getElementById('conteudo').innerHTML = top.window.frames['verificaatendimento'].document.getElementById('verifica4').innerHTML;
		top.window.frames['verifica5'].document.getElementById('conteudo').innerHTML = top.window.frames['verificaatendimento'].document.getElementById('verifica5').innerHTML;
	}
		
	done();
}

function posicaoespera(posicao)
{
	top.document.timer.posicao.value = posicao + "ª pessoa";
}

function novaativacao()
{
	document.alteracaousuario.modo.value = 'senhaemail2';
	document.alteracaousuario.submit();
}

function mensagemativacao()
{
	document.alteracaousuario.modo.value = 'senhaemail3';
	document.alteracaousuario.submit();
}

function documentos()
{
	var documentos = document.exibirservicos.documentos.value;
	if (documentos)
		window.open(documentos);
	else
		alert('Escolha um documento para consultar.');
}

function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
      return opcoes(7);
   }
else
   return true;
}

