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