
//CONFIGURACOES PERSONALIZAR PDF
function handleImage(e,el,name) {
    var reader = new FileReader();
    reader.onload = function (event) {
        var result = event.target.result;
        var data_extension = name.substr(-3);
        console.log(data_extension);
        if(data_extension=="pdf"){
          el.parent().find('.upload-elemento-imagem-upload-geral').append('<img src="/app/elements/images/pdf-icon.png">');
        }else if(data_extension=="ttf"){
          console.log(el.hasClass);
          if(el.hasClass("ttf-regular")){
            el.parent().find('.upload-elemento-imagem-upload-geral').append('<img src="/app/elements/images/regular-icon.svg">');
          }else if(el.hasClass("ttf-bold")){
            el.parent().find('.upload-elemento-imagem-upload-geral').append('<img src="/app/elements/images/bold-icon.svg">');
          }else{
            el.parent().find('.upload-elemento-imagem-upload-geral').append('<img src="/app/elements/images/italico-icon.svg">');
          }
        }else{
          console.log(result);
          el.parent().find('.upload-elemento-imagem-upload-geral').append('<img src='+result+'>');
        }
    }
    reader.readAsDataURL(e.target.files[0]);
}
/*$(".filePhoto").each(function( index ) {
  var $this = $(this);
  $this.on("change", $this, function(e){
      var file = $this[0].files[0];
      alert(file.type);
      if(file.type=="pdf" || file.type=="application/pdf" || file.type=="image/png" || file.type=="image/jpg" || file.type=="image/jpeg"){
        handleImage(e,$this,file.name);
        if(!$this.parent().parent().parent().find(".elimina-foto-currente-fileupload-pdf").length){
          $this.parent().parent().parent().append('<a href="#" class="elimina-foto-currente-fileupload-pdf"><i class="fas fa-trash-alt"></i></a>');
        }
        $this.parent().parent().parent().find(".file_to_delete").remove();
      }else{
        alert("Tipo de ficheiro inválido.");
      }
  });
});*/

$(document).on("click", ".upload-elemento-imagem-upload-geral", function(e){
  if(e.target != this) return;
  var $this =  $(this);
  var parent = $this.parent();
  parent.find(".file-upload-elemento-imagem-upload-geral").click();
});

$(".file-upload-elemento-imagem-upload-geral").each(function( index ) {
  var $this = $(this);
  $this.on("change", $this, function(e){
      e.preventDefault();
      var file = $this[0].files[0];
      console.log($this);
      if($this.hasClass("ttf-file")){
        var data_extension = file.name.substr(-3);
        if(data_extension=="ttf"){
          handleImage(e,$this,file.name);
          if(!$this.parent().find(".upload-elemento-imagem-upload-geral .elimina-foto-currente-fileupload-pdf").length && !$this.parent().find(".upload-elemento-imagem-upload-geral .edita-foto-currente-fileupload-pdf").length){
            $this.parent().find('.upload-elemento-imagem-upload-geral').append('<a href="#" class="edita-foto-currente-fileupload-pdf"></a><a href="#" class="elimina-foto-currente-fileupload-pdf"></a>');
            $this.parent().addClass("active");
          }
          $this.parent().find(".file_to_delete").val(0);
        }else{
          alert("Tipo de ficheiro inválido.");
        }
      }else{
        if(file.type=="pdf" || file.type=="application/pdf" || file.type=="image/png" || file.type=="image/jpg" || file.type=="jpg" || file.type=="image/jpeg" || file.type=="jpeg" || file.type=="image/svg+xml"){
          handleImage(e,$this,file.name);
          if(!$this.parent().find(".upload-elemento-imagem-upload-geral .elimina-foto-currente-fileupload-pdf").length && !$this.parent().find(".upload-elemento-imagem-upload-geral .edita-foto-currente-fileupload-pdf").length){
            $this.parent().find('.upload-elemento-imagem-upload-geral').append('<a href="#" class="edita-foto-currente-fileupload-pdf"></a><a href="#" class="elimina-foto-currente-fileupload-pdf"></a>');
            $this.parent().addClass("active");
          }
          $this.parent().find(".file_to_delete").val(0);
        }else{
          alert("Tipo de ficheiro inválido.");
        }
      }
  });
});

