/*!
 * kesion.drag.load.js 
 * Date: 2017-5-25 13:54 by zhuang
 * 厦门科汛软件有限公司　 版权所有 © 2006-2017
 * 官方地址：http://www.kesion.com
 * 
 * 24小时服务热线：400-008-0263
 * 
 */
 
var $pageCont = $('#pageCont');	//赋值容器
var $main = $('#pageMain');//页面加载iframe
var $realTimeBox = $('#realTimeBox');//实时窗口
var $realTime = $('#realTime'); //实时窗口iframe 名称
var speed = 300;//整体动画速度
var $moduleObject;//初始化模块操作对象	
var labelState = 0; //添加或编辑标签 0:添加 1:编辑
var addState = false; //用于检测点击是否是在版式上选择的添加模块
var htmlContent = ''; //用于字符长度较长的html存储
var styleContent = '';//用于存储样式、信息等
var $contents;	
var appendFile = '<link rel="Stylesheet" href="/admin/drag/fonts/iconfont.css">'+
				 '<link rel="Stylesheet" href="/admin/drag/css/drag.cont.css">'+
				 '<script src="/admin/drag/js/kesion.drag.js"></script>';

var Drag = {
	//添加
	Add:function(obj){
		if($('.ks-popup-box').length==0){
			var $t  = $(obj);
			addState = true;
			$moduleObject = $t.parent();
			$moduleObject.append('<div class="drag-addModule-tips">请在左菜单选择模块嵌入</div>');
			$moduleObject.addClass('drag-z-index').before('<div class="drag-moduleBoxBg" onClick="parent.closeModuleBg(this)" drag-savedelete="true" style="display:none;"></div>');
			$moduleObject.prev('.drag-moduleBoxBg').fadeIn(speed);
			$('#leftTab').find('li:first').click();
			$('#leftTab').find('li:eq(1)').addClass('disabled');
			setTimeout(function(){
				for(var f=0;f<3;f++){
					$('.tab-tips-bg').fadeIn(150);
					$('.tab-tips-bg').fadeOut(150);
				};

			},300);
		};
	},
	//选择
	Select:function(type,url,tab){
		
		if($('.ks-popup-box').length==0&&$contents){
			if($('#realTimeBox').css('display')!='none'){
				closeStyle();
			};
			
			
			if(type=='html'){
				popup.open({
					title:'编辑Html元素',
					area: ['900', '540'], 
					drag:true,
					shade:0.2,
					scrollbar:false,
					url:url
				});
				
			}else if(type=='lable'){
				labelState = 0; //设置为添加状态
				popup.open({
					title:'编辑标签',
					area: ['960','540'], 
					drag:true,
					shade:0.2,
					scrollbar:false,
					url:manageDir+'/drag/module/set-label.aspx?labelUrl='+url+''
				});
					
			}else if(type=='format'){
				popup.open({
					title:'添加版式',
					area: ['800', '540'],
					drag:true,
					shade:0.2,
					scrollbar:false,
					url:url
				});
			}else if(type=='header'||type=='footer'){
				
				var title = '插入头部';

				if(type=='footer'){
					title = '插入底部';
				};
				popup.open({
					title:title,
					area: ['700', '440'], 
					drag:true,
					shade:0.2,
					scrollbar:false,
					url:url
				});
			}
				
		};
	},
	//编辑
	Edit:function(obj){
		if($('.ks-popup-box').length==0){
			var $t = $(obj);
			//改变指向对象
			$moduleObject = $t.parent().parent();
			var moduleType = $moduleObject.attr('drag-type').split(',')[0];
			
			if(moduleType=='html'){
				var moduleHtml = $moduleObject.find('[drag-module="content"]').html();					
				htmlContent = moduleHtml; //存放当前html内容
				popup.open({
					title:'编辑Html元素',
					area: ['900', '540'],
					drag:true,//拖动
					shade:0.2,
					scrollbar:false,//禁止页面滚动条
					url:manageDir+'/drag/module/set-html.aspx?type=edit'
				});
				
			}else if(moduleType=='label'){
				
				labelState = 1;//设置为编辑状态
				var labelName = draglabel();
				if(labelName){
					popup.open({
						title:'编辑标签',
						area: ['960', '540'],
						drag:true,//拖动
						shade:0.2,
						scrollbar:false,//禁止页面滚动条
						url:''+manageDir+'label/LabelEdit.aspx?skinId='+skinId+'&labelName='+labelName+''
					});
				}else{
					popup.tips({
						title:'没有找到对应标签'
					});
				}
				
			}else if(moduleType=='code'){
				var type = 'edit';
				if($moduleObject.attr('drag-render')){
					var codeHtml = $moduleObject.find('.label_data').html();
					type = 'editLabelCode'
				}else{
					var codeHtml = $moduleObject.html();

				}
				$moduleObject.before('<div style="display:none">'+codeHtml+'</div>');
				$moduleObject.prev().clearDrag();
				htmlContent = $moduleObject.prev().html();
				$moduleObject.prev().remove();
				
				popup.open({
					title:'编辑代码',
					area: ['800', '440'],
					drag:true,//拖动
					shade:0.2,
					scrollbar:false,//禁止页面滚动条
					url:manageDir+'/drag/module/set-code.aspx?type='+type
				});
				
			}else if(moduleType=='paging'){
				var pagingId = $moduleObject.attr('drag-paging'); //获取分页id
				popup.open({
					title:'修改分页样式',
					area: ['800', '540'],
					drag:true,//拖动
					shade:0.2,
					scrollbar:false,//禁止页面滚动条
					url:manageDir+'/drag/module/set-paging.aspx?pagingId='+pagingId+''
				});
				
			}else if(moduleType=='header'||moduleType=='footer'){
				
				var labelName = draglabel();
				
				if(labelName){
					
					var $module = $moduleObject.find('['+moduleType+'-id]');
					var moduleId = $module.attr(''+moduleType+'-id');
					var moduleClass = $module[0].className.split(' ');
					var moduleColor = '';
					for(var i in moduleClass){
						if(moduleClass[i].indexOf('m-bg-')!=-1){
							moduleColor = moduleClass[i].split('m-bg-')[1];
							break;
						}
					};

					labelName = labelName.replace('{KS_','').replace('{ks_','').replace('}','');

					var title = '编辑头部';
					if(moduleType=='footer'){
						title = '编辑底部';
					}
					popup.open({
						title:title,
						area: ['700', '300'],
						drag:true,
						shade:0,
						scrollbar:false,
						url:manageDir+'/drag/module/staticLabel.aspx?type=edit&module='+moduleType+'&id='+moduleId+'&labelName='+labelName+'&moduleColor='+moduleColor+'',
						close:function(){
							staticLabel.Edit(moduleColor,moduleType);
						}
					});
					
				}else{
					popup.tips({
						  title:'错误的静态标签',
					});
					
				};
				
			//课程列表
			}else if(moduleType=='style'){
				  
				var styleType = '';
				var renderLength = $moduleObject.find('[drag-render]').length;
				for(var i=0;i<renderLength;i++){
					var renderType = $moduleObject.find('[drag-render]').eq(i).attr('drag-render').split(' in ')[0];
					if(renderType=='loop'){
						$moduleObject = $moduleObject.find('[drag-render]').eq(i);
						styleType = $moduleObject.attr('drag-render').split(' in ')[1];
						break;
					}
				}

				popup.open({
					  title:'选择样式',
					  area: ['800', '500'], 
					  drag:true,
					  shade:0.2,
					  scrollbar:false,
					  url:manageDir+'/drag/module/set-style.aspx?styleType='+styleType+''
				});
			};
			
		};
	},
	Setup:function(obj){
		if($('.ks-popup-box').length==0){
			 var $t = $(obj);
			 $moduleObject = $t.parents('[drag-type]:first');
			 var $setObject = $t.parent();
			 var labelName = draglabel();
			 if(labelName){
				 
				 $moduleObject.find('[drag-mark]').removeAttr('drag-mark');
				 //添加编辑标识
				 $setObject.attr('drag-mark','true');
				 var setupType = $setObject.attr('drag-setup');
				 var labelName = labelName.replace('{KS_','').replace('{ks_','').replace('}','');
				
				 if(setupType=='nav'){
					 popup.open({
						  title:'编辑导航',
						  area: ['800', '560'], 
						  drag:true,
						  shade:0.2,
						  scrollbar:false,
						  url:manageDir+'/drag/module/set-nav.aspx?labelName='+labelName+''
					 });

				 }else if(setupType=='logo'){
					
					styleContent = [$setObject.find('img')[0].currentSrc,$setObject.find('img')[0].alt,$setObject.find('img')[0].width,$setObject.find('img')[0].height]
					
					popup.open({
						  title:'编辑Logo',
						  area: ['800', '510'], 
						  drag:true,
						  shade:0.2,
						  scrollbar:false,
						  url:manageDir+'/drag/module/set-logo.aspx?labelName='+labelName+''
					});
				
				 }else if(setupType=='text'){
					popup.open({
						  title:'编辑文本',
						  area: ['550', '300'], 
						  drag:true,
						  shade:0,
						  scrollbar:false,
						  url:manageDir+'/drag/module/set-text.aspx?labelName='+labelName+''
					});
				 };
				 
			 }else{
				  popup.tips({
						title:'错误的静态标签',
				  });
			 };
 
		};
	},
	//修改样式
	Style:function(obj){
		if($('.ks-popup-box').length==0){
			//改变指向对象
			$moduleObject = $(obj).parent().parent();

			$moduleObject.addClass('drag-z-index').before('<div class="drag-moduleBoxBg" style="display:none;" drag-savedelete="true"></div>');
			$moduleObject.prev().fadeIn(speed);
			
			var ol = $moduleObject.offset().left;
			if(ol<$(window).width()/2){
				$realTimeBox.css({display:'block',left:'auto',right:'-320px'});
				$realTimeBox.animate({right:0},speed)
			}else{
				$realTimeBox.css({display:'block',right:'auto',left:'-320px'});
				$realTimeBox.animate({left:0},speed)
			};
			
			window.open(manageDir+"drag/module/setFormat.aspx","realTime");
			
			
		};
	},
	//添加子版块
	Split:function(obj){
		if($('.ks-popup-box').length==0){
			var $t = $(obj);
			var formatSpacing = $t.parents('[drag-format-spacing]').first().attr('drag-format-spacing'); //模块间距
			if(!formatSpacing){
				formatSpacing = 0;
			};
			$moduleObject = $t.parents('[drag-addModule]').first();			
			
			var formatType = $moduleObject.attr('drag-format');
			
			if($t.parent().prev().size()==0){
				  popup.open({
						title:'拆分',
						area: ['700', '440'],
						drag:true,
						shade:0,
						scrollbar:false,
						url:manageDir+'/drag/module/formatSplit.aspx?formatSpacing='+formatSpacing,
				 });

			}else{
				
				popup.confirm({
					title:'该版式也增加过模块',
						
				});
				
			};
		
		};
	},

	//删除模块
	Delete:function(obj){	
		
		if(document.getElementsByClassName('ks-popup-confirm').length==0){
			var $deleteObject = $(obj).parent().parent();
			popup.confirm({
				  title:'您确定删除吗?',				  
				  yes:function(){
				  	$deleteObject.remove();
				  },
			});
		}
		
		
	},

};

