

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

$().ready(function(){

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

		dateFormat: "dd/mm/yy",
      	minDate:new Date(2018,11,17),
      	maxDate:new Date(2018,11,20)
	});

	$("#pais").select2({
		data: data.paises,
		placeholder: "Select Country",
		width: "100%",
	});/*.one('select2-focus', select2Focus).on("select2-blur", function () {
    $(this).one('select2-focus', select2Focus)
	});

function select2Focus() {
    var select2 = $(this).data('select2');
    setTimeout(function() {
        if (!select2.opened()) {
            select2.open();
        }
    }, 0);
	}*/

	$("#roomtype").select2({
		data: data.roomtypes,
		placeholder: "Select Rooming Preference",
		width:"100%",
		minimumResultsForSearch: -1,
		dropdownCssClass: "bigdrop",

	});


	$('#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
			},
			//invited:{required:true},
			//financiacion:"required",
			letterinvited:"required",
			hiddenRecaptcha: {
					required: function() {
							if(grecaptcha.getResponse() == "") return true;
							else return false;
					}
				}


		},
		messages: {
			nombre: {
				required: "Please enter your firstname",
				minlength: "Your firstname must be at least 2 characters long"
			},
			apellido: {
				required: "Please enter your lastname",
				minlength: "Your lastname must be at least 2 characters long"
			},
			email: "Please enter a valid e-mail address",
			invited: "Select one option please",
			financiacion: "Select one option please",
			letterinvited: "Select one option please",
			hiddenRecaptcha: "Please validate reCAPTCHA",


		},
		submitHandler: function(form){
			
			var formdata = $(form).serializeArray();
			formdata.find(item => item.name === "pais").value = $("#pais").select2("data")[0].text.trim();
			formdata.find(item => item.name === "roomtype").value = $("#roomtype").select2("data")[0].text.trim();
			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,

		});
	}


});
