<script>
//region Insert quantity scripts
$('.buy-list-box').click(function(e){
  e.preventDefault();

  var modal = $("#modal-list-insert-quantity");
  $("#modal-list-insert-quantity .modal-title").html("{{ mt._('_common.quantity') }}");

  var row = $(this).closest('.article-list-row');
  var tglini = row.data('tglini');
  var tglfin = row.data('tglfin');

  $.ajax({
    type: 'POST',
    url: "{{ url('model/ajax/getCurrentArticle') }}",
    dataType: "json",
    data: {
      cdarti: row.data('cdarti'),
      cdcolo: row.data('cdcolo'),
      cdtagl: row.data('cdtagl'),
      tppers: row.data('tppers'),
      modal:  true,
    }
  }).done(function(data) {
    $("#modal-list-insert-quantity .modal-body").html(data);
    {% if tipolo|length > 0 and tipolo[0].tppers != 'PT' %}
    $('[data-toggle="tooltip"]').tooltip();
    {% endif %}

    {% if tipolo|length > 0 and tipolo[0].tppers != 'PT' and
      ((common['order_info'].tpordc == 0 and (common['dateTypeAvaOrder'] == 2 or common['dateTypeAvaOrder'] == 3)) or
       (common['order_info'].tpordc == 1 and (common['dateTypeResOrder'] == 2 or common['dateTypeResOrder'] == 3))) %}
    $.datepicker.setDefaults($.datepicker.regional.{{ session.get('language') }});
    $('.dtmcli').datepicker({ dateFormat: 'dd/mm/yy', minDate: 0,
      onSelect: function(dateText, inst) {
      var index = $(this).data("index");
      var pieces = dateText.split("/");
        $("#row-" + index).data("dtmcli", pieces.length > 0 ? pieces[2] + "-" + pieces[1] + "-" + pieces[0] : "0000-00-00");
      }
    });
    {% endif %}

		// Hide size with position less than tglini or greater than tglfin
		$('.insert-quantity-block').each(function(){
			var index = 1;
			$(this).find('.is-size').each(function(){
				if ((index < tglini && tglini != 0) ||
						(index > tglfin && tglfin != 0)) {
					$(this).addClass('size-disabled');
					$(this).find('.col-4').html('&nbsp;');
				} else {
					$(this).removeClass('size-disabled');
				}
				index++;
			})
		});

    modal.modal("show");

    if ($("#row-3").closest(".insert-quantity-block").css("display") != "none") {
      $("#btn-add-1").css("display", "none");
      $("#btn-add-2").css("display", "none");
      $("#btn-show-2").css("display", "none");
    } else if ($("#row-2").closest(".insert-quantity-block").css("display") != "none") {
      $("#btn-add-1").css("display", "none");
    }

    $('[data-toggle="tooltip"]').tooltip();
  }).error(function(x, t, m) {
		printAjaxError(x, t, m);
  });
});

{% set btn_target = '#modal-list-insert-quantity .modal-body' %}
{% include 'scripts/common/qty_btn.volt' %}