//框架整体高度设置
pageHeight();
$(window).resize(function(){
	pageHeight();
});
function pageHeight(){
	$main.height($(window).height()-$('#pageHead').outerHeight()-$('#pageCont .x-axis').outerHeight());
	
	$('.pageLeft-set,#pageCont').height($(window).height()-$('#pageHead').outerHeight());
	$realTime.height($(window).height()-$realTime.prev('.title').outerHeight())
};


var ajaxNum = 0;
var ajaxLoadNum = 0;
//加载要编辑的页面	
window.open("/plus/ajaxlabel.aspx?action=explaintemplate&skinid="+skinId+"&templatePath="+templatePath,"dragmain");

$main.load(function(){
	
	if(window.location.href.indexOf('isDeBug=1')!=-1){
		isDeBug = 1;
	};
	if(isDeBug==1){
		$('#pageLoad').fadeOut(speed);
	}else{
		$('#pageLoad').show();
	};
	$contents = $(this).contents();

	$contents.find('body').append(appendFile);
	$contents.find('[drag-type="paging"]').each(function() {
        var pagingId = $(this).html().split('PageStr')[1].replace(']','');
		$(this).attr('drag-paging',pagingId);
		var pageStr = PageStrResult(pagingId);
		$(this).html(pageStr);
    });
	
	//可添加模块
	$contents.find('[drag-addModule="true"]').each(function() {
		$(this).addModule({
			mSplit:'no',
		});
		
	});	
	ajaxLoadNum = 0;
	ajaxNum = $contents.find('[drag-render]').length;

	if(ajaxNum==0){
		$('#pageLoad').fadeOut(speed);
	}else{

		//页面字段标签渲染
		$contents.find('[drag-render]').each(function(){
			rendering(this);
		});

	};
	
	loadInt();

});