$(document).on("click", ".elimina-foto-currente-fileupload-pdf", function(e){
  e.preventDefault();
  var $this = $(this);
  var parent = $this.parent();
  //parent.append('<input type="hidden" class="file_to_delete" name="file_to_delete_'+id+'" value="1">');
  parent.find("img").remove();
  parent.parent().removeClass("active").find(".file-upload-elemento-imagem-upload-geral").val('');
  parent.find(".edita-foto-currente-fileupload-pdf").remove();
  parent.parent().find(".file_to_delete").val(1);
  $this.remove();
});

$(document).on("click", ".edita-foto-currente-fileupload-pdf", function(){
  var $this = $(this);
  var parent = $this.parent().parent();
  parent.find(".file-upload-elemento-imagem-upload-geral").click();
});




$("input[name='fonte_regular'], input[name='fonte_medium'], input[name='fonte_italico'], input[name='fonte_bold']").each(function( e ) {
  var $this = $(this);
  $this.on("change", $this, function(e){
    var file = $this[0].files[0];
    if(file.name.slice(-3)!="ttf"){
      $this[0].value = '';
      alert("Tipo de ficheiro inválido.");
    }
  });
});


// Diogo | Coloca os campos a preencher, consoante o Sistema de Faturação escolhido pelo utilizador
if($("#select-sistema-faturacao").length){
    setSistemaFaturacao();
}

function setSistemaFaturacao() {
  //Sistema de Faturação Seleccionado
  var val = document.getElementById('select-sistema-faturacao').value;
  if (val == "keyinvoice") {
    document.getElementById('campoAPIURL').removeAttribute('hidden');
    document.getElementById('campoNome').setAttribute('hidden', true);
  }
  else if (val == "invoicexpress") {
    document.getElementById('campoAPIURL').setAttribute('hidden', true);
    document.getElementById('campoNome').removeAttribute('hidden');
  }
}


