/**
 * @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;

  // 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) {
               alert("An error occurred. Please check your settings!");
        }
  });

  // 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(parseddata) {

                $('#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();

                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;
                     } else {
                         var procrcmessage = parseddata[i].message;
                     }

                     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.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.'></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.'></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.'></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 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' class='oc-dialog-close' 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'><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>";
                   allfrmtomsg += "<table id='frmMsgLstTbl'></table></div>";
                   allfrmtomsg += "<input type='submit' id='sendMsgToNmb' value='Send a message to "+ clckPhNumber +"'>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/apps/sms_relentless/img/dots.svg'></div>";
                   allfrmtomsg += "</div>";

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

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

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

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

                      if ($("#currentsmsnmbrs").val() == null) { $("#selectcalleridbttn").click(); }
                      var clckPhNumberst = clckPhNumber.replace("+", "");
                      $("#smsto").val(clckPhNumberst);
                      $("#smstext").focus();
                      $("#listAllMsgsFromTo").remove();
                      $("#recTblOverlay").remove();
                   });

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

                   // Get the sent/received messages for the current phone number, from the database
		   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 = groupedpernb[i].user_id;
					     }

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

				             var modmessage = '';
				             if (groupedpernb[i].author_displayname) {
						 modmessage = "<span class='msgAuthorNameGrp'>"+ groupedpernb[i].author_displayname + ":</span>" + 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': modmessage,
				                       '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'],
			                                     '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'],
			                                     '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'],
			                                     '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'],
			                                     '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) {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
					               } else {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
					               }
					               rowMessageArrpn.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
					               } else {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
					               }
					               rowMessageArrpn.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArr.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArr.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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("");

				     $("#frmMsgLstTbl").append("<tr class='groupedrowsbody'><td><div class='groupedLstNamespn'>"+ displayNames +"</div></td><td><div id='msgListRowCell' class='groupedLstMsgspn'>"+ convDataPerNmbr +"</div><div id='arrowupWrap'><div id='upArrowSmall' title='Scroll to the top'></div></div></td></tr>");


			             // Store the messages for the current number, to be able to see them later, when clicking on the number
			             var rowMessageArrcpt = [];
//			             for (var m = convData.length - 1; m >= 0; m--) {
			             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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArrcpt.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArrcpt.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
			                  }
			             }

			             messagesPerNmbr[clckPhNumber] = rowMessageArrcpt;

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

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

                                         clickNmb++;

                                         var crefnb = (clickNmb + 1) * nmbToBeLoaded;

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

                                         var rowMessageArrAdd = [];

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

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

			                          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1) {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                          } else {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                          }
			                          rowMessageArrAdd.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                          } else {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                          }
			                          rowMessageArrAdd.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 { 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;

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

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

                                             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");
                                         $("#loadMoreMsgs").css("display", "block");
                         
                                         $("#loadMoreMsgs").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) {
                                             $("#loadMoreMsgsusr").css("display", "block");
                                             var nmbToBeLoaded = nmbTblDefault;
                                         } else { 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;

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

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

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

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

                $('[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' class='oc-dialog-close' title='Close this window'></a>";
                   addDNameWindow += "<div style='display:block;text-align:left;font-size:16px;margin:14px 22px 0px 22px;color:#353535;'>Since this phone number is not associated with any current Nextcloud user, 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) - 152) +"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) {
                                               alert(respupdname);
                                               $("#disNameWindow").remove();
                                               $("#recTblOverlay").remove();
                                  },
				  error: function() {
                                               alert("Error while attempting to save the new Display Name to the database.");
                                               $("#disNameWindow").remove();
                                               $("#recTblOverlay").remove();
                                  }
			     });

                      } else { alert("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');

                $(".receivedrowsbody").hide();

                $('#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) {
                     alert("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);
                             }
                          });

                          if (confirm("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'.")) {

                              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() {
                                            alert("The row(s) have been deleted successfully !");
                                            $('#smstables').removeClass('icon-loading');
                                            $('#receivedsmstableshow').click();
                                   },
                                   error: function() {
                                            alert("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);
          },
          error: function(recdatafromdb) {
                      alert("An error occurred. Please check your settings!");
                      $('#smstables').removeClass('icon-loading');
          }
     });

  });


  // 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(sentparseddata) {


                $('#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();

                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;
                     } else {
                         var procmessage = sentparseddata[i].message;
                     }

                     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.'></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.'></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 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' class='oc-dialog-close' 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'><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>";
                   allfrmtomsg += "<table id='frmMsgLstTbl'></table></div>";
                   allfrmtomsg += "<input type='submit' id='sendMsgToNmb' value='Send a message to "+ clckPhNumber +"'>";
                   allfrmtomsg += "<div id='draglstMsgmWindowsc'><img src='/apps/sms_relentless/img/dots.svg'></div>";
                   allfrmtomsg += "</div>";

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

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

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

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

                      if ($("#currentsmsnmbrs").val() == null) { $("#selectcalleridbttn").click(); }
                      var clckPhNumberst = clckPhNumber.replace("+", "");
                      $("#smsto").val(clckPhNumberst);
                      $("#smstext").focus();
                      $("#listAllMsgsFromTo").remove();
                      $("#recTblOverlay").remove();
                   });

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

                   // Get the sent/received messages for the current phone number, from the database
		   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 = groupedpernb[i].user_id;
					     }

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

				             var modmessage = '';
				             if (groupedpernb[i].author_displayname) {
						 modmessage = "<span class='msgAuthorNameGrp'>"+ groupedpernb[i].author_displayname + ":</span>" + 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': modmessage,
				                       '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'],
			                                     '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'],
			                                     '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'],
			                                     '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'],
			                                     '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) {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
					               } else {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
					               }
					               rowMessageArrpn.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
					               } else {
					                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
					               }
					               rowMessageArrpn.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArr.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArr.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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("");

				     $("#frmMsgLstTbl").append("<tr class='groupedrowsbody'><td><div class='groupedLstNamespn'>"+ displayNames +"</div></td><td><div id='msgListRowCell' class='groupedLstMsgspn'>"+ convDataPerNmbr +"</div><div id='arrowupWrap'><div id='upArrowSmall' title='Scroll to the top'></div></div></td></tr>");


			             // 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArrcpt.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                      } else {
			                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                      }
			                      rowMessageArrcpt.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ convData[m]['message'] +"</div><div style='display:block;margin:6px 0px 0px 4px;font-size:12.5px;color:#353535;'>"+ convData[m]['date'] +"</div></div>");
			                  }
			             }

			             messagesPerNmbr[clckPhNumber] = rowMessageArrcpt;

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

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

                                         clickNmb++;

                                         var crefnb = (clickNmb + 1) * nmbToBeLoaded;

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

                                         var rowMessageArrAdd = [];

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

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

			                          if (convData[m]['status'].indexOf("delivered") > -1 || convData[m]['status'].indexOf("delivery success") > -1) {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                          } else {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                          }
			                          rowMessageArrAdd.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
			                          } else {
			                              var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
			                          }
			                          rowMessageArrAdd.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 { 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;

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

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

                                             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");
                                         $("#loadMoreMsgs").css("display", "block");
                         
                                         $("#loadMoreMsgs").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) {
                                             $("#loadMoreMsgsusr").css("display", "block");
                                             var nmbToBeLoaded = nmbTblDefault;
                                         } else { 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;

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

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

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

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


                $('[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');

                $(".sentrowsbody").hide();

                $('#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) {
                       alert("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);
                             }
                          });

                          if (confirm("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'.")) {

                              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() {
                                            alert("The row(s) have been deleted successfully !");
                                            $('#smstables').removeClass('icon-loading');
                                            $('#sentsmstableshow').click();
                                   },
                                   error: function() {
                                            alert("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);
          },
          error: function(sentdatafromdb) {
                alert("An error occurred!");
                $('#smstables').removeClass('icon-loading');
          }
     });

  });

  // 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 = groupedparsed[i].user_id;
			     }

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

                             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'],
                                                     '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'],
                                                     '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'],
                                                     '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'],
                                                     '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) {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
		                               } else {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
		                               }
		                               rowMessageArrpn.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
		                               } else {
		                                   var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
		                               }
		                               rowMessageArrpn.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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) {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
                                      } else {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
                                      }
                                      rowMessageArr.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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) {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/check.svg' title='Message delivered.'>";
                                      } else {
                                          var sentMsgStatus = "<img src='/apps/sms_relentless/img/question.svg' title='There were issues while sending the message.'>";
                                      }
                                      rowMessageArr.push("<div style='display:block;width:97%;float:right;margin:4px 6px 4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fbff;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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 style='display:block;width:97%;float:left;margin:4px 0px;padding:8px 10px;border:0;border-radius:6px;background-color:#f2fff8;'><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;white-space:normal;'>"+ 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');
		           }
		        });

          },
          error: function() {

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

});