// jquery 公共操作
$(function(){ 
	//直接按回车执行确定操作
	/*
	document.onkeydown = function(e){ 
		var ev = document.all?window.event:e;
		if(ev.keyCode==13) { 
			var num = $(".dg_box").size();
			if(num == '1'){
				ajax_submit();
			} 
		}
	} 
	*/ 
	// 分类的处理  
	$(document).unbind().on("change",".cats",function(){ 
		$this = $(this);
		var pcid=$this.children('option:selected').val(); 
		if(pcid != '0'){ 
			 $.post('?m=category&a=get_one_list'+'&jq_time='+new Date().getTime(),{cid:pcid},function(result){
				var json = eval(result);
				var $html = '<select class="cats" id="is_'+pcid+'"><option value="'+pcid+'">--当前类目--</option>';
				$.each(json,function(i,o){
					$html += '<option value="'+o.cid+'">'+o.name+'</option>';
				});  
				$html += '</select>';
				var size = $("#is_"+pcid).size();
				if(size > 0){
					$this.nextAll().remove();
				}else{
					$this.nextAll().remove(); 
					if(json != ''){	
						$this.after($html);
					}	
				} 
			}); 	
		}else{
			$this.nextAll().remove();
		}
		$("#cats").val(pcid);
	}); 
	// 分类的操作
	$(document).unbind().on("change","select.cats_next",function(){ 
		$this = $(this);
		var pcid=$this.find('option:selected').val(); 
		$this.nextAll().remove();
		category_next(pcid);						 
	}); 
	
});  
// 分类操作
function category_next(pcid){
	cid = cid?cid:'0';
	$.post('?m=category&a=ajax_get_next_list'+'&jq_time='+new Date().getTime(),{pcid:pcid}, function(result){ 
		var data = jQuery.parseJSON(result);
		if(data.error == '0'){
			if(data.last == '0'){
				html = '<select name="cats" class="cats_next">';
				html += '<option value="0">---请选择---</option>';
				$.each(data.category, function(key, val){
					html += '<option value="'+val.cid+'">'+val.name+'</option>'; 
				});
				html += '<select>'; 
				if($('.cats_next').length == 0){ 
					$('.cats_list').html(html); 
				}else{
					if(pcid == '0'){
						$('.cats_list').html(html); 
					}else{
						$('.cats_next:last').after(html);
					}
				} 
			}
			$("#cid").val(pcid);
		}else{
			alert('系统繁忙');
		}
	});
} 
function category_list(cid){
	if(cid == '0'){
		category_next('0');
	}else{
		$.post("?m=category&a=ajax_get_parents_list"+'&jq_time='+new Date().getTime(), {cid:cid}, function(result){
			var data = jQuery.parseJSON(result); 
			html = '';
			$(data).each(function(key, val){
				html += '<select name="cats" class="cats_next">';
				html += '<option value="0">---请选择---</option>';
				$.each(val.list, function(index, obj){ 
					if(obj.cid == val.cid){ 
						html += '<option value="'+obj.cid+'" selected="selected">'+obj.name+'</option>'; 
					}else{ 
						html += '<option value="'+obj.cid+'">'+obj.name+'</option>'; 
					} 
				}); 
				html += '</select>'; 
			});
			$('.cats_list').html(html); 
		});
		$("#cid").val(cid);		
	} 
}


$.extend({
	includePath: '', 
	getCss:function(cssUrl){
		var link = document.createElement('link');
		link.type = 'text/css'; link.rel = 'stylesheet'; link.href = cssUrl;
		document.getElementsByTagName("head")[0].appendChild(link);	
	},
	alert:function(str, callback){
		var timeout;
		var com_con = '<div class="com_bg"></div><div class="com_box"><span>'+str+'</span></div>';
		$("body").append(com_con);
		width = $(".com_box").width();
		inH = $(window).height();
		newHeight = inH/2-100;
		$(".com_box").css({"margin-right":"-"+width/2+"px"}).animate({top:"80px"}, 50);
		
		timeout = setTimeout(function(){
			$(".com_bg").remove(); 
			$(".com_box").hide(1000).remove(); 
			callback();
		},1500); 
		$(document).on('click', '.com_box', function(){
			$(".com_bg").remove(); 
			$(".com_box").hide(1000).remove(); 
			clearTimeout(timeout);
			callback();
		});
	}
});

