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

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

function removeMask(value)
{
	var valueLimpo='';
	var er = /[0-9]{1,1}/;	
	
	for(i=0; i < value.length; i++)
	{
		tmp = value.substring(i, i+1);
			
		//if(!isNaN(tmp))
		if(tmp.match(er))
		{
			valueLimpo+=tmp;
		}
	}
	
	return valueLimpo;
}

function ucfirst (str) 
{
    // Makes a string's first character uppercase  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/ucfirst    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1004.1212
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
            	return true;
            }
        }
    }
     return false;
}

function empty(obj)
{
	var type = typeof obj;
	var er = /^\s{0,}$/;
	var retorno = false;

	if(type=="string")
	{
		if(obj.match(er))
			return true;
	}
	if(type!="undefined")
	{
		if(type == "object")
		{
			retorno  = obj.value.match(er);
		}
		else if(get(obj))
		{
			retorno = get(obj).value.match(er);
		}
	}	

	return retorno;
}


function mascara(campo, mask, e)
{
	campo.maxLength=mask.length;
    
	var src=campo.value.length;
    var mask=mask.substr(src,1);
    
    if(window.event)
    {
	    if(e.keyCode!=13 && (e.keyCode > 47 && e.keyCode < 58))
	    {
	    	if(mask!='#' && src>=0)
	    	{	
	        	campo.value+=mask;
	    	}
	    }
	    else
	    {
	    	e.keyCode=0;
	    }
    }
    else
    {
    	if(e.which!=13 && (e.which > 47 && e.which < 58))
	    {
	    	if(mask!='#' && src>=0)
	    	{	
	        	campo.value+=mask;
	    	}
	    }
	    else if( (e.which > 31 && e.which < 48 ) || (e.which > 57 && e.which < 65 ) || (e.which > 64 && e.which < 91 ) ||  e.which > 90 || e.which == 13)
	    {
	    	e.preventDefault();
	    }
    }
}

function validaEMAIL(email)
{
//	var er = /^[a-z0-9-_.]+@+[a-z0-9-_.]+\.[a-z]{2,4}((\.)[a-z]{2})?$/;
	var er = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	
	return email.match(er);
}

function validaCPF(cpf) 
{
	var cpf = new String(cpf);
    var aux_cpf = "";
    var erro = true;

	// retirar caracteres não numéricos
	aux_cpf = removeMask(cpf);

	if(aux_cpf.length!=11){
		return false;
	}else{
    	var sub = aux_cpf.substr(0,1);
    
    	if(aux_cpf.match(sub+'{11}'))
    		return false;
    		
    	var cpf1 = String(aux_cpf);
    	var cpf2 = cpf.substr(cpf.length-2,2);
      	var controle = "";
      	var start = 2;
      	var end = 10;

      	for(var i=1;i<=2;i++){
      		var soma = 0;
      		
      		for(j=start;j<=end;j++){
      			soma += cpf1.substr((j-i-1),1)*(end+1+i-j);
      		}
        	if(i==2){
          		soma += digito * 2;
        	}
        	
        	digito = (soma * 10) % 11;
        	
        	if(digito==10){
          		digito = 0;
        	}
        	
        	controle += digito;
        	start = 3;
        	end = 11;
      	}
      	if(controle!=cpf2){
        	erro = false;
      	}
    }
  
	return erro;
}

function validaCNPJ(cnpj) 
{
	
	var erro = true; 
	var aux_cnpj = "";	
	var cnpj1=0 , cnpj2=0;
	var fator, controle;

	// retirar caracteres não numéricos

	aux_cnpj = removeMask(cnpj);
	
	if(aux_cnpj.length!=14){
		return false;
	}else{
		var sub = aux_cnpj.substr(0,1);
		
		if(aux_cnpj.match(sub+'{14}'))
			return false;
		
		cnpj1 = aux_cnpj.substr(0,12);
		cnpj2 = aux_cnpj.substr(aux_cnpj.length-2,2);
		fator = "543298765432";
		controle = "";
		
		for(j=0; j<2; j++){
			soma = 0;
			for(i=0; i<12; i++){
				soma += cnpj1.substr(i,1) * fator.substr(i,1);
			}
			if(j==1){
				soma += digito * 2;
			}
			
			digito = (soma * 10) % 11;
			
			if(digito==10){
				digito = 0;
			}
			
			controle += digito;
			
			fator = "654329876543";
		} 
		if(controle != cnpj2){
			erro = false;
		}
	} 
	return erro;
}

