var htimeout = new Object();
var modulesContainers = null;
var ds = null;
try{
	modulesContainers = $("*[isModuleContainer='true']"); //在设计模板时，模块的容器必须加上 isModuleContainer='true' 这个属性
	ds = new DragSort(modulesContainers);
	ds.needHandle = true;
	ds.run(ds);

	$(document).ready(initModuleCtrl);
}catch(e){
	
}

function initModuleCtrl(){
	
	//添加用到的CSS
	$("head").append("<LINK href='/share/jquery-ui-css/ui-lightness/jquery-ui.custom.css' type='text/css' rel='stylesheet'>");

	//初始化模块容器
	modulesContainers.each(function(i,elm){
		bindModuleContainerEvents(elm);
	});

	//建立页头控制条
	buildHeaderBar();
}

function buildHeaderBar(){
	$("head").append("<style type='text/css'>.headerbar{ background:url(/admin/images/navbg.gif);height:40px;color:white;z-index:9999;position:absolute; } .headerbar A{ color:white; } .headerbar A:visited{ color:white; } .headerbar A:hover{ color:yellow!important; }</style>");
	var html = "<table id='headerctl' class='headerbar' width='100%' cellpadding='5' cellspacing='0' border='0'><tr><td align='center'>";
	html += "<a href='../admin/'>管理后台首页</a> | <a href='../admin/site/skin.aspx'>选择网站风格</a> | <a href='../admin/site/menu.aspx'>网站栏目管理</a> | ";
	html += "<a href='../admin/article/'>新闻资讯管理</a> | <a href='../admin/product/'>产品管理</a> | <a href='../admin/order/'>订单管理</a> | ";
	html += "<a href='#' onclick='saveLayout();return false;'>保存布局</a>";
	html += "</td></tr></table>";
	var space = $(html).clone().get(0); //占位，以免控制条挡住最前面的
	space.className = "";
	$("body").get(0).insertBefore(space,$("body").get(0).childNodes[0]);
	$("body").get(0).insertBefore($(html).get(0),$("body").get(0).childNodes[0]);
	$(window).bind("scroll",function(){
		document.getElementById('headerctl').style.top = $(document).scrollTop() + 'px';
	});
}

function saveLayout(){
	var xmlhttp = $.ajax({
	   type: "POST",
	   async: true,
	   url: "../admin/modules/savelayout.aspx",
	   data: {modules:ds.serial(),url:location.toString()},
	   success: function(msg){
		 if(msg == "OK") alert( "模块布局保存成功");
		 else alert( "模块布局保存失败：" + msg);
	   },
	   error: function(request, status, error){
		 alert( "ERROR: " + request.responseText );
	   }
	});
}

//参数中的 elm 是指模块的 容器(Container)
function bindModuleContainerEvents(elm)
{
	//绑定修改子模块的事件
	$(elm).children().each(function(j,elmsub){			
		bindModuleEvents(elm,elmsub);
	});

	//绑定添加子模块的事件
	//$(elm).append("<img src='/images/btn_add_module.gif' style='cursor:pointer;margin-top:5px' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleImage')\">");
	var dialogId = "dlgAdd_" + $(elm).attr('id');
	var html = "<table border='0' cellpadding='5' cellspacing='6' width='100%'></tr>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleText');$('#"+ dialogId +"').remove();return false;\">添加文字模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleImage');$('#"+ dialogId +"').remove();return false;\">添加图片模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleMap');$('#"+ dialogId +"').remove();return false;\">添加地图模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleLinkList');$('#"+ dialogId +"').remove();return false;\">添加友情链接模块</a></td>";
	html += "</tr><tr><td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleUserLogin');$('#"+ dialogId +"').remove();return false;\">添加用户登录模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleVideo');$('#"+ dialogId +"').remove();return false;\">添加视频模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleProductCls');$('#"+ dialogId +"').remove();return false;\">添加产品分类模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleProductSearch');$('#"+ dialogId +"').remove();return false;\">添加产品搜索模块</a></td>";
	html += "</tr><tr><td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleProductList');$('#"+ dialogId +"').remove();return false;\">添加产品列表模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleDownCls');$('#"+ dialogId +"').remove();return false;\">添加下载分类模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleDownSearch');$('#"+ dialogId +"').remove();return false;\">添加下载搜索模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleDownList');$('#"+ dialogId +"').remove();return false;\">添加下载列表模块</a></td>";
	html += "</tr><tr><td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleNewsCls');$('#"+ dialogId +"').remove();return false;\">添加文章分类模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleNewsSearch');$('#"+ dialogId +"').remove();return false;\">添加文章搜索模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleNewsList');$('#"+ dialogId +"').remove();return false;\">添加文章列表模块</a></td>";
	html += "<td><a href='#' onclick=\"editModule('0','"+ $(elm).attr('id') +"','ModuleShopCart');$('#"+ dialogId +"').remove();return false;\">添加购物车模块</a></td>";
	html += "</tr></table>";
	var handle = $("<img>", {src: "/images/btn_add_module.gif",style: "cursor:pointer;margin-top:5px",
		click: function(){
			$("body").append("<div id='"+dialogId+"' style='display:none'>"+ html +"</div>");
			$("#" + dialogId).dialog({title: '添加模块', modal: true,width:500,height:'auto',beforeclose:function(event, ui){$(this).remove();}});
		}
	});
	$(elm).append(handle);
}