function dialog(name, url ,width, height){
	var width = width?width:'500';
	var height = height?height:'auto';
	var num = $(".dg_box").size();
	if(num == '0'){
		$.ajaxSetup ({ cache: false });
		$.ajax({
		 	url:url+'&jq_time='+new Date().getTime(),
			type:"GET",
			success:function(data){
				var dialog = '<div class="dg_bgcolor"></div><div class="dg_box_bar">'+
					'<div class="dg_box" style="width:'+width+'px;">'+
						'<div class="name"><span>'+name+'</span><em onclick="ajax_close();">&nbsp;</em></div>'+
						'<div class="con" style="height:'+height+'px;">'+data+'</div>'+
						'<div class="foot"><a href="javascript:;" onclick="ajax_submit();">确定</a></div>'+
					'</div></div> '; 
				$("body").append(dialog).find(".dg_box_bar").css({opacity:'0',marginTop:'-10px'}).animate({opacity:'1',marginTop:'0'},300);
				div_width = $(".dg_box").width();
				div_height = $(".dg_box").height(); 
				win_width = $(window).width();
				win_height = $(window).height();
			 	left = (win_width/2) - (div_width/2);
				top = (win_height/2) - (div_height/2); 
				$(".dg_box").css({"left":left + "px", "top":top + "px"});
			}
		}); 
	}
} 

// 弹出拖动
$(function(){ 
	var dragging = false; 
	var iX, iY;
	$(document).on('mousedown', '.dg_box .name', function(e){
		dragging = true; 
		offsetLeft = $(".dg_box").offset().left; 
		offsetTop = $(".dg_box").offset().top; 
		iX = e.clientX - offsetLeft;  
		iY = e.clientY - offsetTop; 
		$(".dg_box").setCapture && $(".dg_box").setCapture(); 
		return false; 
	}); 
	document.onmousemove = function(e) {  
		if (dragging) { 
			var e = e || window.event; 
			var oX = e.clientX - iX; 
			var oY = e.clientY - iY;
			// 位置 
			if(oX <=0){
				oX = 0;
			}
			if(oY <=0){
				oY = 0;	
			}
			div_width = $(".dg_box").width();
			div_height = $(".dg_box").height(); 
			win_width = $(window).width();
			win_height = $(window).height(); 
			if(oX >= win_width - div_width){
				oX = win_width - div_width;
			}
			if(oY >= win_height - div_height){
				oY = win_height - div_height;	
			}
			$(".dg_box").css({"left":oX + "px", "top":oY + "px"});
			return false; 
		}
	};
	$(document).on('mouseup',  function(){ 
		dragging = false; 
		$(".dg_box")[0].releaseCapture(); 
		e.cancelBubble = true; 
	})  
})

function ajax_alert(url){
	var dialog = '<div class="dg_bgcolor"></div><div class="dg_box_bar"><div class="alert">正在处理中...请稍后</div></div></div> '; 
	$("body").append(dialog); 
	$.post(url,function(data){
		if(data == true){
			$.alert('设置正确！');
		}else{
			$.alert('数据出错！'); 
			$.alert(data);
		}
		ajax_close();
	});	
}

function ajax_close(){
	$(".dg_box_bar").animate({marginTop:'-10',opacity:'0'},200).delay(200).queue(function(){ $(this).remove(); });
	$(".dg_bgcolor").animate({opacity:'0'},200).delay(200).queue(function(){ $(this).remove(); }); 
}

function ajax_flush(flush_url){ 
	if(flush_url ==  undefined ){ 
		document.getElementById('content').contentWindow.location.reload(true); 
	}else{ 
		$("#content").attr('src',flush_url);	 
	}  
}