(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();


$(document).on("click", ".formulario-opcao-posicoes .adicionar-rows-posicoes", function(){
  var lista_posicoes  = $(".lista-formulario-opcao-posicoes:first");
  var currentEntry = $(".lista-formulario-opcao-posicoes").find('.form-group:last-child');
  newEntry = $(currentEntry.clone()).appendTo(lista_posicoes);
  newEntry.find('input').val('');
  var change_entry = newEntry.find('input').attr("name").match(/\d+/);
  change_entry2 = parseInt(change_entry[0])+1;
  newEntry.find('input.posicao').attr('name','posicao['+change_entry2+'][posicao]');
  newEntry.find('input.valor_hora').attr('name','posicao['+change_entry2+'][valor_hora]');
  newEntry.find('input.valor_dia').attr('name','posicao['+change_entry2+'][valor_dia]');
  newEntry.find('input.valor_mes').attr('name','posicao['+change_entry2+'][valor_mes]');
  newEntry.find('input.cor').attr('name','posicao['+change_entry2+'][cor]');
  newEntry.find(".remover").remove();
  newEntry.append("<div class='col-lg-1 remover'><div class='elimina-row-posicoes-configuracoes d-flex flex-column justify-content-center h-100'><a href='#'><i class='fas fa-trash-alt'></i></a></div></div>");
});


$(document).on("click", ".formulario-opcao-servicos .adicionar-rows-servicos", function(){
  var lista_servicos  = $(".lista-formulario-opcao-servicos:first");
  var currentEntry = $(".lista-formulario-opcao-servicos").find('.form-group:last-child');
  newEntry = $(currentEntry.clone()).appendTo(lista_servicos);
  newEntry.find('input').val('');
  var change_entry = newEntry.find('input').attr("name").match(/\d+/);
  change_entry2 = parseInt(change_entry[0])+1;
  newEntry.find('input.servico').attr('name','servico['+change_entry2+'][servico]');
  newEntry.find(".remover").remove();
  newEntry.append("<div class='col-lg-1 remover'><div class='elimina-row-servicos-configuracoes d-flex flex-column justify-content-center h-100'><a href='#'><i class='fas fa-trash-alt'></i></a></div></div>");
});

$(document).on("click", ".formulario-opcao-origem .adicionar-rows-origem", function(){
  var lista_origem  = $(".lista-formulario-opcao-origem:first");
  var currentEntry = $(".lista-formulario-opcao-origem").find('.form-group:last-child');
  newEntry = $(currentEntry.clone()).appendTo(lista_origem);
  newEntry.find('input').val('');
  var change_entry = newEntry.find('input').attr("name").match(/\d+/);
  change_entry2 = parseInt(change_entry[0])+1;
  newEntry.find('input.origem').attr('name','origem['+change_entry2+'][origem]');
  newEntry.find(".remover").remove();
  newEntry.append("<div class='col-lg-1 remover'><div class='elimina-row-origem-configuracoes d-flex flex-column justify-content-center h-100'><a href='#'><i class='fas fa-trash-alt'></i></a></div></div>");
});

$(document).on("click", ".formulario-opcao-estado .adicionar-rows-estado", function(){
  var lista_estado  = $(".lista-formulario-opcao-estado:first");
  var currentEntry = $(".lista-formulario-opcao-estado").find('.form-group:last-child');
  newEntry = $(currentEntry.clone()).appendTo(lista_estado);
  newEntry.find('input').val('');
  var change_entry = newEntry.find('input').attr("name").match(/\d+/);
  change_entry2 = parseInt(change_entry[0])+1;
  newEntry.find('input.estado').attr('name','estado['+change_entry2+'][estado]');
  newEntry.find('input.cor').attr('name', 'estado['+change_entry2+'][cor]');
  newEntry.find('input.corfundo').attr('name', 'estado['+change_entry2+'][corfundo]');
  newEntry.find(".remover").remove();
  newEntry.append("<div class='col-lg-1 remover'><div class='elimina-row-estado-configuracoes d-flex flex-column justify-content-center h-100'><a href='#'><i class='fas fa-trash-alt'></i></a></div></div>");
});

$(document).on("click", ".elimina-row-posicoes-configuracoes", function(){
  var state = $(this);
  var id = state.data("id");
  var formData2 = new FormData;
  formData2.append("id", id);
  formData2.append("ajax", "elimina_posicao");
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    dataType:'json',
    data: formData2,
    processData: false,
    contentType: false,
    cache: false,
    success: function(response){
      if(response.sucesso==1){
        state.parent().parent().remove();
      }else{
        alert("Não é possivel eliminar esta posição por estar associado a pelo menos 1 utilizador.");
      }
    },
    error:function(xht){
      console.log("error");
    }
  });
});

$(document).on("click", ".elimina-row-servicos-configuracoes", function(){
  var state = $(this);
  var id = state.data("id");
  var formData2 = new FormData;
  formData2.append("id", id);
  formData2.append("ajax", "elimina_servico");
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    dataType:'json',
    data: formData2,
    processData: false,
    contentType: false,
    cache: false,
    success: function(response){
      if(response.sucesso==1){
        state.parent().parent().remove();
      }else if (response.sucesso==0){
        alert("Não é possivel eliminar este servico por estar associado a pelo menos 1 lead.");
      } else {
        alert("Erro!");
      }
    },
    error:function(xht){
      console.log("error");
    }
  });
});

