jQuery(document).ready(function($){
  $.fn.extend ({
    numberInputInit: function() {
      $(".quantity-nav").remove();
      $(this).removeClass("number-input-active");
      this.each(function(){
        $(this).numberInputLoad();
      });
    }
  })

  $.fn.numberInputLoad = function() {
    var id = $(this).attr("id");
    if(id === undefined) {
      return;
    }
    $(this).addClass("number-input-active");
    var nav = '<div class="quantity-nav quantity-nav-'+id+'"><div class="quantity-button quantity-up" data-id='+id+'>+</div><div class="quantity-button quantity-down" data-id='+id+'>-</div></div>';
    $(this).after(nav);
  }

  $(document).on("click", ".quantity-nav .quantity-up", function(){
    var id = $(this).data("id"),
        input = $("#"+id),
        min = input.attr('min'),
        max = input.attr('max');
    var oldValue = parseFloat($(input).val());
    oldValue = isNaN(oldValue) ? 0 : oldValue;
    if (oldValue >= max) {
      var newVal = oldValue;
    } else {
      var newVal = oldValue + 1;
    }
    $(input).val(newVal).trigger("change");
  })
  $(document).on("click", ".quantity-nav .quantity-down", function(){
    var id = $(this).data("id"),
        input = $("#"+id),
        min = input.attr('min'),
        max = input.attr('max');
    var oldValue = parseFloat($(input).val());
    oldValue = isNaN(oldValue) ? 0 : oldValue;
    if (oldValue <= min) {
      var newVal = oldValue;
    } else {
      var newVal = oldValue - 1;
    }
    $(input).val(newVal).trigger("change");
  })
  $(document).on("keydown", "input[type='number'], input[type='phone'], input.numbers-only", function (e) {
      // Allow: backspace, delete, tab, escape, enter and .
      if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
           // Allow: Ctrl/cmd+A
          (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
           // Allow: Ctrl/cmd+C
          (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) ||
           // Allow: Ctrl/cmd+X
          (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === 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();
      }
  });
  $(".numberInput").numberInputInit();
})