[FIX] indentation
[odoo/odoo.git] / addons / website / static / src / js / website.editor.js
1 (function () {
2     'use strict';
3
4     var website = openerp.website;
5     var _t = openerp._t;
6
7     website.add_template_file('/website/static/src/xml/website.editor.xml');
8     website.dom_ready.done(function () {
9         var is_smartphone = $(document.body)[0].clientWidth < 767;
10
11         if (!is_smartphone) {
12             website.ready().then(website.init_editor);
13         }
14
15         $(document).on('click', 'a.js_link2post', function (ev) {
16             ev.preventDefault();
17             website.form(this.pathname, 'POST');
18         });
19
20         $(document).on('submit', '.cke_editable form', function (ev) {
21             // Disable form submition in editable mode
22             ev.preventDefault();
23         });
24
25         $(document).on('hide.bs.dropdown', '.dropdown', function (ev) {
26             // Prevent dropdown closing when a contenteditable children is focused
27             if (ev.originalEvent
28                     && $(ev.target).has(ev.originalEvent.target).length
29                     && $(ev.originalEvent.target).is('[contenteditable]')) {
30                 ev.preventDefault();
31             }
32         });
33     });
34
35     /**
36      * An editing host is an HTML element with @contenteditable=true, or the
37      * child of a document in designMode=on (but that one's not supported)
38      *
39      * https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#editing-host
40      */
41     function is_editing_host(element) {
42         return element.getAttribute('contentEditable') === 'true';
43     }
44     /**
45      * Checks that both the element's content *and the element itself* are
46      * editable: an editing host is considered non-editable because its content
47      * is editable but its attributes should not be considered editable
48      */
49     function is_editable_node(element) {
50         return !(element.data('oe-model') === 'ir.ui.view'
51               || element.data('cke-realelement')
52               || (is_editing_host(element) && element.getAttribute('attributeEditable') !== 'true')
53               || element.isReadOnly());
54     }
55
56     function link_dialog(editor) {
57         return new website.editor.RTELinkDialog(editor).appendTo(document.body);
58     }
59     function image_dialog(editor, image) {
60         return new website.editor.RTEImageDialog(editor, image).appendTo(document.body);
61     }
62
63     // only enable editors manually
64     CKEDITOR.disableAutoInline = true;
65     // EDIT ALL THE THINGS
66     CKEDITOR.dtd.$editable = $.extend(
67         {}, CKEDITOR.dtd.$block, CKEDITOR.dtd.$inline);
68     // Disable removal of empty elements on CKEDITOR activation. Empty
69     // elements are used for e.g. support of FontAwesome icons
70     CKEDITOR.dtd.$removeEmpty = {};
71
72     website.init_editor = function () {
73         CKEDITOR.plugins.add('customdialogs', {
74 //            requires: 'link,image',
75             init: function (editor) {
76                 editor.on('doubleclick', function (evt) {
77                     var element = evt.data.element;
78                     if (element.is('img') && is_editable_node(element)) {
79                         image_dialog(editor, element);
80                         return;
81                     }
82
83                     element = get_selected_link(editor) || evt.data.element;
84                     if (!(element.is('a') && is_editable_node(element))) {
85                         return;
86                     }
87
88                     editor.getSelection().selectElement(element);
89                     link_dialog(editor);
90                 }, null, null, 500);
91
92                 //noinspection JSValidateTypes
93                 editor.addCommand('link', {
94                     exec: function (editor) {
95                         link_dialog(editor);
96                         return true;
97                     },
98                     canUndo: false,
99                     editorFocus: true,
100                 });
101                 //noinspection JSValidateTypes
102                 editor.addCommand('image', {
103                     exec: function (editor) {
104                         image_dialog(editor);
105                         return true;
106                     },
107                     canUndo: false,
108                     editorFocus: true,
109                 });
110
111                 editor.ui.addButton('Link', {
112                     label: 'Link',
113                     command: 'link',
114                     toolbar: 'links,10',
115                 });
116                 editor.ui.addButton('Image', {
117                     label: 'Image',
118                     command: 'image',
119                     toolbar: 'insert,10',
120                 });
121
122                 editor.setKeystroke(CKEDITOR.CTRL + 76 /*L*/, 'link');
123             }
124         });
125         CKEDITOR.plugins.add( 'tablebutton', {
126             requires: 'panelbutton,floatpanel',
127             init: function( editor ) {
128                 var label = "Table";
129
130                 editor.ui.add('TableButton', CKEDITOR.UI_PANELBUTTON, {
131                     label: label,
132                     title: label,
133                     // use existing 'table' icon
134                     icon: 'table',
135                     modes: { wysiwyg: true },
136                     editorFocus: true,
137                     // panel opens in iframe, @css is CSS file <link>-ed within
138                     // frame document, @attributes are set on iframe itself.
139                     panel: {
140                         css: '/website/static/src/css/editor.css',
141                         attributes: { 'role': 'listbox', 'aria-label': label, },
142                     },
143
144                     onBlock: function (panel, block) {
145                         block.autoSize = true;
146                         block.element.setHtml(openerp.qweb.render('website.editor.table.panel', {
147                             rows: 5,
148                             cols: 5,
149                         }));
150
151                         var $table = $(block.element.$).on('mouseenter', 'td', function (e) {
152                             var $e = $(e.target);
153                             var y = $e.index() + 1;
154                             var x = $e.closest('tr').index() + 1;
155
156                             $table
157                                 .find('td').removeClass('selected').end()
158                                 .find('tr:lt(' + String(x) + ')')
159                                 .children().filter(function () { return $(this).index() < y; })
160                                 .addClass('selected');
161                         }).on('click', 'td', function (e) {
162                             var $e = $(e.target);
163
164                             //noinspection JSPotentiallyInvalidConstructorUsage
165                             var table = new CKEDITOR.dom.element(
166                                 $(openerp.qweb.render('website.editor.table', {
167                                     rows: $e.closest('tr').index() + 1,
168                                     cols: $e.index() + 1,
169                                 }))[0]);
170
171                             editor.insertElement(table);
172                             setTimeout(function () {
173                                 //noinspection JSPotentiallyInvalidConstructorUsage
174                                 var firstCell = new CKEDITOR.dom.element(table.$.rows[0].cells[0]);
175                                 var range = editor.createRange();
176                                 range.moveToPosition(firstCell, CKEDITOR.POSITION_AFTER_START);
177                                 range.select();
178                             }, 0);
179                         });
180
181                         block.element.getDocument().getBody().setStyle('overflow', 'hidden');
182                         CKEDITOR.ui.fire('ready', this);
183                     },
184                 });
185             }
186         });
187
188         CKEDITOR.plugins.add('linkstyle', {
189             requires: 'panelbutton,floatpanel',
190             init: function (editor) {
191                 var label = "Link Style";
192
193                 editor.ui.add('LinkStyle', CKEDITOR.UI_PANELBUTTON, {
194                     label: label,
195                     title: label,
196                     icon: '/website/static/src/img/bglink.png',
197                     modes: { wysiwyg: true },
198                     editorFocus: true,
199                     panel: {
200                         css: '/website/static/lib/bootstrap/css/bootstrap.css',
201                         attributes: { 'role': 'listbox', 'aria-label': label },
202                     },
203
204                     types: {
205                         'btn-default': _t("Basic"),
206                         'btn-primary': _t("Primary"),
207                         'btn-success': _t("Success"),
208                         'btn-info': _t("Info"),
209                         'btn-warning': _t("Warning"),
210                         'btn-danger': _t("Danger"),
211                     },
212                     sizes: {
213                         'btn-xs': _t("Extra Small"),
214                         'btn-sm': _t("Small"),
215                         '': _t("Default"),
216                         'btn-lg': _t("Large")
217                     },
218
219                     onRender: function () {
220                         var self = this;
221                         editor.on('selectionChange', function (e) {
222                             var path = e.data.path, el;
223
224                             if (!(e = path.contains('a')) || e.isReadOnly()) {
225                                 self.disable();
226                                 return;
227                             }
228
229                             self.enable();
230                         });
231                         // no hook where button is available, so wait
232                         // "some time" after render.
233                         setTimeout(function () {
234                             self.disable();
235                         }, 0)
236                     },
237                     enable: function () {
238                         this.setState(CKEDITOR.TRISTATE_OFF);
239                     },
240                     disable: function () {
241                         this.setState(CKEDITOR.TRISTATE_DISABLED);
242                     },
243
244                     onOpen: function () {
245                         var link = get_selected_link(editor);
246                         var id = this._.id;
247                         var block = this._.panel._.panel._.blocks[id];
248                         var $root = $(block.element.$);
249                         $root.find('button').removeClass('active').removeProp('disabled');
250
251                         // enable buttons matching link state
252                         for (var type in this.types) {
253                             if (!this.types.hasOwnProperty(type)) { continue; }
254                             if (!link.hasClass(type)) { continue; }
255
256                             $root.find('button[data-type=types].' + type)
257                                  .addClass('active');
258                         }
259                         var found;
260                         for (var size in this.sizes) {
261                             if (!this.sizes.hasOwnProperty(size)) { continue; }
262                             if (!size || !link.hasClass(size)) { continue; }
263                             found = true;
264                             $root.find('button[data-type=sizes].' + size)
265                                  .addClass('active');
266                         }
267                         if (!found && link.hasClass('btn')) {
268                             $root.find('button[data-type="sizes"][data-set-class=""]')
269                                  .addClass('active');
270                         }
271                     },
272
273                     onBlock: function (panel, block) {
274                         var self = this;
275                         block.autoSize = true;
276
277                         var html = ['<div style="padding: 5px">'];
278                         html.push('<div style="white-space: nowrap">');
279                         _(this.types).each(function (label, key) {
280                             html.push(_.str.sprintf(
281                                 '<button type="button" class="btn %s" ' +
282                                         'data-type="types" data-set-class="%s">%s</button>',
283                                 key, key, label));
284                         });
285                         html.push('</div>');
286                         html.push('<div style="white-space: nowrap; margin: 5px 0; text-align: center">');
287                         _(this.sizes).each(function (label, key) {
288                             html.push(_.str.sprintf(
289                                 '<button type="button" class="btn btn-default %s" ' +
290                                         'data-type="sizes" data-set-class="%s">%s</button>',
291                                 key, key, label));
292                         });
293                         html.push('</div>');
294                         html.push('<button type="button" class="btn btn-link btn-block" ' +
295                                           'data-type="reset">Reset</button>');
296                         html.push('</div>');
297
298                         block.element.setHtml(html.join(' '));
299                         var $panel = $(block.element.$);
300                         $panel.on('click', 'button', function () {
301                             self.clicked(this);
302                         });
303                     },
304                     clicked: function (button) {
305                         editor.focus();
306                         editor.fire('saveSnapshot');
307
308                         var $button = $(button),
309                               $link = $(get_selected_link(editor).$);
310                         if (!$link.hasClass('btn')) {
311                             $link.addClass('btn btn-default');
312                         }
313                         switch($button.data('type')) {
314                         case 'reset':
315                             $link.removeClass('btn')
316                                  .removeClass(_.keys(this.types).join(' '))
317                                  .removeClass(_.keys(this.sizes).join(' '));
318                             break;
319                         case 'types':
320                             $link.removeClass(_.keys(this.types).join(' '))
321                                  .addClass($button.data('set-class'));
322                             break;
323                         case 'sizes':
324                             $link.removeClass(_.keys(this.sizes).join(' '))
325                                  .addClass($button.data('set-class'));
326                         }
327                         this._.panel.hide();
328
329                         editor.fire('saveSnapshot');
330                     },
331
332                 });
333             }
334         });
335
336         CKEDITOR.plugins.add('oeref', {
337             requires: 'widget',
338
339             init: function (editor) {
340                 editor.widgets.add('oeref', {
341                     editables: { text: '*' },
342                     draggable: false,
343
344                     upcast: function (el) {
345                         var matches = el.attributes['data-oe-type'] && el.attributes['data-oe-type'] !== 'monetary';
346                         if (!matches) { return false; }
347
348                         if (el.attributes['data-oe-original']) {
349                             while (el.children.length) {
350                                 el.children[0].remove();
351                             }
352                             el.add(new CKEDITOR.htmlParser.text(
353                                 el.attributes['data-oe-original']
354                             ));
355                         }
356                         return true;
357                     },
358                 });
359                 editor.widgets.add('monetary', {
360                     editables: { text: 'span.oe_currency_value' },
361                     draggable: false,
362
363                     upcast: function (el) {
364                         return el.attributes['data-oe-type'] === 'monetary';
365                     }
366                 });
367                 editor.widgets.add('icons', {
368                     draggable: false,
369
370                     init: function () {
371                         this.on('edit', function () {
372                             new website.editor.FontIconsDialog(editor, this.element.$)
373                                 .appendTo(document.body);
374                         });
375                     },
376                     upcast: function (el) {
377                         return el.attributes['class']
378                             && (/\bfa\b/.test(el.attributes['class']));
379                     }
380                 });
381             }
382         });
383
384         var editor = new website.EditorBar();
385         var $body = $(document.body);
386         editor.prependTo($body).then(function () {
387             if (location.search.indexOf("enable_editor") >= 0) {
388                 editor.edit();
389             }
390         });
391     };
392
393     /* ----- TOP EDITOR BAR FOR ADMIN ---- */
394     website.EditorBar = openerp.Widget.extend({
395         template: 'website.editorbar',
396         events: {
397             'click button[data-action=edit]': 'edit',
398             'click button[data-action=save]': 'save',
399             'click a[data-action=cancel]': 'cancel',
400         },
401         container: 'body',
402         customize_setup: function() {
403             var self = this;
404             var view_name = $(document.documentElement).data('view-xmlid');
405             if (!view_name) {
406                 this.$('#customize-menu-button').addClass("hidden");
407             }
408             var menu = $('#customize-menu');
409             this.$('#customize-menu-button').click(function(event) {
410                 menu.empty();
411                 openerp.jsonRpc('/website/customize_template_get', 'call', { 'xml_id': view_name }).then(
412                     function(result) {
413                         _.each(result, function (item) {
414                             if (item.header) {
415                                 menu.append('<li class="dropdown-header">' + item.name + '</li>');
416                             } else {
417                                 menu.append(_.str.sprintf('<li role="presentation"><a href="#" data-view-id="%s" role="menuitem"><strong class="fa fa%s-square-o"></strong> %s</a></li>',
418                                     item.id, item.active ? '-check' : '', item.name));
419                             }
420                         });
421                         // Adding Static Menus
422                         menu.append('<li class="divider"></li>');
423                         menu.append('<li><a data-action="ace" href="#">HTML Editor</a></li>');
424                         menu.append('<li class="js_change_theme"><a href="/page/website.themes">Change Theme</a></li>');
425                         menu.append('<li><a href="/web#return_label=Website&action=website.action_module_website">Install Apps</a></li>');
426                         menu.append('<li><a href="/web#return_label=Website&action=website.action_website_form">Website Settings</a></li>');
427                         self.trigger('rte:customize_menu_ready');
428                     }
429                 );
430             });
431             menu.on('click', 'a[data-action!=ace]', function (event) {
432                 var view_id = $(event.currentTarget).data('view-id');
433                 openerp.jsonRpc('/website/customize_template_toggle', 'call', {
434                     'view_id': view_id
435                 }).then( function() {
436                     window.location.reload();
437                 });
438             });
439         },
440         start: function() {
441             var self = this;
442             this.saving_mutex = new openerp.Mutex();
443
444             this.$('#website-top-edit').hide();
445             this.$('#website-top-view').show();
446
447             $('.dropdown-toggle').dropdown();
448             this.customize_setup();
449
450             this.$buttons = {
451                 edit: this.$('button[data-action=edit]'),
452                 save: this.$('button[data-action=save]'),
453                 cancel: this.$('button[data-action=cancel]'),
454             };
455
456             this.rte = new website.RTE(this);
457             this.rte.on('change', this, this.proxy('rte_changed'));
458             this.rte.on('rte:ready', this, function () {
459                 self.setup_hover_buttons();
460                 self.trigger('rte:ready');
461                 self.check_height();
462             });
463
464             $(window).on('resize', _.debounce(this.check_height.bind(this), 50));
465             this.check_height();
466
467             if (website.is_editable_button) {
468                 this.$("button[data-action=edit]").removeClass("hidden");
469             }
470
471             return $.when(
472                 this._super.apply(this, arguments),
473                 this.rte.appendTo(this.$('#website-top-edit .nav.pull-right'))
474             ).then(function () {
475                 self.check_height();
476             });
477         },
478         check_height: function () {
479             var editor_height = this.$el.outerHeight();
480             if (this.get('height') != editor_height) {
481                 $(document.body).css('padding-top', editor_height);
482                 this.set('height', editor_height);
483             }
484         },
485         edit: function () {
486             this.$buttons.edit.prop('disabled', true);
487             this.$('#website-top-view').hide();
488             this.$('#website-top-edit').show();
489             $('.css_non_editable_mode_hidden').removeClass("css_non_editable_mode_hidden");
490
491             this.rte.start_edition().then(this.check_height.bind(this));
492         },
493         rte_changed: function () {
494             this.$buttons.save.prop('disabled', false);
495         },
496         save: function () {
497             var self = this;
498
499             observer.disconnect();
500             var editor = this.rte.editor;
501             var root = editor.element.$;
502             editor.destroy();
503             // FIXME: select editables then filter by dirty?
504             var defs = this.rte.fetch_editables(root)
505                 .filter('.oe_dirty')
506                 .removeAttr('contentEditable')
507                 .removeClass('oe_dirty oe_editable cke_focus oe_carlos_danger')
508                 .map(function () {
509                     var $el = $(this);
510                     // TODO: Add a queue with concurrency limit in webclient
511                     // https://github.com/medikoo/deferred/blob/master/lib/ext/function/gate.js
512                     return self.saving_mutex.exec(function () {
513                         return self.saveElement($el)
514                             .then(undefined, function (thing, response) {
515                                 // because ckeditor regenerates all the dom,
516                                 // we can't just setup the popover here as
517                                 // everything will be destroyed by the DOM
518                                 // regeneration. Add markings instead, and
519                                 // returns a new rejection with all relevant
520                                 // info
521                                 var id = _.uniqueId('carlos_danger_');
522                                 $el.addClass('oe_dirty oe_carlos_danger');
523                                 $el.addClass(id);
524                                 return $.Deferred().reject({
525                                     id: id,
526                                     error: response.data,
527                                 });
528                             });
529                     });
530                 }).get();
531             return $.when.apply(null, defs).then(function () {
532                 website.reload();
533             }, function (failed) {
534                 // If there were errors, re-enable edition
535                 self.rte.start_edition(true).then(function () {
536                     // jquery's deferred being a pain in the ass
537                     if (!_.isArray(failed)) { failed = [failed]; }
538
539                     _(failed).each(function (failure) {
540                         var html = failure.error.exception_type === "except_osv";
541                         if (html) {
542                             var msg = $("<div/>").text(failure.error.message).html();
543                             var data = msg.substring(3,msg.length-2).split(/', u'/);
544                             failure.error.message = '<b>' + data[0] + '</b><br/>' + data[1];
545                         }
546                         $(root).find('.' + failure.id)
547                             .removeClass(failure.id)
548                             .popover({
549                                 html: html,
550                                 trigger: 'hover',
551                                 content: failure.error.message,
552                                 placement: 'auto top',
553                             })
554                             // Force-show popovers so users will notice them.
555                             .popover('show');
556                     });
557                 });
558             });
559         },
560         /**
561          * Saves an RTE content, which always corresponds to a view section (?).
562          */
563         saveElement: function ($el) {
564             var markup = $el.prop('outerHTML');
565             return openerp.jsonRpc('/web/dataset/call', 'call', {
566                 model: 'ir.ui.view',
567                 method: 'save',
568                 args: [$el.data('oe-id'), markup,
569                        $el.data('oe-xpath') || null,
570                        website.get_context()],
571             });
572         },
573         cancel: function () {
574             new $.Deferred(function (d) {
575                 var $dialog = $(openerp.qweb.render('website.editor.discard')).appendTo(document.body);
576                 $dialog.on('click', '.btn-danger', function () {
577                     d.resolve();
578                 }).on('hidden.bs.modal', function () {
579                     d.reject();
580                 });
581                 d.always(function () {
582                     $dialog.remove();
583                 });
584                 $dialog.modal('show');
585             }).then(function () {
586                 website.reload();
587             })
588         },
589
590         /**
591          * Creates a "hover" button for image and link edition
592          *
593          * @param {String} label the button's label
594          * @param {Function} editfn edition function, called when clicking the button
595          * @param {String} [classes] additional classes to set on the button
596          * @returns {jQuery}
597          */
598         make_hover_button: function (label, editfn, classes) {
599             return $(openerp.qweb.render('website.editor.hoverbutton', {
600                 label: label,
601                 classes: classes,
602             })).hide().appendTo(document.body).click(function (e) {
603                 e.preventDefault();
604                 e.stopPropagation();
605                 editfn.call(this, e);
606             });
607         },
608         /**
609          * For UI clarity, during RTE edition when the user hovers links and
610          * images a small button should appear to make the capability clear,
611          * as not all users think of double-clicking the image or link.
612          */
613         setup_hover_buttons: function () {
614             var editor = this.rte.editor;
615             var $link_button = this.make_hover_button(_t("Change"), function () {
616                 var sel = new CKEDITOR.dom.element(previous);
617                 editor.getSelection().selectElement(sel);
618                 if (previous.tagName.toUpperCase() === 'A') {
619                     link_dialog(editor);
620                 } else if(sel.hasClass('fa')) {
621                     new website.editor.FontIconsDialog(editor, previous)
622                         .appendTo(document.body);
623                 }
624                 $link_button.hide();
625                 previous = null;
626             }, 'btn-xs');
627             var $image_button = this.make_hover_button(_t("Change"), function () {
628                 image_dialog(editor, new CKEDITOR.dom.element(previous));
629                 $image_button.hide();
630                 previous = null;
631             });
632
633             // previous is the state of the button-trigger: it's the
634             // currently-ish hovered element which can trigger a button showing.
635             // -ish, because when moving to the button itself ``previous`` is
636             // still set to the element having triggered showing the button.
637             var previous;
638             $(editor.element.$).on('mouseover', 'a, img, .fa', function () {
639                 // Back from edit button -> ignore
640                 if (previous && previous === this) { return; }
641
642                 var selected = new CKEDITOR.dom.element(this);
643                 if (!is_editable_node(selected) && !selected.hasClass('fa')) {
644                     return;
645                 }
646
647                 previous = this;
648                 var $selected = $(this);
649                 var position = $selected.offset();
650                 if ($selected.is('img')) {
651                     $link_button.hide();
652                     // center button on image
653                     $image_button.show().offset({
654                         top: $selected.outerHeight() / 2
655                                 + position.top
656                                 - $image_button.outerHeight() / 2,
657                         left: $selected.outerWidth() / 2
658                                 + position.left
659                                 - $image_button.outerWidth() / 2,
660                     });
661                 } else {
662                     $image_button.hide();
663                     // put button below link, horizontally centered
664                     $link_button.show().offset({
665                         top: $selected.outerHeight()
666                                 + position.top,
667                         left: $selected.outerWidth() / 2
668                                 + position.left
669                                 - $link_button.outerWidth() / 2
670                     })
671                 }
672             }).on('mouseleave', 'a, img, .fa', function (e) {
673                 var current = document.elementFromPoint(e.clientX, e.clientY);
674                 if (current === $link_button[0] || current === $image_button[0]) {
675                     return;
676                 }
677                 $image_button.add($link_button).hide();
678                 previous = null;
679             });
680         }
681     });
682
683     var blocks_selector = _.keys(CKEDITOR.dtd.$block).join(',');
684     /* ----- RICH TEXT EDITOR ---- */
685     website.RTE = openerp.Widget.extend({
686         tagName: 'li',
687         id: 'oe_rte_toolbar',
688         className: 'oe_right oe_rte_toolbar',
689         // editor.ui.items -> possible commands &al
690         // editor.applyStyle(new CKEDITOR.style({element: "span",styles: {color: "#(color)"},overrides: [{element: "font",attributes: {color: null}}]}, {color: '#ff0000'}));
691
692         init: function (EditorBar) {
693             this.EditorBar = EditorBar;
694             this._super.apply(this, arguments);
695         },
696
697         /**
698          * In Webkit-based browsers, triple-click will select a paragraph up to
699          * the start of the next "paragraph" including any empty space
700          * inbetween. When said paragraph is removed or altered, it nukes
701          * the empty space and brings part of the content of the next
702          * "paragraph" (which may well be e.g. an image) into the current one,
703          * completely fucking up layouts and breaking snippets.
704          *
705          * Try to fuck around with selections on triple-click to attempt to
706          * fix this garbage behavior.
707          *
708          * Note: for consistent behavior we may actually want to take over
709          * triple-clicks, in all browsers in order to ensure consistent cross-
710          * platform behavior instead of being at the mercy of rendering engines
711          * & platform selection quirks?
712          */
713         webkitSelectionFixer: function (root) {
714             root.addEventListener('click', function (e) {
715                 // only webkit seems to have a fucked up behavior, ignore others
716                 // FIXME: $.browser goes away in jquery 1.9...
717                 if (!$.browser.webkit) { return; }
718                 // http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mouseevents
719                 // The detail attribute indicates the number of times a mouse button has been pressed
720                 // we just want the triple click
721                 if (e.detail !== 3) { return; }
722                 e.preventDefault();
723
724                 // Get closest block-level element to the triple-clicked
725                 // element (using ckeditor's block list because why not)
726                 var $closest_block = $(e.target).closest(blocks_selector);
727
728                 // manually set selection range to the content of the
729                 // triple-clicked block-level element, to avoid crossing over
730                 // between block-level elements
731                 document.getSelection().selectAllChildren($closest_block[0]);
732             });
733         },
734         tableNavigation: function (root) {
735             var self = this;
736             $(root).on('keydown', function (e) {
737                 // ignore non-TAB
738                 if (e.which !== 9) { return; }
739
740                 if (self.handleTab(e)) {
741                     e.preventDefault();
742                 }
743             });
744         },
745         /**
746          * Performs whatever operation is necessary on a [TAB] hit, returns
747          * ``true`` if the event's default should be cancelled (if the TAB was
748          * handled by the function)
749          */
750         handleTab: function (event) {
751             var forward = !event.shiftKey;
752
753             var root = window.getSelection().getRangeAt(0).commonAncestorContainer;
754             var $cell = $(root).closest('td,th');
755
756             if (!$cell.length) { return false; }
757
758             var cell = $cell[0];
759
760             // find cell in same row
761             var row = cell.parentNode;
762             var sibling = row.cells[cell.cellIndex + (forward ? 1 : -1)];
763             if (sibling) {
764                 document.getSelection().selectAllChildren(sibling);
765                 return true;
766             }
767
768             // find cell in previous/next row
769             var table = row.parentNode;
770             var sibling_row = table.rows[row.rowIndex + (forward ? 1 : -1)];
771             if (sibling_row) {
772                 var new_cell = sibling_row.cells[forward ? 0 : sibling_row.cells.length - 1];
773                 document.getSelection().selectAllChildren(new_cell);
774                 return true;
775             }
776
777             // at edge cells, copy word/openoffice behavior: if going backwards
778             // from first cell do nothing, if going forwards from last cell add
779             // a row
780             if (forward) {
781                 var row_size = row.cells.length;
782                 var new_row = document.createElement('tr');
783                 while(row_size--) {
784                     var newcell = document.createElement('td');
785                     // zero-width space
786                     newcell.textContent = '\u200B';
787                     new_row.appendChild(newcell);
788                 }
789                 table.appendChild(new_row);
790                 document.getSelection().selectAllChildren(new_row.cells[0]);
791             }
792
793             return true;
794         },
795         /**
796          * Makes the page editable
797          *
798          * @param {Boolean} [restart=false] in case the edition was already set
799          *                                  up once and is being re-enabled.
800          * @returns {$.Deferred} deferred indicating when the RTE is ready
801          */
802         start_edition: function (restart) {
803             var self = this;
804             // create a single editor for the whole page
805             var root = document.getElementById('wrapwrap');
806             if (!restart) {
807                 $(root).on('dragstart', 'img', function (e) {
808                     e.preventDefault();
809                 });
810                 this.webkitSelectionFixer(root);
811                 this.tableNavigation(root);
812             }
813             var def = $.Deferred();
814             var editor = this.editor = CKEDITOR.inline(root, self._config());
815             editor.on('instanceReady', function () {
816                 editor.setReadOnly(false);
817                 // ckeditor set root to editable, disable it (only inner
818                 // sections are editable)
819                 // FIXME: are there cases where the whole editor is editable?
820                 editor.editable().setReadOnly(true);
821
822                 self.setup_editables(root);
823
824                 try {
825                     // disable firefox's broken table resizing thing
826                     document.execCommand("enableObjectResizing", false, "false");
827                     document.execCommand("enableInlineTableEditing", false, "false");
828                 } catch (e) {}
829
830
831                 // detect & setup any CKEDITOR widget within a newly dropped
832                 // snippet. There does not seem to be a simple way to do it for
833                 // HTML not inserted via ckeditor APIs:
834                 // https://dev.ckeditor.com/ticket/11472
835                 $(document.body)
836                     .off('snippet-dropped')
837                     .on('snippet-dropped', function (e, el) {
838                         // CKEDITOR data processor extended by widgets plugin
839                         // to add wrappers around upcasting elements
840                         el.innerHTML = editor.dataProcessor.toHtml(el.innerHTML, {
841                             fixForBody: false,
842                             dontFilter: true,
843                         });
844                         // then repository.initOnAll() handles the conversion
845                         // from wrapper to actual widget instance (or something
846                         // like that).
847                         setTimeout(function () {
848                             editor.widgets.initOnAll();
849                         }, 0);
850                     });
851
852                 self.trigger('rte:ready');
853                 def.resolve();
854             });
855             return def;
856         },
857
858         setup_editables: function (root) {
859             // selection of editable sub-items was previously in
860             // EditorBar#edit, but for some unknown reason the elements were
861             // apparently removed and recreated (?) at editor initalization,
862             // and observer setup was lost.
863             var self = this;
864             // setup dirty-marking for each editable element
865             this.fetch_editables(root)
866                 .addClass('oe_editable')
867                 .each(function () {
868                     var node = this;
869                     var $node = $(node);
870                     // only explicitly set contenteditable on view sections,
871                     // cke widgets system will do the widgets themselves
872                     if ($node.data('oe-model') === 'ir.ui.view') {
873                         node.contentEditable = true;
874                     }
875
876                     observer.observe(node, OBSERVER_CONFIG);
877                     $node.one('content_changed', function () {
878                         $node.addClass('oe_dirty');
879                         self.trigger('change');
880                     });
881                 });
882         },
883
884         fetch_editables: function (root) {
885             return $(root).find('[data-oe-model]')
886                 .not('link, script')
887                 .not('.oe_snippet_editor')
888                 .filter(function () {
889                     var $this = $(this);
890                     // keep view sections and fields which are *not* in
891                     // view sections for top-level editables
892                     return $this.data('oe-model') === 'ir.ui.view'
893                        || !$this.closest('[data-oe-model = "ir.ui.view"]').length;
894                 });
895         },
896
897         _current_editor: function () {
898             return CKEDITOR.currentInstance;
899         },
900         _config: function () {
901             // base plugins minus
902             // - magicline (captures mousein/mouseout -> breaks draggable)
903             // - contextmenu & tabletools (disable contextual menu)
904             // - bunch of unused plugins
905             var plugins = [
906                 'a11yhelp', 'basicstyles', 'blockquote',
907                 'clipboard', 'colorbutton', 'colordialog', 'dialogadvtab',
908                 'elementspath', /*'enterkey',*/ 'entities', 'filebrowser',
909                 'find', 'floatingspace','format', 'htmlwriter', 'iframe',
910                 'indentblock', 'indentlist', 'justify',
911                 'list', 'pastefromword', 'pastetext', 'preview',
912                 'removeformat', 'resize', 'save', 'selectall', 'stylescombo',
913                 'table', 'templates', 'toolbar', 'undo', 'wysiwygarea'
914             ];
915             return {
916                 // FIXME
917                 language: 'en',
918                 // Disable auto-generated titles
919                 // FIXME: accessibility, need to generate user-sensible title, used for @title and @aria-label
920                 title: false,
921                 plugins: plugins.join(','),
922                 uiColor: '',
923                 // FIXME: currently breaks RTE?
924                 // Ensure no config file is loaded
925                 customConfig: '',
926                 // Disable ACF
927                 allowedContent: true,
928                 // Don't insert paragraphs around content in e.g. <li>
929                 autoParagraph: false,
930                 // Don't automatically add &nbsp; or <br> in empty block-level
931                 // elements when edition starts
932                 fillEmptyBlocks: false,
933                 filebrowserImageUploadUrl: "/website/attach",
934                 // Support for sharedSpaces in 4.x
935                 extraPlugins: 'sharedspace,customdialogs,tablebutton,oeref,linkstyle',
936                 // Place toolbar in controlled location
937                 sharedSpaces: { top: 'oe_rte_toolbar' },
938                 toolbar: [{
939                         name: 'basicstyles', items: [
940                         "Bold", "Italic", "Underline", "Strike", "Subscript",
941                         "Superscript", "TextColor", "BGColor", "RemoveFormat"
942                     ]},{
943                     name: 'span', items: [
944                         "Link", "LinkStyle", "Blockquote", "BulletedList",
945                         "NumberedList", "Indent", "Outdent"
946                     ]},{
947                     name: 'justify', items: [
948                         "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"
949                     ]},{
950                     name: 'special', items: [
951                         "Image", "TableButton"
952                     ]},{
953                     name: 'styles', items: [
954                         "Styles"
955                     ]}
956                 ],
957                 // styles dropdown in toolbar
958                 stylesSet: [
959                     {name: "Normal", element: 'p'},
960                     {name: "Heading 1", element: 'h1'},
961                     {name: "Heading 2", element: 'h2'},
962                     {name: "Heading 3", element: 'h3'},
963                     {name: "Heading 4", element: 'h4'},
964                     {name: "Heading 5", element: 'h5'},
965                     {name: "Heading 6", element: 'h6'},
966                     {name: "Formatted", element: 'pre'},
967                     {name: "Address", element: 'address'}
968                 ],
969             };
970         },
971     });
972
973     website.editor = { };
974     website.editor.Dialog = openerp.Widget.extend({
975         events: {
976             'hidden.bs.modal': 'destroy',
977             'click button.save': 'save',
978             'click button[data-dismiss="modal"]': 'cancel',
979         },
980         init: function (editor) {
981             this._super();
982             this.editor = editor;
983         },
984         start: function () {
985             var sup = this._super();
986             this.$el.modal({backdrop: 'static'});
987             return sup;
988         },
989         save: function () {
990             this.close();
991         },
992         cancel: function () {
993         },
994         close: function () {
995             this.$el.modal('hide');
996         },
997     });
998
999     website.editor.LinkDialog = website.editor.Dialog.extend({
1000         template: 'website.editor.dialog.link',
1001         events: _.extend({}, website.editor.Dialog.prototype.events, {
1002             'change :input.url-source': function (e) { this.changed($(e.target)); },
1003             'mousedown': function (e) {
1004                 var $target = $(e.target).closest('.list-group-item');
1005                 if (!$target.length || $target.hasClass('active')) {
1006                     // clicked outside groups, or clicked in active groups
1007                     return;
1008                 }
1009
1010                 this.changed($target.find('.url-source').filter(':input'));
1011             },
1012             'click button.remove': 'remove_link',
1013             'change input#link-text': function (e) {
1014                 this.text = $(e.target).val()
1015             },
1016         }),
1017         init: function (editor) {
1018             this._super(editor);
1019             this.text = null;
1020             // Store last-performed request to be able to cancel/abort it.
1021             this.page_exists_req = null;
1022             this.search_pages_req = null;
1023         },
1024         start: function () {
1025             var self = this;
1026             this.$('#link-page').select2({
1027                 minimumInputLength: 1,
1028                 placeholder: _t("New or existing page"),
1029                 query: function (q) {
1030                     $.when(
1031                         self.page_exists(q.term),
1032                         self.fetch_pages(q.term)
1033                     ).then(function (exists, results) {
1034                         var rs = _.map(results, function (r) {
1035                             return { id: r.url, text: r.name, };
1036                         });
1037                         if (!exists) {
1038                             rs.push({
1039                                 create: true,
1040                                 id: q.term,
1041                                 text: _.str.sprintf(_t("Create page '%s'"), q.term),
1042                             });
1043                         }
1044                         q.callback({
1045                             more: false,
1046                             results: rs
1047                         });
1048                     }, function () {
1049                         q.callback({more: false, results: []});
1050                     });
1051                 },
1052             });
1053             return this._super().then(this.proxy('bind_data'));
1054         },
1055         save: function () {
1056             var self = this, _super = this._super.bind(this);
1057             var $e = this.$('.list-group-item.active .url-source').filter(':input');
1058             var val = $e.val();
1059             if (!val || !$e[0].checkValidity()) {
1060                 // FIXME: error message
1061                 $e.closest('.form-group').addClass('has-error');
1062                 $e.focus();
1063                 return;
1064             }
1065
1066             var done = $.when();
1067             if ($e.hasClass('email-address')) {
1068                 this.make_link('mailto:' + val, false, val);
1069             } else if ($e.hasClass('page')) {
1070                 var data = $e.select2('data');
1071                 if (!data.create) {
1072                     self.make_link(data.id, false, data.text);
1073                 } else {
1074                     // Create the page, get the URL back
1075                     done = $.get(_.str.sprintf(
1076                             '/pagenew/%s?noredirect', encodeURI(data.id)))
1077                         .then(function (response) {
1078                             self.make_link(response, false, data.id);
1079                         });
1080                 }
1081             } else {
1082                 this.make_link(val, this.$('input.window-new').prop('checked'));
1083             }
1084             done.then(_super);
1085         },
1086         make_link: function (url, new_window, label) {
1087         },
1088         bind_data: function (text, href, new_window) {
1089             href = href || this.element && (this.element.data( 'cke-saved-href')
1090                                     ||  this.element.getAttribute('href'));
1091
1092             if (new_window === undefined) {
1093                 new_window = this.element
1094                         ? this.element.getAttribute('target') === '_blank'
1095                         : false;
1096             }
1097             if (text === undefined) {
1098                 text = this.element ? this.element.getText() : '';
1099             }
1100
1101             this.$('input#link-text').val(text);
1102             this.$('input.window-new').prop('checked', new_window);
1103
1104             if (!href) { return; }
1105             var match, $control;
1106             if ((match = /mailto:(.+)/.exec(href))) {
1107                 $control = this.$('input.email-address').val(match[1]);
1108             }
1109             if (!$control) {
1110                 $control = this.$('input.url').val(href);
1111             }
1112
1113             this.changed($control);
1114         },
1115         changed: function ($e) {
1116             this.$('.url-source').filter(':input').not($e).val('')
1117                     .filter(function () { return !!$(this).data('select2'); })
1118                     .select2('data', null);
1119             $e.closest('.list-group-item')
1120                 .addClass('active')
1121                 .siblings().removeClass('active')
1122                 .addBack().removeClass('has-error');
1123         },
1124         call: function (method, args, kwargs) {
1125             var self = this;
1126             var req = method + '_req';
1127
1128             if (this[req]) { this[req].abort(); }
1129
1130             return this[req] = openerp.jsonRpc('/web/dataset/call_kw', 'call', {
1131                 model: 'website',
1132                 method: method,
1133                 args: args,
1134                 kwargs: kwargs,
1135             }).always(function () {
1136                 self[req] = null;
1137             });
1138         },
1139         page_exists: function (term) {
1140             return this.call('page_exists', [null, term], {
1141                 context: website.get_context(),
1142             });
1143         },
1144         fetch_pages: function (term) {
1145             return this.call('search_pages', [null, term], {
1146                 limit: 9,
1147                 context: website.get_context(),
1148             });
1149         },
1150     });
1151     website.editor.RTELinkDialog = website.editor.LinkDialog.extend({
1152         start: function () {
1153             var element;
1154             if ((element = this.get_selected_link()) && element.hasAttribute('href')) {
1155                 this.editor.getSelection().selectElement(element);
1156             }
1157             this.element = element;
1158             if (element) {
1159                 this.add_removal_button();
1160             }
1161
1162             return this._super();
1163         },
1164         add_removal_button: function () {
1165             this.$('.modal-footer').prepend(
1166                 openerp.qweb.render(
1167                     'website.editor.dialog.link.footer-button'));
1168         },
1169         remove_link: function () {
1170             var editor = this.editor;
1171             // same issue as in make_link
1172             setTimeout(function () {
1173                 editor.removeStyle(new CKEDITOR.style({
1174                     element: 'a',
1175                     type: CKEDITOR.STYLE_INLINE,
1176                     alwaysRemoveElement: true,
1177                 }));
1178             }, 0);
1179             this.close();
1180         },
1181         /**
1182          * Greatly simplified version of CKEDITOR's
1183          * plugins.link.dialogs.link.onOk.
1184          *
1185          * @param {String} url
1186          * @param {Boolean} [new_window=false]
1187          * @param {String} [label=null]
1188          */
1189         make_link: function (url, new_window, label) {
1190             var attributes = {href: url, 'data-cke-saved-href': url};
1191             var to_remove = [];
1192             if (new_window) {
1193                 attributes['target'] = '_blank';
1194             } else {
1195                 to_remove.push('target');
1196             }
1197
1198             if (this.element) {
1199                 this.element.setAttributes(attributes);
1200                 this.element.removeAttributes(to_remove);
1201                 if (this.text) { this.element.setText(this.text); }
1202             } else {
1203                 var selection = this.editor.getSelection();
1204                 var range = selection.getRanges(true)[0];
1205
1206                 if (range.collapsed) {
1207                     //noinspection JSPotentiallyInvalidConstructorUsage
1208                     var text = new CKEDITOR.dom.text(
1209                         this.text || label || url);
1210                     range.insertNode(text);
1211                     range.selectNodeContents(text);
1212                 }
1213
1214                 //noinspection JSPotentiallyInvalidConstructorUsage
1215                 new CKEDITOR.style({
1216                     type: CKEDITOR.STYLE_INLINE,
1217                     element: 'a',
1218                     attributes: attributes,
1219                 }).applyToRange(range);
1220
1221                 // focus dance between RTE & dialog blow up the stack in Safari
1222                 // and Chrome, so defer select() until dialog has been closed
1223                 setTimeout(function () {
1224                     range.select();
1225                 }, 0);
1226             }
1227         },
1228         /**
1229          * CKEDITOR.plugins.link.getSelectedLink ignores the editor's root,
1230          * if the editor is set directly on a link it will thus not work.
1231          */
1232         get_selected_link: function () {
1233             return get_selected_link(this.editor);
1234         },
1235     });
1236
1237     /**
1238      * ImageDialog widget. Lets users change an image, including uploading a
1239      * new image in OpenERP or selecting the image style (if supported by
1240      * the caller).
1241      *
1242      * Initialized as usual, but the caller can hook into two events:
1243      *
1244      * @event start({url, style}) called during dialog initialization and
1245      *                            opening, the handler can *set* the ``url``
1246      *                            and ``style`` properties on its parameter
1247      *                            to provide these as default values to the
1248      *                            dialog
1249      * @event save({url, style}) called during dialog finalization, the handler
1250      *                           is provided with the image url and style
1251      *                           selected by the users (or possibly the ones
1252      *                           originally passed in)
1253      */
1254     website.editor.ImageDialog = website.editor.Dialog.extend({
1255         template: 'website.editor.dialog.image',
1256         events: _.extend({}, website.editor.Dialog.prototype.events, {
1257             'change .url-source': function (e) { this.changed($(e.target)); },
1258             'click button.filepicker': function () {
1259                 this.$('input[type=file]').click();
1260             },
1261             'change input[type=file]': 'file_selection',
1262             'change input.url': 'preview_image',
1263             'click a[href=#existing]': 'browse_existing',
1264             'change select.image-style': 'preview_image',
1265         }),
1266
1267         start: function () {
1268             this.$('.modal-footer [disabled]').text("Uploading…");
1269             var $options = this.$('.image-style').children();
1270             this.image_styles = $options.map(function () { return this.value; }).get();
1271
1272             var o = { url: null, style: null, };
1273             // avoid typos, prevent addition of new properties to the object
1274             Object.preventExtensions(o);
1275             this.trigger('start', o);
1276
1277             if (o.url) {
1278                 if (o.style) {
1279                     this.$('.image-style').val(o.style);
1280                 }
1281                 this.set_image(o.url);
1282             }
1283
1284             return this._super();
1285         },
1286         save: function () {
1287             this.trigger('save', {
1288                 url: this.$('input.url').val(),
1289                 style: this.$('.image-style').val(),
1290             });
1291             return this._super();
1292         },
1293         cancel: function () {
1294             this.trigger('cancel');
1295         },
1296
1297         /**
1298          * Sets the provided image url as the dialog's value-to-save and
1299          * refreshes the preview element to use it.
1300          */
1301         set_image: function (url) {
1302             this.$('input.url').val(url);
1303             this.preview_image();
1304         },
1305
1306         file_selection: function () {
1307             this.$el.addClass('nosave');
1308             this.$('button.filepicker').removeClass('btn-danger btn-success');
1309
1310             var self = this;
1311             var callback = _.uniqueId('func_');
1312             this.$('input[name=func]').val(callback);
1313
1314             window[callback] = function (url, error) {
1315                 delete window[callback];
1316                 self.file_selected(url, error);
1317             };
1318             this.$('form').submit();
1319         },
1320         file_selected: function(url, error) {
1321             var $button = this.$('button.filepicker');
1322             if (error) {
1323                 $button.addClass('btn-danger');
1324                 return;
1325             }
1326             $button.addClass('btn-success');
1327             this.set_image(url);
1328         },
1329         preview_image: function () {
1330             this.$el.removeClass('nosave');
1331             var image = this.$('input.url').val();
1332             if (!image) { return; }
1333
1334             this.$('img.image-preview')
1335                 .attr('src', image)
1336                 .removeClass(this.image_styles.join(' '))
1337                 .addClass(this.$('select.image-style').val());
1338         },
1339         browse_existing: function (e) {
1340             e.preventDefault();
1341             new website.editor.ExistingImageDialog(this).appendTo(document.body);
1342         },
1343     });
1344     website.editor.RTEImageDialog = website.editor.ImageDialog.extend({
1345         init: function (editor, image) {
1346             this._super(editor);
1347
1348             this.element = image;
1349
1350             this.on('start', this, this.proxy('started'));
1351             this.on('save', this, this.proxy('saved'));
1352         },
1353         started: function (holder) {
1354             if (!this.element) {
1355                 var selection = this.editor.getSelection();
1356                 this.element = selection && selection.getSelectedElement();
1357             }
1358
1359             var el = this.element;
1360             if (!el || !el.is('img')) {
1361                 return;
1362             }
1363             _(this.image_styles).each(function (style) {
1364                 if (el.hasClass(style)) {
1365                     holder.style = style;
1366                 }
1367             });
1368             holder.url = el.getAttribute('src');
1369         },
1370         saved: function (data) {
1371             var element, editor = this.editor;
1372             if (!(element = this.element)) {
1373                 element = editor.document.createElement('img');
1374                 element.addClass('img');
1375                 element.addClass('img-responsive');
1376                 // focus event handler interactions between bootstrap (modal)
1377                 // and ckeditor (RTE) lead to blowing the stack in Safari and
1378                 // Chrome (but not FF) when this is done synchronously =>
1379                 // defer insertion so modal has been hidden & destroyed before
1380                 // it happens
1381                 setTimeout(function () {
1382                     editor.insertElement(element);
1383                 }, 0);
1384             }
1385
1386             var style = data.style;
1387             element.setAttribute('src', data.url);
1388             element.removeAttribute('data-cke-saved-src');
1389             $(element.$).removeClass(this.image_styles.join(' '));
1390             if (style) { element.addClass(style); }
1391         },
1392     });
1393
1394     var IMAGES_PER_ROW = 6;
1395     var IMAGES_ROWS = 4;
1396     website.editor.ExistingImageDialog = website.editor.Dialog.extend({
1397         template: 'website.editor.dialog.image.existing',
1398         events: _.extend({}, website.editor.Dialog.prototype.events, {
1399             'click .existing-attachments img': 'select_existing',
1400             'click .pager > li': function (e) {
1401                 e.preventDefault();
1402                 var $target = $(e.currentTarget);
1403                 if ($target.hasClass('disabled')) {
1404                     return;
1405                 }
1406                 this.page += $target.hasClass('previous') ? -1 : 1;
1407                 this.display_attachments();
1408             },
1409         }),
1410         init: function (parent) {
1411             this.image = null;
1412             this.page = 0;
1413             this.parent = parent;
1414             this._super(parent.editor);
1415         },
1416
1417         start: function () {
1418             return $.when(
1419                 this._super(),
1420                 this.fetch_existing().then(this.proxy('fetched_existing')));
1421         },
1422
1423         fetch_existing: function () {
1424             return openerp.jsonRpc('/web/dataset/call_kw', 'call', {
1425                 model: 'ir.attachment',
1426                 method: 'search_read',
1427                 args: [],
1428                 kwargs: {
1429                     fields: ['name', 'website_url'],
1430                     domain: [['res_model', '=', 'ir.ui.view']],
1431                     order: 'name',
1432                     context: website.get_context(),
1433                 }
1434             });
1435         },
1436         fetched_existing: function (records) {
1437             this.records = records;
1438             this.display_attachments();
1439         },
1440         display_attachments: function () {
1441             var per_screen = IMAGES_PER_ROW * IMAGES_ROWS;
1442
1443             var from = this.page * per_screen;
1444             var records = this.records;
1445
1446             // Create rows of 3 records
1447             var rows = _(records).chain()
1448                 .slice(from, from + per_screen)
1449                 .groupBy(function (_, index) { return Math.floor(index / IMAGES_PER_ROW); })
1450                 .values()
1451                 .value();
1452
1453             this.$('.existing-attachments').replaceWith(
1454                 openerp.qweb.render(
1455                     'website.editor.dialog.image.existing.content', {rows: rows}));
1456             this.$('.pager')
1457                 .find('li.previous').toggleClass('disabled', (from === 0)).end()
1458                 .find('li.next').toggleClass('disabled', (from + per_screen >= records.length));
1459
1460         },
1461         select_existing: function (e) {
1462             var link = $(e.currentTarget).attr('src');
1463             if (link) {
1464                 this.parent.set_image(link);
1465             }
1466             this.close()
1467         },
1468     });
1469
1470     function get_selected_link(editor) {
1471         var sel = editor.getSelection(),
1472             el = sel.getSelectedElement();
1473         if (el && el.is('a')) { return el; }
1474
1475         var range = sel.getRanges(true)[0];
1476         if (!range) { return null; }
1477
1478         range.shrink(CKEDITOR.SHRINK_TEXT);
1479         var commonAncestor = range.getCommonAncestor();
1480         var viewRoot = editor.elementPath(commonAncestor).contains(function (element) {
1481             return element.data('oe-model') === 'ir.ui.view'
1482         });
1483         if (!viewRoot) { return null; }
1484         // if viewRoot is the first link, don't edit it.
1485         return new CKEDITOR.dom.elementPath(commonAncestor, viewRoot)
1486                 .contains('a', true);
1487     }
1488
1489     website.editor.FontIconsDialog = website.editor.Dialog.extend({
1490         template: 'website.editor.dialog.font-icons',
1491         events : _.extend({}, website.editor.Dialog.prototype.events, {
1492             change: 'update_preview',
1493             'click .font-icons-icon': function (e) {
1494                 e.preventDefault();
1495                 e.stopPropagation();
1496
1497                 this.$('#fa-icon').val(e.target.getAttribute('data-id'));
1498                 this.update_preview();
1499             },
1500             'click #fa-preview span': function (e) {
1501                 e.preventDefault();
1502                 e.stopPropagation();
1503
1504                 this.$('#fa-size').val(e.target.getAttribute('data-size'));
1505                 this.update_preview();
1506             },
1507             'input input#icon-search': function () {
1508                 var needle = this.$('#icon-search').val();
1509                 var icons = this.icons;
1510                 if (needle) {
1511                     icons = _(icons).filter(function (icon) {
1512                         return icon.id.substring(3).indexOf(needle) !== -1;
1513                     });
1514                 }
1515
1516                 this.$('div.font-icons-icons').html(
1517                     openerp.qweb.render(
1518                         'website.editor.dialog.font-icons.icons',
1519                         {icons: icons}));
1520             },
1521         }),
1522
1523         // List of FontAwesome icons in 4.0.3, extracted from the cheatsheet.
1524         // Each icon provides the unicode codepoint as ``text`` and the class
1525         // name as ``id`` so the whole thing can be fed directly to select2
1526         // without post-processing and do the right thing (except for the part
1527         // where we still need to implement ``initSelection``)
1528         // TODO: add id/name to the text in order to allow FAYT selection of icons?
1529         icons: [{"text": "\uf000", "id": "fa-glass"}, {"text": "\uf001", "id": "fa-music"}, {"text": "\uf002", "id": "fa-search"}, {"text": "\uf003", "id": "fa-envelope-o"}, {"text": "\uf004", "id": "fa-heart"}, {"text": "\uf005", "id": "fa-star"}, {"text": "\uf006", "id": "fa-star-o"}, {"text": "\uf007", "id": "fa-user"}, {"text": "\uf008", "id": "fa-film"}, {"text": "\uf009", "id": "fa-th-large"}, {"text": "\uf00a", "id": "fa-th"}, {"text": "\uf00b", "id": "fa-th-list"}, {"text": "\uf00c", "id": "fa-check"}, {"text": "\uf00d", "id": "fa-times"}, {"text": "\uf00e", "id": "fa-search-plus"}, {"text": "\uf010", "id": "fa-search-minus"}, {"text": "\uf011", "id": "fa-power-off"}, {"text": "\uf012", "id": "fa-signal"}, {"text": "\uf013", "id": "fa-cog"}, {"text": "\uf014", "id": "fa-trash-o"}, {"text": "\uf015", "id": "fa-home"}, {"text": "\uf016", "id": "fa-file-o"}, {"text": "\uf017", "id": "fa-clock-o"}, {"text": "\uf018", "id": "fa-road"}, {"text": "\uf019", "id": "fa-download"}, {"text": "\uf01a", "id": "fa-arrow-circle-o-down"}, {"text": "\uf01b", "id": "fa-arrow-circle-o-up"}, {"text": "\uf01c", "id": "fa-inbox"}, {"text": "\uf01d", "id": "fa-play-circle-o"}, {"text": "\uf01e", "id": "fa-repeat"}, {"text": "\uf021", "id": "fa-refresh"}, {"text": "\uf022", "id": "fa-list-alt"}, {"text": "\uf023", "id": "fa-lock"}, {"text": "\uf024", "id": "fa-flag"}, {"text": "\uf025", "id": "fa-headphones"}, {"text": "\uf026", "id": "fa-volume-off"}, {"text": "\uf027", "id": "fa-volume-down"}, {"text": "\uf028", "id": "fa-volume-up"}, {"text": "\uf029", "id": "fa-qrcode"}, {"text": "\uf02a", "id": "fa-barcode"}, {"text": "\uf02b", "id": "fa-tag"}, {"text": "\uf02c", "id": "fa-tags"}, {"text": "\uf02d", "id": "fa-book"}, {"text": "\uf02e", "id": "fa-bookmark"}, {"text": "\uf02f", "id": "fa-print"}, {"text": "\uf030", "id": "fa-camera"}, {"text": "\uf031", "id": "fa-font"}, {"text": "\uf032", "id": "fa-bold"}, {"text": "\uf033", "id": "fa-italic"}, {"text": "\uf034", "id": "fa-text-height"}, {"text": "\uf035", "id": "fa-text-width"}, {"text": "\uf036", "id": "fa-align-left"}, {"text": "\uf037", "id": "fa-align-center"}, {"text": "\uf038", "id": "fa-align-right"}, {"text": "\uf039", "id": "fa-align-justify"}, {"text": "\uf03a", "id": "fa-list"}, {"text": "\uf03b", "id": "fa-outdent"}, {"text": "\uf03c", "id": "fa-indent"}, {"text": "\uf03d", "id": "fa-video-camera"}, {"text": "\uf03e", "id": "fa-picture-o"}, {"text": "\uf040", "id": "fa-pencil"}, {"text": "\uf041", "id": "fa-map-marker"}, {"text": "\uf042", "id": "fa-adjust"}, {"text": "\uf043", "id": "fa-tint"}, {"text": "\uf044", "id": "fa-pencil-square-o"}, {"text": "\uf045", "id": "fa-share-square-o"}, {"text": "\uf046", "id": "fa-check-square-o"}, {"text": "\uf047", "id": "fa-arrows"}, {"text": "\uf048", "id": "fa-step-backward"}, {"text": "\uf049", "id": "fa-fast-backward"}, {"text": "\uf04a", "id": "fa-backward"}, {"text": "\uf04b", "id": "fa-play"}, {"text": "\uf04c", "id": "fa-pause"}, {"text": "\uf04d", "id": "fa-stop"}, {"text": "\uf04e", "id": "fa-forward"}, {"text": "\uf050", "id": "fa-fast-forward"}, {"text": "\uf051", "id": "fa-step-forward"}, {"text": "\uf052", "id": "fa-eject"}, {"text": "\uf053", "id": "fa-chevron-left"}, {"text": "\uf054", "id": "fa-chevron-right"}, {"text": "\uf055", "id": "fa-plus-circle"}, {"text": "\uf056", "id": "fa-minus-circle"}, {"text": "\uf057", "id": "fa-times-circle"}, {"text": "\uf058", "id": "fa-check-circle"}, {"text": "\uf059", "id": "fa-question-circle"}, {"text": "\uf05a", "id": "fa-info-circle"}, {"text": "\uf05b", "id": "fa-crosshairs"}, {"text": "\uf05c", "id": "fa-times-circle-o"}, {"text": "\uf05d", "id": "fa-check-circle-o"}, {"text": "\uf05e", "id": "fa-ban"}, {"text": "\uf060", "id": "fa-arrow-left"}, {"text": "\uf061", "id": "fa-arrow-right"}, {"text": "\uf062", "id": "fa-arrow-up"}, {"text": "\uf063", "id": "fa-arrow-down"}, {"text": "\uf064", "id": "fa-share"}, {"text": "\uf065", "id": "fa-expand"}, {"text": "\uf066", "id": "fa-compress"}, {"text": "\uf067", "id": "fa-plus"}, {"text": "\uf068", "id": "fa-minus"}, {"text": "\uf069", "id": "fa-asterisk"}, {"text": "\uf06a", "id": "fa-exclamation-circle"}, {"text": "\uf06b", "id": "fa-gift"}, {"text": "\uf06c", "id": "fa-leaf"}, {"text": "\uf06d", "id": "fa-fire"}, {"text": "\uf06e", "id": "fa-eye"}, {"text": "\uf070", "id": "fa-eye-slash"}, {"text": "\uf071", "id": "fa-exclamation-triangle"}, {"text": "\uf072", "id": "fa-plane"}, {"text": "\uf073", "id": "fa-calendar"}, {"text": "\uf074", "id": "fa-random"}, {"text": "\uf075", "id": "fa-comment"}, {"text": "\uf076", "id": "fa-magnet"}, {"text": "\uf077", "id": "fa-chevron-up"}, {"text": "\uf078", "id": "fa-chevron-down"}, {"text": "\uf079", "id": "fa-retweet"}, {"text": "\uf07a", "id": "fa-shopping-cart"}, {"text": "\uf07b", "id": "fa-folder"}, {"text": "\uf07c", "id": "fa-folder-open"}, {"text": "\uf07d", "id": "fa-arrows-v"}, {"text": "\uf07e", "id": "fa-arrows-h"}, {"text": "\uf080", "id": "fa-bar-chart-o"}, {"text": "\uf081", "id": "fa-twitter-square"}, {"text": "\uf082", "id": "fa-facebook-square"}, {"text": "\uf083", "id": "fa-camera-retro"}, {"text": "\uf084", "id": "fa-key"}, {"text": "\uf085", "id": "fa-cogs"}, {"text": "\uf086", "id": "fa-comments"}, {"text": "\uf087", "id": "fa-thumbs-o-up"}, {"text": "\uf088", "id": "fa-thumbs-o-down"}, {"text": "\uf089", "id": "fa-star-half"}, {"text": "\uf08a", "id": "fa-heart-o"}, {"text": "\uf08b", "id": "fa-sign-out"}, {"text": "\uf08c", "id": "fa-linkedin-square"}, {"text": "\uf08d", "id": "fa-thumb-tack"}, {"text": "\uf08e", "id": "fa-external-link"}, {"text": "\uf090", "id": "fa-sign-in"}, {"text": "\uf091", "id": "fa-trophy"}, {"text": "\uf092", "id": "fa-github-square"}, {"text": "\uf093", "id": "fa-upload"}, {"text": "\uf094", "id": "fa-lemon-o"}, {"text": "\uf095", "id": "fa-phone"}, {"text": "\uf096", "id": "fa-square-o"}, {"text": "\uf097", "id": "fa-bookmark-o"}, {"text": "\uf098", "id": "fa-phone-square"}, {"text": "\uf099", "id": "fa-twitter"}, {"text": "\uf09a", "id": "fa-facebook"}, {"text": "\uf09b", "id": "fa-github"}, {"text": "\uf09c", "id": "fa-unlock"}, {"text": "\uf09d", "id": "fa-credit-card"}, {"text": "\uf09e", "id": "fa-rss"}, {"text": "\uf0a0", "id": "fa-hdd-o"}, {"text": "\uf0a1", "id": "fa-bullhorn"}, {"text": "\uf0f3", "id": "fa-bell"}, {"text": "\uf0a3", "id": "fa-certificate"}, {"text": "\uf0a4", "id": "fa-hand-o-right"}, {"text": "\uf0a5", "id": "fa-hand-o-left"}, {"text": "\uf0a6", "id": "fa-hand-o-up"}, {"text": "\uf0a7", "id": "fa-hand-o-down"}, {"text": "\uf0a8", "id": "fa-arrow-circle-left"}, {"text": "\uf0a9", "id": "fa-arrow-circle-right"}, {"text": "\uf0aa", "id": "fa-arrow-circle-up"}, {"text": "\uf0ab", "id": "fa-arrow-circle-down"}, {"text": "\uf0ac", "id": "fa-globe"}, {"text": "\uf0ad", "id": "fa-wrench"}, {"text": "\uf0ae", "id": "fa-tasks"}, {"text": "\uf0b0", "id": "fa-filter"}, {"text": "\uf0b1", "id": "fa-briefcase"}, {"text": "\uf0b2", "id": "fa-arrows-alt"}, {"text": "\uf0c0", "id": "fa-users"}, {"text": "\uf0c1", "id": "fa-link"}, {"text": "\uf0c2", "id": "fa-cloud"}, {"text": "\uf0c3", "id": "fa-flask"}, {"text": "\uf0c4", "id": "fa-scissors"}, {"text": "\uf0c5", "id": "fa-files-o"}, {"text": "\uf0c6", "id": "fa-paperclip"}, {"text": "\uf0c7", "id": "fa-floppy-o"}, {"text": "\uf0c8", "id": "fa-square"}, {"text": "\uf0c9", "id": "fa-bars"}, {"text": "\uf0ca", "id": "fa-list-ul"}, {"text": "\uf0cb", "id": "fa-list-ol"}, {"text": "\uf0cc", "id": "fa-strikethrough"}, {"text": "\uf0cd", "id": "fa-underline"}, {"text": "\uf0ce", "id": "fa-table"}, {"text": "\uf0d0", "id": "fa-magic"}, {"text": "\uf0d1", "id": "fa-truck"}, {"text": "\uf0d2", "id": "fa-pinterest"}, {"text": "\uf0d3", "id": "fa-pinterest-square"}, {"text": "\uf0d4", "id": "fa-google-plus-square"}, {"text": "\uf0d5", "id": "fa-google-plus"}, {"text": "\uf0d6", "id": "fa-money"}, {"text": "\uf0d7", "id": "fa-caret-down"}, {"text": "\uf0d8", "id": "fa-caret-up"}, {"text": "\uf0d9", "id": "fa-caret-left"}, {"text": "\uf0da", "id": "fa-caret-right"}, {"text": "\uf0db", "id": "fa-columns"}, {"text": "\uf0dc", "id": "fa-sort"}, {"text": "\uf0dd", "id": "fa-sort-asc"}, {"text": "\uf0de", "id": "fa-sort-desc"}, {"text": "\uf0e0", "id": "fa-envelope"}, {"text": "\uf0e1", "id": "fa-linkedin"}, {"text": "\uf0e2", "id": "fa-undo"}, {"text": "\uf0e3", "id": "fa-gavel"}, {"text": "\uf0e4", "id": "fa-tachometer"}, {"text": "\uf0e5", "id": "fa-comment-o"}, {"text": "\uf0e6", "id": "fa-comments-o"}, {"text": "\uf0e7", "id": "fa-bolt"}, {"text": "\uf0e8", "id": "fa-sitemap"}, {"text": "\uf0e9", "id": "fa-umbrella"}, {"text": "\uf0ea", "id": "fa-clipboard"}, {"text": "\uf0eb", "id": "fa-lightbulb-o"}, {"text": "\uf0ec", "id": "fa-exchange"}, {"text": "\uf0ed", "id": "fa-cloud-download"}, {"text": "\uf0ee", "id": "fa-cloud-upload"}, {"text": "\uf0f0", "id": "fa-user-md"}, {"text": "\uf0f1", "id": "fa-stethoscope"}, {"text": "\uf0f2", "id": "fa-suitcase"}, {"text": "\uf0a2", "id": "fa-bell-o"}, {"text": "\uf0f4", "id": "fa-coffee"}, {"text": "\uf0f5", "id": "fa-cutlery"}, {"text": "\uf0f6", "id": "fa-file-text-o"}, {"text": "\uf0f7", "id": "fa-building-o"}, {"text": "\uf0f8", "id": "fa-hospital-o"}, {"text": "\uf0f9", "id": "fa-ambulance"}, {"text": "\uf0fa", "id": "fa-medkit"}, {"text": "\uf0fb", "id": "fa-fighter-jet"}, {"text": "\uf0fc", "id": "fa-beer"}, {"text": "\uf0fd", "id": "fa-h-square"}, {"text": "\uf0fe", "id": "fa-plus-square"}, {"text": "\uf100", "id": "fa-angle-double-left"}, {"text": "\uf101", "id": "fa-angle-double-right"}, {"text": "\uf102", "id": "fa-angle-double-up"}, {"text": "\uf103", "id": "fa-angle-double-down"}, {"text": "\uf104", "id": "fa-angle-left"}, {"text": "\uf105", "id": "fa-angle-right"}, {"text": "\uf106", "id": "fa-angle-up"}, {"text": "\uf107", "id": "fa-angle-down"}, {"text": "\uf108", "id": "fa-desktop"}, {"text": "\uf109", "id": "fa-laptop"}, {"text": "\uf10a", "id": "fa-tablet"}, {"text": "\uf10b", "id": "fa-mobile"}, {"text": "\uf10c", "id": "fa-circle-o"}, {"text": "\uf10d", "id": "fa-quote-left"}, {"text": "\uf10e", "id": "fa-quote-right"}, {"text": "\uf110", "id": "fa-spinner"}, {"text": "\uf111", "id": "fa-circle"}, {"text": "\uf112", "id": "fa-reply"}, {"text": "\uf113", "id": "fa-github-alt"}, {"text": "\uf114", "id": "fa-folder-o"}, {"text": "\uf115", "id": "fa-folder-open-o"}, {"text": "\uf118", "id": "fa-smile-o"}, {"text": "\uf119", "id": "fa-frown-o"}, {"text": "\uf11a", "id": "fa-meh-o"}, {"text": "\uf11b", "id": "fa-gamepad"}, {"text": "\uf11c", "id": "fa-keyboard-o"}, {"text": "\uf11d", "id": "fa-flag-o"}, {"text": "\uf11e", "id": "fa-flag-checkered"}, {"text": "\uf120", "id": "fa-terminal"}, {"text": "\uf121", "id": "fa-code"}, {"text": "\uf122", "id": "fa-reply-all"}, {"text": "\uf122", "id": "fa-mail-reply-all"}, {"text": "\uf123", "id": "fa-star-half-o"}, {"text": "\uf124", "id": "fa-location-arrow"}, {"text": "\uf125", "id": "fa-crop"}, {"text": "\uf126", "id": "fa-code-fork"}, {"text": "\uf127", "id": "fa-chain-broken"}, {"text": "\uf128", "id": "fa-question"}, {"text": "\uf129", "id": "fa-info"}, {"text": "\uf12a", "id": "fa-exclamation"}, {"text": "\uf12b", "id": "fa-superscript"}, {"text": "\uf12c", "id": "fa-subscript"}, {"text": "\uf12d", "id": "fa-eraser"}, {"text": "\uf12e", "id": "fa-puzzle-piece"}, {"text": "\uf130", "id": "fa-microphone"}, {"text": "\uf131", "id": "fa-microphone-slash"}, {"text": "\uf132", "id": "fa-shield"}, {"text": "\uf133", "id": "fa-calendar-o"}, {"text": "\uf134", "id": "fa-fire-extinguisher"}, {"text": "\uf135", "id": "fa-rocket"}, {"text": "\uf136", "id": "fa-maxcdn"}, {"text": "\uf137", "id": "fa-chevron-circle-left"}, {"text": "\uf138", "id": "fa-chevron-circle-right"}, {"text": "\uf139", "id": "fa-chevron-circle-up"}, {"text": "\uf13a", "id": "fa-chevron-circle-down"}, {"text": "\uf13b", "id": "fa-html5"}, {"text": "\uf13c", "id": "fa-css3"}, {"text": "\uf13d", "id": "fa-anchor"}, {"text": "\uf13e", "id": "fa-unlock-alt"}, {"text": "\uf140", "id": "fa-bullseye"}, {"text": "\uf141", "id": "fa-ellipsis-h"}, {"text": "\uf142", "id": "fa-ellipsis-v"}, {"text": "\uf143", "id": "fa-rss-square"}, {"text": "\uf144", "id": "fa-play-circle"}, {"text": "\uf145", "id": "fa-ticket"}, {"text": "\uf146", "id": "fa-minus-square"}, {"text": "\uf147", "id": "fa-minus-square-o"}, {"text": "\uf148", "id": "fa-level-up"}, {"text": "\uf149", "id": "fa-level-down"}, {"text": "\uf14a", "id": "fa-check-square"}, {"text": "\uf14b", "id": "fa-pencil-square"}, {"text": "\uf14c", "id": "fa-external-link-square"}, {"text": "\uf14d", "id": "fa-share-square"}, {"text": "\uf14e", "id": "fa-compass"}, {"text": "\uf150", "id": "fa-caret-square-o-down"}, {"text": "\uf151", "id": "fa-caret-square-o-up"}, {"text": "\uf152", "id": "fa-caret-square-o-right"}, {"text": "\uf153", "id": "fa-eur"}, {"text": "\uf154", "id": "fa-gbp"}, {"text": "\uf155", "id": "fa-usd"}, {"text": "\uf156", "id": "fa-inr"}, {"text": "\uf157", "id": "fa-jpy"}, {"text": "\uf158", "id": "fa-rub"}, {"text": "\uf159", "id": "fa-krw"}, {"text": "\uf15a", "id": "fa-btc"}, {"text": "\uf15b", "id": "fa-file"}, {"text": "\uf15c", "id": "fa-file-text"}, {"text": "\uf15d", "id": "fa-sort-alpha-asc"}, {"text": "\uf15e", "id": "fa-sort-alpha-desc"}, {"text": "\uf160", "id": "fa-sort-amount-asc"}, {"text": "\uf161", "id": "fa-sort-amount-desc"}, {"text": "\uf162", "id": "fa-sort-numeric-asc"}, {"text": "\uf163", "id": "fa-sort-numeric-desc"}, {"text": "\uf164", "id": "fa-thumbs-up"}, {"text": "\uf165", "id": "fa-thumbs-down"}, {"text": "\uf166", "id": "fa-youtube-square"}, {"text": "\uf167", "id": "fa-youtube"}, {"text": "\uf168", "id": "fa-xing"}, {"text": "\uf169", "id": "fa-xing-square"}, {"text": "\uf16a", "id": "fa-youtube-play"}, {"text": "\uf16b", "id": "fa-dropbox"}, {"text": "\uf16c", "id": "fa-stack-overflow"}, {"text": "\uf16d", "id": "fa-instagram"}, {"text": "\uf16e", "id": "fa-flickr"}, {"text": "\uf170", "id": "fa-adn"}, {"text": "\uf171", "id": "fa-bitbucket"}, {"text": "\uf172", "id": "fa-bitbucket-square"}, {"text": "\uf173", "id": "fa-tumblr"}, {"text": "\uf174", "id": "fa-tumblr-square"}, {"text": "\uf175", "id": "fa-long-arrow-down"}, {"text": "\uf176", "id": "fa-long-arrow-up"}, {"text": "\uf177", "id": "fa-long-arrow-left"}, {"text": "\uf178", "id": "fa-long-arrow-right"}, {"text": "\uf179", "id": "fa-apple"}, {"text": "\uf17a", "id": "fa-windows"}, {"text": "\uf17b", "id": "fa-android"}, {"text": "\uf17c", "id": "fa-linux"}, {"text": "\uf17d", "id": "fa-dribbble"}, {"text": "\uf17e", "id": "fa-skype"}, {"text": "\uf180", "id": "fa-foursquare"}, {"text": "\uf181", "id": "fa-trello"}, {"text": "\uf182", "id": "fa-female"}, {"text": "\uf183", "id": "fa-male"}, {"text": "\uf184", "id": "fa-gittip"}, {"text": "\uf185", "id": "fa-sun-o"}, {"text": "\uf186", "id": "fa-moon-o"}, {"text": "\uf187", "id": "fa-archive"}, {"text": "\uf188", "id": "fa-bug"}, {"text": "\uf189", "id": "fa-vk"}, {"text": "\uf18a", "id": "fa-weibo"}, {"text": "\uf18b", "id": "fa-renren"}, {"text": "\uf18c", "id": "fa-pagelines"}, {"text": "\uf18d", "id": "fa-stack-exchange"}, {"text": "\uf18e", "id": "fa-arrow-circle-o-right"}, {"text": "\uf190", "id": "fa-arrow-circle-o-left"}, {"text": "\uf191", "id": "fa-caret-square-o-left"}, {"text": "\uf192", "id": "fa-dot-circle-o"}, {"text": "\uf193", "id": "fa-wheelchair"}, {"text": "\uf194", "id": "fa-vimeo-square"}, {"text": "\uf195", "id": "fa-try"}, {"text": "\uf196", "id": "fa-plus-square-o"}],
1530         init: function (editor, element) {
1531             this._super(editor);
1532             this.element = element;
1533         },
1534         /**
1535          * Initializes select2: in Chrome and Safari, <select> font apparently
1536          * isn't customizable (?) and the fontawesome glyphs fail to appear.
1537          */
1538         start: function () {
1539             return this._super().then(this.proxy('load_data'));
1540         },
1541         /**
1542          * Removes existing FontAwesome classes on the bound element, and sets
1543          * all the new ones if necessary.
1544          */
1545         save: function () {
1546             var classes = this.element.className.split(/\s+/);
1547             var non_fa_classes = _.reject(classes, function (cls) {
1548                 return cls === 'fa' || /^fa-/.test(cls);
1549             });
1550             var final_classes = non_fa_classes.concat(this.get_fa_classes());
1551             this.element.className = final_classes.join(' ');
1552             this._super();
1553         },
1554         /**
1555          * Looks up the various FontAwesome classes on the bound element and
1556          * sets the corresponding template/form elements to the right state.
1557          * If multiple classes of the same category are present on an element
1558          * (e.g. fa-lg and fa-3x) the last one occurring will be selected,
1559          * which may not match the visual look of the element.
1560          */
1561         load_data: function () {
1562             var classes = this.element.className.split(/\s+/);
1563             for (var i = 0; i < classes.length; i++) {
1564                 var cls = classes[i];
1565                 switch(cls) {
1566                 case 'fa-2x':case 'fa-3x':case 'fa-4x':case 'fa-5x':
1567                     // size classes
1568                     this.$('#fa-size').val(cls);
1569                     continue;
1570                 case 'fa-spin':
1571                 case 'fa-rotate-90':case 'fa-rotate-180':case 'fa-rotate-270':
1572                 case 'fa-flip-horizontal':case 'fa-rotate-vertical':
1573                     this.$('#fa-rotation').val(cls);
1574                     continue;
1575                 case 'fa-fw':
1576                     continue;
1577                 case 'fa-border':
1578                     this.$('#fa-border').prop('checked', true);
1579                     continue;
1580                 default:
1581                     if (!/^fa-/.test(cls)) { continue; }
1582                     this.$('#fa-icon').val(cls);
1583                 }
1584             }
1585             this.update_preview();
1586         },
1587         /**
1588          * Serializes the dialog to an array of FontAwesome classes. Includes
1589          * the base ``fa``.
1590          */
1591         get_fa_classes: function () {
1592             return [
1593                 'fa',
1594                 this.$('#fa-icon').val(),
1595                 this.$('#fa-size').val(),
1596                 this.$('#fa-rotation').val(),
1597                 this.$('#fa-border').prop('checked') ? 'fa-border' : ''
1598             ];
1599         },
1600         update_preview: function () {
1601             var $preview = this.$('#fa-preview').empty();
1602             var sizes = ['', 'fa-2x', 'fa-3x', 'fa-4x', 'fa-5x'];
1603             var classes = this.get_fa_classes();
1604             var no_sizes = _.difference(classes, sizes).join(' ');
1605             var selected = false;
1606             for (var i = sizes.length - 1; i >= 0; i--) {
1607                 var size = sizes[i];
1608
1609                 var $p = $('<span>')
1610                         .attr('data-size', size)
1611                         .addClass(size)
1612                         .addClass(no_sizes);
1613                 if ((size && _.contains(classes, size)) || (!size && !selected)) {
1614                     $p.addClass('font-icons-selected');
1615                     selected = true;
1616                 }
1617                 $preview.prepend($p);
1618             }
1619         }
1620     });
1621
1622     website.Observer = window.MutationObserver || window.WebkitMutationObserver || window.JsMutationObserver;
1623     var OBSERVER_CONFIG = {
1624         childList: true,
1625         attributes: true,
1626         characterData: true,
1627         subtree: true,
1628         attributeOldValue: true,
1629     };
1630     var observer = new website.Observer(function (mutations) {
1631         // NOTE: Webkit does not fire DOMAttrModified => webkit browsers
1632         //       relying on JsMutationObserver shim (Chrome < 18, Safari < 6)
1633         //       will not mark dirty on attribute changes (@class, img/@src,
1634         //       a/@href, ...)
1635         _(mutations).chain()
1636             .filter(function (m) {
1637                 // ignore any change related to mundane image-edit-button
1638                 if (m.target && m.target.className
1639                         && m.target.className.indexOf('image-edit-button') !== -1) {
1640                     return false;
1641                 }
1642                 switch(m.type) {
1643                 case 'attributes': // ignore .cke_focus being added or removed
1644                     // if attribute is not a class, can't be .cke_focus change
1645                     if (m.attributeName !== 'class') { return true; }
1646
1647                     // find out what classes were added or removed
1648                     var oldClasses = (m.oldValue || '').split(/\s+/);
1649                     var newClasses = m.target.className.split(/\s+/);
1650                     var change = _.union(_.difference(oldClasses, newClasses),
1651                                          _.difference(newClasses, oldClasses));
1652                     // ignore mutation if the *only* change is .cke_focus
1653                     return change.length !== 1 || change[0] === 'cke_focus';
1654                 case 'childList':
1655                     // Remove ignorable nodes from addedNodes or removedNodes,
1656                     // if either set remains non-empty it's considered to be an
1657                     // impactful change. Otherwise it's ignored.
1658                     return !!remove_mundane_nodes(m.addedNodes).length ||
1659                            !!remove_mundane_nodes(m.removedNodes).length;
1660                 default:
1661                     return true;
1662                 }
1663             })
1664             .map(function (m) {
1665                 var node = m.target;
1666                 while (node && !$(node).hasClass('oe_editable')) {
1667                     node = node.parentNode;
1668                 }
1669                 return node;
1670             })
1671             .compact()
1672             .uniq()
1673             .each(function (node) { $(node).trigger('content_changed'); })
1674     });
1675     function remove_mundane_nodes(nodes) {
1676         if (!nodes || !nodes.length) { return []; }
1677
1678         var output = [];
1679         for(var i=0; i<nodes.length; ++i) {
1680             var node = nodes[i];
1681             if (node.nodeType === document.ELEMENT_NODE) {
1682                 if (node.nodeName === 'BR' && node.getAttribute('type') === '_moz') {
1683                     // <br type="_moz"> appears when focusing RTE in FF, ignore
1684                     continue;
1685                 }
1686             }
1687
1688             output.push(node);
1689         }
1690         return output;
1691     }
1692 })();