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

	$("#arealist li").live("click",
	function() {
		var newcon = $(this).find(".cname").html();
		var id = $(this).data("id");
		$(".areadd").append("<li><input type='hidden' name='nosale[]' value='" + id + "'><span class='cname'>" + newcon + "</span><span class='close'></span></li>");
		$("#arealist").hide();
		$("#AreaSearch").val("");
	})

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

	$("#unit").on("change",
	function() {
		var un = $(this).val();
		for (i = 0; i < $(".unit").length; i++) {
			$(".unit").eq(i).html(un);
		}
	})

	$(".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("input").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:last .num").live("mouseleave",
	function() {
		var pnum; //Pre数量
		var cnum = $(this).val(); //当前数量
		var i = $(this).parent().index();
		var pre = i - 1;
		var len = $(".priceitem").length;
		if (cnum == "" || cnum == "undefined") {
			$(this).parent().find(".note").html("当前数量不能为空");
			$(this).select();
			return false;
		}

		if (len > 1) {
			pnum = $(".priceitem").eq(pre).find(".num").val();
			if (cnum < pnum) {
				$(this).parent().find(".note").html("数量低于上一项");
				$(this).select();
			}
			else
			{	$(this).parent().find(".note").html("");}			
		}

	})

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

	})

});