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