jquery.tablesorter.js 25 KB

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