<script src="<?php echo BASE_URL;?>js/liveticket.js"></script>
<script src="<?php echo BASE_URL_ORIG;?>js/editor/tinymce.min.js" type="text/javascript"></script>
<?php if ($jakuser->getVar("files") && $jakosub['files'] && $ticket_status_closed != 1) { ?>
<script type="text/javascript" src="<?php echo BASE_URL_ORIG;?>js/dropzone.js"></script>
<?php } ?>

<script>
$(document).ready(function() {

  // fire the live ticket status
  ltJAK(<?php echo $page2;?>, <?php echo JAK_USERID;?>);

  tinymce.init({
      selector: '#content-editor',
      height: 300,
      menubar: false,
      paste_as_text: true,
      entity_encoding : "raw",
      plugins: [
        'advlist autolink lists link image charmap print preview anchor textcolor',
        'searchreplace visualblocks code fullscreen',
        'insertdatetime media table contextmenu paste code responsivefilemanager codesample'
      ],
      toolbar: 'insert | undo redo | styleselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat codesample code',
      language: '<?php echo $BT_LANGUAGE;?>',
      <?php if ($jkl["rtlsupport"]) { ?>
      directionality : 'rtl',
      <?php } ?>
      external_filemanager_path:"<?php echo BASE_URL_ORIG;?>js/editor/filemanager/",
      filemanager_title:"Filemanager" ,
      external_plugins: { "filemanager" : "<?php echo BASE_URL_ORIG;?>js/editor/filemanager/plugin.min.js"},
      // Live Ticket Status
      init_instance_callback: function(editor) {
        editor.on('Change', function(e) {
          ticketTyping(<?php echo $page2;?>, <?php echo JAK_USERID;?>);
        });
      },
      relative_urls: false
    });

  $('.datepicker').datetimepicker({
      format: '<?php echo $duedateformat[1];?>'
  });

  //init DateTimePickers
  md.initFormExtendedDatetimepickers();

  $("#loader").hide();
    
  // JavaScript to disable send button and show loading.gif image
  $("#sendTM").click(function() {
    $("#loader").show();
    $('#sendTM').attr("disabled", "disabled");
    $('.jak_form').submit();
  });

  $('body').on('click', '.btn-delfile', function (e) {
    e.preventDefault();

    var _this = this;
    var rediurl = jQuery(this).attr('href');
    var btnaction = jQuery(this).data("action");
    var title = jQuery(this).data("title");
    var text = jQuery(this).data("text");
    var okbtn = '<button class="alertable-ok" type="submit">'+jQuery(this).data("okbtn")+'</button>';
    var cbtn = '<button class="alertable-cancel" type="button">'+jQuery(this).data("cbtn")+'</button>';

    jQuery.alertable.confirm(title, {prompt: text, okButton: okbtn, cancelButton: cbtn}).then(function() {
        $.ajax({
            url: rediurl,
            dataType: 'json',
            success: function(data) {
              $(_this).closest('tr').find('td').fadeOut();
              $('#answerid-'+data.answerid).fadeOut();

              // Update the counter
              var countSpan = $('#upload-counter').text();
              var newSpan = parseInt(countSpan) - 1;
              $('#upload-counter').html(newSpan);

            }
        });
    }, function() {
      return false;
    });
  });

});

window.onbeforeunload = function(){
  ticketNotTyping(<?php echo $page2;?>, <?php echo JAK_USERID;?>);
  // return 'Are you sure you want to leave?';
};

// Insert the standard response into the editor
$('select#supresp').on("change", function() {
  var respid = this.value;
  if (respid != 0) {

    $.ajax({
    type: "POST",
    url: ls.main_url + 'ajax/oprequests.php',
    data: "oprq=supportresponse&respid="+respid+"&cname=<?php echo $JAK_FORM_DATA["name"];?>&uid="+ls.opid,
    dataType: 'json',
    success: function(msg){

      if (msg.status) {
        tinymce.activeEditor.execCommand('mceInsertContent', false, msg.response);
        md.showNotification('check', '<?php echo $jkl['g14'];?>', 'success', 'top', 'right');
      } else {
        md.showNotification('warning', '<?php echo $jkl['g116'];?>', 'danger', 'top', 'right');
      }
    }
  });
    $('#supresp').val(0);
  }
});

$("#private_note").change(function() {
    if(this.checked) {
      $(".mce-path").addClass('bg-warning');
    } else {
      $(".mce-path").removeClass('bg-warning');
    }
  });

