lib_head.js.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. $dec = ',';
  116. $thousand = ' ';
  117. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  118. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  119. }
  120. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  121. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  122. }
  123. if ($thousand == 'Space') {
  124. $thousand = ' ';
  125. }
  126. ?>
  127. // Javascript libraries for Dolibarr ERP CRM (https://www.dolibarr.org)
  128. // For jQuery date picker
  129. var tradMonths = <?php echo json_encode($tradMonths) ?>;
  130. var tradMonthsShort = <?php echo json_encode($tradMonthsShort) ?>;
  131. var tradDays = <?php echo json_encode($tradDays) ?>;
  132. var tradDaysShort = <?php echo json_encode($tradDaysShort) ?>;
  133. var tradDaysMin = <?php echo json_encode($tradDaysMin) ?>;
  134. var currencyCache = <?php echo json_encode($langs->cache_currencies) ?>;
  135. // For JQuery date picker
  136. $(document).ready(function() {
  137. $.datepicker.setDefaults({
  138. autoSize: true,
  139. changeMonth: true,
  140. changeYear: true,
  141. altField: '#timestamp',
  142. altFormat: '@' // Gives a timestamp dateformat
  143. });
  144. });
  145. jQuery(function($){
  146. $.datepicker.regional['<?php echo $langs->defaultlang ?>'] = {
  147. closeText: '<?php echo $langs->trans("Close2") ?>',
  148. prevText: '<?php echo $langs->trans("Previous") ?>',
  149. nextText: '<?php echo $langs->trans("Next") ?>',
  150. currentText: '<?php echo $langs->trans("Now") ?>',
  151. monthNames: tradMonths,
  152. monthNamesShort: tradMonthsShort,
  153. dayNames: tradDays,
  154. dayNamesShort: tradDaysShort,
  155. dayNamesMin: tradDaysMin,
  156. weekHeader: '<?php echo $langs->trans("Week"); ?>',
  157. dateFormat: '<?php echo $langs->trans("FormatDateShortJQuery"); ?>', /* Note dd/mm/yy means year on 4 digit in jquery format */
  158. firstDay: <?php echo (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : '1'); ?>,
  159. isRTL: <?php echo ($langs->trans("DIRECTION") == 'rtl' ? 'true' : 'false'); ?>,
  160. showMonthAfterYear: false, /* TODO add specific to country */
  161. yearSuffix: '' /* TODO add specific to country */
  162. };
  163. $.datepicker.setDefaults($.datepicker.regional['<?php echo $langs->defaultlang ?>']);
  164. });
  165. /**
  166. * Set array used for select2 translations
  167. */
  168. var select2arrayoflanguage = {
  169. matches: function (matches) { return matches + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2ResultFoundUseArrows")); ?>"; },
  170. noResults: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2NotFound")); ?>"; },
  171. inputTooShort: function (input) {
  172. var n = input.minimum;
  173. /*console.log(input);
  174. console.log(input.minimum);*/
  175. if (n > 1) return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacters")); ?>";
  176. else return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacter")); ?>"
  177. },
  178. loadMore: function (pageNumber) { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2LoadingMoreResults")); ?>"; },
  179. searching: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2SearchInProgress")); ?>"; }
  180. };
  181. /**
  182. * For calendar input
  183. */
  184. // Returns an object given an id
  185. function getObjectFromID(id){
  186. var theObject;
  187. if(document.getElementById)
  188. theObject=document.getElementById(id);
  189. else
  190. theObject=document.all[id];
  191. return theObject;
  192. }
  193. // Called after selection of a date to save details into detailed fields
  194. function dpChangeDay(dateFieldID, format)
  195. {
  196. //showDP.datefieldID=dateFieldID;
  197. console.log("Call dpChangeDay, we save date into detailed fields from format = "+format);
  198. var thefield=getObjectFromID(dateFieldID);
  199. var thefieldday=getObjectFromID(dateFieldID+"day");
  200. var thefieldmonth=getObjectFromID(dateFieldID+"month");
  201. var thefieldyear=getObjectFromID(dateFieldID+"year");
  202. var date=getDateFromFormat(thefield.value, format);
  203. //console.log(date);
  204. if (date)
  205. {
  206. thefieldday.value=date.getDate();
  207. if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
  208. thefieldmonth.value=date.getMonth()+1;
  209. if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
  210. thefieldyear.value=date.getFullYear();
  211. if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
  212. }
  213. else
  214. {
  215. thefieldday.value='';
  216. if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
  217. thefieldmonth.value='';
  218. if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
  219. thefieldyear.value='';
  220. if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
  221. }
  222. }
  223. /*
  224. * =================================================================
  225. * Function:
  226. * formatDate (javascript object Date(), format) Purpose: Returns a date in the
  227. * output format specified. The format string can use the following tags: Field |
  228. * Tags -------------+------------------------------- Year | yyyy (4 digits), yy
  229. * (2 digits) Month | MM (2 digits) Day of Month | dd (2 digits) Hour (1-12) |
  230. * hh (2 digits) Hour (0-23) | HH (2 digits) Minute | mm (2 digits) Second | ss
  231. * (2 digits) Author: Laurent Destailleur Author: Matelli (see
  232. * http://matelli.fr/showcases/patchs-dolibarr/update-date-input-in-action-form.html)
  233. * Licence: GPL
  234. * ==================================================================
  235. */
  236. function formatDate(date,format)
  237. {
  238. // alert('formatDate date='+date+' format='+format);
  239. // Force parametres en chaine
  240. format=format+"";
  241. var result="";
  242. var year=date.getYear()+""; if (year.length < 4) { year=""+(year-0+1900); }
  243. var month=date.getMonth()+1;
  244. var day=date.getDate();
  245. var hour=date.getHours();
  246. var minute=date.getMinutes();
  247. var seconde=date.getSeconds();
  248. var i=0;
  249. while (i < format.length)
  250. {
  251. c=format.charAt(i); // Recupere char du format
  252. substr="";
  253. j=i;
  254. while ((format.charAt(j)==c) && (j < format.length)) // Recupere char successif identiques
  255. {
  256. substr += format.charAt(j++);
  257. }
  258. // alert('substr='+substr);
  259. if (substr == 'yyyy') { result=result+year; }
  260. else if (substr == 'yy') { result=result+year.substring(2,4); }
  261. else if (substr == 'M') { result=result+month; }
  262. else if (substr == 'MM') { result=result+(month<1||month>9?"":"0")+month; }
  263. else if (substr == 'd') { result=result+day; }
  264. else if (substr == 'dd') { result=result+(day<1||day>9?"":"0")+day; }
  265. else if (substr == 'hh') { if (hour > 12) hour-=12; result=result+(hour<0||hour>9?"":"0")+hour; }
  266. else if (substr == 'HH') { result=result+(hour<0||hour>9?"":"0")+hour; }
  267. else if (substr == 'mm') { result=result+(minute<0||minute>9?"":"0")+minute; }
  268. else if (substr == 'ss') { result=result+(seconde<0||seconde>9?"":"0")+seconde; }
  269. else { result=result+substr; }
  270. i+=substr.length;
  271. }
  272. // alert(result);
  273. return result;
  274. }
  275. /*
  276. * =================================================================
  277. * Function: getDateFromFormat(date_string, format_string)
  278. * Purpose: This function takes a date string and a format string.
  279. * It parses the date string with format and it
  280. * returns the date as a javascript Date() object. If date does not match
  281. * format, it returns 0. The format string can use the following tags:
  282. * Field | Tags
  283. * -------------+-----------------------------------
  284. * Year | yyyy (4 digits), yy (2 digits)
  285. * Month | MM (2 digits)
  286. * Day of Month | dd (2 digits)
  287. * Hour (1-12) | hh (2 digits)
  288. * Hour (0-23) | HH (2 digits)
  289. * Minute | mm (2 digits)
  290. * Second | ss (2 digits)
  291. * Author: Laurent Destailleur
  292. * Licence: GPL
  293. * ==================================================================
  294. */
  295. function getDateFromFormat(val,format)
  296. {
  297. // alert('getDateFromFormat val='+val+' format='+format);
  298. // Force parametres en chaine
  299. val=val+"";
  300. format=format+"";
  301. if (val == '') return 0;
  302. var now=new Date();
  303. var year=now.getYear(); if (year.length < 4) { year=""+(year-0+1900); }
  304. var month=now.getMonth()+1;
  305. var day=now.getDate();
  306. var hour=now.getHours();
  307. var minute=now.getMinutes();
  308. var seconde=now.getSeconds();
  309. var i=0;
  310. var d=0; // -d- follows the date string while -i- follows the format
  311. // string
  312. while (i < format.length)
  313. {
  314. c=format.charAt(i); // Recupere char du format
  315. substr="";
  316. j=i;
  317. while ((format.charAt(j)==c) && (j < format.length)) // Recupere char
  318. // successif
  319. // identiques
  320. {
  321. substr += format.charAt(j++);
  322. }
  323. // alert('substr='+substr);
  324. if (substr == "yyyy") year=getIntegerInString(val,d,4,4);
  325. if (substr == "yy") year=""+(getIntegerInString(val,d,2,2)-0+1900);
  326. if (substr == "MM" ||substr == "M")
  327. {
  328. month=getIntegerInString(val,d,1,2);
  329. if (month) d -= 2- month.length;
  330. }
  331. if (substr == "dd")
  332. {
  333. day=getIntegerInString(val,d,1,2);
  334. if (day) d -= 2- day.length;
  335. }
  336. if (substr == "HH" ||substr == "hh" )
  337. {
  338. hour=getIntegerInString(val,d,1,2);
  339. if (dhouray) d -= 2- hour.length;
  340. }
  341. if (substr == "mm"){
  342. minute=getIntegerInString(val,d,1,2);
  343. if (minute) d -= 2- minute.length;
  344. }
  345. if (substr == "ss")
  346. {
  347. seconde=getIntegerInString(val,d,1,2);
  348. if (seconde) d -= 2- seconde.length;
  349. }
  350. i+=substr.length;
  351. d+=substr.length;
  352. }
  353. // Check if format param are ok
  354. if (year==null||year<1) { return 0; }
  355. if (month==null||(month<1)||(month>12)) { return 0; }
  356. if (day==null||(day<1)||(day>31)) { return 0; }
  357. if (hour==null||(hour<0)||(hour>24)) { return 0; }
  358. if (minute==null||(minute<0)||(minute>60)) { return 0; }
  359. if (seconde==null||(seconde<0)||(seconde>60)) { return 0; }
  360. // alert(year+' '+month+' '+day+' '+hour+' '+minute+' '+seconde);
  361. return new Date(year,month-1,day,hour,minute,seconde);
  362. }
  363. /*
  364. * =================================================================
  365. * Function: stringIsInteger(string)
  366. * Purpose: Return true if string is an integer
  367. * ==================================================================
  368. */
  369. function stringIsInteger(str)
  370. {
  371. var digits="1234567890";
  372. for (var i=0; i < str.length; i++)
  373. {
  374. if (digits.indexOf(str.charAt(i))==-1)
  375. {
  376. return false;
  377. }
  378. }
  379. return true;
  380. }
  381. /*
  382. * =================================================================
  383. * Function: getIntegerInString(string,pos,minlength,maxlength)
  384. * Purpose: Return part of string from position i that is integer
  385. * ==================================================================
  386. */
  387. function getIntegerInString(str,i,minlength,maxlength)
  388. {
  389. for (var x=maxlength; x>=minlength; x--)
  390. {
  391. var substr=str.substring(i,i+x);
  392. if (substr.length < minlength) { return null; }
  393. if (stringIsInteger(substr)) { return substr; }
  394. }
  395. return null;
  396. }
  397. /*
  398. * =================================================================
  399. * Purpose: Clean string to have it url encoded
  400. * Input: s
  401. * Author: Laurent Destailleur
  402. * Licence: GPL
  403. * ==================================================================
  404. */
  405. function urlencode(s) {
  406. news=s;
  407. news=news.replace(/\+/gi,'%2B');
  408. news=news.replace(/&/gi,'%26');
  409. return news;
  410. }
  411. /*
  412. * =================================================================
  413. * Purpose: Clean string to have it url encoded
  414. * Input: s
  415. * Author: Laurent Destailleur
  416. * Licence: GPL
  417. * ==================================================================
  418. */
  419. function htmlEntityDecodeJs(inp){
  420. var replacements = {'&lt;':'<','&gt;':'>','&sol;':'/','&quot;':'"','&apos;':'\'','&amp;':'&','&nbsp;':' '};
  421. if (inp)
  422. {
  423. for(var r in replacements){
  424. inp = inp.replace(new RegExp(r,'g'),replacements[r]);
  425. }
  426. return inp.replace(/&#(\d+);/g, function(match, dec) {
  427. return String.fromCharCode(dec);
  428. });
  429. }
  430. else { return ''; }
  431. }
  432. /*
  433. * =================================================================
  434. * Purpose: Applique un delai avant execution. Used for autocompletion of companies.
  435. * Input: funct, delay
  436. * Author: Regis Houssin
  437. * Licence: GPL
  438. * ==================================================================
  439. */
  440. function ac_delay(funct,delay) {
  441. // delay before start of action
  442. setTimeout(funct,delay);
  443. }
  444. /*
  445. * =================================================================
  446. * Purpose:
  447. * Clean values of a "Sortable.serialize". Used by drag and drop.
  448. * Input: expr
  449. * Author: Regis Houssin
  450. * Licence: GPL
  451. * ==================================================================
  452. */
  453. function cleanSerialize(expr) {
  454. if (typeof(expr) != 'string') return '';
  455. var reg = new RegExp("(&)", "g");
  456. var reg2 = new RegExp("[^A-Z0-9,]", "g");
  457. var liste1 = expr.replace(reg, ",");
  458. return liste1.replace(reg2, "");
  459. }
  460. /*
  461. * =================================================================
  462. * Purpose: Display a temporary message in input text fields (For showing help message on
  463. * input field).
  464. * Input: fieldId
  465. * Input: message
  466. * Author: Regis Houssin
  467. * Licence: GPL
  468. * ==================================================================
  469. */
  470. function displayMessage(fieldId,message) {
  471. var textbox = document.getElementById(fieldId);
  472. if (textbox.value == '') {
  473. textbox.style.color = 'grey';
  474. textbox.value = message;
  475. }
  476. }
  477. /*
  478. * =================================================================
  479. * Purpose: Hide a temporary message in input text fields (For showing help message on
  480. * input field).
  481. * Input: fiedId
  482. * Input: message
  483. * Author: Regis Houssin
  484. * Licence: GPL
  485. * ==================================================================
  486. */
  487. function hideMessage(fieldId,message) {
  488. var textbox = document.getElementById(fieldId);
  489. textbox.style.color = 'black';
  490. if (textbox.value == message) textbox.value = '';
  491. }
  492. /*
  493. * Used by button to set on/off.
  494. * Call url then make complementary action (like show/hide, enable/disable or set another option).
  495. *
  496. * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
  497. * @param string code Code
  498. * @param string intput Array of complementary actions to do if success
  499. * @param int entity Entity
  500. * @param int strict Strict
  501. * @param int forcereload Force reload
  502. * @param int userid User id
  503. * @param int value Value to set
  504. * @param string token Token
  505. * @retun boolean
  506. */
  507. function setConstant(url, code, input, entity, strict, forcereload, userid, token, value) {
  508. var saved_url = url; /* avoid undefined url */
  509. $.post( url, {
  510. action: "set",
  511. name: code,
  512. entity: entity,
  513. token: token,
  514. value: value
  515. },
  516. function() { /* handler for success of post */
  517. console.log("Ajax url request to set constant is a success. Make complementary actions and then forcereload="+forcereload+" value="+value);
  518. if (value == 0) {
  519. $("#set_" + code).show();
  520. $("#del_" + code).hide();
  521. } else {
  522. $("#set_" + code).hide();
  523. $("#del_" + code).show();
  524. }
  525. $.each(input, function(type, data) {
  526. // Enable another element
  527. if (type == "disabled" && strict != 1) {
  528. $.each(data, function(key, value) {
  529. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  530. $(newvalue).removeAttr("disabled");
  531. if ($(newvalue).hasClass("butActionRefused") == true) {
  532. $(newvalue).removeClass("butActionRefused");
  533. $(newvalue).addClass("butAction");
  534. }
  535. });
  536. } else if (type == "enabled") {
  537. $.each(data, function(key, value) {
  538. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  539. if (strict == 1)
  540. $(newvalue).removeAttr("disabled");
  541. else
  542. $(newvalue).attr("disabled", true);
  543. if ($(newvalue).hasClass("butAction") == true) {
  544. $(newvalue).removeClass("butAction");
  545. $(newvalue).addClass("butActionRefused");
  546. }
  547. });
  548. // Show another element
  549. } else if (type == "showhide" || type == "show") {
  550. $.each(data, function(key, value) {
  551. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  552. $(newvalue).show();
  553. });
  554. // Set another constant
  555. } else if (type == "set") {
  556. $.each(data, function(key, value) {
  557. $("#set_" + key).hide();
  558. $("#del_" + key).show();
  559. $.post( saved_url, {
  560. action: "set",
  561. name: key,
  562. value: value,
  563. entity: entity,
  564. token: token
  565. });
  566. });
  567. }
  568. });
  569. if (forcereload) {
  570. var url = window.location.href;
  571. if (url.indexOf('dol_resetcache') < 0) {
  572. if (url.indexOf('?') > -1) {
  573. url = url + "&dol_resetcache=1";
  574. } else {
  575. url = url + "?dol_resetcache=1";
  576. }
  577. }
  578. var page_y = $(document).scrollTop();
  579. url = url.replace(/page_y=\d+/g, '');
  580. if (page_y > 0) {
  581. if (url.indexOf('?') > -1) {
  582. url = url + "&page_y="+page_y;
  583. } else {
  584. url = url + "?page_y="+page_y;
  585. }
  586. }
  587. url = url.replace(/&&+/, '&');
  588. console.log("url ro redirect = "+url);
  589. window.location.href = url;
  590. //location.reload();
  591. return false;
  592. }
  593. }).fail(function(error) { console.log("Error, we force reload"); location.reload(); }); /* When it fails, we always force reload to have setEventErrorMessages in session visible */
  594. return true;
  595. }
  596. /*
  597. * Used by button to set on/off
  598. * Call url then make complementary action (like show/hide, enable/disable or set another option).
  599. *
  600. * @param {string} url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
  601. * @param {string} code Code
  602. * @param {string} intput Array of complementary actions to do if success
  603. * @param {int} entity Entity
  604. * @param {int} strict Strict
  605. * @param {int} forcereload Force reload
  606. * @param {int} userid User id
  607. * @param {string} token Token
  608. * @return boolean
  609. */
  610. function delConstant(url, code, input, entity, strict, forcereload, userid, token) {
  611. var saved_url = url; /* avoid undefined url */
  612. $.post( url, {
  613. action: "del",
  614. name: code,
  615. entity: entity,
  616. token: token
  617. },
  618. function() {
  619. console.log("Ajax url request to delete constant is success. Make complementary actions and then forcereload="+forcereload);
  620. $("#del_" + code).hide();
  621. $("#set_" + code).show();
  622. $.each(input, function(type, data) {
  623. // Disable another element
  624. if (type == "disabled") {
  625. $.each(data, function(key, value) {
  626. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  627. $(newvalue).attr("disabled", true);
  628. if ($(newvalue).hasClass("butAction") == true) {
  629. $(newvalue).removeClass("butAction");
  630. $(newvalue).addClass("butActionRefused");
  631. }
  632. });
  633. } else if (type == "enabled" && strict != 1) {
  634. $.each(data, function(key, value) {
  635. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  636. $(newvalue).removeAttr("disabled");
  637. if ($(newvalue).hasClass("butActionRefused") == true) {
  638. $(newvalue).removeClass("butActionRefused");
  639. $(newvalue).addClass("butAction");
  640. }
  641. });
  642. // Hide another element
  643. } else if (type == "showhide" || type == "hide") {
  644. $.each(data, function(key, value) {
  645. var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
  646. $(newvalue).hide();
  647. });
  648. // Delete another constant
  649. } else if (type == "del") {
  650. $.each(data, function(key, value) {
  651. $("#del_" + value).hide();
  652. $("#set_" + value).show();
  653. $.post( saved_url, {
  654. action: "del",
  655. name: value,
  656. entity: entity,
  657. token: token
  658. });
  659. });
  660. }
  661. });
  662. if (forcereload) {
  663. var url = window.location.href;
  664. if (url.indexOf('dol_resetcache') < 0) {
  665. if (url.indexOf('?') > -1) {
  666. url = url + "&dol_resetcache=1";
  667. } else {
  668. url = url + "?dol_resetcache=1";
  669. }
  670. }
  671. var page_y = $(document).scrollTop();
  672. url = url.replace(/page_y=\d+/g, '');
  673. if (page_y > 0) {
  674. if (url.indexOf('?') > -1) {
  675. url = url + "&page_y="+page_y;
  676. } else {
  677. url = url + "?page_y="+page_y;
  678. }
  679. }
  680. url = url.replace(/&&+/, '&');
  681. console.log("url ro redirect = "+url);
  682. window.location.href = url;
  683. //location.reload();
  684. return false;
  685. }
  686. }).fail(function(error) { console.log("Error, we force reload"); location.reload(); }); /* When it fails, we always force reload to have setEventErrorMessages in session visible */
  687. return true;
  688. }
  689. /*
  690. * Call the setConstant or delConstant but with a confirmation before.
  691. * Used by button to set on/off.
  692. *
  693. * @param string action Action
  694. * @param string url Url
  695. * @param string code Code
  696. * @param string intput Array of complementary actions to do if success
  697. * @param string box Box
  698. * @param int entity Entity
  699. * @param int yesButton yesButton
  700. * @param int noButton noButton
  701. * @param int strict Strict
  702. * @param int userid User id
  703. * @param string token Token
  704. * @return boolean
  705. */
  706. function confirmConstantAction(action, url, code, input, box, entity, yesButton, noButton, strict, userid, token) {
  707. var boxConfirm = box;
  708. $("#confirm_" + code)
  709. .attr("title", boxConfirm.title)
  710. .html(boxConfirm.content)
  711. .dialog({
  712. resizable: false,
  713. height: 170,
  714. width: 500,
  715. modal: true,
  716. buttons: [
  717. {
  718. id : 'yesButton_' + code,
  719. text : yesButton,
  720. click : function() {
  721. if (action == "set") {
  722. setConstant(url, code, input, entity, strict, 0, userid, token, 1);
  723. } else if (action == "del") {
  724. delConstant(url, code, input, entity, strict, 0, userid, token);
  725. }
  726. // Close dialog
  727. $(this).dialog("close");
  728. // Execute another method
  729. if (boxConfirm.method) {
  730. var fnName = boxConfirm.method;
  731. if (window.hasOwnProperty(fnName)) {
  732. window[fnName]();
  733. }
  734. }
  735. }
  736. },
  737. {
  738. id : 'noButton_' + code,
  739. text : noButton,
  740. click : function() {
  741. $(this).dialog("close");
  742. }
  743. }
  744. ]
  745. });
  746. // For information dialog box only, hide the noButton
  747. if (boxConfirm.info) {
  748. $("#noButton_" + code).button().hide();
  749. }
  750. return true;
  751. }
  752. /*
  753. * =================================================================
  754. * This is to allow to transform all select box into ajax autocomplete box
  755. * with just one line:
  756. * $(function() { $( "#idofmylist" ).combobox(); });
  757. * Do not use it on large combo boxes
  758. * =================================================================
  759. */
  760. (function( $ ) {
  761. $.widget( "ui.combobox", {
  762. options: {
  763. minLengthToAutocomplete: 0
  764. },
  765. _create: function() {
  766. var savMinLengthToAutocomplete = this.options.minLengthToAutocomplete;
  767. var self = this,
  768. select = this.element.hide(),
  769. selected = select.children( ":selected" ),
  770. value = selected.val() ? selected.text() : "";
  771. var input = this.input = $( "<input>" )
  772. .insertAfter( select )
  773. .val( value )
  774. .attr('id', 'inputautocomplete'+select.attr('id'))
  775. .autocomplete({
  776. delay: 0,
  777. minLength: this.options.minLengthToAutocomplete,
  778. source: function( request, response ) {
  779. var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
  780. response( select.children( "option:enabled" ).map(function() {
  781. var text = $( this ).text();
  782. if ( this.value && ( !request.term || matcher.test(text) ) )
  783. return {
  784. label: text.replace(
  785. new RegExp(
  786. "(?![^&;]+;)(?!<[^<>]*)(" +
  787. $.ui.autocomplete.escapeRegex(request.term) +
  788. ")(?![^<>]*>)(?![^&;]+;)", "gi"
  789. ), "<strong>$1</strong>" ),
  790. value: text,
  791. option: this
  792. };
  793. }) );
  794. },
  795. select: function( event, ui ) {
  796. ui.item.option.selected = true;
  797. self._trigger( "selected", event, {
  798. item: ui.item.option
  799. });
  800. },
  801. change: function( event, ui ) {
  802. if ( !ui.item ) {
  803. var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
  804. valid = false;
  805. select.children( "option" ).each(function() {
  806. if ( $( this ).text().match( matcher ) ) {
  807. this.selected = valid = true;
  808. return false;
  809. }
  810. });
  811. if ( !valid ) {
  812. // remove invalid value, as it didnt match anything
  813. $( this ).val( "" );
  814. select.val( "" );
  815. input.data("ui-autocomplete").term = "";
  816. return false;
  817. }
  818. }
  819. }
  820. })
  821. .addClass( "ui-widget ui-widget-content ui-corner-left dolibarrcombobox" );
  822. input.data("ui-autocomplete")._renderItem = function( ul, item ) {
  823. return $("<li>")
  824. .data( "ui-autocomplete-item", item ) // jQuery UI > 1.10.0
  825. .append( "<a>" + item.label + "</a>" )
  826. .appendTo( ul );
  827. };
  828. this.button = $( "<button type=\'button\'>&nbsp;</button>" )
  829. .attr( "tabIndex", -1 )
  830. .attr( "title", "Show All Items" )
  831. .insertAfter( input )
  832. .button({
  833. icons: {
  834. primary: "ui-icon-triangle-1-s"
  835. },
  836. text: false
  837. })
  838. .removeClass( "ui-corner-all" )
  839. .addClass( "ui-corner-right ui-button-icon" )
  840. .click(function() {
  841. // close if already visible
  842. if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
  843. input.autocomplete( "close" );
  844. return;
  845. }
  846. // pass empty string as value to search for, displaying all results
  847. input.autocomplete({ minLength: 0 });
  848. input.autocomplete( "search", "" );
  849. input.autocomplete({ minLength: savMinLengthToAutocomplete });
  850. input.focus();
  851. });
  852. },
  853. destroy: function() {
  854. this.input.remove();
  855. this.button.remove();
  856. this.element.show();
  857. $.Widget.prototype.destroy.call( this );
  858. }
  859. });
  860. })( jQuery );
  861. /**
  862. * Function to output a dialog box for copy/paste
  863. *
  864. * @param text Text to put into copy/paste area
  865. * @param text2 Text to put under the copy/paste area
  866. */
  867. function copyToClipboard(text,text2)
  868. {
  869. text = text.replace(/<br>/g,"\n");
  870. var newElem = '<textarea id="coordsforpopup" style="border: none; width: 90%; height: 120px;">'+text+'</textarea><br><br>'+text2;
  871. /* alert(newElem); */
  872. $("#dialogforpopup").html(newElem);
  873. $("#dialogforpopup").dialog();
  874. $("#coordsforpopup").select();
  875. return false;
  876. }
  877. /**
  878. * Show a popup HTML page. Use the "window.open" function.
  879. *
  880. * @param url Url
  881. * @param title Title of popup
  882. * @return boolean False
  883. * @see document_preview
  884. */
  885. function newpopup(url, title) {
  886. var argv = newpopup.arguments;
  887. var argc = newpopup.arguments.length;
  888. tmp=url;
  889. console.log("newpopup "+argv[2]+" "+argv[3]);
  890. var l = (argc > 2) ? argv[2] : 600;
  891. var h = (argc > 3) ? argv[3] : 400;
  892. var left = (screen.width - l)/2;
  893. var top = (screen.height - h)/2;
  894. var wfeatures = "directories=0,menubar=0,status=0,resizable=0,scrollbars=1,toolbar=0,width=" + l +",height=" + h + ",left=" + left + ",top=" + top;
  895. fen=window.open(tmp,title,wfeatures);
  896. return false;
  897. }
  898. /**
  899. * Function show document preview. It uses the "dialog" function.
  900. * The a tag around the img must have the src='', class='documentpreview', mime='image/xxx', target='_blank' from getAdvancedPreviewUrl().
  901. *
  902. * @param file Url
  903. * @param type Mime file type ("image/jpeg", "application/pdf", "text/html")
  904. * @param title Title of popup
  905. * @return void
  906. * @see newpopup
  907. */
  908. function document_preview(file, type, title)
  909. {
  910. var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/webp"];
  911. var showOriginalSizeButton = false;
  912. console.log("document_preview A click was done. file="+file+", type="+type+", title="+title);
  913. if ($.inArray(type, ValidImageTypes) < 0) {
  914. /* Not an image */
  915. var width='85%';
  916. var object_width='100%';
  917. var height = ($( window ).height() - 60) * 0.90;
  918. var object_height='98%';
  919. show_preview('notimage');
  920. } else {
  921. /* This is an image */
  922. var object_width=0;
  923. var object_height=0;
  924. var img = new Image();
  925. img.onload = function() {
  926. object_width = this.width;
  927. object_height = this.height;
  928. width = $( window ).width()*0.90;
  929. console.log("object_width="+object_width+" window width="+width);
  930. if(object_width < width){
  931. console.log("Object width is small, we set width of popup according to image width.");
  932. width = object_width + 30
  933. }
  934. height = $( window ).height()*0.85;
  935. console.log("object_height="+object_height+" window height="+height);
  936. if(object_height < height){
  937. console.log("Object height is small, we set height of popup according to image height.");
  938. height = object_height + 80
  939. }
  940. else
  941. {
  942. showOriginalSizeButton = true;
  943. }
  944. show_preview('image');
  945. };
  946. img.src = file;
  947. }
  948. function show_preview(mode) {
  949. /* console.log("mode="+mode+" file="+file+" type="+type+" width="+width+" height="+height); */
  950. var newElem = '<object name="objectpreview" data="'+file+'" type="'+type+'" width="'+object_width+'" height="'+object_height+'" param="noparam"></object>';
  951. optionsbuttons = {}
  952. if (mode == 'image' && showOriginalSizeButton)
  953. {
  954. optionsbuttons = {
  955. "<?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" }); },
  956. "<?php echo dol_escape_js($langs->transnoentitiesnoconv("CloseWindow")); ?>": function() { $( this ).dialog( "close" ); }
  957. };
  958. }
  959. $("#dialogforpopup").html(newElem);
  960. $("#dialogforpopup").dialog({
  961. closeOnEscape: true,
  962. resizable: true,
  963. width: width,
  964. height: height,
  965. modal: true,
  966. title: title,
  967. buttons: optionsbuttons
  968. });
  969. if (showOriginalSizeButton)
  970. {
  971. jQuery(".ui-dialog-content.ui-widget-content > object").css({ "max-height": "100%", "width": "auto", "margin-left": "auto", "margin-right": "auto", "display": "block" });
  972. }
  973. }
  974. }
  975. /*
  976. * Provide a function to get an URL GET parameter in javascript
  977. *
  978. * @param name Name of parameter
  979. * @param valueifnotfound Value if not found
  980. * @return string Value
  981. */
  982. function getParameterByName(name, valueifnotfound)
  983. {
  984. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  985. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  986. results = regex.exec(location.search);
  987. return results === null ? valueifnotfound : decodeURIComponent(results[1].replace(/\+/g, " "));
  988. }
  989. // Code in the public domain from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  990. (function() {
  991. /**
  992. * Decimal adjustment of a number.
  993. *
  994. * @param {String} type The type of adjustment.
  995. * @param {Number} value The number.
  996. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
  997. * @returns {Number} The adjusted value.
  998. */
  999. function decimalAdjust(type, value, exp) {
  1000. // If the exp is undefined or zero...
  1001. if (typeof exp === 'undefined' || +exp === 0) {
  1002. return Math[type](value);
  1003. }
  1004. value = +value;
  1005. exp = +exp;
  1006. // If the value is not a number or the exp is not an integer...
  1007. if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
  1008. return NaN;
  1009. }
  1010. // Shift
  1011. value = value.toString().split('e');
  1012. value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  1013. // Shift back
  1014. value = value.toString().split('e');
  1015. return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  1016. }
  1017. // Decimal round
  1018. if (!Math.round10) {
  1019. Math.round10 = function(value, exp) {
  1020. return decimalAdjust('round', value, exp);
  1021. };
  1022. }
  1023. // Decimal floor
  1024. if (!Math.floor10) {
  1025. Math.floor10 = function(value, exp) {
  1026. return decimalAdjust('floor', value, exp);
  1027. };
  1028. }
  1029. // Decimal ceil
  1030. if (!Math.ceil10) {
  1031. Math.ceil10 = function(value, exp) {
  1032. return decimalAdjust('ceil', value, exp);
  1033. };
  1034. }
  1035. })();
  1036. // Another solution, easier, to build a javascript rounding function
  1037. function dolroundjs(number, decimals) { return +(Math.round(number + "e+" + decimals) + "e-" + decimals); }
  1038. /**
  1039. * Function similar to PHP price()
  1040. *
  1041. * Example use:
  1042. * pricejs(13312.448, 'MT', 'EUR', 'fr_FR')
  1043. * // (depending on conf for 'MT'): '13 312.45 €'
  1044. *
  1045. * pricejs(343000.121, 'MT')
  1046. * // assuming conf for 'MT' is 2 and $langs->defaultlang is 'en_US': '343,000.12'
  1047. *
  1048. * @param {number|string} amount The amount to show
  1049. * @param {string} mode 'MT' or 'MU'
  1050. * @param {string} currency_code ISO code of currency (empty by default)
  1051. * @param {string} force_locale ISO code locale to use (if empty, will use Dolibarr's current locale code)
  1052. * @return {string} The amount with digits
  1053. *
  1054. */
  1055. function pricejs(amount, mode = 'MT', currency_code = '', force_locale = '') {
  1056. var main_max_dec_shown = <?php echo (int) str_replace('.', '', getDolGlobalInt('MAIN_MAX_DECIMALS_SHOWN')); ?>;
  1057. var main_rounding_unit = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); ?>;
  1058. var main_rounding_tot = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); ?>;
  1059. var main_decimal_separator = <?php echo json_encode($dec) ?>;
  1060. var main_thousand_separator = <?php echo json_encode($thousand) ?>;
  1061. var locale_code = force_locale || <?php echo json_encode($langs->defaultlang) ?>;
  1062. var amountAsLocalizedString;
  1063. var useIntl = Boolean(Intl && Intl.NumberFormat);
  1064. var nDigits;
  1065. if (currency_code === 'auto') currency_code = <?php echo json_encode($conf->currency) ?>;
  1066. if (mode === 'MU') nDigits = main_rounding_unit;
  1067. else if (mode === 'MT') nDigits = main_rounding_tot;
  1068. else return 'Bad value for parameter mode';
  1069. if (useIntl) {
  1070. // simple version: let the browser decide how to format the number using the provided language / currency
  1071. // parameters
  1072. var formattingOptions = {
  1073. minimumFractionDigits: nDigits,
  1074. maximumFractionDigits: nDigits
  1075. };
  1076. if (currency_code) {
  1077. formattingOptions['style'] = 'currency';
  1078. formattingOptions['currency'] = currency_code;
  1079. }
  1080. return Intl.NumberFormat(locale_code.replace('_', '-'), formattingOptions).format(amount);
  1081. }
  1082. // No Intl -> attempt to format the number in a way similar to Dolibarr PHP's `price()` function
  1083. amountAsLocalizedString = amount.toFixed(nDigits).replace(
  1084. /((?!^)(?:\d{3})*)(?:\.(\d+))?$/,
  1085. (fullMatch, digitsByThree, decimals) =>
  1086. digitsByThree.replace(
  1087. /\d{3}/g,
  1088. (groupOfThree) => main_thousand_separator + groupOfThree
  1089. ) + (decimals !== undefined ? main_decimal_separator + decimals : '')
  1090. ).replace(/ /, ' ');
  1091. if (!currency_code) return amountAsLocalizedString;
  1092. // print with currency
  1093. var currency_symbol = currency_code;
  1094. // codes of languages / currencies where the symbol must be placed before the amount
  1095. var currencyBeforeAmountCodes = {
  1096. currency: ['AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD'],
  1097. language: ['nl_NL']
  1098. };
  1099. if (currencyCache[currency_code]
  1100. && currencyCache[currency_code]['unicode']
  1101. && currencyCache[currency_code]['unicode'].length) {
  1102. currency_symbol = currencyCache[currency_code]['unicode'].reduce(function (res, cur) {return res + cur}, '');
  1103. }
  1104. if (currencyBeforeAmountCodes.currency.indexOf(currency_code) >= 0
  1105. || currencyBeforeAmountCodes.language.indexOf(locale_code)) {
  1106. // if we use a language or a currency where the symbol is placed before the amount
  1107. return currency_symbol + amountAsLocalizedString;
  1108. }
  1109. // by default: currency symbol after the amount
  1110. return amountAsLocalizedString + ' ' + currency_symbol;
  1111. }
  1112. /**
  1113. * Function similar to PHP price2num()
  1114. *
  1115. * @param {number|string} amount The amount to convert/clean
  1116. * @return {number} The amount in universal numeric format (Example: '99.99999')
  1117. * @todo Implement rounding parameter
  1118. */
  1119. function price2numjs(amount) {
  1120. if (amount == '') return '';
  1121. var dec = <?php echo json_encode($dec) ?>;
  1122. var thousand = <?php echo json_encode($thousand) ?>;
  1123. var main_max_dec_shown = <?php echo (int) str_replace('.', '', getDolGlobalInt('MAIN_MAX_DECIMALS_SHOWN')); ?>;
  1124. var main_rounding_unit = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); ?>;
  1125. var main_rounding_tot = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); ?>;
  1126. var amount = amount.toString();
  1127. // rounding for unit price
  1128. var rounding = main_rounding_unit;
  1129. var pos = amount.indexOf(dec);
  1130. var decpart = '';
  1131. if (pos >= 0) {
  1132. decpart = amount.substring(pos + 1).replace('/0+$/i', ''); // Remove 0 for decimal part
  1133. }
  1134. var nbdec = decpart.length;
  1135. if (nbdec > rounding) {
  1136. rounding = nbdec;
  1137. }
  1138. // If rounding higher than max shown
  1139. if (rounding > main_max_dec_shown) rounding = main_max_dec_shown;
  1140. if (thousand != ',' && thousand != '.') amount = amount.replace(',', '.');
  1141. amount = amount.replace(' ', ''); // To avoid spaces
  1142. amount = amount.replace(thousand, ''); // Replace of thousand before replace of dec to avoid pb if thousand is .
  1143. amount = amount.replace(dec, '.');
  1144. //console.log("amount before="+amount+" rouding="+rounding)
  1145. var res = Math.round10(amount, - rounding);
  1146. // Other solution is
  1147. // var res = dolroundjs(amount, rounding)
  1148. console.log("price2numjs text="+amount+" return="+res);
  1149. return res;
  1150. }
  1151. <?php
  1152. if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY')) {
  1153. ?>
  1154. // Defined properties for JNotify
  1155. $(document).ready(function() {
  1156. if (typeof $.jnotify == 'function') {
  1157. $.jnotify.setup({
  1158. delay: 3000 // the default time to show each notification (in milliseconds)
  1159. , sticky: false // determines if the message should be considered "sticky" (user must manually close notification)
  1160. , closeLabel: "&times;" // the HTML to use for the "Close" link
  1161. , showClose: true // determines if the "Close" link should be shown if notification is also sticky
  1162. , fadeSpeed: 1000 // the speed to fade messages out (in milliseconds)
  1163. , slideSpeed: 250 // the speed used to slide messages out (in milliseconds)
  1164. , classContainer: "jnotify-container"
  1165. , classNotification: "jnotify-notification"
  1166. , classBackground: "jnotify-background"
  1167. , classClose: "jnotify-close"
  1168. , classMessage: "jnotify-message"
  1169. , init: null // callback that occurs when the main jnotify container is created
  1170. , create: null // callback that occurs when when the note is created (occurs just before appearing in DOM)
  1171. , beforeRemove: null // callback that occurs when before the notification starts to fade away
  1172. });
  1173. }
  1174. });
  1175. <?php } ?>
  1176. jQuery(document).ready(function() {
  1177. // Force to hide menus when page is inside an iFrame so we can show any page into a dialog popup
  1178. if (window.location && window.location.pathname.indexOf("externalsite/frametop.php") == -1 && window.location !== window.parent.location ) {
  1179. console.log("Page is detected to be into an iframe, we hide by CSS the menus");
  1180. // The page is in an iframe
  1181. jQuery(".side-nav-vert, .side-nav, .websitebar").hide();
  1182. jQuery(".id-container").css('width', '100%');
  1183. }
  1184. // Code to set tooltip on search field
  1185. jQuery('table.liste tr.liste_titre_filter td.liste_titre input[name^="search"][type=text]:not("maxwidthdate")').attr('title', '<?php echo dol_escape_js($langs->transnoentities("SearchSyntaxTooltipForStringOrNum")) ?>');
  1186. });
  1187. /*
  1188. * Hacky fix for a bug in select2 with jQuery 3.6.0's new nested-focus "protection"
  1189. * see: https://github.com/select2/select2/issues/5993
  1190. * see: https://github.com/jquery/jquery/issues/4382
  1191. *
  1192. * TODO: Recheck with the select2 GH issue and remove once this is fixed on their side
  1193. */
  1194. <?php
  1195. if (empty($conf->global->MAIN_DISABLE_SELECT2_FOCUS_PROTECTION) && !defined('DISABLE_SELECT2_FOCUS_PROTECTION')) {
  1196. ?>
  1197. $(document).on('select2:open', (e) => {
  1198. console.log("Execute the focus (click on combo or use space when on component");
  1199. const target = $(e.target);
  1200. if (target && target.length) {
  1201. let id = target[0].id || target[0].name;
  1202. if (id.substr(-2) == "[]") id = id.substr(0,id.length-2);
  1203. document.querySelector('input[aria-controls*='+id+']').focus();
  1204. }
  1205. });
  1206. <?php
  1207. }
  1208. ?>
  1209. // End of lib_head.js.php