{{ javascript_include("vendors/Chart.js/dist/Chart.bundle.min.js") }}

<!-- document ready -->
<script>
{% if router.getActionName() == "index" %}
var backward_ongoing_qty = false;
var backward_ongoing_val = false;
var forward_ongoing_qty = false;
var forward_ongoing_val = false;
function handleArrowsOpacity(backward, forward, idBackward, idForward) {
  $(idBackward).css('opacity', backward ? '0.5' : '1');
  $(idForward).css('opacity', forward ? '0.5' : '1');
}
{% endif %}

$(document).ready(function($) {
{% if router.getActionName() == "index" %}
  init_daterangepicker();
  $('#backward-slider-best-qty').click(function(){
    if (!backward_ongoing_qty) {
      backward_ongoing_qty = true;

      var left_val = $('#slider-best-qty').css('left');
      left_val = left_val.substr(0, left_val.length - 2);

      var width_move = 220;
      var opacity = false;

      if (parseInt(left_val) + 220 >= 0) {
        width_move = -1 * left_val;
        opacity = true;
      }

      $('#slider-best-qty').animate({
        left: parseInt(left_val) + parseInt(width_move)
      }, 400, function(){
        backward_ongoing_qty = false;
        handleArrowsOpacity(opacity, false, '#backward-slider-best-qty', '#forward-slider-best-qty');
      });
    }
  });
  $('#backward-slider-best-val').click(function(){
    if (!backward_ongoing_val) {
      backward_ongoing_val = true;

      var left_val = $('#slider-best-val').css('left');
      left_val = left_val.substr(0, left_val.length - 2);

      var width_move = 220;
      var opacity = false;

      if (parseInt(left_val) + 220 >= 0) {
        width_move = -1 * left_val;
        opacity = true;
      }

      $('#slider-best-val').animate({
        left: parseInt(left_val) + parseInt(width_move)
      }, 400, function(){
        backward_ongoing_val = false;
        handleArrowsOpacity(opacity, false, '#backward-slider-best-val', '#forward-slider-best-val');
      });
    }
  });
  $('#forward-slider-best-qty').click(function(){
    if (!forward_ongoing_qty) {
      forward_ongoing_qty = true;

      var left_val = $('#slider-best-qty').css('left');
      left_val = left_val.substr(0, left_val.length - 2);

			var slider_width  = $('.slide-best-qty').width();

      var width_move = 220;
      var opacity = false;

      if (slider_width >= ($('#slider-best-qty').width() + parseInt(left_val) - 220)) {
        width_move = ($('#slider-best-qty').width() + parseInt(left_val)) - slider_width;
        opacity = true;
      }

      $('#slider-best-qty').animate({
        left: "-=" + width_move
      }, 400, function(){
        forward_ongoing_qty = false;
        handleArrowsOpacity(false, opacity, '#backward-slider-best-qty', '#forward-slider-best-qty');
      });
    }
	});
  $('#forward-slider-best-val').click(function(){
    if (!forward_ongoing_val) {
      forward_ongoing_val = true;

      var left_val = $('#slider-best-val').css('left');
      left_val = left_val.substr(0, left_val.length - 2);

			var slider_width  = $('.slide-best-val').width();

      var width_move = 220;
      var opacity = false;

      if (slider_width >= ($('#slider-best-val').width() + parseInt(left_val) - 220)) {
        width_move = ($('#slider-best-val').width() + parseInt(left_val)) - slider_width;
        opacity = true;
      }

      $('#slider-best-val').animate({
        left: "-=" + width_move
      }, 400, function(){
        forward_ongoing_val = false;
        handleArrowsOpacity(false, opacity, '#backward-slider-best-val', '#forward-slider-best-val');
      });
    }
	});
{% endif %}
});
</script>

{% include "scripts/common/new_order.volt" %}