$("#modal-list-insert-quantity .modal-body").on('click', '.add-to-cart', function(e) {
	e.preventDefault();
	var header = $(this).closest('.insert-quantity-block').find('.header-insert-block');
	var nuordc = "{{ common['order_info'].nuordc }}";
	var nurorc = header.data('nurorc');
  var cdarti = $("#modal-list-insert-quantity .modal-body .header-modal-list").data("cdarti");
  var cdcolo = $("#modal-list-insert-quantity .modal-body .header-modal-list").data("cdcolo");
	var cdvari = header.data('cdvari');
	var cdcata = "{{ common['order_info'].cdcata }}";
	var quanti = 0;
	var seqdet = header.prop('id').replace("row-", "");
  {% if common['order_info'].tpordc == 0 or (tipolo|length > 0 and tipolo[0].tppers == "PT") %}
  var dtmcli = header.data('dtmcli');
  {% else %}
  var dtmcli = header.find('.dtmcli').val();
  {% endif %}
	var sgrifc = header.data('sgrifc');
	var indorc = header.data('indorc');
	var dsnoco = header.find('.dsnoco-info').val();

	var success = $(this).closest('.insert-quantity-block').find('.success-box');
	var error = $(this).closest('.insert-quantity-block').find('.unsuccess-box');
	error.find('span').html("{{ mt._('quantity.insert.unsuccess') }}");
	success.hide();
	error.hide();

	var octagl = [];
	$(this).closest('.insert-quantity-block').find('.insert-quantity-row.is-size').each(function(){
		var curr_quanti = $(this).find(".input-number").val() > 0 ? parseInt($(this).find(".input-number").val()) : 0
		quanti += curr_quanti;
		octagl.push([
			$(this).data('taglia'),
			$(this).data('prezzo'),
			curr_quanti,
			$(this).data('sconto')
		]);
	});

	var ocasso = [];
	$(this).closest('.insert-quantity-block').find('.insert-quantity-row.is-asso').each(function(){
		var curr_quanti = $(this).find(".input-number").val() > 0 ? parseInt($(this).find(".input-number").val()) : 0
		quanti += (curr_quanti * $(this).data("qtasso"));
		ocasso.push([
			$(this).data('cdasso'),
			curr_quanti
		]);
	});

	$.ajax({
		type: "POST",
		url: "{{ url('model/ajax/saveOrderRow') }}",
		dataType: "json",
		data: {
			nuordc: nuordc,
			nurorc: nurorc,
			cdarti: cdarti,
			cdcolo: cdcolo,
			cdvari: cdvari,
			cdcata: cdcata,
			quanti: quanti,
			seqdet: seqdet,
			dtmcli: dtmcli,
			sgrifc: sgrifc,
			indorc: indorc,
			dsnoco: dsnoco,
			octagl: octagl,
			ocasso: ocasso
		}
	}).done(function(data) {
		if (data['response'] == 'RM') {
			error.find('span').html("{{ mt._('quantity.warning.regqtm.bis') }}");
			error.find('span.min').html(data['min']);
			error.find('span.mul').html(data['mul']);
		  error.fadeIn();
		  setTimeout( function(){
		  	error.fadeOut();
		  }, 10000 );
		} else {
		  if (data['response'] != 'OC' && data['response'] != 'DT' && data['response'] != 'NT' && data['response'] != 'OA') {
		  	header.data('nurorc', data['nurorc']);
        updateShoppingBag(data['tot']['totCart'], data['tot']['totRows']);
		  }
      {% if common['closeQtyModal'] %}
      $('#modal-list-insert-quantity').modal('hide');
      {% else %}
		  success.fadeIn();
		  setTimeout( function(){
		  	success.fadeOut();
		  }, 10000 );
      {% endif %}
    }
	}).error(function(x, t, m) {
    printAjaxError(x, t, m);
		error.fadeIn();
		setTimeout( function(){
			error.fadeOut();
		}, 10000 );
	});
});

{% if tipolo|length > 0 and tipolo[0].tppers != "PT" and
  ((common['order_info'].tpordc == 0 and (common['dateTypeAvaOrder'] == 2 or common['dateTypeAvaOrder'] == 3)) or
   (common['order_info'].tpordc == 1 and (common['dateTypeResOrder'] == 2 or common['dateTypeResOrder'] == 3))) %}
