/******************************************************************
	CADASTRO
******************************************************************/

function validaCadastro()
{
	with (document.cadastro)
	{
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		travaBotao();
		var dados = $("#cadastro").serialize();
		
		$.post("send.acoes.php", dados, function(msg){
	
			var fim = $.trim(msg);
			
			if (fim == "ok")
			{
				abreAlerta("Cadastro enviado com sucesso.");
			}
			
			if (fim == "erro")
			{
				abreAlerta("Ocorreu um erro ao enviar seus dados. Tente novamente.");
			}
			
			destravaBotao();
			nome.value = "Nome:";
			email.value = "E-mail:";
			
		});
	}	
}


/******************************************************************
	ESTOU INTERESSADO
******************************************************************/

function validaProposta()
{
	with (document.proposta)
	{
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(cidade) || isDefValue(cidade, "Cidade:"))
		{
			abreAlerta("Preencha a cidade onde reside.");
			cidade.focus();
			return;
		}
		
		if (isEmpty(loja))
		{
			abreAlerta("Selecione a loja de sua preferência.");
			loja.focus();
			return;
		}
		
		if (isEmpty(cliente))
		{
			abreAlerta("Você já é cliente Carburgo?");
			cliente.focus();
			return;
		}
		
		travaBotao();
		var dados = $("#proposta").serialize();
		
		$.post("send.acoes.php", dados, function(msg){
	
			var fim = $.trim(msg);
			
			if (fim == "ok")
			{
				abreAlerta("Proposta enviada com sucesso, em breve um de nossos vendedores irá entrar em contato com você. Obrigado. Equipe Carburgo.");
			}
			
			if (fim == "erro")
			{
				abreAlerta("Ocorreu um erro ao enviar seus dados. Tente novamente.");
			}
			
			destravaBotao();
			
			nome.value = "Nome:";
			email.value = "E-mail:";
			telefone.value = "Telefone:";
			loja.options[0].selected = true;
			cliente.options[0].selected = true;
			texto.value = "Veículo Atual:";
			
		});
	}	
}


/******************************************************************
	PEÇAS
******************************************************************/

function validaPecas()
{
	with (document.formulario)
	{
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(modelo))
		{
			abreAlerta("Selecione o modelo do veículo.");
			modelo.focus();
			return;
		}
		
		if (isEmpty(ano))
		{
			abreAlerta("Selecione o ano do veículo desejado.");
			ano.focus();
			return;
		}
				
		if (isEmpty(texto))
		{
			abreAlerta("Preencha sua solicitação.");
			texto.focus();
			return;
		}
				
		travaBotao();
		submit();
	}	
}


/******************************************************************
	AGENDAMENTO DE SERVIÇOS
******************************************************************/

