/* ******************************************************
 * Autor	: Stefan Horochovec
 * Email	: stefan@horochovec.com.br
 * Data		: 14/07/2006
 * Versao 	: 0.1
 * Objetivo	: Mostrar ou esconder objetos na tela dinamicamente
 * Param	:	exibe	:	array com o que deve ser mostrado
				esconde	: 	array com o que deve ser escondido
 * ******************************************************/
function exibeEsconde(exibe, esconde) {
	// exibe
	for(var i = 0; i < exibe.length; i++)  {
		if(document.getElementById(exibe[i])) {
			document.getElementById(exibe[i]).style.display = 'block';
		}
	}
	// esconde
	for(var i = 0; i < esconde.length; i++) {
		if(document.getElementById(esconde[i])) {
			document.getElementById(esconde[i]).style.display = 'none';
		}
	}
}

function mudaAbaBoxLogin(acao, abaAcao) {
	
	if (acao == 'mouseOver') {
		
		if (abaAcao == 'representanteOff') {
//			exibeEsconde(new Array('representanteOn', 'txtLoginRepre', 'clienteOff'), new Array('representanteOff', 'txtLoginCliente', 'boxLoginPrimeiroAcesso', 'boxLoginEsqueceuSenha', 'clienteOn'));
			exibeEsconde(new Array('representanteOn', 'txtLoginRepre', 'clienteOff'), new Array('representanteOff', 'txtLoginCliente', 'clienteOn'));
		}	
		if (abaAcao == 'clienteOff') {
			exibeEsconde(new Array('clienteOn', 'txtLoginCliente', 'representanteOff'), new Array('clienteOff', 'txtLoginRepre', 'representanteOn'));			
		}
		
	} else if (acao == 'mouseOut') {

		if (abaAcao == 'clienteOn') {
			if (document.getElementById('tipoLogin').value == '1') {
				document.getElementById('formLogin').action	= "https://www.consisanet.com.br/novo/atualizacao/login.php";
				exibeEsconde(new Array('clienteOn', 'txtLoginCliente', 'representanteOff'), new Array('clienteOff', 'txtLoginRepre', 'representanteOn'));							
			} else {
				document.getElementById('formLogin').action	= "https://www.consisanet.com.br/raiz/helpdesk/valida_login.php";
				exibeEsconde(new Array('clienteOff', 'txtLoginRepre', 'representanteOn'), new Array('clienteOn', 'txtLoginCliente', 'representanteOff'));							
			}
		} 
		if (abaAcao == 'representanteOn') {
			if (document.getElementById('tipoLogin').value == '2') {
				document.getElementById('formLogin').action	= "https://www.consisanet.com.br/raiz/helpdesk/valida_login.php";
				exibeEsconde(new Array('representanteOn', 'txtLoginRepre', 'clienteOff'), new Array('representanteOff', 'txtLoginCliente', 'clienteOn'));							
			} else {
				document.getElementById('formLogin').action	= "https://www.consisanet.com.br/novo/atualizacao/login.php";
				exibeEsconde(new Array('representanteOff', 'txtLoginCliente', 'clienteOn'), new Array('representanteOn', 'txtLoginRepre', 'clienteOff'));							
			}
		}		
	}	
}


function mudaTipoBoxLogin(tipo) {
	
	if (tipo == 'cliente') {
		document.getElementById('tipoLogin').value = 1;
	} else {
		document.getElementById('tipoLogin').value = 2;
	}
	
}

function validaFormLogin() {

	if (gid('txtLogin').value == '' ) {
		gid('txtLogin').focus();
		window.alert('Informe seu usuário');
		return false;
	}
	if (gid('txtSenha').value == '' ) {
		gid('txtSenha').focus();
		window.alert('Informe sua senha');		
		return false;
	}	
	return true;
}

/**
 * Valida formulário de contato
 */
function validaFormularioContato(frm) {
	var retorno = false;	

	if ( validaCadastro(frm) ) {
		retorno = true;
	} else {
		
		return false;
	}
	
	if (retorno) {
		document.forms[frm.name].elements['btnContato'].disabled	= true;
		document.forms[frm.name].elements['btnLimpar'].disabled		= true;
	}
	
	return retorno;
}

