fix for #3620: basket management
[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 that lets the user unclose a basketgroup as long as he hasn't submitted the changes to the page.
477 function unclosegroup(bgid){
478     var div = document.getElementById('basketgroup-'+bgid+'-closed').parentNode;
479     var divtodel = document.getElementById('unclose-' + bgid);
480     if (divtodel){
481         div.removeChild(divtodel);
482     }
483     divtodel = document.getElementById('unclose-' + bgid);
484     if (divtodel){
485         div.removeChild(divtodel);
486     }
487     var closeinput = document.getElementById('basketgroup-'+bgid+'-closed');
488     var ul = document.getElementById('bg-'+bgid);
489
490     var newclose = document.createElement('a');
491     var newrename = document.createElement('a');
492     var newp = document.createElement('p');
493
494     newclose.innerHTML="close";
495     newclose.href="javascript: closebasketgroup('"+bgid+"', 'bg-"+bgid+"');";
496
497     newrename.href="javascript:" + "renameinit("+bgid+");";
498     newrename.innerHTML="rename";
499     
500     var todel = div.getElementsByTagName('p')[0];
501     div.removeChild(todel);
502     
503     var changed = document.getElementById("basketgroup-"+bgid+"-changed");
504     changed.value=1;
505
506     newp.innerHTML=" [ ";
507     newp.appendChild(newrename);
508     newp.innerHTML+=" / ";
509     newp.appendChild(newclose);
510     newp.innerHTML+=" ]";
511
512     div.insertBefore(newp, ul);
513     closeinput.value="0";
514     div.className = "workarea";
515     ul.className="draglist";
516
517 //rescan draglists, we have a new target (again :-)
518     YAHOO.util.Event.onDOMReady(DDApp.init, DDApp, true);
519 }
520
521 //a function to filter basketgroups using a regex (javascript regex)
522 function filterGroups(event, searchstring ){
523     if (!enterpressed(event) && event != "button"){
524         return false;
525     }
526     var reg = new RegExp(searchstring, "g");
527     var Dom = YAHOO.util.Dom;
528     var divs = Dom.getElementsByClassName("workarea", "div");
529
530     for (var i = 0; i < divs.length; ++i){
531         if (! reg.exec(divs[i].innerHTML)){
532             divs[i].style.display='none';
533         }
534         else {
535             divs[i].style.display='';
536         }
537     }
538     divs = Dom.getElementsByClassName("closed", "div");
539     for (var i = 0; i < divs.length; ++i){
540         if (! reg.exec(divs[i].innerHTML)){
541             divs[i].style.display='none';
542         }
543         else {
544             divs[i].style.display='';
545         }
546     }
547 }
548
549 //function to hide (or show) closed baskets (if show is true, it shows all the closed baskets)
550 function showhideclosegroups(show){
551     var Dom = YAHOO.util.Dom;
552     var divs = Dom.getElementsByClassName("closed", "div");
553     var display;
554     if (show){
555         display = '';
556     }
557     else display = 'none';
558     for(var i = 0; i < divs.length; ++i){
559         divs[i].style.display=display;
560     }
561 }
562
563 function renameinit(bgid){
564     var ul = document.getElementById('bg-'+bgid);
565     var div = ul.parentNode;
566     var nameelm = div.getElementsByTagName('h3')[0];
567     var p = div.getElementsByTagName('p')[0];
568
569
570     var nameinput = document.createElement("input");
571     nameinput.type = "text";
572     nameinput.id="rename-"+bgid;
573     nameinput.value = nameelm.innerHTML;
574     nameinput.onkeypress = function(e){rename(e, bgid, document.getElementById('rename-'+bgid).value); };
575 //    nameinput.setAttribute('onkeypress', 'rename(event, bgid, document.getElementById(rename-'+bgid+').value);');
576
577     div.removeChild(nameelm);
578     div.insertBefore(nameinput, p);
579 }
580
581 function rename(event, bgid, name){
582     if (!enterpressed(event)){
583         return false;
584     }
585     var ul = document.getElementById('bg-'+bgid);
586     var div = ul.parentNode;
587     var p = div.getElementsByTagName('p')[0];
588     var nameinput = document.getElementById("rename-"+bgid);
589     var changedinput = document.getElementById("basketgroup-"+bgid+"-changed");
590     var newh3 = document.createElement("h3");
591     var hiddenname = document.getElementById("basketgroup-"+bgid+"-name");
592
593     div.removeChild(nameinput);
594
595     newh3.innerHTML=name;
596     hiddenname.value=name;
597     changedinput.value = 1;
598     div.insertBefore(newh3, p);
599 }
600
601 //=======================================================================
602 //a logging function (a bit buggy, might open millions of log pages when initializing, but works fine after...
603 function log(message) {
604     if (!log.window_ || log.window_.closed) {
605         var win = window.open("", null, "width=400,height=200," +
606                             "scrollbars=yes,resizable=yes,status=no," +
607                             "location=no,menubar=no,toolbar=no");
608         if (!win) return;
609         var doc = win.document;
610         doc.write("<html><head><title>Debug Log</title></head>" +
611                 "<body></body></html>");
612         doc.close();
613         log.window_ = win;
614     }
615     var logLine = log.window_.document.createElement("div");
616     logLine.appendChild(log.window_.document.createTextNode(message));
617     log.window_.document.body.appendChild(logLine);
618 }
619 //=======================================================================
620
621
622
623     function ownerPopup(f) {
624     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');
625     }
626         //
627 //=======================================================================
628 function getElementsByClass( searchClass, domNode, tagName) {
629     if (domNode == null) domNode = document;
630     if (tagName == null) tagName = '*';
631     var el = new Array();
632     var tags = domNode.getElementsByTagName(tagName);
633     var tcl = " "+searchClass+" ";
634     for(i=0,j=0; i<tags.length; i++) {
635         var test = " " + tags[i].className + " ";
636         if (test.indexOf(tcl) != -1)
637             el[j++] = tags[i];
638     }
639     return el;
640 }
641
642
643 function calcTotalRow(cell) {
644
645     var bud_id =  cell.className;
646     var val1 =    cell.value;
647     var remainingTotal =   document.getElementById("budget_est_"+bud_id) ;
648     var remainingNew =0;
649     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
650     var arr =  getElementsByClass(bud_id);
651
652     budgetTotal   =  budgetTotal.replace(/\,/, "");
653
654 //percent strip and convert
655     if ( val1.match(/\%/) )   {
656         val1 = val1.replace(/\%/, "");
657         cell.value =    (val1 / 100) *  Math.abs(budgetTotal ) ;
658     }
659
660     for ( var i=0, len=arr.length; i<len; ++i ){
661         remainingNew   +=   Math.abs(arr[i].value);
662     }
663
664     var cc = new Number(cell.value);
665     cell.value =  cc.toFixed(2); // TIDYME...
666     remainingNew    =    Math.abs( budgetTotal  ) -  remainingNew   ;
667
668     if ( remainingNew  == 0)  {
669         remainingTotal.style.color = 'black';
670     }
671     else if ( remainingNew   > 0   )       {
672         remainingTotal.style.color = 'green';
673     } else  {    // if its negative, make it red..
674         remainingTotal.style.color = 'red';
675     }
676
677     remainingTotal.textContent  = remainingNew.toFixed(2) ;
678 }
679
680 function autoFillRow(bud_id) {
681
682     var remainingTotal =   document.getElementById("budget_est_"+bud_id) ;
683     var remainingNew = new Number;
684     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
685     var arr =  getElementsByClass(bud_id);
686
687     budgetTotal   =  budgetTotal.replace(/\,/, "");
688     var qty = new Number;
689 // get the totals
690     for ( var i=0, len=arr.length; i<len; ++i ) {
691         remainingNew   +=   Math.abs (arr[i].value );
692
693         if ( arr[i].value == 0 ) {
694             qty += 1;
695         }
696     }
697
698     remainingNew    =    Math.abs( budgetTotal) -  remainingNew   ;
699     var newCell = new Number (remainingNew / qty);
700
701     for ( var i=0, len=arr.length; i<len; ++i ) {
702         if (  Math.abs(arr[i].value) == 0 ) {
703             arr[i].value = newCell.toFixed(2) ;
704         }
705     }
706
707     remainingTotal.textContent = '0.00' ;
708     remainingTotal.style.color = 'black';
709 }
710
711
712 function messenger(X,Y,etc){    // FIXME: unused?
713     win=window.open("","mess","height="+X+",width="+Y+",screenX=150,screenY=0");
714     win.focus();
715     win.document.close();
716     win.document.write("<body link='#333333' bgcolor='#ffffff' text='#000000'><font size='2'><p><br />");
717     win.document.write(etc);
718     win.document.write("<center><form><input type=button onclick='self.close()' value='Close'></form></center>");
719     win.document.write("</font></body></html>");
720 }
721
722
723 //=======================================================================
724
725 //  NEXT BLOCK IS USED BY NEWORDERBEMPTY
726
727 function calcNeworderTotal(){
728     //collect values
729     var f        = document.getElementById('Aform');
730     var quantity = new Number(f.quantity.value);
731     var discount = new Number(f.discount.value);
732     var listinc  = new Number (f.listinc.value);
733     var currency = f.currency.value;
734     var applygst = new Number (f.applygst.value);
735     var list_price   =  new Number(f.list_price.value);
736     var invoiceingst =  new Number (f.invoiceincgst.value);
737     var exchangerate =  new Number(f.elements[currency].value);      //get exchange rate
738     var gst_on=(!listinc && invoiceingst);
739
740     //do real stuff
741     var rrp   = new Number(list_price*exchangerate);
742     var ecost = new Number(rrp * (100 - discount ) / 100);
743     var GST   = new Number(0);
744     if (gst_on) {
745             rrp=rrp * (1+f.gstrate.value / 100);
746         GST=ecost * f.gstrate.value / 100;
747     }
748
749     var total =  new Number( (ecost + GST) * quantity);
750
751     f.rrp.value = rrp.toFixed(2);
752
753 //      f.rrp.value = rrp
754 //      f.rrp.value = 'moo'
755
756     f.ecost.value = ecost.toFixed(2);
757     f.total.value = total.toFixed(2);
758     f.list_price.value =  list_price.toFixed(2);
759
760 //  gst-stuff needs verifing, mason.
761     if (f.GST) {
762         f.GST.value=GST;
763     }
764     return true;
765 }
766
767 // ----------------------------------------
768 //USED BY NEWORDEREMPTY.PL
769 /*
770 function fetchSortDropbox(f) {
771     var  budgetId=f.budget_id.value;
772     var handleSuccess = function(o){
773         if(o.responseText !== undefined){
774             sort_dropbox.innerHTML   = o.responseText;
775         }
776     }
777
778     var callback = {   success:handleSuccess };
779     var sUrl = '../acqui/fetch_sort_dropbox.pl?sort=1&budget_id='+budgetId
780     var sort_dropbox = document.getElementById('sort1');
781     var request1 = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
782     var rr = '00';
783
784 // FIXME: ---------  twice , coz the 2 requests get mixed up otherwise
785
786     var handleSuccess2 = function(o){
787     if(o.responseText !== undefined){
788         sort2_dropbox.innerHTML   = o.responseText;
789         }
790     }
791
792     var callback2 = {   success:handleSuccess };
793     var sUrl2 = '../acqui/fetch_sort_dropbox.pl?sort=2&budget_id='+budgetId;
794     var sort2_dropbox = document.getElementById('sort2');
795     var request2 = YAHOO.util.Connect.asyncRequest('GET', sUrl2, callback2);
796
797 }
798 */
799
800
801
802 //USED BY NEWORDEREMPTY.PL
803 function fetchSortDropbox(f) {
804     var  budgetId=f.budget_id.value;
805
806 for (i=1;i<=2;i++) {
807
808     var sort_dropbox = document.getElementById('sort'+i);
809     var url = '../acqui/fetch_sort_dropbox.pl?sort='+i+'&budget_id='+budgetId;
810
811     var xmlhttp = null;
812     xmlhttp = new XMLHttpRequest();
813     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
814         xmlhttp.overrideMimeType('text/xml');
815     }
816
817     xmlhttp.open('GET', url, false);
818     xmlhttp.send(null);
819
820     xmlhttp.onreadystatechange = function() {
821         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
822     // stupid JS...
823         } else {
824     // wait for the call to complete
825         }
826     };
827     // rc =  eval ( xmlhttp.responseText );
828     sort_dropbox.innerHTML  =  xmlhttp.responseText;
829 }
830 }
831
832
833
834
835
836
837
838 //USED BY NEWORDEREMPTY.PL
839 function totalExceedsBudget(budgetId, total) {
840
841     var xmlhttp = null;
842     xmlhttp = new XMLHttpRequest();
843     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
844         xmlhttp.overrideMimeType('text/xml');
845     }
846
847     var url = '../acqui/check_budget_total.pl?budget_id=' + budgetId + "&total=" + total;
848     xmlhttp.open('GET', url, false);
849     xmlhttp.send(null);
850
851     xmlhttp.onreadystatechange = function() {
852         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
853
854             actTotal = eval ( xmlhttp.responseText );
855
856             if (  Math.abs(actTotal) < Math.abs(total)  ) {
857             // if budget is to low :(
858                 return true ;
859             } else {
860                 return false;
861             }
862         }
863     }
864 }
865
866
867 //USED BY AQBUDGETS.TMPL
868 function budgetExceedsParent(budgetTotal, budgetId, newBudgetParent, periodID) {
869
870
871     var xmlhttp = null;
872     xmlhttp = new XMLHttpRequest();
873     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
874         xmlhttp.overrideMimeType('text/xml');
875     }
876
877 // make the call... yawn
878 //    var url = '../admin/check_parent_total.pl?budget_id=' + budgetId +   '&parent_id=' + newBudgetParent  + "&total=" + budgetTotal + "&period_id="+ periodID   ;
879
880
881     var url = '../admin/check_parent_total.pl?total=' + budgetTotal + "&period_id="+ periodID   ;
882
883 if (budgetId ) { url +=  '&budget_id=' + budgetId };
884 if ( newBudgetParent  ) { url +=  '&parent_id=' + newBudgetParent};
885
886
887     xmlhttp.open('GET', url, false);
888     xmlhttp.send(null);
889
890     xmlhttp.onreadystatechange = function() {
891         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
892     // stupid JS...
893         } else {
894     // wait for the call to complete
895         }
896     };
897
898     var result = eval ( xmlhttp.responseText );
899
900     if (result == '1') {
901             return _("- Budget total exceeds parent allocation\n");
902     } else if (result == '2') {
903             return _("- Budget total exceeds period allocation\n");
904     } else  {
905             return false;
906     }
907 }
908
909
910
911
912 //USED BY AQBUDGETS.TMPL
913 function checkBudgetParent(budgetId, newBudgetParent) {
914     var xmlhttp = null;
915     xmlhttp = new XMLHttpRequest();
916     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
917         xmlhttp.overrideMimeType('text/xml');
918     }
919
920     var url = '../admin/check_budget_parent.pl?budget_id=' + budgetId + '&new_parent=' + newBudgetParent;
921     xmlhttp.open('GET', url, false);
922     xmlhttp.send(null);
923
924     xmlhttp.onreadystatechange = function() {
925         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
926     // do something with the results
927         } else {
928     // wait for the call to complete
929         }
930     };
931
932     var result = eval ( xmlhttp.responseText );
933
934     if (result == '1') {
935             return _("- New budget-parent is beneath budget\n");
936 //     } else if (result == '2') {
937 //            return "- New budget-parent has insufficent funds\n";
938 //     } else  {
939 //              return false;
940     }
941 }
942
943
944 function addColumn(p_sType, p_aArgs, p_oValue)
945 {
946     var allRows = document.getElementById('plan').rows;
947     var colnum  = p_oValue[0];
948     var code   = p_oValue[1];
949     var colnum  = new Number(colnum);
950
951     for (var i=0; i<allRows.length; i++) {
952             var allCells  = allRows[i].cells;
953             allCells[colnum+1].style.display="table-cell";
954     }
955
956 // make a menuitem object
957     var hids = document.getElementsByName("hide_cols")
958     for (var i=0; i<hids.length; i++) {
959         if (hids[i].value == code) {
960             var x =  hids[i];
961             x.parentNode.removeChild(x)    // sigh...
962             break;
963         }
964     }
965 }
966
967
968 function delColumn(n, code)
969 {
970     var allRows = document.getElementById('plan').rows;
971
972 // find index
973     var index;
974     var nn  = new Number(n);
975     var code   = code ;
976     for (var i=0; i<allRows.length; i++) {
977         var allCells  = allRows[i].cells;
978         allCells[nn+1].style.display="none";
979     }
980
981     var r = 0;
982     var hids = document.getElementsByName("hide_cols")
983     for (var i=0; i<hids.length; i++) {
984         if (hids[i].value == code) {
985             r = 1;
986             break;
987         }
988     }
989
990     if (r == 0 ) {
991         // add hide_col to form
992         var el = document.createElement("input");
993         el.setAttribute("type", 'hidden' );
994         el.setAttribute("value", code);
995         el.setAttribute("name", 'hide_cols');
996         document.getElementById("hide_div").appendChild(el);
997     }
998 }
999
1000