// -------------------------------------------------------------------------------------------
//  Eventos: utilizar esta função para adicionar eventos como onclick, onsubmit, onkeypress, etc.
// -------------------------------------------------------------------------------------------

function adicionaEvento(campo, evento, funcao)
{
	if (campo.addEventListener)
		campo.addEventListener(evento, funcao, true)
	if (campo.attachEvent)
		campo.attachEvent("on"+evento, funcao)
}

// -------------------------------------------------------------------------------------------
//  Cria a função event (source), cria a função this (e) para campos que utilizaram o adicionaEvento
// -------------------------------------------------------------------------------------------

function criaEventAndThis(e)
{
	if(typeof(e)=='undefined')var e=window.event
	source=e.target?e.target:e.srcElement
	if(source.nodeType == 3)source = source.parentNode
}

// -------------------------------------------------------------------------------------------
//  Cria o evento onfocus para todos os campos do formulário da página, se existir formulário
// -------------------------------------------------------------------------------------------

function criaOnFocus()
{
	for (j=0;j<document.forms.length;j++)
	{
		for (var i=0; i<document.forms[j].elements.length; i++)
		{
			if (document.forms[j].elements[i].type == "text" || document.forms[j].elements[i].type == "password" || document.forms[j].elements[i].type == "textarea" || document.forms[j].elements[i].type == "select-one" || document.forms[j].elements[i].type == "file")
			{
				campoForm = document.forms[j].elements[i]
				adicionaEvento(campoForm, "focus", formFoca)
			}
		}
	}
}

// -------------------------------------------------------------------------------------------
//  Cria o evento onblur para todos os campos do formulário da página, se existir formulário
// -------------------------------------------------------------------------------------------

function criaOnBlur()
{
	for (j=0;j<document.forms.length;j++)
	{
		for (var i=0; i<document.forms[j].elements.length; i++)
		{
			if (document.forms[j].elements[i].type == "text" || document.forms[j].elements[i].type == "password" || document.forms[j].elements[i].type == "textarea" || document.forms[j].elements[i].type == "select-one" || document.forms[j].elements[i].type == "file")
			{
				campoForm = document.forms[j].elements[i]
				adicionaEvento(campoForm, "blur", chamaFormDesfoca)
			}
		}
	}
}

// -------------------------------------------------------------------------------------------
//  Formulário: troca a cor e mensagem dos campo quando foca, perde o foco ou dá erro
// -------------------------------------------------------------------------------------------

function formFoca (e)
{
	criaEventAndThis(e)
	source.style.borderColor = "#619261"
	source.style.borderWidth = "2px"
	source.style.color = "#000"
	escondeTexto(source)
}

function formDesfoca (campo, numtexto)
{
	campo.style.borderColor = "#999"
	campo.style.borderWidth = "1px"
	campo.style.color = "#666"
	mostraTexto(campo, numtexto)
}

function desfocaAreaRestrita()
{
	if (source.name == "area_restrita_carteira_cliente")
		formDesfoca(source,'')
	if (source.name == "area_restrita_senha_cliente")
		formDesfoca(source,'')
	if (source.name == "area_restrita_carteira_cooperado")
		formDesfoca(source,'')
	if (source.name == "area_restrita_senha_cooperado")
		formDesfoca(source,'')
	if (source.name == "area_restrita_carteira_credenciado")
		formDesfoca(source,'')
	if (source.name == "area_restrita_senha_credenciado")
		formDesfoca(source,'')
	if (source.name == "area_restrita_usuario_colaborador")
		formDesfoca(source,'')
	if (source.name == "area_restrita_senha_colaborador")
		formDesfoca(source,'')
	if (source.name == "area_restrita_usuario_corretora")
		formDesfoca(source,'')
	if (source.name == "area_restrita_senha_corretora")
		formDesfoca(source,'')
}

function formErro (campo)
{
	campo.style.borderColor = "#B00"
	campo.style.borderWidth = "2px"
	campo.style.color = "#000"
}

function escondeTexto(campo)
{
	for (var i=1; i <= texto.length; i++)
	{
		if (campo.value == texto[i])
		{
			campo.value = ""
		}
	}
}