function igualar()
{
	var lis = get('baixo').getElementsByTagName('li');
	
	var maior=0;
	for (var i=0; i<lis.length; i++)
	{
		if (lis[i].offsetHeight > maior)
			maior = lis[i].offsetHeight;
	}
	for (i=0; i<lis.length; i++)
		lis[i].style.height = maior+"px";
}

function validaCadCliente(form)
{
	var inputs = form.getElementsByTagName('input');
	var teste = '';
	var essesNao = /^(fantasia|ie|compl|compl2|fax|fax2|celular|celular2|cadastrar|cadastrar2|tipoCliente|tipoCliente2|clienteJuridica|clienteFisica|diavenc|diavenc2|voltar|voltar2)$/;
	var validou = true;
	for (var i=0; i<inputs.length; i++){
		if (!inputs[i].id.match(essesNao)){
			teste = validaCampo(inputs[i].id);
			teste = teste == 'nao' ? false : true;
			validou = validou && teste;
		}
	}
	
	return validou;
}

function validaCampo(id)
{
	var essesNao = /^(email|cemail|cnpj|cpf|email2|cemail2|id|id2|contato|contato2)$/;
	var validou = 'nao';
	if (!id.match(essesNao) && empty(get(id))){
		get("msg_"+id).innerHTML = 'Campo obrigatório.';
		get("msg_"+id).className = 'validaNao';
	}
	else if ((id == 'email' || id == 'email2') && !validaEMAIL(get(id).value)){
		get('msg_'+id).innerHTML = 'Email inválido.';
		get("msg_"+id).className = 'validaNao';
	}
	else if (id == 'cnpj' && !validaCNPJ(get(id).value)){
		get('msg_'+id).innerHTML = 'CNPJ inválido.';
		get("msg_"+id).className = 'validaNao';
	}
	else if (id == 'cpf' && !validaCPF(get(id).value)){
		get('msg_'+id).innerHTML = 'CPF inválido.';
		get("msg_"+id).className = 'validaNao';
	}
	else if ((id == 'cemail' || id == 'cemail2') && get(id).value != get(id.replace('c','')).value){
		get('msg_'+id).innerHTML = 'Deve ser igual ao email.';
		get("msg_"+id).className = 'validaNao';
	}
	else if ((id == 'id' || id == 'id2') && empty(get(id))){
		get('msg_'+id).innerHTML = 'Campo obrigatório.';
		get("msg_"+id).className = 'validaNao';
	}
	else if ((id == 'contato' || id == 'contato2') && !Trim(get(id).value).match(' ')){
		get('msg_'+id).innerHTML = 'Nome completo.';
		get("msg_"+id).className = 'validaNao';
	}
	else if (id == 'id' || id == 'id2'){
		get('msg_'+id).className = '';
		consultaId(get(id).value, 'msg_'+id);
		if (get('msg_'+id).className == 'validaSim')
			validou = 'sim';
	}
	else if (id == 'cpf' || id == 'cnpj'){
		verificaCpfCnpj(id);
		if (get('msg_'+id).innerHTML == '')
			validou = 'sim';
	}
	else{
		get('msg_'+id).innerHTML = '';
		get('msg_'+id).className = '';
		validou = 'sim';
	}
	
	return validou;
}

function mudaOpcao(ativa, inativa)
{
	get(inativa).style.display = 'none';
	get(ativa).style.display = 'block';
}

function logar(event, form)
{
	var keynum;  
           
	if(window.event) // PRA IE
		keynum = event.keyCode  
	else if(event.which) // P/ OUTROS BROWSERS
		keynum = event.which  

	if( keynum==13 ) 
	{ 
		form.submit();
	}  
} 

function prevenir(event)
{
	var keynum;  
           
	if(window.event) // PRA IE
		keynum = event.keyCode  
	else if(event.which) // P/ OUTROS BROWSERS
		keynum = event.which 
		
	if ((keynum > 31 && keynum < 48) || (keynum > 57 && keynum < 65) || (keynum > 90 && keynum < 97) || keynum > 122)
		event.preventDefault();
}

function pagamentos(valor)
{
	if (get('plano_52')){ // então é pra hospedagem
		if (get('plano_52').checked){
			get('mensal').checked = false;
			get('mensal').disabled = true;
			get('valorMensal').innerHTML = '';
		}else{
		get('mensal').disabled = false;
		get('valorMensal').innerHTML = valor.replace('.',',');
		}
	}else{ //então não é hospedagem
		get('valorMensal').innerHTML = valor.replace('.',',');
	}
	if (get('valorPlano'))
		get('valorPlano').value = valor;
	get('valorTrimestral').innerHTML = (3*valor*0.98).toFixed(2).replace('.',',');
	get('valorSemestral').innerHTML = (6*valor*0.95).toFixed(2).replace('.',',');
	get('valorAnual').innerHTML = (12*valor*0.90).toFixed(2).replace('.',',');
	
	if (get('valorHospedagem')){
		if (get('valorHospedagem').value > 0){
			pagamentoHospedagem(parseFloat(get('valorHospedagem').value));
		}
	}
}