function ajaxBuscaMunicipio(busca, atualiza) {
	// Limpa o select
	if(busca != ""){
		
		while ( atualiza.options.length > 0 ) {
			atualiza.options[0] = null;
		}
	
		atualiza.disabled	= true;
		atualiza.options[0] = new Option("Carregando...", "0");
		var xmlhttp			= iniciarAjax();
		
		xmlhttp.open("POST", "../util/AjaxBuscaMunicipio.php", true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				// Limpa o select
				while ( atualiza.options.length > 0 ) {
					atualiza.options[0] = null;
				}
				
				atualiza.disabled	= false;
				var cidades			= xmlhttp.responseText.split("|");
				var cidade			= null;
				
				for (var i = 0; i < cidades.length; i++) {
					cidade = cidades[i].split(",");
					
					atualiza.options[ atualiza.options.length ] = new Option(cidade[1], cidade[0]);
				}
			}
		}
		
		var post = 'estado=' + busca;
		
		xmlhttp.send( post );
	}
}

function gid(id) {
	return document.getElementById(id);
}

/* Muda a cor de fundo do objeto
------------------------------------------------------------------------------*/
function mudaCor(o, cor) {
	if (isDOM()) {
		o.style.background = cor;
	}
}

/* Verifica se Ã© compatÃ­vel com o Modelo de Objeto de Documento (DOM)
------------------------------------------------------------------------------*/
function isDOM() {
	var isMinIE5 = (navigator.appVersion.indexOf("5.")) >= 0 ? 1 : 0;	// MÃ­nimo IE 5
	var isDOM    = (document.getElementById) ? 1 : 0;					// Document Object Model
	
	if (isMinIE5 || isDOM) { 
		return true;
	} else {
		return false;
	}
}

function iniciarAjax() {
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   xmlhttp = false;
	  }
	 }
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	
	return xmlhttp;
}

function cpf_cnpj(campo) {
   // checa se Ã© cpf
    s = limpa_string(campo.value);
	if (s.length == 11) {
		if (valida_CPF(campo.value) == false ) {
		return false;
		}
	}

 // checa se Ã© cnpj
	else if (s.length == 14) {
		if (valida_CNPJ(campo.value) == false ) {
			return false;
			}
		}
	else {
		return false;
	}
	
	return true;
}

function limpa_string(S){
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

    for (var i=0; i<S.length; i++){
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0){temp=temp+digito}
	}
	return temp
}

function valida_CPF(s){
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;

	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(10-i);
	}
	if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1){
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1){
		return false;
	}
	return true;
}

function valida_CNPJ(s){
	var i;
	s = limpa_string(s);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;

	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
	if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1){
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1) {
		return false;
	}

	return true;
}

function validaCadastro(frm) {
	
	/* *** ValidaÃ§Ã£o GenÃ©rica ********************************************************** */
	// Verifica se os campos obrigatÃ³rios estÃ£o vazios
	var campo = document.forms[frm.name].elements;
	
	for (var i = 0; i < campo.length; i++) {
		
		if ( (campo[i].obrigatorio == 'obrigatorio') && (campo[i].value == '') ) {
			return erro(campo[i], 'Preenchimento obrigatório para o campo: "' + campo[i].title + '"');
		}
	}
	
	/* *** ValidaÃ§Ã£o Especfica ******************************************************** */
	
	// Valida nome do cliente
	if ( gid('CLIENTE_NOME').value.length < 5 ) {
		return erro(gid('CLIENTE_NOME'), 'Informe um nome maior que 5 dígitos.');
	}
	
	// Valida fone
	if ( gid('CLIENTE_FONE').value.length < 10 ) {
		return erro(gid('CLIENTE_FONE'), 'O número do seu telefone precisa ter 10 dígitos.');
	}
	
	// Valida e-mail
	if ( !checkMail( gid('CLIENTE_EMAIL').value ) ) {
		return erro(gid('CLIENTE_EMAIL'), 'E-mail Inválido: o e-mail informado está incorreto.');
	}
	
	// SituaÃ§Ãµes em que envolvem senha e a senha redigitada
	var senhaOriginal = gid('CLIENTE_SENHA');
	var senhaConfirma = gid('CLIENTE_SENHA_CONFIRMA');
	
	if ( senhaOriginal && senhaConfirma ) {
		
		if ( senhaOriginal.value.length < 6 ) {
			return erro(senhaOriginal, 'A "senha" deve conter 6 ou mais dígitos.');
		}
		
		if ( senhaConfirma.value.length < 6 ) {
			return erro(senhaConfirma, 'A "senha redigitada" deve conter 6 ou mais dígitos.');
		}
		
		if ( senhaOriginal.value != senhaConfirma.value ) {
			return erro(senhaConfirma, 'A "senha redigitada" não confere com a "senha".');
		}
		
	}
	
	// Valida se existe um MunicÃ­pio selecionado
	if (gid('MUNICIPIO_ID_1').value == '') {
		return erro(senhaConfirma, 'É necessário selecionar um "Município".');
	}
	
	if(gid('CLIENTEEND_CEP_1')){
		// Valida CEP
		if ( (gid('CLIENTEEND_CEP_1').value.length < 8) || (gid('CLIENTEEND_CEP_1').value.length > 8) ) {
			return erro(gid('CLIENTEEND_CEP_1'), 'O número do "CEP" precisa ter 8 dígitos.');
		}
	}
	// ValidaÃ§Ã£o completa, OK, envia para o servidor os dados
	return true;
}

