/**
 * @copyright 2021 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

$(document).ready(function() {

  var userid = "<?php p($userId); ?>";
  var strlength;

  function randomStr(strlength) {
        var fintext = "";
        var keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for (var i = 0; i < strlength; i++) {
             fintext += keyspace.charAt(Math.floor(Math.random() * keyspace.length));
        }
        return fintext;
  }

  $("#generate_tel_rcpt").on("click", function(event) {

     var teltokenrec = randomStr(70);
     var telnyxwhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmstel?telrecparam=') + teltokenrec;

     $("#telapi_url_rec").val(telnyxwhurlrec);
  });

  $("#copyToClipboardtel").on("click", function(event) {
     var $tempEl = $("<input>");
     $("body").append($tempEl);
     $tempEl.val($("#telapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempEl.remove();
     alert("The link has been copied to your clipboard!");
  });

  $("#generate_tel_delrcpt").on("click", function(event) {

     var teltoken = randomStr(70);
     var telnyxwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliverytel?teldrparam=') + teltoken;

     $("#telapi_url").val(telnyxwhurl);
  });


  $("#generate_nex_rcpt").on("click", function(event) {

     var plivotokenrec = randomStr(70);
     var plivowhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmsnex?plivorecparam=') + plivotokenrec;

     $("#nexapi_url_rec").val(plivowhurlrec);
  });

  $("#copyToClipboardnex").on("click", function(event) {
     var $tempElpl = $("<input>");
     $("body").append($tempElpl);
     $tempElpl.val($("#nexapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempElpl.remove();
     alert("The link has been copied to your clipboard!");
  });

  $("#generate_nex_delrcpt").on("click", function(event) {

     var plivotoken = randomStr(70);
     var plivodrwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliverynex?plivodrparam=') + plivotoken;

     $("#nexapi_url").val(plivodrwhurl);
  });


  $("#generate_twil_rcpt").on("click", function(event) {

     var twiltokenrec = randomStr(35);
     var twilwhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmstwil?twilrecparam=') + twiltokenrec;

     $("#twilapi_url_rec").val(twilwhurlrec);
  });

  $("#copyToClipboardtwil").on("click", function(event) {
     var $tempElpl = $("<input>");
     $("body").append($tempElpl);
     $tempElpl.val($("#twilapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempElpl.remove();
     alert("The link has been copied to your clipboard!");
  });

  $("#generate_twil_delrcpt").on("click", function(event) {

     var twiltoken = randomStr(35);
     var twildrwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliverytwil?twildrparam=') + twiltoken;

     $("#twilapi_url").val(twildrwhurl);
  });


  $("#generate_flow_rcpt").on("click", function(event) {

     var flowtokenrec = randomStr(70);
     var flowwhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmsflow?flowrecparam=') + flowtokenrec;

     $("#flowapi_url_rec").val(flowwhurlrec);
  });

  $("#copyToClipboardflow").on("click", function(event) {
     var $tempElpl = $("<input>");
     $("body").append($tempElpl);
     $tempElpl.val($("#flowapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempElpl.remove();
     alert("The link has been copied to your clipboard!");
  });

  $("#generate_flow_delrcpt").on("click", function(event) {

     var flowtoken = randomStr(70);
     var flowdrwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliveryflow?flowdrparam=') + flowtoken;

     $("#flowapi_url").val(flowdrwhurl);
  });


  $("#save_sms_settings").on("click", function(event) {

    event.preventDefault();
    OC.msg.startAction('#smsr_save_msg', t('sms_relentless', 'Saved'));

    var baseUrl = OC.generateUrl('/apps/sms_relentless/user/updatesettings');

    var messagesperpageinit = $("#messagesperpage").val();
    var messagesperpagesec = messagesperpageinit.replace(/[^0-9]/g, '');

    if (messagesperpagesec != '') {
        var messagesperpageproc = messagesperpagesec;
    } else {
        var messagesperpageproc = 100;
    }

    var getnotify = 0;

    if ($("#get_notify").is(':checked')) {
        getnotify = 1;
    }

    var emailaddressinit = $("#notification_email").val();

    function validate_email($email) {
        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        return email_reg.test($email);
    }

    if (validate_email(emailaddressinit)) {
         var notifyemail = emailaddressinit;
    } else {
         var notifyemail = '';
    }

    var telsenderinit = $("#tel_sender_name").val();
    var telsenderproc = telsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var nexsenderinit = $("#nex_sender_name").val();
    var nexsenderproc = nexsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var twilsenderinit = $("#twil_sender_name").val();
    var twilsenderproc = twilsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var includesmsinemail = 0;
    if ($("#includesmsinemail").is(':checked')) {
        includesmsinemail = 1;
    }

    var showdisplaynm = 0;
    if ($("#showdisplaynames").is(':checked')) {
        showdisplaynm = 1;
    }

    var datatosave = {
                      userId: userid,
                      telapiKey: $("#telapi_key").val(),
                      telPubKey: $("#tel_pub_key").val(),
                      telapiUrlRec: $("#telapi_url_rec").val(),
                      telapiUrl: $("#telapi_url").val(),
                      messagingProfileId: $("#messaging_profile_id").val(),
                      nexapiKey: $("#nexapi_key").val(),
                      nexapiSecret: $("#nexapi_secret").val(),
                      nexapiUrlRec: $("#nexapi_url_rec").val(),
                      nexapiUrl: $("#nexapi_url").val(),
                      twilapiKey: $("#twilapi_key").val(),
                      twilapiSecret: $("#twilapi_secret").val(),
                      twilapiUrlRec: $("#twilapi_url_rec").val(),
                      twilapiUrl: $("#twilapi_url").val(),
                      flowapiKey: $("#flowapi_key").val(),
                      flowapiSecret: $("#flowapi_secret").val(),
                      flowapiUrlRec: $("#flowapi_url_rec").val(),
                      flowapiUrl: $("#flowapi_url").val(),
                      telSenderName: telsenderproc,
                      nexSenderName: nexsenderproc,
                      twilSenderName: twilsenderproc,
                      messagesperpage: messagesperpageproc,
                      getNotify: getnotify,
                      notificationEmail: notifyemail,
                      getsmsinemail: includesmsinemail,
                      showDisplayNames: showdisplaynm
    };


    $.ajax({
       method: 'PUT',
       url: baseUrl + '/' + userid,
       contentType: 'application/json',
       data: JSON.stringify(datatosave),
       success: function() {
       },
       error: function() {
            alert('Error while attempting to save the settings! You can check the Nextcloud log to find more details about this issue.');
       }
    });

  });


  var baseUrlget = OC.generateUrl('/apps/sms_relentless/user/getsettings');

  $.ajax({
     method: 'GET',
     url: baseUrlget + '/' + userid,
     contentType: 'application/json',
     success: function(settingsfromdb) {
         $("#telapi_key").val(settingsfromdb.telapi_key);
         $("#tel_pub_key").val(settingsfromdb.tel_pub_key);
         $("#telapi_url_rec").val(settingsfromdb.telapi_url_rec);
         $("#telapi_url").val(settingsfromdb.telapi_url);
         $("#messaging_profile_id").val(settingsfromdb.messaging_profile_id);
         $("#nexapi_key").val(settingsfromdb.nexapi_key);
         $("#nexapi_secret").val(settingsfromdb.nexapi_secret);
         $("#nexapi_url_rec").val(settingsfromdb.nexapi_url_rec);
         $("#nexapi_url").val(settingsfromdb.nexapi_url);
         $("#twilapi_key").val(settingsfromdb.twilapi_key);
         $("#twilapi_secret").val(settingsfromdb.twilapi_secret);
         $("#twilapi_url_rec").val(settingsfromdb.twilapi_url_rec);
         $("#twilapi_url").val(settingsfromdb.twilapi_url);
         $("#flowapi_key").val(settingsfromdb.flowapi_key);
         $("#flowapi_secret").val(settingsfromdb.flowapi_secret);
         $("#flowapi_url_rec").val(settingsfromdb.flowapi_url_rec);
         $("#flowapi_url").val(settingsfromdb.flowapi_url);
         $("#tel_sender_name").val(settingsfromdb.tel_sender_name);
         $("#nex_sender_name").val(settingsfromdb.nex_sender_name);
         $("#twil_sender_name").val(settingsfromdb.twil_sender_name);
         $("#messagesperpage").val(settingsfromdb.messagesperpage);

         if (settingsfromdb.get_notify == 1) {
             $("#get_notify").attr('checked', true);
         } else {
             $("#get_notify").attr('checked', false);
         }

         $("#notification_email").val(settingsfromdb.notification_email);

         if (settingsfromdb.getsmsinemail == 1) {
             $("#includesmsinemail").attr('checked', true);
         } else {
             $("#includesmsinemail").attr('checked', false);
         }

         if (settingsfromdb.show_display_names == 1) {
             $("#showdisplaynames").attr('checked', true);
         } else {
             $("#showdisplaynames").attr('checked', false);
         }


         // Auto-reply settings

         // Get the available phone numbers from all providers associated with the access keys entered on the Settings page (restrictions are applied to numbers for non-admins)
         $("#autoRplPhoneNb").addClass('icon-loading');
         var getnumbersUrl = OC.generateUrl("/apps/sms_relentless/user/getautoreplyconf");

	 $.ajax({
		  url: getnumbersUrl + '/' + userid,
		  type: "GET",
                  contentType: 'application/json',
		  success: function(autoreplydata) {

                                    $("#autoRplPhoneNb").removeClass('icon-loading');
                                    var cusrDisplayName = autoreplydata.userdisplayname;
                                    var availPhoneNmbrs = autoreplydata.phonenumbers;
                                    var autorpldata = autoreplydata.autoreplies;

				    if (autorpldata.length > 0) { 
				        var arplNmb = autorpldata.length;
				    } else { 
				        var arplNmb = 0; 
				    }

				    // List the auto-replies for the phone numbers available for the current user
				    if (arplNmb == 0) {

				        $("#autoReplyTbl").append("<tr><td><input type='text' class='arplAuthor' value='"+ cusrDisplayName +"' disabled></td><td><select id='arpphn-"+ arplNmb +"' class='arplPhoneNmbr'></select></td><td><div id='arplmode-"+ arplNmb +"' class='arplMode'><select id='modeselect-"+ arplNmb +"' class='selectArplMode'><option value='' selected>Select mode</option><option value='daily'>Daily mode</option><option value='vacation'>Vacation mode</option></select><div id='modecont-"+ arplNmb +"' class='modeContent'></div></div></td><td><textarea id='arpltxt-"+ arplNmb +"' class='arplText' rows='20' cols='40' placeholder='Enter the auto-reply message here.'></textarea></td><td><img id='rmRow-"+ arplNmb +"' class='removeRow' src='/core/img/actions/close.svg' title='Remove this row from the database' style='cursor:pointer;margin:9px 8px 0px 18px;'></td><td><input type='submit' id='arplsave-"+ arplNmb +"' class='saveAutoReply' value='Save' title='Save Row' /></td></tr>");
				        $("#autoReplyTbl").append("<div><img id='addArplRow' src='/core/img/actions/add.svg' title='Add Row'></div>");

				    } else {

				        for (k = 0; k < arplNmb; k++) {

                                             if (autorpldata[k].days_of_week != '') {

                                                 var slctdMode = "<option value=''>Select mode</option><option value='daily' selected>Daily mode</option><option value='vacation'>Vacation mode</option>";
                                                 var dailyStartArr = autorpldata[k].daily_start.split(":");
                                                 var dailyEndArr = autorpldata[k].daily_end.split(":");

		                                 var dlHrStartOptions = "";
			                         for (var hr = 0; hr < 24; hr++) {
		                                      if (dailyStartArr[0] != hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlHrStartOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlHrStartOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

		                                 var dlMnStartOptions = "";
			                         for (var mn = 0; mn < 24; mn++) {
		                                      if (dailyStartArr[1] != hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlMnStartOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlMnStartOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

		                                 var dlHrEndOptions = "";
			                         for (var hr = 0; hr < 24; hr++) {
		                                      if (dailyEndArr[0] != hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlHrEndOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlHrEndOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

		                                 var dlMnEndOptions = "";
			                         for (var mn = 0; mn < 24; mn++) {
		                                      if (dailyEndArr[1] != hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlMnEndOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlMnEndOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

                                                 var modeContent = "<div class='daysOfWeek'>Days of the week:<div class='tooltipautoreply'><div id='infoautoreply'>i</div><div class='autorpltooltip'>Enter the order number of the days of the week in which the auto-reply will be sent. For example, to send the auto-reply every day from Monday to Friday (outside the time interval specified below), enter 1,2,3,4,5 To send the auto-reply only Monday, Thursday and Friday enter 1,4,5 To send the auto-reply every day of the week enter 1,2,3,4,5,6,7</div></div></div><input type='text' id='weekdays-"+ k +"' class='daysInWeek' value='"+ autorpldata[k].days_of_week +"'><div class='chooseTInterval'>Send auto-reply <span style='color:#ad0202'>outside</span> this interval:<div class='tooltipautoreplyst'><div id='infoautoreplyst'>i</div><div class='autorpltooltipst'>These fields specify the time of the server. If the server is located in a time zone that is different from that of the owner/company, the time interval entered here should be adjusted accordingly.</div></div></div><div class='selectArplHours'><select id='dmstarthr-"+ k +"' class='selectHrMin'>"+ dlHrStartOptions +"</select><select id='dmstartmn-"+ k +"' class='selectHrMin'>"+ dlMnStartOptions +"</select><span style='font-weight: 600'> — </span><select id='dmendhr-"+ k +"' class='selectHrMin'>"+ dlHrEndOptions +"</select><select id='dmendmn-"+ k +"' class='selectHrMin'>"+ dlMnEndOptions +"</select></div>";

                                             } else {

                                                 var vctnStart = autorpldata[k].vacation_start.split(" ")[0];
                                                 var vctnEnd = autorpldata[k].vacation_end.split(" ")[0];

                                                 var slctdMode = "<option value=''>Select mode</option><option value='daily'>Daily mode</option><option value='vacation' selected>Vacation mode</option>";
                                                 var modeContent = "<div class='chooseDateIntvl'>Send auto-reply <span style='color:#ad0202'>inside</span> this interval:</div><div class='arplstrtendDates'><div class='stdtTitle'>Start Date</div><input type='text' id='startDT-"+ k +"' class='startDate' placeholder='Pick a date' value='"+ vctnStart +"'><div class='enddtTitle'>End Date</div><input type='text' id='endDT-"+ k +"' class='endDate' placeholder='Pick a date' value='"+ vctnEnd +"'></div>"
                                             }

				             $("#autoReplyTbl").append("<tr><td><input type='text' class='arplAuthor' value='"+ autorpldata[k].saved_by_dsplname +"' disabled></td><td><select id='arpphn-"+ k +"' class='arplPhoneNmbr' style='pointer-events:none'><option selected>"+ autorpldata[k].phone_number +"</option></select></td><td><div id='arplmode-"+ k +"' class='arplMode'><select id='modeselect-"+ k +"' class='selectArplMode'>"+ slctdMode +"</select><div id='modecont-"+ k +"' class='modeContent'>"+ modeContent +"</div></div></td><td><textarea id='arpltxt-"+ k +"' class='arplText' rows='20' cols='40' placeholder='Enter the auto-reply message here.'>"+ autorpldata[k].message_text +"</textarea></td><td><img id='rmRow-"+ k +"' class='removeRow' src='/core/img/actions/close.svg' title='Remove this row from the database' style='cursor:pointer;margin:9px 8px 0px 18px;'></td><td><input type='submit' id='arplsave-"+ k +"' class='saveAutoReply' value='Edit' title='Edit Row' /></td></tr>");
				        }
				        $("#autoReplyTbl").append("<div><img id='addArplRow' src='/core/img/actions/add.svg' title='Add Row'></div>");
				    }


				    // Create a list with all the available phone numbers
                                    var numbersListItems = "<option value='' selected>Select phone number</option>";

				    $.each(availPhoneNmbrs, function(key, indsmsnmb) {
					 var emptyinit = indsmsnmb.split(":");
					 var emptysec = emptyinit[1];
					 var emptycheck = emptysec.replace(" ", "").replace("+", "");

					 if (emptycheck != '') {
					     numbersListItems += "<option value='"+ indsmsnmb +"'>"+ indsmsnmb +"</option>";
					 }
				    });

                                    if (arplNmb == 0) {
				        $("#arpphn-"+ arplNmb).append(numbersListItems);
                                    }

                                    // Initialize the date picker
			            $('[id^="endDT-"]').datepicker({ dateFormat: "yy-mm-dd" });
			            $('[id^="startDT-"]').datepicker({ dateFormat: "yy-mm-dd" });


                                    // Select the auto-reply mode
                                    function selectMode() {

		                            $('[id^="modeselect-"]').change(function() {

		                               var crtnmbr = $(this).attr("id").replace("modeselect-", "");

		                               var dailyHrStart = "";
		                               for (var h = 0; h < 24; h++) {
		                                    dailyHrStart += "<option value='"+ h.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ h.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                               }

		                               var dailyMnStart = "";
		                               for (var m = 0; m < 60; m++) {
		                                    dailyMnStart += "<option value='"+ m.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ m.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                               }

		                               var dailyHrEnd = dailyHrStart;
		                               var dailyMnEnd = dailyMnStart;

		                               if ($(this).val() == 'daily') {
		                                   $("#modecont-"+ crtnmbr).empty();
		                                   $("#modecont-"+ crtnmbr).append("<div class='daysOfWeek'>Days of the week:<div class='tooltipautoreply'><div id='infoautoreply'>i</div><div class='autorpltooltip'>Enter the order number of the days of the week. For example, to send the auto-reply every day from Monday to Friday outside the specified time interval, enter 1,2,3,4,5 To send the auto-reply only Monday, Thursday and Friday enter 1,4,5 To send the auto-reply every day of the week enter 1,2,3,4,5,6,7</div></div></div><input type='text' id='weekdays-"+ crtnmbr +"' class='daysInWeek'><div class='chooseTInterval'>Send auto-reply <span style='color:#ad0202'>outside</span> this interval:<div class='tooltipautoreplyst'><div id='infoautoreplyst'>i</div><div class='autorpltooltipst'>These fields specify the time of the server. If the server is located in a time zone that is different from that of the owner/company, the time interval entered here should be adjusted accordingly.</div></div></div><div class='selectArplHours'><select id='dmstarthr-"+ crtnmbr +"' class='selectHrMin'>"+ dailyHrStart +"</select><select id='dmstartmn-"+ crtnmbr +"' class='selectHrMin'>"+ dailyMnStart +"</select><span style='font-weight: 600'> — </span><select id='dmendhr-"+ crtnmbr +"' class='selectHrMin'>"+ dailyHrEnd +"</select><select id='dmendmn-"+ crtnmbr +"' class='selectHrMin'>"+ dailyMnEnd +"</select></div>");
		                               } else if ($(this).val() == 'vacation') {
		                                   $("#modecont-"+ crtnmbr).empty();
		                                   $("#modecont-"+ crtnmbr).append("<div class='chooseDateIntvl'>Send auto-reply <span style='color:#ad0202'>inside</span> this interval:</div><div class='arplstrtendDates'><div class='stdtTitle'>Start Date</div><input type='text' id='startDT-"+ crtnmbr +"' class='startDate' placeholder='Pick a date'><div class='enddtTitle'>End Date</div><input type='text' id='endDT-"+ crtnmbr +"' class='endDate' placeholder='Pick a date' /></div>");
		                               }

					       $("#endDT-"+ crtnmbr +"").datepicker({ dateFormat: "yy-mm-dd" });
					       $("#startDT-"+ crtnmbr +"").datepicker({ dateFormat: "yy-mm-dd" });
		                          });
                                  }
                                  selectMode();

				  // Save the data
				  function saveArplRow() {

				     $('[id^="arplsave-"]').unbind("click");
				     $('[id^="arplsave-"]').click(function(event) {

				        event.preventDefault();
				        var crntrwnmbr = $(this).attr("id").replace("arplsave-", "");

				        if ($(this).attr("value") == "Save") {

				            var phoneNmbr = $("#arpphn-"+ crntrwnmbr).val();
				            var arplText = $("#arpltxt-"+ crntrwnmbr).val();
				            var slctdMode = $("#modeselect-"+ crntrwnmbr).val();

				            var slctddmDays = "";
				            var slctdHrStart = "";
				            var slctdMnStart = "";
				            var slctdHrEnd = "";
				            var slctdMnEnd = "";

				            var vcStartDate = null;
				            var vcEndDate = null;

				            if (slctdMode == 'daily') {

				                slctddmDays = $("#weekdays-"+ crntrwnmbr).val().trim();
				                slctdHrStart = $("#dmstarthr-"+ crntrwnmbr).val().trim();
				                slctdMnStart = $("#dmstartmn-"+ crntrwnmbr).val().trim();
				                slctdHrEnd = $("#dmendhr-"+ crntrwnmbr).val().trim();
				                slctdMnEnd = $("#dmendmn-"+ crntrwnmbr).val().trim();

                                                if (slctdHrStart != '' && slctdMnStart != '') {
                                                    var hrmnStartComp = slctdHrStart +":"+ slctdMnStart;
                                                } else { var hrmnStartComp = ""; }

                                                if (slctdHrEnd != '' && slctdMnEnd != '') {
                                                    var hrmnEndComp = slctdHrEnd +":"+ slctdMnEnd;
                                                } else { var hrmnEndComp = ""; }

                                                if (!(/^[1-7\,]+$/.test(slctddmDays))) {
				                    alert("The 'Days of the week' field can contain only digits from 1 to 7 and commas (,).");
				                    return;
                                                }

                                                if (!(/^[0-9]+$/.test(slctdHrStart + slctdMnStart + slctdHrEnd + slctdMnEnd))) {
				                    alert("The starting and ending values of the time interval for the 'Daily mode' can contain only digits from 0 to 9.");
				                    return;
                                                }

                                                if (slctddmDays.trim() == '' || (slctdHrStart == slctdHrEnd && slctdMnStart == slctdMnEnd)) {
				                    alert("For the 'Daily mode', you have to enter the order number of the days of the week for which you want the auto-reply to be sent, and you have to set a starting time that is different from the ending time!");
				                    return;
                                                }

				            } else if (slctdMode == 'vacation') {
		
                                                if ($("#startDT-"+ crntrwnmbr).val().trim() == '' || $("#endDT-"+ crntrwnmbr).val().trim() == '') {

				                    alert("For the 'Vacation mode', you have to enter both a start date and an end date.");
				                    return;

                                                } else {

                                                    if (!(/^[0-9\-]+$/.test($("#startDT-"+ crntrwnmbr).val().trim() + $("#endDT-"+ crntrwnmbr).val().trim()))) {
				                        alert("The start date and end date values for the 'Vacation mode' can contain only digits from 0 to 9 and hyphens (-).");
				                        return;
                                                    }

		                                    vcStartDate = $("#startDT-"+ crntrwnmbr).val().trim() +" 00:00:00";
				                    vcEndDate = $("#endDT-"+ crntrwnmbr).val().trim() +" 23:59:59";
				                    var strtDateCmp = new Date(vcStartDate).toJSON().slice(0, 10) +" 00:00:00";
				                    var endDateCmp = new Date(vcEndDate).toJSON().slice(0, 10) +" 23:59:59";
				                    var crntDate = new Date().toJSON().slice(0, 10) +" 23:59:59";

                                                    if (vcStartDate.trim() == "" || vcEndDate.trim() == "" || (strtDateCmp >= endDateCmp || ((strtDateCmp < crntDate) && (endDateCmp < crntDate)))) {
				                        alert("For 'Vacation mode', you have to enter both a start date and an end date, the start date must be before the end date and at least the ending of the time interval must be in the future.");
				                        return;
                                                    }
                                                }
				            }


				            if (phoneNmbr != '') {

				              if (arplText.trim() != '') {

				                if (slctdMode != '') {

				                    var saveArplUrl = OC.generateUrl('/apps/sms_relentless/user/updateautoreplies');
				                    var arpldata = {
				                         userId: userid,
				                         savedByDsplname: cusrDisplayName,
				                         phoneNumber: phoneNmbr,
				                         daysOfWeek: slctddmDays,
				                         dailyStart: hrmnStartComp,
				                         dailyEnd: hrmnEndComp,
				                         vacationStart: vcStartDate,
				                         vacationEnd: vcEndDate,
				                         messageText: arplText
				                    };

					            $.ajax({
					              method: 'PUT',
					              url: saveArplUrl + '/' + userid,
					              contentType: 'application/json',
					              data: JSON.stringify(arpldata),
				                      success: function(messagereceived) {

				                                   if (messagereceived == 'success') {
				                                       alert('The auto-reply has been successfully saved to the database!');
				                                   } else if (messagereceived == 'failure') {
				                                       alert('Error while trying to save the auto-reply!');
				                                   } else if (messagereceived == 'not allowed') {
                                                                       alert('You cannot change an auto-reply that was saved by a different user.');
                                                                   }
				                      },
					              error: function() {
						                   alert('Error while attempting to save the auto-reply! You can check the Nextcloud log to find more details about this issue.');
					              }
					            });


                                                } else { alert("Please select the auto-reply mode."); return; }

                                              } else { alert("Please enter the text of the auto-reply."); return; }

                                            } else { alert("Please select a phone number if at least one number is available in the 'Phone Number' drop-down list. Otherwise, you should contact the administrator."); return; }

                                            $(this).attr("value", "Edit");

                                        } else {
                                            $("#arplsave-"+ crntrwnmbr).attr("value", "Save");
                                        }

                                     });

				  }
                                  saveArplRow();


				  // Remove a row
				  function removeArplRow() {
				       $('[id^="rmRow-"]').click(function() {

					  var slctRowRm = $(this).attr("id").replace("rmRow-", "");
					  var crntPhnNmbr = $("#arpphn-"+ slctRowRm).val();

					  if (confirm("Do you really want to remove this row from the database ?")) {

					      var rmvArplUrl = OC.generateUrl('/apps/sms_relentless/user/removeautoreplies');
					      $.ajax({
						   url: rmvArplUrl + '/' + userid,
						   method: "POST",
						   dataType: "text",
						   data: { phoneNumber: crntPhnNmbr },
						   success: function(delresult) {

						                     if (delresult.indexOf("success") > -1) {
						                         alert("The auto-reply has been removed successfully!");
						                         $("#arpphn-"+ slctRowRm).closest("tr").remove();
						                     } else if (delresult.indexOf("failure") > -1) {
						                         alert("Error while trying to remove auto-reply data!");
						                     } else if (delresult.indexOf("not allowed") > -1) {
                                                                         alert("You cannot remove the auto-reply saved by another user.");
                                                                     }
						   },
						   error: function() { alert("Error while attempting to remove auto-reply data! You can check the Nextcloud log to find more details about this issue."); }
					       });
					  }
				       });
				  }
				  removeArplRow();

                                  // Add new row
                                  $("#addArplRow").click(function() {

                                     if ($("#autoReplyTbl").find("tr:last-child").find(".arplPhoneNmbr").length > 0) {
                                         var lastarpl = $("#autoReplyTbl").find("tr:last-child").find(".arplPhoneNmbr").attr("id").replace("arpphn-", "");
                                         var indArplAdd = parseInt(lastarpl + 1);
                                     } else { var indArplAdd = 0; }
			             $("#autoReplyTbl").append("<tr><td><input type='text' class='arplAuthor' value='"+ cusrDisplayName +"' disabled></td><td><select id='arpphn-"+ indArplAdd +"' class='arplPhoneNmbr'>"+ numbersListItems +"</select></td><td><div id='arplmode-"+ indArplAdd +"' class='arplMode'><select id='modeselect-"+ indArplAdd +"' class='selectArplMode'><option value='' selected>Select mode</option><option value='daily'>Daily mode</option><option value='vacation'>Vacation mode</option></select><div id='modecont-"+ indArplAdd +"' class='modeContent'></div></div></td><td><textarea id='arpltxt-"+ indArplAdd +"' class='arplText' rows='20' cols='40' placeholder='Enter the auto-reply message here.'></textarea></td><td><img id='rmRow-"+ indArplAdd +"' class='removeRow' src='/core/img/actions/close.svg' title='Remove this row from the database' style='cursor:pointer;margin:9px 8px 0px 18px;'></td><td><input type='submit' id='arplsave-"+ indArplAdd +"' class='saveAutoReply' value='Save' title='Save Row' /></td></tr>");

                                     selectMode();
                                     saveArplRow();
                                     removeArplRow();

			             // Check if there is an auto-reply set for the same phone number
				     $("#arpphn-"+ indArplAdd).change(function() {
					 var selectedPhNb = $("#arpphn-"+ indArplAdd).val();
					 var allArplPhNmbrs = $("#autoReplyTbl").find("tr").find(".arplPhoneNmbr");
					 var phNbChck = 0;
					 allArplPhNmbrs.each(function() {
					    var slctphnb = ($(this).val())? $(this).val() : $(this).text();
					    if (selectedPhNb == slctphnb) { phNbChck++; }
					 });

					 if (phNbChck == 2) {
					     alert("There is already an auto-reply set up for this phone number. Please edit its own row, or choose a different phone number.");
					     $(this).val('');
					     return;
					 }
				     });
                                  });

		  },
		  error: function() {
                                    $("#autoRplPhoneNb").removeClass('icon-loading'); 
                                    alert("Error while attempting to get the auto-reply settings! You can check the Nextcloud log to find more details about this issue.");
                  }
         });

     },
     error: function() {
                  alert('Error while getting the settings! You can check the Nextcloud log to find more details about this issue.');
     }
  });

});
