(function(win,$) {
	
	// 默认来配置
	$.TableView = {
		// 表格宽度
		tableWidth: 200,
		// 表格间间隙
		tableMargin: 30,
		// 表格可视的数据行数（不包括表头）
		visTrNm: 5,
		// 表格行高度
		trHeight: 30,
		// 表头高度
		thHeight: 30
	};
	// 缓存所有表
	$.TableView.tables = {};
	// 记录数据元关联关系(二维数组)，用以判断连线的有效性，
	// 其数据格式为：[["dataset1:meta1","dataset2:meta2"],["dataset3:meta3","dataset2:meta2"],...]
	$.TableView.metas = [];
	// 缓存所有的连线
	$.TableView.lines = {};
	// 线条id计算器
	$.TableView.lineNum = 0;
	
	var winWidth = $(window).width(),
		winHeight = $(window).height();
		
	/* 重新初始化 */
	function reInit() {
			// 当前图表视图容器
		var curTV = $.TableView.curTV,
			// 画布对象
			canvas = curTV.canvas,
			// 获取缓存的初始数据
			data = curTV.data,
			// 获取当前连线结果
			result = curTV.getResult(),
			// 获取当前所有连线关系
			rels = result.lines;
		
		// 重置缓存	
		$.TableView.tables = {};
		$.TableView.metas = [];
		$.TableView.lines = {};
		$.TableView.lineNum = 0;
		
		// 画面清空
		canvas.clear();
		canvas = null;
		curTV.empty();
		$('.u-operator').remove();
		$('.canvas-container').remove();
		
		// 重新获取窗口大小
		winWidth = $(window).width();
		winHeight = $(window).height();
		
		// 初始化
		curTV.init({
			tables: data.tables,
			rels: rels
		});
	}
	
	/* 初始化 */
	function init(data) {

		var self = this,
			tablesData = data.tables,
			relsData = data.rels,
			TV = $.TableView,
			tables = TV.tables,
			winSize = TV.getWinSize(),
			$canvas = $('<canvas id="cvs_table_viewer">');
			$canvas.css({position: 'absolute',top:0,left:0}).attr({width: winSize.width,height: winSize.height});

		
		_.each(tablesData,function(v,k) {
			TV.createTable(self,v,k);
		});

		$(document.body).append($canvas);
		this.canvas = new fabric.Canvas('cvs_table_viewer');
		TV.curTV = this;

		var $fromTr,$toTr;
		_.each(relsData,function(rel) {
			if(tables[rel.from]!=undefined && tables[rel.to]!=undefined){
				$fromTr = tables[rel.from].$node.find('li.u-table-tr[code='+rel.fromPort+']'),
					$toTr = tables[rel.to].$node.find('li.u-table-tr[code='+rel.toPort+']');
				TV.drawLine($fromTr,$toTr);
			}
		});
		
		TV.updateMeta();
		this.canvas.renderAll();
	}
	
	/* 获取连线结果 */
	function getResult() {
		var TV = $.TableView;
		var result = {lines:[],entrances:[]};
		var lines = TV.lines,metas = [];
		result.lines = _.map(lines,function(line) {
			metas.push(line.fromTable+':'+line.fromPort);
			return {
				from: line.fromTable,
				to: line.toTable,
				fromPort: line.fromPort,
				toPort: line.toPort
			}
		});
		// 剔除重复
		metas = _.union(metas);
		metas = _.filter(metas,function(meta) {
			var fromTable = meta.split(':')[0],
				fromPort = meta.split(':')[1],
				$table = TV.tables[fromTable],
				portLines = TV.getPortLines($table,fromPort);
			var isEntrance = true;
			_.each(portLines,function(pl){
				if(pl.fromTable!==fromTable) {
					isEntrance = false;
				}
			});
			return isEntrance;
		});
		result.entrances = _.map(metas,function(meta) {
			return {
				dataSet: meta.split(':')[0],
				meta: meta.split(':')[1]
			}
		});
		
		return result;	
	}
	 //旋转坐标
	$.TableView.scrollXOY = function(p,theta){
	  return {
	   x:p.x*Math.cos(theta)+p.y*Math.sin(theta),
	   y:p.y*Math.cos(theta)-p.x*Math.sin(theta)
	  };
	 };
	
	/* 判断指定的起始点与终点是否已经有连线 */ 
	$.TableView.hasLine = function($from, $to) {
		var fromTable = $from.closest('ul').attr('code'),
			$fromTable = $.TableView.tables[fromTable],
			fromPort = $from.attr('code'),
			toPort = $to.attr('code'),
			lines = $.TableView.lines;
		var line = _.find($fromTable.lines,function(id) {
			var l = lines[id];
			return (l.fromPort === toPort&& l.toPort=== fromPort) 
			|| (l.fromPort === fromPort&& l.toPort=== toPort) ;
		});
		return line!==undefined;
	};

	/* 获取所有指定行的关联线条 */
	$.TableView.getPortLines = function(table, port) {
		var lines = $.TableView.lines;
		var lineArr = _.filter(table.lines,function(id){
			var line = lines[id];
			return line['fromPort'] === port || line['toPort']===port;
		});
		return _.map(lineArr,function(id) {
			return lines[id];
		});
	};
	
	/* 创建箭头 */
	$.TableView.newArrow = function(line) {
		var tv = $.TableView.curTV,
			canvas = tv.canvas,
			pn = line.points.length,
			sp = line.points[pn-2],
			ep = line.points[pn-1];
		
		var theta= Math.atan((ep.x-sp.x)/(ep.y-sp.y));
		var cep= this.scrollXOY(ep,-theta);
		var csp= this.scrollXOY(sp,-theta);
		var ch1={x:0,y:0};
		var ch2={x:0,y:0};
		var l=(cep.y-csp.y)<0? -5: 5;
		
		ch1.x=cep.x+l;
		ch1.y=cep.y-l;
		ch2.x=cep.x-l;
		ch2.y=cep.y-l;
		var h1= this.scrollXOY(ch1,theta);
		var h2= this.scrollXOY(ch2,theta);

		var polyLine = new fabric.Polyline([
				h1,
				ep,
				h2
			  ],{stroke: '#3FA08E',fill:'#3FA08E'});
		polyLine.selectable  = false;
		
		return polyLine;
	}
	
	/* 创建线条 */
	$.TableView.newLine = function(coords,l1,l2) {

		var x1 = coords[0],
			y1 = coords[1],
			x2 = coords[2],
			y2 = coords[3];
			
		var polyLine;
		if(x1<=x2) {
			var ex = l1*5,
				p1 = {x: x1-2, y: y1},
				p2 = {x: (x1+x2)/2 +ex, y: y1},
				p3 = {x: (x1+x2)/2 +ex, y: y2},
				p4 = {x: x2, y: y2};
			polyLine = new fabric.Polyline([p1,p2,p3,p4],{stroke: '#3FA08E',fill:'transparent'});
		} else {
			var ex  = 20+l1*5, 
				p1 = {x: x1-2, y: y1},
				p2 = {x: x1+ex, y: y1},
				p3 = {x: x1+ex, y: (y1+y2)/2},
				p4 = {x: x2-ex, y: (y1+y2)/2},
				p5 = {x: x2-ex, y: y2},
				p6 = {x: x2, y: y2};
			polyLine = new fabric.Polyline([p1,p2,p3,p4,p5,p6],{stroke: '#3FA08E',fill:'transparent'});
		}
		polyLine.selectable  = false;

		return polyLine;
	};

	/* 画线 */
	$.TableView.drawLine = function($from,$to) {
		var tv = $.TableView.curTV,
			coords = this.getCoords($from,$to),
			overScope = coords.overScope,
			line = this.newLine(coords,$from.index(),$to.index()),
			arrow = this.newArrow(line),
			$fromTable = $from.closest('ul'),
			$toTable = $to.closest('ul');
		var id = ++$.TableView.lineNum;
		$.extend(line,{
			// 线条id
			id:id,
			// 起始表格code
			fromTable: $fromTable.attr('code'),
			// 终止表格code
			toTable: $toTable.attr('code'),
			// 起始行
			fromPort: $from.attr('code'),
			// 终止行
			toPort: $to.attr('code')
		});

		tv.canvas.add(line);
		tv.canvas.add(arrow);
		// 缓存线条附属的箭头
		line.arrow = arrow;
		
		// 添加选中按钮
		var $operator = $('<div class="u-operator">').css({
			position: 'absolute',
			left: (coords[0]+coords[2])/2 - 15 + $from.index()*5,
			top: (coords[1]+coords[3])/2 - 10 ,
			'z-index':1
		}).attr('lineid',line.id).text('选中');
		$(document.body).append($operator);
		
		// 如果经过表格滚动条滚动之后线条超出表格显示范围时，设置线条透明度
		if(overScope) {
			line.setOpacity(0.3);
			arrow.setOpacity(0.3);
			$operator.css('opacity',0.5);
		}
		
		// 立即渲染画布中所有对象
		tv.canvas.renderAll();
		
		// 记录线条
		$.TableView.lines[id] = line;
		// 关联起始位置表格与其附属的线条
		$.TableView.tables[$fromTable.attr('code')].lines.push(id);
		// 关联终止位置表格与其附属的线条
		$.TableView.tables[$toTable.attr('code')].lines.push(id);
		return line;
	};

	/* 克隆指定线条 */
	$.TableView.cloneLine = function(line){
		var TV = $.TableView,
			copy = line.clone();
		$.extend(copy,{
			id:line.id,
			fromTable: line.fromTable,
			toTable: line.toTable,
			fromPort: line.fromPort,
			toPort: line.toPort,
			arrow: line.arrow
		});

		return copy;
	};
	
	/* 获取当前窗口大小 */
	$.TableView.getWinSize = function() {
		return {
			width: winWidth+$(document).scrollLeft(),
			height: winHeight+$(document).scrollTop()
		}
	};
	
	/* 获取起始点与终点的坐标 */
	$.TableView.getCoords = function ($from,$to) {
		var $fromViewer = $from.closest('.m-table-viewer'),
			$toViewer = $to.closest('.m-table-viewer'),
			fromViewerPos = $fromViewer.offset(),
			toViewerPos = $toViewer.offset(),
			fromPos = $from.offset(),
			toPos = $to.offset(),
			h1 = $from.height(),
			h2 = $to.height(),
			minY1 = fromViewerPos.top,
			maxY1 = minY1 + $fromViewer.height(),
			minY2 = toViewerPos.top,
			maxY2 = minY2 + $toViewer.height(),
			y1 = fromPos.top + h1/2,
			y2 = toPos.top + h2/2,
			startPos = {
				x: fromPos.left+ this.tableWidth,
				y: (y1<minY1)?minY1:((y1>maxY1)?maxY1:y1)
			},
			endPos ={
				x: toPos.left,
				y: (y2<minY2)?minY2:((y2>maxY2)?maxY2:y2)
			},
			coords = [startPos.x,startPos.y,endPos.x,endPos.y];
			
			// 判断是否超出表格显示范围
			if(y1<minY1 || y1>maxY1 || y2<minY2 || y2>maxY2) {
				coords.overScope = true;
			}
		return coords;
	};
	
	/* 调整画布大小 */
	$.TableView.resizeCanvas = function() {
		var TV = $.TableView,
		winSize = TV.getWinSize(),
		canvas = TV.curTV.canvas;
		canvas.setHeight(winSize.height);
		canvas.setWidth(winSize.width);
	};
	
	/* 重绘 */
	$.TableView.repaint = function($table) {
		var code = $table.attr('code'),
		tables = $.TableView.tables,
		$t = tables[code],
		lines = $t.lines.slice();
		$t.lines = [];
		this.resizeCanvas();
		_.each(lines, function(id) {
			var line = $.TableView.lines[id];
			if(line) {
				// 移除线条
				line.arrow.remove();
				line.remove();
				// 线条是否选中
				var selected = $('div[lineid='+line.id+']').hasClass('selected');
				// 移除线条相关的按钮
				$('.u-operator[lineid='+line.id+']').remove();
				
				// 解除表格与线条的关联
				var fromTableLines = tables[line.fromTable].lines,
				toTableLines = tables[line.toTable].lines,
				fidx = _.indexOf(fromTableLines, line.id),
				tidx = _.indexOf(toTableLines, line.id) ;
				
				if(fidx>=0) {
					// 解除线条与起始表格的关联
					fromTableLines.splice(fidx,1);
				}
				if(tidx>=0) {
					// 解除线条与终止表格的关联
					toTableLines.splice(tidx,1);
				}
				
				// 删除线条缓存记录
				delete $.TableView.lines[id];
				
				var $from = $('li[code='+line.fromPort+']'),
				$to = $('li[code='+line.toPort+']');
				
				// 复制线条信息，重绘线条
				var newLine = $.TableView.drawLine($from, $to);
				newLine.setStroke(line.getStroke());
				newLine.setStrokeWidth(line.getStrokeWidth());
				newLine.arrow.setStroke(line.arrow.getStroke());
				newLine.arrow.setFill(line.arrow.getFill());
				
				// 保持选中状态
				if(selected) {
					$('.u-operator[lineid='+newLine.id+']').text('删除').addClass('selected');
				}

			}
		});
		
		// 立即渲染画布中所有对象
		$.TableView.curTV.canvas.renderAll();
		
	};
	
	/* 计算表格坐标 */
	$.TableView.calcTableCoord = function(index) {
		var winSize = this.getWinSize(),
			colWidth = this.tableWidth+this.tableMargin*2,
			rowHeight = this.trHeight*this.visTrNm + this.thHeight + this.tableMargin*2,
			colNm = Math.floor(winSize.width/colWidth),
			rowNo = Math.floor(index/colNm),
			colNo = index%colNm;
			console.log(colNm)

		return {
			x: this.tableMargin+colNo*colWidth,
			y: this.tableMargin+rowNo*rowHeight
		}	
	};
	
	/* 创建表格 */
	$.TableView.createTable = function($c,table,index) {
		// 表格整体结构模板
		var tableTpl = '<div class="m-table-viewer">'
							+'<div class="u-table-thead">'
								+table.name
							+'</div>'
							+'<div class="u-list-container">'
								+'<div class="scrollbar">'
									+'<div class="handle">'
										+'<div class="mousearea"></div>'
									+'</div>'
								+'</div>'
								+'<div class="sly">'
									+ '<ul class="table"></ul>'
								+'</div>'
							+'</div>'
						+'</div>',
		// 表格行模板
		trTpl = '<li class="u-table-tr">'+'<div class="j-menu"></div>'+'<div class="j-meta-name"></div>'+'</tr>',
		// 表格覆盖层模板，该覆盖层监听鼠标进出事件，从而改变表格的z-index显示层级
		coverTpl = '<div class="j-cover"></div>',
		$tableWrap = $(tableTpl),
		$tableContainer = $tableWrap.find('.u-list-container'),
		// 滚动区域
		$sly = $tableContainer.find('.sly'),
		// 滚动条
		$scroll = $tableWrap.find('.scrollbar'),
		$table = $tableContainer.find('ul').attr({id:table.id,code:table.code}),
		tablePos = this.calcTableCoord(index);
		
		var self = this;
		_.each(table.data,function(v,k) {
			var $tr = $(trTpl).css({height: self.trHeight +'px','line-height': self.trHeight+'px'});
			$tr.attr({id: v.id,code: v.code}).find('.j-meta-name').text(v.name);
			$table.append($tr);
		});	
		
		$c.append($tableWrap);
		
		// 设置表格容器位置及可拖拽初始化
		$tableWrap.css({position:'absolute',left:tablePos.x,top:tablePos.y}).draggabilly();
		
		// 设置表头样式
		$tableWrap.find('.u-table-thead').css({height:this.thHeight,'line-height':this.thHeight+'px'});
		
		// 计算表格显示行数，从而决定表格容器高度 
		var len = (table.data.length>this.visTrNm)?this.visTrNm:($scroll.hide(),table.data.length);
		$tableWrap.css({ width: this.tableWidth,height: len*this.trHeight+this.thHeight});
		
		// 计算滚动条高度
		$scroll.css({ height: len*this.trHeight - 2});
		
		// 滚动初始化
		$sly.css({ width: this.tableWidth-2,height: len*this.trHeight})
			.sly({ "itemNav": "smart",
				  "scrollBar": $tableWrap.find('.scrollbar'),
				  "scrollBy": this.trHeight,
				  "elasticBounds": 1 });
		
		var width = $tableWrap.width(),
			height = $tableWrap.height(),
			offset = $tableWrap.offset();
		var $cover = $(coverTpl).css({
			position: 'absolute',
			top: offset.top,
			left: offset.left,
			width: width,
			height: height,
			// 设置z-index，使其在最顶层
			'z-index': 10
		}).attr('code',table.code);	
		
		// 添加覆盖层，以便能够选中拖拽处于底层的表格
		$c.append($cover);
		$tableWrap.on( 'dragStart', function( event, pointer ) {
			isDrag = true;
			$(this).closest('.m-table-viewer').css({
				'background-color':'#FFF'
			});
		});
		$tableWrap.on( 'dragMove', function( event, pointer ) {
			self.repaint($table);
			$(this).css('z-index',21);
		});
		$tableWrap.on( 'dragEnd', function( event, pointer ) {
			isDrag = false;
			var left = Math.max(pointer.x,20),
				top = Math.max(pointer.y,20);
			
			if(pointer.x<20 || pointer.y<20) {
				$(this).css({
					left: left,
					top: top
				});
				$.TableView.repaint($(this).find('ul'));
			}
			
			var offset = $(this).offset(),
			code = $(this).find('ul').attr('code');
			$('div.j-cover[code='+code+']').css({top: offset.top,left: offset.left});
			$(this).closest('.m-table-viewer').css({
				'background-color':'transparent'
			});
		});
		$sly.sly('on','moveEnd',function() {
			self.repaint($table);
		});
		$.TableView.tables[table.code] = {
			data: table,
			$node: $table,
			lines: []
		};
	};
	
	/* 判断是否有重复映射 */
	$.TableView.isMetaMultMapping = function(meta1,meta2,meta) {
		var metas = _.union(meta1, meta2, meta);
		var dscs = _.map(metas,function(m) {
			return m.split(":")[0];
		});
		var length = dscs.length;
		if(length>_.union(dscs).length) {
			return true;
		}
		return false;
	};
	
	/* 更新数据元记录 */
	$.TableView.updateMeta = function() {
		var self = this;
		this.metas = [];
		_.map(this.lines,function(line) {
			self.addMeta(line.fromTable+':'+line.fromPort,line.toTable+':'+line.toPort);
		});
	};
	
	/* 增加数据元记录 */
	$.TableView.addMeta = function(meta1,meta2) {

		var idx1,idx2;
		_.map(this.metas,function(meta,k) {
			if(_.indexOf(meta,meta1)>=0) {
				idx1 = k;
			} 
			if(_.indexOf(meta,meta2)>=0) {
				idx2 = k;
			}
		});
		// 如果meta1,meta2同属于同一个this.metas中的集合或者有重复映射则返回
		if((idx1!==undefined &&idx2!==undefined&&idx1===idx2) 
			|| this.isMetaMultMapping(this.metas[idx1], this.metas[idx2],[meta1,meta2])) {
			return false;
		}
		
		// 如果meta1,meta2属于不同this.metas中的集合则合并
		if(idx1>=0 && idx2>=0) {
			this.metas[idx1] = _.union(this.metas[idx1], this.metas[idx2]);
			this.metas.splice(idx2,1);
		} else if(idx1>=0){
			this.metas[idx1].push(meta2);
		} else if(idx2>=0) {
			this.metas[idx2].push(meta1);
		} else {
			this.metas.push([meta1,meta2]);
		}
		return true;
	};
	
	/* 选中线 */
	$.TableView.selectLine = function(line) {
		var TV = $.TableView,
			lines = TV.lines;

		// 重置所有线条的显示
		_.each(lines,function(l){
			if(l!=line&&l.getStroke()!=="#3FA08E") {
				l.setStroke('#3FA08E');
				l.arrow.setStroke('#3FA08E');
				l.arrow.setFill('#3FA08E');
			}
		});	
		$('.u-operator').removeClass('selected').text('选中').css('z-index',1);
		
		// 改变选中的线条的显示
		if(line) {
			line.setStroke('#FF0000');
			line.setStrokeWidth(2);
			line.arrow.setStroke('#FF0000');
			line.arrow.setFill('#FF0000');
			$('.u-operator[lineid='+line.id+']').addClass('selected').text('删除').css('z-index',2);
		}
			
		// 立即渲染画布中所有对象
		TV.curTV.canvas.renderAll();
	};
	
	/* 删除选中的线条 */
	$.TableView.deleteSelectedLine = function() {
		var id= $('.u-operator.selected').attr('lineid'),
			TV = $.TableView,
			line = TV.lines[id],
			tables = TV.tables;
			
		if(line) {
			line.arrow.remove();
			line.remove();
			$('div[lineid='+line.id+']').remove();
			
			var fromTableLines = tables[line.fromTable].lines,
			toTableLines = tables[line.toTable].lines,
			fidx = _.indexOf(fromTableLines, line.id),
			tidx = _.indexOf(toTableLines, line.id) ;
			
			// 解除表格与线条的关联
			if(fidx>=0) {
				fromTableLines.splice(fidx,1);
			}
			if(tidx>=0) {
				toTableLines.splice(tidx,1);
			}

			delete TV.lines[id];
			
			// 更新数据元关系记录
			TV.updateMeta();
		}
	};
	
	/* 选中所有与指定表格及行相连的线条 */
	$.TableView.selectLinesByPort = function(table,port) {
		var lines = this.getPortLines(table,port),
			self = this,
			canvas = this.curTV.canvas;
		_.each(lines,function(line){
			var copy = self.cloneLine(line);
			copy.setStroke("#5559B5");
			copy.arrow.setStroke("#5559B5");
			copy.arrow.setFill("#5559B5");
			line.remove();
			self.lines[line.id] = copy;
			$('.u-operator[lineid='+line.id+']').css('z-index',2);
			canvas.add(copy);
		});
		canvas.renderAll();
	};

	$.fn.tableViewer = function(data) {
		this.init = init;
		this.reInit = reInit;
		this.getResult = getResult;
		this.init(data);
		this.data = data;
	}
	
	// 表格是否处于拖拽状态
	var isDrag = false;
	// 处理鼠标点击表格行
	$(document.body).on('click','.m-table-viewer .u-table-tr',function() {
		var TV = $.TableView,
			canvas = TV.curTV.canvas;
		var isThead = $(this).closest('.u-table-thead').length;
		// 如果再次点击起始行，则取消行选中的from样式标记，并将所有线条样式重置
		if($(this).hasClass('from')) {
			$(this).removeClass('from');
			// TV.selectLine传入null参数时，将重置所有线条样式
			TV.selectLine(null);
			var selected = $('.u-operator.selected').attr('lineid');
			var line = TV.lines[selected];
			if(line) {
				l.setStroke('#3FA08E');
				l.arrow.setStroke('#3FA08E');
				l.arrow.setFill('#3FA08E');
			}
			canvas.renderAll();
			return ;
		}
		// 如果是表头，则返回
		if(isThead) {
			return ;
		}
		
		// 为了防止拖拽引起触发此点击事件处理，通过判断isDrag来阻止
		if(isDrag) {
			isDrag = false;
			return ;
		}
		var $tr = $(this),
			$from = $('.from'),
			$fromTable = $from.closest('ul'),
			$parent = $tr.closest('ul'),
			isRest = $parent.find('.from').length;
			
		// 判断连线的起始和终止是否来自同一个表格，若是则重置	
		if(isRest) {
			$from.removeClass('from');
			$from = $('.from');
			TV.selectLine(null);
		}
		
		// 如果不存在起始位置，则将该点击行设置为起始，并将与其相连的所有线条选中
		if(!$from.length) {
			$tr.addClass('from');
			$.TableView.selectLine(null);
			TV.selectLinesByPort(TV.tables[$tr.closest('ul').attr('code')],$tr.attr('code'));
			return ;
		}
		
		// 判断起始位置与终止位置是否已经存在连线，若有则本次点击无效
		if(TV.hasLine($from,$tr)){
			$from.removeClass('from');
			return ;
		}
		
		var fromTable = $fromTable.attr('code'),
			fromPort = $from.attr('code'),
			toTable = $tr.closest('ul').attr('code'),
			toPort = $tr.attr('code'),
			meta1 = fromTable+':'+fromPort,
			meta2 = toTable+':'+toPort;
			
		// 	添加数据元关联记录，如果成功则画线
		if(TV.addMeta(meta1,meta2)) {
			$tr.addClass('to');
			TV.drawLine($from,$tr);
			$('.from').removeClass('from');
			$('.to').removeClass('to');
		} else {
			$from.removeClass('from');
		}
		TV.selectLine(null);
	})
	// 处理非选中按钮的点击
	.on('click',':not(.u-operator)',function(e) {
		
		if($(e.target).closest('.m-table-viewer').length) {
			return ;
		}
		$('.from').removeClass('from');
		$.TableView.selectLine(null);
	})
	// 处理选中按钮的点击
	.on('click','.u-operator',function() {

		var id = $(this).attr('lineid'),
			TV = $.TableView,
			line = TV.lines[id];
		
		TV.selectLine(line);
	})
	// 处理选中状态下选中按钮的点击
	.on('click','.u-operator.selected',function() {
		$.TableView.deleteSelectedLine();
	})
	// 处理delete按键按下
	.on('keydown',function(e) {
		if(e.keyCode == 46){
			$.TableView.deleteSelectedLine();
	   }
	})
	// 处理鼠标进入表格覆盖层
	.on('mouseenter','div.j-cover',function() {
			
		var code = $(this).attr('code'),
		TV = $.TableView,
		$table = TV.tables[code].$node;
		if(!isDrag) {
			$table.closest('.m-table-viewer').css({
				'z-index': 20
			});
		}
		
	})
	// 处理鼠标离开表格覆盖层
	.on('mouseleave','.m-table-viewer',function() {
			
		var code = $(this).find('ul').attr('code'),
		TV = $.TableView,
		$table = TV.tables[code].$node;
		$table.closest('.m-table-viewer').css({
			'z-index': 0
		});

	});

	// 绑定窗口大小改变事件
	$(window).on('resize',function() {
		
		var TV = $.TableView,
			curTV = TV.curTV;
		curTV.reInit();
		TV.resizeCanvas();
	})
	// 监听窗口滚动
	.on('scroll',function() {
			
		$.TableView.resizeCanvas();
	});
})(window, jQuery);