<script>
{% if router.getActionName() == "index" %}
$('.best-model').click(function(){
  var cdartn = $(this).find(".best-title").html();
  location.href = "{{ url('model') }}/" + cdartn;
});
function resetCanvas(){
  $('iframe').remove();
  $('#canvas-qty').remove(); // this is my <canvas> element
  $('#canvas-val').remove(); // this is my <canvas> element
  $('#canvas-trn').remove(); // this is my <canvas> element
  $('#top-10-qty').append('<canvas id="canvas-qty" width="400" height="400"><canvas>');
  $('#top-10-val').append('<canvas id="canvas-val" width="400" height="400"><canvas>');
  $('#trend-container').append('<canvas id="canvas-trn" width="200" height="200"><canvas>');
};
$('#btn-dashboard').click(function(e){
	e.preventDefault();

	if ($('input[name=periodtype_dashboard]:checked').val() == "custom" && $('input[name=period_dashboard]').val() == "") {
		$('input#all_periodtype_dashboard').prop('checked', true);
	}

	var season 	= $('#season-dashboard').val();
	var dates		= $('input[name=period_dashboard]').val();

	$.ajax({
	  type: "POST",
	  url: "{{ url('statistics/getdashboard') }}",
	  dataType: "json",
	  data: {
	    season: season,
	    dates:  dates,
	  },
    beforeSend: function() {
      resetCanvas();
      $('#all-index-stats').hide();
      $('#loading-dashboard').show();
      $("#dashboard-stats").hide();
    }
	}).done(function(data){
    $('#all-index-stats').show();
    $('#loading-dashboard').hide();
    $("#dashboard-stats").show();

    // Overall analysis
    $("#tot-ord").html(parseFloat(data.tot_ord).toLocaleString());
    $("#qty-tot").html(parseFloat(data.qty_tot).toLocaleString());
    if (data.qty_avg_ord != "nd.") {
      $("#qty-avg-ord").css("font-style", "normal");
      $("#qty-avg-ord").html(parseFloat(data.qty_avg_ord.toFixed(2)).toLocaleString());
    } else {
      $("#qty-avg-ord").css("font-style", "italic");
      $("#qty-avg-ord").html(data.qty_avg_ord);
    }
    $("#val-tot").html(parseFloat(data.val_tot.toFixed(2)).toLocaleString() + " {{ common['currency'] }}");
    if (data.val_avg_ord != "nd.") {
      $("#val-avg-ord").css("font-style", "normal");
      $("#val-avg-ord").html(parseFloat(data.val_avg_ord.toFixed(2)).toLocaleString() + " {{ common['currency'] }}");
    } else {
      $("#val-avg-ord").css("font-style", "italic");
      $("#val-avg-ord").html(data.val_avg_ord);
    }
    if (data.val_avg_prd != "nd.") {
      $("#val-avg-prd").css("font-style", "normal");
      $("#val-avg-prd").html(parseFloat(data.val_avg_prd.toFixed(2)).toLocaleString() + " {{ common['currency'] }}");
    } else {
      $("#val-avg-prd").css("font-style", "italic");
      $("#val-avg-prd").html(data.val_avg_prd);
    }

    // Top 10 quantity
    if (data.top_10_qty.length > 0) {
      $("#top-10-qty").show();
      var labels1   = [];
      var dataset1  = [];
      for (var i = 0; i < data.top_10_qty.length; i++) {
        labels1.push(data.top_10_qty[i].codana + " - " + data.top_10_qty[i].ragsoc);
        dataset1.push(data.top_10_qty[i].tot_qty);
      }
      new Chart(document.getElementById("canvas-qty"),{
        "type":"horizontalBar",
        "data":{
          "labels": labels1,
          "datasets":[{
            "label": "{{ mt._('_common.quantity') }}",
            "data":dataset1,
            "fill":false,
            "backgroundColor": "rgba(96, 96, 96, 0.8)",
            "borderColor":"rgb(96, 96, 96)",
            "borderWidth":1
          }]
        },
        "options":{
          "legend":{"display": false},
          "scales":{"xAxes":[{"ticks":{"beginAtZero":true}}]},
          "maintainAspectRatio": false,
        }
      });
    } else {
      $("#top-10-qty").hide();
    }

    // Top 10 value
    if (data.top_10_val.length > 0) {
      $("#top-10-val").show();
      var labels2   = [];
      var dataset2  = [];
      for (var i = 0; i < data.top_10_val.length; i++) {
        labels2.push(data.top_10_val[i].codana + " - " + data.top_10_val[i].ragsoc);
        dataset2.push(data.top_10_val[i].tot_val);
      }

      new Chart(document.getElementById("canvas-val"),{
        "type":"horizontalBar",
        "data":{
          "labels": labels2,
          "datasets":[{
      			"label": "{{ mt._('_common.value') }}",
            "data":dataset2,
            "fill":false,
      			"backgroundColor": "rgba(0, 168, 204, 0.8)",
      			"borderColor":"rgb(0, 168, 204)",
            "borderWidth":1
          }]
        },
        "options":{
          "legend":{"display": false},
          "scales":{"xAxes":[{"ticks":{"beginAtZero":true}}]},
          "maintainAspectRatio": false,
        }
      });
    } else {
      $("#top-10-val").hide();
    }

    // Top 10 bestseller (quantity)
    if (data.top_10_mod_qty.length > 0) {
      $("#top-10-mod-qty").show();

      for (var i = 0; i < 10; i++) {
        if (i <= data.top_10_mod_qty.length) {
          $("#best-mod-qty" + i).show();
          $("#best-img-qty" + i).attr("src", data.top_10_mod_qty[i].flimag);
          $("#best-img-qty" + i).attr("alt", data.top_10_mod_qty[i].desneu);
          $("#best-img-qty" + i).attr("title", data.top_10_mod_qty[i].desneu);
          $("#best-qty" + i).attr("title", data.top_10_mod_qty[i].desneu);
          $("#best-title-qty" + i).html(data.top_10_mod_qty[i].codneu);
          $("#best-descr-qty" + i).html(data.top_10_mod_qty[i].desneu);
          $("#best-value-qty" + i).html(data.top_10_mod_qty[i].tot_qty);
        } else {
          $("#best-mod-qty" + i).hide();
        }
      }
    } else {
      $("#top-10-mod-qty").hide();
    }
    if ($('.slide-best-qty').width() < 220 * data.top_10_mod_qty.length) {
      $("#backward-slider-best-qty").show();
      $("#forward-slider-best-qty").show();
    } else {
      $("#backward-slider-best-qty").hide();
      $("#forward-slider-best-qty").hide();
    }

    // Top 10 bestseller (value)
    if (data.top_10_mod_val.length > 0) {
      $("#top-10-mod-val").show();

      for (var i = 0; i < 10; i++) {
        if (i <= data.top_10_mod_val.length) {
          $("#best-mod-val" + i).show();
          $("#best-img-val" + i).attr("src", data.top_10_mod_val[i].flimag);
          $("#best-img-val" + i).attr("alt", data.top_10_mod_val[i].desneu);
          $("#best-img-val" + i).attr("title", data.top_10_mod_val[i].desneu);
          $("#best-val" + i).attr("title", data.top_10_mod_val[i].desneu);
          $("#best-title-val" + i).html(data.top_10_mod_val[i].codneu);
          $("#best-descr-val" + i).html(data.top_10_mod_val[i].desneu);
          $("#best-value-val" + i).html(parseFloat(data.top_10_mod_val[i].tot_val, 10).toFixed(2).replace(".", ",").replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") + " {{ common['currency'] }}");
        } else {
          $("#best-mod-val" + i).hide();
        }
      }
    } else {
      $("#top-10-mod-val").hide();
    }
    if ($('.slide-best-val').width() < 220 * data.top_10_mod_val.length) {
      $("#backward-slider-best-val").show();
      $("#forward-slider-best-val").show();
    } else {
      $("#backward-slider-best-val").hide();
      $("#forward-slider-best-val").hide();
    }

    // Trend
    if (data.trend.length > 0) {
      $("#trend").show();
      var labels3   = [];
      var dataset_qty  = [];
      var dataset_val  = [];
      for (var i = 0; i < data.trend.length; i++) {
        var date_format = data.trend[i]["date"].substring(8, 10) + "/" + data.trend[i]["date"].substring(5, 7) + "/" + data.trend[i]["date"].substring(0, 4);
        labels3.push(date_format);
        dataset_qty.push(data.trend[i]["qty"]);
        dataset_val.push(data.trend[i]["val"]);
      }

      var lineChartData = {
        "labels": labels3,
        "datasets": [{
          "label": "{{ mt._('_common.quantity') }}",
          "borderColor":"rgb(96, 96, 96)",
          "backgroundColor": "rgba(96, 96, 96, 0.8)",
          "fill": false,
          "data": dataset_qty,
          "yAxisID": "y-axis-1",
        }, {
          "label": "{{ mt._('_common.value') }}",
          "borderColor": "rgb(0, 168, 204)",
          "backgroundColor": "rgba(0, 168, 204, 0.8)",
          "fill": false,
          "data": dataset_val,
          "yAxisID": "y-axis-2"
        }]
      };

      new Chart(document.getElementById("canvas-trn"),{
        "type":"line",
        "data": lineChartData,
        "options": {
          "responsive": true,
          "hoverMode": 'index',
          "stacked": false,
          "maintainAspectRatio": false,
          "scales": {
            "yAxes": [{
              "type": "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
              "display": true,
              "position": "left",
              "id": "y-axis-1",
            }, {
              "type": "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
              "display": true,
              "position": "right",
              "id": "y-axis-2",

              // grid line settings
              "gridLines": {
                "drawOnChartArea": false, // only want the grid lines for one axis to show up
              },
            }],
          }
        }
      });
    } else {
      $("#trend").hide();
    }

    canvas1 = document.querySelector('#canvas-qty');
    canvas2 = document.querySelector('#canvas-val');
    canvas3 = document.querySelector('#canvas-trn');
    ctx1 = canvas1.getContext('2d');
    ctx2 = canvas2.getContext('2d');
    ctx3 = canvas3.getContext('2d');
    ctx1.canvas.width = $('#top-10-qty').width(); // resize to parent width
    ctx2.canvas.width = $('#top-10-val').width(); // resize to parent width
    ctx3.canvas.width = $('#trend-container').width(); // resize to parent width
    ctx1.canvas.height = $('#top-10-qty').height(); // resize to parent height
    ctx2.canvas.height = $('#top-10-val').height(); // resize to parent height
    ctx3.canvas.height = $('#trend-container').height(); // resize to parent height
	}).error(function(x, t, m) {
		printAjaxError(x, t, m);
	});
});
$('input[name="period_type"]').change(function(){
  if ($('input[name="period_type"]:checked').val() == 0) {
    $('#season-choose').show();
    $('#period-choose').hide();
  } else {
    $('#season-choose').hide();
    $('#period-choose').show();
  }
});

function init_daterangepicker() {
  {% include "scripts/common/daterangepicker_config.volt" %}
	if( typeof ($.fn.daterangepicker) === 'undefined'){ return; }

  drpConfig2['drops'] = 'left';
	$('#period_dashboard-box').daterangepicker(drpConfig2, function(start, end, label) {
    if (start._i != '01/01/1970' && end._i != '01/01/1970') {
      $('#period_dashboard-box span').html(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
      $('#period_dashboard').val(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
    } else {
      $('#period_dashboard-box span').html('{{ mt._("statistics.complete") }}');
      $('#period_dashboard').val('ALL');
    }
	});
  drpConfig2['drops'] = 'up';
	$('#period1-box').daterangepicker(drpConfig3, function(start, end, label) {
	  $('#period1-box span').html(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
	  $('#period1').val(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
	});
	$('#period2-box').daterangepicker(drpConfig3, function(start, end, label) {
	  $('#period2-box span').html(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
	  $('#period2').val(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
	});
  drpConfig2['opens'] = 'left';
	$('#period3-box').daterangepicker(drpConfig3, function(start, end, label) {
	  $('#period3-box span').html(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
	  $('#period3').val(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
	});
}
/*
$('#period_dashboard').daterangepicker({
  opens: "right",
  drops: "left",
  autoUpdateInput: false,
  {% include "scripts/common/daterangepicker_locale.volt" %}
}, function(start, end, label) {
  $('#period_dashboard').val(start.format('DD/MM/YYYY') + " - " + end.format('DD/MM/YYYY'));
});
$('#period1').daterangepicker({
  opens: "right",
  drops: "up",
  autoUpdateInput: false,
  {% include "scripts/common/daterangepicker_locale.volt" %}
}, function(start, end, label) {
  $('#period1').val(start.format('DD/MM/YYYY') + " - " + end.format('DD/MM/YYYY'));
});
$('#period2').daterangepicker({
  opens: "right",
  drops: "up",
  autoUpdateInput: false,
  {% include "scripts/common/daterangepicker_locale.volt" %}
}, function(start, end, label) {
  $('#period2').val(start.format('DD/MM/YYYY') + " - " + end.format('DD/MM/YYYY'));
});
$('#period3').daterangepicker({
  opens: "left",
  drops: "up",
  autoUpdateInput: false,
  {% include "scripts/common/daterangepicker_locale.volt" %}
}, function(start, end, label) {
  $('#period3').val(start.format('DD/MM/YYYY') + " - " + end.format('DD/MM/YYYY'));
});*/
function requestCatSearchResults() {
  var searchText = $("#cat_search_field").val();
  $(".catalog-row").hide();
  $(".catalog-row > .cdcata:contains('" + searchText + "')" ).closest(".catalog-row").show();
  $(".catalog-row > .dscata:contains('" + searchText + "')" ).closest(".catalog-row").show();
  $(".catalog-row > .cdcata:contains('" + searchText.toUpperCase() + "')" ).closest(".catalog-row").show();
  $(".catalog-row > .dscata:contains('" + searchText.toUpperCase() + "')" ).closest(".catalog-row").show();
}
function requestCouSearchResults() {
  var searchText = $("#cou_search_field").val();
  $(".country-row").hide();
  $(".country-row > .nazion:contains('" + searchText + "')" ).closest(".country-row").show();
  $(".country-row > .nazion:contains('" + searchText.toUpperCase() + "')" ).closest(".country-row").show();
}
function requestCusSearchResults() {
  var searchText = $("#cus_search_field").val();
  $(".customer-row").hide();
  $(".customer-row > .codana:contains('" + searchText + "')" ).closest(".customer-row").show();
  $(".customer-row > .ragsoc:contains('" + searchText + "')" ).closest(".customer-row").show();
  $(".customer-row > .ragsoc:contains('" + searchText.toUpperCase() + "')" ).closest(".customer-row").show();
  $(".customer-row > .codana:contains('" + searchText.toUpperCase() + "')" ).closest(".customer-row").show();
}
function requestGenSearchResults() {
  var searchText = $("#gen_search_field").val();
  $(".genre-row").hide();
  $(".genre-row > .genere:contains('" + searchText + "')" ).closest(".genre-row").show();
  $(".genre-row > .genere:contains('" + searchText.toUpperCase() + "')" ).closest(".genre-row").show();
}
function requestLinSearchResults() {
  var searchText = $("#lin_search_field").val();
  $(".line-row").hide();
  $(".line-row > .lineam:contains('" + searchText + "')" ).closest(".line-row").show();
  $(".line-row > .lineam:contains('" + searchText.toUpperCase() + "')" ).closest(".line-row").show();
}
function requestMotSearchResults() {
  var searchText = $("#mot_search_field").val();
  $(".modeltype-row").hide();
  $(".modeltype-row > .tipmod:contains('" + searchText + "')" ).closest(".modeltype-row").show();
  $(".modeltype-row > .tipmod:contains('" + searchText.toUpperCase() + "')" ).closest(".modeltype-row").show();
}
function requestOrtSearchResults() {
  var searchText = $("#ort_search_field").val();
  $(".ordertype-row").hide();
  $(".ordertype-row > .tipord:contains('" + searchText + "')" ).closest(".ordertype-row").show();
  $(".ordertype-row > .tipord:contains('" + searchText.toUpperCase() + "')" ).closest(".ordertype-row").show();
}
function requestZonSearchResults() {
  var searchText = $("#zon_search_field").val();
  $(".zone-row").hide();
  $(".zone-row > .zonage:contains('" + searchText + "')" ).closest(".zone-row").show();
  $(".zone-row > .zonage:contains('" + searchText.toUpperCase() + "')" ).closest(".zone-row").show();
}

$("#cat_search_field").keyup(function() {
  if ($("#cat_search_field").val().length > 1) {
    delay( function() { requestCatSearchResults(); }, 100 );
  } else {
    $("#cat_search_field").html("");
    $(".catalog-row").show();
  }
});
$("#cou_search_field").keyup(function() {
  if ($("#cou_search_field").val().length > 1) {
    delay( function() { requestCouSearchResults(); }, 100 );
  } else {
    $("#cou_search_field").html("");
    $(".country-row").show();
  }
});
$("#cus_search_field").keyup(function() {
  if ($("#cus_search_field").val().length > 1) {
    delay( function() { requestCusSearchResults(); }, 100 );
  } else {
    $("#cus_search_field").html("");
    $(".customer-row").show();
  }
});
$("#gen_search_field").keyup(function() {
  if ($("#gen_search_field").val().length > 1) {
    delay( function() { requestGenSearchResults(); }, 100 );
  } else {
    $("#gen_search_field").html("");
    $(".genre-row").show();
  }
});
$("#lin_search_field").keyup(function() {
  if ($("#lin_search_field").val().length > 1) {
    delay( function() { requestLinSearchResults(); }, 100 );
  } else {
    $("#lin_search_field").html("");
    $(".line-row").show();
  }
});
$("#mot_search_field").keyup(function() {
  if ($("#mot_search_field").val().length > 1) {
    delay( function() { requestMotSearchResults(); }, 100 );
  } else {
    $("#mot_search_field").html("");
    $(".modeltype-row").show();
  }
});
$("#ort_search_field").keyup(function() {
  if ($("#ort_search_field").val().length > 1) {
    delay( function() { requestOrtSearchResults(); }, 100 );
  } else {
    $("#ort_search_field").html("");
    $(".ordertype-row").show();
  }
});
$("#zon_search_field").keyup(function() {
  if ($("#zon_search_field").val().length > 1) {
    delay( function() { requestZonSearchResults(); }, 100 );
  } else {
    $("#zon_search_field").html("");
    $(".zone-row").show();
  }
});

$("#btn-che-all-cat").click(function(){
  $('input[name="catalog-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-cou").click(function(){
  $('input[name="country-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-cus").click(function(){
  $('input[name="customer-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-gen").click(function(){
  $('input[name="genre-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-lin").click(function(){
  $('input[name="line-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-mot").click(function(){
  $('input[name="modeltype-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-ort").click(function(){
  $('input[name="ordertype-checkbox[]"]').prop('checked', true);
});
$("#btn-che-all-zon").click(function(){
  $('input[name="zone-checkbox[]"]').prop('checked', true);
});

$("#btn-unc-all-cat").click(function(){
  $('input[name="catalog-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-cou").click(function(){
  $('input[name="country-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-cus").click(function(){
  $('input[name="customer-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-gen").click(function(){
  $('input[name="genre-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-lin").click(function(){
  $('input[name="line-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-mot").click(function(){
  $('input[name="modeltype-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-ort").click(function(){
  $('input[name="ordertype-checkbox[]"]').prop('checked', false);
});
$("#btn-unc-all-zon").click(function(){
  $('input[name="zone-checkbox[]"]').prop('checked', false);
});

$("#btn-confirm-cat").click(function(){
  var allRowLength = $(".catalog-row").length;
  var selectedRow = $(".catalog-row input:checked").closest(".catalog-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-cat").click();
    $("#sel-cat").html("{{ mt._('statistics.selected.cat.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".cdcata").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-cat").html(selectedText);
  }
  $(".modal-catalogs").modal("hide");
});
$("#btn-confirm-cou").click(function(){
  var allRowLength = $(".country-row").length;
  var selectedRow = $(".country-row input:checked").closest(".country-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-cou").click();
    $("#sel-cou").html("{{ mt._('statistics.selected.cou.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".nazion").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-cou").html(selectedText);
  }
  $(".modal-countries").modal("hide");
});
$("#btn-confirm-cus").click(function(){
  var allRowLength = $(".customer-row").length;
  var selectedRow = $(".customer-row input:checked").closest(".customer-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-cus").click();
    $("#sel-cus").html("{{ mt._('statistics.selected.cus.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".codana").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-cus").html(selectedText);
  }
  $(".modal-customers").modal("hide");
});
$("#btn-confirm-gen").click(function(){
  var allRowLength = $(".genre-row").length;
  var selectedRow = $(".genre-row input:checked").closest(".genre-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-gen").click();
    $("#sel-gen").html("{{ mt._('statistics.selected.gen.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".genere").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-gen").html(selectedText);
  }
  $(".modal-genres").modal("hide");
});
$("#btn-confirm-lin").click(function(){
  var allRowLength = $(".line-row").length;
  var selectedRow = $(".line-row input:checked").closest(".line-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-lin").click();
    $("#sel-lin").html("{{ mt._('statistics.selected.lin.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".lineam").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-lin").html(selectedText);
  }
  $(".modal-lines").modal("hide");
});
$("#btn-confirm-mot").click(function(){
  var allRowLength = $(".modeltype-row").length;
  var selectedRow = $(".modeltype-row input:checked").closest(".modeltype-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-mot").click();
    $("#sel-mot").html("{{ mt._('statistics.selected.mot.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".tipmod").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-mot").html(selectedText);
  }
  $(".modal-modeltypes").modal("hide");
});
$("#btn-confirm-ort").click(function(){
  var allRowLength = $(".ordertype-row").length;
  var selectedRow = $(".ordertype-row input:checked").closest(".ordertype-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-ort").click();
    $("#sel-ort").html("{{ mt._('statistics.selected.ort.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".tipord").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-ort").html(selectedText);
  }
  $(".modal-ordertypes").modal("hide");
});
$("#btn-confirm-zon").click(function(){
  var allRowLength = $(".zone-row").length;
  var selectedRow = $(".zone-row input:checked").closest(".zone-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-zon").click();
    $("#sel-zon").html("{{ mt._('statistics.selected.zon.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".zonage").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-zon").html(selectedText);
  }
  $(".modal-zones").modal("hide");
});

{% if series|length > 0 and series[0] != "" %}
function requestSerSearchResults() {
  var searchText = $("#ser_search_field").val();
  $(".serie-row").hide();
  $(".serie-row > .seriem:contains('" + searchText + "')" ).closest(".serie-row").show();
  $(".serie-row > .seriem:contains('" + searchText.toUpperCase() + "')" ).closest(".serie-row").show();
}
$("#ser_search_field").keyup(function() {
  if ($("#ser_search_field").val().length > 1) {
    delay( function() { requestSerSearchResults(); }, 100 );
  } else {
    $("#ser_search_field").html("");
    $(".serie-row").show();
  }
});
$("#btn-che-all-ser").click(function(){
  $('input[name="serie-checkbox[]"]').prop('checked', true);
});
$("#btn-unc-all-ser").click(function(){
  $('input[name="serie-checkbox[]"]').prop('checked', false);
});
$("#btn-confirm-ser").click(function(){
  var allRowLength = $(".serie-row").length;
  var selectedRow = $(".serie-row input:checked").closest(".serie-row");

  if (allRowLength == selectedRow.length || selectedRow.length == 0) {
    $("#btn-unc-all-ser").click();
    $("#sel-ser").html("{{ mt._('statistics.selected.ser.all') }}");
  } else {
    var selectedText = "";
    selectedRow.each(function(){
      selectedText += $(this).find(".seriem").html() + ", ";
    });

    selectedText = selectedText.substring(0, selectedText.length - 2);
    $("#sel-ser").html(selectedText);
  }
  $(".modal-series").modal("hide");
});
{% endif %}

$("#elaborate").click(function(){
  var typeStats   = $("#grouping").val();
  var catalogs    = [];
  var customers   = [];
  var lines       = [];
  var countries   = [];
  var series      = [];
  var zones       = [];
  var modeltypes  = [];
  var ordertypes  = [];
  var genres      = [];
  var typeTime    = $("input[name='period_type']:checked").val();
  var time1       = "";
  var time2       = "";
  var time3       = "";

  if ($(".catalog-row input:checked").length > 0) {
    $(".catalog-row input:checked").closest(".catalog-row").each(function(){
      catalogs.push($(this).find(".cdcata").html());
    });
  } else {
    catalogs = "all";
  }
  if ($(".customer-row input:checked").length > 0) {
    $(".customer-row input:checked").closest(".customer-row").each(function(){
      customers.push($(this).find(".codana").html());
    });
  } else {
    customers = "all";
  }
  if ($(".line-row input:checked").length > 0) {
    $(".line-row input:checked").closest(".line-row").each(function(){
      lines.push($(this).find(".lineam").html());
    });
  } else {
    lines = "all";
  }
  if ($(".country-row input:checked").length > 0) {
    $(".country-row input:checked").closest(".country-row").each(function(){
      countries.push($(this).find(".nazion").html());
    });
  } else {
    countries = "all";
  }
  if ($(".serie-row input:checked").length > 0) {
    $(".serie-row input:checked").closest(".serie-row").each(function(){
      series.push($(this).find(".seriem").html());
    });
  } else {
    series = "all";
  }
  if ($(".zone-row input:checked").length > 0) {
    $(".zone-row input:checked").closest(".zone-row").each(function(){
      zones.push($(this).find(".zonage").html());
    });
  } else {
    zones = "all";
  }
  if ($(".modeltype-row input:checked").length > 0) {
    $(".modeltype-row input:checked").closest(".modeltype-row").each(function(){
      modeltypes.push($(this).find(".tipmod").html());
    });
  } else {
    modeltypes = "all";
  }
  if ($(".ordertype-row input:checked").length > 0) {
    $(".ordertype-row input:checked").closest(".ordertype-row").each(function(){
      ordertypes.push($(this).find(".tipord").html());
    });
  } else {
    ordertypes = "all";
  }
  if ($(".genre-row input:checked").length > 0) {
    $(".genre-row input:checked").closest(".genre-row").each(function(){
      genres.push($(this).find(".genere").html());
    });
  } else {
    genres = "all";
  }

  if (typeTime == 1) {
    time1 = $("#period1").val();
    time2 = $("#period2").val();
    time3 = $("#period3").val();
  } else {
    time1 = $("#season1").val();
    time2 = $("#season2").val();
    time3 = $("#season3").val();
  }

  if (time1 == "_none" || time1 == "") {
    showTemporary(".msg-error", 5000);
    $("#period1").css("background-color","#ffeeee");
    $("#season1").css("background-color","#ffeeee");
    setTimeout( function(){
      $("#period1").css("background-color","white");
      $("#season1").css("background-color","white");
    }, 5000 );
  } else {
    $('.msg-error').hide();
    $("#period1").css("background-color","white");
    $("#season1").css("background-color","white");
    var form = "<form id='filters' action='{{ url('statistics/detail') }}' method='post'>";
    form += "<input type='text' name='typeStats' value='" + typeStats + "'/>";
    form += "<input type='text' name='typeTime' value='" + typeTime + "'/>";
    form += "<input type='text' name='time1' value='" + time1 + "'/>";
    form += "<input type='text' name='time2' value='" + time2 + "'/>";
    form += "<input type='text' name='time3' value='" + time3 + "'/>";
    if (catalogs != "all") {
      for (var i = 0; i < catalogs.length; i++) {
        form += "<input type='text' name='catalogs[]' value='" + catalogs[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='catalogs' value='all'/>";
    }
    if (countries != "all") {
      for (var i = 0; i < countries.length; i++) {
        form += "<input type='text' name='countries[]' value='" + countries[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='countries' value='all'/>";
    }
    if (customers != "all") {
      for (var i = 0; i < customers.length; i++) {
        form += "<input type='text' name='customers[]' value='" + customers[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='customers' value='all'/>";
    }
    if (genres != "all") {
      for (var i = 0; i < genres.length; i++) {
        form += "<input type='text' name='genres[]' value='" + genres[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='genres' value='all'/>";
    }
    if (lines != "all") {
      for (var i = 0; i < lines.length; i++) {
        form += "<input type='text' name='lines[]' value='" + lines[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='lines' value='all'/>";
    }
    if (modeltypes != "all") {
      for (var i = 0; i < modeltypes.length; i++) {
        form += "<input type='text' name='modeltypes[]' value='" + modeltypes[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='modeltypes' value='all'/>";
    }
    if (ordertypes != "all") {
      for (var i = 0; i < ordertypes.length; i++) {
        form += "<input type='text' name='ordertypes[]' value='" + ordertypes[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='ordertypes' value='all'/>";
    }
    if (series != "all") {
      for (var i = 0; i < series.length; i++) {
        form += "<input type='text' name='series[]' value='" + series[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='series' value='all'/>";
    }
    if (zones != "all") {
      for (var i = 0; i < zones.length; i++) {
        form += "<input type='text' name='zones[]' value='" + zones[i] + "'/>";
      }
    } else {
      form += "<input type='text' name='zones' value='all'/>";
    }
    form += "</form>";

    $("#send-filters-form").html(form);
    $("#send-filters-form > form").submit();
  }
});
{% elseif router.getActionName() == "detail" %}
var $divs = $("div.stat-row");

$('#cus-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.cus').html().toLowerCase(), $(b).find('.cus').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "cus");
  $("#stat-rows").data("direction", "up");
});
$('#cus-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.cus').html().toLowerCase(), $(a).find('.cus').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "cus");
  $("#stat-rows").data("direction", "down");
});
$('#brn-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.brn').html().toLowerCase(), $(b).find('.brn').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "brn");
  $("#stat-rows").data("direction", "up");
});
$('#brn-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.brn').html().toLowerCase(), $(a).find('.brn').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "brn");
  $("#stat-rows").data("direction", "down");
});
$('#lin-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.lin').html().toLowerCase(), $(b).find('.lin').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "lin");
  $("#stat-rows").data("direction", "up");
});
$('#lin-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.lin').html().toLowerCase(), $(a).find('.lin').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "lin");
  $("#stat-rows").data("direction", "down");
});
$('#mod-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.mod').html().toLowerCase(), $(b).find('.mod').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "mod");
  $("#stat-rows").data("direction", "up");
});
$('#mod-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.mod').html().toLowerCase(), $(a).find('.mod').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "mod");
  $("#stat-rows").data("direction", "down");
});
$('#mot-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.mot').html().toLowerCase(), $(b).find('.mot').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "mot");
  $("#stat-rows").data("direction", "up");
});
$('#mot-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.mot').html().toLowerCase(), $(a).find('.mot').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "mot");
  $("#stat-rows").data("direction", "down");
});
$('#art-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.art').html().toLowerCase(), $(b).find('.art').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "art");
  $("#stat-rows").data("direction", "up");
});
$('#art-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.art').html().toLowerCase(), $(a).find('.art').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "art");
  $("#stat-rows").data("direction", "down");
});
$('#ser-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(a).find('.ser').html().toLowerCase(), $(b).find('.ser').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "ser");
  $("#stat-rows").data("direction", "up");
});
$('#ser-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    return String.prototype.localeCompare.call($(b).find('.ser').html().toLowerCase(), $(a).find('.ser').html().toLowerCase());
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "ser");
  $("#stat-rows").data("direction", "down");
});
$('#qty-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    var aVal = $(a).find('.qty').text().toLowerCase();
    var bVal = $(b).find('.qty').text().toLowerCase();
    return parseInt(aVal) - parseInt(bVal);
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "qty");
  $("#stat-rows").data("direction", "up");
});
$('#qty-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    var aVal = $(a).find('.qty').text().toLowerCase();
    var bVal = $(b).find('.qty').text().toLowerCase();
    return parseInt(bVal) - parseInt(aVal);
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "qty");
  $("#stat-rows").data("direction", "down");
});
$('#imp-up').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    var aVal = $(a).find('.imp').text().toLowerCase();
    var bVal = $(b).find('.imp').text().toLowerCase();
    aVal = aVal.substring(0, aVal.length - 2).replace(",", "").replace(".", "");
    bVal = bVal.substring(0, bVal.length - 2).replace(",", "").replace(".", "");
    return parseInt(aVal) - parseInt(bVal);
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "imp");
  $("#stat-rows").data("direction", "up");
});
$('#imp-down').on('click', function () {
  var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
    var aVal = $(a).find('.imp').text().toLowerCase();
    var bVal = $(b).find('.imp').text().toLowerCase();
    aVal = aVal.substring(0, aVal.length - 2).replace(",", "").replace(".", "");
    bVal = bVal.substring(0, bVal.length - 2).replace(",", "").replace(".", "");
    return parseInt(bVal) - parseInt(aVal);
  });
  $("#stat-rows").html(alphabeticallyOrderedDivs);
  $("#stat-rows").data("ordering", "imp");
  $("#stat-rows").data("direction", "down");
});