function mostraTexto(campo, numtexto)
{
	if (campo.value == "" && numtexto != "")
	{
			campo.value = texto[numtexto]
	}
}

function mostraMsgErro(campo,numtexto)
{
	formErro(campo)
	if (campo.name == 'area_restrita_carteira_cliente' || campo.name == 'area_restrita_senha_cliente')
	{
		document.getElementById("msgErroAreaRestritaCliente").innerHTML += "<p>"+ texto[numtexto] +"</p>"
		document.getElementById("msgErroAreaRestritaCliente").style.display = "block"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "none"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "none"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "none"
		if (document.getElementById("formErro"))
			document.getElementById("formErro").style.display = "none"
	}
	else if (campo.name == 'area_restrita_carteira_cooperado' || campo.name == 'area_restrita_senha_cooperado')
	{
		document.getElementById("msgErroAreaRestritaCooperado").innerHTML += "<p>"+ texto[numtexto] +"</p>"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "block"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCliente").style.display = "none"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "none"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "none"
		if (document.getElementById("formErro"))
			document.getElementById("formErro").style.display = "none"
	}
	else if (campo.name == 'area_restrita_carteira_credenciado' || campo.name == 'area_restrita_senha_credenciado')
	{
		document.getElementById("msgErroAreaRestritaCredenciado").innerHTML += "<p>"+ texto[numtexto] +"</p>"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "block"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCliente").style.display = "none"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "none"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "none"
		if (document.getElementById("formErro"))
			document.getElementById("formErro").style.display = "none"
	}
	else if (campo.name == 'area_restrita_usuario_colaborador' || campo.name == 'area_restrita_senha_colaborador')
	{
		document.getElementById("msgErroAreaRestritaColaborador").innerHTML += "<p>"+ texto[numtexto] +"</p>"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "block"
		document.getElementById("msgErroAreaRestritaCliente").style.display = "none"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "none"
		if (document.getElementById("formErro"))
			document.getElementById("formErro").style.display = "none"
	}
	else if (campo.name == 'area_restrita_usuario_corretora' || campo.name == 'area_restrita_senha_corretora')
	{
		document.getElementById("msgErroAreaRestritaCorretora").innerHTML += "<p>"+ texto[numtexto] +"</p>"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "block"
		document.getElementById("msgErroAreaRestritaCliente").style.display = "none"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "none"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "none"
		if (document.getElementById("formErro"))
			document.getElementById("formErro").style.display = "none"
	} else {
		document.getElementById("msgErro").innerHTML += "<p>"+ texto[numtexto] +"</p>"
		document.getElementById("formErro").style.display = "block"
		document.getElementById("msgErroAreaRestritaCliente").style.display = "none"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "none"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "none"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "none"
	}
	falso = 1
}

// -------------------------------------------------------------------------------------------
//  Formulário: funções de validação
// -------------------------------------------------------------------------------------------

function trim(str)
{
	return str.replace(/^\s+|\s+$/g,"")
}

function verificaVazio(campo, numtexto)
{
	if (trim(campo.value) == "" || trim(campo.value) == texto[numtexto])
	{
		mostraMsgErro(campo, numtexto)
	}
}

function verificaVazio2(campo, numtextovalor, numtextomsg)
{
	if (trim(campo.value) == "" || trim(campo.value) == texto[numtextovalor])
	{
		mostraMsgErro(campo, numtextomsg)
	}
}

function verificaNumerico(campo, numtexto)
{
	if (isNaN(campo.value))
	{
		mostraMsgErro(campo, numtexto)
	}
}

function verificaEmail(campo, numtexto)
{
	parte1 = campo.value.indexOf("@")
	parte2 = campo.value.indexOf(".")
	parte3 = campo.value.length
	if (!(parte1 >= 3 && parte2 >= 6 && parte3 >= 9))
	{
		mostraMsgErro(campo, numtexto)
	}
}


function verificaTamanhoMin(campo, minimo, numtexto)
{
	if (campo.value.length < minimo)
	{
		mostraMsgErro(campo, numtexto)
	}
}

