$(document).ready(function(){
    
 function  membercrypt(password = ''){
        var pass= password;
       // alert(pass);
        if (pass != " ")
        {
            var hvalue = CryptoJS.SHA256(pass);
           // alert(hvalue);
            return hvalue;
        }
      }
    
function  memberotptimercountdown(timer,timerdisplayattarid,resendotpbuttonattrid='')
{
    //alert(timerdisplayattarid);
    //alert("test");
    //alert(timer);
    var timer2 = timer;
    var interval = setInterval(function() {
      var timer = timer2.split(':');
      //by parsing integer, I avoid all extra string processing
      var minutes = parseInt(timer[0], 10);
      var seconds = parseInt(timer[1], 10);
      --seconds;
      minutes = (seconds < 0) ? --minutes : minutes;
      if (minutes < 0) clearInterval(interval);
      seconds = (seconds < 0) ? 59 : seconds;
      seconds = (seconds < 10) ? '0' + seconds : seconds;
      //minutes = (minutes < 10) ?  minutes : minutes;
      if(seconds > 0)
      {
        data = 'Resend OTP '+ minutes + ':' + seconds;
        if(data == 'Resend OTP -1:59')
        {
            $('#'+timerdisplayattarid).html(' ');
        }
        else
        {
            $('#'+timerdisplayattarid).html('Resend OTP '+ minutes + ':' + seconds);
        
        }

      }
      else
      {
          $('#'+timerdisplayattarid).html(' ');
          //$('#'+timerdisplayattarid).hide();
          $("#"+resendotpbuttonattrid).show();
          //timer2="00:00";
      }
      timer2 = minutes + ':' + seconds;
    }, 1000);
}



  $("#resendOtp").hide();
  $("#otpTxt").hide();

  $("#generateOtp").on("click",function(e){
    //  alert();
    e.preventDefault();        
    $(".error").html("");
    $(".error").css("display","none");

    
    
    var passwordval = $('#userpassword').val(); 
    var ogpasswordval = passwordval;
    var mobile = $("#mobile").val();
    var isd = $("#isd").val();
    var captcha = $("#membercaptcha").val();
    var username = $("#username").val();
   
    if(mobile !== '' && isd !== '' && captcha !== '' && username !== '' && passwordval != ''){
        
       // var passwordval = $('#userpassword').val(); 
        var haspass = membercrypt(passwordval);
        $('#userpassword').val(haspass);  
        var passwordval1 = $('#userpassword').val(); 
        
      $.ajax({
        type:'POST',
        data:{mobile:mobile,isd:isd,captcha:captcha,username:username,userpassword:passwordval1},
        url:CI_ROOT+"member/generateOtp",
        dataType: "json",
        beforeSend:function(){
          $("#preloader").show(); 
          $("#status").show(); 
        },
        success:function(result){
          $("#preloader").hide(); 
          $("#status").fadeOut();
            $('#userpassword').val(ogpasswordval); 
            $('#membercaptcha').val(''); 
            captcharefresh();
            
          if(result.status == "success"){
            //$("#resendOtp").show();
            $("#otpTxt").show();
            $("#generateOtp").hide();
             $("#otp_text").slideDown();
             $("#countdownotp").html('');
            memberotptimercountdown("0:59","countdownotp","resendOtp");
          }else if(result.status == "error"){
            swal({
              title: "Error",
              icon: "error",
              text: result.msg
            });
          }else if(result.status == "invalid"){
            swal({
              title: "Invalid Request!",
              icon: "error",
              text: "Something went wrong ! Please try again."
            });
          }else if(result.status == "invalid_member"){
            swal({
              title: "Invalid Request!",
              icon: "error",
              text: "username or password or mobile no is invalid."
            });
          }
          else if(result.status == "CaptchaIncorrect"){
            swal({
              title: "Captcha is Incorrect !",
              icon: "error",
              text: ""
            });
          }else if(result.status == "blocked"){
            swal({
              title: "Blocked",
              icon: "error",
              text: "Your mobile no is blocked as you have reached maximum attempt limit for otp verification."
            });
          }else{
            $.each(result, function(i, v){
              $("label[for='"+i+"']").html(v);
            });
                      
            var keys = Object.keys(result);
            $(".error").css("display","block");
            $('input[name="'+keys[0]+'"]').focus();
          }
        }
      });
    }else if(mobile == ''){
      $("label[for='mobile']").html("mobile number is required.");
      $(".error").css("display","block");
      $('input[name="mobile"]').focus();
    }else if(isd == ''){  
      $("label[for='isd']").html("required.");
      $(".error").css("display","block");
      $('select[name="isd"]').focus(); 
    }
    else if(username == ''){  
      $("label[for='username']").html("username is required.");
      $(".error").css("display","block");
      $('input[name="username"]').focus(); 
    }
    else if(passwordval == ''){  
      $("label[for='password']").html("password is required.");
      $(".error").css("display","block");
      $('input[name="userpassword"]').focus(); 
    }
    else if(captcha == ''){  
      $("label[for='membercaptcha']").html("captcha is required.");
      $(".error").css("display","block");
      $('#membercaptcha').focus(); 
    }
  }); 

  $("#resendOtp").on("click",function(e){
    e.preventDefault();        
    $(".footer_error").html("");
    $(".footer_error").css("display","none");

   var passwordval = $('#userpassword').val(); 
   var ogpasswordval = passwordval;
    var mobile = $("#mobile").val();
    var isd = $("#isd").val();
    var captcha = $("#membercaptcha").val();
    var username = $("#username").val();
    
    if(mobile !== '' && isd !== '' && captcha !== '' && username !== '' && passwordval !== ''){
        
        var haspass = membercrypt(passwordval);
        $('#userpassword').val(haspass);  
        var passwordval1 = $('#userpassword').val(); 
      $.ajax({
        type:'POST',
        //data:{mobile:mobile,isd:isd},
        data:{mobile:mobile,isd:isd,captcha:captcha,username:username,userpassword:passwordval1},
        url:CI_ROOT+"member/generateOtp",
        dataType: "json",
        beforeSend:function(){
          $("#preloader").show(); 
          $("#status").show();  
        },
        success:function(result){
          $("#preloader").hide(); 
          $("#status").fadeOut();
             $('#userpassword').val(ogpasswordval); 
             $('#membercaptcha').val(''); 
             
             captcharefresh();
          if(result.status == "success"){
            $("#resendOtp").hide();
            $("#otpTxt").show();
            $("#generateOtp").hide();
             $("#countdownotp").html('');
            memberotptimercountdown("0:59","countdownotp","resendOtp");
                        
          }else if(result.status == "error"){
            swal({
              title: "Error",
              icon: "error",
              text: result.msg
            });
          }else if(result.status == "invalid"){
            swal({
              title: "Invalid Request!",
              icon: "error",
              text: "Something went wrong ! Please try again."
            });
          }else if(result.status == "invalid_member"){
            swal({
              title: "Invalid Request!",
              icon: "error",
              text: "username or password or mobile no is invalid."
            });
          }
          else if(result.status == "CaptchaIncorrect"){
            swal({
              title: "Captcha is Incorrect !",
              icon: "error",
              text: ""
            });
          }else if(result.status == "blocked"){
            swal({
              title: "Blocked",
              icon: "error",
              text: "Your mobile no is blocked as you have reached maximum attempt limit for otp verification."
            });
          }else{
            $.each(result, function(i, v){
              $("label[for='"+i+"']").html(v);
            });
                      
            var keys = Object.keys(result);
            $(".error").css("display","block");
            $('input[name="'+keys[0]+'"]').focus();
          }
        }
      });
    }else if(mobile == ''){
      $("label[for='mobile']").html("Mobile is required.");
      $(".error").css("display","block");
      $('input[name="mobile"]').focus();
    }else if(isd == ''){  
      $("label[for='isd']").html("Required.");
      $(".error").css("display","block");
      $('select[name="isd"]').focus(); 
    }else if(username == ''){  
      $("label[for='username']").html("username is required.");
      $(".error").css("display","block");
      $('input[name="username"]').focus(); 
    }else if(passwordval == ''){  
      $("label[for='password']").html("password is required.");
      $(".error").css("display","block");
      $('input[name="userpassword"]').focus(); 
    }
    else if(captcha == ''){  
      $("label[for='membercaptcha']").html("captcha is required.");
      $(".error").css("display","block");
      $('#membercaptcha').focus(); 
    }
  }); 

  $("#memberLoginForm").on("submit",function(e){
   
    
    var memberoptval = $('#otp').val(); 
    if(memberoptval !== '')
    {
        e.preventDefault();        
        $(".error").html("");
        $(".error").css("display","none");
        //alert(memberoptval);
        var memberhasotp = membercrypt(memberoptval);
        //alert(memberhasotp);
        $('#otp').val(memberhasotp); 
        
        var passwordval = $('#userpassword').val(); 
        var ogpasswordval = passwordval;
        var haspass = membercrypt(passwordval);
        $('#userpassword').val(haspass);  
        var formdata = $(this).serialize();
    
    $.ajax({
      type:'POST',
      data:formdata,
      url:CI_ROOT+"member/loginAction",
      dataType: "json",
      beforeSend:function(){
				$("#preloader").show(); 
				$("#status").show(); 
			},
      success:function(result){
        $("#preloader").hide(); 
        $("#status").fadeOut();
         $('#userpassword').val(ogpasswordval); 
        if(result.status == "success"){
          window.location.href = result.url;
        }else if(result.status == "invalid"){
          swal({
            title: "Invalid Request!",
            icon: "error",
            text: "Something went wrong ! Please try again."
          });
        }else if(result.status == "otp_missing"){
          if($("#otpTxt").is(":visible")){
            $("label[for='otp']").html('Please enter otp');
            $(".error").css("display","block");
            $("input[name='otp']").focus();
          }else{
            swal({
              title: "Verify Mobile",
              icon: "error",
              text: "Please verify your mobile number by clicking Generate OTP."
            });
          }
        }else if(result.status == "blocked"){
          swal({
            title: "Blocked",
            icon: "error",
            text: "Your mobile number is blocked as you have reached maximum attempt limit for otp verification."
          });
        }else if(result.status == "invalid_member"){
          swal({
            title: "Invalid",
            icon: "error",
            text: "Username & Password does not match"
          });
        }else{
          $.each(result, function(i, v) {
            $("label[for='"+i+"']").html(v);
          });
                    
          var keys = Object.keys(result);
          $(".error").css("display","block");
          $('input[name="'+keys[0]+'"]').focus();
        }
      }
    });
    
  }
  else
  {
      if(memberoptval == ''){  
         swal({
              title: "Please verify your mobile number by clicking Generate OTP.",
              icon: "error",
              text: ""
            });
    }
  }
  });
});