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

  var userid = "<?php p($userId); ?>";
  var charcolorthr = 160;
  var textread = '';
  var providerUsed = '';
  var receiversNumbers = [];
  var waittime = 1000;
  var selectedid = '';
  var isMMS = 0;
  var n = 1;
  var textsizekb = 0;
  var uploadedtomms = [];
  var msgtotalflsize = 0;
  var readtxtfile = [];
  var readjpg = [];
  var readpng = [];
  var readgif = [];
  var readbmp = [];
  var readtif = [];
  var readmp4 = [];
  var chosenProvider = '';
  var chosenProvFullName = '';
  var infonotecontent = '';
  var validExtensions = [];
  var maximumsize = 750;
  var maxsizenonimage = 600;
  var maximumfilenumber = 10;
  var maximumsizeinit = 750;

  // Adjust the path, so that the uploaded pdf files can be previewed while Nextcloud is served on a subdomain or on a subdirectory, by Nginx or by Apache
  var locHref = window.location.href;
  var pathSplit = locHref.split('/');
  var firstPathEl = '';
  if (pathSplit.length == 7) { firstPathEl = '/' + pathSplit[3]; }

  // Clean the SMS_Relentless/temp_files directory
  var cleanflUrl = OC.generateUrl("/apps/sms_relentless/user/cleantempdir");

  $.ajax({
          url: cleanflUrl + '/' + userid,
          type: "POST",
          data: { userid: userid },
          cache: false,
          processData: false,
          contentType: false
  });
  
  // Check the available balance
  $("#smsprovider").on("change", function () {

     var provider = $('#smsprovider :selected').val();

     if (provider == "Telnyx") {

        var gettelbalance = function() {

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

          var gettelbalanceUrl = OC.generateUrl("/apps/sms_relentless/user/getbalancetel");

          $.ajax({
              url: gettelbalanceUrl + '/' + userid,
              type: "POST",
              data: { userid: userid },
              cache: false,
              processData: false,
              contentType: false,
              success: function(currentbalancetel) {

                     $('#currentbalance').empty();
                     $('#currentbalance').text(currentbalancetel);
                     $('#currentbalance').removeClass('icon-loading');
              }
          });
        }

        gettelbalance();

     } else if (provider == "Plivo") {

          var getnexbalance = function() {

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

            var getnexbalanceUrl = OC.generateUrl("/apps/sms_relentless/user/getbalancenex");

            $.ajax({
                url: getnexbalanceUrl + '/' + userid,
                type: "POST",
                data: { userid: userid },
                cache: false,
                processData: false,
                contentType: false,
                success: function(currentbalancenex) {

                     $('#currentbalance').empty();
                     $('#currentbalance').text(currentbalancenex);
                     $('#currentbalance').removeClass('icon-loading');
                }
            });
          }

          getnexbalance();

     } else if (provider == "Twilio") {

          var gettwilbalance = function() {

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

            var gettwilbalanceUrl = OC.generateUrl("/apps/sms_relentless/user/getbalancetwil");

            $.ajax({
                url: gettwilbalanceUrl + '/' + userid,
                type: "POST",
                data: { userid: userid },
                cache: false,
                processData: false,
                contentType: false,
                success: function(currentbalancetwil) {

                     $('#currentbalance').empty();
                     $('#currentbalance').text(currentbalancetwil);
                     $('#currentbalance').removeClass('icon-loading');
                }
            });
          }

          gettwilbalance();

     } else if (provider == "Flowroute") {

          var getflowbalance = function() {

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

            var getflowbalanceUrl = OC.generateUrl("/apps/sms_relentless/user/getbalanceflow");

            $.ajax({
                url: getflowbalanceUrl + '/' + userid,
                type: "POST",
                data: { userid: userid },
                cache: false,
                processData: false,
                contentType: false,
                success: function(currentbalanceflow) {

                     $('#currentbalance').empty();
                     $('#currentbalance').text(currentbalanceflow);
                     $('#currentbalance').removeClass('icon-loading');
                }
            });
          }

          getflowbalance();

       } else if (provider == "") {
                $('#currentbalance').text("");
                $('#currentbalance').removeClass('icon-loading');
       }
  });

  // Select the Sender ID
  $("#selectcalleridbttn").on("click", function(event) {

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

     var getsmsnumbersUrl = OC.generateUrl("/apps/sms_relentless/user/getsmsnumbers");

     $.ajax({
          url: getsmsnumbersUrl + '/' + userid,
          type: "POST",
          data: { userid: userid },
          cache: false,
          processData: false,
          contentType: false,
          success: function(currentnmbrs) {

                     $('#currentsmsnmbrs').empty();
                     $('#currentsmsnmbrs').append("<option value='' selected='selected' disabled class='optselectsmsnb'>Choose an ID</option>");

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

                         if (emptycheck != '') {
                             $('#currentsmsnmbrs').append("<option value='"+indsmsnmb+"' class='optselectsmsnb'>"+indsmsnmb+"</option>");
                         }
                     });

                     $('#selectcalleridbttn').removeClass('icon-loading');
          }
     });
  });

  // If a Sender ID is selected, get it
  $("#currentsmsnmbrs").on("change", function () {

          if ($("#currentsmsnmbrs option[value='']").length > 0) {

              selectedid = $('#currentsmsnmbrs :selected').val();
              var setIdsplit = selectedid.split(":");
	      chosenProvider = setIdsplit[0];

              // Set the valid MMS file extensions, maximum MMS message size, maximum message size when non-jpeg/png/gif files are included, maximum number of files and the info note content, for the chosen provider
	      if (chosenProvider == "Tx") {
		  validExtensions = ["jpg", "jpeg", "png", "gif", "mp3", "ogg", "amr", "mp4", "3gpp", "pdf", "vcf", "vcard", "txt"];
		  // Maximum size of message text + files in KB
		  maximumsize = 1024;
                  maximumsizeinit = 1024;
		  maxsizenonimage = 600;
		  maximumfilenumber = 10;
                  chosenProvFullName = "Telnyx";
                  infonotecontent = "To send an MMS, you can upload media files or pick them from Nextcloud. You can add up to 10 files. For Telnyx, if you send only jpeg/jpg, png \
                                     or gif files, the size of all the files plus the size of the text should be \
                                     <a href='https://support.telnyx.com/en/articles/4450150-faqs-about-mms-at-telnyx' style='color:#1b60ba' target='_blank' \
                                     rel='noreferrer noopener'>1024 KB</a> or less. If you send files of other formats, the total size of the files plus the size of the text should \
                                     be 600 KB or less. Allowed formats are jpeg/jpg, png, gif, mp3, ogg, amr, mp4, 3gpp, pdf, vcf, vcard and txt. By default, Telnyx accounts are \
                                     limited to <a href='https://support.telnyx.com/en/articles/3102823-mms-sending-and-receiving' style='color:#1b60ba' target='_blank' \
                                     rel='noreferrer noopener'>1 MMS message per second</a>. Deliverability of MMS messages depends on the carrier and device of the receiver. \
                                     Carriers can reject MMS messages with files exceeding a certain size. The best deliverability is achieved when sending jpeg/jpg, png or \
                                     gif files, with a total message size of 600 KB or less. Telnyx allows sending MMS messages only from US or Canadian phone numbers to other US \
                                     or Canadian phone numbers. Although all the specified file types can be added to the MMS, only the most common media file types (jpeg/jpg, png, \
                                     gif, mp4, ogg, etc.) can be previewed in the adjoining pane.";
                  $("#tooltiptextfourth").html(infonotecontent);
	      } else if (chosenProvider == "Pl") {
		  validExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "wav", "wave", "mp4", "amr", "mpg", "mpeg", "3gpp", "3gpp2", "vcf", "vcard", "x-vcard", "ics", "ical", "ifb", 
                                     "icalendar", "csv", "txt", "pdf", "xls"];
		  // Maximum size of message text + files in KB
		  maximumsize = 5120;
                  maximumsizeinit = 5120;
		  maxsizenonimage = 600;
		  maximumfilenumber = 10;
                  chosenProvFullName = "Plivo";
                  infonotecontent = "To send an MMS, you can upload media files or pick them from Nextcloud. You can add up to 10 files. For Plivo, if you send only jpeg/jpg, png \
                                     or gif files, the size of all the files plus the size of the text should be \
                                     <a href='https://support.plivo.com/hc/en-us/articles/360042280091-What-are-the-MMS-upload-size-limits-and-file-restrictions-' \
                                     style='color:#1b60ba' target='_blank' rel='noreferrer noopener'>5120 KB</a> or less. If you send files of other formats, the total size \
                                     of the files plus the size of the text should be 600 KB or less. <a href='https://support.plivo.com/hc/en-us/articles/360042273051' \
                                     style='color:#1b60ba' target='_blank' rel='noreferrer noopener'>Allowed formats</a> are jpeg/jpg, png, gif, bmp, wav/wave, mp4, amr, mpg, mpeg, 3gpp, \
                                     3gpp2, vcf, vcard, x-vcard, ics, ical, ifb, icalendar, csv, txt, pdf and xls. Deliverability of MMS messages depends on the carrier and \
                                     device of the receiver. Carriers can reject MMS messages with files exceeding a certain size. The best deliverability is \
                                     achieved when sending jpeg/jpg, png or gif files, with a total message size of 600 KB or less. Plivo allows sending MMS messages \
                                     only from US or Canadian phone numbers to other US or Canadian phone numbers. Although all the specified file types can be added to the MMS, \
                                     only the most common media file types (jpeg/jpg, png, gif, wav/wave, mp4, etc.) can be previewed in the adjoining pane.";
                  $("#tooltiptextfourth").html(infonotecontent);
	      } else if (chosenProvider == "Tw") {
		  validExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "au", "snd", "l16", "wav", "wave", "aiff", "pcm", "mp4", "ogg", "ra", "ram", "3gpp", 
                                     "3gpp2", "ac3", "webm", "amr", "mpg", "mpeg", "mov", "qt", "h261", "h263", "h264", "vcf", "vcard", "x-vcard", "csv", "rtf", "ics", "ical", "ifb", 
                                     "icalendar", "directory", "pdf", "pkpass"];
		  // Maximum size of message text + files in KB
		  maximumsize = 5120;
                  maximumsizeinit = 5120;
		  maxsizenonimage = 600;
		  maximumfilenumber = 10;
                  chosenProvFullName = "Twilio";
                  infonotecontent = "To send an MMS, you can upload media files or pick them from Nextcloud. You can add up to 10 files. For Twilio, if you send only jpeg/jpg, png \
                                     or gif files, the size of all the files plus the size of the text should be \
                                     <a href='https://support.twilio.com/hc/en-us/articles/360018832773-Twilio-Programmable-SMS-Supported-File-Types-and-Size-Limits-for-MMS-Media-Messages' \
                                     style='color:#1b60ba' target='_blank' rel='noreferrer noopener'>5120 KB</a> or less. If you send files of other formats, the total size \
                                     of the files plus the size of the text should be 600 KB or less. <a href='https://www.twilio.com/docs/sms/accepted-mime-types' \
                                     style='color:#1b60ba' target='_blank' rel='noreferrer noopener'>Allowed formats</a> are jpeg/jpg, png, gif, bmp, tiff/tif, au, snd, l16, \
                                     wav/wave, aiff, pcm, mp4, ogg, ra, ram, 3gpp, 3gpp2, ac3, webm, amr, mpg, mpeg, mov, qt, h261, h263, h264, vcf, vcard, x-vcard, csv, rtf, ics, \
                                     ical, ifb, icalendar, directory, pdf and pkpass. Deliverability of MMS messages depends on the carrier and device of the receiver. Carriers \
                                     can reject MMS messages with files exceeding a certain size. The best deliverability is achieved when sending jpeg/jpg, png or gif files, \
                                     with a total message size of 600 KB or less. Twilio allows sending MMS messages from US or Canadian phone numbers to other US or Canadian phone \
                                     numbers. However, MMS messages sent internationally will be converted to SMS messages with URL links to the included files. Although all the \
                                     specified file types can be added to the MMS, only the most common media file types (jpeg/jpg, png, gif, wav/wave, mp4, ogg, etc.) can be \
                                     previewed in the adjoining pane."
                  $("#tooltiptextfourth").html(infonotecontent);
	      } else if (chosenProvider == "Fl") {
		  validExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "3gp", "mp4", "avi", "amr", "midi", "wav", "wave", "ac3", "mp3"];
		  // Maximum size of message text + files in KB
		  maximumsize = 750;
                  maximumsizeinit = 750;
		  maxsizenonimage = 600;
		  maximumfilenumber = 10;
                  chosenProvFullName = "Flowroute";
                  infonotecontent = "To send an MMS, you can upload media files or pick them from Nextcloud. You can add up to 10 files. For Flowroute, if you send only jpeg/jpg, \
                                     png or gif files, the size of all the files plus the size of the text should be \
                                     <a href='https://developer.flowroute.com/api/messages/v2.1/send-an-mms/' style='color:#1b60ba' target='_blank' \
                                     rel='noreferrer noopener'>750 KB</a> or less. If you send files of other formats, the total \
                                     size of the files plus the size of the text should be 600 KB or less. \
                                     <a href='https://support.flowroute.com/937402-What-file-types-does-Flowroute-MMS-support' style='color:#1b60ba' target='_blank' \
                                     rel='noreferrer noopener'>Allowed formats</a> are jpeg/jpg, png, gif, bmp, 3gp, mp4, avi, amr, midi, wav/wave, ac3 and mp3. Flowroute accounts are \
                                     limited to <a href='https://developer.flowroute.com/docs/sms-mms-best-practices/#sending-and-receiving-limitations' style='color:#1b60ba' \
                                     target='_blank' rel='noreferrer noopener'>1 MMS message per second</a>. Deliverability of MMS messages depends on the carrier and device \
                                     of the receiver. Carriers can reject MMS messages with files exceeding a certain size. The best deliverability is achieved when sending \
                                     jpeg/jpg, png or gif files, with a total message size of 600 KB or less. Flowroute allows sending MMS messages only from US or Canadian phone \
                                     numbers to other US or Canadian phone numbers. Although all the specified file types can be added to the MMS, only the most common media file \
                                     types (jpeg/jpg, png, gif, wav/wave, mp4, etc.) can be previewed in the adjoining pane."
                  $("#tooltiptextfourth").html(infonotecontent);
	      }

          } else { selectedid = ''; }
  });

  // Check the checkbox to send SMS message to multiple recipients
  $('#tomultchckbx').change(function() {
      if ($(this).is(':checked')) {
          $("#multiplerecivers").css("display", "block");
          $("#smstodiv").css("visibility", "hidden");
          $("#smsto").val("");

          receiversNumbers.length = 0;

      } else {
          $("#multiplerecivers").css("display", "none");
          $("#smstodiv").css("visibility", "visible");

          // Remove the uploaded file(s) if any
          $("#induploadfile").remove();

          receiversNumbers.length = 0;
      }
  });

  // Upload the file with the recipients' phone numbers
  $("#uploadfileforsms").change(function(e) {

     $("#fileuploadednm").empty();

     receiversNumbers.length = 0;

     OC.msg.startAction("#sms_upload_msg", t("sms_relentless", "Uploading ..."));

     var baseUrl = OC.generateUrl("/apps/sms_relentless/user/upload_numbers_file");

     var formData = new FormData();
     formData.append('uploadfileforsms', $('#uploadfileforsms')[0].files[0]);

     var fileup = $('#uploadfileforsms').val();
     var fileuptrim = fileup.split('\\').pop();

     $('#fileuploadednm').append("<div id='induploadfile' class='indgenflcls'><div id='indfilediv' class='indivflcls'>" + fileuptrim + "</div><div id='indivflremove' class='indupfldl'>X</div></div><br>");

     var extension = fileup.replace(/^.*\./, '');

     if (extension == fileup) {
         extension = "";
     } else {
         extension = extension.toLowerCase();
     }

     var validExtensionsmrec = ["txt", "csv"];

     if (jQuery.inArray(extension, validExtensionsmrec) != -1) {

       if (selectedid != '') {

               $.ajax({
                 url: baseUrl + '/' + userid,
                 type: "POST",
                 data: formData,
                 cache: false,
                 processData: false,
                 contentType: false,
                 success: function(numberarray) {

		    if (numberarray.length > 0) {

		        // Get the array of the receivers' phone numbers
		        if (chosenProvider == "Tx") {

		             for(key in numberarray) {
		                 receiversNumbers.push("+"+numberarray[key]);
		             }

		        } else if (chosenProvider == "Pl") {

		             for(key in numberarray) {
		                 receiversNumbers.push(numberarray[key]);
		             }

		          } else if (chosenProvider == "Tw") {

		             for(key in numberarray) {
		                 receiversNumbers.push(numberarray[key]);
		             }
		          } else if (chosenProvider == "Fl") {

		             for(key in numberarray) {
		                 receiversNumbers.push(numberarray[key]);
		             }
		          }

		    } else {
		          alert("The uploaded file doesn't seem to contain any valid phone numbers. Please upload a txt or csv file that contains phone numbers separated by commas, semicolons, vertical bars or new lines.");
		    }
                            
                    // Preview the uploaded file
                    var smsfilename = e.target.files[0].name;
                    var baseUrl = OC.generateUrl("/remote.php/webdav/SMS_Relentless/temp_files/"+smsfilename);

                    var reader = new FileReader();
                    reader.readAsText(e.target.files[0]);
                    reader.onload = function(e) {
                          $("#smstables").empty();
                          $("#smstables").append(e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>'));
                    };

                    $("#smstables").show();

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

                  },
                  error: function(){
                     alert('Error!');
                  }
               });

        } else {
               alert("Please choose a Sender ID from the Set ID drop-down list!");
               $('#sms_upload_msg').hide();
               $('#smstables').removeClass('icon-loading');
        }

     } else {
          alert('The file type is not supported ! Supported formats are txt and csv.');
          $('#pf_upload_msg').hide();
          $('#smstables').removeClass('icon-loading');

          $("#induploadfile").remove();
          $("#sms_upload_msg").hide();
     }

     //Preview uploaded file when clicked
     $("#indfilediv").on("click", function() {

          var smsfilename = e.target.files[0].name;
          var baseUrl = OC.generateUrl("/remote.php/webdav/SMS_Relentless/temp_files/"+smsfilename);

          var reader = new FileReader();
          reader.readAsText(e.target.files[0]);
          reader.onload = function(e) {
                  $("#smstables").empty();
                  $("#smstables").append(e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>'));
          };

          $("#smstables").show();
          $('#sms_upload_msg').hide();
          $('#smstables').removeClass('icon-loading');
     });

     // Remove selected file
     $("#indivflremove").on("click", function() {

          $("#induploadfile").remove();
          $("#sms_upload_msg").hide();

          receiversNumbers.length = 0;

     });

  });

  // Show the number of characters entered in the SMS textarea and the text size in KB
  $("#smstext").on('input', function() {

     $("#char_count").css("display", "inline");

     $("#mtextSize").css("display", "inline");

     $(".maxmessagelength").css("display", "inline-block");

     $("#countchnb").text($(this).val().length);

     var textsize = encodeURIComponent($(this).val()).replace(/%[A-F\d]{2}/g, 'U').length;
     textsizekb = parseFloat(textsize/1024).toFixed(4);
     $("#textsizeinkb").text(textsizekb);

     if ($(this).val().length > charcolorthr) {
         $("#char_count").css("color", "#BB2E4B");
     } else {
         $("#char_count").css("color", "#4cbc86;");
     }

  });


  // Check the checkbox to send file(s) as MMS
  $('#mediafilechckbx').change(function() {

      if ($(this).is(':checked')) {

          isMMS = 1;
          if (selectedid == '') {
              alert("Please, first choose a Sender ID from the Set ID drop-down list !");
              $(this).prop("checked", false);
              isMMS = 0;
              return;
          }
          $("#upmediafiles").css("display", "block");
          $("#submitsms").prop("value", "Send MMS");

      } else {

          isMMS = 0;
          $("#upmediafiles").css("display", "none");
          $("#submitsms").prop("value", "Send SMS");

          // Remove the uploaded file(s) if any
          $(".indgenflclsmms").each(function() { $(this).remove(); });
          $(".indgenpckfls").each(function() { $(this).remove(); });

          uploadedtomms = [];
          n = 1;

          msgtotalflsize = 0;

          $("#filestotsize").hide();
      }
  });


  // Check if the uploaded files' format is jpeg, png or gif and adjust the maximum cumulative size of files, if necessary
  function adjustMaximumSize(uploadedtomms) {
				      
      var nonimgcheck = 0;
      for (var u = 0; u < uploadedtomms.length; u++) {
	   var crupfl = uploadedtomms[u];
	   var extensionup = crupfl.replace(/^.*\./, '');
	   if ($.inArray(extensionup, ["jpg", "jpeg", "png", "gif"]) === -1) {
	       nonimgcheck = 1;
	   }
      }

      if (nonimgcheck == 0) { maximumsize = maximumsizeinit; }
  }

  // Upload files to be sent as MMS
  $("#uploadfileformms").change(function(e) {

     OC.msg.startAction("#pf_upload_msg", t("sms_relentless", "Uploading ..."));
     $('#smstables').addClass('icon-loading');
     $('#filestotsize').show();

     var userid = "<?php p($userId); ?>";
     var baseUrl = OC.generateUrl("/apps/sms_relentless/user/uploadfile");

     var formData = new FormData();
     formData.append('uploadfileformms', $('#uploadfileformms')[0].files[0]);

     var currentflsize = $('#uploadfileformms')[0].files[0].size;

     // Add the size of the current file to the total size of all the files
     msgtotalflsize += Math.floor((currentflsize/1024) * 100)/100;

     var fileup = $('#uploadfileformms').val();
     var fileuptrim = fileup.split('\\').pop();

     if ($.inArray(fileuptrim, uploadedtomms) != -1) {
         var duplicatescheck = 1;
     } else { 
         var duplicatescheck = 0;
     }

     var extension = fileup.replace(/^.*\./, '');

     if (extension == fileup) {
         extension = "";
     } else {
         extension = extension.toLowerCase();
     }

     // If the uploaded file's format is different from jpeg, png or gif, the maximum allowed size of the message will be lower
     if (($.inArray(extension, ["jpg", "jpeg", "png", "gif"]) === -1) && (msgtotalflsize <= Number(maximumsize) - Number(textsizekb))) {
         maximumsize = maxsizenonimage;
     }

     if ($.inArray(extension, validExtensions) != -1) {

       if (duplicatescheck == 0) {

         if (msgtotalflsize <= Number(maximumsize) - Number(textsizekb)) {

            if (n <= maximumfilenumber) {

               $.ajax({
                 url: baseUrl + '/' + userid,
                 type: "POST",
                 data: formData,
                 cache: false,
                 processData: false,
                 contentType: false,
                 success: function(totalflsize) {

                   uploadedtomms.push(fileuptrim);

                   $('#filessizetext').text(totalflsize);

                   var rectotfilesz = parseFloat(totalflsize);

                   if (rectotfilesz <= maximumsize) {
                       $('#submitsms').attr("disabled", false);
                       $('#filestotsize').css('color', '#189558');
                   } else {
                       $('#filestotsize').css('color', '#ba3555');
                       alert("Error ! For "+ chosenProvFullName +", for the chosen files format, the size of all the included files plus the size of the text cannot exceed "+ maximumsize +" KB !");
                       $('#submitsms').attr("disabled", true);
                       $('#smstables').removeClass('icon-loading');
                       $('#pf_upload_msg').hide();
                   }

                   $('#mmsfileuploadednm').append("<div class='indgenflclsmms'><div id='"+n+"indfilediv' class='indivflcls'>" + n + ") " + fileuptrim + "</div><div class='indupfldl'>X</div></div>");
                   n++;

                   // Preview the file when you click on its name
                   $("div:visible[id*='indfilediv']").each(function() {

                        $(this).on("click", function(eventclck) {

                           $("#mmsfoldersview").css("display", "inline-block");
                           var mmsfilenameinit = $(this).text();
                           var mmsfilenamesec = mmsfilenameinit.substring(mmsfilenameinit.indexOf(" ") + 1);
                           var mmsfilename = mmsfilenamesec.replace("X","");
                           var baseUrl = firstPathEl+"/remote.php/webdav/SMS_Relentless/temp_files/"+mmsfilename;
                           var extenlst = mmsfilename.replace(/^.*\./, '');

                           if (extenlst == mmsfilename) {
                               extenlst = "";
                           } else {
                               extenlst = extenlst.toLowerCase();
                           }

                           if (extenlst == 'jpg' || extenlst == 'jpeg') {
                                  $("#smstables").empty();
                                  $("#smstables").append('<img style="width:auto;height:auto" id="uploadedjpg" src="#" />');
                                  $("#uploadedjpg").attr('src', readjpg[mmsfilename]);
                           } else if (extenlst == 'png') {
                                  $("#smstables").empty();
                                  $("#smstables").append('<img style="width:auto;height:auto" id="uploadedpng" src="#" />');
                                  $("#uploadedpng").attr('src', readpng[mmsfilename]);
                           } else if (extenlst == 'gif') {
                                  $("#smstables").empty();
                                  $("#smstables").append('<img style="width:auto;height:auto" id="uploadedgif" src="#" />');
                                  $("#uploadedgif").attr('src', readgif[mmsfilename]);
                           } else if (extenlst == 'bmp') {
                                  $("#smstables").empty();
                                  $("#smstables").append('<img style="width:auto;height:auto" id="uploadedbmp" src="#" />');
                                  $("#uploadedbmp").attr('src', readbmp[mmsfilename]);
                           } else if (extenlst == 'tif' || extenlst == 'tiff') {
                                  var tiffile = '/remote.php/webdav/SMS_Relentless/temp_files/'+mmsfilename;
                                  var xhr = new XMLHttpRequest();
                                  xhr.responseType = 'arraybuffer';
                                  xhr.open('GET', tiffile);
                                  xhr.onload = function (evnt) {
                                      var tiff = new Tiff({buffer: xhr.response});
                                      var tifcanvas = tiff.toCanvas();
                                      $("#smstables").empty();
                                      $("#smstables").append(tifcanvas);
                                  };
                                  xhr.send();
                           } else if (extenlst == 'pdf') {
                                  var viewerclick = OC.generateUrl('/apps/files_pdfviewer/?file={file}', {file: baseUrl});
                                  var $iframe = $('<iframe id="docclickview" style="width:100%;height:100%;display:block;position:absolute;top:0;left:0;z-index:1041;" src="' + viewerclick + '" sandbox="allow-scripts allow-same-origin allow-popups allow-modals"></iframe>');
                                  $("#smstables").empty();
                                  $("#smstables").append($iframe);
                           } else if (extenlst == 'txt') {
                                  $("#smstables").empty();
                                  $("#smstables").append(readtxtfile[mmsfilename]);
                           } else if (extension == 'mp4') {
                                  $("#smstables").empty();
                                  $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmp4" src="'+ baseUrl +'"></video>');
		           } else if (extension == 'ogg') {
		                  $("#smstables").empty();
		                  $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedogg" src="'+ baseUrl +'"></video>');
		           } else if (extension == 'avi') {
		                  $("#smstables").empty();
		                  $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedavi" src="'+ baseUrl +'" type="video/avi"></video>');
		           } else if (extension == 'mpg' || extension == 'mpeg') {
		                  $("#smstables").empty();
		                  $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmpg" src="'+ baseUrl +'"></video>');
		           } else if (extension == 'wav' || extension == 'wave') {
		                  $("#smstables").empty();
		                  $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedwav" src="'+ baseUrl +'"></audio>');
		           } else if (extension == 'mp3') {
		                  $("#smstables").empty();
		                  $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmp3" src="'+ baseUrl +'" type="audio/mp3"></audio>');
		           } else if (extension == 'midi') {
		                  $("#smstables").empty();
		                  $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmidi" src="'+ baseUrl +'" type="audio/midi"></audio>');
		           }

                           $("#smstables").show();
                           $("#mmsfoldersview").hide();
                        });
                   });

                   // Remove uploaded files
                   $('[class*="indupfldl"]').last().click(function() {

                           var userid = "<?php p($userId); ?>";
                           var baseUrl = OC.generateUrl("/apps/sms_relentless/user/removeupfile");

                           var removedfilenameinit = $(this).closest('[class*="indgenflclsmms"]').find('[class*="indivflcls"]').text();

                           var removedfilesplit = removedfilenameinit.split(") ");
                           var removedflnb = parseInt(removedfilesplit[0]);

                           $(this).closest('[class*="indgenflclsmms"]').find('[class*="indivflcls"]').hide();
                           $(this).hide();

                           var removedfilename = removedfilenameinit.substring(removedfilenameinit.indexOf(" ") + 1);

                           uploadedtomms = $.grep(uploadedtomms, function(value) {
                                           return value != removedfilename;
                           });

                           $.ajax({
                                   url: baseUrl + '/' + userid,
                                   type: "POST",
                                   data: {removedfilename: removedfilename},
                                   success: function(totalflsize) {

                                      msgtotalflsize = totalflsize;
                                      $('#filessizetext').text(totalflsize);

                                      adjustMaximumSize(uploadedtomms);

                                      // Check message size
                                      var rectotfilesz = parseFloat(totalflsize);

                                      if (rectotfilesz <= Number(maximumsize) - Number(textsizekb)) {
                                          $('#submitsms').attr("disabled", false);
                                          $('#filestotsize').css('color', '#189558');
                                      } else {
                                          $('#filestotsize').css('color', '#ba3555');
                                          alert("Error ! For "+ chosenProvFullName +", for the chosen files format, the total size of the included files plus the size of the text cannot exceed "+ maximumsize +" KB !");
                                          $('#submitsms').attr("disabled", true);
                                      }

                                      // Rewrite order numbers for files that follow
                                      --n;
                                      $("div:visible[id*='indfilediv']").each(function() {

                                          var getdivtext =  $(this).text();
                                          var splitdivtext = getdivtext.split(") ");
                                          var currentnbvalue = parseInt(splitdivtext[0]);
                                          var newnbvalue = currentnbvalue - 1;

                                          if (currentnbvalue > removedflnb) {
                                              var replacedstr = newnbvalue + ") " + splitdivtext[1];
                                              $(this).text(replacedstr);
                                          }
                                      });

                                      $("div:visible[id*='indflpicked']").each(function() {

                                          var getdivtext =  $(this).text();
                                          var splitdivtext = getdivtext.split(") ");
                                          var currentnbvalue = parseInt(splitdivtext[0]);
                                          var newnbvalue = currentnbvalue - 1;

                                          if (currentnbvalue > removedflnb) {
                                              var replacedstr = newnbvalue + ") " + splitdivtext[1];
                                              $(this).text(replacedstr);
                                          }
                                      });

                                   },
                                   error: function() {
                                          alert('Error removing file(s)!');
                                   }
                           });

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

                   // Preview the uploaded file
                   $("#mmsfoldersview").css("display", "inline-block");
                   var mmsfilename = e.target.files[0].name;
                   var baseUrl = firstPathEl+"/remote.php/webdav/SMS_Relentless/temp_files/"+mmsfilename;


                   if (extension == 'jpg' || extension == 'jpeg') {
                              $("#smstables").empty();
                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedjpg" src="#" />');

                              var reader = new FileReader();
                              reader.onload = function (e) {
                                  readjpg[mmsfilename] = e.target.result;
                                  $("#uploadedjpg").attr('src', readjpg[mmsfilename]);
                              }
                              reader.readAsDataURL(e.target.files[0]);
                   } else if (extension == 'png') {
                              $("#smstables").empty();
                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedpng" src="#" />');

                              var reader = new FileReader();
                              reader.onload = function (e) {
                                  readpng[mmsfilename] = e.target.result;
                                  $("#uploadedpng").attr('src', readpng[mmsfilename]);
                              }
                              reader.readAsDataURL(e.target.files[0]);

                   } else if (extension == 'gif') {
                              $("#smstables").empty();
                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedgif" src="#" />');

                              var reader = new FileReader();
                              reader.onload = function (e) {
                                  readgif[mmsfilename] = e.target.result;
                                  $("#uploadedgif").attr('src', readgif[mmsfilename]);
                              }
                              reader.readAsDataURL(e.target.files[0]);

                   } else if (extension == 'bmp') {
                              $("#smstables").empty();
                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedbmp" src="#" />');

                              var reader = new FileReader();
                              reader.onload = function (e) {
                                  readbmp[mmsfilename] = e.target.result;
                                  $("#uploadedbmp").attr('src', readbmp[mmsfilename]);
                              }
                              reader.readAsDataURL(e.target.files[0]);

                   } else if (extension == 'tif' || extension == 'tiff') {
                              var tiffile = '/remote.php/webdav/SMS_Relentless/temp_files/'+mmsfilename;
                              var xhr = new XMLHttpRequest();
                              xhr.responseType = 'arraybuffer';
                              xhr.open('GET', tiffile);
                              xhr.onload = function (e) {
                                  var tiff = new Tiff({buffer: xhr.response});
                                  var tifcanvas = tiff.toCanvas();
                                  $("#smstables").empty();
                                  $("#smstables").append(tifcanvas);
                              };
                              xhr.send();

                   } else if (extension == 'pdf') {
                              var viewer = OC.generateUrl('/apps/files_pdfviewer/?file={file}', {file: baseUrl});
                              var $iframe = $('<iframe id="docviewer" style="width:100%;height:100%;display:block;position:absolute;top:0;left:0;z-index:1041;" src="' + viewer + '" sandbox="allow-scripts allow-same-origin allow-popups allow-modals"></iframe>');
                              $("#smstables").empty();
                              $("#smstables").append($iframe);

                   } else if (extension == 'txt') {
                              var reader = new FileReader();
                              reader.readAsText(e.target.files[0]);
                              reader.onload = function(e) {
                                  readtxtfile[mmsfilename] = e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>');
                                  $("#smstables").empty();
                                  $("#smstables").append(readtxtfile[mmsfilename]);
                              };
                   } else if (extension == 'mp4') {
                              $("#smstables").empty();
                              $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmp4" src="'+ baseUrl +'"></video>');
                   } else if (extension == 'ogg') {
                              $("#smstables").empty();
                              $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedogg" src="'+ baseUrl +'"></video>');
                   } else if (extension == 'avi') {
                              $("#smstables").empty();
                              $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedavi" src="'+ baseUrl +'" type="video/avi"></video>');
                   } else if (extension == 'mpg' || extension == 'mpeg') {
                              $("#smstables").empty();
                              $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmpg" src="'+ baseUrl +'"></video>');
                   } else if (extension == 'wav' || extension == 'wave') {
                              $("#smstables").empty();
                              $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedwav" src="'+ baseUrl +'"></audio>');
                   } else if (extension == 'mp3') {
                              $("#smstables").empty();
                              $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmp3" src="'+ baseUrl +'" type="audio/mp3"></audio>');
                   } else if (extension == 'midi') {
                              $("#smstables").empty();
                              $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmidi" src="'+ baseUrl +'" type="audio/midi"></audio>');
                   }

                   $("#smstables").show();
                   $('#pf_upload_msg').hide();
                   $('#smstables').removeClass('icon-loading');
                   $("#mmsfoldersview").hide();
                 },
                 error: function(data){
                     alert('Error uploading file!');
                 }
               });

            } else {
                  msgtotalflsize -= Math.floor((currentflsize/1024) * 100)/100;
                  adjustMaximumSize(uploadedtomms);

                  alert("Error ! You cannot send more than 10 files in one MMS !");
                  $('#pf_upload_msg').hide();
                  $('#smstables').removeClass('icon-loading');
            }
         } else {
              msgtotalflsize -= Math.floor((currentflsize/1024) * 100)/100;
              adjustMaximumSize(uploadedtomms);

              alert('Error ! For '+ chosenProvFullName +', for the chosen files format, the size of all the included files plus the size of the text cannot be greater than '+ maxsizenonimage +' KB !');
              $('#pf_upload_msg').hide();
              $('#smstables').removeClass('icon-loading');
         }
       } else {
            msgtotalflsize -= Math.floor((currentflsize/1024) * 100)/100;
            adjustMaximumSize(uploadedtomms);

            alert("Error ! There is already a file named '"+fileuptrim+"' in the 'SMS_Relentless/temp_files' folder !");
            $('#pf_upload_msg').hide();
            $('#smstables').removeClass('icon-loading');
       }

     } else {
          msgtotalflsize -= Math.floor((currentflsize/1024) * 100)/100;
          adjustMaximumSize(uploadedtomms);

          alert('The file type is not supported ! Supported extensions for '+ chosenProvFullName +' are: '+ validExtensions.join(", ") +'.');
          $('#pf_upload_msg').hide();
          $('#smstables').removeClass('icon-loading');
     }
  });


  // Pick file(s) from Nextcloud, to send as MMS
  var mmsfilename = null;

  $("#choosefilen").on("click", function(evn) {

                OC.dialogs.filepicker(
                        t('settings', "Select a file to send as MMS."),
                        function (path) {

                              OC.msg.startAction("#pf_choose_msg", t("sms_relentless", "Please wait ..."));
                              $('#smstables').addClass('icon-loading');
                              $('#filestotsize').show();

                              var userid = "<?php p($userId); ?>";
                              var baseUrl = OC.generateUrl("/apps/sms_relentless/user/pickfile");

                              mmsfilename = path.split('/').pop();

                              if ($.inArray(mmsfilename, uploadedtomms) != -1) {
                                  var duplicatescheck = 1;
                              } else var duplicatescheck = 0;

                              var extension = mmsfilename.replace(/^.*\./, '');

                              if (extension == mmsfilename) {
                                  extension = "";
                              } else {
                                  extension = extension.toLowerCase();
                              }

			      // If the picked file's format is different from jpeg, png or gif, the maximum allowed size of the message will be lower
			      if ($.inArray(extension, ["jpg", "jpeg", "png", "gif"]) === -1) {
				   maximumsize = maxsizenonimage;
			      }

                              if ($.inArray(extension, validExtensions) != -1) {

                                 if (duplicatescheck == 0) {

                                    if (n <= maximumfilenumber) {

                                       $.ajax({
                                          url: baseUrl + '/' + userid,
                                          type: "POST",
                                          data: {path: path},
                                          success: function(pickresult) {

                                                uploadedtomms.push(mmsfilename);

                                                var totalflsize = pickresult[0];
                                                var pickedflsize = pickresult[1];

                                                // Check message size
                                                var rectotfilesz = parseFloat(totalflsize);
                                                var filesplustextsize = Number(rectotfilesz) + Number(textsizekb);

                                                if (filesplustextsize <= maximumsize) {

                                                    $("#mmsfoldersview").css("display", "inline-block");

                                                    $('#filespickednc').append("<div class='indgenpckfls'><div id='"+n+"indflpicked' class='indivflpckd'>" + n + ") " + mmsfilename + "</div><div class='indpckfldl'>X</div></div>");
                                                    n++;

                                                    msgtotalflsize = totalflsize;
                                                    $('#filessizetext').text(totalflsize);
                                                    $('#filestotsize').css('color', '#189558');

                                                } else {

                                                    uploadedtomms = uploadedtomms.filter(function(e) { return e !== mmsfilename });
                                                    $('#filestotsize').css('color', '#ba3555');
                                                    msgtotalflsize -= pickedflsize;
                                                    var baseUrlindrm = OC.generateUrl("/apps/sms_relentless/user/removeupfile");

                                                    $.ajax({
                                                        url: baseUrlindrm + '/' + userid,
                                                        type: "POST",
                                                        data: {removedfilename: mmsfilename},
                                                        success: function(totalflsize) {

                                                                          $('#filessizetext').text(totalflsize);
                                                                          $('#filestotsize').css('color', '#189558');
                                                                          adjustMaximumSize(uploadedtomms);

                                                        },
                                                        error: function(totalflsize) {
                                                                          $('#filessizetext').text(totalflsize);
                                                                          if (parseFloat(totalflsize) > maximumsize) {
                                                                              $('#filestotsize').css('color', '#ba3555');
                                                                          } else { $('#filestotsize').css('color', '#189558'); }
                                                                          alert("Error while trying to remove the last picked file from the 'SMS_Relentless/temp_files' directory!"); 
                                                        }
                                                    });

                                                    alert("Error ! For "+ chosenProvFullName +", for the chosen files format, the size of all the included files plus the size of the text cannot exceed "+ maximumsize +" KB !");

                                                }


                                                // Preview each file when you click on its name
                                                $("div:visible[id*='indflpicked']").each(function() {
                                                   $(this).on("click", function(event) {

                                                      var mmsfilenameinit = $(this).text();
                                                      var mmsfilenamesec = mmsfilenameinit.substring(mmsfilenameinit.indexOf(" ") + 1);
                                                      var mmsfilenamesp = mmsfilenamesec.replace("X","");
                                                      var baseUrl = firstPathEl+"/remote.php/webdav/SMS_Relentless/temp_files/"+mmsfilenamesp;
                                                      var extenlst = mmsfilenamesp.replace(/^.*\./, '');

                                                      if (extenlst == mmsfilenamesp) {
                                                           extenlst = "";
                                                      } else {
                                                           extenlst = extenlst.toLowerCase();
                                                      }


                                                      if (extenlst == 'jpg' || extenlst == 'jpeg') {
                                                              $("#smstables").empty();
                                                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedjpg" src="'+ baseUrl +'" />');
                                                      } else if (extenlst == 'png') {
                                                              $("#smstables").empty();
                                                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedpng" src="'+ baseUrl +'" />');
                                                      } else if (extenlst == 'gif') {
                                                              $("#smstables").empty();
                                                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedgif" src="'+ baseUrl +'" />');
                                                      } else if (extenlst == 'bmp') {
                                                              $("#smstables").empty();
                                                              $("#smstables").append('<img style="width:auto;height:auto" id="uploadedbmp" src="'+ baseUrl +'" />');
                                                      } else if (extenlst == 'tif' || extenlst == 'tiff') {
                                                              var tiffile = '/remote.php/webdav/SMS_Relentless/temp_files/'+mmsfilenamesp;
                                                              var xhr = new XMLHttpRequest();
                                                              xhr.responseType = 'arraybuffer';
                                                              xhr.open('GET', tiffile);
                                                              xhr.onload = function (evnt) {
                                                                  var tiff = new Tiff({buffer: xhr.response});
                                                                  var tifcanvas = tiff.toCanvas();
                                                                  $("#smstables").empty();
                                                                  $("#smstables").append(tifcanvas);
                                                              };
                                                              xhr.send();
                                                      } else if (extenlst == 'pdf') {
                                                              var viewerclick = OC.generateUrl('/apps/files_pdfviewer/?file={file}', {file: baseUrl});
                                                              var $iframe = $('<iframe id="docclickview" style="width:100%;height:100%;display:block;position:absolute;top:0;left:0;z-index:1041;" src="' + viewerclick + '" sandbox="allow-scripts allow-same-origin allow-popups allow-modals"></iframe>');
                                                              $("#smstables").empty();
                                                              $("#smstables").append($iframe);
                                                      } else if (extenlst == 'txt') {
                                                              $("#smstables").empty();
                                                              $("#smstables").append(readtxtfile[mmsfilenamesp]);
                                                      } else if (extension == 'mp4') {
							      $("#smstables").empty();
							      $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmp4" src="'+ baseUrl +'"></video>');
						      } else if (extension == 'ogg') {
							      $("#smstables").empty();
							      $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedogg" src="'+ baseUrl +'"></video>');
						      } else if (extension == 'avi') {
							      $("#smstables").empty();
							      $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedavi" src="'+ baseUrl +'" type="video/avi"></video>');
						      } else if (extension == 'mpg' || extension == 'mpeg') {
							      $("#smstables").empty();
							      $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmpg" src="'+ baseUrl +'"></video>');
						      } else if (extension == 'wav' || extension == 'wave') {
							      $("#smstables").empty();
							      $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedwav" src="'+ baseUrl +'"></audio>');
						      } else if (extension == 'mp3') {
							      $("#smstables").empty();
							      $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmp3" src="'+ baseUrl +'" type="audio/mp3"></audio>');
						      } else if (extension == 'midi') {
							      $("#smstables").empty();
							      $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmidi" src="'+ baseUrl +'" type="audio/midi"></audio>');
						      }


                                                      $("#smstables").show();
                                                      $("#mmsfoldersview").hide();
                                                   });
                                                });


                                                // Remove picked files
                                                $('[class*="indpckfldl"]').last().click(function() {
                                                    var userid = "<?php p($userId); ?>";
                                                    var baseUrl = OC.generateUrl("/apps/sms_relentless/user/removeupfile");

                                                    var removedfilenameinit = $(this).closest('[class*="indgenpckfls"]').find('[class*="indivflpckd"]').text();

                                                    var removedfilesplit = removedfilenameinit.split(") ");
                                                    var removedflnb = parseInt(removedfilesplit[0]);

                                                    $(this).closest('[class*="indgenpckfls"]').find('[class*="indivflpckd"]').hide();
                                                    $(this).hide();
                                                    var removedfilename = removedfilenameinit.substring(removedfilenameinit.indexOf(" ") + 1);

                                                    uploadedtomms = $.grep(uploadedtomms, function(value) {
                                                             return value != removedfilename;
                                                    });

                                                    $.ajax({
                                                        url: baseUrl + '/' + userid,
                                                        type: "POST",
                                                        data: {removedfilename: removedfilename},
                                                        success: function(totalflsize) {

                                                             msgtotalflsize = totalflsize;
                                                             $('#filessizetext').text(totalflsize);
                                                             adjustMaximumSize(uploadedtomms);

                                                             // Check message size
                                                             var rectotfilesz = parseFloat(totalflsize);

                                                             if (rectotfilesz > maximumsize) {
                                                                 $('#filestotsize').css('color', '#ba3555');
                                                                 alert("Error ! For "+ chosenProvFullName +", for the chosen files format, the size of all the included files plus the size of the text cannot exceed "+ maximumsize +" KB !");
                                                                 $('#submitsms').attr("disabled", true);
                                                             } else {
                                                                 $('#submitsms').attr("disabled", false);
                                                                 $('#filestotsize').css('color', '#189558');
                                                               }

                                                             // Rewrite order numbers for files that follow
                                                             --n;
                                                             $("div:visible[id*='indflpicked']").each(function() {

                                                                  var getdivtext =  $(this).text();
                                                                  var splitdivtext = getdivtext.split(") ");
                                                                  var currentnbvalue = parseInt(splitdivtext[0]);
                                                                  var newnbvalue = currentnbvalue - 1;

                                                                  if (currentnbvalue > removedflnb) {
                                                                      var replacedstr = newnbvalue + ") " + splitdivtext[1];
                                                                      $(this).text(replacedstr);
                                                                  }
                                                             });
                                                        },
                                                        error: function() {
                                                             alert('Error !');
                                                        }
                                                    });

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


		                                // Preview the picked file
		                                $("#mmsfoldersview").css("display", "inline-block");
		                                var flUrl = firstPathEl+"/remote.php/webdav/SMS_Relentless/temp_files/"+mmsfilename;
		                                var pickUrl = OC.generateUrl("/apps/sms_relentless/user/getpickedfile");


						if (extension == 'jpg' || extension == 'jpeg') {

		                                            $("#smstables").empty();
		                                            $("#smstables").append('<img style="width:auto;height:auto" id="uploadedjpg" src="'+ flUrl +'" />');

		                                } else if (extension == 'png') {

		                                            $("#smstables").empty();
		                                            $("#smstables").append('<img style="width:auto;height:auto" id="uploadedpng" src="'+ flUrl +'" />');

		                                } else if (extension == 'gif') {

		                                            $("#smstables").empty();
		                                            $("#smstables").append('<img style="width:auto;height:auto" id="uploadedgif" src="'+ flUrl +'" />');

		                                } else if (extension == 'bmp') {

	                                                    $("#smstables").empty();
		                                            $("#smstables").append('<img style="width:auto;height:auto" id="uploadedbmp" src="'+ flUrl +'" />');

		                                } else if (extension == 'tif' || extension == 'tiff') {

		                                       var tiffile = '/remote.php/webdav/SMS_Relentless/temp_files/'+mmsfilename;
		                                       var xhr = new XMLHttpRequest();
		                                       xhr.responseType = 'arraybuffer';
		                                       xhr.open('GET', tiffile);
		                                       xhr.onload = function (event) {
		                                           var tiff = new Tiff({buffer: xhr.response});
		                                           var tifcanvas = tiff.toCanvas();
		                                           $("#smstables").empty();
		                                           $("#smstables").append(tifcanvas);
		                                       };
		                                       xhr.send();

		                                } else if (extension == 'pdf') {

		                                       var viewer = OC.generateUrl('/apps/files_pdfviewer/?file={file}', {file: flUrl});
		                                       var $iframe = $('<iframe id="docviewer" style="width:100%;height:100%;display:block;position:absolute;top:0;left:0;z-index:1041;" src="' + viewer + '" sandbox="allow-scripts allow-same-origin allow-popups allow-modals"></iframe>');
		                                       $("#smstables").empty();
		                                       $("#smstables").append($iframe);

		                                } else if (extension == 'txt') {

							     $.get(flUrl, function(textdata) {
		                                               readtxtfile[mmsfilename] = textdata.replace(/(?:\r\n|\r|\n)/g, '<br>');
		                                               $("#smstables").empty();
							       $("#smstables").append(readtxtfile[mmsfilename]);
							     });

		                                } else if (extension == 'mp4') {
						       $("#smstables").empty();
						       $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmp4" src="'+ baseUrl +'"></video>');
						} else if (extension == 'ogg') {
						       $("#smstables").empty();
						       $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedogg" src="'+ baseUrl +'"></video>');
						} else if (extension == 'avi') {
						       $("#smstables").empty();
						       $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedavi" src="'+ baseUrl +'" type="video/avi"></video>');
						} else if (extension == 'mpg' || extension == 'mpeg') {
						       $("#smstables").empty();
						       $("#smstables").append('<video width="100%" height="auto" controls><source id="uploadedmpg" src="'+ baseUrl +'"></video>');
						} else if (extension == 'wav' || extension == 'wave') {
						       $("#smstables").empty();
						       $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedwav" src="'+ baseUrl +'"></audio>');
						} else if (extension == 'mp3') {
						       $("#smstables").empty();
						       $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmp3" src="'+ baseUrl +'" type="audio/mp3"></audio>');
						} else if (extension == 'midi') {
						       $("#smstables").empty();
						       $("#smstables").append('<audio width="100%" height="auto" controls><source id="uploadedmidi" src="'+ baseUrl +'" type="audio/midi"></audio>');
						}


		                                $("#smstables").show();

		                                $('#pf_choose_msg').hide();
		                                $('#smstables').removeClass('icon-loading');
		                                $("#mmsfoldersview").hide();

                                          },

                                          error: function(data){
                                             alert('Error!');
                                          }

                                       });

                                    } else {
                                        alert("Error ! You cannot send more than "+ maximumfilenumber +" files in one MMS message !");
                                        $('#pf_choose_msg').hide();
                                        $('#smstables').removeClass('icon-loading');
                                      }
                                 } else {
                                      alert("Error ! There is already a file named '"+ mmsfilename +"' in the 'SMS_Relentless/temp_files' folder !");
                                      $('#pf_choose_msg').hide();
                                      $('#smstables').removeClass('icon-loading');
                                   }

                              } else {
                                   alert('The file type is not supported ! Supported extensions for '+ chosenProvFullName +' are: '+ validExtensions.join(", ") +'.');
                                   $('#pf_choose_msg').hide();
                                   $('#smstables').removeClass('icon-loading');
                                }

                        }
                );
  });



  // Send the SMS/MMS message
  $("#submitsms").on("click", function(event) {

     if (isMMS == 0) { var sendingtype = 'SMS'; } else { var sendingtype = 'MMS'; }
     OC.msg.startAction("#sms_submit_msg", t("sms_relentless", "Sending "+ sendingtype +" ... Please wait !"));
     $("#sms_submit_msg").css("display", "inline-block");
     $('#smstables,#recSmsTable,#sentSmsTable').addClass('icon-loading');

     if (selectedid != '') { 

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

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

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

         // Get the interval between message consecutive sending requests, if it's the case
         if ($('#tomultchckbx').is(':checked')) {

             var numbersfile = 1;
             var initinterval = $("#multsmsinterval").val();
             var secinterval = initinterval.replace(/[^0-9]/g, "");

             if (secinterval != '') {
                 var tertinterval = parseInt(secinterval);
                     waittime = tertinterval;
             }

         } else {

             var numbersfile = 0;
             var toNumberinit = $('#smsto').val();
             var toNumber = toNumberinit.replace(/[^0-9,]/g, "");
             var toNumbersec = toNumber.split(",");

                 for (var i = 0; i < toNumbersec.length; i++) {
                      toNumbersec[i] = "+" + toNumbersec[i];
                 }

                 receiversNumbers = toNumbersec.filter(function(v){return v!==""});
         }

         if (numbersfile == 0 && $('#smsto').val().trim() == '') { receiversNumbers.length = 0; }

         var smstext = $("#smstext").val();

         if (receiversNumbers.length != 0) {

              if (smstext != '') {
                  $.ajax({
                     url: relbaseUrl + '/' + userid,
                     type: "POST",
                     data: {
                           receiversPhoneNbs: receiversNumbers,
                           fromsender: selectedsender,
                           waitinterval: waittime,
                           sentsmstext: smstext,
                           ismms: isMMS,
                           mmsfiles: uploadedtomms
                         },
                     success: function() {

                           if (receiversNumbers.length == 1) {
                               alert("The message has been sent ! You can press the 'Sent SMS Messages' button to check the current status and the delivery receipt for this message. If they don't appear immediately, wait about 10 seconds and press the button again.");
                           } else { alert("The messages have been sent ! You can press the 'Sent SMS Messages' button to check the current status and the delivery receipt for each message. If they don't appear immediately, wait about 10 seconds and press the button again."); }

                           $('#sms_submit_msg').hide();
                           $('#smstables,#recSmsTable,#sentSmsTable').removeClass('icon-loading');
                     },
                     error: function() {
                           alert("An error occurred! Please check the recipient's phone number and your settings !");
                           $('#sms_submit_msg').hide();
                           $('#smstables,#recSmsTable,#sentSmsTable').removeClass('icon-loading');
                     }
                  });
              } else {
                     alert("Please enter a message in the text box !");
                     $('#sms_submit_msg').hide();
                     $('#smstables,#recSmsTable,#sentSmsTable').removeClass('icon-loading');
              }
         } else if (receiversNumbers.length == 0 && !($('#tomultchckbx').is(':checked'))) {
                 alert("Please enter the recipient's phone number !");
                 $('#sms_submit_msg').hide();
                 $('#smstables,#recSmsTable,#sentSmsTable').removeClass('icon-loading');
         } else if (receiversNumbers.length == 0 && $('#tomultchckbx').is(':checked')) {
                 alert("Please upload a txt or csv file that contains phone numbers separated by commas, semicolons, vertical bars or new lines !");
                 $('#sms_submit_msg').hide();
                 $('#smstables,#recSmsTable,#sentSmsTable').removeClass('icon-loading');
         }
     } else {
           alert("Please choose a Sender ID from the Set ID drop-down list !");
           $('#smstables,#recSmsTable,#sentSmsTable').removeClass('icon-loading');
           $('#sms_submit_msg').hide();
     }

  });

  // Check the checkbox to delete old messages from the database
  $('#deleteoldchckbox').change(function() {
     if ($(this).is(':checked')) {
         $("#deleteoldsms").css("display", "block");
     } else {
         $("#deleteoldsms").css("display", "none");
     }
  });

  // Set the height of 3 info notes
  $('#setcalleridtp').css('height', $(window).height() - 160);
  $('#tonmbrformat').css('height', $(window).height() - 260);
  $('#uploadfileinfo').css('height', $(window).height() - 390);

  $(window).resize(function() { 
    $('#setcalleridtp').css('height', $(window).height() - 160);
    $('#tonmbrformat').css('height', $(window).height() - 260);
    $('#uploadfileinfo').css('height', $(window).height() - 390);
  });