function validaServico()
{
	var dat = new Date();
	var dia = dat.getDate();
	var mes = dat.getMonth()+1;
	var ano = dat.getYear();
	
	with (document.formulario)
	{
		var dt1 = data1.value.split("/");
		var dt2 = data2.value.split("/");
		
		if (isEmpty(modelo))
		{
			abreAlerta("Selecione o modelo do veículo.");
			modelo.focus();
			return;
		}
		
		if (isEmpty(anofab) || isEmpty(anomod))
		{
			abreAlerta("Selecione o ano de fabricação e modelo de seu veículo.");
			anofab.focus();
			return;
		}
		
		if (isEmpty(km) || isDefValue(km, "Km Atual:"))
		{
			abreAlerta("Preencha a km atual de seu veículo.");
			km.focus();
			return;
		}
		
		if (!isInteger(km))
		{
			abreAlerta("A km deve ser preechido somente com números.");
			km.focus();
			return;
		}
		
		if (isEmpty(placa) || isDefValue(placa, "Placa:") || placa.value.length < 8)
		{
			abreAlerta("Preencha a placa do veículo.");
			placa.focus();
			return;
		}
		
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(estado))
		{
			abreAlerta("Selecione o estado.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(cidade) || isDefValue(cidade, "Cidade:"))
		{
			abreAlerta("Preencha a cidade.");
			cidade.focus();
			return;
		}
		
		if (isEmpty(loja))
		{
			abreAlerta("Selecione a loja de sua preferência.");
			loja.focus();
			return;
		}
		
		if (isEmpty(data1) || isDefValue(data1, "Data:"))
		{
			abreAlerta("Preencha a 1ª opção de data que deseja realizar o serviço.");
			data1.focus();
			return;
		}
		
		if ((data1.value.length > 5 && data1.value.length < 5) || data1.value.indexOf("/") == -1)
		{
			abreAlerta("A data deve estar no formato dd/mm.");
			data1.focus();
			return;
		}
		
		/*if (!isInteger(dt1[0]) || !isInteger(dt1[1]))
		{
			abreAlerta("O dia e o mês devem ser numéricos.");
			data1.focus();
			return;
		}*/
		
		if ((dt1[0] <= dia && dt1[1] == mes) || dt1[1] < mes)
		{
			abreAlerta("Não é permitido agendar serviços em datas passadas.");
			data1.focus();
			return;
		}
		
		if (isEmpty(hora1))
		{
			abreAlerta("Selecione a 1ª opção de horário que deseja realizar o serviço.");
			hora1.focus();
			return;
		}
		
		if (isEmpty(data2) || isDefValue(data2, "Data:"))
		{
			abreAlerta("Preencha a 2ª opção de data que deseja realizar o serviço.");
			data2.focus();
			return;
		}
		
		if (data2.value == data1.value)
		{
			abreAlerta("A 2ª opção de agendamento deve ser diferente da 1ª opção.");
			data2.focus();
			return;
		}
		
		if ((data2.value.length > 5 && data2.value.length < 5) || data2.value.indexOf("/") == -1)
		{
			abreAlerta("A data deve estar no formato dd/mm.");
			data2.focus();
			return;
		}
		
		/*if (!isInteger(dt2[0]) || !isInteger(dt2[1]))
		{
			abreAlerta("O dia e o mês devem ser numéricos.");
			data2.focus();
			return;
		}*/
		
		if ((dt2[0] <= dia && dt2[1] == mes) || dt2[1] < mes)
		{
			abreAlerta("Não é permitido agendar serviços em datas passadas.");
			data1.focus();
			return;
		}
		
		if (isEmpty(hora2))
		{
			abreAlerta("Selecione a 2ª opção de horário que deseja realizar o serviço.");
			hora2.focus();
			return;
		}
		
		if (isEmpty(texto))
		{
			abreAlerta("Descreva o serviço que deseja realizar.");
			texto.focus();
			return;
		}
				
		travaBotao();
		submit();
	}	
}


/******************************************************************
	VENDAS ESPECIAIS
******************************************************************/

function validaVendas()
{
	with (document.formulario)
	{
		if (isEmpty(nome) || isDefValue(nome, "Nome/Empresa:"))
		{
			abreAlerta("Preencha seu nome ou da nome da empresa.");
			nome.focus();
			return;
		}
		
		if (isEmpty(contato) || isDefValue(contato, "Contato:"))
		{
			abreAlerta("Preencha a pessao de contato.");
			contato.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(cep) || isDefValue(cep, "CEP:"))
		{
			abreAlerta("Preencha o cep.");
			cep.focus();
			return;
		}
		
		if (isEmpty(endereco) || isDefValue(endereco, "Endereço:"))
		{
			abreAlerta("Preencha o endereço.");
			endereco.focus();
			return;
		}
				
		if (isEmpty(numero) || isDefValue(numero, "Número:"))
		{
			abreAlerta("Preencha o número.");
			numero.focus();
			return;
		}
		
		if (isEmpty(bairro) || isDefValue(bairro, "Bairro:"))
		{
			abreAlerta("Preencha o bairro.");
			bairro.focus();
			return;
		}
		
		if (isEmpty(estado))
		{
			abreAlerta("Selecione o estado.");
			estado.focus();
			return;
		}
		
		if (isEmpty(cidade) || isDefValue(cidade, "Cidade:"))
		{
			abreAlerta("Preencha a cidade.");
			cidade.focus();
			return;
		}
		
		if (isEmpty(texto) || isDefValue(texto, "Comentários:"))
		{
			abreAlerta("Preencha os comentários.");
			texto.focus();
			return;
		}
				
		travaBotao();
		submit();
	}	
}


/******************************************************************
	BESTDRIVE
******************************************************************/

function validaBestDrive()
{
	with (document.formulario)
	{
		if (isEmpty(modelo))
		{
			abreAlerta("Selecione o modelo do veículo.");
			modelo.focus();
			return;
		}
		
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}		
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(dia) || isEmpty(mes))
		{
			abreAlerta("Selecione o dia e o mês desejado.");
			dia.focus();
			return;
		}
				
		if (isEmpty(horario))
		{
			abreAlerta("Selecione o horário de sua preferência.");
			horario.focus();
			return;
		}
		
		if (isEmpty(loja))
		{
			abreAlerta("Selecione a loja de sua preferência.");
			loja.focus();
			return;
		}
				
		travaBotao();
		submit();
	}	
}


