// jquery 公共操作
function pr(obj){
	var description = ""; 
	for(var i in obj){ 
	var property=obj[i]; 
		description+=i+" = "+property+"\n"; 
	} 
	alert(description); 
}
function recombine_url(serverUrl){
	return serverUrl + (serverUrl.indexOf('?') == -1 ? '?':'&');	
} 
//直接按回车执行确定操作
/*
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(ADMIN+'category/get_one_list'+'?v='+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(ADMIN+'category/ajax_get_next_list'+'?v='+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(ADMIN+"category/ajax_get_parents_list?v="+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; 
		if($(".com_box").length > 0){ 
			$(".com_box span").html(str); 
		}else{
			$("body").append('<div class="com_bg"></div><div class="com_box"><span>'+str+'</span></div>');
			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();
		});
	},
	loadingStart(){
		str = '<img src="'+PUBLIC+'images/loading.gif">';
		$("body").append('<div class="com_bg"></div><div class="com_box"><span>'+str+'</span></div>'); 
		width = $(".com_box").width();
		width = $(".com_box").width();
		inH = $(window).height();
		newHeight = inH/2-100;
		$(".com_box").css({"margin-right":"-"+width/2+"px"}).animate({top:"80px"}, 50); 
	},
	loadingClose(){
		$(".com_bg,.com_box").remove();
	},
	alertLoad:function(str){
		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); 
	}
});
 
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+(url.indexOf('?') == -1 ? '?':'&'),
			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 dialog_page(name, url ,width){
	var width = width?width:'500';
	var height = $(window).height(); 
	var num = $(".dg_box").size();
	if(num == '0'){
		var dialog = '<div class="dg_lbgcolor"></div>'+
					'<div class="dg_lbox" style="width:'+width+'px;">'+
						'<div class="name"><span>'+name+'</span><a onclick="dialog_page_close()">&nbsp;</a></div>'+
						'<div class="con" style="height:'+height+'px;"><iframe id="ifm" style="width:inherit;height:inherit;border:none;" runat="server"></iframe></div>'+ 
					'</div>'; 
		$("body").append(dialog).find(".dg_box_bar").css({opacity:'0', marginLeft:'10px'}).animate({opacity:'1', marginLeft:'0'}, 300);
		$(".dg_lbox").css({"right":"0", "top":"0", "position":"absolute"});
		$(".dg_lbox .con").css({"height":height-50});
		url = url+(url.indexOf('?') == -1 ? '?':'&');
		$("#ifm").attr("src", url);
	}
} 
function dialog_page_close(){ 
		$(".dg_lbgcolor,.dg_lbox").remove(); 				
}
// 弹出拖动
$(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(); }); 
	$(".dg_bgcolor").remove();
}

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

// 内容编辑
function edit_content(id, upload_path){ 
	$.getScript(PUBLIC+'plug/kindeditor/kindeditor-min.js', function(){
		KindEditor.basePath = PUBLIC+'plug/kindeditor/';
		editor = KindEditor.create(id,{
			items : ['source' , 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', '|', 'justifyleft', 'justifycenter', 'justifyright', '|',  'image', 'emoticons', 'link', 'unlink', '|', 'clearhtml', 'quickformat' ],			// 换行用 '/',  
			uploadJson :ADMIN+'album/upload_edit?path='+upload_path,
			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 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 keyid  = td.attr(showPostion);  
				$.post(postUrl+'?v='+new Date().getTime(), fieldKey+'='+keyid+'&'+field+'='+newtxt, function(data){  
					if(data=="1"){  
						td.html(newtxt);  
					}else{
						alert('更新失败');
					} 
				}); 
			}else{ 
				td.html(newtxt); 
			}  	
		});
	}); 
}

// 初始化一些数据
$(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#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');  
			parent.$.loadingStart();
			$.ajax({
				type:'POST',
				url:post_url+'?v='+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 == 'false'){ 
								$('html,body').animate({scrollTop:0}, 'fast');
							}else if(back_status == 'refresh'){ 
								location.reload();
							}else if(back_status == 'frame_reload'){ 
								window.parent.location.reload(); 
							}else{ 
								setTimeout(function(){ 
									parent.document.getElementById('content').contentWindow.history.back();  
								}, 1000); 
							} 
						});  
					}else{
						parent.$.alert(data.msg);
					}
				},error:function(){
					parent.$.loadingClose();
					parent.$.alert('系统繁忙');
				}
			});
			return false;	
		}
		
	});
	// 预览文字
	vtip(); 
});

// 删除操作
function _delete(url, id, status){
	$("a.del,a.del2").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+'?v='+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);
				}
			});
		}						  
	});
	$(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{
				$("input.checked_list").each(function(){ 
					if($(this).is(":checked")){
						ckid = $(this).val();
						$.ajax({
							type:'post',
							url:url+'?v='+new Date().getTime(),
							data:{id:ckid},
							async:false,
							success:function(result){ 
								if(status){
									alert(result);
								}
								var data = jQuery.parseJSON(result); 
								if(data.error == 0){
									parent.$.alert('删除成功');
								}else{
								 	parent.$.alert('删除失败');
								} 
							} 
						});  
					}
				});
				location.reload(); 
			} 
		}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;
} 

// 预览图片文字
function vtip(){
	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"); 
        }
    ); 	
} 

function admin_upload(path, id, file_name){
	upload(id, ADMIN+'album/upload?path='+path+'&file_name='+file_name+'&v='+new Date().getTime(), function(data){
		$(id).parents(".upload_button").next('.upload_tip').attr('data-img', data.url);	
		$(id).parent().parent().find("input").val(data.name); 				
	});	
}