<?php
$fgh = getFullPaymentSettings();


$dsbj = @$fgh['result']['data'][0]['paymentGatewayoffon'];
if (empty($dsbj)) {
} else {

  foreach ($dsbj as $key => $dd) {
    if ($dd['source'] == 'WEBSITE') {
      $paymentSeverOn = $dd['isenable'];
      $paymentSeverText = $dd['desc'];
    }
  }
}

$paymentSetting = @getPaymentGatewaySettings();



// print_r($fgh);

// die();

?>

<!-- date picker -->
<script src="<?= base_url('assets/js/jquery-ui.min.js'); ?>"></script>
<!-- date picker -->
<script src="<?= base_url('assets/js/notify.js') ?>"></script>
<script src="<?= base_url('assets/js/notify.min.js') ?>"></script>
<script src="<?= base_url('assets/js/toast.js') ?>"></script>

<a href="#" class="back-to-top d-flex align-items-center justify-content-center" style="background-color:var(--headerFooter)!important;"><i class="bi bi-arrow-up-short"></i></a>

<!-- <div class="back-to-top d-flex align-items-center justify-content-center" style="background-color:var(--headerFooter)!important;"><div class="shdv"> -->

<!-- </div></div> -->


<!-- Vendor JS Files -->
<script src="<?= base_url('assets/vendor/aos/aos.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/glightbox/js/glightbox.min.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/swiper/swiper-bundle.min.js'); ?>"></script>

<!-- Template Main JS File -->
<script src="<?= base_url('assets/js/main.js'); ?>"></script>

