;
(function($, window, document, undefined) {
	"use strict";

	var table = function(tableId, options) {
		var aaSorting = [];
		var defaults = {
				sPaginationType : "bootstrap_full",
				bPaginate : true, // 开关，是否显示分页器
				bSort : true,
				bInfo : true,
				bAutoWidth : false,
				bDestroy : true,
				bFilter : false, // 开关，是否启用客户端过滤器
				bLengthChange : false, // 开关，是否显示每页大小的下拉框
				bLengthALL : false, // 开关，是否显示每页大小的下拉框
				aLengthMenu : [ [10, 25, 50, 100 ], [10, 25, 50, 100 ] ],
				bPdf : false, // 数据导出pdf 开关
				bExcel : false, // 数据导出Excel 开关
				bCsv : false, // 数据导出Csv 开关
				bPrint : false, // 数据导出print 开关
				bCopy : false, // 数据导出Copy 开关
				bColvis : false, // 数据导出print 开关
				bDataExportTitle : "", // 数据导出title  默认的为网站+表头名
				buttons : [],
				pageSize : 10,
				bProcessing : true,
				url : '',
				bServerSide : true,
				fnRowCallback : '',
				fnServerData : '',
				aaSorting : [],
				aaData : null,
				aoColumns : [],
				scrollX : false,
				scrollY : "",
				scrollCollapse : false,
				dom : "<'row'<'col-sm-6 '><'col-sm-6'f>>"
				+ "<'row'<'col-sm-12'tr>>" + "<'row'<'pull-left dataTables-page-btn  'iB><'pull-right1'l><'dataTables-page-length  pull-right'p>>",
				initComplete : null,
				searchPlaceholder : $.i18n.prop('i18n-tablesearch'),
                sLengthMenu: $.i18n.prop('i18n-pageshow')+"_MENU_"+$.i18n.prop('i18n-pagesize'),
                sZeroRecords: $.i18n.prop('i18n-sZeroRecords'),
                sEmptyTable: $.i18n.prop('i18n-sZeroRecords'),
                sInfo:         $.i18n.prop('i18n-sInfo1') +"_START_" + $.i18n.prop('i18n-sInfo2')+ "_END_" +$.i18n.prop('i18n-sInfo3')+"，"+$.i18n.prop('i18n-sInfo4')+ "_TOTAL_" +$.i18n.prop('i18n-sInfo3'),
                sInfoEmpty:    $.i18n.prop('i18n-sInfo5'),
                sInfoFiltered: "("+$.i18n.prop('i18n-sInfo6')+ "_MAX_" +$.i18n.prop('i18n-sInfo7')+")",
                oPaginate: {
                "sFirst":    $.i18n.prop('i18n-sFirst'),
                "sPrevious":  $.i18n.prop('i18n-sPrevious'),
                "sNext":     $.i18n.prop('i18n-sNext'),
                "sLast":     $.i18n.prop('i18n-sLast')
				},
                button:{
                "copyTitle":$.i18n.prop('i18n-copyTitle'),
                "copySuccess": {
                    "_": $.i18n.prop('i18n-copy')+ "%d" +$.i18n.prop('i18n-article')+$.i18n.prop('i18n-to') ,
                    "1": $.i18n.prop('i18n-copySuccessone')
                 },
                },
				isCheckBox : false,
				multipleCheck : true,
				checkBoxClick : null,// function(checked, data,select,noselect,
				// datas)
				toolBarsPosition : "left",
				toolBars : [
				// {
				// label: "",//按钮名称
				// html:"",//html
				// id: "",//按钮id
				// classes: "",//class
				// icon: "",//图标
				// enable: true,//启用条件，支持function(select,noselect,total){}
				// show: true,//是否显示
				// click: function(selectItems,e){}//单击事件
				// }
				],
				fixedToolBars : false,// 工具栏是否锁定
				fixedHeader : false, // 表头锁定
				fixedContainer : $(window),// 容器
				fixedColumns : [],
				bStateSave:true,
				fnStateLoadParams: function (oSettings, oData) {
					oData.search = "";
					oData.order = aaSorting;
	          	}
			}

		if(options.aaSorting){
			aaSorting = options.aaSorting
		}
		this.tableId = tableId;
		this.options = $.extend({}, defaults, options);
		this.oTable = null;

		this.init();

		// 工具栏实现
		var that = this;
		that.toolBar = new ToolBar(that);
		that.fixedHeader = new FixedHeader(that);
		var fixedContainer = that.options.fixedContainer;
		fixedContainer.scroll(function(e) {
			// 工具栏锁定
			if (that.options.fixedToolBars) {
				that.toolBar.fixedToolBars();
			}

			// 表头锁定
			if (that.options.fixedHeader) {
				var headerTop = that.options.fixedToolBars ? that.toolBar.toolBarsNode.outerHeight() : 0;
				that.fixedHeader.scroll({
					top : headerTop
				});
			}
		});

		// 列锁定
		that.fixedColumns = new FixedColumns(that);

	}

	table.prototype = {
		init : initTable,
		refresh : refreshTable,
		refreshPage : function() {
			this.oTable.fnDraw(false);
		}
	};

	function refreshTable() {
		var self = this;
		self.oTable.fnReloadAjax(self.url);

	}

	function initTable() {
		var self = this;
		var options = self.options;
		var tableId = self.tableId;

		// 复选框实现
		if (options.isCheckBox) {
			// 获取表头中是否已经存在 checkall 复选框
			var existingCheckAll = $('#' + tableId + '>thead>tr th input.checkall');
			if (existingCheckAll.length > 0) {
				// 如果存在，则移除该复选框及其所在的 th 元素
				existingCheckAll.closest('th').remove();
}
			var checkbox = $('<th><input type="checkbox" class="checkall" /></th>');
			$('#' + tableId + '>thead>tr').prepend(checkbox);
			// 插入checkbox列
			var aoColumns = options.aoColumns;
			if (aoColumns) {
				var checkboxColumn = [ {
					"sClass" : "text-center",
					"mData" : " ",
					"bSortable" : false,
					"mRender" : function(data, type, full) {
						return '<input type="checkbox"  class="checkchild"/>';
					}
				} ];
				options.aoColumns = $.merge(checkboxColumn, aoColumns);
			}
		}

		if(options.bLengthALL){
			if(options.aLengthMenu.toString().indexOf($.i18n.prop('i18n-allpagesize'))<0){
				options.aLengthMenu [0].push(-1);
				options.aLengthMenu [1].push($.i18n.prop('i18n-allpagesize'));
			}
		} else{
			if(options.aLengthMenu.toString().indexOf($.i18n.prop('i18n-allpagesize'))>0){
				options.aLengthMenu [0].pop();
				options.aLengthMenu [1].pop();
			}
		}
		var dataExportButtons = options.buttons;
		if (dataExportButtons&&dataExportButtons.length === 0) {
			var bPdfTemp = options.bPdf;
			var bExcelTemp = options.bExcel;
			var bCsvTemp = options.bCsv;
			var bPrintTemp = options.bPrint;
			var bCopyTemp = options.bCopy;
			var bColvisTemp = options.bColvis;
			var bDataExportTitle = options.bDataExportTitle;
			var isCheckBox = options.isCheckBox;
			dataExportButtons = createDataExportButtons(bPdfTemp, bExcelTemp, bCsvTemp, bPrintTemp, bCopyTemp, bColvisTemp, bDataExportTitle,isCheckBox);
		}
		var tableDom = options.dom;
	/*	if(dataExportButtons.length>0){
			tableDom = "<'row'<'col-sm-6 '><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-5 pull-left dataTables-page-btn 'iB><'col-sm-7  dataTables-page-length  pull-right'lp>>";
		}*/
		var _table = $('#' + tableId + '').dataTable({
			sPaginationType : options.sPaginationType,
			bPaginate : options.bPaginate, // 开关，是否显示分页器
			bSort : options.bSort, // 是否排序
			bInfo : options.bInfo, // 分頁信息
			bAutoWidth : options.bAutoWidth,
			bDestroy : options.bDestroy,
			bFilter : options.bFilter, // 开关，是否启用客户端过滤器
			bLengthChange : options.bLengthChange, // 开关，是否显示每页大小的下拉框
			aLengthMenu : options.aLengthMenu, //
			buttons : dataExportButtons, //
			iDisplayLength : options.pageSize, // 每页显示数量
			bProcessing : options.bProcessing,
			sAjaxSource : options.url ? options.url + "?m=" + Math.random() : null,
			bServerSide : options.fnServerData ? options.bServerSide : false,
			fnRowCallback : options.fnRowCallback,
			fnServerData : options.fnServerData ? options.fnServerData : null,
			aaSorting : options.aaSorting,
			aaData : options.aaData,
			aoColumns : options.aoColumns,
			dom : tableDom,
			initComplete : options.initComplete,
			scrollX : options.scrollX,
			scrollY : options.scrollY,
			scrollCollapse : options.scrollCollapse,
			oLanguage : {
				sSearchPlaceholder : options.searchPlaceholder,
                sLengthMenu : options.sLengthMenu,
                sZeroRecords : options.sZeroRecords,
                sEmptyTable : options.sEmptyTable,
                sInfo : options.sInfo,
                sInfoEmpty : options.sInfoEmpty,
                sInfoFiltered : options.sInfoFiltered,
                oPaginate : options.oPaginate,
                buttons : options.button,
			},
			bStateSave:options.bStateSave,
			fnStateLoadParams:options.fnStateLoadParams,
		});

		self.oTable = _table;


		if (options.isCheckBox) {
			self.initCheckBox();
		}
		$('#' + tableId).resize(function() {
			$('#' + tableId).dataTable()&&$('#' + tableId).dataTable()._fnAdjustColumnSizing();
		});
		return _table;
	}

	function createDataExportButtons(pdf, excel, csv, print, copy, colvis, bDataExportTitle,isCheckBox) {
		var buttons = [];
		var exportButtons = [];
		var buttonSize = 0;
		if (excel) {
			var excelBtn = {
				extend : 'excelHtml5',
				text : $.i18n.prop('i18n-tableexportexcel'),
				charSet : "utf8",
				exportOptions: {
					 columns: [':visible']
                },
                customizeData: function ( data ) {
                    for (var i=0; i<data.body.length; i++){
                        for (var j=0; j<data.body[i].length; j++ ){
                        	var numValue = data.body[i][j];
                        	if(numValue&&!isNaN(numValue)&&(numValue+"").length>10){
                        		data.body[i][j] = '\u200C' + data.body[i][j];
                        	}
                        }
                    }
                }
			};
			if (bDataExportTitle) {
				excelBtn.title = bDataExportTitle;
			}
			buttonSize = exportButtons.push(excelBtn);
		}
		if (copy) {
			var copyBtn = {
				extend : 'copyHtml5',
				text : $.i18n.prop('i18n-tablecopy'),
				charSet : "utf8",
				exportOptions: {
                    columns: [':visible',':not(:first-child)']
                }
			};
			if (bDataExportTitle) {
				copyBtn.title = bDataExportTitle;
			}
			buttonSize = exportButtons.push(copyBtn);
		}

		if (buttonSize > 1) {
			buttons.push({
				extend : 'collection',
				text : $.i18n.prop('i18n-tableexportpage'),
				buttons : exportButtons,
				collectionLayout: ' fixed two-column',
				autoClose:true
			});
		} else {
			buttons = exportButtons;
		}
		if (colvis) {
			var colvisBtn = {
					extend : 'colvis',
					text : $.i18n.prop('i18n-tablecoumlm'),
					collectionLayout: 'fixed three-column',
					postfixButtons: [ {extend : 'colvisRestore',
						text : $.i18n.prop('i18n-tableall')}  ]
			};
			if(isCheckBox){
				colvisBtn.columns=':not(:first-child)';
			}
			buttons.push(colvisBtn);
		}/*else{
			var opButtons = [];
			if(buttons.length>0){
				opButtons.push({
					 extend: 'collection',
					 text: '表格操作<span class="cert><span/>',
			         buttons:buttons
		           });
			}
			return opButtons;
		}*/
		return buttons;
	}
	table.prototype.initCheckBox = function() {
		var that = this;
		var dataTable = that.oTable;
		var options = that.options;

		var tHead = $(that.oTable.fnSettings().nTHead);
		var tBody = $(that.oTable.fnSettings().nTBody);

		var checkAll = tHead.find("tr > th input[type=checkbox]").eq(0);
		checkAll.closest("th").css("position", "relative");
		var checkAllCover = {
			dom : $("<span class='checkbox-nofull'></span>"),
			enable : false,
			init : function() {
				var that = this;
				if (!that.enable) {
					that.dom.on("click", function(e) {
						e.stopPropagation();
						that.click();
					});
					that.dom.css(that.getCoverPosition());
					checkAll.after(that.dom);
					that.enable = true;
				}
			},
			getCoverPosition : function() {
				var width = checkAll.outerWidth();
				var height = checkAll.outerHeight();
				var left = checkAll[0].offsetLeft;
				var top = checkAll[0].offsetTop;

				var style = {
					"position" : "absolute",
					"display" : "block",
					"width" : width + "px",
					"height" : height + "px",
					"top" : top + "px",
					"left" : left + "px",
					"background" : "transparent"
				};
				return style;
			},
			remove : function() {
				this.dom.remove();
				this.enable = false;
			},
			click : function() {
				this.remove();
				checkAll.click();
			}
		};

		var active_class = 'success';
		checkAll.on('click', function(e) {
			e.stopPropagation();
			var checked = this.checked;
			tBody.find('tr input[type=checkbox]').each(function() {
				var item = this;
				if (checked)
					$(item).prop('checked', checked).closest("tr").addClass(active_class);
				else
					$(item).prop('checked', checked).closest("tr").removeClass(active_class);
			});

			// 更新按钮状态
			that.toolBar.refresh();

			if (options.checkBoxClick && typeof options.checkBoxClick == "function") {
				var trLength = tBody.find("tr").length;
				var fullDatas = getSelectDatas();
				if (checked) {
					options.checkBoxClick(checked, null, trLength, 0, fullDatas);
				} else {
					options.checkBoxClick(checked, null, 0, trLength, fullDatas);
				}

			}
		});
		tBody.on('click', 'tr input[type=checkbox]', function(e) {
			e.stopPropagation();
			if (!options.multipleCheck) {
				unCheckedBox(this);
			}
			var $row = $(this).closest('tr');
			var checked = this.checked;
			if (checked) {
				$row.addClass(active_class);
			} else {
				$row.removeClass(active_class);
			}
			var trLength = tBody.find("tr").length;
			var checkedLength = tBody.find("tr.success").length;
			if (checkedLength == trLength) {
				checkAll.prop('checked', true);
				checkAllCover.remove();
			} else {
				checkAll.prop('checked', false);
				if (checkedLength == 0) {
					checkAllCover.remove();
				} else if (checkedLength > 0 && checkedLength < trLength) {
					checkAllCover.init();
				}
			}

			// 更新按钮状态
			that.toolBar.refresh();

			if (options.checkBoxClick && typeof options.checkBoxClick == "function") {
				var data = getSelectDatas($row);
				var selectDatas = getSelectDatas();
				options.checkBoxClick(checked, data, checkedLength, trLength, selectDatas);
			}
		});

		var timer = null;
		var num = 0;
		tBody.on('click', 'tr', function(e) {
			num++;
			if (timer) {
				window.clearTimeout(timer);
				timer = null;
			}
			var that = this;
			if (num == 1) {
				timer = setTimeout(function() {
					var checkItem = $(that).find("input[type=checkbox]");
					checkItem.click();
					window.clearTimeout(timer);
					timer = null;
					num = 0;
				}, 300);
			} else {
				timer = setTimeout(function() {
					window.clearTimeout(timer);
					timer = null;
					num = 0;
				}, 300);
			}
		});

		function unCheckedBox(exclude) {
			tBody.find('tr input[type=checkbox]:checked').each(function() {
				if (exclude != this) {
					$(this).prop('checked', false).closest("tr").removeClass(active_class);
				}
			});
			$(exclude).prop('checked', true).closest("tr").addClass(active_class);
		}

		function getSelectDatas($dom) {
			if ($dom) {
				return dataTable.fnGetData($dom);
			} else {
				var $trs = tBody.find("tr.success");
				var datas = [];
				$trs.each(function() {
					var data = dataTable.fnGetData($(this));
					datas.push(data);
				});
				return datas;
			}
		}

		that.oTable.on('draw.dt', function() {
			checkAll.prop('checked', false);
			checkAllCover.remove();
			tBody.closest("table").find("span.checkbox-nofull").remove();
		});

	}

	var toolBarItem = {
		label : "",// 按钮名称
		html : "",// html
		id : "",// 按钮id
		classes : "",// class
		icon : "",// 图标
		enable : true,// 启用条件，支持function(select,noselect,total,datas){}
		show : true,// 是否显示
		click : null
	// 单击事件function(e,selectItems){}
	};
	var ToolBar = function(table) {
		this.tableId = table.tableId;
		this.options = table.options;
		this.dataTable = table.oTable;
		this.init();
	}

	ToolBar.prototype.init = function() {
		// 初始化工具栏
		var that = this;
		var tableId = that.tableId;
		var nTableWrapper = that.dataTable.fnSettings().nTableWrapper;

		var toolBarsNode = $(nTableWrapper).closest("div.widget-body").children("div.toolBars");
		if (toolBarsNode.length > 0) {
			toolBarsNode.attr("id", tableId + "-toolBar");
			that.toolBarsNode = toolBarsNode;
		}
		var toolBars = that.options.toolBars;
		if (toolBars && toolBars.length > 0) {
			if (toolBarsNode.length == 0) {
				toolBarsNode = $('<div class="widget-body-toolbar toolBars" id="' + tableId + '-toolBar"></div>');

				that.toolBarsNode = toolBarsNode;
			}

			var toolBarsTemp = $("<div></div>");
			$.each(toolBars, function(i, value) {
				var item = $.extend({}, toolBarItem, value);

				var itemNode = null;
				var inSideButton = true;
				if (item.html) {
					itemNode = $(html);
				} else {
					var classes = item.classes;
					if (item.id) {
						itemNode = toolBarsNode.children("#" + item.id);
						if (itemNode.length == 0) {
							itemNode = $("#" + item.id);
							if (itemNode.length > 0) {
								inSideButton = false;
							}
						}
					}
					if (itemNode && itemNode.length > 0) {
						if (classes) {
							itemNode.attr("class", "btn" + classes);
						}
						var iconspan = itemNode.children("span.fa");
						if (item.icon) {
							if (iconspan.length > 0) {
								iconspan.attr("class", "fa " + item.icon);
							} else {
								itemNode.prepend($('<span class="fa ' + item.icon + '"></span>'));
							}
						}
						if (item.label) {
							itemNode.text("");
							itemNode.append(iconspan).append("&nbsp;" + item.label);
						}
					} else {
						classes = classes ? classes : "btn-primary";
						itemNode = $('<button id="' + item.id + '" type="button" class="btn  ' + classes + '">&nbsp;' + item.label + '</button>');
						if (item.icon) {
							itemNode.prepend($('<span class="fa ' + item.icon + '"></span>'));
						}
					}
				}
				if (itemNode) {
					itemNode.click(function(e) {
						if (item.click && typeof item.click == "function") {// click事件
							var $trs = $("#" + tableId + " tbody tr.success");
							var datas = [];
							$trs.each(function() {
								var data = that.dataTable.fnGetData($(this));
								datas.push(data);
							});
							item.click(datas, e);
						}
					});
					if (inSideButton) {
						toolBarsTemp.append(itemNode);
					}
					item.element = itemNode;
					toolBars[i] = item;
				}
			});
			if (toolBarsTemp.children().length > 0) {
				toolBarsNode.append(toolBarsTemp.children());
				$(nTableWrapper).before(toolBarsNode);
			}

			var position = that.options.toolBarsPosition;
			toolBarsNode.css("text-align", position);
			// 刷新工具栏
			that.refresh();
			// table刷新，按钮状态
			that.dataTable.on('draw.dt', function() {
				that.refresh();
			});
		}
	}

	ToolBar.prototype.refresh = function() {// 工具栏刷新
		var that = this;
		var toolBarsNode = that.toolBarsNode;
		var isCheckBox = that.options.isCheckBox;
		if (!toolBarsNode || !isCheckBox) {
			return;
		}

		var nTBody = that.dataTable.fnSettings().nTBody;
		var total = $(nTBody).find("tr").length;
		var select = $(nTBody).find("tr.success").length;
		var noselect = total - select;
		var datas = [];
		$(nTBody).find("tr.success").each(function() {
			var data = that.dataTable.fnGetData($(this));
			datas.push(data);
		});
		var toolBars = that.options.toolBars;
		$.each(toolBars, function(i, item) {
			var element = item.element;
			var show = item.show;
			if (!show) {
				element.hide();
			} else {
				element.show();
				var enable = item.enable;
				if (enable && typeof enable == "function") {
					enable = enable(select, noselect, total, datas);
				}
				if (enable) {
					if (element.hasClass("disabled")) {
						element.removeClass("disabled");
					}
				} else {
					if (!element.hasClass("disabled")) {
						element.addClass("disabled");
					}
				}
			}
		});
	}

	ToolBar.prototype.fixedToolBars = function(o) {
		var o = o || {};
		var that = this;
		var toolBarsNode = that.toolBarsNode;
		if (!toolBarsNode) {// 判断工具栏是否存在
			return;
		}
		var fixedContainer = that.options.fixedContainer;
		var position = that.position;
		if (!position) {
			position = {};
			position.top = o.top || 0;
			position.containerTop = fixedContainer.offset() ? fixedContainer.offset().top : 0;
			position.offsetHeight = toolBarsNode.outerHeight();
			position.offsetWidth = toolBarsNode.outerWidth();
			position.offsetTop = toolBarsNode.offset().top;
			position.translateTop = position.offsetTop - position.containerTop;
			position.initcss = toolBarsNode.attr("style") || "";
			position.floatcss = {
				"position" : "fixed",
				"top" : position.top + position.containerTop + "px",
				"width" : position.offsetWidth + "px",
				"z-index" : "99999"
			}
		}
		var scrollTop = fixedContainer.scrollTop();

		var tableNode = $(that.dataTable[0]);
		var tableBottomTop = tableNode.outerHeight() + position.translateTop + position.offsetHeight;
		if (scrollTop > position.translateTop - position.top && scrollTop < tableBottomTop - position.top) {
			if (!position.tempNode) {
				position.tempNode = toolBarsNode.clone(false);
				toolBarsNode.after(position.tempNode);
				toolBarsNode.css(position.floatcss);
			}
		} else {
			if (position.tempNode) {
				toolBarsNode.attr("style", position.initcss);
				position.tempNode.remove();
				position.tempNode = null;
			}
		}

		that.position = position;
	}

	var FixedHeader = function(table) {
		this.tableId = table.tableId;
		this.options = table.options;
		this.dataTable = table.oTable;

		if (!this.options.fixedHeader) {
			this.scroll = function() {
			};
			return;
		}

		var scrollX = this.options.scrollX;
		var headerNode = null;
		if (scrollX) {
			headerNode = $(this.dataTable.fnSettings().nScrollHead);
		} else {
			headerNode = $(this.dataTable.fnSettings().nTHead);
			this.dataTable.on('draw.dt', function() {
				if (this.position && this.position.tempNode) {
					this._matchWidths(this.position.tempNode, this.headerNode);
				}
			}.bind(this));
		}
		this.headerNode = headerNode;

		this.scroll = function(o) {
			var that = this;
			var fixedHeader = that.options.fixedHeader;
			if (!fixedHeader) {// 判断table header是否锁定
				return;
			}
			var headerNode = that.headerNode;
			if (headerNode && headerNode.length > 0) {
				floating.call(that, o, headerNode);
			}
		}

		function floating(o, headerNode) {
			var o = o || {};
			var that = this;

			var fixedContainer = that.options.fixedContainer;
			var position = that.position;
			if (!position) {
				position = {};
				position.top = o.top || 0;
				position.containerTop = fixedContainer.offset() ? fixedContainer.offset().top : 0;
				position.offsetHeight = headerNode.outerHeight();
				position.offsetWidth = headerNode.outerWidth();
				position.offsetTop = headerNode.offset().top;
				position.translateTop = position.offsetTop - position.containerTop;
				position.initcss = headerNode.attr("style") || "";
				position.floatcss = {
					"position" : "fixed",
					"top" : position.top + position.containerTop + "px",
					"width" : position.offsetWidth + "px",
					"z-index" : "99999"
				}
			}
			var scrollTop = fixedContainer.scrollTop();

			var tableNode = $(that.dataTable[0]);
			var tableBottomTop = tableNode.outerHeight() + position.translateTop + position.offsetHeight;
			if (scrollTop > position.translateTop - position.top && scrollTop < tableBottomTop - position.top) {
				if (!position.tempNode) {
					position.tempNode = headerNode.clone(false);
					headerNode.after(position.tempNode);
					headerNode.css(position.floatcss);
					that._matchWidths(position.tempNode, headerNode);
				} else {
					headerNode.css(position.floatcss);
				}
			} else {
				if (position.tempNode) {
					headerNode.attr("style", position.initcss);
					position.tempNode.remove();
					position.tempNode = null;
				}
			}
			that.position = position;
		}

		this._matchWidths = function(from, to) {
			var get = function(name) {
				return $(name, from).map(function() {
					return $(this)[0].offsetWidth;
				}).toArray();
			};

			var set = function(name, toWidths) {
				$(name, to).each(function(i) {
					$(this).css({
						width : toWidths[i],
						minWidth : toWidths[i]
					});
				});
			};

			var thWidths = get('th');
			var tdWidths = get('td');

			set('th', thWidths);
			set('td', tdWidths);
		}
	}

	var FixedColumns = function(table) {
		var that = this;
		that.tableId = table.tableId;
		that.options = table.options;
		that.dataTable = table.oTable;

		var fixedColumns = that.options.fixedColumns;
		var scrollX = that.options.scrollX;
		if (scrollX && fixedColumns.length > 0) {
			that.scrollBody = $(that.dataTable.fnSettings().nScrollBody);
			that.scrollHead = $(that.dataTable.fnSettings().nScrollHead);
			that.tableLeft = that.scrollHead.offset().left;
			that.columnOptions = {};

			that.scrollBody.find("table").addClass("nocollapse");
			that.scrollHead.find("table").addClass("nocollapse");

			that.scrollBody.scroll(function(e) {
				that.position = {
					scrollLeft : this.scrollLeft,
					scrollHeight : this.scrollHeight,
					scrollTop : this.scrollTop,
					scrollWidth : this.scrollWidth
				};
				that.floating();
			});
		}

		that.floating = function() {
			var position = this.position;

			$.each(fixedColumns, function(i, value) {
				var columnOption = that.columnOptions[value] || {};
				var column = that.scrollHead.find("tr>th:nth-child(" + value + ")");
				if (i == 0) {
					columnOption.precolWidth = 0;
				} else {
					var preColumnOption = that.columnOptions[fixedColumns[i - 1]];
					columnOption.precolWidth = preColumnOption.beforeWidth;
				}
				columnOption.offsetWidth = column.outerWidth();
				columnOption.offsetLeft = column[0].offsetLeft;
				columnOption.beforeWidth = columnOption.precolWidth + columnOption.offsetWidth;
				columnOption.scrollStart = columnOption.offsetLeft - columnOption.precolWidth;

				if (position.scrollLeft > columnOption.scrollStart) {
					that.setColTransform(value, position.scrollLeft - columnOption.scrollStart);
				} else {
					that.setColTransform(value, 0);
				}
				that.columnOptions[value] = columnOption;

			});
		}

		that.setColTransform = function(columnsIndex, translate) {// 设置位移
			var nTableWrapper = $(that.dataTable.fnSettings().nTableWrapper);
			var thNode = nTableWrapper.find("tr>th:nth-child(" + columnsIndex + ")");
			var tdNode = nTableWrapper.find("tr>td:nth-child(" + columnsIndex + ")");

			var cssStyles = {
				"transform" : "translateX(" + translate + "px)"
			}
			thNode.css(cssStyles);
			tdNode.css(cssStyles);
		}

	}

	table.prototype.getSelectedDatas = function() {
		var that = this;
		var dataTable = that.oTable;
		var tBody = $(that.oTable.fnSettings().nTBody);
		var $trs = tBody.find("tr.success");
		var datas = [];
		$trs.each(function() {
			var data = dataTable.fnGetData($(this));
			if (data) {
				datas.push(data);
			}
		});
		return datas;
	}

	window.table = table;
})(jQuery, window, document);
