dolibarr 21.0.0-beta
lib_head.js.php
Go to the documentation of this file.
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 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * or see https://www.gnu.org/
21 */
22
29if (!defined('NOREQUIRESOC')) {
30 define('NOREQUIRESOC', '1');
31}
32if (!defined('NOCSRFCHECK')) {
33 define('NOCSRFCHECK', 1);
34}
35if (!defined('NOTOKENRENEWAL')) {
36 define('NOTOKENRENEWAL', 1);
37}
38if (!defined('NOLOGIN')) {
39 define('NOLOGIN', 1);
40}
41if (!defined('NOREQUIREMENU')) {
42 define('NOREQUIREMENU', 1);
43}
44if (!defined('NOREQUIREHTML')) {
45 define('NOREQUIREHTML', 1);
46}
47if (!defined('NOREQUIREAJAX')) {
48 define('NOREQUIREAJAX', '1');
49}
50
51session_cache_limiter('public');
52
53require_once '../../main.inc.php';
59/*
60 * View
61 */
62
63// Define javascript type
64top_httphead('text/javascript; charset=UTF-8');
65// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
66if (empty($dolibarr_nocache)) {
67 header('Cache-Control: max-age=10800, public, must-revalidate');
68} else {
69 header('Cache-Control: no-cache');
70}
71
72
73
74// Define tradMonths javascript array (we define this in datepicker AND in parent page to avoid errors with IE8)
75$tradMonths = array(
76dol_escape_js($langs->transnoentitiesnoconv("Month01")),
77dol_escape_js($langs->transnoentitiesnoconv("Month02")),
78dol_escape_js($langs->transnoentitiesnoconv("Month03")),
79dol_escape_js($langs->transnoentitiesnoconv("Month04")),
80dol_escape_js($langs->transnoentitiesnoconv("Month05")),
81dol_escape_js($langs->transnoentitiesnoconv("Month06")),
82dol_escape_js($langs->transnoentitiesnoconv("Month07")),
83dol_escape_js($langs->transnoentitiesnoconv("Month08")),
84dol_escape_js($langs->transnoentitiesnoconv("Month09")),
85dol_escape_js($langs->transnoentitiesnoconv("Month10")),
86dol_escape_js($langs->transnoentitiesnoconv("Month11")),
87dol_escape_js($langs->transnoentitiesnoconv("Month12"))
88);
89
90$tradMonthsShort = array(
91$langs->trans("MonthShort01"),
92$langs->trans("MonthShort02"),
93$langs->trans("MonthShort03"),
94$langs->trans("MonthShort04"),
95$langs->trans("MonthShort05"),
96$langs->trans("MonthShort06"),
97$langs->trans("MonthShort07"),
98$langs->trans("MonthShort08"),
99$langs->trans("MonthShort09"),
100$langs->trans("MonthShort10"),
101$langs->trans("MonthShort11"),
102$langs->trans("MonthShort12")
103);
104
105$tradDays = array(
106$langs->trans("Sunday"),
107$langs->trans("Monday"),
108$langs->trans("Tuesday"),
109$langs->trans("Wednesday"),
110$langs->trans("Thursday"),
111$langs->trans("Friday"),
112$langs->trans("Saturday")
113);
114
115$tradDaysShort = array(
116$langs->trans("ShortSunday"),
117$langs->trans("ShortMonday"),
118$langs->trans("ShortTuesday"),
119$langs->trans("ShortWednesday"),
120$langs->trans("ShortThursday"),
121$langs->trans("ShortFriday"),
122$langs->trans("ShortSaturday")
123);
124
125$tradDaysMin = array(
126$langs->trans("SundayMin"),
127$langs->trans("MondayMin"),
128$langs->trans("TuesdayMin"),
129$langs->trans("WednesdayMin"),
130$langs->trans("ThursdayMin"),
131$langs->trans("FridayMin"),
132$langs->trans("SaturdayMin")
133);
134
135
136$dec = ',';
137$thousand = ' ';
138if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
139 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
140}
141if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
142 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
143}
144if ($thousand == 'Space') {
145 $thousand = ' ';
146}
147
148?>
149// Javascript libraries for Dolibarr ERP CRM (https://www.dolibarr.org)
150
151// For jQuery date picker
152var tradMonths = <?php echo json_encode($tradMonths) ?>;
153var tradMonthsShort = <?php echo json_encode($tradMonthsShort) ?>;
154var tradDays = <?php echo json_encode($tradDays) ?>;
155var tradDaysShort = <?php echo json_encode($tradDaysShort) ?>;
156var tradDaysMin = <?php echo json_encode($tradDaysMin) ?>;
157var currencyCache = <?php echo json_encode($langs->cache_currencies) ?>;
158
159// For JQuery date picker
160$(document).ready(function() {
161 $.datepicker.setDefaults({
162 autoSize: true,
163 changeMonth: true,
164 changeYear: true,
165 altField: '#timestamp',
166 altFormat: '@' // Gives a timestamp dateformat
167 });
168});
169
170jQuery(function($){
171 $.datepicker.regional['<?php echo $langs->defaultlang ?>'] = {
172 closeText: '<?php echo $langs->trans("Close2") ?>',
173 prevText: '<?php echo $langs->trans("Previous") ?>',
174 nextText: '<?php echo $langs->trans("Next") ?>',
175 currentText: '<?php echo $langs->trans("Now") ?>',
176 monthNames: tradMonths,
177 monthNamesShort: tradMonthsShort,
178 dayNames: tradDays,
179 dayNamesShort: tradDaysShort,
180 dayNamesMin: tradDaysMin,
181 weekHeader: '<?php echo $langs->trans("Week"); ?>',
182 dateFormat: '<?php echo $langs->trans("FormatDateShortJQuery"); ?>', /* Note dd/mm/yy means year on 4 digit in jquery format */
183 firstDay: <?php echo(isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : '1'); ?>,
184 isRTL: <?php echo($langs->trans("DIRECTION") == 'rtl' ? 'true' : 'false'); ?>,
185 showMonthAfterYear: false, /* TODO add specific to country */
186 yearSuffix: '' /* TODO add specific to country */
187 };
188 $.datepicker.setDefaults($.datepicker.regional['<?php echo $langs->defaultlang ?>']);
189});
190
191
192
197var select2arrayoflanguage = {
198 matches: function (matches) { return matches + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2ResultFoundUseArrows")); ?>"; },
199 noResults: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2NotFound")); ?>"; },
200 inputTooShort: function (input) {
201 var n = input.minimum;
202 /*console.log(input); console.log(input.minimum);*/
203 if (n > 1) return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacters")); ?>";
204 else return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacter")); ?>"
205 },
206 loadMore: function (pageNumber) { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2LoadingMoreResults")); ?>"; },
207 searching: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2SearchInProgress")); ?>"; }
208};
209
210
215// Returns an object given an id
216function getObjectFromID(id){
217 var theObject;
218 if(document.getElementById)
219 theObject=document.getElementById(id);
220 else
221 theObject=document.all[id];
222 return theObject;
223}
224
225// Called after selection of a date to save details into detailed fields
226function dpChangeDay(dateFieldID, format)
227{
228 //showDP.datefieldID=dateFieldID;
229 console.log("Call dpChangeDay, we save date into detailed fields from format = "+format);
230
231 var thefield=getObjectFromID(dateFieldID);
232 var thefieldday=getObjectFromID(dateFieldID+"day");
233 var thefieldmonth=getObjectFromID(dateFieldID+"month");
234 var thefieldyear=getObjectFromID(dateFieldID+"year");
235
236 var date=getDateFromFormat(thefield.value, format);
237 //console.log(date);
238 if (date)
239 {
240 thefieldday.value=date.getDate();
241 if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
242 thefieldmonth.value=date.getMonth()+1;
243 if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
244 thefieldyear.value=date.getFullYear();
245 if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
246 }
247 else
248 {
249 thefieldday.value='';
250 if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
251 thefieldmonth.value='';
252 if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
253 thefieldyear.value='';
254 if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
255 }
256}
257
258/*
259 * =================================================================
260 * Function: formatDate(javascript object Date(), format)
261 * Purpose: Returns a date in the output format specified. The format string can use the following tags:
262 * Year | yyyy (4 digits), yy (2 digits)
263 * Month | MM (2 digits)
264 * Day of Month | dd (2 digits)
265 * Hour (1-12) | hh (2 digits) Hour (0-23) | HH (2 digits)
266 * Minute | mm (2 digits)
267 * Second | ss (2 digits)
268 * Author: Laurent Destailleur Author: Matelli (see http://matelli.fr/showcases/patchs-dolibarr/update-date-input-in-action-form.html)
269 * Licence: GPL
270 * ==================================================================
271 */
272function formatDate(date,format)
273{
274 // alert('formatDate date='+date+' format='+format);
275
276 // Force parameters en chaine
277 format=format+"";
278
279 var result="";
280
281 var year=date.getFullYear();
282 var month=date.getMonth()+1;
283 var day=date.getDate();
284 var hour=date.getHours();
285 var minute=date.getMinutes();
286 var seconde=date.getSeconds();
287
288 var i=0;
289 while (i < format.length)
290 {
291 c=format.charAt(i); // Recupere char du format
292 var substr = '';
293 j=i;
294 while ((format.charAt(j)==c) && (j < format.length)) // Recupere char successif identiques
295 {
296 substr += format.charAt(j++);
297 }
298
299 // alert('substr='+substr);
300 if (substr == 'yyyy') { result=result+year; }
301 else if (substr == 'yy') { result=result+year.substring(2,4); }
302 else if (substr == 'M') { result=result+month; }
303 else if (substr == 'MM') { result=result+(month<1||month>9?"":"0")+month; }
304 else if (substr == 'd') { result=result+day; }
305 else if (substr == 'dd') { result=result+(day<1||day>9?"":"0")+day; }
306 else if (substr == 'hh') { if (hour > 12) hour-=12; result=result+(hour<0||hour>9?"":"0")+hour; }
307 else if (substr == 'HH') { result=result+(hour<0||hour>9?"":"0")+hour; }
308 else if (substr == 'mm') { result=result+(minute<0||minute>9?"":"0")+minute; }
309 else if (substr == 'ss') { result=result+(seconde<0||seconde>9?"":"0")+seconde; }
310 else { result=result+substr; }
311
312 i+=substr.length;
313 }
314
315 // alert(result);
316 return result;
317}
318
319
320/*
321 * =================================================================
322 * Function: getDateFromFormat(date_string, format_string)
323 * Purpose: This function takes a date string and a format string.
324 * It parses the date string with format and it
325 * returns the date as a javascript Date() object. If date does not match
326 * format, it returns 0. The format string can use the following tags:
327 * Field | Tags
328 * -------------+-----------------------------------
329 * Year | yyyy (4 digits), yy (2 digits)
330 * Month | MM (2 digits)
331 * Day of Month | dd (2 digits)
332 * Hour (1-12) | hh (2 digits)
333 * Hour (0-23) | HH (2 digits)
334 * Minute | mm (2 digits)
335 * Second | ss (2 digits)
336 * Author: Laurent Destailleur
337 * Licence: GPL
338 * ==================================================================
339 */
340function getDateFromFormat(val,format)
341{
342 // alert('getDateFromFormat val='+val+' format='+format);
343
344 // Force parameters en chaine
345 val=val+"";
346 format=format+"";
347
348 if (val == '') return 0;
349
350 var now=new Date();
351 var year=now.getFullYear();
352 var month=now.getMonth()+1;
353 var day=now.getDate();
354 var hour=now.getHours();
355 var minute=now.getMinutes();
356 var seconde=now.getSeconds();
357
358 var i=0;
359 var d=0; // -d- follows the date string while -i- follows the format
360 // string
361
362 while (i < format.length)
363 {
364 c=format.charAt(i); // Recupere char du format
365 substr="";
366 j=i;
367 while ((format.charAt(j)==c) && (j < format.length)) // Recupere char
368 // successif
369 // identiques
370 {
371 substr += format.charAt(j++);
372 }
373
374 // alert('substr='+substr);
375 if (substr == "yyyy") year=getIntegerInString(val,d,4,4);
376 if (substr == "yy") year=""+(getIntegerInString(val,d,2,2)-0+2000); /* #28334 */
377 if (substr == "MM" ||substr == "M")
378 {
379 month=getIntegerInString(val,d,1,2);
380 if (month) d -= 2- month.length;
381 }
382 if (substr == "dd")
383 {
384 day=getIntegerInString(val,d,1,2);
385 if (day) d -= 2- day.length;
386 }
387 if (substr == "HH" ||substr == "hh" )
388 {
389 hour=getIntegerInString(val,d,1,2);
390 if (dhouray) d -= 2- hour.length;
391 }
392 if (substr == "mm"){
393 minute=getIntegerInString(val,d,1,2);
394 if (minute) d -= 2- minute.length;
395 }
396 if (substr == "ss")
397 {
398 seconde=getIntegerInString(val,d,1,2);
399 if (seconde) d -= 2- seconde.length;
400 }
401
402 i+=substr.length;
403 d+=substr.length;
404 }
405
406 // Check if format param are ok
407 if (year==null||year<1) { return 0; }
408 if (month==null||(month<1)||(month>12)) { return 0; }
409 if (day==null||(day<1)||(day>31)) { return 0; }
410 if (hour==null||(hour<0)||(hour>24)) { return 0; }
411 if (minute==null||(minute<0)||(minute>60)) { return 0; }
412 if (seconde==null||(seconde<0)||(seconde>60)) { return 0; }
413
414 // alert(year+' '+month+' '+day+' '+hour+' '+minute+' '+seconde);
415 return new Date(year,month-1,day,hour,minute,seconde);
416}
417
418/*
419 * =================================================================
420 * Function: stringIsInteger(string)
421 * Purpose: Return true if string is an integer
422 * ==================================================================
423 */
424function stringIsInteger(str)
425{
426 var digits="1234567890";
427 for (var i=0; i < str.length; i++)
428 {
429 if (digits.indexOf(str.charAt(i))==-1)
430 {
431 return false;
432 }
433 }
434 return true;
435}
436
437/*
438 * =================================================================
439 * Function: getIntegerInString(string,pos,minlength,maxlength)
440 * Purpose: Return part of string from position i that is integer
441 * ==================================================================
442 */
443function getIntegerInString(str,i,minlength,maxlength)
444{
445 for (var x=maxlength; x>=minlength; x--)
446 {
447 var substr=str.substring(i,i+x);
448 if (substr.length < minlength) { return null; }
449 if (stringIsInteger(substr)) { return substr; }
450 }
451 return null;
452}
453
454
455/*
456 * =================================================================
457 * Purpose: Clean string to have it url encoded
458 * Input: s
459 * Author: Laurent Destailleur
460 * Licence: GPL
461 * ==================================================================
462 */
463function urlencode(s) {
464 var news = s;
465 news = news.replace(/\+/gi,'%2B');
466 news = news.replace(/&/gi,'%26');
467 return news;
468}
469
470/*
471 * =================================================================
472 * Purpose: Clean string to get a HTML coded string.
473 * Input: s
474 * Author: Laurent Destailleur
475 * Licence: GPL
476 * ==================================================================
477 */
478function htmlEntityDecodeJs(inp){
479 var replacements = {'&lt;':'<','&gt;':'>','&sol;':'/','&quot;':'"','&apos;':'\'','&amp;':'&','&nbsp;':' '};
480 if (inp) {
481 for(var r in replacements){
482 inp = inp.replace(new RegExp(r,'g'),replacements[r]);
483 }
484 return inp.replace(/&#(\d+);/g, function(match, dec) {
485 return String.fromCharCode(dec);
486 });
487 } else {
488 return '';
489 }
490}
491
492
493/*
494 * =================================================================
495 * Purpose: Applique un delai avant execution. Used for autocompletion of companies.
496 * Input: funct, delay
497 * Author: Regis Houssin
498 * Licence: GPL
499 * ==================================================================
500 */
501 function ac_delay(funct,delay) {
502 // delay before start of action
503 setTimeout(funct,delay);
504}
505
506
507/*
508 * =================================================================
509 * Purpose:
510 * Clean values of a "Sortable.serialize". Used by drag and drop.
511 * Input: expr
512 * Author: Regis Houssin
513 * Licence: GPL
514 * ==================================================================
515 */
516function cleanSerialize(expr) {
517 if (typeof(expr) != 'string') {
518 return '';
519 }
520 var reg = new RegExp("(&)", "g");
521 var reg2 = new RegExp("[^A-Z0-9,]", "g");
522 var liste1 = expr.replace(reg, ",");
523 return liste1.replace(reg2, "");
524}
525
526
527/*
528 * =================================================================
529 * Purpose: Display a temporary message in input text fields (For showing help message on
530 * input field).
531 * Input: fieldId
532 * Input: message
533 * Author: Regis Houssin
534 * Licence: GPL
535 * ==================================================================
536 */
537function displayMessage(fieldId,message) {
538 var textbox = document.getElementById(fieldId);
539 if (textbox.value == '') {
540 textbox.style.color = 'grey';
541 textbox.value = message;
542 }
543}
544
545/*
546 * =================================================================
547 * Purpose: Hide a temporary message in input text fields (For showing help message on
548 * input field).
549 * Input: fiedId
550 * Input: message
551 * Author: Regis Houssin
552 * Licence: GPL
553 * ==================================================================
554 */
555function hideMessage(fieldId,message) {
556 var textbox = document.getElementById(fieldId);
557 textbox.style.color = 'black';
558 if (textbox.value == message) textbox.value = '';
559}
560
561
562/*
563 * Used by button to set on/off.
564 * Call url then make complementary action (like show/hide, enable/disable or set another option).
565 *
566 * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
567 * @param string code Code
568 * @param string input Array of complementary actions to do if success
569 * @param int entity Entity
570 * @param int strict Strict (0=?, 1=?)
571 * @param int forcereload Force reload
572 * @param int userid User id
573 * @param string token Token
574 * @param int value Value to set
575 * @param int userconst 1=On/Off of user constant instead of global const
576 * @return boolean
577 */
578function setConstant(url, code, input, entity, strict, forcereload, userid, token, value, userconst) {
579 var saved_url = url; /* avoid undefined url */
580
581 $.post( url, {
582 action: "set",
583 name: code,
584 entity: entity,
585 token: token,
586 value: value,
587 userconst: userconst
588 },
589 function() { /* handler for success of post */
590 console.log("Ajax url request to set constant is a success. Make complementary actions and then forcereload="+forcereload+" value="+value);
591 if (value == 0) {
592 $("#set_" + code).show();
593 $("#del_" + code).hide();
594 } else {
595 $("#set_" + code).hide();
596 $("#del_" + code).show();
597 }
598 $.each(input, function(type, data) {
599 // Enable another element
600 if (type == "disabled" && strict != 1) {
601 $.each(data, function(key, value) {
602 var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
603 $(newvalue).removeAttr("disabled");
604 if ($(newvalue).hasClass("butActionRefused") == true) {
605 $(newvalue).removeClass("butActionRefused");
606 $(newvalue).addClass("butAction");
607 }
608 });
609 } else if (type == "enabled") {
610 $.each(data, function(key, value) {
611 var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
612 if (strict == 1)
613 $(newvalue).removeAttr("disabled");
614 else
615 $(newvalue).attr("disabled", true);
616 if ($(newvalue).hasClass("butAction") == true) {
617 $(newvalue).removeClass("butAction");
618 $(newvalue).addClass("butActionRefused");
619 }
620 });
621 // Show another element
622 } else if (type == "showhide" || type == "show") {
623 $.each(data, function(key, value) {
624 var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
625 $(newvalue).show();
626 });
627 // Set another constant
628 } else if (type == "set") {
629 $.each(data, function(key, value) {
630 $("#set_" + key).hide();
631 $("#del_" + key).show();
632 $.post( saved_url, {
633 action: "set",
634 name: key,
635 value: value,
636 entity: entity,
637 token: token
638 });
639 });
640 }
641 });
642 if (forcereload) {
643 var url = window.location.href;
644 if (url.indexOf('dol_resetcache') < 0) {
645 if (url.indexOf('?') > -1) {
646 url = url + "&dol_resetcache=1";
647 } else {
648 url = url + "?dol_resetcache=1";
649 }
650 }
651 var page_y = $(document).scrollTop();
652 url = url.replace(/page_y=\d+/g, '');
653 if (page_y > 0) {
654 if (url.indexOf('?') > -1) {
655 url = url + "&page_y="+page_y;
656 } else {
657 url = url + "?page_y="+page_y;
658 }
659 }
660 url = url.replace(/&&+/, '&');
661 console.log("url ro redirect = "+url);
662
663 window.location.href = url;
664 //location.reload();
665 return false;
666 }
667 }).fail(function(error) { console.log("Error, we force reload"); location.reload(); }); /* When it fails, we always force reload to have setEventErrorMessages in session visible */
668
669 return true;
670}
671
672/*
673 * Used by button to set on/off
674 * Call url then make complementary action (like show/hide, enable/disable or set another option).
675 *
676 * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
677 * @param string code Code
678 * @param string input Array of complementary actions to do if success
679 * @param int entity Entity
680 * @param int strict Strict
681 * @param int forcereload Force reload
682 * @param int userid User id
683 * @param string token Token
684 * @param int userconst 1=On/Off of user constant instead of global const
685 * @return boolean
686 */
687function delConstant(url, code, input, entity, strict, forcereload, userid, token, userconst) {
688 var saved_url = url; /* avoid undefined url */
689
690 $.post( url, {
691 action: "del",
692 name: code,
693 entity: entity,
694 token: token,
695 userconst: userconst
696 },
697 function() {
698 console.log("Ajax url request to delete constant is success. Make complementary actions and then forcereload="+forcereload);
699 $("#del_" + code).hide();
700 $("#set_" + code).show();
701 $.each(input, function(type, data) {
702 // Disable another element
703 if (type == "disabled") {
704 $.each(data, function(key, value) {
705 var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
706 $(newvalue).attr("disabled", true);
707 if ($(newvalue).hasClass("butAction") == true) {
708 $(newvalue).removeClass("butAction");
709 $(newvalue).addClass("butActionRefused");
710 }
711 });
712 } else if (type == "enabled" && strict != 1) {
713 $.each(data, function(key, value) {
714 var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
715 $(newvalue).removeAttr("disabled");
716 if ($(newvalue).hasClass("butActionRefused") == true) {
717 $(newvalue).removeClass("butActionRefused");
718 $(newvalue).addClass("butAction");
719 }
720 });
721 // Hide another element
722 } else if (type == "showhide" || type == "hide") {
723 $.each(data, function(key, value) {
724 var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
725 $(newvalue).hide();
726 });
727 // Delete another constant
728 } else if (type == "del") {
729 $.each(data, function(key, value) {
730 $("#del_" + value).hide();
731 $("#set_" + value).show();
732 $.post( saved_url, {
733 action: "del",
734 name: value,
735 entity: entity,
736 token: token
737 });
738 });
739 }
740 });
741 if (forcereload) {
742 var url = window.location.href;
743 if (url.indexOf('dol_resetcache') < 0) {
744 if (url.indexOf('?') > -1) {
745 url = url + "&dol_resetcache=1";
746 } else {
747 url = url + "?dol_resetcache=1";
748 }
749 }
750 var page_y = $(document).scrollTop();
751 url = url.replace(/page_y=\d+/g, '');
752 if (page_y > 0) {
753 if (url.indexOf('?') > -1) {
754 url = url + "&page_y="+page_y;
755 } else {
756 url = url + "?page_y="+page_y;
757 }
758 }
759 url = url.replace(/&&+/, '&');
760 console.log("url ro redirect = "+url);
761
762 window.location.href = url;
763 //location.reload();
764 return false;
765 }
766 }).fail(function(error) { console.log("Error, we force reload"); location.reload(); }); /* When it fails, we always force reload to have setEventErrorMessages in session visible */
767
768 return true;
769}
770
771/*
772 * Call the setConstant or delConstant but with a confirmation before.
773 * Used by button to set on/off.
774 *
775 * @param string action Action
776 * @param string url Url
777 * @param string code Code
778 * @param string input Array of complementary actions to do if success
779 * @param string box Box
780 * @param int entity Entity
781 * @param int yesButton yesButton
782 * @param int noButton noButton
783 * @param int strict Strict
784 * @param int userid User id
785 * @param string token Token
786 * @return boolean
787 */
788function confirmConstantAction(action, url, code, input, box, entity, yesButton, noButton, strict, userid, token) {
789 var boxConfirm = box;
790 $("#confirm_" + code)
791 .attr("title", boxConfirm.title)
792 .html(boxConfirm.content)
793 .dialog({
794 resizable: false,
795 height: 170,
796 width: 500,
797 modal: true,
798 buttons: [
799 {
800 id : 'yesButton_' + code,
801 text : yesButton,
802 click : function() {
803 if (action == "set") {
804 setConstant(url, code, input, entity, strict, 0, userid, token, 1);
805 } else if (action == "del") {
806 delConstant(url, code, input, entity, strict, 0, userid, token);
807 }
808 // Close dialog
809 $(this).dialog("close");
810 // Execute another method
811 if (boxConfirm.method) {
812 var fnName = boxConfirm.method;
813 if (window.hasOwnProperty(fnName)) {
814 window[fnName]();
815 }
816 }
817 }
818 },
819 {
820 id : 'noButton_' + code,
821 text : noButton,
822 click : function() {
823 $(this).dialog("close");
824 }
825 }
826 ]
827 });
828 // For information dialog box only, hide the noButton
829 if (boxConfirm.info) {
830 $("#noButton_" + code).button().hide();
831 }
832
833 return true;
834}
835
836
837/*
838 * =================================================================
839 * This is to allow to transform all select box into ajax autocomplete box
840 * with just one line:
841 * $(function() { $( "#idofmylist" ).combobox(); });
842 * Do not use it on large combo boxes
843 * =================================================================
844 */
845(function( $ ) {
846 $.widget( "ui.combobox", {
847 options: {
848 minLengthToAutocomplete: 0
849 },
850 _create: function() {
851 var savMinLengthToAutocomplete = this.options.minLengthToAutocomplete;
852 var self = this,
853 select = this.element.hide(),
854 selected = select.children( ":selected" ),
855 value = selected.val() ? selected.text() : "";
856 var input = this.input = $( "<input>" )
857 .insertAfter( select )
858 .val( value )
859 .attr('id', 'inputautocomplete'+select.attr('id'))
860 .autocomplete({
861 delay: 0,
862 minLength: this.options.minLengthToAutocomplete,
863 source: function( request, response ) {
864 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
865 response( select.children( "option:enabled" ).map(function() {
866 var text = $( this ).text();
867 if ( this.value && ( !request.term || matcher.test(text) ) )
868 return {
869 label: text.replace(
870 new RegExp(
871 "(?![^&;]+;)(?!<[^<>]*)(" +
872 $.ui.autocomplete.escapeRegex(request.term) +
873 ")(?![^<>]*>)(?![^&;]+;)", "gi"
874 ), "<strong>$1</strong>" ),
875 value: text,
876 option: this
877 };
878 }) );
879 },
880 select: function( event, ui ) {
881 ui.item.option.selected = true;
882 self._trigger( "selected", event, {
883 item: ui.item.option
884 });
885 },
886 change: function( event, ui ) {
887 if ( !ui.item ) {
888 var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
889 valid = false;
890 select.children( "option" ).each(function() {
891 if ( $( this ).text().match( matcher ) ) {
892 this.selected = valid = true;
893 return false;
894 }
895 });
896 if ( !valid ) {
897 // remove invalid value, as it didn't match anything
898 $( this ).val( "" );
899 select.val( "" );
900 input.data("ui-autocomplete").term = "";
901 return false;
902 }
903 }
904 }
905 })
906 .addClass( "ui-widget ui-widget-content ui-corner-left dolibarrcombobox" );
907
908 input.data("ui-autocomplete")._renderItem = function( ul, item ) {
909 return $("<li>")
910 .data( "ui-autocomplete-item", item ) // jQuery UI > 1.10.0
911 .append( "<a>" + item.label + "</a>" )
912 .appendTo( ul );
913 };
914
915 this.button = $( "<button type=\'button\'>&nbsp;</button>" )
916 .attr( "tabIndex", -1 )
917 .attr( "title", "Show All Items" )
918 .insertAfter( input )
919 .button({
920 icons: {
921 primary: "ui-icon-triangle-1-s"
922 },
923 text: false
924 })
925 .removeClass( "ui-corner-all" )
926 .addClass( "ui-corner-right ui-button-icon" )
927 .click(function() {
928 // close if already visible
929 if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
930 input.autocomplete( "close" );
931 return;
932 }
933
934 // pass empty string as value to search for, displaying all results
935 input.autocomplete({ minLength: 0 });
936 input.autocomplete( "search", "" );
937 input.autocomplete({ minLength: savMinLengthToAutocomplete });
938 input.focus();
939 });
940 },
941
942 destroy: function() {
943 this.input.remove();
944 this.button.remove();
945 this.element.show();
946 $.Widget.prototype.destroy.call( this );
947 }
948 });
949})( jQuery );
950
951
952
959function copyToClipboard(text,text2)
960{
961 text = text.replace(/<br>/g,"\n");
962 var newElem = '<textarea id="coordsforpopup" style="border: none; width: 90%; height: 120px;">'+text+'</textarea><br><br>'+text2;
963 /* alert(newElem); */
964 $("#dialogforpopup").html(newElem);
965 $("#dialogforpopup").dialog();
966 $("#coordsforpopup").select();
967
968 return false;
969}
970
971
980function newpopup(url, title) {
981 var argv = newpopup.arguments;
982 var argc = newpopup.arguments.length;
983 var tmp = url;
984 console.log("newpopup "+argv[2]+" "+argv[3]);
985 var l = (argc > 2) ? argv[2] : 600;
986 var h = (argc > 3) ? argv[3] : 400;
987 var left = (screen.width - l)/2;
988 var top = (screen.height - h)/2;
989 var wfeatures = "directories=0,menubar=0,status=0,resizable=0,scrollbars=1,toolbar=0,location=0,width=" + l +",height=" + h + ",left=" + left + ",top=" + top;
990 fen = window.open(tmp, title, wfeatures);
991
992 return false;
993}
994
1005function document_preview(file, type, title)
1006{
1007 var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/webp"];
1008 var showOriginalSizeButton = false;
1009
1010 console.log("document_preview A click was done: file="+file+", type="+type+", title="+title);
1011
1012 if ($.inArray(type, ValidImageTypes) < 0) {
1013 /* Not an image */
1014 var width='85%';
1015 var object_width='100%';
1016 var height = ($( window ).height() - 60) * 0.90;
1017 var object_height='98%';
1018
1019 show_preview('notimage');
1020
1021 } else {
1022 /* This is an image */
1023 var object_width=0;
1024 var object_height=0;
1025
1026 var img = new Image();
1027
1028 img.onload = function() {
1029 object_width = this.width;
1030 object_height = this.height;
1031
1032 width = $( window ).width()*0.90;
1033 console.log("object_width="+object_width+" window width="+width);
1034 if(object_width < width){
1035 console.log("Object width is small, we set width of popup according to image width.");
1036 width = object_width + 30
1037 }
1038 height = $( window ).height()*0.85;
1039 console.log("object_height="+object_height+" window height="+height);
1040 if(object_height < height){
1041 console.log("Object height is small, we set height of popup according to image height.");
1042 height = object_height + 80
1043 }
1044 else
1045 {
1046 showOriginalSizeButton = true;
1047 }
1048
1049 show_preview('image');
1050
1051 };
1052 img.src = file;
1053
1054 }
1055
1056 function show_preview(mode) {
1057 /* console.log("mode="+mode+" file="+file+" type="+type+" width="+width+" height="+height); */
1058 var newElem = '<object name="objectpreview" data="'+file+'" type="'+type+'" width="'+object_width+'" height="'+object_height+'" param="noparam"></object>';
1059
1060 optionsbuttons = {}
1061 if (mode == 'image' && showOriginalSizeButton)
1062 {
1063 var curRot = 0;
1064 optionsbuttons = {
1065 "<?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" }); },
1066 "<?php echo dol_escape_js($langs->transnoentitiesnoconv("RotateImage")); ?>": function() { curRot += 90; jQuery(".ui-dialog-content.ui-widget-content > object").css("transform","rotate(" + curRot + "deg)"); },
1067 "<?php echo dol_escape_js($langs->transnoentitiesnoconv("CloseWindow")); ?>": function() { $( this ).dialog( "close" ); }
1068 };
1069 }
1070
1071 $("#dialogforpopup").html(newElem);
1072
1073 $("#dialogforpopup").dialog({
1074 closeOnEscape: true,
1075 resizable: true,
1076 width: width,
1077 height: height,
1078 modal: true,
1079 title: title,
1080 buttons: optionsbuttons
1081 });
1082
1083 if (showOriginalSizeButton)
1084 {
1085 jQuery(".ui-dialog-content.ui-widget-content > object").css({ "max-height": "100%", "width": "auto", "margin-left": "auto", "margin-right": "auto", "display": "block" });
1086 }
1087 }
1088}
1089
1090/*
1091 * Provide a function to get an URL GET parameter in javascript
1092 *
1093 * @param name Name of parameter
1094 * @param valueifnotfound Value if not found
1095 * @return string Value
1096 */
1097function getParameterByName(name, valueifnotfound)
1098{
1099 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
1100 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
1101 results = regex.exec(location.search);
1102 return results === null ? valueifnotfound : decodeURIComponent(results[1].replace(/\+/g, " "));
1103}
1104
1109 // Define the list of operators for each general field category
1110 const operatorList = {
1111 selectlink: {
1112 Is: '<?php print dol_escape_js($langs->trans('Is')); ?>',
1113 IsNot: '<?php print dol_escape_js($langs->trans('IsNot')); ?>',
1114 },
1115 text: {
1116 Contains: '<?php print dol_escape_js($langs->trans('Contains')); ?>',
1117 DoesNotContain: '<?php print dol_escape_js($langs->trans('DoesNotContain')); ?>',
1118 Is: '<?php print dol_escape_js($langs->trans('Is')); ?>',
1119 IsNot: '<?php print dol_escape_js($langs->trans('IsNot')); ?>',
1120 StartsWith: '<?php print dol_escape_js($langs->trans('StartsWith')); ?>',
1121 EndsWith: '<?php print dol_escape_js($langs->trans('EndsWith')); ?>'
1122 },
1123 number: {
1124 '=': '<?php print dol_escape_js($langs->trans('Is')); ?>',
1125 '!=': '<?php print dol_escape_js($langs->trans('IsNot')); ?>',
1126 '<': '<?php print dol_escape_js($langs->trans('IsLowerThan')); ?>',
1127 '>': '<?php print dol_escape_js($langs->trans('IsHigherThan')); ?>',
1128 '<=': '<?php print dol_escape_js($langs->trans('IsLowerThanOrEqual')); ?>',
1129 '>=': '<?php print dol_escape_js($langs->trans('IsHigherThanOrEqual')); ?>',
1130 },
1131 date: {
1132 Is: '<?php print dol_escape_js($langs->trans('Is')); ?>',
1133 IsNot: '<?php print dol_escape_js($langs->trans('IsNot')); ?>',
1134 IsBefore: '<?php print dol_escape_js($langs->trans('IsBefore')); ?>',
1135 IsAfter: '<?php print dol_escape_js($langs->trans('IsAfter')); ?>',
1136 IsOnOrBefore: '<?php print dol_escape_js($langs->trans('IsOnOrBefore')); ?>',
1137 IsOnOrAfter: '<?php print dol_escape_js($langs->trans('IsOnOrAfter')); ?>'
1138 },
1139 html: {
1140 Contains: '<?php print $langs->trans('Contains'); ?>'
1141 }
1142 };
1143
1144
1145 // Determine the general category for the given type using regex
1146 let generalType = "";
1147
1148 console.log('Get list of operators for type='+type);
1149
1150 if (/^select$/i.test(type) || /^link$/i.test(type)) {
1151 generalType = "selectlink";
1152 } else if (/^(varchar|char|text|blob|nchar|mediumtext|longtext)\(\d+\)$/i.test(type) || /^varchar$/i.test(type)) {
1153 generalType = "text";
1154 } else if (/^(int|integer|float|double|decimal|numeric)(\(\d+,\d+\))?$/i.test(type)) {
1155 generalType = "number";
1156 } else if (/^(date|datetime|timestamp)$/i.test(type)) {
1157 generalType = "date";
1158 } else if (/^(tinyint|smallint)\(\d+\)$/i.test(type)) {
1159 generalType = "number";
1160 } else if (/^html$/i.test(type)) {
1161 generalType = "html";
1162 } else {
1163 // Handle unknown or unsupported types
1164 console.log("The type of field "+type+" is not supported");
1165 return [];
1166 }
1167
1168 // Return the operators for the general type, or an empty array if not found
1169 return operatorList[generalType] || [];
1170}
1171
1175function generateFilterString(column, operator, context, fieldType) {
1176 let filter = "";
1177
1178 switch (operator) {
1179 case "Contains":
1180 filter = column + " like \'%" + context + "%\'";
1181 break;
1182 case "DoesNotContain":
1183 filter = column + " notlike \'%" + context + "%\'";
1184 break;
1185 case "Is":
1186 filter = column + " = \'" + context + "\'";
1187 break;
1188 case "IsNot":
1189 filter = column + " != \'" + context + "\'";
1190 break;
1191 case "StartsWith":
1192 filter = column + " like \'" + context + "%\'";
1193 break;
1194 case "EndsWith":
1195 filter = column + " like \'%" + context + "\'";
1196 break;
1197 case "=":
1198 filter = column + " = \'" + context + "\'";
1199 break;
1200 case "!=":
1201 filter = column + " != \'" + context + "\'";
1202 break;
1203 case "<":
1204 filter = column + " < \'" + context + "\'";
1205 break;
1206 case ">":
1207 filter = column + " > \'" + context + "\'";
1208 break;
1209 case "<=":
1210 filter = column + " <= \'" + context + "\'";
1211 break;
1212 case ">=":
1213 filter = column + " >= \'" + context + "\'";
1214 break;
1215 case "IsBefore":
1216 filter = column + " < \'" + context + "\'";
1217 break;
1218 case "IsAfter":
1219 filter = column + " > \'" + context + "\'";
1220 break;
1221 case "IsOnOrBefore":
1222 filter = column + " <= \'" + context + "\'";
1223 break;
1224 case "IsOnOrAfter":
1225 filter = column + " >= \'" + context + "\'";
1226 break;
1227 default:
1228 filter = "";
1229 }
1230
1231 return filter;
1232}
1233
1234// Code in the public domain from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
1235(function() {
1244 function decimalAdjust(type, value, exp) {
1245 // If the exp is undefined or zero...
1246 if (typeof exp === 'undefined' || +exp === 0) {
1247 return Math[type](value);
1248 }
1249 value = +value;
1250 exp = +exp;
1251 // If the value is not a number or the exp is not an integer...
1252 if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
1253 return NaN;
1254 }
1255 // Shift
1256 value = value.toString().split('e');
1257 value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
1258 // Shift back
1259 value = value.toString().split('e');
1260 return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
1261 }
1262
1263 // Decimal round
1264 if (!Math.round10) {
1265 Math.round10 = function(value, exp) {
1266 return decimalAdjust('round', value, exp);
1267 };
1268 }
1269 // Decimal floor
1270 if (!Math.floor10) {
1271 Math.floor10 = function(value, exp) {
1272 return decimalAdjust('floor', value, exp);
1273 };
1274 }
1275 // Decimal ceil
1276 if (!Math.ceil10) {
1277 Math.ceil10 = function(value, exp) {
1278 return decimalAdjust('ceil', value, exp);
1279 };
1280 }
1281})();
1282
1283// Another solution, easier, to build a javascript rounding function
1284function dolroundjs(number, decimals) { return +(Math.round(number + "e+" + decimals) + "e-" + decimals); }
1285
1303function pricejs(amount, mode = 'MT', currency_code = '', force_locale = '') {
1304 var main_max_dec_shown = <?php echo (int) str_replace('.', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN')); ?>;
1305 var main_rounding_unit = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); ?>;
1306 var main_rounding_tot = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); ?>;
1307 var main_decimal_separator = <?php echo json_encode($dec) ?>;
1308 var main_thousand_separator = <?php echo json_encode($thousand) ?>;
1309 var locale_code = force_locale || <?php echo json_encode($langs->defaultlang) ?>;
1310 var amountAsLocalizedString;
1311 var useIntl = Boolean(Intl && Intl.NumberFormat);
1312 var nDigits;
1313 if (currency_code === 'auto') currency_code = <?php echo json_encode($conf->currency) ?>;
1314
1315 if (mode === 'MU') nDigits = main_rounding_unit;
1316 else if (mode === 'MT') nDigits = main_rounding_tot;
1317 else return 'Bad value for parameter mode';
1318
1319 if (useIntl) {
1320 // simple version: let the browser decide how to format the number using the provided language / currency
1321 // parameters
1322 var formattingOptions = {
1323 minimumFractionDigits: nDigits,
1324 maximumFractionDigits: nDigits
1325 };
1326 if (currency_code) {
1327 formattingOptions['style'] = 'currency';
1328 formattingOptions['currency'] = currency_code;
1329 }
1330 return Intl.NumberFormat(locale_code.replace('_', '-'), formattingOptions).format(amount);
1331 }
1332
1333 // No Intl -> attempt to format the number in a way similar to Dolibarr PHP's `price()` function
1334 amountAsLocalizedString = amount.toFixed(nDigits).replace(
1335 /((?!^)(?:\d{3})*)(?:\.(\d+))?$/,
1336 (fullMatch, digitsByThree, decimals) =>
1337 digitsByThree.replace(
1338 /\d{3}/g,
1339 (groupOfThree) => main_thousand_separator + groupOfThree
1340 ) + (decimals !== undefined ? main_decimal_separator + decimals : '')
1341 ).replace(/ /, ' ');
1342 if (!currency_code) return amountAsLocalizedString;
1343
1344 // print with currency
1345 var currency_symbol = currency_code;
1346
1347 // codes of languages / currencies where the symbol must be placed before the amount
1348 var currencyBeforeAmountCodes = {
1349 currency: ['AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD'],
1350 language: ['nl_NL']
1351 };
1352
1353 if (currencyCache[currency_code]
1354 && currencyCache[currency_code]['unicode']
1355 && currencyCache[currency_code]['unicode'].length) {
1356 currency_symbol = currencyCache[currency_code]['unicode'].reduce(function (res, cur) {return res + cur}, '');
1357 }
1358
1359 if (currencyBeforeAmountCodes.currency.indexOf(currency_code) >= 0
1360 || currencyBeforeAmountCodes.language.indexOf(locale_code)) {
1361 // if we use a language or a currency where the symbol is placed before the amount
1362 return currency_symbol + amountAsLocalizedString;
1363 }
1364
1365 // by default: currency symbol after the amount
1366 return amountAsLocalizedString + ' ' + currency_symbol;
1367}
1368
1376function price2numjs(amount) {
1377 if (amount == '') return '';
1378
1379 var dec = <?php echo json_encode($dec) ?>;
1380 var thousand = <?php echo json_encode($thousand) ?>;
1381
1382 var main_max_dec_shown = <?php echo (int) str_replace('.', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN')); ?>;
1383 var main_rounding_unit = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); ?>;
1384 var main_rounding_tot = <?php echo (int) getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); ?>;
1385
1386 var amount = amount.toString();
1387
1388 // rounding for unit price
1389 var rounding = main_rounding_unit;
1390 var pos = amount.indexOf(dec);
1391 var decpart = '';
1392 if (pos >= 0) {
1393 decpart = amount.substring(pos + 1).replace('/0+$/i', ''); // Remove 0 for decimal part
1394 }
1395 var nbdec = decpart.length;
1396 if (nbdec > rounding) {
1397 rounding = nbdec;
1398 }
1399 // If rounding higher than max shown
1400 if (rounding > main_max_dec_shown) rounding = main_max_dec_shown;
1401 if (thousand != ',' && thousand != '.') amount = amount.replace(',', '.');
1402 amount = amount.replace(' ', ''); // To avoid spaces
1403 amount = amount.replace(thousand, ''); // Replace of thousand before replace of dec to avoid pb if thousand is .
1404 amount = amount.replace(dec, '.');
1405
1406 //console.log("amount before="+amount+" rounding="+rounding)
1407 var res = Math.round10(amount, - rounding);
1408 // Other solution is
1409 // var res = dolroundjs(amount, rounding)
1410
1411 console.log("price2numjs text="+amount+" return="+res);
1412
1413 return res;
1414}
1415
1416
1417<?php
1418if (!getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && !defined('DISABLE_JQUERY_JNOTIFY')) {
1419 ?>
1420// Defined properties for JNotify
1421$(document).ready(function() {
1422 if (typeof $.jnotify == 'function') {
1423 $.jnotify.setup({
1424 delay: 3000 // the default time to show each notification (in milliseconds)
1425 , sticky: false // determines if the message should be considered "sticky" (user must manually close notification)
1426 , closeLabel: "&times;" // the HTML to use for the "Close" link
1427 , showClose: true // determines if the "Close" link should be shown if notification is also sticky
1428 , fadeSpeed: 1000 // the speed to fade messages out (in milliseconds)
1429 , slideSpeed: 250 // the speed used to slide messages out (in milliseconds)
1430 , classContainer: "jnotify-container"
1431 , classNotification: "jnotify-notification"
1432 , classBackground: "jnotify-background"
1433 , classClose: "jnotify-close"
1434 , classMessage: "jnotify-message"
1435 , init: null // callback that occurs when the main jnotify container is created
1436 , create: null // callback that occurs when when the note is created (occurs just before appearing in DOM)
1437 , beforeRemove: null // callback that occurs when before the notification starts to fade away
1438 });
1439 }
1440});
1441 <?php
1442} ?>
1443
1444
1445
1446jQuery(document).ready(function() {
1447 // Force to hide menus when page is inside an iFrame so we can show any page into a dialog popup
1448 if (window.location && window.location.pathname.indexOf("externalsite/frametop.php") == -1 && window.location !== window.parent.location ) {
1449 console.log("Page is detected to be into an iframe, we hide by CSS the menus");
1450 // The page is in an iframe
1451 jQuery(".side-nav-vert, .side-nav, .websitebar").hide();
1452 jQuery(".id-container").css('width', '100%');
1453
1454 }
1455
1456 // Code to set tooltip on search field
1457 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")) ?>');
1458});
1459
1460
1461jQuery(document).ready(function() {
1462 jQuery(document).on("click", ".butAction.dropdown-toggle", function(event) {
1463 console.log("Click on .butAction.dropdown-toggle");
1464 let parentHolder = jQuery(event.target).parent();
1465 let dropDownContent = parentHolder.children(".dropdown-content");
1466 let offset = parentHolder.offset();
1467 let widthDocument = $(document).width();
1468 let heightDocument = $(document).height();
1469 let right = widthDocument - offset.left - parentHolder.width();
1470 let widthPopup = parentHolder.children(".dropdown-content").width();
1471 if (widthPopup + right >= widthDocument) {
1472 //right = 10;
1473 }
1474
1475 parentHolder.toggleClass("open"); /* If open, it closes, if closed, it opens */
1476
1477 // Check tooltip is in viewport
1478 let dropDownContentTop = dropDownContent.offset().top;
1479 let dropDownContentLeft = dropDownContent.offset().left;
1480 let dropDownContentHeight = dropDownContent.outerHeight();
1481 let dropDownContentBottom = dropDownContentTop + dropDownContentHeight;
1482 let viewportBottom = $(window).scrollTop() + $(window).height();
1483
1484 // Change dropdown Up/Down orientation if dropdown is close to bottom viewport
1485 if(parentHolder.hasClass('open')
1486 && dropDownContentBottom > viewportBottom // Check bottom of dropdown is behind viewport
1487 && dropDownContentTop - dropDownContentHeight > 0 // check if set dropdown to --up will not go over the top of document
1488 ){
1489 parentHolder.addClass("--up");
1490 }else{
1491 parentHolder.removeClass("--up");
1492 }
1493
1494 // Change dropdown left/right offset if dropdown is close to left viewport
1495 if(parentHolder.hasClass('open') && dropDownContentLeft < 0){
1496 parentHolder.addClass("--left");
1497 }else{
1498 parentHolder.removeClass("--left");
1499 }
1500 });
1501
1502 // Close drop down
1503 jQuery(document).on("click", function(event) {
1504 // search if click was outside drop down
1505 if (!$(event.target).closest('.butAction.dropdown-toggle').length) {
1506 /* console.log("click close butAction - we click outside"); */
1507 let parentholder = jQuery(".butAction.dropdown-toggle").closest(".dropdown.open");
1508 if (parentholder){
1509 // Hide the menus.
1510 parentholder.removeClass("open --up --left");
1511 }
1512 }
1513 });
1514});
1515
1516
1517<?php
1518if (!getDolGlobalString('MAIN_DISABLE_SELECT2_FOCUS_PROTECTION') && !defined('DISABLE_SELECT2_FOCUS_PROTECTION')) {
1519 ?>
1520/*
1521 * Hacky fix for a bug in select2 with jQuery 3.6.4's new nested-focus "protection"
1522 * This fix needs to click a second time when clicking into a combo with ajax (see Test4d and Test5a in test_forms.php
1523 * see: https://github.com/select2/select2/issues/5993
1524 * see: https://github.com/jquery/jquery/issues/4382
1525 *
1526 * TODO: Recheck with the select2 GH issue and remove once this is fixed on their side
1527 */
1528$(document).on('select2:open', (e) => {
1529 console.log("Execute the focus (click on combo or use space when on component");
1530 const target = $(e.target);
1531 if (target && target.length) {
1532 let id = target[0].id || target[0].name;
1533 if (id.substr(-2) == "[]") id = id.substr(0,id.length-2);
1534 document.querySelector('input[aria-controls*='+id+']').focus();
1535 }
1536});
1537 <?php
1538}
1539?>
1540
1541
1542// End of lib_head.js.php
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
ui state ui widget content ui state ui widget header ui state a ui button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
getOperatorsForFieldType(type)
Get the list of operators for a given field type.
copyToClipboard(text, text2)
Function to output a dialog box for copy/paste.
document_preview(file, type, title)
Function show document preview.
pricejs(amount, mode='MT', currency_code='', force_locale='')
Function similar to PHP price()
generateFilterString(column, operator, context, fieldType)
Generate a filter string based on the given column, operator, context and field type.
newpopup(url, title)
Show a popup HTML page.
price2numjs(amount)
Function similar to PHP price2num()
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:149
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:152
fail($message)
Abort invoice creation with a given error message.
Definition invoice.php:101