[WIP] point_of_sale: finished css optimisations
[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             this.pos.get('cashRegisters').each(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.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.get('cashier') || this.pos.get('user');
652             }else{
653                 user = this.pos.get('selectedOrder').get_client()  || this.pos.get('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         start: function(){
709             var self = this;
710
711             this.$el.draggable();
712             this.$('.toggle').click(function(){
713                 var content = self.$('.content');
714                 var bg      = self.$el;
715                 if(!self.minimized){
716                     content.animate({'height':'0'},200);
717                 }else{
718                     content.css({'height':'auto'});
719                 }
720                 self.minimized = !self.minimized;
721             });
722             this.$('.button.accept_payment').click(function(){
723                 self.pos.proxy.debug_accept_payment();
724             });
725             this.$('.button.reject_payment').click(function(){
726                 self.pos.proxy.debug_reject_payment();
727             });
728             this.$('.button.set_weight').click(function(){
729                 var kg = Number(self.$('input.weight').val());
730                 if(!isNaN(kg)){
731                     self.pos.proxy.debug_set_weight(kg);
732                 }
733             });
734             this.$('.button.reset_weight').click(function(){
735                 self.$('input.weight').val('');
736                 self.pos.proxy.debug_reset_weight();
737             });
738             this.$('.button.custom_ean').click(function(){
739                 var ean = self.pos.barcode_reader.sanitize_ean(self.$('input.ean').val() || '0');
740                 self.$('input.ean').val(ean);
741                 self.pos.barcode_reader.scan('ean13',ean);
742             });
743             this.$('.button.reference').click(function(){
744                 self.pos.barcode_reader.scan('reference',self.$('input.ean').val());
745             });
746             _.each(this.eans, function(ean, name){
747                 self.$('.button.'+name).click(function(){
748                     self.$('input.ean').val(ean);
749                     self.pos.barcode_reader.scan('ean13',ean);
750                 });
751             });
752             _.each(this.events, function(name){
753                 self.pos.proxy.add_notification(name,function(){
754                     self.$('.event.'+name).stop().clearQueue().css({'background-color':'#6CD11D'}); 
755                     self.$('.event.'+name).animate({'background-color':'#1E1E1E'},2000);
756                 });
757             });
758             self.pos.proxy.add_notification('help_needed',function(){
759                 self.$('.status.help_needed').addClass('on');
760             });
761             self.pos.proxy.add_notification('help_canceled',function(){
762                 self.$('.status.help_needed').removeClass('on');
763             });
764             self.pos.proxy.add_notification('transaction_start',function(){
765                 self.$('.status.transaction').addClass('on');
766             });
767             self.pos.proxy.add_notification('transaction_end',function(){
768                 self.$('.status.transaction').removeClass('on');
769             });
770             self.pos.proxy.add_notification('weighting_start',function(){
771                 self.$('.status.weighting').addClass('on');
772             });
773             self.pos.proxy.add_notification('weighting_end',function(){
774                 self.$('.status.weighting').removeClass('on');
775             });
776         },
777     });
778
779 // ---------- Main Point of Sale Widget ----------
780
781     // this is used to notify the user that data is being synchronized on the network
782     module.SynchNotificationWidget = module.PosBaseWidget.extend({
783         template: "SynchNotificationWidget",
784         init: function(parent, options){
785             options = options || {};
786             this._super(parent, options);
787         },
788         renderElement: function() {
789             var self = this;
790             this._super();
791             this.$el.click(function(){
792                 self.pos.flush();
793             });
794         },
795         start: function(){
796             var self = this;
797             this.pos.bind('change:nbr_pending_operations', function(){
798                 self.renderElement();
799             });
800         },
801         get_nbr_pending: function(){
802             return this.pos.get('nbr_pending_operations');
803         },
804     });
805
806
807     // The PosWidget is the main widget that contains all other widgets in the PointOfSale.
808     // It is mainly composed of :
809     // - a header, containing the list of orders
810     // - a leftpane, containing the list of bought products (orderlines) 
811     // - a rightpane, containing the screens (see pos_screens.js)
812     // - an actionbar on the bottom, containing various action buttons
813     // - popups
814     // - an onscreen keyboard
815     // a screen_selector which controls the switching between screens and the showing/closing of popups
816
817     module.PosWidget = module.PosBaseWidget.extend({
818         template: 'PosWidget',
819         init: function() { 
820             this._super(arguments[0],{});
821
822             instance.web.blockUI(); 
823
824             this.pos = new module.PosModel(this.session);
825             this.pos.pos_widget = this;
826             this.pos_widget = this; //So that pos_widget's childs have pos_widget set automatically
827
828             this.numpad_visible = true;
829             this.left_action_bar_visible = true;
830             this.leftpane_visible = true;
831             this.leftpane_width   = '440px';
832             this.cashier_controls_visible = true;
833             this.image_cache = new module.ImageCache(); // for faster products image display
834
835             FastClick.attach(document.body);
836
837         },
838       
839         start: function() {
840             var self = this;
841             return self.pos.ready.done(function() {
842                 $('.oe_tooltip').remove();  // remove tooltip from the start session button
843                 
844                 // remove default webclient handlers that induce click delay
845                 $(document).off();
846                 $(window).off();
847                 $('html').off();
848                 $('body').off();
849                 $(self.$el).parent().off();
850                 $('document').off();
851                 $('.oe_web_client').off();
852                 $('.openerp_webclient_container').off();
853
854                 /*this.el.addEventHandler('click',function(event){
855                     event.stopPropagation();
856                     event.preventDefault();
857                 });*/
858
859                 self.build_currency_template();
860                 self.renderElement();
861                 
862                 self.$('.neworder-button').click(function(){
863                     self.pos.add_new_order();
864                 });
865
866                 self.$('.deleteorder-button').click(function(){
867                     self.pos.delete_current_order();
868                 });
869                 
870                 //when a new order is created, add an order button widget
871                 self.pos.get('orders').bind('add', function(new_order){
872                     var new_order_button = new module.OrderButtonWidget(null, {
873                         order: new_order,
874                         pos: self.pos
875                     });
876                     new_order_button.appendTo(this.$('.orders'));
877                     new_order_button.selectOrder();
878                 }, self);
879
880                 self.pos.add_new_order();
881
882                 self.build_widgets();
883
884                 if(self.pos.iface_big_scrollbars){
885                     self.$el.addClass('big-scrollbars');
886                 }
887
888                 self.screen_selector.set_default_screen();
889
890                 self.pos.barcode_reader.connect();
891
892                 instance.webclient.set_content_full_screen(true);
893
894                 if (!self.pos.get('pos_session')) {
895                     self.screen_selector.show_popup('error', 'Sorry, we could not create a user session');
896                 }else if(!self.pos.get('pos_config')){
897                     self.screen_selector.show_popup('error', 'Sorry, we could not find any PoS Configuration for this session');
898                 }
899             
900                 instance.web.unblockUI();
901                 self.$('.loader').animate({opacity:0},1500,'swing',function(){self.$('.loader').addClass('oe_hidden');});
902
903                 self.pos.flush();
904
905             }).fail(function(){   // error when loading models data from the backend
906                 instance.web.unblockUI();
907                 return new instance.web.Model("ir.model.data").get_func("search_read")([['name', '=', 'action_pos_session_opening']], ['res_id'])
908                     .pipe( _.bind(function(res){
909                         return instance.session.rpc('/web/action/load', {'action_id': res[0]['res_id']})
910                             .pipe(_.bind(function(result){
911                                 var action = result.result;
912                                 this.do_action(action);
913                             }, this));
914                     }, self));
915             });
916         },
917         
918         // This method instantiates all the screens, widgets, etc. If you want to add new screens change the
919         // startup screen, etc, override this method.
920         build_widgets: function() {
921             var self = this;
922
923             // --------  Screens ---------
924
925             this.product_screen = new module.ProductScreenWidget(this,{});
926             this.product_screen.appendTo(this.$('.screens'));
927
928             this.receipt_screen = new module.ReceiptScreenWidget(this, {});
929             this.receipt_screen.appendTo(this.$('.screens'));
930
931             this.payment_screen = new module.PaymentScreenWidget(this, {});
932             this.payment_screen.appendTo(this.$('.screens'));
933
934             this.welcome_screen = new module.WelcomeScreenWidget(this,{});
935             this.welcome_screen.appendTo(this.$('.screens'));
936
937             this.client_payment_screen = new module.ClientPaymentScreenWidget(this, {});
938             this.client_payment_screen.appendTo(this.$('.screens'));
939
940             this.scale_invite_screen = new module.ScaleInviteScreenWidget(this, {});
941             this.scale_invite_screen.appendTo(this.$('.screens'));
942
943             this.scale_screen = new module.ScaleScreenWidget(this,{});
944             this.scale_screen.appendTo(this.$('.screens'));
945
946             // --------  Popups ---------
947
948             this.help_popup = new module.HelpPopupWidget(this, {});
949             this.help_popup.appendTo(this.$el);
950
951             this.error_popup = new module.ErrorPopupWidget(this, {});
952             this.error_popup.appendTo(this.$el);
953
954             this.error_product_popup = new module.ProductErrorPopupWidget(this, {});
955             this.error_product_popup.appendTo(this.$el);
956
957             this.error_session_popup = new module.ErrorSessionPopupWidget(this, {});
958             this.error_session_popup.appendTo(this.$el);
959
960             this.choose_receipt_popup = new module.ChooseReceiptPopupWidget(this, {});
961             this.choose_receipt_popup.appendTo(this.$el);
962
963             this.error_negative_price_popup = new module.ErrorNegativePricePopupWidget(this, {});
964             this.error_negative_price_popup.appendTo(this.$el);
965
966             this.error_no_client_popup = new module.ErrorNoClientPopupWidget(this, {});
967             this.error_no_client_popup.appendTo(this.$el);
968
969             this.error_invoice_transfer_popup = new module.ErrorInvoiceTransferPopupWidget(this, {});
970             this.error_invoice_transfer_popup.appendTo(this.$el);
971
972             // --------  Misc ---------
973
974             this.notification = new module.SynchNotificationWidget(this,{});
975             this.notification.appendTo(this.$('.pos-rightheader'));
976
977             this.username   = new module.UsernameWidget(this,{});
978             this.username.replace(this.$('.placeholder-UsernameWidget'));
979
980             this.action_bar = new module.ActionBarWidget(this);
981             this.action_bar.replace(this.$(".placeholder-RightActionBar"));
982
983             this.left_action_bar = new module.ActionBarWidget(this);
984             this.left_action_bar.replace(this.$('.placeholder-LeftActionBar'));
985
986             this.paypad = new module.PaypadWidget(this, {});
987             this.paypad.replace(this.$('.placeholder-PaypadWidget'));
988
989             this.numpad = new module.NumpadWidget(this);
990             this.numpad.replace(this.$('.placeholder-NumpadWidget'));
991
992             this.order_widget = new module.OrderWidget(this, {});
993             this.order_widget.replace(this.$('.placeholder-OrderWidget'));
994
995             this.onscreen_keyboard = new module.OnscreenKeyboardWidget(this, {
996                 'keyboard_model': 'simple'
997             });
998             this.onscreen_keyboard.replace(this.$('.placeholder-OnscreenKeyboardWidget'));
999
1000             this.close_button = new module.HeaderButtonWidget(this,{
1001                 label: _t('Close'),
1002                 action: function(){ self.close(); },
1003             });
1004             this.close_button.appendTo(this.$('.pos-rightheader'));
1005
1006             this.client_button = new module.HeaderButtonWidget(this,{
1007                 label: _t('Self-Checkout'),
1008                 action: function(){ self.screen_selector.set_user_mode('client'); },
1009             });
1010             this.client_button.appendTo(this.$('.pos-rightheader'));
1011
1012             
1013             // --------  Screen Selector ---------
1014
1015             this.screen_selector = new module.ScreenSelector({
1016                 pos: this.pos,
1017                 screen_set:{
1018                     'products': this.product_screen,
1019                     'payment' : this.payment_screen,
1020                     'client_payment' : this.client_payment_screen,
1021                     'scale_invite' : this.scale_invite_screen,
1022                     'scale':    this.scale_screen,
1023                     'receipt' : this.receipt_screen,
1024                     'welcome' : this.welcome_screen,
1025                 },
1026                 popup_set:{
1027                     'help': this.help_popup,
1028                     'error': this.error_popup,
1029                     'error-product': this.error_product_popup,
1030                     'error-session': this.error_session_popup,
1031                     'error-negative-price': this.error_negative_price_popup,
1032                     'choose-receipt': this.choose_receipt_popup,
1033                     'error-no-client': this.error_no_client_popup,
1034                     'error-invoice-transfer': this.error_invoice_transfer_popup,
1035                 },
1036                 default_client_screen: 'welcome',
1037                 default_cashier_screen: 'products',
1038                 default_mode: this.pos.iface_self_checkout ?  'client' : 'cashier',
1039             });
1040
1041             if(this.pos.debug){
1042                 this.debug_widget = new module.DebugWidget(this);
1043                 this.debug_widget.appendTo(this.$('.pos-content'));
1044             }
1045         },
1046
1047         changed_pending_operations: function () {
1048             var self = this;
1049             this.synch_notification.on_change_nbr_pending(self.pos.get('nbr_pending_operations').length);
1050         },
1051         // shows or hide the numpad and related controls like the paypad.
1052         set_numpad_visible: function(visible){
1053             if(visible !== this.numpad_visible){
1054                 this.numpad_visible = visible;
1055                 if(visible){
1056                     this.set_left_action_bar_visible(false);
1057                     this.numpad.show();
1058                     this.paypad.show();
1059                 }else{
1060                     this.numpad.hide();
1061                     this.paypad.hide();
1062                 }
1063             }
1064         },
1065         set_left_action_bar_visible: function(visible){
1066             if(visible !== this.left_action_bar_visible){
1067                 this.left_action_bar_visible = visible;
1068                 if(visible){
1069                     this.set_numpad_visible(false);
1070                     this.left_action_bar.show();
1071                 }else{
1072                     this.left_action_bar.hide();
1073                 }
1074             }
1075         },
1076         //shows or hide the leftpane (contains the list of orderlines, the numpad, the paypad, etc.)
1077         set_leftpane_visible: function(visible){
1078             if(visible !== this.leftpane_visible){
1079                 this.leftpane_visible = visible;
1080                 if(visible){
1081                     this.$('.pos-leftpane').removeClass('oe_hidden').animate({'width':this.leftpane_width},500,'swing');
1082                     this.$('.pos-rightpane').animate({'left':this.leftpane_width},500,'swing');
1083                 }else{
1084                     var leftpane = this.$('.pos-leftpane');
1085                     leftpane.animate({'width':'0px'},500,'swing', function(){ leftpane.addClass('oe_hidden'); });
1086                     this.$('.pos-rightpane').animate({'left':'0px'},500,'swing');
1087                 }
1088             }
1089         },
1090         //shows or hide the controls in the PosWidget that are specific to the cashier ( Orders, close button, etc. ) 
1091         set_cashier_controls_visible: function(visible){
1092             if(visible !== this.cashier_controls_visible){
1093                 this.cashier_controls_visible = visible;
1094                 if(visible){
1095                     this.$('.pos-rightheader').removeClass('oe_hidden');
1096                 }else{
1097                     this.$('.pos-rightheader').addClass('oe_hidden');
1098                 }
1099             }
1100         },
1101         close: function() {
1102             var self = this;
1103
1104             function close(){
1105                 return new instance.web.Model("ir.model.data").get_func("search_read")([['name', '=', 'action_client_pos_menu']], ['res_id']).pipe(
1106                         _.bind(function(res) {
1107                     return this.rpc('/web/action/load', {'action_id': res[0]['res_id']}).pipe(_.bind(function(result) {
1108                         var action = result;
1109                         action.context = _.extend(action.context || {}, {'cancel_action': {type: 'ir.actions.client', tag: 'reload'}});
1110                         this.do_action(action);
1111                     }, this));
1112                 }, self));
1113             }
1114
1115             var draft_order = _.find( self.pos.get('orders').models, function(order){
1116                 return order.get('orderLines').length !== 0 && order.get('paymentLines').length === 0;
1117             });
1118             if(draft_order){
1119                 if (confirm(_t("Pending orders will be lost.\nAre you sure you want to leave this session?"))) {
1120                     return close();
1121                 }
1122             }else{
1123                 return close();
1124             }
1125         },
1126         destroy: function() {
1127             this.pos.destroy();
1128             instance.webclient.set_content_full_screen(false);
1129             this._super();
1130         }
1131     });
1132 }