function pagamentoHospedagem(valor)
{
	
	var valorPlano = get('valorPlano').value;
	
	if (get('hospeda_52').checked){
		get('valorMensal').innerHTML = valorPlano.replace('.',',');
		get('valorTrimestral').innerHTML = (3*valorPlano*0.98).toFixed(2).replace('.',','); 
		get('valorSemestral').innerHTML = (6*valorPlano*0.95).toFixed(2).replace('.',','); 
		get('valorAnual').innerHTML = (12*valorPlano*0.90).toFixed(2).replace('.',','); 
		get('valorHospedagem').value = 0;
	}else{
		get('valorMensal').innerHTML = (parseFloat(valorPlano) + parseFloat(valor)).toFixed(2).replace('.',',');
		get('valorTrimestral').innerHTML = (parseFloat((3*valor*0.98).toFixed(2)) + parseFloat((3*valorPlano*0.98).toFixed(2))).toFixed(2).replace('.',','); 
		get('valorSemestral').innerHTML = (parseFloat((6*valor*0.95).toFixed(2)) + parseFloat((6*valorPlano*0.95).toFixed(2))).toFixed(2).replace('.',',');
		get('valorAnual').innerHTML = (parseFloat((12*valor*0.90).toFixed(2)) + parseFloat((12*valorPlano*0.90).toFixed(2))).toFixed(2).replace('.',',');
		get('valorHospedagem').value = valor;
	}
}

function apareceHospedagem()
{
	var atual = get('opcaoHospedagem').style.display;
	
	if (atual == 'none'){
		get('opcaoHospedagem').style.display = 'block'; 
		pagamentoHospedagem(get('valorHospedagem').value);
	}
	else{
		var valor = get('valorHospedagem').value;
		get('opcaoHospedagem').style.display = 'none'; 
		pagamentoHospedagem(0);
		get('valorHospedagem').value = valor;
	}
}

function validaHospedagem(form)
{
	var inputs = form.getElementsByTagName('input');
	var teste = false;
	var teste2 = false;
	for (var i=0; i<inputs.length; i++){
		if (inputs[i].name == 'plano'){
			teste = teste || inputs[i].checked;
		}else if(inputs[i].name == 'pagamento'){
			teste2 = teste2 || inputs[i].checked;
		}
	}
	var erro= '';
	if (!teste)
		erro = 'Um plano deve ser selecionado!\n';
	if (!teste2)
		erro += 'Uma opção de pagamento deve ser escolhida!';
		
	if (erro){
		alert(erro);
		return false;
	}else{
		return true;
	}
}

function validaConfirmacao()
{
	if (!get('concordo').checked){
		alert('Você precisa concordar com o contrato.');
		return false;
	}else{
		return true;
	}
}

function esconde(id)
{
	get(id).style.display = 'none';
}

function calculaPreco(ciclo)
{
	get('precos').src = "_assets/imagens/valores-"+ciclo+".gif";
	var ciclo;
	
	switch(ciclo){
		case 'mensal':
			get('desconto').innerHTML = '&nbsp;';
			ciclo = "&ciclo=1";
			break;
		case 'trimestral':
			get('desconto').innerHTML = '<img src="_assets/imagens/lado_desconto_2.gif" alt="" title="" />';
			ciclo = "&ciclo=2";
			break;
		case 'semestral':
			get('desconto').innerHTML = '<img src="_assets/imagens/lado_desconto_5.gif" alt="" title="" />';
			ciclo = "&ciclo=3";
			break;
		case 'anual':
			get('desconto').innerHTML = '<img src="_assets/imagens/lado_desconto_10.gif" alt="" title="" />';
			ciclo = "&ciclo=4";
			break;
	}
	
	get('plano-52').href = "contratacao/?servico=hospedagem&plano=52"+ciclo;
	get('plano-53').href = "contratacao/?servico=hospedagem&plano=53"+ciclo;
	get('plano-54').href = "contratacao/?servico=hospedagem&plano=54"+ciclo;
	get('plano-55').href = "contratacao/?servico=hospedagem&plano=55"+ciclo;
	get('plano-56').href = "contratacao/?servico=hospedagem&plano=56"+ciclo;
}