function verificaTamanho(campo, tamanho, numtexto)
{
	if (campo.value.length != tamanho)
	{
		mostraMsgErro(campo, numtexto)
	}
}

function verificaData(campo, numtexto)
{
	if (campo.value.length < 10)
	{
		var erro = 1
	}
	var dia = parseInt(campo.value.substr(0,2));
	var mes = parseFloat(campo.value.substr(3,2));
	var ano = parseInt(campo.value.substr(6,4));
	var bisexto = ano % 4;
	var monthMax = new Array(31,31,29,31,30,31,30,31,31,30,31,30,31);

	if(bisexto == 0)
	{
		monthMax[2] = 29;
	}
	else
	{
	  monthMax[2] = 28;
	}
	if (dia > parseInt(monthMax[mes]) || mes > 12 || mes < 1 || campo.value.substr(2,1) != "/" || campo.value.substr(5,1) != "/" || erro == 1)
	{
		mostraMsgErro(campo, numtexto)
	}
}

function mascaraData(e)
{
	criaEventAndThis(e)

    function mascaraDataNumerica(e)
	{
		criaEventAndThis(e)
		var char = source.value.length - 1
		if ((isNaN(source.value.substr(char,1)) && source.value.substr(char,1) != "/") || (source.value.substr(char,1) == "/" && char != 2 && char != 5))
		{
			source.value = source.value.substr(0,char)
		}
	}
	adicionaEvento(source, "keyup", mascaraDataNumerica)
	adicionaEvento(source, "keydown", mascaraDataNumerica)
	
	if (e.keyCode != 8 && e.keyCode != 46)
	{
		if (source.value.length == 2 || source.value.length == 5)
		{
			source.value += "/"
			source.selectionStart++
		}
	}
}

function mascaraNumero(e)
{
	criaEventAndThis(e)
	var char = source.value.length - 1
	if (isNaN(source.value.substr(char,1)))
	{
		source.value = source.value.substr(0,char)
	}
}

// -------------------------------------------------------------------------------------------
//  Formulário: chama validação e mostra mensagem de erro
// -------------------------------------------------------------------------------------------

var texto = new Array()

texto[50] = "Digite o nº da sua carteira"
texto[51] = "Digite a sua senha"
texto[52] = "Digite o nº do seu CRM"
texto[53] = "Digite o seu login"
texto[54] = "Digite a data"
texto[55] = "Data formato: dd/mm/aaaa"
texto[56] = "Carteira deve ser numérica"
texto[57] = "Carteira com 13 dígitos"
texto[58] = "Digite o código Unimed"

