lib_head.js.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. <?php
  2. /* Copyright (C) 2005-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. * or see https://www.gnu.org/
  19. */
  20. /**
  21. * \file htdocs/core/js/lib_head.js.php
  22. * \brief File that include javascript functions (included if option use_javascript activated)
  23. * JQuery (providing object $) and JQuery-UI (providing $datepicker) libraries must be loaded before this file.
  24. */
  25. if (!defined('NOREQUIRESOC')) {
  26. define('NOREQUIRESOC', '1');
  27. }
  28. if (!defined('NOCSRFCHECK')) {
  29. define('NOCSRFCHECK', 1);
  30. }
  31. if (!defined('NOTOKENRENEWAL')) {
  32. define('NOTOKENRENEWAL', 1);
  33. }
  34. if (!defined('NOLOGIN')) {
  35. define('NOLOGIN', 1);
  36. }
  37. if (!defined('NOREQUIREMENU')) {
  38. define('NOREQUIREMENU', 1);
  39. }
  40. if (!defined('NOREQUIREHTML')) {
  41. define('NOREQUIREHTML', 1);
  42. }
  43. if (!defined('NOREQUIREAJAX')) {
  44. define('NOREQUIREAJAX', '1');
  45. }
  46. session_cache_limiter('public');
  47. require_once '../../main.inc.php';
  48. /*
  49. * View
  50. */
  51. // Define javascript type
  52. top_httphead('text/javascript; charset=UTF-8');
  53. // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
  54. if (empty($dolibarr_nocache)) {
  55. header('Cache-Control: max-age=10800, public, must-revalidate');
  56. } else {
  57. header('Cache-Control: no-cache');
  58. }
  59. // Define tradMonths javascript array (we define this in datepicker AND in parent page to avoid errors with IE8)
  60. $tradMonths = array(
  61. dol_escape_js($langs->transnoentitiesnoconv("Month01")),
  62. dol_escape_js($langs->transnoentitiesnoconv("Month02")),
  63. dol_escape_js($langs->transnoentitiesnoconv("Month03")),
  64. dol_escape_js($langs->transnoentitiesnoconv("Month04")),
  65. dol_escape_js($langs->transnoentitiesnoconv("Month05")),
  66. dol_escape_js($langs->transnoentitiesnoconv("Month06")),
  67. dol_escape_js($langs->transnoentitiesnoconv("Month07")),
  68. dol_escape_js($langs->transnoentitiesnoconv("Month08")),
  69. dol_escape_js($langs->transnoentitiesnoconv("Month09")),
  70. dol_escape_js($langs->transnoentitiesnoconv("Month10")),
  71. dol_escape_js($langs->transnoentitiesnoconv("Month11")),
  72. dol_escape_js($langs->transnoentitiesnoconv("Month12"))
  73. );
  74. $tradMonthsShort = array(
  75. $langs->trans("MonthShort01"),
  76. $langs->trans("MonthShort02"),
  77. $langs->trans("MonthShort03"),
  78. $langs->trans("MonthShort04"),
  79. $langs->trans("MonthShort05"),
  80. $langs->trans("MonthShort06"),
  81. $langs->trans("MonthShort07"),
  82. $langs->trans("MonthShort08"),
  83. $langs->trans("MonthShort09"),
  84. $langs->trans("MonthShort10"),
  85. $langs->trans("MonthShort11"),
  86. $langs->trans("MonthShort12")
  87. );
  88. $tradDays = array(
  89. $langs->trans("Sunday"),
  90. $langs->trans("Monday"),
  91. $langs->trans("Tuesday"),
  92. $langs->trans("Wednesday"),
  93. $langs->trans("Thursday"),
  94. $langs->trans("Friday"),
  95. $langs->trans("Saturday")
  96. );
  97. $tradDaysShort = array(
  98. $langs->trans("ShortSunday"),
  99. $langs->trans("ShortMonday"),
  100. $langs->trans("ShortTuesday"),
  101. $langs->trans("ShortWednesday"),
  102. $langs->trans("ShortThursday"),
  103. $langs->trans("ShortFriday"),
  104. $langs->trans("ShortSaturday")
  105. );
  106. $tradDaysMin = array(
  107. $langs->trans("SundayMin"),
  108. $langs->trans("MondayMin"),
  109. $langs->trans("TuesdayMin"),
  110. $langs->trans("WednesdayMin"),
  111. $langs->trans("ThursdayMin"),
  112. $langs->trans("FridayMin"),
  113. $langs->trans("SaturdayMin")
  114. );
  115. ?>
  116. // Javascript libraries for Dolibarr ERP CRM (https://www.dolibarr.org)
  117. // For jQuery date picker
  118. var tradMonths = <?php echo json_encode($tradMonths) ?>;
  119. var tradMonthsShort = <?php echo json_encode($tradMonthsShort) ?>;
  120. var tradDays = <?php echo json_encode($tradDays) ?>;
  121. var tradDaysShort = <?php echo json_encode($tradDaysShort) ?>;
  122. var tradDaysMin = <?php echo json_encode($tradDaysMin) ?>;
  123. // For JQuery date picker
  124. $(document).ready(function() {
  125. $.datepicker.setDefaults({
  126. autoSize: true,
  127. changeMonth: true,
  128. changeYear: true,
  129. altField: '#timestamp',
  130. altFormat: '@' // Gives a timestamp dateformat
  131. });
  132. });
  133. jQuery(function($){
  134. $.datepicker.regional['<?php echo $langs->defaultlang ?>'] = {
  135. closeText: '<?php echo $langs->trans("Close2") ?>',
  136. prevText: '<?php echo $langs->trans("Previous") ?>',
  137. nextText: '<?php echo $langs->trans("Next") ?>',
  138. currentText: '<?php echo $langs->trans("Now") ?>',
  139. monthNames: tradMonths,
  140. monthNamesShort: tradMonthsShort,
  141. dayNames: tradDays,
  142. dayNamesShort: tradDaysShort,
  143. dayNamesMin: tradDaysMin,
  144. weekHeader: '<?php echo $langs->trans("Week"); ?>',
  145. dateFormat: '<?php echo $langs->trans("FormatDateShortJQuery"); ?>', /* Note dd/mm/yy means year on 4 digit in jquery format */
  146. firstDay: <?php echo (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : '1'); ?>,
  147. isRTL: <?php echo ($langs->trans("DIRECTION") == 'rtl' ? 'true' : 'false'); ?>,
  148. showMonthAfterYear: false, /* TODO add specific to country */
  149. yearSuffix: '' /* TODO add specific to country */
  150. };
  151. $.datepicker.setDefaults($.datepicker.regional['<?php echo $langs->defaultlang ?>']);
  152. });
  153. /**
  154. * Set array used for select2 translations
  155. */
  156. var select2arrayoflanguage = {
  157. matches: function (matches) { return matches + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2ResultFoundUseArrows")); ?>"; },
  158. noResults: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2NotFound")); ?>"; },
  159. inputTooShort: function (input) {
  160. var n = input.minimum;
  161. /*console.log(input);
  162. console.log(input.minimum);*/
  163. if (n > 1) return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacters")); ?>";
  164. else return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacter")); ?>"
  165. },
  166. loadMore: function (pageNumber) { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2LoadingMoreResults")); ?>"; },
  167. searching: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2SearchInProgress")); ?>"; }
  168. };
  169. /**
  170. * For calendar input
  171. */
  172. // Returns an object given an id
  173. function getObjectFromID(id){
  174. var theObject;
  175. if(document.getElementById)
  176. theObject=document.getElementById(id);
  177. else
  178. theObject=document.all[id];
  179. return theObject;
  180. }
  181. // Called after selection of a date to save details into detailed fields
  182. function dpChangeDay(dateFieldID, format)
  183. {
  184. //showDP.datefieldID=dateFieldID;
  185. console.log("Call dpChangeDay, we save date into detailed fields from format = "+format);
  186. var thefield=getObjectFromID(dateFieldID);
  187. var thefieldday=getObjectFromID(dateFieldID+"day");
  188. var thefieldmonth=getObjectFromID(dateFieldID+"month");
  189. var thefieldyear=getObjectFromID(dateFieldID+"year");
  190. var date=getDateFromFormat(thefield.value, format);
  191. //console.log(date);
  192. if (date)
  193. {
  194. thefieldday.value=date.getDate();
  195. if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
  196. thefieldmonth.value=date.getMonth()+1;
  197. if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
  198. thefieldyear.value=date.getFullYear();
  199. if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
  200. }
  201. else
  202. {
  203. thefieldday.value='';
  204. if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
  205. thefieldmonth.value='';
  206. if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
  207. thefieldyear.value='';
  208. if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
  209. }
  210. }
  211. /*
  212. * =================================================================
  213. * Function:
  214. * formatDate (javascript object Date(), format) Purpose: Returns a date in the
  215. * output format specified. The format string can use the following tags: Field |
  216. * Tags -------------+------------------------------- Year | yyyy (4 digits), yy
  217. * (2 digits) Month | MM (2 digits) Day of Month | dd (2 digits) Hour (1-12) |
  218. * hh (2 digits) Hour (0-23) | HH (2 digits) Minute | mm (2 digits) Second | ss
  219. * (2 digits) Author: Laurent Destailleur Author: Matelli (see
  220. * http://matelli.fr/showcases/patchs-dolibarr/update-date-input-in-action-form.html)
  221. * Licence: GPL
  222. * ==================================================================
  223. */
  224. function formatDate(date,format)
  225. {
  226. // alert('formatDate date='+date+' format='+format);
  227. // Force parametres en chaine
  228. format=format+"";
  229. var result="";
  230. var year=date.getYear()+""; if (year.length < 4) { year=""+(year-0+1900); }
  231. var month=date.getMonth()+1;
  232. var day=date.getDate();
  233. var hour=date.getHours();
  234. var minute=date.getMinutes();
  235. var seconde=date.getSeconds();
  236. var i=0;
  237. while (i < format.length)
  238. {
  239. c=format.charAt(i); // Recupere char du format
  240. substr="";
  241. j=i;
  242. while ((format.charAt(j)==c) && (j < format.length)) // Recupere char successif identiques
  243. {
  244. substr += format.charAt(j++);
  245. }
  246. // alert('substr='+substr);
  247. if (substr == 'yyyy') { result=result+year; }
  248. else if (substr == 'yy') { result=result+year.substring(2,4); }
  249. else if (substr == 'M') { result=result+month; }
  250. else if (substr == 'MM') { result=result+(month<1||month>9?"":"0")+month; }
  251. else if (substr == 'd') { result=result+day; }
  252. else if (substr == 'dd') { result=result+(day<1||day>9?"":"0")+day; }
  253. else if (substr == 'hh') { if (hour > 12) hour-=12; result=result+(hour<0||hour>9?"":"0")+hour; }
  254. else if (substr == 'HH') { result=result+(hour<0||hour>9?"":"0")+hour; }
  255. else if (substr == 'mm') { result=result+(minute<0||minute>9?"":"0")+minute; }
  256. else if (substr == 'ss') { result=result+(seconde<0||seconde>9?"":"0")+seconde; }
  257. else { result=result+substr; }
  258. i+=substr.length;
  259. }
  260. // alert(result);
  261. return result;
  262. }
  263. /*
  264. * =================================================================
  265. * Function: getDateFromFormat(date_string, format_string)
  266. * Purpose: This function takes a date string and a format string.
  267. * It parses the date string with format and it
  268. * returns the date as a javascript Date() object. If date does not match
  269. * format, it returns 0. The format string can use the following tags:
  270. * Field | Tags
  271. * -------------+-----------------------------------
  272. * Year | yyyy (4 digits), yy (2 digits)
  273. * Month | MM (2 digits)
  274. * Day of Month | dd (2 digits)
  275. * Hour (1-12) | hh (2 digits)
  276. * Hour (0-23) | HH (2 digits)
  277. * Minute | mm (2 digits)
  278. * Second | ss (2 digits)
  279. * Author: Laurent Destailleur
  280. * Licence: GPL
  281. * ==================================================================
  282. */
  283. function getDateFromFormat(val,format)
  284. {
  285. // alert('getDateFromFormat val='+val+' format='+format);
  286. // Force parametres en chaine
  287. val=val+"";
  288. format=format+"";
  289. if (val == '') return 0;
  290. var now=new Date();
  291. var year=now.getYear(); if (year.length < 4) { year=""+(year-0+1900); }
  292. var month=now.getMonth()+1;
  293. var day=now.getDate();
  294. var hour=now.getHours();
  295. var minute=now.getMinutes();
  296. var seconde=now.getSeconds();
  297. var i=0;
  298. var d=0; // -d- follows the date string while -i- follows the format
  299. // string
  300. while (i < format.length)
  301. {
  302. c=format.charAt(i); // Recupere char du format
  303. substr="";
  304. j=i;
  305. while ((format.charAt(j)==c) && (j < format.length)) // Recupere char
  306. // successif
  307. // identiques
  308. {
  309. substr += format.charAt(j++);
  310. }
  311. // alert('substr='+substr);
  312. if (substr == "yyyy") year=getIntegerInString(val,d,4,4);
  313. if (substr == "yy") year=""+(getIntegerInString(val,d,2,2)-0+1900);
  314. if (substr == "MM" ||substr == "M")
  315. {
  316. month=getIntegerInString(val,d,1,2);
  317. if (month) d -= 2- month.length;
  318. }
  319. if (substr == "dd")
  320. {
  321. day=getIntegerInString(val,d,1,2);
  322. if (day) d -= 2- day.length;
  323. }
  324. if (substr == "HH" ||substr == "hh" )
  325. {
  326. hour=getIntegerInString(val,d,1,2);
  327. if (dhouray) d -= 2- hour.length;
  328. }
  329. if (substr == "mm"){
  330. minute=getIntegerInString(val,d,1,2);
  331. if (minute) d -= 2- minute.length;
  332. }
  333. if (substr == "ss")
  334. {
  335. seconde=getIntegerInString(val,d,1,2);
  336. if (seconde) d -= 2- seconde.length;
  337. }
  338. i+=substr.length;
  339. d+=substr.length;
  340. }
  341. // Check if format param are ok
  342. if (year==null||year<1) { return 0; }
  343. if (month==null||(month<1)||(month>12)) { return 0; }
  344. if (day==null||(day<1)||(day>31)) { return 0; }
  345. if (hour==null||(hour<0)||(hour>24)) { return 0; }
  346. if (minute==null||(minute<0)||(minute>60)) { return 0; }
  347. if (seconde==null||(seconde<0)||(seconde>60)) { return 0; }
  348. // alert(year+' '+month+' '+day+' '+hour+' '+minute+' '+seconde);
  349. return new Date(year,month-1,day,hour,minute,seconde);
  350. }
  351. /*
  352. * =================================================================
  353. * Function: stringIsInteger(string)
  354. * Purpose: Return true if string is an integer
  355. * ==================================================================
  356. */
  357. function stringIsInteger(str)
  358. {
  359. var digits="1234567890";
  360. for (var i=0; i < str.length; i++)
  361. {
  362. if (digits.indexOf(str.charAt(i))==-1)
  363. {
  364. return false;
  365. }
  366. }
  367. return true;
  368. }
  369. /*
  370. * =================================================================
  371. * Function: getIntegerInString(string,pos,minlength,maxlength)
  372. * Purpose: Return part of string from position i that is integer
  373. * ==================================================================
  374. */
  375. function getIntegerInString(str,i,minlength,maxlength)
  376. {
  377. for (var x=maxlength; x>=minlength; x--)
  378. {
  379. var substr=str.substring(i,i+x);
  380. if (substr.length < minlength) { return null; }
  381. if (stringIsInteger(substr)) { return substr; }
  382. }
  383. return null;
  384. }
  385. /*
  386. * =================================================================
  387. * Purpose: Clean string to have it url encoded
  388. * Input: s
  389. * Author: Laurent Destailleur
  390. * Licence: GPL
  391. * ==================================================================
  392. */
  393. function urlencode(s) {
  394. news=s;
  395. news=news.replace(/\+/gi,'%2B');
  396. news=news.replace(/&/gi,'%26');
  397. return news;
  398. }
  399. /*
  400. * =================================================================
  401. * Purpose: Clean string to have it url encoded
  402. * Input: s
  403. * Author: Laurent Destailleur
  404. * Licence: GPL
  405. * ==================================================================
  406. */
  407. function htmlEntityDecodeJs(inp){
  408. var replacements = {'&lt;':'<','&gt;':'>','&sol;':'/','&quot;':'"','&apos;':'\'','&amp;':'&','&nbsp;':' '};
  409. if (inp)
  410. {
  411. for(var r in replacements){
  412. inp = inp.replace(new RegExp(r,'g'),replacements[r]);
  413. }
  414. return inp.replace(/&#(\d+);/g, function(match, dec) {
  415. return String.fromCharCode(dec);
  416. });
  417. }
  418. else { return ''; }
  419. }
  420. /*
  421. * =================================================================
  422. * Purpose: Applique un delai avant execution. Used for autocompletion of companies.
  423. * Input: funct, delay
  424. * Author: Regis Houssin
  425. * Licence: GPL
  426. * ==================================================================
  427. */
  428. function ac_delay(funct,delay) {
  429. // delay before start of action
  430. setTimeout(funct,delay);
  431. }
  432. /*
  433. * =================================================================
  434. * Purpose:
  435. * Clean values of a "Sortable.serialize". Used by drag and drop.
  436. * Input: expr
  437. * Author: Regis Houssin
  438. * Licence: GPL
  439. * ==================================================================
  440. */
  441. function cleanSerialize(expr) {
  442. if (typeof(expr) != 'string') return '';
  443. var reg = new RegExp("(&)", "g");
  444. var reg2 = new RegExp("[^A-Z0-9,]", "g");
  445. var liste1 = expr.replace(reg, ",");
  446. return liste1.replace(reg2, "");
  447. }
  448. /*
  449. * =================================================================
  450. * Purpose: Display a temporary message in input text fields (For showing help message on
  451. * input field).
  452. * Input: fieldId
  453. * Input: message
  454. * Author: Regis Houssin
  455. * Licence: GPL
  456. * ==================================================================
  457. */
  458. function displayMessage(fieldId,message) {
  459. var textbox = document.getElementById(fieldId);
  460. if (textbox.value == '') {
  461. textbox.style.color = 'grey';
  462. textbox.value = message;
  463. }
  464. }
  465. /*
  466. * =================================================================
  467. * Purpose: Hide a temporary message in input text fields (For showing help message on
  468. * input field).
  469. * Input: fiedId
  470. * Input: message
  471. * Author: Regis Houssin
  472. * Licence: GPL
  473. * ==================================================================
  474. */
  475. function hideMessage(fieldId,message) {
  476. var textbox = document.getElementById(fieldId);
  477. textbox.style.color = 'black';
  478. if (textbox.value == message) textbox.value = '';
  479. }
  480. /*
  481. * Used by button to set on/off.
  482. * Call url then make complementary action (like show/hide, enable/disable or set another option).
  483. *
  484. * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
  485. * @param string code Code
  486. * @param string intput Array of complementary actions to do if success
  487. * @param int entity Entity
  488. * @param int strict Strict
  489. * @param int forcereload Force reload
  490. * @param int userid User id
  491. * @param string token Token
  492. */
  493. function setConstant(url, code, input, entity, strict, forcereload, userid, token) {
  494. var saved_url = url; /* avoid undefined url */
  495. $.post( url, {
  496. action: "set",
  497. name: code,
  498. entity: entity,
  499. token: token
  500. },
  501. function() { /* handler for success of post */
  502. console.log("url request success forcereload="+forcereload);
  503. $("#set_" + code).hide();
  504. $("#del_" + code).show();
  505. $.each(input, function(type, data) {
  506. // Enable another element
  507. if (type == "disabled" && strict != 1) {
  508. $.each(data, function(key, value) {
  509. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  510. $(newvalue).removeAttr("disabled");
  511. if ($(newvalue).hasClass("butActionRefused") == true) {
  512. $(newvalue).removeClass("butActionRefused");
  513. $(newvalue).addClass("butAction");
  514. }
  515. });
  516. } else if (type == "enabled") {
  517. $.each(data, function(key, value) {
  518. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  519. if (strict == 1)
  520. $(newvalue).removeAttr("disabled");
  521. else
  522. $(newvalue).attr("disabled", true);
  523. if ($(newvalue).hasClass("butAction") == true) {
  524. $(newvalue).removeClass("butAction");
  525. $(newvalue).addClass("butActionRefused");
  526. }
  527. });
  528. // Show another element
  529. } else if (type == "showhide" || type == "show") {
  530. $.each(data, function(key, value) {
  531. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  532. $(newvalue).show();
  533. });
  534. // Set another constant
  535. } else if (type == "set") {
  536. $.each(data, function(key, value) {
  537. $("#set_" + key).hide();
  538. $("#del_" + key).show();
  539. $.post( saved_url, {
  540. action: "set",
  541. name: key,
  542. value: value,
  543. entity: entity,
  544. token: token
  545. });
  546. });
  547. }
  548. });
  549. if (forcereload) {
  550. location.reload();
  551. }
  552. }).fail(function(error) { location.reload(); }); /* When it fails, we always force reload to have setEventErrorMEssage in session visible */
  553. }
  554. /*
  555. * Used by button to set on/off
  556. * Call url then make complementary action (like show/hide, enable/disable or set another option).
  557. *
  558. * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
  559. * @param string code Code
  560. * @param string intput Array of complementary actions to do if success
  561. * @param int entity Entity
  562. * @param int strict Strict
  563. * @param int forcereload Force reload
  564. * @param int userid User id
  565. * @param string token Token
  566. */
  567. function delConstant(url, code, input, entity, strict, forcereload, userid, token) {
  568. var saved_url = url; /* avoid undefined url */
  569. $.post( url, {
  570. action: "del",
  571. name: code,
  572. entity: entity,
  573. token: token
  574. },
  575. function() {
  576. console.log("url request success forcereload="+forcereload);
  577. $("#del_" + code).hide();
  578. $("#set_" + code).show();
  579. $.each(input, function(type, data) {
  580. // Disable another element
  581. if (type == "disabled") {
  582. $.each(data, function(key, value) {
  583. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  584. $(newvalue).attr("disabled", true);
  585. if ($(newvalue).hasClass("butAction") == true) {
  586. $(newvalue).removeClass("butAction");
  587. $(newvalue).addClass("butActionRefused");
  588. }
  589. });
  590. } else if (type == "enabled" && strict != 1) {
  591. $.each(data, function(key, value) {
  592. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  593. $(newvalue).removeAttr("disabled");
  594. if ($(newvalue).hasClass("butActionRefused") == true) {
  595. $(newvalue).removeClass("butActionRefused");
  596. $(newvalue).addClass("butAction");
  597. }
  598. });
  599. // Hide another element
  600. } else if (type == "showhide" || type == "hide") {
  601. $.each(data, function(key, value) {
  602. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  603. $(newvalue).hide();
  604. });
  605. // Delete another constant
  606. } else if (type == "del") {
  607. $.each(data, function(key, value) {
  608. $("#del_" + value).hide();
  609. $("#set_" + value).show();
  610. $.post( saved_url, {
  611. action: "del",
  612. name: value,
  613. entity: entity,
  614. token: token
  615. });
  616. });
  617. }
  618. });
  619. if (forcereload) {
  620. location.reload();
  621. }
  622. }).fail(function(error) { location.reload(); }); /* When it fails, we always force reload to have setEventErrorMEssage in session visible */
  623. }
  624. /*
  625. * Call the setConstant or delConstant but with a confirmation before.
  626. * Used by button to set on/off.
  627. *
  628. * @param string action Action
  629. * @param string url Url
  630. * @param string code Code
  631. * @param string intput Array of complementary actions to do if success
  632. * @param string box Box
  633. * @param int entity Entity
  634. * @param int yesButton yesButton
  635. * @param int noButton noButton
  636. * @param int strict Strict
  637. * @param int userid User id
  638. * @param string token Token
  639. */
  640. function confirmConstantAction(action, url, code, input, box, entity, yesButton, noButton, strict, userid, token) {
  641. var boxConfirm = box;
  642. $("#confirm_" + code)
  643. .attr("title", boxConfirm.title)
  644. .html(boxConfirm.content)
  645. .dialog({
  646. resizable: false,
  647. height: 170,
  648. width: 500,
  649. modal: true,
  650. buttons: [
  651. {
  652. id : 'yesButton_' + code,
  653. text : yesButton,
  654. click : function() {
  655. if (action == "set") {
  656. setConstant(url, code, input, entity, strict, 0, userid, token);
  657. } else if (action == "del") {
  658. delConstant(url, code, input, entity, strict, 0, userid, token);
  659. }
  660. // Close dialog
  661. $(this).dialog("close");
  662. // Execute another method
  663. if (boxConfirm.method) {
  664. var fnName = boxConfirm.method;
  665. if (window.hasOwnProperty(fnName)) {
  666. window[fnName]();
  667. }
  668. }
  669. }
  670. },
  671. {
  672. id : 'noButton_' + code,
  673. text : noButton,
  674. click : function() {
  675. $(this).dialog("close");
  676. }
  677. }
  678. ]
  679. });
  680. // For information dialog box only, hide the noButton
  681. if (boxConfirm.info) {
  682. $("#noButton_" + code).button().hide();
  683. }
  684. }
  685. /*
  686. * =================================================================
  687. * This is to allow to transform all select box into ajax autocomplete box
  688. * with just one line:
  689. * $(function() { $( "#idofmylist" ).combobox(); });
  690. * Do not use it on large combo boxes
  691. * =================================================================
  692. */
  693. (function( $ ) {
  694. $.widget( "ui.combobox", {
  695. options: {
  696. minLengthToAutocomplete: 0
  697. },
  698. _create: function() {
  699. var savMinLengthToAutocomplete = this.options.minLengthToAutocomplete;
  700. var self = this,
  701. select = this.element.hide(),
  702. selected = select.children( ":selected" ),
  703. value = selected.val() ? selected.text() : "";
  704. var input = this.input = $( "<input>" )
  705. .insertAfter( select )
  706. .val( value )
  707. .attr('id', 'inputautocomplete'+select.attr('id'))
  708. .autocomplete({
  709. delay: 0,
  710. minLength: this.options.minLengthToAutocomplete,
  711. source: function( request, response ) {
  712. var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
  713. response( select.children( "option:enabled" ).map(function() {
  714. var text = $( this ).text();
  715. if ( this.value && ( !request.term || matcher.test(text) ) )
  716. return {
  717. label: text.replace(
  718. new RegExp(
  719. "(?![^&;]+;)(?!<[^<>]*)(" +
  720. $.ui.autocomplete.escapeRegex(request.term) +
  721. ")(?![^<>]*>)(?![^&;]+;)", "gi"
  722. ), "<strong>$1</strong>" ),
  723. value: text,
  724. option: this
  725. };
  726. }) );
  727. },
  728. select: function( event, ui ) {
  729. ui.item.option.selected = true;
  730. self._trigger( "selected", event, {
  731. item: ui.item.option
  732. });
  733. },
  734. change: function( event, ui ) {
  735. if ( !ui.item ) {
  736. var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
  737. valid = false;
  738. select.children( "option" ).each(function() {
  739. if ( $( this ).text().match( matcher ) ) {
  740. this.selected = valid = true;
  741. return false;
  742. }
  743. });
  744. if ( !valid ) {
  745. // remove invalid value, as it didnt match anything
  746. $( this ).val( "" );
  747. select.val( "" );
  748. input.data("ui-autocomplete").term = "";
  749. return false;
  750. }
  751. }
  752. }
  753. })
  754. .addClass( "ui-widget ui-widget-content ui-corner-left dolibarrcombobox" );
  755. input.data("ui-autocomplete")._renderItem = function( ul, item ) {
  756. return $("<li>")
  757. .data( "ui-autocomplete-item", item ) // jQuery UI > 1.10.0
  758. .append( "<a>" + item.label + "</a>" )
  759. .appendTo( ul );
  760. };
  761. this.button = $( "<button type=\'button\'>&nbsp;</button>" )
  762. .attr( "tabIndex", -1 )
  763. .attr( "title", "Show All Items" )
  764. .insertAfter( input )
  765. .button({
  766. icons: {
  767. primary: "ui-icon-triangle-1-s"
  768. },
  769. text: false
  770. })
  771. .removeClass( "ui-corner-all" )
  772. .addClass( "ui-corner-right ui-button-icon" )
  773. .click(function() {
  774. // close if already visible
  775. if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
  776. input.autocomplete( "close" );
  777. return;
  778. }
  779. // pass empty string as value to search for, displaying all results
  780. input.autocomplete({ minLength: 0 });
  781. input.autocomplete( "search", "" );
  782. input.autocomplete({ minLength: savMinLengthToAutocomplete });
  783. input.focus();
  784. });
  785. },
  786. destroy: function() {
  787. this.input.remove();
  788. this.button.remove();
  789. this.element.show();
  790. $.Widget.prototype.destroy.call( this );
  791. }
  792. });
  793. })( jQuery );
  794. /**
  795. * Function to output a dialog box for copy/paste
  796. *
  797. * @param string text Text to put into copy/paste area
  798. * @param string text2 Text to put under the copy/paste area
  799. */
  800. function copyToClipboard(text,text2)
  801. {
  802. text = text.replace(/<br>/g,"\n");
  803. var newElem = '<textarea id="coordsforpopup" style="border: none; width: 90%; height: 120px;">'+text+'</textarea><br><br>'+text2;
  804. /* alert(newElem); */
  805. $("#dialogforpopup").html(newElem);
  806. $("#dialogforpopup").dialog();
  807. $("#coordsforpopup").select();
  808. return false;
  809. }
  810. /**
  811. * Show a popup HTML page. Use the "window.open" function.
  812. *
  813. * @param string url Url
  814. * @param string title Title of popup
  815. * @return boolean False
  816. * @see document_preview
  817. */
  818. function newpopup(url, title) {
  819. var argv = newpopup.arguments;
  820. var argc = newpopup.arguments.length;
  821. tmp=url;
  822. console.log("newpopup "+argv[2]+" "+argv[3]);
  823. var l = (argc > 2) ? argv[2] : 600;
  824. var h = (argc > 3) ? argv[3] : 400;
  825. var left = (screen.width - l)/2;
  826. var top = (screen.height - h)/2;
  827. var wfeatures = "directories=0,menubar=0,status=0,resizable=0,scrollbars=1,toolbar=0,width=" + l +",height=" + h + ",left=" + left + ",top=" + top;
  828. fen=window.open(tmp,title,wfeatures);
  829. return false;
  830. }
  831. /**
  832. * Function show document preview. It uses the "dialog" function.
  833. * The a tag around the img must have the src='', class='documentpreview', mime='image/xxx', target='_blank' from getAdvancedPreviewUrl().
  834. *
  835. * @param string file Url
  836. * @param string type Mime file type ("image/jpeg", "application/pdf", "text/html")
  837. * @param string title Title of popup
  838. * @return void
  839. * @see newpopup
  840. */
  841. function document_preview(file, type, title)
  842. {
  843. var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/webp"];
  844. var showOriginalSizeButton = false;
  845. console.log("document_preview A click was done. file="+file+", type="+type+", title="+title);
  846. if ($.inArray(type, ValidImageTypes) < 0) {
  847. /* Not an image */
  848. var width='85%';
  849. var object_width='100%';
  850. var height = ($( window ).height() - 60) * 0.90;
  851. var object_height='98%';
  852. show_preview('notimage');
  853. } else {
  854. /* This is an image */
  855. var object_width=0;
  856. var object_height=0;
  857. var img = new Image();
  858. img.onload = function() {
  859. object_width = this.width;
  860. object_height = this.height;
  861. width = $( window ).width()*0.90;
  862. console.log("object_width="+object_width+" window width="+width);
  863. if(object_width < width){
  864. console.log("Object width is small, we set width of popup according to image width.");
  865. width = object_width + 30
  866. }
  867. height = $( window ).height()*0.85;
  868. console.log("object_height="+object_height+" window height="+height);
  869. if(object_height < height){
  870. console.log("Object height is small, we set height of popup according to image height.");
  871. height = object_height + 80
  872. }
  873. else
  874. {
  875. showOriginalSizeButton = true;
  876. }
  877. show_preview('image');
  878. };
  879. img.src = file;
  880. }
  881. function show_preview(mode) {
  882. /* console.log("mode="+mode+" file="+file+" type="+type+" width="+width+" height="+height); */
  883. var newElem = '<object name="objectpreview" data="'+file+'" type="'+type+'" width="'+object_width+'" height="'+object_height+'" param="noparam"></object>';
  884. optionsbuttons = {}
  885. if (mode == 'image' && showOriginalSizeButton)
  886. {
  887. optionsbuttons = {
  888. "<?php echo dol_escape_js($langs->transnoentitiesnoconv("OriginalSize")); ?>": function() { console.log("Click on original size"); jQuery(".ui-dialog-content.ui-widget-content > object").css({ "max-height": "none" }); },
  889. "<?php echo dol_escape_js($langs->transnoentitiesnoconv("CloseWindow")); ?>": function() { $( this ).dialog( "close" ); }
  890. };
  891. }
  892. $("#dialogforpopup").html(newElem);
  893. $("#dialogforpopup").dialog({
  894. closeOnEscape: true,
  895. resizable: true,
  896. width: width,
  897. height: height,
  898. modal: true,
  899. title: title,
  900. buttons: optionsbuttons
  901. });
  902. if (showOriginalSizeButton)
  903. {
  904. jQuery(".ui-dialog-content.ui-widget-content > object").css({ "max-height": "100%", "width": "auto", "margin-left": "auto", "margin-right": "auto", "display": "block" });
  905. }
  906. }
  907. }
  908. /*
  909. * Provide a function to get an URL GET parameter in javascript
  910. *
  911. * @param string name Name of parameter
  912. * @param mixed valueifnotfound Value if not found
  913. * @return string Value
  914. */
  915. function getParameterByName(name, valueifnotfound)
  916. {
  917. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  918. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  919. results = regex.exec(location.search);
  920. return results === null ? valueifnotfound : decodeURIComponent(results[1].replace(/\+/g, " "));
  921. }
  922. // Code in the public domain from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  923. (function() {
  924. /**
  925. * Decimal adjustment of a number.
  926. *
  927. * @param {String} type The type of adjustment.
  928. * @param {Number} value The number.
  929. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
  930. * @returns {Number} The adjusted value.
  931. */
  932. function decimalAdjust(type, value, exp) {
  933. // If the exp is undefined or zero...
  934. if (typeof exp === 'undefined' || +exp === 0) {
  935. return Math[type](value);
  936. }
  937. value = +value;
  938. exp = +exp;
  939. // If the value is not a number or the exp is not an integer...
  940. if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
  941. return NaN;
  942. }
  943. // Shift
  944. value = value.toString().split('e');
  945. value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  946. // Shift back
  947. value = value.toString().split('e');
  948. return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  949. }
  950. // Decimal round
  951. if (!Math.round10) {
  952. Math.round10 = function(value, exp) {
  953. return decimalAdjust('round', value, exp);
  954. };
  955. }
  956. // Decimal floor
  957. if (!Math.floor10) {
  958. Math.floor10 = function(value, exp) {
  959. return decimalAdjust('floor', value, exp);
  960. };
  961. }
  962. // Decimal ceil
  963. if (!Math.ceil10) {
  964. Math.ceil10 = function(value, exp) {
  965. return decimalAdjust('ceil', value, exp);
  966. };
  967. }
  968. })();
  969. // Another solution, easier, to build a javascript rounding function
  970. function dolroundjs(number, decimals) { return +(Math.round(number + "e+" + decimals) + "e-" + decimals); }
  971. /**
  972. * Function similar to PHP price()
  973. *
  974. * @param {number|string} amount The amount to show
  975. * @param {string} mode 'MT' or 'MU'
  976. * @return {string} The amount with digits
  977. */
  978. function pricejs(amount, mode) {
  979. var main_max_dec_shown = <?php echo (int) str_replace('.', '', $conf->global->MAIN_MAX_DECIMALS_SHOWN); ?>;
  980. var main_rounding_unit = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_UNIT; ?>;
  981. var main_rounding_tot = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_TOT; ?>;
  982. if (mode == 'MU') return amount.toFixed(main_rounding_unit);
  983. if (mode == 'MT') return amount.toFixed(main_rounding_tot);
  984. return 'Bad value for parameter mode';
  985. }
  986. /**
  987. * Function similar to PHP price2num()
  988. *
  989. * @param {number|string} amount The amount to convert/clean
  990. * @return {string} The amount in universal numeric format (Example: '99.99999')
  991. * @todo Implement rounding parameter
  992. */
  993. function price2numjs(amount) {
  994. if (amount == '') return '';
  995. <?php
  996. $dec = ',';
  997. $thousand = ' ';
  998. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  999. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  1000. }
  1001. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  1002. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  1003. }
  1004. if ($thousand == 'Space') {
  1005. $thousand = ' ';
  1006. }
  1007. print "var dec='".dol_escape_js($dec)."'; var thousand='".dol_escape_js($thousand)."';\n"; // Set var in javascript
  1008. ?>
  1009. var main_max_dec_shown = <?php echo (int) str_replace('.', '', $conf->global->MAIN_MAX_DECIMALS_SHOWN); ?>;
  1010. var main_rounding_unit = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_UNIT; ?>;
  1011. var main_rounding_tot = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_TOT; ?>;
  1012. var amount = amount.toString();
  1013. // rounding for unit price
  1014. var rounding = main_rounding_unit;
  1015. var pos = amount.indexOf(dec);
  1016. var decpart = '';
  1017. if (pos >= 0) decpart = amount.substr(pos + 1).replace('/0+$/i', ''); // Remove 0 for decimal part
  1018. var nbdec = decpart.length;
  1019. if (nbdec > rounding) rounding = nbdec;
  1020. // If rounding higher than max shown
  1021. if (rounding > main_max_dec_shown) rounding = main_max_dec_shown;
  1022. if (thousand != ',' && thousand != '.') amount = amount.replace(',', '.');
  1023. amount = amount.replace(' ', ''); // To avoid spaces
  1024. amount = amount.replace(thousand, ''); // Replace of thousand before replace of dec to avoid pb if thousand is .
  1025. amount = amount.replace(dec, '.');
  1026. //console.log("amount before="+amount+" rouding="+rounding)
  1027. var res = Math.round10(amount, - rounding);
  1028. // Other solution is
  1029. // var res = dolroundjs(amount, rounding)
  1030. console.log("price2numjs text="+amount+" return="+res);
  1031. return res;
  1032. }
  1033. <?php
  1034. if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY')) {
  1035. ?>
  1036. // Defined properties for JNotify
  1037. $(document).ready(function() {
  1038. if (typeof $.jnotify == 'function')
  1039. {
  1040. $.jnotify.setup({
  1041. delay: 3000 // the default time to show each notification (in milliseconds)
  1042. , sticky: false // determines if the message should be considered "sticky" (user must manually close notification)
  1043. , closeLabel: "&times;" // the HTML to use for the "Close" link
  1044. , showClose: true // determines if the "Close" link should be shown if notification is also sticky
  1045. , fadeSpeed: 1000 // the speed to fade messages out (in milliseconds)
  1046. , slideSpeed: 250 // the speed used to slide messages out (in milliseconds)
  1047. , classContainer: "jnotify-container"
  1048. , classNotification: "jnotify-notification"
  1049. , classBackground: "jnotify-background"
  1050. , classClose: "jnotify-close"
  1051. , classMessage: "jnotify-message"
  1052. , init: null // callback that occurs when the main jnotify container is created
  1053. , create: null // callback that occurs when when the note is created (occurs just before appearing in DOM)
  1054. , beforeRemove: null // callback that occurs when before the notification starts to fade away
  1055. });
  1056. }
  1057. });
  1058. <?php } ?>
  1059. // Force to hide menus when page is inside an iFrame
  1060. $(document).ready(function() {
  1061. if (window.location !== window.parent.location ) {
  1062. console.log("Page is detected to be into an iframe, we hide by CSS the menus");
  1063. // The page is in an iframe
  1064. jQuery(".side-nav-vert, .side-nav, .websitebar").hide();
  1065. jQuery(".id-container").css('width', '100%');
  1066. }
  1067. });
  1068. // End of lib_head.js.php