//TOGGLE DE ENTIDADE DO NOVO ORÇAMENTO
$(document).on("click", '.toggle-lista-entidade', function() {
  var $this = jQuery(this);
  var parent = $this.parent().parent();
  parent.toggleClass("active");
  if(parent.hasClass("active")){
    jQuery(".titulo-lista-entidade-novo-orcamento h4").text("Nova entidade");
    jQuery(this).text("Entidade existente");
  }else{
    jQuery(".titulo-lista-entidade-novo-orcamento h4").text("Existente");
    jQuery(this).text("Adicionar nova entidade");
  }
});

var table = $('#table-orcamentos').DataTable({
  "responsive": true,
  "serverSide": false,
  "ajax": {
      url: "/app/data/datatables.php", // json datasource
      data: {action: 'getOrcamentos'},
      type: 'post',
  },
  error: function () {

  },
  columnDefs: [
    { targets: 'no-sort', orderable: false },
    { "targets": [5], "visible": false, "searchable": true },
    { "targets": [7], "className": 'text-center' },
  ],
  "language": {
      "lengthMenu": "_MENU_",
      "info": "A mostrar _START_-_END_ de _TOTAL_",
      "search": "Pesquisar:",
      "paginate": {
        "next": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" viewBox=\"0 0 451.846 451.847\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 451.846 451.847;\" xml:space=\"preserve\"><path d=\"M345.441,248.292L151.154,442.573c-12.359,12.365-32.397,12.365-44.75,0c-12.354-12.354-12.354-32.391,0-44.744 L278.318,225.92L106.409,54.017c-12.354-12.359-12.354-32.394,0-44.748c12.354-12.359,32.391-12.359,44.75,0l194.287,194.284 c6.177,6.18,9.262,14.271,9.262,22.366C354.708,234.018,351.617,242.115,345.441,248.292z\"/></svg>",
        "last": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" viewBox=\"0 0 245 245\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 245 245;\" xml:space=\"preserve\"><path class=\"st0\" d=\"M205.4,122.5l-84.2,95.2c-6.2,6.2-6.2,16.4,0,22.6s16.4,6.2,22.6,0l94-106.3c3.2-3.2,4.7-7.3,4.6-11.5 c0-4.2-1.5-8.4-4.6-11.5l-94-106.3c-6.2-6.2-16.4-6.2-22.6,0s-6.2,16.4,0,22.6L205.4,122.5z\"/><path class=\"st0\" d=\"M91.5,122.5L7.3,217.7C1,224,1,234.1,7.2,240.3c6.2,6.2,16.4,6.2,22.6,0l94-106.3c3.2-3.2,4.7-7.3,4.6-11.5c0-4.2-1.5-8.4-4.6-11.5L29.9,4.6c-6.3-6.2-16.4-6.2-22.6,0C1,10.8,1,21,7.3,27.2L91.5,122.5z\"/></svg>",
        "previous": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"  x=\"0px\" y=\"0px\" viewBox=\"0 0 451.847 451.847\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 451.847 451.847;\" xml:space=\"preserve\"><path d=\"M97.141,225.92c0-8.095,3.091-16.192,9.259-22.366L300.689,9.27c12.359-12.359,32.397-12.359,44.751,0 c12.354,12.354,12.354,32.388,0,44.748L173.525,225.92l171.903,171.909c12.354,12.354,12.354,32.391,0,44.744 c-12.354,12.365-32.386,12.365-44.745,0l-194.29-194.281C100.226,242.115,97.141,234.018,97.141,225.92z\"/></svg>",
        "first": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"  viewBox=\"0 0 245.019 245.019\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 245.019 245.019;\" xml:space=\"preserve\"><path d=\"M39.597,122.521l84.224-95.22c6.229-6.229,6.229-16.368,0-22.597 c-6.229-6.229-16.368-6.229-22.597,0L7.179,110.984c-3.178,3.178-4.672,7.342-4.64,11.505c-0.032,4.163,1.462,8.359,4.64,11.537 	l94.044,106.344c6.229,6.198,16.368,6.198,22.597,0c6.229-6.198,6.229-16.4,0-22.597L39.597,122.521z\"/> <path d=\"M153.569,122.521l84.16-95.22c6.325-6.261,6.325-16.4,0.064-22.629 	c-6.198-6.229-16.4-6.229-22.597,0l-94.044,106.312c-3.178,3.178-4.704,7.342-4.64,11.505c-0.032,4.163,1.462,8.359,4.64,11.537 l94.013,106.344c6.261,6.198,16.432,6.198,22.597,0c6.261-6.198,6.261-16.4,0-22.597L153.569,122.521z\"/></svg>",
      }
    },
    "dom": "<'row'<'col-sm-12 text-right'B>>" + "<'row'<'col-sm-12'tr>>" + "<'row'<'col-sm-5'i><'col-sm-7'p>>",
    "order": [[ 0, "desc" ]]
  });

  $('.estado-filter').on('change', function(){
     table.columns(7).search(this.value).draw();
  });

  $('.id-filter').on('keyup', function(){
     table.columns(0).search(this.value).draw();
  });

  $('.entidade-filter').on('change', function(){
     table.columns(1).search(this.value).draw();
  });

  $(document).on('dp.change', 'input.datetimepicker.filter', function() {
     table.draw();
  });

  $(document).on('keyup', 'input.valor.filter', function() {
     table.draw();
  });