function checkMail(email) {
	var filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if ( !filtro.test(email) ) { 
		return false;
	}
	
	return true;
}

function erro(campo, msg) {
	var cor = '#E25053';
	
	mudaCor(campo, cor);
	alert(msg);
	
	campo.focus();
	campo.select();
	
	return false;
}

function validaFormulario(frm) {
	// Verifica se os campos obrigatÃ³rios estÃ£o vazios
	var campo = document.forms[frm.name].elements;
	for (var i = 0; i < campo.length; i++) {

		if ( (campo[i].obrigatorio == 'obrigatorio') && (campo[i].value == '') ) {
			
			return erro(campo[i], 'Preenchimento obrigatório para o campo: "' + campo[i].title + '"');
		}
	}
}
function popUp (width, height, titulo, url) {
	var left, top;
	if (screen.width < width)
		left = 0;
	else
		left = (screen.width  - width) / 2;
	
	if (screen.height < height)
		top = 0;
	else
		top = (screen.height - height) / 4;
	if ( navigator.appName == "Netscape" ) {  
		var w = window.open (url, titulo, "height="+height+",width="+width+",screenX=" + left + ",screenY=" + top + ",toolbar=no,menubar=no,resizable=no,scrollbars=no,statusbar=yes");
	} else {  
		var w = window.open (url, titulo, "height="+height+",width="+width+",left=" + left + ",top=" + top + ",toolbar=no,menubar=no,resizable=no,scrollbars=no,statusbar=yes");
	}
	if (w) 
	w.focus ();
}

function novaJanela (width, height, titulo, url) {
	var left, top;
	
	if(width == ""){
		width = screen.width / 2;
	}
	
	if(height == ""){
		height = screen.height / 2;
	}
	
	if (screen.width < width)
		left = 0;
	else
		left = (screen.width  - width) / 2;
	
	if (screen.height < height)
		top = 0;
	else
		top = (screen.height - height) / 4;
	
	if ( navigator.appName == "Netscape" ) {  
		var w = window.open (url, titulo, "height="+height+",width="+width+",screenX=" + left + ",screenY=" + top + ",toolbar=yes,menubar=yes,resizable=yes,scrollbars=yes,statusbar=yes");
	} else {  
		var w = window.open (url, titulo, "height="+height+",width="+width+",left=" + left + ",top=" + top + ",toolbar=yes,menubar=yes,resizable=yes,scrollbars=yes,statusbar=yes");
	}
	if (w) 
	w.focus ();
}

function popUpScroll (width, height, titulo, url) {
	var left, top;
	if (screen.width < width)
		left = 0;
	else
		left = (screen.width  - width) / 2;
	
	if (screen.height < height)
		top = 0;
	else
		top = (screen.height - height) / 4;
	if ( navigator.appName == "Netscape" ) {  
		var w = window.open (url, titulo, "height="+height+",width="+width+",screenX=" + left + ",screenY=" + top + ",toolbar=no,menubar=no,resizable=no,scrollbars=yes,statusbar=yes");
	} else {  
		var w = window.open (url, titulo, "height="+height+",width="+width+",left=" + left + ",top=" + top + ",toolbar=no,menubar=no,resizable=no,scrollbars=yes,statusbar=yes");
	}
	if (w) 
	w.focus ();
}

function confirmaExclusao(url) {
	if(confirm('Você tem certeza que deseja excluir esta informação?')) {
		location.href = url;
	}
}

function confirmaLimparCarrinho(url) {
	if(confirm('Você tem certeza que deseja limpar seu carrinho de compras?')) {
		location.href = url;
	}
}

function mascara_data(data){

	var mydata = '';
    mydata += data.value;
    if (mydata.length == 2)
    {
		mydata = mydata + '/';
        data.value = mydata;
    }
    if (mydata.length == 5)
    {
        mydata = mydata + '/';
        data.value = mydata;
    }
	
	if (mydata.length == 10){ 
	    verifica_data(data); 
	}
	else
		return mydata;
}

function soNumero(myfield, e, dec) {
	var key;
	var keychar;
	if (dec == null) dec = "";
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;
	// numbers
	else if ((("0123456789" + dec).indexOf(keychar) > -1))
	   return true;
	// decimal point jump
	else
	   return false;
}