//解析标签
function rendering(obj,flag){
	var render = $(obj).attr('drag-render').split(' in ');	
	/*
	 *renderingType 渲染类型
	 *——loop 解析页面循环体
	 *——order 解析排序
	 *——filter 解析筛选项
	 *——view 解析内容页字段
	 */
	var renderingType = render[0];
	var moduleName = render[1].split('|')[0].split('.')[0],
		subModuleName =  render[1].split('|')[0].split('.')[1].split('(')[0];
	var labelName = 'none',
		loopNum = 0;
	if(renderingType=='loop'){
		labelName = render[1].split('|')[0].split('.')[1].split('(')[1].split(',')[0];
		loopNum = render[1].split('|')[0].split('.')[1].split('(')[1].split(',')[1].replace(')','');

	}
	var moduleCont = $(obj).html();

	$.post("/plus/ajaxlabel.aspx",{action:"listlabeltype",tp:moduleCont,skinid:skinId,labeltype:renderingType,module:moduleName,submodule:subModuleName,labelname:labelName,num:loopNum},
	function(data){
		try{				
		    $(obj).html(data);
			frames['dragmain'].moduleJs();
			loadInt();	
			ajaxLoadNum++;		
			if(ajaxLoadNum==ajaxNum){
				$('#pageLoad').fadeOut(speed);
			};
			if(flag==true){
				$(obj).animate({opacity:'1'},speed);
			}
		}catch(e){
			
		};
		   
	},"text");
};

