[FIX] point_of_sale: drag & dropping the debug widget
[odoo/odoo.git] / addons / point_of_sale / static / src / js / widgets.js
1 function openerp_pos_widgets(instance, module){ //module is instance.point_of_sale
2     var QWeb = instance.web.qweb,
3         _t = instance.web._t;
4
5     // The ImageCache is used to hide the latency of the application cache on-disk access in chrome 
6     // that causes annoying flickering on product pictures. Why the hell a simple access to
7     // the application cache involves such latency is beyond me, hopefully one day this can be
8     // removed.
9     module.ImageCache   = instance.web.Class.extend({
10         init: function(options){
11             options = options || {};
12             this.max_size = options.max_size || 500;
13
14             this.cache = {};
15             this.access_time = {};
16             this.size = 0;
17         },
18         get_image_uncached: function(url){
19             var img =  new Image();
20             img.src = url;
21             return img;
22         },
23         // returns a DOM Image object from an url, and cache the last 500 (by default) results
24         get_image: function(url){
25             var cached = this.cache[url];
26             if(cached){
27                 this.access_time[url] = (new Date()).getTime();
28                 return cached;
29             }else{
30                 var img = new Image();
31                 img.src = url;
32                 while(this.size >= this.max_size){
33                     var oldestUrl = null;
34                     var oldestTime = (new Date()).getTime();
35                     for(var url in this.cache){
36                         var time = this.access_time[url];
37                         if(time <= oldestTime){
38                             oldestTime = time;
39                             oldestUrl  = url;
40                         }
41                     }
42                     if(oldestUrl){
43                         delete this.cache[oldestUrl];
44                         delete this.access_time[oldestUrl];
45                     }
46                     this.size--;
47                 }
48                 this.cache[url] = img;
49                 this.access_time[url] = (new Date()).getTime();
50                 this.size++;
51                 return img;
52             }
53         },
54     });
55
56     module.NumpadWidget = module.PosBaseWidget.extend({
57         template:'NumpadWidget',
58         init: function(parent, options) {
59             this._super(parent);
60             this.state = new module.NumpadState();
61             window.numpadstate = this.state;
62             var self = this;
63         },
64         start: function() {
65             this.state.bind('change:mode', this.changedMode, this);
66             this.changedMode();
67             this.$el.find('.numpad-backspace').click(_.bind(this.clickDeleteLastChar, this));
68             this.$el.find('.numpad-minus').click(_.bind(this.clickSwitchSign, this));
69             this.$el.find('.number-char').click(_.bind(this.clickAppendNewChar, this));
70             this.$el.find('.mode-button').click(_.bind(this.clickChangeMode, this));
71         },
72         clickDeleteLastChar: function() {
73             return this.state.deleteLastChar();
74         },
75         clickSwitchSign: function() {
76             return this.state.switchSign();
77         },
78         clickAppendNewChar: function(event) {
79             var newChar;
80             newChar = event.currentTarget.innerText || event.currentTarget.textContent;
81             return this.state.appendNewChar(newChar);
82         },
83         clickChangeMode: function(event) {
84             var newMode = event.currentTarget.attributes['data-mode'].nodeValue;
85             return this.state.changeMode(newMode);
86         },
87         changedMode: function() {
88             var mode = this.state.get('mode');
89             $('.selected-mode').removeClass('selected-mode');
90             $(_.str.sprintf('.mode-button[data-mode="%s"]', mode), this.$el).addClass('selected-mode');
91         },
92     });
93
94     // The paypad allows to select the payment method (cashregisters) 
95     // used to pay the order.
96     module.PaypadWidget = module.PosBaseWidget.extend({
97         template: 'PaypadWidget',
98         renderElement: function() {
99             var self = this;
100             this._super();
101
102             _.each(this.pos.cashregisters,function(cashregister) {
103                 var button = new module.PaypadButtonWidget(self,{
104                     pos: self.pos,
105                     pos_widget : self.pos_widget,
106                     cashregister: cashregister,
107                 });
108                 button.appendTo(self.$el);
109             });
110         }
111     });
112
113     module.PaypadButtonWidget = module.PosBaseWidget.extend({
114         template: 'PaypadButtonWidget',
115         init: function(parent, options){
116             this._super(parent, options);
117             this.cashregister = options.cashregister;
118         },
119         renderElement: function() {
120             var self = this;
121             this._super();
122
123             this.$el.click(function(){
124                 if (self.pos.get('selectedOrder').get('screen') === 'receipt'){  //TODO Why ?
125                     console.warn('TODO should not get there...?');
126                     return;
127                 }
128                 self.pos.get('selectedOrder').addPaymentline(self.cashregister);
129                 self.pos_widget.screen_selector.set_current_screen('payment');
130             });
131         },
132     });
133
134     module.OrderWidget = module.PosBaseWidget.extend({
135         template:'OrderWidget',
136         init: function(parent, options) {
137             var self = this;
138             this._super(parent,options);
139             this.editable = false;
140             this.pos.bind('change:selectedOrder', this.change_selected_order, this);
141             this.bind_orderline_events();
142             this.line_click_handler = function(event){
143                 if(!self.editable){
144                     return;
145                 }
146                 self.pos.get('selectedOrder').selectLine(this.orderline);
147                 self.pos_widget.numpad.state.reset();
148             };
149         },
150         enable_numpad: function(){
151             this.disable_numpad();  //ensure we don't register the callbacks twice
152             this.numpad_state = this.pos_widget.numpad.state;
153             if(this.numpad_state){
154                 this.numpad_state.reset();
155                 this.numpad_state.bind('set_value',   this.set_value, this);
156             }
157                     
158         },
159         disable_numpad: function(){
160             if(this.numpad_state){
161                 this.numpad_state.unbind('set_value',  this.set_value);
162                 this.numpad_state.reset();
163             }
164         },
165         set_editable: function(editable){
166             this.editable = editable;
167             if(editable){
168                 this.enable_numpad();
169             }else{
170                 this.disable_numpad();
171                 this.pos.get('selectedOrder').deselectLine();
172             }
173         },
174         set_value: function(val) {
175                 var order = this.pos.get('selectedOrder');
176                 if (this.editable && order.getSelectedLine()) {
177                 var mode = this.numpad_state.get('mode');
178                 if( mode === 'quantity'){
179                     order.getSelectedLine().set_quantity(val);
180                 }else if( mode === 'discount'){
181                     order.getSelectedLine().set_discount(val);
182                 }else if( mode === 'price'){
183                     order.getSelectedLine().set_unit_price(val);
184                 }
185                 }
186         },
187         change_selected_order: function() {
188             this.bind_orderline_events();
189             this.renderElement();
190         },
191         bind_orderline_events: function() {
192             var lines = this.pos.get('selectedOrder').get('orderLines');
193                 lines.unbind();
194                 lines.bind('add', function(){ 
195                         this.numpad_state.reset();
196                         this.renderElement(true);
197                     },this);
198                 lines.bind('remove', function(line){
199                         this.remove_orderline(line);
200                         this.numpad_state.reset();
201                         this.update_summary();
202                     },this);
203                 lines.bind('change', function(line){
204                         this.rerender_orderline(line);
205                         this.update_summary();
206                     },this);
207         },
208         render_orderline: function(orderline){
209             var el_str  = openerp.qweb.render('Orderline',{widget:this, line:orderline}); 
210             var el_node = document.createElement('div');
211                 el_node.innerHTML = _.str.trim(el_str);
212                 el_node = el_node.childNodes[0];
213                 el_node.orderline = orderline;
214                 el_node.addEventListener('click',this.line_click_handler);
215
216             orderline.node = el_node;
217             return el_node;
218         },
219         remove_orderline: function(order_line){
220             if(this.pos.get('selectedOrder').get('orderLines').length === 0){
221                 this.renderElement();
222             }else{
223                 order_line.node.parentNode.removeChild(order_line.node);
224             }
225         },
226         rerender_orderline: function(order_line){
227             var node = order_line.node;
228             var replacement_line = this.render_orderline(order_line);
229             node.parentNode.replaceChild(replacement_line,node);
230         },
231         // overriding the openerp framework replace method for performance reasons
232         replace: function($target){
233             this.renderElement();
234             var target = $target[0];
235             target.parentNode.replaceChild(this.el,target);
236         },
237         renderElement: function(scrollbottom){
238             this.pos_widget.numpad.state.reset();
239
240             var order  = this.pos.get('selectedOrder');
241             var orderlines = order.get('orderLines').models;
242
243             var el_str  = openerp.qweb.render('OrderWidget',{widget:this, order:order, orderlines:orderlines});
244             var el_node = document.createElement('div');
245                 el_node.innerHTML = _.str.trim(el_str);
246                 el_node = el_node.childNodes[0];
247
248             var list_container = el_node.querySelector('.orderlines');
249             for(var i = 0, len = orderlines.length; i < len; i++){
250                 var orderline = this.render_orderline(orderlines[i]);
251                 list_container.appendChild(orderline);
252             }
253
254             if(this.el && this.el.parentNode){
255                 this.el.parentNode.replaceChild(el_node,this.el);
256             }
257             this.el = el_node;
258             this.update_summary();
259
260             if(scrollbottom){
261                 this.el.querySelector('.order-scroller').scrollTop = 100 * orderlines.length;
262             }
263         },
264         update_summary: function(){
265             var order = this.pos.get('selectedOrder');
266             var total     = order ? order.getTotalTaxIncluded() : 0;
267             var taxes     = order ? total - order.getTotalTaxExcluded() : 0;
268
269             this.el.querySelector('.summary .total > .value').innerText = this.format_currency(total);
270             this.el.querySelector('.summary .total .subentry .value').innerText = this.format_currency(taxes);
271         },
272     });
273
274     module.OrderButtonWidget = module.PosBaseWidget.extend({
275         template:'OrderButtonWidget',
276         init: function(parent, options) {
277             this._super(parent,options);
278             var self = this;
279
280             this.order = options.order;
281             this.order.bind('destroy',this.destroy, this );
282             this.order.bind('change', this.renderElement, this );
283             this.pos.bind('change:selectedOrder', this.renderElement,this );
284         },
285         renderElement:function(){
286             this._super();
287             var self = this;
288             this.$el.click(function(){ 
289                 self.selectOrder();
290             });
291             if( this.order === this.pos.get('selectedOrder') ){
292                 this.$el.addClass('selected');
293             }
294         },
295         selectOrder: function(event) {
296             this.pos.set({
297                 selectedOrder: this.order
298             });
299         },
300         destroy: function(){
301             this.order.unbind('destroy', this.destroy, this);
302             this.order.unbind('change',  this.renderElement, this);
303             this.pos.unbind('change:selectedOrder', this.renderElement, this);
304             this._super();
305         },
306     });
307
308     module.ActionButtonWidget = instance.web.Widget.extend({
309         template:'ActionButtonWidget',
310         icon_template:'ActionButtonWidgetWithIcon',
311         init: function(parent, options){
312             this._super(parent, options);
313             this.label = options.label || 'button';
314             this.rightalign = options.rightalign || false;
315             this.click_action = options.click;
316             this.disabled = options.disabled || false;
317             if(options.icon){
318                 this.icon = options.icon;
319                 this.template = this.icon_template;
320             }
321         },
322         set_disabled: function(disabled){
323             if(this.disabled != disabled){
324                 this.disabled = !!disabled;
325                 this.renderElement();
326             }
327         },
328         renderElement: function(){
329             this._super();
330             if(this.click_action && !this.disabled){
331                 this.$el.click(_.bind(this.click_action, this));
332             }
333         },
334     });
335
336     module.ActionBarWidget = instance.web.Widget.extend({
337         template:'ActionBarWidget',
338         init: function(parent, options){
339             this._super(parent,options);
340             this.button_list = [];
341             this.buttons = {};
342             this.visibility = {};
343         },
344         set_element_visible: function(element, visible, action){
345             if(visible != this.visibility[element]){
346                 this.visibility[element] = !!visible;
347                 if(visible){
348                     this.$('.'+element).removeClass('oe_hidden');
349                 }else{
350                     this.$('.'+element).addClass('oe_hidden');
351                 }
352             }
353             if(visible && action){
354                 this.action[element] = action;
355                 this.$('.'+element).off('click').click(action);
356             }
357         },
358         set_button_disabled: function(name, disabled){
359             var b = this.buttons[name];
360             if(b){
361                 b.set_disabled(disabled);
362             }
363         },
364         destroy_buttons:function(){
365             for(var i = 0; i < this.button_list.length; i++){
366                 this.button_list[i].destroy();
367             }
368             this.button_list = [];
369             this.buttons = {};
370             return this;
371         },
372         get_button_count: function(){
373             return this.button_list.length;
374         },
375         add_new_button: function(button_options){
376             var button = new module.ActionButtonWidget(this,button_options);
377             this.button_list.push(button);
378             if(button_options.name){
379                 this.buttons[button_options.name] = button;
380             }
381             button.appendTo(this.$('.pos-actionbar-button-list'));
382             return button;
383         },
384         show:function(){
385             this.$el.removeClass('oe_hidden');
386         },
387         hide:function(){
388             this.$el.addClass('oe_hidden');
389         },
390     });
391
392     module.ProductCategoriesWidget = module.PosBaseWidget.extend({
393         template: 'ProductCategoriesWidget',
394         init: function(parent, options){
395             var self = this;
396             this._super(parent,options);
397             this.product_type = options.product_type || 'all';  // 'all' | 'weightable'
398             this.onlyWeightable = options.onlyWeightable || false;
399             this.category = this.pos.root_category;
400             this.breadcrumb = [];
401             this.subcategories = [];
402             this.product_list_widget = options.product_list_widget || null;
403             this.category_cache = {};
404             this.set_category();
405             
406             this.switch_category_handler = function(event){
407                 self.set_category(self.pos.db.get_category_by_id(Number(this.dataset['categoryId'])));
408                 self.renderElement();
409             };
410             
411             this.clear_search_handler = function(event){
412                 console.log("CLEAR SEARCH");
413                 self.clear_search();
414             };
415
416             var search_timeout  = null;
417             this.search_handler = function(event){
418                 clearTimeout(search_timeout);
419
420                 var query = this.value;
421
422                 search_timeout = setTimeout(function(){
423                     self.perform_search(self.category, query, event.which === 13);
424                 },70);
425             };
426         },
427
428         // changes the category. if undefined, sets to root category
429         set_category : function(category){
430             var db = this.pos.db;
431             if(!category){
432                 this.category = db.get_category_by_id(db.root_category_id);
433             }else{
434                 this.category = category;
435             }
436             this.breadcrumb = [];
437             var ancestors_ids = db.get_category_ancestors_ids(this.category.id);
438             for(var i = 1; i < ancestors_ids.length; i++){
439                 this.breadcrumb.push(db.get_category_by_id(ancestors_ids[i]));
440             }
441             if(this.category.id !== db.root_category_id){
442                 this.breadcrumb.push(this.category);
443             }
444             this.subcategories = db.get_category_by_id(db.get_category_childs_ids(this.category.id));
445         },
446
447         get_image_url: function(category){
448             return window.location.origin + '/web/binary/image?model=pos.category&field=image_medium&id='+category.id;
449         },
450
451         render_category: function( category, with_image ){
452             if(!this.category_cache[category.id]){
453
454                 if(with_image){
455                     var image_url = this.get_image_url(category);
456                     var category_html = QWeb.render('CategoryButton',{ 
457                             widget:  this, 
458                             category: category, 
459                         });
460                         category_html = _.str.trim(category_html);
461                     var category_node = document.createElement('div');
462                         category_node.innerHTML = category_html;
463                         category_node = category_node.childNodes[0];
464                     var img = category_node.querySelector('img');
465                         img.parentNode.replaceChild(this.pos_widget.image_cache.get_image(image_url),img);
466                 }else{
467                     var category_html = QWeb.render('CategorySimpleButton',{ 
468                             widget:  this, 
469                             category: category, 
470                         });
471                         category_html = _.str.trim(category_html);
472                     var category_node = document.createElement('div');
473                         category_node.innerHTML = category_html;
474                         category_node = category_node.childNodes[0];
475                 }
476                 this.category_cache[category.id] = category_node;
477             }
478             return this.category_cache[category.id];
479         },
480
481         replace: function($target){
482             this.renderElement();
483             var target = $target[0];
484             target.parentNode.replaceChild(this.el,target);
485         },
486
487         renderElement: function(){
488             var self = this;
489
490             var el_str  = openerp.qweb.render(this.template, {widget: this});
491             var el_node = document.createElement('div');
492                 el_node.innerHTML = el_str;
493                 el_node = el_node.childNodes[1];
494
495             if(this.el && this.el.parentNode){
496                 this.el.parentNode.replaceChild(el_node,this.el);
497             }
498
499             this.el = el_node;
500
501             var hasimages = false;  //if none of the subcategories have images, we don't display buttons with icons
502             for(var i = 0; i < this.subcategories.length; i++){
503                 if(this.subcategories[i].image){
504                     hasimages = true;
505                     break;
506                 }
507             }
508
509             var list_container = el_node.querySelector('.category-list');
510             for(var i = 0, len = this.subcategories.length; i < len; i++){
511                 list_container.appendChild(this.render_category(this.subcategories[i],hasimages));
512             };
513
514             var buttons = el_node.querySelectorAll('.js-category-switch');
515             for(var i = 0; i < buttons.length; i++){
516                 buttons[i].addEventListener('click',this.switch_category_handler);
517             }
518
519             var products = this.pos.db.get_product_by_category(this.category.id);
520             this.product_list_widget.set_product_list(products);
521
522             this.el.querySelector('.searchbox input').addEventListener('keyup',this.search_handler);
523
524             this.el.querySelector('.search-clear').addEventListener('click',this.clear_search_handler);
525
526             if(this.pos.config.iface_vkeyboard && this.pos_widget.onscreen_keyboard){
527                 this.pos_widget.onscreen_keyboard.connect(this.$('.searchbox input'));
528             }
529         },
530         
531         // resets the current category to the root category
532         reset_category: function(){
533             this.set_category();
534             this.renderElement();
535         },
536
537         // empties the content of the search box
538         clear_search: function(){
539             var products = this.pos.db.get_product_by_category(this.category.id);
540             this.product_list_widget.set_product_list(products);
541             var input = this.el.querySelector('.searchbox input');
542                 input.value = '';
543                 input.focus();
544         },
545         perform_search: function(category, query, buy_result){
546             if(query){
547                 var products = this.pos.db.search_product_in_category(category.id,query)
548                 if(buy_result && products.length === 1){
549                         this.pos.get('selectedOrder').addProduct(products[0]);
550                         this.clear_search();
551                 }else{
552                     this.product_list_widget.set_product_list(products);
553                 }
554             }else{
555                 var products = this.pos.db.get_product_by_category(this.category.id);
556                 this.product_list_widget.set_product_list(products);
557             }
558         },
559
560     });
561
562     module.ProductListWidget = module.PosBaseWidget.extend({
563         template:'ProductListWidget',
564         init: function(parent, options) {
565             var self = this;
566             this._super(parent,options);
567             this.model = options.model;
568             this.productwidgets = [];
569             this.weight = options.weight || 0;
570             this.show_scale = options.show_scale || false;
571             this.next_screen = options.next_screen || false;
572
573             this.click_product_handler = function(event){
574                 var product = self.pos.db.get_product_by_id(this.dataset['productId']);
575                 options.click_product_action(product);
576             };
577
578             this.product_list = options.product_list || [];
579             this.product_cache = {};
580         },
581         set_product_list: function(product_list){
582             this.product_list = product_list;
583             this.renderElement();
584         },
585         get_product_image_url: function(product){
586             return window.location.origin + '/web/binary/image?model=product.product&field=image_medium&id='+product.id;
587         },
588         replace: function($target){
589             this.renderElement();
590             var target = $target[0];
591             target.parentNode.replaceChild(this.el,target);
592         },
593
594         render_product: function(product){
595             if(!this.product_cache[product.id]){
596                 var image_url = this.get_product_image_url(product);
597                 var product_html = QWeb.render('Product',{ 
598                         widget:  this, 
599                         product: product, 
600                     });
601                 var product_node = document.createElement('div');
602                 product_node.innerHTML = product_html;
603                 product_node = product_node.childNodes[1];
604                 var img = product_node.querySelector('img');
605                 img.parentNode.replaceChild(this.pos_widget.image_cache.get_image(image_url),img);
606                 this.product_cache[product.id] = product_node;
607             }
608             return this.product_cache[product.id];
609         },
610
611         renderElement: function() {
612             var self = this;
613
614             // this._super()
615             var el_str  = openerp.qweb.render(this.template, {widget: this});
616             var el_node = document.createElement('div');
617                 el_node.innerHTML = el_str;
618                 el_node = el_node.childNodes[1];
619
620             if(this.el && this.el.parentNode){
621                 this.el.parentNode.replaceChild(el_node,this.el);
622             }
623             this.el = el_node;
624
625             var list_container = el_node.querySelector('.product-list');
626             for(var i = 0, len = this.product_list.length; i < len; i++){
627                 var product_node = this.render_product(this.product_list[i]);
628                 product_node.addEventListener('click',this.click_product_handler);
629                 list_container.appendChild(product_node);
630             };
631         },
632     });
633
634     module.UsernameWidget = module.PosBaseWidget.extend({
635         template: 'UsernameWidget',
636         init: function(parent, options){
637             var options = options || {};
638             this._super(parent,options);
639             this.mode = options.mode || 'cashier';
640         },
641         set_user_mode: function(mode){
642             this.mode = mode;
643             this.refresh();
644         },
645         refresh: function(){
646             this.renderElement();
647         },
648         get_name: function(){
649             var user;
650             if(this.mode === 'cashier'){
651                 user = this.pos.cashier || this.pos.user;
652             }else{
653                 user = this.pos.get('selectedOrder').get_client()  || this.pos.user;
654             }
655             if(user){
656                 return user.name;
657             }else{
658                 return "";
659             }
660         },
661     });
662
663     module.HeaderButtonWidget = module.PosBaseWidget.extend({
664         template: 'HeaderButtonWidget',
665         init: function(parent, options){
666             options = options || {};
667             this._super(parent, options);
668             this.action = options.action;
669             this.label   = options.label;
670         },
671         renderElement: function(){
672             var self = this;
673             this._super();
674             if(this.action){
675                 this.$el.click(function(){
676                     self.action();
677                 });
678             }
679         },
680         show: function(){ this.$el.removeClass('oe_hidden'); },
681         hide: function(){ this.$el.addClass('oe_hidden'); },
682     });
683
684     // The debug widget lets the user control and monitor the hardware and software status
685     // without the use of the proxy
686     module.DebugWidget = module.PosBaseWidget.extend({
687         template: "DebugWidget",
688         eans:{
689             admin_badge:  '0410100000006',
690             client_badge: '0420200000004',
691             invalid_ean:  '1232456',
692             soda_33cl:    '5449000000996',
693             oranges_kg:   '2100002031410',
694             lemon_price:  '2301000001560',
695             unknown_product: '9900000000004',
696         },
697         events:[
698             'scan_item_success',
699             'scan_item_error_unrecognized',
700             'payment_request',
701             'open_cashbox',
702             'print_receipt',
703             'print_pdf_invoice',
704             'weighting_read_kg',
705             'payment_status',
706         ],
707         minimized: false,
708         init: function(parent,options){
709             this._super(parent,options);
710             var self = this;
711             
712             this.minimized = false;
713
714             // for dragging the debug widget around
715             this.dragging  = false;
716             this.drag_x = 0;
717             this.drag_y = 0;
718
719             this.mouseleave_handler = function(event){
720                 self.dragging = false;
721             };
722             this.mouseup_handler = function(event){
723                 self.dragging = false;
724             };
725             this.mousedown_handler = function(event){
726                 self.dragging = true;
727                 self.drag_x = event.screenX;
728                 self.drag_y = event.screenY;
729             };
730             this.mousemove_handler = function(event){
731                 if(self.dragging){
732                     var top = this.offsetTop;
733                     var left = this.offsetLeft;
734                     var dx   = event.screenX - self.drag_x;
735                     var dy   = event.screenY - self.drag_y;
736
737                     self.drag_x = event.screenX;
738                     self.drag_y = event.screenY;
739
740                     this.style.right = 'auto';
741                     this.style.bottom = 'auto';
742                     this.style.left = left + dx + 'px';
743                     this.style.top  = top  + dy + 'px';
744                 }
745             };
746         },
747         start: function(){
748             var self = this;
749
750             this.el.addEventListener('mouseleave', this.mouseleave_handler);
751             this.el.addEventListener('mouseup',    this.mouseup_handler);
752             this.el.addEventListener('mousedown',  this.mousedown_handler);
753             this.el.addEventListener('mousemove',  this.mousemove_handler);
754
755             this.$('.toggle').click(function(){
756                 var content = self.$('.content');
757                 var bg      = self.$el;
758                 if(!self.minimized){
759                     content.animate({'height':'0'},200);
760                 }else{
761                     content.css({'height':'auto'});
762                 }
763                 self.minimized = !self.minimized;
764             });
765             this.$('.button.accept_payment').click(function(){
766                 self.pos.proxy.debug_accept_payment();
767             });
768             this.$('.button.reject_payment').click(function(){
769                 self.pos.proxy.debug_reject_payment();
770             });
771             this.$('.button.set_weight').click(function(){
772                 var kg = Number(self.$('input.weight').val());
773                 if(!isNaN(kg)){
774                     self.pos.proxy.debug_set_weight(kg);
775                 }
776             });
777             this.$('.button.reset_weight').click(function(){
778                 self.$('input.weight').val('');
779                 self.pos.proxy.debug_reset_weight();
780             });
781             this.$('.button.custom_ean').click(function(){
782                 var ean = self.pos.barcode_reader.sanitize_ean(self.$('input.ean').val() || '0');
783                 self.$('input.ean').val(ean);
784                 self.pos.barcode_reader.scan('ean13',ean);
785             });
786             this.$('.button.reference').click(function(){
787                 self.pos.barcode_reader.scan('reference',self.$('input.ean').val());
788             });
789             _.each(this.eans, function(ean, name){
790                 self.$('.button.'+name).click(function(){
791                     self.$('input.ean').val(ean);
792                     self.pos.barcode_reader.scan('ean13',ean);
793                 });
794             });
795             _.each(this.events, function(name){
796                 self.pos.proxy.add_notification(name,function(){
797                     self.$('.event.'+name).stop().clearQueue().css({'background-color':'#6CD11D'}); 
798                     self.$('.event.'+name).animate({'background-color':'#1E1E1E'},2000);
799                 });
800             });
801             self.pos.proxy.add_notification('help_needed',function(){
802                 self.$('.status.help_needed').addClass('on');
803             });
804             self.pos.proxy.add_notification('help_canceled',function(){
805                 self.$('.status.help_needed').removeClass('on');
806             });
807             self.pos.proxy.add_notification('transaction_start',function(){
808                 self.$('.status.transaction').addClass('on');
809             });
810             self.pos.proxy.add_notification('transaction_end',function(){
811                 self.$('.status.transaction').removeClass('on');
812             });
813             self.pos.proxy.add_notification('weighting_start',function(){
814                 self.$('.status.weighting').addClass('on');
815             });
816             self.pos.proxy.add_notification('weighting_end',function(){
817                 self.$('.status.weighting').removeClass('on');
818             });
819         },
820     });
821
822 // ---------- Main Point of Sale Widget ----------
823
824     // this is used to notify the user that data is being synchronized on the network
825     module.SynchNotificationWidget = module.PosBaseWidget.extend({
826         template: "SynchNotificationWidget",
827         init: function(parent, options){
828             options = options || {};
829             this._super(parent, options);
830         },
831         renderElement: function() {
832             var self = this;
833             this._super();
834             this.$el.click(function(){
835                 self.pos.flush();
836             });
837         },
838         start: function(){
839             var self = this;
840             this.pos.bind('change:nbr_pending_operations', function(){
841                 self.renderElement();
842             });
843         },
844         get_nbr_pending: function(){
845             return this.pos.get('nbr_pending_operations');
846         },
847     });
848
849
850     // The PosWidget is the main widget that contains all other widgets in the PointOfSale.
851     // It is mainly composed of :
852     // - a header, containing the list of orders
853     // - a leftpane, containing the list of bought products (orderlines) 
854     // - a rightpane, containing the screens (see pos_screens.js)
855     // - an actionbar on the bottom, containing various action buttons
856     // - popups
857     // - an onscreen keyboard
858     // a screen_selector which controls the switching between screens and the showing/closing of popups
859
860     module.PosWidget = module.PosBaseWidget.extend({
861         template: 'PosWidget',
862         init: function() { 
863             this._super(arguments[0],{});
864             console.log('UH');
865
866             instance.web.blockUI(); 
867
868             this.pos = new module.PosModel(this.session);
869             this.pos.pos_widget = this;
870             this.pos_widget = this; //So that pos_widget's childs have pos_widget set automatically
871
872             this.numpad_visible = true;
873             this.left_action_bar_visible = true;
874             this.leftpane_visible = true;
875             this.leftpane_width   = '440px';
876             this.cashier_controls_visible = true;
877             this.image_cache = new module.ImageCache(); // for faster products image display
878
879             FastClick.attach(document.body);
880
881         },
882       
883         start: function() {
884             var self = this;
885             return self.pos.ready.done(function() {
886                 $('.oe_tooltip').remove();  // remove tooltip from the start session button
887                 
888                 // remove default webclient handlers that induce click delay
889                 $(document).off();
890                 $(window).off();
891                 $('html').off();
892                 $('body').off();
893                 $(self.$el).parent().off();
894                 $('document').off();
895                 $('.oe_web_client').off();
896                 $('.openerp_webclient_container').off();
897
898                 /*this.el.addEventHandler('click',function(event){
899                     event.stopPropagation();
900                     event.preventDefault();
901                 });*/
902
903                 self.build_currency_template();
904                 self.renderElement();
905                 
906                 self.$('.neworder-button').click(function(){
907                     self.pos.add_new_order();
908                 });
909
910                 self.$('.deleteorder-button').click(function(){
911                     self.pos.delete_current_order();
912                 });
913                 
914                 //when a new order is created, add an order button widget
915                 self.pos.get('orders').bind('add', function(new_order){
916                     var new_order_button = new module.OrderButtonWidget(null, {
917                         order: new_order,
918                         pos: self.pos
919                     });
920                     new_order_button.appendTo(this.$('.orders'));
921                     new_order_button.selectOrder();
922                 }, self);
923
924                 self.pos.add_new_order();
925
926                 self.build_widgets();
927
928                 if(self.pos.config.iface_big_scrollbars){
929                     self.$el.addClass('big-scrollbars');
930                 }
931
932                 self.screen_selector.set_default_screen();
933
934                 self.pos.barcode_reader.connect();
935
936                 instance.webclient.set_content_full_screen(true);
937
938                 if (!self.pos.session) {
939                     self.screen_selector.show_popup('error', 'Sorry, we could not create a user session');
940                 }else if(!self.pos.config){
941                     self.screen_selector.show_popup('error', 'Sorry, we could not find any PoS Configuration for this session');
942                 }
943             
944                 instance.web.unblockUI();
945                 self.$('.loader').animate({opacity:0},1500,'swing',function(){self.$('.loader').addClass('oe_hidden');});
946
947                 self.pos.flush();
948
949             }).fail(function(){   // error when loading models data from the backend
950                 instance.web.unblockUI();
951                 return new instance.web.Model("ir.model.data").get_func("search_read")([['name', '=', 'action_pos_session_opening']], ['res_id'])
952                     .pipe( _.bind(function(res){
953                         return instance.session.rpc('/web/action/load', {'action_id': res[0]['res_id']})
954                             .pipe(_.bind(function(result){
955                                 var action = result.result;
956                                 this.do_action(action);
957                             }, this));
958                     }, self));
959             });
960         },
961         
962         // This method instantiates all the screens, widgets, etc. If you want to add new screens change the
963         // startup screen, etc, override this method.
964         build_widgets: function() {
965             var self = this;
966
967             // --------  Screens ---------
968
969             this.product_screen = new module.ProductScreenWidget(this,{});
970             this.product_screen.appendTo(this.$('.screens'));
971
972             this.receipt_screen = new module.ReceiptScreenWidget(this, {});
973             this.receipt_screen.appendTo(this.$('.screens'));
974
975             this.payment_screen = new module.PaymentScreenWidget(this, {});
976             this.payment_screen.appendTo(this.$('.screens'));
977
978             this.welcome_screen = new module.WelcomeScreenWidget(this,{});
979             this.welcome_screen.appendTo(this.$('.screens'));
980
981             this.client_payment_screen = new module.ClientPaymentScreenWidget(this, {});
982             this.client_payment_screen.appendTo(this.$('.screens'));
983
984             this.scale_invite_screen = new module.ScaleInviteScreenWidget(this, {});
985             this.scale_invite_screen.appendTo(this.$('.screens'));
986
987             this.scale_screen = new module.ScaleScreenWidget(this,{});
988             this.scale_screen.appendTo(this.$('.screens'));
989
990             // --------  Popups ---------
991
992             this.help_popup = new module.HelpPopupWidget(this, {});
993             this.help_popup.appendTo(this.$el);
994
995             this.error_popup = new module.ErrorPopupWidget(this, {});
996             this.error_popup.appendTo(this.$el);
997
998             this.error_product_popup = new module.ProductErrorPopupWidget(this, {});
999             this.error_product_popup.appendTo(this.$el);
1000
1001             this.error_session_popup = new module.ErrorSessionPopupWidget(this, {});
1002             this.error_session_popup.appendTo(this.$el);
1003
1004             this.choose_receipt_popup = new module.ChooseReceiptPopupWidget(this, {});
1005             this.choose_receipt_popup.appendTo(this.$el);
1006
1007             this.error_negative_price_popup = new module.ErrorNegativePricePopupWidget(this, {});
1008             this.error_negative_price_popup.appendTo(this.$el);
1009
1010             this.error_no_client_popup = new module.ErrorNoClientPopupWidget(this, {});
1011             this.error_no_client_popup.appendTo(this.$el);
1012
1013             this.error_invoice_transfer_popup = new module.ErrorInvoiceTransferPopupWidget(this, {});
1014             this.error_invoice_transfer_popup.appendTo(this.$el);
1015
1016             // --------  Misc ---------
1017
1018             this.notification = new module.SynchNotificationWidget(this,{});
1019             this.notification.appendTo(this.$('.pos-rightheader'));
1020
1021             this.username   = new module.UsernameWidget(this,{});
1022             this.username.replace(this.$('.placeholder-UsernameWidget'));
1023
1024             this.action_bar = new module.ActionBarWidget(this);
1025             this.action_bar.replace(this.$(".placeholder-RightActionBar"));
1026
1027             this.left_action_bar = new module.ActionBarWidget(this);
1028             this.left_action_bar.replace(this.$('.placeholder-LeftActionBar'));
1029
1030             this.paypad = new module.PaypadWidget(this, {});
1031             this.paypad.replace(this.$('.placeholder-PaypadWidget'));
1032
1033             this.numpad = new module.NumpadWidget(this);
1034             this.numpad.replace(this.$('.placeholder-NumpadWidget'));
1035
1036             this.order_widget = new module.OrderWidget(this, {});
1037             this.order_widget.replace(this.$('.placeholder-OrderWidget'));
1038
1039             this.onscreen_keyboard = new module.OnscreenKeyboardWidget(this, {
1040                 'keyboard_model': 'simple'
1041             });
1042             this.onscreen_keyboard.replace(this.$('.placeholder-OnscreenKeyboardWidget'));
1043
1044             this.close_button = new module.HeaderButtonWidget(this,{
1045                 label: _t('Close'),
1046                 action: function(){ self.close(); },
1047             });
1048             this.close_button.appendTo(this.$('.pos-rightheader'));
1049
1050             this.client_button = new module.HeaderButtonWidget(this,{
1051                 label: _t('Self-Checkout'),
1052                 action: function(){ self.screen_selector.set_user_mode('client'); },
1053             });
1054             this.client_button.appendTo(this.$('.pos-rightheader'));
1055
1056             
1057             // --------  Screen Selector ---------
1058
1059             this.screen_selector = new module.ScreenSelector({
1060                 pos: this.pos,
1061                 screen_set:{
1062                     'products': this.product_screen,
1063                     'payment' : this.payment_screen,
1064                     'client_payment' : this.client_payment_screen,
1065                     'scale_invite' : this.scale_invite_screen,
1066                     'scale':    this.scale_screen,
1067                     'receipt' : this.receipt_screen,
1068                     'welcome' : this.welcome_screen,
1069                 },
1070                 popup_set:{
1071                     'help': this.help_popup,
1072                     'error': this.error_popup,
1073                     'error-product': this.error_product_popup,
1074                     'error-session': this.error_session_popup,
1075                     'error-negative-price': this.error_negative_price_popup,
1076                     'choose-receipt': this.choose_receipt_popup,
1077                     'error-no-client': this.error_no_client_popup,
1078                     'error-invoice-transfer': this.error_invoice_transfer_popup,
1079                 },
1080                 default_client_screen: 'welcome',
1081                 default_cashier_screen: 'products',
1082                 default_mode: this.pos.config.iface_self_checkout ?  'client' : 'cashier',
1083             });
1084
1085             if(this.pos.debug){
1086                 this.debug_widget = new module.DebugWidget(this);
1087                 this.debug_widget.appendTo(this.$('.pos-content'));
1088             }
1089         },
1090
1091         changed_pending_operations: function () {
1092             var self = this;
1093             this.synch_notification.on_change_nbr_pending(self.pos.get('nbr_pending_operations').length);
1094         },
1095         // shows or hide the numpad and related controls like the paypad.
1096         set_numpad_visible: function(visible){
1097             if(visible !== this.numpad_visible){
1098                 this.numpad_visible = visible;
1099                 if(visible){
1100                     this.set_left_action_bar_visible(false);
1101                     this.numpad.show();
1102                     this.paypad.show();
1103                 }else{
1104                     this.numpad.hide();
1105                     this.paypad.hide();
1106                 }
1107             }
1108         },
1109         set_left_action_bar_visible: function(visible){
1110             if(visible !== this.left_action_bar_visible){
1111                 this.left_action_bar_visible = visible;
1112                 if(visible){
1113                     this.set_numpad_visible(false);
1114                     this.left_action_bar.show();
1115                 }else{
1116                     this.left_action_bar.hide();
1117                 }
1118             }
1119         },
1120         //shows or hide the leftpane (contains the list of orderlines, the numpad, the paypad, etc.)
1121         set_leftpane_visible: function(visible){
1122             if(visible !== this.leftpane_visible){
1123                 this.leftpane_visible = visible;
1124                 if(visible){
1125                     this.$('.pos-leftpane').removeClass('oe_hidden').animate({'width':this.leftpane_width},500,'swing');
1126                     this.$('.pos-rightpane').animate({'left':this.leftpane_width},500,'swing');
1127                 }else{
1128                     var leftpane = this.$('.pos-leftpane');
1129                     leftpane.animate({'width':'0px'},500,'swing', function(){ leftpane.addClass('oe_hidden'); });
1130                     this.$('.pos-rightpane').animate({'left':'0px'},500,'swing');
1131                 }
1132             }
1133         },
1134         //shows or hide the controls in the PosWidget that are specific to the cashier ( Orders, close button, etc. ) 
1135         set_cashier_controls_visible: function(visible){
1136             if(visible !== this.cashier_controls_visible){
1137                 this.cashier_controls_visible = visible;
1138                 if(visible){
1139                     this.$('.pos-rightheader').removeClass('oe_hidden');
1140                 }else{
1141                     this.$('.pos-rightheader').addClass('oe_hidden');
1142                 }
1143             }
1144         },
1145         close: function() {
1146             var self = this;
1147
1148             function close(){
1149                 return new instance.web.Model("ir.model.data").get_func("search_read")([['name', '=', 'action_client_pos_menu']], ['res_id']).pipe(
1150                         _.bind(function(res) {
1151                     return this.rpc('/web/action/load', {'action_id': res[0]['res_id']}).pipe(_.bind(function(result) {
1152                         var action = result;
1153                         action.context = _.extend(action.context || {}, {'cancel_action': {type: 'ir.actions.client', tag: 'reload'}});
1154                         this.do_action(action);
1155                     }, this));
1156                 }, self));
1157             }
1158
1159             var draft_order = _.find( self.pos.get('orders').models, function(order){
1160                 return order.get('orderLines').length !== 0 && order.get('paymentLines').length === 0;
1161             });
1162             if(draft_order){
1163                 if (confirm(_t("Pending orders will be lost.\nAre you sure you want to leave this session?"))) {
1164                     return close();
1165                 }
1166             }else{
1167                 return close();
1168             }
1169         },
1170         destroy: function() {
1171             this.pos.destroy();
1172             instance.webclient.set_content_full_screen(false);
1173             this._super();
1174         }
1175     });
1176 }