function validaForm(form)
{
	falso = 0
	ajax = 0
	ajaxRestrito = 0
	login = ""
	pass = ""
	
	if (document.getElementById("msgErro"))
		document.getElementById("msgErro").innerHTML = ""
	document.getElementById("msgErroAreaRestritaCliente").innerHTML = ""
	document.getElementById("msgErroAreaRestritaCooperado").innerHTML = ""
	document.getElementById("msgErroAreaRestritaColaborador").innerHTML = ""
	document.getElementById("msgErroAreaRestritaCorretora").innerHTML = ""
	document.getElementById("msgErroAreaRestritaCredenciado").innerHTML = ""
	
	if (form.name == "form_area_restrita_cliente")
	{
		verificaVazio2 (document.form_area_restrita_cliente.area_restrita_carteira_cliente,'',50)
		verificaNumerico (document.form_area_restrita_cliente.area_restrita_carteira_cliente,56)
		verificaVazio2 (document.form_area_restrita_cliente.area_restrita_senha_cliente,'',54)
		verificaData (document.form_area_restrita_cliente.area_restrita_senha_cliente,55)
		if (document.form_area_restrita_cliente.area_restrita_carteira_cliente.value.length != 13) mostraMsgErro(document.form_area_restrita_cliente.area_restrita_carteira_cliente,57)
		ajaxRestrito = 3
		login = form.area_restrita_carteira_cliente.value
		pass = form.area_restrita_senha_cliente.value
	}
	else if (form.name == "form_area_restrita_cooperado")
	{
		verificaVazio2 (document.form_area_restrita_cooperado.area_restrita_carteira_cooperado,'',52)
		verificaVazio2 (document.form_area_restrita_cooperado.area_restrita_senha_cooperado,'',51)
		ajaxRestrito = 1
		login = form.area_restrita_carteira_cooperado.value
		pass = form.area_restrita_senha_cooperado.value
	}
	else if (form.name == "form_area_restrita_credenciado")
	{
		verificaVazio2 (document.form_area_restrita_credenciado.area_restrita_carteira_credenciado,'',58)
		verificaVazio2 (document.form_area_restrita_credenciado.area_restrita_senha_credenciado,'',51)
		ajaxRestrito = 5
		login = form.area_restrita_carteira_credenciado.value
		pass = form.area_restrita_senha_credenciado.value
	}
	else if (form.name == "form_area_restrita_colaborador")
	{
		verificaVazio2 (document.form_area_restrita_colaborador.area_restrita_usuario_colaborador,'',53)
		verificaVazio2 (document.form_area_restrita_colaborador.area_restrita_senha_colaborador,'',51)
		ajaxRestrito = 2
		login = form.area_restrita_usuario_colaborador.value
		pass = form.area_restrita_senha_colaborador.value
	}
	else if (form.name == "form_area_restrita_corretora")
	{
		verificaVazio2 (document.form_area_restrita_corretora.area_restrita_usuario_corretora,'',53)
		verificaVazio2 (document.form_area_restrita_corretora.area_restrita_senha_corretora,'',51)
		ajaxRestrito = 4
		login = form.area_restrita_usuario_corretora.value
		pass = form.area_restrita_senha_corretora.value
	}
	else
	{
		validador(form) //fica no arquivo .js da página
	}
	
	if (falso == 1)
	{
		return false
	}
	else
	{
		document.getElementById("msgErroAreaRestritaCliente").style.display = "none"
		document.getElementById("msgErroAreaRestritaCooperado").style.display = "none"
		document.getElementById("msgErroAreaRestritaCredenciado").style.display = "none"
		document.getElementById("msgErroAreaRestritaColaborador").style.display = "none"
		document.getElementById("msgErroAreaRestritaCorretora").style.display = "none"
		if (document.getElementById("formErro"))
			document.getElementById("formErro").style.display = "none"
			
		if (ajax == 1)
		{
			chamaAjax()
			return false
		}
		else if (ajaxRestrito == 1)
		{
			iniciaAjax('http://www.unimedvr.com.br/identificacao/validacao_senha_ajax.php','login='+escape(login)+'&pass='+escape(pass),'validandoAreaRestritaCooperado','AreaRestrita')
			return false
		}
		else if (ajaxRestrito == 2)
		{
			iniciaAjax('http://www.unimedvr.com.br/identificacao/validacao_senha_colaborador_ajax.php','login='+escape(login)+'&pass='+escape(pass),'validandoAreaRestritaColaborador','AreaRestrita')
			return false
		}
		else if (ajaxRestrito == 3)
		{
			iniciaAjax('http://www.unimedvr.com.br/identificacao/validacao_senha_cliente_ajax.php','login='+escape(login)+'&pass='+escape(pass),'validandoAreaRestritaCliente','AreaRestrita')
			return false
		}
		else if (ajaxRestrito == 4)
		{
			iniciaAjax('http://www.unimedvr.com.br/identificacao/validacao_senha_corretora_ajax.php','login='+escape(login)+'&pass='+escape(pass),'validandoAreaRestritaCorretora','AreaRestrita')
			return false
		}
		else if (ajaxRestrito == 5)
		{
			iniciaAjax('http://www.unimedvr.com.br/identificacao/validacao_senha_credenciado_ajax.php','login='+escape(login)+'&pass='+escape(pass),'validandoAreaRestritaCredenciado','AreaRestrita')
			return false
		}
		else
		{
			return true
		}
	
	}
}

// -------------------------------------------------------------------------------------------
//  Acessibilidade: troca o tamanho da fonte e grava em cookie
// -------------------------------------------------------------------------------------------

