jquery.tablesorter.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. /*
  2. *
  3. * TableSorter 2.0 - Client-side table sorting with ease!
  4. * Version 2.0.3
  5. * @requires jQuery v1.2.3
  6. *
  7. * Copyright (c) 2007 Christian Bach
  8. * Examples and docs at: http://tablesorter.com
  9. * Dual licensed under the MIT and GPL licenses:
  10. * http://www.opensource.org/licenses/mit-license.php
  11. * http://www.gnu.org/licenses/gpl.html
  12. *
  13. */
  14. /**
  15. *
  16. * @description Create a sortable table with multi-column sorting capabilitys
  17. *
  18. * @example $('table').tablesorter();
  19. * @desc Create a simple tablesorter interface.
  20. *
  21. * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
  22. * @desc Create a tablesorter interface and sort on the first and secound column in ascending order.
  23. *
  24. * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
  25. * @desc Create a tablesorter interface and disableing the first and secound column headers.
  26. *
  27. * @example $('table').tablesorter({ 0: {sorter:"integer"}, 1: {sorter:"currency"} });
  28. * @desc Create a tablesorter interface and set a column parser for the first and secound column.
  29. *
  30. *
  31. * @param Object settings An object literal containing key/value pairs to provide optional settings.
  32. *
  33. * @option String cssHeader (optional) A string of the class name to be appended to sortable tr elements in the thead of the table.
  34. * Default value: "header"
  35. *
  36. * @option String cssAsc (optional) A string of the class name to be appended to sortable tr elements in the thead on a ascending sort.
  37. * Default value: "headerSortUp"
  38. *
  39. * @option String cssDesc (optional) A string of the class name to be appended to sortable tr elements in the thead on a descending sort.
  40. * Default value: "headerSortDown"
  41. *
  42. * @option String sortInitialOrder (optional) A string of the inital sorting order can be asc or desc.
  43. * Default value: "asc"
  44. *
  45. * @option String sortMultisortKey (optional) A string of the multi-column sort key.
  46. * Default value: "shiftKey"
  47. *
  48. * @option String textExtraction (optional) A string of the text-extraction method to use.
  49. * For complex html structures inside td cell set this option to "complex",
  50. * on large tables the complex option can be slow.
  51. * Default value: "simple"
  52. *
  53. * @option Object headers (optional) An array containing the forces sorting rules.
  54. * This option let's you specify a default sorting rule.
  55. * Default value: null
  56. *
  57. * @option Array sortList (optional) An array containing the forces sorting rules.
  58. * This option let's you specify a default sorting rule.
  59. * Default value: null
  60. *
  61. * @option Array sortForce (optional) An array containing forced sorting rules.
  62. * This option let's you specify a default sorting rule, which is prepended to user-selected rules.
  63. * Default value: null
  64. *
  65. * @option Array sortAppend (optional) An array containing forced sorting rules.
  66. * This option let's you specify a default sorting rule, which is appended to user-selected rules.
  67. * Default value: null
  68. *
  69. * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter should apply fixed widths to the table columns.
  70. * This is usefull when using the pager companion plugin.
  71. * This options requires the dimension jquery plugin.
  72. * Default value: false
  73. *
  74. * @option Boolean cancelSelection (optional) Boolean flag indicating if tablesorter should cancel selection of the table headers text.
  75. * Default value: true
  76. *
  77. * @option Boolean debug (optional) Boolean flag indicating if tablesorter should display debuging information usefull for development.
  78. *
  79. * @type jQuery
  80. *
  81. * @name tablesorter
  82. *
  83. * @cat Plugins/Tablesorter
  84. *
  85. * @author Christian Bach/christian.bach@polyester.se
  86. */
  87. (function($) {
  88. $.extend({
  89. tablesorter: new function() {
  90. var parsers = [], widgets = [];
  91. this.defaults = {
  92. cssHeader: "header",
  93. cssAsc: "headerSortUp",
  94. cssDesc: "headerSortDown",
  95. sortInitialOrder: "asc",
  96. sortMultiSortKey: "shiftKey",
  97. sortForce: null,
  98. sortAppend: null,
  99. textExtraction: "simple",
  100. parsers: {},
  101. widgets: [],
  102. widgetZebra: {css: ["even","odd"]},
  103. headers: {},
  104. widthFixed: false,
  105. cancelSelection: true,
  106. sortList: [],
  107. headerList: [],
  108. dateFormat: "us",
  109. decimal: '.',
  110. debug: false
  111. };
  112. /* debuging utils */
  113. function benchmark(s,d) {
  114. log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
  115. }
  116. this.benchmark = benchmark;
  117. function log(s) {
  118. if (typeof console != "undefined" && typeof console.debug != "undefined") {
  119. console.log(s);
  120. } else {
  121. alert(s);
  122. }
  123. }
  124. /* parsers utils */
  125. function buildParserCache(table,$headers) {
  126. if(table.config.debug) { var parsersDebug = ""; }
  127. var rows = table.tBodies[0].rows;
  128. if(table.tBodies[0].rows[0]) {
  129. var list = [], cells = rows[0].cells, l = cells.length;
  130. for (var i=0;i < l; i++) {
  131. var p = false;
  132. if($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter) ) {
  133. p = getParserById($($headers[i]).metadata().sorter);
  134. } else if((table.config.headers[i] && table.config.headers[i].sorter)) {
  135. p = getParserById(table.config.headers[i].sorter);
  136. }
  137. if(!p) {
  138. p = detectParserForColumn(table,cells[i]);
  139. }
  140. if(table.config.debug) { parsersDebug += "column:" + i + " parser:" +p.id + "\n"; }
  141. list.push(p);
  142. }
  143. }
  144. if(table.config.debug) { log(parsersDebug); }
  145. return list;
  146. };
  147. function detectParserForColumn(table,node) {
  148. var l = parsers.length;
  149. for(var i=1; i < l; i++) {
  150. if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)) {
  151. return parsers[i];
  152. }
  153. }
  154. // 0 is always the generic parser (text)
  155. return parsers[0];
  156. }
  157. function getParserById(name) {
  158. var l = parsers.length;
  159. for(var i=0; i < l; i++) {
  160. if(parsers[i].id.toLowerCase() == name.toLowerCase()) {
  161. return parsers[i];
  162. }
  163. }
  164. return false;
  165. }
  166. /* utils */
  167. function buildCache(table) {
  168. if(table.config.debug) { var cacheTime = new Date(); }
  169. var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
  170. totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
  171. parsers = table.config.parsers,
  172. cache = {row: [], normalized: []};
  173. for (var i=0;i < totalRows; ++i) {
  174. /** Add the table data to main data array */
  175. var c = table.tBodies[0].rows[i], cols = [];
  176. cache.row.push($(c));
  177. for(var j=0; j < totalCells; ++j) {
  178. cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));
  179. }
  180. cols.push(i); // add position for rowCache
  181. cache.normalized.push(cols);
  182. cols = null;
  183. };
  184. if(table.config.debug) { benchmark("Building cache for " + totalRows + " rows:", cacheTime); }
  185. return cache;
  186. };
  187. function getElementText(config,node) {
  188. if(!node) return "";
  189. var t = "";
  190. if(config.textExtraction == "simple") {
  191. if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
  192. t = node.childNodes[0].innerHTML;
  193. } else {
  194. t = node.innerHTML;
  195. }
  196. } else {
  197. if(typeof(config.textExtraction) == "function") {
  198. t = config.textExtraction(node);
  199. } else {
  200. t = $(node).text();
  201. }
  202. }
  203. return t;
  204. }
  205. function appendToTable(table,cache) {
  206. if(table.config.debug) {var appendTime = new Date()}
  207. var c = cache,
  208. r = c.row,
  209. n= c.normalized,
  210. totalRows = n.length,
  211. checkCell = (n[0].length-1),
  212. tableBody = $(table.tBodies[0]),
  213. rows = [];
  214. for (var i=0;i < totalRows; i++) {
  215. rows.push(r[n[i][checkCell]]);
  216. if(!table.config.appender) {
  217. var o = r[n[i][checkCell]];
  218. var l = o.length;
  219. for(var j=0; j < l; j++) {
  220. tableBody[0].appendChild(o[j]);
  221. }
  222. //tableBody.append(r[n[i][checkCell]]);
  223. }
  224. }
  225. if(table.config.appender) {
  226. table.config.appender(table,rows);
  227. }
  228. rows = null;
  229. if(table.config.debug) { benchmark("Rebuilt table:", appendTime); }
  230. //apply table widgets
  231. applyWidget(table);
  232. // trigger sortend
  233. setTimeout(function() {
  234. $(table).trigger("sortEnd");
  235. },0);
  236. };
  237. function buildHeaders(table) {
  238. if(table.config.debug) { var time = new Date(); }
  239. var meta = ($.metadata) ? true : false, tableHeadersRows = [];
  240. for(var i = 0; i < table.tHead.rows.length; i++) { tableHeadersRows[i]=0; };
  241. $tableHeaders = $("thead th",table);
  242. $tableHeaders.each(function(index) {
  243. this.count = 0;
  244. this.column = index;
  245. this.order = formatSortingOrder(table.config.sortInitialOrder);
  246. if(checkHeaderMetadata(this) || checkHeaderOptions(table,index)) this.sortDisabled = true;
  247. if(!this.sortDisabled) {
  248. $(this).addClass(table.config.cssHeader);
  249. }
  250. // add cell to headerList
  251. table.config.headerList[index]= this;
  252. });
  253. if(table.config.debug) { benchmark("Built headers:", time); log($tableHeaders); }
  254. return $tableHeaders;
  255. };
  256. function checkCellColSpan(table, rows, row) {
  257. var arr = [], r = table.tHead.rows, c = r[row].cells;
  258. for(var i=0; i < c.length; i++) {
  259. var cell = c[i];
  260. if ( cell.colSpan > 1) {
  261. arr = arr.concat(checkCellColSpan(table, headerArr,row++));
  262. } else {
  263. if(table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row+1])) {
  264. arr.push(cell);
  265. }
  266. //headerArr[row] = (i+row);
  267. }
  268. }
  269. return arr;
  270. };
  271. function checkHeaderMetadata(cell) {
  272. if(($.metadata) && ($(cell).metadata().sorter === false)) { return true; };
  273. return false;
  274. }
  275. function checkHeaderOptions(table,i) {
  276. if((table.config.headers[i]) && (table.config.headers[i].sorter === false)) { return true; };
  277. return false;
  278. }
  279. function applyWidget(table) {
  280. var c = table.config.widgets;
  281. var l = c.length;
  282. for(var i=0; i < l; i++) {
  283. getWidgetById(c[i]).format(table);
  284. }
  285. }
  286. function getWidgetById(name) {
  287. var l = widgets.length;
  288. for(var i=0; i < l; i++) {
  289. if(widgets[i].id.toLowerCase() == name.toLowerCase() ) {
  290. return widgets[i];
  291. }
  292. }
  293. };
  294. function formatSortingOrder(v) {
  295. if(typeof(v) != "Number") {
  296. i = (v.toLowerCase() == "desc") ? 1 : 0;
  297. } else {
  298. i = (v == (0 || 1)) ? v : 0;
  299. }
  300. return i;
  301. }
  302. function isValueInArray(v, a) {
  303. var l = a.length;
  304. for(var i=0; i < l; i++) {
  305. if(a[i][0] == v) {
  306. return true;
  307. }
  308. }
  309. return false;
  310. }
  311. function setHeadersCss(table,$headers, list, css) {
  312. // remove all header information
  313. $headers.removeClass(css[0]).removeClass(css[1]);
  314. var h = [];
  315. $headers.each(function(offset) {
  316. if(!this.sortDisabled) {
  317. h[this.column] = $(this);
  318. }
  319. });
  320. var l = list.length;
  321. for(var i=0; i < l; i++) {
  322. h[list[i][0]].addClass(css[list[i][1]]);
  323. }
  324. }
  325. function fixColumnWidth(table,$headers) {
  326. var c = table.config;
  327. if(c.widthFixed) {
  328. var colgroup = $('<colgroup>');
  329. $("tr:first td",table.tBodies[0]).each(function() {
  330. colgroup.append($('<col>').css('width',$(this).width()));
  331. });
  332. $(table).prepend(colgroup);
  333. };
  334. }
  335. function updateHeaderSortCount(table,sortList) {
  336. var c = table.config, l = sortList.length;
  337. for(var i=0; i < l; i++) {
  338. var s = sortList[i], o = c.headerList[s[0]];
  339. o.count = s[1];
  340. o.count++;
  341. }
  342. }
  343. /* sorting methods */
  344. function multisort(table,sortList,cache) {
  345. if(table.config.debug) { var sortTime = new Date(); }
  346. var dynamicExp = "var sortWrapper = function(a,b) {", l = sortList.length;
  347. for(var i=0; i < l; i++) {
  348. var c = sortList[i][0];
  349. var order = sortList[i][1];
  350. var s = (getCachedSortType(table.config.parsers,c) == "text") ? ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ? "sortNumeric" : "sortNumericDesc");
  351. var e = "e" + i;
  352. dynamicExp += "var " + e + " = " + s + "(a[" + c + "],b[" + c + "]); ";
  353. dynamicExp += "if(" + e + ") { return " + e + "; } ";
  354. dynamicExp += "else { ";
  355. }
  356. // if value is the same keep orignal order
  357. var orgOrderCol = cache.normalized[0].length - 1;
  358. dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";
  359. for(var i=0; i < l; i++) {
  360. dynamicExp += "}; ";
  361. }
  362. dynamicExp += "return 0; ";
  363. dynamicExp += "}; ";
  364. eval(dynamicExp);
  365. cache.normalized.sort(sortWrapper);
  366. if(table.config.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order+ " time:", sortTime); }
  367. return cache;
  368. };
  369. function sortText(a,b) {
  370. return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  371. };
  372. function sortTextDesc(a,b) {
  373. return ((b < a) ? -1 : ((b > a) ? 1 : 0));
  374. };
  375. function sortNumeric(a,b) {
  376. return a-b;
  377. };
  378. function sortNumericDesc(a,b) {
  379. return b-a;
  380. };
  381. function getCachedSortType(parsers,i) {
  382. return parsers[i].type;
  383. };
  384. /* public methods */
  385. this.construct = function(settings) {
  386. return this.each(function() {
  387. if(!this.tHead || !this.tBodies) return;
  388. var $this, $document,$headers, cache, config, shiftDown = 0, sortOrder;
  389. this.config = {};
  390. config = $.extend(this.config, $.tablesorter.defaults, settings);
  391. // store common expression for speed
  392. $this = $(this);
  393. // build headers
  394. $headers = buildHeaders(this);
  395. // try to auto detect column type, and store in tables config
  396. this.config.parsers = buildParserCache(this,$headers);
  397. // build the cache for the tbody cells
  398. cache = buildCache(this);
  399. // get the css class names, could be done else where.
  400. var sortCSS = [config.cssDesc,config.cssAsc];
  401. // fixate columns if the users supplies the fixedWidth option
  402. fixColumnWidth(this);
  403. // apply event handling to headers
  404. // this is to big, perhaps break it out?
  405. $headers.click(function(e) {
  406. $this.trigger("sortStart");
  407. var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
  408. if(!this.sortDisabled && totalRows > 0) {
  409. // store exp, for speed
  410. var $cell = $(this);
  411. // get current column index
  412. var i = this.column;
  413. // get current column sort order
  414. this.order = this.count++ % 2;
  415. // user only whants to sort on one column
  416. if(!e[config.sortMultiSortKey]) {
  417. // flush the sort list
  418. config.sortList = [];
  419. if(config.sortForce != null) {
  420. var a = config.sortForce;
  421. for(var j=0; j < a.length; j++) {
  422. if(a[j][0] != i) {
  423. config.sortList.push(a[j]);
  424. }
  425. }
  426. }
  427. // add column to sort list
  428. config.sortList.push([i,this.order]);
  429. // multi column sorting
  430. } else {
  431. // the user has clicked on an all ready sortet column.
  432. if(isValueInArray(i,config.sortList)) {
  433. // revers the sorting direction for all tables.
  434. for(var j=0; j < config.sortList.length; j++) {
  435. var s = config.sortList[j], o = config.headerList[s[0]];
  436. if(s[0] == i) {
  437. o.count = s[1];
  438. o.count++;
  439. s[1] = o.count % 2;
  440. }
  441. }
  442. } else {
  443. // add column to sort list array
  444. config.sortList.push([i,this.order]);
  445. }
  446. };
  447. setTimeout(function() {
  448. //set css for headers
  449. setHeadersCss($this[0],$headers,config.sortList,sortCSS);
  450. appendToTable($this[0],multisort($this[0],config.sortList,cache));
  451. },1);
  452. // stop normal event by returning false
  453. return false;
  454. }
  455. // cancel selection
  456. }).mousedown(function() {
  457. if(config.cancelSelection) {
  458. this.onselectstart = function() {return false};
  459. return false;
  460. }
  461. });
  462. // apply easy methods that trigger binded events
  463. $this.bind("update",function() {
  464. // rebuild parsers.
  465. this.config.parsers = buildParserCache(this,$headers);
  466. // rebuild the cache map
  467. cache = buildCache(this);
  468. }).bind("sorton",function(e,list) {
  469. $(this).trigger("sortStart");
  470. config.sortList = list;
  471. // update and store the sortlist
  472. var sortList = config.sortList;
  473. // update header count index
  474. updateHeaderSortCount(this,sortList);
  475. //set css for headers
  476. setHeadersCss(this,$headers,sortList,sortCSS);
  477. // sort the table and append it to the dom
  478. appendToTable(this,multisort(this,sortList,cache));
  479. }).bind("appendCache",function() {
  480. appendToTable(this,cache);
  481. }).bind("applyWidgetId",function(e,id) {
  482. getWidgetById(id).format(this);
  483. }).bind("applyWidgets",function() {
  484. // apply widgets
  485. applyWidget(this);
  486. });
  487. if($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
  488. config.sortList = $(this).metadata().sortlist;
  489. }
  490. // if user has supplied a sort list to constructor.
  491. if(config.sortList.length > 0) {
  492. $this.trigger("sorton",[config.sortList]);
  493. }
  494. // apply widgets
  495. applyWidget(this);
  496. });
  497. };
  498. this.addParser = function(parser) {
  499. var l = parsers.length, a = true;
  500. for(var i=0; i < l; i++) {
  501. if(parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
  502. a = false;
  503. }
  504. }
  505. if(a) { parsers.push(parser); };
  506. };
  507. this.addWidget = function(widget) {
  508. widgets.push(widget);
  509. };
  510. this.formatFloat = function(s) {
  511. var i = parseFloat(s);
  512. return (isNaN(i)) ? 0 : i;
  513. };
  514. this.formatInt = function(s) {
  515. var i = parseInt(s);
  516. return (isNaN(i)) ? 0 : i;
  517. };
  518. this.isDigit = function(s,config) {
  519. var DECIMAL = '\\' + config.decimal;
  520. var exp = '/(^[+]?0(' + DECIMAL +'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)' + DECIMAL +'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*' + DECIMAL +'0+$)/';
  521. return RegExp(exp).test($.trim(s));
  522. };
  523. this.clearTableBody = function(table) {
  524. if($.browser.msie) {
  525. function empty() {
  526. while ( this.firstChild ) this.removeChild( this.firstChild );
  527. }
  528. empty.apply(table.tBodies[0]);
  529. } else {
  530. table.tBodies[0].innerHTML = "";
  531. }
  532. };
  533. }
  534. });
  535. // extend plugin scope
  536. $.fn.extend({
  537. tablesorter: $.tablesorter.construct
  538. });
  539. var ts = $.tablesorter;
  540. // add default parsers
  541. ts.addParser({
  542. id: "text",
  543. is: function(s) {
  544. return true;
  545. },
  546. format: function(s) {
  547. return $.trim(s.toLowerCase());
  548. },
  549. type: "text"
  550. });
  551. ts.addParser({
  552. id: "digit",
  553. is: function(s,table) {
  554. var c = table.config;
  555. return $.tablesorter.isDigit(s,c);
  556. },
  557. format: function(s) {
  558. return $.tablesorter.formatFloat(s);
  559. },
  560. type: "numeric"
  561. });
  562. ts.addParser({
  563. id: "currency",
  564. is: function(s) {
  565. return /^[£$€?.]/.test(s);
  566. },
  567. format: function(s) {
  568. return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));
  569. },
  570. type: "numeric"
  571. });
  572. ts.addParser({
  573. id: "ipAddress",
  574. is: function(s) {
  575. return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
  576. },
  577. format: function(s) {
  578. var a = s.split("."), r = "", l = a.length;
  579. for(var i = 0; i < l; i++) {
  580. var item = a[i];
  581. if(item.length == 2) {
  582. r += "0" + item;
  583. } else {
  584. r += item;
  585. }
  586. }
  587. return $.tablesorter.formatFloat(r);
  588. },
  589. type: "numeric"
  590. });
  591. ts.addParser({
  592. id: "url",
  593. is: function(s) {
  594. return /^(https?|ftp|file):\/\/$/.test(s);
  595. },
  596. format: function(s) {
  597. return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));
  598. },
  599. type: "text"
  600. });
  601. ts.addParser({
  602. id: "isoDate",
  603. is: function(s) {
  604. return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
  605. },
  606. format: function(s) {
  607. return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(new RegExp(/-/g),"/")).getTime() : "0");
  608. },
  609. type: "numeric"
  610. });
  611. ts.addParser({
  612. id: "percent",
  613. is: function(s) {
  614. return /\%$/.test($.trim(s));
  615. },
  616. format: function(s) {
  617. return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));
  618. },
  619. type: "numeric"
  620. });
  621. ts.addParser({
  622. id: "usLongDate",
  623. is: function(s) {
  624. return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));
  625. },
  626. format: function(s) {
  627. return $.tablesorter.formatFloat(new Date(s).getTime());
  628. },
  629. type: "numeric"
  630. });
  631. ts.addParser({
  632. id: "shortDate",
  633. is: function(s) {
  634. return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
  635. },
  636. format: function(s,table) {
  637. var c = table.config;
  638. s = s.replace(/\-/g,"/");
  639. if(c.dateFormat == "us") {
  640. // reformat the string in ISO format
  641. s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
  642. } else if(c.dateFormat == "uk") {
  643. //reformat the string in ISO format
  644. s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
  645. } else if(c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
  646. s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
  647. }
  648. return $.tablesorter.formatFloat(new Date(s).getTime());
  649. },
  650. type: "numeric"
  651. });
  652. ts.addParser({
  653. id: "time",
  654. is: function(s) {
  655. return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
  656. },
  657. format: function(s) {
  658. return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
  659. },
  660. type: "numeric"
  661. });
  662. ts.addParser({
  663. id: "metadata",
  664. is: function(s) {
  665. return false;
  666. },
  667. format: function(s,table,cell) {
  668. var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
  669. return $(cell).metadata()[p];
  670. },
  671. type: "numeric"
  672. });
  673. // add default widgets
  674. ts.addWidget({
  675. id: "zebra",
  676. format: function(table) {
  677. if(table.config.debug) { var time = new Date(); }
  678. $("tr:visible",table.tBodies[0])
  679. .filter(':even')
  680. .removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0])
  681. .end().filter(':odd')
  682. .removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);
  683. if(table.config.debug) { $.tablesorter.benchmark("Applying Zebra widget", time); }
  684. }
  685. });
  686. })(jQuery);