function getId(id) {
	return document.getElementById(id);
}

function mostraId(id)
{
	$("#"+id).show("fast");
}

function escondeId(id)
{
	$("#"+id).hide("fast");
}

function mostraEscondeId(id)
{
	if(getId(id).style.display=='none')
	{
		$("#"+id).show("fast");
	}
	else
	{
		$("#"+id).hide("fast");
	}
}


// ESPERA
//===================================================================
function carregando()
{
	getId('carregando').style.display = 'block';
}

function carregou()
{
	getId('carregando').style.display = 'none';
}

function enviando()
{
	getId('enviando').style.display = 'block';
}

function enviou()
{
	getId('enviando').style.display = 'none';
}


//==============================================================
// CADASTRO
//==============================================================

function cad_setPlano()
{
	if(getId('id_plano').value!='')
	{
		carregando();
		xajax_cad_setPlano(getId('id_plano').value);
	}
}

function cad_cancelaAssinatura()
{
	if(confirm('Cancelar assinatura?'))
	{
		carregando();
		xajax_cad_cancelaAssinatura();
	}
	return false;
}

function checkEstado()
{
	var c = document.getElementById("estado"), i=0;
	for (; i<c.options.length; i++)
	{    
		if(c.options[i].selected)
		{
			if(c.options[i].value!='')
			{
				getId('checkExterior').checked = false;
				getId('pais').value = 'Brasil';
			}
		}
	}
}

function clickExterior()
{
	getId('pais').value = '';
	var c = document.getElementById("estado"), i=0;
	for (; i<c.options.length; i++)
	{    
		if (c.options[i].value == '')
		{
			c.options[i].selected = true;
			getId('checkExterior').checked = true;
			break;
		}
		
	}
	getId('pais').focus();
}

function cad_insereAssinante()
{
	var cpf_radio = getId('cpf_radio');
	var cnpj_radio = getId('cnpj_radio');

	var cpf = getId('cpf');
	var cnpj = getId('cnpj');
	var nome = getId('nome');
	var email = getId('email');
	var email_conf = getId('email_conf');
	var senha = getId('senha');
	var senha_conf = getId('senha_conf');
	var cidade = getId('cidade');
	var estado = getId('estado');
	var pais = getId('pais');
	var erro = 0;
	var erros = '';
	
	if(cpf_radio.checked){
		if(!isCpf(cpf.value))
		{
			++erro;
			erros = erros + '- CPF Inválido! <br />';
		}
		cpf_cnpj = cpf.value;
	}else{
		if(!valida_cnpj(cnpj.value))
		{
			++erro;
			erros = erros + '- CNPJ Inválido! <br />';
		}
		cpf_cnpj = cnpj.value;
	}
	
	if(nome.value.length < 5)
	{
		++erro;
		erros += '- Preencha seu nome / razão social completo! <br />';
	}
	
	if(!checkMail(email.value))
	{
		++erro;
		erros += '- Email inválido! <br />';
	}
	else
	{
		if(email.value != email_conf.value)
		{
			++erro;
			erros += '- Email e confirmação não conferem! <br />';
		}
	}
	
	if(senha.value.length < 6)
	{
		++erro;
		erros += '- Sua senha deve conter no mínimo 6 caractéres! <br />';
	}
	else
	{
		if(senha.value != senha_conf.value)
		{
			++erro;
			erros += '- Senha e confirmação não conferem! <br />';
		}
	}
	
	if(cidade.value=='')
	{
		++erro;
		erros += '- Informe sua cidade! <br />';
	}

	if(erro==0)
	{
		getId('msgErro').innerHTML = '';		
		carregando();
		xajax_cad_insereAssinante(cpf_cnpj, nome.value, email.value, senha.value, cidade.value, estado.value, pais.value);
	}
	else
	{
		getId('msgErro').innerHTML = erros;
	}
}

function confirmaAssinatura(id_assinante, id_plano)
{
	var t_deposito = getId('deposito');
	var t_boleto = getId('boleto');
	var forma = "";
	
	if(t_boleto.checked==false && t_deposito.checked==false)
	{
		alert('Selecione a forma de pagamento!');
		return false;
	}
	if(t_boleto.checked==true)
	{
		forma = 'boleto';
	}
	if(t_deposito.checked==true)
	{
		forma = 'deposito';
	}
	carregando();
	xajax_confirmaAssinatura(id_assinante, id_plano, forma);
	
}

function assinaPlano(id_plano)
{
	carregando();
	xajax_assinaPlano(id_plano);
}

function verificaEmail(email)
{
	if(email!='')
		xajax_verificaEmail(email);
}

function verificaCpf(cpf)
{
	if(email!='')
		xajax_verificaCpf(cpf);
}

function novaAssinatura()
{
	carregando();
	xajax_novaAssinatura();
}

//*************************************************************

// RENOVAÇÃO

function ren_setPlano()
{
	if(getId('id_plano').value!='')
	{
		carregando();
		xajax_ren_setPlano(getId('id_plano').value);
	}
}