$("#modal-list-insert-quantity .modal-body").on('change', ".dtmcli", function() {
	var index = $(this).data("index");
	var value = $(this).val();
	$("#row-" + index).data("dtmcli", value);
});
{% endif %}
$("#modal-list-insert-quantity .modal-body").on('click', ".btn-add-delete", function(){
	var id = $(this).prop('id');
	$(this).hide();
	switch (id) {
	case 'btn-add-1':
	$("#row-2").closest(".insert-quantity-block").show();
		$("html, body").animate({ scrollTop: $('#row-2').offset().top - 180}, 1000, function(){
			$("#btn-add-2").show();
			$("#btn-delete-2").show();
		});
		break;
	case 'btn-add-2':
		$("#row-3").closest(".insert-quantity-block").show();
		$("html, body").animate({ scrollTop: $('#row-3').offset().top - 180}, 1000, function(){
			$("#btn-delete-2").hide();
			$("#btn-add-3").show();
		});
		break;
	case 'btn-delete-2':
		$("#btn-add-1").show();
		var block = $(this).closest(".insert-quantity-block");
		$("html, body").animate({ scrollTop: $('#row-1').offset().top - 180}, 1000, function(){
			block.hide();
		});
	  break;
	case 'btn-delete-3':
		$("#btn-add-2").show();
		$("#btn-delete-2").show();
		var block = $(this).closest(".insert-quantity-block");
		$("html, body").animate({ scrollTop: $('#row-2').offset().top - 180}, 1000, function(){
			block.hide();
		});
		break;
	}
});

{% if common['isOrder'] and common['order_info'].tpordc == 0 and session.get('auth')['type'] == 4 and common['order_info'].indema != '' %}
$("#modal-list-insert-quantity .modal-body").on('click', "#open-modal-notify-product", function() {
  $('.insert-quantity-block,#notify_products,.header-modal-list').slideUp(400,function(){
    {% if tipolo|length > 0 and tipolo[0].tppers == 'PT' %}
    checkArtcol();
    checkArtvar();
    {% endif %}
    loadNotifyQuantityBox();
    $('#currentdesiderata').slideDown();
    $("#modal-list-insert-quantity .modal-title").html("{{ mt._('model.notifyavailability') }}");
  });
});
$("#modal-list-insert-quantity .modal-body").on('click', "#back-notify-me", function() {
  $('#currentdesiderata').slideUp(400,function(){
    $('.insert-quantity-block,#notify_products,.header-modal-list').slideDown();
    $("#modal-list-insert-quantity .modal-title").html("{{ mt._('_common.quantity') }}");
  });
});
{% endif %}
//endregion

{% if common['isOrder'] and common['order_info'].tpordc == 0 %}
//region Notify availability modal
$('.modal-body').on('change', '#notify_anaart', function(){
	{% if tipolo|length > 0 and tipolo[0].tppers == 'PT' %}
	checkArtcol();
	checkArtvar();
	{% endif %}
	loadNotifyQuantityBox();
});
	{% if tipolo|length > 0 and tipolo[0].tppers == 'PT' %}
function checkArtcol() {
	var currAnaart = $("#notify_anaart").val();
	$("#notify_artcol option").hide();
	$("#notify_artcol option[data-cdarti='" + currAnaart + "']").show();
	var stop = 0;
	$("#notify_artcol option").each(function(){
		if ($(this).css('display') == 'block' && stop != 1) {
			$("#notify_artcol").val($(this).val());
			stop = 1;
		}
	});
	if (stop == 0) {
		$("#notify_artcol").val("");
	}
}
function checkArtvar() {
	var currAnaart = $("#notify_anaart").val();
	$("#notify_artvar option[data-all='false']").hide();
	$("#notify_artvar option[data-cdarti='" + currAnaart + "']").show();
	var stop = 0;
	$("#notify_artvar option").each(function(){
		if ($(this).css('display') == 'block' && stop != 1) {
			$("#notify_artvar").val($(this).val());
			stop = 1;
		}
	});
	if (stop == 0) {
		$("#notify_artvar").val("");
	}
}
	{% endif %}
function loadNotifyQuantityBox() {
	{% if tipolo|length > 0 and tipolo[0].tppers == 'PT' %}
	$('#notify-me').show();
	if ($("#notify_artcol").val()) {
		var preagg = $('#notify_artvar').length == 1 ? $('#notify_artvar option:selected').data('preagg') : 0;
	{% else %}
	var preagg = 0;
	{% endif %}
	$.ajax({
		type: "POST",
		url: "{{ url('model/ajax/getCurrentDesiderataSizes') }}",
		dataType: "json",
		data: {
			cdarti: $("#notify_anaart").val(),
			cdtagl: "{{ tipolo|length > 0 ? tipolo[0].cdtagl : '' }}",
			preagg: preagg
		}
	}).done(function(data) {
		$('#modal-notify-body').html(data);
	}).error(function(x, t, m) {
		printAjaxError(x, t, m);
	});
	{% if tipolo|length > 0 and tipolo[0].tppers == 'PT' %}
	} else {
		$('#modal-notify-body').html('');
		$('#notify-me').hide();
	}
	{% endif %}
}