$(document).on("click", ".elimina-row-origem-configuracoes", function(){
  var state = $(this);
  var id = state.data("id");
  var formData2 = new FormData;
  formData2.append("id", id);
  formData2.append("ajax", "elimina_origem");
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    dataType:'json',
    data: formData2,
    processData: false,
    contentType: false,
    cache: false,
    success: function(response){
      if(response.sucesso==1){
        state.parent().parent().remove();
      }else if (response.sucesso==0){
        alert("Não é possivel eliminar esta origem por estar associada a pelo menos 1 lead.");
      } else {
        alert("Erro!");
      }
    },
    error:function(xht){
      console.log("error");
    }
  });
});

$(document).on("click", ".elimina-row-estado-configuracoes", function(){
  var state = $(this);
  var id = state.data("id");
  var formData2 = new FormData;
  formData2.append("id", id);
  formData2.append("ajax", "elimina_estado");
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    dataType:'json',
    data: formData2,
    processData: false,
    contentType: false,
    cache: false,
    success: function(response){
      if(response.sucesso==1){
        state.parent().parent().remove();
      }else if (response.sucesso==0){
        alert("Não é possivel eliminar este estado por estar associado a pelo menos 1 lead.");
      } else {
        alert("Erro!");
      }
    },
    error:function(xht){
      console.log("error");
    }
  });
});

$(document).on("click input keyup hover change", "#estilobtn, .estilobtn ", function(){
  var parent = jQuery(this).parent();
  var state = $(this).val();
  parent.css("background-color",state);
});

$(document).on("click", ".eliminarestado", function(){
  var id = $(this).data('id');
  var assunto = $(this).data('assunto');
  $('#eliminar_lista_modal .assunto_ticket').html(assunto)
  $('#eliminar_lista_modal input[name="tarestadoid"]').val(id);
  $('#eliminar_lista_modal').modal('show');
});

$(document).on("click", ".eliminardepartamento", function () {
  var id = $(this).data("id");
  var assunto = $(this).data("assunto");
  $("#eliminar_departamento_modal .assunto_ticket").html(assunto);
  $('#eliminar_departamento_modal input[name="iddepartamento"]').val(id);
  $("#eliminar_departamento_modal").modal("show");
});



