$(function(){
	//漂浮导航菜单
	$("#menuPanel").find("ul li").each(function(index){
		$(this).click(function(){
			$(this).siblings().removeClass("cur");
			$(this).addClass("cur");
			$(".panelDiv").hide();
			$(".panelDiv").eq(index).show();
		});
	});

	//商品分类 改变时 获取对应的商品属性
	$("select[name='catId']").change(function(){
		var ele = $(this);
		var catId = $(this).val();
		if(catId && !isNaN(parseInt(catId,10))){
			$("#form-line-attrs").remove();
			var sdata = { inajax:1,catId:catId };
			$.ajax({ type:"POST",url:"/data/goodsfilter",data:sdata,dataType:'json',success:function(json){
					if(json.success){
						var line = $('<div class="form-line" id="form-line-attrs"><label class="label">自定义属性：</label><div class="element"></div></div>');
						$.each(json.data,function(i,data){
							var  attr = data.type;
							if(attr.type=='select'){
								var html = $('<select name="attr['+attr.id+']"><option value="">'+attr.name+'</option></select>');
								$.each(data.item,function(itemIndex,ext){
									html.append('<option value="'+ext.id+'">'+ext.value+'</option>');
								});
							}else{
								var html = $('<div class="attr"><div class="col">'+attr.name+':</div><div class="val"><ul class="clearfix"></ul></div></div>');
								$.each(data.item,function(itemIndex,ext){
									html.find(".val").find("ul").append('<li><input type="checkbox" name="attr['+attr.id+'][]" id="attr['+attr.id+']['+itemIndex+']" value="'+ext.id+'"><label for="attr['+attr.id+']['+itemIndex+']">'+ext.value+'</label></li>');
								});						
							}
							line.find(".element").append(html);
						});
						ele.parent(".element").parent(".form-line").after(line);
					}
				}
			});
		}
	});
	//添加推广商品时判断商品的唯一性
	$('input[name="iid"]').change(function(){
		var iid = $(this).val();
		if(iid!=""){
			$("#iid_repeat").remove();
			$.ajax({ type:"POST",url:"/qkadmin/goods",data:"inajax=1&act=check&iid="+iid,cache:false,dataType:'json',success:function(json){
					if(json.success && json.data.id){ $("input[name='iid']").after('<span id="iid_repeat" class="red">已经存在该商品</span>'); }else{}
				}
			})
		}
	});
	//添加新分类
	$("#addcat").button().click(function(){
		var parentCat = $("select[name='catId']");
		var catDialog = $('<div id="catForm" class="form">分类名称：<input type="text" class="text" name="catName" id="catName" value="" /><br/><br/>上级分类：<select name="parentId" id="parentId">'+parentCat.html()+'</select></div>').dialog({ width:400,height:200,title:'添加商品分类',resizable:false,dialogClass:'layer_global_main',buttons:{
			"确定":function(){
				var name = $("#catName").val();
				var parentId = $("#parentId").val();
				var sdata = { inajax:1,act:'add',name:name,parentId:parentId };
				$.ajax({ type:"POST",url:"/qkadmin/category","data":sdata,dataType:'json',success:function(json){ if(json.success){
					var id = json.data.id; $("select[name='catId']").prepend('<option value="'+json.data.id+'">'+name+'</option>'); catDialog.remove().dialog("destroy"); 
					$("select[name='catId'] option").removeAttr("selected");$("select[name='catId']").find("option").eq(0).attr("selected","selected");
					qlib.tips({ msg:json.message,icon:'success' });
				}else{ qlib.tips({ msg:json.message,icon:'error' }); } } });
			}
		} });		
	});
	//添加新品牌
	$("#addbrand").button().click(function(){
		var brandDialog = $('<div id="brandForm" class="form">品牌名称：<input type="text" class="text" name="brandName" id="brandName" value="" /></div>').dialog({ width:250,height:140,title:'添加商品品牌',resizable:false,dialogClass:'layer_global_main',buttons:{
			"确定":function(){
				var name = $("#brandName").val();
				var sdata = { inajax:1,act:'add',name:name };
				$.ajax({ type:"POST",url:"/qkadmin/brand","data":sdata,dataType:'json',success:function(json){ if(json.success){
					var id = json.data.id; $("select[name='brandId']").prepend('<option value="'+json.data.id+'">'+name+'</option>'); brandDialog.dialog("destroy");brandDialog.remove(); 
					$("select[name='brandId'] option").removeAttr("selected");$("select[name='brandId']").find("option").eq(0).attr("selected","selected");
				}else{ qlib.tips({ msg:json.message,icon:'error' }); } }});
			}
		} })
	});
	//表单验证
	$("#goodsForm").validate({
		rules:{
			"name":{ required:true }
		},
		messages:{
			"name":{ required:'请填写商品名称' }
		},
		submitHandler:function(form){
			qlib.tips({ timer:false });
			ue.sync();
			$("#goodsForm").ajaxSubmit({ dataType:'json',success:function(rt,st,xhr,form){
					if(rt.success){
						var act = $("input[name='act']").val();
						if(act=='add'){
							$("#goodsForm input[type='text'],#goodsForm textarea").val(''); 
							$("input[type='checkbox'][name='promotion']").removeAttr("checked");
							var goodsImgNum = $(".goods-img").length;
							$(".goods-img").each(function(index){ if(index<goodsImgNum-1){ $(this).remove(); } });
							$("#insertId").val('');
							if(ue)ue.setContent("");
							$(".img-main").find("img").attr('src','/static/images/default.png');
							$("input[name='thumbIds']").val('');
						}
						qlib.tips({ msg:rt.message,icon:'success' });
					}else{ qlib.tips(rt.message); }
				},error:function(){ qlib.tips('ajax处理错误'); }
			});
		}
	});
	
	//获取淘宝客商品的折扣信息
	$("#getCouponInfo").click(function(){
		qlib.tips();
				$.ajax({
					type:"POST",
					url:"/qkadmin/taoke/data",
					data:"inajax=1&act=getCoupon&iid="+$("input[name='iid']").val(),
					cache:false,
					dataType:"json",
					success:function(json){
						if(json.success){
							qlib.tips({ msg:'获取成功',icon:'success' });
							$("input[name='promotion']").attr("checked","checked");
							$("input[name='promoteName']").val(json.data.name);
							$("input[name='promotePrice']").val(json.data.item_promo_price);
							$("input[name='promoteStarttime']").val(json.data.start_time);
							$("input[name='promoteEndtime']").val(json.data.end_time);
						}else{
							qlib.tips({ msg:'获取失败：'+json.message,icon:'error' });
						}
					},
					error:function(data){
						qlib.tips(json);
					}
				});		
	});
	//获取淘宝/拍拍客商品信息
	$("#getTaoInfo").click(function(){
		var iid = $("input[name='iid']").val();
		if(iid){
		qlib.tips({ timer:false });
				$.ajax({
					type:"POST",
					url:"/goods/add",
					data:"inajax=1&act=getinfo&iid="+iid,
					cache:false,
					dataType:"json",
					success:function(json){
						if(json.success){
							qlib.tips({ msg:'获取成功',icon:'success',timer:1000,modal:false });
							var item=json.data.item;
							$("input[name='link']").val(item.url);
							//$("input[name='inventory']").val(item.item.num);
							//$("input[]").attr("href",item.item.detail_url);
							$("input[name='name']").val(item.title);
							//$("p.seller a").attr("href",item.shop_click_url);
							//$("input[name='nick']").val(item.item.nick);
							//$("nick").val(item.item.nick);
							//$("input[name='linkPrice']").val(item.item.price);
							$("input[name='marketPrice']").val(item.marketPrice);
							$("input[name='price']").val(item.price);
							$("#good_price").val(item.price);
							$("#iid").val(item.id);
							$("input[name='picUrl']").val(item.img);
							$("span.price").html("<em>￥</em>"+item.price);
							//$("input[name='clickUrl']").val(item.click_url);
							//$("input[name='shopClickUrl']").val(item.shop_click_url);
							if(item.promotionInfo){
								var pro = item.promotionInfo;
								$("input[name='promotion']").attr("checked","checked");
								$("input[name='promoteName']").val(pro.name);
								$("input[name='promotePrice']").val(pro.item_promo_price);
								$("input[name='promoteStarttime']").val(pro.start_time);
								$("input[name='promoteEndtime']").val(pro.end_time);
								$(".promotion").removeClass("none");
							}else{
								$("input[name='promotion']").removeAttr("checked");
							}
							$("#editor").val(item.desc);
							$("#detail").removeClass("none");
							if(ue)ue.setContent(item.desc);
							ue.sync();
						}else{
							qlib.tips({ msg:json.message,icon:'error',timer:5000 });
						}
					}
				});
		}
	});
	//从外部链接下载图片
	$("a#uploadUrl").click(function(){
		var upurl = $('<div id="upurl" class="form"><input type="text" class="text w600" id="remotepicurl" name="remotepicurl" value="" /><br/>请输入完整的图片URL地址，以 http:// 开始 <br/><input type="checkbox" name="tolocal" value="1" id="tolocal" class="none" /><label for="tolocal" class="none"> 获取后下载到本地</label></div>').dialog({
			title:'添加网络图片',width:670,height:160,modal:true,resizable:false,dialogClass:'layer_global_main',
			buttons:{
				'提交':function(e){
					var url = $("#remotepicurl").val();
					if(url && /^http:\/\/(.*)/.test(url)){
						$(e.srcElement).attr("disabled",true);
						$.ajax({
							type:"POST",url:"/qkadmin/goods",data:"inajax=1&act=upurl&url="+url+"",dataType:'json',success:function(json){
							$(e.srcElement).attr("disabled",false);
							if(json.success){
								var val = $("#insertId").val(); if(val){ val = val + ","; }else{ val = ""; }
								$("#img-src").attr("src","/"+json.url);
								$("#insertId").val(val+json.data);
								$("#newupload").trigger("click");
								upurl.dialog('destroy');upurl.remove();
							}else{
								alert(json.message);
							}
							},error:function(){ $(e.srcElement).attr("disabled",false); }
						});
					}
				}
			}
		})
	});
	
	//商品表单删除图片
	$(".delImg").unbind().click(function(){
		var obj = $(this);
		var id = $(this).attr("sid");
		var sdata = "inajax=1&act=edit&col=iStatus&val=0&id="+id;
		$.ajax({
			type:"POST",
			url:"/qkadmin/attachment",
			data:sdata,
			dataType:"json",
			success:function(data){
				if(data.success){
					obj.parent(".goods-img").remove();
					Msg("Success");
				}
			}
		})
	});
	//商品列表删除商品
	$(".delBtn").click(function(){
		if(!confirm(lang[4])){ return false; }
			var tr = $(this).parent("td").parent("tr");
			var id = $(this).attr("sid");
			if(parseInt(id,10)){
				var sdata = "inajax=1&act=del&id="+id;
				$.ajax({
					type:"POST",
					url:"/qkadmin/goods",
					data:sdata,
					dataType:"json",
					success:function(data){
						if(data.success){
							tr.fadeOut("slow").remove();
						}else{
							qlib.tips(data.message);
						}
					}
				});
			}
		return false;
	});
	//清空所有商品
	$("#clearGoodsBtn").click(function(){
		if(!confirm("清空后商品全部删除，请谨慎操作，是否确定清空商品？")){ return false; }
		$.ajax({
			type:"POST",
			url:"/qkadmin/goods",
			data:"inajax=1&act=clear",
			dataType:"json",
			success:function(data){
				if(data.success){
					alert("清空成功");
					location.reload();
				}
			}
		});
	});

	$("input[name='buyWay'][value='1']:radio").click(function(){
		$("input[name='scorePrice']").val(0);
	});






	/*
	$("select[name='catId']").change(function(){
		var catId = $(this).val();
		attrHtml(catId);
	});
	function attrHtml(catId){
		if(!isNaN(parseInt(catId,10))){
		var surl = "{$baseUrl}data/attr/";
		{if $smarty.get.id!=""} 
			surl += "goodsId/"+{$smarty.get.id}+"/";
		{/if}
			$.ajax({
				type:"POST",
				url:surl,
				data:"format=html&catId="+catId,
				success:function(data){
					$("#attrs").html(data);
				}
			})
		};
	};

	var catId = $("select[name='catId'] option:selected").val();
	attrHtml(catId);
*/

	$("#getClickUrl").click(function(){
		var iid = $("input#iid").val();
		if(!iid){qlib.tips('请先填写商品ID');return false;}
		$.ajax({type:'POST',url:"/data/taoke",data:{inajax:1,act:'getClickUrl',iid:iid},dataType:'json',success:function(json){if(json.success){qlib.tips('获取成功');$("input[name='clickUrl']").val(json.data.clickUrl);}else{qlib.tips({icon:'error',msg:json.message});}}});
	});

});