//初始化操作
function loadInt(){
	
	$contents.find('.drag-operating,.drag-dashed-line,.drag-setup-btn').remove();
	//可编辑模块
	$contents.find('[drag-type]').each(function(){
		var typeSplit = $(this).attr('drag-type').split(',');
		var type = typeSplit[0];
		//添加操作按钮组
		
		if(!$(this).attr('drag-setDrag')){//检查是否可拖动
			$(this).operating({
				arr:2,
				ys:true,
			});
		}else{
			if($(this).attr('drag-setDrag')=='inner,main'){
				$(this).operating({
					arr:3,
					ys:true,
					style:2
				});
			}else{
				$(this).operating({
					arr:3,
					ys:true,
				});
			}
		};
	    
	});
	
	//可拖动模块
	$contents.find('[drag-setDrag]').each(function() {

		//设置可编辑
		if(!$(this).attr('drag-type')){
			if($(this).attr('drag-setDrag')=='inner,main'){
				$(this).operating({
					arr:1,
					ys:true,
					style:2
				});
			}else{
				$(this).operating({
					arr:1,
					ys:true
				});
			}
		};
		
		var dragType = $(this).attr('drag-setDrag');
		var parent = $(this).attr('drag-parent');
		$(this).setDrag({
			type:dragType,
			parent:parent,
		});
		
	});
	
	//小模块设置  导航、搜索等
	$contents.find('[drag-setup]').each(function() {
        $(this).setup();
    });
	
	//屏蔽链接
	$contents.on('click','a',function(){
		return false;
	});
	
};


//网站基本配置、当前模板配置、风格管理、颜色配置窗口
//openSetWindow 打开窗口
//closeSetWindow 关闭窗口

function openSetWindow(obj,url){
	var oldSetWindow = $('#headSetTab').find('.active').index();
	var $this = $(obj);
	var index = $this.index();
	if(index!=oldSetWindow){
		oldSetWindow = index;
		$this.addClass('active').siblings().removeClass('active');
		$('.pageLeft-set').find('iframe').remove();
		$('.pageLeft-set').append('<iframe src="'+url+'"></iframe>')
		$('.pageLeft-set').show().animate({left:0},300);
	};
	
};

function closeSetWindow(){
	var setWidth = $('.pageLeft-set').outerWidth();
	$('.pageLeft-set').animate({left:'-'+setWidth+'px'},300);
	$('#headSetTab').find('span').removeClass('active')
	setTimeout(function(){
		$('.pageLeft-set').hide();
	},300);
	
};

//关闭样式编辑窗口
function closeStyle(){
	$moduleObject.prev('.drag-moduleBoxBg').fadeOut(speed);
	setTimeout(function(){
		$moduleObject.parent().prev('.drag-moduleBoxBg').remove();
	},speed);
	$moduleObject.removeClass('drag-z-index');
	var boxLeft = $realTimeBox[0].style.left;
	var boxRight = $realTimeBox[0].style.right;
	if(boxLeft=='auto'){
		$realTimeBox.animate({right:'-320px'},speed);
		setTimeout(function(){
			$realTimeBox.hide();
		},speed);
	}else{
		$realTimeBox.animate({left:'-320px'},speed);
		setTimeout(function(){
			$realTimeBox.hide();
		},speed);
	};

};

