typo fix : list_price instead of listprice
[koha.git] / koha-tmpl / intranet-tmpl / prog / en / js / acq.js
1 //=======================================================================
2 //input validation:
3 // acqui/uncertainprice.tmpl uses this
4 function uncheckbox(form, field) {
5     var price = new Number(form.elements['price' + field].value);
6     var tmpprice = "";
7     var errmsg = "ERROR: Price is not a valid number, please check the price and try again!"
8     if (isNaN(price)) {
9         alert(errmsg);
10         for(var i=0; i<form.elements['price' + field].value.length; ++i) {
11             price = new Number(form.elements['price' + field].value[i]);
12             if(! isNaN(price) || form.elements['price' + field].value[i] == ".") {
13                 tmpprice += form.elements['price' + field].value[i];
14             }
15         }
16         form.elements['price' + field].value = tmpprice;
17         return false;
18     }
19     form.elements['uncertainprice' + field].checked = false;
20     return true;
21 }
22
23 // returns false if value is empty
24 function isNotNull(f,noalert) {
25     if (f.value.length ==0) {
26         return false;
27     }
28     return true;
29 }
30
31 function isNull(f,noalert) {
32     if (f.value.length > 0) {
33         return false;
34     }
35     return true;
36 }
37
38
39
40
41
42
43
44 //Function returns false if v is not a number (if maybenull is 0, it also returns an error if the number is 0)
45 function isNum(v,maybenull) {
46     var n = new Number(v.value);
47     if (isNaN(n)) {
48         return false;
49     }
50     if (maybenull==0 && v.value=='') {
51
52
53     return false;
54     }
55     return true;
56 }
57
58 // this function checks if date is like DD/MM/YYYY
59 function CheckDate(field) {
60     var d = field.value;
61     if (d!="") {
62         var amin = 1900;
63         var amax = 2100;
64         var date = d.split("/");
65         var ok=1;
66         var msg;
67         if ( (date.length < 2) && (ok==1) ) {
68             msg = _("Separator must be /");
69                 alert(msg); ok=0; field.focus();
70                 return false;
71         }
72         var dd   = date[0];
73         var mm   = date[1];
74         var yyyy = date[2];
75         // checking days
76         if ( ((isNaN(dd))||(dd<1)||(dd>31)) && (ok==1) ) {
77             msg = _("day not correct.");
78             alert(msg); ok=0; field.focus();
79             return false;
80         }
81         // checking months
82         if ( ((isNaN(mm))||(mm<1)||(mm>12)) && (ok==1) ) {
83             msg = _("month not correct.");
84             alert(msg); ok=0; field.focus();
85             return false;
86         }
87         // checking years
88         if ( ((isNaN(yyyy))||(yyyy<amin)||(yyyy>amax)) && (ok==1) ) {
89             msg = _("years not correct.");
90             alert(msg); ok=0; field.focus();
91             return false;
92         }
93         // check day/month combination
94         if ((mm==4 || mm==6 || mm==9 || mm==11) && dd==31) {
95             msg = _("Invalid Day/Month combination. Please ensure that    you have a valid day/month combination.");
96             alert(msg); ok=0; field.focus();
97             return false;
98         }
99         // check for february 29th
100         if (mm == 2) {
101             var isleap = (yyyy % 4 == 0 && (yyyy % 100 != 0 || yyyy %    400 == 0));
102             if (dd>29 || (dd==29 && !isleap)) {
103                 msg = _("Invalid Day. This year is not a leap year.       Please enter a value less than 29 for the day.");
104                 alert(msg); ok=0; field.focus();
105                 return false
106             }
107         }
108     }
109     return true;
110 }
111
112 // Checks wether start date is greater than end date
113 function CompareDate(startdate, enddate) {
114     startdate=startdate.split("/");
115     syear = startdate[2];
116     smonth = startdate[1];
117     sday = startdate[0];
118     enddate=enddate.split("/");
119     eyear = enddate[2];
120     emonth = enddate[1];
121     eday = enddate[0];
122
123     var sdate = new Date(syear,smonth-1,sday);
124     var edate = new Date(eyear,emonth-1,eday);
125     if (sdate > edate) {
126         msg = _("Start date after end date, please check the dates!");
127         alert(msg); ok=0; field.focus();
128         return false;
129     }
130     return true;
131 }
132
133 // checks wether end date is before today, returns false if it is
134 function CheckEndDate(enddate) {
135     enddate=enddate.split("/");
136     eyear = enddate[2];
137     emonth = enddate[1];
138     eday = enddate[0];
139     var edate = new Date(eyear,emonth-1,eday);
140     var today = new Date( );
141     if (today > edate) {
142         msg = _("End date before today, Invalid end date!");
143         alert(msg); ok=0; field.focus();
144         return false;
145     }
146     return true;
147 }
148
149
150
151 //=======================================================================
152
153 //=======================================================================
154 // Functions for drag-and-drop functionality
155
156
157 (function() {
158
159 var Dom = YAHOO.util.Dom;
160 var Event = YAHOO.util.Event;
161 var DDM = YAHOO.util.DragDropMgr;
162
163 DDApp = {
164     init: function() {
165     var uls = document.getElementsByTagName('ul');
166     var i,j;
167     var ddtarget;
168     for (i=0; i<uls.length;i=i+1) {
169         if (uls[i].className == "draglist" || uls[i].className == "draglist_alt") {
170             ddtarget = YAHOO.util.DragDropMgr.getDDById(uls[i].id);
171 // The yahoo drag and drop is written (broken or not) in such a way, that if an element is subscribed as a target multiple times,
172 // it has to be unlinked multiple times, so we need to test wether it is allready a target, otherwise we'll have a problem when closing the group
173             if( ! ddtarget ) {
174                 new YAHOO.util.DDTarget(uls[i].id);
175             }
176             var children = uls[i].getElementsByTagName('li');
177             for( j=0; j<children.length; j=j+1) {
178 // The yahoo drag and drop is (broken or not) in such a way, that if an element is subscribed as a target multiple times,
179 // it has to be unlinked multiple times, so we need to test wether it is allready a target, otherwise we'll have a problem when closing the group
180                 ddtarget = YAHOO.util.DragDropMgr.getDDById(children[j].id);
181                 if( ! ddtarget ) {
182                     new DDList(children[j].id);
183                 }
184             }
185         }
186     }
187     }
188 };
189
190
191 // drag and drop implementation
192
193 DDList = function(id, sGroup, config) {
194
195     DDList.superclass.constructor.call(this, id, sGroup, config);
196
197     this.logger = this.logger || YAHOO;
198     var el = this.getDragEl();
199     Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent
200
201     this.goingUp = false;
202     this.lastY = 0;
203 };
204
205 YAHOO.extend(DDList, YAHOO.util.DDProxy, {
206
207     startDrag: function(x, y) {
208         this.logger.log(this.id + " startDrag");
209
210         // make the proxy look like the source element
211         var dragEl = this.getDragEl();
212         var clickEl = this.getEl();
213         Dom.setStyle(clickEl, "visibility", "hidden");
214
215         dragEl.innerHTML = clickEl.innerHTML;
216
217         Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
218         Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
219         Dom.setStyle(dragEl, "border", "2px solid gray");
220     },
221
222     endDrag: function(e) {
223
224         var srcEl = this.getEl();
225         var proxy = this.getDragEl();
226
227         // Show the proxy element and animate it to the src element's location
228         Dom.setStyle(proxy, "visibility", "");
229         var a = new YAHOO.util.Motion(
230             proxy, {
231                 points: {
232                     to: Dom.getXY(srcEl)
233                 }
234             },
235             0.2,
236             YAHOO.util.Easing.easeOut
237         )
238         var proxyid = proxy.id;
239         var thisid = this.id;
240
241         // Hide the proxy and show the source element when finished with the animation
242         a.onComplete.subscribe(function() {
243                 Dom.setStyle(proxyid, "visibility", "hidden");
244                 Dom.setStyle(thisid, "visibility", "");
245             });
246         a.animate();
247 // if we are in basketgrouping page, when finished moving, edit the basket's info to reflect new status
248         if(typeof(basketgroups) != 'undefined') {
249             a.onComplete.subscribe(function() {
250                 var reg = new RegExp("[-]+", "g");
251 // add a changed input to each moved basket, so we know which baskets to modify,
252 // and so we don't need to modify each and every basket and basketgroup each time the page is loaded
253 // FIXME: we shouldn't use getElementsByTagName, it's not explicit enough :-(
254                 srcEl.getElementsByTagName('input')[1].value = "1";
255                 if ( srcEl.parentNode.parentNode.className == "workarea" ) {
256                     var dstbgroupid = srcEl.parentNode.parentNode.getElementsByTagName('input')[srcEl.parentNode.parentNode.getElementsByTagName('input').length-2].name.split(reg)[1];
257                     srcEl.className="grouped";
258                     srcEl.getElementsByTagName('input')[0].value = dstbgroupid;
259 //FIXME: again, we shouldn't be using getElementsByTagName!!
260                     srcEl.parentNode.parentNode.getElementsByTagName('input')[srcEl.parentNode.parentNode.getElementsByTagName('input').length-1].value = 1;
261                 }
262                 else if ( srcEl.parentNode.parentNode.className == "workarea_alt" ){
263                         srcEl.className="ungrouped";
264                         srcEl.getElementsByTagName('input')[0].value = "0";
265                 }
266             });
267         }
268     },
269
270     onDragDrop: function(e, id) {
271
272         // If there is one drop interaction, the li was dropped either on the list,
273         // or it was dropped on the current location of the source element.
274         if (DDM.interactionInfo.drop.length === 1) {
275
276             // The position of the cursor at the time of the drop (YAHOO.util.Point)
277             var pt = DDM.interactionInfo.point;
278
279             // The region occupied by the source element at the time of the drop
280             var region = DDM.interactionInfo.sourceRegion;
281
282             // Check to see if we are over the source element's location.  We will
283             // append to the bottom of the list once we are sure it was a drop in
284             // the negative space (the area of the list without any list items)
285             if (!region.intersect(pt)) {
286                 var destEl = Dom.get(id);
287                 var destDD = DDM.getDDById(id);
288                 destEl.appendChild(this.getEl());
289                 destDD.isEmpty = false;
290                 DDM.refreshCache();
291             }
292         }
293     },
294
295     onDrag: function(e) {
296
297         // Keep track of the direction of the drag for use during onDragOver
298         var y = Event.getPageY(e);
299
300         if (y < this.lastY) {
301             this.goingUp = true;
302         } else if (y > this.lastY) {
303             this.goingUp = false;
304         }
305         this.lastY = y;
306     },
307
308     onDragOver: function(e, id) {
309
310         var srcEl = this.getEl();
311         var destEl = Dom.get(id);
312
313         // We are only concerned with list items, we ignore the dragover
314         // notifications for the list.
315         if (destEl.nodeName.toLowerCase() == "li") {
316             var orig_p = srcEl.parentNode;
317             var p = destEl.parentNode;
318
319             if (this.goingUp) {
320                 p.insertBefore(srcEl, destEl); // insert above
321             } else {
322                 p.insertBefore(srcEl, destEl.nextSibling); // insert below
323             }
324
325             DDM.refreshCache();
326         }
327     }
328 });
329 })();
330
331
332
333
334 //creates new group, parameter is the group's name
335 function newGroup(event, name) {
336     if (name == ''){
337         return 0;
338     }
339     if (!enterpressed(event) && event != "button"){
340         return false;
341     }
342     var pardiv = document.getElementById('groups');
343     var newdiv = document.createElement('div');
344     var newh3 = document.createElement('h3');
345     var newul = document.createElement('ul');
346     var newclose = document.createElement('a');
347     var newrename = document.createElement('a');
348     var newbasketgroupname = document.createElement('input');
349     var nbgclosed = document.createElement('input');
350     var newp = document.createElement('p');
351     var reg=new RegExp("[-]+", "g");
352     var i = 0;
353     var maxid = 0;
354     while( i < pardiv.getElementsByTagName('input').length ){
355         if (! isNaN(parseInt(pardiv.getElementsByTagName('input')[i].name.split(reg)[1])) && parseInt(pardiv.getElementsByTagName('input')[i].name.split(reg)[1]) > maxid){
356             maxid = parseInt(pardiv.getElementsByTagName('input')[i].name.split(reg)[1]);
357         }
358         ++i;
359     }
360 // var bgid = parseInt(pardiv.getElementsByTagName('input')[pardiv.getElementsByTagName('input').length-2].name.split(reg)[1]) + 1;
361     var bgid = maxid + 1;
362     var newchanged = document.createElement('input');
363
364     newul.id="bg-"+bgid;
365     newul.className='draglist';
366
367     newh3.innerHTML=name;
368 //    newh3.style.display="inline";
369
370     newclose.innerHTML="close";
371     newclose.href="javascript: closebasketgroup('"+bgid+"', 'bg-"+bgid+"');";
372
373     newrename.href="javascript:" + "renameinit("+bgid+");";
374     newrename.innerHTML="rename";
375
376 //    newp.style.display="inline";
377     newp.innerHTML=" [ ";
378     newp.appendChild(newrename);
379     newp.innerHTML+=" / ";
380     newp.appendChild(newclose);
381     newp.innerHTML+=" ]";
382
383     newbasketgroupname.type="hidden";
384     newbasketgroupname.name="basketgroup-" + bgid + "-name";
385     newbasketgroupname.id = "basketgroup-" + bgid + "-name";
386     newbasketgroupname.value=name;
387
388     nbgclosed.type="hidden";
389     nbgclosed.name="basketgroup-" + bgid + "-closed";
390     nbgclosed.value="0";
391     nbgclosed.id=nbgclosed.name;
392
393     newchanged.type="hidden";
394     newchanged.id="basketgroup-"+bgid+"-changed";
395     newchanged.name=newchanged.id;
396     newchanged.value="1";
397
398     newdiv.style.backgroundColor='red';
399     newdiv.appendChild(newh3);
400     newdiv.appendChild(newp);
401     newdiv.appendChild(newul);
402     newdiv.appendChild(newbasketgroupname);
403     newdiv.appendChild(nbgclosed);
404     newdiv.appendChild(newchanged);
405     newdiv.className='workarea';
406     pardiv.appendChild(newdiv);
407
408     YAHOO.util.Event.onDOMReady(DDApp.init, DDApp, true);
409 }
410
411 //this traps enters in input fields
412 function enterpressed(event){
413     var keycode;
414     if (window.event) keycode = window.event.keyCode;
415     else if (event) keycode = event.which;
416     else return false;
417
418     if (keycode == 13)
419     {
420         return true;
421     }
422     else return false;
423 }
424
425
426
427
428
429 //Closes a basketgroup
430 function closebasketgroup(bgid) {
431     var answer=confirm(_("Are you sure you want to close this basketgroup?"));
432     if(! answer){
433         return;
434     }
435     ulid = 'bg-'+bgid;
436     var i = 0;
437     tagname='basketgroup-'+bgid+'-closed';
438     var ddtarget;
439     var closeinput = document.getElementById(tagname);
440     closeinput.value = 1;
441     var changed = document.getElementById("basketgroup-"+bgid+"-changed");
442     changed.value=1;
443
444     var div = document.getElementById(tagname).parentNode;
445     var stufftoremove = div.getElementsByTagName('p')[0];
446     var ul = document.getElementById(ulid);
447     var lis = ul.getElementsByTagName('li');
448     if (lis.length == 0 ) {
449         alert(_("Why close an empty basket?"));
450         return;
451     }
452     var cantprint = document.createElement('p');
453
454     div.className = "closed";
455     ul.className="closed";
456
457     for(i=0; i<lis.length; ++i) {
458         ddtarget = YAHOO.util.DragDropMgr.getDDById(lis[i].id);
459         ddtarget.unreg();
460     }
461     ddtarget = YAHOO.util.DragDropMgr.getDDById(ul.id);
462     ddtarget.unreg();
463     div.removeChild(stufftoremove);
464 // the print button is disabled because the page's content might (or is probably) not in sync with what the database contains
465     cantprint.innerHTML=_("You need to save the page before printing");
466     cantprint.id = 'cantprint-' + bgid;
467     var unclosegroup = document.createElement('a');
468     unclosegroup.href='javascript:unclosegroup('+bgid+');';
469     unclosegroup.innerHTML=_("reopen basketgroup");
470     unclosegroup.id = 'unclose-' + bgid;
471
472     div.appendChild(cantprint);
473     div.appendChild(unclosegroup);
474 }
475
476 function closeandprint(bg){
477         if(document.location = '/cgi-bin/koha/acqui/basketgroup.pl?op=closeandprint&amp;basketgroupid=' + bg ){
478                 setTimeout("window.location.reload();",3000);
479         }else{
480                 alert('Error downloading the file');
481         }
482 }
483
484 //function that lets the user unclose a basketgroup as long as he hasn't submitted the changes to the page.
485 function unclosegroup(bgid){
486     var div = document.getElementById('basketgroup-'+bgid+'-closed').parentNode;
487     var divtodel = document.getElementById('unclose-' + bgid);
488     if (divtodel){
489         div.removeChild(divtodel);
490     }
491     divtodel = document.getElementById('unclose-' + bgid);
492     if (divtodel){
493         div.removeChild(divtodel);
494     }
495     var closeinput = document.getElementById('basketgroup-'+bgid+'-closed');
496     var ul = document.getElementById('bg-'+bgid);
497
498     var newclose = document.createElement('a');
499     var newrename = document.createElement('a');
500     var newp = document.createElement('p');
501
502     newclose.innerHTML="close";
503     newclose.href="javascript: closebasketgroup('"+bgid+"', 'bg-"+bgid+"');";
504
505     newrename.href="javascript:" + "renameinit("+bgid+");";
506     newrename.innerHTML="rename";
507     
508     var todel = div.getElementsByTagName('p')[0];
509     div.removeChild(todel);
510     
511     var changed = document.getElementById("basketgroup-"+bgid+"-changed");
512     changed.value=1;
513
514     newp.innerHTML=" [ ";
515     newp.appendChild(newrename);
516     newp.innerHTML+=" / ";
517     newp.appendChild(newclose);
518     newp.innerHTML+=" ]";
519
520     div.insertBefore(newp, ul);
521     closeinput.value="0";
522     div.className = "workarea";
523     ul.className="draglist";
524
525 //rescan draglists, we have a new target (again :-)
526     YAHOO.util.Event.onDOMReady(DDApp.init, DDApp, true);
527 }
528
529 //a function to filter basketgroups using a regex (javascript regex)
530 function filterGroups(event, searchstring ){
531     if (!enterpressed(event) && event != "button"){
532         return false;
533     }
534     var reg = new RegExp(searchstring, "g");
535     var Dom = YAHOO.util.Dom;
536     var divs = Dom.getElementsByClassName("workarea", "div");
537
538     for (var i = 0; i < divs.length; ++i){
539         if (! reg.exec(divs[i].innerHTML)){
540             divs[i].style.display='none';
541         }
542         else {
543             divs[i].style.display='';
544         }
545     }
546     divs = Dom.getElementsByClassName("closed", "div");
547     for (var i = 0; i < divs.length; ++i){
548         if (! reg.exec(divs[i].innerHTML)){
549             divs[i].style.display='none';
550         }
551         else {
552             divs[i].style.display='';
553         }
554     }
555 }
556
557 //function to hide (or show) closed baskets (if show is true, it shows all the closed baskets)
558 function showhideclosegroups(show){
559     var Dom = YAHOO.util.Dom;
560     var divs = Dom.getElementsByClassName("closed", "div");
561     var display;
562     if (show){
563         display = '';
564     }
565     else display = 'none';
566     for(var i = 0; i < divs.length; ++i){
567         divs[i].style.display=display;
568     }
569 }
570
571 function renameinit(bgid){
572     var ul = document.getElementById('bg-'+bgid);
573     var div = ul.parentNode;
574     var nameelm = div.getElementsByTagName('h3')[0];
575     var p = div.getElementsByTagName('p')[0];
576
577
578     var nameinput = document.createElement("input");
579     nameinput.type = "text";
580     nameinput.id="rename-"+bgid;
581     nameinput.value = nameelm.innerHTML;
582     nameinput.onkeypress = function(e){rename(e, bgid, document.getElementById('rename-'+bgid).value); };
583 //    nameinput.setAttribute('onkeypress', 'rename(event, bgid, document.getElementById(rename-'+bgid+').value);');
584
585     div.removeChild(nameelm);
586     div.insertBefore(nameinput, p);
587 }
588
589 function rename(event, bgid, name){
590     if (!enterpressed(event)){
591         return false;
592     }
593     var ul = document.getElementById('bg-'+bgid);
594     var div = ul.parentNode;
595     var p = div.getElementsByTagName('p')[0];
596     var nameinput = document.getElementById("rename-"+bgid);
597     var changedinput = document.getElementById("basketgroup-"+bgid+"-changed");
598     var newh3 = document.createElement("h3");
599     var hiddenname = document.getElementById("basketgroup-"+bgid+"-name");
600
601     div.removeChild(nameinput);
602
603     newh3.innerHTML=name;
604     hiddenname.value=name;
605     changedinput.value = 1;
606     div.insertBefore(newh3, p);
607 }
608
609 //=======================================================================
610 //a logging function (a bit buggy, might open millions of log pages when initializing, but works fine after...
611 function log(message) {
612     if (!log.window_ || log.window_.closed) {
613         var win = window.open("", null, "width=400,height=200," +
614                             "scrollbars=yes,resizable=yes,status=no," +
615                             "location=no,menubar=no,toolbar=no");
616         if (!win) return;
617         var doc = win.document;
618         doc.write("<html><head><title>Debug Log</title></head>" +
619                 "<body></body></html>");
620         doc.close();
621         log.window_ = win;
622     }
623     var logLine = log.window_.document.createElement("div");
624     logLine.appendChild(log.window_.document.createTextNode(message));
625     log.window_.document.body.appendChild(logLine);
626 }
627 //=======================================================================
628
629
630
631     function ownerPopup(f) {
632     window.open("/cgi-bin/koha/admin/aqbudget_owner_search.pl?op=budget",'PatronPopup','width=740,height=450,location=yes,toolbar=no,scrollbars=yes,resize=yes');
633     }
634         //
635 //=======================================================================
636 function getElementsByClass( searchClass, domNode, tagName) {
637     if (domNode == null) domNode = document;
638     if (tagName == null) tagName = '*';
639     var el = new Array();
640     var tags = domNode.getElementsByTagName(tagName);
641     var tcl = " "+searchClass+" ";
642     for(i=0,j=0; i<tags.length; i++) {
643         var test = " " + tags[i].className + " ";
644         if (test.indexOf(tcl) != -1)
645             el[j++] = tags[i];
646     }
647     return el;
648 }
649
650
651 function calcTotalRow(cell) {
652
653     var bud_id =  cell.className;
654     var val1 =    cell.value;
655     var remainingTotal =   document.getElementById("budget_est_"+bud_id) ;
656     var remainingNew =0;
657     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
658     var arr =  getElementsByClass(bud_id);
659
660     budgetTotal   =  budgetTotal.replace(/\,/, "");
661
662 //percent strip and convert
663     if ( val1.match(/\%/) )   {
664         val1 = val1.replace(/\%/, "");
665         cell.value =    (val1 / 100) *  Math.abs(budgetTotal ) ;
666     }
667
668     for ( var i=0, len=arr.length; i<len; ++i ){
669         remainingNew   +=   Math.abs(arr[i].value);
670     }
671
672     var cc = new Number(cell.value);
673     cell.value =  cc.toFixed(2); // TIDYME...
674     remainingNew    =    Math.abs( budgetTotal  ) -  remainingNew   ;
675
676     if ( remainingNew  == 0)  {
677         remainingTotal.style.color = 'black';
678     }
679     else if ( remainingNew   > 0   )       {
680         remainingTotal.style.color = 'green';
681     } else  {    // if its negative, make it red..
682         remainingTotal.style.color = 'red';
683     }
684
685     remainingTotal.textContent  = remainingNew.toFixed(2) ;
686 }
687
688 function autoFillRow(bud_id) {
689
690     var remainingTotal =   document.getElementById("budget_est_"+bud_id) ;
691     var remainingNew = new Number;
692     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
693     var arr =  getElementsByClass(bud_id);
694
695     budgetTotal   =  budgetTotal.replace(/\,/, "");
696     var qty = new Number;
697 // get the totals
698     for ( var i=0, len=arr.length; i<len; ++i ) {
699         remainingNew   +=   Math.abs (arr[i].value );
700
701         if ( arr[i].value == 0 ) {
702             qty += 1;
703         }
704     }
705
706     remainingNew    =    Math.abs( budgetTotal) -  remainingNew   ;
707     var newCell = new Number (remainingNew / qty);
708
709     for ( var i=0, len=arr.length; i<len; ++i ) {
710         if (  Math.abs(arr[i].value) == 0 ) {
711             arr[i].value = newCell.toFixed(2) ;
712         }
713     }
714
715     remainingTotal.textContent = '0.00' ;
716     remainingTotal.style.color = 'black';
717 }
718
719
720 function messenger(X,Y,etc){    // FIXME: unused?
721     win=window.open("","mess","height="+X+",width="+Y+",screenX=150,screenY=0");
722     win.focus();
723     win.document.close();
724     win.document.write("<body link='#333333' bgcolor='#ffffff' text='#000000'><font size='2'><p><br />");
725     win.document.write(etc);
726     win.document.write("<center><form><input type=button onclick='self.close()' value='Close'></form></center>");
727     win.document.write("</font></body></html>");
728 }
729
730
731 //=======================================================================
732
733 //  NEXT BLOCK IS USED BY NEWORDERBEMPTY
734
735 function calcNeworderTotal(){
736     //collect values
737     var f        = document.getElementById('Aform');
738     var quantity = new Number(f.quantity.value);
739     var discount = new Number(f.discount.value);
740     var listinc  = new Number (f.listinc.value);
741     var currency = f.currency.value;
742     var applygst = new Number (f.applygst.value);
743     var listprice   =  new Number(f.listprice.value);
744     var invoiceingst =  new Number (f.invoiceincgst.value);
745     var exchangerate =  new Number(f.elements[currency].value);      //get exchange rate
746     var gst_on=(!listinc && invoiceingst);
747
748     //do real stuff
749     var rrp   = new Number(listprice*exchangerate);
750     var ecost = new Number(rrp * (100 - discount ) / 100);
751     var GST   = new Number(0);
752     if (gst_on) {
753             rrp=rrp * (1+f.gstrate.value / 100);
754         GST=ecost * f.gstrate.value / 100;
755     }
756
757     var total =  new Number( (ecost + GST) * quantity);
758
759     f.rrp.value = rrp.toFixed(2);
760
761 //      f.rrp.value = rrp
762 //      f.rrp.value = 'moo'
763
764     f.ecost.value = ecost.toFixed(2);
765     f.total.value = total.toFixed(2);
766     f.listprice.value =  listprice.toFixed(2);
767
768 //  gst-stuff needs verifing, mason.
769     if (f.GST) {
770         f.GST.value=GST;
771     }
772     return true;
773 }
774
775 // ----------------------------------------
776 //USED BY NEWORDEREMPTY.PL
777 /*
778 function fetchSortDropbox(f) {
779     var  budgetId=f.budget_id.value;
780     var handleSuccess = function(o){
781         if(o.responseText !== undefined){
782             sort_dropbox.innerHTML   = o.responseText;
783         }
784     }
785
786     var callback = {   success:handleSuccess };
787     var sUrl = '../acqui/fetch_sort_dropbox.pl?sort=1&budget_id='+budgetId
788     var sort_dropbox = document.getElementById('sort1');
789     var request1 = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
790     var rr = '00';
791
792 // FIXME: ---------  twice , coz the 2 requests get mixed up otherwise
793
794     var handleSuccess2 = function(o){
795     if(o.responseText !== undefined){
796         sort2_dropbox.innerHTML   = o.responseText;
797         }
798     }
799
800     var callback2 = {   success:handleSuccess };
801     var sUrl2 = '../acqui/fetch_sort_dropbox.pl?sort=2&budget_id='+budgetId;
802     var sort2_dropbox = document.getElementById('sort2');
803     var request2 = YAHOO.util.Connect.asyncRequest('GET', sUrl2, callback2);
804
805 }
806 */
807
808
809
810 //USED BY NEWORDEREMPTY.PL
811 function fetchSortDropbox(f) {
812     var  budgetId=f.budget_id.value;
813
814 for (i=1;i<=2;i++) {
815
816     var sort_dropbox = document.getElementById('sort'+i);
817     var url = '../acqui/fetch_sort_dropbox.pl?sort='+i+'&budget_id='+budgetId;
818
819     var xmlhttp = null;
820     xmlhttp = new XMLHttpRequest();
821     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
822         xmlhttp.overrideMimeType('text/xml');
823     }
824
825     xmlhttp.open('GET', url, false);
826     xmlhttp.send(null);
827
828     xmlhttp.onreadystatechange = function() {
829         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
830     // stupid JS...
831         } else {
832     // wait for the call to complete
833         }
834     };
835     // rc =  eval ( xmlhttp.responseText );
836     sort_dropbox.innerHTML  =  xmlhttp.responseText;
837 }
838 }
839
840
841
842
843
844
845
846 //USED BY NEWORDEREMPTY.PL
847 function totalExceedsBudget(budgetId, total) {
848
849     var xmlhttp = null;
850     xmlhttp = new XMLHttpRequest();
851     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
852         xmlhttp.overrideMimeType('text/xml');
853     }
854
855     var url = '../acqui/check_budget_total.pl?budget_id=' + budgetId + "&total=" + total;
856     xmlhttp.open('GET', url, false);
857     xmlhttp.send(null);
858
859     xmlhttp.onreadystatechange = function() {
860         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
861
862             actTotal = eval ( xmlhttp.responseText );
863
864             if (  Math.abs(actTotal) < Math.abs(total)  ) {
865             // if budget is to low :(
866                 return true ;
867             } else {
868                 return false;
869             }
870         }
871     }
872 }
873
874
875 //USED BY AQBUDGETS.TMPL
876 function budgetExceedsParent(budgetTotal, budgetId, newBudgetParent, periodID) {
877
878
879     var xmlhttp = null;
880     xmlhttp = new XMLHttpRequest();
881     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
882         xmlhttp.overrideMimeType('text/xml');
883     }
884
885 // make the call... yawn
886 //    var url = '../admin/check_parent_total.pl?budget_id=' + budgetId +   '&parent_id=' + newBudgetParent  + "&total=" + budgetTotal + "&period_id="+ periodID   ;
887
888
889     var url = '../admin/check_parent_total.pl?total=' + budgetTotal + "&period_id="+ periodID   ;
890
891 if (budgetId ) { url +=  '&budget_id=' + budgetId };
892 if ( newBudgetParent  ) { url +=  '&parent_id=' + newBudgetParent};
893
894
895     xmlhttp.open('GET', url, false);
896     xmlhttp.send(null);
897
898     xmlhttp.onreadystatechange = function() {
899         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
900     // stupid JS...
901         } else {
902     // wait for the call to complete
903         }
904     };
905
906     var result = eval ( xmlhttp.responseText );
907
908     if (result == '1') {
909             return _("- Budget total exceeds parent allocation\n");
910     } else if (result == '2') {
911             return _("- Budget total exceeds period allocation\n");
912     } else  {
913             return false;
914     }
915 }
916
917
918
919
920 //USED BY AQBUDGETS.TMPL
921 function checkBudgetParent(budgetId, newBudgetParent) {
922     var xmlhttp = null;
923     xmlhttp = new XMLHttpRequest();
924     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
925         xmlhttp.overrideMimeType('text/xml');
926     }
927
928     var url = '../admin/check_budget_parent.pl?budget_id=' + budgetId + '&new_parent=' + newBudgetParent;
929     xmlhttp.open('GET', url, false);
930     xmlhttp.send(null);
931
932     xmlhttp.onreadystatechange = function() {
933         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
934     // do something with the results
935         } else {
936     // wait for the call to complete
937         }
938     };
939
940     var result = eval ( xmlhttp.responseText );
941
942     if (result == '1') {
943             return _("- New budget-parent is beneath budget\n");
944 //     } else if (result == '2') {
945 //            return "- New budget-parent has insufficent funds\n";
946 //     } else  {
947 //              return false;
948     }
949 }
950
951
952 function addColumn(p_sType, p_aArgs, p_oValue)
953 {
954     var allRows = document.getElementById('plan').rows;
955     var colnum  = p_oValue[0];
956     var code   = p_oValue[1];
957     var colnum  = new Number(colnum);
958
959     for (var i=0; i<allRows.length; i++) {
960             var allCells  = allRows[i].cells;
961             allCells[colnum+1].style.display="table-cell";
962     }
963
964 // make a menuitem object
965     var hids = document.getElementsByName("hide_cols")
966     for (var i=0; i<hids.length; i++) {
967         if (hids[i].value == code) {
968             var x =  hids[i];
969             x.parentNode.removeChild(x)    // sigh...
970             break;
971         }
972     }
973 }
974
975
976 function delColumn(n, code)
977 {
978     var allRows = document.getElementById('plan').rows;
979
980 // find index
981     var index;
982     var nn  = new Number(n);
983     var code   = code ;
984     for (var i=0; i<allRows.length; i++) {
985         var allCells  = allRows[i].cells;
986         allCells[nn+1].style.display="none";
987     }
988
989     var r = 0;
990     var hids = document.getElementsByName("hide_cols")
991     for (var i=0; i<hids.length; i++) {
992         if (hids[i].value == code) {
993             r = 1;
994             break;
995         }
996     }
997
998     if (r == 0 ) {
999         // add hide_col to form
1000         var el = document.createElement("input");
1001         el.setAttribute("type", 'hidden' );
1002         el.setAttribute("value", code);
1003         el.setAttribute("name", 'hide_cols');
1004         document.getElementById("hide_div").appendChild(el);
1005     }
1006 }
1007
1008