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