$(document).on("click", '.btn_eliminar_orcamento', function() {
  $("#orcamentoeliminarid").val($(this).data("id"));
  $('#eliminar_orcamento').modal('show');
});

$(document).on("click", '.link-abrir-descricoes-tabela-orcamentos', function(e) {
  e.preventDefault();
  var link = $(this);
  link.toggleClass("active");
  $( ".parent-tabela-orcamentos " ).each(function( index ) {
    jQuery(this).find(".tabela-orcamentos tbody tr").each(function( index ) {
      var $this = $(this);
      if(link.hasClass("active")){
        if(!$this.find(".collapse-td-nome-tabela-orcamentos").hasClass("show")){
          $this.find(".descricao-td-nome-tabela-orcamentos a").click();
        }
        link.text("Esconder descrições dos elementos");
      }else{
        if($this.find(".collapse-td-nome-tabela-orcamentos").hasClass("show")){
          $this.find(".descricao-td-nome-tabela-orcamentos a").click();
        }
        link.text("Mostrar descrições dos elementos");
      }
    });
  });
});



//QUANDO MUDA DE ESTADO DO ORÇAMENTO
$(document).on("click", '.change-estado, .btnalterarestado', function() {
  var orcid = $(this).data('orcid'),
      estadoid = $(this).data('id');
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "modal_orcamento_aprovado", "orcid": orcid, "estadoid" : estadoid },
    cache: false,
    success: function(response){
      $('#modal_alterar_estado .modal-body').html(response);
      $('#modal_alterar_estado').modal('show');
    }
  });
});


//ACTUALIZA VALORES/CUSTO DA ELEMENTO

$(document).on("change paste keyup",".topo-lista-novo-elemento-tabela-orcamentos input[name='valor']", function() {
  var parent = $(this).parent();
  var qtd = 0;
  var calc = 0;
  var valor = jQuery(this).val();
  if(parent.find("input[name='quantidade']").length){
    if(parent.find("input[name='quantidade']").val()){
      qtd = parent.find("input[name='quantidade']").val();
    }
  }else{
    if(parent.find("input[name='qtd_tempoestimado']").val()){
      qtd =  parent.find("input[name='qtd_tempoestimado']").val();
    }
  }
  if(qtd>0){
    calc = parseFloat(valor/qtd).toFixed(2);
  }
  parent.find("input[name='valor_unitario']").val(calc);
});

$(document).on("change paste keyup",".topo-lista-novo-elemento-tabela-orcamentos input[name='custo']", function() {
  var parent = $(this).parent();
  var qtd = 0;
  var calc = 0;
  var valor = jQuery(this).val();
  if(parent.find("input[name='quantidade']").length){
    if(parent.find("input[name='quantidade']").val()){
      qtd = parent.find("input[name='quantidade']").val();
    }
  }else{
    if(parent.find("input[name='qtd_tempoestimado']").val()){
      qtd =  parent.find("input[name='qtd_tempoestimado']").val();
    }
  }
  if(qtd>0){
    calc = parseFloat(valor/qtd).toFixed(2);
  }
  parent.find("input[name='custo_unitario']").val(calc);
});

