jqModal-Dialoge durch jQuery-UI-Dialoge ersetzen
[kivitendo-erp.git] / js / autocomplete_part.js
1 namespace('kivi', function(k){
2   k.PartPicker = function($real, options) {
3     // short circuit in case someone double inits us
4     if ($real.data("part_picker"))
5       return $real.data("part_picker");
6
7     var KEY = {
8       ESCAPE: 27,
9       ENTER:  13,
10       TAB:    9,
11     };
12     var o = $.extend({
13       limit: 20,
14       delay: 50,
15     }, options);
16     var STATES = {
17       UNIQUE: 1,
18       UNDEFINED: 0,
19     }
20     var real_id = $real.attr('id');
21     var $dummy  = $('#' + real_id + '_name');
22     var $type   = $('#' + real_id + '_type');
23     var $unit   = $('#' + real_id + '_unit');
24     var $convertible_unit = $('#' + real_id + '_convertible_unit');
25     var $column = $('#' + real_id + '_column');
26     var state   = STATES.PICKED;
27     var last_real = $real.val();
28     var last_dummy = $dummy.val();
29     var timer;
30
31     function open_dialog () {
32       k.popup_dialog({
33         url: 'controller.pl?action=Part/part_picker_search',
34         data: $.extend({
35           real_id: real_id,
36         }, ajax_data($dummy.val())),
37         id: 'part_selection',
38         dialog: { title: k.t8('Part picker') }
39       });
40       window.clearTimeout(timer);
41       return true;
42     }
43
44     function ajax_data(term) {
45       var data = {
46         'filter.all:substr::ilike': term,
47         'filter.obsolete': 0,
48         'filter.unit_obj.convertible_to': $convertible_unit && $convertible_unit.val() ? $convertible_unit.val() : '',
49         column:   $column && $column.val() ? $column.val() : '',
50         current:  $real.val(),
51       };
52
53       if ($type && $type.val())
54         data['filter.type'] = $type.val().split(',');
55
56       if ($unit && $unit.val())
57         data['filter.unit'] = $unit.val().split(',');
58
59       return data;
60     }
61
62     function set_item (item) {
63       if (item.id) {
64         $real.val(item.id);
65         // autocomplete ui has name, ajax items have description
66         $dummy.val(item.name ? item.name : item.description);
67       } else {
68         $real.val('');
69         $dummy.val('');
70       }
71       state = STATES.PICKED;
72       last_real = $real.val();
73       last_dummy = $dummy.val();
74       $real.trigger('change');
75     }
76
77     function make_defined_state () {
78       if (state == STATES.PICKED)
79         return true
80       else if (state == STATES.UNDEFINED && $dummy.val() == '')
81         set_item({})
82       else
83         set_item({ id: last_real, name: last_dummy })
84     }
85
86     function update_results () {
87       $.ajax({
88         url: 'controller.pl?action=Part/part_picker_result',
89         data: $.extend({
90             'real_id': $real.val(),
91         }, ajax_data(function(){ var val = $('#part_picker_filter').val(); return val === undefined ? '' : val })),
92         success: function(data){ $('#part_picker_result').html(data) }
93       });
94     };
95
96     function result_timer (event) {
97       window.clearTimeout(timer);
98       timer = window.setTimeout(update_results, 100);
99     }
100
101     function close_popup() {
102       $('#part_selection').dialog('close');
103     };
104
105     $dummy.autocomplete({
106       source: function(req, rsp) {
107         $.ajax($.extend(o, {
108           url:      'controller.pl?action=Part/ajax_autocomplete',
109           dataType: "json",
110           data:     ajax_data(req.term),
111           success:  function (data){ rsp(data) }
112         }));
113       },
114       select: function(event, ui) {
115         set_item(ui.item);
116       },
117     });
118     /*  In case users are impatient and want to skip ahead:
119      *  Capture <enter> key events and check if it's a unique hit.
120      *  If it is, go ahead and assume it was selected. If it wasn't don't do
121      *  anything so that autocompletion kicks in.  For <tab> don't prevent
122      *  propagation. It would be nice to catch it, but javascript is too stupid
123      *  to fire a tab event later on, so we'd have to reimplement the "find
124      *  next active element in tabindex order and focus it".
125      */
126     /* note:
127      *  event.which does not contain tab events in keypressed in firefox but will report 0
128      *  chrome does not fire keypressed at all on tab or escape
129      *  TODO: users expect tab to work on keydown but enter to trigger on keyup,
130      *        should be handled seperately
131      */
132     $dummy.keydown(function(event){
133       if (event.which == KEY.ENTER || event.which == KEY.TAB) { // enter or tab or tab
134         // if string is empty assume they want to delete
135         if ($dummy.val() == '') {
136           set_item({});
137           return true;
138         } else if (state == STATES.PICKED) {
139           return true;
140         }
141         $.ajax({
142           url: 'controller.pl?action=Part/ajax_autocomplete',
143           dataType: "json",
144           data: $.extend( ajax_data($dummy.val()), { prefer_exact: 1 } ),
145           success: function (data){
146             if (data.length == 1) {
147               set_item(data[0]);
148               if (event.which == KEY.ENTER)
149                 $('#update_button').click();
150             } else if (data.length > 1) {
151              if (event.which == KEY.ENTER)
152                 open_dialog();
153               else
154                 make_defined_state();
155             } else {
156               if (event.which == KEY.TAB)
157                 make_defined_state();
158             }
159           }
160         });
161         if (event.which == KEY.ENTER)
162           return false;
163       } else {
164         state = STATES.UNDEFINED;
165       }
166     });
167
168     $dummy.blur(function(){
169       window.clearTimeout(timer);
170       timer = window.setTimeout(make_defined_state, 100);
171     });
172
173     // now add a picker div after the original input
174     var pcont  = $('<span>').addClass('position-absolute');
175     var picker = $('<div>');
176     $dummy.after(pcont);
177     pcont.append(picker);
178     picker.addClass('icon16 CRM--Schnellsuche').click(open_dialog);
179
180     var pp = {
181       real:           function() { return $real },
182       dummy:          function() { return $dummy },
183       type:           function() { return $type },
184       unit:           function() { return $unit },
185       convertible_unit: function() { return $convertible_unit },
186       column:         function() { return $column },
187       update_results: update_results,
188       result_timer:   result_timer,
189       set_item:       set_item,
190       reset:          make_defined_state,
191       init_results:    function () {
192         $('div.part_picker_part').each(function(){
193           $(this).click(function(){
194             set_item({
195               name: $(this).children('input.part_picker_description').val(),
196               id:   $(this).children('input.part_picker_id').val(),
197             });
198             close_popup();
199             return true;
200           });
201         });
202         $('#part_selection').keydown(function(e){
203            if (e.which == KEY.ESCAPE) {
204              close_popup();
205              $dummy.focus();
206            }
207         });
208       }
209     }
210     $real.data('part_picker', pp);
211     return pp;
212   }
213 });
214
215 $(function(){
216   $('input.part_autocomplete').each(function(i,real){
217     kivi.PartPicker($(real));
218   })
219 });