DeliveryOrder: besseres update nach stock dialog
[kivitendo-erp.git] / js / kivi.DeliveryOrder.js
1 namespace('kivi.DeliveryOrder', function(ns) {
2   ns.check_cv = function() {
3     if ($('#type').val() == 'sales_delivery_order') {
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 continue?");
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: 'action', value: 'DeliveryOrder/' + action });
55
56     $.post("controller.pl", data, kivi.eval_json_result);
57   };
58
59   ns.delete_order = function() {
60     var data = $('#order_form').serializeArray();
61     data.push({ name: 'action', value: 'DeliveryOrder/delete' });
62
63     $.post("controller.pl", data, kivi.eval_json_result);
64   };
65
66   ns.show_print_options = function(warn_on_duplicates, warn_on_reqdate) {
67     if (!ns.check_cv()) return;
68     if (warn_on_duplicates && !ns.check_duplicate_parts(kivi.t8("Do you really want to print?"))) return;
69     if (warn_on_reqdate    && !ns.check_valid_reqdate())   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.open_stock_in_out_dialog = function(clicked, in_out) {
82     var $row = $(clicked).parents("tbody").first();
83     var id = $row.find('[name="orderitem_ids[+]"]').val();
84     $row.uniqueId();
85
86     kivi.popup_dialog({
87       id: "stock_in_out_dialog",
88       url: "controller.pl?action=DeliveryOrder/stock_in_out_dialog",
89       data: {
90         id:            $("#id").val(),
91         type:          $("#type").val(),
92         parts_id:      $row.find("[name$=parts_id]").val(),
93         unit:          $row.find("[name$=unit]").val(),
94         qty_as_number: $row.find("[name$=qty_as_number]").val(),
95         stock:         $row.find("[name$=stock_info]").val(),
96         item_id:       id,
97         row:           $row.attr("id"),
98       },
99       dialog: { title: kivi.t8('Transfer stock') }
100     });
101   };
102
103   ns.save_updated_stock = function() {
104     // stock information is saved in DOM as a yaml dump.
105     // we don't want to do this in javascript so we do a tiny roundtrip to the backend
106
107     let data = [];
108     $("#stock-in-out-table tr.listrow").each((i,row) => {
109       data.push({
110         qty:         kivi.parse_amount($(row).find(".data-qty").val()),
111         warehouse_id:                  $(row).find(".data-warehouse-id").val(),
112         bin_id:                        $(row).find(".data-bin-id").val(),
113         chargenumber:                  $(row).find(".data-chargenumber").val(),
114         bestbefore:                    $(row).find(".data-bestbefore").val(),
115         unit:                          $(row).find(".data-unit").val(),
116         delivery_order_items_stock_id: $(row).find(".data-stock-id").val(),
117       });
118     });
119
120     let row = $(".data-row").val();
121
122     $.post("controller.pl",
123       kivi.serialize({
124         action:     "DeliveryOrder/update_stock_information",
125         unit:       $("#" + row).find("[name$=unit]").val(),
126         stock_info: data,
127         row:        row
128       }),
129       (data) => {
130         $("#" + row + " .data-stock-info").val(data.stock_info);
131         $("#" + row + " .data-stock-qty").text(data.stock_qty)
132         $("#stock_in_out_dialog").dialog("close");
133       }
134     );
135   };
136
137   ns.print = function() {
138     $('#print_options').dialog('close');
139
140     var data = $('#order_form').serializeArray();
141     data = data.concat($('#print_options_form').serializeArray());
142     data.push({ name: 'action', value: 'DeliveryOrder/print' });
143
144     $.post("controller.pl", data, kivi.eval_json_result);
145   };
146
147   var email_dialog;
148
149   ns.setup_send_email_dialog = function() {
150     kivi.SalesPurchase.show_all_print_options_elements();
151     kivi.SalesPurchase.show_print_options_elements([ 'sendmode', 'media', 'copies', 'remove_draft' ], false);
152
153     $('#print_options_form table').first().remove().appendTo('#email_form_print_options');
154
155     var to_focus = $('#email_form_to').val() === '' ? 'to' : 'subject';
156     $('#email_form_' + to_focus).focus();
157   };
158
159   ns.finish_send_email_dialog = function() {
160     kivi.SalesPurchase.show_all_print_options_elements();
161
162     $('#email_form_print_options table').first().remove().prependTo('#print_options_form');
163     return true;
164   };
165
166   ns.show_email_dialog = function(html) {
167     var id            = 'send_email_dialog';
168     var dialog_params = {
169       id:     id,
170       width:  800,
171       height: 600,
172       title:  kivi.t8('Send email'),
173       modal:  true,
174       beforeClose: kivi.DeliveryOrder.finish_send_email_dialog,
175       close: function(event, ui) {
176         email_dialog.remove();
177       }
178     };
179
180     $('#' + id).remove();
181
182     email_dialog = $('<div style="display:none" id="' + id + '"></div>').appendTo('body');
183     email_dialog.html(html);
184     email_dialog.dialog(dialog_params);
185
186     kivi.DeliveryOrder.setup_send_email_dialog();
187
188     $('.cancel').click(ns.close_email_dialog);
189
190     return true;
191   };
192
193   ns.send_email = function() {
194     // push button only once -> slow response from mail server
195     ns.email_dialog_disable_send();
196
197     var data = $('#order_form').serializeArray();
198     data = data.concat($('[name^="email_form."]').serializeArray());
199     data = data.concat($('[name^="print_options."]').serializeArray());
200     data.push({ name: 'action', value: 'DeliveryOrder/send_email' });
201     $.post("controller.pl", data, kivi.eval_json_result);
202   };
203
204   ns.email_dialog_disable_send = function() {
205     // disable mail send event to prevent
206     // impatient users to send multiple times
207     $('#send_email').prop('disabled', true);
208   };
209
210   ns.close_email_dialog = function() {
211     email_dialog.dialog("close");
212   };
213
214   ns.set_number_in_title = function(elt) {
215     $('#nr_in_title').html($(elt).val());
216   };
217
218   ns.reload_cv_dependent_selections = function() {
219     $('#order_shipto_id').val('');
220     var data = $('#order_form').serializeArray();
221     data.push({ name: 'action', value: 'DeliveryOrder/customer_vendor_changed' });
222
223     $.post("controller.pl", data, kivi.eval_json_result);
224   };
225
226   ns.reformat_number = function(event) {
227     $(event.target).val(kivi.format_amount(kivi.parse_amount($(event.target).val()), -2));
228   };
229
230   ns.reformat_number_as_null_number = function(event) {
231     if ($(event.target).val() === '') {
232       return;
233     }
234     ns.reformat_number(event);
235   };
236
237   ns.update_exchangerate = function(event) {
238     if (!ns.check_cv()) {
239       $('#order_currency_id').val($('#old_currency_id').val());
240       return;
241     }
242
243     var rate_input = $('#order_exchangerate_as_null_number');
244     // unset exchangerate if currency changed
245     if ($('#order_currency_id').val() !== $('#old_currency_id').val()) {
246       rate_input.val('');
247     }
248
249     // only set exchangerate if unset
250     if (rate_input.val() !== '') {
251       return;
252     }
253
254     var data = $('#order_form').serializeArray();
255     data.push({ name: 'action', value: 'DeliveryOrder/update_exchangerate' });
256
257     $.ajax({
258       url: 'controller.pl',
259       data: data,
260       method: 'POST',
261       dataType: 'json',
262       success: function(data){
263         if (!data.is_standard) {
264           $('#currency_name').text(data.currency_name);
265           if (data.exchangerate) {
266             rate_input.val(data.exchangerate);
267           } else {
268             rate_input.val('');
269           }
270           $('#exchangerate_settings').show();
271         } else {
272           rate_input.val('');
273           $('#exchangerate_settings').hide();
274         }
275         if ($('#order_currency_id').val() != $('#old_currency_id').val() ||
276             !data.is_standard && data.exchangerate != $('#old_exchangerate').val()) {
277           kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
278         }
279         $('#old_currency_id').val($('#order_currency_id').val());
280         $('#old_exchangerate').val(data.exchangerate);
281       }
282     });
283   };
284
285   ns.exchangerate_changed = function(event) {
286     if (kivi.parse_amount($('#order_exchangerate_as_null_number').val()) != kivi.parse_amount($('#old_exchangerate').val())) {
287       kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
288       $('#old_exchangerate').val($('#order_exchangerate_as_null_number').val());
289     }
290   };
291
292   ns.unit_change = function(event) {
293     var row           = $(event.target).parents("tbody").first();
294     var item_id_dom   = $(row).find('[name="orderitem_ids[+]"]');
295     var sellprice_dom = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
296     var select_elt    = $(row).find('[name="order.orderitems[].unit"]');
297
298     var oldval = $(select_elt).data('oldval');
299     $(select_elt).data('oldval', $(select_elt).val());
300
301     var data = $('#order_form').serializeArray();
302     data.push({ name: 'action',           value: 'DeliveryOrder/unit_changed'     },
303               { name: 'item_id',          value: item_id_dom.val()        },
304               { name: 'old_unit',         value: oldval                   },
305               { name: 'sellprice_dom_id', value: sellprice_dom.attr('id') });
306
307     $.post("controller.pl", data, kivi.eval_json_result);
308   };
309
310   ns.update_sellprice = function(item_id, price_str) {
311     var row       = $('#item_' + item_id).parents("tbody").first();
312     var price_elt = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
313     var html_elt  = $(row).find('[name="sellprice_text"]');
314     price_elt.val(price_str);
315     html_elt.html(price_str);
316   };
317
318   ns.load_second_row = function(row) {
319     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
320     var div_elt     = $(row).find('[name="second_row"]');
321
322     if ($(div_elt).data('loaded') == 1) {
323       return;
324     }
325     var data = $('#order_form').serializeArray();
326     data.push({ name: 'action',     value: 'DeliveryOrder/load_second_rows' },
327               { name: 'item_ids[]', value: item_id_dom.val()        });
328
329     $.post("controller.pl", data, kivi.eval_json_result);
330   };
331
332   ns.load_all_second_rows = function() {
333     var rows = $('.row_entry').filter(function(idx, elt) {
334       return $(elt).find('[name="second_row"]').data('loaded') != 1;
335     });
336
337     var item_ids = $.map(rows, function(elt) {
338       var item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
339       return { name: 'item_ids[]', value: item_id };
340     });
341
342     if (item_ids.length == 0) {
343       return;
344     }
345
346     var data = $('#order_form').serializeArray();
347     data.push({ name: 'action', value: 'DeliveryOrder/load_second_rows' });
348     data = data.concat(item_ids);
349
350     $.post("controller.pl", data, kivi.eval_json_result);
351   };
352
353   ns.hide_second_row = function(row) {
354     $(row).children().not(':first').hide();
355     $(row).data('expanded', 0);
356     var elt = $(row).find('.expand');
357     elt.attr('src', "image/expand.svg");
358     elt.attr('alt', kivi.t8('Show details'));
359     elt.attr('title', kivi.t8('Show details'));
360   };
361
362   ns.show_second_row = function(row) {
363     $(row).children().not(':first').show();
364     $(row).data('expanded', 1);
365     var elt = $(row).find('.expand');
366     elt.attr('src', "image/collapse.svg");
367     elt.attr('alt', kivi.t8('Hide details'));
368     elt.attr('title', kivi.t8('Hide details'));
369   };
370
371   ns.toggle_second_row = function(row) {
372     if ($(row).data('expanded') == 1) {
373       ns.hide_second_row(row);
374     } else {
375       ns.show_second_row(row);
376     }
377   };
378
379   ns.init_row_handlers = function() {
380     kivi.run_once_for('.reformat_number', 'on_change_reformat', function(elt) {
381       $(elt).change(ns.reformat_number);
382     });
383
384     kivi.run_once_for('.unitselect', 'on_change_unit_with_oldval', function(elt) {
385       $(elt).data('oldval', $(elt).val());
386       $(elt).change(ns.unit_change);
387     });
388
389     kivi.run_once_for('.row_entry', 'on_kbd_click_show_hide', function(elt) {
390       $(elt).keydown(function(event) {
391         var row;
392         if (event.keyCode == 40 && event.shiftKey === true) {
393           // shift arrow down
394           event.preventDefault();
395           row = $(event.target).parents(".row_entry").first();
396           ns.load_second_row(row);
397           ns.show_second_row(row);
398           return false;
399         }
400         if (event.keyCode == 38 && event.shiftKey === true) {
401           // shift arrow up
402           event.preventDefault();
403           row = $(event.target).parents(".row_entry").first();
404           ns.hide_second_row(row);
405           return false;
406         }
407       });
408     });
409
410     kivi.run_once_for('.expand', 'expand_second_row', function(elt) {
411       $(elt).click(function(event) {
412         event.preventDefault();
413         var row = $(event.target).parents(".row_entry").first();
414         ns.load_second_row(row);
415         ns.toggle_second_row(row);
416         return false;
417       })
418     });
419
420   };
421
422   ns.redisplay_line_values = function(is_sales, data) {
423     $('.row_entry').each(function(idx, elt) {
424       $(elt).find('[name="linetotal"]').html(data[idx][0]);
425       if (is_sales && $(elt).find('[name="second_row"]').data('loaded') == 1) {
426         var mt = data[idx][1];
427         var mp = data[idx][2];
428         var h  = '<span';
429         if (mt[0] === '-') h += ' class="plus0"';
430         h += '>' + mt + '&nbsp;&nbsp;' + mp + '%';
431         h += '</span>';
432         $(elt).find('[name="linemargin"]').html(h);
433       }
434     });
435   };
436
437   ns.redisplay_cvpartnumbers = function(data) {
438     $('.row_entry').each(function(idx, elt) {
439       $(elt).find('[name="cvpartnumber"]').html(data[idx][0]);
440     });
441   };
442
443   ns.renumber_positions = function() {
444     $('.row_entry [name="position"]').each(function(idx, elt) {
445       $(elt).html(idx+1);
446     });
447     $('.row_entry').each(function(idx, elt) {
448       $(elt).data("position", idx+1);
449     });
450   };
451
452   ns.reorder_items = function(order_by) {
453     var dir = $('#' + order_by + '_header_id a img').attr("data-sort-dir");
454     $('#row_table_id thead a img').remove();
455
456     var src;
457     if (dir == "1") {
458       dir = "0";
459       src = "image/up.png";
460     } else {
461       dir = "1";
462       src = "image/down.png";
463     }
464
465     $('#' + order_by + '_header_id a').append('<img border=0 data-sort-dir=' + dir + ' src=' + src + ' alt="' + kivi.t8('sort items') + '">');
466
467     var data = $('#order_form').serializeArray();
468     data.push({ name: 'action',   value: 'DeliveryOrder/reorder_items' },
469               { name: 'order_by', value: order_by              },
470               { name: 'sort_dir', value: dir                   });
471
472     $.post("controller.pl", data, kivi.eval_json_result);
473   };
474
475   ns.redisplay_items = function(data) {
476     var old_rows = $('.row_entry').detach();
477     var new_rows = [];
478     $(data).each(function(idx, elt) {
479       new_rows.push(old_rows[elt.old_pos - 1]);
480     });
481     $(new_rows).appendTo($('#row_table_id'));
482     ns.renumber_positions();
483   };
484
485   ns.get_insert_before_item_id = function(wanted_pos) {
486     if (wanted_pos === '') return;
487
488     var insert_before_item_id;
489     // selection by data does not seem to work if data is changed at runtime
490     // var elt = $('.row_entry [data-position="' + wanted_pos + '"]');
491     $('.row_entry').each(function(idx, elt) {
492       if ($(elt).data("position") == wanted_pos) {
493         insert_before_item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
494         return false;
495       }
496     });
497
498     return insert_before_item_id;
499   };
500
501   ns.add_item = function() {
502     if ($('#add_item_parts_id').val() === '') return;
503     if (!ns.check_cv()) return;
504
505     $('#row_table_id thead a img').remove();
506
507     var insert_before_item_id = ns.get_insert_before_item_id($('#add_item_position').val());
508
509     var data = $('#order_form').serializeArray();
510     data.push({ name: 'action', value: 'DeliveryOrder/add_item' },
511               { name: 'insert_before_item_id', value: insert_before_item_id });
512
513     $.post("controller.pl", data, kivi.eval_json_result);
514   };
515
516   ns.open_multi_items_dialog = function() {
517     if (!ns.check_cv()) return;
518
519     var pp = $("#add_item_parts_id").data("part_picker");
520     pp.o.multiple=1;
521     pp.open_dialog();
522   };
523
524   ns.add_multi_items = function(data) {
525     var insert_before_item_id = ns.get_insert_before_item_id($('#multi_items_position').val());
526     data = data.concat($('#order_form').serializeArray());
527     data.push({ name: 'action', value: 'DeliveryOrder/add_multi_items' },
528               { name: 'insert_before_item_id', value: insert_before_item_id });
529     $.post("controller.pl", data, kivi.eval_json_result);
530   };
531
532   ns.delete_order_item_row = function(clicked) {
533     var row = $(clicked).parents("tbody").first();
534     $(row).remove();
535
536     ns.renumber_positions();
537   };
538
539   ns.row_table_scroll_down = function() {
540     $('#row_table_scroll_id').scrollTop($('#row_table_scroll_id')[0].scrollHeight);
541   };
542
543   ns.show_longdescription_dialog = function(clicked) {
544     var row                 = $(clicked).parents("tbody").first();
545     var position            = $(row).find('[name="position"]').html();
546     var partnumber          = $(row).find('[name="partnumber"]').html();
547     var description_elt     = $(row).find('[name="order.orderitems[].description"]');
548     var longdescription_elt = $(row).find('[name="order.orderitems[].longdescription"]');
549
550     var params = {
551       runningnumber:           position,
552       partnumber:              partnumber,
553       description:             description_elt.val(),
554       default_longdescription: longdescription_elt.val(),
555       set_function:            function(val) {
556         longdescription_elt.val(val);
557       }
558     };
559
560     kivi.SalesPurchase.edit_longdescription_with_params(params);
561   };
562
563   ns.price_chooser_item_row = function(clicked) {
564     if (!ns.check_cv()) return;
565     var row         = $(clicked).parents("tbody").first();
566     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
567
568     var data = $('#order_form').serializeArray();
569     data.push({ name: 'action',  value: 'DeliveryOrder/price_popup' },
570               { name: 'item_id', value: item_id_dom.val()   });
571
572     $.post("controller.pl", data, kivi.eval_json_result);
573   };
574
575   ns.show_vc_details_dialog = function() {
576     if (!ns.check_cv()) return;
577     var vc;
578     var vc_id;
579     var title;
580     if ($('#order_customer_id').val()) {
581       vc    = 'customer';
582       vc_id = $('#order_customer_id').val();
583       title = kivi.t8('Customer details');
584     } else {
585       vc    = 'vendor';
586       vc_id = $('#order_vendor_id').val();
587       title = kivi.t8('Vendor details');
588     }
589
590     kivi.popup_dialog({
591       url:    'controller.pl',
592       data:   { action: 'DeliveryOrder/show_customer_vendor_details_dialog',
593                 type  : $('#type').val(),
594                 vc    : vc,
595                 vc_id : vc_id
596               },
597       id:     'jq_customer_vendor_details_dialog',
598       dialog: {
599         title:  title,
600         width:  800,
601         height: 650
602       }
603     });
604     return true;
605   };
606
607   ns.update_row_from_master_data = function(clicked) {
608     var row = $(clicked).parents("tbody").first();
609     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
610
611     var data = $('#order_form').serializeArray();
612     data.push({ name: 'action', value: 'DeliveryOrder/update_row_from_master_data' });
613     data.push({ name: 'item_ids[]', value: item_id_dom.val() });
614
615     $.post("controller.pl", data, kivi.eval_json_result);
616   };
617
618   ns.update_all_rows_from_master_data = function() {
619     var item_ids = $.map($('.row_entry'), function(elt) {
620       var item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
621       return { name: 'item_ids[]', value: item_id };
622     });
623
624     if (item_ids.length == 0) {
625       return;
626     }
627
628     var data = $('#order_form').serializeArray();
629     data.push({ name: 'action', value: 'DeliveryOrder/update_row_from_master_data' });
630     data = data.concat(item_ids);
631
632     $.post("controller.pl", data, kivi.eval_json_result);
633   };
634
635   ns.show_calculate_qty_dialog = function(clicked) {
636     var row        = $(clicked).parents("tbody").first();
637     var input_id   = $(row).find('[name="order.orderitems[].qty_as_number"]').attr('id');
638     var formula_id = $(row).find('[name="formula[+]"]').attr('id');
639
640     calculate_qty_selection_dialog("", input_id, "", formula_id);
641     return true;
642   };
643
644   ns.edit_custom_shipto = function() {
645     if (!ns.check_cv()) return;
646
647     kivi.SalesPurchase.edit_custom_shipto();
648   };
649
650   ns.purchase_order_check_for_direct_delivery = function() {
651     if ($('#type').val() != 'sales_order') {
652       kivi.submit_form_with_action($('#order_form'), 'DeliveryOrder/purchase_order');
653     }
654
655     var empty = true;
656     var shipto;
657     if ($('#order_shipto_id').val() !== '') {
658       empty = false;
659       shipto = $('#order_shipto_id option:selected').text();
660     } else {
661       $('#shipto_inputs [id^="shipto"]').each(function(idx, elt) {
662         if (!empty)                                     return true;
663         if (/^shipto_to_copy/.test($(elt).prop('id')))  return true;
664         if (/^shiptocp_gender/.test($(elt).prop('id'))) return true;
665         if (/^shiptocvar_/.test($(elt).prop('id')))     return true;
666         if ($(elt).val() !== '') {
667           empty = false;
668           return false;
669         }
670       });
671       var shipto_elements = [];
672       $([$('#shiptoname').val(), $('#shiptostreet').val(), $('#shiptozipcode').val(), $('#shiptocity').val()]).each(function(idx, elt) {
673         if (elt !== '') shipto_elements.push(elt);
674       });
675       shipto = shipto_elements.join('; ');
676     }
677
678     var use_it = false;
679     if (!empty) {
680       ns.direct_delivery_dialog(shipto);
681     } else {
682       kivi.submit_form_with_action($('#order_form'), 'DeliveryOrder/purchase_order');
683     }
684   };
685
686   ns.direct_delivery_callback = function(accepted) {
687     $('#direct-delivery-dialog').dialog('close');
688
689     if (accepted) {
690       $('<input type="hidden" name="use_shipto">').appendTo('#order_form').val('1');
691     }
692
693     kivi.submit_form_with_action($('#order_form'), 'DeliveryOrder/purchase_order');
694   };
695
696   ns.direct_delivery_dialog = function(shipto) {
697     $('#direct-delivery-dialog').remove();
698
699     var text1 = kivi.t8('You have entered or selected the following shipping address for this customer:');
700     var text2 = kivi.t8('Do you want to carry this shipping address over to the new purchase order so that the vendor can deliver the goods directly to your customer?');
701     var html  = '<div id="direct-delivery-dialog"><p>' + text1 + '</p><p>' + shipto + '</p><p>' + text2 + '</p>';
702     html      = html + '<hr><p>';
703     html      = html + '<input type="button" value="' + kivi.t8('Yes') + '" size="30" onclick="kivi.DeliveryOrder.direct_delivery_callback(true)">';
704     html      = html + '&nbsp;';
705     html      = html + '<input type="button" value="' + kivi.t8('No')  + '" size="30" onclick="kivi.DeliveryOrder.direct_delivery_callback(false)">';
706     html      = html + '</p></div>';
707     $(html).hide().appendTo('#order_form');
708
709     kivi.popup_dialog({id: 'direct-delivery-dialog',
710                        dialog: {title:  kivi.t8('Carry over shipping address'),
711                                 height: 300,
712                                 width:  500 }});
713   };
714
715   ns.follow_up_window = function() {
716     var id   = $('#id').val();
717     var type = $('#type').val();
718
719     var number_info = '';
720     if ($('#type').val() == 'sales_order' || $('#type').val() == 'purchase_order') {
721       number_info = $('#order_ordnumber').val();
722     } else if ($('#type').val() == 'sales_quotation' || $('#type').val() == 'request_quotation') {
723       number_info = $('#order_quonumber').val();
724     }
725
726     var name_info = '';
727     if ($('#type').val() == 'sales_order' || $('#type').val() == 'sales_quotation') {
728       name_info = $('#order_customer_id_name').val();
729     } else if ($('#type').val() == 'purchase_order' || $('#type').val() == 'request_quotation') {
730       name_info = $('#order_vendor_id_name').val();
731     }
732
733     var info = '';
734     if (number_info !== '') { info += ' (' + number_info + ')' }
735     if (name_info   !== '') { info += ' (' + name_info + ')' }
736
737     if (!$('#follow_up_rowcount').lenght) {
738       $('<input type="hidden" name="follow_up_rowcount"        id="follow_up_rowcount">').appendTo('#order_form');
739       $('<input type="hidden" name="follow_up_trans_id_1"      id="follow_up_trans_id_1">').appendTo('#order_form');
740       $('<input type="hidden" name="follow_up_trans_type_1"    id="follow_up_trans_type_1">').appendTo('#order_form');
741       $('<input type="hidden" name="follow_up_trans_info_1"    id="follow_up_trans_info_1">').appendTo('#order_form');
742       $('<input type="hidden" name="follow_up_trans_subject_1" id="follow_up_trans_subject_1">').appendTo('#order_form');
743     }
744     $('#follow_up_rowcount').val(1);
745     $('#follow_up_trans_id_1').val(id);
746     $('#follow_up_trans_type_1').val(type);
747     $('#follow_up_trans_info_1').val(info);
748     $('#follow_up_trans_subject_1').val($('#order_transaction_description').val());
749
750     follow_up_window();
751   };
752
753   ns.create_part = function() {
754     var data = $('#order_form').serializeArray();
755     data.push({ name: 'action', value: 'DeliveryOrder/create_part' });
756
757     $.post("controller.pl", data, kivi.eval_json_result);
758   };
759
760 });
761
762 $(function() {
763   $('#order_customer_id').change(kivi.DeliveryOrder.reload_cv_dependent_selections);
764   $('#order_vendor_id').change(kivi.DeliveryOrder.reload_cv_dependent_selections);
765
766   $('#order_currency_id').change(kivi.DeliveryOrder.update_exchangerate);
767   $('#order_transdate_as_date').change(kivi.DeliveryOrder.update_exchangerate);
768   $('#order_exchangerate_as_null_number').change(kivi.DeliveryOrder.exchangerate_changed);
769
770   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_description').val(o.description) });
771   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_unit').val(o.unit) });
772
773   $('.add_item_input').keydown(function(event) {
774     if (event.keyCode == 13) {
775       event.preventDefault();
776       kivi.DeliveryOrder.add_item();
777       return false;
778     }
779   });
780
781   kivi.DeliveryOrder.init_row_handlers();
782
783   $('#row_table_id').on('sortstop', function(event, ui) {
784     $('#row_table_id thead a img').remove();
785     kivi.DeliveryOrder.renumber_positions();
786   });
787
788   $('#expand_all').on('click', function(event) {
789     event.preventDefault();
790     if ($('#expand_all').data('expanded') == 1) {
791       $('#expand_all').data('expanded', 0);
792       $('#expand_all').attr('src', 'image/expand.svg');
793       $('#expand_all').attr('alt', kivi.t8('Show all details'));
794       $('#expand_all').attr('title', kivi.t8('Show all details'));
795       $('.row_entry').each(function(idx, elt) {
796         kivi.DeliveryOrder.hide_second_row(elt);
797       });
798     } else {
799       $('#expand_all').data('expanded', 1);
800       $('#expand_all').attr('src', "image/collapse.svg");
801       $('#expand_all').attr('alt', kivi.t8('Hide all details'));
802       $('#expand_all').attr('title', kivi.t8('Hide all details'));
803       kivi.DeliveryOrder.load_all_second_rows();
804       $('.row_entry').each(function(idx, elt) {
805         kivi.DeliveryOrder.show_second_row(elt);
806       });
807     }
808     return false;
809   });
810
811   $('.reformat_number_as_null_number').change(kivi.DeliveryOrder.reformat_number_as_null_number);
812
813 });