<script type="text/javascript">
  $('#tabs .nav-link2').on('click', function() {
    const activeTab = $('.nav-link2.active');

    if (activeTab.attr('tab-name') === 'Devotee') {
      $('#signupLink').hide();
    } else {
      $('#signupLink').show();
    }
  });

  var loader = new ldLoader({
    root: ".ldld.full"
  });
  if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
    loader.on();
  }

  document.addEventListener("click", function(event) {
    if (event.target.matches(".navlink-reload, .loader")) {
      // loader.on();
    } else if (event.target.matches(".navlink, .loader")) {
      loader.on();
    }
  });

  window.onload = function() {
    loader.off();
  };

  $(function() {
    $('#timepicker').mdtimepicker();
    $('.modal').modal({
      backdrop: 'static',
      keyboard: false
    });
  });
  $("#loginBtn").hide();




  function checkLoginStatus(serviceAmt = '', serviceName = '', service_Id = '', serviceCategoryTypes = '', serviceTypes = '', dayTypes = '', startDate = '', startTime = '') {

    loader.on();

    if (serviceAmt == 'OUTSIDE') {
      pageName = 'REQUEST-OUTSIDE';
    } else if (serviceAmt == 'APARAKARYA') {
      pageName = 'APARAKARYA';
    } else if (serviceAmt == 'REQUEST-FORM') {
      pageName = 'REQUEST-FORM';
    } else if (serviceAmt == 'PAY-LATER') {
      pageName = 'PAY-LATER';
    } else if (serviceAmt == 'facilitiesPage') {
      pageName = 'facilitiesPage';
    } else if (serviceAmt == 'checkout') {
      pageName = 'checkout';
    } else if (serviceAmt == 'TodayPanchangamMail') {
      pageName = 'TodayPanchangamMail';
    } else if (serviceAmt == 'partishipent_events') {
      $("#hpEvntName").val(serviceName);
      $("#hpEvntName1").val(serviceCategoryTypes);
      $("#hEvtCount").val(serviceTypes);
      $("#hEvntStartDate").val(dayTypes);
      $("#hEvntendDate").val(startDate);
      pageName = 'partishipent_events';
    } else if (serviceAmt == 'checkout_prasadam') {
      pageName = 'checkout_prasadam';
    }else if (serviceAmt == 'checkout_akshaya_patra') {
      pageName = 'checkout_akshaya_patra';
    } else if (serviceAmt == 'checkout_akshaya_patra') {
      pageName = 'checkout_akshaya_patra';
    } else {
      pageName = '';

    }


    var amt = (serviceAmt / 1).toFixed(2);
    var serviceName = serviceName;
    var serviceId = service_Id;

    var serviceCategoryTypes = serviceCategoryTypes;
    var serviceTypes = serviceTypes;
    var dayTypes = dayTypes;
    var startDate = startDate;
    var startTime = startTime;



    if (serviceCategoryTypes == 'DONATIONS') {
      $("#dateTimeTable").css('display', 'none');
    }
    if ($("#DonateToTemple").val() == 'DONATIONS') {
      $("#DonateToTemple").val('')
    };

    if (serviceCategoryTypes == 'DONATIONS' && amt == 0.00) {
      $("#edittable").html('<input style="text-align: right;" type="number" class="form-control currency" id="serviceAmt" min="1.00" value="1.00" required/>');
    } else {

      $("#edittable").html('<h4 id="servicePrice">' + amt + '</h4><input type="hidden" name="" value="' + amt + '" id="serviceAmt">');
    }

    // event.preventDefault();
    $.ajax({
      url: "<?= base_url('check-login-status'); ?>",
      type: "POST",
      dataType: "json",
      success: function(data) {
        loader.off();
        if (data == 0) {
          $("#signupModal").modal("hide");
          $("#EventDetailsModal").modal("hide");
          $('#servicePrice').text('$' + amt);
          $('#serviceName').text(serviceName);

          if (serviceCategoryTypes == 'EVENTS') {

            $('#fullPackage').val('true');
          }


          $('#serviceId').val(serviceId);
          if (amt != 0.00) {
            $('#serviceAmt').val(amt);
          }
          openLoginModal(pageName);
          $('#serviceCategoryTypes').val(serviceCategoryTypes);
          $('#serviceTypes').val(serviceTypes);
          $('#dayTypes').val(dayTypes);
          $('#startDate').val(startDate);
          $('#serviceStartDate').val(startDate);
          $('#startTime').val(startTime);
          $('#timepicker').val(startTime);

        } else {

          if (pageName == 'REQUEST-FORM') {

            window.location.href = "<?= base_url('services/serviceRequest'); ?>";
          } else if (pageName == 'REQUEST-OUTSIDE') {
            window.location.href = "<?= base_url('services/request/outside-temple'); ?>";
          } else if (pageName == 'APARAKARYA') {
            window.location.href = "<?= base_url('services/request/aparakarya'); ?>";
          } else if (pageName == 'PAY-LATER') {
            window.location.href = "<?= base_url('services/payLater'); ?>";
          } else if (pageName == 'facilitiesPage') {
            window.location.href = "<?= base_url('facilities'); ?>";
          } else if (pageName == 'checkout') {
            window.location.href = "<?= base_url('checkout'); ?>";
          } else if (pageName == 'checkout_prasadam') {
            window.location.href = "<?= base_url('checkout_prasadam'); ?>";
          } else if (pageName == 'checkout_akshaya_patra') {
            window.location.href = "<?= base_url('checkout_akshaya_patra'); ?>";
          } else if (pageName == 'TodayPanchangamMail') {
            SendPanchangamMailPdf();
          } else if (pageName == 'partishipent_events') {
            // $("#pEvntName").text(serviceName);
            // $("#pEvntName1").text(serviceCategoryTypes);
            // $("#inppEvntName").val(serviceName);
            // $("#inppEvntName1").val(serviceCategoryTypes);
            // $("#inppEvntId").val(serviceId);
            // $("#EvtCount").attr("max", serviceTypes);
            // $("#EvntDate").attr("min", dayTypes);
            // $("#EvntDate").attr("max", startDate);
            // $("#partishipent_events-Modal").modal("show");

            OpenEventPartishipentModal(serviceId);
          } else if (serviceCategoryTypes == 'EVENTS') {

            $('#fullPackage').val('true');
          } else {


            $("#loginModal").modal("hide");
            $('#servicePrice').text('$' + amt);
            $('#serviceName').text(serviceName);
            $('#serviceId').val(serviceId);
            $('#serviceCategoryTypes').val(serviceCategoryTypes);
            $('#serviceTypes').val(serviceTypes);
            $('#dayTypes').val(dayTypes);
            $('#startDate').val(startDate);
            $("#serviceStartDate").val(startDate);
            $('#startTime').val(startTime);
            $("#timepicker").val(startTime);
            if (amt != 0.00) {
              $('#serviceAmt').val(amt);
            }

            $.ajax({
              url: "<?= base_url('Home/getServiceDetailsById'); ?>",
              type: "POST",
              data: {
                'serviceId': serviceId
              },
              success: function(serviceDetails) {
                loader.off();
                var details = JSON.parse(serviceDetails);
                console.log("details====");
                console.log(details);
                if (serviceCategoryTypes == 'EVENTS') {

                  $('#fullPackage').val('true');
                }

                if (serviceDetails != '') {
                  $("#servicesDetails").html();

                  if (details.startDate != '') {
                    if ($("#serviceStartDate").val() != '') {
                      $("#serviceStartDate").val('');
                    }
                    $("#serviceStartDate").val('');
                    $("#serviceStartDate").val(details.startDate);
                    $("#serviceStartDate").prop('readonly', true);
                  } else {
                    if ($("#serviceStartDate").val() != '') {
                      $("#serviceStartDate").val('');
                    }
                    $("#serviceStartDate").val('');
                    $("#serviceStartDate").val(details.startDate);
                    $("#serviceStartDate").prop('readonly', false);
                  }

                  if (details.startTime != '') {

                    if ($("#timepicker").val() != '') {
                      $("#timepicker").val('');
                    }

                    $("#timepicker").val(details.startTime);
                    $("#timepicker").prop('readonly', true);
                    $("#timepicker").prop('disabled', true);


                  } else {
                    if ($("#timepicker").val() != '') {
                      $("#timepicker").val('');
                    }

                    $("#timepicker").val(details.startTime);
                    $("#timepicker").prop('readonly', false);
                    $("#timepicker").prop('disabled', false);
                  }


                  $("#modaleventCloseBtn").click();
                  if ($("#fromPage").val() == 'membership-form') {

                    $("#membershipModal").modal("show");

                  } else {
                    $("#paymentModal").modal("show");
                  }
                }
              }
            });



            if ($("#serviceCategoryTypes").val() == 'AWAY-TEMPLE') {
              $("#addressField").html('<p>Please Select Your Service Location:</p> <input type="radio" id="home" name="ServiceAddress" value="home" checked required>  <label for="home">Home</label><br> <input type="radio" id="other" name="ServiceAddress" value="other">  <label for="other">Other Location</label><br><textarea class="form-control my-3" placeholder="Enter Your Full address" id="Address" name="Address" style="display:none" required></textarea>');


              $('input:radio[name="ServiceAddress"]').change(function() {
                if ($(this).val() == 'home') {
                  $("#Address").css('display', 'none');
                } else {
                  $("#Address").css('display', 'inline-flex');
                }
              });

            }
          }
        }
      }
    });
  }


  function subscribeNewsletterCheckLogin() {
    loader.on();

    // event.preventDefault();
    $.ajax({
      url: "<?= base_url('check-login-status'); ?>",
      type: "POST",
      dataType: "json",
      success: function(data) {
        loader.off();
        if (data == 0) {
          openLoginModal('newsletter');
        } else {
          subscribeNewsletter();
        }

      }
    });
  }

  function subscribeNewsletter() {

    // event.preventDefault();

    loader.on();
    $.ajax({
      url: "<?= base_url('Home/subscribeNewsletter'); ?>",
      type: "POST",
      dataType: "json",
      success: function(data) {
        // alert(data);
        loader.off();

        swal({
            html: true,
            title: data,
            type: "success",
            confirmButtonText: 'OK',
            confirmButtonColor: 'var(--main-color-new-theme)',
          },

          function() {
            if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
              window.location.href = "<?= base_url('logout'); ?>"
            } else {
              window.location.reload();
            }

          });
      }
    });

  }

  function openLoginModal(page = '') {


    var fromPage = page;
    if (page.length > 0) {
      $("#fromPage").val(page);
    }
    $("form").get(0).reset();

    var emailotpntn = document.getElementById('emailotpntn');

    emailotpntn.disabled = false;
    emailotpntn.innerText = 'LOGIN';
    $("#loginPhoneNumber").val('+1');
    $("#loginEmail").val('');
    $('.signupBtnClose').click();
    $("#signupModal").modal("hide");
    $("#loginModal").modal("show");


    $(".vOtpBox").hide();
    $("#emailotpntn").show();
    $(".mobile_section").show();
    $(".email_section").show();
  }

  function openSignupModal() {
    $("form").get(0).reset();
    $('#signupEmail').attr("disabled", false);
    $("#signup-error-flashmsg1").removeClass("d-none");
    var signupBtn = document.getElementById('signupBtn');


    $("#signupEmail").attr("placeholder", "Enter Email - Head of Household");
    $("#fname").attr("placeholder", "Enter First Name - Head of Household");
    $("#lname").attr("placeholder", "Enter Last Name - Head of Household");

    $('#companySection').addClass("d-none");
    // $('#addCompanySection').addClass("d-none");
    $('#addCompany').prop('checked', false);
    $("#companyEmail").removeAttr('readonly');
    $("#companyEmail").val("");
    $("#companyFirstName").val("");
    $("#companyLastName").val("");
    $("#companyPhone").val('+1');

    $('#companyEmail, #companyFirstName, #companyPhone').prop('required', false);


    $("#signupBtn").removeClass('d-none');
    $("#verifySignupEmailbtn").text('VERIFY');
    $("#verifySignupEmailbtn").removeAttr('disabled');
    $("#signupBtnAlert").removeClass('d-none');
    $("#signupBtn").addClass('d-none');
    // signupBtn.disabled = false;
    signupBtn.innerText = 'REGISTER';
    $('.loginBtnClose').click();
    $("#loginModal").modal("hide");
    $("#loginModal2").modal("hide");
    $("#signupModal").modal("show");
  }

  function startTimer() {

    resendButton.disabled = true;

    let timeLeft = 120;
    let minutes, seconds;

    timerMessage.style.display = "block";
    resendButton.style.display = "none";

    const countdown = setInterval(() => {
      minutes = Math.floor(timeLeft / 60);
      seconds = timeLeft % 60;
      timeCounter2.innerText = `${minutes}:${seconds.toString().padStart(2, "0")}`;

      timeLeft--;

      if (timeLeft === 0) {
        clearInterval(countdown);
        timerMessage.style.display = "none";
        resendButton.style.display = "block";
        resendButton.disabled = false;
      }
    }, 1000);
  }

  function sendEmailOtp(url) {



    loader.on();
    //test
    var email = $('#loginEmail').val();
    var phoneval = $('#loginPhoneNumber').val();
    var phoneLength = $('#loginPhoneNumber').val().length;

    if (email == "" && phoneLength < 12) {


      showToast({
        eleWrapper: '#login-error-flashmsg',
        msg: 'Please enter valid email or valid mobile number.',
        theme: 'warning',
        closeButton: false,
        autoClose: true,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });
      loader.off();

    } else {
      $("#login-error-flashmsg").html("");

      if (email == "") {
        // event.preventDefault();
        LoginUser('<?= base_url('signin'); ?>');
        loader.off();
      } else {

        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if (email.match(mailformat)) {
          var btn = document.getElementById('emailotpntn');
          btn.disabled = true;
          btn.innerText = 'SENDING';


          // event.preventDefault();
          var url = url;
          var email = $('#loginEmail').val();

          const activeLoginTab = $('.nav-link.active');
          const LoginTabName = activeLoginTab.attr('tab-name');

          $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: {
              'email': email,
              'LoginTabName': LoginTabName
            },
            success: function(data) {
              loader.off();


              if (data['statusCode'] == '1') {

                $("#emailotpntn").hide();
                $(".mobile_section").hide();

                btn.disabled = true;
                btn.innerText = 'SENT';
                $('#otptoggle').css('display', 'inline-flex');
                var btn2 = document.getElementById('emailotpverifybtn');
                btn2.disabled = false;
                btn.disabled = true;


                $("#AdministratorTab").addClass('disabled');
                $("#devoteeTab").addClass('disabled');




                startTimer();


                $("#emailotp").focus();

                showToast({
                  eleWrapper: '#login-success-flashmsg',
                  msg: 'OTP sent on this email id!',
                  theme: 'success',
                  closeButton: false,
                  autoClose: true,
                  afterShow: function() {
                    console.log('After show function');
                  },
                  afterClose: function() {
                    console.log('After close function');
                  }
                });

                $(".mobile-section").hide();

              } else if (data['statusCode'] == '2') {
                btn.disabled = false;
                btn.innerText = 'LOGIN';

                showToast({
                  eleWrapper: '#login-success-flashmsg',
                  msg: 'Technical Error! Please Login With Phone Number or Contact Admin.',
                  theme: 'error',
                  closeButton: false,
                  autoClose: true,
                  afterShow: function() {
                    console.log('After show function');
                  },
                  afterClose: function() {
                    console.log('After close function');
                  }
                });
              } else {


                if (LoginTabName == 'Management') {

                  btn.disabled = false;
                  btn.innerText = 'LOGIN';


                  showToast({
                    eleWrapper: '#login-error-flashmsg',
                    msg: 'This email id is not registered please signup.',
                    theme: 'error',
                    closeButton: false,
                    autoClose: true,
                    afterShow: function() {
                      console.log('After show function');
                    },
                    afterClose: function() {
                      console.log('After close function');
                    }
                  });

                } else {

                  showToast({
                    eleWrapper: '#signup-error-flashmsg',
                    msg: 'This email id is not registered please signup.',
                    theme: 'error',
                    closeButton: false,
                    autoClose: true,
                    afterShow: function() {
                      console.log('After show function');
                    },
                    afterClose: function() {
                      console.log('After close function');
                    }
                  });


                  $("#loginModal").modal('hide');
                  $("#signupModal").modal('show');

                  $("#signupEmail").val(email);


                }
              }
            }
          });

        } else {
          btn.disabled = false;
          btn.innerText = 'LOGIN';

          showToast({
            eleWrapper: '#login-error-flashmsg',
            msg: 'Please enter a valid email address.',
            theme: 'warning',
            closeButton: false,
            autoClose: true,
            afterShow: function() {
              console.log('After show function');
            },
            afterClose: function() {
              console.log('After close function');
            }
          });
          loader.off();
        }

      }
      loader.off();
    }
  }

  function verifyEmailOtp(url) {
    loader.on();
    var btn = document.getElementById('emailotpverifybtn');
    btn.disabled = true;
    btn.innerText = 'VERIFYING';


    // event.preventDefault();
    var url = url;
    var otp = $('#emailotp').val();

    if (otp == "") {
      $("#login-success-flashmsg").html("");

      showToast({
        eleWrapper: '#login-error-flashmsg',
        msg: 'Please enter 6 digit OTP!',
        theme: 'warning',
        closeButton: false,
        autoClose: true,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });
      btn.disabled = false;
      btn.innerText = 'VERIFY';
      loader.off();

    } else {
      var email = $('#loginEmail').val();
      $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: {
          'otp': otp,
          'email': email
        },
        success: function(data) {
          loader.off();

          if (data['statusCode'] == 1) {
            btn.disabled = true;
            btn.innerText = 'VERIFIED';
            if ($("#includeSankalpamModal").val() == 'YES') {
              $("#loginModal").modal("hide");
            }
            PhoneLogin('<?= base_url('signin'); ?>');

          } else {
            $("#login-error-flashmsg").html("");
            $("#login-success-flashmsg").html("");


            showToast({
              eleWrapper: '#login-error-flashmsg',
              msg: data['message'],
              theme: 'warning',
              closeButton: false,
              autoClose: true,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });
            btn.disabled = false;
            btn.innerText = 'VERIFY';
          }


        }
      });
    }
  }




  function LoginUser(url) {
    loader.on();
    var btn = document.getElementById('emailotpntn');
    btn.disabled = true;
    btn.innerText = 'PLEASE WAIT...';

    // event.preventDefault();
    var url = url;
    var email = $('#loginEmail').val();
    var phone = $('#loginPhoneNumber').val();

    var newphone = 0;
    var cuntryCode = $("#loginModal .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    var value = phone.replace(cuntryCode, '');
    newphone = value;



    const activeLoginTab = $('.nav-link.active');

    const LoginTabName = activeLoginTab.attr('tab-name');




    $.ajax({
      url: url,
      type: "POST",
      dataType: "json",
      data: {
        'email': email,
        'phone': newphone,
        'LoginTabName': LoginTabName
      },
      success: function(data) {
        loader.off();
        console.log(data);

        if (data.statusCode == 1) {
          btn.disabled = true;
          btn.innerText = 'SENT';

          if (phone != "") {
            submitPhoneNumberAuth();
            $("#emailotpntn").hide();
            $(".email_section").hide();
            $("#loginPhoneNumber").attr('disabled', 'disabled');
          } else {

            $('#otptoggle').css("display", "none");

            var btn2 = document.getElementById('emailotpverifybtn');
            btn2.disabled = false;
            btn.disabled = true;

            // alert('Login Successful.');
            $('.loginBtnClose').click();
            $("#loginModal").modal("hide");

            if ($("#fromPage").val() == 'membership-form') {
              console.log(data.data[0].memberShipExpiryDate);
              if (data.data[0].memberShipExpiryDate) {
                const today = new Date();
                const targetDate = new Date(data.data[0].memberShipExpiryDate);

                if (data.data[0].membershipStatus && today.getTime() <= targetDate.getTime() && data.data[0].membershipStatus == 'ACTIVE') {
                  // alert('Ypur are already member');
                  swal({
                      html: true,
                      title: "Your are already a member!",
                      text: "Your are already a member! ",
                      type: "warning",
                      confirmButtonText: 'OK',
                      confirmButtonColor: 'var(--main-color-new-theme)',
                      // timer:5000,
                    },

                    function() {

                      window.location.href = "<?= base_url('admin/membership'); ?>"


                    });
                } else {
                  $("#membershipModal").modal("show");
                }
              } else {
                if (data.data[0].membershipStatus && data.data[0].membershipStatus == 'ACTIVE') {
                  // alert('Ypur are already member');
                  swal({
                      html: true,
                      title: "Your are already a member!",
                      text: "Your are already a member! ",
                      type: "warning",
                      confirmButtonText: 'OK',
                      confirmButtonColor: 'var(--main-color-new-theme)',
                      // timer:5000,
                    },

                    function() {

                      window.location.href = "<?= base_url('admin/membership'); ?>"


                    });
                } else {
                  $("#membershipModal").modal("show");
                }
              }

            } else {
              $("#paymentModal").modal("show");
            }

          }

        } else {


          showToast({
            eleWrapper: '#signup-error-flashmsg',
            msg: 'This phone no. is not registered please signup.',
            theme: 'error',
            closeButton: false,
            autoClose: true,
            afterShow: function() {
              console.log('After show function');
            },
            afterClose: function() {
              console.log('After close function');
            }
          });

          if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
            openBoxlog('signup');
            btn.disabled = false;
            btn.innerText = 'LOGIN';
          } else {


            if (LoginTabName == 'Management') {

              btn.disabled = false;
              btn.innerText = 'LOGIN';


              showToast({
                eleWrapper: '#login-error-flashmsg',
                msg: 'This phone no. is not registered please signup.',
                theme: 'error',
                closeButton: false,
                autoClose: true,
                afterShow: function() {
                  console.log('After show function');
                },
                afterClose: function() {
                  console.log('After close function');
                }
              });

            } else {

              $("#signupEmail").val(email);
              $("#signupPhoneNumber").val(phone);
              $("#loginModal").modal('hide');
              $("#signupModal").modal('show');

            }
          }
        }



      }
    });

  }


  //Phone Login

  function PhoneLogin(url) {

    // event.preventDefault();
    loader.on();
    var url = url;
    var email = $('#loginEmail').val();
    var phone = $('#loginPhoneNumber').val();
    var newphone = 0;
    var cuntryCode = $("#loginModal .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    var value = phone.replace(cuntryCode, '');
    newphone = value;



    const activeLoginTab = $('.nav-link.active');
    const LoginTabName = activeLoginTab.attr('tab-name');
    console.log(LoginTabName);



    $.ajax({
      url: url,
      type: "POST",
      dataType: "json",
      data: {
        'email': email,
        'phone': newphone,
        'sessionCreate': 1,
        'LoginTabName': LoginTabName
      },
      success: function(data) {
        loader.off();
        console.log(data);
        if (data.statusCode == 1) {
          // alert('Login Successful.');
          $(".dotlgbtn").text('MY ACCOUNT');

          if ($('#serviceId').val()) {
            $('.loginBtnClose').click();
            $("#loginModal").modal("hide");
            if ($("#fromPage").val() == 'membership-form') {
              // console.log("details[0]");
              // console.log(data.data[0]);
              console.log(data.data[0].memberShipExpiryDate);
              if (data.data[0].memberShipExpiryDate) {
                const today = new Date();
                const targetDate = new Date(data.data[0].memberShipExpiryDate);

                if (data.data[0].membershipStatus && today.getTime() <= targetDate.getTime() && data.data[0].membershipStatus == 'ACTIVE') {
                  // alert('Ypur are already member');
                  swal({
                      html: true,
                      title: "Your are already a member!",
                      text: "Your are already a member! ",
                      type: "warning",
                      confirmButtonText: 'OK',
                      confirmButtonColor: 'var(--main-color-new-theme)',
                      // timer:5000,
                    },

                    function() {

                      window.location.href = "<?= base_url('admin/membership'); ?>"


                    });
                } else {
                  $("#membershipModal").modal("show");
                }
              } else {
                if (data.data[0].membershipStatus && data.data[0].membershipStatus == 'ACTIVE') {
                  // alert('Ypur are already member');
                  swal({
                      html: true,
                      title: "Your are already a member!",
                      text: "Your are already a member! ",
                      type: "warning",
                      confirmButtonText: 'OK',
                      confirmButtonColor: 'var(--main-color-new-theme)',
                      // timer:5000,
                    },

                    function() {

                      window.location.href = "<?= base_url('admin/membership'); ?>"


                    });
                } else {
                  $("#membershipModal").modal("show");
                }
              }


            } else if ($("#fromPage").val() == 'partishipent_events') {
              // $("#pEvntName").text($("#hpEvntName").val());
              // $("#pEvntName1").text($("#hpEvntName1").val());
              // $("#inppEvntName").val($("#hpEvntName").val());
              // $("#inppEvntName1").val($("#hpEvntName1").val());
              // $("#inppEvntId").val($('#serviceId').val());
              // $("#EvtCount").attr("max", $("#hEvtCount").val());
              // $("#EvntDate").attr("min", $("#hEvntStartDate").val());
              // $("#EvntDate").attr("max", $("#hEvntendDate").val());
              // $("#partishipent_events-Modal").modal("show");

              OpenEventPartishipentModal($('#serviceId').val());
            } else if ($("#fromPage").val() == 'TodayPanchangamMail') {
              SendPanchangamMailPdf();
            } else {
              $("#paymentModal").modal("show");
            }


          } else if ($('#donateToTempleBtnBeforeLogin').val()) {
            $('.loginBtnClose').click();
            $("#loginModal").modal("hide");
            $("#DonateToTemple").val('DONATIONS');
            $("#DonateToTemplePaymentModal").modal("show");

          } else {
            if ($("#fromPage").val() == 'newsletter') {
              $('.loginBtnClose').click();
              $("#loginModal").modal("hide");
              subscribeNewsletter();

            } else if ($("#fromPage").val() == 'REQUEST-FORM') {
              window.location.href = "<?= base_url('services/serviceRequest'); ?>";
            } else if ($("#fromPage").val() == 'REQUEST-OUTSIDE') {
              window.location.href = "<?= base_url('services/request/outside-temple'); ?>";
            } else if ($("#fromPage").val() == 'APARAKARYA') {
              window.location.href = "<?= base_url('services/request/aparakarya'); ?>";
            } else if ($("#fromPage").val() == 'MAKE-PAYMENTS-FORM') {
              window.location.href = "<?= base_url('services/MakePayment'); ?>";
            } else if ($("#fromPage").val() == 'events') {
              window.location.href = "<?= base_url('events/checkout'); ?>";
            } else if ($("#fromPage").val() == 'facilitiesPage') {
              window.location.href = "<?= base_url('facilities'); ?>";
            } else if ($("#fromPage").val() == 'checkout') {
              window.location.href = "<?= base_url('checkout'); ?>";
            } else if ($("#fromPage").val() == 'checkout_prasadam') {
              window.location.href = "<?= base_url('checkout_prasadam'); ?>";
            }else if ($("#fromPage").val() == 'checkout_akshaya_patra') {
              window.location.href = "<?= base_url('checkout_akshaya_patra'); ?>";
            } else if ($("#fromPage").val() == 'TodayPanchangamMail') {
              SendPanchangamMailPdf();
            } else if ($("#fromPage").val() == 'partishipent_events') {
              // $("#pEvntName").text($("#hpEvntName").val());
              // $("#pEvntName1").text($("#hpEvntName1").val());
              // $("#inppEvntName").val($("#hpEvntName").val());
              // $("#inppEvntName1").val($("#hpEvntName1").val());
              // $("#inppEvntId").val($('#serviceId').val());
              // $("#EvtCount").attr("max", $("#hEvtCount").val());
              // $("#EvntDate").attr("min", $("#hEvntStartDate").val());
              // $("#EvntDate").attr("max", ("#hEvntendDate").val());
              // $("#partishipent_events-Modal").modal("show");

              OpenEventPartishipentModal($('#serviceId').val());
            } else if ($("#fromPage").val() == 'services') {

              var includeSankalpam = $("#includeSankalpamModal").val();

              if (includeSankalpam == 'YES') {
                $("#loginModal").modal("hide");
                $("#susbc-form-btn").click();
              } else {
                window.location.href = "<?= base_url('checkout/service') ?>";
              }
            } else if ($("#fromPage").val() == 'paylaterServices') {

              var includeSankalpam = $("#includeSankalpamModal").val();

              if (includeSankalpam == 'YES') {
                $("#loginModal").modal("hide");
                $("#susbc-form-btn").click();
              } else {
                window.location.href = "<?= base_url('paylater-services/checkout') ?>";
              }
            } else if ($("#fromPage").val() == 'donations') {
              window.location.href = "<?= base_url('donations/checkout'); ?>";

            } else if ($("#fromPage").val() == 'recurring-sponsorships') {
              window.location.href = "<?= base_url('recurring-sponsor/checkout'); ?>";

            } else if ($("#fromPage").val() == 'sponsorships') {
              window.location.href = "<?= base_url('checkout/sponsorship'); ?>";
            } else if ($("#fromPage").val() == 'view-cart') {
              window.location.href = "<?= base_url('Services/ViewCart'); ?>";
            } else if ($("#fromPage").val() == 'facilities') {
              $("#loginModal").modal("hide");
              BookNow();

            } else if ($("#fromPage").val() == 'pledge_form') {
              submitRecurringForm();
            } else if ($("#includeSankalpamModal").val() == 'YES') {
              $("#loginModal").modal("hide");
            } else {

              if (LoginTabName == 'Management') {

                window.location.href = "<?= base_url('managements/member-directory'); ?>";

              } else {

                window.location.href = "<?= base_url('Admin/Dashboard'); ?>";
              }
            }
          }
        } else {
          $("#loginModal").modal('hide');
          $("#signupModal").modal('show');
          showToast({
            eleWrapper: '#signup-error-flashmsg',
            msg: 'This phone no. is not registered please signup.',
            theme: 'error',
            closeButton: false,
            autoClose: true,
            afterShow: function() {
              console.log('After show function');
            },
            afterClose: function() {
              console.log('After close function');
            }
          });

        }
      }
    });

  }



  function SignupUser(url) {
    loader.on();

    var btn = document.getElementById('signupBtn');


    // event.preventDefault();


    var phone = $('#signupPhoneNumber').val();

    if (phone.length < 6) {

      showToast({
        eleWrapper: '#signup-error-flashmsg',
        msg: 'Please enter a valid phone number.',
        theme: 'warning',
        closeButton: false,
        autoClose: true,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });

      $('#signupPhoneNumber').focus();
      loader.off();

    }

    btn.disabled = true;
    btn.innerText = 'PLEASE WAIT...';

    var url = url;
    var fname = $('#fname').val();
    var lname = $('#lname').val();
    var email = $('#signupEmail').val();

    var newphone = 0;
    var cuntryCode = $("#signupModal .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    var value = phone.replace(cuntryCode, '');
    newphone = value;

    $.ajax({
      url: url,
      type: "POST",
      dataType: "json",
      data: {
        'fname': fname,
        'lname': lname,
        'email': email,
        'phone': newphone,
        'countryCode': cuntryCode
      },
      success: function(data) {

        loader.off();

        console.log(data);

        var loginbtn = document.getElementById('loginBtn');
        var emailotpntn = document.getElementById('emailotpntn');

        const obj = JSON.parse(data);
        if (obj.message == '') {

          loginbtn.disabled = false;
          loginbtn.innerText = 'LOGIN';

          emailotpntn.disabled = false;
          emailotpntn.innerText = 'LOGIN';


          showToast({
            eleWrapper: '#login-success-flashmsg',
            msg: data,
            theme: 'success',
            closeButton: false,
            autoClose: true,
            afterShow: function() {
              console.log('After show function');
            },
            afterClose: function() {
              console.log('After close function');
            }
          });


          if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
            openBoxlog('login');
          } else {
            $('.signupBtnClose').click();
            $("#signupModal").modal("hide");
            $("#loginModal").modal("show");
          }
        } else {
          if (obj.message == 'success') {
            loginbtn.disabled = false;
            loginbtn.innerText = 'LOGIN';

            emailotpntn.disabled = false;
            emailotpntn.innerText = 'LOGIN';


            showToast({
              eleWrapper: '#login-success-flashmsg',
              msg: obj.message,
              theme: 'success',
              closeButton: false,
              autoClose: true,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });


            if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
              openBoxlog('login');
            } else {
              $('.signupBtnClose').click();
              $("#signupModal").modal("hide");
              $("#loginModal").modal("show");
            }

            btn.disabled = false;
            btn.innerText = 'REGISTER';
          } else {
            loginbtn.disabled = false;
            loginbtn.innerText = 'LOGIN';

            emailotpntn.disabled = false;
            emailotpntn.innerText = 'LOGIN';


            showToast({
              eleWrapper: '#signup-error-flashmsg',
              msg: obj.message,
              theme: 'error',
              closeButton: false,
              autoClose: true,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });

            btn.disabled = false;
            btn.innerText = 'REGISTER';
          }
        }
      }




    });


    return false;
  }
