utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. // Some general purpose JS functions for the iTop application
  2. //IE 8 compatibility, copied from: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/IndexOf
  3. if (!Array.prototype.indexOf) {
  4. if (false) // deactivated since it causes troubles: for(k in aData) => returns the indexOf function as first element on empty arrays !
  5. {
  6. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  7. "use strict";
  8. if (this == null) {
  9. throw new TypeError();
  10. }
  11. var t = Object(this);
  12. var len = t.length >>> 0;
  13. if (len === 0) {
  14. return -1;
  15. }
  16. var n = 0;
  17. if (arguments.length > 1) {
  18. n = Number(arguments[1]);
  19. if (n != n) { // shortcut for verifying if it's NaN
  20. n = 0;
  21. } else if (n != 0 && n != Infinity && n != -Infinity) {
  22. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  23. }
  24. }
  25. if (n >= len) {
  26. return -1;
  27. }
  28. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  29. for (; k < len; k++) {
  30. if (k in t && t[k] === searchElement) {
  31. return k;
  32. }
  33. }
  34. return -1;
  35. }
  36. }
  37. }
  38. /**
  39. * Reload a truncated list
  40. */
  41. aTruncatedLists = {}; // To keep track of the list being loaded, each member is an ajaxRequest object
  42. function ReloadTruncatedList(divId, sSerializedFilter, sExtraParams)
  43. {
  44. $('#'+divId).block();
  45. //$('#'+divId).blockUI();
  46. if (aTruncatedLists[divId] != undefined)
  47. {
  48. try
  49. {
  50. aAjaxRequest = aTruncatedLists[divId];
  51. aAjaxRequest.abort();
  52. }
  53. catch(e)
  54. {
  55. // Do nothing special, just continue
  56. console.log('Uh,uh, exception !');
  57. }
  58. }
  59. aTruncatedLists[divId] = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style=list',
  60. { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
  61. function(data)
  62. {
  63. aTruncatedLists[divId] = undefined;
  64. if (data.length > 0)
  65. {
  66. $('#'+divId).html(data);
  67. $('#'+divId+' .listResults').tableHover(); // hover tables
  68. $('#'+divId+' .listResults').each( function()
  69. {
  70. var table = $(this);
  71. var id = $(this).parent();
  72. aTruncatedLists[divId] = undefined;
  73. var checkbox = (table.find('th:first :checkbox').length > 0);
  74. if (checkbox)
  75. {
  76. // There is a checkbox in the first column, don't make it sortable
  77. table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager")}); // sortable and zebra tables
  78. }
  79. else
  80. {
  81. // There is NO checkbox in the first column, all columns are considered sortable
  82. table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager"), totalRows:97, filter: sSerializedFilter, extra_params: sExtraParams }); // sortable and zebra tables
  83. }
  84. });
  85. $('#'+divId).unblock();
  86. }
  87. }
  88. );
  89. }
  90. /**
  91. * Truncate a previously expanded list !
  92. */
  93. function TruncateList(divId, iLimit, sNewLabel, sLinkLabel)
  94. {
  95. $('#'+divId).block();
  96. var iCount = 0;
  97. $('#'+divId+' table.listResults tr:gt('+iLimit+')').each( function(){
  98. $(this).remove();
  99. });
  100. $('#lbl_'+divId).html(sNewLabel);
  101. $('#'+divId+' table.listResults tr:last td').addClass('truncated');
  102. $('#'+divId+' table.listResults').addClass('truncated');
  103. $('#trc_'+divId).html(sLinkLabel);
  104. $('#'+divId+' .listResults').trigger("update"); // Reset the cache
  105. $('#'+divId).unblock();
  106. }
  107. /**
  108. * Reload any block -- used for periodic auto-reload
  109. */
  110. function ReloadBlock(divId, sStyle, sSerializedFilter, sExtraParams)
  111. {
  112. // Check if the user is not editing the list properties right now
  113. var bDialogOpen = false;
  114. var oDataTable = $('#'+divId+' :itop-datatable');
  115. if (oDataTable.length > 0)
  116. {
  117. bDialogOpen = oDataTable.datatable('IsDialogOpen');
  118. }
  119. if (!bDialogOpen)
  120. {
  121. $('#'+divId).block();
  122. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style='+sStyle,
  123. { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
  124. function(data){
  125. $('#'+divId).empty();
  126. $('#'+divId).append(data);
  127. $('#'+divId).removeClass('loading');
  128. }
  129. );
  130. }
  131. }
  132. /**
  133. * Update the display and value of a file input widget when the user picks a new file
  134. */
  135. function UpdateFileName(id, sNewFileName)
  136. {
  137. var aPath = sNewFileName.split('\\');
  138. var sNewFileName = aPath[aPath.length-1];
  139. $('#'+id).val(sNewFileName);
  140. $('#'+id).trigger('validate');
  141. $('#name_'+id).text(sNewFileName);
  142. return true;
  143. }
  144. /**
  145. * Reload a search form for the specified class
  146. */
  147. function ReloadSearchForm(divId, sClassName, sBaseClass, sContext)
  148. {
  149. var oDiv = $('#ds_'+divId);
  150. oDiv.block();
  151. // deprecated in jQuery 1.8
  152. //var oFormEvents = $('#ds_'+divId+' form').data('events');
  153. var oForm = $('#ds_'+divId+' form');
  154. var oFormEvents = $._data(oForm[0], "events");
  155. // Save the submit handlers
  156. aSubmit = new Array();
  157. if ( (oFormEvents != null) && (oFormEvents.submit != undefined))
  158. {
  159. for(var index = 0; index < oFormEvents.submit.length; index++)
  160. {
  161. aSubmit [index ] = { data:oFormEvents.submit[index].data, namespace:oFormEvents.submit[index].namespace, handler: oFormEvents.submit[index].handler};
  162. }
  163. }
  164. sAction = $('#ds_'+divId+' form').attr('action');
  165. // Save the current values in the form
  166. var oMap = {};
  167. $('#ds_'+divId+" form :input[name!='']").each(function() {
  168. oMap[this.name] = this.value;
  169. });
  170. oMap.operation = 'search_form';
  171. oMap.className = sClassName;
  172. oMap.baseClass = sBaseClass;
  173. oMap.currentId = divId;
  174. oMap.action = sAction;
  175. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, oMap,
  176. function(data) {
  177. oDiv.empty();
  178. oDiv.append(data);
  179. if (aSubmit.length > 0)
  180. {
  181. var oForm = $('#ds_'+divId+' form'); // Form was reloaded, recompute it
  182. for(var index = 0; index < aSubmit.length; index++)
  183. {
  184. // Restore the previously bound submit handlers
  185. if (aSubmit[index].data != undefined)
  186. {
  187. oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].data, aSubmit[index].handler)
  188. }
  189. else
  190. {
  191. oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].handler)
  192. }
  193. }
  194. }
  195. oDiv.unblock();
  196. oDiv.parent().resize(); // Inform the parent that the form has just been (potentially) resized
  197. }
  198. );
  199. }
  200. /**
  201. * Stores - in a persistent way - user specific preferences
  202. * depends on a global variable oUserPreferences created/filled by the iTopWebPage
  203. * that acts as a local -write through- cache
  204. */
  205. function SetUserPreference(sPreferenceCode, sPrefValue, bPersistent)
  206. {
  207. sPreviousValue = undefined;
  208. try
  209. {
  210. sPreviousValue = oUserPreferences[sPreferenceCode];
  211. }
  212. catch(err)
  213. {
  214. sPreviousValue = undefined;
  215. }
  216. oUserPreferences[sPreferenceCode] = sPrefValue;
  217. if (bPersistent && (sPrefValue != sPreviousValue))
  218. {
  219. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
  220. { operation: 'set_pref', code: sPreferenceCode, value: sPrefValue} ); // Make it persistent
  221. }
  222. }
  223. /**
  224. * Get user specific preferences
  225. * depends on a global variable oUserPreferences created/filled by the iTopWebPage
  226. * that acts as a local -write through- cache
  227. */
  228. function GetUserPreference(sPreferenceCode, sDefaultValue)
  229. {
  230. var value = sDefaultValue;
  231. if ( oUserPreferences[sPreferenceCode] != undefined)
  232. {
  233. value = oUserPreferences[sPreferenceCode];
  234. }
  235. return value;
  236. }
  237. /**
  238. * Check/uncheck a whole list of checkboxes
  239. */
  240. function CheckAll(sSelector, bValue)
  241. {
  242. var value = bValue;
  243. $(sSelector).each( function() {
  244. if (this.checked != value)
  245. {
  246. this.checked = value;
  247. $(this).trigger('change');
  248. }
  249. });
  250. }
  251. /**
  252. * Toggle (enabled/disabled) the specified field of a form
  253. */
  254. function ToogleField(value, field_id)
  255. {
  256. if (value)
  257. {
  258. $('#'+field_id).removeAttr('disabled');
  259. }
  260. else
  261. {
  262. $('#'+field_id).attr('disabled', 'disabled');
  263. }
  264. $('#'+field_id).trigger('update');
  265. $('#'+field_id).trigger('validate');
  266. }
  267. /**
  268. * For the fields that cannot be visually disabled, they can be blocked
  269. * @return
  270. */
  271. function BlockField(field_id, bBlocked)
  272. {
  273. if (bBlocked)
  274. {
  275. $('#'+field_id).block({ message: ' ** disabled ** '});
  276. }
  277. else
  278. {
  279. $('#'+field_id).unblock();
  280. }
  281. }
  282. /**
  283. * Updates (enables/disables) a "duration" field
  284. */
  285. function ToggleDurationField(field_id)
  286. {
  287. // Toggle all the subfields that compose the "duration" input
  288. aSubFields = new Array('d', 'h', 'm', 's');
  289. if ($('#'+field_id).attr('disabled'))
  290. {
  291. for(var i=0; i<aSubFields.length; i++)
  292. {
  293. $('#'+field_id+'_'+aSubFields[i]).attr('disabled', 'disabled');
  294. }
  295. }
  296. else
  297. {
  298. for(var i=0; i<aSubFields.length; i++)
  299. {
  300. $('#'+field_id+'_'+aSubFields[i]).removeAttr('disabled');
  301. }
  302. }
  303. }
  304. /**
  305. * PropagateCheckBox
  306. */
  307. function PropagateCheckBox(bCurrValue, aFieldsList, bCheck)
  308. {
  309. if (bCurrValue == bCheck)
  310. {
  311. for(var i=0;i<aFieldsList.length;i++)
  312. {
  313. $('#enable_'+aFieldsList[i]).attr('checked', bCheck);
  314. ToogleField(bCheck, aFieldsList[i]);
  315. }
  316. }
  317. }
  318. function FixTableSorter(table)
  319. {
  320. if ($('th.header', table).length == 0)
  321. {
  322. // Table is not sort-able, let's fix it
  323. var checkbox = (table.find('th:first :checkbox').length > 0);
  324. if (checkbox)
  325. {
  326. // There is a checkbox in the first column, don't make it sort-able
  327. table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
  328. }
  329. else
  330. {
  331. // There is NO checkbox in the first column, all columns are considered sort-able
  332. table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
  333. }
  334. }
  335. }
  336. function DashletCreationDlg(sOQL)
  337. {
  338. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', {operation: 'dashlet_creation_dlg', oql: sOQL}, function(data){
  339. $('body').append(data);
  340. });
  341. return false;
  342. }
  343. function ShortcutListDlg(sOQL, sDataTableId, sContext)
  344. {
  345. var sDataTableName = 'datatable_'+sDataTableId;
  346. var oTableSettings = {
  347. oColumns: $('#'+sDataTableName).datatable('option', 'oColumns'),
  348. iPageSize: $('#'+sDataTableName).datatable('option', 'iPageSize')
  349. };
  350. var sTableSettings = JSON.stringify(oTableSettings);
  351. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, {operation: 'shortcut_list_dlg', oql: sOQL, table_settings: sTableSettings}, function(data){
  352. $('body').append(data);
  353. });
  354. return false;
  355. }
  356. function DisplayHistory(sSelector, sFilter, iCount, iStart)
  357. {
  358. $(sSelector).block();
  359. var oParams = { operation: 'history_from_filter', filter: sFilter, start: iStart, count: iCount };
  360. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  361. $(sSelector).html(data).unblock();
  362. }
  363. );
  364. }