function showAddModuleTypes(container){
	
}

//参数中的 elm 是指模块的 容器(Container), elmsub 是指具体的模块
function bindModuleEvents(elm,elmsub)
{
	if($(elmsub).attr("isDragItem") != 'true') return;
	$(elmsub).bind("mouseover",function(){
		clearTimeout(htimeout[$(elmsub).attr("id")]);
		var handleid = "mh_"+ $(elmsub).attr("id");
		//if($(elmsub).children("table[isHandle]").length == 0){
		if($("#" + handleid).length == 0){
			var width = $(elmsub).width();
			var html = "<table id='"+ handleid +"' isHandle='true' bgcolor='red' style='position:absolute;width:"+ width +";' class='ModuleItemHandle' border='0' cellpadding='3' cellspacing='1'>";
			html += "<tr><td isDragHandle='true' style='cursor:move' style='color:white'>拖动</td><td align='right' width='70' style='color:white'>";
			html += "<span style='cursor:pointer' onclick=\"editModule('"+ $(elmsub).attr("id") +"','"+ $(elm).attr('id') +"');return false;\">修改</span> - ";
			html += "<span style='cursor:pointer' onclick=\"delModule('"+ $(elmsub).attr("id") +"');return false;\">移除</span></td></tr></table>";
			//jQuery.get(0) 相当于将 jQuery 对象转为 DOM 对象
			var domObj = $(html).get(0);
			$(elmsub).get(0).insertBefore(domObj,$(elmsub).get(0).childNodes[0]);
			$(elmsub).css("border","1px solid red");
		}
	});

	$(elmsub).bind("mouseout",function(e){
		//htimeout[$(elmsub).attr("id")] = setTimeout(function(e){$(elmsub).children("table[isHandle]").remove();},3);
		var handleid = "mh_"+ $(elmsub).attr("id");
		htimeout[$(elmsub).attr("id")] = setTimeout(function(e){$("#" + handleid).remove();$(elmsub).css("border","none");},3);
	});
}

//slocation 是指模块容器的ID，主要是新建模块时用到
function editModule(moduleId,slocation,moduleType){
	$("body").append("<div id='dialog' style='display:none'>"+ (moduleId == '0' ? '添加模块':'修改模块') +"</div>");
	var iframe = $("<iframe src='../admin/modules/ModuleEdit.aspx?moduleId="+ moduleId +"&moduleType="+ moduleType +"&location="+ slocation +"&dialogId=dialog&url="+ escape(window.location.toString()) +"' id='moduleEditFrame' name='moduleEditFrame' framemargin='0' frameborder='0' width='99%' height='410'></iframe>");
	$("#dialog").html(iframe);
	$("#dialog").dialog({
		title: '修改模块', modal: true,width:800,height:'auto',position:['center',50],
		//buttons: { "关闭": function() { $(this).dialog("close")} },
		beforeclose: function(event, ui){
				var loadedmoduleslocations = $("#" + slocation).find("div[name='LoadedModules']").html();
				var xmlhttp = $.ajax({
					type: "GET",url: "LoadModule.aspx",data: "moduleId=" + moduleId + "&location=" + loadedmoduleslocations + "&loadpage=" + escape(window.location.toString()),
					success: function(msg){
						if(moduleId == '0'){
							$("#" + slocation).children().remove();
							$("#" + slocation).append(msg);
							bindModuleContainerEvents($("#" + slocation));
						}
						else $("#" + moduleId).html($(msg).html());
						//$("#" + moduleId).replaceWith(msg);//如果用这个，需要重新初始化 mouseover 等感应操作
					},
					error: function(request, status, error){
						if(moduleId == '0');
						else $("#" + moduleId).html(request.responseText);
					}
				});
				//$("#dialog").html("");
				$("#moduleEditFrame").remove(); //不remove这个的话，会导致编辑内部iframe无法自动适应高度
				//$("#dialog").children().remove();
				$("#dialog").dialog( "destroy" );
				//$("#dialog").remove(); //直接remove对话框掉编辑器会出问题
			}
		}
	);
}

function delModule(moduleId){
	$("body").append("<div id='dialogdel' style='z-index:99999'>删除后不可恢复，确定删除此模块吗？</div>");
	$("#dialogdel").dialog({
		title: '删除模块', modal: true,width:300,
		buttons: { "取消": function() { $(this).dialog("close")},"确定": function() { 
				var result = delModuleAjax(moduleId);
				$(this).dialog("close");
				if(result == "OK") $("#" + moduleId).remove();
				else{
					$("body").append("<div id='dialogerr'>"+ result +"</div>");
					$("#dialogerr").dialog({title: '错误信息',width:700,height:600,beforeclose:function(event, ui){$("#dialogerr").remove();}});
				}
			}
		},
		beforeclose: function(event, ui) { $("#dialogdel").remove(); }
		}
	);
}

function delModuleAjax(moduleId){
	//return "OK";
	var xmlhttp = $.ajax({
	   type: "GET",
	   async: false,
	   url: "../admin/modules/del.aspx",
	   data: "moduleId=" + moduleId
	   /*
	   success: function(msg){
		 //alert( "SUCCESS: " + msg );
		 return "OK";
	   },
	   error: function(request, status, error){
		 //alert( "ERROR: " + request.responseText );
		 return request.responseText;
	   }*/
	});

	return xmlhttp.responseText;
}