//返回标签数据
function LabelBack(labelName,windowName,labelType){
	if (labelType==undefined){
	  labelType=2;
	}
	$.ajax({
		url:"/plus/AjaxLabel.aspx?action=explainlabel&labeltype="+labelType+"&skinId="+skinId+"&labelId="+escape(labelName),
		success:function(LabelContent){

			//添加标签
			if(labelState==0){
				try{					
					if(LabelContent.indexOf('drag-carousel=')!=-1){
						
						//轮播图标签
						if(addState==true){
							$moduleObject.before('<div drag-type="label" drag-setDrag="inner,sub">\n'+
											 '	<div drag-module="content">\n'+
											 '		<div class="draglabel" labelname="'+labelName+'">\n'+
											 '		'+LabelContent+'\n'+
											 '		</div>\n'+
											 '	</div>\n'+
											 '</div>\n');

							var obj = $moduleObject.prev().find('[drag-carousel]');

							//删除分割按钮
							$moduleObject.parent().find('.drag-split-btn,.drag-format-close').remove();

							closeModuleBg();

      					}else{

      						var appendContent = '<div drag-type="label" drag-setDrag="inner,main">\n'+
											 	'	<div drag-module="content">\n'+
											 	'		<div class="draglabel" labelname="'+labelName+'">\n'+
											 	'		'+LabelContent+'\n'+
											 	'		</div>\n'+
											 	'	</div>\n'+
											 	'</div>\n';

							appendToLastTarget(appendContent,true);

							var obj = $moduleObject.find('[drag-carousel]');

      					}
      					
      					frames['dragmain'].carouseJs(obj);
						
					}else{
						
						if(addState==true){
							$moduleObject.before('<div drag-type="label" drag-setDrag="inner,sub">\n'+
												 '	<div class="m-title1" drag-module="title"><span>标签</span></div>\n'+
												 '	<div drag-module="content">\n'+
												 '		<div class="draglabel" labelname="'+labelName+'">\n'+
											  	 '		'+LabelContent+'\n'+
											     '		</div>\n'+
												 '	</div>\n'+
												 '</div>\n');
							
							$moduleObject = $moduleObject.prev();
							
							//删除分割按钮
							$moduleObject.parent().find('.drag-split-btn,.drag-format-close').remove();

							closeModuleBg();

						}else{
							
							var appendContent = '<div drag-type="label" drag-setDrag="inner,main">\n'+
												'	<div class="mainBox">\n'+
												'		<div class="m-title1" drag-module="title"><span>标签</span></div>\n'+
												'		<div drag-module="content">\n'+
												'			<div class="draglabel" labelname="'+labelName+'">\n'+
											  	'			'+LabelContent+'\n'+
											    '			</div>\n'+
												'		</div>\n'+
												'	</div>\n'+
												'</div>\n';
							
							appendToLastTarget(appendContent,true);
							
						}

					}

				}catch(e){
					
				}

				
				loadInt();

				popup.tips({
					  title:'添加成功',
				});

				
				scrollToObjLocation();
			
			//修改标签
			}else if(labelState==1){
				
				try{
					$moduleObject.find('.draglabel').first().html(LabelContent);
					if(LabelContent.indexOf('drag-carousel=')!=-1){
					 	frames['dragmain'].carouseJs($moduleObject.find('[drag-carousel]'));
					};

				}catch(e){
					
				}

				popup.tips({
					  title:'修改成功',
				});

			};
			
			frames['dragmain'].moduleJs();
			
			closeWindow(windowName);
			
		}
	});
					
};

//将内容写入页面最底部
function appendToLastTarget(content,setModuleObject){
	$contents.find('#dragConfig').prev().after(content);
	if(setModuleObject==true){
		//设置为操作对象
		$moduleObject = $contents.find('#dragConfig').prev();
	}
};

//模块返回结果
function ModuleBack(result,type){
	  if(type=='format'){

	  	appendToLastTarget(result,true);

		setFormatSplit($moduleObject);
	
		scrollToObjLocation();
		loadInt();
		  
		 
	 }else if(type=='formatSplit'){
		 
		 //拆分
		$moduleObject.before(result);
		
		setFormatSplit($moduleObject.parent());
  			
		$moduleObject.remove();
		
		 
	 }else if(type=='html'){
		  
		  if(addState==true){
			  $moduleObject.before('<div drag-type="html" drag-setDrag="inner,sub">\n'+
								   '	<div drag-module="content">\n'+
								   '		'+result+'\n'+
								   '	</div>\n'+
								   '</div>');
			  $moduleObject.find('.drag-split-btn').remove();
			  
		  }else{

		  	  var htmlResult = '<div drag-type="html" drag-setDrag="inner,main">\n'+
		  	  				   '	<div class="mainBox">\n'+
							   '		<div drag-module="content">\n'+
							   '			'+result+'\n'+
							   '		</div>\n'+
							   '	</div>'+
							   '</div>'

		  		appendToLastTarget(htmlResult,true);

		  };
		  scrollToObjLocation();
		  loadInt();
		  
	 }else if(type=='editHtml'){
	 	$moduleObject.find('[drag-module="content"]').html(result);
		
	 //标题	
	 }else if(type=='editLabelCode'){
	 	$moduleObject.css('opacity','0').html(result)
	 	rendering($moduleObject,true);
	 };
	
};

