Bug 7088: (follow-up) AllowRenewalLimitOverride fix
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / additem.js
1 function addItem( node, unique_item_fields ) {
2     var index = $(node).closest("div").attr('id');
3     var current_qty = parseInt($("#quantity").val());
4     var max_qty;
5     if($("#quantity_to_receive").length != 0){
6         max_qty = parseInt($("#quantity_to_receive").val());
7     } else  {
8         max_qty = 99999;
9     }
10     if ( $("#items_list table").find('tr[idblock="' + index + '"]').length == 0 ) {
11         if ( current_qty < max_qty ) {
12             if ( current_qty < max_qty - 1 )
13                 cloneItemBlock(index, unique_item_fields);
14             addItemInList(index, unique_item_fields);
15             $("#" + index).find("input[name='buttonPlus']").val( (window.MSG_ADDITEM_JS_UPDATEITEM ) );
16             $("#"+ index).find("input[name='buttonPlusMulti']").remove();
17             $("#" + index).find("input[name='multiValue']").remove();
18             $("#quantity").val(current_qty + 1).change();
19         } else if ( current_qty >= max_qty ) {
20             alert(window.MSG_ADDITEM_JS_CANT_RECEIVE_MORE_ITEMS
21                 || "You can't receive any more items.");
22         }
23     } else {
24         if ( current_qty < max_qty )
25             cloneItemBlock(index, unique_item_fields);
26         var tr = constructTrNode(index);
27         $("#items_list table").find('tr[idblock="' + index + '"]:first').replaceWith(tr);
28     }
29     $("#" + index).hide();
30 }
31
32 function addMulti( count, node, unique_item_fields){
33     var index = $(node).closest("div").attr('id');
34     var countItemsBefore = $("#items_list tbody tr").length;
35     var current_qty = parseInt( $('#quantity').val(), 10 );
36     $("#procModal").modal('show');
37     $("#" + index).hide();
38     for(var i=0;i<count;i++){
39        cloneItemBlock(index, unique_item_fields, function(cloneIndex){
40             addItemInList(cloneIndex,unique_item_fields, function(){
41                     if( ($("#items_list tbody tr").length-countItemsBefore)==(count)){
42                         $("#multiValue").val('');
43                         $('#'+index).appendTo('#outeritemblock');
44                         $('#'+index).show();
45                         $('#'+index + ' #add_multiple_copies' ).css("visibility","hidden");
46                         $("#procModal").modal('hide');
47                     }
48             });
49             $("#" + cloneIndex).find("input[name='buttonPlus']").val( (window.MSG_ADDITEM_JS_UPDATEITEM ) );
50             $("#" + cloneIndex).find("input[name='buttonPlusMulti']").remove();
51             $("#" + cloneIndex).find("input[name='multiValue']").remove();
52             $("#" + cloneIndex).hide();
53             current_qty++;
54             $('#quantity').val( current_qty );
55        });
56     }
57 }
58
59
60 function checkCount(node, unique_item_fields){
61     var count = parseInt( $("#multiValue").val(), 10 );
62     if ( isNaN( count ) || count <=0) {
63         $("#multiCountModal").modal('show');
64     }
65     else{
66         addMulti( count, node, unique_item_fields);
67     }
68 }
69
70 function showItem(index) {
71     $("#outeritemblock").children("div").each(function(){
72         if ( $(this).attr('id') == index ) {
73             $(this).show();
74         } else {
75             if ( $("#items_list table").find('tr[idblock="' + $(this).attr('id') + '"]').length == 0 ) {
76                 $(this).remove();
77             } else {
78                 $(this).hide();
79             }
80         }
81     });
82 }
83
84 function constructTrNode(index, unique_item_fields) {
85     var fields = ['barcode', 'homebranch', 'holdingbranch', 'notforloan',
86         'restricted', 'location', 'itemcallnumber', 'copynumber',
87         'stocknumber', 'ccode', 'itype', 'materials', 'itemnotes'];
88
89     var result = "<tr idblock='" + index + "'>";
90     var edit_link = "<a href='#itemfieldset' style='text-decoration:none' onclick='showItem(\"" + index + "\");' class='btn btn-default btn-xs'><i class='fa fa-pencil'></i> "
91         + (window.MSG_ADDITEM_JS_EDIT || "Edit") + "</a>";
92     var del_link = "<a style='cursor:pointer' "
93         + "onclick='deleteItemBlock(this, \"" + index + "\", \"" + unique_item_fields + "\");' class='btn btn-default btn-xs'><i class='fa fa-trash'></i> "
94         + (window.MSG_ADDITEM_JS_DELETE || "Delete") + "</a>";
95     result += "<td class='actions'>" + edit_link + " " + del_link + "</td>";
96     for(i in fields) {
97         var field = fields[i];
98         var field_elt = $("#" + index)
99             .find("[name='kohafield'][value='items."+field+"']")
100             .prevAll("[name='field_value']")[0];
101         var field_value;
102         if($(field_elt).is('select')) {
103             field_value = $(field_elt).find("option:selected").text();
104         } else {
105             field_value = $(field_elt).val();
106         }
107         if (field_value == undefined) {
108             field_value = '';
109         }
110         result += "<td>" + field_value + "</td>";
111     }
112     result += "</tr>";
113
114     return result;
115 }
116
117 function addItemInList(index, unique_item_fields, callback) {
118     $("#items_list").show();
119     var tr = constructTrNode(index, unique_item_fields);
120     $("#items_list table tbody").append(tr);
121     if (typeof callback === "function"){
122         callback();
123     }
124 }
125
126 function deleteItemBlock(node_a, index, unique_item_fields) {
127     $("#" + index).remove();
128     var current_qty = parseInt($("#quantity").val());
129     var max_qty;
130     if($("#quantity_to_receive").length != 0) {
131         max_qty = parseInt($("#quantity_to_receive").val());
132     } else {
133         max_qty = 99999;
134     }
135     $("#quantity").val(current_qty - 1).change();
136     $(node_a).parents('tr').remove();
137     if(current_qty - 1 == 0)
138         $("#items_list").hide();
139
140     if ( $("#quantity").val() <= max_qty - 1) {
141         if ( $("#outeritemblock").children("div :visible").length == 0 ) {
142             $("#outeritemblock").children("div:last").show();
143         }
144     }
145     if ( $("#quantity").val() == 0 && $("#outeritemblock > div").length == 0) {
146         cloneItemBlock(0, unique_item_fields);
147     }
148 }
149
150 function cloneItemBlock(index, unique_item_fields, callback) {
151     var original;
152     if(index) {
153         original = $("#" + index); //original <div>
154     }
155     var dont_copy_fields = new Array();
156     if(unique_item_fields) {
157         var dont_copy_fields = unique_item_fields.split(' ');
158         for(i in dont_copy_fields) {
159             dont_copy_fields[i] = "items." + dont_copy_fields[i];
160         }
161     }
162
163     $.ajax({
164         url: "/cgi-bin/koha/services/itemrecorddisplay.pl",
165         dataType: 'html',
166         data: {
167             frameworkcode: 'ACQ'
168         },
169         success: function(data, textStatus, jqXHR) {
170             /* Create the item block */
171             var random = Math.floor(Math.random()*100000); // get a random itemid.
172             var clone = $("<div/>", { id: 'itemblock'+random });
173             $("#outeritemblock").append(clone);
174             $(clone).append(data);
175             /* Change all itemid fields value */
176             $(clone).find("input[name='itemid']").each(function(){
177                 $(this).val(random);
178             });
179             /* Add buttons + and Clear */
180             var buttonPlus = "<fieldset class=\"action\">";
181                 buttonPlus += '<input type="button" class="addItemControl" name="buttonPlus" style="cursor:pointer; margin:0 1em;" onclick="addItem(this,\'' + unique_item_fields + '\')" value="' + (window.MSG_ADDITEM_JS_ADDITEM || 'Add item')+ '" />';
182                 buttonPlus += '<input type="button" class="addItemControl cancel" name="buttonClear" style="cursor:pointer;" onclick="clearItemBlock(this)" value="' + (window.MSG_ADDITEM_JS_CLEAR || 'Clear')+ '" />';
183                 buttonPlus += '<input type="button" class="addItemControl" name="buttonPlusMulti" onclick="javascript:this.nextSibling.style.display=\'inline\'; return false;" style="cursor:pointer; margin:0 1em;" value="' + (window.MSG_ADDITEM_JS_ADDMULTI || 'Add multiple items')+ '" />';
184                 buttonPlus += '<span id="add_multiple_copies" style="display:none">'
185                             +     '<input type="number" class="addItemControl" id="multiValue" name="multiValue" placeholder="'+window.MSG_ADDITEM_JS_MULTIVAL+'" />'
186                             +     '<input type="button" class="addItemControl" name=buttonAddMulti" style="cursor:pointer; margin:0 1em;" onclick="checkCount( this ,\'' + unique_item_fields + '\')" value="' + (window.MSG_ADDITEM_JS_SUBMITMULTI || 'Add') + '" />'
187                             +     '<div class="dialog message">' + window.MSG_ADDITEM_JS_MULTI_UNIQUE_NOTE + '</div>'
188                             + '</span>';
189                 buttonPlus += "</fieldset>";
190             $(clone).append(buttonPlus);
191             /* Copy values from the original block (input) */
192             $(original).find("input[name='field_value']").each(function(){
193                 var kohafield = $(this).siblings("input[name='kohafield']").val();
194                 if($(this).val() && $.inArray(kohafield,dont_copy_fields) == -1) {
195                     $(this).parent("div").attr("id").match(/^(subfield.)/);
196                     var id = RegExp.$1;
197                     var value = $(this).val();
198                     $(clone).find("div[id^='"+id+"'] input[name='field_value']").val(value);
199                 }
200             });
201             /* Copy values from the original block (select) */
202             $(original).find("select[name='field_value']").each(function(){
203                 var kohafield = $(this).siblings("input[name='kohafield']").val();
204                 if($(this).val() && $.inArray(kohafield,dont_copy_fields) == -1) {
205                     $(this).parent("div").attr("id").match(/^(subfield.)/);
206                     var id = RegExp.$1;
207                     var value = $(this).val();
208                     $(clone).find("div[id^='"+id+"'] select[name='field_value']").val(value);
209                 }
210             });
211
212             if (typeof callback === "function"){
213                 var cloneIndex = "itemblock"+random;
214                 callback(cloneIndex);
215             }
216             BindPluginEvents(data);
217         }
218     });
219 }
220
221 function BindPluginEvents(data) {
222 // the script tag in data for plugins contains a document ready that binds
223 // the events for the plugin
224 // when we append, this code does not get executed anymore; so we do it here
225     var events= data.match(/BindEventstag_\d+_subfield_._\d+/g);
226     if ( events == null ) return;
227     for(var i=0; i<events.length; i++) {
228         window[events[i]]();
229         if( i<events.length-1 && events[i]==events[i+1] ) { i++; }
230             // normally we find the function name twice
231     }
232 }
233
234 function clearItemBlock(node) {
235     var index = $(node).closest("div").attr('id');
236     var block = $("#"+index);
237     $(block).find("input[type='text']").each(function(){
238         $(this).val("");
239     });
240     $(block).find("select").each(function(){
241         $(this).find("option:first").attr("selected", true);
242     });
243 }
244
245 function check_additem(unique_item_fields) {
246     var success = true;
247     var data = new Object();
248     data['field'] = new Array();
249     data['value'] = new Array();
250     var array_fields = unique_item_fields.split(' ');
251     $(".order_error").empty(); // Clear error div
252
253     // Check if a value is duplicated in form
254     for ( field in array_fields ) {
255         var fieldname = array_fields[field];
256         if (fieldname == '') {
257             continue;
258         }
259         var values = new Array();
260         $("[name='kohafield'][value='items."+ fieldname +"']").each(function(){
261             var input = $(this).prevAll("input[name='field_value']")[0];
262             if($(input).val()) {
263                 values.push($(input).val());
264                 data['field'].push(fieldname);
265                 data['value'].push($(input).val());
266             }
267         });
268
269         var sorted_arr = values.sort();
270         for (var i = 0; i < sorted_arr.length - 1; i += 1) {
271             if (sorted_arr[i + 1] == sorted_arr[i]) {
272                 $(".order_error").append(
273                     fieldname + " '" + sorted_arr[i] + "' "
274                     + (window.MSG_ADDITEM_JS_IS_DUPLICATE || "is duplicated")
275                     + "<br/>");
276                 success = false;
277             }
278         }
279     }
280
281     // If there is a duplication, we raise an error
282     if ( success == false ) {
283         $(".order_error").show();
284         return false;
285     }
286
287     $.ajax({
288         url: '/cgi-bin/koha/acqui/check_uniqueness.pl',
289         async: false,
290         dataType: 'json',
291         data: data,
292         success: function(data) {
293             for (field in data) {
294                 success = false;
295                 for (var i=0; i < data[field].length; i++) {
296                     var value = data[field][i];
297                     $(".order_error").append(
298                         field + " '" + value + "' "
299                         + (window.MSG_ADDITEM_JS_ALREADY_EXISTS_IN_DB
300                             || "already exists in database")
301                         + "<br />"
302                     );
303                 }
304             }
305         }
306     });
307
308     if ( success == false ) {
309         $(".order_error").show();
310     }
311     return success;
312 }
313