/*$("#button").click(function (e) {
   e.preventDefault();
   myDropzone.processQueue();
});

if ($('#dropzone_paginas_internas_orcamentos').length) {
  Dropzone.autoDiscover = false;
  var Dropzone_orcamentos = new Dropzone("#dropzone_paginas_internas_orcamentos",{
    autoProcessQueue: false,
    url: "/app/elements/images" ,
    dictDefaultMessage: "Escolha as páginas internas do orçamento.",
    dictRemoveFile:  "",
    dictCancelUpload: "",
    previewTemplate: '<div class="dz-preview" id="dz-preview-template"><div class="dz-image"><img data-dz-thumbnail ></div><div class="dz-details"><div class="dz-filename"><span data-dz-name></span></div><div class="dz-size" data-dz-size></div></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-success-mark"><span></span></div><div class="dz-error-mark"><span></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="dz-draganddrop"></a></div>',
    addRemoveLinks: true,
    parallelUploads: 100,
    acceptedFiles: 'image/*,.pdf',
    init: function() {
      var myDropzone = this;
      var files_to_remove=[];
      $.ajax({
        url: '/app/elements/functions/ajax.php',
        type: 'post',
        data: {'ajax':'dropzone_obtem_ficheros'},
        cache: false,
        dataType: 'json',
        success: function(response){
          var i=0;
          $.each(response, function(key,value) {
            files_to_remove[value.name]=0;
            var mockFile = { name: value.name, size: value.size, extension: value.extension};
            myDropzone.emit("addedfile", mockFile);
            if(value.extension=="pdf"){
              myDropzone.emit("thumbnail", mockFile, "/app/elements/images/pdf-icon.png");
            }else{
              myDropzone.emit("thumbnail", mockFile, value.path);
            }
            myDropzone.emit("complete", mockFile);
            i++;
          });
        },
        error: function (request, status, error) {
          console.log(error);
        }
      });
      $("form").submit(function (e) {
          e.preventDefault();
          myDropzone.processQueue();
          var formData2 = new FormData;
          formData2.append("files_to_remove", JSON.stringify(files_to_remove));
          formData2.append("ajax", "configuracoes_pdf_eliminar");
          $.ajax({
            url: '/app/elements/functions/ajax.php',
            type: 'POST',
            dataType:'json',
            data: formData2,
            processData: false,
            contentType: false,
            cache: false,
            success: function(response){

            },
            error:function(xht){
              console.log("error");
            }
          });
      });
      this.on('removedfile', function(file) {
          files_to_remove[file.name]=1;
      });
      this.on("sending", function(file, xhr, formData) {
        var filenames = [];
        $('.dz-preview .dz-filename').each(function() {
          filenames.push($(this).find('span').text());
        });
        formData.append('filenames', filenames);
        console.log(filenames);
      });

      this.on('complete', function(file) {
        var formData1 = new FormData;
        formData1.append("ficheirosUpload", file);
        formData1.append("ajax", "configuracoes_pdf_gravar");
        $.ajax({
          url: '/app/elements/functions/ajax.php',
          type: 'POST',
          dataType:'json',
          data: formData1,
          processData: false,
          async:false,
          contentType: false,
          cache: false,
          success: function(response){

          },
          error:function(xht){
            console.log(xht);
          }
        });
      });
    }
  });


  $("#dropzone_paginas_internas_orcamentos").sortable({
    items: '.dz-preview',
    tolerance:'pointer',
    containment: '#dropzone_paginas_internas_orcamentos',
    filter: ".dz-default",
    stop: function () {
          var queue = Dropzone_orcamentos.files;
          newQueue = [];
          $('.dropzone .dz-preview .dz-filename [data-dz-name]').each(function (count, el) {
              var name = el.innerHTML;
              queue.forEach(function (file) {
                  if (file.name === name) {
                      newQueue.push(file);
                  }
              });
          });
         console.log(newQueue);
         Dropzone_orcamentos.files = newQueue;
         console.log(Dropzone_orcamentos.files);
    }
  });

  $("#dropzone_paginas_internas_orcamentos").disableSelection();



}*/

//PAGINAS INTERNAS