//处理头、底静态标签
var staticLabel = {
	//添加
	Add:function(result,labelName,windowName,type){

		var labelContent = '<div class="clearfix" drag-type="'+type+'" drag-setdrag="inner,main">\n'+
							 '	<div class="draglabel" labelname="{KS_'+labelName+'}">\n'+result+'</div>\n'+
							 '<div>';
		if(type=='header'){
			$contents.find('body').prepend(labelContent);
			scrollToObjLocation('top');
			frames['dragmain'].headLoadJs();
		}else if(type=='footer'){
			appendToLastTarget(labelContent);
			scrollToObjLocation('bottom');
		};
		loadInt();
		closeWindow(windowName); //关闭当前窗口
	},
	//编辑版式，监听颜色实时预览
	Edit:function(color,type){
		var $module = $moduleObject.find('['+type+'-id]');
		var moduleClass = $module[0].className.split(' ');
		for(var i in moduleClass){
			if(moduleClass[i].indexOf('m-bg-')!=-1){
				$module.removeClass(moduleClass[i]);
			}
		};
		$module.addClass('m-bg-'+color);
	},
	//保存
	Save:function(labelName,windowName){
		$moduleObject.find('.draglabel').clearDrag();
		var labelContent = $moduleObject.find('.draglabel').html();
		$.post("/plus/AjaxLabel.aspx?flag=modify", { labelname: labelName, labelcontent: labelContent, action: "savelabel", skinid: skinId },function (data) {
            if(data == 'success') {
				popup.tips({
					  title:'保存成功',
			   	});
			
			    loadInt();
			    closeWindow(windowName); //关闭当前窗口
				frames['dragmain'].headLoadJs();

            }else {
				parent.popup.tips({
					title:data,
				});
            };

        }, "text");

	},
	//选择现有标签插入
	Insert:function(labelName,windowName,type){
		$.ajax({
			url:"/plus/AjaxLabel.aspx?action=explainlabel&labeltype=4&skinId="+skinId+"&labelId="+escape(labelName),success:function(LabelContent){
				
				var labelContent = '<div class="clearfix" drag-type="'+type+'" drag-setdrag="inner,main">\n'+
						 '	<div class="draglabel" labelname="{KS_'+labelName+'}">\n'+LabelContent+'</div>\n'+
						 '<div>';
				if(type=='header'){
					$contents.find('body').prepend(labelContent);
					scrollToObjLocation('top');
					frames['dragmain'].headLoadJs();
				}else if(type=='footer'){
					appendToLastTarget(labelContent);
					scrollToObjLocation('bottom');
					
				}
				
				loadInt();
				closeWindow(windowName);
		
			}
		});
		
	}
};


//设置版式分割
function setFormatSplit(target){
	target.find('.drag-addModule,.drag-dashed-line').remove();
	target.find('[drag-addModule="true"]').each(function() {
		$(this).addModule({
			 mSplit:'yes',
		});
	});
};

//删除版式
function closeFormat(obj){
	var $format = $(obj).parents('[drag-format]').first();
	var formatNumber = parseInt($format[0].className.split('col-')[1]); //get format class name
	var $parentFormat = $format.parent();
	var parentNumber = parseInt($parentFormat[0].className.split('col-')[1]); //get parent format class name
	var $siblings = $format.siblings('[drag-format="sub"]');
	var siblingsLength = $siblings.length;
	if($parentFormat.attr('drag-format')=='main'&&siblingsLength==0){
		$parentFormat.parent().remove();//满足条件则删除整个版式
	}else{

		if(formatNumber==12){				
			if(siblingsLength<=1&&$parentFormat.attr('drag-format')!='main'){
				$parentFormat.html($siblings.html());
				setFormatSplit($parentFormat);

			}else{
				$format.remove();
			}
			
		}else{

			if(siblingsLength<=1&&$parentFormat.attr('drag-format')!='main'){
				$parentFormat.html($siblings.html());
				setFormatSplit($parentFormat);
			}else{

				$siblings.each(function(){
					var thisNumber = parseInt(this.className.split('col-')[1]);
					var averageValue = Math.ceil(formatNumber/siblingsLength); //获取平均值
					thisNumber+=averageValue;

					formatNumber-=averageValue;
					siblingsLength--;
					$(this).attr('class','col-'+thisNumber+' clearfix');
					
				});

				$format.remove();

			};

		};
		
		
	};

};

//关闭左侧
function closeLeft(obj){
	
	if($(obj).html().indexOf('drag-i-left')!=-1){
		$(obj).addClass('btn-close-on');
		$(obj).html('<i class="drag-font drag-i-right"></i>');
		$('#pageLeft').animate({left:'-200px'},speed);
		$('.wraper').animate({paddingLeft:0},speed);

	}else{
		$(obj).removeClass('btn-close-on');
		$(obj).html('<i class="drag-font drag-i-left"></i>');
		$('#pageLeft').animate({left:'0px'},speed);
		$('.wraper').animate({paddingLeft:'200px'},speed);
	}
};

