Merge branch 'master' of git@stigma.nowoczesnapolska.org.pl:platforma
[redakcja.git] / project / static / js / editor.js
1 function Panel(panelWrap) {
2         var self = this;
3         self.wrap = panelWrap;
4         self.contentDiv = $('.panel-content', panelWrap);
5         self.instanceId = Math.ceil(Math.random() * 1000000000);
6         $.log('new panel - wrap: ', self.wrap);
7         
8         $(document).bind('panel:unload.' + self.instanceId, 
9                         function(event, data) { self.unload(event, data); });   
10
11         $(document).bind('panel:contentChanged', function(event, data) {
12                 $.log(self, ' got changed event from: ', data);
13                 if(self != data) 
14                         self.otherPanelChanged(event.target);
15                 else 
16                         self.markChanged();
17
18                 return false;           
19         });
20 }
21
22 Panel.prototype.callHook = function() {
23     args = $.makeArray(arguments)
24     var hookName = args.splice(0,1)[0]
25     var noHookAction = args.splice(0,1)[0]
26
27         $.log('calling hook: ', hookName, 'with args: ', args);
28         if(this.hooks && this.hooks[hookName])
29         {               
30                 return this.hooks[hookName].apply(this, args);
31         }
32     else if (noHookAction instanceof Function)
33         return noHookAction(args);
34     else return false;
35 }
36
37 Panel.prototype.load = function (url) {
38     $.log('preparing xhr load: ', this.wrap);
39     $(document).trigger('panel:unload', this);
40         var self = this;
41         self.current_url = url;
42
43     $.ajax({
44         url: url,
45         dataType: 'html',
46                 success: function(data, tstat) {
47                         panel_hooks = null;
48                         $(self.contentDiv).html(data);
49                         self.hooks = panel_hooks;                       
50                         panel_hooks = null;
51                         self.callHook('load');
52                 },
53         error: function(request, textStatus, errorThrown) {
54             $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
55         }
56     });
57 }
58
59 Panel.prototype.unload = function(event, data) {
60         $.log('got unload signal', this, ' target: ', data);
61
62         if( data == this ) {
63                 $.log('unloading', this);
64         $(this.contentDiv).html('');
65                 this.callHook('unload');
66                 this.hooks = null; // flush the hooks
67                 return false;
68     };
69 }
70
71 Panel.prototype.refresh = function(event, data) {
72     reload = function() {
73         $.log('hard reload for panel ', this.current_url);
74         this.load(this.current_url);
75         return true;
76     }
77
78     if( this.callHook('refresh', reload) )
79         $('.change-notification', this.wrap).fadeOut();
80
81
82 Panel.prototype.otherPanelChanged = function(other) {
83         $.log('panel ', other, ' changed.');
84         if(!this.callHook('dirty'))
85         $('.change-notification', this.wrap).fadeIn();
86 }       
87
88 Panel.prototype.markChanged = function () {
89         this.wrap.addClass('changed');
90 }
91
92 Panel.prototype.changed = function () {
93         return this.wrap.hasClass('changed');
94 }
95
96 Panel.prototype.unmarkChanged = function () {
97         this.wrap.removeClass('changed');
98 }
99
100 Panel.prototype.saveInfo = function() {
101         var saveInfo = {};
102         this.callHook('saveInfo', null, saveInfo);
103         return saveInfo;
104 }
105
106
107 function Editor() {
108         this.rootDiv = $('#panels');
109 }
110
111 Editor.prototype.setupUI = function() {
112         // set up the UI visually and attach callbacks
113         var self = this;
114    
115         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
116     self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
117     
118         $('#panels > *.panel-wrap').each(function() {
119                 var panelWrap = $(this);
120                 $.log('wrap: ', panelWrap);
121                 panel = new Panel(panelWrap);
122                 panelWrap.data('ctrl', panel); // attach controllers to wraps
123         panel.load($('.panel-toolbar select', panelWrap).val());
124         
125         $('.panel-toolbar select', panelWrap).change(function() {
126             var url = $(this).val();
127             panelWrap.data('ctrl').load(url);
128             self.savePanelOptions();
129         });
130     });
131
132         $(document).bind('panel:contentChanged', function(event, data) {
133         $('#toolbar-button-save').removeAttr('disabled');
134         });
135     
136     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
137     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
138 }
139
140 Editor.prototype.loadConfig = function() {
141     // Load options from cookie
142     var defaultOptions = {
143         panels: [
144             {name: 'htmleditor', ratio: 0.5},
145             {name: 'gallery', ratio: 0.5}
146         ]
147     }
148     
149     try {
150         var cookie = $.cookie('options');
151         this.options = $.secureEvalJSON(cookie);
152         if (!this.options) {
153             this.options = defaultOptions;
154         }
155     } catch (e) {    
156         this.options = defaultOptions;
157     }
158     $.log(this.options);
159     
160     this.loadPanelOptions();
161 }
162
163 Editor.prototype.loadPanelOptions = function() {
164     var self = this;
165     var totalWidth = 0;
166     
167     $('.panel-wrap', self.rootDiv).each(function(index) {
168         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
169         if ($(this).hasClass('last-panel')) {
170             $(this).css({
171                 left: totalWidth,
172                 right: 0,
173             });
174         } else {
175             $(this).css({
176                 left: totalWidth,
177                 width: panelWidth,
178             });
179             totalWidth += panelWidth;               
180         }
181         $.log('panel:', this, $(this).css('left'));
182         $('.panel-toolbar select', this).val(
183             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
184         )
185     });   
186 }
187
188 Editor.prototype.savePanelOptions = function() {
189     var self = this;
190     var panels = [];
191     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
192         panels.push({
193             name: $('.panel-toolbar option:selected', this).attr('name'),
194             ratio: $(this).width() / self.rootDiv.width()
195         })
196     });
197     self.options.panels = panels;
198     $.log($.toJSON(self.options));
199     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
200 }
201
202 Editor.prototype.saveToBranch = function() {
203         var changed_panel = $('.panel-wrap.changed');
204         var self = this;
205         $.log('Saving to local branch - panel:', changed_panel);
206
207         if( changed_panel.length == 0) {
208                 $.log('Nothing to save.');
209                 return; /* no changes */
210         }
211
212         if( changed_panel.length > 1) {
213                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
214                 return;
215         }
216
217         saveInfo = changed_panel.data('ctrl').saveInfo();
218
219         $.ajax({
220                 url: saveInfo.url,
221                 dataType: 'json',
222                 success: function(data, textStatus) {
223                         if (data.result != 'ok')
224                                 $.log('save errors: ', data.errors)
225                         else 
226                                 self.refreshPanels(changed_panel);
227             $('#toolbar-button-save').attr('disabled', 'disabled');
228                 },
229                 error: function(rq, tstat, err) {
230                         $.log('save error', rq, tstat, err);
231                 },
232                 type: 'POST',
233                 data: saveInfo.postData
234         });
235 };
236
237 Editor.prototype.refreshPanels = function(goodPanel) {
238         var self = this;
239         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
240
241         panels.each(function() {
242                 var panel = $(this).data('ctrl');
243                 $.log(this, panel);
244                 if ( panel.changed() )
245                         panel.unmarkChanged();
246                 else 
247                         panel.refresh();
248         });
249 };              
250
251 $(function() {
252         editor = new Editor();
253
254         // do the layout
255         editor.loadConfig();
256         editor.setupUI();
257 });