Warnung Währungs-/Kurswechsel: Text u. Übersetzung angepasst
[kivitendo-erp.git] / js / kivi.Order.js
1 namespace('kivi.Order', function(ns) {
2   ns.check_cv = function() {
3     if ($('#type').val() == 'sales_order' || $('#type').val() == 'sales_quotation') {
4       if ($('#order_customer_id').val() === '') {
5         alert(kivi.t8('Please select a customer.'));
6         return false;
7       }
8     } else  {
9       if ($('#order_vendor_id').val() === '') {
10         alert(kivi.t8('Please select a vendor.'));
11         return false;
12       }
13     }
14     return true;
15   };
16
17   ns.check_duplicate_parts = function(question) {
18     var id_arr = $('[name="order.orderitems[].parts_id"]').map(function() { return this.value; }).get();
19
20     var i, obj = {}, pos = [];
21
22     for (i = 0; i < id_arr.length; i++) {
23       var id = id_arr[i];
24       if (obj.hasOwnProperty(id)) {
25         pos.push(i + 1);
26       }
27       obj[id] = 0;
28     }
29
30     if (pos.length > 0) {
31       question = question || kivi.t8("Do you really want to save?");
32       return confirm(kivi.t8("There are duplicate parts at positions") + "\n"
33                      + pos.join(', ') + "\n"
34                      + question);
35     }
36     return true;
37   };
38
39   ns.check_valid_reqdate = function() {
40     if ($('#order_reqdate_as_date').val() === '') {
41       alert(kivi.t8('Please select a delivery date.'));
42       return false;
43     } else {
44       return true;
45     }
46   };
47
48   ns.save = function(action, warn_on_duplicates, warn_on_reqdate) {
49     if (!ns.check_cv()) return;
50     if (warn_on_duplicates && !ns.check_duplicate_parts()) return;
51     if (warn_on_reqdate    && !ns.check_valid_reqdate())   return;
52
53     var data = $('#order_form').serializeArray();
54     data.push({ name: 'order.language_id', value: $('#language_id').val() }); // language from print options
55     data.push({ name: 'action', value: 'Order/' + action });
56
57     $.post("controller.pl", data, kivi.eval_json_result);
58   };
59
60   ns.delete_order = function() {
61     var data = $('#order_form').serializeArray();
62     data.push({ name: 'action', value: 'Order/delete' });
63
64     $.post("controller.pl", data, kivi.eval_json_result);
65   };
66
67   ns.show_print_options = function(warn_on_duplicates) {
68     if (!ns.check_cv()) return;
69     if (warn_on_duplicates && !ns.check_duplicate_parts(kivi.t8("Do you really want to print?"))) return;
70
71     kivi.popup_dialog({
72       id: 'print_options',
73       dialog: {
74         title: kivi.t8('Print options'),
75         width:  800,
76         height: 300
77       }
78     });
79   };
80
81   ns.print = function() {
82     $('#print_options').dialog('close');
83
84     var data = $('#order_form').serializeArray();
85     data = data.concat($('#print_options_form').serializeArray());
86     data.push({ name: 'order.language_id', value: $('#language_id').val() }); // language from print options
87     data.push({ name: 'action', value: 'Order/print' });
88
89     $.post("controller.pl", data, kivi.eval_json_result);
90   };
91
92   ns.email = function(warn_on_duplicates) {
93     if (warn_on_duplicates && !ns.check_duplicate_parts(kivi.t8("Do you really want to send by mail?"))) return;
94     if (!ns.check_cv()) return;
95
96     var data = $('#order_form').serializeArray();
97     data.push({ name: 'order.language_id', value: $('#language_id').val() }); // language from print options
98     data.push({ name: 'action', value: 'Order/show_email_dialog' });
99
100     $.post("controller.pl", data, kivi.eval_json_result);
101   };
102
103   var email_dialog;
104
105   ns.setup_send_email_dialog = function() {
106     kivi.SalesPurchase.show_all_print_options_elements();
107     kivi.SalesPurchase.show_print_options_elements([ 'sendmode', 'media', 'copies', 'remove_draft' ], false);
108
109     $('#print_options_form table').first().remove().appendTo('#email_form_print_options');
110
111     var to_focus = $('#email_form_to').val() === '' ? 'to' : 'subject';
112     $('#email_form_' + to_focus).focus();
113   };
114
115   ns.finish_send_email_dialog = function() {
116     kivi.SalesPurchase.show_all_print_options_elements();
117
118     $('#email_form_print_options table').first().remove().prependTo('#print_options_form');
119     return true;
120   };
121
122   ns.show_email_dialog = function(html) {
123     var id            = 'send_email_dialog';
124     var dialog_params = {
125       id:     id,
126       width:  800,
127       height: 600,
128       title:  kivi.t8('Send email'),
129       modal:  true,
130       beforeClose: kivi.Order.finish_send_email_dialog,
131       close: function(event, ui) {
132         email_dialog.remove();
133       }
134     };
135
136     $('#' + id).remove();
137
138     email_dialog = $('<div style="display:none" id="' + id + '"></div>').appendTo('body');
139     email_dialog.html(html);
140     email_dialog.dialog(dialog_params);
141
142     kivi.Order.setup_send_email_dialog();
143
144     $('.cancel').click(ns.close_email_dialog);
145
146     return true;
147   };
148
149   ns.send_email = function() {
150     var data = $('#order_form').serializeArray();
151     data = data.concat($('[name^="email_form."]').serializeArray());
152     data = data.concat($('[name^="print_options."]').serializeArray());
153     data.push({ name: 'order.language_id', value: $('#language_id').val() }); // language from print options
154     data.push({ name: 'action', value: 'Order/send_email' });
155     $.post("controller.pl", data, kivi.eval_json_result);
156   };
157
158   ns.close_email_dialog = function() {
159     email_dialog.dialog("close");
160   };
161
162   ns.set_number_in_title = function(elt) {
163     $('#nr_in_title').html($(elt).val());
164   };
165
166   ns.reload_cv_dependent_selections = function() {
167     var data = $('#order_form').serializeArray();
168     data.push({ name: 'action', value: 'Order/customer_vendor_changed' });
169
170     $.post("controller.pl", data, kivi.eval_json_result);
171   };
172
173   ns.reformat_number = function(event) {
174     $(event.target).val(kivi.format_amount(kivi.parse_amount($(event.target).val()), -2));
175   };
176
177   ns.update_exchangerate = function(event) {
178     var rate_input = $('#order_exchangerate_as_null_number');
179     rate_input.prop('disabled', true);
180
181     var data = $('#order_form').serializeArray();
182     data.push({ name: 'action', value: 'Order/update_exchangerate' });
183
184     $.ajax({
185       url: 'controller.pl',
186       data: data,
187       method: 'POST',
188       dataType: 'json',
189       success: function(data){
190         if (!data.is_standard) {
191           $('#currency_name').text(data.currency_name);
192           var rate_text = $('#exchangerate_text');
193           if (data.exchangerate) {
194             rate_text.text(data.exchangerate);
195             rate_input.hide();
196           } else {
197             rate_text.text('');
198             rate_input.prop('disabled', false);
199             rate_input.show().val(0);
200           }
201           $('#exchangerate_settings').show();
202         } else {
203           $('#exchangerate_settings').hide();
204         }
205         if ($('#order_currency_id').val() != $('#old_currency_id').val() ||
206             !data.is_standard && data.exchangerate != $('#old_exchangerate').val()) {
207           kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
208         }
209         $('#old_currency_id').val($('#order_currency_id').val());
210         $('#old_exchangerate').val(data.exchangerate);
211       }
212     });
213   };
214
215   ns.exchangerate_changed = function(event) {
216     if (kivi.parse_amount($('#order_exchangerate_as_null_number').val()) != kivi.parse_amount($('#old_exchangerate').val())) {
217       kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
218       $('#old_exchangerate').val($('#order_exchangerate_as_null_number').val());
219     }
220   };
221
222   ns.recalc_amounts_and_taxes = function() {
223     var data = $('#order_form').serializeArray();
224     data.push({ name: 'action', value: 'Order/recalc_amounts_and_taxes' });
225
226     $.post("controller.pl", data, kivi.eval_json_result);
227   };
228
229   ns.unit_change = function(event) {
230     var row           = $(event.target).parents("tbody").first();
231     var item_id_dom   = $(row).find('[name="orderitem_ids[+]"]');
232     var sellprice_dom = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
233     var select_elt    = $(row).find('[name="order.orderitems[].unit"]');
234
235     var oldval = $(select_elt).data('oldval');
236     $(select_elt).data('oldval', $(select_elt).val());
237
238     var data = $('#order_form').serializeArray();
239     data.push({ name: 'action',           value: 'Order/unit_changed'     },
240               { name: 'item_id',          value: item_id_dom.val()        },
241               { name: 'old_unit',         value: oldval                   },
242               { name: 'sellprice_dom_id', value: sellprice_dom.attr('id') });
243
244     $.post("controller.pl", data, kivi.eval_json_result);
245   };
246
247   ns.update_sellprice = function(item_id, price_str) {
248     var row       = $('#item_' + item_id).parents("tbody").first();
249     var price_elt = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
250     var html_elt  = $(row).find('[name="sellprice_text"]');
251     price_elt.val(price_str);
252     html_elt.html(price_str);
253   };
254
255   ns.load_second_row = function(row) {
256     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
257     var div_elt     = $(row).find('[name="second_row"]');
258
259     if ($(div_elt).data('loaded') == 1) {
260       return;
261     }
262     var data = $('#order_form').serializeArray();
263     data.push({ name: 'action',     value: 'Order/load_second_rows' },
264               { name: 'item_ids[]', value: item_id_dom.val()        });
265
266     $.post("controller.pl", data, kivi.eval_json_result);
267   };
268
269   ns.load_all_second_rows = function() {
270     var rows = $('.row_entry').filter(function(idx, elt) {
271       return $(elt).find('[name="second_row"]').data('loaded') != 1;
272     });
273
274     var item_ids = $.map(rows, function(elt) {
275       var item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
276       return { name: 'item_ids[]', value: item_id };
277     });
278
279     if (item_ids.length == 0) {
280       return;
281     }
282
283     var data = $('#order_form').serializeArray();
284     data.push({ name: 'action', value: 'Order/load_second_rows' });
285     data = data.concat(item_ids);
286
287     $.post("controller.pl", data, kivi.eval_json_result);
288   };
289
290   ns.hide_second_row = function(row) {
291     $(row).children().not(':first').hide();
292     $(row).data('expanded', 0);
293     var elt = $(row).find('.expand');
294     elt.attr('src', "image/expand.svg");
295     elt.attr('alt', kivi.t8('Show details'));
296     elt.attr('title', kivi.t8('Show details'));
297   };
298
299   ns.show_second_row = function(row) {
300     $(row).children().not(':first').show();
301     $(row).data('expanded', 1);
302     var elt = $(row).find('.expand');
303     elt.attr('src', "image/collapse.svg");
304     elt.attr('alt', kivi.t8('Hide details'));
305     elt.attr('title', kivi.t8('Hide details'));
306   };
307
308   ns.toggle_second_row = function(row) {
309     if ($(row).data('expanded') == 1) {
310       ns.hide_second_row(row);
311     } else {
312       ns.show_second_row(row);
313     }
314   };
315
316   ns.init_row_handlers = function() {
317     kivi.run_once_for('.recalc', 'on_change_recalc', function(elt) {
318       $(elt).change(ns.recalc_amounts_and_taxes);
319     });
320
321     kivi.run_once_for('.reformat_number', 'on_change_reformat', function(elt) {
322       $(elt).change(ns.reformat_number);
323     });
324
325     kivi.run_once_for('.unitselect', 'on_change_unit_with_oldval', function(elt) {
326       $(elt).data('oldval', $(elt).val());
327       $(elt).change(ns.unit_change);
328     });
329
330     kivi.run_once_for('.row_entry', 'on_kbd_click_show_hide', function(elt) {
331       $(elt).keydown(function(event) {
332         var row;
333         if (event.keyCode == 40 && event.shiftKey === true) {
334           // shift arrow down
335           event.preventDefault();
336           row = $(event.target).parents(".row_entry").first();
337           ns.load_second_row(row);
338           ns.show_second_row(row);
339           return false;
340         }
341         if (event.keyCode == 38 && event.shiftKey === true) {
342           // shift arrow up
343           event.preventDefault();
344           row = $(event.target).parents(".row_entry").first();
345           ns.hide_second_row(row);
346           return false;
347         }
348       });
349     });
350
351     kivi.run_once_for('.expand', 'expand_second_row', function(elt) {
352       $(elt).click(function(event) {
353         event.preventDefault();
354         var row = $(event.target).parents(".row_entry").first();
355         ns.load_second_row(row);
356         ns.toggle_second_row(row);
357         return false;
358       })
359     });
360
361   };
362
363   ns.redisplay_line_values = function(is_sales, data) {
364     $('.row_entry').each(function(idx, elt) {
365       $(elt).find('[name="linetotal"]').html(data[idx][0]);
366       if (is_sales && $(elt).find('[name="second_row"]').data('loaded') == 1) {
367         var mt = data[idx][1];
368         var mp = data[idx][2];
369         var h  = '<span';
370         if (mt[0] === '-') h += ' class="plus0"';
371         h += '>' + mt + '&nbsp;&nbsp;' + mp + '%';
372         h += '</span>';
373         $(elt).find('[name="linemargin"]').html(h);
374       }
375     });
376   };
377
378   ns.redisplay_cvpartnumbers = function(data) {
379     $('.row_entry').each(function(idx, elt) {
380       $(elt).find('[name="cvpartnumber"]').html(data[idx][0]);
381     });
382   };
383
384   ns.renumber_positions = function() {
385     $('.row_entry [name="position"]').each(function(idx, elt) {
386       $(elt).html(idx+1);
387     });
388     $('.row_entry').each(function(idx, elt) {
389       $(elt).data("position", idx+1);
390     });
391   };
392
393   ns.reorder_items = function(order_by) {
394     var dir = $('#' + order_by + '_header_id a img').attr("data-sort-dir");
395     $('#row_table_id thead a img').remove();
396
397     var src;
398     if (dir == "1") {
399       dir = "0";
400       src = "image/up.png";
401     } else {
402       dir = "1";
403       src = "image/down.png";
404     }
405
406     $('#' + order_by + '_header_id a').append('<img border=0 data-sort-dir=' + dir + ' src=' + src + ' alt="' + kivi.t8('sort items') + '">');
407
408     var data = $('#order_form').serializeArray();
409     data.push({ name: 'action',   value: 'Order/reorder_items' },
410               { name: 'order_by', value: order_by              },
411               { name: 'sort_dir', value: dir                   });
412
413     $.post("controller.pl", data, kivi.eval_json_result);
414   };
415
416   ns.redisplay_items = function(data) {
417     var old_rows = $('.row_entry').detach();
418     var new_rows = [];
419     $(data).each(function(idx, elt) {
420       new_rows.push(old_rows[elt.old_pos - 1]);
421     });
422     $(new_rows).appendTo($('#row_table_id'));
423     ns.renumber_positions();
424   };
425
426   ns.get_insert_before_item_id = function(wanted_pos) {
427     if (wanted_pos === '') return;
428
429     var insert_before_item_id;
430     // selection by data does not seem to work if data is changed at runtime
431     // var elt = $('.row_entry [data-position="' + wanted_pos + '"]');
432     $('.row_entry').each(function(idx, elt) {
433       if ($(elt).data("position") == wanted_pos) {
434         insert_before_item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
435         return false;
436       }
437     });
438
439     return insert_before_item_id;
440   };
441
442   ns.add_item = function() {
443     if ($('#add_item_parts_id').val() === '') return;
444     if (!ns.check_cv()) return;
445
446     $('#row_table_id thead a img').remove();
447
448     var insert_before_item_id = ns.get_insert_before_item_id($('#add_item_position').val());
449
450     var data = $('#order_form').serializeArray();
451     data.push({ name: 'action', value: 'Order/add_item' },
452               { name: 'insert_before_item_id', value: insert_before_item_id });
453
454     $.post("controller.pl", data, kivi.eval_json_result);
455   };
456
457   ns.setup_multi_items_dialog = function() {
458     $('#multi_items_filter_table input, #multi_items_filter_table select').keydown(function(event) {
459       if (event.keyCode == 13) {
460         event.preventDefault();
461         ns.multi_items_dialog_update_result();
462         return false;
463       }
464     });
465
466     $('#multi_items_filter_all_substr_multi_ilike').focus();
467   };
468
469   ns.show_multi_items_dialog = function() {
470     if (!ns.check_cv()) return;
471
472     $('#row_table_id thead a img').remove();
473
474     kivi.popup_dialog({
475       url:    'controller.pl?action=Order/show_multi_items_dialog',
476       data:   { type: $('#type').val() },
477       id:     'jq_multi_items_dialog',
478       load:   kivi.Order.setup_multi_items_dialog,
479       dialog: {
480         title:  kivi.t8('Add multiple items'),
481         width:  800,
482         height: 500
483       }
484     });
485     return true;
486   };
487
488   ns.close_multi_items_dialog = function() {
489     $('#jq_multi_items_dialog').dialog('close');
490   };
491
492   ns.multi_items_dialog_update_result = function() {
493     var data = $('#multi_items_form').serializeArray();
494     data.push({ name: 'type', value: $('#type').val() });
495     $.ajax({
496       url:     'controller.pl?action=Order/multi_items_update_result',
497       data:    data,
498       method:  'post',
499       success: function(data) {
500         $('#multi_items_result').html(data);
501         ns.multi_items_dialog_enable_continue();
502         ns.multi_items_result_setup_events();
503       }
504     });
505   };
506
507   ns.multi_items_dialog_disable_continue = function() {
508     // disable keydown-event and continue button to prevent
509     // impatient users to add parts multiple times
510     $('#multi_items_result input, #multi_items_position').off("keydown");
511     $('#multi_items_dialog_continue_button').prop('disabled', true);
512   };
513
514   ns.multi_items_dialog_enable_continue = function()  {
515     $('#multi_items_result input, #multi_items_position').keydown(function(event) {
516       if(event.keyCode == 13) {
517         event.preventDefault();
518         ns.add_multi_items();
519         return false;
520       }
521     });
522     $('#multi_items_dialog_continue_button').prop('disabled', false);
523   };
524
525   ns.multi_items_result_setup_events = function() {
526     $('#multi_items_all_qty').change(ns.reformat_number);
527     $('#multi_items_all_qty').change(function(event) {
528       $('.multi_items_qty').val($(event.target).val());
529     });
530     $('.multi_items_qty').change(ns.reformat_number);
531   }
532
533   ns.add_multi_items = function() {
534     // rows at all
535     var n_rows = $('.multi_items_qty').length;
536     if (n_rows == 0) return;
537
538     // filled rows
539     n_rows = $('.multi_items_qty').filter(function() {
540       return $(this).val().length > 0;
541     }).length;
542     if (n_rows == 0) return;
543
544     ns.multi_items_dialog_disable_continue();
545
546     var insert_before_item_id = ns.get_insert_before_item_id($('#multi_items_position').val());
547
548     var data = $('#order_form').serializeArray();
549     data = data.concat($('#multi_items_form').serializeArray());
550     data.push({ name: 'action', value: 'Order/add_multi_items' },
551               { name: 'insert_before_item_id', value: insert_before_item_id });
552     $.post("controller.pl", data, kivi.eval_json_result);
553   };
554
555   ns.set_input_to_one = function(clicked) {
556     if ($(clicked).val() == '') {
557       $(clicked).val(kivi.format_amount(1.00, -2));
558     }
559     $(clicked).select();
560   };
561
562   ns.delete_order_item_row = function(clicked) {
563     var row = $(clicked).parents("tbody").first();
564     $(row).remove();
565
566     ns.renumber_positions();
567     ns.recalc_amounts_and_taxes();
568   };
569
570   ns.row_table_scroll_down = function() {
571     $('#row_table_scroll_id').scrollTop($('#row_table_scroll_id')[0].scrollHeight);
572   };
573
574   ns.show_longdescription_dialog = function(clicked) {
575     var row                 = $(clicked).parents("tbody").first();
576     var position            = $(row).find('[name="position"]').html();
577     var partnumber          = $(row).find('[name="partnumber"]').html();
578     var description_elt     = $(row).find('[name="order.orderitems[].description"]');
579     var description         = description_elt.val();
580     var longdescription_elt = $(row).find('[name="order.orderitems[].longdescription"]');
581     var longdescription;
582
583     if (!longdescription_elt.length) {
584       var data = [
585         { name: 'action',   value: 'Order/get_item_longdescription'                          },
586         { name: 'type',     value: $('#type').val()                                          },
587         { name: 'item_id',  value: $(row).find('[name="order.orderitems[+].id"]').val()      },
588         { name: 'parts_id', value: $(row).find('[name="order.orderitems[].parts_id"]').val() }
589       ];
590
591       $.ajax({
592         url:      'controller.pl',
593         data:     data,
594         method:   "GET",
595         async:    false,
596         dataType: 'text',
597         success:  function(val) {
598           longdescription = val;
599         }
600       });
601     } else {
602       longdescription = longdescription_elt.val();
603     }
604
605     var params = {
606       runningnumber:           position,
607       partnumber:              partnumber,
608       description:             description,
609       default_longdescription: longdescription,
610       set_function:            function(val) {
611         longdescription_elt.remove();
612         $('<input type="hidden" name="order.orderitems[].longdescription">').insertAfter(description_elt).val(val);
613       }
614     };
615
616     kivi.SalesPurchase.edit_longdescription_with_params(params);
617   };
618
619   ns.price_chooser_item_row = function(clicked) {
620     if (!ns.check_cv()) return;
621     var row         = $(clicked).parents("tbody").first();
622     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
623
624     var data = $('#order_form').serializeArray();
625     data.push({ name: 'action',  value: 'Order/price_popup' },
626               { name: 'item_id', value: item_id_dom.val()   });
627
628     $.post("controller.pl", data, kivi.eval_json_result);
629   };
630
631   ns.update_price_source = function(item_id, source, descr, price_str, price_editable) {
632     var row        = $('#item_' + item_id).parents("tbody").first();
633     var source_elt = $(row).find('[name="order.orderitems[].active_price_source"]');
634     var button_elt = $(row).find('[name="price_chooser_button"]');
635
636     button_elt.val(button_elt.val().replace(/.*\|/, descr + " |"));
637     source_elt.val(source);
638
639     var editable_div_elt     = $(row).find('[name="editable_price"]');
640     var not_editable_div_elt = $(row).find('[name="not_editable_price"]');
641     if (price_editable == 1 && source === '') {
642       // editable
643       $(editable_div_elt).show();
644       $(not_editable_div_elt).hide();
645       $(editable_div_elt).find(':input').prop("disabled", false);
646       $(not_editable_div_elt).find(':input').prop("disabled", true);
647     } else {
648       // not editable
649       $(editable_div_elt).hide();
650       $(not_editable_div_elt).show();
651       $(editable_div_elt).find(':input').prop("disabled", true);
652       $(not_editable_div_elt).find(':input').prop("disabled", false);
653     }
654
655     if (price_str) {
656       var price_elt = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
657       var html_elt  = $(row).find('[name="sellprice_text"]');
658       price_elt.val(price_str);
659       html_elt.html(price_str);
660       ns.recalc_amounts_and_taxes();
661     }
662
663     kivi.io.close_dialog();
664   };
665
666   ns.update_discount_source = function(item_id, source, descr, discount_str, price_editable) {
667     var row        = $('#item_' + item_id).parents("tbody").first();
668     var source_elt = $(row).find('[name="order.orderitems[].active_discount_source"]');
669     var button_elt = $(row).find('[name="price_chooser_button"]');
670
671     button_elt.val(button_elt.val().replace(/\|.*/, "| " + descr));
672     source_elt.val(source);
673
674     var editable_div_elt     = $(row).find('[name="editable_discount"]');
675     var not_editable_div_elt = $(row).find('[name="not_editable_discount"]');
676     if (price_editable == 1 && source === '') {
677       // editable
678       $(editable_div_elt).show();
679       $(not_editable_div_elt).hide();
680       $(editable_div_elt).find(':input').prop("disabled", false);
681       $(not_editable_div_elt).find(':input').prop("disabled", true);
682     } else {
683       // not editable
684       $(editable_div_elt).hide();
685       $(not_editable_div_elt).show();
686       $(editable_div_elt).find(':input').prop("disabled", true);
687       $(not_editable_div_elt).find(':input').prop("disabled", false);
688     }
689
690     if (discount_str) {
691       var discount_elt = $(row).find('[name="order.orderitems[].discount_as_percent"]');
692       var html_elt     = $(row).find('[name="discount_text"]');
693       discount_elt.val(discount_str);
694       html_elt.html(discount_str);
695       ns.recalc_amounts_and_taxes();
696     }
697
698     kivi.io.close_dialog();
699   };
700
701   ns.show_periodic_invoices_config_dialog = function() {
702     if ($('#type').val() !== 'sales_order') return;
703
704     kivi.popup_dialog({
705       url:    'controller.pl?action=Order/show_periodic_invoices_config_dialog',
706       data:   { type:              $('#type').val(),
707                 id:                $('#id').val(),
708                 config:            $('#order_periodic_invoices_config').val(),
709                 customer_id:       $('#order_customer_id').val(),
710                 transdate_as_date: $('#order_transdate_as_date').val(),
711                 language_id:       $('#language_id').val()
712               },
713       id:     'jq_periodic_invoices_config_dialog',
714       load:   kivi.reinit_widgets,
715       dialog: {
716         title:  kivi.t8('Edit the configuration for periodic invoices'),
717         width:  800,
718         height: 650
719       }
720     });
721     return true;
722   };
723
724   ns.close_periodic_invoices_config_dialog = function() {
725     $('#jq_periodic_invoices_config_dialog').dialog('close');
726   };
727
728   ns.assign_periodic_invoices_config = function() {
729     var data = $('[name="Form"]').serializeArray();
730     data.push({ name: 'type',   value: $('#type').val() },
731               { name: 'action', value: 'Order/assign_periodic_invoices_config' });
732     $.post("controller.pl", data, kivi.eval_json_result);
733   };
734
735   ns.check_save_active_periodic_invoices = function() {
736     var type = $('#type').val();
737     if (type !== 'sales_order') return true;
738
739     var active = false;
740     $.ajax({
741       url:      'controller.pl',
742       data:     { action: 'Order/get_has_active_periodic_invoices',
743                   type  : type,
744                   id    : $('#id').val(),
745                   config: $('#order_periodic_invoices_config').val(),
746                 },
747       method:   "GET",
748       async:    false,
749       dataType: 'text',
750       success:  function(val) {
751         active = val;
752       }
753     });
754
755     if (active == 1) {
756       return confirm(kivi.t8('This sales order has an active configuration for periodic invoices. If you save then all subsequently created invoices will contain those changes as well, but not those that have already been created. Do you want to continue?'));
757     }
758
759     return true;
760   };
761
762   ns.show_vc_details_dialog = function() {
763     if (!ns.check_cv()) return;
764     var vc;
765     var vc_id;
766     var title;
767     if ($('#type').val() == 'sales_order' || $('#type').val() == 'sales_quotation' ) {
768       vc    = 'customer';
769       vc_id = $('#order_customer_id').val();
770       title = kivi.t8('Customer details');
771     } else {
772       vc    = 'vendor';
773       vc_id = $('#order_vendor_id').val();
774       title = kivi.t8('Vendor details');
775     }
776
777     kivi.popup_dialog({
778       url:    'controller.pl',
779       data:   { action: 'Order/show_customer_vendor_details_dialog',
780                 type  : $('#type').val(),
781                 vc    : vc,
782                 vc_id : vc_id
783               },
784       id:     'jq_customer_vendor_details_dialog',
785       dialog: {
786         title:  title,
787         width:  800,
788         height: 650
789       }
790     });
791     return true;
792   };
793
794   ns.update_row_from_master_data = function(clicked) {
795     var row = $(clicked).parents("tbody").first();
796     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
797
798     var data = $('#order_form').serializeArray();
799     data.push({ name: 'action', value: 'Order/update_row_from_master_data' });
800     data.push({ name: 'item_ids[]', value: item_id_dom.val() });
801
802     $.post("controller.pl", data, kivi.eval_json_result);
803   };
804
805   ns.update_all_rows_from_master_data = function() {
806     var item_ids = $.map($('.row_entry'), function(elt) {
807       var item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
808       return { name: 'item_ids[]', value: item_id };
809     });
810
811     if (item_ids.length == 0) {
812       return;
813     }
814
815     var data = $('#order_form').serializeArray();
816     data.push({ name: 'action', value: 'Order/update_row_from_master_data' });
817     data = data.concat(item_ids);
818
819     $.post("controller.pl", data, kivi.eval_json_result);
820   };
821
822   ns.show_calculate_qty_dialog = function(clicked) {
823     var row        = $(clicked).parents("tbody").first();
824     var input_id   = $(row).find('[name="order.orderitems[].qty_as_number"]').attr('id');
825     var formula_id = $(row).find('[name="formula[+]"]').attr('id');
826
827     calculate_qty_selection_dialog("", input_id, "", formula_id);
828     return true;
829   };
830
831 });
832
833 $(function() {
834   if ($('#type').val() == 'sales_order' || $('#type').val() == 'sales_quotation' ) {
835     $('#order_customer_id').change(kivi.Order.reload_cv_dependent_selections);
836   } else {
837     $('#order_vendor_id').change(kivi.Order.reload_cv_dependent_selections);
838   }
839
840   $('#order_currency_id').change(kivi.Order.update_exchangerate);
841   $('#order_transdate_as_date').change(kivi.Order.update_exchangerate);
842   $('#order_exchangerate_as_null_number').change(kivi.Order.exchangerate_changed);
843
844   if ($('#type').val() == 'sales_order' || $('#type').val() == 'sales_quotation' ) {
845     $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_sellprice_as_number').val(kivi.format_amount(o.sellprice, -2)) });
846   } else {
847     $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_sellprice_as_number').val(kivi.format_amount(o.lastcost, -2)) });
848   }
849   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_description').val(o.description) });
850   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_unit').val(o.unit) });
851
852   $('.add_item_input').keydown(function(event) {
853     if (event.keyCode == 13) {
854       event.preventDefault();
855       kivi.Order.add_item();
856       return false;
857     }
858   });
859
860   kivi.Order.init_row_handlers();
861
862   $('#row_table_id').on('sortstop', function(event, ui) {
863     $('#row_table_id thead a img').remove();
864     kivi.Order.renumber_positions();
865   });
866
867   $('#expand_all').on('click', function(event) {
868     event.preventDefault();
869     if ($('#expand_all').data('expanded') == 1) {
870       $('#expand_all').data('expanded', 0);
871       $('#expand_all').attr('src', 'image/expand.svg');
872       $('#expand_all').attr('alt', kivi.t8('Show all details'));
873       $('#expand_all').attr('title', kivi.t8('Show all details'));
874       $('.row_entry').each(function(idx, elt) {
875         kivi.Order.hide_second_row(elt);
876       });
877     } else {
878       $('#expand_all').data('expanded', 1);
879       $('#expand_all').attr('src', "image/collapse.svg");
880       $('#expand_all').attr('alt', kivi.t8('Hide all details'));
881       $('#expand_all').attr('title', kivi.t8('Hide all details'));
882       kivi.Order.load_all_second_rows();
883       $('.row_entry').each(function(idx, elt) {
884         kivi.Order.show_second_row(elt);
885       });
886     }
887     return false;
888   });
889
890 });