acqui-home new links to budget and dealing with budget instead of bookfund
[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=_("unclose 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 moveallungroupedto(event, newbgname){
564     if (!enterpressed(event) && event != "button"){
565         return false;
566     }
567     var Dom = YAHOO.util.Dom;
568     var ungrouped = Dom.getElementsByClassName("ungrouped", "li");
569     var unclosed = Dom.getElementsByClassName("workarea", "div");
570     var reg = new RegExp("[-]+", "g");
571
572     for (var i = 0; i < unclosed.length; ++i){
573         if(unclosed[i].getElementsByTagName('h3')[0].innerHTML == newbgname){
574             var ul = unclosed[i].getElementsByTagName('ul')[0];
575             var id = unclosed[i].getElementsByTagName('input')[unclosed[i].getElementsByTagName('input').length-2].name.split(reg)[1];
576             for (var j = 0; j< ungrouped.length; ++j){
577                 ungrouped[j].className = "grouped";
578                 ungrouped[j].getElementsByTagName('input')[0].value = id;
579                 ul.appendChild(ungrouped[j]);
580 //FIXME: these should be using getElementById, but i don't know how.
581 //this might not be explicit enough, and it's quite complex and hard to read. (above is the basketgroupid of the basket,
582 // below is the changed status
583                 ungrouped[j].getElementsByTagName('input')[1].value = 1;
584
585             }
586         }
587     }
588 }
589
590 function renameinit(bgid){
591     var ul = document.getElementById('bg-'+bgid);
592     var div = ul.parentNode;
593     var nameelm = div.getElementsByTagName('h3')[0];
594     var p = div.getElementsByTagName('p')[0];
595
596
597     var nameinput = document.createElement("input");
598     nameinput.type = "text";
599     nameinput.id="rename-"+bgid;
600     nameinput.value = nameelm.innerHTML;
601     nameinput.onkeypress = function(e){rename(e, bgid, document.getElementById('rename-'+bgid).value); };
602 //    nameinput.setAttribute('onkeypress', 'rename(event, bgid, document.getElementById(rename-'+bgid+').value);');
603
604     div.removeChild(nameelm);
605     div.insertBefore(nameinput, p);
606 }
607
608 function rename(event, bgid, name){
609     if (!enterpressed(event)){
610         return false;
611     }
612     var ul = document.getElementById('bg-'+bgid);
613     var div = ul.parentNode;
614     var p = div.getElementsByTagName('p')[0];
615     var nameinput = document.getElementById("rename-"+bgid);
616     var changedinput = document.getElementById("basketgroup-"+bgid+"-changed");
617     var newh3 = document.createElement("h3");
618     var hiddenname = document.getElementById("basketgroup-"+bgid+"-name");
619
620     div.removeChild(nameinput);
621
622     newh3.innerHTML=name;
623     hiddenname.value=name;
624     changedinput.value = 1;
625     div.insertBefore(newh3, p);
626 }
627
628 //=======================================================================
629 //a logging function (a bit buggy, might open millions of log pages when initializing, but works fine after...
630 function log(message) {
631     if (!log.window_ || log.window_.closed) {
632         var win = window.open("", null, "width=400,height=200," +
633                               "scrollbars=yes,resizable=yes,status=no," +
634                               "location=no,menubar=no,toolbar=no");
635         if (!win) return;
636         var doc = win.document;
637         doc.write("<html><head><title>Debug Log</title></head>" +
638                   "<body></body></html>");
639         doc.close();
640         log.window_ = win;
641     }
642     var logLine = log.window_.document.createElement("div");
643     logLine.appendChild(log.window_.document.createTextNode(message));
644     log.window_.document.body.appendChild(logLine);
645 }
646 //=======================================================================
647
648
649
650     function ownerPopup(f) {
651       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');
652     }
653         //
654 //=======================================================================
655 function getElementsByClass( searchClass, domNode, tagName) {
656     if (domNode == null) domNode = document;
657     if (tagName == null) tagName = '*';
658     var el = new Array();
659     var tags = domNode.getElementsByTagName(tagName);
660     var tcl = " "+searchClass+" ";
661     for(i=0,j=0; i<tags.length; i++) {
662         var test = " " + tags[i].className + " ";
663         if (test.indexOf(tcl) != -1)
664             el[j++] = tags[i];
665     }
666     return el;
667 }
668
669
670 function calcTotalRow(cell) {
671
672     var bud_id =  cell.className;
673     var val1 =    cell.value;
674     var remainingTotal =   document.getElementById("budget_est_"+bud_id) ;
675     var remainingNew =0;
676     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
677     var arr =  getElementsByClass(bud_id);
678
679     budgetTotal   =  budgetTotal.replace(/\,/, "");
680
681 //percent strip and convert
682     if ( val1.match(/\%/) )   {
683         val1 = val1.replace(/\%/, "");
684         cell.value =    (val1 / 100) *  Math.abs(budgetTotal ) ;
685     }
686
687     for ( var i=0, len=arr.length; i<len; ++i ){
688         remainingNew   +=   Math.abs(arr[i].value);
689     }
690
691     var cc = new Number(cell.value);
692     cell.value =  cc.toFixed(2); // TIDYME...
693     remainingNew    =    Math.abs( budgetTotal  ) -  remainingNew   ;
694
695     if ( remainingNew  == 0)  {
696         remainingTotal.style.color = 'black';
697     }
698     else if ( remainingNew   > 0   )       {
699          remainingTotal.style.color = 'green';
700     } else  {    // if its negative, make it red..
701         remainingTotal.style.color = 'red';
702     }
703
704     remainingTotal.textContent  = remainingNew.toFixed(2) ;
705 }
706
707 function autoFillRow(bud_id) {
708
709     var remainingTotal =   document.getElementById("budget_est_"+bud_id) ;
710     var remainingNew = new Number;
711     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
712     var arr =  getElementsByClass(bud_id);
713
714     budgetTotal   =  budgetTotal.replace(/\,/, "");
715     var qty = new Number;
716 // get the totals
717     for ( var i=0, len=arr.length; i<len; ++i ) {
718         remainingNew   +=   Math.abs (arr[i].value );
719
720         if ( arr[i].value == 0 ) {
721             qty += 1;
722         }
723     }
724
725     remainingNew    =    Math.abs( budgetTotal) -  remainingNew   ;
726     var newCell = new Number (remainingNew / qty);
727
728     for ( var i=0, len=arr.length; i<len; ++i ) {
729         if (  Math.abs(arr[i].value) == 0 ) {
730             arr[i].value = newCell.toFixed(2) ;
731         }
732     }
733
734     remainingTotal.textContent = '0.00' ;
735     remainingTotal.style.color = 'black';
736 }
737
738
739 function messenger(X,Y,etc){    // FIXME: unused?
740     win=window.open("","mess","height="+X+",width="+Y+",screenX=150,screenY=0");
741     win.focus();
742     win.document.close();
743     win.document.write("<body link='#333333' bgcolor='#ffffff' text='#000000'><font size='2'><p><br />");
744     win.document.write(etc);
745     win.document.write("<center><form><input type=button onclick='self.close()' value='Close'></form></center>");
746     win.document.write("</font></body></html>");
747 }
748
749
750 //=======================================================================
751
752 //  NEXT BLOCK IS USED BY NEWORDERBEMPTY
753
754 function calcNeworderTotal(f){
755         //collect values
756         var quantity = new Number(f.quantity.value);
757         var discount = new Number(f.discount.value);
758         var listinc  = new Number (f.listinc.value);
759         var currency = f.currency.value;
760         var applygst = new Number (f.applygst.value);
761         var list_price   =  new Number(f.list_price.value);
762         var invoiceingst =  new Number (f.invoiceincgst.value);
763         var exchangerate =  new Number(f.elements[currency].value);      //get exchange rate
764         var gst_on=(!listinc && invoiceingst);
765
766         //do real stuff
767         var rrp   = new Number(list_price*exchangerate);
768         var ecost = new Number(rrp * (100 - discount ) / 100);
769         var GST   = new Number(0);
770         if (gst_on) {
771             rrp=rrp * (1+f.gstrate.value / 100);
772             GST=ecost * f.gstrate.value / 100;
773         }
774
775         var total =  new Number( (ecost + GST) * quantity);
776
777         f.rrp.value = rrp.toFixed(2);
778
779 //      f.rrp.value = rrp
780 //      f.rrp.value = 'moo'
781
782         f.ecost.value = ecost.toFixed(2);
783         f.total.value = total.toFixed(2);
784         f.list_price.value =  list_price.toFixed(2);
785
786 //  gst-stuff needs verifing, mason.
787         if (f.GST) {
788                 f.GST.value=GST;
789     }
790         return true;
791 }
792
793 // ----------------------------------------
794 //USED BY NEWORDEREMPTY.PL
795 /*
796 function fetchSortDropbox(f) {
797         var  budgetId=f.budget_id.value;
798         var handleSuccess = function(o){
799         if(o.responseText !== undefined){
800             sort_dropbox.innerHTML   = o.responseText;
801             }
802         }
803
804         var callback = {   success:handleSuccess };
805     var sUrl = '../acqui/fetch_sort_dropbox.pl?sort=1&budget_id='+budgetId
806     var sort_dropbox = document.getElementById('sort1');
807     var request1 = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
808         var rr = '00';
809
810 // FIXME: ---------  twice , coz the 2 requests get mixed up otherwise
811
812         var handleSuccess2 = function(o){
813     if(o.responseText !== undefined){
814         sort2_dropbox.innerHTML   = o.responseText;
815         }
816         }
817
818         var callback2 = {   success:handleSuccess };
819         var sUrl2 = '../acqui/fetch_sort_dropbox.pl?sort=2&budget_id='+budgetId;
820         var sort2_dropbox = document.getElementById('sort2');
821         var request2 = YAHOO.util.Connect.asyncRequest('GET', sUrl2, callback2);
822
823 }
824 */
825
826
827
828 //USED BY NEWORDEREMPTY.PL
829 function fetchSortDropbox(f) {
830     var  budgetId=f.budget_id.value;
831
832  for (i=1;i<=2;i++) {
833
834     var sort_dropbox = document.getElementById('sort'+i);
835     var url = '../acqui/fetch_sort_dropbox.pl?sort='+i+'&budget_id='+budgetId;
836
837     var xmlhttp = null;
838     xmlhttp = new XMLHttpRequest();
839     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
840         xmlhttp.overrideMimeType('text/xml');
841     }
842
843     xmlhttp.open('GET', url, false);
844     xmlhttp.send(null);
845
846     xmlhttp.onreadystatechange = function() {
847         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
848       // stupid JS...
849           } else {
850       // wait for the call to complete
851           }
852      };
853      // rc =  eval ( xmlhttp.responseText );
854     sort_dropbox.innerHTML  =  xmlhttp.responseText;
855  }
856 }
857
858
859
860
861
862
863
864 //USED BY NEWORDEREMPTY.PL
865 function totalExceedsBudget(budgetId, total) {
866
867     var xmlhttp = null;
868     xmlhttp = new XMLHttpRequest();
869     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
870         xmlhttp.overrideMimeType('text/xml');
871     }
872
873     var url = '../acqui/check_budget_total.pl?budget_id=' + budgetId + "&total=" + total;
874     xmlhttp.open('GET', url, false);
875     xmlhttp.send(null);
876
877     xmlhttp.onreadystatechange = function() {
878         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
879
880             actTotal = eval ( xmlhttp.responseText );
881
882                 if (  Math.abs(actTotal) < Math.abs(total)  ) {
883                 // if budget is to low :(
884                     return true ;
885             } else {
886                     return false;
887             }
888         }
889     }
890 }
891
892
893 //USED BY AQBUDGETS.TMPL
894 function budgetExceedsParent(budgetTotal, budgetId, newBudgetParent, periodID) {
895
896
897     var xmlhttp = null;
898     xmlhttp = new XMLHttpRequest();
899     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
900         xmlhttp.overrideMimeType('text/xml');
901     }
902
903 // make the call... yawn
904 //    var url = '../admin/check_parent_total.pl?budget_id=' + budgetId +   '&parent_id=' + newBudgetParent  + "&total=" + budgetTotal + "&period_id="+ periodID   ;
905
906
907     var url = '../admin/check_parent_total.pl?total=' + budgetTotal + "&period_id="+ periodID   ;
908
909 if (budgetId ) { url +=  '&budget_id=' + budgetId };
910 if ( newBudgetParent  ) { url +=  '&parent_id=' + newBudgetParent};
911
912
913     xmlhttp.open('GET', url, false);
914     xmlhttp.send(null);
915
916     xmlhttp.onreadystatechange = function() {
917           if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
918       // stupid JS...
919           } else {
920       // wait for the call to complete
921           }
922      };
923
924     var result = eval ( xmlhttp.responseText );
925
926      if (result == '1') {
927             return _("- Budget total exceeds parent allocation\n");
928      } else if (result == '2') {
929             return _("- Budget total exceeds period allocation\n");
930      } else  {
931              return false;
932      }
933 }
934
935
936
937
938 //USED BY AQBUDGETS.TMPL
939 function checkBudgetParent(budgetId, newBudgetParent) {
940     var xmlhttp = null;
941     xmlhttp = new XMLHttpRequest();
942     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
943         xmlhttp.overrideMimeType('text/xml');
944     }
945
946     var url = '../admin/check_budget_parent.pl?budget_id=' + budgetId + '&new_parent=' + newBudgetParent;
947     xmlhttp.open('GET', url, false);
948     xmlhttp.send(null);
949
950     xmlhttp.onreadystatechange = function() {
951           if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
952       // do something with the results
953           } else {
954       // wait for the call to complete
955           }
956      };
957
958      var result = eval ( xmlhttp.responseText );
959
960      if (result == '1') {
961             return _("- New budget-parent is beneath budget\n");
962 //     } else if (result == '2') {
963 //            return "- New budget-parent has insufficent funds\n";
964 //     } else  {
965 //              return false;
966      }
967 }
968