function verifica_data(data){
	
      dia = (data.value.substring(0,2));
      mes = (data.value.substring(3,5));
      ano = (data.value.substring(6,10));
      situacao = "";
      // verifica o dia valido para cada mes
      if ((dia < 1)||(dia < 1 || dia > 30) && (  mes == 4 || mes == 6 || mes == 9 || mes == 11 ) || dia > 31)
      {
      situacao = "falsa";
      }
      // verifica se o mes e valido
      if (mes < 1 || mes > 12 )
      {
      situacao = "falsa";
      }
      // verifica se e ano bissexto
      if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4))))
      {
      situacao = "falsa";
      }

      if (data.value == "")
      {
          situacao = "falsa";
      }

      if (situacao == "falsa")
      {
        return false;
      }
	  else
	  	return true;
}

function abreChat(width, height, myname, url) {
    abriu=false;
	var left, top;
	if (screen.width < width)
	    left = 0;
	else
		left = (screen.width  - width) / 2;
	if (screen.height < height)
		top = 0;
	else
		top = (screen.height - height) / 4;
	if ( navigator.appName == "Netscape" )
	{  
		var w = window.open (url, myname, "height="+height+",width="+width+",screenX=" + left + ",screenY=" + top + ",scrollbars=yes,status=no,toolbar=0,menubar=no,location=0,directories=0,resizeble=no");
	} else {  
		var w = window.open (url, myname, "height="+height+",width="+width+",left=" + left + ",top=" + top + ",scrollbars=yes,status=no,toolbar=0,menubar=no,location=0,directories=0,resizeble=no");
	}
	if (w) {
		abriu=true;
		w.focus ();
		return false;
	}
	if(abriu==false) {
	  alert('Você está com o bloqueador de pop-ups hablitado.\nPara acessar o chat você precisa desabilitar o bloqueador de pop-ups.');
	  return false
    }
}

function copiarDadosEndereco(frm) {
	
	gid('ESTADO_SIGLA_2').value				= gid('ESTADO_SIGLA_1').value;
	
	ajaxBuscaMunicipio( gid('ESTADO_SIGLA_1').options[ gid('ESTADO_SIGLA_1').selectedIndex ].value, gid('MUNICIPIO_ID_2') );
	
	var tempo = setTimeout(
					function() {
						gid('MUNICIPIO_ID_2').selectedIndex		= gid('MUNICIPIO_ID_1').selectedIndex;
					},
					200
	);
	
	gid('CLIENTEEND_CEP_2').value			= gid('CLIENTEEND_CEP_1').value;
	gid('CLIENTEEND_ENDERECO_2').value		= gid('CLIENTEEND_ENDERECO_1').value;
	gid('CLIENTEEND_BAIRRO_2').value		= gid('CLIENTEEND_BAIRRO_1').value;
	gid('CLIENTEEND_CXPOSTAL_2').value		= gid('CLIENTEEND_CXPOSTAL_1').value;
	gid('CLIENTEEND_NUMERO_2').value		= gid('CLIENTEEND_NUMERO_1').value;
	gid('CLIENTEEND_COMPLEMENTO_2').value	= gid('CLIENTEEND_COMPLEMENTO_1').value;
}

function buscaCidade(estado,cidade,divCidade,cidadeValor){
	
	var ajaxFormname  = estado.form.name;
	var url = '/beta/rels/cidades.php?estado='+estado.value+'&cidade='+cidade+'&municipio='+cidadeValor;
	
	//função que trata erros
	 function ComErro(or1){
	  alert("Houve um erro na solicitação das informações." );
	  Form.enable(ajaxFormname);
	 }
	 function Sucesso(or1){
	 //$(ajaxDivcidade).innerHTML = "Informações carregadas com sucesso." ;
	  //setTimeout("$("+ajaxDivcidade+").innerHTML = ''",2000);
	  Form.enable(ajaxFormname);
	 }
	 //função que é chamada ao final do carregamento da página 
	 function MostraCapital(or1){
		if (or1.responseText != "")
		  //Pega o retorno da Solicitação e preenche a div
		   $(divCidade).innerHTML = or1.responseText ;
		Form.enable(ajaxFormname);
	 }

	/*************************************************************************************************/
	//Inicializa a busca
	Form.disable(ajaxFormname);
    //Chamando metódo Ajax.Request()
                  var pars = 'divNome=' + divCidade; 
                  var opts = { 
                          postBody: pars, 
                          onComplete: MostraCapital,
						  onSuccess: Sucesso
                   } 
                   var myAjax = new Ajax.Request(url, opts); 
	/*************************************************************************************************/
				   
}

function carregaModulo(frm, action){

		frm.action = action;
		frm.target = '_self';
		frm.submit();
		frm.target = '_blank';		
}
