Bug 32147: Capitalization: E-Resource management
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / acq.js
1 /* global confirmDelete */
2 /* exported uncheckbox isNotNull isNull isNum log calcTotalRow autoFillRow messenger updateCosts calcNewsuggTotal getAuthValueDropbox totalExceedsBudget budgetExceedsParent checkBudgetParent hideColumn showColumn showAllColumns hideAllColumns */
3
4 //=======================================================================
5 //input validation:
6 // acqui/uncertainprice.tmpl uses this
7 function uncheckbox(form, field) {
8     var price = new Number(form.elements['price' + field].value);
9     var tmpprice = "";
10     var errmsg = __("ERROR: Price is not a valid number, please check the price and try again!");
11     if (isNaN(price)) {
12         alert(errmsg);
13         for(var i=0; i<form.elements['price' + field].value.length; ++i) {
14             price = new Number(form.elements['price' + field].value[i]);
15             if(! isNaN(price) || form.elements['price' + field].value[i] == ".") {
16                 tmpprice += form.elements['price' + field].value[i];
17             }
18         }
19         form.elements['price' + field].value = tmpprice;
20         return false;
21     }
22     form.elements['uncertainprice' + field].checked = false;
23     return true;
24 }
25
26 // returns false if value is empty
27 function isNotNull(f,noalert) {
28     if (f.value.length ==0) {
29         return false;
30     }
31     return true;
32 }
33
34 function isNull(f,noalert) {
35     if (f.value.length > 0) {
36         return false;
37     }
38     return true;
39 }
40
41 //Function returns false if v is not a number (if maybenull is 0, it also returns an error if the number is 0)
42 function isNum(v,maybenull) {
43     var n = new Number(v.value);
44     if (isNaN(n)) {
45         return false;
46     }
47     if (maybenull==0 && v.value=='') {
48
49
50     return false;
51     }
52     return true;
53 }
54
55
56 //a logging function (a bit buggy, might open millions of log pages when initializing, but works fine after...
57 function log(message) {
58     if (!log.window_ || log.window_.closed) {
59         var win = window.open("", null, "width=400,height=200," +
60                             "scrollbars=yes,resizable=yes,status=no," +
61                             "location=no,menubar=no,toolbar=no");
62         if (!win) return;
63         var doc = win.document;
64         doc.write("<html><head><title>Debug Log</title></head>" +
65                 "<body></body></html>");
66         doc.close();
67         log.window_ = win;
68     }
69     var logLine = log.window_.document.createElement("div");
70     logLine.appendChild(log.window_.document.createTextNode(message));
71     log.window_.document.body.appendChild(logLine);
72 }
73
74 //=======================================================================
75 function getElementsByClass( searchClass, domNode, tagName) {
76     if (domNode == null) domNode = document;
77     if (tagName == null) tagName = '*';
78     var el = new Array();
79     var tags = domNode.getElementsByTagName(tagName);
80     var tcl = " "+searchClass+" ";
81     for(i=0,j=0; i<tags.length; i++) {
82         var test = " " + tags[i].className + " ";
83         if (test.indexOf(tcl) != -1)
84             el[j++] = tags[i];
85     }
86     return el;
87 }
88
89
90 function calcTotalRow(cell) {
91
92     var string = cell.name;
93     var pos = string.indexOf(",", 0);
94     var bud_id = string.substring(0, pos);
95     var val1 =    cell.value;
96     var remainingTotal =   document.getElementById("budget_est_"+bud_id);
97     var remainingNew =0;
98     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
99     var arr =  getElementsByClass(cell.className);
100
101     budgetTotal   =  budgetTotal.replace(/\,/, "");
102
103 //percent strip and convert
104     if ( val1.match(/\%/) )   {
105         val1 = val1.replace(/\%/, "");
106         cell.value =    (val1 / 100) *  Math.abs(budgetTotal ) ;
107     }
108
109     for ( var i=0, len=arr.length; i<len; ++i ){
110         remainingNew   +=   Math.abs(arr[i].value);
111     }
112
113     var cc = new Number(cell.value);
114     cell.value =  cc.toFixed(2); // TIDYME...
115     remainingNew    =    Math.abs( budgetTotal  ) -  remainingNew   ;
116
117     if ( remainingNew  == 0)  {
118         remainingTotal.style.color = 'black';
119     }
120     else if ( remainingNew   > 0   )       {
121         remainingTotal.style.color = 'green';
122     } else  {    // if its negative, make it red..
123         remainingTotal.style.color = 'red';
124     }
125
126     remainingTotal.textContent  = remainingNew.toFixed(2) ;
127 }
128
129 function autoFillRow(bud_id) {
130
131     var remainingTotal =   document.getElementById("budget_est_"+bud_id);
132     var remainingNew = new Number;
133     var budgetTotal  =  document.getElementById("budget_tot_"+bud_id ).textContent;
134     var arr =  getElementsByClass("plan_entry_" + bud_id);
135
136     budgetTotal   =  budgetTotal.replace(/\,/, "");
137     var qty = new Number;
138 // get the totals
139     var novalueArr = new Array();
140     for ( var i=0, len=arr.length; i<len; ++i ) {
141         remainingNew   +=   Math.abs (arr[i].value );
142
143         if ( arr[i].value == 0 ) {
144             novalueArr[qty] = arr[i];
145             qty += 1;
146         }
147     }
148
149     remainingNew    =    Math.abs( budgetTotal) -  remainingNew   ;
150     var newCell = new Number (remainingNew / qty);
151     var rest = new Number (remainingNew - (newCell.toFixed(2) * (novalueArr.length - 1)));
152
153     for (var i = 0; i<novalueArr.length; ++i) {
154          if (i == novalueArr.length - 1) {
155              novalueArr[i].value = rest.toFixed(2);
156          }else {
157              novalueArr[i].value = newCell.toFixed(2);
158         }
159     }
160
161     remainingTotal.textContent = '0.00' ;
162     remainingTotal.style.color = 'black';
163 }
164
165
166 function messenger(X,Y,etc){    // FIXME: unused?
167     win=window.open("","mess","height="+X+",width="+Y+",screenX=150,screenY=0");
168     win.focus();
169     win.document.close();
170     win.document.write("<body link='#333333' bgcolor='#ffffff' text='#000000'><font size='2'><p><br />");
171     win.document.write(etc);
172     win.document.write("<center><form><input type=button onclick='self.close()' value='Close'></form></center>");
173     win.document.write("</font></body></html>");
174 }
175
176
177 //=======================================================================
178
179 //  NEXT BLOCK IS USED BY NEWORDERBEMPTY
180
181 function updateCosts(){
182     var quantity = new Number($("#quantity").val());
183     var discount = new Number($("#discount").val());
184     var listprice   =  new Number($("#listprice").val());
185     var currcode = new String($("#currency").val());
186     var exchangerate =  new Number($("#currency_rate_"+currcode).val());
187     var gst_on=false;
188
189     var rrp   = new Number(listprice*exchangerate);
190     var rep   = new Number(listprice*exchangerate);
191     var ecost = rrp;
192     if ( 100-discount != 100 ) { //Prevent rounding issues if no discount
193         ecost = new Number(Math.floor(rrp * (100 - discount )) / 100);
194     }
195     var total =  new Number( ecost * quantity);
196     $("#rrp").val(rrp.toFixed(2));
197     $("#replacementprice").val(rep.toFixed(2));
198     $("#ecost").val(ecost.toFixed(2));
199     $("#total").val(total.toFixed(2));
200     $("listprice").val(listprice.toFixed(2));
201
202     return true;
203 }
204
205 // Calculates total amount in a suggestion
206
207 function calcNewsuggTotal(){
208     //collect values
209     var quantity = Number(document.getElementById('quantity').value);
210     var currcode = String(document.getElementById('currency').value);
211     var price   =  Number(document.getElementById('price').value);
212     var exchangerate =  Number(document.getElementById('currency_rate_'+currcode).value);
213
214     var total =  Number(quantity*price*exchangerate);
215
216     document.getElementById('total').value = total.toFixed(2);
217     document.getElementById('price').value =  price.toFixed(2);
218     return true;
219 }
220
221 function getAuthValueDropbox( name, cat, destination, selected ) {
222     if ( typeof(selected) == 'undefined' ) {
223         selected = "";
224     }
225     if (cat == null || cat == "") {
226         $(destination).replaceWith(' <input type="text" name="' + name + '" value="' + selected + '" />' );
227         return;
228     }
229     $.ajax({
230         url: "/cgi-bin/koha/acqui/ajax-getauthvaluedropbox.pl",
231         data: {
232             name: name,
233             category: cat,
234             default: selected
235         },
236         async: false,
237         success: function(data){
238             if(data === "0"){
239                 $(destination).replaceWith(' <input type="text" name="' + name + '" value="' + selected + '" />' );
240             }else{
241                 $(destination).replaceWith(data);
242             }
243         }
244     });
245 }
246
247 //USED BY NEWORDEREMPTY.PL
248 function totalExceedsBudget(budgetId, total) {
249
250     var xmlhttp = null;
251     xmlhttp = new XMLHttpRequest();
252     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
253         xmlhttp.overrideMimeType('text/xml');
254     }
255
256     var url = '../acqui/check_budget_total.pl?budget_id=' + budgetId + "&total=" + total;
257     xmlhttp.open('GET', url, false);
258     xmlhttp.send(null);
259
260     xmlhttp.onreadystatechange = function() {
261         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
262
263             actTotal = eval ( xmlhttp.responseText );
264
265             if (  Math.abs(actTotal) < Math.abs(total)  ) {
266             // if budget is to low :(
267                 return true ;
268             } else {
269                 return false;
270             }
271         }
272     }
273 }
274
275
276 //USED BY AQBUDGETS.TMPL
277 function budgetExceedsParent(budgetTotal, budgetId, newBudgetParent, periodID) {
278
279
280     var xmlhttp = null;
281     xmlhttp = new XMLHttpRequest();
282     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
283         xmlhttp.overrideMimeType('text/xml');
284     }
285
286 // make the call... yawn
287 //    var url = '../admin/check_parent_total.pl?budget_id=' + budgetId +   '&parent_id=' + newBudgetParent  + "&total=" + budgetTotal + "&period_id="+ periodID   ;
288
289
290     var url = '../admin/check_parent_total.pl?total=' + budgetTotal + "&period_id="+ periodID   ;
291
292 if (budgetId ) { url +=  '&budget_id=' + budgetId };
293 if ( newBudgetParent  ) { url +=  '&parent_id=' + newBudgetParent};
294
295
296     xmlhttp.open('GET', url, false);
297     xmlhttp.send(null);
298
299     xmlhttp.onreadystatechange = function() {
300         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
301     // stupid JS...
302         } else {
303     // wait for the call to complete
304         }
305     };
306
307     var result = eval ( xmlhttp.responseText );
308
309     if (result == '1') {
310             return "- " + __("Fund amount exceeds parent allocation") + "\n";
311     } else if (result == '2') {
312             return "- " + __("Fund amount exceeds period allocation") + "\n";
313     } else  {
314             return false;
315     }
316 }
317
318
319
320
321 //USED BY AQBUDGETS.TMPL
322 function checkBudgetParent(budgetId, newBudgetParent) {
323     var xmlhttp = null;
324     xmlhttp = new XMLHttpRequest();
325     if ( typeof xmlhttp.overrideMimeType != 'undefined') {
326         xmlhttp.overrideMimeType('text/xml');
327     }
328
329     var url = '../admin/check_budget_parent.pl?budget_id=' + budgetId + '&new_parent=' + newBudgetParent;
330     xmlhttp.open('GET', url, false);
331     xmlhttp.send(null);
332
333     xmlhttp.onreadystatechange = function() {
334         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
335     // do something with the results
336         } else {
337     // wait for the call to complete
338         }
339     };
340
341     var result = eval ( xmlhttp.responseText );
342
343     if (result == '1') {
344             return "- " + __("New budget-parent is beneath budget") + "\n";
345 //     } else if (result == '2') {
346 //            return "- New budget-parent has insufficent funds\n";
347 //     } else  {
348 //              return false;
349     }
350 }
351
352 function hideColumn(num) {
353     $("#hideall,#showall").prop("checked", false).parent().removeClass("selected");
354     $("#"+num).parent().removeClass("selected");
355     var hide = Number(num.replace("col","")) + 2;
356     // hide header and cells matching the index
357     $("#plan td:nth-child("+hide+"),#plan th:nth-child("+hide+")").toggle();
358 }
359
360 function showColumn(num){
361     $("#hideall").prop("checked", false).parent().removeClass("selected");
362     $("#"+num).parent().addClass("selected");
363     // set the index of the table column to hide
364     show = Number(num.replace("col","")) + 2;
365     // hide header and cells matching the index
366     $("#plan td:nth-child("+show+"),#plan th:nth-child("+show+")").toggle();
367 }
368
369 function showAllColumns(){
370     $("#selections").find("input:checkbox").each(function () {
371         $(this).prop("checked", true);
372     });
373     $("#selections span").addClass("selected");
374     $("#plan td:nth-child(2),#plan tr th:nth-child(2)").nextAll().show();
375     $("#hideall").prop("checked", false).parent().removeClass("selected");
376 }
377 function hideAllColumns(){
378     var allCols = $("#plan th").length;
379     $("#selections").find("input:checkbox").each(function () {
380         $(this).prop("checked", false);
381     });
382     $("#selections span").removeClass("selected");
383     $("#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
384     $("#hideall").prop("checked", true).parent().addClass("selected");
385 }
386
387 $(document).ready(function(){
388     $("#deletesupplier").on("click", function(){
389         confirmDelete(__("Are you sure you want to delete this vendor?") );
390     });
391 });