// JavaScript Document 
var editor; 
$(function(){ 
	$("form").submit(function(){ 
		var goods_cats = $("#goods_cats option:selected").val();
		if(goods_cats == 0){
			$.alert('请选择分类');	return false;
		}
		
		var title = $("#title").val();
		if(title == ''){
			$.alert('请填写商品标题'); return false;
		}
		
		var price = $("#price").val();
		if(price == ''){
			$.alert('价格不能为空'); return false;
		}
		 
		var mark_price = $("#market_price").val();
		if(mark_price == ''){
			$.alert('市场价格不能为空');return false;
		}
		if(mark_price != ''){
			if(parseFloat(mark_price) <= parseFloat(price)){
				$.alert('市场价格不能低于或者等于原价格');return false;
			} 
		} 
		var stock = $("#stock").val();
		if(stock == ''){
			$.alert('库存不能为空'); return false;
		}
		
		var goods_img = $('#goods_img').val(); 
		if(goods_img == '' || typeof(goods_img) == 'undefined'){
			$.alert('请最少上传一张主图'); return false; 
		}
		
		var status = $('input[name="status"]:checked').val(); 
		if(typeof(status) =='undefined'){ 
			$.alert('请选择商品状态'); return false; 
		}
		$('.add_goods_submit').attr("disabled", true).val('正在提交..'); 
	 	$.ajax({
			type:'POST',
			url:SELLER+'goods/save?v='+new Date().getTime(),
			data:$("#form").serialize(),
			success:function(result){ 
				var data = jQuery.parseJSON(result); 
				if(data.error == 0){
					$.alert('保存成功', function(){
						$('.add_goods_submit').attr("disabled", false).val('保存');
						history.back(-1);						 
					}); 
				}else{ 
					$('.add_goods_submit').attr("disabled", false).val('保存');
					$.alert(data.msg); 
				}
			},error:function(){
				$.loadingClose();
				$('.add_goods_submit').attr("disabled", false).val('保存');
				$.alert('错误');
			}
		}); 
		return false;
 	}); 
	
	// 打折促销
	$(document).on('click', ".act_status", function(){ 
		sku_list();
		var act_status = $("input[name='act_status']:checked").val(); 
		if(act_status){
			$(".act_con").show();
			$(".act_price").show();
		}else{
			$(".act_con").hide();
			$(".act_price").hide();
		}
	});
	$(document).on('blur', ".sku_remark", function(){ 
		html = $(this).val();
		data_id = $(this).attr('data-id');
		$(".sku_img_"+data_id).html(html);
		
	});
	
	// SKU值新增 
	$(document).on('click', '.sku_add_a', function(){
		html = '<div class="sku_add_lbox">'+
			   '	<input type="text" class="sku_add_val" value=""/>'+
			   '	<input type="button" class="sku_add_btn" value="确定">'+
			   '	<a href="javascript:;" class="sku_add_cancel">取消</a>'+
			   '</div>'; 
		$(this).parent('.sku_add_label').html(html); 				
	});
	
	$(document).on('click', '.sku_add_cancel', function(){
		html = '<a href="javascript:;" class="sku_add_a">+添加</a>';
		$(this).parents('.sku_add_label').html(html);
	});
	
	// 添加规格值
	$(document).on('click', '.sku_add_btn', function(){
		$this = $(this); 
		name = $this.prev().val();		// 增加数据
		if(name != ''){
			pid = $this.parents('.sku_add_label').attr('data-pid');
			$.post(SELLER+'goods/sku_save', {pid:pid, name:name}, function(result){
				data = jQuery.parseJSON(result);
				if(data.error == '0'){
					label_html = '<label><input class="sku_checkbox" type="checkbox" name="sku_val" value="'+data.id+'"><em>'+name+'</em><a href="javascript:;" data-id="'+data.id+'" class="del2">删除</a></label>';
					$this.parents('.sku_add_label').before(label_html); 
					$this.parents('.sku_add_label').html('<a href="javascript:;" class="sku_add_a">+添加</a>'); 
				}else{
					$.alert(data.msg);
				} 
			}); 
		}else{
			$.alert('请填写规格值');	
		}
	});
	
	// 规格
	$(document).on('click', '.sku_insert_a', function(){
		html = '<div class="sku_insert_lbox">'+
			   '	<input type="text" class="sku_insert_val" value=""/>'+
			   '	<input type="button" class="sku_insert_btn" value="确定">'+
			   '	<a href="javascript:;" class="sku_insert_cancel">取消</a>'+
			   '</div>';
		$(this).parent('.sku_insert').html(html); 
	});
	$(document).on('click', '.sku_insert_cancel', function(){
		html = '<a href="javascript:;" class="sku_insert_a">新增规格</a>';
		$(this).parents('.sku_insert').html(html);
	});
	// 添加规格
	$(document).on('click', '.sku_insert_btn', function(){
		$this = $(this);
		name = $this.prev().val();	// 增加数据
		cid = $("#cid").val();
		if(cid == '' || cid == undefined){
			$.alert('提交错误，分类不能为空');
		}
		if(name != ''){
			$.post(SELLER+'goods/sku_save', {pid:'0', cid:cid, name:name}, function(result){
				data = jQuery.parseJSON(result);
				if(data.error == '0'){
					html = 	'<div class="sku_con">'+
						'<div class="sku_name"><span>'+name+'</span><a href="javascript:;" data-id="'+data.id+'" class="del2">删除</a></div>'+
						'<div class="sku_detail">'+
							'<div class="sku_add_label" data-pid="'+data.id+'"><a href="javascript:;" class="sku_add_a">+添加</a></div>'+
						'</div>'+
					'</div>'; 
					if($('#sku_checkbox .sku_con').length == 0){
						$("#sku_checkbox").html(html);
					}else{
						$("#sku_checkbox .sku_con:last").after(html);	
					} 
					$this.parents('.sku_insert').html('<a href="javascript:;" class="sku_insert_a">新增规格</a>'); 
				}else{
					$.alert(data.msg);
				} 
			}); 
		}else{
			$.alert('请填写规格');	
		}
	});
	// 删除规格
	$(document).on('click', '.sku_name a', function(){
		$this = $(this);
		if(!confirm("确认要删除？")) { 
			if(window.event){
				window.event.returnValue = false;
			}else{  
				event.preventDefault();	//for firefox
			}
		}else{
			id = $this.attr('data-id');
			$.post(SELLER+'goods/sku_del', {sku_id:id}, function(result){
				data = jQuery.parseJSON(result);
				if(data.error == '0'){
					$this.parents('.sku_con').remove(); 
				}else{
					$.alert(data.msg);	
				}
			}); 
		}
	});
	// 删除规格值
	$(document).on('click', '.sku_detail label a', function(){
		$this = $(this);
		if(!confirm("确认要删除？")) { 
			if(window.event){
				window.event.returnValue = false;
			}else{  
				event.preventDefault();	//for firefox
			}
		}else{
			id = $this.attr('data-id');
			$.post(SELLER+'goods/sku_del', {sku_id:id}, function(result){
				data = jQuery.parseJSON(result);
				if(data.error == '0'){
					$this.parent('label').remove();
				}else{
					$.alert(data.msg);	
				}
			}); 	
		} 
	});
	
	// ---------SKU点击显示---------------  
	$(document).on('click',".sku_checkbox",function(){ 
		sku_list();
	}); 
	function sku_list(){
		var goods_id = $("#goods_id").val(); 
		var ids = '';
		$(".sku_con input[name='sku_val']:checkbox").each(function(){
			if(this.checked){ 
				ids += $(this).val()+','; 
			}  		
		}); 
		var ids = ids.substring(0,ids.length-1); 
		$.post(SELLER+'goods/sku_img',{val:ids, goods_id:goods_id},function(data){ 
			$("#sku_color_img").html(data); 
		}); 
		var act_status = $("input[name='act_status']:checked").val();  
		if(act_status == 1){
			$.post(SELLER+'goods/sku_list',{val:ids, goods_id:goods_id, act_status:'1'},function(data){ 
				$("#sku_list").html(data); 
			}); 
		}else{
			$.post(SELLER+'goods/sku_list',{val:ids, goods_id:goods_id},function(data){ 
				$("#sku_list").html(data); 
			});
		}
	}
	
	// 填充价格 
	$(document).on('dblclick',".fill_price",function(){ 
		price = $(this).val();
		if(price){
			$(".fill_price").val(price);
			$("#price").val(price);
		}  
	});
	
	// 填充库存
	$(document).on('dblclick',".fill_stock",function(){
		stock = $(this).val();
		if(stock){
			var sum=0;
			$("input.fill_stock").each(function(){ 
				 sum+=+stock; 
			});
			$(".fill_stock").val(stock);
			$("#stock").val(sum);	
		} 
	});
	
	
	
});  

