lib_head.js.php 36 KB

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