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

  // 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',
          dataType:'text',
          success: function(recdatafromdb) {

                parseddata = $.parseJSON(recdatafromdb);

                $('#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.'>DB<br>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++) {
                     $("#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'>"+parseddata[i].from+"</td><td class='tocolrec'>"+parseddata[i].to+"</td><td class='messagecolumnrec'>"+parseddata[i].message+"</td></tr>");
                }

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

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

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

                // 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",
          dataType:'text',
          success: function(sentdatafromdb) {

                sentparseddata = $.parseJSON(sentdatafromdb);

                $('#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.'>DB<br>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++) {
                     $('#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'>"+sentparseddata[i].from+"</td><td class='tocolumnsent'>"+sentparseddata[i].to+"</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'>"+sentparseddata[i].message+"</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');

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

  });

});
