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