//滚动至target位置
function scrollToObjLocation(type,errorValue){
	var objOffsetTop = 0;
	if(type=='bottom'){
		objOffsetTop = $contents.find('body')[0].scrollHeight;
	}else if(type=='top'){
		objOffsetTop = 0
	}else{
		objOffsetTop = $moduleObject.offset().top;
		if(errorValue){
			objOffsetTop-=errorValue;
		}
	}
	$contents.find('body,html').animate({scrollTop:objOffsetTop},speed);
};

//关闭样式编辑模块遮罩层
function closeModuleBg(obj){

	$contents.find('.drag-addModule-tips').remove();
	$contents.find('.drag-moduleBoxBg').fadeOut(speed);
	setTimeout(function(){
		$(obj).remove();
	},speed);
	addState = false;
	
	$('#leftTab').find('li').removeClass('disabled');

};


//关闭弹出层
function closeWindow(name){
	closePopup(name);
};

var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
/*RGB颜色转换为16进制*/
String.prototype.colorHex = function(){
	 var that = this;
	 if(/^(rgb|RGB)/.test(that)){
		  var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(",");
		  var strHex = "#";
		  for(var i=0; i<aColor.length; i++){
			   var hex = Number(aColor[i]).toString(16);
			   if(hex === "0"){
					hex += hex;    
			   }
			   strHex += hex;
		  }
		  if(strHex.length !== 7){
			   strHex = that;    
		  }
		  return strHex;
	 }else if(reg.test(that)){
		  var aNum = that.replace(/#/,"").split("");
		  if(aNum.length === 6){
			   return that;    
		  }else if(aNum.length === 3){
			   var numHex = "#";
			   for(var i=0; i<aNum.length; i+=1){
					numHex += (aNum[i]+aNum[i]);
			   }
			   return numHex;
		  }
	 }else{
		  return that;    
	 }
};

//返回16进制颜色
function colorHexBack(value){
	return value.colorHex();
}


// get label name
function draglabel(){
	var labelname = $moduleObject.find('.draglabel').first().attr('labelname');
	return labelname;
};

//分页
function PageStrResult(id){
	if(id==1){
		var pageStr = '<div class="m-paging m-paging1">\n'+
          	  		  '		<div class="m-paging-box">\n'+
          	  		  '			<a href="javascript:void(0);">首页</a>\n'+
          	  		  '			<a href="javascript:void(0);">上一页</a>\n'+
          	  		  '			<a href="javascript:void(0);" class="curr">1</a>\n'+
          	  		  '			<a href="javascript:void(0);">2</a>\n'+
          	  		  '			<a href="javascript:void(0);">3</a>\n'+
          	  		  '			<a href="javascript:void(0);">4</a>\n'+
          	  		  '			<a href="javascript:void(0);">5</a>\n'+
          	  		  '			<a href="javascript:void(0);">下一页</a>\n'+
          	  		  '			<a href="javascript:void(0);">末页</a>\n'+
          	  		  '		</div>\n'+
          	  		  '</div>';
	}else if(id==2){
		var pageStr = '<div class="m-paging m-paging2">\n'+
          	  		  '		<div class="m-paging-box">\n'+
          	  		  '			<a href="javascript:void(0);"><i class="modulefont m-icon-left"></i></a>\n'+
          	  		  '			<a href="javascript:void(0);" class="curr">1</a>\n'+
          	  		  '			<a href="javascript:void(0);">2</a>\n'+
          	  		  '			<a href="javascript:void(0);">3</a>\n'+
          	  		  '			<a href="javascript:void(0);">4</a>\n'+
          	  		  '			<a href="javascript:void(0);">5</a>\n'+
          	  		  '			<a href="javascript:void(0);"><i class="modulefont m-icon-right"></i></a>\n'+
          	  		  '		</div>\n'+
          	  		  '</div>';
	}else if(id==3){
		var pageStr = '<div class="m-paging m-paging3">\n'+
          	  		  '		<div class="m-paging-box">\n'+
          	  		  '			<a href="javascript:void(0);"><i class="m-paging-icon-first"></i>首页</a>\n'+
					  '			<a href="javascript:void(0);"><i class="m-paging-icon-prev"></i>上一页</a>\n'+
          	  		  '			<a href="javascript:void(0);" class="curr">1</a>\n'+
          	  		  '			<a href="javascript:void(0);">2</a>\n'+
          	  		  '			<a href="javascript:void(0);">3</a>\n'+
          	  		  '			<a href="javascript:void(0);">4</a>\n'+
          	  		  '			<a href="javascript:void(0);">5</a>\n'+
          	  		  '			<a href="javascript:void(0);">下一页<i class="m-paging-icon-next"></i></a>\n'+
          	  		  '			<a href="javascript:void(0);">末页<i class="m-paging-icon-last"></i></a>\n'+
          	  		  '		</div>\n'+
          	  		  '</div>';
	}else if(id==4){
		var pageStr = '<div class="m-paging m-paging4">\n'+
        			  '		<div class="m-paging-box">\n'+
        			  '			<a href="javascript:void(0);">首页</a>\n'+
        			  '			<a href="javascript:void(0);">上一页</a>\n'+
        			  '			<span class="m-paging-span">1/5\n'+
        			  '				<div class="m-paging-select">\n'+
        			  '					<a href="javascript:void(0);">1</a>\n'+
        			  '					<a href="javascript:void(0);">2</a>\n'+
        			  '					<a href="javascript:void(0);">3</a>\n'+
        			  '					<a href="javascript:void(0);">4</a>\n'+
        			  '					<a href="javascript:void(0);">5</a>\n'+
        			  '				</div>\n'+
        			  '			</span>\n'+
        			  '			<a href="javascript:void(0);">下一页</a>\n'+
        			  '			<a href="javascript:void(0);">末页</a>\n'+
        			  '		</div>\n'+
        			  '</div>'
	}else if(id==5){
		var pageStr = '<div class="m-paging m-paging5">\n'+
          	  		  '		<div class="m-paging-box">\n'+
          	  		  '			<a href="javascript:void(0);"><i class="modulefont m-icon-arrow-left"></i></a>\n'+
          	  		  '			<a href="javascript:void(0);" class="curr">1</a>\n'+
          	  		  '			<a href="javascript:void(0);">2</a>\n'+
          	  		  '			<a href="javascript:void(0);">3</a>\n'+
          	  		  '			<a href="javascript:void(0);">4</a>\n'+
          	  		  '			<a href="javascript:void(0);">5</a>\n'+
          	  		  '			<a href="javascript:void(0);"><i class="modulefont m-icon-back"></i></a>\n'+
          	  		  '		</div>\n'+
          	  		  '</div>';
	};
	return pageStr;
};
//预览
function pagePreview(){
	if(tpType!='home'){
		$('.head-preview').fadeToggle(300);
		var modelid=-1;
		switch(tpType){
			case "courselist":
			  modelid=-1;
			  break;
			case "livelist":
			  modelid=-2;
			  break;
			case "facelist":
			  modelid=-3;
			  break;
		}
		$.post("/plus/AjaxLabel.aspx",{action:"navclasslist",flag:"preview",modelid:modelid},
		function(data){
			   
			   $("#previewItem").append(data).find("li").click(function(){
	                 window.open($(this).attr("url"));
				});
			   
		},"text");

	}else{
		window.open('/');
	};
	
};


//保存
function saveThisPage(){

	$contents.clearDrag();
	
	//将已渲染的数据替换为未解析的代码
	$contents.find('.label_data').each(function() {
        var labelData = $(this).html();
		$(this).parent().html(labelData);
		
    });

	//标签替换
    $contents.find('.draglabel').each(function() {
        var labelName = $(this).attr('labelname');
        if(labelName){
        	this.outerHTML = labelName;
        };
       
    });
	
	//分页替换
	$contents.find('[drag-type="paging"]').each(function() {
		var pagingId = $(this).attr('drag-paging');
		$(this).html('[KS:PageStr'+pagingId+']');
	});
	
	//部分SQL标签带参数，如果参数解析出错，则需要特殊处理
	// $contents.find('[drag-sql]').each(function() {
	// 	var sqlName = '{SQL_'+$(this).attr('drag-sql').split(' and ')[0];
	// 	var sqlParameter = $(this).attr('drag-sql').split(' and ')[1].split(',');
	// 	var newParameter = $.map(sqlParameter,function(text){
	// 		if(text.indexOf('KS')!=-1){
	// 			text = '{'+text+'}'
	// 		}
	// 		return text;
	// 	});
	// 	newParameter = newParameter.join(',')
	// 	$(this).html(sqlName+'('+newParameter+')}');
	// });

	//删除标记的内容
	$contents.find('[drag-savedelete]').remove();

	//获取页面HTML
	var pageHtml = '<!DOCTYPE html>\n'+$contents[0].all[0].outerHTML.replace(appendFile,'');
	var pageDragConfigJs = frames['dragmain'].dragConfigJs;
	if(pageDragConfigJs){
		pageHtml = pageHtml.replace(pageDragConfigJs,'');
	}
	
	pageHtml = pageHtml.replace(new RegExp(tpDir,"gm"),"{$GetTemplateDir}");
	pageHtml = pageHtml.replace(new RegExp("&amp;","gm"),"&");

	//保存
	$.post("/plus/AjaxLabel.aspx",{content:pageHtml,action:"savetemplate",skinid:skinId,templatePath:templatePath},
	function(data){
		   
		   if(data=='success'){
				popup.tips({
					  title:'保存成功',
				});
		   		window.location.reload();
	   };
		   
	},"text");
	
	
	
};