// 内容编辑
function editor_content(id, upload_path){ 
	$.getCss('public/plug/kindeditor/themes/default/default.css');
	$.getScript('public/plug/kindeditor/kindeditor-min.js', function(){
		KindEditor.basePath = 'public/plug/kindeditor/';															 	
		KindEditor.create(id, { 
			afterBlur: function () { this.sync(); },
			allowImageUpload : true,
			cssData:'body { font-size: 12px; color:#333; line-height:25px; font-family: Microsoft YaHei,tahoma; }',
			uploadJson :'?m=album&a=upload_edit&path='+upload_path,
			items : [   'formatblock', 'fontname', 'fontsize', '|', 	
						'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', '|', 
						'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', '|', 
						'image', 'emoticons', 'baidumap', 'link', 'unlink', '|',  
						'clearhtml', 'quickformat', 'source', 'fullscreen',  '|', 'about'
					]	// 换行用 '/', 
		
		}); 
		editor.sync();
	}); 
} 
// 直接编辑
function ajaxEdit(clickPostion, showPostion, postUrl, fieldKey, field){
	$(clickPostion).click(function(){  
		var td = $(this); 
		var txt = td.text(); 
		var input = $("<input type='text' size='2' class='edit_input' value='" + txt + "'/>"); 
		td.html(input); 
		input.click(function(){ return false; });  
		input.trigger("focus"); 
		input.blur(function() { 
			var newtxt = $(this).val();
			if (newtxt != txt) { 
				td.html(newtxt);
				//var caid = $.trim(td.prev().text());  
				var keyid  = td.attr(showPostion);  
				$.post(postUrl+'&jq_time='+new Date().getTime(), fieldKey+'='+keyid+'&'+field+'='+newtxt, function(data){  
					if(data=="1"){  
						td.html(newtxt);  
					}else{
						alert('更新失败');
					} 
				}); 
			}else{ 
				td.html(newtxt); 
			}  	
		});
	}); 
}

/* 文件上传 */
function upload(path, id, file_name){
	$(function(){
		jQuery.getScript("public/js/ajaxfileupload.js", function() {
			$(document).on('change','#'+id,function(){ 
				var $this=$(this); 
				$("#upload_msg").ajaxStart(function(){ 
					$(this).show(); 
				});
				if(file_name == 'undefined'){
					file_name = '';
				}
				$.ajaxFileUpload({ 
					url:'?m=album&a=upload&path='+path+'&file_name='+file_name+'&jq_time='+new Date().getTime(),
					secureuri:false, 
					fileElementId:id,
					dataType: 'text',	//text json
					success: function(result){ 
						var data = jQuery.parseJSON(result);
						if(data.error == '0'){
							$("#"+id).parents(".upload_button").next('.upload_tip').attr('data-img', data.url);	
							$("#"+id).parent().parent().find("input").val(data.name); 
						}else{
							alert(data.msg);
						}
					}
				});
			});
		}); 
	});
}
 

// 初始化一些数据
$(function(){
	/* 全选操作 */ 
	$(document).on('click', '.checked_all', function(){
		if(this.checked){    
			$(".checked_list:checkbox").attr("checked", true);  $(".checked_all").attr('checked', true); 
		}else{    
			$(".checked_list:checkbox").attr("checked", false); $(".checked_all").attr('checked', false);  
		}
	}); 
	$(document).on('click', 'input.checked_list', function(){
		var num = 0;
		var loop = 0;
		$("input.checked_list").each(function(){
			if($(this).attr("checked")){
				num++;
			}
			loop++;
		});
		if(num == loop){
			$(".checked_all").attr("checked", true);
		}else{
			$(".checked_all").attr("checked", false);	
		}
	});
	
	function table_width(){
		var table_width = 0;
		$("table.ltable thead th").each(function(){
			var th_width = $(this).attr('width');
			if(th_width == '' || th_width == undefined){
				th_width = 100;
			}
			table_width	+= parseFloat(th_width);
		});	
		$("table.ltable").css('width', table_width);   
	} 
	table_width();
	
	// 后退
	$(".cnav a.back").click(function(){ 
		window.history.back();  
	}); 
	
	// 保存
	$("form").submit(function(){
		$this = $(this);
		var post_url = $this.attr('action'); 
		var post_method = $this.attr('method'); 
		if(post_method == 'post'){
			var status = $this.attr('status'); 
			var back_status = $this.attr('back'); 
			$.ajax({
				type:'POST',
				url:post_url+'&jq_time='+new Date().getTime(),
				data:$this.serialize(), 
				success:function(result){
					if(status != undefined){ 
						alert(result); 
					}
					data = $.parseJSON(result);
					if(data.error == 0){ 
						parent.$.alert('保存成功', function(){
							if((back_status != undefined) || (back_status == '')){ 
								$('html,body').animate({scrollTop:0}, 'fast');
							}else{
								window.history.back(); 
							}  
						}); 
						if((back_status != undefined) || (back_status == '')){
							$('html,body').animate({scrollTop:0}, 'fast');
						}
					}else{
						parent.$.alert(data.msg);
					}
				},error:function(){
					parent.$.alert('系统繁忙');
				}
			}); 
			return false;	
		}else{
				
		}
	});
	// 预览文字
	vtip(); 
});

