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