PartPicker: Strict-Modus & Warnungen von jshint beseitigt
[kivitendo-erp.git] / js / autocomplete_part.js
1 namespace('kivi', function(k){
2   "use strict";
3
4   k.PartPicker = function($real, options) {
5     // short circuit in case someone double inits us
6     if ($real.data("part_picker"))
7       return $real.data("part_picker");
8
9     var KEY = {
10       ESCAPE: 27,
11       ENTER:  13,
12       TAB:    9,
13       LEFT:   37,
14       RIGHT:  39,
15       PAGE_UP: 33,
16       PAGE_DOWN: 34,
17     };
18     var CLASSES = {
19       PICKED:       'partpicker-picked',
20       UNDEFINED:    'partpicker-undefined',
21       FAT_SET_ITEM: 'partpicker_fat_set_item',
22     }
23     var o = $.extend({
24       limit: 20,
25       delay: 50,
26       fat_set_item: $real.hasClass(CLASSES.FAT_SET_ITEM),
27     }, options);
28     var STATES = {
29       PICKED:    CLASSES.PICKED,
30       UNDEFINED: CLASSES.UNDEFINED
31     }
32     var real_id = $real.attr('id');
33     var $dummy             = $('#' + real_id + '_name');
34     var $part_type         = $('#' + real_id + '_part_type');
35     var $classification_id = $('#' + real_id + '_classification_id');
36     var $unit              = $('#' + real_id + '_unit');
37     var $convertible_unit  = $('#' + real_id + '_convertible_unit');
38     var state   = STATES.PICKED;
39     var last_real = $real.val();
40     var last_dummy = $dummy.val();
41     var timer;
42
43     function open_dialog () {
44       k.popup_dialog({
45         url: 'controller.pl?action=Part/part_picker_search',
46         data: $.extend({
47           real_id: real_id,
48         }, ajax_data($dummy.val())),
49         id: 'part_selection',
50         dialog: {
51           title: k.t8('Part picker'),
52           width: 800,
53           height: 800,
54         }
55       });
56       window.clearTimeout(timer);
57       return true;
58     }
59
60     function ajax_data(term) {
61       var data = {
62         'filter.all:substr:multi::ilike': term,
63         'filter.obsolete': 0,
64         'filter.unit_obj.convertible_to': $convertible_unit && $convertible_unit.val() ? $convertible_unit.val() : '',
65         no_paginate:  $('#no_paginate').prop('checked') ? 1 : 0,
66         current:  $real.val(),
67       };
68
69       if ($part_type && $part_type.val())
70         data['filter.part_type'] = $part_type.val().split(',');
71
72       if ($classification_id && $classification_id.val())
73         data['filter.classification_id'] = $classification_id.val().split(',');
74
75       if ($unit && $unit.val())
76         data['filter.unit'] = $unit.val().split(',');
77
78       return data;
79     }
80
81     function set_item (item) {
82       if (item.id) {
83         $real.val(item.id);
84         // autocomplete ui has name, use the value for ajax items, which contains displayable_name
85         $dummy.val(item.name ? item.name : item.value);
86       } else {
87         $real.val('');
88         $dummy.val('');
89       }
90       state = STATES.PICKED;
91       last_real = $real.val();
92       last_dummy = $dummy.val();
93       last_unverified_dummy = $dummy.val();
94       $real.trigger('change');
95
96       if (o.fat_set_item && item.id) {
97         $.ajax({
98           url: 'controller.pl?action=Part/show.json',
99           data: { id: item.id },
100           success: function(rsp) {
101             $real.trigger('set_item:PartPicker', rsp);
102           },
103         });
104       } else {
105         $real.trigger('set_item:PartPicker', item);
106       }
107       annotate_state();
108     }
109
110     function make_defined_state () {
111       if (state == STATES.PICKED) {
112         annotate_state();
113         return true
114       } else if (state == STATES.UNDEFINED && $dummy.val() === '')
115         set_item({})
116       else {
117         last_unverified_dummy = $dummy.val();
118         set_item({ id: last_real, name: last_dummy })
119       }
120       annotate_state();
121     }
122
123     function annotate_state () {
124       if (state == STATES.PICKED)
125         $dummy.removeClass(STATES.UNDEFINED).addClass(STATES.PICKED);
126       else if (state == STATES.UNDEFINED && $dummy.val() === '')
127         $dummy.removeClass(STATES.UNDEFINED).addClass(STATES.PICKED);
128       else {
129         last_unverified_dummy = $dummy.val();
130         $dummy.addClass(STATES.UNDEFINED).removeClass(STATES.PICKED);
131       }
132     }
133
134     function update_results () {
135       $.ajax({
136         url: 'controller.pl?action=Part/part_picker_result',
137         data: $.extend({
138             'real_id': $real.val(),
139         }, ajax_data(function(){ var val = $('#part_picker_filter').val(); return val === undefined ? '' : val })),
140         success: function(data){ $('#part_picker_result').html(data) }
141       });
142     }
143
144     function result_timer (event) {
145       if (!$('no_paginate').prop('checked')) {
146         if (event.keyCode == KEY.PAGE_UP) {
147           $('#part_picker_result a.paginate-prev').click();
148           return;
149         }
150         if (event.keyCode == KEY.PAGE_DOWN) {
151           $('#part_picker_result a.paginate-next').click();
152           return;
153         }
154       }
155       window.clearTimeout(timer);
156       timer = window.setTimeout(update_results, 100);
157     }
158
159     function close_popup() {
160       $('#part_selection').dialog('close');
161     }
162
163     function handle_changed_text(callbacks) {
164       $.ajax({
165         url: 'controller.pl?action=Part/ajax_autocomplete',
166         dataType: "json",
167         data: $.extend( ajax_data($dummy.val()), { prefer_exact: 1 } ),
168         success: function (data) {
169           if (data.length == 1) {
170             set_item(data[0]);
171             if (callbacks && callbacks.match_one) callbacks.match_one(data[0]);
172           } else if (data.length > 1) {
173             state = STATES.UNDEFINED;
174             if (callbacks && callbacks.match_many) callbacks.match_many(data);
175           } else {
176             state = STATES.UNDEFINED;
177             if (callbacks &&callbacks.match_none) callbacks.match_none();
178           }
179           annotate_state();
180         }
181       });
182     }
183
184     $dummy.autocomplete({
185       source: function(req, rsp) {
186         $.ajax($.extend(o, {
187           url:      'controller.pl?action=Part/ajax_autocomplete',
188           dataType: "json",
189           data:     ajax_data(req.term),
190           success:  function (data){ rsp(data) }
191         }));
192       },
193       select: function(event, ui) {
194         set_item(ui.item);
195       },
196     });
197     /*  In case users are impatient and want to skip ahead:
198      *  Capture <enter> key events and check if it's a unique hit.
199      *  If it is, go ahead and assume it was selected. If it wasn't don't do
200      *  anything so that autocompletion kicks in.  For <tab> don't prevent
201      *  propagation. It would be nice to catch it, but javascript is too stupid
202      *  to fire a tab event later on, so we'd have to reimplement the "find
203      *  next active element in tabindex order and focus it".
204      */
205     /* note:
206      *  event.which does not contain tab events in keypressed in firefox but will report 0
207      *  chrome does not fire keypressed at all on tab or escape
208      */
209     $dummy.keydown(function(event){
210       if (event.which == KEY.ENTER || event.which == KEY.TAB) {
211         // if string is empty assume they want to delete
212         if ($dummy.val() === '') {
213           set_item({});
214           return true;
215         } else if (state == STATES.PICKED) {
216           return true;
217         }
218         if (event.which == KEY.TAB) {
219           event.preventDefault();
220           handle_changed_text();
221         }
222         if (event.which == KEY.ENTER) {
223           handle_changed_text({
224             match_one:  function(){$('#update_button').click();},
225             match_many: function(){open_dialog();}
226           });
227           return false;
228         }
229       } else {
230         state = STATES.UNDEFINED;
231       }
232     });
233
234     $dummy.on('paste', function(){
235       setTimeout(function() {
236         handle_changed_text();
237       }, 1);
238     });
239
240     $dummy.blur(function(){
241       window.clearTimeout(timer);
242       timer = window.setTimeout(annotate_state, 100);
243     });
244
245     // now add a picker div after the original input
246     var popup_button = $('<span>').addClass('ppp_popup_button');
247     $dummy.after(popup_button);
248     popup_button.click(open_dialog);
249
250     var pp = {
251       real:              function() { return $real },
252       dummy:             function() { return $dummy },
253       part_type:         function() { return $part_type },
254       classification_id: function() { return $classification_id },
255       unit:              function() { return $unit },
256       convertible_unit:  function() { return $convertible_unit },
257       update_results: update_results,
258       result_timer:   result_timer,
259       set_item:       set_item,
260       reset:          make_defined_state,
261       is_defined_state: function() { return state == STATES.PICKED },
262       init_results:    function () {
263         $('div.part_picker_part').each(function(){
264           $(this).click(function(){
265             set_item({
266               id:   $(this).children('input.part_picker_id').val(),
267               name: $(this).children('input.part_picker_description').val(),
268               classification_id: $(this).children('input.part_picker_classification_id').val(),
269               unit: $(this).children('input.part_picker_unit').val(),
270               partnumber:  $(this).children('input.part_picker_partnumber').val(),
271               description: $(this).children('input.part_picker_description').val(),
272             });
273             close_popup();
274             $dummy.focus();
275             return true;
276           });
277         });
278         $('#part_selection').keydown(function(e){
279            if (e.which == KEY.ESCAPE) {
280              close_popup();
281              $dummy.focus();
282            }
283         });
284       }
285     }
286     $real.data('part_picker', pp);
287     return pp;
288   }
289 });
290
291 $(function(){
292   $('input.part_autocomplete').each(function(i,real){
293     kivi.PartPicker($(real));
294   })
295 });