</script>


<!-- Mobile OTP AUTH BY FIREBASE -->
<!-- Add the latest firebase dependecies from CDN -->
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-auth.js"></script>


<script>
  var firebaseConfig = {
    apiKey: "AIzaSyAcxU5AvD6qtVG76xDCXaf2vzuPIX_DwMw",
    authDomain: "login-7aff9.firebaseapp.com",
    projectId: "login-7aff9",
    storageBucket: "login-7aff9.appspot.com",
    messagingSenderId: "981533541532",
    appId: "1:981533541532:web:9846cc5487bb8fead35959",
    measurementId: "G-57D5BT4B2F"
  };


  firebase.initializeApp(firebaseConfig);
  window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
    "recaptcha-container", {
      size: "normal",
      callback: function(response) {
        submitPhoneNumberAuth();
      }
    }
  );

  function submitPhoneNumberAuth() {
    $("#AdministratorTab").addClass('disabled');
    $("#devoteeTab").addClass('disabled');

    var phoneNumber = document.getElementById("loginPhoneNumber").value;
    var appVerifier = window.recaptchaVerifier;
    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber, appVerifier)
      .then(function(confirmationResult) {
        window.confirmationResult = confirmationResult;

        if (confirmationResult.verificationId) {
          // $("#mobiletoggle").toggle();
          $("#mobiletoggle").css('display', 'inline-flex');
          $('#mobileotp').focus();
          $("#AdministratorTab").addClass('disabled');
          $("#devoteeTab").addClass('disabled');

          showToast({
            eleWrapper: '.otpsendmsg_number',
            msg: 'OTP has been sent on this mobile number.',
            theme: 'success',
            closeButton: false,
            autoClose: true,
            afterShow: function() {
              console.log('After show function');
            },
            afterClose: function() {
              console.log('After close function');
            }
          });

          // $(".otpsendmsg_number").html("OTP has been sent on this mobile number.");
          // setTimeout(function(){$(".otpsendmsg_number").text('');},6000);
          $("#recaptcha-container").remove();
        }


      })
      .catch(function(error) {
        console.log(error);
      });
  }

  function submitPhoneNumberAuthCode() {
    var btn = document.getElementById('mobileotpverifybtn');
    btn.disabled = true;
    btn.innerText = 'VERIFYING';


    var code = document.getElementById("mobileotp").value;
    if (code == "") {
      btn.disabled = false;
      btn.innerText = 'VERIFY';
      $(".otpsendmsg_number").html("");


      showToast({
        eleWrapper: '.otpsendmsg_number_error',
        msg: 'Please enter 6 digit OTP!',
        theme: 'warning',
        closeButton: false,
        autoClose: true,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });


      // $(".otpsendmsg_number_error").html("Please enter 6 digit OTP!");
      // setTimeout(function(){$(".otpsendmsg_number_error").text('');},6000);

    } else {
      confirmationResult
        .confirm(code)
        .then(function(result) {
          var user = result.user;
          // console.log(user);

          PhoneLogin('<?= base_url('signin'); ?>');


          // console.log("USER LOGGED IN");

        })
        .catch(function(error) {
          alert('Invalid OTP/OTP Expired!!')
          var btn = document.getElementById('mobileotpverifybtn');
          btn.disabled = false;
          btn.innerText = 'VERIFY';
          // console.log(error);
        });

      firebase.auth().onAuthStateChanged(function(user) {});
    }
  }
