(function($){
	$.fn.empty_tbody = function() {
		$(this).html("");
	}
})(jQuery);

jQuery(document).on("click", ".remove-item", function(e) {
	id = $(this).data("id");
	$("#"+id).remove();
})

jQuery(document).on("click", "#add-btn", function(e){
	e.preventDefault();
	if($("#new-qty").validateInput()) {
		if($("#new-description").validateInput()) {
			if($("#new-unit_price").validateInput()) {
				var id = "row"+Math.round(Math.random() * 10000)+Math.round(Math.random() * 10000)+Math.round(Math.random() * 10000);
				var tr = $("<tr id=\""+id+"\"></tr>");
				var qty = $("#new-qty").val();
				var description = $("#new-description").val();
				var unit_price = $("#new-unit_price").val();
				var qty_price = unit_price * qty;
				$(tr).addElement({
					element: "td",
					content: qty+"<input name=\"items[qty][]\" value=\""+qty+"\" style=\"display: none;\">"
				}).addElement({
					element: "td",
					content: description+"<input name=\"items[description][]\" value=\""+description+"\" style=\"display: none;\">"
				}).addElement({
					element: "td",
					content: unit_price+"<input name=\"items[unit_price][]\" value=\""+unit_price+"\" style=\"display: none;\">"
				}).addElement({
					element: "td",
					content: qty_price
				}).addElement({
					element: "td",
					content: "<a href=\"javaScript:void(0)\" data-id=\""+id+"\" class=\"remove-item\">Remove</a>"
				});
				$("#items-table tbody").append(tr);
				$("#new-qty").val("");
				$("#new-description").val("");
				$("#new-unit_price").val("");
				$("#new-qty_price").html("");
				$("#add-btn").attr("disabled", true);
			}
		}
	}
})

jQuery(document).on("change, keyup", "#new-description, #new-qty, #new-unit_price", function(e) {
	var qty = $("#new-qty").val();
	var unit_price = $("#new-unit_price").val();
	if(qty !== "" && qty !== 0 && unit_price !== "" && unit_price !== 0) {
		var qty_price = qty * unit_price;
		$("#new-qty_price").html(qty_price);
		$("#add-btn").attr("disabled", false);
	} else {
		$("#new-qty_price").html("");
		$("#add-btn").attr("disabled", true);
	}
})