$(document).ready(function(e) {
  $('.glyphicon-copy').click(function(ev) {
    var name = $(this).attr('data-name');
    var n = $(this).attr('data-n');
    var total = $("input[name='cuotas']").val();

    if (name == 'fecha') {
      copyDate(n, total);
      return;
    }

    var value = $("input[name='" + name + n + "']").val();
    if (value == '') {
      return;
    }

    if (name == 'numero') {
      copyIncrement(name, value, n, total);
      return;
    }

    copyDown(name, value, n, total);
  });
});

function copyDate(start, end) {
  var d = $("select[name='day" + start + "']").val()
  var m = $("select[name='month" + start + "']").val() - 1
  var y = $("select[name='year" + start + "']").val()

  var f = new Date(y, m, d)

  for (i = parseInt(start) + 1; i < end; i ++) {
    f = new Date(f.setMonth(f.getMonth() + 1));
    if (f.getDate() < d) {
      f.setDate(0)
    }

    $("select[name='day" + i + "']").val(f.getDate())
    $("select[name='month" + i + "']").val(f.getMonth() + 1)
    $("select[name='year" + i + "']").val(f.getFullYear())
  }
}

function copyIncrement(name, value, start, end, type = 'input') {
  var val = parseInt(value) + 1;
  for (i = parseInt(start) + 1; i < end; i ++) {
    $(type + "[name='" + name + i + "']").val(val ++);
  }
}

function copyDown(name, value, start, end, type = 'input') {
  for (i = parseInt(start) + 1; i < end; i ++) {
    $(type + "[name='" + name + i + "']").val(value);
  }
}
