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