$("#modal-list-insert-quantity .modal-body").on('click', '#notify-me', function(){
	$('#notify-success').hide();
	$('#notify-error').hide();
	var sizes = [];
	$('.modal-body .insert-quantity-row').each(function(){
		if ($(this).find('.input-notify-number').val() != '' && $(this).find('.input-notify-number').val() > 0) {
			sizes.push({
				'taglia': $(this).find('.taglia').html(),
				'prezzo': $(this).find('.price').data('price'),
				'quanti': $(this).find('.input-notify-number').val(),
			})
		}
	});

	$.ajax({
		type: "POST",
		url: "{{ url('model/ajax/savedesiderataqty') }}",
		dataType: "json",
		data: {
			cdarti: $("#notify_anaart").val(),
			cdcolo: $("#notify_artcol").length == 1 ? $("#notify_artcol").val() : '',
			cdvari: $("#notify_artvar").length == 1 ? $("#notify_artvar").val() : '',
			sizes:	sizes
		}
	}).done(function(data) {
		$('#notify-success').show();
	}).error(function(x, t, m) {
    printAjaxError(x, t, m);
		$('#notify-error').show();
	});
});

$("#modal-list-insert-quantity .modal-body").on('click', '#modal-notify-body .btn-notify-number', function(e){
	e.preventDefault();

  var type   	= $(this).attr('data-type');
	var parent 	= $(this).closest(".insert-quantity-row");
	var input		= parent.find("input");

  var currentVal = input.val() != '' ? parseInt(input.val()) : 0;
	if (!isNaN(currentVal)) {
		if (type == 'minus' && currentVal != '') {
			input.val(currentVal - 1 == 0 ? "" : currentVal - 1).change();
		} else if (type == 'plus') {
			input.val(parseInt(currentVal) + 1).change();
		}
	}
});
$("#modal-list-insert-quantity .modal-body").on('focusin', '#modal-notify-body .input-notify-number', function(){
	$(this).data('old_value', $(this).val());
});
$("#modal-list-insert-quantity .modal-body").on('change', '#modal-notify-body .input-notify-number', function() {
	if ($(this).val() == 0) {
		$(this).val("");
	}

  var valueCurrent = $(this).val() != '' ? parseInt($(this).val()) : 0;
	var parent 	= $(this).closest(".insert-quantity-row");
	var min_btn	= parent.find(".minus-qty");
	var plu_btn	= parent.find(".plus-qty");
	var input		= parent.find("input");

	if (parseInt(input.val()) == 0 || input.val() == '') {
		min_btn.addClass('disabled');
		min_btn.removeClass('enabled');
	} else {
		min_btn.addClass('enabled');
		min_btn.removeClass('disabled');
	}
});
$("#modal-list-insert-quantity .modal-body").on('keydown', '#modal-notify-body .input-notify-number', function (e) {
	// Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
  	// Allow: Ctrl+A
    (e.keyCode == 65 && e.ctrlKey === true) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39)) {
    // let it happen, don't do anything
    	return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
  	e.preventDefault();
  }
});
//endregion
{% endif %}

{% if common['isOrder'] %}
$(document).ready(function(){
  resizeBuyButton();
});
$(window).resize(function() {
  resizeBuyButton();
});
function resizeBuyButton() {
  if ($(window).width() < 767) {
    var height = $('.small-img img').height();
    var l_height = height / 2;
    $('.buy-list-box').css('line-height', l_height + "px");
  } else {
    $('.buy-list-box').css('line-height', 'auto');
  }
}
{% endif %}

</script>