function aumentaFonte ()
{
	document.getElementById("estrutura").style.fontSize = parseInt(document.getElementById("estrutura").style.fontSize.substr(0,document.getElementById("estrutura").style.fontSize.length - 1)) + 10 + "%"
	criaCookie("fonte", document.getElementById("estrutura").style.fontSize, 365);
}

function diminuiFonte ()
{
	document.getElementById("estrutura").style.fontSize = parseInt(document.getElementById("estrutura").style.fontSize.substr(0,document.getElementById("estrutura").style.fontSize.length - 1)) - 10 + "%"
	criaCookie("fonte", document.getElementById("estrutura").style.fontSize, 365);
}

function restauraFonte ()
{
	document.getElementById("estrutura").style.fontSize = "100%"
	criaCookie("fonte", document.getElementById("estrutura").style.fontSize, 365);
}

function criaCookie (nome,valor,dias)
{
	var date = new Date();
	date.setTime (date.getTime() + (dias*24*60*60*1000));
	var expires = "; expires=" + date.toGMTString();
	document.cookie = nome + "=" + escape(valor) + expires + "; path=/;";
}

function leCookie (nome)
{
	var nameEQ = nome + "=";
	var ca = document.cookie.split(';');
	for (var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ')
		{
			c = c.substring (1,c.length);
		}
		if (c.indexOf(nameEQ) == 0)
		{
			return unescape (c.substring (nameEQ.length,c.length));
		}
	}
	return null;
}

function utilizaCookie()
{
	var tamanho = leCookie ("fonte");
	if (tamanho != null)
	{
		document.getElementById("estrutura").style.fontSize = tamanho
	}
	else
	{
		document.getElementById("estrutura").style.fontSize = "100%"
	}
}	

// -------------------------------------------------------------------------------------------
//  Mostra area restrita
// -------------------------------------------------------------------------------------------

function chamaAreaRestrita(area)
{
	document.getElementById("area_restrita").style.display = "none"
	document.getElementById("area_restrita_"+area).style.display = "block"
	if (area == 'colaborador') document.getElementById("area_restrita_usuario_colaborador").focus()
	if (area == 'cooperado') document.getElementById("area_restrita_carteira_cooperado").focus()
	if (area == 'credenciado') document.getElementById("area_restrita_carteira_credenciado").focus()
	if (area == 'cliente') document.getElementById("area_restrita_carteira_cliente").focus()
	if (area == 'corretora') document.getElementById("area_restrita_usuario_corretora").focus()
}

function fechaAreaRestrita()
{
	document.getElementById("area_restrita_cliente").style.display = "none"
	document.getElementById("area_restrita_cooperado").style.display = "none"
	document.getElementById("area_restrita_credenciado").style.display = "none"
	document.getElementById("area_restrita_colaborador").style.display = "none"
	document.getElementById("area_restrita_corretora").style.display = "none"
	document.getElementById("area_restrita").style.display = "block"
}

function sairAreaRestrita(caminho)
{
	//iniciaAjaxExecuta(caminho+'session/logoff.php','login=1','1000','carregando')
	location.href = caminho+'session/logoff.php'
}

// -------------------------------------------------------------------------------------------
//  Mensagens
// -------------------------------------------------------------------------------------------

function mostraMsg(msg)
{
	document.getElementById("msgTexto").innerHTML = '<p>'+ msg +'</p>'
	document.getElementById("msg").style.display = "block"
}

function fechaMsg()
{
	document.getElementById("msg").style.display = "none"
}

// -------------------------------------------------------------------------------------------
//  Erro AJAX
// -------------------------------------------------------------------------------------------

function mostraErroDesc()
{
	if (document.getElementById("erroJavaDesc").style.display == 'none' || document.getElementById("erroJavaDesc").style.display == '')
	{
		document.getElementById("erroJava").style.width = '400px'
		document.getElementById("erroJavaDesc").style.display = 'inline'
	}
	else
	{
		document.getElementById("erroJavaDesc").style.display = 'none'
		document.getElementById("erroJava").style.width = '150px'
	}
}