function stopLoading (){
  $('#pdf-stats').find(".loading").remove();
};

function isNotLoading (){
  return ($('#pdf-stats').find(".loading").length == 0);
};

$('#pdf-stats').on('click', function(e) {
  e.preventDefault();

  if (isNotLoading()) {
    $(this).append('<span class="loading">{{ image("img/assets/preloader.gif", "class": "float-left h20") }}</span>');

    {% if multistats %}
    var info = { multistats: true, times:
        {% if time2 != "_none" and time2 != "" and time3 != "_none" and time3 != "" %}3{% else %}2{% endif %}, typeTitle: $("#info-type").text(), typeStats: "{{ typeStats }}", time: $("#info-time").data('time'), time2: $("#info-time").data('time2'), time3: $("#info-time").data('time3'), filter: $("#info-filter").text() };
    {% else %}
    var info = { multistats: false, typeTitle: $("#info-type").text(), typeStats: "{{ typeStats }}", time: $("#info-time").data('time'), filter: $("#info-filter").text() };
    {% endif %}

    $.ajax({
      type: "POST",
      url: "{{ url('statistics/createxls') }}",
      dataType: "json",
      data: {
        info:   info,
      }
    }).done(function(data) {
      stopLoading();

      // download
      var link = document.createElement('a');
      link.href = "../public/io/stats/" + data;
      link.download = data;
      document.body.appendChild(link);
      link.click();
    }).error(function(x, t, m) {
  		printAjaxError(x, t, m);
    });
  }
});
{% endif %}
</script>