if($(".parent-paginasinternas").length){
  function handleImagePaginasInternas(e,el,name) {
      var reader = new FileReader();
      reader.onload = function (event) {
          var result = event.target.result;
          var data_extension = name.substr(-3);
          console.log(data_extension);
          if(data_extension=="pdf"){
            el.parent().find('.upload-elemento-imagem-upload-geral-paginas-internas').append('<img src="/app/elements/images/pdf-icon.png">');
          }else{
            console.log(result);
            el.parent().find('.upload-elemento-imagem-upload-geral-paginas-internas').append('<img src='+result+'>');
          }
      }
      reader.readAsDataURL(e.target.files[0]);
  }

  $(document).on("click", ".upload-elemento-imagem-upload-geral-paginas-internas", function(e){
    if(e.target != this) return;
    var $this =  $(this);
    var parent = $this.parent();
    parent.find(".file-upload-elemento-imagem-upload-geral-paginas-internas").click();
  });

  $(document).on("change", ".file-upload-elemento-imagem-upload-geral-paginas-internas", function(e){
    var $this = $(this);
    e.preventDefault();
    var file = $this[0].files[0];
    console.log($this);
      if(file.type=="pdf" || file.type=="application/pdf" || file.type=="image/png" || file.type=="image/jpg" || file.type=="jpg" || file.type=="image/jpeg" || file.type=="jpeg"){
        handleImagePaginasInternas(e,$this,file.name);
        if(!$this.parent().find(".upload-elemento-imagem-upload-geral-paginas-internas .elimina-foto-currente-fileupload-pdf-paginas-internas").length ){
          $this.parent().find('.upload-elemento-imagem-upload-geral-paginas-internas').append('<a href="#" class="draganddrop-paginas-internas"></a><a href="#" class="elimina-foto-currente-fileupload-pdf-paginas-internas"></a>');
          $this.parent().addClass("active");
          $(".parent-paginasinternas").append('<div class="elemento-imagem-upload-geral-paginas-internas"><div class="upload-elemento-imagem-upload-geral-paginas-internas"></div><input class="file-upload-elemento-imagem-upload-geral-paginas-internas" type="file" name="paginas_internas[]"></div>');
        }
        //$this.parent().parent().parent().find(".file_to_delete").remove();
      }else{
        alert("Tipo de ficheiro inválido.");
      }
  });

  $(document).on("click", ".elimina-foto-currente-fileupload-pdf-paginas-internas", function(e){
    e.preventDefault();
    var $this = $(this);
    var parent = $this.parent().parent();
    parent.remove();
    var elimina_imagem = $(this).attr("data-name");
    var current_internas_eliminar = $("input[name='pag_internas_eliminar']").val();
    if(current_internas_eliminar){
      var current_internas_total = current_internas_eliminar+","+elimina_imagem;
      $("input[name='pag_internas_eliminar']").val(current_internas_total);
    }else{
      $("input[name='pag_internas_eliminar']").val(elimina_imagem);
    }

    var ordem="";
    $(".parent-paginasinternas .elemento-imagem-upload-geral-paginas-internas:not(:last-child)").each(function( index ) {
      $this = $(this);
      if(index==0){
        ordem=$this.find(".elimina-foto-currente-fileupload-pdf-paginas-internas").attr("data-name");
      }else{
        ordem=ordem+","+$this.find(".elimina-foto-currente-fileupload-pdf-paginas-internas").attr("data-name");
      }
    });
    $("input[name='pag_internas_ordem']").val(ordem);

  });

}

$(document).ready(function() {
   $(function() {
     $(".parent-paginasinternas").sortable({
         items: '.elemento-imagem-upload-geral-paginas-internas:not(:last-child)',
         containment: '.parent-paginasinternas',
         update: function(event, ui) {
             var ordem="";
             $(".parent-paginasinternas .elemento-imagem-upload-geral-paginas-internas:not(:last-child)").each(function( index ) {
               $this = $(this);
               if(index==0){
                 ordem=$this.find(".elimina-foto-currente-fileupload-pdf-paginas-internas").attr("data-name");
               }else{
                 ordem=ordem+","+$this.find(".elimina-foto-currente-fileupload-pdf-paginas-internas").attr("data-name");
               }
             });
             $("input[name='pag_internas_ordem']").val(ordem);
         },
       });
    });
});
var ivasold = '';
$(document).ready(function() {
if($('#validar').length > 0){
  //Mudança de Sistema faturação - IVAS
  ivasold = $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "obter_ivas_atual"},
      cache: false,
      async: false
  }).responseText;
  console.log(ivasold);
}
});
function comparar_ivas() {
  var ivasnew = $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "obter_ivas_atual"},
      cache: false,
      async: false
  }).responseText;

  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "obter_form_verificacao_ivas", "old": ivasold, "new": ivasnew},
      cache: false,
      success: function(response){
        if(response != 'iguais')
        {
          $('#validar .modal-content').html(response)
          $('#validar').modal('show');
        }
      }
  });
}

//Testar configuração de e-mail
$(document).on("click", ".btn-testar-configuracao", function(e){
  e.preventDefault();
  $("#modal_testar_email_conf").modal("show");
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "email_testar_configuracoes", "departamentoid" : $(this).data("departamentoid")},
    cache: false,
    success: function(response){
      $('#modal_testar_email_conf_body').html(response);
    },
  });
});
