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

$(document).ready(function() {

  var userid = "<?php p($userId); ?>";
  var parseddata = null;
  var sentparseddata = null;
  var groupedparsed = null;
  // Set the default number of messages per page
  var messagesperpage = 100;
  var intervalRfrRec = 0;
  var intervalRfrSent = 0;

  // Get the number of messages per page from the database
  var getNoPerPageUrl = OC.generateUrl("/apps/sms_relentless/user/getmessagesperpage");

  $.ajax({
        url: getNoPerPageUrl + '/' + userid,
        method: 'GET',
        success: function(mesperpagedb) {
                 messagesperpage = parseInt(mesperpagedb);

        },
        error: function(mesperpagedb) {
                 showAlert("Error while getting the number of messages per page. You can check the Nextcloud log to find more details about this issue!");
        }
  });


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

     $('#smstables').empty();
     var getReceivedUrl = OC.generateUrl("/apps/sms_relentless/user/getreceivedtable");

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

     $.ajax({
          url: getReceivedUrl + '/' + userid,
          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.' /></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='/apps/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='/apps/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='/apps/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='/apps/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 = '/apps/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 = '/apps/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='/apps/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='/apps/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='/apps/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 = '/apps/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 = '/apps/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='/apps/sms_relentless/img/dots.svg'></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='stopAutoRefresh'>Stop auto refresh</div><div id='refreshMsgsConv' title='Refresh list'></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 style='display:block;width:100%;height:14px;'><img id='expandWindowRpl' src='/apps/sms_relentless/img/arrowDown.svg' title='Expand to send a reply'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/apps/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;'></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 });

                   var intervalRfr = 0;
                   var rplchck = 0;

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


	           // 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') == '/apps/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          $("#listAllMsgsConv").css("height", "618px");
	                  $(this).attr('src', '/apps/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');
                          $("#stopAutoRefresh").css("visibility", "visible");
                          intervalRfr = setInterval(function() { $("#refreshMsgsConv").click(); }, 5000);

                          $("#stopAutoRefresh").text("Stop auto refresh");
                          $("#stopAutoRefresh").css("color", "#0a559e");

                          $("#stopAutoRefresh").unbind("click");
                          $("#stopAutoRefresh").click(function() { 
                             if ($("#stopAutoRefresh").text() == "Stop auto refresh") {
                                  clearInterval(intervalRfr);
                                  $("#stopAutoRefresh").text("Start auto refresh");
                                  $("#stopAutoRefresh").css("color", "#04957b");
                             } else {
                                  clearInterval(intervalRfr);
                                  intervalRfr = setInterval(function() { $("#refreshMsgsConv").click(); }, 5000);
                                  $("#stopAutoRefresh").text("Stop auto refresh");
                                  $("#stopAutoRefresh").css("color", "#0a559e");
                             }
                          });

                          rplchck = 1;

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          $("#listAllMsgsConv").css("height", "490px");
                          $(this).attr('src', '/apps/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
                          $("#stopAutoRefresh").css("visibility", "hidden");
                          $("#stopAutoRefresh").unbind("click");
                          clearInterval(intervalRfr);
                          rplchck = 0;
	              }
	           });


                   // 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 + '/' + userid,
				     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='/apps/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:15px;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 sent/received messages for the current 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 + '/' + userid,
				  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'],
					                             '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'],
					                             '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'],
					                             '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'],
					                             'table': noDupMsgData[n]['table']
					              });
					          }
					     }

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

					     // Collect the display names of the users that sent messages from the current number
					     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='diplNmAllMsg' class='dispNameListAll' title='Show all the messages for this number.'>"+ phNumberFrom +"</div>";

					     // Store the display names for the current number, 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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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 number, to be able to see them later, when clicking on the number
					     let rowMessageArrcpt = [];
					     for (let m = 0; m < convData.length; m++) {

					          if (convData[m]['direction'] == 'sent_from') {

					              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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
                                             if (rplchck == 0) {
		                                 $("#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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                             });


					     // 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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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");

		                                 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");
		                                     }

		                                     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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });

					         $(".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").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });


					     // Download MMS files when clicking on their URLs
					     $('[id^="mmsTblUrl-"]').on('click', function(evt) {

					        var clckedUrl = $(this).text();
					        var flNamearr = clckedUrl.split("/");
					        var flName = flNamearr.reverse()[0];

					        confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

					           var mmsLink = document.createElement("a");
					           mmsLink.setAttribute('href', clckedUrl);
					           mmsLink.setAttribute('download', flName);
                                                   mmsLink.setAttribute('target', '_blank');
					           document.body.appendChild(mmsLink);
					           mmsLink.click();
					           mmsLink.remove();
					        });

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

				  },
				  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); });

                }

                $('[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='/apps/sms_relentless/img/dots.svg'></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='stopAutoRefreshtf'>Stop auto refresh</div><div id='refreshMsgsConvtf' title='Refresh list'></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 style='display:block;width:100%;height:14px;'><img id='expandWindowRpl' src='/apps/sms_relentless/img/arrowDown.svg' title='Expand to send a message'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/apps/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;'></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 });

                   var intervalRfr = 0;
                   var rplchck = 0;

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

	           // 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') == '/apps/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          $("#listAllMsgsFromTo").css("height", "618px");
	                  $(this).attr('src', '/apps/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');
                          $("#stopAutoRefreshtf").css("visibility", "visible");
                          intervalRfr = setInterval(function() { $("#refreshMsgsConvtf").click(); }, 5000);

                          $("#stopAutoRefreshtf").text("Stop auto refresh");
                          $("#stopAutoRefreshtf").css("color", "#0a559e");

                          $("#stopAutoRefreshtf").unbind("click");
                          $("#stopAutoRefreshtf").click(function() { 
                             if ($("#stopAutoRefreshtf").text() == "Stop auto refresh") {
                                  clearInterval(intervalRfr);
                                  $("#stopAutoRefreshtf").text("Start auto refresh");
                                  $("#stopAutoRefreshtf").css("color", "#04957b");
                             } else {
                                  clearInterval(intervalRfr);
                                  intervalRfr = setInterval(function() { $("#refreshMsgsConvtf").click(); }, 5000);
                                  $("#stopAutoRefreshtf").text("Stop auto refresh");
                                  $("#stopAutoRefreshtf").css("color", "#0a559e");
                             }
                          });

                          rplchck = 1;

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          $("#listAllMsgsFromTo").css("height", "490px");
                          $(this).attr('src', '/apps/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
                          $("#stopAutoRefreshtf").css("visibility", "hidden");
                          $("#stopAutoRefreshtf").unbind("click");
                          clearInterval(intervalRfr);
                          rplchck = 0;
	              }
	           });


                   // 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 + '/' + userid,
				     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='/apps/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:15px;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 + '/' + userid,
				  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) {
						var c = new Date(a.date);
						var d = new Date(b.date);
						return c-d;
					     });
		                             convData.reverse();

					     // 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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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
		                             if (rplchck == 0) {
		                                 $("#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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                             });


					     // 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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });


					     // Download MMS files when clicking on their URLs
					     $('[id^="mmsTblUrl-"]').on('click', function(evt) {

					        var clckedUrl = $(this).text();
					        var flNamearr = clckedUrl.split("/");
					        var flName = flNamearr.reverse()[0];

					        confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

					           var mmsLink = document.createElement("a");
					           mmsLink.setAttribute('href', clckedUrl);
					           mmsLink.setAttribute('download', flName);
                                                   mmsLink.setAttribute('target', '_blank');
					           document.body.appendChild(mmsLink);
					           mmsLink.click();
					           mmsLink.remove();
					        });

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

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

                   getMsgsPerNmbr(clckPhNumber);

                   $("#refreshMsgsConvtf").click(function() { getMsgsPerNmbr(clckPhNumber); });
                }

                $('[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='/apps/sms_relentless/img/dots.svg'></div>";
                   addDNameWindow += "<a id='closeDisNmWindow' title='Close this window'></a>";
                   addDNameWindow += "<div style='display:block;text-align:left;font-size:16px;margin:14px 22px 0px 22px;color:#353535;'>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-size:16px;font-weight:500;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 + '/' + userid,
				  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 = jQuery("#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();
                                 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 + '/' + userid,
                                   method: "POST",
                                   dataType:'text',
                                   data: {recmessagedbIDs: checkboxIds},
                                   success: function() {
                                              showAlert("The row(s) have been deleted successfully !");
                                              $('#smstables').removeClass('icon-loading');
                                              $('#receivedsmstableshow').click();
                                   },
                                   error: function() {
                                              showAlert("There was an error while deleting the selected row(s) !");
                                              $('#smstables').removeClass('icon-loading');
                                   }
                              });
                          });

                  }
               });


               // 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);


               // Download MMS files when clicking on their URLs
               $('[id^="mmsTblUrl-"]').on('click', function(evt) {

                  var clckedUrl = $(this).text();
                  var flNamearr = clckedUrl.split("/");
                  var flName = flNamearr.reverse()[0];

                  confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

		     var mmsLink = document.createElement("a");
		     mmsLink.setAttribute('href', clckedUrl);
		     mmsLink.setAttribute('download', flName);
		     mmsLink.setAttribute('target', '_blank');
		     document.body.appendChild(mmsLink);
		     mmsLink.click();
		     mmsLink.remove();
                  });

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

          },
          error: function(recdatafromdb) {
                      showAlert("Error. You can check the Nextcloud log to find more details about this issue.");
                      $('#smstables').removeClass('icon-loading');
          }
     });

     // Show the auto-refresh button
     if ($("#stopAutoRefreshSentBtn").text() == "Stop auto refresh") {
         $("#stopAutoRefreshSentBtn").click();
     }
     $("#stopAutoRefreshRec").css("display", "inline-block");
     $("#stopAutoRefreshSent").css("display", "none");

  });


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

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

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

     $.ajax({
          url: getSentUrl + '/' + userid,
          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.' /></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 title='When a 5 or 6 digits code appears in this column, the first 3 digits specify the mobile country code and the last 2 or 3 digits specify the mobile network code of the receiver. You can look up the mobile country code and then the mobile network code on https://en.wikipedia.org/wiki/Mobile_country_code#National_operators'>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='/apps/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='/apps/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='/apps/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='/apps/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>";

                         $('#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'>"+ sentparseddata[i].network +"</td><td class='pricecolumnsent'>"+ sentparseddata[i].price +"</td><td class='statuscolumnsent'>"+ sentparseddata[i].status +"</td><td class='deliveryrcptcolsent'>"+ sentparseddata[i].deliveryreceipt +"</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='/apps/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='/apps/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='/apps/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>";

                         $('#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'>"+ sentparseddata[i].network +"</td><td class='pricecolumnsent'>"+ sentparseddata[i].price +"</td><td class='statuscolumnsent'>"+ sentparseddata[i].status +"</td><td class='deliveryrcptcolsent'>"+ sentparseddata[i].deliveryreceipt +"</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 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='/apps/sms_relentless/img/dots.svg'></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='stopAutoRefresh'>Stop auto refresh</div><div id='refreshMsgsConv' title='Refresh list'></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 style='display:block;width:100%;height:14px;'><img id='expandWindowRpl' src='/apps/sms_relentless/img/arrowDown.svg' title='Expand to send a reply'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/apps/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;'></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 });

                   var intervalRfr = 0;
                   var rplchck = 0;

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

	           // 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') == '/apps/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          $("#listAllMsgsConv").css("height", "618px");
	                  $(this).attr('src', '/apps/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');
                          $("#stopAutoRefresh").css("visibility", "visible");
                          intervalRfr = setInterval(function() { $("#refreshMsgsConv").click(); }, 5000);

                          $("#stopAutoRefresh").text("Stop auto refresh");
                          $("#stopAutoRefresh").css("color", "#0a559e");

                          $("#stopAutoRefresh").unbind("click");
                          $("#stopAutoRefresh").click(function() { 
                             if ($("#stopAutoRefresh").text() == "Stop auto refresh") {
                                  clearInterval(intervalRfr);
                                  $("#stopAutoRefresh").text("Start auto refresh");
                                  $("#stopAutoRefresh").css("color", "#04957b");
                             } else {
                                  clearInterval(intervalRfr);
                                  intervalRfr = setInterval(function() { $("#refreshMsgsConv").click(); }, 5000);
                                  $("#stopAutoRefresh").text("Stop auto refresh");
                                  $("#stopAutoRefresh").css("color", "#0a559e");
                             }
                          });

                          rplchck = 1;

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          $("#listAllMsgsConv").css("height", "490px");
                          $(this).attr('src', '/apps/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
                          $("#stopAutoRefresh").css("visibility", "hidden");
                          $("#stopAutoRefresh").unbind("click");
                          clearInterval(intervalRfr);
                          rplchck = 0;
	              }
	           });


                   // 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 + '/' + userid,
				     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='/apps/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:15px;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 sent/received messages for the current 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 + '/' + userid,
				  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'],
					                             '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'],
					                             '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'],
					                             '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'],
					                             'table': noDupMsgData[n]['table']
					              });
					          }
					     }

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

					     // Collect the display names of the users that sent messages from the current number
					     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='diplNmAllMsg' class='dispNameListAll' title='Show all the messages for this number.'>"+ phNumberTo +"</div>";

					     // Store the display names for the current number, 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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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 number, to be able to see them later, when clicking on the number
					     let rowMessageArrcpt = [];
					     for (let m = 0; m < convData.length; m++) {

					          if (convData[m]['direction'] == 'sent_from') {

					              if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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
		                             if (rplchck == 0) {
		                                 $("#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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      let sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                             });


					     // 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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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");

		                                 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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });


					     // Download MMS files when clicking on their URLs
					     $('[id^="mmsTblUrl-"]').on('click', function(evt) {

					        var clckedUrl = $(this).text();
					        var flNamearr = clckedUrl.split("/");
					        var flName = flNamearr.reverse()[0];

					        confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

					           var mmsLink = document.createElement("a");
					           mmsLink.setAttribute('href', clckedUrl);
					           mmsLink.setAttribute('download', flName);
                                                   mmsLink.setAttribute('target', '_blank');
					           document.body.appendChild(mmsLink);
					           mmsLink.click();
					           mmsLink.remove();
					        });

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

				  },
				  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); });

                }

                $('[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='/apps/sms_relentless/img/dots.svg'></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='stopAutoRefreshtf'>Stop auto refresh</div><div id='refreshMsgsConvtf' title='Refresh list'></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 style='display:block;width:100%;height:14px;'><img id='expandWindowRpl' src='/apps/sms_relentless/img/arrowDown.svg' title='Expand to send a message'></div>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/apps/sms_relentless/img/dots.svg' style='padding:4px;vertical-align:top;'></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 });

                   var intervalRfr = 0;
                   var rplchck = 0;

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

	           // 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') == '/apps/sms_relentless/img/arrowDown.svg') {
                          $("#sendMsgReply").css("display", "block");
                          $("#listAllMsgsFromTo").css("height", "618px");
	                  $(this).attr('src', '/apps/sms_relentless/img/arrowUp.svg');
                          $(this).attr('title', 'Collapse');
                          $("#stopAutoRefreshtf").css("visibility", "visible");
                          intervalRfr = setInterval(function() { $("#refreshMsgsConvtf").click(); }, 5000);

                          $("#stopAutoRefreshtf").text("Stop auto refresh");
                          $("#stopAutoRefreshtf").css("color", "#0a559e");

                          $("#stopAutoRefreshtf").unbind("click");
                          $("#stopAutoRefreshtf").click(function() { 
                             if ($("#stopAutoRefreshtf").text() == "Stop auto refresh") {
                                  clearInterval(intervalRfr);
                                  $("#stopAutoRefreshtf").text("Start auto refresh");
                                  $("#stopAutoRefreshtf").css("color", "#04957b");
                             } else {
                                  clearInterval(intervalRfr);
                                  intervalRfr = setInterval(function() { $("#refreshMsgsConvtf").click(); }, 5000);
                                  $("#stopAutoRefreshtf").text("Stop auto refresh");
                                  $("#stopAutoRefreshtf").css("color", "#0a559e");
                             }
                          });

                          rplchck = 1;

	              } else {

                          $("#sendMsgReply").css("display", "none");
                          $("#listAllMsgsFromTo").css("height", "490px");
                          $(this).attr('src', '/apps/sms_relentless/img/arrowDown.svg');
                          $(this).attr('title', 'Expand to send a reply');
                          $("#stopAutoRefreshtf").css("visibility", "hidden");
                          $("#stopAutoRefreshtf").unbind("click");
                          clearInterval(intervalRfr);
                          rplchck = 0;
	              }
	           });


                   // 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 + '/' + userid,
				     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='/apps/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:15px;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 + '/' + userid,
				  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) {
						var c = new Date(a.date);
						var d = new Date(b.date);
						return c-d;
					     });
		                             convData.reverse();

					     // 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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
							       } else {
							           var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					              } else {
					                  var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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
		                             if (rplchck == 0) {
		                                 $("#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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
					                  } else {
					                      var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                             });


					     // 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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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").scrollTop($("#msgListRowCell").height() - scrlheight);
		                                 });


					         $(".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").click(function() {
						$("#frmMsgLstWrap").animate({scrollTop : 0},400);
					     });


					     // Download MMS files when clicking on their URLs
					     $('[id^="mmsTblUrl-"]').on('click', function(evt) {

					        var clckedUrl = $(this).text();
					        var flNamearr = clckedUrl.split("/");
					        var flName = flNamearr.reverse()[0];

					        confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

					           var mmsLink = document.createElement("a");
					           mmsLink.setAttribute('href', clckedUrl);
					           mmsLink.setAttribute('download', flName);
                                                   mmsLink.setAttribute('target', '_blank');
					           document.body.appendChild(mmsLink);
					           mmsLink.click();
					           mmsLink.remove();
					        });

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

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

                   getMsgsPerNmbrSec(clckPhNumber);

                   $("#refreshMsgsConvtf").click(function() { getMsgsPerNmbrSec(clckPhNumber); });
                }


                $('[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="networkcolumnsent"]').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 = jQuery("#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();
                                 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 + '/' + userid,
                                   method: "POST",
                                   dataType:'text',
                                   data: {sentmessagedbIDs: sentcheckboxIds},
                                   success: function() {
                                            showAlert("The row(s) have been deleted successfully !");
                                            $('#smstables').removeClass('icon-loading');
                                            $('#sentsmstableshow').click();
                                   },
                                   error: function() {
                                            showAlert("There was an error while deleting the selected row(s) !");
                                            $('#smstables').removeClass('icon-loading');
                                   }
                              });
                          });
                    }
                });

                // 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);


                // Download MMS files when clicking on their URLs
                $('[id^="mmsTblUrl-"]').on('click', function(evt) {

                   var clckedUrl = $(this).text();
                   var flNamearr = clckedUrl.split("/");
                   var flName = flNamearr.reverse()[0];

                   confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

		      var mmsLink = document.createElement("a");
		      mmsLink.setAttribute('href', clckedUrl);
		      mmsLink.setAttribute('download', flName);
                      mmsLink.setAttribute('target', '_blank');
		      document.body.appendChild(mmsLink);
		      mmsLink.click();
		      mmsLink.remove();
                   });

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

          },
          error: function(sentdatafromdb) {
                showAlert("Error! You can check the Nextcloud log to find more details about this issue.");
                $('#smstables').removeClass('icon-loading');
          }
     });

     // Show the auto-refresh button
     if ($("#stopAutoRefreshRecBtn").text() == "Stop auto refresh") {
         $("#stopAutoRefreshRecBtn").click();
     }
     $("#stopAutoRefreshSent").css("display", "inline-block");
     $("#stopAutoRefreshRec").css("display", "none");

  });


  // List grouped messages
  $("#groupedtableshow").on("click", function(event) {

     $('#smstables').empty();
     var getGroupedUrl = OC.generateUrl("/apps/sms_relentless/user/getgroupedtable");

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

     $.ajax({
          method: 'GET',
          url: getGroupedUrl + '/' + userid,
          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) {
			        var c = new Date(a.date);
			        var d = new Date(b.date);
			        return c-d;
		             });

                             // 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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                               } else {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[b]['status'].indexOf("delivery success") > -1 || convData[b]['status'].indexOf("Retrieved") > -1) {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
		                               } else {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                      } else {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1 || convData[m]['status'].indexOf("Retrieved") > -1) {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='`delivery success` received.'>";
                                      } else {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='This message did not receive a `delivery success` receipt. However, it is 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='/apps/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:15px;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='/apps/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:15px;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='/apps/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:15px;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='/apps/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='/apps/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') == '/apps/sms_relentless/img/arrowDown.svg') {
                                       $("#singlerowfl_"+ idnumbrfl).find(".fixedRowHeight").removeClass("fixedRowHeight");
		                       crntExpandfl.attr('src', '/apps/sms_relentless/img/arrowUp.svg');
		                   } else {
                                       $("#singlerowfl_"+ idnumbrfl).find(".groupedLstNmbr,.groupedLstNames,.groupedLstMsgs").addClass("fixedRowHeight");
                                       crntExpandfl.attr('src', '/apps/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') == '/apps/sms_relentless/img/arrowDown.svg') {
                                $("#singlerow_"+ idnumbr).find(".fixedRowHeight").removeClass("fixedRowHeight");
                                crntExpand.attr('src', '/apps/sms_relentless/img/arrowUp.svg');
                            } else {
                                $("#singlerow_"+ idnumbr).find(".groupedLstNmbr,.groupedLstNames,.groupedLstMsgs").addClass("fixedRowHeight");
                                crntExpand.attr('src', '/apps/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');
		           }
		        });


		        // Download MMS files when clicking on their URLs
		        $('[id^="mmsTblUrl-"]').on('click', function(evt) {

		           var clckedUrl = $(this).text();
		           var flNamearr = clckedUrl.split("/");
		           var flName = flNamearr.reverse()[0];

		           confirmAlert("Download this file only if you trust the sender and the domain of the URL.");

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

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

			      var mmsLink = document.createElement("a");
			      mmsLink.setAttribute('href', clckedUrl);
			      mmsLink.setAttribute('download', flName);
                              mmsLink.setAttribute('target', '_blank');
			      document.body.appendChild(mmsLink);
			      mmsLink.click();
			      mmsLink.remove();
		           });

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

          },
          error: function() {

                        showAlert("Error while attempting to get the messages from the database.");
                        $('#smstables').removeClass('icon-loading');
          }
     });
  });


  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 'Received SMS Messages' page
  $("#app-content").append("<div id='stopAutoRefreshRec'><div id='stopAutoRefreshRecBtn'>Start auto refresh</div><div id='refreshTimerRec' class='arftimer' style='--duration: 15;--size: 24;'><div class='arfmask'></div></div></div>");

  // 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>");

  $("#stopAutoRefreshRecBtn").click(function() { 
     if ($("#stopAutoRefreshRecBtn").text() == "Stop auto refresh") {
         clearInterval(intervalRfrRec);
         clearInterval(intervalRfrSent);
         $("#stopAutoRefreshRecBtn").text("Start auto refresh");
         $("#stopAutoRefreshRecBtn").css("color", "#0a559e");
         $("#refreshTimerRec").css("display", "none");
     } else {
         clearInterval(intervalRfrRec);
         clearInterval(intervalRfrSent);
         intervalRfrRec = setInterval(function() { $("#receivedsmstableshow").click(); }, 15000);
         $("#stopAutoRefreshRecBtn").text("Stop auto refresh");
         $("#stopAutoRefreshRecBtn").css("color", "#04957b");
         $("#refreshTimerRec").css("display", "inline-block");
     }
  });

  $("#stopAutoRefreshSentBtn").click(function() {
     if ($("#stopAutoRefreshSentBtn").text() == "Stop auto refresh") {
         clearInterval(intervalRfrSent);
         clearInterval(intervalRfrRec);
         $("#stopAutoRefreshSentBtn").text("Start auto refresh");
         $("#stopAutoRefreshSentBtn").css("color", "#0a559e");
         $("#refreshTimerSent").css("display", "none");
     } else {
         clearInterval(intervalRfrSent);
         clearInterval(intervalRfrRec);
         intervalRfrSent = setInterval(function() { $("#sentsmstableshow").click(); }, 15000);
         $("#stopAutoRefreshSentBtn").text("Stop auto refresh");
         $("#stopAutoRefreshSentBtn").css("color", "#04957b");
         $("#refreshTimerSent").css("display", "inline-block");
     }
  });

});
