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     var result = false;
27
28         $.log('calling hook: ', hookName, 'with args: ', args);
29         if(this.hooks && this.hooks[hookName])
30                 result = this.hooks[hookName].apply(this, args);
31         else if (noHookAction instanceof Function) 
32         result = noHookAction(args);
33     return result;
34 }
35
36 Panel.prototype.load = function (url) {
37     $.log('preparing xhr load: ', this.wrap);
38     $(document).trigger('panel:unload', this);
39         var self = this;
40         self.current_url = url;
41
42     $.ajax({
43         url: url,
44         dataType: 'html',
45                 success: function(data, tstat) {
46                         panel_hooks = null;
47                         $(self.contentDiv).html(data);
48                         self.hooks = panel_hooks;                       
49                         panel_hooks = null;
50                         self.callHook('load');
51                 },
52         error: function(request, textStatus, errorThrown) {
53             $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
54             $(self.contentDiv).html("<p>Wystapił błąd podczas wczytywania panelu.");
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     var self = this;
73     reload = function() {
74         $.log('hard reload for panel ', self.current_url);
75         self.load(self.current_url);
76         return true;
77     }
78
79     if( this.callHook('refresh', reload) )
80         $('.change-notification', this.wrap).fadeOut();
81
82
83 Panel.prototype.otherPanelChanged = function(other) {
84         $.log('panel ', other, ' changed.');
85         if(!this.callHook('dirty'))
86         $('.change-notification', this.wrap).fadeIn();
87 }       
88
89 Panel.prototype.markChanged = function () {
90         this.wrap.addClass('changed');
91 }
92
93 Panel.prototype.changed = function () {
94         return this.wrap.hasClass('changed');
95 }
96
97 Panel.prototype.unmarkChanged = function () {
98         this.wrap.removeClass('changed');
99 }
100
101 Panel.prototype.saveInfo = function() {
102         var saveInfo = {};
103         this.callHook('saveInfo', null, saveInfo);
104         return saveInfo;
105 }
106
107
108 function Editor() {
109         this.rootDiv = $('#panels');
110     this.popupQueue = [];
111     this.autosaveTimer = null;
112 }
113
114 Editor.prototype.setupUI = function() {
115         // set up the UI visually and attach callbacks
116         var self = this;
117    
118         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
119     // self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
120     
121         $('#panels > *.panel-wrap').each(function() {
122                 var panelWrap = $(this);
123                 $.log('wrap: ', panelWrap);
124                 panel = new Panel(panelWrap);
125                 panelWrap.data('ctrl', panel); // attach controllers to wraps
126         panel.load($('.panel-toolbar select', panelWrap).val());
127         
128         $('.panel-toolbar select', panelWrap).change(function() {
129             var url = $(this).val();
130             panelWrap.data('ctrl').load(url);
131             self.savePanelOptions();
132         });
133     });
134
135         $(document).bind('panel:contentChanged', function() { self.onContentChanged.apply(self, arguments) });
136     
137     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
138     $('#toolbar-button-commit').click( function (event, data) { self.sendPullRequest(); } );
139     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
140 }
141
142 Editor.prototype.loadConfig = function() {
143     // Load options from cookie
144     var defaultOptions = {
145         panels: [
146             {name: 'htmleditor', ratio: 0.5},
147             {name: 'gallery', ratio: 0.5}
148         ]
149     }
150     
151     try {
152         var cookie = $.cookie('options');
153         this.options = $.secureEvalJSON(cookie);
154         if (!this.options) {
155             this.options = defaultOptions;
156         }
157     } catch (e) {    
158         this.options = defaultOptions;
159     }
160     $.log(this.options);
161     
162     this.loadPanelOptions();
163 }
164
165 Editor.prototype.loadPanelOptions = function() {
166     var self = this;
167     var totalWidth = 0;
168     
169     $('.panel-wrap', self.rootDiv).each(function(index) {
170         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
171         if ($(this).hasClass('last-panel')) {
172             $(this).css({
173                 left: totalWidth,
174                 right: 0,
175             });
176         } else {
177             $(this).css({
178                 left: totalWidth,
179                 width: panelWidth,
180             });
181             totalWidth += panelWidth;               
182         }
183         $.log('panel:', this, $(this).css('left'));
184         $('.panel-toolbar select', this).val(
185             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
186         )
187     });   
188 }
189
190 Editor.prototype.savePanelOptions = function() {
191     var self = this;
192     var panels = [];
193     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
194         panels.push({
195             name: $('.panel-toolbar option:selected', this).attr('name'),
196             ratio: $(this).width() / self.rootDiv.width()
197         })
198     });
199     self.options.panels = panels;
200     $.log($.toJSON(self.options));
201     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
202 }
203
204 Editor.prototype.saveToBranch = function(msg) 
205 {
206         var changed_panel = $('.panel-wrap.changed');
207         var self = this;
208         $.log('Saving to local branch - panel:', changed_panel);
209
210     if(!msg) msg = "Zapis z edytora platformy.";
211
212         if( changed_panel.length == 0) {
213                 $.log('Nothing to save.');
214                 return true; /* no changes */
215         }
216
217         if( changed_panel.length > 1) {
218                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
219                 return false;
220         }
221
222         saveInfo = changed_panel.data('ctrl').saveInfo();
223     $.extend(saveInfo.postData, {'commit_message': msg});
224
225         $.ajax({
226                 url: saveInfo.url,
227                 dataType: 'json',
228                 success: function(data, textStatus) {
229                         if (data.result != 'ok')
230                                 $.log('save errors: ', data.errors)
231                         else {
232                                 self.refreshPanels(changed_panel);
233                 $('#toolbar-button-save').attr('disabled', 'disabled');
234                 $('#toolbar-button-commit').removeAttr('disabled');
235                 if(self.autosaveTimer)
236                     clearTimeout(self.autosaveTimer);
237
238                 self.showPopup('save-successful');
239             }
240                 },
241                 error: function(rq, tstat, err) {
242             self.showPopup('save-error');
243                 },
244                 type: 'POST',
245                 data: saveInfo.postData
246         });
247
248     return true;
249 };
250
251 Editor.prototype.autoSave = function() 
252 {
253     this.autosaveTimer = null;
254     // first check if there is anything to save
255     $.log('Autosave');
256     this.saveToBranch("Automatyczny zapis z edytora platformy.");
257 }
258
259 Editor.prototype.onContentChanged = function(event, data) {
260         var self = this;
261
262         $('#toolbar-button-save').removeAttr('disabled');
263         $('#toolbar-button-commit').attr('disabled', 'disabled');
264     
265         if(this.autosaveTimer) return;    
266         this.autosaveTimer = setTimeout( function() { self.autoSave(); }, 300000 );
267 };
268
269 Editor.prototype.refreshPanels = function(goodPanel) {
270         var self = this;
271         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
272
273         panels.each(function() {
274                 var panel = $(this).data('ctrl');
275                 $.log('Refreshing: ', this, panel);
276                 if ( panel.changed() )
277                         panel.unmarkChanged();
278                 else 
279                         panel.refresh();
280         });
281 };              
282
283
284 Editor.prototype.sendPullRequest = function () {
285     if( $('.panel-wrap.changed').length != 0)        
286         alert("There are unsaved changes - can't make a pull request.");
287
288     this.showPopup('not-implemented');
289 /*
290         $.ajax({
291                 url: '/pull-request',
292                 dataType: 'json',
293                 success: function(data, textStatus) {
294             $.log('data: ' + data);
295                 },
296                 error: function(rq, tstat, err) {
297                         $.log('commit error', rq, tstat, err);
298                 },
299                 type: 'POST',
300                 data: {}
301         }); */
302 }
303
304 Editor.prototype.showPopup = function(name) 
305 {
306     var self = this;
307     self.popupQueue.push(name)
308
309     if( self.popupQueue.length > 1) 
310         return;
311
312     $('#message-box > #' + name).fadeIn();
313  
314    self._nextPopup = function() {
315         var elem = self.popupQueue.pop()
316         if(elem) {
317             elem = $('#message-box > #' + elem);
318             elem.fadeOut(300, function() {
319                 if( self.popupQueue.length > 0) 
320                     $('#message-box > #' + self.popupQueue[0]).fadeIn();
321                     setTimeout(self._nextPopup, 1700);
322             });
323
324         }
325     }
326
327     setTimeout(self._nextPopup, 2000);
328 }
329
330
331 $(function() {
332         editor = new Editor();
333
334         // do the layout
335         editor.loadConfig();
336         editor.setupUI();
337 });