﻿function validarRadar() {
	var oValidator = new Utils.Validator();
	var erros = new Array();
	var y = new Date();
	
	var dia = $id("sla_dp_data").value.substr(0,2);
	var mes = $id("sla_dp_data").value.substr(3,2);
	var ano = $id("sla_dp_data").value.substr(6,4);

	try{
		if((mes==04 && dia > 30) || (mes==06 && dia > 30) || (mes==09 && dia > 30) || (mes==11 && dia > 30)){
			throw "DATA INVALIDA";
		}
		else if(ano%4!=0 && mes==2 && dia>28){
			throw "DATA INVALIDA";
		}
		else if(ano%4==0 && mes==2 && dia>29){
			throw "DATA INVALIDA";
		}
		setError("sla_dp_data",false);	
	}
	catch(e){
		setError("sla_dp_data",true);
		erros.push("Data Inválida");
	}
	
	if(!oValidator.check($id("sla_dp_nome").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_nome",true);
		erros.push("Nome completo é requerido");
	} else {
		setError("sla_dp_nome",false);
	}
	if(!oValidator.check($id("sla_dp_rg").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_rg",true);
		erros.push("RG é requerido");
	} else {
		setError("sla_dp_rg",false);
	}
	if(!oValidator.check($id("sla_dp_cpf").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_cpf",true);
		erros.push("CPF é requerido");
	} else {
		setError("sla_dp_cpf",false);
	}
	if(!oValidator.check($id("sla_dp_sexo").value,oValidator.type.REQUIRED)) {
		setError("txtNomeBanda",true);
		erros.push("Informe seu sexo");
	} else {
		setError("sla_dp_sexo",false);
	}
	if(!oValidator.check($id("sla_dp_data").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_data",true);
		erros.push("Dada de Nascimento é requerido");
	} else {
		setError("sla_dp_data",false);
	}

	if(dia >0 && dia < 32 && mes >0 && mes <13 && ano >=1900 && ano <= y.getFullYear()){
		setError("sla_dp_data",false);
	} else {	
		setError("sla_dp_data",true);
		erros.push("Dada de Nascimento incorreta");		
	}
	
	if(!oValidator.check($id("sla_dp_endereco").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_endereco",true);
		erros.push("Endereço é requerido");
	} else {
		setError("sla_dp_endereco",false);
	}
	if(!oValidator.check($id("sla_dp_cidade").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_cidade",true);
		erros.push("Cidade é requerido");
	} else {
		setError("sla_dp_cidade",false);
	}
	if(!oValidator.check($id("sla_dp_estado").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_estado",true);
		erros.push("Estado é requerido");
	} else {
		setError("sla_dp_estado",false);
	}
	if(!oValidator.check($id("sla_dp_pais").value,oValidator.type.REQUIRED)) {
		setError("sla_dp_pais",true);
		erros.push("País é requerido");
	} else {
		setError("sla_dp_pais",false);
	}
	
	if(!oValidator.check($id("txtNomeBanda").value,oValidator.type.REQUIRED)) {
		setError("txtNomeBanda",true);
		erros.push("Nome da banda é requerido");
	} else {
		setError("txtNomeBanda",false);
	}
	if(!oValidator.check($id("txtSobre").value,oValidator.type.REQUIRED)) {
		setError("txtSobre",true);
		erros.push("Informação sobre a banda é requerida");
	} else {
		setError("txtSobre",false);
	}
	if(!oValidator.check($id("txtIntegrantes").value,oValidator.type.REQUIRED)) {
		setError("txtIntegrantes",true);
		erros.push("Informe os integrantes da banda");
	} else {
		setError("txtIntegrantes",false);
	}
	if(!oValidator.check($id("txtCidade").value,oValidator.type.REQUIRED) || ($id("txtCidade").value == "Cidade")) {
		setError("txtCidade",true);
		erros.push("Cidade é requerida");
	} else {
		setError("txtCidade",false);
	}
	if(!oValidator.check($id("txtUF").value,oValidator.type.REQUIRED)) {
		setError("txtUF",true);
		erros.push("Selecione um Estado");
	} else {
		setError("txtUF",false);
	}
	if(!oValidator.check($id("txtEmail").value,oValidator.type.EMAIL)) {
		setError("txtEmail",true);
		erros.push("Informe um e-mail válido");
	} else {
		setError("txtEmail",false);
	}
	if((!oValidator.check($id("txtSenha").value,oValidator.type.REQUIRED)) && ($id("radarID").value == "")) {
		setError("txtSenha",true);
		erros.push("Digite uma senha");
	} else if(!oValidator.check([$id("txtSenha").value,$id("txtConfirmarSenha").value],oValidator.type.COMPARE)) {
		setError("txtSenha",true);
		erros.push("Senhas não conferem");
	} else {
		setError("txtSenha",false);
	}
	//INICIO: VALIDAR TRACKS
	for(var i = 1; i <= 3; i++) {
		if(($id("txtNomeM" + i).value != "") && ($id("faixasampling" + i).value == "")) {
			erros.push("Você deve fazer o upload para a música " + $id("txtNomeM" + i).value);
		} else if(($id("txtNomeM" + i).value == "") && ($id("faixasampling" + i).value != "")) {
			setError("txtNomeM" + i,true);
			erros.push("Você deve digitar o nome da música " + i);
		} else {
			setError("txtNomeM" + i,false);
		}
	}
	//FIM: VALIDAR TRACKS
	if($id("radarID").value ==""){
		if(!$id("checkbox").checked) erros.push("Você deve aceitar os termos gerais para participar");
	}
	if($id("radarID").value ==""){
		if(!$id("checkboxReg").checked) erros.push("Você deve aceitar o Regulamento para participar");
	}
	if(erros.length > 0) {
		alert(erros.join("\n"));
		return false;
	}
	return true;

}

soNumeros = function(alvo) {
	var valor = alvo.value;
	for(var i = 0; i < valor.length; i++) {
		if(isNaN(valor.charAt(i))) {
			valor = valor.substr(0, i) + valor.substr(i+1);
			i--;
		}
	}
	if(alvo.value != valor) alvo.value = valor;
}


function cadastrarRadar() {
	if(validarRadar()) {
		var campos = new Array(
			"sla_dp_nome","sla_dp_rg","sla_dp_cpf","sla_dp_sexo","sla_dp_data","sla_dp_endereco",
			"sla_dp_cidade","sla_dp_estado","sla_dp_pais","radarID","txtNomeBanda","txtSobre",
			"txtIntegrantes","txtSite","sla_radar_img","txtCidade","txtUF","txtNomeM1",	"txtNomeM2",
			"txtNomeM3","faixasampling1","faixasampling2","faixasampling3","txtNews","txtVideos",
			"txtFotos","txtTags","txtEmail","txtSenha","txtConfirmarSenha"
		);
		
		var querystring = buildQuerystring(campos);
		var xmlHttp = createXMLHttpRequest();
		var btnCadastrarBanda = $id("btn-cadastrar-banda");
		
		xmlHttp.open("POST","db_save.asp?mtd=radar_cadastro",true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("x-requested-with", "ajax");
		xmlHttp.onreadystatechange = function() {
			switch(xmlHttp.readyState) {
				case 1:
					btnCadastrarBanda.disabled = true;
					btnCadastrarBanda.value = "Carregando...";
					//showLightbox({content:"Carregando...", height:200});
					break;
				case 4:
					if(xmlHttp.status == 200) {
						try {
							var resposta = eval("("+xmlHttp.responseText+")");
							if(resposta.status == "erro") {
								var erros = "";
								for(var i in resposta) {
									if(i != "status") erros += resposta[i] + "\n";
								}
								alert(erros);
							} else {
								//alert("Cadastro salvo com sucesso");
								if(document.getElementById("radarID").value != "") {
									window.location = ".?"+document.getElementById("radarID").value+"/radar/"+document.getElementById("txtNomeBanda").value;
								} else {
									window.location = ".?/radar/cadastro/sucesso";
								}
							}
						} catch(e) {
							alert("Não foi possível realizar o cadastro");
						}
					} else {
						alert("Não foi possível realizar o cadastro");
					}
					btnCadastrarBanda.disabled = false;
					btnCadastrarBanda.value = "Enviar Cadastro"
					break;
				default:				
			}
		}
		xmlHttp.send(querystring);
	}
}

function dataMask(val){
	var qtdeChar = val.value.length;
	if(qtdeChar == 2 || qtdeChar == 5){
		val.value = val.value+"/"		
	}
/*
var dia = val.value.substr(0,2);
	var mes = val.value.substr(2,2)
	var ano
*/
}
function validaCPF(val) {
			 if(val.value != ""){
					 cpf = val.value;
					 erro = new String;
					 if (cpf.length < 11) erro += "Sao necessarios 11 digitos parao CPF! \n\n"; 
					 var nonNumbers = /\D/;
					 if (nonNumbers.test(cpf)) erro += "CPF suporta apenas numeros! \n\n"; 
					 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
							 erro += "Numero de CPF invalido!"
				   }
				   var a = [];
				   var b = new Number;
				   var c = 11;
				   for (i=0; i<11; i++){
						   a[i] = cpf.charAt(i);
						   if (i < 9) b += (a[i] * --c);
				   }
				   if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
				   b = 0;
				   c = 11;
				   for (y=0; y<10; y++) b += (a[y] * c--); 
				   if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
				   if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
						   erro +="Digito verificador com problema!";
				   }
				   if (erro.length > 0){
						   alert(erro);
						   val.value = "";
						   return false;
				   }
				   return true;
			 }
}


function setError(id,error) {
	var field = document.getElementById(id);
	if(error == true) {
		field.style.border = "1px solid red";
		field.style.background = "#FEE";
	} else {
		field.style.border = "1px solid #8d99b1";
		field.style.background = "#FFF";
	}
}

function buildQuerystring(items) {
	var querystring = "";
	for(var item in items) {
		if(querystring != "") querystring += "&";
		querystring += items[item] + "=" + escape(document.getElementById(items[item]).value);
	}
	return querystring;
}

function $id(id) {
	return document.getElementById(id);
}

function init() {
	$id("txtCidade").onfocus = function() {
		if(this.value == "Cidade") this.value = "";
	}
	$id("txtCidade").onblur = function() {
		if(this.value == "") this.value = "Cidade";
	}
}

window.onload = init;
