/**
 * @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 parseddata = null;
  var sentparseddata = null;
  var groupedparsed = null;
  var messagesperpage = 100;
  var newMsgInterval = 5000;
  var archivedConvNmbr = null;
  var newMsgRcd = 0;
  var intervalRfrSent = 0;
  var intervalNmfr = null;
  var ctappdir = 'apps';

  // Get the app's directory
  var getappdirurl = OC.generateUrl('/apps/sms_relentless/user/getappdirectory');

  $.ajax({
     method: 'GET',
     url: getappdirurl,
     contentType: 'application/json',
     success: function(appdirfdb) {
                ctappdir = appdirfdb;
     },
     error: function() {
                alert("An error occurred while getting the app's directory. You can check the Nextcloud log to find more details about this issue.");
     }
  });

  // Get the number of messages per page and the time interval for checking for new received messages, from the database
  var getNoPerPageUrl = OC.generateUrl("/apps/sms_relentless/user/getmsgsperpgnewmsgarchnb");

  $.ajax({
        url: getNoPerPageUrl,
        method: 'GET',
        success: function(mesperpagedb) {

                 if (mesperpagedb.msgsperpage) { messagesperpage = mesperpagedb.msgsperpage; }
                 if (mesperpagedb.newmsgcheck) { newMsgInterval = mesperpagedb.newmsgcheck * 1000; }
                 if (mesperpagedb.archconvnb == 0 || mesperpagedb.archconvnb) { archivedConvNmbr = mesperpagedb.archconvnb; }
        },
        error: function() {
                 showAlert("Error while getting the number of messages per page. You can check the Nextcloud log to find more details about this issue!");
        }
  });

  // Get the 'new received message' indicator from the database
  function checkIfNewMessage() {

        var getNewMsgInd = OC.generateUrl("/apps/sms_relentless/user/getnewmsgindicator");

        $.ajax({
              url: getNewMsgInd,
              method: 'GET',
              success: function(newmsgdb) {
                       newMsgRcd = newmsgdb;
                       if (newMsgRcd == 1) { 

                           if ($("#listAllMsgsFromTo").is(":visible")) { $('#smstables').empty(); setTimeout(function() { $("#refreshMsgsConvtf").click(); }, 500); }
                           if ($("#listAllMsgsConv").is(":visible")) { $('#smstables').empty(); setTimeout(function() { $("#refreshMsgsConv").click(); }, 500); }
                           if ($("#conversationsTable").is(":visible")) {

                               var archCvId = '';
                               var actCvId = '';

                               $(".convsListArch").each(function() { 
		                   if ($(this).css('background-color') === "rgb(241, 224, 239)") {
                                       archCvId = $(this).attr("id");
		                   }
                               });

		               $(".convsListAct").each(function() {
		                   if ($(this).css('background-color') === "rgb(215, 239, 239)") {
                                       actCvId = $(this).attr("id");
		                   }
		               });

                               $('#smstables').empty();
                               $("#conversationsshow").click();
                               setTimeout(function() { if (actCvId != '') { document.getElementById(actCvId).click(); } else if (archCvId != '') { document.getElementById(actCvId).click(); } }, 800);

                           } else {
                               $('#smstables').empty();
                               $("#receivedsmstableshow").click();
                           }
                       }
              },
              error: function() {
                           // showAlert("Error while getting the 'new received message' indicator. You can check the Nextcloud log to find more details about this issue!");
              }
        });
  }


  // List received messages
  $("#receivedsmstableshow").on("click", function(event) {

     $('#smstables').empty();
     clearInterval(intervalNmfr);

     var getReceivedUrl = OC.generateUrl("/apps/sms_relentless/user/getreceivedtable");

     $('#smstables').addClass('icon-loading');

     $.ajax({
          url: getReceivedUrl,
          method: 'GET',
          contentType: 'application/json',
          success: function(datafdb) {

                var parseddata = datafdb.datarows;

                $('#smstables').append("<div id='toptablerec'><div class='topbuttonandpage'><span id='recarrow' title='Show/Hide filters and Delete button'></span></div><div id='paginationrec' class='recpages'>Pages </div></div>");
                $('#smstables').append("<table id='recSmsTable'></table>");

                $('#recSmsTable').append("<tr id='recfiltersrow'><td class='selectalldvfilter'><button id='clearrecfilters' title='Clear all filters.'></button><button id='deleterecrows' title='Permanently delete the selected row(s) from below from the database.'></button></td><td class='selectalldvfilter'><input type='text' id='dbidtextrec' class='indivfilterrec' title='Enter a database ID number to apply the filter.'><input type='submit' id='databaseidfilter' class='filterbuttonsrec' value='' title='Filter rows by the specified database ID.' /></td><td class='selectalldvfilter'><input type='text' id='useridtextrec' class='indivfilterrec' title='Enter a Nextcloud username to apply the filter.' /><input type='submit' id='useridfilter' class='filterbuttonsrec' value='' title='Filter rows by the specified username.' /></td><td class='selectalldvfilter'><input type='text' id='messageidtextrec' class='indivfilterrec' title='Enter a fragment from a message ID to apply the filter.'  /><input type='submit' id='messageidfilter' class='filterbuttonsrec' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='datetextrec' class='indivfilterrec' title='Enter a fragment of a date to apply the filter.'/><input type='submit' id='datefilter' class='filterbuttonsrec' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='fromtextrec' class='indivfilterrec' title='Enter a fragment of a sender&#146s phone number or alphanumeric sender ID, to apply the filter.' /><input type='submit' id='fromfilter' class='filterbuttonsrec' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='totextrec' class='indivfilterrec' value='' title='Enter a fragment of a recipient&#146s phone number to apply the filter.'  /><input type='submit' id='tofilter' class='filterbuttonsrec' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='messagetextrec' class='indivfilterrec' title='Enter a fragment of a message to apply the filter.' /><input type='submit' id='messagefilter' class='filterbuttonsrec' value='' title='Filter rows by the specified string.'/></td></tr>");
                $('#recSmsTable').append("<tr class='receivedrows' id='recheaderrow'><th id='selectalldv' class='selectsmsdv'><input type='checkbox' id='selectAllChckbx' class ='indivchckbx' title='Select all rows from all pages.' /></th><th title='The database ID of each message.'>ID</th><th>User ID</th><th>Message ID</th><th>Date</th><th>From</th><th>To</th><th>Received Message</th></tr>");

                $('#recfiltersrow').hide();

                if (datafdb.showdispnm == 1) {

                    for (var i = 0; i < parseddata.length; i++) {

                         if (parseddata[i].author_displayname) {
                             var procrcmessage = "<span class='messageAuthorName'>"+ parseddata[i].author_displayname + ":</span>" + parseddata[i].message +"<div id='showMsgConv-"+ i +"' class='lstMsgConv'><img class='lstMsgConvImg' src='/" + ctappdir + "/sms_relentless/img/reply.svg' title='Show all the messages exchanged between the current 2 phone numbers.'></div>";
                         } else {
                             var procrcmessage = parseddata[i].message +"<div id='showMsgConv-"+ i +"' class='lstMsgConv'><img class='lstMsgConvImg' src='/" + ctappdir + "/sms_relentless/img/reply.svg' title='Show all the messages exchanged between the current 2 phone numbers.'></div>";
                         }

                         if (parseddata[i].internal_sender == 0) {
                             var procrecFrom = "<div id='frmNmbr-"+ i +"'><div id='addDispName-"+ i +"' style='display:block;margin-right:5px;'><img class='addNameToPhNb' src='/" + ctappdir + "/sms_relentless/img/user-grey.svg' title='Associate a Display Name with this phone number'></div>"+ parseddata[i].from +"<div id='showMsgFrom-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src='/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";
                         } else {
                             var procrecFrom = "<div id='frmNmbr-"+ i +"'>"+ parseddata[i].from +"<div id='showMsgFrom-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src = '/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";
                         }

                         var procrecTo = "<div id='toNmbr-"+ i +"'>"+ parseddata[i].to +"<div id='showMsgTo-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src = '/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";

                         $("#recSmsTable").append("<tr id='singlerow_"+ i +"' class='receivedrowsbody'><td class='selectsmsdv'><input type='checkbox' id='selectspec_"+ i +"' class='indivchckbx' /></td><td class='dbidcolumnrec'>"+ parseddata[i].id +"</td><td class='useridcolrec'>"+ parseddata[i].user_id +"</td><td class='messageidcolrec'>"+ parseddata[i].message_id +"</td><td class='datecolrec'>"+ parseddata[i].date +"</td><td class='fromcolumnrec'>"+ procrecFrom +"</td><td class='tocolrec'>"+ procrecTo +"</td><td class='messagecolumnrec'>"+ procrcmessage +"</td></tr>");
                    }

                } else {

                    for (var i = 0; i < parseddata.length; i++) {

                         var procrcmessage = parseddata[i].message +"<div id='showMsgConv-"+ i +"' class='lstMsgConv'><img class='lstMsgConvImg' src='/" + ctappdir + "/sms_relentless/img/reply.svg' title='Show all the messages exchanged between the current 2 phone numbers.'></div>";

                         if (parseddata[i].internal_sender == 0) {
                             var procrecFrom = "<div id='frmNmbr-"+ i +"'><div id='addDispName-"+ i +"' style='display:block;margin-right:5px;'><img class='addNameToPhNb' src='/" + ctappdir + "/sms_relentless/img/user-grey.svg' title='Associate a Display Name with this phone number'></div>"+ parseddata[i].from +"<div id='showMsgFrom-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src='/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";
                         } else {
                             var procrecFrom = "<div id='frmNmbr-"+ i +"'>"+ parseddata[i].from +"<div id='showMsgFrom-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src = '/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";
                         }

                         var procrecTo = "<div id='toNmbr-"+ i +"'>"+ parseddata[i].to +"<div id='showMsgTo-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src = '/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";

                         $("#recSmsTable").append("<tr id='singlerow_"+ i +"' class='receivedrowsbody'><td class='selectsmsdv'><input type='checkbox' id='selectspec_"+ i +"' class='indivchckbx' /></td><td class='dbidcolumnrec'>"+ parseddata[i].id +"</td><td class='useridcolrec'>"+ parseddata[i].user_id +"</td><td class='messageidcolrec'>"+ parseddata[i].message_id +"</td><td class='datecolrec'>"+ parseddata[i].date +"</td><td class='fromcolumnrec'>"+ procrecFrom +"</td><td class='tocolrec'>"+ procrecTo +"</td><td class='messagecolumnrec'>"+ procrcmessage +"</td></tr>");
                    }
                }

                $('#smstables').append("<div id='totalrecmessages'>Total displayed messages: " + parseddata.length + "</div>");

                $('#smstables').removeClass('icon-loading');
                $('#recarrow').removeClass('arrowUpCl');
                $('#recarrow').addClass('arrowDownCl');

                // Show the pop-up window that lists all the messages exchanged between the current 2 phone numbers
                function showRecMsgPerConv(phNumberFrom, phNumberTo) {

                   let allfrmtomsg = "<div id='listAllMsgsConv'>";
                   allfrmtomsg += "<div id='draglstMsgmWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
                   allfrmtomsg += "<a id='closeFrmMsgWindow' title='Close this window'></a>";
                   allfrmtomsg += "<div class='showByNmbrTitle'>Messages exchanged between <span style='color:#04957b'>"+ phNumberFrom +"</span> and <span style='color:#04957b'>"+ phNumberTo +"</span></div>";
                   allfrmtomsg += "<div id='frmMsgLstWrap'>";
                   allfrmtomsg += "<table id='frmMsgLstTbl'>";
                   allfrmtomsg += "<tr class='groupedrowsbody'><td><div id='grpdbynamelst' class='groupedLstNamespn'></div></td><td><div id='loadMoreMsgs' title='Click to load older messages.'>Load more messages</div><div id='loadMoreMsgsusr' title='Click to load older messages.'>Load more messages</div><div id='msgListRowCell' class='groupedLstMsgspn'></div><div id='refreshMsgsWrap'><div id='refreshMsgsConv' title='Refresh list of messages'></div></div><div id='arrowupWrap'><div id='upArrowSmall' title='Scroll to the top'></div></div></td></tr>";
                   allfrmtomsg += "</table></div>";
                   allfrmtomsg += "<div id='sendMsgReply'><table id='sendMsgConv'><tr><td><div id='fromPhoneNmbrConv'>From: <select id='selectFromNbConv'></select></div><div id='toPhoneNmbrConv'>To: <span id='toNmbrConv' style='color:#04957b'>"+ phNumberFrom +"</span></div></td></tr>";
                   allfrmtomsg += "<tr><td><textarea id='sendMsgConvText' placeholder='Enter a message here, then press Send SMS.'></textarea></td></tr></table>";
                   allfrmtomsg += "<div id='sendMsgConvBtn'>Send SMS</div></div>";
                   allfrmtomsg += "<div id='expandWindowRplCtn' title='Expand to send a reply'><img id='expandWindowRpl' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;cursor:grab;'></div>";
                   allfrmtomsg += "</div>";

                   $("#content").append("<div id='recTblOverlay'></div>");
                   $("#content").append(allfrmtomsg);

                   let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 340) +"px";
                   let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 300) +"px";
                   $("#listAllMsgsConv").css({ "top" : topDist, "left" : leftDist });

                   $("#closeFrmMsgWindow").click(function() { $("#listAllMsgsConv").remove(); $("#recTblOverlay").remove(); });
                   $("#recTblOverlay").click(function() { $("#listAllMsgsConv").remove(); $("#recTblOverlay").remove(); });


	           // Expand the window when clicking on the arrow, to be able to send a reply message
                   $("#expandWindowRpl").unbind("click");
	           $("#expandWindowRpl").click(function() {

	              if ($(this).attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsConv").css("height", "618px");
                          } else {
                              $("#listAllMsgsConv").css("height", parseInt($(window).height() - 32) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 304) + "px");
                          }
	                  $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsConv").css("height", "490px");
                          } else {
                              $("#listAllMsgsConv").css("height", parseInt($(window).height() - 120) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 232) + "px");
                          }
                          $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
	              }
	           });


                   // Send a message from the 'conversation' window
                   $("#sendMsgConvBtn").click(function() {

                      $("#sendMsgConv,#sendMsgConvBtn").addClass('icon-loading');
                      var msgToSend = $("#sendMsgConvText").val();
                      var selectedid = $("#selectFromNbConv").val();
                      var toNumber = $("#toNmbrConv").text();
                      var receiversNumbers = [toNumber];

		      if (selectedid != '') { 

			  var sendersplit = selectedid.split(":");
			  var providercap = sendersplit[0];
			  var provsec = sendersplit[1];

			  if (/[a-zA-Z]/.test(provsec)) {
			      var alphanumcheck = true;
			  } else { var alphanumcheck = false; }

			  if (providercap == 'Tx' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == false) {
			      var selectedsender = selectedid.replace(/[^0-9]/g, "");
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  } else if (providercap == 'Tx' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  }

                          var uploadedtomms = [];

	                  if (msgToSend != '') {

				  $.ajax({
				     url: relbaseUrl,
				     type: "POST",
				     data: {
				           receiversPhoneNbs: receiversNumbers,
				           fromsender: selectedsender,
				           waitinterval: 1000,
				           sentsmstext: msgToSend,
				           ismms: 0,
				           mmsfiles: uploadedtomms
				         },
				     success: function(displayname) {

                                           var tzdate = new Date();
                                           var presDatest = new Date(tzdate.getTime() - (tzdate.getTimezoneOffset() * 60000)).toJSON();
                                           var presDatedb = presDatest.split(".")[0];
                                           var presDatesc = presDatedb.split("T");
                                           var presDate = presDatesc[0] +" "+ presDatesc[1];
                                           var sentMessageStatus = '';

                                           if (displayname) {
                                               var msgToSendproc = "<span class='msgAuthorNameGrp'>"+ displayname + ":</span>" + msgToSend; 
                                           } else { var msgToSendproc = msgToSend; }

                                           $("#msgListRowCell").append("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ selectedsender +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ receiversNumbers[0] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ msgToSendproc +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ presDate +"</div><div class='sentMssgStatus'>"+ sentMessageStatus +"</div></div>");

                                           // Scroll down to the bottom of the window
                                           $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

                                           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     },
				     error: function() {
                                           showAlert("Error while sending the message. You can check your Nextcloud log to find out more about this issue.");
				           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     }
				  });
			  } else {
                                  showAlert("Please enter a message in the text box!");
				  $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
			  }
		      } else {
                              showAlert("Please choose a Sender ID from the 'From' drop-down list!");
			      $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
		      }
                   });


	           // Make the window draggable
	           function makeMgrWndDraggable(e) {

			   window.pmdragging = {};
			   pmdragging.pageX0 = e.pageX;
			   pmdragging.pageY0 = e.pageY;
			   pmdragging.elem = $("#listAllMsgsConv");
			   pmdragging.offset0 = $("#listAllMsgsConv").offset();

			   function handle_dragging(e) {
			       let left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
			       let top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
			       $(pmdragging.elem).offset({top: top, left: left});
			   }

			   function handle_mouseup(e) {
			       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
			   }

			   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
	           }
	           $("#draglstMsgmWindow").mousedown(makeMgrWndDraggable);
	           $("#draglstMsgmWindowsc").mousedown(makeMgrWndDraggable);


                   // Append the available phone numbers to the From drop-down list
                   var availPhoneNmbrs = [];
                   $("#currentsmsnmbrs .optselectsmsnb").each(function() {
                      var crtphnmbr = $(this).attr("value");
                      if (crtphnmbr != "") { availPhoneNmbrs.push(crtphnmbr); }
                   });

                   if (availPhoneNmbrs.length > 0) {
                       var avphopt = "";
                       for (let d = 0; d < availPhoneNmbrs.length; d++) {
                            if (availPhoneNmbrs[d].indexOf(phNumberTo) === -1) {
                                avphopt += "<option value='"+ availPhoneNmbrs[d] +"'>"+ availPhoneNmbrs[d] +"</option>";
                            } else {
                                avphopt += "<option value='"+ availPhoneNmbrs[d] +"' selected>"+ availPhoneNmbrs[d] +"</option>";
                            }
                       }
                       $("#selectFromNbConv").append(avphopt);

                   } else { $("#selectFromNbConv").append("<option value='' selected>No IDs</option>"); }


                   // Get the messages exchanged between the current 2 phone numbers, from the database
                   function getMsgsForNumbers(phNumberFrom, phNumberTo) {

			   let getGrpConvUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedforreply");

			   $('#listAllMsgsConv').addClass('icon-loading');

			   let totalPhNmbrs = 0;

			   $.ajax({
				  method: 'POST',
				  url: getGrpConvUrl,
				  contentType: 'application/json',
		                  data: JSON.stringify({ "phoneNmbrFrom": phNumberFrom, "phoneNmbrTo": phNumberTo }),
				  success: function(groupedperconv) {

					     $('#listAllMsgsConv').removeClass('icon-loading');

					     let fromtoNmbrsData = [];

					     for (let i = 0; i < groupedperconv.length; i++) {

						     if (groupedperconv[i].author_displayname) {
							 var authordnm = groupedperconv[i].author_displayname;
						     } else { 
							 var authordnm = '';
						     }

						     var sentfromnmbrarr = groupedperconv[i].from.split(": ");
						     if (sentfromnmbrarr[1]) {
					                 var groupednbfrom = sentfromnmbrarr[1];
                                                     } else {
					                 var groupednbfrom = sentfromnmbrarr[0];
                                                     }

						     var modmessagerec = '';
						     if (groupedperconv[i].author_displayname) {
							 modmessagerec = "<span class='msgAuthorNameGrp'>"+ groupedperconv[i].author_displayname + ":</span>" + groupedperconv[i].message;
						     } else {
					                 modmessagerec = groupedperconv[i].message;
		                                     }

						     if (groupedperconv[i].to.indexOf(": ") > -1) {
						         var groupednmbrtopre = groupedperconv[i].to.split(": ");
						         var groupednmbrto = groupednmbrtopre[1];
						     } else { 
						         var groupednmbrto = groupedperconv[i].to;
						     }

						     fromtoNmbrsData.push({
						               'author_displayname': authordnm,
						               'from': groupednbfrom,
						               'to': groupednmbrto,
						               'message': modmessagerec,
						               'date': groupedperconv[i].date,
						               'status': groupedperconv[i].deliveryreceipt,
						               'table': groupedperconv[i].table
						     });
					     }


					     // Remove the duplicates
					     let noDupMsgData = [];
					     $.each(fromtoNmbrsData, function(i, e) {
						    let matchingData = $.grep(noDupMsgData, function(item) {
						            return item.from == e.from && item.to == e.to && item.message == e.message && item.table == 'received' && e.table == 'sent';
						    });
						    if (matchingData.length === 0) {
							noDupMsgData.push(e);
						    }
					     });

					     let messagesPerNmbr = {};
					     let msgsNamesPerNmbr = {};
					     let msgsNmbrsNames = {};

					     let displayNamesarr = [];
					     let convData = [];

					     for (let n = 0; n < noDupMsgData.length; n++) {

					          if (noDupMsgData[n]['from'] == phNumberFrom && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == phNumberFrom && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_to',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });


					          } else if (noDupMsgData[n]['from'] == phNumberFrom && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == phNumberFrom && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_on',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });
					          }
					     }

					     // Sort messages by date
					     convData.sort(function(a, b) {
                                                return new Date(b.date) - new Date(a.date);
					     });

					     // Collect the display names of the users that sent messages from the current numbers
					     let selectedNames = [];
					     let displayNames = '';
					     for (let v = 0; v < convData.length; v++) {
					          if (selectedNames.indexOf(convData[v]['author_displayname']) == -1) { 
					              selectedNames.push(convData[v]['author_displayname']);
					              displayNames += "<div id='diplNm_"+ phNumberFrom +"_"+ v +"' class='dispNameList' name='"+ convData[v]['author_displayname'] +"'>"+ convData[v]['author_displayname'] +"</div>";
					          }
					     }
					     displayNames += "<div id='diplNmAllMsgcv' class='dispNameListAll' title='Show all the messages exchanged between the current 2 phone numbers.'>All messages</div>";

					     // Store the display names for the current numbers, to be able to see them later
					     let ctPhNumber = phNumberFrom;
					     msgsNamesPerNmbr[ctPhNumber] = displayNames;

					     // Store the messages sent by each user, to be able to see them later when clicking on the user's name
					     for (let h = 0; h < selectedNames.length; h++) {

					          let rowMessageArrpn = [];

					          for (let b = 0; b < convData.length; b++) {

					               if (selectedNames[h] == convData[b]['author_displayname']) {

							   if (convData[b]['direction'] == 'sent_from') {
                                                               if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                               }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'sent_to') {
                                                               if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
                                                               } else {
                                                                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                               }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_from') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_on') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
					                   }
					               }
					          }
					          let crtNmber = phNumberFrom;
					          let crtName = selectedNames[h];
					          msgsNmbrsNames[crtNmber] = msgsNmbrsNames[crtNmber] || {};
		                                  msgsNmbrsNames[crtNmber][crtName] = rowMessageArrpn;
					     }

		                             // The number of messages to be loaded by default
		                             let nmbTblDefault = 50;

		                             // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                             if (convData.length > nmbTblDefault) {
		                                 $("#loadMoreMsgs").css("display", "block");
		                                 var nmbToBeLoaded = nmbTblDefault;
		                             } else { var nmbToBeLoaded = convData.length; }

					     let rowMessageArr = [];

					     for (var m = nmbToBeLoaded - 1; m >= 0; m--) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
                                                      if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     let convDataPerNmbr = rowMessageArr.join("");
		                             $("#grpdbynamelst").empty();
		                             $("#grpdbynamelst").append(displayNames);
		                             $("#msgListRowCell").empty();
		                             $("#msgListRowCell").append(convDataPerNmbr);

					     // Store the messages for the current From number, to be able to see them later
					     let rowMessageArrcpt = [];
					     for (let m = 0; m < convData.length; m++) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     messagesPerNmbr[phNumberFrom] = rowMessageArrcpt;

		                             // Scroll down to the bottom of the window
	                                     $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                             // Load more messages
		                             let clickNmb = 0;
		                             $("#loadMoreMsgs").click(function() {

		                                 clickNmb++;

		                                 var crefnb = (clickNmb + 1) * nmbToBeLoaded;

		                                 if (crefnb > convData.length) {
		                                     var nmbmsg = convData.length - 1;
		                                     $("#loadMoreMsgs").css("display", "none");
		                                 } else { 
		                                     var nmbmsg = crefnb - 1;
		                                 }

		                                 let rowMessageArrAdd = [];

		                                 for (let m = nmbmsg; m >= clickNmb * nmbToBeLoaded; m--) {

					              if (convData[m]['direction'] == 'sent_from') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }    
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'sent_to') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_from') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_on') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					              }
		                                 }

					         let convDataPerNmbrad = rowMessageArrAdd.join("");

		                                 let scrlheight = $("#msgListRowCell").height();
		                                 $("#msgListRowCell").prepend(convDataPerNmbrad);

		                                 $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);

		                             });


					     // Show the messages sent by each user whose name is clicked
					     $('[id*="diplNm_"]').click(function() {

					         let crntNmbr = $(this).attr("id").split("_")[1];
					         let crntDisName = $(this).attr("name");                               
		                                 $("#loadMoreMsgs").css("display", "none");

		                                 let convDataprn = [];
		                                 $.each(msgsNmbrsNames[crntNmbr][crntDisName], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgsusr").css("display", "block");
		                                     let nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgsusr").css("display", "none");
		                                     let nmbToBeLoaded = convDataprn.length;
		                                 }

					         let rowMessageArrprnst = [];

					         for (let n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         let convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                                 // Load more messages
		                                 let clckNb = 0;
		                                 $("#loadMoreMsgsusr").unbind("click");
		                                 $("#loadMoreMsgsusr").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgs").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgsusr").css("display", "none");
		                                     } else { 
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgsusr").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });


					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsgcv").css("color", "#04957b");
					         $(this).css("color", "#1b8efe");
					     });


					     // Show again all the messages exchanged between the current two phone numbers
					     $("#diplNmAllMsgcv").click(function() {

		                                 $("#loadMoreMsgsusr").css("display", "none");

		                                 let convDataprn = [];
		                                 $.each(messagesPerNmbr[phNumberFrom], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgs").css("display", "block");
		                                     let nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgs").css("display", "none");
		                                     let nmbToBeLoaded = convDataprn.length;
		                                 }

					         let rowMessageArrprnst = [];

					         for (let n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         let convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);


		                                 // Load more messages
		                                 let clckNb = 0;
		                                 $("#loadMoreMsgs").unbind("click");
		                                 $("#loadMoreMsgs").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgsusr").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgs").css("display", "none");
		                                     } else {
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgs").css("display", "block");
		                                     }

		                                     let rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             let convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     let scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });

					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsgcv").css("color", "#04957b");
					         $(this).css("color", "#04c6a4");

					     });


					     // Show the scroll-up arrow
					     $("#frmMsgLstWrap").scroll(function() {
						if ($(this).scrollTop() > 900) {
						      $('#upArrowSmall').fadeIn();
						} else {
						      $('#upArrowSmall').fadeOut();
						}
					     });

					     $("#upArrowSmall").unbind("click");
					     $("#upArrowSmall").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });

				  },
				  error: function() {
		                             showAlert("Error while attempting to get message data from the database!");
					     $('#listAllMsgsConv').removeClass('icon-loading');
				  }
			   });

                   }

                   getMsgsForNumbers(phNumberFrom, phNumberTo);

                   $("#refreshMsgsConv").click(function() { getMsgsForNumbers(phNumberFrom, phNumberTo); setTimeout(function() { $("#diplNmAllMsgcv").click(); }, 1000); });
                }

                $('[id^="showMsgConv-"]').click(function() {

                   let ctrwnmbr = $(this).attr("id").replace("showMsgConv-", "");
                   let phNumberFrom = $("#frmNmbr-"+ ctrwnmbr).text();
                   let phNumberTo = $("#toNmbr-"+ ctrwnmbr).text().split(": ")[1];

                   showRecMsgPerConv(phNumberFrom, phNumberTo);
                });


                // Show the pop-up window that lists all the messages sent/received to/from a phone number
                function showMsgPerNmbr(clckPhNumber) {

                   var allfrmtomsg = "<div id='listAllMsgsFromTo'>";
                   allfrmtomsg += "<div id='draglstMsgmWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
                   allfrmtomsg += "<a id='closeFrmMsgWindow' title='Close this window'></a>";
                   allfrmtomsg += "<div class='showByNmbrTitle'>Messages sent/received to/from  <span style='color:#04957b'>"+ clckPhNumber +"</span></div>";
                   allfrmtomsg += "<div id='frmMsgLstWrap'>";
                   allfrmtomsg += "<table id='frmMsgLstTbl'>";
                   allfrmtomsg += "<tr class='groupedrowsbody'><td><div id='grpdbynamelst' class='groupedLstNamespn'></div></td><td><div id='loadMoreMsgs' title='Click to load older messages.'>Load more messages</div><div id='loadMoreMsgsusr' title='Click to load older messages.'>Load more messages</div><div id='msgListRowCell' class='groupedLstMsgspn'></div><div id='refreshMsgsWraptf'><div id='refreshMsgsConvtf' title='Refresh list of messages'></div></div><div id='arrowupWrap'><div id='upArrowSmall' title='Scroll to the top'></div></div></td></tr>";
                   allfrmtomsg += "</table></div>";
                   allfrmtomsg += "<div id='sendMsgReply'><table id='sendMsgConv'><tr><td><div id='fromPhoneNmbrConv'>From: <select id='selectFromNbConv'></select></div><div id='toPhoneNmbrConv'>To: <span id='toNmbrConv' style='color:#04957b'>"+ clckPhNumber +"</span></div></td></tr>";
                   allfrmtomsg += "<tr><td><textarea id='sendMsgConvText' placeholder='Enter a message here, then press Send SMS.'></textarea></td></tr></table>";
                   allfrmtomsg += "<div id='sendMsgConvBtn'>Send SMS</div></div>";
                   allfrmtomsg += "<div id='expandWindowRplCtn' title='Expand to send a message'><img id='expandWindowRpl' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;cursor:grab'></div>";
                   allfrmtomsg += "</div>";

                   $("#content").append("<div id='recTblOverlay'></div>");
                   $("#content").append(allfrmtomsg);

                   var topDist = parseInt((window.innerHeight / 2).toFixed(2) - 340) +"px";
                   var leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 300) +"px";
                   $("#listAllMsgsFromTo").css({ "top" : topDist, "left" : leftDist });

                   $("#closeFrmMsgWindow").click(function() { $("#listAllMsgsFromTo").remove(); $("#recTblOverlay").remove(); });
                   $("#recTblOverlay").click(function() { $("#listAllMsgsFromTo").remove(); $("#recTblOverlay").remove(); });

	           // Expand the window when clicking on the arrow, to be able to send a reply message
                   $("#expandWindowRpl").unbind("click");
	           $("#expandWindowRpl").click(function() {

	              if ($(this).attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsFromTo").css("height", "618px");
                          } else {
                              $("#listAllMsgsFromTo").css("height", parseInt($(window).height() - 32) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 304) + "px");
                          }
	                  $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsFromTo").css("height", "490px");
                          } else {
                              $("#listAllMsgsFromTo").css("height", parseInt($(window).height() - 120) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 232) + "px");
                          }
                          $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
	              }
	           });


                   // Send a message from the 'conversation' window
                   $("#sendMsgConvBtn").click(function() {

                      $("#sendMsgConv,#sendMsgConvBtn").addClass('icon-loading');
                      var msgToSend = $("#sendMsgConvText").val();
                      var selectedid = $("#selectFromNbConv").val();
                      var toNumber = $("#toNmbrConv").text();
                      var receiversNumbers = [toNumber];

		      if (selectedid != '') { 

			  var sendersplit = selectedid.split(":");
			  var providercap = sendersplit[0];
			  var provsec = sendersplit[1];

			  if (/[a-zA-Z]/.test(provsec)) {
			      var alphanumcheck = true;
			  } else { var alphanumcheck = false; }

			  if (providercap == 'Tx' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == false) {
			      var selectedsender = selectedid.replace(/[^0-9]/g, "");
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  } else if (providercap == 'Tx' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  }

                          var uploadedtomms = [];

	                  if (msgToSend != '') {

				  $.ajax({
				     url: relbaseUrl,
				     type: "POST",
				     data: {
				           receiversPhoneNbs: receiversNumbers,
				           fromsender: selectedsender,
				           waitinterval: 1000,
				           sentsmstext: msgToSend,
				           ismms: 0,
				           mmsfiles: uploadedtomms
				         },
				     success: function(displayname) {

                                           var tzdate = new Date();
                                           var presDatest = new Date(tzdate.getTime() - (tzdate.getTimezoneOffset() * 60000)).toJSON();
                                           var presDatedb = presDatest.split(".")[0];
                                           var presDatesc = presDatedb.split("T");
                                           var presDate = presDatesc[0] +" "+ presDatesc[1];
                                           var sentMessageStatus = '';

                                           if (displayname) {
                                               var msgToSendproc = "<span class='msgAuthorNameGrp'>"+ displayname + ":</span>" + msgToSend; 
                                           } else { var msgToSendproc = msgToSend; }

                                           $("#msgListRowCell").append("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ selectedsender +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ receiversNumbers[0] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ msgToSendproc +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ presDate +"</div><div class='sentMssgStatus'>"+ sentMessageStatus +"</div></div>");

                                           // Scroll down to the bottom of the window
                                           $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

                                           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     },
				     error: function() {
                                           showAlert("Error while sending the message. You can check your Nextcloud log to find out more about this issue.");
				           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     }
				  });
			  } else {
                                  showAlert("Please enter a message in the text box!");
				  $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
			  }
		      } else {
                              showAlert("Please choose a Sender ID from the 'From' drop-down list!");
			      $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
		      }

                   });


	           // Make the window draggable
	           function makeMgrWndDraggable(e) {

			   window.pmdragging = {};
			   pmdragging.pageX0 = e.pageX;
			   pmdragging.pageY0 = e.pageY;
			   pmdragging.elem = $("#listAllMsgsFromTo");
			   pmdragging.offset0 = $("#listAllMsgsFromTo").offset();

			   function handle_dragging(e) {
			       var left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
			       var top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
			       $(pmdragging.elem).offset({top: top, left: left});
			   }

			   function handle_mouseup(e) {
			       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
			   }

			   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
	           }
	           $("#draglstMsgmWindow").mousedown(makeMgrWndDraggable);
	           $("#draglstMsgmWindowsc").mousedown(makeMgrWndDraggable);


                   // Append the available phone numbers to the From drop-down list
                   var availPhoneNmbrs = [];
                   $("#currentsmsnmbrs .optselectsmsnb").each(function() {
                      var crtphnmbr = $(this).attr("value");
                      if (crtphnmbr != "") { availPhoneNmbrs.push(crtphnmbr); }
                   });

                   if (availPhoneNmbrs.length > 0) {
                       var avphopt = "";
                       for (let d = 0; d < availPhoneNmbrs.length; d++) {
                            avphopt += "<option value='"+ availPhoneNmbrs[d] +"'>"+ availPhoneNmbrs[d] +"</option>";
                       }
                       $("#selectFromNbConv").append(avphopt);

                   } else { $("#selectFromNbConv").append("<option value='' selected>No IDs</option>"); }


                   // Get the sent/received messages for the current phone number, from the database
                   function getMsgsPerNmbr(clckPhNumber) {

			   var getGroupedPnUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedpernumber");

			   $('#listAllMsgsFromTo').addClass('icon-loading');
			   var totalPhNmbrs = 0;

			   $.ajax({
				  method: 'POST',
				  url: getGroupedPnUrl,
				  contentType: 'application/json',
		                  data: JSON.stringify({ "phoneNumber": clckPhNumber }),
				  success: function(groupedpernb) {

					     $('#listAllMsgsFromTo').removeClass('icon-loading');

					     var fromtoNmbrsData = [];

					     for (var i = 0; i < groupedpernb.length; i++) {

						     if (groupedpernb[i].author_displayname) {
							 var authordnm = groupedpernb[i].author_displayname;
						     } else { 
							 var authordnm = '';
						     }

						     var sentfromnmbrarr = groupedpernb[i].from.split(": ");
						     if (sentfromnmbrarr[1]) {
							 var groupednbfrom = sentfromnmbrarr[1];
						     } else {
							 var groupednbfrom = sentfromnmbrarr[0];
						     }

						     var modmessagerec = '';
						     if (groupedpernb[i].author_displayname) {
							 modmessagerec = "<span class='msgAuthorNameGrp'>"+ groupedpernb[i].author_displayname + ":</span>" + groupedpernb[i].message;
						     } else {
					                 modmessagerec = groupedpernb[i].message;
		                                     }

						     if (groupedpernb[i].to.indexOf(": ") > -1) {
						         var groupednmbrtopre = groupedpernb[i].to.split(": ");
						         var groupednmbrto = groupednmbrtopre[1];
						     } else { 
						         var groupednmbrto = groupedpernb[i].to;
						     }

						     fromtoNmbrsData.push({
						               'author_displayname': authordnm,
						               'from': groupednbfrom,
						               'to': groupednmbrto,
						               'message': modmessagerec,
						               'date': groupedpernb[i].date,
						               'status': groupedpernb[i].deliveryreceipt,
						               'table': groupedpernb[i].table
						     });
					     }


					     // Remove the duplicates
					     var noDupMsgData = [];
					     $.each(fromtoNmbrsData, function(i, e) {
						    var matchingData = $.grep(noDupMsgData, function(item) {
						            return item.from == e.from && item.to == e.to && item.message == e.message && item.table == 'received' && e.table == 'sent';
						    });
						    if (matchingData.length === 0) {
							noDupMsgData.push(e);
						    }
					     });

					     var messagesPerNmbr = {};
					     var msgsNamesPerNmbr = {};
					     var msgsNmbrsNames = {};

					     var displayNamesarr = [];
					     var convData = [];

					     for (var n = 0; n < noDupMsgData.length; n++) {

					          if (noDupMsgData[n]['from'] == clckPhNumber && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == clckPhNumber && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_to',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });


					          } else if (noDupMsgData[n]['from'] == clckPhNumber && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == clckPhNumber && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_on',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });
					          }
					     }

					     // Sort messages by date
					     convData.sort(function(a, b) {
                                                return new Date(b.date) - new Date(a.date);
					     });

					     // Collect the display names of the users that sent messages from the current number
					     var selectedNames = [];
					     var displayNames = '';
					     for (var v = 0; v < convData.length; v++) {
					          if (selectedNames.indexOf(convData[v]['author_displayname']) == -1) { 
					              selectedNames.push(convData[v]['author_displayname']);
					              displayNames += "<div id='diplNm_"+ clckPhNumber +"_"+ v +"' class='dispNameList' name='"+ convData[v]['author_displayname'] +"'>"+ convData[v]['author_displayname'] +"</div>";
					          }
					     }
					     displayNames += "<div id='diplNmAllMsg' class='dispNameListAll' title='Show all the messages for this number.'>"+ clckPhNumber +"</div>";

					     // Store the display names for the current number, to be able to see them later
					     var ctPhNumber = clckPhNumber;
					     msgsNamesPerNmbr[ctPhNumber] = displayNames;

					     // Store the messages sent by each user, to be able to see them later when clicking on the user's name
					     for (var h = 0; h < selectedNames.length; h++) {

					          var rowMessageArrpn = [];
					          for (var b = 0; b < convData.length; b++) {

					               if (selectedNames[h] == convData[b]['author_displayname']) {

							   if (convData[b]['direction'] == 'sent_from') {
							       if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							       }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'sent_to') {
							       if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							       }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_from') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_on') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
					                   }
					               }
					          }
					          var crtNmber = clckPhNumber;
					          var crtName = selectedNames[h];
					          msgsNmbrsNames[crtNmber] = msgsNmbrsNames[crtNmber] || {};
		                                  msgsNmbrsNames[crtNmber][crtName] = rowMessageArrpn;
					     }

		                             // The number of messages to be loaded by default
		                             var nmbTblDefault = 50;

		                             // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                             if (convData.length > nmbTblDefault) {
		                                 $("#loadMoreMsgs").css("display", "block");
		                                 var nmbToBeLoaded = nmbTblDefault;
		                             } else { var nmbToBeLoaded = convData.length; }

					     var rowMessageArr = [];
					     for (var m = nmbToBeLoaded - 1; m >= 0; m--) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     var convDataPerNmbr = rowMessageArr.join("");

		                             $("#grpdbynamelst").empty();
		                             $("#grpdbynamelst").append(displayNames);
		                             $("#msgListRowCell").empty();
		                             $("#msgListRowCell").append(convDataPerNmbr);

					     // Store the messages for the current number, to be able to see them later, when clicking on the number
					     var rowMessageArrcpt = [];
					     for (var m = 0; m < convData.length; m++) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     messagesPerNmbr[clckPhNumber] = rowMessageArrcpt;

		                             // Scroll down to the bottom of the window
	                                     $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                             // Load more messages
		                             var clickNmb = 0;
		                             $("#loadMoreMsgs").click(function() {

		                                 clickNmb++;

		                                 var crefnb = (clickNmb + 1) * nmbToBeLoaded;

		                                 if (crefnb > convData.length) {
		                                     var nmbmsg = convData.length - 1;
		                                     $("#loadMoreMsgs").css("display", "none");
		                                 } else { 
		                                     var nmbmsg = crefnb - 1;
		                                 }

		                                 var rowMessageArrAdd = [];

		                                 for (var m = nmbmsg; m >= clickNmb * nmbToBeLoaded; m--) {

					              if (convData[m]['direction'] == 'sent_from') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'sent_to') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_from') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_on') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					              }
		                                 }

					         var convDataPerNmbrad = rowMessageArrAdd.join("");

		                                 var scrlheight = $("#msgListRowCell").height();
		                                 $("#msgListRowCell").prepend(convDataPerNmbrad);

		                                 $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                             });


					     // Show the messages sent by each user whose name is clicked
					     $('[id*="diplNm_"]').click(function() {

					         var crntNmbr = $(this).attr("id").split("_")[1];
					         var crntDisName = $(this).attr("name");
		                                 $("#loadMoreMsgs").css("display", "none");

		                                 var convDataprn = [];
		                                 $.each(msgsNmbrsNames[crntNmbr][crntDisName], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgsusr").css("display", "block");
		                                     var nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgsusr").css("display", "none");
		                                     var nmbToBeLoaded = convDataprn.length;
		                                 }

					         var rowMessageArrprnst = [];

					         for (var n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         var convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                                 // Load more messages
		                                 var clckNb = 0;
		                                 $("#loadMoreMsgsusr").unbind("click");
		                                 $("#loadMoreMsgsusr").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgs").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgsusr").css("display", "none");
		                                     } else { 
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgsusr").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });

					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsg").css("color", "#04957b");
					         $(this).css("color", "#1b8efe");
					     });


					     // Show again all the messages sent/received to/from the clicked number
					     $("#diplNmAllMsg").click(function() {

		                                 $("#loadMoreMsgsusr").css("display", "none");

		                                 var convDataprn = [];
		                                 $.each(messagesPerNmbr[clckPhNumber], function(index, item) {
		                                        convDataprn.push(item);
		                                 });


		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgs").css("display", "block");
		                                     var nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgs").css("display", "none");
		                                     var nmbToBeLoaded = convDataprn.length;
		                                 }

					         var rowMessageArrprnst = [];

					         for (var n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         var convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);


		                                 // Load more messages
		                                 var clckNb = 0;
		                                 $("#loadMoreMsgs").unbind("click");
		                                 $("#loadMoreMsgs").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgsusr").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgs").css("display", "none");
		                                     } else { 
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgs").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });


					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsg").css("color", "#04957b");
					         $(this).css("color", "#04c6a4");

					     });


					     // Show the scroll-up arrow
					     $("#frmMsgLstWrap").scroll(function() {
						if ($(this).scrollTop() > 900) {
						      $('#upArrowSmall').fadeIn();
						} else {
						      $('#upArrowSmall').fadeOut();
						}
					     });

					     $("#upArrowSmall").unbind("click");
					     $("#upArrowSmall").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });

				  },
				  error: function() {
		                             showAlert("Error while attempting to get message data from the database!");
					     $('#listAllMsgsFromTo').removeClass('icon-loading');
				  }
			   });

                   }

                   getMsgsPerNmbr(clckPhNumber);

                   $("#refreshMsgsConvtf").click(function() { getMsgsPerNmbr(clckPhNumber); setTimeout(function() { $("#diplNmAllMsg").click(); }, 1000); });
                }

                $('[id^="showMsgFrom-"]').click(function() {

                   var ctrwnb = $(this).attr("id").replace("showMsgFrom-", "");
                   var clckPhNumber = $("#frmNmbr-"+ ctrwnb).text();

                   showMsgPerNmbr(clckPhNumber);
                })

                $('[id^="showMsgTo-"]').click(function() {
                   var ctrwnbTo = $(this).attr("id").replace("showMsgTo-", "");
                   if ($("#toNmbr-"+ ctrwnbTo).text().indexOf(":") > -1) {
                       var clckPhNbTo = $("#toNmbr-"+ ctrwnbTo).text().split(": ")[1];
                   } else { var clckPhNbTo = $("#toNmbr-"+ ctrwnbTo).text(); };

                   showMsgPerNmbr(clckPhNbTo);
                })

                // Show the pop-up window for adding a Display Name to the 'From' numbers of unknown senders
                $('[id^="addDispName-"]').click(function() {

                   var crrownb = $(this).attr("id").replace("addDispName-", "");
                   var slctPhoneNb = $("#frmNmbr-"+ crrownb).text();

                   var addDNameWindow = "<div id='disNameWindow'>";
                   addDNameWindow += "<div id='dragDispNmWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg'></div>";
                   addDNameWindow += "<a id='closeDisNmWindow' title='Close this window'></a>";
                   addDNameWindow += "<div style='display:block;text-align:left;margin:14px 22px 0px 22px;color:#353535;font-family:Inter;font-size:15px;font-weight:400;'>If this is an external phone number (the number of a person that doesn't have a Nextcloud account), you can save a Display Name for this number, so that all the messages coming from it will be preceded by the specified Display Name:</div>";
                   addDNameWindow += "<div style='display:block;text-align:center;color:#49B382;font-family:Inter;font-size:15px;font-weight:600;margin:6px 0px 10px 0px;'>"+ slctPhoneNb +"</div>";
                   addDNameWindow += "<input type='text' id='saveDispNmText' placeholder='Eg: John Smith' style='display:block;width:80%;height:30px;margin:10px auto;padding:0px 12px;border-radius: 20px;'>";
                   addDNameWindow += "<input type='submit' id='saveDispName' value='Save'>";
                   addDNameWindow += "</div>";

                   $("#content").append("<div id='recTblOverlay'></div>");
                   $("#content").append(addDNameWindow);

                   var topNmDist = parseInt((window.innerHeight / 2).toFixed(2) - 180) +"px";
                   var leftNmDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
                   $("#disNameWindow").css({ "top" : topNmDist, "left" : leftNmDist });

                   $("#closeDisNmWindow").click(function() { $("#disNameWindow").remove(); $("#recTblOverlay").remove(); });
                   $("#recTblOverlay").click(function() { $("#disNameWindow").remove(); $("#recTblOverlay").remove(); });


	           // Make the window draggable
	           function makeMgrWndDraggable(e) {

			   window.pmdragging = {};
			   pmdragging.pageX0 = e.pageX;
			   pmdragging.pageY0 = e.pageY;
			   pmdragging.elem = $("#disNameWindow");
			   pmdragging.offset0 = $("#disNameWindow").offset();

			   function handle_dragging(e) {
			       var left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
			       var top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
			       $(pmdragging.elem).offset({top: top, left: left});
			   }

			   function handle_mouseup(e) {
			       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
			   }

			   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
	           }
	           $("#dragDispNmWindow").mousedown(makeMgrWndDraggable);

                   // Save the Display Name
                   $("#saveDispName").click(function() {

                      var dispNmText = $("#saveDispNmText").val();

                      if (/^[a-zA-Z0-9\s\-\/\.\)\(\']+$/.test(dispNmText) && dispNmText.length < 256) {

                             var saveDispNameUrl = OC.generateUrl("/apps/sms_relentless/user/savedisplayname");

			     $.ajax({
				  url: saveDispNameUrl,
				  method: 'POST',
				  dataType:'text',
                                  data: { 
                                          authorDisplayname: dispNmText,
                                          from: slctPhoneNb
                                         },
				  success: function(respupdname) {
                                               showAlert(respupdname);
                                               $("#disNameWindow").remove();
                                               $("#recTblOverlay").remove();
                                  },
				  error: function() {
                                               showAlert("Error while attempting to save the new Display Name to the database.");
                                               $("#disNameWindow").remove();
                                               $("#recTblOverlay").remove();
                                  }
			     });

                      } else {
                              showAlert("The Display Name should contain only letters, numbers, spaces, hyphens (-), slashes (/), periods (.), round brackets (()) and single quotation marks ('), it should not be empty and should have less than 256 characters.");
                      }
                   });

                });


                // Add pagination
                var rowsShown = messagesperpage;
                var rowsTotal = $("#recSmsTable tr").length;

                var numPages = (rowsTotal - 2) / rowsShown;

                for (i = 0; i < numPages; i++) {
                     var pageNum = i + 1;
                     $('#paginationrec').append('<a href="#" rel="' + i + '" class="pagenumbersrec">' + pageNum + '</a> ');
                }

                $('#paginationrec').children(":first").addClass('active');

                $('#paginationrec a:first').addClass('active');

                // Show table page when clicking a page number
                $('.recpages a').bind('click', function() {

                   $('#paginationrec').children().removeClass('active');

                   $(this).addClass('active');

                   var currentPageNo = $(this).text();

                   $('#paginationrec a').each(function() {
                       if ($(this).text() == currentPageNo) {
                           $(this).addClass('active');
                       }
                   });

                   // Sort table rows
		   var rows = $('#recSmsTable tr').get();

		   rows.sort(function(a, b) {

		        var A = parseInt($('td.dbidcolumnrec', a).text());
		        var B = parseInt($('td.dbidcolumnrec', b).text());

		        if (A < B) {
		            return -1;
		        }

		        if (A > B) {
		            return 1;
		        }

		        return 0;
		   });

		   $.each(rows, function(index, row) {
		      $('#recSmsTable').append(row);
		   });

                   var currPage = $(this).attr('rel');
                   var startItem = currPage * rowsShown;
                   var endItem = startItem + rowsShown;

                   $(".receivedrowsbody").hide().slice(startItem, endItem).css('display', 'table-row');

                   $('#totalrecmessages').remove();
                   $('#smstables').append("<div id='totalrecmessages'>Total displayed messages: " + parseddata.length + "</div>");
                });

                $('#paginationrec').children(":last").trigger('click');

                // Select all records
                $('#selectAllChckbx').change(function() {
                  if ($(this).is(':checked')) {
                       $(".indivchckbx").prop("checked", true);
                  } else {
                       $(".indivchckbx").prop("checked", false);
                  }
                });

                function reorderRecRows() {
                   var currenttext = $(".filterbuttonsrec").closest('[class="filterbuttonsrec"]').find('[class="indivfilterrec"]').text();
                   if (currenttext == '') {
                       $('tr').sort(function (a, b) {
                          return parseInt($('td.dbidcolumnrec', b).text()) < parseInt($('td.dbidcolumnrec', a).text());
                       }).appendTo("#recSmsTable");
                   }
                }

                // Filter rows
                $("#databaseidfilter").on("click", function(event) {

                      var databaseId = $("#dbidtextrec").val();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty1 = 0;
                          $(".indivfilterrec").not("#dbidtextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty1 = 1;
                              }
                          });

                          if (checkrecEmpty1 == 0) {
                              $(this).show();
                          }

                          if (databaseId != '') {
                             if ($(this).find('[class="dbidcolumnrec"]').text() == databaseId) {
                                $("#recSmsTable").append(this);
                                if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                $(this).hide();
                             }
                          } else {
                                $(this).show();
                                msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });


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

                      var useridtxt = $("#useridtextrec").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty2 = 0;
                          $(".indivfilterrec").not("#useridtextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty2 = 1;
                              }
                          });

                          if (checkrecEmpty2 == 0) {
                              $(this).show();
                          }

                          if (useridtxt != '') {
                             var useridfound = $(this).find('[class="useridcolrec"]').text().toLowerCase();
                             if(useridfound.indexOf(useridtxt) != -1) {
                                $("#recSmsTable").append(this);
                                if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                $(this).hide();
                             }
                          } else {
                                $(this).show();
                                msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var messageidtxt = $("#messageidtextrec").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty3 = 0;
                          $(".indivfilterrec").not("#messageidtextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty3 = 1;
                              }
                          });

                          if (checkrecEmpty3 == 0) {
                              $(this).show();
                          }

                          if (messageidtxt != '') {
                             var foundtdmssgid = $(this).find('[class="messageidcolrec"]').text().toLowerCase();
                             if (foundtdmssgid.indexOf(messageidtxt) != -1) {
                                $("#recSmsTable").append(this);
                                if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                $(this).hide();
                             }
                          } else {
                                $(this).show();
                                msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var datetxtvr = $("#datetextrec").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty4 = 0;
                          $(".indivfilterrec").not("#datetextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty4 = 1;
                              }
                          });

                          if (checkrecEmpty4 == 0) {
                              $(this).show();
                          }

                          if (datetxtvr != '') {
                              var founddate = $(this).find('[class="datecolrec"]').text().toLowerCase();
                              if (founddate.indexOf(datetxtvr) != -1) {
                                  $("#recSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var fromtxtvr = $("#fromtextrec").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty5 = 0;
                          $(".indivfilterrec").not("#fromtextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty5 = 1;
                              }
                          });

                          if (checkrecEmpty5 == 0) {
                              $(this).show();
                          }

                          if (fromtxtvr != '') {
                             var foundfrom = $(this).find('[class="fromcolumnrec"]').text().toLowerCase();
                             if (foundfrom.indexOf(fromtxtvr) != -1) {
                                 $("#recSmsTable").append(this);
                                 if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                 $(this).hide();
                             }
                          } else {
                                 $(this).show();
                                 msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var totxtvr = $("#totextrec").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty6 = 0;
                          $(".indivfilterrec").not("#totextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty6 = 1;
                              }
                          });

                          if (checkrecEmpty6 == 0) {
                              $(this).show();
                          }

                          if (totxtvr != '') {
                             var foundto = $(this).find('[class="tocolrec"]').text().toLowerCase();
                             if (foundto.indexOf(totxtvr) != -1) {
                                 $("#recSmsTable").append(this);
                                 if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                 $(this).hide();
                             }
                          } else {
                                 $(this).show();
                                 msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var messagetxtvr = $("#messagetextrec").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".receivedrowsbody").each(function() {

                          var checkrecEmpty7 = 0;
                          $(".indivfilterrec").not("#messagetextrec").each(function() {
                              if ($(this).val() != '') {
                                  checkrecEmpty7 = 1;
                              }
                          });

                          if (checkrecEmpty7 == 0) {
                              $(this).show();
                          }

                          if (messagetxtvr != '') {
                             var foundmessage = $(this).find('[class="messagecolumnrec"]').text().toLowerCase();
                             if (foundmessage.indexOf(messagetxtvr) != -1) {
                                $("#recSmsTable").append(this);
                                if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                $(this).hide();
                             }
                          } else {
                                $(this).show();
                                msgrowsNo++;
                          }
                      });

                      reorderRecRows();
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total filtered messages: " + msgrowsNo + "</div>");
               });

               // Clear all filters
               $("#clearrecfilters").on("click", function(event) {
                      $(".receivedrowsbody").each(function() {
                          $(this).show();
                      });
                      $(".indivfilterrec").val("");
                      $('#totalrecmessages').remove();
                      $('#smstables').append("<div id='totalrecmessages'>Total displayed messages: " + parseddata.length + "</div>");
               });

               // Delete selected rows from the database
               $("#deleterecrows").on("click", function() {
                  var checkcheckbx = $("#recSmsTable input[type=checkbox]:checked").length;
                  if (checkcheckbx == 0) {
                      showAlert("Please select the row(s) to permanently delete from the database !");
                  } else {
                          var checkboxIds = [];
                          $(".receivedrowsbody").each(function() {
                             var rowcheckbx = $(this).find('input[type="checkbox"]');
                             if (rowcheckbx.is(":checked")) {
                                 var dbrowid = $(this).find('[class="dbidcolumnrec"]').text() + "|" + $(this).find('[class="messageidcolrec"]').text();
                                 checkboxIds.push(dbrowid);
                             }
                          });

		          confirmAlert("Please note that the row(s) you selected will be permanently deleted from the database, without being saved before removal. This action cannot be undone ! If you really want to permanently delete the selected row(s) press 'OK'.");

		          $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

		          $("#confirmOk").click(function() {

		              $("#alertMsgOverlay").remove();
		              $("#alertConfMessage").remove();

                              var deleterecRowsUrl = OC.generateUrl("/apps/sms_relentless/user/removerecrows");
                              $('#smstables').addClass('icon-loading');

                              $.ajax({
                                   url: deleterecRowsUrl,
                                   type: "POST",
                                   data: { "recmessagedbIDs": checkboxIds },
                                   success: function(delmsgrec) {
		                              $('#smstables').removeClass('icon-loading');
                                              if (delmsgrec == "success") {
                                                  showAlert("The row(s) have been deleted successfully !");
                                                  $('#receivedsmstableshow').click();
                                              } else if (delmsgrec == "not allowed") {
                                                  showAlert("At least one message couldn't be deleted because of permission issues. Non-admin users can delete the messages sent/received from/on the numbers shared with them only if they are allowed by an admin.");
                                              } else {
                                                  showAlert("There was an error while deleting the selected row(s) !");
                                              }
                                   },
                                   error: function() {
                                              $('#smstables').removeClass('icon-loading');
                                              showAlert("There was an error while attempting to delete the selected row(s) !");
                                   }
                              });
                          });

                  }
               });


               // Show/Hide filter row
	       $('#recarrow').on('click', function() {
	          if ($('#recfiltersrow').is(':visible')) {
		      $('#recfiltersrow').hide();
                      $('#recheaderrow').css('top', '0px');
                      $(this).removeClass('arrowUpCl');
                      $(this).addClass('arrowDownCl');
		  } else {
		      $('#recfiltersrow').show();
                      $('#recheaderrow').css('top', '158px');
                      $(this).removeClass('arrowDownCl');
                      $(this).addClass('arrowUpCl');
                  }
               });

               $("#app-content").animate({scrollTop:$("#recSmsTable").prop("scrollHeight")},200);
          },
          error: function() {
                      showAlert("Error. You can check the Nextcloud log to find more details about this issue.");
                      $('#smstables').removeClass('icon-loading');
          }
     });

     // Look for the 'new received message' indicator in the database, to know if the received messages list needs to be refreshed
     intervalNmfr = setInterval(function() { checkIfNewMessage(); }, newMsgInterval);

     $("#stopAutoRefreshSent").css("display", "none");

  });

  $("#receivedsmstableshow").click();

  // List sent messages
  $("#sentsmstableshow").on("click", function(event) {

     $('#smstables').empty();
     clearInterval(intervalNmfr);

     var getSentUrl = OC.generateUrl("/apps/sms_relentless/user/getsenttable");
     $('#smstables').addClass('icon-loading');

     $.ajax({
          url: getSentUrl,
          method: "GET",
          contentType: 'application/json',
          success: function(sentdatafdb) {

                var sentparseddata = sentdatafdb.datarows;

                $('#smstables').append("<div id='toptablesent'><div class='topbuttonandpage'><span id='sentarrow' title='Show/Hide filters and Delete button'></span></div><div id='paginationsent' class='pages'>Pages </div></div>");
                $('#smstables').append("<table id='sentSmsTable'></table>");
                $('#sentSmsTable').append("<tr id='sentfiltersrow'><td class='selectalldvfilter'><button id='clearsentfilters' title='Clear all filters.'></button><button id='deletesentrows' title='Permanently delete the selected row(s) from below from the database.'></button></td><td class='selectalldvfilter'><input type='text' id='dbidtextsent' class='indivfiltersent' title='Enter a database ID number to apply the filter.'><input type='submit' id='databaseidfilter' class='filterbuttonsent' value='' title='Filter rows by the specified database ID.' /></td><td class='selectalldvfilter'><input type='text' id='useridtext' class='indivfiltersent' title='Enter a Nextcloud username to apply the filter.' /><input type='submit' id='useridfilter' class='filterbuttonsent' value='' title='Filter rows by the specified username.' /></td><td class='selectalldvfilter'><input type='text' id='messageidtext' class='indivfiltersent' title='Enter a fragment from a message ID to apply the filter.'  /><input type='submit' id='messageidfilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='datetext' class='indivfiltersent' title='Enter a fragment of a date to apply the filter.'/><input type='submit' id='datefilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='fromtext' class='indivfiltersent' title='Enter a fragment of a sender&#146s phone number or alphanumeric Sender ID, to apply the filter.' /><input type='submit' id='fromfilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='totext' class='indivfiltersent' value='' title='Enter a fragment of a recipient&#146s phone number to apply the filter.'  /><input type='submit' id='tofilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.' /></td><td class='selectalldvfilter'><input type='text' id='networktext' class='indivfiltersent' title='Enter a fragment of a network number to apply the filter.' /><input type='submit' id='networkfilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.'/></td><td class='selectalldvfilter'><input type='text' id='pricetext' class='indivfiltersent' title='Enter a fragment of a price string to apply the filter.' /><input type='submit' id='pricefilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.'/></td><td class='selectalldvfilter'><input type='text' id='statustext' class='indivfiltersent' title='Enter a fragment of a status to apply the filter.' /><input type='submit' id='statusfilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.'/></td><td class='selectalldvfilter'><input type='text' id='deliveryrcpttext' class='indivfiltersent' title='Enter a fragment of a delivery receit to apply the filter.' /><input type='submit' id='deliveryrecfilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.'/></td><td class='selectalldvfilter'><input type='text' id='messagetext' class='indivfiltersent' title='Enter a fragment of a message to apply the filter.' /><input type='submit' id='messagefilter' class='filterbuttonsent' value='' title='Filter rows by the specified string.'/></td></tr>");
                $('#sentSmsTable').append("<tr class='sentrows' id='sentheaderrow'><th id='selectalldv' class='selectsmsdv'><input type='checkbox' id='selectAllChckbx' class ='indivchckbx' title='Select all rows from all pages.' /></th><th title='The database ID of each message.'>ID</th><th>User ID</th><th>Message ID</th><th>Date</th><th>From</th><th>To</th><th>Network</th><th title=\"The currency is the currency configured in the client account, on the SMS provider's website.\">Price</th><th id='sentstatuscolumn' title=\"This column generally shows the status received from the recipient's carrier, or any errors generated when attempting to send the message.\">Status</th><th title='Not all delivery receipts guarantee that the target received the message. Some delivery receipts represent successful completion of just one step in the delivery process, such as transmitting the message to another telephony operator.'>Delivery<br>Receit</th><th>Sent Message</th></tr>");

                $('#sentfiltersrow').hide();

                if (sentdatafdb.showdispnm == 1) {

                    for (var i = 0; i < sentparseddata.length; i++) {

                         if (sentparseddata[i].author_displayname) {
                             var procmessage = "<span class='messageAuthorName'>"+ sentparseddata[i].author_displayname + ":</span>" + sentparseddata[i].message +"<div id='showMsgConv-"+ i +"' class='lstMsgConv'><img class='lstMsgConvImg' src='/" + ctappdir + "/sms_relentless/img/reply.svg' title='Show all the messages exchanged between the current 2 phone numbers.'></div>";
                         } else {
                             var procmessage = sentparseddata[i].message +"<div id='showMsgConv-"+ i +"' class='lstMsgConv'><img class='lstMsgConvImg' src='/" + ctappdir + "/sms_relentless/img/reply.svg' title='Show all the messages exchanged between the current 2 phone numbers.'></div>";
                         }

                         var procsentFrom = "<div id='frmNmbr-"+ i +"'>"+ sentparseddata[i].from +"<div id='showMsgFrom-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src='/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";

                         var procsentTo = "<div id='toNmbr-"+ i +"'>"+ sentparseddata[i].to +"<div id='showMsgTo-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src='/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";

                         var sentMsgPrice = (sentparseddata[i].price != 0 && sentparseddata[i].price != null)? sentparseddata[i].price : "";
                         var sentDlvrRcpt = (sentparseddata[i].deliveryreceipt != null)? sentparseddata[i].deliveryreceipt : "";

                         $('#sentSmsTable').append("<tr id='singlerow_"+ i +"' class='sentrowsbody'><td class='selectsmsdv'><input type='checkbox' id='selectspec_"+ i +"' class='indivchckbx' /></td><td class='sentdbidcolumn'>"+ sentparseddata[i].id +"</td><td class='useridcolsent'>"+ sentparseddata[i].user_id +"</td><td class='messageidcolsent'>"+ sentparseddata[i].message_id +"</td><td class='datecolsent'>"+ sentparseddata[i].date +"</td><td class='fromcolumnsent'>"+ procsentFrom +"</td><td class='tocolumnsent'>"+ procsentTo +"</td><td class='networkcolumnsent'><div class='networkNmContent'>"+ sentparseddata[i].network +"</div><div id='phNetwork-"+ i +"' class='phNetworkImg' title='Click to see the name of the receiver`s carrier'><img src='/" + ctappdir + "/sms_relentless/img/network.svg' class='recNetworkImg'></div></td><td class='pricecolumnsent'>"+ sentMsgPrice +"</td><td class='statuscolumnsent'>"+ sentparseddata[i].status +"</td><td class='deliveryrcptcolsent'>"+ sentDlvrRcpt +"</td><td class='messagecolumnsent'>"+ procmessage +"</td></tr>");
                    }

                } else {

                    for (var i = 0; i < sentparseddata.length; i++) {

                         var procmessage = sentparseddata[i].message +"<div id='showMsgConv-"+ i +"' class='lstMsgConv'><img class='lstMsgConvImg' src='/" + ctappdir + "/sms_relentless/img/reply.svg' title='Show all the messages exchanged between the current 2 phone numbers.'></div>";

                         var procsentFrom = "<div id='frmNmbr-"+ i +"'>"+ sentparseddata[i].from +"<div id='showMsgFrom-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src='/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";

                         var procsentTo = "<div id='toNmbr-"+ i +"'>"+ sentparseddata[i].to +"<div id='showMsgTo-"+ i +"' class='listToFromMsgs'><img class='lstMsgToFromImg' src='/" + ctappdir + "/sms_relentless/img/list.svg' title='Show all the messages sent/received to/from this phone number, that I am allowed to see.'></div></div>";

                         var sentMsgPricesc = (sentparseddata[i].price != 0 && sentparseddata[i].price != null)? sentparseddata[i].price : "";
                         var sentDlvrRcptsc = (sentparseddata[i].deliveryreceipt != null)? sentparseddata[i].deliveryreceipt : "";

                         $('#sentSmsTable').append("<tr id='singlerow_"+ i +"' class='sentrowsbody'><td class='selectsmsdv'><input type='checkbox' id='selectspec_"+ i +"' class='indivchckbx' /></td><td class='sentdbidcolumn'>"+ sentparseddata[i].id +"</td><td class='useridcolsent'>"+ sentparseddata[i].user_id +"</td><td class='messageidcolsent'>"+ sentparseddata[i].message_id +"</td><td class='datecolsent'>"+ sentparseddata[i].date +"</td><td class='fromcolumnsent'>"+ procsentFrom +"</td><td class='tocolumnsent'>"+ procsentTo +"</td><td class='networkcolumnsent'><div class='networkNmContent'>"+ sentparseddata[i].network +"</div><div id='phNetwork-"+ i +"' class='phNetworkImg' title='Click to see the name of the receiver`s carrier'><img src='/" + ctappdir + "/sms_relentless/img/network.svg' class='recNetworkImg'></div></td><td class='pricecolumnsent'>"+ sentMsgPricesc +"</td><td class='statuscolumnsent'>"+ sentparseddata[i].status +"</td><td class='deliveryrcptcolsent'>"+ sentDlvrRcptsc +"</td><td class='messagecolumnsent'>"+ procmessage +"</td></tr>");
                    }
                }

                $('#smstables').append("<div id='totalsentmessages'><span>Total displayed messages: " + sentparseddata.length + "</span></div>");

                $('#smstables').removeClass('icon-loading');

                $('#sentarrow').removeClass('arrowUpCl');
                $('#sentarrow').addClass('arrowDownCl');

                // Show the name of the carrier's network
                $('[id^="phNetwork-"]').click(function() {
                   var ntwrkText = $(this).closest(".networkcolumnsent").find('[class="networkNmContent"]').text();
                   if (ntwrkText) {
                       if (/^[0-9\s]*$/.test(ntwrkText)) {
                           if (ntwrkText.trim() != "") {
                               showAlert("The code of the receiver's carrier is:<span style='display:block;text-align:center;font-weight:700;'>"+ ntwrkText +"</span>You can look up the name of the carrier on <a href='https://en.wikipedia.org/wiki/Mobile_country_code#National_operators' style='color:#1b60ba' target='_blank' rel='noreferrer noopener'>this Wikipedia page</a>, taking into account that the first 3 digits specify the mobile country code, while the last 2 or 3 digits specify the mobile network code.");
                           } else { showAlert("The name of the receiver's carrier is not known."); }
                       } else {
                           if (ntwrkText.toLowerCase() != "null") {
                               showAlert("The name of the receiver's carrier is:<br>"+ ntwrkText);
                           } else { showAlert("The name of the receiver's carrier is not known."); }
                       }
                   } else { 
                       showAlert("The name of the receiver's carrier is not known."); 
                   }
                });

                // Show the pop-up window that lists all the messages exchanged between the current 2 phone numbers
                function showSentMsgPerConv(phNumberFrom, phNumberTo) {

                   let allfrmtomsg = "<div id='listAllMsgsConv'>";
                   allfrmtomsg += "<div id='draglstMsgmWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
                   allfrmtomsg += "<a id='closeFrmMsgWindow' title='Close this window'></a>";
                   allfrmtomsg += "<div class='showByNmbrTitle'>Messages exchanged between <span style='color:#04957b'>"+ phNumberFrom +"</span> and <span style='color:#04957b'>"+ phNumberTo +"</span></div>";
                   allfrmtomsg += "<div id='frmMsgLstWrap'>";
                   allfrmtomsg += "<table id='frmMsgLstTbl'>";
                   allfrmtomsg += "<tr class='groupedrowsbody'><td><div id='grpdbynamelst' class='groupedLstNamespn'></div></td><td><div id='loadMoreMsgs' title='Click to load older messages.'>Load more messages</div><div id='loadMoreMsgsusr' title='Click to load older messages.'>Load more messages</div><div id='msgListRowCell' class='groupedLstMsgspn'></div><div id='refreshMsgsWrap'><div id='refreshMsgsConv' title='Refresh list of messages'></div></div><div id='arrowupWrap'><div id='upArrowSmall' title='Scroll to the top'></div></div></td></tr>";
                   allfrmtomsg += "</table></div>";
                   allfrmtomsg += "<div id='sendMsgReply'><table id='sendMsgConv'><tr><td><div id='fromPhoneNmbrConv'>From: <select id='selectFromNbConv'></select></div><div id='toPhoneNmbrConv'>To: <span id='toNmbrConv' style='color:#04957b'>"+ phNumberTo +"</span></div></td></tr>";
                   allfrmtomsg += "<tr><td><textarea id='sendMsgConvText' placeholder='Enter a message here, then press Send SMS.'></textarea></td></tr></table>";
                   allfrmtomsg += "<div id='sendMsgConvBtn'>Send SMS</div></div>";
                   allfrmtomsg += "<div id='expandWindowRplCtn' title='Expand to send a reply'><img id='expandWindowRpl' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;cursor:grab;'></div>";
                   allfrmtomsg += "</div>";

                   $("#content").append("<div id='recTblOverlay'></div>");
                   $("#content").append(allfrmtomsg);

                   let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 340) +"px";
                   let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 300) +"px";
                   $("#listAllMsgsConv").css({ "top" : topDist, "left" : leftDist });

                   $("#closeFrmMsgWindow").click(function() { $("#listAllMsgsConv").remove(); $("#recTblOverlay").remove(); });
                   $("#recTblOverlay").click(function() { $("#listAllMsgsConv").remove(); $("#recTblOverlay").remove(); });

	           // Expand the window when clicking on the arrow, to be able to send a reply message
                   $("#expandWindowRpl").unbind("click");
	           $("#expandWindowRpl").click(function() {

	              if ($(this).attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsConv").css("height", "618px");
                          } else {
                              $("#listAllMsgsConv").css("height", parseInt($(window).height() - 32) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 304) + "px");
                          }
	                  $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsConv").css("height", "490px");
                          } else {
                              $("#listAllMsgsConv").css("height", parseInt($(window).height() - 120) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 232) + "px");
                          }
                          $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
	              }
	           });


                   // Send a message from the 'conversation' window
                   $("#sendMsgConvBtn").click(function() {

                      $("#sendMsgConv,#sendMsgConvBtn").addClass('icon-loading');
                      var msgToSend = $("#sendMsgConvText").val();
                      var selectedid = $("#selectFromNbConv").val();
                      var toNumber = $("#toNmbrConv").text();
                      var receiversNumbers = [toNumber];

		      if (selectedid != '') { 

			  var sendersplit = selectedid.split(":");
			  var providercap = sendersplit[0];
			  var provsec = sendersplit[1];

			  if (/[a-zA-Z]/.test(provsec)) {
			      var alphanumcheck = true;
			  } else { var alphanumcheck = false; }

			  if (providercap == 'Tx' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == false) {
			      var selectedsender = selectedid.replace(/[^0-9]/g, "");
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  } else if (providercap == 'Tx' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  }

                          var uploadedtomms = [];

	                  if (msgToSend != '') {

				  $.ajax({
				     url: relbaseUrl,
				     type: "POST",
				     data: {
				           receiversPhoneNbs: receiversNumbers,
				           fromsender: selectedsender,
				           waitinterval: 1000,
				           sentsmstext: msgToSend,
				           ismms: 0,
				           mmsfiles: uploadedtomms
				         },
				     success: function(displayname) {

                                           var tzdate = new Date();
                                           var presDatest = new Date(tzdate.getTime() - (tzdate.getTimezoneOffset() * 60000)).toJSON();
                                           var presDatedb = presDatest.split(".")[0];
                                           var presDatesc = presDatedb.split("T");
                                           var presDate = presDatesc[0] +" "+ presDatesc[1];
                                           var sentMessageStatus = '';

                                           if (displayname) {
                                               var msgToSendproc = "<span class='msgAuthorNameGrp'>"+ displayname + ":</span>" + msgToSend; 
                                           } else { var msgToSendproc = msgToSend; }

                                           $("#msgListRowCell").append("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ selectedsender +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ receiversNumbers[0] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ msgToSendproc +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ presDate +"</div><div class='sentMssgStatus'>"+ sentMessageStatus +"</div></div>");

                                           // Scroll down to the bottom of the window
                                           $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

                                           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     },
				     error: function() {
				           showAlert("Error while sending the message. You can check your Nextcloud log to find out more about this issue.");
				           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     }
				  });
			  } else {
				  showAlert("Please enter a message in the text box!");
				  $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
			  }
		      } else {
			      showAlert("Please choose a Sender ID from the 'From' drop-down list!");
			      $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
		      }
                   });


	           // Make the window draggable
	           function makeMgrWndDraggable(e) {

			   window.pmdragging = {};
			   pmdragging.pageX0 = e.pageX;
			   pmdragging.pageY0 = e.pageY;
			   pmdragging.elem = $("#listAllMsgsConv");
			   pmdragging.offset0 = $("#listAllMsgsConv").offset();

			   function handle_dragging(e) {
			       let left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
			       let top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
			       $(pmdragging.elem).offset({top: top, left: left});
			   }

			   function handle_mouseup(e) {
			       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
			   }

			   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
	           }
	           $("#draglstMsgmWindow").mousedown(makeMgrWndDraggable);
	           $("#draglstMsgmWindowsc").mousedown(makeMgrWndDraggable);


                   // Append the available phone numbers to the From drop-down list
                   var availPhoneNmbrs = [];
                   $("#currentsmsnmbrs .optselectsmsnb").each(function() {
                      var crtphnmbr = $(this).attr("value");
                      if (crtphnmbr != "") { availPhoneNmbrs.push(crtphnmbr); }
                   });

                   if (availPhoneNmbrs.length > 0) {
                       var avphopt = "";
                       for (let d = 0; d < availPhoneNmbrs.length; d++) {
                            if (availPhoneNmbrs[d].indexOf(phNumberFrom) === -1) {
                                avphopt += "<option value='"+ availPhoneNmbrs[d] +"'>"+ availPhoneNmbrs[d] +"</option>";
                            } else {
                                avphopt += "<option value='"+ availPhoneNmbrs[d] +"' selected>"+ availPhoneNmbrs[d] +"</option>";
                            }
                       }
                       $("#selectFromNbConv").append(avphopt);

                   } else { $("#selectFromNbConv").append("<option value='' selected>No IDs</option>"); }


                   // Get the messages exchanged between the current 2 phone numbers, from the database
                   function getMsgsForNumbersSec(phNumberFrom, phNumberTo) {

			   let getGrpConvUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedforreply");

			   $('#listAllMsgsConv').addClass('icon-loading');
			   let totalPhNmbrs = 0;

			   $.ajax({
				  method: 'POST',
				  url: getGrpConvUrl,
				  contentType: 'application/json',
		                  data: JSON.stringify({ "phoneNmbrFrom": phNumberFrom, "phoneNmbrTo": phNumberTo }),
				  success: function(groupedperconv) {

					     $('#listAllMsgsConv').removeClass('icon-loading');

					     let fromtoNmbrsData = [];

					     for (let i = 0; i < groupedperconv.length; i++) {

						     if (groupedperconv[i].author_displayname) {
							 var authordnm = groupedperconv[i].author_displayname;
						     } else { 
							 var authordnm = '';
						     }

						     var sentfromnmbrarr = groupedperconv[i].from.split(": ");
						     if (sentfromnmbrarr[1]) {
							 var groupednbfrom = sentfromnmbrarr[1];
						     } else {
							 var groupednbfrom = sentfromnmbrarr[0];
						     }

						     var modmessagerec = '';
						     if (groupedperconv[i].author_displayname) {
							 modmessagerec = "<span class='msgAuthorNameGrp'>"+ groupedperconv[i].author_displayname + ":</span>" + groupedperconv[i].message;
						     } else {
					                 modmessagerec = groupedperconv[i].message;
		                                     }

						     if (groupedperconv[i].to.indexOf(": ") > -1) {
						         var groupednmbrtopre = groupedperconv[i].to.split(": ");
						         var groupednmbrto = groupednmbrtopre[1];
						     } else { 
						         var groupednmbrto = groupedperconv[i].to;
						     }

						     fromtoNmbrsData.push({
						               'author_displayname': authordnm,
						               'from': groupednbfrom,
						               'to': groupednmbrto,
						               'message': modmessagerec,
						               'date': groupedperconv[i].date,
						               'status': groupedperconv[i].deliveryreceipt,
						               'table': groupedperconv[i].table
						     });
					     }


					     // Remove the duplicates
					     let noDupMsgData = [];
					     $.each(fromtoNmbrsData, function(i, e) {
						    let matchingData = $.grep(noDupMsgData, function(item) {
						            return item.from == e.from && item.to == e.to && item.message == e.message && item.table == 'received' && e.table == 'sent';
						    });
						    if (matchingData.length === 0) {
							noDupMsgData.push(e);
						    }
					     });

					     let messagesPerNmbr = {};
					     let msgsNamesPerNmbr = {};
					     let msgsNmbrsNames = {};

					     let displayNamesarr = [];
					     let convData = [];

					     for (let n = 0; n < noDupMsgData.length; n++) {

					          if (noDupMsgData[n]['from'] == phNumberTo && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == phNumberTo && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_to',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });


					          } else if (noDupMsgData[n]['from'] == phNumberTo && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == phNumberTo && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_on',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });
					          }
					     }

					     // Sort messages by date
					     convData.sort(function(a, b) {
                                                return new Date(b.date) - new Date(a.date);
					     });

					     // Collect the display names of the users that sent messages from the current numbers
					     let selectedNames = [];
					     let displayNames = '';
					     for (let v = 0; v < convData.length; v++) {
					          if (selectedNames.indexOf(convData[v]['author_displayname']) == -1) {
					              selectedNames.push(convData[v]['author_displayname']);
					              displayNames += "<div id='diplNm_"+ phNumberTo +"_"+ v +"' class='dispNameList' name='"+ convData[v]['author_displayname'] +"'>"+ convData[v]['author_displayname'] +"</div>";
					          }
					     }
					     displayNames += "<div id='diplNmAllMsgcv' class='dispNameListAll' title='Show all the messages exchanged between the current 2 phone numbers.'>All messages</div>";

					     // Store the display names for the current numbers, to be able to see them later
					     let ctPhNumber = phNumberTo;
					     msgsNamesPerNmbr[ctPhNumber] = displayNames;

					     // Store the messages sent by each user, to be able to see them later when clicking on the user's name
					     for (let h = 0; h < selectedNames.length; h++) {

					          let rowMessageArrpn = [];
					          for (let b = 0; b < convData.length; b++) {

					               if (selectedNames[h] == convData[b]['author_displayname']) {

							   if (convData[b]['direction'] == 'sent_from') {
							       if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							       }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'sent_to') {
							       if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							       }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_from') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_on') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
					                   }
					               }
					          }
					          let crtNmber = phNumberTo;
					          let crtName = selectedNames[h];
					          msgsNmbrsNames[crtNmber] = msgsNmbrsNames[crtNmber] || {};
		                                  msgsNmbrsNames[crtNmber][crtName] = rowMessageArrpn;
					     }

		                             // The number of messages to be loaded by default
		                             let nmbTblDefault = 50;

		                             // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                             if (convData.length > nmbTblDefault) {
		                                 $("#loadMoreMsgs").css("display", "block");
		                                 var nmbToBeLoaded = nmbTblDefault;
		                             } else { var nmbToBeLoaded = convData.length; }

					     let rowMessageArr = [];
					     for (var m = nmbToBeLoaded - 1; m >= 0; m--) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     let convDataPerNmbr = rowMessageArr.join("");

		                             $("#grpdbynamelst").empty();
		                             $("#grpdbynamelst").append(displayNames);
		                             $("#msgListRowCell").empty();
		                             $("#msgListRowCell").append(convDataPerNmbr);

					     // Store the messages for the current To number, to be able to see them later
					     let rowMessageArrcpt = [];
					     for (let m = 0; m < convData.length; m++) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     messagesPerNmbr[phNumberTo] = rowMessageArrcpt;

		                             // Scroll down to the bottom of the window
		                             $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                             // Load more messages
		                             let clickNmb = 0;
		                             $("#loadMoreMsgs").click(function() {

		                                 clickNmb++;

		                                 var crefnb = (clickNmb + 1) * nmbToBeLoaded;

		                                 if (crefnb > convData.length) {
		                                     var nmbmsg = convData.length - 1;
		                                     $("#loadMoreMsgs").css("display", "none");
		                                 } else { 
		                                     var nmbmsg = crefnb - 1;
		                                 }

		                                 var rowMessageArrAdd = [];

		                                 for (let m = nmbmsg; m >= clickNmb * nmbToBeLoaded; m--) {

					              if (convData[m]['direction'] == 'sent_from') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'sent_to') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_from') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_on') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					              }
		                                 }

					         let convDataPerNmbrad = rowMessageArrAdd.join("");

		                                 let scrlheight = $("#msgListRowCell").height();
		                                 $("#msgListRowCell").prepend(convDataPerNmbrad);

		                                 $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                             });


					     // Show the messages sent by each user whose name is clicked
					     $('[id*="diplNm_"]').click(function() {

					         let crntNmbr = $(this).attr("id").split("_")[1];
					         let crntDisName = $(this).attr("name");                               
		                                 $("#loadMoreMsgs").css("display", "none");

		                                 let convDataprn = [];
		                                 $.each(msgsNmbrsNames[crntNmbr][crntDisName], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgsusr").css("display", "block");
		                                     let nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgsusr").css("display", "none");
		                                     let nmbToBeLoaded = convDataprn.length;
		                                 }

					         let rowMessageArrprnst = [];

					         for (let n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         let convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                                 // Load more messages
		                                 let clckNb = 0;
		                                 $("#loadMoreMsgsusr").unbind("click");
		                                 $("#loadMoreMsgsusr").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgs").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgsusr").css("display", "none");
		                                     } else { 
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgsusr").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });


					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsgcv").css("color", "#04957b");
					         $(this).css("color", "#1b8efe");
					     });


					     // Show again all the messages sent/received to/from the clicked number
					     $("#diplNmAllMsgcv").click(function() {

		                                 $("#loadMoreMsgsusr").css("display", "none");

		                                 let convDataprn = [];
		                                 $.each(messagesPerNmbr[phNumberTo], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgs").css("display", "block");
		                                     let nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgs").css("display", "none");
		                                     let nmbToBeLoaded = convDataprn.length;
		                                 }

					         let rowMessageArrprnst = [];

					         for (let n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         let convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);


		                                 // Load more messages
		                                 let clckNb = 0;
		                                 $("#loadMoreMsgs").unbind("click");
		                                 $("#loadMoreMsgs").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgsusr").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgs").css("display", "none");
		                                     } else { 
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgs").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });

					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsgcv").css("color", "#04957b");
					         $(this).css("color", "#04c6a4");
					     });


					     // Show the scroll-up arrow
					     $("#frmMsgLstWrap").scroll(function() {
						if ($(this).scrollTop() > 900) {
						      $('#upArrowSmall').fadeIn();
						} else {
						      $('#upArrowSmall').fadeOut();
						}
					     });

					     $("#upArrowSmall").unbind("click");
					     $("#upArrowSmall").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });
				  },
				  error: function() {
					     showAlert("Error while attempting to get message data from the database!");
					     $('#listAllMsgsConv').removeClass('icon-loading');
				  }
			   });
                   }

                   getMsgsForNumbersSec(phNumberFrom, phNumberTo);

                   $("#refreshMsgsConv").click(function() { getMsgsForNumbersSec(phNumberFrom, phNumberTo); setTimeout(function() { $("#diplNmAllMsgcv").click(); }, 1000); });
                }

                $('[id^="showMsgConv-"]').click(function() {

                   let ctrwnmbr = $(this).attr("id").replace("showMsgConv-", "");
                   let phNumberFrom = $("#frmNmbr-"+ ctrwnmbr).text().split(": ")[1];
                   let phNumberTo = $("#toNmbr-"+ ctrwnmbr).text();

                   showSentMsgPerConv(phNumberFrom, phNumberTo);
                });


                // Show the pop-up window that lists all the messages sent/received to/from a phone number
                function showMsgPerNmbr(clckPhNumber) {

                   var allfrmtomsg = "<div id='listAllMsgsFromTo'>";
                   allfrmtomsg += "<div id='draglstMsgmWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
                   allfrmtomsg += "<a id='closeFrmMsgWindow' title='Close this window'></a>";
                   allfrmtomsg += "<div class='showByNmbrTitle'>Messages sent/received to/from  <span style='color:#04957b'>"+ clckPhNumber +"</span></div>";
                   allfrmtomsg += "<div id='frmMsgLstWrap'>";
                   allfrmtomsg += "<table id='frmMsgLstTbl'>";
                   allfrmtomsg += "<tr class='groupedrowsbody'><td><div id='grpdbynamelst' class='groupedLstNamespn'></div></td><td><div id='loadMoreMsgs' title='Click to load older messages.'>Load more messages</div><div id='loadMoreMsgsusr' title='Click to load older messages.'>Load more messages</div><div id='msgListRowCell' class='groupedLstMsgspn'></div><div id='refreshMsgsWraptf'><div id='refreshMsgsConvtf' title='Refresh list of messages'></div></div><div id='arrowupWrap'><div id='upArrowSmall' title='Scroll to the top'></div></div></td></tr>";
                   allfrmtomsg += "</table></div>";
                   allfrmtomsg += "<div id='sendMsgReply'><table id='sendMsgConv'><tr><td><div id='fromPhoneNmbrConv'>From: <select id='selectFromNbConv'></select></div><div id='toPhoneNmbrConv'>To: <span id='toNmbrConv' style='color:#04957b'>"+ clckPhNumber +"</span></div></td></tr>";
                   allfrmtomsg += "<tr><td><textarea id='sendMsgConvText' placeholder='Enter a message here, then press Send SMS.'></textarea></td></tr></table>";
                   allfrmtomsg += "<div id='sendMsgConvBtn'>Send SMS</div></div>";
                   allfrmtomsg += "<div id='expandWindowRplCtn' title='Expand to send a message'><img id='expandWindowRpl' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;cursor:grab;'></div>";
                   allfrmtomsg += "</div>";

                   $("#content").append("<div id='recTblOverlay'></div>");
                   $("#content").append(allfrmtomsg);

                   var topDist = parseInt((window.innerHeight / 2).toFixed(2) - 340) +"px";
                   var leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 300) +"px";
                   $("#listAllMsgsFromTo").css({ "top" : topDist, "left" : leftDist });

                   $("#closeFrmMsgWindow").click(function() { $("#listAllMsgsFromTo").remove(); $("#recTblOverlay").remove(); });
                   $("#recTblOverlay").click(function() { $("#listAllMsgsFromTo").remove(); $("#recTblOverlay").remove(); });

	           // Expand the window when clicking on the arrow, to be able to send a reply message
                   $("#expandWindowRpl").unbind("click");
	           $("#expandWindowRpl").click(function() {

	              if ($(this).attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsFromTo").css("height", "618px");
                          } else {
                              $("#listAllMsgsFromTo").css("height", parseInt($(window).height() - 32) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 304) + "px");
                          }
	                  $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          if ($(window).width() > 600) {
                              $("#listAllMsgsFromTo").css("height", "490px");
                          } else {
                              $("#listAllMsgsFromTo").css("height", parseInt($(window).height() - 120) + "px");
                              $("#frmMsgLstWrap").css("height", parseInt($(window).height() - 232) + "px");
                          }
                          $(this).attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
	              }
	           });


                   // Send a message from the 'conversation' window
                   $("#sendMsgConvBtn").click(function() {

                      $("#sendMsgConv,#sendMsgConvBtn").addClass('icon-loading');
                      var msgToSend = $("#sendMsgConvText").val();
                      var selectedid = $("#selectFromNbConv").val();
                      var toNumber = $("#toNmbrConv").text();
                      var receiversNumbers = [toNumber];

		      if (selectedid != '') {

			  var sendersplit = selectedid.split(":");
			  var providercap = sendersplit[0];
			  var provsec = sendersplit[1];

			  if (/[a-zA-Z]/.test(provsec)) {
			      var alphanumcheck = true;
			  } else { var alphanumcheck = false; }

			  if (providercap == 'Tx' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == false) {
			      var selectedsender = selectedid.replace(/[^0-9]/g, "");
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == false) {  
			      var senderproc = selectedid.replace(/[^0-9]/g, "");
			      var selectedsender = "+" + senderproc;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  } else if (providercap == 'Tx' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "telnyx";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
			  } else if (providercap == 'Pl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "plivo";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
			  } else if (providercap == 'Tw' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "twilio";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
			  } else if (providercap == 'Fl' && alphanumcheck == true) {
			      var selectedsender = provsec;
			      var providerUsed = "flowroute";
			      var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
			  }

                          var uploadedtomms = [];

	                  if (msgToSend != '') {

				  $.ajax({
				     url: relbaseUrl,
				     type: "POST",
				     data: {
				           receiversPhoneNbs: receiversNumbers,
				           fromsender: selectedsender,
				           waitinterval: 1000,
				           sentsmstext: msgToSend,
				           ismms: 0,
				           mmsfiles: uploadedtomms
				         },
				     success: function(displayname) {

                                           var tzdate = new Date();
                                           var presDatest = new Date(tzdate.getTime() - (tzdate.getTimezoneOffset() * 60000)).toJSON();
                                           var presDatedb = presDatest.split(".")[0];
                                           var presDatesc = presDatedb.split("T");
                                           var presDate = presDatesc[0] +" "+ presDatesc[1];
                                           var sentMessageStatus = '';

                                           if (displayname) {
                                               var msgToSendproc = "<span class='msgAuthorNameGrp'>"+ displayname + ":</span>" + msgToSend; 
                                           } else { var msgToSendproc = msgToSend; }

                                           $("#msgListRowCell").append("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ selectedsender +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ receiversNumbers[0] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ msgToSendproc +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ presDate +"</div><div class='sentMssgStatus'>"+ sentMessageStatus +"</div></div>");

                                           // Scroll down to the bottom of the window
                                           $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

                                           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     },
				     error: function() {
				           showAlert("Error while sending the message. You can check your Nextcloud log to find out more about this issue.");
				           $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
				     }
				  });
			  } else {
				  showAlert("Please enter a message in the text box!");
				  $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
			  }
		      } else {
			      showAlert("Please choose a Sender ID from the 'From' drop-down list!");
			      $("#sendMsgConv,#sendMsgConvBtn").removeClass('icon-loading');
		      }

                   });


	           // Make the window draggable
	           function makeMgrWndDraggable(e) {

			   window.pmdragging = {};
			   pmdragging.pageX0 = e.pageX;
			   pmdragging.pageY0 = e.pageY;
			   pmdragging.elem = $("#listAllMsgsFromTo");
			   pmdragging.offset0 = $("#listAllMsgsFromTo").offset();

			   function handle_dragging(e) {
			       var left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
			       var top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
			       $(pmdragging.elem).offset({top: top, left: left});
			   }

			   function handle_mouseup(e) {
			       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
			   }

			   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
	           }
	           $("#draglstMsgmWindow").mousedown(makeMgrWndDraggable);
	           $("#draglstMsgmWindowsc").mousedown(makeMgrWndDraggable);


                   // Append the available phone numbers to the From drop-down list
                   var availPhoneNmbrs = [];
                   $("#currentsmsnmbrs .optselectsmsnb").each(function() {
                      var crtphnmbr = $(this).attr("value");
                      if (crtphnmbr != "") { availPhoneNmbrs.push(crtphnmbr); }
                   });

                   if (availPhoneNmbrs.length > 0) {
                       var avphopt = "";
                       for (let d = 0; d < availPhoneNmbrs.length; d++) {
                            avphopt += "<option value='"+ availPhoneNmbrs[d] +"'>"+ availPhoneNmbrs[d] +"</option>";
                       }
                       $("#selectFromNbConv").append(avphopt);

                   } else { $("#selectFromNbConv").append("<option value='' selected>No IDs</option>"); }


                   // Get the sent/received messages for the current phone number, from the database
                   function getMsgsPerNmbrSec(clckPhNumber) {

			   var getGroupedPnUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedpernumber");

			   $('#listAllMsgsFromTo').addClass('icon-loading');
			   var totalPhNmbrs = 0;

			   $.ajax({
				  method: 'POST',
				  url: getGroupedPnUrl,
				  contentType: 'application/json',
		                  data: JSON.stringify({ "phoneNumber": clckPhNumber }),
				  success: function(groupedpernb) {

					     $('#listAllMsgsFromTo').removeClass('icon-loading');

					     var fromtoNmbrsData = [];

					     for (var i = 0; i < groupedpernb.length; i++) {

						     if (groupedpernb[i].author_displayname) {
							 var authordnm = groupedpernb[i].author_displayname;
						     } else { 
							 var authordnm = '';
						     }

						     var sentfromnmbrarr = groupedpernb[i].from.split(": ");
						     if (sentfromnmbrarr[1]) {
							 var groupednbfrom = sentfromnmbrarr[1];
						     } else {
							 var groupednbfrom = sentfromnmbrarr[0];
						     }

						     var modmessagesent = '';
						     if (groupedpernb[i].author_displayname) {
							 modmessagesent = "<span class='msgAuthorNameGrp'>"+ groupedpernb[i].author_displayname + ":</span>" + groupedpernb[i].message;
						     } else {
					                 modmessagesent = groupedpernb[i].message;
		                                     }

						     if (groupedpernb[i].to.indexOf(": ") > -1) {
						         var groupednmbrtopre = groupedpernb[i].to.split(": ");
						         var groupednmbrto = groupednmbrtopre[1];
						     } else { 
						         var groupednmbrto = groupedpernb[i].to;
						     }

						     fromtoNmbrsData.push({
						               'author_displayname': authordnm,
						               'from': groupednbfrom,
						               'to': groupednmbrto,
						               'message': modmessagesent,
						               'date': groupedpernb[i].date,
						               'status': groupedpernb[i].deliveryreceipt,
						               'table': groupedpernb[i].table
						     });
					     }


					     // Remove the duplicates
					     var noDupMsgData = [];
					     $.each(fromtoNmbrsData, function(i, e) {
						    var matchingData = $.grep(noDupMsgData, function(item) {
						            return item.from == e.from && item.to == e.to && item.message == e.message && item.table == 'received' && e.table == 'sent';
						    });
						    if (matchingData.length === 0) {
							noDupMsgData.push(e);
						    }
					     });

					     var messagesPerNmbr = {};
					     var msgsNamesPerNmbr = {};
					     var msgsNmbrsNames = {};

					     var displayNamesarr = [];
					     var convData = [];

					     for (var n = 0; n < noDupMsgData.length; n++) {

					          if (noDupMsgData[n]['from'] == clckPhNumber && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == clckPhNumber && noDupMsgData[n]['table'] == 'sent') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'sent_to',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });


					          } else if (noDupMsgData[n]['from'] == clckPhNumber && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_from',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });

					          } else if (noDupMsgData[n]['to'] == clckPhNumber && noDupMsgData[n]['table'] == 'received') {

					              convData.push({
					                             'author_displayname': noDupMsgData[n]['author_displayname'],
					                             'message': noDupMsgData[n]['message'],
					                             'from': noDupMsgData[n]['from'],
					                             'to': noDupMsgData[n]['to'],
					                             'date': noDupMsgData[n]['date'],
					                             'direction': 'received_on',
					                             'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
					                             'table': noDupMsgData[n]['table']
					              });
					          }
					     }

					     // Sort messages by date
					     convData.sort(function(a, b) {
                                                return new Date(b.date) - new Date(a.date);
					     });

					     // Collect the display names of the users that sent messages from the current number
					     var selectedNames = [];
					     var displayNames = '';
					     for (var v = 0; v < convData.length; v++) {
					          if (selectedNames.indexOf(convData[v]['author_displayname']) == -1) { 
					              selectedNames.push(convData[v]['author_displayname']);
					              displayNames += "<div id='diplNm_"+ clckPhNumber +"_"+ v +"' class='dispNameList' name='"+ convData[v]['author_displayname'] +"'>"+ convData[v]['author_displayname'] +"</div>";
					          }
					     }
					     displayNames += "<div id='diplNmAllMsg' class='dispNameListAll' title='Show all the messages for this number.'>"+ clckPhNumber +"</div>";

					     // Store the display names for the current number, to be able to see them later
					     var ctPhNumber = clckPhNumber;
					     msgsNamesPerNmbr[ctPhNumber] = displayNames;

					     // Store the messages sent by each user, to be able to see them later when clicking on the user's name
					     for (var h = 0; h < selectedNames.length; h++) {

					          var rowMessageArrpn = [];
					          for (var b = 0; b < convData.length; b++) {

					               if (selectedNames[h] == convData[b]['author_displayname']) {

							   if (convData[b]['direction'] == 'sent_from') {
							       if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							       }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'sent_to') {
							       if (convData[b]['status']) {
							           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
					                               if (convData[b]['status'].indexOf("undelivered") > -1) {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                       } else {
							                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                       }
							           } else {
							               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							           }
							       } else {
							           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							       }
							       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_from') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
							   } else if (convData[b]['direction'] == 'received_on') {
							       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
					                   }
					               }
					          }
					          var crtNmber = clckPhNumber;
					          var crtName = selectedNames[h];
					          msgsNmbrsNames[crtNmber] = msgsNmbrsNames[crtNmber] || {};
		                                  msgsNmbrsNames[crtNmber][crtName] = rowMessageArrpn;
					     }

		                             // The number of messages to be loaded by default
		                             var nmbTblDefault = 50;

		                             // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                             if (convData.length > nmbTblDefault) {
		                                 $("#loadMoreMsgs").css("display", "block");
		                                 var nmbToBeLoaded = nmbTblDefault;
		                             } else { var nmbToBeLoaded = convData.length; }

					     var rowMessageArr = [];
					     for (var m = nmbToBeLoaded - 1; m >= 0; m--) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }    
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     var convDataPerNmbr = rowMessageArr.join("");
		                             $("#grpdbynamelst").empty();
		                             $("#grpdbynamelst").append(displayNames);
		                             $("#msgListRowCell").empty();
		                             $("#msgListRowCell").append(convDataPerNmbr);

					     // Store the messages for the current number, to be able to see them later, when clicking on the number
					     var rowMessageArrcpt = [];
					     for (var m = 0; m < convData.length; m++) {

					          if (convData[m]['direction'] == 'sent_from') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'sent_to') {
					              if (convData[m]['status']) {
						          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                              if (convData[m]['status'].indexOf("undelivered") > -1) {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                              }
						          } else {
						              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						          }
					              } else {
					                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					              }
					              rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_from') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					          } else if (convData[m]['direction'] == 'received_on') {

						      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					          }
					     }

					     messagesPerNmbr[clckPhNumber] = rowMessageArrcpt;

		                             // Scroll down to the bottom of the window
		                             $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                             // Load more messages
		                             var clickNmb = 0;
		                             $("#loadMoreMsgs").click(function() {

		                                 clickNmb++;

		                                 var crefnb = (clickNmb + 1) * nmbToBeLoaded;

		                                 if (crefnb > convData.length) {
		                                     var nmbmsg = convData.length - 1;
		                                     $("#loadMoreMsgs").css("display", "none");
		                                 } else { 
		                                     var nmbmsg = crefnb - 1;
		                                 }

		                                 var rowMessageArrAdd = [];

		                                 for (var m = nmbmsg; m >= clickNmb * nmbToBeLoaded; m--) {

					              if (convData[m]['direction'] == 'sent_from') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'sent_to') {
					                  if (convData[m]['status']) {
						              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
				                                  if (convData[m]['status'].indexOf("undelivered") > -1) {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                                  } else {
						                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                                  }
						              } else {
						                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
						              }
					                  } else {
					                      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					                  }
					                  rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_from') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

					              } else if (convData[m]['direction'] == 'received_on') {

							  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
					              }
		                                 }

					         var convDataPerNmbrad = rowMessageArrAdd.join("");

		                                 var scrlheight = $("#msgListRowCell").height();
		                                 $("#msgListRowCell").prepend(convDataPerNmbrad);

		                                 $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                             });


					     // Show the messages sent by each user whose name is clicked
					     $('[id*="diplNm_"]').click(function() {

					         var crntNmbr = $(this).attr("id").split("_")[1];
					         var crntDisName = $(this).attr("name");                               
		                                 $("#loadMoreMsgs").css("display", "none");

		                                 var convDataprn = [];
		                                 $.each(msgsNmbrsNames[crntNmbr][crntDisName], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgsusr").css("display", "block");
		                                     var nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgsusr").css("display", "none");
		                                     var nmbToBeLoaded = convDataprn.length;
		                                 }

					         var rowMessageArrprnst = [];

					         for (var n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         var convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);

		                                 // Load more messages
		                                 var clckNb = 0;
		                                 $("#loadMoreMsgsusr").unbind("click");
		                                 $("#loadMoreMsgsusr").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgs").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgsusr").css("display", "none");
		                                     } else { 
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgsusr").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });


					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsg").css("color", "#04957b");
					         $(this).css("color", "#1b8efe");
					     });


					     // Show again all the messages sent/received to/from the clicked number
					     $("#diplNmAllMsg").click(function() {

		                                 $("#loadMoreMsgsusr").css("display", "none");

		                                 var convDataprn = [];
		                                 $.each(messagesPerNmbr[clckPhNumber], function(index, item) {
		                                        convDataprn.push(item);
		                                 });

		                                 // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
		                                 if (convDataprn.length > nmbTblDefault) {
		                                     $("#loadMoreMsgs").css("display", "block");
		                                     var nmbToBeLoaded = nmbTblDefault;
		                                 } else {
		                                     $("#loadMoreMsgs").css("display", "none");
		                                     var nmbToBeLoaded = convDataprn.length;
		                                 }

					         var rowMessageArrprnst = [];

					         for (var n = nmbToBeLoaded - 1; n >= 0; n--) {
		                                      rowMessageArrprnst.push(convDataprn[n]);
					         }

					         var convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                 $("#msgListRowCell").empty();
		                                 $("#msgListRowCell").append(convDataPerNmbrprnst);

		                                 // Scroll down to the bottom of the window
		                                 $("#frmMsgLstWrap").animate({scrollTop:$("#frmMsgLstTbl").prop("scrollHeight")},200);


		                                 // Load more messages
		                                 var clckNb = 0;
		                                 $("#loadMoreMsgs").unbind("click");
		                                 $("#loadMoreMsgs").click(function() {

		                                     clckNb++;
		                                     var crefnb = (clckNb + 1) * nmbToBeLoaded;

		                                     $("#loadMoreMsgsusr").css("display", "none");

		                                     if (crefnb > convDataprn.length) {
		                                         var nmbmsg = convDataprn.length - 1;
		                                         $("#loadMoreMsgs").css("display", "none");
		                                     } else {
		                                         var nmbmsg = crefnb - 1;
		                                         $("#loadMoreMsgs").css("display", "block");
		                                     }

		                                     var rowMessageArrAddst = [];

		                                     for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

		                                          rowMessageArrAddst.push(convDataprn[q]);
		                                     }

					             var convDataPerNmbradst = rowMessageArrAddst.join("");

		                                     var scrlheight = $("#msgListRowCell").height();
		                                     $("#msgListRowCell").prepend(convDataPerNmbradst);

		                                     $("#frmMsgLstWrap").animate({scrollTop: $("#msgListRowCell").height() - scrlheight}, 0);
		                                 });


					         $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
					         $("#diplNmAllMsg").css("color", "#04957b");
					         $(this).css("color", "#04c6a4");
					     });


					     // Show the scroll-up arrow
					     $("#frmMsgLstWrap").scroll(function() {
						if ($(this).scrollTop() > 900) {
						      $('#upArrowSmall').fadeIn();
						} else {
						      $('#upArrowSmall').fadeOut();
						}
					     });

					     $("#upArrowSmall").unbind("click");
					     $("#upArrowSmall").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });
				  },
				  error: function() {
					     showAlert("Error while attempting to get message data from the database!");
					     $('#listAllMsgsFromTo').removeClass('icon-loading');
				  }
			   });
                   }

                   getMsgsPerNmbrSec(clckPhNumber);

                   $("#refreshMsgsConvtf").click(function() { getMsgsPerNmbrSec(clckPhNumber); setTimeout(function() { $("#diplNmAllMsg").click(); }, 1000); });
                }


                $('[id^="showMsgFrom-"]').click(function() {

                   var ctrwnb = $(this).attr("id").replace("showMsgFrom-", "");
                   if ($("#frmNmbr-"+ ctrwnb).text().indexOf(":") > -1) {
                       var clckPhNumber = $("#frmNmbr-"+ ctrwnb).text().split(": ")[1];
                   } else { var clckPhNumber = $("#frmNmbr-"+ ctrwnb).text(); }

                   showMsgPerNmbr(clckPhNumber);
                })

                $('[id^="showMsgTo-"]').click(function() {
                   var ctrwnbTo = $(this).attr("id").replace("showMsgTo-", "");
                   var clckPhNbTo = $("#toNmbr-"+ ctrwnbTo).text();

                   showMsgPerNmbr(clckPhNbTo);
                })


                // Add pagination
                var rowsShown = messagesperpage;
                var rowsTotal = $("#sentSmsTable tr").length;
                var numPages = (rowsTotal - 2) / rowsShown;

                for (i = 0; i < numPages; i++) {
                     var pageNum = i + 1;
                     $('#paginationsent').append('<a href="#" rel="' + i + '" class="pagenumbers">' + pageNum + '</a> ');
                }

                $('#paginationsent').children(":first").addClass('active');

                $('#paginationsent a:first').addClass('active');

                // Show table page when clicking on page number
                $('.pages a').bind('click', function () {

                      $('#paginationsent').children().removeClass('active');

                      $(this).addClass('active');

                      var currentsentPgNo = $(this).text();

                      $('#paginationsent a').each(function() {
                         if ($(this).text() == currentsentPgNo) {
                             $(this).addClass('active');
                         }
                      });

                      // Sort table rows
		      var rows = $('#sentSmsTable tr').get();

		      rows.sort(function(a, b) {

		           var A = parseInt($('td.sentdbidcolumn', a).text());
		           var B = parseInt($('td.sentdbidcolumn', b).text());

		           if (A < B) {
		               return -1;
		           }

		           if (A > B) {
		               return 1;
		           }

		           return 0;
		      });

		      $.each(rows, function(index, row) {
		         $('#sentSmsTable').append(row);
		      });

                      var currPage = $(this).attr('rel');
                      var startItem = currPage * rowsShown;
                      var endItem = startItem + rowsShown;

                      $('.sentrowsbody').hide().slice(startItem, endItem).css('display', 'table-row');

                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total displayed messages: " + sentparseddata.length + "</div>");
                });

                $('#paginationsent').children(":last").trigger('click');

                // Select all records
                $('#selectAllChckbx').change(function() {
                   if ($(this).is(':checked')) {
                       $(".indivchckbx").prop("checked", true);
                   } else {
                       $(".indivchckbx").prop("checked", false);
                   }
                });

                function reorderSentRows() {
                    var currenttext = $(".filterbuttonsent").closest('[class="filterbuttonsent"]').find('[class="indivfiltersent"]').text();
                    if (currenttext == '') {
                        $('tr').sort(function (a, b) {
                           return parseInt($('td.sentdbidcolumn', b).text()) < parseInt($('td.sentdbidcolumn', a).text());
                        }).appendTo("#sentSmsTable");
                    }
                }

                // Filter rows
                $("#databaseidfilter").on("click", function(event) {

                       var databaseId = $("#dbidtextsent").val();
                       var msgrowsNo = 0;

                       $(".sentrowsbody").each(function() {

                          var checkEmpty = 0;
                          $(".indivfiltersent").not("#dbidtextsent").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty = 1;
                              }
                          });

                          if (checkEmpty == 0) {
                              $(this).show();
                          }

                          if (databaseId != '') {
                             if ($(this).find('[class="sentdbidcolumn"]').text() == databaseId) {
                                 $("#sentSmsTable").append(this);
                                 if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                 $(this).hide();
                             }
                          } else {
                                 $(this).show();
                                 msgrowsNo++;
                          }
                       });

                       reorderSentRows();
                       $('#totalsentmessages').remove();
                       $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                       var useridtxt = $("#useridtext").val().toLowerCase();
                       var msgrowsNo = 0;

                       $(".sentrowsbody").each(function() {

                          var checkEmpty1 = 0;
                          $(".indivfiltersent").not("#useridtext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty1 = 1;
                              }
                          });

                          if (checkEmpty1 == 0) {
                              $(this).show();
                          }

                          if (useridtxt != '') {
                              var founduserid = $(this).find('[class="useridcolsent"]').text().toLowerCase();
                              if (founduserid.indexOf(useridtxt) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                  $(this).hide();
                             }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                       });

                       reorderSentRows();
                       $('#totalsentmessages').remove();
                       $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                       var messageidtxt = $("#messageidtext").val().toLowerCase();
                       var msgrowsNo = 0;

                       $(".sentrowsbody").each(function() {

                          var checkEmpty2 = 0;
                          $(".indivfiltersent").not("#messageidtext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty2 = 1;
                              }
                          });

                          if (checkEmpty2 == 0) {
                              $(this).show();
                          }

                          if (messageidtxt != '') {
                              var foundtdmssgid = $(this).find('[class="messageidcolsent"]').text().toLowerCase();
                              if (foundtdmssgid.indexOf(messageidtxt) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                       });

                       reorderSentRows();
                       $('#totalsentmessages').remove();
                       $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                       var datetxtvr = $("#datetext").val().toLowerCase();
                       var msgrowsNo = 0;

                       $(".sentrowsbody").each(function() {

                          var checkEmpty3 = 0;
                          $(".indivfiltersent").not("#datetext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty3 = 1;
                              }
                          });

                          if (checkEmpty3 == 0) {
                              $(this).show();
                          }

                          if (datetxtvr != '') {
                             var founddate = $(this).find('[class="datecolsent"]').text().toLowerCase();
                             if (founddate.indexOf(datetxtvr) != -1) {
                                 $("#sentSmsTable").append(this);
                                 if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                 $(this).hide();
                             }
                          } else {
                                 $(this).show();
                                 msgrowsNo++;
                          }
                       });

                       reorderSentRows();
                       $('#totalsentmessages').remove();
                       $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                       var fromtxtvr = $("#fromtext").val().toLowerCase();
                       var msgrowsNo = 0;

                       $(".sentrowsbody").each(function() {

                          var checkEmpty4 = 0;
                          $(".indivfiltersent").not("#fromtext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty4 = 1;
                              }
                          });

                          if (checkEmpty4 == 0) {
                              $(this).show();
                          }

                          if (fromtxtvr != '') {
                             var foundfrom = $(this).find('[class="fromcolumnsent"]').text().toLowerCase();
                             if (foundfrom.indexOf(fromtxtvr) != -1) {
                                 $("#sentSmsTable").append(this);
                                 if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                 $(this).hide();
                             }
                          } else {
                                 $(this).show();
                                 msgrowsNo++;
                          }
                       });

                       reorderSentRows();
                       $('#totalsentmessages').remove();
                       $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var totxtvr = $("#totext").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".sentrowsbody").each(function() {

                          var checkEmpty5 = 0;
                          $(".indivfiltersent").not("#totext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty5 = 1;
                              }
                          });

                          if (checkEmpty5 == 0) {
                              $(this).show();
                          }

                          if (totxtvr != '') {
                             var foundto = $(this).find('[class="tocolumnsent"]').text().toLowerCase();
                             if (foundto.indexOf(totxtvr) != -1) {
                                 $("#sentSmsTable").append(this);
                                 if ($(this).is(":visible")) { msgrowsNo++; }
                             } else {
                                 $(this).hide();
                             }
                          } else {
                                 $(this).show();
                                 msgrowsNo++;
                          }
                      });

                      reorderSentRows();
                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var networktxtvr = $("#networktext").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".sentrowsbody").each(function() {

                          var checkEmpty6 = 0;
                          $(".indivfiltersent").not("#networktext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty6 = 1;
                              }
                          });

                          if (checkEmpty6 == 0) {
                              $(this).show();
                          }

                          if (networktxtvr != '') {
                              var foundnetwork = $(this).find('[class="networkNmContent"]').text().toLowerCase();
                              if (foundnetwork.indexOf(networktxtvr) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                      });

                      reorderSentRows();
                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var pricetxtvr = $("#pricetext").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".sentrowsbody").each(function() {

                          var checkEmpty7 = 0;
                          $(".indivfiltersent").not("#pricetext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty7 = 1;
                              }
                          });

                          if (checkEmpty7 == 0) {
                              $(this).show();
                          }

                          if (pricetxtvr != '') {
                              var foundprice = $(this).find('[class="pricecolumnsent"]').text().toLowerCase();
                              if (foundprice.indexOf(pricetxtvr) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                      });

                      reorderSentRows();
                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var statustxtvr = $("#statustext").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".sentrowsbody").each(function() {

                          var checkEmpty8 = 0;
                          $(".indivfiltersent").not("#statustext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty8 = 1;
                              }
                          });

                          if (checkEmpty8 == 0) {
                              $(this).show();
                          }

                          if (statustxtvr != '') {
                              var foundstatus = $(this).find('[class="statuscolumnsent"]').text().toLowerCase();
                              if (foundstatus.indexOf(statustxtvr) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                      });

                      reorderSentRows();
                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var deliverytxtvr = $("#deliveryrcpttext").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".sentrowsbody").each(function() {

                          var checkEmpty9 = 0;
                          $(".indivfiltersent").not("#deliveryrcpttext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty9 = 1;
                              }
                          });

                          if (checkEmpty9 == 0) {
                              $(this).show();
                          }

                          if (deliverytxtvr != '') {
                              var founddeliveryrcpt = $(this).find('[class="deliveryrcptcolsent"]').text().toLowerCase();
                              if (founddeliveryrcpt.indexOf(deliverytxtvr) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                      });

                      reorderSentRows();
                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

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

                      var messagetxtvr = $("#messagetext").val().toLowerCase();
                      var msgrowsNo = 0;

                      $(".sentrowsbody").each(function() {

                          var checkEmpty10 = 0;
                          $(".indivfiltersent").not("#messagetext").each(function() {
                              if ($(this).val() != '') {
                                  checkEmpty10 = 1;
                              }
                          });

                          if (checkEmpty10 == 0) {
                              $(this).show();
                          }

                          if (messagetxtvr != '') {
                              var foundmessage = $(this).find('[class="messagecolumnsent"]').text().toLowerCase();
                              if (foundmessage.indexOf(messagetxtvr) != -1) {
                                  $("#sentSmsTable").append(this);
                                  if ($(this).is(":visible")) { msgrowsNo++; }
                              } else {
                                  $(this).hide();
                              }
                          } else {
                                  $(this).show();
                                  msgrowsNo++;
                          }
                      });

                      reorderSentRows();
                      $('#totalsentmessages').remove();
                      $('#smstables').append("<div id='totalsentmessages'>Total filtered messages: " + msgrowsNo + "</div>");
                });

                // Clear all filters
                $("#clearsentfilters").on("click", function(event) {
                       $(".sentrowsbody").each(function() {
                          $(this).show();
                       });
                       $(".indivfiltersent").val("");
                       $('#totalsentmessages').remove();
                       $('#smstables').append("<div id='totalsentmessages'>Total displayed messages: " + sentparseddata.length + "</div>");
                });

                // Delete selected rows from the database
                $("#deletesentrows").on("click", function() {

                   var checkcheckbx = $("#sentSmsTable input[type=checkbox]:checked").length;
                   if (checkcheckbx == 0) {
                       showAlert("Please select the row(s) to permanently delete from the database !");
                   } else {
                          var sentcheckboxIds = [];
                          $(".sentrowsbody").each(function() {
                             var sentrowcheckbx = $(this).find('input[type="checkbox"]');
                             if (sentrowcheckbx.is(":checked")) {
                                 var dbrowid = $(this).find('[class="sentdbidcolumn"]').text() + "|" + $(this).find('[class="messageidcolsent"]').text();
                                 sentcheckboxIds.push(dbrowid);
                             }
                          });

		          confirmAlert("Please note that the row(s) you selected will be permanently deleted from the database, without being saved before removal. This action cannot be undone ! If you really want to permanently delete the selected row(s) press 'OK'.");

		          $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

		          $("#confirmOk").click(function() {

		              $("#alertMsgOverlay").remove();
		              $("#alertConfMessage").remove();

                              var deletesentRowsUrl = OC.generateUrl("/apps/sms_relentless/user/removesentrows");
                              $('#smstables').addClass('icon-loading');

                              $.ajax({
                                   url: deletesentRowsUrl,
                                   type: "POST",
                                   data: { "sentmessagedbIDs": sentcheckboxIds },
                                   success: function(delmsgsent) {
				            $('#smstables').removeClass('icon-loading');
                                            if (delmsgsent == "success") {
                                                showAlert("The row(s) have been deleted successfully !");
                                                $('#sentsmstableshow').click();
                                            } else if (delmsgsent == "not allowed") {
                                                showAlert("At least one message couldn't be deleted because of permission issues. Non-admin users can delete the messages sent/received from/on the numbers shared with them only if they are allowed by an admin.");
                                            } else {
                                                showAlert("There was an error while deleting the selected row(s) !");
                                            }
                                   },
                                   error: function() {
                                            $('#smstables').removeClass('icon-loading');
                                            showAlert("There was an error while attempting to delete the selected row(s) !");
                                   }
                              });
                          });
                    }
                });

                // Show/Hide filter row
	        $('#sentarrow').on('click', function() {
	           if ($('#sentfiltersrow').is(':visible')) {
		       $('#sentfiltersrow').hide();
                       $('#sentheaderrow').css('top', '0px');
                       $(this).removeClass('arrowUpCl');
                       $(this).addClass('arrowDownCl');
		   } else {
		       $('#sentfiltersrow').show();
                       $('#sentheaderrow').css('top', '158px');
                       $(this).removeClass('arrowDownCl');
                       $(this).addClass('arrowUpCl');
                   }
                });

                $("#app-content").animate({scrollTop:$("#sentSmsTable").prop("scrollHeight")},200);
          },
          error: function() {
                showAlert("Error! You can check the Nextcloud log to find more details about this issue.");
                $('#smstables').removeClass('icon-loading');
          }
     });

     // Look for the 'new received message' indicator in the database, to know if the received messages list needs to be refreshed
     intervalNmfr = setInterval(function() { checkIfNewMessage(); }, newMsgInterval);

     // Show the auto-refresh button
     $("#stopAutoRefreshSent").css("display", "inline-block");

  });


  // List conversations
  $("#conversationsshow").on("click", function(event) {

     $('#smstables').empty();
     $("#stopAutoRefreshSent").css("display", "none");
     clearInterval(intervalNmfr);
     $('#smstables').append("<table id='conversationsTable'><tr><td><div id='convArchAndActive'></div></td><td><div id='conversationsText'></div></td></tr></table>");
     $("#conversationsTable").css({ "width" : $("#smstables").width(), "height" : $("#smstables").height() - 10 });
     $("#convArchAndActive").css({ "width" : $("#conversationsTable").width() * 0.25, "height" : $("#conversationsTable").height() });
     $("#conversationsText").css({ "width" : $("#conversationsTable").width() * 0.74, "height" : $("#conversationsTable").height() });
     $("#conversationsText").append("<div id='convImgGrey'><img src='/" + ctappdir + "/sms_relentless/img/conversations.svg'></div>");
     $("#convImgGrey").css({ "top" : $("#conversationsTable").height() * 0.5 - 109, "left" : $("#conversationsTable").width() * 0.63 - 144 });
     $("#convTextHeader").css("width", $("#conversationsTable").width() * 0.74);

     var getConvUrl = OC.generateUrl("/apps/sms_relentless/user/getconversations");
     $('#smstables').addClass('icon-loading');

     $.ajax({
          url: getConvUrl,
          method: 'GET',
          contentType: 'application/json',
          success: function(convdatafdb) {

                     $('#smstables').removeClass('icon-loading');
                     if (convdatafdb.length == 0) { showAlert("The conversations list is empty. It will be populated after you'll send messages."); }

		     let convArchived = [];
                     let convActive = [];

		     for (let c = 0; c < convdatafdb.length; c++) {
                          if (convdatafdb[c]['archived'] == 1) {
                              convArchived.push({
                                'conversation_id': convdatafdb[c]['conversation_id'],
                                'archived': convdatafdb[c]['archived'],
                                'last_archived': convdatafdb[c]['last_archived'],
                                'last_unarchived': convdatafdb[c]['last_unarchived'],
                                'archived_by': convdatafdb[c]['archived_by'],
                                'unarchived_by': convdatafdb[c]['unarchived_by'],
                                'last_msg_date': convdatafdb[c]['last_msg_date'],
                                'last_msg_from': convdatafdb[c]['last_msg_from'],
                                'last_msg_to': convdatafdb[c]['last_msg_to'],
                                'last_message': convdatafdb[c]['last_message'],
                                'lastmsgdisplayname': convdatafdb[c]['lastmsgdisplayname'],
                                'flagged': convdatafdb[c]['flagged'],
                                'flagunflagby': convdatafdb[c]['flagunflagby'],
                                'flagunflagdate': convdatafdb[c]['flagunflagdate'],
                                'tag': (convdatafdb[c]['tag'] != null)? convdatafdb[c]['tag'] : "",
                                'taguntagby': convdatafdb[c]['taguntagby'],
                                'taguntagdate': convdatafdb[c]['taguntagdate'],
                                'description': (convdatafdb[c]['description'] != null)? convdatafdb[c]['description'] : "",
                                'descriptionby': convdatafdb[c]['descriptionby'],
                                'descriptiondate': convdatafdb[c]['descriptiondate']
                              });
                          } else {
                              convActive.push({
                                'conversation_id': convdatafdb[c]['conversation_id'],
                                'archived': convdatafdb[c]['archived'],
                                'last_archived': convdatafdb[c]['last_archived'],
                                'last_unarchived': convdatafdb[c]['last_unarchived'],
                                'archived_by': convdatafdb[c]['archived_by'],
                                'unarchived_by': convdatafdb[c]['unarchived_by'],
                                'last_msg_date': convdatafdb[c]['last_msg_date'],
                                'last_msg_from': convdatafdb[c]['last_msg_from'],
                                'last_msg_to': convdatafdb[c]['last_msg_to'],
                                'last_message': convdatafdb[c]['last_message'],
                                'lastmsgdisplayname': convdatafdb[c]['lastmsgdisplayname'],
                                'flagged': convdatafdb[c]['flagged'],
                                'flagunflagby': convdatafdb[c]['flagunflagby'],
                                'flagunflagdate': convdatafdb[c]['flagunflagdate'],
                                'tag': (convdatafdb[c]['tag'] != null)? convdatafdb[c]['tag'] : "",
                                'taguntagby': convdatafdb[c]['taguntagby'],
                                'taguntagdate': convdatafdb[c]['taguntagdate'],
                                'description': (convdatafdb[c]['description'] != null)? convdatafdb[c]['description'] : "",
                                'descriptionby': convdatafdb[c]['descriptionby'],
                                'descriptiondate': convdatafdb[c]['descriptiondate']
                              });
                          }
                     }

                     // Order the array of archived conversations by date
		     convArchived.sort(function(a, b) {
                          let c = new Date(a.last_msg_date);
                          let d = new Date(b.last_msg_date);
                          return c-d;
		     });

                     // Order the array of active conversations by date
		     convActive.sort(function(a, b) {
                          let c = new Date(a.last_msg_date);
                          let d = new Date(b.last_msg_date);
                          return c-d;
		     });


                     // List the conversations 
                     var taggsArrin = [];

	             if (archivedConvNmbr == 0) {
	                 // Don't list any archived conversations
	                 var archivedCvNb = 0;

	             } else if (archivedConvNmbr != 0 && archivedConvNmbr != null) {

                         var archCount = 0;
	                 let fcnv = (archivedConvNmbr <= convArchived.length)? convArchived.length - archivedConvNmbr : 0;
	                 for (let s = fcnv; s < convArchived.length; s++) {

	                      var emptyRedFlags = (convArchived[s]['flagged'] == 1)? "cvFlagRed" : "cvFlagEmpty";
	                      if (convArchived[s]['tag'] != "") { var cvTagTxts = convArchived[s]['tag']; var cvTagAdds = "convTagAdded"; taggsArrin.push(convArchived[s]['tag']); } else { var cvTagTxts = ""; var cvTagAdds = "convTag"; }
	                      var cvDescAdds = (convArchived[s]['description'] != "")? "convDescAdded" : "convDesc";
	                      $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ s +"'><div id='archivedImg-"+ s +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[s]['conversation_id'] +"' data-archivedyesno='"+ convArchived[s]['archived'] +"' data-archdispname='"+ convArchived[s]['archived_by'] +"' data-unarchdispname='"+ convArchived[s]['unarchived_by'] +"' data-lastarchived='"+ convArchived[s]['last_archived'] +"' data-lastunarchived='"+ convArchived[s]['last_unarchived'] +"' data-convdescription='"+ convArchived[s]['description'] +"' data-convdescchangeby='"+ convArchived[s]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[s]['descriptiondate'] +"' data-tag='"+ cvTagTxts +"' data-taguntagby='"+ convArchived[s]['taguntagby'] +"' data-taguntagdate='"+ convArchived[s]['taguntagdate'] +"' data-flagged='"+ convArchived[s]['flagged'] +"' data-flagunflagby='"+ convArchived[s]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[s]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ s +"'>From: "+ convArchived[s]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ s +"'>To: "+ convArchived[s]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[s]['lastmsgdisplayname'] +":</span>"+ convArchived[s]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[s]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ s +"' class='"+ cvDescAdds +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ s +"' class='"+ cvTagAdds +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxts +"</div><div id='addArchFlag-"+ s +"' class='"+ emptyRedFlags +"' title='Click to set or remove flag.'></div></div>");
                              archCount++;
	                 }
	                 var archivedCvNb = archCount;

	             } else {

	                 for (let a = 0; a < convArchived.length; a++) {

	                      var emptyRedFlaga = (convArchived[a]['flagged'] == 1)? "cvFlagRed" : "cvFlagEmpty";
	                      if (convArchived[a]['tag'] != "") { var cvTagTxta = convArchived[a]['tag']; var cvTagAdda = "convTagAdded"; taggsArrin.push(convArchived[a]['tag']); } else { var cvTagTxta = ""; var cvTagAdda = "convTag"; }
	                      var cvDescAdda = (convArchived[a]['description'] != "")? "convDescAdded" : "convDesc";
	                      $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ a +"'><div id='archivedImg-"+ a +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[a]['conversation_id'] +"' data-archivedyesno='"+ convArchived[a]['archived'] +"' data-archdispname='"+ convArchived[a]['archived_by'] +"' data-unarchdispname='"+ convArchived[a]['unarchived_by'] +"' data-lastarchived='"+ convArchived[a]['last_archived'] +"' data-lastunarchived='"+ convArchived[a]['last_unarchived'] +"' data-convdescription='"+ convArchived[a]['description'] +"' data-convdescchangeby='"+ convArchived[a]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[a]['descriptiondate'] +"' data-tag='"+ cvTagTxta +"' data-taguntagby='"+ convArchived[a]['taguntagby'] +"' data-taguntagdate='"+ convArchived[a]['taguntagdate'] +"' data-flagged='"+ convArchived[a]['flagged'] +"' data-flagunflagby='"+ convArchived[a]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[a]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ a +"'>From: "+ convArchived[a]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ a +"'>To: "+ convArchived[a]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[a]['lastmsgdisplayname'] +":</span>"+ convArchived[a]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[a]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ a +"' class='"+ cvDescAdda +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ a +"' class='"+ cvTagAdda +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxta +"</div><div id='addArchFlag-"+ a +"' class='"+ emptyRedFlaga +"' title='Click to set or remove flag.'></div></div>");
	                 }
	                 var archivedCvNb = convArchived.length;
	             }

	             for (let t = 0; t < convActive.length; t++) {

	                  var emptyRedFlagt = (convActive[t]['flagged'] == 1)? "cvFlagRed" : "cvFlagEmpty";
	                  if (convActive[t]['tag'] != "") { var cvTagTxtt = convActive[t]['tag']; var cvTagAddt = "convTagAdded"; taggsArrin.push(convActive[t]['tag']); } else { var cvTagTxtt = ""; var cvTagAddt = "convTag"; }
	                  var cvDescAddt = (convActive[t]['description'] != "")? "convDescAdded" : "convDesc";
	                  $("#convArchAndActive").append("<div class='convsListAct convsLst' id='indActConv-"+ t +"'><div id='activeImg-"+ t +"' class='archactImg activeConvImg' data-conversationid='"+ convActive[t]['conversation_id'] +"' data-archivedyesno='"+ convActive[t]['archived'] +"' data-archdispname='"+ convActive[t]['archived_by'] +"' data-unarchdispname='"+ convActive[t]['unarchived_by'] +"' data-lastarchived='"+ convActive[t]['last_archived'] +"' data-lastunarchived='"+ convActive[t]['last_unarchived'] +"' data-convdescription='"+ convActive[t]['description'] +"' data-convdescchangeby='"+ convActive[t]['descriptionby'] +"' data-convdescchangedate='"+ convActive[t]['descriptiondate'] +"' data-tag='"+ cvTagTxtt +"' data-taguntagby='"+ convActive[t]['taguntagby'] +"' data-taguntagdate='"+ convActive[t]['taguntagdate'] +"' data-flagged='"+ convActive[t]['flagged'] +"' data-flagunflagby='"+ convActive[t]['flagunflagby'] +"' data-flagunflagdate='"+ convActive[t]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/active.svg' title='Active conversation'></div><div class='convLastMsgFrom' id='indActCvFrom-"+ t +"'>From: "+ convActive[t]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indActCvTo-"+ t +"'>To: "+ convActive[t]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convActive[t]['lastmsgdisplayname'] +":</span>"+ convActive[t]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Active conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convActive[t]['last_msg_date'] +"</div></div><div id='addActDesc-"+ t +"' class='"+ cvDescAddt +"' title='Click to add or modify description.'></div><div id='addActTag-"+ t +"' class='"+ cvTagAddt +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxtt +"</div><div id='addActFlag-"+ t +"' class='"+ emptyRedFlagt +"' title='Click to set or remove flag.'></div></div>");
	             }

                     // Remove the duplicates from the tags array
                     function uniqueElem(value, index, array) { return array.indexOf(value) === index; }
                     var taggsArr = taggsArrin.filter(uniqueElem);

	             // Add the row that specifies the number of conversations displayed
	             var totalConvNb = archivedCvNb + convActive.length;
	             $("#convArchAndActive").append("<div id='totalConvNmbr'>"+ totalConvNb +" conversations displayed (<span id='archivedCvImg' title='Archived conversations'></span>"+ archivedCvNb +"<span id='activeCvImg' title='Active conversations'></span>"+ convActive.length +" )</div>");

		     // Remove the empty display names, if any
		     $(".msgAuthorNameConv").each(function() { if ($(this).text() == ":") { $(this).remove(); } });

                     function convListContent() {

		             // Scroll to the bottom of the conversations list
		             $("#convArchAndActive").animate({scrollTop: $("#convArchAndActive").prop("scrollHeight")}, 200);

		             // Show all the content of the truncated messages when hovering over them
		             $(".convLastMsg").each(function() {
		                $(this).on("mouseenter", function() {
		                  $(this).css("-webkit-line-clamp", "none");
		                });
		                $(this).on("mouseleave", function() {
		                  $(this).css("-webkit-line-clamp", "3");
		                });
		             });

		             // Show the pop-up window for adding or modifying the conversation description
		             $('[id^="addArchDesc-"],[id^="addActDesc-"]').click(function(evt) {

		                evt.stopPropagation();
		                var conversationId = $(this).closest(".convsLst").find(".archactImg").data("conversationid");
		                var cvDesc = $(this).closest(".convsLst").find(".archactImg").data("convdescription");
		                var cvDescChangeBy = $(this).closest(".convsLst").find(".archactImg").data("convdescchangeby");
		                var cvDescChangeDate = $(this).closest(".convsLst").find(".archactImg").data("convdescchangedate");
		                var lstmsgFrom = $(this).closest(".convsLst").find(".convLastMsgFrom").text().replace("From: ", "");
		                var lstmsgTo = $(this).closest(".convsLst").find(".convLastMsgTo").text().replace("To: ", "");;

		                if (cvDescChangeBy) { var convDescTitle = "<span style='font-weight:500'>Description</span> last saved by <span style='font-weight:500;color:#365b8b;'>"+ cvDescChangeBy +"</span> at "+ cvDescChangeDate ; } else { var convDescTitle = "Add a description for this conversation:"; }
		                if (cvDesc) { var convTextContent = cvDesc; } else { var convTextContent = ""; }

		                var addDescWindow = "<div id='convDescWindow'>";
		                addDescWindow += "<div id='dragDescWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
		                addDescWindow += "<a id='closeDescWindow' title='Close this window'></a>";
		                addDescWindow += "<div id='convBetween'>"+ lstmsgFrom +"<div id='btwnNbCvTitle'></div>"+ lstmsgTo +"</div>";
		                addDescWindow += "<div id='convTitle'>"+ convDescTitle +"</div>";
		                addDescWindow += "<textarea id='descriptionText' placeholder='Eg: Second conversation with John Smith.' disabled>"+ convTextContent +"</textarea>";
		                addDescWindow += "<input type='submit' id='saveConvDesc' value='Edit'>";
		                addDescWindow += "</div>";

		                $("#content").append("<div id='recTblOverlay'></div>");
		                $("#content").append(addDescWindow);

		                var topNmDist = parseInt((window.innerHeight / 2).toFixed(2) - 180) +"px";
		                var leftNmDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
		                $("#convDescWindow").css({ "top" : topNmDist, "left" : leftNmDist });

		                $("#closeDescWindow").click(function() { $("#convDescWindow").remove(); $("#recTblOverlay").remove(); });
		                $("#recTblOverlay").click(function() { $("#convDescWindow").remove(); $("#recTblOverlay").remove(); });

			        // Make the window draggable
			        function makeMgrWndDraggable(e) {

				   window.pmdragging = {};
				   pmdragging.pageX0 = e.pageX;
				   pmdragging.pageY0 = e.pageY;
				   pmdragging.elem = $("#convDescWindow");
				   pmdragging.offset0 = $("#convDescWindow").offset();

				   function handle_dragging(e) {
				       var left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
				       var top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
				       $(pmdragging.elem).offset({top: top, left: left});
				   }

				   function handle_mouseup(e) {
				       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
				   }

				   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
			        }
			        $("#dragDescWindow").mousedown(makeMgrWndDraggable);


		                // Save the description
		                $("#saveConvDesc").click(function() {

		                   if ($(this).val() == "Save") {

		                       $("#descriptionText").prop("disabled", false);
		                       $("#descriptionText").css("background-color", "#ffffff");
		                       var descText = $("#descriptionText").val();

		                       if (/^[a-zA-Z0-9\'\.\,\)\(\/\-\s\r\n]*$/.test(descText)) {

		                            var saveConvDescUrl = OC.generateUrl("/apps/sms_relentless/user/saveconvdescription");

		                            $.ajax({
					       url: saveConvDescUrl,
					       type: 'POST',
		                               data: { 
		                                      convDescription: descText,
		                                      convId: conversationId
		                                 },
					       success: function(respupdesc) {
		                                           showAlert(respupdesc);
		                                           $("#convDescWindow").remove();
		                                           $("#recTblOverlay").remove();

		                                           // Refresh the conversations list
						           var archCvIdsc = '';
						           var actCvIdsc = '';

						           $(".convsListArch").each(function() { 
							       if ($(this).css('background-color') === "rgb(241, 224, 239)") {
						                   archCvIdsc = $(this).attr("id");
							       }
						           });

							   $(".convsListAct").each(function() {
							       if ($(this).css('background-color') === "rgb(215, 239, 239)") {
						                   actCvIdsc = $(this).attr("id");
							       }
							   });

						           $('#smstables').empty();
						           $("#conversationsshow").click();
						           setTimeout(function() { if (actCvIdsc != '') { document.getElementById(actCvIdsc).click(); } else if (archCvIdsc != '') { document.getElementById(actCvIdsc).click(); } }, 800);
		                               },
					       error: function() {
		                                           showAlert("Error while attempting to save the conversation description to the database.");
		                                           $("#convDescWindow").remove();
		                                           $("#recTblOverlay").remove();
		                               }
					    });

		                       } else {
		                               showAlert("The conversation description must contain only letters, numbers, spaces, commas (,), hyphens (-), slashes (/), periods (.), round brackets (()), single quotation marks ('), new lines, or an empty string.");
		                       }

		                   } else {

		                       $(this).attr("value", "Save");
		                       $("#descriptionText").prop("disabled", false);
		                       $("#descriptionText").css("background-color", "#ffffff");
		                   }
		                });
		             });


		             // Show the pop-up window for adding or modifying the conversation tag
		             $('[id^="addArchTag-"],[id^="addActTag-"]').click(function(ev) {

		                ev.stopPropagation();
		                var conversationIdt = $(this).closest(".convsLst").find(".archactImg").data("conversationid");
		                var cvTag = $(this).closest(".convsLst").find(".archactImg").data("tag");
		                var cvTagChangeBy = $(this).closest(".convsLst").find(".archactImg").data("taguntagby");
		                var cvTagChangeDate = $(this).closest(".convsLst").find(".archactImg").data("taguntagdate");
		                var lstmsgFromt = $(this).closest(".convsLst").find(".convLastMsgFrom").text().replace("From: ", "");
		                var lstmsgTot = $(this).closest(".convsLst").find(".convLastMsgTo").text().replace("To: ", "");;

		                if (cvTagChangeBy) { var convTagTitle = "<span style='font-weight:500'>Tag</span> last saved by <span style='font-weight:500;color:#365b8b;'>"+ cvTagChangeBy +"</span> at "+ cvTagChangeDate ; } else { var convTagTitle = "Add a tag to this conversation:"; }
		                if (cvTag) { var tagTextContent = cvTag; } else { var tagTextContent = ""; }

		                var addTagWindow = "<div id='convTagWindow'>";
		                addTagWindow += "<div id='dragTagWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
		                addTagWindow += "<a id='closeTagWindow' title='Close this window'></a>";
		                addTagWindow += "<div id='convBetween'>"+ lstmsgFromt +"<div id='btwnNbCvTitle'></div>"+ lstmsgTot +"</div>";
		                addTagWindow += "<div id='convTitle'>"+ convTagTitle +"</div>";
		                addTagWindow += "<input type='text' id='tagText' placeholder='Eg: urgent' disabled value='"+ tagTextContent +"'>";
		                addTagWindow += "<input type='submit' id='saveConvTag' value='Edit'>";
		                addTagWindow += "</div>";

		                $("#content").append("<div id='recTblOverlay'></div>");
		                $("#content").append(addTagWindow);

		                var topNmDistt = parseInt((window.innerHeight / 2).toFixed(2) - 180) +"px";
		                var leftNmDistt = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
		                $("#convTagWindow").css({ "top" : topNmDistt, "left" : leftNmDistt });

		                $("#closeTagWindow").click(function() { $("#convTagWindow").remove(); $("#recTblOverlay").remove(); });
		                $("#recTblOverlay").click(function() { $("#convTagWindow").remove(); $("#recTblOverlay").remove(); });

			        // Make the window draggable
			        function makeMgrWndDraggable(e) {

				   window.pmdragging = {};
				   pmdragging.pageX0 = e.pageX;
				   pmdragging.pageY0 = e.pageY;
				   pmdragging.elem = $("#convTagWindow");
				   pmdragging.offset0 = $("#convTagWindow").offset();

				   function handle_dragging(e) {
				       var left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
				       var top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
				       $(pmdragging.elem).offset({top: top, left: left});
				   }

				   function handle_mouseup(e) {
				       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
				   }

				   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
			        }
			        $("#dragTagWindow").mousedown(makeMgrWndDraggable);

		                // Save the tag
		                $("#saveConvTag").click(function() {

		                   if ($(this).val() == "Save") {

		                       $("#tagText").prop("disabled", false);
		                       $("#tagText").css("background-color", "#ffffff");
		                       var tagTextCt = $("#tagText").val();

		                       if (tagTextCt.length <= 100) {

		                           if (/^[a-zA-Z0-9\'\.\,\)\(\/\-\s\r\n]*$/.test(tagTextCt)) {

		                                var saveConvTagUrl = OC.generateUrl("/apps/sms_relentless/user/saveconvtag");

		                                $.ajax({
						   url: saveConvTagUrl,
						   type: 'POST',
		                                   data: { 
		                                          convTag: tagTextCt,
		                                          convId: conversationIdt
		                                          },
						   success: function(respuptag) {
		                                               showAlert(respuptag);
		                                               $("#convTagWindow").remove();
		                                               $("#recTblOverlay").remove();

		                                               // Refresh the conversations list
						               var archCvIdsc = '';
						               var actCvIdsc = '';

						               $(".convsListArch").each(function() { 
								   if ($(this).css('background-color') === "rgb(241, 224, 239)") {
						                       archCvIdsc = $(this).attr("id");
								   }
						               });

							       $(".convsListAct").each(function() {
								   if ($(this).css('background-color') === "rgb(215, 239, 239)") {
						                       actCvIdsc = $(this).attr("id");
								   }
							       });

						               $('#smstables').empty();
						               $("#conversationsshow").click();
						               setTimeout(function() { if (actCvIdsc != '') { document.getElementById(actCvIdsc).click(); } else if (archCvIdsc != '') { document.getElementById(actCvIdsc).click(); } }, 800);
		                                   },
						   error: function() {
		                                           showAlert("Error while attempting to save the conversation tag to the database.");
		                                           $("#convTagWindow").remove();
		                                           $("#recTblOverlay").remove();
		                                   }
					        });

		                           } else { showAlert("The conversation tag must contain only letters, numbers, spaces, commas (,), hyphens (-), slashes (/), periods (.), round brackets (()), single quotation marks ('), new lines, or an empty string."); }

		                       } else { showAlert("The conversation tag cannot exceed 100 characters in length."); }

		                   } else {

		                       $(this).attr("value", "Save");
		                       $("#tagText").prop("disabled", false);
		                       $("#tagText").css("background-color", "#ffffff");
		                   }
		                });
		             });


		             // Show the pop-up window for adding or modifying the conversation flag
		             $('[id^="addArchFlag-"],[id^="addActFlag-"]').click(function(ev) {

		                ev.stopPropagation();
		                var conversationIdf = $(this).closest(".convsLst").find(".archactImg").data("conversationid");
		                var cvFlag = $(this).closest(".convsLst").find(".archactImg").data("flagged");
		                var cvFlagChangeBy = $(this).closest(".convsLst").find(".archactImg").data("flagunflagby");
		                var cvFlagChangeDate = $(this).closest(".convsLst").find(".archactImg").data("flagunflagdate");
		                var lstmsgFromf = $(this).closest(".convsLst").find(".convLastMsgFrom").text().replace("From: ", "");
		                var lstmsgTof = $(this).closest(".convsLst").find(".convLastMsgTo").text().replace("To: ", "");;

		                if (cvFlag == 1) { var flgSetRem = "set"; } else if (cvFlag == 0) { var flgSetRem = "removed"; } else { var flgSetRem = "modified"; }
		                if (cvFlagChangeBy) { var convFlagTitle = "<span style='font-weight:500'>Flag</span> last "+ flgSetRem +" by <span style='font-weight:500;color:#365b8b;'>"+ cvFlagChangeBy +"</span> at "+ cvFlagChangeDate +":"; } else { var convFlagTitle = "Set a flag for this conversation:"; }

		                var addFlagWindow = "<div id='convFlagWindow'>";
		                addFlagWindow += "<div id='dragFlagWindow'><img src='/" + ctappdir + "/sms_relentless/img/dots.svg' style='cursor:grab'></div>";
		                addFlagWindow += "<a id='closeFlagWindow' title='Close this window'></a>";
		                addFlagWindow += "<div id='convBetween'>"+ lstmsgFromf +"<div id='btwnNbCvTitle'></div>"+ lstmsgTof +"</div>";
		                addFlagWindow += "<div id='convTitle'>"+ convFlagTitle +"</div>";
		                addFlagWindow += "<input type='submit' id='setConvFlag'>";
		                addFlagWindow += "</div>";

		                $("#content").append("<div id='recTblOverlay'></div>");
		                $("#content").append(addFlagWindow);

		                if (cvFlag == 1) { $("#setConvFlag").prop("value", "Remove flag"); } else { $("#setConvFlag").prop("value", "Set flag"); }

		                var topNmDistf = parseInt((window.innerHeight / 2).toFixed(2) - 180) +"px";
		                var leftNmDistf = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
		                $("#convFlagWindow").css({ "top" : topNmDistf, "left" : leftNmDistf });

		                $("#closeFlagWindow").click(function() { $("#convFlagWindow").remove(); $("#recTblOverlay").remove(); });
		                $("#recTblOverlay").click(function() { $("#convFlagWindow").remove(); $("#recTblOverlay").remove(); });

			        // Make the window draggable
			        function makeMgrWndDraggable(e) {

				   window.pmdragging = {};
				   pmdragging.pageX0 = e.pageX;
				   pmdragging.pageY0 = e.pageY;
				   pmdragging.elem = $("#convFlagWindow");
				   pmdragging.offset0 = $("#convFlagWindow").offset();

				   function handle_dragging(e) {
				       var left = pmdragging.offset0.left + (e.pageX - pmdragging.pageX0);
				       var top = pmdragging.offset0.top + (e.pageY - pmdragging.pageY0);
				       $(pmdragging.elem).offset({top: top, left: left});
				   }

				   function handle_mouseup(e) {
				       $('body').off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
				   }

				   $('body').on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
			        }
			        $("#dragFlagWindow").mousedown(makeMgrWndDraggable);

		                // Save the flag
		                $("#setConvFlag").click(function() {

		                   if ($(this).val() == "Set flag") { var convFlag = 1; } else { var convFlag = 0; }

		                   var saveConvFlagUrl = OC.generateUrl("/apps/sms_relentless/user/saveconvflag");

		                   $.ajax({
					   url: saveConvFlagUrl,
					   type: 'POST',
		                           data: { 
		                                  convFlag: convFlag,
		                                  convId: conversationIdf
		                                  },
					   success: function(respupflag) {

		                                       if (respupflag != "success") { showAlert("Error while trying to save the conversation flag to the database."); }

		                                       $("#convFlagWindow").remove();
		                                       $("#recTblOverlay").remove();

		                                       // Refresh the conversations list
					               var archCvIdsc = '';
					               var actCvIdsc = '';

					               $(".convsListArch").each(function() { 
							   if ($(this).css('background-color') === "rgb(241, 224, 239)") {
					                       archCvIdsc = $(this).attr("id");
							   }
					               });

						       $(".convsListAct").each(function() {
							   if ($(this).css('background-color') === "rgb(215, 239, 239)") {
					                       actCvIdsc = $(this).attr("id");
							   }
						       });

					               $('#smstables').empty();
					               $("#conversationsshow").click();
					               setTimeout(function() { if (actCvIdsc != '') { document.getElementById(actCvIdsc).click(); } else if (archCvIdsc != '') { document.getElementById(actCvIdsc).click(); } }, 800);
		                           },
					   error: function() {
		                                   showAlert("Error while attempting to save the conversation flag to the database.");
		                                   $("#convFlagWindow").remove();
		                                   $("#recTblOverlay").remove();
		                           }
				   });
		                });
		             });


		             // Get the messages exchanged between the current 2 phone numbers, from the database
		             function getMsgsForNmbrs(phNumberFrom, phNumberTo, conversationId, archivedConv, archivedBy, unarchivedBy, lastArchived, lastUnarchived, flagged, flagunflagby, flagunflagdate, tag, taguntagby, taguntagdate, convdescription, convdescchangeby, convdescchangedate) {

				   let getGrpConvUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedforreply");

				   $('#conversationsText').addClass('icon-loading');

				   let totalPhNmbrs = 0;

				   $.ajax({
					  method: 'POST',
					  url: getGrpConvUrl,
					  contentType: 'application/json',
				          data: JSON.stringify({ "phoneNmbrFrom": phNumberFrom, "phoneNmbrTo": phNumberTo }),
					  success: function(groupedperconv) {

						     $('#conversationsText').removeClass('icon-loading');

						     let fromtoNmbrsData = [];

						     for (let i = 0; i < groupedperconv.length; i++) {

							     if (groupedperconv[i].author_displayname) {
								 var authordnm = groupedperconv[i].author_displayname;
							     } else { 
								 var authordnm = '';
							     }

							     var sentfromnmbrarr = groupedperconv[i].from.split(": ");
							     if (sentfromnmbrarr[1]) {
							         var groupednbfrom = sentfromnmbrarr[1];
		                                             } else {
							         var groupednbfrom = sentfromnmbrarr[0];
		                                             }

							     var modmessagerec = '';
							     if (groupedperconv[i].author_displayname) {
								 modmessagerec = "<span class='msgAuthorNameGrp'>"+ groupedperconv[i].author_displayname + ":</span>" + groupedperconv[i].message;
							     } else {
							         modmessagerec = groupedperconv[i].message;
				                             }

							     if (groupedperconv[i].to.indexOf(": ") > -1) {
								 var groupednmbrtopre = groupedperconv[i].to.split(": ");
								 var groupednmbrto = groupednmbrtopre[1];
							     } else { 
								 var groupednmbrto = groupedperconv[i].to;
							     }

							     fromtoNmbrsData.push({
								       'author_displayname': authordnm,
								       'from': groupednbfrom,
								       'to': groupednmbrto,
								       'message': modmessagerec,
								       'date': groupedperconv[i].date,
								       'status': groupedperconv[i].deliveryreceipt,
								       'table': groupedperconv[i].table
							     });
						     }


						     // Remove the duplicates
						     let noDupMsgData = [];
						     $.each(fromtoNmbrsData, function(i, e) {
							    let matchingData = $.grep(noDupMsgData, function(item) {
								    return item.from == e.from && item.to == e.to && item.message == e.message && item.table == 'received' && e.table == 'sent';
							    });
							    if (matchingData.length === 0) {
								noDupMsgData.push(e);
							    }
						     });

						     let messagesPerNmbr = {};
						     let msgsNamesPerNmbr = {};
						     let msgsNmbrsNames = {};

						     let displayNamesarr = [];
						     let convData = [];

						     for (let n = 0; n < noDupMsgData.length; n++) {

							  if (noDupMsgData[n]['from'] == phNumberFrom && noDupMsgData[n]['table'] == 'sent') {

							      convData.push({
							                     'author_displayname': noDupMsgData[n]['author_displayname'],
							                     'message': noDupMsgData[n]['message'],
							                     'from': noDupMsgData[n]['from'],
							                     'to': noDupMsgData[n]['to'],
							                     'date': noDupMsgData[n]['date'],
							                     'direction': 'sent_from',
					                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
							                     'table': noDupMsgData[n]['table']
							      });

							  } else if (noDupMsgData[n]['to'] == phNumberFrom && noDupMsgData[n]['table'] == 'sent') {

							      convData.push({
							                     'author_displayname': noDupMsgData[n]['author_displayname'],
							                     'message': noDupMsgData[n]['message'],
							                     'from': noDupMsgData[n]['from'],
							                     'to': noDupMsgData[n]['to'],
							                     'date': noDupMsgData[n]['date'],
							                     'direction': 'sent_to',
					                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
							                     'table': noDupMsgData[n]['table']
							      });


							  } else if (noDupMsgData[n]['from'] == phNumberFrom && noDupMsgData[n]['table'] == 'received') {

							      convData.push({
							                     'author_displayname': noDupMsgData[n]['author_displayname'],
							                     'message': noDupMsgData[n]['message'],
							                     'from': noDupMsgData[n]['from'],
							                     'to': noDupMsgData[n]['to'],
							                     'date': noDupMsgData[n]['date'],
							                     'direction': 'received_from',
					                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
							                     'table': noDupMsgData[n]['table']
							      });

							  } else if (noDupMsgData[n]['to'] == phNumberFrom && noDupMsgData[n]['table'] == 'received') {

							      convData.push({
							                     'author_displayname': noDupMsgData[n]['author_displayname'],
							                     'message': noDupMsgData[n]['message'],
							                     'from': noDupMsgData[n]['from'],
							                     'to': noDupMsgData[n]['to'],
							                     'date': noDupMsgData[n]['date'],
							                     'direction': 'received_on',
					                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
							                     'table': noDupMsgData[n]['table']
							      });
							  }
						     }

						     // Sort messages by date
						     convData.sort(function(a, b) {
		                                        return new Date(b.date) - new Date(a.date);
						     });

						     // Collect the display names of the users that sent messages from the current numbers
						     let selectedNames = [];
						     let displayNames = '';
						     for (let v = 0; v < convData.length; v++) {
							  if (selectedNames.indexOf(convData[v]['author_displayname']) == -1) { 
							      selectedNames.push(convData[v]['author_displayname']);
							      displayNames += "<div id='diplNm_"+ phNumberFrom +"_"+ v +"' class='dispNameList' name='"+ convData[v]['author_displayname'] +"'>"+ convData[v]['author_displayname'] +"</div>";
							  }
						     }
						     displayNames += "<div id='diplNmAllMsgcv' class='dispNameListAll' title='Show all the messages exchanged between the current 2 phone numbers.'>All messages</div>";

						     // Store the display names for the current numbers, to be able to see them later
						     let ctPhNumber = phNumberFrom;
						     msgsNamesPerNmbr[ctPhNumber] = displayNames;

						     // Store the messages sent by each user, to be able to see them later when clicking on the user's name
						     for (let h = 0; h < selectedNames.length; h++) {

							  let rowMessageArrpn = [];

							  for (let b = 0; b < convData.length; b++) {

							       if (selectedNames[h] == convData[b]['author_displayname']) {

								   if (convData[b]['direction'] == 'sent_from') {
		                                                       if (convData[b]['status']) {
									   if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							                       if (convData[b]['status'].indexOf("undelivered") > -1) {
									           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                               } else {
									           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                               }
									   } else {
									       var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
									   }
								       } else {
									   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                       }
								       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
								   } else if (convData[b]['direction'] == 'sent_to') {
		                                                       if (convData[b]['status']) {
									   if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							                       if (convData[b]['status'].indexOf("undelivered") > -1) {
									           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                               } else {
									           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                               }
									   } else {
									       var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
									   }
		                                                       } else {
		                                                           var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                       }
								       rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
								   } else if (convData[b]['direction'] == 'received_from') {
								       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
								   } else if (convData[b]['direction'] == 'received_on') {
								       rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
							           }
							       }
							  }
							  let crtNmber = phNumberFrom;
							  let crtName = selectedNames[h];
							  msgsNmbrsNames[crtNmber] = msgsNmbrsNames[crtNmber] || {};
				                          msgsNmbrsNames[crtNmber][crtName] = rowMessageArrpn;
						     }

				                     // The number of messages to be loaded by default
				                     var nmbTblDefault = 50;

				                     // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
				                     if (convData.length > nmbTblDefault) {
				                         $("#loadMoreMsgs").css("display", "block");
				                         var nmbToBeLoaded = nmbTblDefault;
				                     } else { var nmbToBeLoaded = convData.length; }

						     let rowMessageArr = [];

						     for (var m = nmbToBeLoaded - 1; m >= 0; m--) {

							  if (convData[m]['direction'] == 'sent_from') {
							      if (convData[m]['status']) {
								  if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
						                      if (convData[m]['status'].indexOf("undelivered") > -1) {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                      } else {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                      }
								  } else {
								      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
								  }
							      } else {
							          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							      }
							      rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

							  } else if (convData[m]['direction'] == 'sent_to') {
		                                              if (convData[m]['status']) {
								  if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
						                      if (convData[m]['status'].indexOf("undelivered") > -1) {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                      } else {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                      }
								  } else {
								      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
								  }
							      } else {
							          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							      }
							      rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

							  } else if (convData[m]['direction'] == 'received_from') {

							      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

							  } else if (convData[m]['direction'] == 'received_on') {

							      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
							  }
						     }

						     let convDataPerNmbr = rowMessageArr.join("");


		                                     if (archivedConv == 1) {
		                                         var archiveImg = "unarchiveConv";
		                                         var archTitle = "Unarchive this conversation.";
		                                         var removeConvImg = "removeConv";
		                                         var removeConvTitle = "Permanently delete all the messages in this conversation.";
		                                         var archornottitle = "Archived Conversation";
		                                     } else {
		                                         var archiveImg = "archiveConv";
		                                         var archTitle = "Archive this conversation.";
		                                         var removeConvImg = "removeConvGrey";
		                                         var removeConvTitle = "Only archived conversations can be deleted.";
		                                         var archornottitle = "Active Conversation";
		                                     }

		                                     if (archivedBy == null || archivedBy == '') {
		                                         var lastArchUnarch = "<font style='color:#178e84;font-weight:600;'>Active Conversation</font> | "+ phNumberFrom +"<div id='betweenNmbrs'></div>"+ phNumberTo +"";
		                                     } else if (archivedConv == 1 && archivedBy && lastArchived) {
		                                         var lastArchUnarch = "<font style='color:#9e6897;font-weight:600;'>Archived Conversation</font> | "+ phNumberFrom +"<div id='betweenNmbrs'></div>"+ phNumberTo +" | Last archived by <font style='color:#365b8b;font-weight:600;'>"+ archivedBy + "</font> on "+ lastArchived;
		                                     } else if (archivedConv == 0 && unarchivedBy && lastUnarchived) {
		                                         var lastArchUnarch = "<font style='color:#178e84;font-weight:600;'>Active Conversation</font> | "+ phNumberFrom +"<div id='betweenNmbrs'></div>"+ phNumberTo +" | Last unarchived by <font style='color:#365b8b;font-weight:600;'>"+ unarchivedBy + "</font> on "+ lastUnarchived;
		                                     }

		                                     if (convdescription) {
		                                         var cvDescAdded = "convDescAddedCvt";
		                                         var cvDescText = convdescription + " (<span style='font-weight:500'>Description</span> last saved by <span style='font-weight:500;color:#365b8b;'>"+ convdescchangeby +"</span> at "+ convdescchangedate +".)"; 
		                                     } else { 
		                                         var cvDescAdded = "convDescCvt"; var cvDescText = ""; 
		                                     }

		                                     if (tag) { 
		                                         var cvTagAdded = "convTagAddedCvt"; 
		                                         var cvTagText = "<span style='font-size:14px;font-weight:500;color:#39608a;'>"+ tag + "</span> (<span style='font-weight:500'>Tag</span> last saved by <span style='font-weight:500;color:#365b8b;'>"+ taguntagby +"</span> at "+ taguntagdate +".)"; 
		                                     } else { 
		                                         var cvTagAdded = "convTagCvt"; var cvTagText = ""; 
		                                     }

		                                     if (flagged == 1) { 
		                                         var cvFlagAdded = "cvFlagRedCvt"; 
		                                         var cvFlagText = "(<span style='font-weight:500'>Flag</span> last set by <span style='font-weight:500;color:#365b8b;'>"+ flagunflagby +"</span> at "+ flagunflagdate +".)"; 
		                                     } else if (flagged == 0) { 
		                                         var cvFlagAdded = "cvFlagEmptyCvt"; 
		                                         var cvFlagText = "(<span style='font-weight:500'>Flag</span> last removed by <span style='font-weight:500;color:#365b8b;'>"+ flagunflagby +"</span> at "+ flagunflagdate +".)"; 
		                                     } else { 
		                                         var cvFlagAdded = "cvFlagEmptyCvt";
		                                         var cvFlagText = "";
		                                     }

				                     $("#conversationsText").empty();
		                                     $("#conversationsText").append("<div id='convTextHeader'><table id='convTextTbl'><tr><td style='width:5% !important'><div id='archUnarchAct' class='"+ archiveImg +"' title='"+ archTitle +"'></div></td><td id='convBarTitle'><div id='titleFirstRow'>"+ lastArchUnarch +"</div><div id='titleSecRow'><div id='titleConvDesc'><div class='"+ cvDescAdded +"' title='Conversation description'></div><div class='cvDescContent'>"+ cvDescText +"</div></div><div id='titleConvTag'><div class='"+ cvTagAdded +"' title='Conversation tag'></div><div class='cvTagContent'>"+ cvTagText +"</div></div><div id='titleConvFlag'><div class='"+ cvFlagAdded +"' title='Conversation flag'></div><div class='cvFlagContent'>"+ cvFlagText +"</div></div><div id='titleConvDelete'><div id='deleteAllMsgConv' title='Permanently delete the entire conversation from the database'></div><div id='deleteMsgsCvText'>Permanently delete from the database all the messages included in this conversation.</div></div></div><div id='expandTitle'><div id='expandTitleImg'></div></div></td><td style='width:5% !important'><div id='convParticipants' class='convPart' title='Show the list with conversation participants.'></div></td></tr></table></div><div id='grpdbynamelstcv'></div><div id='loadMoreMsgs' title='Click to load older messages.'>Load more messages</div><div id='loadMoreMsgsusr' title='Click to load older messages.'>Load more messages</div>");
		                                     $("#conversationsText").append("<div id='loadMoreMsgs' title='Click to load older messages.'>Load more messages</div><div id='loadMoreMsgsusr' title='Click to load older messages.'>Load more messages</div><div id='convListRowCell'></div>");

		                                     var allmsgconv = "<div id='sendMsgReplySec'><table id='sendMsgConvSec'><tr><td><div id='fromPhnNmbrCv'>From: <select id='selectFromNbConv'></select></div><div id='toPhnNmbrCv'>To: <select id='selectToNbConv'></select></div></td></tr>";
		                                     allmsgconv += "<tr><td><textarea id='sendMsgConvTextSec' placeholder='Enter a message here, then press Send SMS.'></textarea></td></tr></table>";
		                                     allmsgconv += "<div id='sendMsgBtnConv'>Send SMS</div></div>";
		                                     allmsgconv += "<div id='expToSendReply' title='Expand to send a message'><img id='expandWindowRplSec' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div>";

		                                     $("#conversationsText").append(allmsgconv);

				                     $("#convListRowCell").append(convDataPerNmbr);

				                     if (convData.length > nmbTblDefault) {
				                         $("#loadMoreMsgs").css("display", "block");
				                     }

		                                     $("#sendMsgConvSec").css("width", $("#conversationsText").width() - 20);
		                                     $("#sendMsgConvTextSec").css("width", $("#conversationsText").width() - 20);

		                                     // Expand the conversation title bar to see the conversation details
		                                     $("#expandTitleImg").click(function() {
		                                        if ($("#titleSecRow").is(":visible")) {
		                                            $("#titleSecRow").css("display", "none"); 
		                                            $("#expandTitleImg").css("background-image", "url('/" + ctappdir + "/sms_relentless/img/arrowDown_small.svg')");
		                                            $("#expandTitleImg").prop("title", "Expand to see conversation details");
		                                        } else {
		                                            $("#titleSecRow").css("display", "block"); 
		                                            $("#expandTitleImg").css("background-image", "url('/" + ctappdir + "/sms_relentless/img/arrowUp_small.svg')");
		                                            $("#expandTitleImg").prop("title", "Collapse");
		                                        }
		                                     });

		                                     // Delete all the messages in a conversation
		                                     $("#deleteAllMsgConv").click(function() {

							  confirmAlert("Are you sure that you want to permanently delete from the database all the messages included in this conversation ? This action cannot be undone.");

							  $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); return; });

							  $("#confirmOk").click(function() {

		                                              confirmAlert("Confirm that you want to permanently delete from the database all the messages included in this conversation !");

							      $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); return; });

							      $("#confirmOk").click(function() {

								 $("#alertMsgOverlay").remove();
								 $("#alertConfMessage").remove();

								 var deleteConvUrl = OC.generateUrl("/apps/sms_relentless/user/removeconvmsgs");
								 $('#smstables').addClass('icon-loading');

								 $.ajax({
								      url: deleteConvUrl,
								      type: "POST",
								      data: { "conversationId": conversationId },
								      success: function(delcvmsgres) {
						                                 $('#smstables').removeClass('icon-loading');
								                 if (delcvmsgres == "success") {
								                     showAlert("The messages included in this conversation have been deleted successfully !");
								                     $('#conversationsshow').click();
								                 } else if (delcvmsgres == "not allowed") { 
								                     showAlert("Only admins can delete messages !");
								                 } else {
								                     showAlert("There was an error while deleting the messages included in this conversation !");
								                 }
								      },
								      error: function() {
								                 $('#smstables').removeClass('icon-loading');
								                 showAlert("There was an error while attempting to delete the messages included in this conversation !");
								      }
								 });
							      });
							  });
		                                     });


						     // Expand the reply section when clicking on the arrow, to be able to send replies
						     $("#expToSendReply").unbind("click");
						     $("#expToSendReply").click(function() {

							if ($("#expandWindowRplSec").attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
							    $("#sendMsgReplySec").css("display", "block");
		                                            $("#conversationsText").animate({scrollTop: $("#conversationsText").prop("scrollHeight")}, 100);
							    $("#expandWindowRplSec").attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
							    $(this).attr('title', 'Collapse');
							} else {
							    $("#sendMsgReplySec").css("display", "none");
							    $("#expandWindowRplSec").attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg');
							    $(this).attr('title', 'Expand to send a reply');
							}
						     });

						     // Append the available phone numbers to the From drop-down list
						     var availPhoneNmbrs = [];
						     $("#currentsmsnmbrs .optselectsmsnb").each(function() {
							var crtphnmbr = $(this).attr("value");
							if (crtphnmbr != "") { availPhoneNmbrs.push(crtphnmbr); }
						     });

						     if (availPhoneNmbrs.length > 0) {
		                                         var extcheck = true;
							 var avphopt = "";
							 var avphoptto = "";
							 for (let d = 0; d < availPhoneNmbrs.length; d++) {
							      if (availPhoneNmbrs[d].indexOf(phNumberTo) === -1) {
								  avphopt += "<option value='"+ availPhoneNmbrs[d] +"'>"+ availPhoneNmbrs[d] +"</option>";
							      } else {
								  avphopt += "<option value='"+ availPhoneNmbrs[d] +"' selected>"+ availPhoneNmbrs[d] +"</option>";
		                                                  extcheck = false;
							      }
		                                              if (availPhoneNmbrs[d].indexOf("+") > -1) {
							          avphoptto += "<option value='"+ availPhoneNmbrs[d] +"'>"+ availPhoneNmbrs[d] +"</option>";
		                                              }
							 }

							 $("#selectFromNbConv").append(avphopt);
							 if (extcheck) {
							     avphoptto += "<option value='"+ phNumberTo +"' selected>"+ phNumberTo +"</option>";
							 } else { avphoptto += "<option value='"+ phNumberFrom +"' selected>"+ phNumberFrom +"</option>"; }
							 $("#selectToNbConv").append(avphoptto);

		                                         // Warn of beginning/continuing a different conversation if sending the message from/to a number different from the numbers that participate in the conversation
		                                         $("#selectFromNbConv").change(function() {
		                                            var selNmbr = $(this).val().split(": ")[1];
		                                            if (selNmbr != phNumberTo && selNmbr != phNumberFrom) { showAlert("You have selected a phone number that is different from the numbers that participate in this conversation. If you send a message from/to a different number than the 2 numbers that participate in the current conversation, you will begin or continue a different conversation. Thus, your message won't appear in the current conversation, but in a different one."); }
		                                         });

		                                         $("#selectToNbConv").change(function() {
		                                            if ($(this).val().indexOf(": ") > -1) {
		                                                var selNmbrto = $(this).val().split(": ")[1];
		                                            } else { var selNmbrto = $(this).val(); }
		                                            if (selNmbrto != phNumberFrom && selNmbrto != phNumberTo) { showAlert("You have selected a phone number that is different from the numbers that participate in this conversation. If you send a message from/to a different number than the 2 numbers that participate in the current conversation, you will begin or continue a different conversation. Thus, your message won't appear in the current conversation, but in a different one."); }
		                                         });

						     } else { 
		                                         $("#selectFromNbConv").append("<option value='' selected>No IDs</option>");
		                                         $("#selectToNbConv").append("<option value='"+ phNumberFrom +"' selected>"+ phNumberFrom +"</option>");
		                                     }

						     // Send a message from the reply section
						     $("#sendMsgBtnConv").click(function() {

							$("#sendMsgConvSec,#sendMsgBtnConv").addClass('icon-loading');
							var msgToSend = $("#sendMsgConvTextSec").val();
							var selectedid = $("#selectFromNbConv").val();
							var toNumberinit = $("#selectToNbConv").val().split("+");
		                                        var toNumber = "+" + toNumberinit[1];
							var receiversNumbers = [toNumber];

							if (selectedid != '') {

							    var sendersplit = selectedid.split(":");
							    var providercap = sendersplit[0];
							    var provsec = sendersplit[1];

							    if (/[a-zA-Z]/.test(provsec)) {
								var alphanumcheck = true;
							    } else { var alphanumcheck = false; }

							    if (providercap == 'Tx' && alphanumcheck == false) {  
								var senderproc = selectedid.replace(/[^0-9]/g, "");
								var selectedsender = "+" + senderproc;
								var providerUsed = "telnyx";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
							    } else if (providercap == 'Pl' && alphanumcheck == false) {
								var selectedsender = selectedid.replace(/[^0-9]/g, "");
								var providerUsed = "plivo";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
							    } else if (providercap == 'Tw' && alphanumcheck == false) {  
								var senderproc = selectedid.replace(/[^0-9]/g, "");
								var selectedsender = "+" + senderproc;
								var providerUsed = "twilio";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
							    } else if (providercap == 'Fl' && alphanumcheck == false) {  
								var senderproc = selectedid.replace(/[^0-9]/g, "");
								var selectedsender = "+" + senderproc;
								var providerUsed = "flowroute";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
							    } else if (providercap == 'Tx' && alphanumcheck == true) {
								var selectedsender = provsec;
								var providerUsed = "telnyx";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
							    } else if (providercap == 'Pl' && alphanumcheck == true) {
								var selectedsender = provsec;
								var providerUsed = "plivo";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
							    } else if (providercap == 'Tw' && alphanumcheck == true) {
								var selectedsender = provsec;
								var providerUsed = "twilio";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstwil");
							    } else if (providercap == 'Fl' && alphanumcheck == true) {
								var selectedsender = provsec;
								var providerUsed = "flowroute";
								var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsflow");
							    }

							  var uploadedtomms = [];

							    if (msgToSend != '') {

								  $.ajax({
								     url: relbaseUrl,
								     type: "POST",
								     data: {
									   receiversPhoneNbs: receiversNumbers,
									   fromsender: selectedsender,
									   waitinterval: 1000,
									   sentsmstext: msgToSend,
									   ismms: 0,
									   mmsfiles: uploadedtomms
									 },
								     success: function(displayname) {

								           var tzdate = new Date();
								           var presDatest = new Date(tzdate.getTime() - (tzdate.getTimezoneOffset() * 60000)).toJSON();
								           var presDatedb = presDatest.split(".")[0];
								           var presDatesc = presDatedb.split("T");
								           var presDate = presDatesc[0] +" "+ presDatesc[1];
								           var sentMessageStatus = '';

								           if (displayname) {
								               var msgToSendproc = "<span class='msgAuthorNameGrp'>"+ displayname + ":</span>" + msgToSend; 
								           } else { var msgToSendproc = msgToSend; }

								           $("#convListRowCell").append("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ selectedsender +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ receiversNumbers[0] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ msgToSendproc +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ presDate +"</div><div class='sentMssgStatus'>"+ sentMessageStatus +"</div></div>");

								           // Scroll down to the bottom of the window
								           $("#conversationsText").animate({scrollTop:$("#conversationsText").prop("scrollHeight")},200);

								           $("#sendMsgConvSec,#sendMsgBtnConv").removeClass('icon-loading');
								     },
								     error: function() {
									   showAlert("Error while sending the message. You can check your Nextcloud log to find out more about this issue.");
									   $("#sendMsgConvSec,#sendMsgBtnConv").removeClass('icon-loading');
								     }
								  });
							    } else {
								    showAlert("Please enter a message in the text box!");
								    $("#sendMsgConvSec,#sendMsgBtnConv").removeClass('icon-loading');
							    }
							} else {
								showAlert("Please choose a Sender ID from the 'From' drop-down list!");
								$("#sendMsgConvSec,#sendMsgBtnConv").removeClass('icon-loading');
							}
						     });


		                                     // Show the list with conversation participants
				                     $("#grpdbynamelstcv").empty();
		                                     $("#grpdbynamelstcv").append("<div style='display:block;position:relative;width:100%;height:0;'><div id='closeConvPart' title='Close the list of conversation participants.'></div></div>");
				                     $("#grpdbynamelstcv").append(displayNames);

		                                     $("#convParticipants").click(function() { 
		                                        if ($("#grpdbynamelstcv").is(":visible")) {
		                                            $("#grpdbynamelstcv").css("display", "none");
		                                            $("#convParticipants").removeClass("convPartRed");
		                                            $("#convParticipants").addClass("convPart");
		                                            $("#convParticipants").prop("title", "Show the list with conversation participants.");
		                                        } else { 
		                                            $("#grpdbynamelstcv").css("display", "block");
		                                            $("#convParticipants").removeClass("convPart");
		                                            $("#convParticipants").addClass("convPartRed");
		                                            $("#convParticipants").prop("title", "Close the list with conversation participants.");

				                            $("#closeConvPart").click(function() {
				                               $("#grpdbynamelstcv").css("display", "none");
				                               $("#convParticipants").removeClass("convPartRed");
				                               $("#convParticipants").addClass("convPart");
				                               $("#convParticipants").prop("title", "Show the list with conversation participants.");
				                            });
		                                        }
		                                     });


						     // Store the messages for the current From number, to be able to see them later
						     let rowMessageArrcpt = [];
						     for (let m = 0; m < convData.length; m++) {

							  if (convData[m]['direction'] == 'sent_from') {
							      if (convData[m]['status']) {
								  if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
						                      if (convData[m]['status'].indexOf("undelivered") > -1) {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                      } else {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                      }
								  } else {
								      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
								  }
							      } else {
							          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							      }
							      rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

							  } else if (convData[m]['direction'] == 'sent_to') {
							      if (convData[m]['status']) {
								  if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
						                      if (convData[m]['status'].indexOf("undelivered") > -1) {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                      } else {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                      }
								  } else {
								      var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
								  }
							      } else {
							          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							      }
							      rowMessageArrcpt.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

							  } else if (convData[m]['direction'] == 'received_from') {

							      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

							  } else if (convData[m]['direction'] == 'received_on') {

							      rowMessageArrcpt.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
							  }
						     }

						     messagesPerNmbr[phNumberFrom] = rowMessageArrcpt;

				                     // Scroll down to the bottom of the window
			                             $("#conversationsText").animate({scrollTop: $("#conversationsText").prop("scrollHeight")},200);

				                     // Load more messages
				                     var clickNmb = 0;
		                                     $("#loadMoreMsgs").unbind("click");
				                     $("#loadMoreMsgs").click(function() {

				                         clickNmb++;

				                         var crefnb = (clickNmb + 1) * nmbToBeLoaded;

				                         if (crefnb > convData.length) {
				                             var nmbmsg = convData.length - 1;
				                             $("#loadMoreMsgs").css("display", "none");
				                         } else { 
				                             var nmbmsg = crefnb - 1;
				                         }

				                         let rowMessageArrAdd = [];

				                         for (let m = nmbmsg; m >= clickNmb * nmbToBeLoaded; m--) {

							      if (convData[m]['direction'] == 'sent_from') {
							          if (convData[m]['status']) {
								      if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
						                          if (convData[m]['status'].indexOf("undelivered") > -1) {
								              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                          } else {
								              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                          }
								      } else {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
								      }
							          } else {
							              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							          }    
							          rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

							      } else if (convData[m]['direction'] == 'sent_to') {
							          if (convData[m]['status']) {
								      if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
						                          if (convData[m]['status'].indexOf("undelivered") > -1) {
								              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                                                          } else {
								              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                                                          }
								      } else {
								          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
								      }
							          } else {
							              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
							          }
							          rowMessageArrAdd.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

							      } else if (convData[m]['direction'] == 'received_from') {

								  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

							      } else if (convData[m]['direction'] == 'received_on') {

								  rowMessageArrAdd.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
							      }
				                         }

							 let convDataPerNmbrad = rowMessageArrAdd.join("");

				                         let scrlheight = $("#convListRowCell").height();
				                         $("#convListRowCell").prepend(convDataPerNmbrad);
		                                         $("#conversationsText").animate({scrollTop: $("#convListRowCell").height() - scrlheight}, 0);

				                     });


						     // Show the messages sent by each user whose name is clicked
						     $('[id*="diplNm_"]').click(function() {

							 let crntNmbr = $(this).attr("id").split("_")[1];
							 let crntDisName = $(this).attr("name");                               
				                         $("#loadMoreMsgs").css("display", "none");

				                         let convDataprn = [];
				                         $.each(msgsNmbrsNames[crntNmbr][crntDisName], function(index, item) {
				                                convDataprn.push(item);
				                         });

				                         // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
				                         if (convDataprn.length > nmbTblDefault) {
				                             $("#loadMoreMsgsusr").css("display", "block");
				                             let nmbToBeLoaded = nmbTblDefault;
				                         } else {
				                             $("#loadMoreMsgsusr").css("display", "none");
				                             let nmbToBeLoaded = convDataprn.length;
				                         }

							 let rowMessageArrprnst = [];

							 for (let n = nmbToBeLoaded - 1; n >= 0; n--) {
				                              rowMessageArrprnst.push(convDataprn[n]);
							 }

							 let convDataPerNmbrprnst = rowMessageArrprnst.join("");

		                                         $("#convListRowCell").empty();
		                                         $("#convListRowCell").append(convDataPerNmbrprnst);

				                         // Scroll down to the bottom of the window
				                         $("#conversationsText").animate({scrollTop: $("#conversationsText").prop("scrollHeight")}, 200);

				                         // Load more messages
				                         var clckNb = 0;
				                         $("#loadMoreMsgsusr").unbind("click");
				                         $("#loadMoreMsgsusr").click(function() {

				                             clckNb++;
				                             var crefnb = (clckNb + 1) * nmbToBeLoaded;

				                             $("#loadMoreMsgs").css("display", "none");

				                             if (crefnb > convDataprn.length) {
				                                 var nmbmsg = convDataprn.length - 1;
				                                 $("#loadMoreMsgsusr").css("display", "none");
				                             } else { 
				                                 var nmbmsg = crefnb - 1;
				                                 $("#loadMoreMsgsusr").css("display", "block");
				                             }

				                             var rowMessageArrAddst = [];

				                             for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

				                                  rowMessageArrAddst.push(convDataprn[q]);
				                             }

							     var convDataPerNmbradst = rowMessageArrAddst.join("");

				                             let scrlheight = $("#convListRowCell").height();
				                             $("#convListRowCell").prepend(convDataPerNmbradst);

		                                             $("#conversationsText").animate({scrollTop: $("#convListRowCell").height() - scrlheight }, 0);
				                         });


							 $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
							 $("#diplNmAllMsgcv").css("color", "#04957b");
							 $(this).css("color", "#1b8efe");
						     });


						     // Show again all the messages exchanged between the current 2 phone numbers
						     $("#diplNmAllMsgcv").click(function() {

				                         $("#loadMoreMsgsusr").css("display", "none");

				                         let convDataprn = [];
				                         $.each(messagesPerNmbr[phNumberFrom], function(index, item) {
				                                convDataprn.push(item);
				                         });

				                         // If the total number of messages is greater than the default number of messages to display, show the 'Load more messages' button
				                         if (convDataprn.length > nmbTblDefault) {
				                             $("#loadMoreMsgs").css("display", "block");
				                             let nmbToBeLoaded = nmbTblDefault;
				                         } else {
				                             $("#loadMoreMsgs").css("display", "none");
				                             let nmbToBeLoaded = convDataprn.length;
				                         }

							 let rowMessageArrprnst = [];

							 for (let n = nmbToBeLoaded - 1; n >= 0; n--) {
				                              rowMessageArrprnst.push(convDataprn[n]);
							 }

							 let convDataPerNmbrprnst = rowMessageArrprnst.join("");

				                         $("#convListRowCell").empty();
				                         $("#convListRowCell").append(convDataPerNmbrprnst);

				                         // Scroll down to the bottom of the window
				                         $("#conversationsText").animate({scrollTop: $("#conversationsText").prop("scrollHeight")}, 200);


				                         // Load more messages
				                         let clckNb = 0;
				                         $("#loadMoreMsgs").unbind("click");
				                         $("#loadMoreMsgs").click(function() {

				                             clckNb++;
				                             var crefnb = (clckNb + 1) * nmbToBeLoaded;

				                             $("#loadMoreMsgsusr").css("display", "none");

				                             if (crefnb > convDataprn.length) {
				                                 var nmbmsg = convDataprn.length - 1;
				                                 $("#loadMoreMsgs").css("display", "none");
				                             } else {
				                                 var nmbmsg = crefnb - 1;
				                                 $("#loadMoreMsgs").css("display", "block");
				                             }

				                             let rowMessageArrAddst = [];

				                             for (var q = nmbmsg; q >= clckNb * nmbToBeLoaded; q--) {

				                                  rowMessageArrAddst.push(convDataprn[q]);
				                             }

							     let convDataPerNmbradst = rowMessageArrAddst.join("");

				                             let scrlheight = $("#convListRowCell").height();
				                             $("#convListRowCell").prepend(convDataPerNmbradst);

		                                             $("#conversationsText").animate({scrollTop: $("#convListRowCell").height() - scrlheight }, 0);

				                         });

							 $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
							 $("#diplNmAllMsgcv").css("color", "#04957b");
							 $(this).css("color", "#04c6a4");

						     });


						     // Show the scroll-up arrow
						     $("#conversationsText").scroll(function() {
							if ($(this).scrollTop() > 900) {
							      $('#upArrow').fadeIn();
							} else {
							      $('#upArrow').fadeOut();
							}
						     });

						     $("#upArrow").click(function(e) {
							$("#conversationsText").animate({scrollTop: 0}, 400);
						     });


						     // Archive/Unarchive the current conversation
						     $("#archUnarchAct").click(function() {

		                                        if (archivedConv == 1) {

							    confirmAlert("Do you really want to <b>unarchive</b> this conversation ?");

							    $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

							    $("#confirmOk").click(function() {

							       $("#alertMsgOverlay").remove();
							       $("#alertConfMessage").remove();

							       var unarchiveUrl = OC.generateUrl("/apps/sms_relentless/user/unarchiveconv");
		                                               $('#smstables').addClass('icon-loading');

							       $.ajax({
								  url: unarchiveUrl,
		                                                  type: "POST",
								  data: { "conversationId": conversationId },
								  success: function(respunarch) {

								              if (respunarch == "success") {

								                  $('#smstables').removeClass('icon-loading');

		                                                                  // Refresh the conversations list and the current conversation
										  $('#smstables').empty();
										  $("#conversationsshow").click();

		                                                                  setTimeout(function() {
										     $(".convsListAct").each(function() {
											 if ($(this).find('[id^="activeImg-"]').data("conversationid") == conversationId) {
											     let actCvIda = $(this).attr("id");
		                                                                             document.getElementById(actCvIda).click();
											 }
										     });
		                                                                  }, 800);

								              } else {
								                  showAlert("There was an error while unarchiving the conversation !");
								              }
								  },
								  error: function() {
								              showAlert("Error while attempting to unarchive the conversation.");
		                                                              $('#smstables').removeClass('icon-loading');
								  }
							       });
							    });

		                                        } else {

							    confirmAlert("Do you really want to <b>archive</b> this conversation ?");

							    $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

							    $("#confirmOk").click(function() {

							       $("#alertMsgOverlay").remove();
							       $("#alertConfMessage").remove();

							       var archiveUrl = OC.generateUrl("/apps/sms_relentless/user/archiveconv");
		                                               $('#smstables').addClass('icon-loading');

							       $.ajax({
								  url: archiveUrl,
		                                                  type: "POST",
								  data: { "conversationId": conversationId },
								  success: function(resparch) {

								              if (resparch == "success") {

								                  $('#smstables').removeClass('icon-loading');

		                                                                  // Refresh the conversations list and the current conversation
										  $('#smstables').empty();
										  $("#conversationsshow").click();

		                                                                  setTimeout(function() {
										     $(".convsListArch").each(function() {
											 if ($(this).find('[id^="archivedImg-"]').data("conversationid") == conversationId) {
											     let actCvIdb = $(this).attr("id");
		                                                                             document.getElementById(actCvIdb).click();
											 }
										     });
		                                                                  }, 800);

								              } else {
								                  showAlert("There was an error while archiving the conversation !");
								              }
								  },
								  error: function() {
								              showAlert("Error while attempting to archive the conversation.");
		                                                              $('#smstables').removeClass('icon-loading');
								  }
							       });
							    });
		                                        }
						     });

					  },
					  error: function() {
				                     showAlert("Error while attempting to get conversation messages from the database!");
						     $('#listAllMsgsConv').removeClass('icon-loading');
					  }
				   });
		             }

		             $('[id^="indArchConv-"]').click(function() {

		                $(".convsListArch").each(function(){ $(this).css("background-color", "rgb(252, 245, 251)"); });
		                $(".convsListAct").each(function(){ $(this).css("background-color", "rgb(239, 252, 252)"); });
		                $(this).css("background-color", "rgb(241, 224, 239)");

		                let crtordnmbr = $(this).attr("id").replace("indArchConv-", "");
		                let phnNmbrFrom = $("#indArchCvFrom-"+ crtordnmbr).text().split(": ")[1];
		                let phnNmbrTo = $("#indArchCvTo-"+ crtordnmbr).text().split(": ")[1];
		                let conversationId = $(this).find('[id^="archivedImg-"]').data("conversationid");
		                let archivedConv = $(this).find('[id^="archivedImg-"]').data("archivedyesno");
		                let archivedBy = $(this).find('[id^="archivedImg-"]').data("archdispname");
		                let unarchivedBy = $(this).find('[id^="archivedImg-"]').data("unarchdispname");
		                let lastArchived = $(this).find('[id^="archivedImg-"]').data("lastarchived");
		                let lastUnarchived = $(this).find('[id^="archivedImg-"]').data("lastunarchived");
		                let flagged = $(this).find('[id^="archivedImg-"]').data("flagged");
		                let flagunflagby = $(this).find('[id^="archivedImg-"]').data("flagunflagby");
		                let flagunflagdate = $(this).find('[id^="archivedImg-"]').data("flagunflagdate");
		                let tag = $(this).find('[id^="archivedImg-"]').data("tag");
		                let taguntagby = $(this).find('[id^="archivedImg-"]').data("taguntagby");
		                let taguntagdate = $(this).find('[id^="archivedImg-"]').data("taguntagdate");
		                let convdescription = $(this).find('[id^="archivedImg-"]').data("convdescription");
		                let convdescchangeby = $(this).find('[id^="archivedImg-"]').data("convdescchangeby");
		                let convdescchangedate = $(this).find('[id^="archivedImg-"]').data("convdescchangedate");

		                $("#conversationsText").empty();
		                getMsgsForNmbrs(phnNmbrFrom, phnNmbrTo, conversationId, archivedConv, archivedBy, unarchivedBy, lastArchived, lastUnarchived, flagged, flagunflagby, flagunflagdate, tag, taguntagby, taguntagdate, convdescription, convdescchangeby, convdescchangedate);
		             });

		             $('[id^="indActConv-"]').click(function() {

		                $(".convsListArch").each(function(){ $(this).css("background-color", "rgb(252, 245, 251)"); });
		                $(".convsListAct").each(function(){ $(this).css("background-color", "rgb(239, 252, 252)"); });
		                $(this).css("background-color", "rgb(215, 239, 239)");

		                let crtordnmbr = $(this).attr("id").replace("indActConv-", "");
		                let phnNmbrFrom = $("#indActCvFrom-"+ crtordnmbr).text().split(": ")[1];
		                let phnNmbrTo = $("#indActCvTo-"+ crtordnmbr).text().split(": ")[1];
		                let conversationId = $(this).find('[id^="activeImg-"]').data("conversationid");
		                let archivedConv = $(this).find('[id^="activeImg-"]').data("archivedyesno");
		                let archivedBy = $(this).find('[id^="activeImg-"]').data("archdispname");
		                let unarchivedBy = $(this).find('[id^="activeImg-"]').data("unarchdispname");
		                let lastArchived = $(this).find('[id^="activeImg-"]').data("lastarchived");
		                let lastUnarchived = $(this).find('[id^="activeImg-"]').data("lastunarchived");
		                let flagged = $(this).find('[id^="activeImg-"]').data("flagged");
		                let flagunflagby = $(this).find('[id^="activeImg-"]').data("flagunflagby");
		                let flagunflagdate = $(this).find('[id^="activeImg-"]').data("flagunflagdate");
		                let tag = $(this).find('[id^="activeImg-"]').data("tag");
		                let taguntagby = $(this).find('[id^="activeImg-"]').data("taguntagby");
		                let taguntagdate = $(this).find('[id^="activeImg-"]').data("taguntagdate");
		                let convdescription = $(this).find('[id^="activeImg-"]').data("convdescription");
		                let convdescchangeby = $(this).find('[id^="activeImg-"]').data("convdescchangeby");
		                let convdescchangedate = $(this).find('[id^="activeImg-"]').data("convdescchangedate");

		                $("#conversationsText").empty();
		                getMsgsForNmbrs(phnNmbrFrom, phnNmbrTo, conversationId, archivedConv, archivedBy, unarchivedBy, lastArchived, lastUnarchived, flagged, flagunflagby, flagunflagdate, tag, taguntagby, taguntagdate, convdescription, convdescchangeby, convdescchangedate);
		             });
                     }
                     convListContent();

                     // Add the filter section
                     $("#convArchAndActive").prepend("<div id='filterSection' title='Click to show filters'><div id='filterSecImg'></div></div>");

                     // Add the 'Filter by flag' filter
                     $("#convArchAndActive").prepend("<div id='filterByFlag'><div id='filterByFlagImg'></div><select id='flagFilter'><option value='filterbyflag' selected='selected' disabled=''>Filter by flag</option><option value='flagged'>Flagged</option><option value='unflagged'>Unflagged</option></select><div id='clearFlagFilter' title='Clear all filters'></div></div>");

                     $("#flagFilter").change(function() {

                        var flagSel = $(this).val();

                        $(".convsLst").each(function() { $(this).remove(); });
                        $("#totalConvNmbr").remove();
                        $('#tagFilter option[value="filterbytag"]').prop("selected", true);
                        $("#flagFilter").css("background-color", "#f5f0ff");
                        $("#tagFilter").css("background-color", "#f0fbff");

                        if (flagSel == "flagged") {

		             if (archivedConvNmbr == 0) {
		                 // Don't list any archived conversations
		                 var archivedCvNbf = 0;

		             } else if (archivedConvNmbr != 0 && archivedConvNmbr != null) {

                                 var archInd = 0;
		                 let fcnv = (archivedConvNmbr <= convArchived.length)? convArchived.length - archivedConvNmbr : 0;
		                 for (let s = fcnv; s < convArchived.length; s++) {

                                      if (convArchived[s]['flagged'] == 1) {
		                          var emptyRedFlags = "cvFlagRed";
		                          if (convArchived[s]['tag'] != "") { var cvTagTxts = convArchived[s]['tag']; var cvTagAdds = "convTagAdded"; } else { var cvTagTxts = ""; var cvTagAdds = "convTag"; }
		                          var cvDescAdds = (convArchived[s]['description'] != "")? "convDescAdded" : "convDesc";
		                          $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ s +"'><div id='archivedImg-"+ s +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[s]['conversation_id'] +"' data-archivedyesno='"+ convArchived[s]['archived'] +"' data-archdispname='"+ convArchived[s]['archived_by'] +"' data-unarchdispname='"+ convArchived[s]['unarchived_by'] +"' data-lastarchived='"+ convArchived[s]['last_archived'] +"' data-lastunarchived='"+ convArchived[s]['last_unarchived'] +"' data-convdescription='"+ convArchived[s]['description'] +"' data-convdescchangeby='"+ convArchived[s]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[s]['descriptiondate'] +"' data-tag='"+ cvTagTxts +"' data-taguntagby='"+ convArchived[s]['taguntagby'] +"' data-taguntagdate='"+ convArchived[s]['taguntagdate'] +"' data-flagged='"+ convArchived[s]['flagged'] +"' data-flagunflagby='"+ convArchived[s]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[s]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ s +"'>From: "+ convArchived[s]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ s +"'>To: "+ convArchived[s]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[s]['lastmsgdisplayname'] +":</span>"+ convArchived[s]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[s]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ s +"' class='"+ cvDescAdds +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ s +"' class='"+ cvTagAdds +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxts +"</div><div id='addArchFlag-"+ s +"' class='"+ emptyRedFlags +"' title='Click to set or remove flag.'></div></div>");
                                          archInd++;
                                      }
		                 }
		                 var archivedCvNbf = archInd;

		             } else {

                                 var archInd = 0;
		                 for (let a = 0; a < convArchived.length; a++) {

                                      if (convArchived[a]['flagged'] == 1) {
		                          var emptyRedFlaga = "cvFlagRed";
		                          if (convArchived[a]['tag'] != "") { var cvTagTxta = convArchived[a]['tag']; var cvTagAdda = "convTagAdded"; } else { var cvTagTxta = ""; var cvTagAdda = "convTag"; }
		                          var cvDescAdda = (convArchived[a]['description'] != "")? "convDescAdded" : "convDesc";
		                          $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ a +"'><div id='archivedImg-"+ a +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[a]['conversation_id'] +"' data-archivedyesno='"+ convArchived[a]['archived'] +"' data-archdispname='"+ convArchived[a]['archived_by'] +"' data-unarchdispname='"+ convArchived[a]['unarchived_by'] +"' data-lastarchived='"+ convArchived[a]['last_archived'] +"' data-lastunarchived='"+ convArchived[a]['last_unarchived'] +"' data-convdescription='"+ convArchived[a]['description'] +"' data-convdescchangeby='"+ convArchived[a]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[a]['descriptiondate'] +"' data-tag='"+ cvTagTxta +"' data-taguntagby='"+ convArchived[a]['taguntagby'] +"' data-taguntagdate='"+ convArchived[a]['taguntagdate'] +"' data-flagged='"+ convArchived[a]['flagged'] +"' data-flagunflagby='"+ convArchived[a]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[a]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ a +"'>From: "+ convArchived[a]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ a +"'>To: "+ convArchived[a]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[a]['lastmsgdisplayname'] +":</span>"+ convArchived[a]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[a]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ a +"' class='"+ cvDescAdda +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ a +"' class='"+ cvTagAdda +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxta +"</div><div id='addArchFlag-"+ a +"' class='"+ emptyRedFlaga +"' title='Click to set or remove flag.'></div></div>");
                                          archInd++;
                                      }
		                 }
		                 var archivedCvNbf = archInd;
		             }

                             var actInd = 0;
		             for (let t = 0; t < convActive.length; t++) {

                                  if (convActive[t]['flagged'] == 1) {
		                      var emptyRedFlagt = "cvFlagRed";
		                      if (convActive[t]['tag'] != "") { var cvTagTxtt = convActive[t]['tag']; var cvTagAddt = "convTagAdded"; } else { var cvTagTxtt = ""; var cvTagAddt = "convTag"; }
		                      var cvDescAddt = (convActive[t]['description'] != "")? "convDescAdded" : "convDesc";
		                      $("#convArchAndActive").append("<div class='convsListAct convsLst' id='indActConv-"+ t +"'><div id='activeImg-"+ t +"' class='archactImg activeConvImg' data-conversationid='"+ convActive[t]['conversation_id'] +"' data-archivedyesno='"+ convActive[t]['archived'] +"' data-archdispname='"+ convActive[t]['archived_by'] +"' data-unarchdispname='"+ convActive[t]['unarchived_by'] +"' data-lastarchived='"+ convActive[t]['last_archived'] +"' data-lastunarchived='"+ convActive[t]['last_unarchived'] +"' data-convdescription='"+ convActive[t]['description'] +"' data-convdescchangeby='"+ convActive[t]['descriptionby'] +"' data-convdescchangedate='"+ convActive[t]['descriptiondate'] +"' data-tag='"+ cvTagTxtt +"' data-taguntagby='"+ convActive[t]['taguntagby'] +"' data-taguntagdate='"+ convActive[t]['taguntagdate'] +"' data-flagged='"+ convActive[t]['flagged'] +"' data-flagunflagby='"+ convActive[t]['flagunflagby'] +"' data-flagunflagdate='"+ convActive[t]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/active.svg' title='Active conversation'></div><div class='convLastMsgFrom' id='indActCvFrom-"+ t +"'>From: "+ convActive[t]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indActCvTo-"+ t +"'>To: "+ convActive[t]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convActive[t]['lastmsgdisplayname'] +":</span>"+ convActive[t]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Active conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convActive[t]['last_msg_date'] +"</div></div><div id='addActDesc-"+ t +"' class='"+ cvDescAddt +"' title='Click to add or modify description.'></div><div id='addActTag-"+ t +"' class='"+ cvTagAddt +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxtt +"</div><div id='addActFlag-"+ t +"' class='"+ emptyRedFlagt +"' title='Click to set or remove flag.'></div></div>");
                                      actInd++;
                                  }
		             }

		             var totalConvNbf = archivedCvNbf + actInd;

                        } else if (flagSel == "unflagged") {

		             if (archivedConvNmbr == 0) {
		                 // Don't list any archived conversations
		                 var archivedCvNbf = 0;

		             } else if (archivedConvNmbr != 0 && archivedConvNmbr != null) {

                                 var archInd = 0;
		                 let fcnv = (archivedConvNmbr <= convArchived.length)? convArchived.length - archivedConvNmbr : 0;
		                 for (let s = fcnv; s < convArchived.length; s++) {

                                      if (convArchived[s]['flagged'] != 1) {
		                          var emptyRedFlags = "cvFlagEmpty";
		                          if (convArchived[s]['tag'] != "") { var cvTagTxts = convArchived[s]['tag']; var cvTagAdds = "convTagAdded"; } else { var cvTagTxts = ""; var cvTagAdds = "convTag"; }
		                          var cvDescAdds = (convArchived[s]['description'] != "")? "convDescAdded" : "convDesc";
		                          $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ s +"'><div id='archivedImg-"+ s +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[s]['conversation_id'] +"' data-archivedyesno='"+ convArchived[s]['archived'] +"' data-archdispname='"+ convArchived[s]['archived_by'] +"' data-unarchdispname='"+ convArchived[s]['unarchived_by'] +"' data-lastarchived='"+ convArchived[s]['last_archived'] +"' data-lastunarchived='"+ convArchived[s]['last_unarchived'] +"' data-convdescription='"+ convArchived[s]['description'] +"' data-convdescchangeby='"+ convArchived[s]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[s]['descriptiondate'] +"' data-tag='"+ cvTagTxts +"' data-taguntagby='"+ convArchived[s]['taguntagby'] +"' data-taguntagdate='"+ convArchived[s]['taguntagdate'] +"' data-flagged='"+ convArchived[s]['flagged'] +"' data-flagunflagby='"+ convArchived[s]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[s]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ s +"'>From: "+ convArchived[s]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ s +"'>To: "+ convArchived[s]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[s]['lastmsgdisplayname'] +":</span>"+ convArchived[s]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[s]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ s +"' class='"+ cvDescAdds +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ s +"' class='"+ cvTagAdds +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxts +"</div><div id='addArchFlag-"+ s +"' class='"+ emptyRedFlags +"' title='Click to set or remove flag.'></div></div>");
                                          archInd++;
                                      }
		                 }
		                 var archivedCvNbf = archInd;

		             } else {

                                 var archInd = 0;
		                 for (let a = 0; a < convArchived.length; a++) {

                                      if (convArchived[a]['flagged'] != 1) {
		                          var emptyRedFlaga = "cvFlagEmpty";
		                          if (convArchived[a]['tag'] != "") { var cvTagTxta = convArchived[a]['tag']; var cvTagAdda = "convTagAdded"; } else { var cvTagTxta = ''; var cvTagAdda = "convTag"; }
		                          var cvDescAdda = (convArchived[a]['description'] != "")? "convDescAdded" : "convDesc";
		                          $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ a +"'><div id='archivedImg-"+ a +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[a]['conversation_id'] +"' data-archivedyesno='"+ convArchived[a]['archived'] +"' data-archdispname='"+ convArchived[a]['archived_by'] +"' data-unarchdispname='"+ convArchived[a]['unarchived_by'] +"' data-lastarchived='"+ convArchived[a]['last_archived'] +"' data-lastunarchived='"+ convArchived[a]['last_unarchived'] +"' data-convdescription='"+ convArchived[a]['description'] +"' data-convdescchangeby='"+ convArchived[a]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[a]['descriptiondate'] +"' data-tag='"+ cvTagTxta +"' data-taguntagby='"+ convArchived[a]['taguntagby'] +"' data-taguntagdate='"+ convArchived[a]['taguntagdate'] +"' data-flagged='"+ convArchived[a]['flagged'] +"' data-flagunflagby='"+ convArchived[a]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[a]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ a +"'>From: "+ convArchived[a]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ a +"'>To: "+ convArchived[a]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[a]['lastmsgdisplayname'] +":</span>"+ convArchived[a]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[a]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ a +"' class='"+ cvDescAdda +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ a +"' class='"+ cvTagAdda +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxta +"</div><div id='addArchFlag-"+ a +"' class='"+ emptyRedFlaga +"' title='Click to set or remove flag.'></div></div>");
                                          archInd++;
                                      }
		                 }
		                 var archivedCvNbf = archInd;
		             }

                             var actInd = 0;
		             for (let t = 0; t < convActive.length; t++) {

                                  if (convActive[t]['flagged'] != 1) {
		                      var emptyRedFlagt = "cvFlagEmpty";
		                      if (convActive[t]['tag'] != "") { var cvTagTxtt = convActive[t]['tag']; var cvTagAddt = "convTagAdded"; } else { var cvTagTxtt = ""; var cvTagAddt = "convTag"; }
		                      var cvDescAddt = (convActive[t]['description'] != "")? "convDescAdded" : "convDesc";
		                      $("#convArchAndActive").append("<div class='convsListAct convsLst' id='indActConv-"+ t +"'><div id='activeImg-"+ t +"' class='archactImg activeConvImg' data-conversationid='"+ convActive[t]['conversation_id'] +"' data-archivedyesno='"+ convActive[t]['archived'] +"' data-archdispname='"+ convActive[t]['archived_by'] +"' data-unarchdispname='"+ convActive[t]['unarchived_by'] +"' data-lastarchived='"+ convActive[t]['last_archived'] +"' data-lastunarchived='"+ convActive[t]['last_unarchived'] +"' data-convdescription='"+ convActive[t]['description'] +"' data-convdescchangeby='"+ convActive[t]['descriptionby'] +"' data-convdescchangedate='"+ convActive[t]['descriptiondate'] +"' data-tag='"+ cvTagTxtt +"' data-taguntagby='"+ convActive[t]['taguntagby'] +"' data-taguntagdate='"+ convActive[t]['taguntagdate'] +"' data-flagged='"+ convActive[t]['flagged'] +"' data-flagunflagby='"+ convActive[t]['flagunflagby'] +"' data-flagunflagdate='"+ convActive[t]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/active.svg' title='Active conversation'></div><div class='convLastMsgFrom' id='indActCvFrom-"+ t +"'>From: "+ convActive[t]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indActCvTo-"+ t +"'>To: "+ convActive[t]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convActive[t]['lastmsgdisplayname'] +":</span>"+ convActive[t]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Active conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convActive[t]['last_msg_date'] +"</div></div><div id='addActDesc-"+ t +"' class='"+ cvDescAddt +"' title='Click to add or modify description.'></div><div id='addActTag-"+ t +"' class='"+ cvTagAddt +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxtt +"</div><div id='addActFlag-"+ t +"' class='"+ emptyRedFlagt +"' title='Click to set or remove flag.'></div></div>");
                                      actInd++;
                                  }
		             }

		             var totalConvNbf = archivedCvNbf + actInd;
                        }

	                // Add the row that specifies the number of conversations displayed
	                $("#convArchAndActive").append("<div id='totalConvNmbr'>"+ totalConvNbf +" conversations displayed (<span id='archivedCvImg' title='Archived conversations'></span>"+ archivedCvNbf +"<span id='activeCvImg' title='Active conversations'></span>"+ actInd +" )</div>");

		        // Remove the empty display names, if any
		        $(".msgAuthorNameConv").each(function() { if ($(this).text() == ":") { $(this).remove(); } });

                        convListContent();
                     });

                     // Clear the flag filter
                     $("#clearFlagFilter").click(function() { $("#conversationsshow").click(); });


                     // Add the 'Filter by tag' filter
                     var selectTagOpt = "<option value='filterbytag' selected='selected' disabled=''>Filter by tag</option>";
                     for (let v = 0; v < taggsArr.length; v++) {
                          selectTagOpt += "<option value='"+ taggsArr[v] +"'>"+ taggsArr[v] +"</option>";
                     }
                     selectTagOpt += "<option value=''>--- empty tag ---</option>";
                     $("#convArchAndActive").prepend("<div id='filterByTag'><div id='filterByTagImg'></div><select id='tagFilter'>"+ selectTagOpt +"</select><div id='clearTagFilter' title='Clear all filters'></div></div>");

                     $("#tagFilter").change(function() {

                        var tagSel = $(this).val();

                        $(".convsLst").each(function() { $(this).remove(); });
                        $("#totalConvNmbr").remove();
                        $('#flagFilter option[value="filterbyflag"]').prop("selected", true);
                        $("#tagFilter").css("background-color", "#f5f0ff");
                        $("#flagFilter").css("background-color", "#f0fbff");

			if (archivedConvNmbr == 0) {
		            // Don't list any archived conversations
		            var archivedCvNbt = 0;

		        } else if (archivedConvNmbr != 0 && archivedConvNmbr != null) {

                                 var archIndt = 0;
		                 let fcnv = (archivedConvNmbr <= convArchived.length)? convArchived.length - archivedConvNmbr : 0;
		                 for (let s = fcnv; s < convArchived.length; s++) {

                                      if (String(convArchived[s]['tag']) == tagSel) {
		                          var emptyRedFlags = (convArchived[s]['flagged'] == 1)? "cvFlagRed" : "cvFlagEmpty";
		                          if (convArchived[s]['tag'] != "") { var cvTagTxts = convArchived[s]['tag']; var cvTagAdds = "convTagAdded"; } else { var cvTagTxts = ""; var cvTagAdds = "convTag"; }
		                          var cvDescAdds = (convArchived[s]['description'] != "")? "convDescAdded" : "convDesc";
		                          $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ s +"'><div id='archivedImg-"+ s +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[s]['conversation_id'] +"' data-archivedyesno='"+ convArchived[s]['archived'] +"' data-archdispname='"+ convArchived[s]['archived_by'] +"' data-unarchdispname='"+ convArchived[s]['unarchived_by'] +"' data-lastarchived='"+ convArchived[s]['last_archived'] +"' data-lastunarchived='"+ convArchived[s]['last_unarchived'] +"' data-convdescription='"+ convArchived[s]['description'] +"' data-convdescchangeby='"+ convArchived[s]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[s]['descriptiondate'] +"' data-tag='"+ cvTagTxts +"' data-taguntagby='"+ convArchived[s]['taguntagby'] +"' data-taguntagdate='"+ convArchived[s]['taguntagdate'] +"' data-flagged='"+ convArchived[s]['flagged'] +"' data-flagunflagby='"+ convArchived[s]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[s]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ s +"'>From: "+ convArchived[s]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ s +"'>To: "+ convArchived[s]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[s]['lastmsgdisplayname'] +":</span>"+ convArchived[s]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[s]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ s +"' class='"+ cvDescAdds +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ s +"' class='"+ cvTagAdds +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxts +"</div><div id='addArchFlag-"+ s +"' class='"+ emptyRedFlags +"' title='Click to set or remove flag.'></div></div>");
                                          archIndt++;
                                      }
		                 }
		                 var archivedCvNbt = archIndt;

		        } else {

                                 var archIndt = 0;
		                 for (let a = 0; a < convArchived.length; a++) {

                                      if (String(convArchived[a]['tag']) == tagSel) {
		                          var emptyRedFlaga = (convArchived[a]['flagged'] == 1)? "cvFlagRed" : "cvFlagEmpty";
		                          if (convArchived[a]['tag'] != "") { var cvTagTxta = convArchived[a]['tag']; var cvTagAdda = "convTagAdded"; } else { var cvTagTxta = ""; var cvTagAdda = "convTag"; }
		                          var cvDescAdda = (convArchived[a]['description'] != "")? "convDescAdded" : "convDesc";
		                          $("#convArchAndActive").append("<div class='convsListArch convsLst' id='indArchConv-"+ a +"'><div id='archivedImg-"+ a +"' class='archactImg archConvImg' data-conversationid='"+ convArchived[a]['conversation_id'] +"' data-archivedyesno='"+ convArchived[a]['archived'] +"' data-archdispname='"+ convArchived[a]['archived_by'] +"' data-unarchdispname='"+ convArchived[a]['unarchived_by'] +"' data-lastarchived='"+ convArchived[a]['last_archived'] +"' data-lastunarchived='"+ convArchived[a]['last_unarchived'] +"' data-convdescription='"+ convArchived[a]['description'] +"' data-convdescchangeby='"+ convArchived[a]['descriptionby'] +"' data-convdescchangedate='"+ convArchived[a]['descriptiondate'] +"' data-tag='"+ cvTagTxta +"' data-taguntagby='"+ convArchived[a]['taguntagby'] +"' data-taguntagdate='"+ convArchived[a]['taguntagdate'] +"' data-flagged='"+ convArchived[a]['flagged'] +"' data-flagunflagby='"+ convArchived[a]['flagunflagby'] +"' data-flagunflagdate='"+ convArchived[a]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/archived.svg' title='Archived conversation'></div><div class='convLastMsgFrom' id='indArchCvFrom-"+ a +"'>From: "+ convArchived[a]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indArchCvTo-"+ a +"'>To: "+ convArchived[a]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convArchived[a]['lastmsgdisplayname'] +":</span>"+ convArchived[a]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Archived conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convArchived[a]['last_msg_date'] +"</div></div><div id='addArchDesc-"+ a +"' class='"+ cvDescAdda +"' title='Click to add or modify description.'></div><div id='addArchTag-"+ a +"' class='"+ cvTagAdda +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxta +"</div><div id='addArchFlag-"+ a +"' class='"+ emptyRedFlaga +"' title='Click to set or remove flag.'></div></div>");
                                          archIndt++;
                                      }
		                 }
		                 var archivedCvNbt = archIndt;
		        }

                        var actIndt = 0;
		        for (let t = 0; t < convActive.length; t++) {

                             if (String(convActive[t]['tag']) == tagSel) {
		                 var emptyRedFlagt = (convActive[t]['flagged'] == 1)? "cvFlagRed" : "cvFlagEmpty";
		                 if (convActive[t]['tag'] != "") { var cvTagTxtt = convActive[t]['tag']; var cvTagAddt = "convTagAdded"; } else { var cvTagTxtt = ""; var cvTagAddt = "convTag"; }
		                 var cvDescAddt = (convActive[t]['description'] != "")? "convDescAdded" : "convDesc";
		                 $("#convArchAndActive").append("<div class='convsListAct convsLst' id='indActConv-"+ t +"'><div id='activeImg-"+ t +"' class='archactImg activeConvImg' data-conversationid='"+ convActive[t]['conversation_id'] +"' data-archivedyesno='"+ convActive[t]['archived'] +"' data-archdispname='"+ convActive[t]['archived_by'] +"' data-unarchdispname='"+ convActive[t]['unarchived_by'] +"' data-lastarchived='"+ convActive[t]['last_archived'] +"' data-lastunarchived='"+ convActive[t]['last_unarchived'] +"' data-convdescription='"+ convActive[t]['description'] +"' data-convdescchangeby='"+ convActive[t]['descriptionby'] +"' data-convdescchangedate='"+ convActive[t]['descriptiondate'] +"' data-tag='"+ cvTagTxtt +"' data-taguntagby='"+ convActive[t]['taguntagby'] +"' data-taguntagdate='"+ convActive[t]['taguntagdate'] +"' data-flagged='"+ convActive[t]['flagged'] +"' data-flagunflagby='"+ convActive[t]['flagunflagby'] +"' data-flagunflagdate='"+ convActive[t]['flagunflagdate'] +"'><img src='/" + ctappdir + "/sms_relentless/img/active.svg' title='Active conversation'></div><div class='convLastMsgFrom' id='indActCvFrom-"+ t +"'>From: "+ convActive[t]['last_msg_from'] +"</div><div class='convLastMsgTo' id='indActCvTo-"+ t +"'>To: "+ convActive[t]['last_msg_to'] +"</div><div class='convLastMsg'><span class='msgAuthorNameConv'>"+ convActive[t]['lastmsgdisplayname'] +":</span>"+ convActive[t]['last_message'] +"</div><div class='dateSection'><div class='dateClock' title='Last message date. (Active conversations are ordered by the date of the last message.)'></div><div class='convLastMsgDate'>"+ convActive[t]['last_msg_date'] +"</div></div><div id='addActDesc-"+ t +"' class='"+ cvDescAddt +"' title='Click to add or modify description.'></div><div id='addActTag-"+ t +"' class='"+ cvTagAddt +"' title='Click to add or modify tag.'></div><div class='archactTag'>"+ cvTagTxtt +"</div><div id='addActFlag-"+ t +"' class='"+ emptyRedFlagt +"' title='Click to set or remove flag.'></div></div>");
                                 actIndt++;
                             }
		        }

		        var totalConvNbt = archivedCvNbt + actIndt;

	                // Add the row that specifies the number of conversations displayed
	                $("#convArchAndActive").append("<div id='totalConvNmbr'>"+ totalConvNbt +" conversations displayed (<span id='archivedCvImg' title='Archived conversations'></span>"+ archivedCvNbt +"<span id='activeCvImg' title='Active conversations'></span>"+ actIndt +" )</div>");

		        // Remove the empty display names, if any
		        $(".msgAuthorNameConv").each(function() { if ($(this).text() == ":") { $(this).remove(); } });

                        convListContent();
                     });

                     // Clear the tag filter
                     $("#clearTagFilter").click(function() { $("#conversationsshow").click(); });

                     // Show/Hide the filters
                     $("#filterSection").click(function() {
                        if ($("#filterByTag").is(":visible")) {
                            $("#filterByTag,#filterByFlag").css("display", "none");
                            $("#filterSection").css("background-color", "#f0fbff");
                            $("#filterSection").prop("title", "Click to show filters");
                        } else {
                            $("#filterByTag,#filterByFlag").css("display", "block");
                            $("#filterSection").css("background-color", "#f0f5ff");
                            $("#filterSection").prop("title", "Click to hide filters");
                        }
                     });

          },
          error: function() {
                     showAlert("Error! You can check the Nextcloud log to find more details about this issue.");
                     $('#smstables').removeClass('icon-loading');
          }
     });

     // Look for the 'new received message' indicator in the database, to know if the received messages list needs to be refreshed
     intervalNmfr = setInterval(function() { checkIfNewMessage(); }, newMsgInterval);

  });


  // List grouped messages
  $("#groupedtableshow").on("click", function(event) {

     $('#smstables').empty();
     $("#stopAutoRefreshSent").css("display", "none");
     clearInterval(intervalNmfr);

     var getGroupedUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedtable");

     $('#smstables').addClass('icon-loading');
     var totalPhNmbrs = 0;

     $.ajax({
          method: 'GET',
          url: getGroupedUrl,
          contentType: 'application/json',
          success: function(groupedparsed) {

		        $('#smstables').append("<div id='toptablegrp'><div class='topbuttonandpage'><span id='recarrow' title='Show/Hide filters'></span></div><div id='paginationgrp' class='grppages'>Pages </div></div>");
		        $('#smstables').append("<table id='groupedSmsTable'></table>");

                        $('#groupedSmsTable').append("<tr id='grpfiltersrow'><td colspan='2'><div id='filterByNumber'></div></td><td><button id='cleargrpfilter' title='Clear the filter'></button></td></tr>");
                        $('#groupedSmsTable').append("<tr class='groupedmsgrows' id='grpheaderrow'><th>Phone Number</th><th>Senders / Receivers</th><th>Messages</th></tr>");

                        $('#grpfiltersrow').hide();

                        var fromtoNmbrsData = [];
                        var fromtoNumberArr = [];

		        for (var i = 0; i < groupedparsed.length; i++) {

			     if (groupedparsed[i].author_displayname) {
			         var authordnm = groupedparsed[i].author_displayname;
			     } else { 
			         var authordnm = '';
			     }

			     var sentfromnmbrarr = groupedparsed[i].from.split(": ");
                             if (sentfromnmbrarr[1]) {
			         var groupednbfrom = sentfromnmbrarr[1];
                             } else {
			         var groupednbfrom = sentfromnmbrarr[0];
                             }

                             var modmessage = '';
                             if (groupedparsed[i].author_displayname) {
			         modmessage = "<span class='msgAuthorNameGrp'>"+ groupedparsed[i].author_displayname + ":</span>" + groupedparsed[i].message;
                             } else {
			         modmessage = groupedparsed[i].message;
                             }

                             if (groupedparsed[i].to.indexOf(": ") > -1) {
                                 var groupednmbrtopre = groupedparsed[i].to.split(": ");
                                 var groupednmbrto = groupednmbrtopre[1];
                             } else { 
                                 var groupednmbrto = groupedparsed[i].to;
                             }

                             fromtoNmbrsData.push({
                                       'author_displayname': authordnm,
                                       'from': groupednbfrom,
                                       'to': groupednmbrto,
                                       'message': modmessage,
                                       'date': groupedparsed[i].date,
                                       'status': groupedparsed[i].deliveryreceipt,
                                       'table': groupedparsed[i].table
                             });

                             if (fromtoNumberArr.indexOf(groupednbfrom) == -1) { fromtoNumberArr.push(groupednbfrom); }
                             if (fromtoNumberArr.indexOf(groupednmbrto) == -1) { fromtoNumberArr.push(groupednmbrto); }
		        }

                        totalPhNmbrs = fromtoNumberArr.length;

                        // Remove the duplicates
			var noDupMsgData = [];
			$.each(fromtoNmbrsData, function(i, e) {
			    var matchingData = $.grep(noDupMsgData, function(item) {
                                return item.from == e.from && item.to == e.to && item.message == e.message && item.table == 'received' && e.table == 'sent'
			    });
			    if (matchingData.length === 0) {
				noDupMsgData.push(e);
			    }
			});

                        var messagesPerNmbr = {};
                        var msgsNamesPerNmbr = {};
                        var msgsNmbrsNames = {};

                        for (var k = 0; k < fromtoNumberArr.length; k++) {

                             var displayNamesarr = [];
                             var convData = [];

                             for (var n = 0; n < noDupMsgData.length; n++) {

                                  if (noDupMsgData[n]['from'] == fromtoNumberArr[k] && noDupMsgData[n]['table'] == 'sent') {

                                      convData.push({
                                                     'author_displayname': noDupMsgData[n]['author_displayname'],
                                                     'message': noDupMsgData[n]['message'],
                                                     'from': noDupMsgData[n]['from'],
                                                     'to': noDupMsgData[n]['to'],
                                                     'date': noDupMsgData[n]['date'],
                                                     'direction': 'sent_from',
                                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
                                                     'table': noDupMsgData[n]['table']
                                      });

                                  } else if (noDupMsgData[n]['to'] == fromtoNumberArr[k] && noDupMsgData[n]['table'] == 'sent') {

                                      convData.push({
                                                     'author_displayname': noDupMsgData[n]['author_displayname'],
                                                     'message': noDupMsgData[n]['message'],
                                                     'from': noDupMsgData[n]['from'],
                                                     'to': noDupMsgData[n]['to'],
                                                     'date': noDupMsgData[n]['date'],
                                                     'direction': 'sent_to',
                                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
                                                     'table': noDupMsgData[n]['table']
                                      });


                                  } else if (noDupMsgData[n]['from'] == fromtoNumberArr[k] && noDupMsgData[n]['table'] == 'received') {

                                      convData.push({
                                                     'author_displayname': noDupMsgData[n]['author_displayname'],
                                                     'message': noDupMsgData[n]['message'],
                                                     'from': noDupMsgData[n]['from'],
                                                     'to': noDupMsgData[n]['to'],
                                                     'date': noDupMsgData[n]['date'],
                                                     'direction': 'received_from',
                                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
                                                     'table': noDupMsgData[n]['table']
                                      });

                                  } else if (noDupMsgData[n]['to'] == fromtoNumberArr[k] && noDupMsgData[n]['table'] == 'received') {

                                      convData.push({
                                                     'author_displayname': noDupMsgData[n]['author_displayname'],
                                                     'message': noDupMsgData[n]['message'],
                                                     'from': noDupMsgData[n]['from'],
                                                     'to': noDupMsgData[n]['to'],
                                                     'date': noDupMsgData[n]['date'],
                                                     'direction': 'received_on',
                                                     'status': (noDupMsgData[n]['status'] == null)? "" : noDupMsgData[n]['status'],
                                                     'table': noDupMsgData[n]['table']
                                      });
                                  }
                             }

                             // Sort messages by date
		             convData.sort(function(a, b) {
                                return new Date(a.date) - new Date(b.date);
		             });

                             // Collect the display names of the users that sent messages from the current number
                             var selectedNames = [];
                             var displayNames = '';
                             for (var v = 0; v < convData.length; v++) {
                                  if (selectedNames.indexOf(convData[v]['author_displayname']) == -1) { 
                                      selectedNames.push(convData[v]['author_displayname']);
                                      displayNames += "<div id='diplNm_"+ fromtoNumberArr[k] +"_"+ v +"' class='dispNameList' name='"+ convData[v]['author_displayname'] +"'>"+ convData[v]['author_displayname'] +"</div>";
                                  }
                             }

                             // Store the display names for the current number, to be able to see them later when selecting the number from the drop-down list
                             var ctPhNumber = fromtoNumberArr[k];
                             msgsNamesPerNmbr[ctPhNumber] = displayNames;

                             // Store the messages sent by each user, to be able to see them later when clicking on the user's name
                             for (var h = 0; h < selectedNames.length; h++) {

                                  var rowMessageArrpn = [];
                                  for (var b = 0; b < convData.length; b++) {

                                       if (selectedNames[h] == convData[b]['author_displayname']) {

		                           if (convData[b]['direction'] == 'sent_from') {
		                               if (convData[b]['status']) {
					           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
			                               if (convData[b]['status'].indexOf("undelivered") > -1) {
					                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                       } else {
					                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                       }
					           } else {
					               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					           }
		                               } else {
		                                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                               }
		                               rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
		                           } else if (convData[b]['direction'] == 'sent_to') {
		                               if (convData[b]['status']) {
					           if (convData[b]['status'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
			                               if (convData[b]['status'].indexOf("undelivered") > -1) {
					                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                                       } else {
					                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                                       }
					           } else {
					               var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
					           }
		                               } else {
		                                   var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
		                               }
		                               rowMessageArrpn.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");
		                           } else if (convData[b]['direction'] == 'received_from') {
		                               rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
		                           } else if (convData[b]['direction'] == 'received_on') {
		                               rowMessageArrpn.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[b]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[b]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[b]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[b]['date'] +"</div></div>");
                                           }
                                       }
                                  }
                                  var convDataPerNmbrpn = rowMessageArrpn.join("<br>");
                                  var crtNmber = fromtoNumberArr[k];
                                  var crtName = selectedNames[h];
                                  msgsNmbrsNames[crtNmber] = msgsNmbrsNames[crtNmber] || {};
                                  msgsNmbrsNames[crtNmber][crtName] = convDataPerNmbrpn;
                             }

                             var rowMessageArr = [];
                             for (var m = 0; m < convData.length; m++) {

                                  if (convData[m]['direction'] == 'sent_from') {
                                      if (convData[m]['status']) {
				          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
		                              if (convData[m]['status'].indexOf("undelivered") > -1) {
				                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                              } else {
				                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                              }
				          } else {
				              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
				          }
                                      } else {
                                          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                      }
                                      rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 6px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

                                  } else if (convData[m]['direction'] == 'sent_to') {
                                      if (convData[m]['status']) {
				          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
		                              if (convData[m]['status'].indexOf("undelivered") > -1) {
				                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                              } else {
				                  var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                              }
				          } else {
				              var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
				          }
                                      } else {
                                          var sentMsgStatus = "<img src='/" + ctappdir + "/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is still possible that it reached its destination.'>";
                                      }
                                      rowMessageArr.push("<div class='groupedSentMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;color:#06866f;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/outgoing.svg' title='Message sent to current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:inline-block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div><div class='sentMssgStatus'>"+ sentMsgStatus +"</div></div>");

                                  } else if (convData[m]['direction'] == 'received_from') {

		                      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received from current number.'></div><div style='display:inline-block;color:#06866f;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#353535;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");

                                  } else if (convData[m]['direction'] == 'received_on') {

		                      rowMessageArr.push("<div class='groupedRecMsg'><div style='display:block;margin:0px 0px 6px 0px;'><div style='display:inline-block;margin:0px 12px 0px 3px;'><img src='/" + ctappdir + "/sms_relentless/img/incoming.svg' title='Message received on current number.'></div><div style='display:inline-block;color:#353535;'>From: "+ convData[m]['from'] +"</div><div style='display:inline-block;margin:0px 0px 0px 12px;color:#06866f;'>To: "+ convData[m]['to'] +"</div></div><div style='display:block;font-size:14px;color:#353535;font-weight:500;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
                                  }
                             }

                             var convDataPerNmbr = rowMessageArr.join("");

                             var rowPhoneNumber = "<div id='nmbrow_"+ fromtoNumberArr[k] +"' class='phoneNmbrRow'>"+ fromtoNumberArr[k] +"</div>";

		             $("#groupedSmsTable").append("<tr id='singlerow_"+ k +"' class='groupedrowsbody'><td><div class='groupedLstNmbr fixedRowHeight'>"+ rowPhoneNumber +"</div></td><td><div class='groupedLstNames fixedRowHeight'>"+ displayNames +"</div></td><td style='width:100%'><div class='groupedLstMsgs fixedRowHeight'>"+ convDataPerNmbr +"</div></td></tr>");
                             $("#groupedSmsTable").append("<tr id='expandRow_"+ k +"' class='groupedrowsexp'><td colspan='3'><div style='display:block;width:100%;height:14px;cursor:pointer;'><img class='expandGrpRow' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div><td></tr>");

                             // Store the messages for the current number, to be able to see them later, when clicking on the number
                             var ctNmbr = fromtoNumberArr[k];
                             messagesPerNmbr[ctNmbr] = convDataPerNmbr;
                        }


                        // Add the 'filter by number' drop-down list
                        var nmbrslst = "<option value='title'>Filter messages by number</option>";
                        for (var p = 0; p < fromtoNumberArr.length; p++) {
                             nmbrslst += "<option value='"+ fromtoNumberArr[p] +"'>"+ fromtoNumberArr[p] +"</option>";
                        }
                        $("#filterByNumber").append("<select id='selectListedNmbrs'>"+ nmbrslst +"</select>");


                        $("#selectListedNmbrs").change(function() {

                          var selectedNmbr = $(this).val();

                          if (selectedNmbr != "title") {

                              $(".groupedrowsbody,.groupedrowsexp").each(function() { $(this).hide(); });
		              $("#groupedSmsTable").append("<tr id='singlerowfl_"+ fromtoNumberArr.indexOf(selectedNmbr) +"' class='groupedrowsbody'><td><div class='groupedLstNmbr fixedRowHeight'><div id='nmbrow_"+ selectedNmbr +"' style='font-size:15px;font-weight:500;color:#06866f;cursor:pointer;'>"+ selectedNmbr +"</div></div></td><td><div class='groupedLstNames fixedRowHeight'>"+ msgsNamesPerNmbr[selectedNmbr] +"</div></td><td style='width:100%'><div class='groupedLstMsgs fixedRowHeight'>"+ messagesPerNmbr[selectedNmbr] +"</div></td></tr>");
                              $("#groupedSmsTable").append("<tr id='expandRowfl_"+ fromtoNumberArr.indexOf(selectedNmbr) +"' class='groupedrowsexp'><td colspan='3'><div style='display:block;width:100%;height:14px;cursor:pointer;'><img class='expandGrpRow' src='/" + ctappdir + "/sms_relentless/img/arrowDown.svg'></div><td></tr>");


                               // Show the messages sent by each user whose name is listed for the phone number of the current row
                               $('[id*="diplNm_"]').click(function() {

                                  var crntNmbr = $(this).attr("id").split("_")[1];
                                  var crntDisName = $(this).attr("name");                        
                                  var clsmsgcell = $(this).closest(".groupedrowsbody").find(".groupedLstMsgs");
                                  clsmsgcell.empty();
                                  clsmsgcell.html(msgsNmbrsNames[crntNmbr][crntDisName]);

                                  $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
                                  $(this).css("color", "#1483f0");
                                  $("#nmbrow_"+ selectedNmbr).css("color", "#06866f");
                                  $(".groupedLstNmbr").each(function () { $(this).css("color", "#06866f"); });
                               });


		               // Show all the messages sent to/from the clicked number
		               $('[id*="nmbrow_"]').click(function() {
		                  var rwNmbr = $(this).attr("id").replace("nmbrow_", "");
		                  var rowmsgcell = $(this).closest(".groupedrowsbody").find(".groupedLstMsgs");
		                  rowmsgcell.empty();
		                  rowmsgcell.html(messagesPerNmbr[rwNmbr]);

		                  $(".phoneNmbrRow").each(function() { $(this).css("color", "#06866f"); });
		                  $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
		                  $(this).css("color", "#08b899");
		               });


		               // Expand the rows to see all the messages
		               $('[id^="expandRowfl_"]').click(function() {
		                   var idnumbrfl = $(this).attr("id").replace("expandRowfl_", "");
		                   var crntExpandfl = $(this).find(".expandGrpRow");

		                   if (crntExpandfl.attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
                                       $("#singlerowfl_"+ idnumbrfl).find(".fixedRowHeight").removeClass("fixedRowHeight");
		                       crntExpandfl.attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
		                   } else {
                                       $("#singlerowfl_"+ idnumbrfl).find(".groupedLstNmbr,.groupedLstNames,.groupedLstMsgs").addClass("fixedRowHeight");
                                       crntExpandfl.attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg'); 
		                   }
		               });

		               $('#totalgrpmessages').remove();
		               $('#smstables').append("<div id='totalgrpmessages'>Total displayed phone numbers: 1</div>");
                           }
                        });

                        // Clear the 'filter by number' filter
                        $("#cleargrpfilter").click(function() {
                               $('[id^="singlerowfl_"]').remove();
                               $('[id^="expandRowfl_"]').remove();
                               $(".groupedrowsbody,.groupedrowsexp").each(function() { $(this).show(); });
                               $("#selectListedNmbrs").val("title");
		               $('#totalgrpmessages').remove();
		               $('#smstables').append("<div id='totalgrpmessages'>Total displayed phone numbers: "+ totalPhNmbrs +"</div>");
                        });

                        // Show the messages sent by each user whose name is listed for the phone number on the current row
                        $('[id*="diplNm_"]').click(function() {

                           var crntNmbr = $(this).attr("id").split("_")[1];
                           var crntDisName = $(this).attr("name");                               
                           var clsmsgcell = $(this).closest(".groupedrowsbody").find(".groupedLstMsgs");
                           clsmsgcell.empty();
                           clsmsgcell.html(msgsNmbrsNames[crntNmbr][crntDisName]);

                           $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
                           $(this).css("color", "#1483f0");
                        });

                        // Show all the messages sent to/from the clicked number
                        $('[id*="nmbrow_"]').click(function() {
                           var rwNmbr = $(this).attr("id").replace("nmbrow_", "");
                           var rowmsgcell = $(this).closest(".groupedrowsbody").find(".groupedLstMsgs");
                           rowmsgcell.empty();
                           rowmsgcell.html(messagesPerNmbr[rwNmbr]);

                           $(".phoneNmbrRow").each(function() { $(this).css("color", "#06866f"); });
                           $(".dispNameList").each(function() { $(this).css("color", "#0a559e"); });
                           $(this).css("color", "#08b899");
                        });


		        $('#smstables').removeClass('icon-loading');
		        $('#recarrow').removeClass('arrowUpCl');
		        $('#recarrow').addClass('arrowDownCl');

                        // Expand the rows to see all the messages
                        $('[id^="expandRow_"]').click(function() {
                            var idnumbr = $(this).attr("id").replace("expandRow_", "");
                            var crntExpand = $(this).find(".expandGrpRow");

                            if (crntExpand.attr('src') == '/' + ctappdir + '/sms_relentless/img/arrowDown.svg') {
                                $("#singlerow_"+ idnumbr).find(".fixedRowHeight").removeClass("fixedRowHeight");
                                crntExpand.attr('src', '/' + ctappdir + '/sms_relentless/img/arrowUp.svg');
                            } else {
                                $("#singlerow_"+ idnumbr).find(".groupedLstNmbr,.groupedLstNames,.groupedLstMsgs").addClass("fixedRowHeight");
                                crntExpand.attr('src', '/' + ctappdir + '/sms_relentless/img/arrowDown.svg'); 
                            }
                        });


		        // Add pagination
		        var rowsShowngrp = messagesperpage;
		        var rowsTotalgrp = $("#groupedSmsTable tr").length;

		        var numPagesgrp = ((rowsTotalgrp - 2) / rowsShowngrp) / 2;

		        for (i = 0; i < numPagesgrp; i++) {
		             var pageNumgrp = i + 1;
		             $('#paginationgrp').append('<a href="#" rel="' + i + '" class="pagenumbersgrp">' + pageNumgrp + '</a> ');
		        }

		        $('#paginationgrp').children(":first").addClass('active');

		        $(".groupedrowsbody,.groupedrowsexp").hide();

		        $('#paginationgrp a:first').addClass('active');

		        // Show table page when clicking a page number
		        $('.grppages a').bind('click', function() {

		           $('#paginationgrp').children().removeClass('active');

		           $(this).addClass('active');

		           var currentPageNogrp = $(this).text();

		           $('#paginationgrp a').each(function() {
		               if ($(this).text() == currentPageNogrp) {
		                   $(this).addClass('active');
		               }
		           });

		           var currPagegrp = $(this).attr('rel');
		           var startItemgrp = currPagegrp * rowsShowngrp;
		           var endItemgrp = startItemgrp + rowsShowngrp;

		           $(".groupedrowsbody").hide().slice(startItemgrp, endItemgrp).css('display', 'table-row');
		           $(".groupedrowsexp").hide().slice(startItemgrp, endItemgrp).css('display', 'table-row');

		           $('#totalgrpmessages').remove();
		           $('#smstables').append("<div id='totalgrpmessages'>Total displayed phone numbers: " + totalPhNmbrs + "</div>");
		        });

                        $('#paginationgrp').children(":last").trigger('click');


		        // Show/Hide filter row
		        $('#recarrow').on('click', function() {
			   if ($('#grpfiltersrow').is(':visible')) {
			       $('#grpfiltersrow').hide();
		               $('#grpheaderrow').css('top', '0px');
		               $(this).removeClass('arrowUpCl');
		               $(this).addClass('arrowDownCl');
			   } else {
			       $('#grpfiltersrow').show();
		               $('#grpheaderrow').css('top', '158px');
		               $(this).removeClass('arrowDownCl');
		               $(this).addClass('arrowUpCl');
		           }
		        });
          },
          error: function() {
                        showAlert("Error while attempting to get the messages from the database.");
                        $('#smstables').removeClass('icon-loading');
          }
     });
  });


  // List user activity data
  $("#activitytableshow").on("click", function(event) {

     $('#smstables').empty();
     $("#stopAutoRefreshSent").css("display", "none");
     clearInterval(intervalNmfr);

     var getActivityUrl = OC.generateUrl("/apps/sms_relentless/user/getactivitytable");

     $('#smstables').addClass('icon-loading');

     $.ajax({
          method: 'POST',
          url: getActivityUrl,
          contentType: 'application/json',
          data: JSON.stringify({ "interval" : "day" }),
          success: function(msgnbperusr) {

		        $('#smstables').append("<table id='activityTable'></table>");

                        $('#activityTable').append("<tr id='actheaderrow'><th title='Admins can see the number of messages sent by themselves and by the users with whom they shared their API keys, while non-admins can see only the number of messages sent by themselves.'>Display Name</th><th>Interval</th><th>Number of Messages Sent</th></tr>");

		        for (var i = 0; i < msgnbperusr.length; i++) {

                             var msgpernbdata = "";
                             var msgpusrobj = msgnbperusr[i]['nbdata']['msgpernmbr'];
                             var nmbrarr = Object.keys(msgpusrobj);

                             for (var b = 0; b < nmbrarr.length; b++) {
                                  var nbarrval = msgpusrobj[nmbrarr[b]];                              
                                  for (var c = 0; c < Object.keys(nbarrval).length; c++) {
                                       msgpernbdata += "<div style='display:block;'>" + Object.values(nbarrval)[c] + " messages from <b>" + Object.keys(nbarrval)[c] +"</b> to <b>" + nmbrarr[b] + "</b></div>";
                                  }
                             }

                             $("#activityTable").append("<tr id='singlerow_"+ i +"' class='actrowsbody'><td class='activityDspNm'><div class='actDispName'>"+ msgnbperusr[i]['displayname'] +"</div></td><td class='actInterval'><div id='lastDayBtn_"+ i +"' class='intervalBtn'>Last Day</div><div id='lastWeekBtn_"+ i +"' class='intervalBtn'>Last Week</div><div id='lastMonthBtn_"+ i +"' class='intervalBtn'>Last Month</div></td><td><div id='actMsgNumbers_"+ i +"'><div style='display:block;width:100%;'>"+ msgpernbdata +"</div><div style='display:block;color:#12937b;font-weight:500;'>Total: <div style='display:inline-block;margin:0 6px;'>"+ msgnbperusr[i]['nbdata']['totalmessage'] +" Messages</div><div style='display:inline-block;margin:0 6px;'>"+ msgnbperusr[i]['nbdata']['totalwordnb'] +" Words</div><div style='display:inline-block;margin:0 6px;'>"+ msgnbperusr[i]['nbdata']['totalcharnb'] +" Characters</div></div></div></td></tr>");
                        }

                        $('[id^="lastDayBtn_"]').each(function() { $(this).css("background-color", "#fdecfa"); });

                        $('#smstables').removeClass('icon-loading');

                        $('[id^="lastDayBtn_"]').click(function() {

                           var idnbr = $(this).attr("id").replace("lastDayBtn_", "");
                           var crtDspNm = $(this).closest(".actrowsbody").find(".actDispName").text();
                           $("#actMsgNumbers_"+ idnbr +"").empty();

		           var getIndActUrl = OC.generateUrl("/apps/sms_relentless/user/getindactivity");

		           $('#smstables').addClass('icon-loading');

		           $.ajax({
			       method: 'POST',
			       url: getIndActUrl,
			       contentType: 'application/json',
			       data: JSON.stringify({ "interval" : "day", "indusrdspnm" : crtDspNm }),
			       success: function(msgusrind) {

				            var msgindusr = "";
				            var msgindusrobj = msgusrind[0]['nbdata']['msgpernmbr'];
				            var nmbindarr = Object.keys(msgindusrobj);

				            for (var b = 0; b < nmbindarr.length; b++) {
				                 var nbindval = msgindusrobj[nmbindarr[b]];                              
				                 for (var c = 0; c < Object.keys(nbindval).length; c++) {
				                      msgindusr += "<div style='display:block;'>" + Object.values(nbindval)[c] + " messages from <b>" + Object.keys(nbindval)[c] +"</b> to <b>" + nmbindarr[b] + "</b></div>";
				                 }
				            }

                                            $("#actMsgNumbers_"+ idnbr +"").append("<div style='display:block;width:100%;'>"+ msgindusr +"</div><div style='display:block;color:#12937b;font-weight:500;'>Total: <div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalmessage'] +" Messages</div><div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalwordnb'] +" Words</div><div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalcharnb'] +" Characters</div></div>");

                                            $("#lastDayBtn_"+ idnbr +"").css("background-color", "#fdecfa");
                                            $("#lastWeekBtn_"+ idnbr +"").css("background-color", "#ffffff");
                                            $("#lastMonthBtn_"+ idnbr +"").css("background-color", "#ffffff");

				            $('#smstables').removeClass('icon-loading');
			       },
			       error: function() {
				        showAlert("Error while getting activity data from the database. You can check the Nextcloud log to find more details about this issue.");
				        $('#smstables').removeClass('icon-loading');
			       }
		           });
                        });

                        $('[id^="lastWeekBtn_"]').click(function() {

                           var idnbr = $(this).attr("id").replace("lastWeekBtn_", "");
                           var crtDspNm = $(this).closest(".actrowsbody").find(".actDispName").text();
                           $("#actMsgNumbers_"+ idnbr +"").empty();

		           var getIndActUrl = OC.generateUrl("/apps/sms_relentless/user/getindactivity");

		           $('#smstables').addClass('icon-loading');

		           $.ajax({
			       method: 'POST',
			       url: getIndActUrl,
			       contentType: 'application/json',
			       data: JSON.stringify({ "interval" : "week", "indusrdspnm" : crtDspNm }),
			       success: function(msgusrind) {

				            var msgindusr = "";
				            var msgindusrobj = msgusrind[0]['nbdata']['msgpernmbr'];
				            var nmbindarr = Object.keys(msgindusrobj);

				            for (var b = 0; b < nmbindarr.length; b++) {
				                 var nbindval = msgindusrobj[nmbindarr[b]];                              
				                 for (var c = 0; c < Object.keys(nbindval).length; c++) {
				                      msgindusr += "<div style='display:block;'>" + Object.values(nbindval)[c] + " messages from <b>" + Object.keys(nbindval)[c] +"</b> to <b>" + nmbindarr[b] + "</b></div>";
				                 }
				            }

                                            $("#actMsgNumbers_"+ idnbr +"").append("<div style='display:block;width:100%;'>"+ msgindusr +"</div><div style='display:block;color:#12937b;font-weight:500;'>Total: <div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalmessage'] +" Messages</div><div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalwordnb'] +" Words</div><div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalcharnb'] +" Characters</div></div>");

                                            $("#lastDayBtn_"+ idnbr +"").css("background-color", "#ffffff");
                                            $("#lastWeekBtn_"+ idnbr +"").css("background-color", "#fdecfa");
                                            $("#lastMonthBtn_"+ idnbr +"").css("background-color", "#ffffff");

				            $('#smstables').removeClass('icon-loading');
			       },
			       error: function() {
				            showAlert("Error while getting activity data from the database. You can check the Nextcloud log to find more details about this issue.");
				            $('#smstables').removeClass('icon-loading');
			       }
		           });
                        });

                        $('[id^="lastMonthBtn_"]').click(function() {

                           var idnbr = $(this).attr("id").replace("lastMonthBtn_", "");
                           var crtDspNm = $(this).closest(".actrowsbody").find(".actDispName").text();
                           $("#actMsgNumbers_"+ idnbr +"").empty();

		           var getIndActUrl = OC.generateUrl("/apps/sms_relentless/user/getindactivity");

		           $('#smstables').addClass('icon-loading');

		           $.ajax({
			       method: 'POST',
			       url: getIndActUrl,
			       contentType: 'application/json',
			       data: JSON.stringify({ "interval" : "month", "indusrdspnm" : crtDspNm }),
			       success: function(msgusrind) {

				            var msgindusr = "";
				            var msgindusrobj = msgusrind[0]['nbdata']['msgpernmbr'];
				            var nmbindarr = Object.keys(msgindusrobj);

				            for (var b = 0; b < nmbindarr.length; b++) {
				                 var nbindval = msgindusrobj[nmbindarr[b]];                              
				                 for (var c = 0; c < Object.keys(nbindval).length; c++) {
				                      msgindusr += "<div style='display:block;'>" + Object.values(nbindval)[c] + " messages from <b>" + Object.keys(nbindval)[c] +"</b> to <b>" + nmbindarr[b] + "</b></div>";
				                 }
				            }

                                            $("#actMsgNumbers_"+ idnbr +"").append("<div style='display:block;width:100%;'>"+ msgindusr +"</div><div style='display:block;color:#12937b;font-weight:500;'>Total: <div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalmessage'] +" Messages</div><div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalwordnb'] +" Words</div><div style='display:inline-block;margin:0 6px;'>"+ msgusrind[0]['nbdata']['totalcharnb'] +" Characters</div></div>");

                                            $("#lastDayBtn_"+ idnbr +"").css("background-color", "#ffffff");
                                            $("#lastWeekBtn_"+ idnbr +"").css("background-color", "#ffffff");
                                            $("#lastMonthBtn_"+ idnbr +"").css("background-color", "#fdecfa");

				            $('#smstables').removeClass('icon-loading');
			       },
			       error: function() {
				            showAlert("Error while getting activity data from the database. You can check the Nextcloud log to find more details about this issue.");
				            $('#smstables').removeClass('icon-loading');
			       }
		           });
                        });

          },
          error: function() {
                        showAlert("Error while attempting to get user activity data from the database. You can check the Nextcloud log to find more details about this issue.");
                        $('#smstables').removeClass('icon-loading');
          }
     });

     // Look for the 'new received message' indicator in the database, to know if the received messages list needs to be refreshed
     intervalNmfr = setInterval(function() { checkIfNewMessage(); }, newMsgInterval);
  });


  function showAlert(alertText) {

     let alertwnd = "<div id='alertMessage'>";
     alertwnd += "<a id='closeAlertWnd' title='Close this window'></a>";
     alertwnd += "<div id='alertTextWrap'>"+ alertText +"</div>";
     alertwnd += "<input type='submit' id='alertOk' value='OK'>";
     alertwnd += "</div>";

     $("#content").append("<div id='alertMsgOverlay'></div>");
     $("#content").append(alertwnd);

     let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 152) +"px";
     let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
     $("#alertMessage").css({ "top" : topDist, "left" : leftDist });

     $("#closeAlertWnd").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
     $("#alertMsgOverlay").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
     $("#alertOk").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
  }

  function confirmAlert(alertText) {

     $("#alertMsgOverlay").remove();
     $("#alertConfMessage").remove();

     let alertwndcf = "<div id='alertConfMessage'>";
     alertwndcf += "<a id='closeAlertWndcf' title='Close this window'></a>";
     alertwndcf += "<div id='alertTextWrap'>"+ alertText +"</div>";
     alertwndcf += "<div id='cancelOkWrap'><input type='submit' id='confirmCancel' value='Cancel'>";
     alertwndcf += "<input type='submit' id='confirmOk' value='OK'></div>";
     alertwndcf += "</div>";

     $("#content").append("<div id='alertMsgOverlay'></div>");
     $("#content").append(alertwndcf);

     let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 152) +"px";
     let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
     $("#alertConfMessage").css({ "top" : topDist, "left" : leftDist });

     $("#closeAlertWndcf").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });
     $("#alertMsgOverlay").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });
  }


  // Append the auto-refresh button that refreshes the 'Sent SMS Messages' page
  $("#app-content").append("<div id='stopAutoRefreshSent'><div id='stopAutoRefreshSentBtn'>Start auto refresh</div><div id='refreshTimerSent' class='arftimer' style='--duration: 15;--size: 24;'><div class='arfmask'></div></div></div>");

  $("#stopAutoRefreshSentBtn").click(function() {
     if ($("#stopAutoRefreshSentBtn").text() == "Stop auto refresh") {
         clearInterval(intervalRfrSent);
         $("#stopAutoRefreshSentBtn").text("Start auto refresh");
         $("#stopAutoRefreshSentBtn").css("color", "#0a559e");
         $("#refreshTimerSent").css("display", "none");
     } else {
         clearInterval(intervalRfrSent);
         intervalRfrSent = setInterval(function() { $("#sentsmstableshow").click(); }, 15000);
         $("#stopAutoRefreshSentBtn").text("Stop auto refresh");
         $("#stopAutoRefreshSentBtn").css("color", "#04957b");
         $("#refreshTimerSent").css("display", "inline-block");
     }
  });

});