</script>


<!-- Live Client Id -->

<?php

$fgh = getFullPaymentSettings();


$dsbj = @$fgh['result']['data'][0]['paymentGatewayoffon'];
if (!empty($dsbj)) {
  foreach ($dsbj as $key => $dd) {
    if ($dd['source'] == 'WEBSITE') {
      $paymentSeverOn = @$dd['isenable'];
      $paymentSeverText = $dd['desc'];
    }
  }
}



if (@$paymentSeverOn == 1 && @$paymentSetting == 'PAYPAL') { ?>
  <?php $paypalLiveClientId  = getclientInfoById()['data'][0]['paypalClientId']; ?>

  <script src="https://www.paypal.com/sdk/js?client-id=<?= $paypalLiveClientId ?>&enable-funding=venmo&intent=capture" data-sdk-integration-source="integrationbuilder"></script>



  <script>
    const paypalButtonsComponent = paypal.Buttons({
      style: {
        shape: 'rect',
        color: 'gold',
        layout: 'vertical',
        label: 'paypal',

      },
      // set up the transaction
      createOrder: (data, actions) => {



        if ($("#DonateToTemple").val() == 'DONATIONS') {
          amt = $("#DonationAmt").val();
        } else {
          amt = $("#serviceAmt").val()
        }


        const createOrderPayload = {
          purchase_units: [{
            amount: {

              value: amt
            }
          }]
        };





        return actions.order.create(createOrderPayload);
      },
      // finalize the transaction


      onApprove: (data, actions) => {
        const captureOrderHandler = (details) => {

          loader.on();
          const payerName = details.payer.name.given_name;
          var payer_firstname = details.payer.name.given_name;
          var payer_lastname = details.payer.name.surname;
          var orderid = details.id;
          var status = details.status;
          var email = details.payer.email_address;
          var transaction_id = details.purchase_units[0].payments.captures[0].id;
          var serviceAmount = details.purchase_units[0].amount.value;
          if ($('#fullPackage').val() == 'true') {
            var fullPackage = $('#fullPackage').val();
          }

          if ($("#DonateToTemple").val() == 'DONATIONS') {
            var serviceName = $("#DonationName").text();
            var service_Id = $("#DonationId").val();
            var serviceCategoryTypes = $("#DonationCategoryTypes").val();
            var serviceTypes = $("#DonationTypes").val();
            var dayTypes = $("#DonationdayTypes").val();
            var startDate = $("#DonationstartDate").val();
            var startTime = $("#DonationstartTime").val();
          } else {
            var serviceName = $("#serviceName").text();
            var service_Id = $("#serviceId").val();
            var serviceCategoryTypes = $("#serviceCategoryTypes").val();
            var serviceTypes = $("#serviceTypes").val();
            var dayTypes = $("#dayTypes").val();



            var startDate = $("#serviceStartDate").val();
            var startTime = $("#timepicker").val();


            if ($("#Address").val() != '') {
              var Address = $("#Address").val();
            } else {
              var Address = "";
            }

          }





          $.ajax({
            url: "<?= base_url('add-service-cart'); ?>",
            type: "POST",
            dataType: "json",
            data: {
              'fname': payer_firstname,
              'lname': payer_lastname,
              'fullPackage': fullPackage,
              'orderid': orderid,
              'status': status,
              'email': email,
              'services_Id': service_Id,
              'serviceAmount': serviceAmount,
              'serviceName': serviceName,
              'transaction_id': transaction_id,
              'serviceCategoryTypes': serviceCategoryTypes,
              'serviceTypes': serviceTypes,
              'dayTypes': dayTypes,
              'startDate': startDate,
              'startTime': startTime,
              'qty': 1,
              'serviceAddress': Address
            },
            success: function(response) {
              loader.off();
              console.log(response);

              if (response.statusCode == 1) {
                // console.log(response);
                $('.PaymentClosebtn').click();
                $("#paymentModal").modal("hide");


                if (serviceCategoryTypes == 'DONATIONS') {
                  $("#DonateToTemplePaymentModal").modal("hide");

                  swal({
                      html: true,
                      title: "Donation is processed successfully!",
                      text: "<span style='font-weight: 600;margin:5px;padding:5px'>Token No:</span> " + response.data[0].invoiceNo,
                      type: "success",
                      confirmButtonText: 'OK',
                      confirmButtonColor: 'var(--main-color-new-theme)',
                      // timer:5000,
                    },

                    function() {
                      if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
                        window.location.href = "<?= base_url('logout'); ?>"
                      } else {
                        window.location.reload();
                      }

                    });
                } else {
                  swal({
                      html: true,
                      title: "Service Booking Confirmed!",
                      text: "<span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + response.data[0].invoiceNo,
                      type: "success",
                      confirmButtonText: 'OK',
                      confirmButtonColor: 'var(--main-color-new-theme)',
                      // timer:5000,
                    },

                    function() {
                      if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
                        window.location.href = "<?= base_url('logout'); ?>"
                      } else {
                        window.location.reload();
                      }

                    });
                }


              } else {
                $('.PaymentClosebtn').click();
                $("#paymentModal").modal("hide");
                swal({
                    html: true,
                    title: "Failed!",
                    text: "<span>Transaction Failed!<span><br><span style='font-weight: 600;margin:5px;padding:5px'>Token No:</span> " + response.data[0].invoiceNo,
                    type: "error",
                    confirmButtonText: 'OK',
                    confirmButtonColor: 'var(--main-color-new-theme)',
                    // timer:5000,
                  },
                  function() {
                    window.location.reload();
                  });

              }

            }
          });


          // Ajax Request End

        };

        return actions.order.capture().then(captureOrderHandler);
      },


      onError: (err) => {
        alert('Transaction Failed');

      }
    });

    paypalButtonsComponent
      .render("#paypal-button-container")
      .catch((err) => {
        console.log('PayPal Buttons failed to render');
      });
  </script>

