Bug 7598: [Follow-up] make strings in acquisitions JavaScript translatable
[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 = MSG_INVALIDPRICE;
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 //Function returns false if v is not a number (if maybenull is 0, it also returns an error if the number is 0)
39 function isNum(v,maybenull) {
40     var n = new Number(v.value);
41     if (isNaN(n)) {
42         return false;
43     }
44     if (maybenull==0 && v.value=='') {
45
46
47     return false;
48     }
49     return true;
50 }
51
52 //=======================================================================
53
54 //=======================================================================
55 // Functions for drag-and-drop functionality
56
57 if( typeof(YAHOO) === "object"){
58     (function() {
59
60     var Dom = YAHOO.util.Dom;
61     var Event = YAHOO.util.Event;
62     var DDM = YAHOO.util.DragDropMgr;
63
64     DDApp = {
65         init: function() {
66         var uls = document.getElementsByTagName('ul');
67         var i,j;
68         var ddtarget;
69         for (i=0; i<uls.length;i=i+1) {
70             if (uls[i].className == "draglist" || uls[i].className == "draglist_alt") {
71                 ddtarget = YAHOO.util.DragDropMgr.getDDById(uls[i].id);
72     // 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,
73     // it has to be unlinked multiple times, so we need to test whether it is allready a target, otherwise we'll have a problem when closing the group
74                 if( ! ddtarget ) {
75                     new YAHOO.util.DDTarget(uls[i].id);
76                 }
77                 var children = uls[i].getElementsByTagName('li');
78                 for( j=0; j<children.length; j=j+1) {
79     // The yahoo drag and drop is (broken or not) in such a way, that if an element is subscribed as a target multiple times,
80     // it has to be unlinked multiple times, so we need to test whether it is allready a target, otherwise we'll have a problem when closing the group
81                     ddtarget = YAHOO.util.DragDropMgr.getDDById(children[j].id);
82                     if( ! ddtarget ) {
83                         new DDList(children[j].id);
84                     }
85                 }
86             }
87         }
88         }
89     };
90
91
92     // drag and drop implementation
93
94     DDList = function(id, sGroup, config) {
95
96         DDList.superclass.constructor.call(this, id, sGroup, config);
97
98         this.logger = this.logger || YAHOO;
99         var el = this.getDragEl();
100         Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent
101
102         this.goingUp = false;
103         this.lastY = 0;
104     };
105
106     YAHOO.extend(DDList, YAHOO.util.DDProxy, {
107
108         startDrag: function(x, y) {
109             this.logger.log(this.id + " startDrag");
110
111             // make the proxy look like the source element
112             var dragEl = this.getDragEl();
113             var clickEl = this.getEl();
114             Dom.setStyle(clickEl, "visibility", "hidden");
115
116             dragEl.innerHTML = clickEl.innerHTML;
117
118             Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
119             Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
120             Dom.setStyle(dragEl, "border", "2px solid gray");
121         },
122
123         endDrag: function(e) {
124
125             var srcEl = this.getEl();
126             var proxy = this.getDragEl();
127
128             // Show the proxy element and animate it to the src element's location
129             Dom.setStyle(proxy, "visibility", "");
130             var a = new YAHOO.util.Motion(
131                 proxy, {
132                     points: {
133                         to: Dom.getXY(srcEl)
134                     }
135                 },
136                 0.2,
137                 YAHOO.util.Easing.easeOut
138             )
139             var proxyid = proxy.id;
140             var thisid = this.id;
141
142             // Hide the proxy and show the source element when finished with the animation
143             a.onComplete.subscribe(function() {
144                     Dom.setStyle(proxyid, "visibility", "hidden");
145                     Dom.setStyle(thisid, "visibility", "");
146                 });
147             a.animate();
148     // if we are in basketgrouping page, when finished moving, edit the basket's info to reflect new status
149             if(typeof(basketgroups) != 'undefined') {
150                 a.onComplete.subscribe(function() {
151                     var reg = new RegExp("[-]+", "g");
152     // add a changed input to each moved basket, so we know which baskets to modify,
153     // and so we don't need to modify each and every basket and basketgroup each time the page is loaded
154     // FIXME: we shouldn't use getElementsByTagName, it's not explicit enough :-(
155                     srcEl.getElementsByTagName('input')[1].value = "1";
156                     if ( srcEl.parentNode.parentNode.className == "workarea" ) {
157                         var dstbgroupid = srcEl.parentNode.parentNode.getElementsByTagName('input')[srcEl.parentNode.parentNode.getElementsByTagName('input').length-2].name.split(reg)[1];
158                         srcEl.className="grouped";
159                         srcEl.getElementsByTagName('input')[0].value = dstbgroupid;
160     //FIXME: again, we shouldn't be using getElementsByTagName!!
161                         srcEl.parentNode.parentNode.getElementsByTagName('input')[srcEl.parentNode.parentNode.getElementsByTagName('input').length-1].value = 1;
162                     }
163                     else if ( srcEl.parentNode.parentNode.className == "workarea_alt" ){
164                             srcEl.className="ungrouped";
165                             srcEl.getElementsByTagName('input')[0].value = "0";
166                     }
167                 });
168             }
169         },
170
171         onDragDrop: function(e, id) {
172
173             // If there is one drop interaction, the li was dropped either on the list,
174             // or it was dropped on the current location of the source element.
175             if (DDM.interactionInfo.drop.length === 1) {
176
177                 // The position of the cursor at the time of the drop (YAHOO.util.Point)
178                 var pt = DDM.interactionInfo.point;
179
180                 // The region occupied by the source element at the time of the drop
181                 var region = DDM.interactionInfo.sourceRegion;
182
183                 // Check to see if we are over the source element's location.  We will
184                 // append to the bottom of the list once we are sure it was a drop in
185                 // the negative space (the area of the list without any list items)
186                 if (!region.intersect(pt)) {
187                     var destEl = Dom.get(id);
188                     var destDD = DDM.getDDById(id);
189                     destEl.appendChild(this.getEl());
190                     destDD.isEmpty = false;
191                     DDM.refreshCache();
192                 }
193             }
194         },
195
196         onDrag: function(e) {
197
198             // Keep track of the direction of the drag for use during onDragOver
199             var y = Event.getPageY(e);
200
201             if (y < this.lastY) {
202                 this.goingUp = true;
203             } else if (y > this.lastY) {
204                 this.goingUp = false;
205             }
206             this.lastY = y;
207         },
208
209         onDragOver: function(e, id) {
210
211             var srcEl = this.getEl();
212             var destEl = Dom.get(id);
213
214             // We are only concerned with list items, we ignore the dragover
215             // notifications for the list.
216             if (destEl.nodeName.toLowerCase() == "li") {
217                 var orig_p = srcEl.parentNode;
218                 var p = destEl.parentNode;
219
220                 if (this.goingUp) {
221                     p.insertBefore(srcEl, destEl); // insert above
222                 } else {
223                     p.insertBefore(srcEl, destEl.nextSibling); // insert below
224                 }
225
226                 DDM.refreshCache();
227             }
228         }
229     });
230     })();
231 }
232
233
234
235 //creates new group, parameter is the group's name
236 function newGroup(event, name) {
237     if (name == ''){
238         return 0;
239     }
240     if (!enterpressed(event) && event != "button"){
241         return false;
242     }
243     var pardiv = document.getElementById('groups');
244     var newdiv = document.createElement('div');
245     var newh3 = document.createElement('h3');
246     var newul = document.createElement('ul');
247     var newclose = document.createElement('a');
248     var newrename = document.createElement('a');
249     var newbasketgroupname = document.createElement('input');
250     var nbgclosed = document.createElement('input');
251     var newp = document.createElement('p');
252     var reg=new RegExp("[-]+", "g");
253     var i = 0;
254     var maxid = 0;
255     while( i < pardiv.getElementsByTagName('input').length ){
256         if (! isNaN(parseInt(pardiv.getElementsByTagName('input')[i].name.split(reg)[1])) && parseInt(pardiv.getElementsByTagName('input')[i].name.split(reg)[1]) > maxid){
257             maxid = parseInt(pardiv.getElementsByTagName('input')[i].name.split(reg)[1]);
258         }
259         ++i;
260     }
261 // var bgid = parseInt(pardiv.getElementsByTagName('input')[pardiv.getElementsByTagName('input').length-2].name.split(reg)[1]) + 1;
262     var bgid = maxid + 1;
263     var newchanged = document.createElement('input');
264
265     newul.id="bg-"+bgid;
266     newul.className='draglist';
267
268     newh3.innerHTML=name;
269 //    newh3.style.display="inline";
270
271     newclose.innerHTML="close";
272     newclose.href="javascript: closebasketgroup('"+bgid+"', 'bg-"+bgid+"');";
273
274     newrename.href="javascript:" + "renameinit("+bgid+");";
275     newrename.innerHTML="rename";
276
277 //    newp.style.display="inline";
278     newp.innerHTML=" [ ";
279     newp.appendChild(newrename);
280     newp.innerHTML+=" / ";
281     newp.appendChild(newclose);
282     newp.innerHTML+=" ]";
283
284     newbasketgroupname.type="hidden";
285     newbasketgroupname.name="basketgroup-" + bgid + "-name";
286     newbasketgroupname.id = "basketgroup-" + bgid + "-name";
287     newbasketgroupname.value=name;
288
289     nbgclosed.type="hidden";
290     nbgclosed.name="basketgroup-" + bgid + "-closed";
291     nbgclosed.value="0";
292     nbgclosed.id=nbgclosed.name;
293
294     newchanged.type="hidden";
295     newchanged.id="basketgroup-"+bgid+"-changed";
296     newchanged.name=newchanged.id;
297     newchanged.value="1";
298
299     newdiv.style.backgroundColor='red';
300     newdiv.appendChild(newh3);
301     newdiv.appendChild(newp);
302     newdiv.appendChild(newul);
303     newdiv.appendChild(newbasketgroupname);
304     newdiv.appendChild(nbgclosed);
305     newdiv.appendChild(newchanged);
306     newdiv.className='workarea';
307     pardiv.appendChild(newdiv);
308
309     YAHOO.util.Event.onDOMReady(DDApp.init, DDApp, true);
310 }
311
312 //this traps enters in input fields
313 function enterpressed(event){
314     var keycode;
315     if (window.event) keycode = window.event.keyCode;
316     else if (event) keycode = event.which;
317     else return false;
318
319     if (keycode == 13)
320     {
321         return true;
322     }
323     else return false;
324 }
325
326
327
328
329
330 //Closes a basketgroup
331 function closebasketgroup(bgid) {
332     var answer = confirm(MSG_CONFIRM_CLOSE_BASKETGROUP);
333     if(! answer){
334         return;
335     }
336     ulid = 'bg-'+bgid;
337     var i = 0;
338     tagname='basketgroup-'+bgid+'-closed';
339     var ddtarget;
340     var closeinput = document.getElementById(tagname);
341     closeinput.value = 1;
342     var changed = document.getElementById("basketgroup-"+bgid+"-changed");
343     changed.value=1;
344
345     var div = document.getElementById(tagname).parentNode;
346     var stufftoremove = div.getElementsByTagName('p')[0];
347     var ul = document.getElementById(ulid);
348     var lis = ul.getElementsByTagName('li');
349     if (lis.length == 0 ) {
350         alert(MSG_CLOSE_EMPTY_BASKET);
351         return;
352     }
353     var cantprint = document.createElement('p');
354
355     div.className = "closed";
356     ul.className="closed";
357
358     for(i=0; i<lis.length; ++i) {
359         ddtarget = YAHOO.util.DragDropMgr.getDDById(lis[i].id);
360         ddtarget.unreg();
361     }
362     ddtarget = YAHOO.util.DragDropMgr.getDDById(ul.id);
363     ddtarget.unreg();
364     div.removeChild(stufftoremove);
365 // the print button is disabled because the page's content might (or is probably) not in sync with what the database contains
366     cantprint.innerHTML = MSG_SAVE_BEFORE_PRINTING;
367     cantprint.id = 'cantprint-' + bgid;
368     var unclosegroup = document.createElement('a');
369     unclosegroup.href='javascript:unclosegroup('+bgid+');';
370     unclosegroup.innerHTML= MSG_REOPEN_BASKETGROUP;
371     unclosegroup.id = 'unclose-' + bgid;
372
373     div.appendChild(cantprint);
374     div.appendChild(unclosegroup);
375 }
376
377 function closeandprint(bg){
378         if(document.location = '/cgi-bin/koha/acqui/basketgroup.pl?op=closeandprint&amp;basketgroupid=' + bg ){
379                 setTimeout("window.location.reload();",3000);
380         }else{
381         alert(MSG_FILE_DOWNLOAD_ERROR);
382         }
383 }
384
385 //function that lets the user unclose a basketgroup as long as he hasn't submitted the changes to the page.
386 function unclosegroup(bgid){
387     var div = document.getElementById('basketgroup-'+bgid+'-closed').parentNode;
388     var divtodel = document.getElementById('unclose-' + bgid);
389     if (divtodel){
390         div.removeChild(divtodel);
391     }
392     divtodel = document.getElementById('unclose-' + bgid);
393     if (divtodel){
394         div.removeChild(divtodel);
395     }
396     var closeinput = document.getElementById('basketgroup-'+bgid+'-closed');
397     var ul = document.getElementById('bg-'+bgid);
398
399     var newclose = document.createElement('a');
400     var newrename = document.createElement('a');
401     var newp = document.createElement('p');
402
403     newclose.innerHTML="close";
404     newclose.href="javascript: closebasketgroup('"+bgid+"', 'bg-"+bgid+"');";
405
406     newrename.href="javascript:" + "renameinit("+bgid+");";
407     newrename.innerHTML="rename";
408     
409     var todel = div.getElementsByTagName('p')[0];
410     div.removeChild(todel);
411     
412     var changed = document.getElementById("basketgroup-"+bgid+"-changed");
413     changed.value=1;
414
415     newp.innerHTML=" [ ";
416     newp.appendChild(newrename);
417     newp.innerHTML+=" / ";
418     newp.appendChild(newclose);
419     newp.innerHTML+=" ]";
420
421     div.insertBefore(newp, ul);
422     closeinput.value="0";
423     div.className = "workarea";
424     ul.className="draglist";
425
426 //rescan draglists, we have a new target (again :-)
427     YAHOO.util.Event.onDOMReady(DDApp.init, DDApp, true);
428 }
429
430 //a function to filter basketgroups using a regex (javascript regex)
431 function filterGroups(event, searchstring ){
432     if (!enterpressed(event) && event != "button"){
433         return false;
434     }
435     var reg = new RegExp(searchstring, "g");
436     var Dom = YAHOO.util.Dom;
437     var divs = Dom.getElementsByClassName("workarea", "div");
438
439     for (var i = 0; i < divs.length; ++i){
440         if (! reg.exec(divs[i].innerHTML)){
441             divs[i].style.display='none';
442         }
443         else {
444             divs[i].style.display='';
445         }
446     }
447     divs = Dom.getElementsByClassName("closed", "div");
448     for (var i = 0; i < divs.length; ++i){
449         if (! reg.exec(divs[i].innerHTML)){
450             divs[i].style.display='none';
451         }
452         else {
453             divs[i].style.display='';
454         }
455     }
456 }
457
458 //function to hide (or show) closed baskets (if show is true, it shows all the closed baskets)
459 function showhideclosegroups(show){
460     var Dom = YAHOO.util.Dom;
461     var divs = Dom.getElementsByClassName("closed", "div");
462     var display;
463     if (show){
464         display = '';
465     }
466     else display = 'none';
467     for(var i = 0; i < divs.length; ++i){
468         divs[i].style.display=display;
469     }
470 }
471
472 function renameinit(bgid){
473     var ul = document.getElementById('bg-'+bgid);
474     var div = ul.parentNode;
475     var nameelm = div.getElementsByTagName('h3')[0];
476     var p = div.getElementsByTagName('p')[0];
477
478
479     var nameinput = document.createElement("input");
480     nameinput.type = "text";
481     nameinput.id="rename-"+bgid;
482     nameinput.value = nameelm.innerHTML;
483     nameinput.onkeypress = function(e){rename(e, bgid, document.getElementById('rename-'+bgid).value); };
484 //    nameinput.setAttribute('onkeypress', 'rename(event, bgid, document.getElementById(rename-'+bgid+').value);');
485
486     div.removeChild(nameelm);
487     div.insertBefore(nameinput, p);
488 }
489
490 function rename(event, bgid, name){
491     if (!enterpressed(event)){
492         return false;
493     }
494     var ul = document.getElementById('bg-'+bgid);
495     var div = ul.parentNode;
496     var p = div.getElementsByTagName('p')[0];
497     var nameinput = document.getElementById("rename-"+bgid);
498     var changedinput = document.getElementById("basketgroup-"+bgid+"-changed");
499     var newh3 = document.createElement("h3");
500     var hiddenname = document.getElementById("basketgroup-"+bgid+"-name");
501
502     div.removeChild(nameinput);
503
504     newh3.innerHTML=name;
505     hiddenname.value=name;
506     changedinput.value = 1;
507     div.insertBefore(newh3, p);
508 }
509
510 //=======================================================================
511 //a logging function (a bit buggy, might open millions of log pages when initializing, but works fine after...
512 function log(message) {
513     if (!log.window_ || log.window_.closed) {
514         var win = window.open("", null, "width=400,height=200," +
515                             "scrollbars=yes,resizable=yes,status=no," +
516                             "location=no,menubar=no,toolbar=no");
517         if (!win) return;
518         var doc = win.document;
519         doc.write("<html><head><title>Debug Log</title></head>" +
520                 "<body></body></html>");
521         doc.close();
522         log.window_ = win;
523     }
524     var logLine = log.window_.document.createElement("div");
525     logLine.appendChild(log.window_.document.createTextNode(message));
526     log.window_.document.body.appendChild(logLine);
527 }
528
529 //=======================================================================
530 function getElementsByClass( searchClass, domNode, tagName) {
531     if (domNode == null) domNode = document;
532     if (tagName == null) tagName = '*';
533     var el = new Array();
534     var tags = domNode.getElementsByTagName(tagName);
535     var tcl = " "+searchClass+" ";
536     for(i=0,j=0; i<tags.length; i++) {
537         var test = " " + tags[i].className + " ";
538         if (test.indexOf(tcl) != -1)
539             el[j++] = tags[i];
540     }
541     return el;
542 }
543
544
545 function calcTotalRow(cell) {
546
547     var string = cell.name;
548     var pos = string.indexOf(",", 0);
549     var bud_id = string.substring(0, pos);
550     var val1 =    cell.value;
551     var remainingTotal =   document.getElementById("budget_est_"+bud_id);
552     var remainingNew =0;
553     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
554     var arr =  getElementsByClass(cell.className);
555
556     budgetTotal   =  budgetTotal.replace(/\,/, "");
557
558 //percent strip and convert
559     if ( val1.match(/\%/) )   {
560         val1 = val1.replace(/\%/, "");
561         cell.value =    (val1 / 100) *  Math.abs(budgetTotal ) ;
562     }
563
564     for ( var i=0, len=arr.length; i<len; ++i ){
565         remainingNew   +=   Math.abs(arr[i].value);
566     }
567
568     var cc = new Number(cell.value);
569     cell.value =  cc.toFixed(2); // TIDYME...
570     remainingNew    =    Math.abs( budgetTotal  ) -  remainingNew   ;
571
572     if ( remainingNew  == 0)  {
573         remainingTotal.style.color = 'black';
574     }
575     else if ( remainingNew   > 0   )       {
576         remainingTotal.style.color = 'green';
577     } else  {    // if its negative, make it red..
578         remainingTotal.style.color = 'red';
579     }
580
581     remainingTotal.textContent  = remainingNew.toFixed(2) ;
582 }
583
584 function autoFillRow(bud_id) {
585
586     var remainingTotal =   document.getElementById("budget_est_"+bud_id);
587     var remainingNew = new Number;
588     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
589     var arr =  getElementsByClass("plan_entry_" + bud_id);
590
591     budgetTotal   =  budgetTotal.replace(/\,/, "");
592     var qty = new Number;
593 // get the totals
594     var novalueArr = new Array();
595     for ( var i=0, len=arr.length; i<len; ++i ) {
596         remainingNew   +=   Math.abs (arr[i].value );
597
598         if ( arr[i].value == 0 ) {
599             novalueArr[qty] = arr[i];
600             qty += 1;
601         }
602     }
603
604     remainingNew    =    Math.abs( budgetTotal) -  remainingNew   ;
605     var newCell = new Number (remainingNew / qty);
606     var rest = new Number (remainingNew - (newCell.toFixed(2) * (novalueArr.length - 1)));
607
608     for (var i = 0; i<novalueArr.length; ++i) {
609          if (i == novalueArr.length - 1) {
610              novalueArr[i].value = rest.toFixed(2);
611          }else {
612              novalueArr[i].value = newCell.toFixed(2);
613         }
614     }
615
616     remainingTotal.textContent = '0.00' ;
617     remainingTotal.style.color = 'black';
618 }
619
620
621 function messenger(X,Y,etc){    // FIXME: unused?
622     win=window.open("","mess","height="+X+",width="+Y+",screenX=150,screenY=0");
623     win.focus();
624     win.document.close();
625     win.document.write("<body link='#333333' bgcolor='#ffffff' text='#000000'><font size='2'><p><br />");
626     win.document.write(etc);
627     win.document.write("<center><form><input type=button onclick='self.close()' value='Close'></form></center>");
628     win.document.write("</font></body></html>");
629 }
630
631
632 //=======================================================================
633
634 //  NEXT BLOCK IS USED BY NEWORDERBEMPTY
635
636 function updateCosts(){
637     var quantity = new Number($("#quantity").val());
638     var discount = new Number($("#discount").val());
639     var applygst = new Number ($("#applygst").val());
640     var listprice   =  new Number($("#listprice").val());
641     var currcode = new String($("#currency").val());
642     var exchangerate =  new Number($("#currency_rate_"+currcode).val());
643     var gst_on=false;
644
645     var rrp   = new Number(listprice*exchangerate);
646     var ecost = rrp;
647     if ( 100-discount != 100 ) { //Prevent rounding issues if no discount
648         ecost = new Number(Math.floor(rrp * (100 - discount )) / 100);
649     }
650     var total =  new Number( ecost * quantity);
651     $("#rrp").val(rrp.toFixed(2));
652     $("#ecost").val(ecost.toFixed(2));
653     $("#total").val(total.toFixed(2));
654     $("listprice").val(listprice.toFixed(2));
655
656     return true;
657 }
658
659 // Calculates total amount in a suggestion
660
661 function calcNewsuggTotal(){
662     //collect values
663     var quantity = new Number(document.getElementById('quantity').value);
664 //    var currency = f.currency.value;
665     var currcode = new String(document.getElementById('currency').value);
666     var price   =  new Number(document.getElementById('price').value);
667     var exchangerate =  new Number(document.getElementById('currency_rate_'+currcode).value);
668
669     var total =  new Number(quantity*price*exchangerate);
670
671     document.getElementById('total').value = total.toFixed(2);
672     document.getElementById('price').value =  price.toFixed(2);
673     return true;
674 }
675
676
677 // ----------------------------------------
678 //USED BY NEWORDEREMPTY.PL
679 /*
680 function fetchSortDropbox(f) {
681     var  budgetId=f.budget_id.value;
682     var handleSuccess = function(o){
683         if(o.responseText !== undefined){
684             sort_dropbox.innerHTML   = o.responseText;
685         }
686     }
687
688     var callback = {   success:handleSuccess };
689     var sUrl = '../acqui/fetch_sort_dropbox.pl?sort=1&budget_id='+budgetId
690     var sort_dropbox = document.getElementById('sort1');
691     var request1 = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
692     var rr = '00';
693
694 // FIXME: ---------  twice , coz the 2 requests get mixed up otherwise
695
696     var handleSuccess2 = function(o){
697     if(o.responseText !== undefined){
698         sort2_dropbox.innerHTML   = o.responseText;
699         }
700     }
701
702     var callback2 = {   success:handleSuccess };
703     var sUrl2 = '../acqui/fetch_sort_dropbox.pl?sort=2&budget_id='+budgetId;
704     var sort2_dropbox = document.getElementById('sort2');
705     var request2 = YAHOO.util.Connect.asyncRequest('GET', sUrl2, callback2);
706
707 }
708 */
709
710
711
712 //USED BY NEWORDEREMPTY.PL
713 function fetchSortDropbox(f) {
714     var  budgetId=f.budget_id.value;
715
716 for (i=1;i<=2;i++) {
717
718     var sort_zone = document.getElementById('sort'+i+'_zone');
719     var url = '../acqui/fetch_sort_dropbox.pl?sort='+i+'&budget_id='+budgetId;
720
721     var xmlhttp = null;
722     xmlhttp = new XMLHttpRequest();
723     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
724         xmlhttp.overrideMimeType('text/xml');
725     }
726
727     xmlhttp.open('GET', url, false);
728     xmlhttp.send(null);
729
730     xmlhttp.onreadystatechange = function() {
731         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
732     // stupid JS...
733         } else {
734     // wait for the call to complete
735         }
736     };
737     // rc =  eval ( xmlhttp.responseText );
738     var retRootType = xmlhttp.responseXML.firstChild.nodeName;
739     var existingInputs = sort_zone.getElementsByTagName('input');
740     if (existingInputs.length > 0 && retRootType == 'input') {
741         // when sort is already an input, do not override to preseve value
742         return;
743     }
744     sort_zone.innerHTML = xmlhttp.responseText;
745 }
746 }
747
748
749
750
751
752
753
754 //USED BY NEWORDEREMPTY.PL
755 function totalExceedsBudget(budgetId, total) {
756
757     var xmlhttp = null;
758     xmlhttp = new XMLHttpRequest();
759     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
760         xmlhttp.overrideMimeType('text/xml');
761     }
762
763     var url = '../acqui/check_budget_total.pl?budget_id=' + budgetId + "&total=" + total;
764     xmlhttp.open('GET', url, false);
765     xmlhttp.send(null);
766
767     xmlhttp.onreadystatechange = function() {
768         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
769
770             actTotal = eval ( xmlhttp.responseText );
771
772             if (  Math.abs(actTotal) < Math.abs(total)  ) {
773             // if budget is to low :(
774                 return true ;
775             } else {
776                 return false;
777             }
778         }
779     }
780 }
781
782
783 //USED BY AQBUDGETS.TMPL
784 function budgetExceedsParent(budgetTotal, budgetId, newBudgetParent, periodID) {
785
786
787     var xmlhttp = null;
788     xmlhttp = new XMLHttpRequest();
789     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
790         xmlhttp.overrideMimeType('text/xml');
791     }
792
793 // make the call... yawn
794 //    var url = '../admin/check_parent_total.pl?budget_id=' + budgetId +   '&parent_id=' + newBudgetParent  + "&total=" + budgetTotal + "&period_id="+ periodID   ;
795
796
797     var url = '../admin/check_parent_total.pl?total=' + budgetTotal + "&period_id="+ periodID   ;
798
799 if (budgetId ) { url +=  '&budget_id=' + budgetId };
800 if ( newBudgetParent  ) { url +=  '&parent_id=' + newBudgetParent};
801
802
803     xmlhttp.open('GET', url, false);
804     xmlhttp.send(null);
805
806     xmlhttp.onreadystatechange = function() {
807         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
808     // stupid JS...
809         } else {
810     // wait for the call to complete
811         }
812     };
813
814     var result = eval ( xmlhttp.responseText );
815
816     if (result == '1') {
817             return MSG_BUDGET_PARENT_ALLOCATION;
818     } else if (result == '2') {
819             return MSG_BUDGET_PERIOD_ALLOCATION;
820     } else  {
821             return false;
822     }
823 }
824
825
826
827
828 //USED BY AQBUDGETS.TMPL
829 function checkBudgetParent(budgetId, newBudgetParent) {
830     var xmlhttp = null;
831     xmlhttp = new XMLHttpRequest();
832     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
833         xmlhttp.overrideMimeType('text/xml');
834     }
835
836     var url = '../admin/check_budget_parent.pl?budget_id=' + budgetId + '&new_parent=' + newBudgetParent;
837     xmlhttp.open('GET', url, false);
838     xmlhttp.send(null);
839
840     xmlhttp.onreadystatechange = function() {
841         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
842     // do something with the results
843         } else {
844     // wait for the call to complete
845         }
846     };
847
848     var result = eval ( xmlhttp.responseText );
849
850     if (result == '1') {
851             return MSG_PARENT_BENEATH_BUDGET;
852 //     } else if (result == '2') {
853 //            return "- New budget-parent has insufficent funds\n";
854 //     } else  {
855 //              return false;
856     }
857 }
858
859 function hideColumn(num) {
860     $("#hideall,#showall").removeAttr("checked").parent().removeClass("selected");
861     $("#"+num).parent().removeClass("selected");
862     var hide = Number(num.replace("col","")) + 2;
863     // hide header and cells matching the index
864     $("#plan td:nth-child("+hide+"),#plan th:nth-child("+hide+")").toggle();
865 }
866
867 function showColumn(num){
868     $("#hideall").removeAttr("checked").parent().removeClass("selected");
869     $("#"+num).parent().addClass("selected");
870     // set the index of the table column to hide
871     show = Number(num.replace("col","")) + 2;
872     // hide header and cells matching the index
873     $("#plan td:nth-child("+show+"),#plan th:nth-child("+show+")").toggle();
874 }
875
876 function showAllColumns(){
877     $("#selections").checkCheckboxes();
878     $("#selections span").addClass("selected");
879     $("#plan td:nth-child(2),#plan tr th:nth-child(2)").nextAll().show();
880     $("#hideall").removeAttr("checked").parent().removeClass("selected");
881 }
882 function hideAllColumns(){
883     var allCols = $("#plan th").length;
884     $("#selections").unCheckCheckboxes();
885     $("#selections span").removeClass("selected");
886     $("#plan td:nth-child(2),#plan th:nth-child(2)").nextUntil("th:nth-child("+(allCols-1)+"),td:nth-child("+(allCols-1)+")").hide(); // hide all but the last two columns
887     $("#hideall").attr("checked","checked").parent().addClass("selected");
888 }