A compact, versatile library


/ Published in: JavaScript
Save to your folder(s)

This is my own (compact) JS library which contains a variety of methods - cookies, (fast) sorting of tables,paragraphs, etc., highlighting rows, moving elements up or down, converting strings to dates, updating a clock etc.. Include the library and add a JS line such as 'var adg = new AndyG_ns.ADG_Utils();' to access the methods.
The ADG_Drag class is not mine - if anyone knows the author please advise me and I will acknowledge. Andy.


Copy this code and paste it in your HTML
  1. //This prototype is provided by the Mozilla foundation and is distributed under the MIT license.
  2. if (!Array.prototype.every) { //http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
  3. Array.prototype.every = function(fun /*, thisp*/) {
  4. var len = this.length; // required if browser doesn't support 'every()' - IE!!
  5. if (typeof fun !== "function")
  6. throw new TypeError();
  7. var thisp = arguments[1];
  8. for (var i = 0; i < len; i++) {
  9. if (i in this && !fun.call(thisp, this[i], i, this))
  10. return false;
  11. }
  12. return true;
  13. };
  14. }
  15. if (!Array.prototype.some) { // required if browser doesn't support the 'some()' method
  16. Array.prototype.some = function(fun /*, thisp */) { // this code must remain 'as is'
  17. "use strict";
  18. if (this === void 0 || this === null)
  19. throw new TypeError();
  20. var t = Object(this);
  21. var len = t.length >>> 0;
  22. if (typeof fun !== "function")
  23. throw new TypeError();
  24. var thisp = arguments[1];
  25. for (var i = 0; i < len; i++) {
  26. if (i in t && fun.call(thisp, t[i], i, t))
  27. return true;
  28. }
  29. return false;
  30. };
  31. }
  32. if (!Array.prototype.indexOf) {
  33. Array.prototype.indexOf = function(elt /*, from*/) {
  34. var len = this.length;
  35. var from = Number(arguments[1]) || 0;
  36. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  37. if (from < 0)
  38. from += len;
  39. for (; from < len; from++) {
  40. if (from in this && this[from] === elt)
  41. return from;
  42. }
  43. return -1;
  44. };
  45. }
  46.  
  47. // Create an empty namespace:
  48. var AndyG_ns = AndyG_ns || {};
  49. AndyG_ns._construct = function () {
  50. function ADG_Utils () { // my Class
  51. var MonthNames = ["January","February","March","April","May","June","July",
  52. "August","September","October","November","December"];
  53. var DayNames = [ "Sunday","Monday","Tueday","Wednesday","Thursday","Friday","Saturday" ];
  54. var ShortMths = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  55. var ShortDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  56.  
  57. var Left = function (str,n) { // returns characters from the left of a string
  58. if ( n <= 0 ) return "";
  59. return ( (n > String(str).length) ? str : String(str).substring(0,n) );
  60. }
  61. var Right = function (str, n) { // returns characters from the right of a string
  62. if (n <= 0) return "";
  63. else if (n > String(str).length)
  64. return str;
  65. else
  66. return String(str).substring(String(str).length-n, n);
  67. }
  68. var TrimLR = function (text) { // would trim leading and trailiing spaces v.fast (Steven Levithan)
  69. text = text.replace(/^\s+/, "");
  70. for (var i = text.length - 1; i >= 0; i--) {
  71. if (/\S/.test(text.charAt(i))) {
  72. text = text.substring(0, i + 1);
  73. break;
  74. }
  75. }
  76. return text;
  77. }
  78. var $ = function () { // Example: var els = $('obj1name',obj2,'obj2name');
  79. var elements = {}, doc, argLen, i, element; // Saves having to write 'document.getElementById' repeatedly,
  80. doc = document; // but could also be useful for grouping elements.
  81. argLen = arguments.length;
  82. for (i = 0, element; i < argLen; i++) {
  83. element = arguments[i];
  84. if (typeof element === 'string')
  85. element = doc.getElementById(element);
  86. if (argLen === 1)
  87. return element;
  88. elements.push(element);
  89. }
  90. return elements;
  91. }
  92. var DeleteEl = function (el) {
  93. var elem = $(el);
  94. elem.parentNode.removeChild(elem);
  95. }
  96. var DisplayMsg = function (oMsg,sMsg,colour) { // uses a hidden span to display any message (for 2 secs)
  97. var msgObj = $(oMsg); // clicking a message will cancel future messages
  98. if ( (msgObj.firstChild.nodeValue !== 'messages cancelled') && sMsg ) {
  99. msgObj.style.color = colour || 'green'; // the default text colour is green
  100. msgObj.firstChild.nodeValue = sMsg;
  101. msgObj.style.display = 'inline';
  102. window.setTimeout(function () { msgObj.style.display = 'none'; } ,2000);
  103. }
  104. }
  105. var MoveElDown = function (container,elem) {
  106. // Moves elem to the bottom of the container. For example, moves a paragraph to the end of
  107. // it's containing DIV. If the element is already the last one, moves it to the top.
  108. var firstElem;
  109. if (elem.nextSibling) // move element to end of container
  110. container.appendChild(elem);
  111. else { // element is already the last one..
  112. firstElem = container.getElementsByTagName(elem.nodeName)[0]; // get the 1st element in the container
  113. container.insertBefore(elem,firstElem); // insert the current paragraph before it
  114. }
  115. }
  116. var MoveElDownwards = function (container,elem) {
  117. // Moves an element one place further down within it's container.
  118. // If the element is already at the bottom, moves it to the top.
  119. var nextElem, firstElem;
  120. if (elem.nextSibling) {
  121. nextElem = elem.nextSibling;
  122. if (nextElem.nextSibling)
  123. container.insertBefore(elem,nextElem.nextSibling);
  124. else
  125. container.appendChild(elem);
  126. } else {
  127. firstElem = container.getElementsByTagName(elem.nodeName)[0];
  128. container.insertBefore(elem,firstElem);
  129. }
  130. }
  131. var MoveElUp = function (container,elem) {
  132. var firstElem;
  133. if (elem.previousSibling) {
  134. firstElem = container.getElementsByTagName(elem.nodeName)[0];
  135. container.insertBefore(elem,firstElem);
  136. } else {
  137. container.appendChild(elem);
  138. }
  139. }
  140. var MoveElUpwards = function (container, elem) {
  141. if (elem.previousSibling)
  142. container.insertBefore(elem,elem.previousSibling);
  143. else
  144. container.appendChild(elem); // must be at the top
  145. }
  146. var RemoveToolTips = function (mins) {
  147. if ( document.getElementsByTagName('button') ) { // if there are any buttons
  148. window.setInterval(function () { // hide tooltips after 5 mins, by removing the
  149. // 'title' attribute from all buttons
  150. var btns = document.getElementsByTagName('button');
  151. var i = btns.length;
  152. while ( i-- ) btns[i].removeAttribute('title');
  153. }, mins * 60 * 1000);
  154. }
  155. }
  156. /*
  157. Developed by Robert Nyman, http://www.robertnyman.com
  158. Code/licensing: http://code.google.com/p/getelementsbyclassname/
  159. */
  160. var getElementsByClassName = function (className, tag, elm) {
  161. if (document.getElementsByClassName) { // use built-in method
  162. getElementsByClassName = function (className, tag, elm) {
  163. elm = elm || document;
  164. var elements = elm.getElementsByClassName(className),
  165. nodeName = (tag) ? new RegExp("\\b" + tag + "\\b", "i") : null,
  166. returnElements = [], current;
  167. for(var i=0, il=elements.length; i < il; i++){
  168. current = elements[i];
  169. if(!nodeName || nodeName.test(current.nodeName)) {
  170. returnElements.push(current);
  171. }
  172. }
  173. return returnElements;
  174. };
  175. }
  176. else if (document.evaluate) { // using XPath
  177. getElementsByClassName = function (className, tag, elm) {
  178. tag = tag || "*";
  179. elm = elm || document;
  180. var classes = className.split(" "), classesToCheck = "",
  181. xhtmlNamespace = "http://www.w3.org/1999/xhtml",
  182. namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
  183. returnElements = [], elements, node;
  184. for(var j=0, jl=classes.length; j < jl; j++) {
  185. classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
  186. }
  187. try {
  188. elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
  189. }
  190. catch (e) {
  191. elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
  192. }
  193. while ((node = elements.iterateNext())) {
  194. returnElements.push(node);
  195. }
  196. return returnElements;
  197. };
  198. } else {
  199. getElementsByClassName = function (className, tag, elm) {
  200. tag = tag || "*";
  201. elm = elm || document;
  202. var classes = className.split(" "), classesToCheck = [],
  203. elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
  204. current, returnElements = [], match;
  205. for(var k=0, kl=classes.length; k < kl; k++) {
  206. classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
  207. }
  208. for(var l=0, ll=elements.length; l < ll; l++) {
  209. current = elements[l];
  210. match = false;
  211. for(var m=0, ml=classesToCheck.length; m < ml; m++) {
  212. match = classesToCheck[m].test(current.className);
  213. if (!match) {
  214. break;
  215. }
  216. }
  217. if (match) {
  218. returnElements.push(current);
  219. }
  220. }
  221. return returnElements;
  222. };
  223. }
  224. return getElementsByClassName(className, tag, elm);
  225. }
  226. var ResetAll = function (aFrm) { // clears all text and checkboxes within a form
  227. var allInputs, i, inp, frm = $(aFrm);
  228. if ( !confirm('Clear text-boxes and untick check-boxes?') ) return false;
  229. allInputs = frm.getElementsByTagName('input');
  230. i = allInputs.length;
  231. while ( i-- ) {
  232. inp = allInputs[i];
  233. if ( inp.type === 'text' ) inp.value = '';
  234. else if ( inp.type === 'checkbox' ) inp.checked = false;
  235. }
  236. return true;
  237. }
  238. var SetCookie = function ( name, value, expires, path, domain, secure ) {
  239. // the caller should Trim the name/value pair
  240. // sets the name/value pair (encoded) - 'expires' is the number of days
  241. var expires_date;
  242. if (expires) {
  243. expires_date = new Date();
  244. expires_date.setDate(expires_date.getDate() + expires);
  245. }
  246. document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) +
  247. ( ( expires ) ? ";expires=" + expires_date.toUTCString() : "" ) +
  248. ( ( path ) ? ";path=" + path : "" ) +
  249. ( ( domain ) ? ";domain=" + domain : "" ) +
  250. ( ( secure ) ? ";secure" : "" );
  251. }
  252. var DeleteCookie = function ( name, path, domain ) { // the caller should Trim the name/value pair
  253. document.cookie = encodeURIComponent(name) + "=" + // encodes the name before deleting
  254. ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) +
  255. ";expires=Fri, 01-Jan-2010 00:00:01 UTC";
  256. }
  257. var DelAllCookies = function () {
  258. var currDate = new Date(), i;
  259. var theCookie = document.cookie.split(";");
  260. currDate = currDate.toUTCString();
  261. i = theCookie.length;
  262. while ( i-- ) {
  263. document.cookie = theCookie[i] + "; expires =" + currDate;
  264. }
  265. }
  266. // The following four functions do not Trim the name or value before use - the calling fns should do this.
  267. var Name_Exists = function ( cookie_name ) { // case-insensitive
  268. var testName, myReg;
  269. if (document.cookie.length == 0) return false;
  270. testName = cookie_name.EscapeR();
  271. myReg = new RegExp('(^|;) ?' + testName + '=([^;]*)(;|$)','i');
  272. return myReg.test(decodeURIComponent(document.cookie));
  273. }
  274. var Value_Exists = function ( cookie_value ) { // case insensitive
  275. var testName, myReg;
  276. if (document.cookie.length == 0) return false;
  277. testName = cookie_value.EscapeR();
  278. myReg = new RegExp('(=)' + testName + '(;|$)','i');
  279. return myReg.test(decodeURIComponent(document.cookie));
  280. }
  281. var Get_Name = function ( cookie_value ) { // (case-insensitive)
  282. var testName, myReg, results;
  283. if (document.cookie.length == 0) return '';
  284. testName = cookie_value.EscapeR();
  285. myReg = new RegExp('(^|;) ?([^=]*)=' + testName + '(;|$)','i');
  286. results = decodeURIComponent(document.cookie).match(myReg);
  287. return ( results ) ? results[2] : '';
  288. }
  289. var Get_Value = function ( cookie_name ) { // (case-insensitive)
  290. var testName, myReg, results;
  291. if (document.cookie.length == 0) return '';
  292. testName = cookie_name.EscapeR();
  293. myReg = new RegExp('(^|;) ?' + testName + '=([^;]*)(;|$)','i');
  294. results = decodeURIComponent(document.cookie).match(myReg);
  295. return ( results ) ? results[2] : '';
  296. }
  297. var GetCookieStr = function () { // returns a string which could be placed in a textarea (for example)
  298. return decodeURIComponent(document.cookie).replace(/([^=;]+)=([^;]*)[;\s]*/g,'$1 ($2)\n') || '';
  299. }
  300. var Asc = function (a, b) { // used by sort() method (case insensitive)
  301. var x = a.toLowerCase();
  302. var y = b.toLowerCase();
  303. return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  304. }
  305. var Desc = function (a, b) { // used by sort() method (case insensitive)
  306. var x = a.toLowerCase();
  307. var y = b.toLowerCase();
  308. return ((x > y) ? -1 : ((x < y) ? 1 : 0));
  309. }
  310. var SortNum = function(a, b) {
  311. return a-b;
  312. }
  313. var IsAscending = function (element, index, array) { // used by every() method
  314. return ( index == 0 || element.toLowerCase() >= array[index-1].toLowerCase() );
  315. }
  316. var IsDescending = function (element, index, array) { // used by every() method
  317. return ( index == 0 || element.toLowerCase() <= array[index-1].toLowerCase() );
  318. }
  319. var SortElements = function (parentEl, childTag, colTag, colIndex) { // example use: SortElements('table1','tr','td',2)
  320. var i, j, cTags = {}; // or SortElements('list1','li')
  321. var parent, childLen, aChild, elem; // or SortElements('divName','p','span',3)
  322. var origKey, origKeys={}, sortedKeys=[], keyNo='', sortedLen, sorted, frag;
  323.  
  324. parent = $(parentEl);
  325. cTags = parent.getElementsByTagName(childTag);
  326. for ( i = 0, childLen = cTags.length; i < childLen; i++ ) { // go forward examining each child
  327. aChild = cTags[i];
  328. elem = (colTag) ? aChild.getElementsByTagName(colTag)[colIndex] : aChild;
  329. if ( elem ) {
  330. origKey = elem.getAttribute('sort') || elem.firstChild.nodeValue;
  331. // you can supply 'sort' attributes to enable correct sorting of numbers or dates.
  332. // For example, <td sort='2011/02/12'> for a date.
  333. keyNo = origKey + (10000 + i); // need to ensure unique keys - means we can only sort 9999 items!
  334. origKeys[keyNo] = aChild; // (browsers can't cope with anything like this no of rows.)
  335. sortedKeys[sortedKeys.length] = keyNo;
  336. }
  337. }
  338. sorted = sortedKeys.every(IsAscending);
  339. sortedKeys.sort(Asc);
  340. if ( sorted ) { // if they were already in Asc order..
  341. sortedKeys.reverse();
  342. }
  343. frag = document.createDocumentFragment();
  344. for (i = 0, sortedLen = sortedKeys.length; i < sortedLen; i++) {
  345. frag.appendChild(origKeys[sortedKeys[i]]);
  346. }
  347. parent.appendChild(frag);
  348. sortedKeys = null; // probably not necessary as the array goes out of scope
  349. return sorted; // t/f was the list already in ascending order?
  350. }
  351. var ApplyFilter = function (txt,tbl,col) { // filters a table by a specified column index
  352. var theTable = $(tbl), i, theRow, cellText;
  353.  
  354. txt = txt.toLowerCase();
  355. i = theTable.rows.length;
  356. while ( --i ) { // ignore the first (header) row
  357. theRow = theTable.rows[i];
  358. cellText = theRow.cells[col].firstChild.nodeValue.toLowerCase();
  359. theRow.style.display = ( cellText.indexOf(txt)+1 ) ? '' : 'none';
  360. }
  361. }
  362. var AlignTables = function (tbl, cols, direction) { // cols is an array identifying which
  363. var i, j, r, colLen, rLen; // column nos. to align. Direction should be 'left', 'center'
  364. var dirs = ['left','center','right']; // or 'right'. Use this to amend an existing table.
  365. // Ignores the first row (assumes it's a header row).
  366. if ( dirs.indexOf(direction) < 0 ) {
  367. return false; // direction should be left, center or right
  368. }
  369. tbl = $(tbl);
  370. for ( i = 1, rLen = tbl.rows.length; i < rLen; i++) {
  371. r = tbl.rows[i];
  372. for ( j = 0, colLen = cols.length; j < colLen; j++)
  373. r.cells[cols[j]].style.textAlign = direction;
  374. }
  375. return true;
  376. }
  377. var AddSortToTables = function () { // if table attribute 'sortIt="yes"'
  378. var tables, i, j, tblLen, tbl, hdrs, aHdr, hdrsLen;
  379. function PreserveSortScope(a,b,c,d) { // used when table attribute sortIt = "yes"
  380. return function() { // assigns the SortElements fn. to a table header
  381. SortElements(a,b,c,d);
  382. }
  383. }
  384. tables = document.getElementsByTagName('table'); // add sorting to table headers,
  385. for ( i = 0, tblLen = tables.length; i < tblLen; i++ ) { // if they have attribute sortIt="yes"
  386. tbl = tables[i];
  387. if ( tbl.getAttribute('sortIt') && tbl.getAttribute('sortIt') == 'yes' ) {
  388. hdrs = tbl.getElementsByTagName('th');
  389. if ( hdrs ) {
  390. for ( j = 0, hdrsLen=hdrs.length; j < hdrsLen; j++ ) {
  391. aHdr = hdrs[j];
  392. AddEvent(aHdr,'click',PreserveSortScope(tbl,'tr','td',j));
  393. }
  394. }
  395. }
  396. }
  397. }
  398. var AddSortByDate = function (tbl,col,dateMask) {
  399. // Input: the table name (or object), a column index, and a date mask e.g. 'dd-mmm-yy'
  400. // Adds a sort attribute to every cell to enable sorting correctly by date.
  401. // (ignores the first row, assuming it is a header row.)
  402. var i, rLen, cell;
  403. tbl = $(tbl);
  404. for ( i = 1, rLen = tbl.rows.length; i < rLen; i++) {
  405. cell = tbl.rows[i].cells[col];
  406. cell.setAttribute('sort',StringToDate(cell.firstChild.nodeValue,dateMask));
  407. }
  408. return true;
  409. }
  410. var AddSortByNumber = function (tbl, col) {
  411. // (ignores the first row, assuming it is a header row.)
  412. var i, rLen, cell, tempNum;
  413. tbl = $(tbl);
  414. for ( i = 1, rLen = tbl.rows.length; i < rLen; i++) {
  415. cell = tbl.rows[i].cells[col];
  416. tempNum = cell.firstChild.nodeValue;
  417. tempNum = tempNum.replace(/[^0-9.]/g,'');
  418. tempNum = 10000000000000 + parseFloat(tempNum);
  419. cell.setAttribute('sort',tempNum);
  420. }
  421. return true;
  422. }
  423. var HighlightRows = function (tbl,colour,withIndex) {
  424. // Supply the table name (or object) and the colour you want for the highlight
  425. // E.g. HighlightRows('table1','yellow')
  426. // Any row background colour will be re-instated on mouseout; if a cell already
  427. // has a background colour this will remain.
  428. // If withIndex (optional) is true, pointing at a row will show a tooltip 'Row 24'.
  429. var OnMouseOver = function (e) {
  430. var evt = e || window.event;
  431. var elem = evt.target || evt.srcElement;
  432. if ( elem.nodeName == 'TD' ) {
  433. elem.prevColour = elem.parentNode.style.backgroundColor;
  434. elem.parentNode.style.backgroundColor = colour;
  435. if (withIndex == true) elem.setAttribute('title','Row ' + elem.parentNode.rowIndex);
  436. }
  437. };
  438. var OnMouseOut = function (e) {
  439. var evt = e || window.event;
  440. var elem = evt.target || evt.srcElement;
  441. if ( elem.nodeName == 'TD' ) {
  442. elem.parentNode.style.backgroundColor = elem.prevColour;
  443. }
  444. };
  445. tbl = $(tbl);
  446. AddEvent(tbl,'mouseover',OnMouseOver);
  447. AddEvent(tbl,'mouseout',OnMouseOut);
  448. }
  449. var GetToday = function (sFormat) { // returns a string with today's date
  450. var currDT = new Date();
  451. var D = currDT.getDate();
  452. var DDDD = DayNames[currDT.getDay()];
  453. var DDD = DDDD.substr(0,3);
  454. var M = currDT.getMonth()+1;
  455. var MMMM = MonthNames[currDT.getMonth()];
  456. var MMM = MMMM.substr(0,3);
  457. var YYYY = currDT.getFullYear();
  458. var YY = ('' + YYYY).substr(2,2);
  459. var H = currDT.getHours();
  460. var N = currDT.getMinutes();
  461. var S = currDT.getSeconds();
  462. var DD = ( D < 10 ? "0" : "" ) + D; // Pad with leading zeros, if required
  463. var MM = ( M < 10 ? "0" : "" ) + M;
  464. var HH = ( H < 10 ? "0" : "" ) + H;
  465. var NN = ( N < 10 ? "0" : "" ) + N;
  466. var SS = ( S < 10 ? "0" : "" ) + S;
  467.  
  468. sFormat = ( sFormat ) ? sFormat.toUpperCase() : 'DD/MM/YYYY';
  469. var sParsed = sFormat.replace(/D{1,4}|M{1,4}|Y{2,4}|H{1,2}|N{1,2}|S{1,2}/g,function (m) {
  470. try {
  471. return eval(m);
  472. } catch (e) {
  473. return '';
  474. }
  475. });
  476. return sParsed;
  477. }
  478. var FormatDate = function (sFormat, aDate) {
  479. // Example use: FormatDate('ddd, dd mmm YYYY hh:nn'); - use 'nn' for mins
  480. // If aDate is not supplied the current date is assumed.
  481. var currDT = aDate || new Date();
  482.  
  483. sFormat = sFormat.toUpperCase();
  484. function ReplaceDTChars(match) {
  485. switch (match) {
  486. case 'D': return currDT.getDate();
  487. case 'DD':
  488. var currDate = currDT.getDate();
  489. return ( currDate < 10 ? "0" : "" ) + currDate;
  490. case 'DDD': return DayNames[currDT.getDay()].substring(0,3);
  491. case 'DDDD': return DayNames[currDT.getDay()];
  492. case 'M': return currDT.getMonth()+1;
  493. case 'MM':
  494. var currMonth = currDT.getMonth()+1;
  495. return ( currMonth < 10 ? "0" : "" ) + currMonth;
  496. case 'MMM': return MonthNames[currDT.getMonth()].substring(0,3);
  497. case 'MMMM': return MonthNames[currDT.getMonth()];
  498. case 'Y':
  499. case 'YY': return ('' + currDT.getFullYear()).substring(2);
  500. case 'YYY':
  501. case 'YYYY': return '' + currDT.getFullYear();
  502. case 'H': return currDT.getHours();
  503. case 'HH':
  504. var currHr = currDT.getHours();
  505. return ( currHr < 10 ? "0" : "" ) + currHr;
  506. case 'N': return currDT.getMinutes();
  507. case 'NN':
  508. var currMin = currDT.getMinutes();
  509. return ( currMin < 10 ? "0" : "" ) + currMin;
  510. case 'S': return currDT.getSeconds();
  511. case 'SS':
  512. var currSecs = currDT.getSeconds();
  513. return ( currSecs < 10 ? "0" : "" ) + currSecs;
  514. default: return match;
  515. }
  516. }
  517. return sFormat.replace(/D{1,4}|M{1,4}|Y{1,4}|H{1,2}|N{1,2}|S{1,2}/g,function(m){return ReplaceDTChars(m)});
  518. }
  519. function StringToDate(sDate, sFormat, cutOff) {
  520. // Input: a date value as a string, it's format as a string e.g. 'dd-mmm-yy'
  521. // Optional: a cutoff (integer) for 2 digit years.
  522. // If no 'd' appears in the format string then the 1st of the month is assumed.
  523. // If the year is 20 and the cut-off is 30 then the value will be converted to 2020;
  524. // if the year is 40 then this will be converted to 1940.
  525. // If no cut-off is supplied then '20' will be pre-pended to the year (YY).
  526. // Output: a string in the format 'YYYY/MM/DD' or ''
  527. // Will not attempt to convert certain combinations e.g. DMM, MDD, DDM, YYYYD
  528. var sParsed, fndSingle; // sParsed will be constructed in the format 'YYYY/MM/DD'
  529. sDate = sDate.toString().toUpperCase();
  530. sFormat = sFormat.toUpperCase();
  531.  
  532. if (sFormat.search(/MMMM|MMM/) + 1) { // replace Mar/March with 03, etc.
  533. sDate = sDate.replace(new RegExp('(' + ShortMths.join('|') + ')[A-Z]*', 'g'), function(m){
  534. var i = ShortMths.indexOf(m.substr(0, 3)) + 1;
  535. return ((i < 10) ? "0" + i : "" + i).toString();
  536. });
  537. sFormat = sFormat.replace(/MMMM|MMM/g, 'MM');
  538. }
  539. if (sFormat.search(/DDDD|DDD/) + 1) { // replace Tue/Tuesday, etc. with ''
  540. sDate = sDate.replace(new RegExp('(' + ShortDays.join('|') + ')[A-Z]*', 'g'), '');
  541. sFormat = sFormat.replace(/DDDD|DDD/g, '');
  542. }
  543. sDate = sDate.replace(/(^|\D)(\d)(?=\D|$)/g, function($0, $1, $2){ // single digits 2 with 02
  544. return $1 + '0' + $2;
  545. });
  546. sFormat = sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g, function($0, $1, $2){
  547. return $1 + $2 + $2; // replace D or M with DD and MM
  548. });
  549. fndSingle = sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/)+1; // are there still single Ds or Ms?
  550. if ( fndSingle ) return ''; // do not attempt to parse, for example, 'DMM'
  551. sFormat = sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g, function($0, $1, $2, index){
  552. var tempDate = sDate.substr(0, index + 1);
  553. tempDate += (cutOff) ? ((parseInt(sDate.substr(index + 1, 2)) > cutOff) ? '19' : '20') : '20';
  554. tempDate += sDate.substr(index + 1);
  555. sDate = tempDate;
  556. return $1 + $2 + $2;
  557. });
  558. sParsed = ('YYYY/MM/DD').replace(/YYYY|MM|DD/g, function(m){
  559. return (sFormat.indexOf(m) + 1) ? sDate.substr(sFormat.indexOf(m), m.length) : '';
  560. });
  561. if (sParsed.charAt(0) == '/') { // if no year specified, assume the current year
  562. sParsed = (new Date().getFullYear()) + sParsed;
  563. }
  564. if (sParsed.charAt(sParsed.length - 1) == '/') { // if no date, assume the 1st of the month
  565. sParsed += '01';
  566. }
  567. return ( sParsed.length == 10 ) ? sParsed : ''; // should end up with 10 characters..
  568. }
  569. var StartClock = function (clockID, sFormat) { // supply the id of the clock or an object
  570. var theClock = $(clockID);
  571. sFormat = sFormat || 'hh:nn';
  572. if ( theClock ) { // if there is a clock
  573. theClock.firstChild.nodeValue = GetToday(sFormat); // start the clock
  574. ( function () { setInterval( function () { // this is called a 'closure'
  575. this.clock = theClock.firstChild;
  576. clock.nodeValue = GetToday(sFormat); },3000); }
  577. ) (); // updates the clock every three seconds
  578. }
  579. }
  580. var GetParam = function (name) { // get named parameter from url
  581. var regexS = "[\\?&]"+name+"=([^&#]*)";
  582. var regex = new RegExp( regexS,'i' ); // case insensitive
  583. var results = regex.exec( window.location.href );
  584. return (results == null) ? "" : decodeURIComponent(results[1]);
  585. }
  586. var Delay = function (mills) { // cause an 'artificial' delay of mills (milliseconds)
  587. var date = new Date();
  588. var curDate = null;
  589. do { curDate = new Date(); }
  590. while (curDate-date < mills);
  591. }
  592. var AddEvent = function (elem, eventType, func) {
  593. if ( elem.addEventListener )
  594. elem.addEventListener(eventType, func, false);
  595. else if ( elem.attachEvent )
  596. elem.attachEvent('on' + eventType, func);
  597. else
  598. elem['on' + eventType] = func;
  599. }
  600. var RemoveEvent = function (elem, eventType, func) {
  601. if ( elem.removeEventListener )
  602. elem.removeEventListener(eventType, func, false);
  603. else if ( elem.detachEvent )
  604. elem.detachEvent('on' + eventType, func);
  605. else
  606. elem['on' + eventType] = null;
  607. }
  608. // Expose class methods:
  609. // String functions/ methods ***********************************************
  610. this.Left = Left;
  611. this.Right = Right;
  612. this.TrimLR = TrimLR;
  613. // DOM functions ***********************************************************
  614. this.$ = $;
  615. this.DeleteEl = DeleteEl;
  616. this.DisplayMsg = DisplayMsg;
  617. this.MoveElDown = MoveElDown;
  618. this.MoveElDownwards = MoveElDownwards;
  619. this.MoveElUp = MoveElUp;
  620. this.MoveElUpwards = MoveElUpwards;
  621. this.RemoveToolTips = RemoveToolTips;
  622. this.getElementsByClassName = getElementsByClassName;
  623. // Form functions **********************************************************
  624. this.ResetAll = ResetAll;
  625. // Cookie functions ********************************************************
  626. this.SetCookie = SetCookie;
  627. this.DeleteCookie = DeleteCookie;
  628. this.DelAllCookies = DelAllCookies;
  629. this.Name_Exists = Name_Exists;
  630. this.Value_Exists = Value_Exists;
  631. this.Get_Name = Get_Name;
  632. this.Get_Value = Get_Value;
  633. this.GetCookieStr = GetCookieStr;
  634. // Sort functions **********************************************************
  635. this.Asc = Asc;
  636. this.Desc = Desc;
  637. this.SortNum = SortNum;
  638. this.IsAscending = IsAscending;
  639. this.IsDescending = IsDescending;
  640. this.SortElements = SortElements;
  641. // Table functions *********************************************************
  642. this.ApplyFilter = ApplyFilter;
  643. this.AlignTables = AlignTables;
  644. this.AddSortToTables = AddSortToTables; // uses the Sort functions
  645. this.AddSortByDate = AddSortByDate;
  646. this.AddSortByNumber = AddSortByNumber;
  647. this.HighlightRows = HighlightRows;
  648. // Date/Time functions *****************************************************
  649. this.GetToday = GetToday;
  650. this.FormatDate = FormatDate;
  651. this.StringToDate = StringToDate;
  652. this.StartClock = StartClock;
  653. // Miscellaneous ***********************************************************
  654. this.GetParam = GetParam;
  655. this.Delay = Delay;
  656. this.AddEvent = AddEvent;
  657. this.RemoveEvent = RemoveEvent;
  658. }
  659. function ADG_Drag() { // Class : allow draggable elements
  660. this._startX; this._startY; // mouse starting positions
  661. this._offsetX; this._offsetY; // current element offsets
  662. this._dragElement; // needs to be passed from OnMouseDown to OnMouseMove
  663. this._oldZIndex; // we temporarily increase the z-index during drag
  664.  
  665. var InitDragDrop = function () {
  666. _startX = 0; _startY = 0;
  667. _offsetX = 0; _offsetY = 0;
  668. _oldZIndex = 0;
  669. document.onmousedown = OnMouseDown;
  670. document.onmouseup = OnMouseUp;
  671. };
  672. var OnMouseDown = function (e) {
  673. if (e == null) e = window.event; // IE is retarded and doesn't pass the event object
  674. var target = e.target != null ? e.target : e.srcElement; // IE uses srcElement, others use target
  675. // for IE, left click == 1; for Firefox, left click == 0
  676. if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'dragIt') { // grab the mouse position
  677. _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position
  678. _offsetX = ExtractNumber(target.style.left);
  679. _offsetY = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged
  680. _oldZIndex = target.style.zIndex; target.style.zIndex = 100; // we need to access the element in OnMouseMove
  681. _dragElement = target; // tell our code to start moving the element with the mouse
  682. document.onmousemove = OnMouseMove; // cancel out any text selections
  683. document.body.focus(); // prevent text selection in IE
  684. document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image
  685. target.ondragstart = function() { return false; }; // prevent text selection (except IE)
  686. return false;
  687. }
  688. };
  689. var OnMouseMove = function (e) {
  690. if (e == null) var e = window.event; // this is the actual "drag code"
  691. _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
  692. _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
  693. };
  694. var OnMouseUp = function (e) { // When the mouse is released, we remove the event handlers and reset _dragElement:
  695. if (_dragElement != null) {
  696. _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown
  697. document.onmousemove = null;
  698. document.onselectstart = null;
  699. _dragElement.ondragstart = null; // this is how we know we're not dragging
  700. _dragElement = null;
  701. }
  702. };
  703. var ExtractNumber = function (value) {
  704. var n = parseInt(value);
  705. return n == null || isNaN(n) ? 0 : n;
  706. };
  707. this.InitDragDrop = InitDragDrop; // only need to expose this method
  708. }
  709.  
  710. this.ADG_Utils = ADG_Utils; // expose the classes
  711. this.ADG_Drag = ADG_Drag;
  712. }
  713.  
  714. AndyG_ns._construct();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.