<?php } ?>




<script>
  function nonEditCuntryCode(el) {
    var cuntryCode = $("#loginModal .iti__selected-flag").attr('title');
    // alert(cuntryCode);
    cuntryCode = (cuntryCode.split(':')[1]).trim();

    if (el.value.length > cuntryCode.length) {
      var value = el.value.replace(cuntryCode, '');; //replace all $ with empty string
      el.value = cuntryCode + value;
    } else {
      el.value = cuntryCode;
    }
  }



  function nonEditCuntryCode1(el) {
    var cuntryCode = $("#signupModal .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    if (el.value.length > cuntryCode.length) {
      var value = el.value.replace(cuntryCode, '');; //replace all $ with empty string
      el.value = cuntryCode + value;
    } else {
      el.value = cuntryCode;
    }
  }


  function nonEditCuntryCode2(el) {
    var cuntryCode = $("#CompanyPhoneDiv .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    if (el.value.length > cuntryCode.length) {
      var value = el.value.replace(cuntryCode, ''); //replace all $ with empty string
      el.value = cuntryCode + value;
    } else {
      el.value = cuntryCode;
    }
  }


  function checkValue(str, max) {
    if (str.charAt(0) !== '0' || str == '00') {
      var num = parseInt(str);
      if (isNaN(num) || num <= 0 || num > max) num = 1;
      str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
    };
    return str;
  };

  function date_reformat_mm(date) {
    date.addEventListener('input', function(e) {
      this.type = 'text';
      var input = this.value;
      if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
      var values = input.split('/').map(function(v) {
        return v.replace(/\D/g, '')
      });
      if (values[0]) values[0] = checkValue(values[0], 12);
      if (values[1]) values[1] = checkValue(values[1], 31);
      var output = values.map(function(v, i) {
        return v.length == 2 && i < 2 ? v + '/' : v;
      });
      this.value = output.join('').substr(0, 14);
    });

  }



  function openBoxlog(type) {
    if (type == 'signup') {
      $(".login-box-msg h4").text('SIGN UP');
      $("#loginModal").hide();
      $(".inLogin").hide();
      $("#signupModal").show();
      $(".inSignup").show();

    } else if (type == 'login') {
      $(".login-box-msg h4").text('LOGIN IN');
      $("#signupModal").hide();
      $(".inSignup").hide();
      $("#loginModal").show();
      $(".inLogin").show();
    }
  }

  /*----------------------------------*/

  /*==================================================*/
  /*==================Script For Currency Input (.00)=================*/
  /*==================================================*/
  $(document).ready(function() {
    $.fn.currencyInput = function() {
      this.each(function() {
        var wrapper = $("<div class='currency-input' />");
        $(this).wrap(wrapper);
        // $(this).before("<span class='currency-symbol' style='padding:7px 13px'>$</span>");
        $(this).change(function() {
          var min = parseFloat($(this).attr("min"));
          var max = parseFloat($(this).attr("max"));
          var value = this.valueAsNumber;
          if (value < min)
            value = min;
          else if (value > max)
            value = max;
          $(this).val(value.toFixed(2));
        });
      });
    };



    $('input.currency').currencyInput();
  });



  function loginBy(type) {


    if (type == 'email') {
      var cuntryCode = $("#loginModal .iti__selected-flag").attr('title');
      cuntryCode = (cuntryCode.split(':')[1]).trim();
      $("#loginPhoneNumber").val(cuntryCode);
    } else {
      $("#loginEmail").val('');
    }



  }

  // $(".modalClbtn").click(function(){window.location.reload();});



  $(document).ready(function() {
    $('.eye-toggle').on('click', function() {
      var eyeIcon = $(this).find('i');
      if ($(this).attr("aria-expanded") == "true") {
        eyeIcon.removeClass('fa-eye-slash').addClass('fa-eye');
      } else if ($(this).attr("aria-expanded") == "false") {
        eyeIcon.removeClass('fa-eye').addClass('fa-eye-slash');
      }
    });
  });


  $(".amount-input").on({
    keyup: function() {
      var inputId = $(this).attr('id');
      var id = inputId.replace('anyAmtEvent', '');
      formatCurrency($(this), id);
    },
    blur: function() {
      var inputId = $(this).attr('id');
      var id = inputId.replace('anyAmtEvent', '');
      formatCurrency($(this), id, "blur");
    }
  });

  $(".amount-input-donations").on({
    keyup: function() {
      var inputId = $(this).attr('id');
      var id = inputId.replace('anyAmtDonation', '');
      formatCurrency($(this), id);
    },
    blur: function() {
      var inputId = $(this).attr('id');
      var id = inputId.replace('anyAmtDonation', '');
      formatCurrency($(this), id, "blur");
    }
  });

  function formatCurrency(input, id, blur) {
    var input_val = input.val();

    if (input_val === "") {
      return;
    }

    var original_len = input_val.length;
    var caret_pos = input.prop("selectionStart");

    if (input_val.indexOf(".") >= 0) {
      var decimal_pos = input_val.indexOf(".");
      var left_side = input_val.substring(0, decimal_pos);
      var right_side = input_val.substring(decimal_pos);

      left_side = left_side.replace(/\D/g, "");
      right_side = right_side.replace(/\D/g, "");

      if (blur === "blur") {
        right_side += "00";
      }

      right_side = right_side.substring(0, 2);

      input_val = left_side + "." + right_side;
    } else {
      input_val = input_val.replace(/\D/g, "");

      if (blur === "blur") {
        input_val += ".00";
      }
    }

    input.val(input_val);

    $("#checkbox_" + id).attr('data-price', input_val);

    var updated_len = input_val.length;
    caret_pos = updated_len - original_len + caret_pos;
    input[0].setSelectionRange(caret_pos, caret_pos);
  }







  function ViewCartMobile(page) {
    if (parseInt($(".cart-count").text()) > 0) {
      // window.location.href = "<?= base_url('checkout') ?>";
      CartCheckLoginTabFacility('checkout');

    } else {
      swal({
        title: "Your cart is empty!",
        text: "Please add some items to your cart.",
        icon: "warning",
        confirmButtonText: 'OK',
        confirmButtonColor: 'var(--main-color-new-theme)',
      });


    }

  }


  $(document).ready(function() {
    $(".each-word").each(function() {
      var $this = $(this);
      var htmlContent = $this.html();
      var modifiedContent = htmlContent.replace(/(?:<[^>]*>)|(\b[a-z])([a-z]+)?\b/gim, function(match, p1, p2) {
        if (p1) {
          return "<span class='first-letter'>" + p1 + "</span>" + (p2 || "");
        } else {
          return match; // Preserve HTML tags
        }
      });
      $this.html(modifiedContent);
    });
  });


  // $('.phone').on('input', function (e) {
  //   var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  //   e.target.value = !x[2] ? x[1] : '' + x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
  // });
