
$(function () {
  Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
  };

  $("#bform .btn-primary").prop("disabled", true);
  var totalWeight = 0;
  var orders = [];
  var isLocked = false;
  $(".add-brochure").click(function (e) {
    $(".orderlink").addClass("active");
    e.preventDefault();
    $('.order-message').html('');
    var orderId = $(this).data('bid');
    var articleWeight = $(this).data('weight');
    if (orders.indexOf(orderId) != -1) {
      totalWeight = totalWeight - articleWeight;
      orders.remove(orders.indexOf(orderId));
      $(this).toggleClass("active");
      $(this).closest(".item").toggleClass("active");
      //$(".brochure-orders-link").removeClass("active");
      $(".brochure-orders-empty").removeClass("active");
      $("#bform .btn-primary").prop("disabled", true);
    } else {
      //$(".brochure-orders-link").addClass("active");
      $(".brochure-orders-empty").removeClass("active");
      $(".brochure-orders-link").addClass("active");
      if (totalWeight + articleWeight <= 950) {
        totalWeight = totalWeight + articleWeight;
        orders.push(orderId);
        $(this).toggleClass("active");
        $(this).closest(".item").toggleClass("active");
        $("#bform .btn-primary").prop("disabled", false);
      } else {
        //$('#order-message').html('Das Gesamtgewicht, darf 950g nicht überschreiten.');
        $('.order-message').html('Sie haben das Maximalgewicht erreicht!');

      }
    }

    $('#brochures-orderedbrochures').val(orders.join(','));

    $('#itemcount').html(orders.length);
    $('#weightcount').html(totalWeight);
    if (totalWeight > 950 && !isLocked) {
      $('.add-brochure:not(active)').attr('disabled');
      isLocked = true;

    }
    if (totalWeight <= 950 && isLocked) {
      $('.add-brochure:not(active)').removeAttr('disabled');
      isLocked = false;
    }
  });
  $(".add-brochure").click(function () {
    // If checked
    var value = $(this).data('title'),
      link = $(this).data('link'),
      $list = $("#brochure-item-list");
    if ($(this).hasClass("active")) {
      //add to the right
      $list.append("<li data-value='" + value + "'><a href='#" + link + "'>" + value + "</a></li>");
    } else {
      //hide to the right
      $list.find('li[data-value="' + value + '"]').slideUp("fast", function () {
        $(this).remove();
      });
    }
  });

});

$(document).ready(function () {
  $('.brochure-form input').on('keyup', function () {
    if ($(this).val().length > 0) {
      var character = $(this).val().charAt(0);
      if (character != character.toUpperCase()) {
        $(this).val($(this).val().charAt(0).toUpperCase() + $(this).val().substr(1));
      }
    }
  });
});



