[MERGE] forward port of branch 8.0 up to ed1c173
[odoo/odoo.git] / addons / website / static / src / js / website.snippets.editor.js
1 (function () {
2     'use strict';
3
4     var dummy = function () {};
5
6     var website = openerp.website;
7     website.add_template_file('/website/static/src/xml/website.snippets.xml');
8
9     website.EditorBar.include({
10         start: function () {
11             var self = this;
12             $("[data-oe-model]").on('click', function (event) {
13                 var $this = $(event.srcElement);
14                 var tag = $this[0] && $this[0].tagName.toLowerCase();
15                 if (!(tag === 'a' || tag === "button") && !$this.parents("a, button").length) {
16                     self.$('[data-action="edit"]').parent().effect('bounce', {distance: 18, times: 5}, 250);
17                 }
18             });
19             return this._super();
20         },
21         edit: function () {
22             var self = this;
23             $("[data-oe-model] *, [data-oe-type=html] *").off('click');
24             window.snippets = this.snippets = new website.snippet.BuildingBlock(this);
25             this.snippets.appendTo(this.$el);
26             website.snippet.stop_animation();
27             this.on('rte:ready', this, function () {
28                 self.snippets.$button.removeClass("hidden");
29                 website.snippet.start_animation();
30                 $("#wrapwrap *").off('mousedown mouseup click');
31             });
32
33             return this._super.apply(this, arguments);
34         },
35         save: function () {
36             this.snippets.clean_for_save();
37             this._super();
38         },
39     });
40
41     /* ----- SNIPPET SELECTOR ---- */
42
43     var observer = new website.Observer(function (mutations) {
44         if (!_(mutations).find(function (m) {
45                     return m.type === 'childList' && m.addedNodes.length > 0;
46                 })) {
47             return;
48         }
49     });
50
51     $.extend($.expr[':'],{
52         checkData: function(node,i,m){
53             var dataName = m[3];
54             while (node) {
55                 if (node.dataset && node.dataset[dataName]) {
56                     return true;
57                 } else {
58                     node = node.parentNode;
59                 }
60             }
61             return false;
62         },
63         hasData: function(node,i,m){
64             return !!_.toArray(node.dataset).length;
65         },
66     });
67
68     if (!website.snippet) website.snippet = {};
69     website.snippet.templateOptions = [];
70     website.snippet.globalSelector = "";
71     website.snippet.selector = [];
72     website.snippet.BuildingBlock = openerp.Widget.extend({
73         template: 'website.snippets',
74         activeSnippets: [],
75         init: function (parent) {
76             this.parent = parent;
77             this._super.apply(this, arguments);
78             if(!$('#oe_manipulators').length){
79                 $("<div id='oe_manipulators'></div>").appendTo('body');
80             }
81             this.$active_snipped_id = false;
82             this.snippets = [];
83
84             observer.observe(document.body, {
85                 childList: true,
86                 subtree: true,
87             });
88         },
89         start: function() {
90             var self = this;
91
92             this.$button = $(openerp.qweb.render('website.snippets_button'))
93                 .prependTo(this.parent.$("#website-top-edit ul"))
94                 .find("button");
95
96             this.$button.click(_.bind(this.show_blocks, this));
97
98             this.$snippet = $("#oe_snippets");
99             this.$wrapwrap = $("#wrapwrap");
100             this.$wrapwrap.click(function () {
101                 self.$el.addClass("hidden");
102             });
103
104             this.fetch_snippet_templates();
105             this.bind_snippet_click_editor();
106             this.$el.addClass("hidden");
107
108             $(document).on('click', '.dropdown-submenu a[tabindex]', function (e) {
109                 e.preventDefault();
110             });
111
112             this.getParent().on('change:height', this, function (editor) {
113                 self.$el.css('top', editor.get('height'));
114             });
115             this.$el.css('top', this.parent.get('height'));
116         },
117         show_blocks: function () {
118             var self = this;
119             this.make_active(false);
120             this.$el.toggleClass("hidden");
121             if (this.$el.hasClass("hidden")) {
122                 return;
123             }
124
125             //this.enable_snippets( this.$snippet.find(".tab-pane.active") );
126             var categories = this.$snippet.find(".tab-pane.active")
127                 .add(this.$snippet.find(".tab-pane:not(.active)"))
128                 .get().reverse();
129             function enable() {
130                 self.enable_snippets( $(categories.pop()) );
131                 if (categories.length) {
132                     setTimeout(enable,10);
133                 }
134             }
135             setTimeout(enable,0);
136         },
137         enable_snippets: function ($category) {
138             var self = this;
139             $category.find(".oe_snippet_body").each(function () {
140                 var $snippet = $(this);
141
142                 if (!$snippet.data('selectors')) {
143                     var selectors = [];
144                     for (var k in website.snippet.templateOptions) {
145                         var option = website.snippet.templateOptions[k];
146                         if ($snippet.is(option.base_selector)) {
147
148                             var dropzone = [];
149                             if (option['drop-near']) dropzone.push(option['drop-near']);
150                             if (option['drop-in']) dropzone.push(option['drop-in']);
151                             if (option['drop-in-vertical']) dropzone.push(option['drop-in-vertical']);
152                             selectors = selectors.concat(dropzone);
153                         }
154                     }
155                     $snippet.data('selectors', selectors.length ? selectors.join(":first, ") + ":first" : "");
156                 }
157
158                 if ($snippet.data('selectors').length && self.$wrapwrap.find($snippet.data('selectors')).size()) {
159                     $snippet.closest(".oe_snippet").removeClass("disable");
160                 } else {
161                     $snippet.closest(".oe_snippet").addClass("disable");
162                 }
163             });
164             $('#oe_snippets .scroll a[data-toggle="tab"][href="#' + $category.attr("id") + '"]')
165                 .toggle(!!$category.find(".oe_snippet:not(.disable)").size());
166         },
167         _get_snippet_url: function () {
168             return '/website/snippets';
169         },
170         _add_check_selector : function (selector, no_check) {
171             var data = selector.split(",");
172             var selectors = [];
173             for (var k in data) {
174                 selectors.push(data[k].replace(/^\s+|\s+$/g, '') + (no_check ? "" : ":checkData(oeModel)"));
175             }
176             return selectors.join(", ");
177         },
178         fetch_snippet_templates: function () {
179             var self = this;
180
181             openerp.jsonRpc(this._get_snippet_url(), 'call', {})
182                 .then(function (html) {
183                     var $html = $(html);
184
185                     var selector = [];
186                     var $styles = $html.find("[data-js], [data-selector]");
187                     $styles.each(function () {
188                         var $style = $(this);
189                         var no_check = $style.data('no-check');
190                         var option_id = $style.data('js');
191                         var option = {
192                             'option' : option_id,
193                             'base_selector': $style.data('selector'),
194                             'selector': self._add_check_selector($style.data('selector'), no_check),
195                             '$el': $style,
196                             'drop-near': $style.data('drop-near') && self._add_check_selector($style.data('drop-near'), no_check),
197                             'drop-in': $style.data('drop-in') && self._add_check_selector($style.data('drop-in'), no_check),
198                             'data': $style.data()
199                         };
200                         website.snippet.templateOptions.push(option);
201                         selector.push(option.selector);
202                     });
203                     $styles.addClass("hidden");
204                     website.snippet.globalSelector = selector.join(",");
205
206                     self.$snippets = $html.find(".tab-content > div > div")
207                         .addClass("oe_snippet")
208                         .each(function () {
209                             if (!$('.oe_snippet_thumbnail', this).size()) {
210                                 var $div = $(
211                                     '<div class="oe_snippet_thumbnail">'+
212                                         '<div class="oe_snippet_thumbnail_img"/>'+
213                                         '<span class="oe_snippet_thumbnail_title"></span>'+
214                                     '</div>');
215                                 $div.find('span').text($(this).attr("name"));
216                                 $(this).prepend($div);
217                             }
218                             $("> *:not(.oe_snippet_thumbnail)", this).addClass('oe_snippet_body');
219                         });
220
221                     self.$el.append($html);
222
223                     self.make_snippet_draggable(self.$snippets);
224                 });
225         },
226         cover_target: function ($el, $target){
227             var pos = $target.offset();
228             var mt = parseInt($target.css("margin-top") || 0);
229             var mb = parseInt($target.css("margin-bottom") || 0);
230             $el.css({
231                 'width': $target.outerWidth(),
232                 'top': pos.top - mt - 5,
233                 'left': pos.left
234             });
235             $el.find(".oe_handle.e,.oe_handle.w").css({'height': $target.outerHeight() + mt + mb+1});
236             $el.find(".oe_handle.s").css({'top': $target.outerHeight() + mt + mb});
237             $el.find(".oe_handle.size").css({'top': $target.outerHeight() + mt});
238             $el.find(".oe_handle.s,.oe_handle.n").css({'width': $target.outerWidth()-2});
239         },
240         show: function () {
241             this.$el.removeClass("hidden");
242         },
243         hide: function () {
244             this.$el.addClass("hidden");
245         },
246         bind_snippet_click_editor: function () {
247             var self = this;
248             var snipped_event_flag;
249             self.$wrapwrap.on('click', function (event) {
250                 var srcElement = event.srcElement || (event.originalEvent && (event.originalEvent.originalTarget || event.originalEvent.target));
251                 if (snipped_event_flag || !srcElement) {
252                     return;
253                 }
254                 snipped_event_flag = true;
255
256                 setTimeout(function () {snipped_event_flag = false;}, 0);
257                 var $target = $(srcElement);
258
259                 if ($target.parents(".oe_overlay").length) {
260                     return;
261                 }
262
263                 if (!$target.is(website.snippet.globalSelector)) {
264                     $target = $target.parents(website.snippet.globalSelector).first();
265                 }
266
267                 if (self.$active_snipped_id && self.$active_snipped_id.is($target)) {
268                     return;
269                 }
270                 self.make_active($target);
271             });
272         },
273         snippet_blur: function ($snippet) {
274             if ($snippet) {
275                 if ($snippet.data("snippet-editor")) {
276                     $snippet.data("snippet-editor").on_blur();
277                 }
278             }
279         },
280         snippet_focus: function ($snippet) {
281             if ($snippet) {
282                 if ($snippet.data("snippet-editor")) {
283                     $snippet.data("snippet-editor").on_focus();
284                 }
285             }
286         },
287         clean_for_save: function () {
288             var self = this;
289             var options = website.snippet.options;
290             var template = website.snippet.templateOptions;
291             for (var k in template) {
292                 var Option = options[template[k]['option']];
293                 if (Option && Option.prototype.clean_for_save !== dummy) {
294                     self.$wrapwrap.find(template[k].selector).each(function () {
295                         new Option(self, null, $(this), k).clean_for_save();
296                     });
297                 }
298             }
299             self.$wrapwrap.find("*[contentEditable], *[attributeEditable]")
300                 .removeAttr('contentEditable')
301                 .removeAttr('attributeEditable');
302         },
303         make_active: function ($snippet) {
304             if ($snippet && this.$active_snipped_id && this.$active_snipped_id.get(0) === $snippet.get(0)) {
305                 return;
306             }
307             if (this.$active_snipped_id) {
308                 this.snippet_blur(this.$active_snipped_id);
309                 this.$active_snipped_id = false;
310             }
311             if ($snippet && $snippet.length) {
312                 if(_.indexOf(this.snippets, $snippet.get(0)) === -1) {
313                     this.snippets.push($snippet.get(0));
314                 }
315                 this.$active_snipped_id = $snippet;
316                 this.create_overlay(this.$active_snipped_id);
317                 this.snippet_focus($snippet);
318             }
319             this.$snippet.trigger('snippet-activated', $snippet);
320             if ($snippet) {
321                 $snippet.trigger('snippet-activated', $snippet);
322             }
323         },
324         create_overlay: function ($snippet) {
325             if (typeof $snippet.data("snippet-editor") === 'undefined') {
326                 var $targets = this.activate_overlay_zones($snippet);
327                 if (!$targets.length) return;
328                 $snippet.data("snippet-editor", new website.snippet.Editor(this, $snippet));
329             }
330             this.cover_target($snippet.data('overlay'), $snippet);
331         },
332
333         // activate drag and drop for the snippets in the snippet toolbar
334         make_snippet_draggable: function($snippets){
335             var self = this;
336             var $tumb = $snippets.find(".oe_snippet_thumbnail_img:first");
337             var left = $tumb.outerWidth()/2;
338             var top = $tumb.outerHeight()/2;
339             var $toInsert, dropped, $snippet, action, snipped_id;
340
341             $snippets.draggable({
342                 greedy: true,
343                 helper: 'clone',
344                 zIndex: '1000',
345                 appendTo: 'body',
346                 cursor: "move",
347                 handle: ".oe_snippet_thumbnail",
348                 cursorAt: {
349                     'left': left,
350                     'top': top
351                 },
352                 start: function(){
353                     self.hide();
354                     dropped = false;
355                     // snippet_selectors => to get drop-near, drop-in
356                     $snippet = $(this);
357                     var $base_body = $snippet.find('.oe_snippet_body');
358                     var selector = [];
359                     var selector_siblings = [];
360                     var selector_children = [];
361                     var vertical = false;
362                     var temp = website.snippet.templateOptions;
363                     for (var k in temp) {
364                         if ($base_body.is(temp[k].base_selector)) {
365                             selector.push(temp[k].base_selector);
366                             if (temp[k]['drop-near'])
367                                 selector_siblings.push(temp[k]['drop-near']);
368                             if (temp[k]['drop-in'])
369                                 selector_children.push(temp[k]['drop-in']);
370                         }
371                     }
372
373                     $toInsert = $base_body.clone();
374                     action = $snippet.find('.oe_snippet_body').size() ? 'insert' : 'mutate';
375
376                     if( action === 'insert'){
377                         if (!selector_siblings.length && !selector_children.length) {
378                             console.debug($snippet.find(".oe_snippet_thumbnail_title").text() + " have not insert action: data-drop-near or data-drop-in");
379                             return;
380                         }
381                         self.activate_insertion_zones({
382                             siblings: selector_siblings.join(","),
383                             children: selector_children.join(","),
384                         });
385
386                     } else if( action === 'mutate' ){
387                         if (!$snippet.data('selector')) {
388                             console.debug($snippet.data("option") + " have not oe_snippet_body class and have not data-selector tag");
389                             return;
390                         }
391                         var $targets = self.activate_overlay_zones(selector_children.join(","));
392                         $targets.each(function(){
393                             var $clone = $(this).data('overlay').clone();
394                              $clone.addClass("oe_drop_zone").data('target', $(this));
395                             $(this).data('overlay').after($clone);
396                         });
397
398                     }
399
400                     $('.oe_drop_zone').droppable({
401                         over:   function(){
402                             if( action === 'insert'){
403                                 dropped = true;
404                                 $(this).first().after($toInsert);
405                             }
406                         },
407                         out:    function(){
408                             var prev = $toInsert.prev();
409                             if( action === 'insert' && this === prev[0]){
410                                 dropped = false;
411                                 $toInsert.detach();
412                             }
413                         }
414                     });
415                 },
416                 stop: function(ev, ui){
417                     $toInsert.removeClass('oe_snippet_body');
418                     
419                     if (action === 'insert' && ! dropped && self.$wrapwrap.find('.oe_drop_zone') && ui.position.top > 3) {
420                         var el = self.$wrapwrap.find('.oe_drop_zone').nearest({x: ui.position.left, y: ui.position.top}).first();
421                         if (el.length) {
422                             el.after($toInsert);
423                             dropped = true;
424                         }
425                     }
426
427                     self.$wrapwrap.find('.oe_drop_zone').droppable('destroy').remove();
428                     
429                     if (dropped) {
430                         var $target = false;
431                         $target = $toInsert;
432
433                         setTimeout(function () {
434                             self.$snippet.trigger('snippet-dropped', $target);
435
436                             website.snippet.start_animation(true, $target);
437
438                             // reset snippet for rte
439                             $target.removeData("snippet-editor");
440                             if ($target.data("overlay")) {
441                                 $target.data("overlay").remove();
442                                 $target.removeData("overlay");
443                             }
444                             $target.find(website.snippet.globalSelector).each(function () {
445                                 var $snippet = $(this);
446                                 $snippet.removeData("snippet-editor");
447                                 if ($snippet.data("overlay")) {
448                                     $snippet.data("overlay").remove();
449                                     $snippet.removeData("overlay");
450                                 }
451                             });
452                             // end
453
454                             // drop_and_build_snippet
455                             self.create_overlay($target);
456                             if ($target.data("snippet-editor")) {
457                                 $target.data("snippet-editor").drop_and_build_snippet();
458                             }
459                             for (var k in website.snippet.templateOptions) {
460                                 $target.find(website.snippet.templateOptions[k].selector).each(function () {
461                                     var $snippet = $(this);
462                                     self.create_overlay($snippet);
463                                     if ($snippet.data("snippet-editor")) {
464                                         $snippet.data("snippet-editor").drop_and_build_snippet();
465                                     }
466                                 });
467                             }
468                             // end
469
470                             self.make_active($target);
471                         },0);
472                     } else {
473                         $toInsert.remove();
474                     }
475                 },
476             });
477         },
478
479         // return the original snippet in the editor bar from a snippet id (string)
480         get_snippet_from_id: function(id){
481             return $('.oe_snippet').filter(function(){
482                     return $(this).data('option') === id;
483                 }).first();
484         },
485
486         // Create element insertion drop zones. two css selectors can be provided
487         // selector.children -> will insert drop zones as direct child of the selected elements
488         //   in case the selected elements have children themselves, dropzones will be interleaved
489         //   with them.
490         // selector.siblings -> will insert drop zones after and before selected elements
491         activate_insertion_zones: function(selector){
492             var self = this;
493             var child_selector = selector.children;
494             var sibling_selector = selector.siblings;
495
496             var zone_template = $("<div class='oe_drop_zone oe_insert'></div>");
497
498             if(child_selector){
499                 self.$wrapwrap.find(child_selector).each(function (){
500                     var $zone = $(this);
501                     var vertical;
502                     var float = window.getComputedStyle(this).float;
503                     if (float === "left" || float === "right") {
504                         vertical = $zone.parent().outerHeight()+'px';
505                     }
506                     var $drop = zone_template.clone();
507                     if (vertical) {
508                         $drop.addClass("oe_vertical").css('height', vertical);
509                     }
510                     $zone.find('> *:not(.oe_drop_zone):visible').after($drop);
511                     $zone.prepend($drop.clone());
512                 });
513             }
514
515             if(sibling_selector){
516                 self.$wrapwrap.find(sibling_selector, true).each(function (){
517                     var $zone = $(this);
518                     var $drop, vertical;
519                     var float = window.getComputedStyle(this).float;
520                     if (float === "left" || float === "right") {
521                         vertical = $zone.parent().outerHeight()+'px';
522                     }
523
524                     if($zone.prev('.oe_drop_zone:visible').length === 0){
525                         $drop = zone_template.clone();
526                         if (vertical) {
527                             $drop.addClass("oe_vertical").css('height', vertical);
528                         }
529                         $zone.before($drop);
530                     }
531                     if($zone.next('.oe_drop_zone:visible').length === 0){
532                         $drop = zone_template.clone();
533                         if (vertical) {
534                             $drop.addClass("oe_vertical").css('height', vertical);
535                         }
536                         $zone.after($drop);
537                     }
538                 });
539             }
540
541             var count;
542             do {
543                 count = 0;
544                 // var $zones = $('.oe_drop_zone + .oe_drop_zone');    // no two consecutive zones
545                 // count += $zones.length;
546                 // $zones.remove();
547
548                 $zones = self.$wrapwrap.find('.oe_drop_zone > .oe_drop_zone:not(.oe_vertical)').remove();   // no recursive zones
549                 count += $zones.length;
550                 $zones.remove();
551             } while (count > 0);
552
553             // Cleaning up zones placed between floating or inline elements. We do not like these kind of zones.
554             var $zones = self.$wrapwrap.find('.oe_drop_zone:not(.oe_vertical)');
555             $zones.each(function (){
556                 var zone = $(this);
557                 var prev = zone.prev();
558                 var next = zone.next();
559                 var float_prev = prev.css('float')   || 'none';
560                 var float_next = next.css('float')   || 'none';
561                 var disp_prev  = prev.css('display') ||  null;
562                 var disp_next  = next.css('display') ||  null;
563                 if(     (float_prev === 'left' || float_prev === 'right')
564                     &&  (float_next === 'left' || float_next === 'right')  ){
565                     zone.remove();
566                 }else if( !( disp_prev === null
567                           || disp_next === null
568                           || disp_prev === 'block'
569                           || disp_next === 'block' )){
570                     zone.remove();
571                 }
572             });
573         },
574
575         // generate drop zones covering the elements selected by the selector
576         // we generate overlay drop zones only to get an idea of where the snippet are, the drop
577         activate_overlay_zones: function(selector){
578             var $targets = typeof selector === "string" ? this.$wrapwrap.find(selector) : selector;
579             var self = this;
580
581             function is_visible($el){
582                 return     $el.css('display')    != 'none'
583                         && $el.css('opacity')    != '0'
584                         && $el.css('visibility') != 'hidden';
585             }
586
587             // filter out invisible elements
588             $targets = $targets.filter(function(){ return is_visible($(this)); });
589
590             // filter out elements with invisible parents
591             $targets = $targets.filter(function(){
592                 var parents = $(this).parents().filter(function(){ return !is_visible($(this)); });
593                 return parents.length === 0;
594             });
595
596             $targets.each(function () {
597                 var $target = $(this);
598                 if (!$target.data('overlay')) {
599                     var $zone = $(openerp.qweb.render('website.snippet_overlay'));
600
601                     // fix for pointer-events: none with ie9
602                     if (document.body && document.body.addEventListener) {
603                         $zone.on("click mousedown mousedown", function passThrough(event) {
604                             event.preventDefault();
605                             $target.each(function() {
606                                // check if clicked point (taken from event) is inside element
607                                 event.srcElement = this;
608                                 $(this).trigger(event.type);
609                             });
610                             return false;
611                         });
612                     }
613
614                     $zone.appendTo('#oe_manipulators');
615                     $zone.data('target',$target);
616                     $target.data('overlay',$zone);
617
618                     $target.on("DOMNodeInserted DOMNodeRemoved DOMSubtreeModified", function () {
619                         self.cover_target($zone, $target);
620                     });
621                     var resize = function () {
622                         if ($zone.parent().length) {
623                             self.cover_target($zone, $target);
624                         } else {
625                             $('body').off("resize", resize);
626                         }
627                     };
628                     $('body').on("resize", resize);
629                 }
630                 self.cover_target($target.data('overlay'), $target);
631             });
632             return $targets;
633         }
634     });
635
636
637     website.snippet.options = {};
638     website.snippet.Option = openerp.Class.extend({
639         // initialisation (don't overwrite)
640         init: function (BuildingBlock, editor, $target, option_id) {
641             this.BuildingBlock = BuildingBlock;
642             this.editor = editor;
643             this.$target = $target;
644             var option = website.snippet.templateOptions[option_id];
645             var styles = this.$target.data("snippet-option-ids") || {};
646             styles[option_id] = this;
647             this.$target.data("snippet-option-ids", styles);
648             this.$overlay = this.$target.data('overlay') || $('<div>');
649             this.option= option_id;
650             this.$el = option.$el.find(">li").clone();
651             this.data = option.$el.data();
652
653             this.set_active();
654             this.$target.on('snippet-option-reset', _.bind(this.set_active, this));
655             this._bind_li_menu();
656
657             this.start();
658         },
659
660         _bind_li_menu: function () {
661             this.$el.filter("li:hasData").find('a:first')
662                 .off('mouseenter click')
663                 .on('mouseenter click', _.bind(this._mouse, this));
664
665             this.$el
666                 .off('mouseenter click', "li:hasData a")
667                 .on('mouseenter click', "li:hasData a", _.bind(this._mouse, this));
668
669             this.$el.closest("ul").add(this.$el)
670                 .off('mouseleave')
671                 .on('mouseleave', _.bind(this.reset, this));
672
673             this.$el
674                 .off('mouseleave', "ul")
675                 .on('mouseleave', "ul", _.bind(this.reset, this));
676
677             this.reset_methods = [];
678             this.reset_time = null;
679         },
680
681         /**
682          * this method handles mouse:over and mouse:leave on the snippet editor menu
683          */
684          _time_mouseleave: null,
685         _mouse: function (event) {
686             var $next = $(event.currentTarget).parent();
687
688             // triggers preview or apply methods if a menu item has been clicked
689             this.select(event.type === "click" ? "click" : "over", $next);
690             if (event.type === 'click') {
691                 this.set_active();
692                 this.$target.trigger("snippet-option-change", [this]);
693             } else {
694                 this.$target.trigger("snippet-option-preview", [this]);
695             }
696         },
697         /* 
698         *  select and set item active or not (add highlight item and his parents)
699         *  called before start
700         */
701         set_active: function () {
702             var classes = _.uniq((this.$target.attr("class") || '').split(/\s+/));
703             this.$el.find('[data-toggle_class], [data-select_class]')
704                 .add(this.$el)
705                 .filter('[data-toggle_class], [data-select_class]')
706                 .removeClass("active")
707                 .filter('[data-toggle_class="' + classes.join('"], [data-toggle_class="') + '"] ,'+
708                     '[data-select_class="' + classes.join('"], [data-select_class="') + '"]')
709                 .addClass("active");
710         },
711
712         start: function () {
713         },
714
715         on_focus : function () {
716             this._bind_li_menu();
717         },
718
719         on_blur : function () {
720         },
721
722         on_clone: function ($clone) {
723         },
724
725         on_remove: function () {
726         },
727
728         drop_and_build_snippet: function () {
729         },
730
731         reset: function (event) {
732             var self = this;
733             var lis = self.$el.add(self.$el.find('li')).filter('.active').get();
734             lis.reverse();
735             _.each(lis, function (li) {
736                 var $li = $(li);
737                 for (var k in self.reset_methods) {
738                     var method = self.reset_methods[k];
739                     if ($li.is('[data-'+method+']') || $li.closest('[data-'+method+']').size()) {
740                         delete self.reset_methods[k];
741                     }
742                 }
743                 self.select("reset", $li);
744             });
745
746             for (var k in self.reset_methods) {
747                 var method = self.reset_methods[k];
748                 if (method) {
749                     self[method]("reset", null);
750                 }
751             }
752             self.reset_methods = [];
753             self.$target.trigger("snippet-option-reset", [this]);
754         },
755
756         // call data-method args as method
757         select: function (type, $li) {
758             var self = this,
759                 $methods = [],
760                 el = $li[0],
761                 $el;
762             clearTimeout(this.reset_time);
763
764             function filter (k) { return k !== 'oeId' && k !== 'oeModel' && k !== 'oeField' && k !== 'oeXpath' && k !== 'oeSourceId';}
765             function hasData(el) {
766                 for (var k in el.dataset) {
767                     if (filter (k)) {
768                         return true;
769                     }
770                 }
771                 return false;
772             }
773             function method(el) {
774                 var data = {};
775                 for (var k in el.dataset) {
776                     if (filter (k)) {
777                         data[k] = el.dataset[k];
778                     }
779                 }
780                 return data;
781             }
782
783             while (el && this.$el.is(el) || _.some(this.$el.map(function () {return $.contains(this, el);}).get()) ) {
784                 if (hasData(el)) {
785                     $methods.push(el);
786                 }
787                 el = el.parentNode;
788             }
789
790             $methods.reverse();
791
792             _.each($methods, function (el) {
793                 var $el = $(el);
794                 var methods = method(el);
795
796                 for (var k in methods) {
797                     if (self[k]) {
798                         if (type !== "reset" && self.reset_methods.indexOf(k) === -1) {
799                             self.reset_methods.push(k);
800                         }
801                         self[k](type, methods[k], $el);
802                     } else {
803                         console.error("'"+self.option+"' snippet have not method '"+k+"'");
804                     }
805                 }
806             });
807         },
808
809         // default method for snippet
810         toggle_class: function (type, value, $li) {
811             var $lis = this.$el.find('[data-toggle_class]').add(this.$el).filter('[data-toggle_class]');
812
813             function map ($lis) {
814                 return $lis.map(function () {return $(this).data("toggle_class");}).get().join(" ");
815             }
816             var classes = map($lis);
817             var active_classes = map($lis.filter('.active, :has(.active)'));
818
819             this.$target.removeClass(classes);
820             this.$target.addClass(active_classes);
821
822             if (type !== 'reset') {
823                 this.$target.toggleClass(value);
824             }
825         },
826         select_class: function (type, value, $li) {
827             var $lis = this.$el.find('[data-select_class]').add(this.$el).filter('[data-select_class]');
828
829             var classes = $lis.map(function () {return $(this).data('select_class');}).get();
830
831             this.$target.removeClass(classes.join(" "));
832             if(value) this.$target.addClass(value);
833         },
834         eval: function (type, value, $li) {
835             var fn = new Function("node", "type", "value", "$li", value);
836             fn.call(this, this, type, value, $li);
837         },
838
839         clean_for_save: dummy
840     });
841     website.snippet.options.background = website.snippet.Option.extend({
842         start: function () {
843             this._super();
844             var src = this.$target.css("background-image").replace(/url\(['"]*|['"]*\)|^none$/g, "");
845             if (this.$target.hasClass('oe_custom_bg')) {
846                 this.$el.find('li[data-choose_image]').data("background", src).attr("data-background", src);
847             }
848         },
849         background: function(type, value, $li) {
850             if (value && value.length) {
851                 this.$target.css("background-image", 'url(' + value + ')');
852                 this.$target.addClass("oe_img_bg");
853             } else {
854                 this.$target.css("background-image", "");
855                 this.$target.removeClass("oe_img_bg").removeClass("oe_custom_bg");
856             }
857         },
858         choose_image: function(type, value, $li) {
859             if(type !== "click") return;
860
861             var self = this;
862             var $image = $('<img class="hidden"/>');
863             $image.attr("src", value);
864             $image.appendTo(self.$target);
865
866             self.element = new CKEDITOR.dom.element($image[0]);
867             var editor = new website.editor.MediaDialog(self, self.element);
868             editor.appendTo(document.body);
869             editor.$('[href="#editor-media-video"], [href="#editor-media-icon"]').addClass('hidden');
870
871             $image.on('saved', self, function (o) {
872                 var value = $image.attr("src");
873                 self.$target.css("background-image", 'url(' + value + ')');
874                 self.$el.find('li[data-choose_image]').data("background", value).attr("data-background", value);
875                 self.$target.trigger("snippet-option-change", [self]);
876                 $image.remove();
877                 self.$target.addClass('oe_custom_bg oe_img_bg');
878                 self.set_active();
879             });
880             editor.on('cancel', self, function () {
881                 self.$target.trigger("snippet-option-change", [self]);
882                 $image.remove();
883             });
884         },
885         set_active: function () {
886             var self = this;
887             var src = this.$target.css("background-image").replace(/url\(['"]*|['"]*\)|^none$/g, "");
888             this._super();
889
890             this.$el.find('li[data-background]:not([data-background=""])')
891                 .removeClass("active")
892                 .each(function () {
893                     var background = $(this).data("background") || $(this).attr("data-background");
894                     if ((src.length && background.length && src.indexOf(background) !== -1) || (!src.length && !background.length)) {
895                         $(this).addClass("active");
896                     }
897                 });
898
899             if (!this.$el.find('li[data-background].active').size()) {
900                 this.$el.find('li[data-background=""]:not([data-choose_image])').addClass("active");
901             } else {
902                 this.$el.find('li[data-background=""]:not([data-choose_image])').removeClass("active");
903             }
904         }
905     });
906
907     website.snippet.options.colorpicker = website.snippet.Option.extend({
908         start: function () {
909             var self = this;
910             var res = this._super();
911
912             this.$el.find('li').append( openerp.qweb.render('website.colorpicker') );
913
914             var classes = [];
915             this.$el.find("table.colorpicker td > *").map(function () {
916                 var $color = $(this);
917                 var color = $color.attr("class");
918                 if (self.$target.hasClass(color)) {
919                     self.color = color;
920                     $color.parent().addClass("selected");
921                 }
922                 classes.push(color);
923             });
924             this.classes = classes.join(" ");
925
926             this.bind_events();
927             return res;
928         },
929         bind_events: function () {
930             var self = this;
931             var $td = this.$el.find("table.colorpicker td");
932             var $colors = $td.children();
933             $colors
934                 .mouseenter(function () {
935                     self.$target.removeClass(self.classes).addClass($(this).attr("class"));
936                 })
937                 .mouseleave(function () {
938                     self.$target.removeClass(self.classes)
939                         .addClass($td.filter(".selected").children().attr("class"));
940                 })
941                 .click(function () {
942                     $td.removeClass("selected");
943                     $(this).parent().addClass("selected");
944                 });
945         }
946     });
947
948     website.snippet.options.slider = website.snippet.Option.extend({
949         unique_id: function () {
950             var id = 0;
951             $(".carousel").each(function () {
952                 var cid = 1 + parseInt($(this).attr("id").replace(/[^0123456789]/g, ''),10);
953                 if (id < cid) id = cid;
954             });
955             return "myCarousel" + id;
956         },
957         drop_and_build_snippet: function() {
958             this.id = this.unique_id();
959             this.$target.attr("id", this.id);
960             this.$target.find("[data-slide]").attr("data-cke-saved-href", "#" + this.id);
961             this.$target.find("[data-target]").attr("data-target", "#" + this.id);
962             this.rebind_event();
963         },
964         on_clone: function ($clone) {
965             var id = this.unique_id();
966             $clone.attr("id", id);
967             $clone.find("[data-slide]").attr("href", "#" + id);
968             $clone.find("[data-slide-to]").attr("data-target", "#" + id);
969         },
970         // rebind event to active carousel on edit mode
971         rebind_event: function () {
972             var self = this;
973             this.$target.find('.carousel-indicators [data-slide-to]').off('click').on('click', function () {
974                 self.$target.carousel(+$(this).data('slide-to')); });
975
976             this.$target.attr('contentEditable', 'false');
977             this.$target.find('.oe_structure, .content>.row, [data-slide]').attr('contentEditable', 'true');
978         },
979         clean_for_save: function () {
980             this._super();
981             this.$target.find(".item").removeClass("next prev left right active")
982                 .first().addClass("active");
983             this.$indicators.find('li').removeClass('active')
984                 .first().addClass("active");
985         },
986         start : function () {
987             var self = this;
988             this._super();
989             this.$target.carousel({interval: false});
990             this.id = this.$target.attr("id");
991             this.$inner = this.$target.find('.carousel-inner');
992             this.$indicators = this.$target.find('.carousel-indicators');
993             this.$target.carousel('pause');
994             this.rebind_event();
995         },
996         add_slide: function (type, value) {
997             if(type !== "click") return;
998
999             var self = this;
1000             var cycle = this.$inner.find('.item').length;
1001             var $active = this.$inner.find('.item.active, .item.prev, .item.next').first();
1002             var index = $active.index();
1003             this.$target.find('.carousel-control, .carousel-indicators').removeClass("hidden");
1004             this.$indicators.append('<li data-target="#' + this.id + '" data-slide-to="' + cycle + '"></li>');
1005
1006             var $clone = this.$target.find(".item.active").clone();
1007
1008             // insert
1009             $clone.removeClass('active').insertAfter($active);
1010             setTimeout(function() {
1011                 self.$target.carousel().carousel(++index);
1012                 self.rebind_event();
1013             },0);
1014             return $clone;
1015         },
1016         remove_slide: function (type, value) {
1017             if(type !== "click") return;
1018
1019             if (this.remove_process) {
1020                 return;
1021             }
1022             var self = this;
1023             var new_index = 0;
1024             var cycle = this.$inner.find('.item').length - 1;
1025             var index = this.$inner.find('.item.active').index();
1026
1027             if (cycle > 0) {
1028                 this.remove_process = true;
1029                 var $el = this.$inner.find('.item.active');
1030                 self.$target.on('slid.bs.carousel', function (event) {
1031                     $el.remove();
1032                     self.$indicators.find("li:last").remove();
1033                     self.$target.off('slid.bs.carousel');
1034                     self.rebind_event();
1035                     self.remove_process = false;
1036                     if (cycle == 1) {
1037                         self.on_remove_slide(event);
1038                     }
1039                 });
1040                 setTimeout(function () {
1041                     self.$target.carousel( index > 0 ? --index : cycle );
1042                 }, 500);
1043             } else {
1044                 this.$target.find('.carousel-control, .carousel-indicators').addClass("hidden");
1045             }
1046         },
1047         interval : function(type, value) {
1048             this.$target.attr("data-interval", value);
1049         },
1050         set_active: function () {
1051             this.$el.find('li[data-interval]').removeClass("active")
1052                 .filter('li[data-interval='+this.$target.attr("data-interval")+']').addClass("active");
1053         },
1054     });
1055     website.snippet.options.carousel = website.snippet.options.slider.extend({
1056         getSize: function () {
1057             this.grid = this._super();
1058             this.grid.size = 8;
1059             return this.grid;
1060         },
1061         clean_for_save: function () {
1062             this._super();
1063             this.$target.removeClass('oe_img_bg ' + this._class).css("background-image", "");
1064         },
1065         load_style_options : function () {
1066             this._super();
1067             $(".snippet-option-size li[data-value='']").remove();
1068         },
1069         start : function () {
1070             var self = this;
1071             this._super();
1072
1073             // set background and prepare to clean for save
1074             var add_class = function (c){
1075                 if (c) self._class = (self._class || "").replace(new RegExp("[ ]+" + c.replace(" ", "|[ ]+")), '') + ' ' + c;
1076                 return self._class || "";
1077             };
1078             this.$target.on('slid.bs.carousel', function () {
1079                 if(self.editor && self.editor.styles.background) {
1080                     self.editor.styles.background.$target = self.$target.find(".item.active");
1081                     self.editor.styles.background.set_active();
1082                 }
1083                 self.$target.carousel("pause");
1084             });
1085             this.$target.trigger('slid.bs.carousel');
1086         },
1087         add_slide: function (type, data) {
1088             if(type !== "click") return;
1089
1090             var $clone = this._super(type, data);
1091             // choose an other background
1092             var bg = this.$target.data("snippet-option-ids").background;
1093             if (!bg) return $clone;
1094
1095             var $styles = bg.$el.find("li[data-background]");
1096             var $select = $styles.filter(".active").removeClass("active").next("li[data-background]");
1097             if (!$select.length) {
1098                 $select = $styles.first();
1099             }
1100             $select.addClass("active");
1101             $clone.css("background-image", $select.data("background") ? "url('"+ $select.data("background") +"')" : "");
1102
1103             return $clone;
1104         },
1105         // rebind event to active carousel on edit mode
1106         rebind_event: function () {
1107             var self = this;
1108             this.$target.find('.carousel-control').off('click').on('click', function () {
1109                 self.$target.carousel( $(this).data('slide')); });
1110
1111             this.$target.find('.carousel-image, .carousel-inner .content > div').attr('contentEditable', 'true');
1112             this.$target.find('.carousel-image').attr('attributeEditable', 'true');
1113             this._super();
1114         },
1115     });
1116     website.snippet.options.marginAndResize = website.snippet.Option.extend({
1117         start: function () {
1118             var self = this;
1119             this._super();
1120
1121             var resize_values = this.getSize();
1122             if (resize_values.n) this.$overlay.find(".oe_handle.n").removeClass("readonly");
1123             if (resize_values.s) this.$overlay.find(".oe_handle.s").removeClass("readonly");
1124             if (resize_values.e) this.$overlay.find(".oe_handle.e").removeClass("readonly");
1125             if (resize_values.w) this.$overlay.find(".oe_handle.w").removeClass("readonly");
1126             if (resize_values.size) this.$overlay.find(".oe_handle.size").removeClass("readonly");
1127
1128             this.$overlay.find(".oe_handle:not(.size), .oe_handle.size .size").on('mousedown', function (event){
1129                 event.preventDefault();
1130
1131                 var $handle = $(this);
1132
1133                 var resize_values = self.getSize();
1134                 var compass = false;
1135                 var XY = false;
1136                 if ($handle.hasClass('n')) {
1137                     compass = 'n';
1138                     XY = 'Y';
1139                 }
1140                 else if ($handle.hasClass('s')) {
1141                     compass = 's';
1142                     XY = 'Y';
1143                 }
1144                 else if ($handle.hasClass('e')) {
1145                     compass = 'e';
1146                     XY = 'X';
1147                 }
1148                 else if ($handle.hasClass('w')) {
1149                     compass = 'w';
1150                     XY = 'X';
1151                 }
1152                 else if ($handle.hasClass('size')) {
1153                     compass = 'size';
1154                     XY = 'Y';
1155                 }
1156
1157                 var resize = resize_values[compass];
1158                 if (!resize) return;
1159
1160
1161                 if (compass === 'size') {
1162                     var offset = self.$target.offset().top;
1163                     if (self.$target.css("background").match(/rgba\(0, 0, 0, 0\)/)) {
1164                         self.$target.addClass("resize_editor_busy");
1165                     }
1166                 } else {
1167                     var xy = event['page'+XY];
1168                     var current = resize[2] || 0;
1169                     _.each(resize[0], function (val, key) {
1170                         if (self.$target.hasClass(val)) {
1171                             current = key;
1172                         }
1173                     });
1174                     var begin = current;
1175                     var beginClass = self.$target.attr("class");
1176                     var regClass = new RegExp("\\s*" + resize[0][begin].replace(/[-]*[0-9]+/, '[-]*[0-9]+'), 'g');
1177                 }
1178
1179                 self.BuildingBlock.editor_busy = true;
1180
1181                 var cursor = $handle.css("cursor")+'-important';
1182                 var $body = $(document.body);
1183                 $body.addClass(cursor);
1184
1185                 var body_mousemove = function (event){
1186                     event.preventDefault();
1187                     if (compass === 'size') {
1188                         var dy = event.pageY-offset;
1189                         dy = dy - dy%resize;
1190                         if (dy <= 0) dy = resize;
1191                         self.$target.css("height", dy+"px");
1192                         self.$target.css("overflow", "hidden");
1193                         self.on_resize(compass, null, dy);
1194                         self.BuildingBlock.cover_target(self.$overlay, self.$target);
1195                         return;
1196                     }
1197                     var dd = event['page'+XY] - xy + resize[1][begin];
1198                     var next = current+1 === resize[1].length ? current : (current+1);
1199                     var prev = current ? (current-1) : 0;
1200
1201                     var change = false;
1202                     if (dd > (2*resize[1][next] + resize[1][current])/3) {
1203                         self.$target.attr("class", (self.$target.attr("class")||'').replace(regClass, ''));
1204                         self.$target.addClass(resize[0][next]);
1205                         current = next;
1206                         change = true;
1207                     }
1208                     if (prev != current && dd < (2*resize[1][prev] + resize[1][current])/3) {
1209                         self.$target.attr("class", (self.$target.attr("class")||'').replace(regClass, ''));
1210                         self.$target.addClass(resize[0][prev]);
1211                         current = prev;
1212                         change = true;
1213                     }
1214
1215                     if (change) {
1216                         self.on_resize(compass, beginClass, current);
1217                         self.BuildingBlock.cover_target(self.$overlay, self.$target);
1218                     }
1219                 };
1220
1221                 var body_mouseup = function(){
1222                     $body.unbind('mousemove', body_mousemove);
1223                     $body.unbind('mouseup', body_mouseup);
1224                     $body.removeClass(cursor);
1225                     self.BuildingBlock.editor_busy = false;
1226                     self.$target.removeClass("resize_editor_busy");
1227                 };
1228                 $body.mousemove(body_mousemove);
1229                 $body.mouseup(body_mouseup);
1230             });
1231             this.$overlay.find(".oe_handle.size .auto_size").on('click', function (event){
1232                 self.$target.css("height", "");
1233                 self.$target.css("overflow", "");
1234                 self.BuildingBlock.cover_target(self.$overlay, self.$target);
1235                 return false;
1236             });
1237         },
1238         getSize: function () {
1239             this.grid = {};
1240             return this.grid;
1241         },
1242
1243         on_focus : function () {
1244             this._super();
1245             this.change_cursor();
1246         },
1247
1248         change_cursor : function () {
1249             var _class = this.$target.attr("class") || "";
1250
1251             var col = _class.match(/col-md-([0-9-]+)/i);
1252             col = col ? +col[1] : 0;
1253
1254             var offset = _class.match(/col-md-offset-([0-9-]+)/i);
1255             offset = offset ? +offset[1] : 0;
1256
1257             var overlay_class = this.$overlay.attr("class").replace(/(^|\s+)block-[^\s]*/gi, '');
1258             if (col+offset >= 12) overlay_class+= " block-e-right";
1259             if (col === 1) overlay_class+= " block-w-right block-e-left";
1260             if (offset === 0) overlay_class+= " block-w-left";
1261
1262             var mb = _class.match(/mb([0-9-]+)/i);
1263             mb = mb ? +mb[1] : 0;
1264             if (mb >= 128) overlay_class+= " block-s-bottom";
1265             else if (!mb) overlay_class+= " block-s-top";
1266
1267             var mt = _class.match(/mt([0-9-]+)/i);
1268             mt = mt ? +mt[1] : 0;
1269             if (mt >= 128) overlay_class+= " block-n-top";
1270             else if (!mt) overlay_class+= " block-n-bottom";
1271
1272             this.$overlay.attr("class", overlay_class);
1273         },
1274         
1275         /* on_resize
1276         *  called when the box is resizing and the class change, before the cover_target
1277         *  @compass: resize direction : 'n', 's', 'e', 'w'
1278         *  @beginClass: attributes class at the begin
1279         *  @current: curent increment in this.grid
1280         */
1281         on_resize: function (compass, beginClass, current) {
1282             this.change_cursor();
1283         }
1284     });
1285     website.snippet.options["margin-y"] = website.snippet.options.marginAndResize.extend({
1286         getSize: function () {
1287             this.grid = this._super();
1288             var grid = [0,4,8,16,32,48,64,92,128];
1289             this.grid = {
1290                 // list of class (Array), grid (Array), default value (INT)
1291                 n: [_.map(grid, function (v) {return 'mt'+v;}), grid],
1292                 s: [_.map(grid, function (v) {return 'mb'+v;}), grid],
1293                 // INT if the user can resize the snippet (resizing per INT px)
1294                 size: null
1295             };
1296             return this.grid;
1297         },
1298     });
1299     website.snippet.options["margin-x"] = website.snippet.options.marginAndResize.extend({
1300         getSize: function () {
1301             this.grid = this._super();
1302             var width = this.$target.parents(".row:first").first().outerWidth();
1303
1304             var grid = [1,2,3,4,5,6,7,8,9,10,11,12];
1305             this.grid.e = [_.map(grid, function (v) {return 'col-md-'+v;}), _.map(grid, function (v) {return width/12*v;})];
1306
1307             var grid = [-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11];
1308             this.grid.w = [_.map(grid, function (v) {return 'col-md-offset-'+v;}), _.map(grid, function (v) {return width/12*v;}), 12];
1309
1310             return this.grid;
1311         },
1312         _drag_and_drop_after_insert_dropzone: function(){
1313             var self = this;
1314             var $zones = $(".row:has(> .oe_drop_zone)").each(function () {
1315                 var $row = $(this);
1316                 var width = $row.innerWidth();
1317                 var pos = 0;
1318                 while (width > pos + self.size.width) {
1319                     var $last = $row.find("> .oe_drop_zone:last");
1320                     $last.each(function () {
1321                         pos = $(this).position().left;
1322                     });
1323                     if (width > pos + self.size.width) {
1324                         $row.append("<div class='col-md-1 oe_drop_to_remove'/>");
1325                         var $add_drop = $last.clone();
1326                         $row.append($add_drop);
1327                         self._drag_and_drop_active_drop_zone($add_drop);
1328                     }
1329                 }
1330             });
1331         },
1332         _drag_and_drop_start: function () {
1333             this._super();
1334             this.$target.attr("class",this.$target.attr("class").replace(/\s*(col-lg-offset-|col-md-offset-)([0-9-]+)/g, ''));
1335         },
1336         _drag_and_drop_stop: function () {
1337             this.$target.addClass("col-md-offset-" + this.$target.prevAll(".oe_drop_to_remove").length);
1338             this._super();
1339         },
1340         hide_remove_button: function() {
1341             this.$overlay.find('.oe_snippet_remove').toggleClass("hidden", !this.$target.siblings().length);
1342         },
1343         on_focus : function () {
1344             this._super();
1345             this.hide_remove_button();
1346         },
1347         on_clone: function ($clone) {
1348             var _class = $clone.attr("class").replace(/\s*(col-lg-offset-|col-md-offset-)([0-9-]+)/g, '');
1349             $clone.attr("class", _class);
1350             this.hide_remove_button();
1351             return false;
1352         },
1353         on_remove: function () {
1354             this._super();
1355             this.hide_remove_button();
1356         },
1357         on_resize: function (compass, beginClass, current) {
1358             if (compass === 'w') {
1359                 // don't change the right border position when we change the offset (replace col size)
1360                 var beginCol = Number(beginClass.match(/col-md-([0-9]+)|$/)[1] || 0);
1361                 var beginOffset = Number(beginClass.match(/col-md-offset-([0-9-]+)|$/)[1] || beginClass.match(/col-lg-offset-([0-9-]+)|$/)[1] || 0);
1362                 var offset = Number(this.grid.w[0][current].match(/col-md-offset-([0-9-]+)|$/)[1] || 0);
1363                 if (offset < 0) {
1364                     offset = 0;
1365                 }
1366                 var colSize = beginCol - (offset - beginOffset);
1367                 if (colSize <= 0) {
1368                     colSize = 1;
1369                     offset = beginOffset + beginCol - 1;
1370                 }
1371                 this.$target.attr("class",this.$target.attr("class").replace(/\s*(col-lg-offset-|col-md-offset-|col-md-)([0-9-]+)/g, ''));
1372
1373                 this.$target.addClass('col-md-' + (colSize > 12 ? 12 : colSize));
1374                 if (offset > 0) {
1375                     this.$target.addClass('col-md-offset-' + offset);
1376                 }
1377             }
1378             this._super(compass, beginClass, current);
1379         },
1380     });
1381
1382     website.snippet.options.resize = website.snippet.options.marginAndResize.extend({
1383         getSize: function () {
1384             this.grid = this._super();
1385             this.grid.size = 8;
1386             return this.grid;
1387         },
1388     });
1389
1390     website.snippet.options.parallax = website.snippet.Option.extend({
1391         getSize: function () {
1392             this.grid = this._super();
1393             this.grid.size = 8;
1394             return this.grid;
1395         },
1396         on_resize: function (compass, beginClass, current) {
1397             this.$target.data("snippet-view").set_values();
1398         },
1399         start : function () {
1400             var self = this;
1401             this._super();
1402             if (!self.$target.data("snippet-view")) {
1403                 this.$target.data("snippet-view", new website.snippet.animationRegistry.parallax(this.$target));
1404             }
1405             this.scroll();
1406             this.$target.on('snippet-option-change snippet-option-preview', function () {
1407                 self.$target.data("snippet-view").set_values();
1408             });
1409             this.$target.attr('contentEditable', 'false');
1410
1411             this.$target.find('> div > .oe_structure').attr('contentEditable', 'true'); // saas-3 retro-compatibility
1412
1413             this.$target.find('> div > div:not(.oe_structure) > .oe_structure').attr('contentEditable', 'true');
1414         },
1415         scroll: function (type, value) {
1416             this.$target.attr('data-scroll-background-ratio', value);
1417             this.$target.data("snippet-view").set_values();
1418         },
1419         set_active: function () {
1420             var value = this.$target.attr('data-scroll-background-ratio') || 0;
1421             this.$el.find('[data-scroll]').removeClass("active")
1422                 .filter('[data-scroll="' + (this.$target.attr('data-scroll-background-ratio') || 0) + '"]').addClass("active");
1423         },
1424         clean_for_save: function () {
1425             this._super();
1426             this.$target.find(".parallax")
1427                 .css("background-position", '')
1428                 .removeAttr("data-scroll-background-offset");
1429         }
1430     });
1431
1432     website.snippet.options.transform = website.snippet.Option.extend({
1433         start: function () {
1434             var self = this;
1435             this._super();
1436             this.$overlay.find('.oe_snippet_clone, .oe_handles').addClass('hidden');
1437             this.$overlay.find('[data-toggle="dropdown"]')
1438                 .on("mousedown", function () {
1439                     self.$target.transfo("hide");
1440                 });
1441         },
1442         style: function (type, value) {
1443             if (type !== 'click') return;
1444             var settings = this.$target.data("transfo").settings;
1445             this.$target.transfo({ hide: (settings.hide = !settings.hide) });
1446         },
1447         clear_style: function (type, value) {
1448             if (type !== 'click') return;
1449             this.$target.removeClass("fa-spin").attr("style", "");
1450             this.resetTransfo();
1451         },
1452         resetTransfo: function () {
1453             var self = this;
1454             this.$target.transfo("destroy");
1455             this.$target.transfo({
1456                 hide: true,
1457                 callback: function () {
1458                     var pos = $(this).data("transfo").$center.offset();
1459                     self.$overlay.css({
1460                         'top': pos.top,
1461                         'left': pos.left,
1462                         'position': 'absolute',
1463                     });
1464                     self.$overlay.find(".oe_overlay_options").attr("style", "width:0; left:0!important; top:0;");
1465                     self.$overlay.find(".oe_overlay_options > .btn-group").attr("style", "width:160px; left:-80px;");
1466                 }});
1467             this.$target.data('transfo').$markup
1468                 .on("mouseover", function () {
1469                     self.$target.trigger("mouseover");
1470                 })
1471                 .mouseover();
1472         },
1473         on_focus : function () {
1474             this.resetTransfo();
1475         },
1476         on_blur : function () {
1477             this.$target.transfo("hide");
1478         },
1479     });
1480
1481     website.snippet.options.media = website.snippet.Option.extend({
1482         start: function () {
1483             var self = this;
1484             this._super();
1485
1486             website.snippet.start_animation(true, this.$target);
1487
1488             $(document.body).on("media-saved", self, function (event, prev , item) {
1489                 self.editor.on_blur();
1490                 self.BuildingBlock.make_active(false);
1491                 if (self.$target.parent().data("oe-field") !== "image") {
1492                     self.BuildingBlock.make_active($(item));
1493                 }
1494             });
1495         },
1496         edition: function (type, value) {
1497             if(type !== "click") return;
1498             this.element = new CKEDITOR.dom.element(this.$target[0]);
1499             new website.editor.MediaDialog(this, this.element).appendTo(document.body);
1500         },
1501         on_focus : function () {
1502             var self = this;
1503             if (this.$target.parent().data("oe-field") === "image") {
1504                 this.$overlay.addClass("hidden");
1505                 self.element = new CKEDITOR.dom.element(self.$target[0]);
1506                 new website.editor.MediaDialog(self, self.element).appendTo(document.body);
1507                 self.BuildingBlock.make_active(false);
1508             }
1509             setTimeout(function () {
1510                 self.$target.find(".css_editable_mode_display").removeAttr("_moz_abspos");
1511             },0);
1512         },
1513     });
1514
1515     website.snippet.Editor = openerp.Class.extend({
1516         init: function (BuildingBlock, dom) {
1517             this.BuildingBlock = BuildingBlock;
1518             this.$target = $(dom);
1519             this.$overlay = this.$target.data('overlay');
1520             this.load_style_options();
1521             this.get_parent_block();
1522             this.start();
1523         },
1524
1525         // activate drag and drop for the snippets in the snippet toolbar
1526         _drag_and_drop: function(){
1527             var self = this;
1528             this.dropped = false;
1529             this.$overlay.draggable({
1530                 greedy: true,
1531                 appendTo: 'body',
1532                 cursor: "move",
1533                 handle: ".oe_snippet_move",
1534                 cursorAt: {
1535                     left: 18,
1536                     top: 14
1537                 },
1538                 helper: function() {
1539                     var $clone = $(this).clone().css({width: "24px", height: "24px", border: 0});
1540                     $clone.find(".oe_overlay_options >:not(:contains(.oe_snippet_move)), .oe_handle").remove();
1541                     $clone.find(":not(.glyphicon)").css({position: 'absolute', top: 0, left: 0});
1542                     $clone.appendTo("body").removeClass("hidden");
1543                     return $clone;
1544                 },
1545                 start: _.bind(self._drag_and_drop_start, self),
1546                 stop: _.bind(self._drag_and_drop_stop, self)
1547             });
1548         },
1549         _drag_and_drop_after_insert_dropzone: function (){},
1550         _drag_and_drop_active_drop_zone: function ($zones){
1551             var self = this;
1552             $zones.droppable({
1553                 over:   function(){
1554                     $(".oe_drop_zone.hide").removeClass("hide");
1555                     $(this).addClass("hide").first().after(self.$target);
1556                     self.dropped = true;
1557                 },
1558                 out:    function(){
1559                     $(this).removeClass("hide");
1560                     self.$target.detach();
1561                     self.dropped = false;
1562                 },
1563             });
1564         },
1565         _drag_and_drop_start: function (){
1566             var self = this;
1567             self.BuildingBlock.hide();
1568             self.BuildingBlock.editor_busy = true;
1569             self.size = {
1570                 width: self.$target.width(),
1571                 height: self.$target.height()
1572             };
1573             self.$target.after("<div class='oe_drop_clone' style='display: none;'/>");
1574             self.$target.detach();
1575             self.$overlay.addClass("hidden");
1576
1577             self.BuildingBlock.activate_insertion_zones({
1578                 siblings: self.selector_siblings,
1579                 children: self.selector_children,
1580             });
1581
1582             $("body").addClass('move-important');
1583
1584             self._drag_and_drop_after_insert_dropzone();
1585             self._drag_and_drop_active_drop_zone($('.oe_drop_zone'));
1586         },
1587         _drag_and_drop_stop: function (){
1588             var self = this;
1589             if (!self.dropped) {
1590                 $(".oe_drop_clone").after(self.$target);
1591             }
1592             self.$overlay.removeClass("hidden");
1593             $("body").removeClass('move-important');
1594             $('.oe_drop_zone').droppable('destroy').remove();
1595             $(".oe_drop_clone, .oe_drop_to_remove").remove();
1596             self.BuildingBlock.editor_busy = false;
1597             self.get_parent_block();
1598             setTimeout(function () {self.BuildingBlock.create_overlay(self.$target);},0);
1599         },
1600
1601         load_style_options: function () {
1602             var self = this;
1603             var $styles = this.$overlay.find('.oe_options');
1604             var $ul = $styles.find('ul:first');
1605             this.styles = {};
1606             this.selector_siblings = [];
1607             this.selector_children = [];
1608             _.each(website.snippet.templateOptions, function (val, option_id) {
1609                 if (!self.$target.is(val.selector)) {
1610                     return;
1611                 }
1612                 if (val['drop-near']) self.selector_siblings.push(val['drop-near']);
1613                 if (val['drop-in']) self.selector_children.push(val['drop-in']);
1614
1615                 var option = val['option'];
1616                 var Editor = website.snippet.options[option] || website.snippet.Option;
1617                 var editor = self.styles[option] = new Editor(self.BuildingBlock, self, self.$target, option_id);
1618                 $ul.append(editor.$el.addClass("snippet-option-" + option));
1619             });
1620             this.selector_siblings = this.selector_siblings.join(",");
1621             if (this.selector_siblings === "")
1622                 this.selector_siblings = false;
1623             this.selector_children = this.selector_children.join(",");
1624             if (this.selector_children === "")
1625                 this.selector_children = false;
1626
1627             if (!this.selector_siblings && !this.selector_children) {
1628                 this.$overlay.find(".oe_snippet_move, .oe_snippet_clone, .oe_snippet_remove").addClass('hidden');
1629             }
1630
1631
1632             if ($ul.find("li").length) {
1633                 $styles.removeClass("hidden");
1634             }
1635             this.$overlay.find('[data-toggle="dropdown"]').dropdown();
1636         },
1637
1638         get_parent_block: function () {
1639             var self = this;
1640             var $button = this.$overlay.find('.oe_snippet_parent');
1641             var $parent = this.$target.parents(website.snippet.globalSelector).first();
1642             if ($parent.length) {
1643                 $button.removeClass("hidden");
1644                 $button.off("click").on('click', function (event) {
1645                     event.preventDefault();
1646                     setTimeout(function () {
1647                         self.BuildingBlock.make_active($parent);
1648                     }, 0);
1649                 });
1650             } else {
1651                 $button.addClass("hidden");
1652             }
1653         },
1654
1655         /*
1656         *  start
1657         *  This method is called after init and _readXMLData
1658         */
1659         start: function () {
1660             var self = this;
1661             this.$overlay.on('click', '.oe_snippet_clone', _.bind(this.on_clone, this));
1662             this.$overlay.on('click', '.oe_snippet_remove', _.bind(this.on_remove, this));
1663             this._drag_and_drop();
1664         },
1665
1666         on_clone: function () {
1667             var $clone = this.$target.clone(false);
1668             this.$target.after($clone);
1669             for (var i in this.styles){
1670                 this.styles[i].on_clone($clone);
1671             }
1672             return false;
1673         },
1674
1675         on_remove: function () {
1676             this.on_blur();
1677             var index = _.indexOf(this.BuildingBlock.snippets, this.$target.get(0));
1678             for (var i in this.styles){
1679                 this.styles[i].on_remove();
1680             }
1681             delete this.BuildingBlock.snippets[index];
1682
1683             // remove node and his empty
1684             var parent,
1685                 node = this.$target.parent()[0];
1686
1687             this.$target.remove();
1688             function check(node) {
1689                 if ($(node).outerHeight() > 8) {
1690                     return false;
1691                 }
1692                 for (var k=0; k<node.children.length; k++) {
1693                     if (node.children[k].tagName || node.children[k].textContent.match(/[^\s]/)) {
1694                         return false;
1695                     }
1696                 }
1697                 return true;
1698             }
1699             while (check(node)) {
1700                 parent = node.parentNode;
1701                 parent.removeChild(node);
1702                 node = parent;
1703             }
1704
1705             this.$overlay.remove();
1706             return false;
1707         },
1708
1709         /*
1710         *  drop_and_build_snippet
1711         *  This method is called just after that a thumbnail is drag and dropped into a drop zone
1712         *  (after the insertion of this.$body, if this.$body exists)
1713         */
1714         drop_and_build_snippet: function () {
1715             for (var i in this.styles){
1716                 this.styles[i].drop_and_build_snippet();
1717             }
1718         },
1719
1720         /* on_focus
1721         *  This method is called when the user click inside the snippet in the dom
1722         */
1723         on_focus : function () {
1724             this.$overlay.addClass('oe_active');
1725             for (var i in this.styles){
1726                 this.styles[i].on_focus();
1727             }
1728         },
1729
1730         /* on_focus
1731         *  This method is called when the user click outside the snippet in the dom, after a focus
1732         */
1733         on_blur : function () {
1734             for (var i in this.styles){
1735                 this.styles[i].on_blur();
1736             }
1737             this.$overlay.removeClass('oe_active');
1738         },
1739     });
1740
1741 })();