<?php if ($jakuser->getVar("files") && $jakosub['files'] && $ticket_status_closed != 1) { ?>
Dropzone.autoDiscover = false;
  $(function() {
      // Now that the DOM is fully loaded, create the dropzone, and setup the
      // event listeners
      var myDropzone = new Dropzone("#share-attachments", {dictResponseError: "SERVER ERROR",
      dictDefaultMessage: '<i class="fa fa-file-upload fa-3x"></i>',
      acceptedFiles: "<?php echo JAK_ALLOWEDO_FILES;?>",
      addRemoveLinks: true,
      url: "<?php echo BASE_URL_ORIG;?>uploader/uploaderto.php"});
    myDropzone.on("sending", function(file, xhr, formData) {
        // Will send the filesize along with the file as POST data.
        formData.append("ticketId", <?php echo $page2;?>);
        formData.append("userIDU", <?php echo $jakuser->getVar("id");?>);
        formData.append("base_url", "<?php echo BASE_URL_ORIG;?>");
        formData.append("operatorNameU", "<?php echo $jakuser->getVar("name");?>");
        formData.append("operatorLanguage", "<?php echo $USER_LANGUAGE;?>");
    });
    myDropzone.on("success", function(file, serverResponse) {
        //myDropzone.removeAllFiles();
        // Update the counter
        var thefile = "";
        var countSpan = $('#upload-counter').text();
        var newSpan = parseInt(countSpan) + 1;
        $('#upload-counter').html(newSpan);
        // console.log(serverResponse);
        data = JSON.parse(serverResponse);
        if (data.isimage) {
          thefile = '<tr><td><a data-toggle="lightbox" href="<?php echo BASE_URL_ORIG;?>_showfile.php?i='+data.filepath+'"><img src="<?php echo BASE_URL_ORIG;?>_showfile.php?i='+data.filepath+'" alt="'+data.filename+'" class="img-thumbnail" width="50"></a> <a href="<?php echo BASE_URL_ORIG;?>_showfile.php?i='+data.filepath+'" class="btn btn-info btn-sm"><i class="fa fa-file-download"></i></a> <a href="'+data.delpath+'" class="btn btn-danger btn-sm btn-delfile" data-title="<?php echo addslashes($jkl["g48"]);?>" data-text="<?php echo addslashes($jkl["e32"]);?>" data-type="warning" data-okbtn="<?php echo addslashes($jkl["g279"]);?>" data-cbtn="<?php echo addslashes($jkl["g280"]);?>"><i class="fa fa-trash-alt"></i></a></td></tr>';
        } else {
          thefile = '<tr><td>'+data.filename+' <a href="<?php echo BASE_URL_ORIG;?>_showfile.php?i='+data.filepath+'" class="btn btn-info btn-sm"><i class="fa fa-file-download"></i></a> <a href="'+data.delpath+'" class="btn btn-danger btn-sm btn-delfile" data-title="<?php echo addslashes($jkl["g48"]);?>" data-text="<?php echo addslashes($jkl["e32"]);?>" data-type="warning" data-okbtn="<?php echo addslashes($jkl["g279"]);?>" data-cbtn="<?php echo addslashes($jkl["g280"]);?>"><i class="fa fa-trash-alt"></i></a></td></tr>';
        }

        // Attach file visually
        $('#attach-list').append(thefile);

        // Notification messages
        md.showNotification('check', '<?php echo $jkl['e38'];?>', 'success', 'top', 'right');
        
    });
  });
<?php } ?>

$(document).on("click", ".btn-translate", function(e) {
  e.preventDefault();

  var _this = $(this);
  var wscan = $(_this).data("scan");
  var tid = $(_this).data("ticketid");
  var aid = $(_this).data("answerid");
  var tcontent = tinymce.get("content-editor").getContent();
  var tlang = $('#jak_tlang').find(":selected").val();

  // No content so we stop
  if (wscan != "answer" && tcontent == "") return false;

  // Check if we translate something but the language is empty
  if (wscan == "translate" && tlang == "-") {

    md.showNotification('warning', '<?php echo addslashes($jkl['e47']);?>', 'danger', 'top', 'right');

    return false;

  }

  // Show the loader
  $(".tl-loader", _this).removeClass("d-none");
          
  $.ajax({
    type: "POST",
    url: ls.main_url + 'ajax/translate_ticket.php',
    data: "wsource="+wscan+"&id="+tid+"&aid="+aid+"&tcontent="+tcontent+"&uid="+ls.opid+"&lang="+tlang,
    dataType: 'json',
    success: function(msg){
              
      if (msg.status == 1) {

        // Success message
        md.showNotification('check', msg.txt, 'success', 'top', 'right');

        // We will add the translation below
        if (aid != 0) {
          $('.aitranslate'+aid).html(msg.translation).fadeIn();
        } else {
          $('.aitranslatem'+tid).html(msg.translation).fadeIn();
        }

        // We have a new language
        if (msg.lang) $("#jak_tlang").val(msg.lang);
        $('.selectpicker').selectpicker('refresh');

      } else if (msg.status == 2) {

        // We have a fine new text, let's add it
        tinymce.activeEditor.setContent(msg.grammar_correct);


      } else if (msg.status == 3) {

        // We have a translation, let's add it
        tinymce.activeEditor.setContent(msg.translate_correct);

      } else {

        md.showNotification('warning', msg.txt, 'danger', 'top', 'right');
      }

      // Hide the loader
      $(".tl-loader", _this).addClass("d-none");
      return true;
    }
  });
});

</script>
