

function recaptchaCallback(){
	 $('#hiddenRecaptcha').valid();
}

$().ready(function(){
	$("#otrotitulohidden").hide()
	$("#statusmsg").hide();
	$("#txtbda,#txteda").datepicker({

		dateFormat: "dd/mm/yy",
      	minDate:new Date(2018,11,17),
      	maxDate:new Date(2018,11,20)
	});
	$("#titulo").select2({
		data: [
		"Estudiante de grado",
		"Estudiante de posgrado",
		"Posdoctorando",
		"Profesor",
		"Otro",
		],
		placeholder: "Seleccione",
		width: "100%",
		minimumResultsForSearch: Infinity,
 	 });
	$("#titulo").on('select2:select', function (e){
		var data = e.params.data;
		if(data.text==="Otro")
			$("#otrotitulohidden").show(500)
		else
			$("#otrotitulohidden").hide();
	})
	$("#pais").select2({
		data: data.paises,
		placeholder: "Seleccione",
		width: "100%",
	});

	$('#registerform').on('submit',function(e) {
		e.preventDefault();
	});
	var validator = $('#registerform').validate({
		ignore: '.ignore',
		rules: {
			nombre: {
				required: true,
				minlength: 2
			},
			apellido: {
				required: true,
				minlength: 2
			},
			email:{
				required: true,
				email: true
			},
			ciudad:{required:true},
			pais:{required:true},
			titulo:{required:true},
			otrotitulo:{required: function(){
				if($("#titulo").select2('data')[0].id === 'Otro')
					return true;
				else return false
			}},
			profesion:{required:true},
			afiliacion:{required:true},
			hiddenRecaptcha: {
					required: function() {
							if(grecaptcha.getResponse() == "") return true;
							else return false;
					}
				}


		},
		messages: {
			nombre: {
				required: "Debe ingresar Nombre",
				minlength: "Nombre debe tener al menos 2 caracteres"
			},
			apellido: {
				required: "Debe ingresar Apellido",
				minlength: "Apellido debe tener al menos 2 caracteres"
			},
			email: "Dirección de e-mail inválida",
			ciudad:"Ingrese ciudad",
			pais:"Seleccione País",
			titulo: "Debe ingresar profesión o actividiad",
			otrotitulo:"Aclare el detalle de su profesión o actividad",
			afiliacion:"Debe ingresar su afiliación",
			hiddenRecaptcha: "Debe validar reCAPTCHA",


		},
		submitHandler: function(form){
			
			var formdata = $(form).serializeArray();
			formdata.find(item => item.name === "pais").value = $("#pais").select2("data")[0].text.trim();
			if ($("#titulo").select2("data")[0].id !== "Otro")
        		formdata.find((item) => item.name === "titulo").value = $("#titulo").select2("data")[0].text.trim();
			else
				formdata.find((item) => item.name === "titulo").value = $("#otrotitulo").val()
			console.log(formdata)	
			var parameters = $.param(formdata);			
			/*$.ajax({
				url: 'api/register',
				type: "POST",
				data: parameters,
				success:function(result){
					console.log(result);
				},
				error: function(jqxhr, status, exception){
					console.log(exception);
					console.log(jqxhr);
				}
			});*/
			
			var req = $.post('api/register', parameters)
			req.done(function(data){
				
				if(data.success){
					
					validator.resetForm();
					reset($("#registerform"));
					showMsg(false,data.msg);
				}
				else{
				
					var errMsg = data.msg+"<ul>";
					$.each(data.errors, function(k,v){
						errMsg+="<li>"+v+"</li>";
					});
					errMsg+="</ul>";
					console.log(errMsg);
					showMsg(true,errMsg);
				}
			});

		},
		errorElement: "em",
		errorPlacement: function ( error, element ) {
			// Add the `help-block` class to the error element
			error.addClass("help-block");
			var esradio = $(element).prop("type") == "radio";
			var padre = element.parents(".input-container");
			var escaptcha = padre.find(".g-recaptcha").length;
			padre.addClass("has-feedback");
			padre.append(error);
			var iconstatus = $("<span class='glyphicon glyphicon-remove form-control-feedback'></span>");
			if(!$.contains(padre,"span.glyhpicon")){
				error.before(iconstatus);
			}
			if(esradio || escaptcha){
				error.css("display", "inline");
				$(iconstatus).css("display", "inline");
				$(iconstatus).css("position", "initial");
			}
		},
		success: function(label,element){
			var esradio = $(element).prop("type") == "radio";
			var padre = $(element).parents(".input-container");
			var iconstatus = padre.children("span.glyphicon");
			if(!iconstatus){
				label.before("<span class='glyphicon glyphicon-ok form-control-feedback'></span>");
			}
		},
		highlight: function ( element, errorClass, validClass ) {
			var padre = $(element).parents(".input-container");
			var iconstatus = padre.children("span.glyphicon");
			padre.addClass("has-error").removeClass("has-success");
			iconstatus.addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
			padre.addClass( "has-error" ).removeClass( "has-success" );
		},
		unhighlight: function (element, errorClass, validClass) {
			var padre = $(element).parents(".input-container");
			var iconstatus = padre.children("span.glyphicon");
			padre.addClass("has-success").removeClass("has-error");
			iconstatus.addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
			padre.addClass( "has-success" ).removeClass( "has-error" );
		},
    //});

	});
	function reset($form){
		//$form.find("input").val('');
		//$form.find("input:radio,input:checkbox").removeAttr("checked").removeAttr("selected");
		$form.find(".input-container").removeClass("has-feedback has-success has-error");
		$form.find("span.form-control-feedback").remove();
		$form.find("em.error").remove();
		$(':input','#registerform')
  		.removeAttr('checked')
  		.removeAttr('selected')
  		.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  		.val('');
		grecaptcha.reset();
		$form[0].reset();
	}
	function showMsg(error,msg){

		var msgTxt = $("#msgModal .modal-body .alert");
		if(error){
			msgTxt.removeClass("alert-success");
			msgTxt.addClass("alert-danger");
			msgTxt.html('<strong><span class="glyphicon glyphicon-remove-sign">'
								+'</span>Error! </strong><br/>'+msg);
		}
		else{
			msgTxt.removeClass("alert-danger");
			msgTxt.addClass("alert-success");
			msgTxt.html('<strong><span class="glyphicon glyphicon-ok-sign">'
								+'</span>Success! </strong><br/>'+msg);

		}
		$("#msgModal").modal({
			show:true,

		});
	}


});
