<script src="<?php echo BASE_URL;?>js/editor/tinymce.min.js"></script>
<?php if ($uploadactive) { ?>
  <script src="<?php echo BASE_URL;?>js/dropzone.js"></script>
<?php } ?>
<script>

// Working Flag to 0
var working = false;
Dropzone.autoDiscover = false;

$(document).ready(function() {
  tinymce.init({
    selector: '#content-editor',
    height: 300,
    menubar: false,
    paste_as_text: true,
    entity_encoding : "raw",
    plugins: [
    'advlist autolink lists link charmap print preview textcolor',
    'searchreplace visualblocks code fullscreen',
    'insertdatetime table contextmenu paste code codesample'
    ],
    toolbar: 'insert | undo redo | bold italic underline | bullist numlist | removeformat codesample code',
    language: '<?php echo $BT_LANGUAGE;?>',
    <?php if ($jkl["rtlsupport"]) { ?>
      directionality : 'rtl',
    <?php } ?>
    relative_urls: false
  });

  <?php if (JAK_TICKET_SIMILAR == 1) { ?>

    $("#subject").on("keyup", function(e) {
    // We call the function for client is typing and input is bigger then 3
    if (e.keyCode != 13 && $(this).val().length > 2) {
      ticketSearch($(this).val());
    } else {
      $('#loadsimArticle').html("");
      $('#similarArticle').fadeOut();
      return false;
    }
  });

  <?php } ?>

  $('#jak_depid').change(function(){
    ticketDepartment($(this).val());
  });

  $("#loader, #ticketpriority, #ticketoption").hide();

  // Now that the DOM is fully loaded, create the dropzone, and setup the
  var myDropzone = new Dropzone("#share-attachments", {dictResponseError: "SERVER ERROR",
    dictDefaultMessage: '<i class="fa fa-file-upload fa-3x"></i>',
    acceptedFiles: "<?php echo JAK_ALLOWED_FILES;?>",
    addRemoveLinks: true,
    autoProcessQueue: false,
    url: "<?php echo BASE_URL;?>uploader/uploadert.php"});

  // JavaScript to disable send button and show loading.gif image
  $('.jak_form').submit(function(e){

    e.preventDefault();

    if(working) return false;
    
    working = true;

    $("#loader").show();
    $('.sendTM').attr("disabled", "disabled");
    $(this).find('input').removeClass("is-invalid");

  // Call the server and due the necessary
  var request = $.ajax({
    async: true,
    url: '<?php echo JAK_rewrite::jakParseurl(JAK_SUPPORT_URL, 'n');?>',
    type: "POST",
    data: $(this).serialize(),
    dataType: "json",
    processData: false,
    cache: false
  });

  request.done(function(data) {

    working = false;

    if (data.status) {

      if (myDropzone.files != "") {

        myDropzone.on("sending", function(file, xhr, formData) {
            // Will send the filesize along with the file as POST data.
            formData.append("ticketId", data.ticketid);
            formData.append("userIDU", data.userid);
            formData.append("userIDC", data.clientid);
            formData.append("base_url", "<?php echo BASE_URL;?>");
        });

        myDropzone.processQueue();

        myDropzone.on("queuecomplete", function(a,b,c){
          // Redirect to the ticket
          window.location.replace(data.redirecturl);
        });

      } else {
        // Redirect to the ticket
        window.location.replace(data.redirecturl);
      }

    } else {

        $.notifyClose();

        // We will need to go through each error message
        $.each(data.errors,function(k,v) {
          $.notify({icon: 'warning', message: v}, {type: 'danger', animate: {
            enter: 'animate__animated animate__fadeInDown',
            exit: 'animate__animated animate__fadeOutUp'
          }});
          console.log(v);
          $('#'+k).addClass("is-invalid");
        });

        $("#loader").hide();
        $('.sendTM').removeAttr("disabled");

      }


    });

});

});

function ticketDepartment(v) {

  // Check if we have a value
  if (v) {

    // Ticket Priorities
    var tprio = $('#ticketpriority');

    // Ticket Options
    var topt = $('#ticketoption');

    // Custom fields
    var tcfield = $('#custom_fields');

    // Get the value again from the input field
    var depid = $('#jak_depid').val();

    // Now let's cross check if the value is the same or stop the request
    if (depid != v) {
      tprio.fadeOut();
      topt.fadeOut();
      tcfield.fadeOut();
      // return false;
    }

    var request = new XMLHttpRequest();
    request.open('GET', '<?php echo BASE_URL;?>include/new_ticket.php?depid='+depid, true);

    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);

        if (data.status == 1) {

          if (data.ticketpriority) {

            let sel = document.querySelector('#prioirty');

            // We will need to empty the list first
            for (a in sel.options) { sel.options.remove(0); }

            data.ticketpriority.forEach((tprio)=>{
                let prioopt = document.createElement('option');
                prioopt.value = tprio.id;
                let prioTitle = document.createTextNode(tprio.title);
                prioopt.appendChild(prioTitle);
                sel.appendChild(prioopt);
            });

            tprio.fadeIn();

          }

          if (data.ticketoptions) {

            let sel2 = document.querySelector('#toption');

            // We will need to empty the list first
            for (a in sel2.options) { sel2.options.remove(0); }

            data.ticketoptions.forEach((topt)=>{
                let optopt = document.createElement('option');
                optopt.value = topt.id;
                let optTitle = document.createTextNode(topt.title);
                optopt.appendChild(optTitle);
                sel2.appendChild(optopt);
            });

            topt.fadeIn();

          }

          if (data.customfields) {

            $('#custom_fields').html(data.customfields);

            tcfield.fadeIn();

          }

          if (data.precontent) tinymce.activeEditor.execCommand('mceInsertContent', false, data.precontent);

        } else {

          $.notifyClose();

          $.notify({icon: 'warning', message: data.errormsg}, {type: 'danger', animate: {
            enter: 'animate__animated animate__fadeInDown',
            exit: 'animate__animated animate__fadeOutUp'
          }});

          // Nothing to do, remove the container    
          tprio.fadeOut();
          topt.fadeOut();
          tcfield.fadeOut();

        }
      }
    }

    request.onerror = function() {
        return false;
      }

      request.send();

    } else {

      $.notifyClose();

      $.notify({icon: 'warning', message: '<?php echo addslashes($jkl['e25']);?>'}, {type: 'danger', animate: {
        enter: 'animate__animated animate__fadeInDown',
        exit: 'animate__animated animate__fadeOutUp'
      }});

    return false;
  }
}

function ticketSearch(v) {

  // Check if we have a value
  if (v) {

    // similar Article Container
    var sac = $('#similarArticle');

    // similar Article Div
    var sadiv = $('#loadsimArticle');

    // Get the value again from the input field
    var newTsubject = $('#subject').val();

    // Now let's cross check if the value is the same or stop the request
    if (newTsubject != v) {
      sadiv.html("");
      sac.fadeOut();
      return false;
    }

    var request = new XMLHttpRequest();
    request.open('GET', '<?php echo BASE_URL;?>include/similar_search.php?s='+newTsubject, true);

    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);

        if (data.status == 1) {

          // Show Similar Article Container
          sac.fadeIn();

          // Load the content
          sadiv.html(data.articles);

        } else {

          // Nothing to do, remove the container    
          sadiv.html("");
          sac.fadeOut();

        }
      }
    }

    request.onerror = function() {
        // There was a connection error of some sort
        sadiv.html("");
        sac.fadeOut();
      }

      request.send();

    } else {
    // We could not output something.
    sadiv.html("");
    sac.fadeOut();
    return false;
  }
}
</script>