/******************************************************************
	CURRÍCULO
******************************************************************/

function validaCurriculo()
{
	with (document.formulario)
	{
		if (isEmpty(arquivo))
		{
			abreAlerta("Selecione seu currículo.");
			arquivo.focus();
			return;				 
		}
		
		if (!testFileType(arquivo.value, ['doc', 'docx', 'rft', 'pdf']))
		{
			abreAlerta("Formato de arquivo inválido.");
			arquivo.focus();
			return;				 
		}
		
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(estado))
		{
			abreAlerta("Selecione o estado onde reside.");
			estado.focus();
			return;
		}
		
		if (isEmpty(cidade) || isDefValue(cidade, "Cidade:"))
		{
			abreAlerta("Selecione a cidade onde reside.");
			cidade.focus();
			return;
		}
		
		if (isEmpty(area))
		{
			abreAlerta("Selecione a área de interesse.");
			area.focus();
			return;
		}
				
		travaBotao();
		submit();
	}	
}


/******************************************************************
	CONTATO
******************************************************************/

function validaContato()
{
	with (document.formulario)
	{
		if (isEmpty(nome) || isDefValue(nome, "Nome:"))
		{
			abreAlerta("Preencha seu nome.");
			nome.focus();
			return;
		}
		
		if (isEmpty(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("Preencha seu e-mail.");
			email.focus();
			return;
		}
		
		if (!isEmail(email) || isDefValue(email, "E-mail:"))
		{
			abreAlerta("E-mail digitado é inválido.");
			email.focus();
			return;
		}
		
		if (isEmpty(telefone) || isDefValue(telefone, "Telefone:"))
		{
			abreAlerta("Preencha um telefone de contato.");
			telefone.focus();
			return;
		}
		
		if (isEmpty(estado))
		{
			abreAlerta("Selecione o estado onde reside.");
			estado.focus();
			return;
		}
		
		if (isEmpty(cidade) || isDefValue(cidade, "Cidade:"))
		{
			abreAlerta("Selecione a cidade onde reside.");
			cidade.focus();
			return;
		}
		
		if (isEmpty(assunto))
		{
			abreAlerta("Selecione o assunto.");
			assunto.focus();
			return;
		}
				
		if (isEmpty(mensagem) || isDefValue(mensagem, "Mensagem:"))
		{
			abreAlerta("Preencha a mensagem.");
			mensagem.focus();
			return;
		}
				
		travaBotao();
		submit();
	}	
}


/******************************************************************
	ALERTA
******************************************************************/

function abreAlerta(msg)
{
	alert(msg); 	
}


/******************************************************************
	INPUT SUBMIT
******************************************************************/

function travaBotao(inp)
{
	var btn = (inp==null || inp=="") ? "input:image" : inp;
	$(btn).attr("disabled", "disabled");	
}

function destravaBotao(inp)
{
	var btn = (inp==null || inp=="") ? "input:image" : inp;
	$(btn).removeAttr("disabled");	
}


/******************************************************************
	FOCUS E BLUR
******************************************************************/

function onFocus(campo, valor)
{
	if (campo.value == valor)
	{
		campo.value = "";
	}
}

function onBlur(campo, valor)
{
	if (campo.value == "")
	{
		campo.value = valor;
	}
}


/******************************************************************
	VALIDAÇÕES PADRÃO
******************************************************************/


function clearForm(form) 
{
	// iterate over all of the inputs for the form
	// element that was passed in
	$(':input', form).each(function() {
		
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		
		// it's ok to reset the value attr of text inputs,
		// password inputs, and textareas
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = "";
		
		// checkboxes and radios need to have their checked state cleared
		// but should *not* have their 'value' changed
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		
		// select elements need to have their 'selectedIndex' property set to -1
		// (this works for both single and multiple select elements)
		else if (tag == 'select')
			this.selectedIndex = -1;
		
	});
}

function isEmpty(str)
{
	if (str.value == "" || str.value.length == 0)
	{
		return true;	
	}
	else
	{
		return false;
	}
}

function isDefValue(str, def)
{
	if (str.value == def)
	{
		return true;	
	}
	else
	{
		return false;
	}
}

function isInvalidFormat(str)
{
	var er = new RegExp(/[@!#$%&*+=?|-]/);
	
	if (typeof(str.value) == "string")
	{
        if (er.test(str.value))
		{ 
			return true; 
		}
    }
	else if (typeof(str) == "object")
	{
        if (er.test(str))
		{
           return true;
        }
    }
	else
	{
        return false;
    }
}

function isEqual(str1, str2)
{
	if (str2.value == str1.value)
	{
		return true;	
	}
	else
	{
		return false;
	}
}

function isNotEqual(str, val)
{
	if (str.value != val)
	{
		return true;	
	}
	else
	{
		return false;
	}
}

function isDate(str) 
{
	var dia = str.value.substr(0,2);
	var mes = str.value.substr(3,2);
	var ano = str.value.substr(6,4);
	
	var data = new Date();
	var intDia;
	var intMes;
	var intAno;

	data.setFullYear(ano, mes-1, dia);

	intDia = (data.getDate() == dia);
	intMes = (data.getMonth() == mes-1);
	intAno = (data.getFullYear() == ano);

	if (intDia && intMes && intAno)
	{
		return true;
	}
	else
	{
		return false;	
	}
}

function isEmail(str)
{
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
   
    if (typeof(str.value) == "string")
	{
        if (er.test(str.value))
		{ 
			return true; 
		}
    }
	else if (typeof(str) == "object")
	{
        if (er.test(str))
		{
           return true;
        }
    }
	else
	{
        return false;
    }
}

function isImage(str)
{
    var er = new RegExp(/[\w]+\.(gif|jpg|bmp|png|jpeg)$/gi);
   
    if (typeof(str.value) == "string")
	{
        if (er.test(str.value))
		{ 
			return true; 
		}
    }
	else if (typeof(str) == "object")
	{
        if (er.test(str))
		{
           return true;
        }
    }
	else
	{
        return false;
    }
}

function isDDD(str)
{
	var ddd = str.value.substr(1,2);
	
	if (ddd == "00" || str.length == 0 || str == "")
	{
		return false;
	}
	else
	{
		return true;	
	}
}

function isPhoneNumber(str)
{
	var fone   = str.value.substr(5,9);
	var digito = str.value.substr(5,1);
	var numero = fone.replace(".", "");	
	
	if (numero == "00000000" || numero == "11111111" || numero == "22222222" || numero == "33333333" || numero == "44444444" || numero == "55555555" || numero == "66666666" || numero == "77777777" || numero == "88888888" || numero == "99999999" || str.value.length < 14 || str.value == "" || digito == 0 || digito == 8 || digito == 9)
	{
		return false;
	}
	else
	{
		return true;	
	}
}

function isCelularNumber(str)
{
	var fone   = str.value.substr(5,9);
	var digito = str.value.substr(5,1);
	var numero = fone.replace(".", "");
	
	if (numero == "00000000" || numero == "11111111" || numero == "22222222" || numero == "33333333" || numero == "44444444" || numero == "55555555" || numero == "66666666" || numero == "77777777" || numero == "88888888" || numero == "99999999" || str.value.length < 14 || str.value == "" || digito < 8)
	{
		return false;
	}
	else
	{
		return true;	
	}
}

function isInteger(str)
{
	var er = new RegExp(/^[0-9]+$/);
	
	if (er.test(str.value)) 
	{
		return true;
	} 
	else 
	{
		return false;
	}
}

function testFileType(fileName, fileTypes) //['gif', 'jpg', 'png', 'jpeg']
{
	if (!fileName) return;
	
	dots = fileName.split(".");
	
	//get the part AFTER the LAST period.
	fileType = "." + dots[dots.length-1];
	
	return (fileTypes.join(".").indexOf(fileType) != -1) ? true : false;
}

function calculaIdade(d, m, y)
{
	var dia = parseInt(d);
	var mes = parseInt(m)-1;
	var ano = parseInt(y);
	
	var age;
	var now = new Date();
	
	diaAtual = now.getDate();
	mesAtual = now.getMonth();
	anoAtual = now.getFullYear();
	
	if ((mesAtual > mes)||(mesAtual == mes & diaAtual >= dia))
	{
		age = ano;
	}
	else
	{
		age = ano+1;
	}
	
	return anoAtual-age;
}