//QUANDO MUDA O SELECT DO NOME DO ELEMENTO ACTUALIZA A POSIÇÃO
$(document).on("change", 'select[name="elemento"]', function() {
  var select = $(this);
  var parent =select.parent().parent();
  var nome_elemento = select.find("option:selected").val();

  //ACTUALIZA POSICOES
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "atualiza_select_posicoes", "nome_elemento": nome_elemento },
    cache: false,
    async:false,
    success: function(response){
      parent.find("select[name='posicao_atribuida']").html(response);
    }
  });

  //ACTUALIZA CUSTO
  $.ajax({
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "atualiza_select_custo", "nome_elemento": nome_elemento },
    cache: false,
    success: function(response){
      parent.find("input[name='custo']").val(response.replace(/ /g,''));
      parent.find("input[name='custo_unitario']").val(response.replace(/ /g,''));
    }
  });

});

$(document).on("change paste keyup",".topo-lista-novo-elemento-tabela-orcamentos input[name='qtd_tempoestimado']", function() {
  var parent = $(this).parent();
  var qtd = jQuery(this).val();
  var valor_custo_unitario = 0;
  var valor_unitario = 0;
  if(parent.find("input[name='custo_unitario']").val()){
    valor_custo_unitario = parent.find("input[name='custo_unitario']").val();
  }
  if(parent.find("input[name='valor_unitario']").val()){
    valor_unitario = parent.find("input[name='valor_unitario']").val();
  }
  var valorarredondado_custo = parseFloat(valor_custo_unitario*qtd).toFixed(2);
  var valorarredondado_valor = parseFloat(valor_unitario*qtd).toFixed(2);
  parent.find("input[name='custo']").val(valorarredondado_custo);
  parent.find("input[name='valor']").val(valorarredondado_valor);
});


//ACTUALIZA VALORES/CUSTO DA MODAL
$(document).on("change paste keyup","#modal_editar_elemento_conteudo input[name='valor']", function() {
  var valor_uni = jQuery(this).val();
  if(jQuery("#modal_editar_elemento_conteudo input[name='quantidade']").length){
    var qtd = jQuery("#modal_editar_elemento_conteudo input[name='quantidade']").val();
  }else{
    var qtd = jQuery("#modal_editar_elemento_conteudo input[name='tempoestimado']").val();
  }
  var calc = parseFloat(valor_uni/qtd).toFixed(2);
  jQuery("#modal_editar_elemento_conteudo input[name='valor_unitario']").val(calc);
});

$(document).on("change paste keyup","#modal_editar_elemento_conteudo input[name='custo']", function() {
  var valor_uni = jQuery(this).val();
  if(jQuery("#modal_editar_elemento_conteudo input[name='quantidade']").length){
    var qtd = jQuery("#modal_editar_elemento_conteudo input[name='quantidade']").val();
  }else{
    var qtd = jQuery("#modal_editar_elemento_conteudo input[name='tempoestimado']").val();
  }
  var calc = parseFloat(valor_uni/qtd).toFixed(2);
  jQuery("#modal_editar_elemento_conteudo input[name='custo_unitario']").val(calc);
});


$(document).on("change paste keyup","#modal_editar_elemento_conteudo input[name='quantidade']", function() {
  var qtd = jQuery(this).val();
  var valor_unitario = jQuery("#modal_editar_elemento_conteudo input[name='valor_unitario']").val();
  var custo_unitario = jQuery("#modal_editar_elemento_conteudo input[name='custo_unitario']").val();
  var calc = parseFloat(qtd*valor_unitario).toFixed(2);
  var calc2 = parseFloat(qtd*custo_unitario).toFixed(2);
  $("#modal_editar_elemento_conteudo").find("input[name='valor']").val(calc);
  $("#modal_editar_elemento_conteudo").find("input[name='custo']").val(calc2);
});

$(document).on("change paste keyup","#modal_editar_elemento_conteudo input[name='tempoestimado']", function() {
  var qtd = jQuery(this).val();
  var valor_unitario = jQuery("#modal_editar_elemento_conteudo input[name='valor_unitario']").val();
  var custo_unitario = jQuery("#modal_editar_elemento_conteudo input[name='custo_unitario']").val();
  var calc = parseFloat(qtd*valor_unitario).toFixed(2);
  var calc2 = parseFloat(qtd*custo_unitario).toFixed(2);
  $("#modal_editar_elemento_conteudo").find("input[name='valor']").val(calc);
  $("#modal_editar_elemento_conteudo").find("input[name='custo']").val(calc2);
});