function ren_cancelaAssinatura()
{
	if(confirm('Cancelar renovação?'))
	{
		xajax_ren_cancelaAssinatura();
	}
}

function confirmaRenovacaoAssinatura(id_assinante, id_plano)
{
	var t_deposito = getId('deposito');
	var t_boleto = getId('boleto');
	var forma = "";
	
	if(t_boleto.checked==false && t_deposito.checked==false)
	{
		alert('Selecione a forma de pagamento!');
		return false;
	}
	if(t_boleto.checked==true)
	{
		forma = 'boleto';
	}
	if(t_deposito.checked==true)
	{
		forma = 'deposito';
	}
	carregando();
	xajax_confirmaRenovacaoAssinatura(id_assinante, id_plano, forma);
}

//*************************************************************

function checkMail(mail){
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(mail) == "string"){
			if(er.test(mail)){ return true; }
	}else if(typeof(mail) == "object"){
			if(er.test(mail.value)){
									return true;
							}
	}else{
			return false;
			}
}

//*************************************************************
// Função de auto-tabulação
// Parâmetros:
// input - o elemento de formulário que está sendo utilizado 
// len - o tamanho do campo antes do tab automático (normalmente o maxlength)
// e - ? Sempre passar event
//
// Forma de utilização no HTML:
// <input onKeyUp="return autoTab(this, 3, event);">
//*************************************************************
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
	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();
	}

	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;
	}
	return true;
}

//================================================================================================

function isCpf(cpf) {
	// flag para o return
	var erro = 0;
	// so caracteres numericos
	onze = /^(\d{11})+$/;
	if (!onze.test(cpf)){
			// tento tirar a mascara que o campo pode ter
			soNum = /^(\d{3})+\.+(\d{3})+\.+(\d{3})+\-+(\d{2})+$/;
			if (soNum.test(cpf)){
					num = soNum.exec(cpf);
					cpf = num[1] + num[2] + num[3] + num[4];
			}else {
					return false;
			}
	}
	
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999" ){
			return false;
	}
	var a = [];
	var b = new Number;

	var c = 11;

	for (var i = 0; i < 11; i++){
			a[i] = cpf.charAt(i);
			if (i < 9)
					b += (a[i] * --c);
	}

	a[9] = ((x = b % 11) < 2) ? 0 : 11 - x;
	b = 0;
	c = 11;

	for (var y = 0; y < 10; y++)
			b += (a[y] * c--);

	a[10] = ((x = b % 11) < 2) ? 0 : 11 - x;
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])) {
			return false;
	}
	return true;
} 

function valida_cnpj(cnpj)
{
var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
digitos_iguais = 1;
if (cnpj.length < 14 && cnpj.length < 15)
			return false;
for (i = 0; i < cnpj.length - 1; i++)
			if (cnpj.charAt(i) != cnpj.charAt(i + 1))
						{
						digitos_iguais = 0;
						break;
						}
if (!digitos_iguais)
			{
			tamanho = cnpj.length - 2
			numeros = cnpj.substring(0,tamanho);
			digitos = cnpj.substring(tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--)
						{
						soma += numeros.charAt(tamanho - i) * pos--;
						if (pos < 2)
									pos = 9;
						}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(0))
						return false;
			tamanho = tamanho + 1;
			numeros = cnpj.substring(0,tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--)
						{
						soma += numeros.charAt(tamanho - i) * pos--;
						if (pos < 2)
									pos = 9;
						}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(1))
						return false;
			return true;
			}
else
			return false;
} 



//================================================================================================

function isTelefone(telefone, valueMax) {
    if(valueMax==8){
        telTamanho = /^(\d{8})+$/;
    }else if(valueMax == 2){
        telTamanho = /^(\d{2})+$/;
    }
    if (!telTamanho.test(telefone)){
        return false;
    }
    if (telefone == "00000000" || telefone == "11111111" || telefone == "22222222" || telefone == "33333333" || telefone == "44444444" || telefone == "55555555" || telefone == "66666666" || telefone == "77777777" || telefone == "88888888" || telefone == "99999999" ){
        return false;
    }   
    return true;
}

//================================================================================================

function isDate(dia, mes, ano){
    if(dia != "" && ano != "" && mes != ""){
        if(mes == 2){
            if(ano%4 != 0){
                if(dia > 28){
                    return "Dia inexistente";
                }
            }else{
                if(dia > 29){
                    return "Dia inexistente";
                }
            }
        }else if(mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12){
            if(dia > 31){
                return "Dia inexistente";
            }
        }else{
            if(dia > 30){
                return "Dia inexistente";
            }
        }
    }
    return "";
}

//================================================================================================

function somenteNumero(e){
	var tecla=(window.event)?event.keyCode:e.which;
	if((tecla > 47 && tecla < 58) || tecla == 0) return true;
	else{
	if (tecla != 8) return false;
	else return true;
	}
}
