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