(function($) {
  'use strict';
  var form = $("#frm_reg");

  var $validator=$("#frm_reg").validate({
      rules: {
		sponsorID:{
		  required: true,
		  digits: true,
		  minlength: 9
		},
		placementID:{
		  digits: true,
		  minlength: 9
		},
        firstName: {
          required: true,
          minlength: 3
        },
        lastName: {
          required: true,
          minlength: 3
        },
	    mobileNumber:{
        required: true,
        digits: true,
	    minlength: 10,
		},
        emailID: {
          required: true,
          email: true
        },
        terms: "required"
      },
      messages: {
		sponsorID:{
        required: 'Please enter a 9 digit valid sponsor id.',
        digits:   'Please enter a 9 digit valid sponsor id.',
		minlength: 'Please enter a 9 digit valid sponsor id.'
		},
		placementID:{
        digits: 'Please enter a 9 digit valid placement id.',
		minlength: 'Please enter a 9 digit valid sponsor id.'
		},
        firstName: {
          required: "Please enter a First Name",
          minlength: "First Name must consist of at least 3 characters"
        },
		lastName: {
          required: "Please enter a Last Name",
          minlength: "Last Name must consist of at least 3 characters"
        },
	    mobile:{
          required: 'Please provide mobile number.',
          digits:'Please enter a valid mobile number.',
		  minlength: "Please enter 10 digit mobile number."
        },
        emailID: "Please enter a valid email address",
        agree: "Please accept our policy",
        topic: "Please select at least 2 topics"
      },
      errorPlacement: function(label, element) {
        label.addClass('mt-2 text-danger');
        label.insertAfter(element);
      },
      highlight: function(element, errorClass) {
        $(element).parent().addClass('has-danger')
        $(element).addClass('form-control-danger')
      }

    });




  form.children("div").steps({
    headerTag: "h3",
    bodyTag: "section",
    transitionEffect: "slideLeft",
	onStepChanging: function(event, currentIndex, newIndex) {
     var valid = form.valid();
	 if(!valid) {
	    $validator.focusInvalid();
	  	return false;
	 }
	 else
		 return true;

    },
    onFinished: function(event, currentIndex) {

   if($("#frm_reg").valid())
		$("#frm_reg").submit();

    }
  });


  /*var validationForm = $("#example-validation-form");
  validationForm.val({
    errorPlacement: function errorPlacement(error, element) {
      element.before(error);
    },
    rules: {
      confirm: {
        equalTo: "#password"
      }
    }
  });


  validationForm.children("div").steps({
    headerTag: "h3",
    bodyTag: "section",
    transitionEffect: "slideLeft",
    onStepChanging: function(event, currentIndex, newIndex) {
      validationForm.val({
        ignore: [":disabled", ":hidden"]
      })
      return validationForm.val();
    },
    onFinishing: function(event, currentIndex) {
      validationForm.val({
        ignore: [':disabled']
      })
      return validationForm.val();
    },
    onFinished: function(event, currentIndex) {
      alert("Submitted!");
    }
  });


  var verticalForm = $("#example-vertical-wizard");
  verticalForm.children("div").steps({
    headerTag: "h3",
    bodyTag: "section",
    transitionEffect: "slideLeft",
    stepsOrientation: "vertical",
    onFinished: function(event, currentIndex) {
      alert("Submitted!");
    }
  });*/

   
   
   $("#sponsorID").on("keypress keyup blur paste change",function (event) {
	   
           $(this).val($(this).val().replace(/[^\d].+/, ""));
            if ((event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
			else
			{
				if($("#sponsorID").val().length==9)
				{

					  $.post("registeruser.php",
					  {
						refer_id: $("#sponsorID").val(),
						ajax : 1,

					  },

					  function(data, status){
						if(status)
						{
						  data = JSON.parse(data);
						  if(data.status==1)
						  {
							 $("#sponsorName").text(data.user_info.name + "  " + data.user_info.last_name);
						  }
						  else
						  {
							 $("#sponsorName").text("Invalid Member ID!");

						  }

						}

						else
						  {
							alert("Cannot get a response from the server. Please try later!");
							$('#finish').attr('disabled', true);

						  }
						
						});
				}

				
			}
    });


	$("#placementID").on("keypress keyup blur paste change",function (event) {    
           $(this).val($(this).val().replace(/[^\d].+/, ""));
		   
		   if ($("#placementID").val().length==0) 
		   {
			    $("#placementName").text("");

           }
			
		
		    else
			{   
			   if($("#placementID").val().length==9)
				{
				  
				  $.post("registeruser.php",
				  {
					refer_id: $("#placementID").val(),
					ajax : 1,
				  },

				  function(data, status){
					if(status)
					{
					  data = JSON.parse(data);

					  if(data.status==1)
					  {
						 $("#placementName").text(data.user_info.name + "  " + data.user_info.last_name);

						 if(data.user_info.tree_data.length == 2)
						 {
							$("#cmbPlacement").html("");
							$("#step_continue").attr("disabled",true);
							$("#placementID").val("");
							alert("Both leg of your Placement ID is occupied. Please enter a different Placement ID!");
							$("#placementName").text("");
						    $("#cmbPlacement").html("<option value=\"left\">Left</option><option value=\"right\">Right</option>");
						 }

						 else
						 {
							if(data.user_info.tree_data.length == 0)
							{
								$("#cmbPlacement").html("<option value=\"left\">Left</option><option value=\"right\">Right</option>");

							}
							else
							{
								if(data.user_info.tree_data[0].left_node==1)
									$("#cmbPlacement").html("<option value=\"right\">Right</option>");

								else
									$("#cmbPlacement").html("<option value=\"left\">Left</option>");

							}


						 }

					  }

					  else
					  {
						$("#placementName").text("Placement ID Invalid!");
						/*$("#lblPlacementName").attr("class","active");
						$("#step_continue").attr("disabled",true);*/
					  }
					}

					

					else
					  {
						alert("Cannot get a response from the server. Please try later!");
					  }

					});

			   
				}
			}

	});


	 $("#frm_reg").on('submit',(function(e){
		 e.preventDefault();
		 $("#cmbPlacement").removeAttr("disabled");
		 $("#loader_Registration").show();
		 $(".actions").hide();
         
		 $("#countryCode").val($("#mobileNumber").intlTelInput("getSelectedCountryData")['dialCode']);
		 //form_Data.append("countryCode",countryData['dialCode']);

		 $.ajax({
			type        : 'POST', 
			url         : 'registeruser.php', 
			data        : new FormData(this),
			dataType    : 'json', 
			encode      : true,
			cache		: false,
			contentType : false,
			processData : false,
			})

			.done(function(data){
			  $("#loader_Registration").hide();
			  $("#btnLogin").show();
			  $(".actions").show();


			  if(data.status==1){
				alert(data.message);
                if(data.page_type)
					location.href = "http://localhost/MyBooster/panel/my-network.php";

				else
					location.href = "http://localhost/MyBooster/";

			
			  }

			  else{
				alert(data.message);
			  } 

			}) 
			
			.fail(function(data){
				$("loader_Registration").hide();
			    $("#btnLogin").show();
				alert("Some error has occured. Please try again later!"); 
			});



		}));


		if($(window).width() < 767)
		{
			$("#steps-uid-0-t-0, #steps-uid-0-t-2").click(function(){

				$(".wizard .content").css("height","24em");


			});



			$("#steps-uid-0-t-1").click(function(){

				$(".wizard .content").css("height","34em");

			});
		}
		
		

			$("a").click(function(){

				$("#frm_reg").validate();
				//alert("hI");

			});


	$("#btnReset").click(function(e){
	   
		 var login_submit = $("#frmResetPassword").validate({
		   rules:{
				resetID:{
					required: true,
					digits: true
				 },
				 resetEmail:{
					required: true,
					email: true
				  },
				  otp_received:{
					required: true,
					digits: true,
					minlength: 4,
				  }
			},       
			messages:{
			   resetID:{
					required: 'Please enter your Member ID',
					digits  : 'Please enter a valid Member ID.'
				},
				resetEmail:{
					required: 'Please enter Email ID',
					digits  : 'Please enter a valid Email ID.'
				 },
				otp_received:{
					 required: 'Please enter OTP',
					 digits:'Please enter a valid OTP.',
					 minlength:'Please enter a valid OTP.',
				 }
			 },
			
			  errorPlacement: function(label, element) {
				label.addClass('mt-2 text-danger');
				label.insertAfter(element);
			  },
			  highlight: function(element, errorClass) {
				$(element).parent().addClass('has-danger')
				$(element).addClass('form-control-danger')
			  }
		  });

		 if($("#frmResetPassword").valid())
		  $("#frmResetPassword").submit();
	  });

	 
	  $("#frmResetPassword").on('submit',(function(e){

		  $("#btnReset").attr("disabled","disabled").css("cursor","wait");
		  e.preventDefault();
		  $("#loader").show();
		  $("#btnReset").hide();

		  	 
		  var formData = {
			'memberID': $('input[name=resetID').val(),
			'emailID': $('input[name=resetEmail]').val(),
			'otpRequest': $('input[name=otp_request]').val(),
			'otp_received': $('input[name=otp_received]').val(),
		  };

		  $.ajax({
			type        : 'POST', 
			url         : 'forgot-password.php', 
			data        : formData, 
			dataType    : 'json', 
			encode      : true
		  })

		  .done(function(data){
			$("div.loader").addClass("hide");
			$("#loader").hide();
		    $("#btnReset").show();

			if (data.status==1) {  
				
				if(data.OTPResponse==true){
					  $('#displaytitle').text("Confirm OTP");
				      $("#btnReset").text("Submit OTP");
					  $('#userCredential').addClass("d-none");
					  $('#userOTP').removeClass("d-none");
				 }

				 else{
					  alert(data.message);
					  location.reload();
				 }
		
			 }

			else{
				alert(data.message);
			} 
			$("#btnReset").removeAttr("disabled").css("cursor","pointer");;
		  }) 

		  .fail(function(data){
			 $("div.loader").addClass("hide");
			 $("#btnReset").removeAttr("disabled").css("cursor","pointer");;
		  });
	   
	  }))




$("#submitPasswordModal").click(function(e){
	   
		 var passwordModal = $("#frmPasswordModal").validate({
		   rules:{
				loginPassword:{
					required: true,
   	    	        minlength: 6,
				},
				loginPasswordConfirm:{
					required: true,
    	 			equalTo: "#loginPassword"
				},
				transPassword:{
					required: true,
					minlength: 6,
				},
				transPasswordConfirm:{
					required: true,
    				equalTo: "#transPassword",
				},
				motherName:{
					required: true,
				}			
			},       
			messages:{
				loginPassword:{
					required : 'Please enter your new login password.',
                    minlength: 'Your password must be at least 6 characters long.',
				},
				loginPasswordConfirm:{
					required: 'Please confirm your new login password.',
					equalTo : "New and Confirm Password should be same.",
				 },
				transPassword:{
					required   : 'Please enter your new transaction password.',
                    minlength  : 'Your password must be at least 6 characters long.',
		    	 },
				transPasswordConfirm:{
					 required: 'Please confirm your new transaction password.',
    				 equalTo : "New and Confirm Password should be same.",
		    	 },
				motherName:{
					 required: 'Please enter your mother\'s name.',
		    	 }

			 },
			
			  errorPlacement: function(label, element) {
				label.addClass('mt-2 text-danger');
				label.insertAfter(element);
			  },
			  highlight: function(element, errorClass) {
				$(element).parent().addClass('has-danger')
				$(element).addClass('form-control-danger')
			  }
		  });

		 if($("#frmPasswordModal").valid())
		  $("#frmPasswordModal").submit();

		
	  });

	 
	  $("#frmPasswordModal").on('submit',(function(e){

		 $("#submitPasswordModal").attr("disabled","disabled").css("cursor","wait");

		  e.preventDefault();
		  $("#loaderModal").show();
		  $("#submitPasswordModal").hide();
		  $("#closeModal").hide();

		  var formData = {
			'loginPassword': $('input[name=loginPassword').val(),
			'loginPasswordConfirm': $('input[name=loginPasswordConfirm]').val(),
			'transPassword': $('input[name=transPassword]').val(),
			'transPasswordConfirm': $('input[name=transPasswordConfirm]').val(),
			'motherName': $('input[name=motherName]').val(),
		  };


		  $.ajax({
			type        : 'POST', 
			url         : '../API/API_secureAccount.php', 
			data        :  formData, 
			dataType    : 'json', 
			encode      : true
		  })


		  .done(function(data){
			$("#loaderModal").hide();
		   	$("#submitPasswordModal").show();
		    $("#closeModal").show();

			if (data.success==1) {  
        		alert(data.message);
				location.reload();
		
			 }

			else{
				alert(data.message);
			}
			
			$("#submitPasswordModal").removeAttr("disabled").css("cursor","pointer");

		  }) 

		  .fail(function(data){
			 $("#loaderModal").hide();
			 $("#submitPasswordModal").show();
		     $("#closeModal").show();
        	 $("#submitPasswordModal").removeAttr("disabled").css("cursor","pointer");
		  });

		   
	  }))



})(jQuery);


	
	  