/*编辑器异步加载*/ 
$.getScript(PUBLIC+'plug/kindeditor/kindeditor-min.js', function(){
	KindEditor.plugin('multiimage2', function(K) {
		var self = this, name = 'multiimage2';
		self.clickToolbar(name, function() {
			upload_manage('editor_img', '', true);
		});
	});
	KindEditor.basePath = PUBLIC+'plug/kindeditor/';
	editor = KindEditor.create('textarea[name="content"]',{
		items : ['source' , 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', '|',  'multiimage2', 'emoticons', 'link', 'unlink', '|', 'clearhtml', 'quickformat' ],			// 换行用 '/',  
		afterCreate : function() {
			var self = this;
			K.ctrl(document, 13, function(){
				self.sync();
				K('form[name=example]')[0].submit();
			});
			K.ctrl(self.edit.doc, 13, function() {
				self.sync();
				K('form[name=example]')[0].submit();
			});
		},
		afterBlur:function(){ 	// 输完更新
			this.sync(); 
		}
	}); 
}); 

/*添加图片*/
function upload_insert(postion, file_id){ 
	if(postion == 'head_img'){ 					// 主图添加
		$(".uimg_ck_value").each(function(){ 
			ck_img_url = $(this).attr('data-url');
			ck_img_name = $(this).attr('data-name'); 
			
			var img_box = '<div class="show_img">'+ 
							'<div class="img">'+
								'<img src="'+ck_img_url+'">'+
								'<input type="hidden" value="'+ck_img_name+'" id="goods_img" name="goods_img[]">'+ 
							'</div>'+	
							'<a href="javascript:;" class="delhdimg">&nbsp;</a>'+  
						'</div>';
			if($('.show_img').length == 0){
				$('.show_hd_img').html(img_box);
			}else{
				if($('.show_img').length <= 5){
					$('.show_img:last').after(img_box);
				}
			} 
		});
	}else if(postion == 'sku_img'){				// 规格图片添加
		ck_img_url = $(".uimg_ck_value").attr('data-url');
		ck_img_name = $(".uimg_ck_value").attr('data-name');
		if(ck_img_url){
			$('.sku_show_'+file_id).html('<img src="'+ck_img_url+'" width="28">');
			$('.sku_img_value_'+file_id).val(ck_img_name); 	
		}else{
			$.alert('没有选中图片');
		} 
	}else if(postion == 'editor_img'){	// 内容的添加 
		$(".uimg_ck_value").each(function(v){ 
			ck_img_url = $(this).attr('data-url'); 
			ck_img_name = $(this).attr('data-name');  
			if(ck_img_url.indexOf("?") < 0 || ck_img_url.indexOf("?") == '' || ck_img_url.indexOf("?") == undefined){
				
			}else{
				ck_img_url = ck_img_url.substring(0, ck_img_url.indexOf("?"));	
			} 
			editor.insertHtml('<p><img src="'+ck_img_url+'"/></p>');
		});	
	}
	img_close();
}

function edit_cats(){ 
	if(!confirm('当前页面编辑的将清除')) {
		return false;
	}
}

$(function(){ 
	// 删除一个小图 
	$(document).on('click', ".show_hd_img .show_img a.delhdimg",function(e){
		$(this).parents('.show_img').remove();
	});
	
	/**/
	var is_move = false; 
	var iX, iY, mX, xY;
	var move_html;
	var box_this;
	$(document).on('mousedown', '.show_hd_img .show_img .img', function(e){ 
		e = e || window.event;  
		$this = $(this); 
		box_this = $this;
		
		is_move = true; 
		html = $this.clone().html(); 
		move_html = '<div class="show_img"><div class="img">'+html+'</div><a href="javascript:;" class="delhdimg">&nbsp;</a></div>';
		aaas = '<div class="move_show_img">'+move_html+'</div>';
		$("body").append(aaas); 
		
		var top = $this.offset().top;
		var left = $this.offset().left;
		var top2 = e.clientY;
		var left2 = e.clientX;
		iX = e.clientX - left;
		iY = e.clientY - top;  
		$(".move_show_img").css({'top':top, 'left':left});
		$(".move_show_img").setCapture && $(".move_show_img").setCapture();
	  	return false;
	}); 
	
	$(document).mousemove(function(e){
 		if(is_move){ 
			var e = e || window.event; 
			var box_left = $(".show_hd_img").offset().left;
			var box_top = $(".show_hd_img").offset().top;
			var box_w = $(".show_hd_img").width();
			var box_h = $(".show_hd_img").height();
			
			var mleft = $(".move_show_img").offset().left; 
			var mtop = $(".move_show_img").offset().top;
			var mW = $(".move_show_img").width(); 
			var mH = $(".move_show_img").height();
			
			var e = e || window.event; 
			var oX = e.clientX - iX; 
			var oY = e.clientY - iY;
			
			if(box_left > oX){
				mX = box_left;
			}else if(box_left+box_w-mW-10 < oX){		// 10 为marign填充右边的位置
				mX = box_left+box_w-mW-10;
			}else{
				mX = oX;	
			}
			$(".move_show_img").css({"left":mX + "px"}); 
			return false;
		}
	});
	
	$(document).mouseup(function(e){
		if(is_move){
			is_move = false;
			$this = $(this);
			var box_left = $(".show_hd_img").offset().left;
			var box_top = $(".show_hd_img").offset().top;
			
			length = $(".show_hd_img .show_img").length;
			show_w = $(".show_hd_img .show_img").width()+10;
			 
			for(i=1; i<=length; i++){
				if((box_left+(show_w*(i-1)) <= mX) && (mX < (box_left+(show_w*i)))){
					$(".show_hd_img .show_img").eq(i-1).before(move_html);
				} 
			}
			box_this.parent().remove();
			$(".move_show_img").remove();	
			$(".move_show_img")[0].releaseCapture(); 
			e.cancelBubble = true;	
		}
	}); 
	
	
});