// 删除操作
function _delete(url, id, status){
	$("a.del").click(function(){
		if (!confirm("您真的确定要删除吗？\n\n请确认！")) {
			if(window.event){
				window.event.returnValue = false;
			}else{  
				event.preventDefault();	//for firefox
			}
		}else{
			ckid = $(this).attr('data-id');
			$.post(url+'&jq_time='+new Date().getTime(), {id:ckid}, function(result){
				if(status){
					alert(result);
				}
				var data = jQuery.parseJSON(result); 
				if(data.error == 0){
					parent.$.alert('删除成功');
					location.reload(); 
				}else{
					alert(result+":"+data.msg);
				}
			});
		}						  
	});
	$(id).click(function(){
		ckid = checkbox_ck_id(); 
		if(ckid != ''){
			if (!confirm("您真的确定要删除吗？\n\n请确认！")) {
				if(window.event){
					window.event.returnValue = false;
				}else{  
					event.preventDefault();	//for firefox
				}
			}else{ 
				$.post(url+'&jq_time='+new Date().getTime(), {id:ckid}, function(result){
					if(status){
						alert(result);
					}
					var data = jQuery.parseJSON(result); 
					if(data.error == 0){
						parent.$.alert('删除成功');
						location.reload(); 
					}else{
						parent.$.alert(data.msg);
					} 
				});	
			} 
		}else{
			parent.$.alert('没有选中'); 
		}
	});  
}
function checkbox_ck_id(){
	ckid = '';
	$("input.checked_list").each(function(){ 
		if($(this).is(":checked")){ 
			ckid += $(this).val()+','; 
		}
	});
	ckid = ckid.substring(0, ckid.length-1); 
 	return ckid;
}  
// 预览图片文字
this.vtip = function() {    
    this.xOffset = -10; 		// x distance from mouse
    this.yOffset = 15; 			// y distance from mouse       
    $(".vtip").unbind().hover(    
        function(e) {
           	data_img = $(this).attr('data-img');
		    if(data_img == 'undefined' || data_img == ''){
				data_ttl = $(this).attr('data-ttl');
				if(data_ttl == 'undefined' || data_ttl == ''){
					this.t = data_ttl; 
				}else{
					this.t = '暂无预览';
				}
			}else{
				this.t = '<img src="'+data_img+'" style="max-width:500px;"/>';
			} 
            this.title = ''; 
            this.top = (e.pageY + yOffset);
			this.left = (e.pageX + xOffset); 
			$('body').css("cursor","help"); 
			$('p#vtip').width()>450?$('p#vtip').width(450):'';
            $('body').append( '<p id="vtip">' + this.t + '</p>' );		 
            $('p#vtip').css("top", this.top+"px").css("left", this.left+"px").fadeIn(0);			   
        },
        function() {
            this.title = this.t;
			$('body').css("cursor","");
            $("p#vtip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
         this.top = (e.pageY + yOffset);
         this.left = (e.pageX + xOffset);                         
         $("p#vtip").css("top", this.top+"px").css("left", this.left+"px"); 
        }
    ); 
}; 