</script>

<script type="text/javascript" src="<?= base_url('assets/js/country_code.js'); ?>"></script>
<script type="text/javascript" src="<?= base_url('assets/js/country_code2.js'); ?>"></script>
<script type="text/javascript" src="<?= base_url('assets/js/country_code3.js'); ?>"></script>
<script type="text/javascript" src="<?= base_url('assets/js/time-picker.js'); ?>"></script>
<script>
  function sendMemberAuthCode(url) {


    var email = $('#signupEmail').val();

    $("#login-error-flashmsg").html("");

    if (email == "") {
      // event.preventDefault();
      // LoginUser('<?= base_url('signin'); ?>');
      showToast({
        eleWrapper: '#signup-error-flashmsg',
        msg: ' Please enter your email id and verify.',
        theme: 'error',
        closeButton: false,
        autoClose: true,
        duration: 60000,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });
      loader.off();
    } else {

      var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if (email.match(mailformat)) {
        var btn = document.getElementById('verifySignupEmailbtn');
        btn.disabled = true;
        // btn.innerText = 'SENDING';
        btn.innerHTML = '<div class="spinner-border" role="status" style="font-size:20px!important;"><span class="sr-only">Loading...</span></div>';


        // event.preventDefault();
        var url = url;


        const activeLoginTab = $('.nav-link.active');
        const LoginTabName = activeLoginTab.attr('tab-name');

        $.ajax({
          url: url,
          type: "POST",
          dataType: "json",
          data: {
            'email': email,
            'LoginTabName': LoginTabName
          },
          success: function(data) {
            loader.off();
            console.log(data['statusCode'] == '1');
            console.log(data['statusCode'] == 1);

            if (data['statusCode'] == '1') {
              btn.disabled = true;
              btn.innerText = 'SEND';
              $("#signUpOtp").val('');
              $("#signup-auth-success-flashmsg").text('');
              $("#signup-auth-error-flashmsg").text('');
              $("#memberAuthCodeVerifyBtn").disabled = false;
              $("#memberAuthCodeVerifyBtn").innerText = 'Verify OTP';
              $('#signUpOTP').modal('show');
              $('body *').not('#signUpOTP, #signUpOTP *').addClass('dimmed');
              showToast({
                eleWrapper: '#signup-auth-success-flashmsg',
                msg: 'OTP sent on your email id ' + email,
                theme: 'success',
                closeButton: false,
                autoClose: true,
                afterShow: function() {
                  console.log('After show function');
                },
                afterClose: function() {
                  console.log('After close function');
                }
              });
            } else if (data['statusCode'] == '-1') {
              btn.disabled = false;
              btn.innerText = 'VERIFY';
              showToast({
                eleWrapper: '#signup-error-flashmsg',
                msg: data['message'],
                theme: 'error',
                closeButton: false,
                autoClose: true,
                afterShow: function() {
                  console.log('After show function');
                },
                afterClose: function() {
                  console.log('After close function');
                }
              });
            } else {

              btn.disabled = false;
              btn.innerText = 'VERIFY';
              showToast({
                eleWrapper: '#signup-error-flashmsg',
                msg: 'Technical Error! Please Login With Phone Number or Contact Admin.',
                theme: 'error',
                closeButton: false,
                autoClose: true,
                afterShow: function() {
                  console.log('After show function');
                },
                afterClose: function() {
                  console.log('After close function');
                }
              });
            }

          }
        });

      } else {


        showToast({
          eleWrapper: '#signup-error-flashmsg',
          msg: 'Please enter a valid email address.',
          theme: 'error',
          closeButton: false,
          autoClose: true,
          afterShow: function() {
            console.log('After show function');
          },
          afterClose: function() {
            console.log('After close function');
          }
        });
        loader.off();
      }

    }
    loader.off();

  }

  function verifyMemberAuthCode(url) {
    loader.on();
    var btn = document.getElementById('memberAuthCodeVerifyBtn');
    btn.disabled = true;
    btn.innerText = 'VERIFYING';


    // event.preventDefault();
    var url = url;
    var otp = $('#signUpOtp').val();

    if (otp == "") {
      $("#login-success-flashmsg").html("");

      showToast({
        eleWrapper: '#signup-auth-error-flashmsg',
        msg: 'Please enter 6 digit OTP!',
        theme: 'error',
        closeButton: false,
        autoClose: true,
        duration: 60000,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });
      btn.disabled = false;
      btn.innerText = 'VERIFY';
      loader.off();

    } else {
      var email = $('#signupEmail').val();
      $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: {
          'otp': otp,
          'email': email
        },
        success: function(data) {
          loader.off();
          console.log("statusCOde: " + data['statusCode']);
          if (data['statusCode'] == 1) {
            showToast({
              eleWrapper: '#signup-auth-success-flashmsg',
              msg: data['message'],
              theme: 'success',
              closeButton: false,
              autoClose: true,
              duration: 60000,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });
            $("#signupBtn").removeAttr("disabled");
            $("#signupBtn").removeClass('d-none');
            $("#signupBtnAlert").addClass('d-none');
            $('#verifySignupEmailbtn').disabled = true;
            $('#verifySignupEmailbtn').text('VERIFIED');
            $("#signUpOTP").modal("hide");
            $("#signup-error-flashmsg1").addClass("d-none");
            $('body *').removeClass('dimmed');

          } else {
            $("#signup-auth-error-flashmsg").html("");
            $("#signup-auth-success-flashmsg").html("");


            showToast({
              eleWrapper: '#signup-auth-error-flashmsg',
              msg: data['message'],
              theme: 'error',
              closeButton: false,
              autoClose: true,
              duration: 60000,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });
            btn.disabled = false;
            btn.innerText = 'VERIFY';
          }


        }
      });
    }
  }

  function closesignUpOTPModal() {
    var btn = document.getElementById('verifySignupEmailbtn');
    btn.disabled = false;
    btn.innerText = 'VERIFY';
    $('body *').removeClass('dimmed');
    $("#signUpOTP").modal("hide");

  };

  function SignupUserLogin(url) {
    event.preventDefault();

    loader.on();

    var btn = document.getElementById('signupBtn');




    var phone = $('#signupPhoneNumber').val();
    // alert(phone);








    btn.disabled = true;
    btn.innerText = 'PLEASE WAIT...';

    var url = url;
    var fname = $('#fname').val();
    var lname = $('#lname').val();
    var email = $('#signupEmail').val();

    var newphone = 0;
    var cuntryCode = $("#signupModal .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    var value = phone.replace(cuntryCode, '');
    newphone = value;
    if (fname.length <= 0 || value <= 0 || email.length <= 0 || lname.length <= 0) {
      btn.disabled = false;
      btn.innerText = 'REGISTER';
      showToast({
        eleWrapper: '#signup-error-flashmsg',
        msg: "<b>Alert! </b>Please enter all required fields.",
        theme: 'error',
        closeButton: false,
        autoClose: true,
        duration: 60000,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });
    } else if (phone.length < 6) {

      showToast({
        eleWrapper: '#signup-error-flashmsg',
        msg: 'Please enter a valid phone number.',
        theme: 'error',
        closeButton: false,
        autoClose: true,
        duration: 60000,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });

      $('#signupPhoneNumber').focus();
      loader.off();

    } else {


      $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: {
          'fname': fname,
          'lname': lname,
          'email': email,
          'phone': newphone,
          'countryCode': cuntryCode
        },
        success: function(data) {

          loader.off();

          // console.log(data);

          var loginbtn = document.getElementById('signupBtn');
          var emailotpntn = document.getElementById('emailotpntn');

          const obj = JSON.parse(data);
          if (obj.message == '') {

            loginbtn.disabled = false;
            loginbtn.innerText = 'LOGIN';

            emailotpntn.disabled = false;
            emailotpntn.innerText = 'LOGIN';


            showToast({
              eleWrapper: '#login-success-flashmsg',
              msg: data,
              theme: 'success',
              closeButton: false,
              autoClose: true,
              duration: 60000,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });


            if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
              openBoxlog('login');
            } else {
              $('.signupBtnClose').click();
              $("#signupModal").modal("hide");
              $("#loginModal").modal("show");
            }



          } else {



            if (obj.statusCode == '1') {
              loginbtn.disabled = true;
              loginbtn.innerText = 'LOGIN';

              emailotpntn.disabled = false;
              emailotpntn.innerText = 'LOGIN';


              showToast({
                eleWrapper: '#login-success-flashmsg',
                msg: obj.message,
                theme: 'success',
                closeButton: false,
                autoClose: true,
                afterShow: function() {
                  console.log('After show function');
                },
                afterClose: function() {
                  console.log('After close function');
                }
              });


              if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
                openBoxlog('login');
              } else {
                // $('.signupBtnClose').click();
                // $("#signupModal").modal("hide");
                // $("#loginModal").modal("show");
                window.location.href = "<?= base_url('devotee-dashboard') ?>";
              }

              btn.disabled = false;
              btn.innerText = 'REGISTER';
            } else {
              loginbtn.disabled = false;
              loginbtn.innerText = 'LOGIN';

              emailotpntn.disabled = false;
              emailotpntn.innerText = 'LOGIN';


              showToast({
                eleWrapper: '#signup-error-flashmsg',
                msg: obj.message,
                theme: 'error',
                closeButton: false,
                autoClose: true,
                afterShow: function() {
                  console.log('After show function');
                },
                afterClose: function() {
                  console.log('After close function');
                }
              });

              btn.disabled = false;
              btn.innerText = 'REGISTER';
            }
          }
        }




      });
    }


    return false;
  }

  function checkVerifyEmail() {


    // swal({
    //     html: true,
    //     title: "Please verify your email",
    //     text: "<span style='font-weight: 600;margin:5px;padding:5px'></span> ",
    //     type: "error",
    //     confirmButtonText: 'OK',
    //     confirmButtonColor: 'var(--main-color-new-theme)',
    //     // timer:5000,
    //   },

    //   function() {
    //     // if ((location.href.match(/([^\/]*)\/*$/)[1]).indexOf('Payonline') != -1) {
    //     //   window.location.href = "<?= base_url('logout'); ?>"
    //     // } else {
    //     //   window.location.reload();
    //     // }

    //   });

    showToast({
      eleWrapper: '#signup-error-flashmsg',
      msg: 'Please verify your email id.',
      theme: 'error',
      closeButton: false,
      autoClose: true,
      duration: 60000,
      afterShow: function() {
        console.log('After show function');
      },
      afterClose: function() {
        console.log('After close function');
      }
    });
  }

  function resendMemberAuthCode(url) {


    var email = $('#signupEmail').val();

    $("#login-error-flashmsg").html("");



    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (email.match(mailformat)) {
      var btn = document.getElementById('resendOtpBtn');
      btn.innerText = 'SENDING';


      // event.preventDefault();
      var url = url;


      const activeLoginTab = $('.nav-link.active');
      const LoginTabName = activeLoginTab.attr('tab-name');

      $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: {
          'email': email,
          'LoginTabName': LoginTabName
        },
        success: function(data) {
          loader.off();
          console.log(data['statusCode'] == '1');
          console.log(data['statusCode'] == 1);
          btn.innerText = 'Resend OTP?';
          if (data['statusCode'] == '1') {


            $('#signUpOTP').modal('show');
            $('body *').not('#signUpOTP, #signUpOTP *').addClass('dimmed');
            showToast({
              eleWrapper: '#signup-auth-success-flashmsg',
              msg: 'OTP sent on your email ' + email,
              theme: 'success',
              closeButton: false,
              autoClose: true,
              duration: 60000,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });
          } else if (data['statusCode'] == '-1') {

            showToast({
              eleWrapper: '#signup-error-flashmsg',
              msg: data['message'],
              theme: 'error',
              closeButton: false,
              autoClose: true,
              duration: 60000,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });
          } else {


            showToast({
              eleWrapper: '#signup-error-flashmsg',
              msg: 'Technical Error! Please Login With Phone Number or Contact Admin.',
              theme: 'error',
              closeButton: false,
              autoClose: true,
              duration: 60000,
              afterShow: function() {
                console.log('After show function');
              },
              afterClose: function() {
                console.log('After close function');
              }
            });
          }

        }
      });

    } else {


      showToast({
        eleWrapper: '#signup-error-flashmsg',
        msg: 'Please enter a valid email address.',
        theme: 'error',
        closeButton: false,
        autoClose: true,
        duration: 60000,
        afterShow: function() {
          console.log('After show function');
        },
        afterClose: function() {
          console.log('After close function');
        }
      });
      loader.off();
    }


    loader.off();

  }


  function CartCheckLoginTabFacility(page = '') {

    loader.on();


    var page_name = page;
    event.preventDefault();
    $.ajax({
      url: "<?= base_url('check-login-status') ?>",
      type: "POST",
      dataType: "json",
      success: function(data) {


        if (data == 0) {
          loader.off();
          var res = openLoginModal(page_name);

        } else {
          if (page_name == "facilitiesPage") {
            // alert(page_name);
            window.location.href = "<?= base_url('facilities') ?>";

          } else if (page_name == "checkout") {
            window.location.href = "<?= base_url('checkout') ?>";

          } else {
            window.location.href = "<?= base_url('Admin/Dashboard') ?>";

          }

        }

      }
    });




  }

  function updateCartCount() {

    $.ajax({
      url: '<?= base_url('Home/updateCartCount') ?>', // Replace with your API endpoint
      type: 'POST',
      success: function(response) {
        loader.off();
        // console.log(response);
        response = JSON.parse(response);
        $(".cart-count").text(response);
      },
      error: function(xhr, status, error) {
        loader.off();
        // Handle error
        // console.error('Error submitting form:', error);
        alert('Error submitting form');
      }
    });
  }


  function OpenEventPartishipentModal(id) {
    $("#partishipent_events-Modal").modal("show");
    $.ajax({
      url: '<?= base_url() ?>/Home/loadPartishipentModal/' + id,
      method: 'GET',
      success: function(response) {
        $('#partishipent_events-Modal .modal-body').html(response);
      },
      error: function() {
        $('#partishipent_events-Modal ,modal-body').html('<p>Error loading data</p>');
      }
    });
  }

  function SendPanchangamMailPdf() {
    loader.on();
    $.ajax({
      url: '<?= base_url() ?>/Home/sendPanchangaPdfMail',
      method: 'GET',
      success: function(response) {
        loader.off();
        let res = typeof response === 'string' ? JSON.parse(response) : response;
        console.log(res.statusCode);
        let titleTxt = res.statusCode == "1" ? "Panchangam pdf sent to your registered email id," : res.msg ?? "Something went wrong.";
        swal({
            html: true,
            title: titleTxt,
            type: res.statusCode == "1" ? "success" : "error",
            confirmButtonText: 'OK',
            confirmButtonColor: 'var(--main-color-new-theme)',
          },

          function() {
            loader.on();
            window.location.reload();
            // console.log("okk sendPanchangaPdfMail");

          });
      },
      error: function() {
        loader.off();
        alert('Error submitting form');
        loader.on();
        window.location.reload();
      }
    });
  }

  function openLoginModal2(page = '') {


    var fromPage = page;
    if (page.length > 0) {
      $("#fromPage").val(page);
    }
    $("form").get(0).reset();





    var emailotpntn = document.getElementById('emailotpntn');

    emailotpntn.disabled = false;
    emailotpntn.innerText = 'LOGIN';

    $('.signupBtnClose').click();
    $("#signupModal").modal("hide");
    $("#loginModal2").modal("show");


    $(".vOtpBox").hide();
    $("#emailotpntn2").show();
    $(".mobile_section").show();
    $(".email_section").show();
  }

  function WithoutOtpLogin(e) {
    e.preventDefault(); // Prevent the default form submission
    // alert('ok');
    // Gather the form dataalert
    var email = $("#loginEmail2").val();
    var phone = $("#signupPhoneNumber2").val();
    var newphone = 0;
    var cuntryCode = $("#loginModal2 .iti__selected-flag").attr('title');
    cuntryCode = (cuntryCode.split(':')[1]).trim();
    // var value = phone.replace(cuntryCode, '');
    // newphone = value;
    var value = phone.replace(cuntryCode, '').trim(); // ✅ Country code hatana
    newphone = value.replace(/\s+/g, '');
    newphone = value.replace(/\D+/g, '');
    // alert(email);
    // alert(newphone);
    // Perform the AJAX request
    $.ajax({
      url: '<?= base_url('signin') ?>', // Replace with your API endpoint
      type: 'POST', // Assuming the API expects POST requests
      data: {
        email: email,
        phone: newphone,
        sessionCreate: 1,
      },
      success: function(response) {
        // console.log(response);
        response = JSON.parse(response);
        // alert(response);
        //  alert(response.statusCode);

        if (response.statusCode == '1') {
          window.location.href = "<?= base_url('make-a-payment-checkout') ?>";
        } else {
          openSignupModal();
          // alert('Form submitted successfully');
        }
        // Handle success
        // console.log('Form submitted successfully:', response);
        // alert('Form submitted successfully');
      },
      error: function(xhr, status, error) {
        // Handle error
        // console.error('Error submitting form:', error);
        alert('Error submitting form');
      }
    });
  }

  function serviceDesc(e, serviceId) {
    // alert(e.value);
    $("#checkbox_" + serviceId).attr('data-servicedesc', e.value);
  }

     function ValidateAkshyaPatraCheckout() {

        loader.on();
        $.ajax({
            url: '<?php echo base_url('validate_akshaya_patra_checkout') ?>', // PHP file that checks profile
            method: 'POST',
            dataType: 'json',
            success: function(response) {
                if (!response) {
                    loader.off();
                    Swal.fire({
                        title: "Oops",
                        text: "Minimum order value must be $10!",
                        icon: "question"
                    });
                } else {

                    loader.on();


                    var page_name = 'checkout_akshaya_patra';
                    // event.preventDefault();
                    $.ajax({
                        url: "<?php echo base_url('check-login-status') ?>",
                        type: "POST",
                        dataType: "json",
                        success: function(data) {


                            if (data == 0) {
                                loader.off();
                                var res = openLoginModal(page_name);

                            } else {
                                window.location.href = "<?php echo base_url('checkout_akshaya_patra') ?>";

                            }

                        }
                    });



                }
            }
        });
    }

       function ValidateCheckout() {






        loader.on();
        $.ajax({
            url: '<?php echo base_url('validate_prasadam_checkout') ?>', // PHP file that checks profile
            method: 'POST',
            dataType: 'json',
            success: function(response) {
                if (!response) {
                    loader.off();
                    Swal.fire({
                        title: "Oops",
                        text: "Minimum order value must be $10!",
                        icon: "question"
                    });
                } else {

                    loader.on();


                    var page_name = 'checkout_prasadam';
                    // event.preventDefault();
                    $.ajax({
                        url: "<?php echo base_url('check-login-status') ?>",
                        type: "POST",
                        dataType: "json",
                        success: function(data) {


                            if (data == 0) {
                                loader.off();
                                var res = openLoginModal(page_name);

                            } else {
                                window.location.href = "<?php echo base_url('checkout_prasadam') ?>";

                            }

                        }
                    });



                }
            }
        });
    }
</script>
</body>

</html>