[FIX] sprurious widgetification and editability of icon elements
[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         } else {
14             // remove padding of fake editor bar
15             document.body.style.padding = 0;
16         }
17
18         $(document).on('click', 'a.js_link2post', function (ev) {
19             ev.preventDefault();
20             website.form(this.pathname, 'POST');
21         });
22
23         $(document).on('click', '.cke_editable label', function (ev) {
24             ev.preventDefault();
25         });
26
27         $(document).on('submit', '.cke_editable form', function (ev) {
28             // Disable form submition in editable mode
29             ev.preventDefault();
30         });
31
32         $(document).on('hide.bs.dropdown', '.dropdown', function (ev) {
33             // Prevent dropdown closing when a contenteditable children is focused
34             if (ev.originalEvent
35                     && $(ev.target).has(ev.originalEvent.target).length
36                     && $(ev.originalEvent.target).is('[contenteditable]')) {
37                 ev.preventDefault();
38             }
39         });
40     });
41
42     /**
43      * An editing host is an HTML element with @contenteditable=true, or the
44      * child of a document in designMode=on (but that one's not supported)
45      *
46      * https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#editing-host
47      */
48     function is_editing_host(element) {
49         return element.getAttribute('contentEditable') === 'true';
50     }
51     /**
52      * Checks that both the element's content *and the element itself* are
53      * editable: an editing host is considered non-editable because its content
54      * is editable but its attributes should not be considered editable
55      */
56     function is_editable_node(element) {
57         return !(element.data('oe-model') === 'ir.ui.view'
58               || element.data('cke-realelement')
59               || (is_editing_host(element) && element.getAttribute('attributeEditable') !== 'true')
60               || element.isReadOnly());
61     }
62
63     function link_dialog(editor) {
64         return new website.editor.RTELinkDialog(editor).appendTo(document.body);
65     }
66     function image_dialog(editor, image) {
67         return new website.editor.RTEImageDialog(editor, image).appendTo(document.body);
68     }
69
70     // only enable editors manually
71     CKEDITOR.disableAutoInline = true;
72     // EDIT ALL THE THINGS
73     CKEDITOR.dtd.$editable = _.omit(
74         $.extend({}, CKEDITOR.dtd.$block, CKEDITOR.dtd.$inline),
75         // well maybe not *all* the things
76         'ul', 'ol', 'li', 'table', 'tr', 'th', 'td');
77     // Disable removal of empty elements on CKEDITOR activation. Empty
78     // elements are used for e.g. support of FontAwesome icons
79     CKEDITOR.dtd.$removeEmpty = {};
80
81     website.init_editor = function () {
82         CKEDITOR.plugins.add('customdialogs', {
83 //            requires: 'link,image',
84             init: function (editor) {
85                 editor.on('doubleclick', function (evt) {
86                     var element = evt.data.element;
87                     if (element.is('img') && is_editable_node(element)) {
88                         image_dialog(editor, element);
89                         return;
90                     }
91
92                     element = get_selected_link(editor) || evt.data.element;
93                     if (!(element.is('a') && is_editable_node(element))) {
94                         return;
95                     }
96
97                     editor.getSelection().selectElement(element);
98                     link_dialog(editor);
99                 }, null, null, 500);
100
101                 //noinspection JSValidateTypes
102                 editor.addCommand('link', {
103                     exec: function (editor) {
104                         link_dialog(editor);
105                         return true;
106                     },
107                     canUndo: false,
108                     editorFocus: true,
109                 });
110                 //noinspection JSValidateTypes
111                 editor.addCommand('image', {
112                     exec: function (editor) {
113                         image_dialog(editor);
114                         return true;
115                     },
116                     canUndo: false,
117                     editorFocus: true,
118                 });
119
120                 editor.ui.addButton('Link', {
121                     label: 'Link',
122                     command: 'link',
123                     toolbar: 'links,10',
124                 });
125                 editor.ui.addButton('Image', {
126                     label: 'Image',
127                     command: 'image',
128                     toolbar: 'insert,10',
129                 });
130
131                 editor.setKeystroke(CKEDITOR.CTRL + 76 /*L*/, 'link');
132             }
133         });
134         CKEDITOR.plugins.add( 'tablebutton', {
135             requires: 'panelbutton,floatpanel',
136             init: function( editor ) {
137                 var label = "Table";
138
139                 editor.ui.add('TableButton', CKEDITOR.UI_PANELBUTTON, {
140                     label: label,
141                     title: label,
142                     // use existing 'table' icon
143                     icon: 'table',
144                     modes: { wysiwyg: true },
145                     editorFocus: true,
146                     // panel opens in iframe, @css is CSS file <link>-ed within
147                     // frame document, @attributes are set on iframe itself.
148                     panel: {
149                         css: '/website/static/src/css/editor.css',
150                         attributes: { 'role': 'listbox', 'aria-label': label, },
151                     },
152
153                     onBlock: function (panel, block) {
154                         block.autoSize = true;
155                         block.element.setHtml(openerp.qweb.render('website.editor.table.panel', {
156                             rows: 5,
157                             cols: 5,
158                         }));
159
160                         var $table = $(block.element.$).on('mouseenter', 'td', function (e) {
161                             var $e = $(e.target);
162                             var y = $e.index() + 1;
163                             var x = $e.closest('tr').index() + 1;
164
165                             $table
166                                 .find('td').removeClass('selected').end()
167                                 .find('tr:lt(' + String(x) + ')')
168                                 .children().filter(function () { return $(this).index() < y; })
169                                 .addClass('selected');
170                         }).on('click', 'td', function (e) {
171                             var $e = $(e.target);
172
173                             //noinspection JSPotentiallyInvalidConstructorUsage
174                             var table = new CKEDITOR.dom.element(
175                                 $(openerp.qweb.render('website.editor.table', {
176                                     rows: $e.closest('tr').index() + 1,
177                                     cols: $e.index() + 1,
178                                 }))[0]);
179
180                             editor.insertElement(table);
181                             setTimeout(function () {
182                                 //noinspection JSPotentiallyInvalidConstructorUsage
183                                 var firstCell = new CKEDITOR.dom.element(table.$.rows[0].cells[0]);
184                                 var range = editor.createRange();
185                                 range.moveToPosition(firstCell, CKEDITOR.POSITION_AFTER_START);
186                                 range.select();
187                             }, 0);
188                         });
189
190                         block.element.getDocument().getBody().setStyle('overflow', 'hidden');
191                         CKEDITOR.ui.fire('ready', this);
192                     },
193                 });
194             }
195         });
196
197         CKEDITOR.plugins.add('linkstyle', {
198             requires: 'panelbutton,floatpanel',
199             init: function (editor) {
200                 var label = "Link Style";
201
202                 editor.ui.add('LinkStyle', CKEDITOR.UI_PANELBUTTON, {
203                     label: label,
204                     title: label,
205                     icon: '/website/static/src/img/bglink.png',
206                     modes: { wysiwyg: true },
207                     editorFocus: true,
208                     panel: {
209                         css: '/website/static/lib/bootstrap/css/bootstrap.css',
210                         attributes: { 'role': 'listbox', 'aria-label': label },
211                     },
212
213                     types: {
214                         'btn-default': _t("Basic"),
215                         'btn-primary': _t("Primary"),
216                         'btn-success': _t("Success"),
217                         'btn-info': _t("Info"),
218                         'btn-warning': _t("Warning"),
219                         'btn-danger': _t("Danger"),
220                     },
221                     sizes: {
222                         'btn-xs': _t("Extra Small"),
223                         'btn-sm': _t("Small"),
224                         '': _t("Default"),
225                         'btn-lg': _t("Large")
226                     },
227
228                     onRender: function () {
229                         var self = this;
230                         editor.on('selectionChange', function (e) {
231                             var path = e.data.path, el;
232
233                             if (!(e = path.contains('a')) || e.isReadOnly()) {
234                                 self.disable();
235                                 return;
236                             }
237
238                             self.enable();
239                         });
240                         // no hook where button is available, so wait
241                         // "some time" after render.
242                         setTimeout(function () {
243                             self.disable();
244                         }, 0)
245                     },
246                     enable: function () {
247                         this.setState(CKEDITOR.TRISTATE_OFF);
248                     },
249                     disable: function () {
250                         this.setState(CKEDITOR.TRISTATE_DISABLED);
251                     },
252
253                     onOpen: function () {
254                         var link = get_selected_link(editor);
255                         var id = this._.id;
256                         var block = this._.panel._.panel._.blocks[id];
257                         var $root = $(block.element.$);
258                         $root.find('button').removeClass('active').removeProp('disabled');
259
260                         // enable buttons matching link state
261                         for (var type in this.types) {
262                             if (!this.types.hasOwnProperty(type)) { continue; }
263                             if (!link.hasClass(type)) { continue; }
264
265                             $root.find('button[data-type=types].' + type)
266                                  .addClass('active');
267                         }
268                         var found;
269                         for (var size in this.sizes) {
270                             if (!this.sizes.hasOwnProperty(size)) { continue; }
271                             if (!size || !link.hasClass(size)) { continue; }
272                             found = true;
273                             $root.find('button[data-type=sizes].' + size)
274                                  .addClass('active');
275                         }
276                         if (!found && link.hasClass('btn')) {
277                             $root.find('button[data-type="sizes"][data-set-class=""]')
278                                  .addClass('active');
279                         }
280                     },
281
282                     onBlock: function (panel, block) {
283                         var self = this;
284                         block.autoSize = true;
285
286                         var html = ['<div style="padding: 5px">'];
287                         html.push('<div style="white-space: nowrap">');
288                         _(this.types).each(function (label, key) {
289                             html.push(_.str.sprintf(
290                                 '<button type="button" class="btn %s" ' +
291                                         'data-type="types" data-set-class="%s">%s</button>',
292                                 key, key, label));
293                         });
294                         html.push('</div>');
295                         html.push('<div style="white-space: nowrap; margin: 5px 0; text-align: center">');
296                         _(this.sizes).each(function (label, key) {
297                             html.push(_.str.sprintf(
298                                 '<button type="button" class="btn btn-default %s" ' +
299                                         'data-type="sizes" data-set-class="%s">%s</button>',
300                                 key, key, label));
301                         });
302                         html.push('</div>');
303                         html.push('<button type="button" class="btn btn-link btn-block" ' +
304                                           'data-type="reset">Reset</button>');
305                         html.push('</div>');
306
307                         block.element.setHtml(html.join(' '));
308                         var $panel = $(block.element.$);
309                         $panel.on('click', 'button', function () {
310                             self.clicked(this);
311                         });
312                     },
313                     clicked: function (button) {
314                         editor.focus();
315                         editor.fire('saveSnapshot');
316
317                         var $button = $(button),
318                               $link = $(get_selected_link(editor).$);
319                         if (!$link.hasClass('btn')) {
320                             $link.addClass('btn btn-default');
321                         }
322                         switch($button.data('type')) {
323                         case 'reset':
324                             $link.removeClass('btn')
325                                  .removeClass(_.keys(this.types).join(' '))
326                                  .removeClass(_.keys(this.sizes).join(' '));
327                             break;
328                         case 'types':
329                             $link.removeClass(_.keys(this.types).join(' '))
330                                  .addClass($button.data('set-class'));
331                             break;
332                         case 'sizes':
333                             $link.removeClass(_.keys(this.sizes).join(' '))
334                                  .addClass($button.data('set-class'));
335                         }
336                         this._.panel.hide();
337
338                         editor.fire('saveSnapshot');
339                     },
340
341                 });
342             }
343         });
344
345         CKEDITOR.plugins.add('oeref', {
346             requires: 'widget',
347
348             init: function (editor) {
349                 editor.widgets.add('oeref', {
350                     editables: { text: '*' },
351                     draggable: false,
352
353                     upcast: function (el) {
354                         var matches = el.attributes['data-oe-type'] && el.attributes['data-oe-type'] !== 'monetary';
355                         if (!matches) { return false; }
356
357                         if (el.attributes['data-oe-original']) {
358                             while (el.children.length) {
359                                 el.children[0].remove();
360                             }
361                             el.add(new CKEDITOR.htmlParser.text(
362                                 el.attributes['data-oe-original']
363                             ));
364                         }
365                         return true;
366                     },
367                 });
368                 editor.widgets.add('monetary', {
369                     editables: { text: 'span.oe_currency_value' },
370                     draggable: false,
371
372                     upcast: function (el) {
373                         return el.attributes['data-oe-type'] === 'monetary';
374                     }
375                 });
376                 editor.widgets.add('icons', {
377                     draggable: false,
378
379                     init: function () {
380                         this.on('edit', function () {
381                             new website.editor.FontIconsDialog(editor, this.element.$)
382                                 .appendTo(document.body);
383                         });
384                     },
385                     upcast: function (el) {
386                         return el.hasClass('fa')
387                             // ignore ir.ui.view (other data-oe-model should
388                             // already have been matched by oeref and
389                             // monetary?
390                             && !el.attributes['data-oe-model'];
391                     }
392                 });
393             }
394         });
395
396         var editor = new website.EditorBar();
397         var $body = $(document.body);
398         editor.prependTo($body).then(function () {
399             if (location.search.indexOf("enable_editor") >= 0) {
400                 editor.edit();
401             }
402         });
403     };
404
405     /* ----- TOP EDITOR BAR FOR ADMIN ---- */
406     website.EditorBar = openerp.Widget.extend({
407         template: 'website.editorbar',
408         events: {
409             'click button[data-action=edit]': 'edit',
410             'click button[data-action=save]': 'save',
411             'click a[data-action=cancel]': 'cancel',
412         },
413         container: 'body',
414         customize_setup: function() {
415             var self = this;
416             var view_name = $(document.documentElement).data('view-xmlid');
417             if (!view_name) {
418                 this.$('#customize-menu-button').addClass("hidden");
419             }
420             var menu = $('#customize-menu');
421             this.$('#customize-menu-button').click(function(event) {
422                 menu.empty();
423                 openerp.jsonRpc('/website/customize_template_get', 'call', { 'xml_id': view_name }).then(
424                     function(result) {
425                         _.each(result, function (item) {
426                             if (item.xml_id === "website.debugger" && !window.location.search.match(/[&?]debug(&|$)/)) return;
427                             if (item.header) {
428                                 menu.append('<li class="dropdown-header">' + item.name + '</li>');
429                             } else {
430                                 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>',
431                                     item.id, item.active ? '-check' : '', item.name));
432                             }
433                         });
434                         // Adding Static Menus
435                         menu.append('<li class="divider"></li>');
436                         menu.append('<li><a data-action="ace" href="#">HTML Editor</a></li>');
437                         menu.append('<li class="js_change_theme"><a href="/page/website.themes">Change Theme</a></li>');
438                         menu.append('<li><a href="/web#return_label=Website&action=website.action_module_website">Install Apps</a></li>');
439                         self.trigger('rte:customize_menu_ready');
440                     }
441                 );
442             });
443             menu.on('click', 'a[data-action!=ace]', function (event) {
444                 var view_id = $(event.currentTarget).data('view-id');
445                 openerp.jsonRpc('/website/customize_template_toggle', 'call', {
446                     'view_id': view_id
447                 }).then( function() {
448                     window.location.reload();
449                 });
450             });
451         },
452         start: function() {
453             // remove placeholder editor bar
454             var fakebar = document.getElementById('website-top-navbar-placeholder');
455             if (fakebar) {
456                 fakebar.parentNode.removeChild(fakebar);
457             }
458
459             var self = this;
460             this.saving_mutex = new openerp.Mutex();
461
462             this.$('#website-top-edit').hide();
463             this.$('#website-top-view').show();
464
465             $('.dropdown-toggle').dropdown();
466             this.customize_setup();
467
468             this.$buttons = {
469                 edit: this.$('button[data-action=edit]'),
470                 save: this.$('button[data-action=save]'),
471                 cancel: this.$('button[data-action=cancel]'),
472             };
473
474             this.rte = new website.RTE(this);
475             this.rte.on('change', this, this.proxy('rte_changed'));
476             this.rte.on('rte:ready', this, function () {
477                 self.setup_hover_buttons();
478                 self.trigger('rte:ready');
479                 self.check_height();
480             });
481
482             $(window).on('resize', _.debounce(this.check_height.bind(this), 50));
483             this.check_height();
484
485             if (website.is_editable_button) {
486                 this.$("button[data-action=edit]").removeClass("hidden");
487             }
488
489             return $.when(
490                 this._super.apply(this, arguments),
491                 this.rte.appendTo(this.$('#website-top-edit .nav.pull-right'))
492             ).then(function () {
493                 self.check_height();
494             });
495         },
496         check_height: function () {
497             var editor_height = this.$el.outerHeight();
498             if (this.get('height') != editor_height) {
499                 $(document.body).css('padding-top', editor_height);
500                 this.set('height', editor_height);
501             }
502         },
503         edit: function () {
504             this.$buttons.edit.prop('disabled', true);
505             this.$('#website-top-view').hide();
506             this.$('#website-top-edit').show();
507             $('.css_non_editable_mode_hidden').removeClass("css_non_editable_mode_hidden");
508
509             this.rte.start_edition().then(this.check_height.bind(this));
510             this.trigger('rte:called');
511         },
512         rte_changed: function () {
513             this.$buttons.save.prop('disabled', false);
514         },
515         save: function () {
516             var self = this;
517
518             observer.disconnect();
519             var editor = this.rte.editor;
520             var root = editor.element.$;
521             editor.destroy();
522             // FIXME: select editables then filter by dirty?
523             var defs = this.rte.fetch_editables(root)
524                 .filter('.oe_dirty')
525                 .removeAttr('contentEditable')
526                 .removeClass('oe_dirty oe_editable cke_focus oe_carlos_danger')
527                 .map(function () {
528                     var $el = $(this);
529                     // TODO: Add a queue with concurrency limit in webclient
530                     // https://github.com/medikoo/deferred/blob/master/lib/ext/function/gate.js
531                     return self.saving_mutex.exec(function () {
532                         return self.saveElement($el)
533                             .then(undefined, function (thing, response) {
534                                 // because ckeditor regenerates all the dom,
535                                 // we can't just setup the popover here as
536                                 // everything will be destroyed by the DOM
537                                 // regeneration. Add markings instead, and
538                                 // returns a new rejection with all relevant
539                                 // info
540                                 var id = _.uniqueId('carlos_danger_');
541                                 $el.addClass('oe_dirty oe_carlos_danger');
542                                 $el.addClass(id);
543                                 return $.Deferred().reject({
544                                     id: id,
545                                     error: response.data,
546                                 });
547                             });
548                     });
549                 }).get();
550             return $.when.apply(null, defs).then(function () {
551                 website.reload();
552             }, function (failed) {
553                 // If there were errors, re-enable edition
554                 self.rte.start_edition(true).then(function () {
555                     // jquery's deferred being a pain in the ass
556                     if (!_.isArray(failed)) { failed = [failed]; }
557
558                     _(failed).each(function (failure) {
559                         var html = failure.error.exception_type === "except_osv";
560                         if (html) {
561                             var msg = $("<div/>").text(failure.error.message).html();
562                             var data = msg.substring(3,msg.length-2).split(/', u'/);
563                             failure.error.message = '<b>' + data[0] + '</b><br/>' + data[1];
564                         }
565                         $(root).find('.' + failure.id)
566                             .removeClass(failure.id)
567                             .popover({
568                                 html: html,
569                                 trigger: 'hover',
570                                 content: failure.error.message,
571                                 placement: 'auto top',
572                             })
573                             // Force-show popovers so users will notice them.
574                             .popover('show');
575                     });
576                 });
577             });
578         },
579         /**
580          * Saves an RTE content, which always corresponds to a view section (?).
581          */
582         saveElement: function ($el) {
583             var markup = $el.prop('outerHTML');
584             return openerp.jsonRpc('/web/dataset/call', 'call', {
585                 model: 'ir.ui.view',
586                 method: 'save',
587                 args: [$el.data('oe-id'), markup,
588                        $el.data('oe-xpath') || null,
589                        website.get_context()],
590             });
591         },
592         cancel: function () {
593             new $.Deferred(function (d) {
594                 var $dialog = $(openerp.qweb.render('website.editor.discard')).appendTo(document.body);
595                 $dialog.on('click', '.btn-danger', function () {
596                     d.resolve();
597                 }).on('hidden.bs.modal', function () {
598                     d.reject();
599                 });
600                 d.always(function () {
601                     $dialog.remove();
602                 });
603                 $dialog.modal('show');
604             }).then(function () {
605                 website.reload();
606             })
607         },
608
609         /**
610          * Creates a "hover" button for image and link edition
611          *
612          * @param {String} label the button's label
613          * @param {Function} editfn edition function, called when clicking the button
614          * @param {String} [classes] additional classes to set on the button
615          * @returns {jQuery}
616          */
617         make_hover_button: function (label, editfn, classes) {
618             return $(openerp.qweb.render('website.editor.hoverbutton', {
619                 label: label,
620                 classes: classes,
621             })).hide().appendTo(document.body).click(function (e) {
622                 e.preventDefault();
623                 e.stopPropagation();
624                 editfn.call(this, e);
625             });
626         },
627         /**
628          * For UI clarity, during RTE edition when the user hovers links and
629          * images a small button should appear to make the capability clear,
630          * as not all users think of double-clicking the image or link.
631          */
632         setup_hover_buttons: function () {
633             var editor = this.rte.editor;
634             var $link_button = this.make_hover_button(_t("Change"), function () {
635                 var sel = new CKEDITOR.dom.element(previous);
636                 editor.getSelection().selectElement(sel);
637                 if(sel.hasClass('fa')) {
638                     new website.editor.FontIconsDialog(editor, previous)
639                         .appendTo(document.body);
640                 } else if (previous.tagName.toUpperCase() === 'A') {
641                     link_dialog(editor);
642                 }
643                 $link_button.hide();
644                 previous = null;
645             }, 'btn-xs');
646             var $image_button = this.make_hover_button(_t("Change"), function () {
647                 image_dialog(editor, new CKEDITOR.dom.element(previous));
648                 $image_button.hide();
649                 previous = null;
650             }, 'btn-sm');
651
652             function is_icons_widget(element) {
653                 var w = editor.widgets.getByElement(element);
654                 return w && w.name === 'icons';
655             }
656
657             // previous is the state of the button-trigger: it's the
658             // currently-ish hovered element which can trigger a button showing.
659             // -ish, because when moving to the button itself ``previous`` is
660             // still set to the element having triggered showing the button.
661             var previous;
662             $(editor.element.$).on('mouseover', 'a, img, .fa', function () {
663                 // Back from edit button -> ignore
664                 if (previous && previous === this) { return; }
665
666                 // hover button should appear for "editable" links and images
667                 // (img and a nodes whose *attributes* are editable, they
668                 // can not be "editing hosts") *or* for non-editing-host
669                 // elements bearing an ``fa`` class. These should have been
670                 // made into CKE widgets which are editing hosts by
671                 // definition, so instead check if the element has been
672                 // converted/upcasted to an fa widget
673                 var selected = new CKEDITOR.dom.element(this);
674                 if (!(is_editable_node(selected) || is_icons_widget(selected))) {
675                     return;
676                 }
677
678                 previous = this;
679                 var $selected = $(this);
680                 var position = $selected.offset();
681                 if ($selected.is('img')) {
682                     $link_button.hide();
683                     // center button on image
684                     $image_button.show().offset({
685                         top: $selected.outerHeight() / 2
686                                 + position.top
687                                 - $image_button.outerHeight() / 2,
688                         left: $selected.outerWidth() / 2
689                                 + position.left
690                                 - $image_button.outerWidth() / 2,
691                     });
692                 } else {
693                     $image_button.hide();
694                     // put button below link, horizontally centered
695                     $link_button.show().offset({
696                         top: $selected.outerHeight()
697                                 + position.top,
698                         left: $selected.outerWidth() / 2
699                                 + position.left
700                                 - $link_button.outerWidth() / 2
701                     })
702                 }
703             }).on('mouseleave', 'a, img, .fa', function (e) {
704                 var current = document.elementFromPoint(e.clientX, e.clientY);
705                 if (current === $link_button[0] || current === $image_button[0]) {
706                     return;
707                 }
708                 $image_button.add($link_button).hide();
709                 previous = null;
710             });
711         }
712     });
713
714     var blocks_selector = _.keys(CKEDITOR.dtd.$block).join(',');
715     /* ----- RICH TEXT EDITOR ---- */
716     website.RTE = openerp.Widget.extend({
717         tagName: 'li',
718         id: 'oe_rte_toolbar',
719         className: 'oe_right oe_rte_toolbar',
720         // editor.ui.items -> possible commands &al
721         // editor.applyStyle(new CKEDITOR.style({element: "span",styles: {color: "#(color)"},overrides: [{element: "font",attributes: {color: null}}]}, {color: '#ff0000'}));
722
723         init: function (EditorBar) {
724             this.EditorBar = EditorBar;
725             this._super.apply(this, arguments);
726         },
727
728         /**
729          * In Webkit-based browsers, triple-click will select a paragraph up to
730          * the start of the next "paragraph" including any empty space
731          * inbetween. When said paragraph is removed or altered, it nukes
732          * the empty space and brings part of the content of the next
733          * "paragraph" (which may well be e.g. an image) into the current one,
734          * completely fucking up layouts and breaking snippets.
735          *
736          * Try to fuck around with selections on triple-click to attempt to
737          * fix this garbage behavior.
738          *
739          * Note: for consistent behavior we may actually want to take over
740          * triple-clicks, in all browsers in order to ensure consistent cross-
741          * platform behavior instead of being at the mercy of rendering engines
742          * & platform selection quirks?
743          */
744         webkitSelectionFixer: function (root) {
745             root.addEventListener('click', function (e) {
746                 // only webkit seems to have a fucked up behavior, ignore others
747                 // FIXME: $.browser goes away in jquery 1.9...
748                 if (!$.browser.webkit) { return; }
749                 // http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mouseevents
750                 // The detail attribute indicates the number of times a mouse button has been pressed
751                 // we just want the triple click
752                 if (e.detail !== 3) { return; }
753                 e.preventDefault();
754
755                 // Get closest block-level element to the triple-clicked
756                 // element (using ckeditor's block list because why not)
757                 var $closest_block = $(e.target).closest(blocks_selector);
758
759                 // manually set selection range to the content of the
760                 // triple-clicked block-level element, to avoid crossing over
761                 // between block-level elements
762                 document.getSelection().selectAllChildren($closest_block[0]);
763             });
764         },
765         tableNavigation: function (root) {
766             var self = this;
767             $(root).on('keydown', function (e) {
768                 // ignore non-TAB
769                 if (e.which !== 9) { return; }
770
771                 if (self.handleTab(e)) {
772                     e.preventDefault();
773                 }
774             });
775         },
776         /**
777          * Performs whatever operation is necessary on a [TAB] hit, returns
778          * ``true`` if the event's default should be cancelled (if the TAB was
779          * handled by the function)
780          */
781         handleTab: function (event) {
782             var forward = !event.shiftKey;
783
784             var root = window.getSelection().getRangeAt(0).commonAncestorContainer;
785             var $cell = $(root).closest('td,th');
786
787             if (!$cell.length) { return false; }
788
789             var cell = $cell[0];
790
791             // find cell in same row
792             var row = cell.parentNode;
793             var sibling = row.cells[cell.cellIndex + (forward ? 1 : -1)];
794             if (sibling) {
795                 document.getSelection().selectAllChildren(sibling);
796                 return true;
797             }
798
799             // find cell in previous/next row
800             var table = row.parentNode;
801             var sibling_row = table.rows[row.rowIndex + (forward ? 1 : -1)];
802             if (sibling_row) {
803                 var new_cell = sibling_row.cells[forward ? 0 : sibling_row.cells.length - 1];
804                 document.getSelection().selectAllChildren(new_cell);
805                 return true;
806             }
807
808             // at edge cells, copy word/openoffice behavior: if going backwards
809             // from first cell do nothing, if going forwards from last cell add
810             // a row
811             if (forward) {
812                 var row_size = row.cells.length;
813                 var new_row = document.createElement('tr');
814                 while(row_size--) {
815                     var newcell = document.createElement('td');
816                     // zero-width space
817                     newcell.textContent = '\u200B';
818                     new_row.appendChild(newcell);
819                 }
820                 table.appendChild(new_row);
821                 document.getSelection().selectAllChildren(new_row.cells[0]);
822             }
823
824             return true;
825         },
826         /**
827          * Makes the page editable
828          *
829          * @param {Boolean} [restart=false] in case the edition was already set
830          *                                  up once and is being re-enabled.
831          * @returns {$.Deferred} deferred indicating when the RTE is ready
832          */
833         start_edition: function (restart) {
834             var self = this;
835             // create a single editor for the whole page
836             var root = document.getElementById('wrapwrap');
837             if (!restart) {
838                 $(root).on('dragstart', 'img', function (e) {
839                     e.preventDefault();
840                 });
841                 this.webkitSelectionFixer(root);
842                 this.tableNavigation(root);
843             }
844             var def = $.Deferred();
845             var editor = this.editor = CKEDITOR.inline(root, self._config());
846             editor.on('instanceReady', function () {
847                 editor.setReadOnly(false);
848                 // ckeditor set root to editable, disable it (only inner
849                 // sections are editable)
850                 // FIXME: are there cases where the whole editor is editable?
851                 editor.editable().setReadOnly(true);
852
853                 self.setup_editables(root);
854
855                 try {
856                     // disable firefox's broken table resizing thing
857                     document.execCommand("enableObjectResizing", false, "false");
858                     document.execCommand("enableInlineTableEditing", false, "false");
859                 } catch (e) {}
860
861                 // detect & setup any CKEDITOR widget within a newly dropped
862                 // snippet. There does not seem to be a simple way to do it for
863                 // HTML not inserted via ckeditor APIs:
864                 // https://dev.ckeditor.com/ticket/11472
865                 $(document.body)
866                     .off('snippet-dropped')
867                     .on('snippet-dropped', function (e, el) {
868                         // CKEDITOR data processor extended by widgets plugin
869                         // to add wrappers around upcasting elements
870                         el.innerHTML = editor.dataProcessor.toHtml(el.innerHTML, {
871                             fixForBody: false,
872                             dontFilter: true,
873                         });
874                         // then repository.initOnAll() handles the conversion
875                         // from wrapper to actual widget instance (or something
876                         // like that).
877                         setTimeout(function () {
878                             editor.widgets.initOnAll();
879                         }, 0);
880                     });
881
882                 self.trigger('rte:ready');
883                 def.resolve();
884             });
885             return def;
886         },
887
888         setup_editables: function (root) {
889             // selection of editable sub-items was previously in
890             // EditorBar#edit, but for some unknown reason the elements were
891             // apparently removed and recreated (?) at editor initalization,
892             // and observer setup was lost.
893             var self = this;
894             // setup dirty-marking for each editable element
895             this.fetch_editables(root)
896                 .addClass('oe_editable')
897                 .each(function () {
898                     var node = this;
899                     var $node = $(node);
900                     // only explicitly set contenteditable on view sections,
901                     // cke widgets system will do the widgets themselves
902                     if ($node.data('oe-model') === 'ir.ui.view') {
903                         node.contentEditable = true;
904                     }
905
906                     observer.observe(node, OBSERVER_CONFIG);
907                     $node.one('content_changed', function () {
908                         $node.addClass('oe_dirty');
909                         self.trigger('change');
910                     });
911                 });
912         },
913
914         fetch_editables: function (root) {
915             return $(root).find('[data-oe-model]')
916                 .not('link, script')
917                 .not('.oe_snippet_editor')
918                 .filter(function () {
919                     var $this = $(this);
920                     // keep view sections and fields which are *not* in
921                     // view sections for top-level editables
922                     return $this.data('oe-model') === 'ir.ui.view'
923                        || !$this.closest('[data-oe-model = "ir.ui.view"]').length;
924                 });
925         },
926
927         _current_editor: function () {
928             return CKEDITOR.currentInstance;
929         },
930         _config: function () {
931             // base plugins minus
932             // - magicline (captures mousein/mouseout -> breaks draggable)
933             // - contextmenu & tabletools (disable contextual menu)
934             // - bunch of unused plugins
935             var plugins = [
936                 'a11yhelp', 'basicstyles', 'blockquote',
937                 'clipboard', 'colorbutton', 'colordialog', 'dialogadvtab',
938                 'elementspath', /*'enterkey',*/ 'entities', 'filebrowser',
939                 'find', 'floatingspace','format', 'htmlwriter', 'iframe',
940                 'indentblock', 'indentlist', 'justify',
941                 'list', 'pastefromword', 'pastetext', 'preview',
942                 'removeformat', 'resize', 'save', 'selectall', 'stylescombo',
943                 'table', 'templates', 'toolbar', 'undo', 'wysiwygarea'
944             ];
945             return {
946                 // FIXME
947                 language: 'en',
948                 // Disable auto-generated titles
949                 // FIXME: accessibility, need to generate user-sensible title, used for @title and @aria-label
950                 title: false,
951                 plugins: plugins.join(','),
952                 uiColor: '',
953                 // FIXME: currently breaks RTE?
954                 // Ensure no config file is loaded
955                 customConfig: '',
956                 // Disable ACF
957                 allowedContent: true,
958                 // Don't insert paragraphs around content in e.g. <li>
959                 autoParagraph: false,
960                 // Don't automatically add &nbsp; or <br> in empty block-level
961                 // elements when edition starts
962                 fillEmptyBlocks: false,
963                 filebrowserImageUploadUrl: "/website/attach",
964                 // Support for sharedSpaces in 4.x
965                 extraPlugins: 'sharedspace,customdialogs,tablebutton,oeref,linkstyle',
966                 // Place toolbar in controlled location
967                 sharedSpaces: { top: 'oe_rte_toolbar' },
968                 toolbar: [{
969                         name: 'basicstyles', items: [
970                         "Bold", "Italic", "Underline", "Strike", "Subscript",
971                         "Superscript", "TextColor", "BGColor", "RemoveFormat"
972                     ]},{
973                     name: 'span', items: [
974                         "Link", "LinkStyle", "Blockquote", "BulletedList",
975                         "NumberedList", "Indent", "Outdent"
976                     ]},{
977                     name: 'justify', items: [
978                         "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"
979                     ]},{
980                     name: 'special', items: [
981                         "Image", "TableButton"
982                     ]},{
983                     name: 'styles', items: [
984                         "Styles"
985                     ]}
986                 ],
987                 // styles dropdown in toolbar
988                 stylesSet: [
989                     {name: "Normal", element: 'p'},
990                     {name: "Heading 1", element: 'h1'},
991                     {name: "Heading 2", element: 'h2'},
992                     {name: "Heading 3", element: 'h3'},
993                     {name: "Heading 4", element: 'h4'},
994                     {name: "Heading 5", element: 'h5'},
995                     {name: "Heading 6", element: 'h6'},
996                     {name: "Formatted", element: 'pre'},
997                     {name: "Address", element: 'address'}
998                 ],
999             };
1000         },
1001     });
1002
1003     website.editor = { };
1004     website.editor.Dialog = openerp.Widget.extend({
1005         events: {
1006             'hidden.bs.modal': 'destroy',
1007             'click button.save': 'save',
1008             'click button[data-dismiss="modal"]': 'cancel',
1009         },
1010         init: function (editor) {
1011             this._super();
1012             this.editor = editor;
1013         },
1014         start: function () {
1015             var sup = this._super();
1016             this.$el.modal({backdrop: 'static'});
1017             this.$('input:first').focus();
1018             return sup;
1019         },
1020         save: function () {
1021             this.close();
1022         },
1023         cancel: function () {
1024         },
1025         close: function () {
1026             this.$el.modal('hide');
1027         },
1028     });
1029
1030     website.editor.LinkDialog = website.editor.Dialog.extend({
1031         template: 'website.editor.dialog.link',
1032         events: _.extend({}, website.editor.Dialog.prototype.events, {
1033             'change :input.url-source': function (e) { this.changed($(e.target)); },
1034             'mousedown': function (e) {
1035                 var $target = $(e.target).closest('.list-group-item');
1036                 if (!$target.length || $target.hasClass('active')) {
1037                     // clicked outside groups, or clicked in active groups
1038                     return;
1039                 }
1040
1041                 this.changed($target.find('.url-source').filter(':input'));
1042             },
1043             'click button.remove': 'remove_link',
1044             'change input#link-text': function (e) {
1045                 this.text = $(e.target).val()
1046             },
1047         }),
1048         init: function (editor) {
1049             this._super(editor);
1050             this.text = null;
1051             // Store last-performed request to be able to cancel/abort it.
1052             this.page_exists_req = null;
1053             this.search_pages_req = null;
1054         },
1055         start: function () {
1056             var self = this;
1057             var last;
1058             this.$('#link-page').select2({
1059                 minimumInputLength: 1,
1060                 placeholder: _t("New or existing page"),
1061                 query: function (q) {
1062                     if (q.term == last) return;
1063                     last = q.term;
1064                     $.when(
1065                         self.page_exists(q.term),
1066                         self.fetch_pages(q.term)
1067                     ).then(function (exists, results) {
1068                         var rs = _.map(results, function (r) {
1069                             return { id: r.url, text: r.name, };
1070                         });
1071                         if (!exists) {
1072                             rs.push({
1073                                 create: true,
1074                                 id: q.term,
1075                                 text: _.str.sprintf(_t("Create page '%s'"), q.term),
1076                             });
1077                         }
1078                         q.callback({
1079                             more: false,
1080                             results: rs
1081                         });
1082                     }, function () {
1083                         q.callback({more: false, results: []});
1084                     });
1085                 },
1086             });
1087             return this._super().then(this.proxy('bind_data'));
1088         },
1089         save: function () {
1090             var self = this, _super = this._super.bind(this);
1091             var $e = this.$('.list-group-item.active .url-source').filter(':input');
1092             var val = $e.val();
1093             if (!val || !$e[0].checkValidity()) {
1094                 // FIXME: error message
1095                 $e.closest('.form-group').addClass('has-error');
1096                 $e.focus();
1097                 return;
1098             }
1099
1100             var done = $.when();
1101             if ($e.hasClass('email-address')) {
1102                 this.make_link('mailto:' + val, false, val);
1103             } else if ($e.hasClass('page')) {
1104                 var data = $e.select2('data');
1105                 if (!data.create) {
1106                     self.make_link(data.id, false, data.text);
1107                 } else {
1108                     // Create the page, get the URL back
1109                     done = $.get(_.str.sprintf(
1110                             '/website/add/%s?noredirect=1', encodeURI(data.id)))
1111                         .then(function (response) {
1112                             self.make_link(response, false, data.id);
1113                         });
1114                 }
1115             } else {
1116                 this.make_link(val, this.$('input.window-new').prop('checked'));
1117             }
1118             done.then(_super);
1119         },
1120         make_link: function (url, new_window, label) {
1121         },
1122         bind_data: function (text, href, new_window) {
1123             href = href || this.element && (this.element.data( 'cke-saved-href')
1124                                     ||  this.element.getAttribute('href'));
1125
1126             if (new_window === undefined) {
1127                 new_window = this.element
1128                         ? this.element.getAttribute('target') === '_blank'
1129                         : false;
1130             }
1131             if (text === undefined) {
1132                 text = this.element ? this.element.getText() : '';
1133             }
1134
1135             this.$('input#link-text').val(text);
1136             this.$('input.window-new').prop('checked', new_window);
1137
1138             if (!href) { return; }
1139             var match, $control;
1140             if ((match = /mailto:(.+)/.exec(href))) {
1141                 $control = this.$('input.email-address').val(match[1]);
1142             }
1143             if (!$control) {
1144                 $control = this.$('input.url').val(href);
1145             }
1146
1147             this.changed($control);
1148         },
1149         changed: function ($e) {
1150             this.$('.url-source').filter(':input').not($e).val('')
1151                     .filter(function () { return !!$(this).data('select2'); })
1152                     .select2('data', null);
1153             $e.closest('.list-group-item')
1154                 .addClass('active')
1155                 .siblings().removeClass('active')
1156                 .addBack().removeClass('has-error');
1157         },
1158         call: function (method, args, kwargs) {
1159             var self = this;
1160             var req = method + '_req';
1161
1162             if (this[req]) { this[req].abort(); }
1163
1164             return this[req] = openerp.jsonRpc('/web/dataset/call_kw', 'call', {
1165                 model: 'website',
1166                 method: method,
1167                 args: args,
1168                 kwargs: kwargs,
1169             }).always(function () {
1170                 self[req] = null;
1171             });
1172         },
1173         page_exists: function (term) {
1174             return this.call('page_exists', [null, term], {
1175                 context: website.get_context(),
1176             });
1177         },
1178         fetch_pages: function (term) {
1179             return this.call('search_pages', [null, term], {
1180                 limit: 9,
1181                 context: website.get_context(),
1182             });
1183         },
1184     });
1185     website.editor.RTELinkDialog = website.editor.LinkDialog.extend({
1186         start: function () {
1187             var element;
1188             if ((element = this.get_selected_link()) && element.hasAttribute('href')) {
1189                 this.editor.getSelection().selectElement(element);
1190             }
1191             this.element = element;
1192             if (element) {
1193                 this.add_removal_button();
1194             }
1195
1196             return this._super();
1197         },
1198         add_removal_button: function () {
1199             this.$('.modal-footer').prepend(
1200                 openerp.qweb.render(
1201                     'website.editor.dialog.link.footer-button'));
1202         },
1203         remove_link: function () {
1204             var editor = this.editor;
1205             // same issue as in make_link
1206             setTimeout(function () {
1207                 editor.removeStyle(new CKEDITOR.style({
1208                     element: 'a',
1209                     type: CKEDITOR.STYLE_INLINE,
1210                     alwaysRemoveElement: true,
1211                 }));
1212             }, 0);
1213             this.close();
1214         },
1215         /**
1216          * Greatly simplified version of CKEDITOR's
1217          * plugins.link.dialogs.link.onOk.
1218          *
1219          * @param {String} url
1220          * @param {Boolean} [new_window=false]
1221          * @param {String} [label=null]
1222          */
1223         make_link: function (url, new_window, label) {
1224             var attributes = {href: url, 'data-cke-saved-href': url};
1225             var to_remove = [];
1226             if (new_window) {
1227                 attributes['target'] = '_blank';
1228             } else {
1229                 to_remove.push('target');
1230             }
1231
1232             if (this.element) {
1233                 this.element.setAttributes(attributes);
1234                 this.element.removeAttributes(to_remove);
1235                 if (this.text) { this.element.setText(this.text); }
1236             } else {
1237                 var selection = this.editor.getSelection();
1238                 var range = selection.getRanges(true)[0];
1239
1240                 if (range.collapsed) {
1241                     //noinspection JSPotentiallyInvalidConstructorUsage
1242                     var text = new CKEDITOR.dom.text(
1243                         this.text || label || url);
1244                     range.insertNode(text);
1245                     range.selectNodeContents(text);
1246                 }
1247
1248                 //noinspection JSPotentiallyInvalidConstructorUsage
1249                 new CKEDITOR.style({
1250                     type: CKEDITOR.STYLE_INLINE,
1251                     element: 'a',
1252                     attributes: attributes,
1253                 }).applyToRange(range);
1254
1255                 // focus dance between RTE & dialog blow up the stack in Safari
1256                 // and Chrome, so defer select() until dialog has been closed
1257                 setTimeout(function () {
1258                     range.select();
1259                 }, 0);
1260             }
1261         },
1262         /**
1263          * CKEDITOR.plugins.link.getSelectedLink ignores the editor's root,
1264          * if the editor is set directly on a link it will thus not work.
1265          */
1266         get_selected_link: function () {
1267             return get_selected_link(this.editor);
1268         },
1269     });
1270
1271     /**
1272      * ImageDialog widget. Lets users change an image, including uploading a
1273      * new image in OpenERP or selecting the image style (if supported by
1274      * the caller).
1275      *
1276      * Initialized as usual, but the caller can hook into two events:
1277      *
1278      * @event start({url, style}) called during dialog initialization and
1279      *                            opening, the handler can *set* the ``url``
1280      *                            and ``style`` properties on its parameter
1281      *                            to provide these as default values to the
1282      *                            dialog
1283      * @event save({url, style}) called during dialog finalization, the handler
1284      *                           is provided with the image url and style
1285      *                           selected by the users (or possibly the ones
1286      *                           originally passed in)
1287      */
1288     website.editor.ImageDialog = website.editor.Dialog.extend({
1289         template: 'website.editor.dialog.image',
1290         events: _.extend({}, website.editor.Dialog.prototype.events, {
1291             'change .url-source': function (e) { this.changed($(e.target)); },
1292             'click button.filepicker': function () {
1293                 this.$('input[type=file]').click();
1294             },
1295             'change input[type=file]': 'file_selection',
1296             'change input.url': 'preview_image',
1297             'click a[href=#existing]': 'browse_existing',
1298             'change select.image-style': 'preview_image',
1299         }),
1300
1301         start: function () {
1302             this.$('button.wait').text("Uploading…");
1303             var $options = this.$('.image-style').children();
1304             this.image_styles = $options.map(function () { return this.value; }).get();
1305
1306             var o = { url: null, style: null, };
1307             // avoid typos, prevent addition of new properties to the object
1308             Object.preventExtensions(o);
1309             this.trigger('start', o);
1310
1311             if (o.url) {
1312                 if (o.style) {
1313                     this.$('.image-style').val(o.style);
1314                 }
1315                 this.set_image(o.url);
1316             }
1317
1318             return this._super();
1319         },
1320         save: function () {
1321             this.trigger('save', {
1322                 url: this.$('input.url').val(),
1323                 style: this.$('.image-style').val(),
1324             });
1325             return this._super();
1326         },
1327         cancel: function () {
1328             this.trigger('cancel');
1329         },
1330
1331         /**
1332          * Sets the provided image url as the dialog's value-to-save and
1333          * refreshes the preview element to use it.
1334          */
1335         set_image: function (url, error) {
1336             this.$('input.url').val(
1337                 error ? '' : url);
1338             this.$('input.url').val(url);
1339             this.preview_image();
1340         },
1341
1342         file_selection: function () {
1343             this.$el.addClass('nosave');
1344             this.$('form').removeClass('has-error').find('.help-block').empty();
1345             this.$('button.filepicker').removeClass('btn-danger btn-success');
1346
1347             var self = this;
1348             var callback = _.uniqueId('func_');
1349             this.$('input[name=func]').val(callback);
1350
1351             window[callback] = function (url, error) {
1352                 delete window[callback];
1353                 self.file_selected(url, error);
1354             };
1355             this.$('form').submit();
1356         },
1357         file_selected: function(url, error) {
1358             var $button = this.$('button.filepicker');
1359             if (!error) {
1360                 $button.addClass('btn-success');
1361             } else {
1362                 url = null;
1363                 this.$('form').addClass('has-error')
1364                     .find('.help-block').text(error);
1365                 $button.addClass('btn-danger');
1366             }
1367             this.set_image(url, error);
1368         },
1369         preview_image: function () {
1370             var loaded = function () {
1371                 this.$el.removeClass('nosave');
1372             }.bind(this);
1373             var image = this.$('input.url').val();
1374             if (!image) { loaded(); return; }
1375
1376             var $img = this.$('img.image-preview')
1377                 .attr('src', image)
1378                 .removeClass(this.image_styles.join(' '))
1379                 .addClass(this.$('select.image-style').val());
1380
1381             if ($img.prop('complete')) {
1382                 loaded();
1383             } else {
1384                 $img.load(loaded)
1385             }
1386         },
1387         browse_existing: function (e) {
1388             e.preventDefault();
1389             this.$('form').removeClass('has-error').find('.help-block').empty();
1390             this.$('button.filepicker').removeClass('btn-danger btn-success');
1391             new website.editor.ExistingImageDialog(this).appendTo(document.body);
1392         },
1393     });
1394     website.editor.RTEImageDialog = website.editor.ImageDialog.extend({
1395         init: function (editor, image) {
1396             this._super(editor);
1397
1398             this.element = image;
1399
1400             this.on('start', this, this.proxy('started'));
1401             this.on('save', this, this.proxy('saved'));
1402         },
1403         started: function (holder) {
1404             if (!this.element) {
1405                 var selection = this.editor.getSelection();
1406                 this.element = selection && selection.getSelectedElement();
1407             }
1408
1409             var el = this.element;
1410             if (!el || !el.is('img')) {
1411                 return;
1412             }
1413             _(this.image_styles).each(function (style) {
1414                 if (el.hasClass(style)) {
1415                     holder.style = style;
1416                 }
1417             });
1418             holder.url = el.getAttribute('src');
1419         },
1420         saved: function (data) {
1421             var element, editor = this.editor;
1422             if (!(element = this.element)) {
1423                 element = editor.document.createElement('img');
1424                 element.addClass('img');
1425                 element.addClass('img-responsive');
1426                 // focus event handler interactions between bootstrap (modal)
1427                 // and ckeditor (RTE) lead to blowing the stack in Safari and
1428                 // Chrome (but not FF) when this is done synchronously =>
1429                 // defer insertion so modal has been hidden & destroyed before
1430                 // it happens
1431                 setTimeout(function () {
1432                     editor.insertElement(element);
1433                 }, 0);
1434             }
1435
1436             var style = data.style;
1437             element.setAttribute('src', data.url);
1438             element.removeAttribute('data-cke-saved-src');
1439             $(element.$).removeClass(this.image_styles.join(' '));
1440             if (style) { element.addClass(style); }
1441         },
1442     });
1443
1444     var IMAGES_PER_ROW = 6;
1445     var IMAGES_ROWS = 4;
1446     website.editor.ExistingImageDialog = website.editor.Dialog.extend({
1447         template: 'website.editor.dialog.image.existing',
1448         events: _.extend({}, website.editor.Dialog.prototype.events, {
1449             'click .existing-attachments img': 'select_existing',
1450             'click .pager > li': function (e) {
1451                 e.preventDefault();
1452                 var $target = $(e.currentTarget);
1453                 if ($target.hasClass('disabled')) {
1454                     return;
1455                 }
1456                 this.page += $target.hasClass('previous') ? -1 : 1;
1457                 this.display_attachments();
1458             },
1459             'click .existing-attachment-remove': 'try_remove',
1460         }),
1461         init: function (parent) {
1462             this.image = null;
1463             this.page = 0;
1464             this.parent = parent;
1465             this._super(parent.editor);
1466         },
1467
1468         start: function () {
1469             return $.when(
1470                 this._super(),
1471                 this.fetch_existing().then(this.proxy('fetched_existing')));
1472         },
1473
1474         fetch_existing: function () {
1475             return openerp.jsonRpc('/web/dataset/call_kw', 'call', {
1476                 model: 'ir.attachment',
1477                 method: 'search_read',
1478                 args: [],
1479                 kwargs: {
1480                     fields: ['name', 'website_url'],
1481                     domain: [['res_model', '=', 'ir.ui.view']],
1482                     order: 'id desc',
1483                     context: website.get_context(),
1484                 }
1485             });
1486         },
1487         fetched_existing: function (records) {
1488             this.records = records;
1489             this.display_attachments();
1490         },
1491         display_attachments: function () {
1492             this.$('.help-block').empty();
1493             var per_screen = IMAGES_PER_ROW * IMAGES_ROWS;
1494
1495             var from = this.page * per_screen;
1496             var records = this.records;
1497
1498             // Create rows of 3 records
1499             var rows = _(records).chain()
1500                 .slice(from, from + per_screen)
1501                 .groupBy(function (_, index) { return Math.floor(index / IMAGES_PER_ROW); })
1502                 .values()
1503                 .value();
1504
1505             this.$('.existing-attachments').replaceWith(
1506                 openerp.qweb.render(
1507                     'website.editor.dialog.image.existing.content', {rows: rows}));
1508             this.$('.pager')
1509                 .find('li.previous').toggleClass('disabled', (from === 0)).end()
1510                 .find('li.next').toggleClass('disabled', (from + per_screen >= records.length));
1511
1512         },
1513         select_existing: function (e) {
1514             var link = $(e.currentTarget).attr('src');
1515             if (link) {
1516                 this.parent.set_image(link);
1517             }
1518             this.close()
1519         },
1520
1521         try_remove: function (e) {
1522             var $help_block = this.$('.help-block').empty();
1523             var self = this;
1524             var id = parseInt($(e.target).data('id'), 10);
1525             var attachment = _.findWhere(this.records, {id: id});
1526
1527             return openerp.jsonRpc('/web/dataset/call_kw', 'call', {
1528                 model: 'ir.attachment',
1529                 method: 'try_remove',
1530                 args: [],
1531                 kwargs: {
1532                     ids: [id],
1533                     context: website.get_context()
1534                 }
1535             }).then(function (prevented) {
1536                 if (_.isEmpty(prevented)) {
1537                     self.records = _.without(self.records, attachment);
1538                     self.display_attachments();
1539                     return;
1540                 }
1541                 $help_block.replaceWith(openerp.qweb.render(
1542                     'website.editor.dialog.image.existing.error', {
1543                         views: prevented[id]
1544                     }
1545                 ));
1546             });
1547         },
1548     });
1549
1550     function get_selected_link(editor) {
1551         var sel = editor.getSelection(),
1552             el = sel.getSelectedElement();
1553         if (el && el.is('a')) { return el; }
1554
1555         var range = sel.getRanges(true)[0];
1556         if (!range) { return null; }
1557
1558         range.shrink(CKEDITOR.SHRINK_TEXT);
1559         var commonAncestor = range.getCommonAncestor();
1560         var viewRoot = editor.elementPath(commonAncestor).contains(function (element) {
1561             return element.data('oe-model') === 'ir.ui.view'
1562         });
1563         if (!viewRoot) { return null; }
1564         // if viewRoot is the first link, don't edit it.
1565         return new CKEDITOR.dom.elementPath(commonAncestor, viewRoot)
1566                 .contains('a', true);
1567     }
1568
1569     website.editor.FontIconsDialog = website.editor.Dialog.extend({
1570         template: 'website.editor.dialog.font-icons',
1571         events : _.extend({}, website.editor.Dialog.prototype.events, {
1572             change: 'update_preview',
1573             'click .font-icons-icon': function (e) {
1574                 e.preventDefault();
1575                 e.stopPropagation();
1576
1577                 this.$('#fa-icon').val(e.target.getAttribute('data-id'));
1578                 this.update_preview();
1579             },
1580             'click #fa-preview span': function (e) {
1581                 e.preventDefault();
1582                 e.stopPropagation();
1583
1584                 this.$('#fa-size').val(e.target.getAttribute('data-size'));
1585                 this.update_preview();
1586             },
1587             'input input#icon-search': function () {
1588                 var needle = this.$('#icon-search').val();
1589                 var icons = this.icons;
1590                 if (needle) {
1591                     icons = _(icons).filter(function (icon) {
1592                         return icon.id.substring(3).indexOf(needle) !== -1;
1593                     });
1594                 }
1595
1596                 this.$('div.font-icons-icons').html(
1597                     openerp.qweb.render(
1598                         'website.editor.dialog.font-icons.icons',
1599                         {icons: icons}));
1600             },
1601         }),
1602
1603         // List of FontAwesome icons in 4.0.3, extracted from the cheatsheet.
1604         // Each icon provides the unicode codepoint as ``text`` and the class
1605         // name as ``id`` so the whole thing can be fed directly to select2
1606         // without post-processing and do the right thing (except for the part
1607         // where we still need to implement ``initSelection``)
1608         // TODO: add id/name to the text in order to allow FAYT selection of icons?
1609         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"}],
1610         init: function (editor, element) {
1611             this._super(editor);
1612             this.element = element;
1613         },
1614         /**
1615          * Initializes select2: in Chrome and Safari, <select> font apparently
1616          * isn't customizable (?) and the fontawesome glyphs fail to appear.
1617          */
1618         start: function () {
1619             return this._super().then(this.proxy('load_data'));
1620         },
1621         /**
1622          * Removes existing FontAwesome classes on the bound element, and sets
1623          * all the new ones if necessary.
1624          */
1625         save: function () {
1626             var classes = this.element.className.split(/\s+/);
1627             var non_fa_classes = _.reject(classes, function (cls) {
1628                 return cls === 'fa' || /^fa-/.test(cls);
1629             });
1630             var final_classes = non_fa_classes.concat(this.get_fa_classes());
1631             this.element.className = final_classes.join(' ');
1632             this._super();
1633         },
1634         /**
1635          * Looks up the various FontAwesome classes on the bound element and
1636          * sets the corresponding template/form elements to the right state.
1637          * If multiple classes of the same category are present on an element
1638          * (e.g. fa-lg and fa-3x) the last one occurring will be selected,
1639          * which may not match the visual look of the element.
1640          */
1641         load_data: function () {
1642             var classes = this.element.className.split(/\s+/);
1643             for (var i = 0; i < classes.length; i++) {
1644                 var cls = classes[i];
1645                 switch(cls) {
1646                 case 'fa-2x':case 'fa-3x':case 'fa-4x':case 'fa-5x':
1647                     // size classes
1648                     this.$('#fa-size').val(cls);
1649                     continue;
1650                 case 'fa-spin':
1651                 case 'fa-rotate-90':case 'fa-rotate-180':case 'fa-rotate-270':
1652                 case 'fa-flip-horizontal':case 'fa-rotate-vertical':
1653                     this.$('#fa-rotation').val(cls);
1654                     continue;
1655                 case 'fa-fw':
1656                     continue;
1657                 case 'fa-border':
1658                     this.$('#fa-border').prop('checked', true);
1659                     continue;
1660                 default:
1661                     if (!/^fa-/.test(cls)) { continue; }
1662                     this.$('#fa-icon').val(cls);
1663                 }
1664             }
1665             this.update_preview();
1666         },
1667         /**
1668          * Serializes the dialog to an array of FontAwesome classes. Includes
1669          * the base ``fa``.
1670          */
1671         get_fa_classes: function () {
1672             return [
1673                 'fa',
1674                 this.$('#fa-icon').val(),
1675                 this.$('#fa-size').val(),
1676                 this.$('#fa-rotation').val(),
1677                 this.$('#fa-border').prop('checked') ? 'fa-border' : ''
1678             ];
1679         },
1680         update_preview: function () {
1681             var $preview = this.$('#fa-preview').empty();
1682             var sizes = ['', 'fa-2x', 'fa-3x', 'fa-4x', 'fa-5x'];
1683             var classes = this.get_fa_classes();
1684             var no_sizes = _.difference(classes, sizes).join(' ');
1685             var selected = false;
1686             for (var i = sizes.length - 1; i >= 0; i--) {
1687                 var size = sizes[i];
1688
1689                 var $p = $('<span>')
1690                         .attr('data-size', size)
1691                         .addClass(size)
1692                         .addClass(no_sizes);
1693                 if ((size && _.contains(classes, size)) || (!size && !selected)) {
1694                     $p.addClass('font-icons-selected');
1695                     selected = true;
1696                 }
1697                 $preview.prepend($p);
1698             }
1699         }
1700     });
1701
1702     website.Observer = window.MutationObserver || window.WebkitMutationObserver || window.JsMutationObserver;
1703     var OBSERVER_CONFIG = {
1704         childList: true,
1705         attributes: true,
1706         characterData: true,
1707         subtree: true,
1708         attributeOldValue: true,
1709     };
1710     var observer = new website.Observer(function (mutations) {
1711         // NOTE: Webkit does not fire DOMAttrModified => webkit browsers
1712         //       relying on JsMutationObserver shim (Chrome < 18, Safari < 6)
1713         //       will not mark dirty on attribute changes (@class, img/@src,
1714         //       a/@href, ...)
1715         _(mutations).chain()
1716             .filter(function (m) {
1717                 // ignore any change related to mundane image-edit-button
1718                 if (m.target && m.target.className
1719                         && m.target.className.indexOf('image-edit-button') !== -1) {
1720                     return false;
1721                 }
1722                 switch(m.type) {
1723                 case 'attributes': // ignore .cke_focus being added or removed
1724                     // ignore id modification
1725                     if (m.attributeName === 'id') { return false; }
1726                     // if attribute is not a class, can't be .cke_focus change
1727                     if (m.attributeName !== 'class') { return true; }
1728
1729                     // find out what classes were added or removed
1730                     var oldClasses = (m.oldValue || '').split(/\s+/);
1731                     var newClasses = m.target.className.split(/\s+/);
1732                     var change = _.union(_.difference(oldClasses, newClasses),
1733                                          _.difference(newClasses, oldClasses));
1734                     // ignore mutation if the *only* change is .cke_focus
1735                     return change.length !== 1 || change[0] === 'cke_focus';
1736                 case 'childList':
1737                     setTimeout(function () {
1738                         fixup_browser_crap(m.addedNodes);
1739                     }, 0);
1740                     // Remove ignorable nodes from addedNodes or removedNodes,
1741                     // if either set remains non-empty it's considered to be an
1742                     // impactful change. Otherwise it's ignored.
1743                     return !!remove_mundane_nodes(m.addedNodes).length ||
1744                            !!remove_mundane_nodes(m.removedNodes).length;
1745                 default:
1746                     return true;
1747                 }
1748             })
1749             .map(function (m) {
1750                 var node = m.target;
1751                 while (node && !$(node).hasClass('oe_editable')) {
1752                     node = node.parentNode;
1753                 }
1754                 return node;
1755             })
1756             .compact()
1757             .uniq()
1758             .each(function (node) { $(node).trigger('content_changed'); })
1759     });
1760     function remove_mundane_nodes(nodes) {
1761         if (!nodes || !nodes.length) { return []; }
1762
1763         var output = [];
1764         for(var i=0; i<nodes.length; ++i) {
1765             var node = nodes[i];
1766             if (node.nodeType === document.ELEMENT_NODE) {
1767                 if (node.nodeName === 'BR' && node.getAttribute('type') === '_moz') {
1768                     // <br type="_moz"> appears when focusing RTE in FF, ignore
1769                     continue;
1770                 }
1771             }
1772
1773             output.push(node);
1774         }
1775         return output;
1776     }
1777
1778     var programmatic_styles = {
1779         float: 1,
1780         display: 1,
1781         position: 1,
1782         top: 1,
1783         left: 1,
1784         right: 1,
1785         bottom: 1,
1786     };
1787     function fixup_browser_crap(nodes) {
1788         if (!nodes || !nodes.length) { return; }
1789         /**
1790          * Checks that the node only has a @style, not e.g. @class or whatever
1791          */
1792         function has_only_style(node) {
1793             for (var i = 0; i < node.attributes.length; i++) {
1794                 var attr = node.attributes[i];
1795                 if (attr.attributeName !== 'style') {
1796                     return false;
1797                 }
1798             }
1799             return true;
1800         }
1801         function has_programmatic_style(node) {
1802             for (var i = 0; i < node.style.length; i++) {
1803               var style = node.style[i];
1804               if (programmatic_styles[style]) {
1805                   return true;
1806               }
1807             }
1808             return false;
1809         }
1810
1811         for (var i=0; i<nodes.length; ++i) {
1812             var node = nodes[i];
1813             if (node.nodeType !== document.ELEMENT_NODE) { continue; }
1814
1815             if (node.nodeName === 'SPAN'
1816                     && has_only_style(node)
1817                     && !has_programmatic_style(node)) {
1818                 // On backspace, webkit browsers create a <span> with a bunch of
1819                 // inline styles "remembering" where they come from. Refs:
1820                 //    http://www.neotericdesign.com/blog/2013/3/working-around-chrome-s-contenteditable-span-bug
1821                 //    https://code.google.com/p/chromium/issues/detail?id=226941
1822                 //    https://bugs.webkit.org/show_bug.cgi?id=114791
1823                 //    http://dev.ckeditor.com/ticket/9998
1824                 var child, parent = node.parentNode;
1825                 while (child = node.firstChild) {
1826                     parent.insertBefore(child, node);
1827                 }
1828                 parent.removeChild(node);
1829                 // chances are we had e.g.
1830                 //  <p>foo</p>
1831                 //  <p>bar</p>
1832                 // merged the lines getting this in webkit
1833                 //  <p>foo<span>bar</span></p>
1834                 // after unwrapping the span, we have 2 text nodes
1835                 //  <p>[foo][bar]</p>
1836                 // where we probably want only one. Normalize will merge
1837                 // adjacent text nodes. However, does not merge text and cdata
1838                 parent.normalize();
1839             }
1840         }
1841     }
1842 })();