/*!
 * kesion.drag.js
 * 2017-4-25 v1.0 by zhuang
 * 厦门科汛软件有限公司　 版权所有 © 2006-2017
 * 官方地址：http://www.kesion.com
 * 
 * 24小时服务热线：400-008-0263
 * 
 */

var box=null;
var isreload=false;
function openWin(title,url,reload,width,height){ 
      if (width==null) width=760;
      if (height == null) height = 450;
	  isreload=reload;
	  box=$.dialog.open(url,{ id:'topbox',lock: true, title: title, width: width, height: height, close: function() {
       if (isreload) {
          top.frames['dragmain'].location.reload();
        }
      }
   });
};

var $contents = $(top.frames['dragmain'].document);

//禁止浏览器的图片默认拖动事件
var $img = $contents.find("img");
var moving = function(event){
	//something
};

//IE下需要在document的mousemove里面取消默认事件;要用原生JS的事件不能用JQuery
$contents[0].onmousemove = function(e){
	var ev = e || event;
	ev.cancelBubble=true;
	ev.returnValue = false;
}

$img.mousedown(function(event){
	//FF下需要在mousedown取消默认操作;
	event.preventDefault();
	event.stopPropagation();
	$(this).bind("mousemove",moving);    
	
});


(function ($) {
	
	$.fn.setup = function(options){
		$(this).append('<div class="drag-setup-btn" onClick="parent.Drag.Setup(this)"><i class="drag-font drag-i-pen"></i></div>');
		if($(this).css('position')=='static'){
			$(this).addClass('drag-relative');
		};
	};
	
	$.fn.addModule = function(options){
		var mSplit = options.mSplit||'';
		
		if(mSplit=='no'){
			$(this).append('<div class="drag-addModule"><span onClick="parent.Drag.Add(this)">添加模块</span></div>');
		
		}else{
			$(this).append('<div class="drag-addModule"><div class="drag-format-close" onClick="parent.closeFormat(this)"></div><span onClick="parent.Drag.Add(this)">添加模块</span><span class="drag-split-btn" onClick="parent.Drag.Split(this)">拆分</span></div>');
		}
		$(this).mousemove(function(){
			  $(this).find('.drag-format-close:last').show();
		}).mouseout(function(){
			  $(this).find('.drag-format-close:last').hide();
		});

		if($(this).css('position')=='static'){
			$(this).addClass('drag-relative');
		};

	};
	
	$.fn.operating = function(options){
		 var arr = options.arr;
		 var ys = options.ys;
		 var style = '';
		 if(options.style==2){
		 	 style = ' drag-operating2';
		 }
		 var styleSpan = '';
		 if(ys==true){
		 	styleSpan = '<span onClick="parent.Drag.Style(this)"><i class="drag-font drag-i-style1"></i></span>'
		 };
		 
		 if(arr==1){
			 $(this).append('<div class="drag-operating'+style+'">'+
			 					'<span class="drag-td"><i class="drag-font drag-i-drag"></i></span>'+
								''+styleSpan+''+
								'<span onClick="parent.Drag.Delete(this)"><i class="drag-font drag-i-del"></i></span>'+
							'</div>');

		 }else if(arr==2){
			 $(this).append('<div class="drag-operating'+style+'">'+
			 					'<span onClick="parent.Drag.Edit(this)"><i class="drag-font drag-i-edit"></i></span>'+
								''+styleSpan+''+
								'<span onClick="parent.Drag.Delete(this)"><i class="drag-font drag-i-del"></i></span>'+
								'</div>');

		 }else if(arr==3){
			 $(this).append('<div class="drag-operating'+style+'">'+
			 					'<span class="drag-td"><i class="drag-font drag-i-drag"></i></span>'+
								'<span onClick="parent.Drag.Edit(this)"><i class="drag-font drag-i-edit"></i></span>'+
								''+styleSpan+''+
								'<span onClick="parent.Drag.Delete(this)"><i class="drag-font drag-i-del"></i></span>'+
							'</div>');
		 	
		 };
		 
		 $(this).append('<div class="drag-dashed-line"><i class="ddl-l"></i><i class="ddl-r"></i><i class="ddl-t"></i><i class="ddl-b"></i></div>');
		 
		$(this).mouseover(function(){
			$(this).find('.drag-operating:last,.drag-dashed-line:last').show();
		});
		$(this).mouseout(function(){
			$(this).find('.drag-operating:last,.drag-dashed-line:last').hide();
		});

		if($(this).css('position')=='static'){
			$(this).addClass('drag-relative');
		};
		

	};
	//清除拖拽操做多出的代码  用于保存
	$.fn.clearDrag = function(options){
		var $t = $(this);
		$t.find('.drag-operating,.drag-dashed-line,.drag-addModule,.drag-setup-btn').remove();
		$t.find('.drag-relative').each(function(){
			if($(this).attr('class')=='drag-relative'){
				$(this).removeAttr('class');
			}else{
				$(this).removeClass('drag-relative');
			};
		});
		
	};
		
	$.fn.setDrag = function(options){
		
		var $t = $(this);
		var doc = $contents[0];
		
		var dragType = options.type;
		var type = dragType.split(',')[0];
		var parent = options.parent;
		var flag = false;//拖动开关
		var offsetX = $t.offset().left;
		var offsetY = $t.offset().top;
		var pageX;
		var pageY;
		var $this;//操作对象						
		
		if(type=='innerAny'){
			var $parent;//父节点
			if(parent==undefined){
				$parent = $t.parent();
			}else{
				$parent = $t.parents('[drag-id='+parent+']');
				//检测是否有父节点
				if($parent.size()==0){
					if($t.find('.drag-operating').last().size()>0){
						var errorText = $t[0].outerHTML.replace(''+$t.find('.drag-operating').last()[0].outerHTML+'','');
						console.error('检测到父节点id:"'+parent+'"未找到，具体位置：'+errorText+'');
						
					}else{
						console.error('检测到父节点id:"'+parent+'"未找到，具体位置：'+$t[0].outerHTML+'');	
					};
					
					console.warn('已自动设置默认父节点');
					$parent = $t.parent();
					
				};
			};
			
			if($parent.css('position')=='static'){
				$parent.css({position:'relative'});
			};
			if($t.css('position')=='fixed'){
			
				if($t.find('.drag-operating').last().size()>0){
					var errorText = $t[0].outerHTML.replace(''+$t.find('.drag-operating').last()[0].outerHTML+'','');
					console.error('innerAny属性不支持position设置为fixed，具体位置：'+errorText+'');
					
				}else{
					console.error('innerAny属性不支持position设置为fixed，具体位置：'+$t[0].outerHTML+'');
				};
				
				console.warn('已自动将position设置为absolute');
				$t.css({position:'absolute'});
			};
			
			var parentOffsetX = $parent.offset().left;
			var parentOffsetY = $parent.offset().top;
			var minLeft = -(offsetX-parentOffsetX-$parent.css('border-left-width').replace('px',''));
			var maxLeft = parentOffsetX+$parent.outerWidth()-offsetX-$t.outerWidth()-$parent.css('border-right-width').replace('px','');
			var minTop = -(offsetY-parentOffsetY-$parent.css('border-top-width').replace('px',''));
			var maxTop = parentOffsetY+$parent.outerHeight()-offsetY-$t.outerHeight()-$parent.css('border-bottom-width').replace('px','');
			if($t.css('position')=='absolute'){
				var tMarginLeft = $t.css('marginLeft').replace('px','');
				var tMarginTop = $t.css('marginTop').replace('px','');
				if(tMarginLeft=='auto'){
					marginLeft = 0;
				};
				if(tMarginTop=='auto'){
					marginLeft = 0;
				};
				minLeft = 0 - Number(tMarginLeft);
				maxLeft = maxLeft+Number(tMarginLeft);
				minTop = 0 - Number(tMarginTop);
				maxTop = maxTop+Number(tMarginTop);
			
			};

		};
		
		
		if(type=='any'||type=='innerAny'){
			
			var posLeft = $t.position().left;
			var cssLeft = $t.css('left');
			var posTop = $t.position().top;
			var cssTop = $t.css('top');
			
			if(cssLeft=='auto'){
				if($t.css('position')=='absolute'||$t.css('position')=='fixed'){
					
					$t.css({left:posLeft});
					
				}else if($t.css('position')=='static'){
					
					$t.css({position:'relative',left:'0'});
					
				}else if($t.css('position')=='relative'){
					
					$t.css({left:'0'});
					
				};
			}else{
				$t.css({left:cssLeft});
			};
			
			if(cssTop=='auto'){
				if($t.css('position')=='absolute'||$t.css('position')=='fixed'){
					
					$t.css({top:posTop});
					
				}else if($t.css('position')=='static'){
					
					$t.css({position:'relative',top:'0'});
					
				}else if($t.css('position')=='relative'){
					
					$t.css({top:'0'});
					
				};
			}else{
				$t.css({top:cssTop});
			};
			
			
			$t.find('.drag-operating:last .drag-td').mousedown(function(e){
				
				$this = $t;
				flag = true;//标记为可拖动
				cssLeft = Number($t.css('left').replace('px',''));
				cssTop = Number($t.css('top').replace('px',''));
				$t.css({left:cssLeft,top:cssTop});
				pageX = e.pageX;
				pageY = e.pageY;
				
			  
			});
			
			  //开始拖动
			  $(doc).mousemove(function(e){	
			  	  
				  if(flag==true){
					
				    X = e.pageX-pageX;
					
					if(X<=0){
						//向左移动
						X = cssLeft-(-X);
						if(type=='innerAny'){
							X = Math.max(X,minLeft)
						};
					}else{
						//向右移动
						X = cssLeft+X;
						if(type=='innerAny'){
							X = Math.min(X,maxLeft)
						};
					};
					
					Y = e.pageY-pageY;
					
					if(Y<=0){
						//向上移动
						Y = cssTop-(-Y);
						if(type=='innerAny'){
							Y = Math.max(Y,minTop)
						};
					}else{
						//向下移动
						Y = cssTop+Y;
						if(type=='innerAny'){
							Y = Math.min(Y,maxTop)
						};
					};
					
					
					$t.css({left:X,top:Y});
					
				  };
				  
			  });
			  
			  
			  $(doc).mouseup(function(e){
				  flag = false;//标记为不可拖动
				  if($this){
					  cssLeft = Number($this.css('left').replace('px',''));
					  cssTop = Number($this.css('top').replace('px',''));
					  
					  $this = 0;//重置$this
				  };
				
			  });
			
		}else if(type=='inner'){//相同类名 任意拖拽
		
			  var $dragEmptyBox;
			  var $dragBoxWrap;
			  var $dragMark;//标记
			  var wrapPosLeft;
			  var wrapPosTop;
			  var originalHeight;
			  
			  var clientX; 
			  var clientY;
			  $t.find('.drag-operating:last .drag-td').mousedown(function(e){
				  
				  clientX = e.clientX;
				  clientY = e.clientY;
				  $this = $t; //由于下面的document事件得不到当前$t的值，所以需要新建this对象
				  flag = true;
				  dragType = $t.attr('drag-setDrag');
				  
				  var tWidth = $t.outerWidth()-2;
				  var tHeight = $t.outerHeight()-2;
				  var tFloat = $t.css('float');
				  var tMargin = $t.css('margin');
				  $t.wrap('<div id="dragBoxWrap"></div>');
				  $dragBoxWrap = $t.parent();
				  $dragBoxWrap.before('<div id="dragMark" style="display:none;"></div>');
				  $dragMark = $dragBoxWrap.prev();
				  
				  $dragMark.before('<div id="dragEmptyBox"><span>放在这里</span></div>');
				  $dragEmptyBox = $dragMark.prev();
				  
				  var axis = dragType.split(',')[2];
				  
				  if(axis=='x'||axis=='X'){
				  	  $dragEmptyBox.attr('style','width:'+tWidth+'px;height:'+tHeight+'px;float:'+tFloat+';margin:'+tMargin+';');
				  }else{
					  originalHeight = Math.min(tHeight,160);
				  	  $dragEmptyBox.attr('style','height:'+originalHeight+'px;');
				  };
				  
				  wrapPosLeft = clientX-30;
				  wrapPosTop = clientY-30;
				   				   
				  $dragBoxWrap.css({left:wrapPosLeft,top:wrapPosTop});
				  
				  //检测是否有兄弟级
				  if($dragBoxWrap.siblings('[drag-setDrag="'+dragType+'"]').size()==0){
				  	 $dragBoxWrap.before('<div class="dragInitialCont" drag-setDrag="'+dragType+'">拖动内容放到容器中</div>');//空容器
					 
				  };
				  
					
			  });			  
			   
			  //开始拖动
			  $(doc).mousemove(function(e){
				  
				  if(flag==true){
				  		
						var ePageX = e.pageX;
						var ePageY = e.pageY;
							    
						var eClientX = e.clientX;
					  
						var X = eClientX-clientX;
						
						if(X<=0){
							//向左移动
							X = wrapPosLeft-(-X);
							
						}else{
							//向右移动
							X = wrapPosLeft+X;
							
						};
						
						var eClientY = e.clientY;
						var Y = eClientY-clientY;
						
						if(Y<=0){
							//向上移动
							Y = wrapPosTop-(-Y);
							
						}else{
							//向下移动
							Y = wrapPosTop+Y;
							
						};
						
						$dragBoxWrap.css({left:X,top:Y});

					  var thisDragType = $this.attr('drag-setDrag');
					  $contents.find('[drag-setDrag="'+thisDragType+'"]').not($this).each(function() {
						   var targetX = $(this).offset().left;
						   var targetMaxX = targetX+$(this).outerWidth();
						   var targetY = $(this).offset().top;
						   var targetMaxY = targetY+$(this).outerHeight();
						   
						   if(ePageX>=targetX&&ePageX<=targetMaxX&&ePageY>=targetY&&ePageY<=targetMaxY){
							    if($(this)[0].className=='dragInitialCont'){
									$(this).html('放到该容器中...');
									$dragEmptyBox.addClass('hide');
								}else{		
									$('.dragInitialCont').html('拖动内容放到容器中');
									$dragEmptyBox.removeClass('hide');
								};
								
								var axis = $(this).attr('drag-setDrag').split(',')[2];
								if(axis=='x'||axis=='X'){
									var newWidth = $(this).outerWidth()-2;
									var newHeight = $(this).outerHeight()-2;
									var newFloat = $(this).css('float');
									var newMargin = $(this).css('margin');
									
									$dragEmptyBox.attr('style','width:'+newWidth+'px;height:'+newHeight+'px;float:'+newFloat+';margin:'+newMargin+';');

									if(ePageX>targetX+$(this).outerWidth()/2){
										$dragEmptyBox.insertAfter($(this));
										
									}else{
										$dragEmptyBox.insertBefore($(this));
									};
									
									
								}else{
									$dragEmptyBox.attr('style','height:'+originalHeight+'px;');
									if(ePageY>targetY+$(this).outerHeight()/2){
										$dragEmptyBox.insertAfter($(this));
										
										
									}else{
										$dragEmptyBox.insertBefore($(this));
									};
								};
								//通过$dragEmptyBox的位置判断拖放位置
								
						   }else{
						   		$('.dragInitialCont').html('拖动内容放到容器中');
						   };
						   
						   
						   
                      });
					  
				  };
			  });
			  
			  
			  $(doc).mouseup(function(){
				  
				  flag = false;//标记为不可拖动
				  
				  if($this){
					  
					  var thisDragType = $this.attr('drag-setDrag');
					  $dragEmptyBox.after($this);
					  
					  if($this.siblings('.dragInitialCont[drag-setDrag="'+thisDragType+'"]').size()>0){  //如果还存在空容器，说明最后一个模块没有移动，则删除空容器
						 $this.siblings('.dragInitialCont[drag-setDrag="'+thisDragType+'"]').remove();
					  };
					  
					  $contents.find('.dragInitialCont').show();
					  $dragEmptyBox.remove();
					  $dragBoxWrap.remove();
					  $dragMark.remove();
					  
					  //重置
				  	  $this = 0;
				  };
				  
				  
			  });
			  
			  
		};
		
		
	};
	

	$.fn.stretch = function(){
		var $this = $(this);
		var offsetLeft = $this.offset().left;
		var offsetTop = $this.offset().top;
		var maxLeft  = offsetLeft+$this.outerWidth();
		var maxTop = offsetTop+$this.outerHeight();
		var width = $this.width();
		var height = $this.height();
		var $body = $('body');
		var cursor = $this.css('cursor');
		var error = 6;
		var stretchFlag = false;
		var ePageX;
		var ePageY;
		var type;
		
		$(document).mousemove(function(e){
			var pageX = e.pageX;
			var pageY = e.pageY;
			if(pageX>=offsetLeft&&pageX<=offsetLeft+error||pageX>=maxLeft-error&&pageX<=maxLeft){
				$this.css({cursor:'ew-resize'});
				type = 1;
			}else if(pageY>offsetTop&&pageY<offsetTop+error||pageY>=maxTop-error&&pageY<=maxTop){
				$this.css({cursor:'n-resize'});
			}else if(pageX>=offsetLeft&&pageX<=offsetLeft+error&&pageY>offsetTop&&pageY<offsetTop+error){
				$this.css({cursor:'nwse-resize'});
			}else{
				$this.css({cursor:cursor});
				
			};
			
			if(stretchFlag==true){
				if(type==1){
					result = ePageX-pageX;
					if(result>0){
						result = width+result;
					}else{
						result = Math.max(width-(-result),60);
					};
					$this.width(result)
				};
			};
			
			
		});
		
		$this.mousedown(function(e){
			ePageX = e.pageX;
			ePageY = e.pageY;
			if(type&&type!=0){
				stretchFlag = true;
				
			};
			
			
		});

		$(document).mouseup(function(){
			type=0;
			stretchFlag = false;
		});		
		
		
		
	};
	
	
})(jQuery);


