$(document).ready(function() {
	$("#productSearch").on("input",
	function() {
		var str = $(this).val();
		$.ajax({
			type: "GET",
			url: "Searchproduct.php",
			dataType: "html",
			contentType: "application/json;charset=utf-8",
			data: {
				"str": str
			},
			timeout: 20000,
			success: function(e) {
				$("#productlist").show();
				$("#productlist ul").html(e);
			}
		});
	});

	$(".productlist li").live("click",
	function() {
		var id = $(this).data("id");
		var unit = $(this).data("unit");
		var n = "<div class='proname'>" + $(this).find(".name").html() + "</div>";
		var pic = "<div class='propic'>" + $(this).find(".pic").html() + "</div>";
		var item = "<div class='proitem'><div class='prodelet'></div>" + n + pic + "<div class='proprice'><div class='priceitem'><input type='hidden' name='productId' value="+id+"><label>≥</label><input type='number' autocomplete='off' class='txt3 num' name='num'><label class='unit'>" + unit + "</label> <label>售价</label><input type='text' class='txt3 price' autocomplete='off' name='price'><label>RMB</label> <span class='additem'></span><span class='delitem'></span><span class='note'></span></div></div></div>";
		$(".prowapper").append(item);
		$("#productlist").hide();
		$("#productSearch").val("");
	})

	$(".prodelet").live("click",
	function() {
		$(this).parent().remove();
	})

	$(".priceitem .additem").live("click",
	function() {
		var priceitem = $(this).parent().clone();
		var i = $(this).parent().index();
		var lastnum = $(".priceitem").eq(i).find(".num").val();
		var lastprice = $(".priceitem").eq(i).find(".price").val();
		if (lastnum == "" || lastprice == "") //未输入无法继续添加
		{
			return false
		} else {
			priceitem.find(".num").val("");
			priceitem.find(".price").val("");			
			$(this).parent().after(priceitem);
		}
	})

	$(".priceitem .delitem").live("click",
	function() {
		var n = $(this).parent().siblings().length;
		if (n > 0) {
			priceitem = $(this).parent().remove();
		} else {
			return false
		}
	})

	$(".priceitem .num").live("blur",
	function() {
		var pnum; //Pre数量
		var cnum = $(this).val(); //当前数量
		var i = $(this).parent().index();

		var pre = i - 1;
		var len = $(".priceitem").length;
		if (len > 1) {
			pnum = $(".priceitem").eq(pre).find(".num").val();
			console.log(pnum);
			if (eval(cnum) < eval(pnum)) {
				$(this).parent().find(".note").html("当前数量不能小于上一项");
				$(this).select();
			}
			else
			{$(this).parent().find(".note").html("");}
		}

	})

	$(".priceitem .price").live("blur",
	function() {
		var pprice; //Pre数量
		var cprice = $(this).val(); //当前数量
		var i = $(this).parent().index();
		var pre = i - 1;
		var len = $(".priceitem").length;
		if (len > 1) {
			pprice = $(".priceitem").eq(pre).find(".price").val();
			if (eval(cprice) > eval(pprice)) {
				$(this).parent().find(".note").html("当前售价不能高于上一项");
				$(this).select();
			}
			else
			{$(this).parent().find(".note").html("");}			
		}

	})

});