/**
 * @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 readtxtfile = [];
  var readhtmlfile = [];
  var readjpg = [];
  var readpng = [];

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

  // Check the available balance
  $("#checkbalance").on("click", function(event) {

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

     var getbalanceUrl = OC.generateUrl("/apps/pax_fax/user/getbalance");

     $.ajax({
          url: getbalanceUrl,
          type: "POST",
          cache: false,
          processData: false,
          contentType: false,
          success: function(faxbalance) {

                     if (faxbalance != "n/a") {
                         var balanceindlrs = faxbalance / 100;
                         var balanceproc = "$ " + balanceindlrs.toFixed(2);
                         $('#currentbalance').text(balanceproc);
                     } else { 
                         $('#currentbalance').text("n/a"); 
                     }

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

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

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

     var getfaxnumbersUrl = OC.generateUrl("/apps/pax_fax/user/getfaxnumbers");
     var selectednmbr = null;

     $.ajax({
          url: getfaxnumbersUrl,
          type: "POST",
          cache: false,
          processData: false,
          contentType: false,
          success: function(faxnmbrs) {

                    $('#currentfaxnmbrs').empty();
                    $('#currentfaxnmbrs').append("<option value='' selected='selected' disabled class='optselectfxnb'>Choose an ID</option>");
                    if (faxnmbrs.provider == "phaxio") {
                        $('#currentfaxnmbrs').append("<option value='' class='optselectfxnb'>Blank Caller ID</option>");
                    }

                    $.each(faxnmbrs.nblist, function(key, indfxnmb) {
                           $('#currentfaxnmbrs').append("<option value='"+indfxnmb+"' class='optselectfxnb'>"+indfxnmb+"</option>");
                    });

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

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

  $.ajax({
          url: cleanflUrl,
          type: "POST",
          cache: false,
          processData: false,
          contentType: false
  });

  var n = 1;
  var uploadedtofax = [];

  // Upload files to be faxed
  $("#uploadfileforfax").change(function(e){

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

     var baseUrl = OC.generateUrl("/apps/pax_fax/user/uploadfile");

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

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

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

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

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

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

     var validExtensions = ["pdf", "doc", "docx", "tif", "tiff", "jpg", "jpeg", "odt", "txt", "html", "png"];

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

       if (duplicatescheck == 0) {

         if (currentflsize < 20971520) {

            if (n < 21) {

               uploadedtofax.push(fileuptrim);

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

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

                   // Check if the total file size is over 20 MB
                   var rectotfilesz = parseFloat(totalflsize.replace(" MB", ""));

                   if (rectotfilesz > 20.00) {
                       $('#filestotsize').css('color', '#ba3555');
                       alert("Error ! You can't send files having a total size of more than 20 MB in one fax call ! Please consider removing files so that the total files size would drop to or below 20 MB");
                       $('#submitfax').attr("disabled", true);
                   } else {
                       $('#submitfax').attr("disabled", false);
                       $('#filestotsize').css('color', '#1eb16a');
                     }


                   $('#fileuploadednm').append("<div class='indgenflcls'><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) {
                           var faxfilenameinit = $(this).text();
                           var faxfilenamesec = faxfilenameinit.substring(faxfilenameinit.indexOf(" ") + 1);
                           var faxfilename = faxfilenamesec.replace("X","");
                           var baseUrl = firstPathEl+"/remote.php/webdav/Pax_Fax/temp_files/"+faxfilename;
                           var extenlst = faxfilename.replace(/^.*\./, '');

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

                           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>');
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append($iframe);
                           } else if (extenlst == 'txt') {
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append(readtxtfile[faxfilename]);
                           } else if (extenlst == 'html') {
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append(readhtmlfile[faxfilename]);
                           } else if (extenlst == 'jpg' || extenlst == 'jpeg') {
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append('<img style="width:100%;height:100%" id="uploadedjpg" src="#" />');
                                  $("#uploadedjpg").attr('src', readjpg[faxfilename]);
                           } else if (extenlst == 'png') {
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append('<img style="width:100%;height:100%" id="uploadedpng" src="#" />');
                                  $("#uploadedpng").attr('src', readpng[faxfilename]);
                           } else if (extenlst == 'odt') {
                                  $("#faxdocpreview").empty();
                                  function odfInit() {
                                     var odfelement = document.getElementById("faxdocpreview");
                                     odfcanvas = new odf.OdfCanvas(odfelement);
                                     odfcanvas.load(baseUrl);
                                  }
                                  window.setTimeout(odfInit, 0);
                           } else if (extenlst == 'tif' || extenlst == 'tiff') {
                                  var tiffile = '/remote.php/webdav/Pax_Fax/temp_files/'+faxfilename;
                                  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();
                                      $("#faxdocpreview").empty();
                                      $("#faxdocpreview").append(tifcanvas);
                                  };
                                  xhr.send();
                           }

                           $("#faxdocpreview").show();
                           $("#faxfoldersview").hide();
                        });
                   });

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

                           var baseUrl = OC.generateUrl("/apps/pax_fax/user/removeupfile");

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

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

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

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

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

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

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

                                      // Check file size
                                      var rectotfilesz = parseFloat(totalflsize.replace(" MB", ""));

                                      if (rectotfilesz > 20.00) {
                                          $('#filestotsize').css('color', '#ba3555');
                                             alert("Error ! You can't send files having a total size of more than 20 MB in one fax call ! Please consider removing files so that the total files size would drop to or below 20 MB");
                                          $('#submitfax').attr("disabled", true);
                                      } else {
                                          $('#submitfax').attr("disabled", false);
                                          $('#filestotsize').css('color', '#1eb16a');
                                        }

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

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

                   // Preview the uploaded file
                   var faxfilename = e.target.files[0].name;
                   var baseUrl = firstPathEl+"/remote.php/webdav/Pax_Fax/temp_files/"+faxfilename;

                   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>');
                              $("#faxdocpreview").empty();
                              $("#faxdocpreview").append($iframe);
                   } else if (extension == 'txt') {
                              var reader = new FileReader();
                              reader.readAsText(e.target.files[0]);
                              reader.onload = function(e) {
                                  readtxtfile[faxfilename] = e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>');
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append(readtxtfile[faxfilename]);
                              };
                   } else if (extension == 'html') {
                              var reader = new FileReader();
                              reader.readAsText(e.target.files[0]);
                              reader.onload = function(e) {
                                  readhtmlfile[faxfilename] = e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>');
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append(readhtmlfile[faxfilename]);
                              };
                   } else if (extension == 'jpg' || extension == 'jpeg') {
                              $("#faxdocpreview").empty();
                              $("#faxdocpreview").append('<img style="width:100%;height:100%" id="uploadedjpg" src="#" />');

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

                              var reader = new FileReader();
                              reader.onload = function (e) {
                                  readpng[faxfilename] = e.target.result;
                                  $("#uploadedpng").attr('src', readpng[faxfilename]);
                              }
                              reader.readAsDataURL(e.target.files[0]);
                   } else if (extension == 'odt') {
                              $("#faxdocpreview").empty();
                              function odfInit() {
                                 var odfelement = document.getElementById("faxdocpreview");
                                 odfcanvas = new odf.OdfCanvas(odfelement);
                                 odfcanvas.load(baseUrl);
                              }
                              window.setTimeout(odfInit, 0);
                   } else if (extension == 'tif' || extension == 'tiff') {
                              var tiffile = '/remote.php/webdav/Pax_Fax/temp_files/'+faxfilename;
                              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();
                                  $("#faxdocpreview").empty();
                                  $("#faxdocpreview").append(tifcanvas);
                              };
                              xhr.send();
                   }

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

            } else {
                  alert("Error ! You can't send as fax more than 20 files in one fax call !");
                  $('#pf_upload_msg').hide();
                  $('#faxdocpreview').removeClass('icon-loading');
              }
         } else {
              alert("Error ! You can't send files having a total size of more than 20 MB in one fax call !");
              $('#pf_upload_msg').hide();
              $('#faxdocpreview').removeClass('icon-loading');
           }
       } else {
            alert("Error ! There is already a file named '"+fileuptrim+"' in the 'Pax_Fax/temp_files' folder !");
            $('#pf_upload_msg').hide();
            $('#faxdocpreview').removeClass('icon-loading');
         }

     } else {
          alert('The file type is not supported ! Supported formats are: pdf, doc, docx, tiff/tif, jpeg/jpg, odt, txt, html, png.');
          $('#pf_upload_msg').hide();
          $('#faxdocpreview').removeClass('icon-loading');
       }
  });


  // Pick file to fax, from Nextcloud
  var faxfilename = null;

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

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

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

                              var baseUrl = OC.generateUrl("/apps/pax_fax/user/pickfile");

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

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

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

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

                              var validExtensions = ["pdf", "doc", "docx", "tif", "tiff", "jpg", "jpeg", "odt", "txt", "html", "png"];

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

                                 if (duplicatescheck == 0) {

                                    if (n < 21) {

                                       uploadedtofax.push(faxfilename);

                                       $.ajax({
                                          url: baseUrl,
                                          type: "POST",
                                          data: { path: path },
                                          success: function(totalflsize) {

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

                                                // Check if the total file size is over 20 MB
                                                var rectotfilesz = parseFloat(totalflsize.replace(" MB", ""));

                                                if (rectotfilesz > 20.00) {
                                                    $('#filestotsize').css('color', '#ba3555');
                                                    alert("Error ! You can't send files having a total size of more than 20 MB in one fax call ! Please consider removing files so that the total files size would drop to or below 20 MB");
                                                    $('#submitfax').attr("disabled", true);
                                                } else {
                                                    $('#submitfax').attr("disabled", false);
                                                    $('#filestotsize').css('color', '#1eb16a');
                                                }

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

                                                // Preview each file when you click on its name
                                                $("div:visible[id*='indflpicked']").each(function() {
                                                   $(this).on("click", function(event) {
                                                      var faxfilenameinit = $(this).text();
                                                      var faxfilenamesec = faxfilenameinit.substring(faxfilenameinit.indexOf(" ") + 1);
                                                      var faxfilenamesp = faxfilenamesec.replace("X","");
                                                      var baseUrl = firstPathEl+"/remote.php/webdav/Pax_Fax/temp_files/"+faxfilenamesp;
                                                      var extenlst = faxfilenamesp.replace(/^.*\./, '');

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

                                                      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>');
                                                           $("#faxdocpreview").empty();
                                                           $("#faxdocpreview").append($iframe);
                                                      } else if (extenlst == 'txt') {
                                                              $("#faxdocpreview").empty();
                                                              $("#faxdocpreview").append(readtxtfile[faxfilenamesp]);
                                                      } else if (extenlst == 'html') {
                                                              $("#faxdocpreview").empty();
                                                              $("#faxdocpreview").append(readhtmlfile[faxfilenamesp]);
                                                      } else if (extenlst == 'jpg' || extenlst == 'jpeg') {
                                                              $("#faxdocpreview").empty();
                                                              $("#faxdocpreview").append('<img style="width:auto;height:auto" id="uploadedjpg" src="'+ baseUrl +'" />');
                                                      } else if (extenlst == 'png') {
                                                              $("#faxdocpreview").empty();
                                                              $("#faxdocpreview").append('<img style="width:auto;height:auto" id="uploadedpng" src="'+ baseUrl +'" />');
                                                      } else if (extenlst == 'odt') {
                                                              $("#faxdocpreview").empty();
                                                              function odfInit() {
                                                                 var odfelement = document.getElementById("faxdocpreview");
                                                                 odfcanvas = new odf.OdfCanvas(odfelement);
                                                                 odfcanvas.load(baseUrl);
                                                              }
                                                              window.setTimeout(odfInit, 0);
                                                      } else if (extenlst == 'tif' || extenlst == 'tiff') {
                                                              var tiffile = '/remote.php/webdav/Pax_Fax/temp_files/'+faxfilenamesp;
                                                              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();
                                                                  $("#faxdocpreview").empty();
                                                                  $("#faxdocpreview").append(tifcanvas);
                                                              };
                                                              xhr.send();
                                                      }

                                                      $("#faxdocpreview").show();
                                                      $("#faxfoldersview").hide();
                                                   });
                                                });

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

                                                    var baseUrl = OC.generateUrl("/apps/pax_fax/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);

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

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

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

                                                             // Check file size
                                                             var rectotfilesz = parseFloat(totalflsize.replace(" MB", ""));

                                                             if (rectotfilesz > 20.00) {
                                                                 $('#filestotsize').css('color', '#ba3555');
                                                                 alert("Error ! You can't send files having a total size of more than 20 MB in one fax call ! Please consider removing files so that the total files size would drop at or below 20 MB");
                                                                 $('#submitfax').attr("disabled", true);
                                                             } else {
                                                                 $('#submitfax').attr("disabled", false);
                                                                 $('#filestotsize').css('color', '#1eb16a');
                                                               }

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

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


		                                // Preview the picked file
		                                var flUrl = firstPathEl+"/remote.php/webdav/Pax_Fax/temp_files/"+faxfilename;
		                                var pickUrl = OC.generateUrl("/apps/pax_fax/user/prevpickedfile");

		                                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>');
		                                    $("#faxdocpreview").empty();
		                                    $("#faxdocpreview").append($iframe);
		                                } else if (extension == 'txt') {
						           $.get(flUrl, function(textdata) {
		                                             readtxtfile[faxfilename] = textdata.replace(/(?:\r\n|\r|\n)/g, '<br>');
		                                             $("#faxdocpreview").empty();
		                                             $("#faxdocpreview").append(readtxtfile[faxfilename]);
							   });
		                                } else if (extension == 'html') {
							   $.get(flUrl, function(htmldata) {
		                                             readhtmlfile[faxfilename] = htmldata.replace(/(?:\r\n|\r|\n)/g, '<br>');
		                                             $("#faxdocpreview").empty();
		                                             $("#faxdocpreview").append(readhtmlfile[faxfilename]);
							   });
		                                } else if (extension == 'jpg' || extension == 'jpeg') {
		                                           $("#faxdocpreview").empty();
		                                           $("#faxdocpreview").append('<img style="width:auto;height:auto" id="uploadedjpg" src="'+ flUrl +'" />');
		                                } else if (extension == 'png') {
		                                           $("#faxdocpreview").empty();
		                                           $("#faxdocpreview").append('<img style="width:auto;height:auto" id="uploadedpng" src="'+ flUrl +'" />');
                                                           $("#uploadedpng").attr('src', readpng[faxfilename]);
		                                } else if (extension == 'odt') {
		                                       $("#faxdocpreview").empty();
		                                       function odfInit() {
		                                           var odfelement = document.getElementById("faxdocpreview");
		                                           odfcanvas = new odf.OdfCanvas(odfelement);
		                                           odfcanvas.load(flUrl);
		                                       }
		                                       window.setTimeout(odfInit, 0);

		                                } else if (extension == 'tif' || extension == 'tiff') {
		                                       var tiffile = '/remote.php/webdav/Pax_Fax/temp_files/'+faxfilename;
		                                       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();
		                                           $("#faxdocpreview").empty();
		                                           $("#faxdocpreview").append(tifcanvas);
		                                       };
		                                       xhr.send();
		                                }

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

		                                $('#pf_choose_msg').hide();
		                                $('#faxdocpreview').removeClass('icon-loading');
		                                $("#faxfoldersview").hide();

                                          },

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

                                       });

                                    } else {
                                        alert("Error ! You can't fax more than 20 files in one fax call !");
                                        $('#pf_choose_msg').hide();
                                        $('#faxdocpreview').removeClass('icon-loading');
                                      }
                                 } else {
                                      alert("Error ! There is already a file named '"+faxfilename+"' in the 'Pax_Fax/temp_files' folder !");
                                      $('#pf_choose_msg').hide();
                                      $('#faxdocpreview').removeClass('icon-loading');
                                   }

                              } else {
                                   alert('The file type is not supported ! Supported formats are: pdf, doc, docx, tiff/tif, jpeg/jpg, odt, txt, html, png.');
                                   $('#pf_choose_msg').hide();
                                   $('#faxdocpreview').removeClass('icon-loading');
                                }

                        }
                );
  });


  // Submit the fax
  $("#submitfax").on("click", function(event){

     var selectedcid = $('#currentfaxnmbrs :selected').text();

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

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

     OC.msg.startAction("#pf_submit_msg", t("pax_fax", "Sending fax ... Please wait !"));
     $('#faxdocpreview').addClass('icon-loading');

     $('#submitfax').attr("disabled", true);

     var baseUrl = OC.generateUrl("/apps/pax_fax/user/sendfax");

     var toNumberwc = toNumberinit.replace(/[^0-9]/g, "");

     if (uploadedtofax.length != 0) {

         if (toNumberwc != '') {

             $.ajax({
                url: baseUrl,
                type: "POST",
                data: {
                       uploadedtofax: uploadedtofax,
                       selectedcid: selectedcid,
                       toNumber: toNumber
                      },
                success: function(sendingresult) {

                   if (sendingresult.success == true) {
                       alert("The fax has been sent successfully ! You can see the sent fax by clicking on the 'Sent Faxes' button.");
                   } else {
                       alert("Error ! The fax couldn't be sent because of the following error: "+ sendingresult.errortype +" You can see the failed fax by clicking on the 'Failed Sent Faxes' button.");
                   }

                   $("div:visible[id*='indfilediv']").hide();
                   $("div:visible[id*='indflpicked']").hide();
                   $('[class*="indupfldl"]').hide();
                   $('[class*="indpckfldl"]').hide();
                   $('#faxdocpreview').hide();
                   $('#filestotsize').hide();
                   $('#pf_submit_msg').hide();
                },
                error: function(sendingresult) {

                   alert('Error ! Please check your settings !');

                   $("div:visible[id*='indfilediv']").hide();
                   $("div:visible[id*='indflpicked']").hide();
                   $('[class*="indupfldl"]').hide();
                   $('[class*="indpckfldl"]').hide();
                   $('#pf_submit_msg').hide();
                   $('#filestotsize').hide();
                   $('#faxdocpreview').hide();

                   location.reload(true);
                }
             });

         } else {
              $('#pf_submit_msg').hide();
              $('#faxdocpreview').removeClass('icon-loading');
              alert("Please enter the fax number of the recipient !");
         }

     } else {
              $('#pf_submit_msg').hide();
              $('#faxdocpreview').removeClass('icon-loading');
              alert("Please upload a file or pick a file from Nextcloud to send as fax !");
     }
  });

  $("#receivedfaxdir").on("click", function(event){
     $("#faxdocpreview").hide();
     $("#faxfoldersview").show();
     $("#faxfoldersview").addClass("icon-loading");
     $("#faxfoldersview :last-child").remove();
     var fxreceived = OC.generateUrl("/apps/files/?dir=/Pax_Fax/faxes_received");
     $("#faxfoldersview").append("<iframe id='embeddedView' src='" + fxreceived + "' width='100%' height='100%'></iframe>");
     $("#app-content").scrollTop(50);
     setTimeout(function() { $("#faxfoldersview").removeClass("icon-loading"); }, 1000);
  });

  $("#sentfaxdir").on("click", function(event){
     $("#faxdocpreview").hide();
     $("#faxfoldersview").show();
     $("#faxfoldersview").addClass("icon-loading");
     $("#faxfoldersview :last-child").remove();
     var fxsent = OC.generateUrl("/apps/files/?dir=/Pax_Fax/faxes_sent");
     $("#faxfoldersview").append("<iframe id='embeddedView' src='" + fxsent + "' width='100%' height='100%'></iframe>");
     $("#app-content").scrollTop(50);
     setTimeout(function() { $("#faxfoldersview").removeClass("icon-loading"); }, 1000);
  });

  $("#receivedfaileddir").on("click", function(event){
     $("#faxdocpreview").hide();
     $("#faxfoldersview").show();
     $("#faxfoldersview").addClass("icon-loading");
     $("#faxfoldersview :last-child").remove();
     var fxrecfailed = OC.generateUrl("/apps/files/?dir=/Pax_Fax/faxes_received_failed");
     $("#faxfoldersview").append("<iframe id='embeddedView' src='" + fxrecfailed + "' width='100%' height='100%'></iframe>");
     $("#app-content").scrollTop(50);
     setTimeout(function() { $("#faxfoldersview").removeClass("icon-loading"); }, 1000);
  });

  $("#sentfaileddir").on("click", function(event){
     $("#faxdocpreview").hide();
     $("#faxfoldersview").show();
     $("#faxfoldersview").addClass("icon-loading");
     $("#faxfoldersview :last-child").remove();
     var fxsentfailed = OC.generateUrl("/apps/files/?dir=/Pax_Fax/faxes_received_failed");
     $("#faxfoldersview").append("<iframe id='embeddedView' src='" + fxsentfailed + "' width='100%' height='100%'></iframe>");
     $("#app-content").scrollTop(50);
     setTimeout(function() { $("#faxfoldersview").removeClass("icon-loading"); }, 1000);
  });

  $(".indivflpckd").on("click", function(event){
     $("#faxfoldersview").hide();
  });

  $(".indivflcls").on("click", function(event){
     $("#faxfoldersview").hide();
  });

});
