Poprawienie odwołania do formularza zmiany galerii w /panels/gallery.html.
[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         }
55     });
56 }
57
58 Panel.prototype.unload = function(event, data) {
59         $.log('got unload signal', this, ' target: ', data);
60
61         if( data == this ) {
62                 $.log('unloading', this);
63         $(this.contentDiv).html('');
64                 this.callHook('unload');
65                 this.hooks = null; // flush the hooks
66                 return false;
67     };
68 }
69
70 Panel.prototype.refresh = function(event, data) {
71     var self = this;
72     reload = function() {
73         $.log('hard reload for panel ', self.current_url);
74         self.load(self.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     this.popupQueue = [];
110     this.autosaveTimer = null;
111 }
112
113 Editor.prototype.setupUI = function() {
114         // set up the UI visually and attach callbacks
115         var self = this;
116    
117         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
118     // self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
119     
120         $('#panels > *.panel-wrap').each(function() {
121                 var panelWrap = $(this);
122                 $.log('wrap: ', panelWrap);
123                 panel = new Panel(panelWrap);
124                 panelWrap.data('ctrl', panel); // attach controllers to wraps
125         panel.load($('.panel-toolbar select', panelWrap).val());
126         
127         $('.panel-toolbar select', panelWrap).change(function() {
128             var url = $(this).val();
129             panelWrap.data('ctrl').load(url);
130             self.savePanelOptions();
131         });
132     });
133
134         $(document).bind('panel:contentChanged', function() { self.onContentChanged.apply(self, arguments) });
135     
136     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
137     $('#toolbar-button-commit').click( function (event, data) { self.sendPullRequest(); } );
138     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
139 }
140
141 Editor.prototype.loadConfig = function() {
142     // Load options from cookie
143     var defaultOptions = {
144         panels: [
145             {name: 'htmleditor', ratio: 0.5},
146             {name: 'gallery', ratio: 0.5}
147         ]
148     }
149     
150     try {
151         var cookie = $.cookie('options');
152         this.options = $.secureEvalJSON(cookie);
153         if (!this.options) {
154             this.options = defaultOptions;
155         }
156     } catch (e) {    
157         this.options = defaultOptions;
158     }
159     $.log(this.options);
160     
161     this.loadPanelOptions();
162 }
163
164 Editor.prototype.loadPanelOptions = function() {
165     var self = this;
166     var totalWidth = 0;
167     
168     $('.panel-wrap', self.rootDiv).each(function(index) {
169         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
170         if ($(this).hasClass('last-panel')) {
171             $(this).css({
172                 left: totalWidth,
173                 right: 0,
174             });
175         } else {
176             $(this).css({
177                 left: totalWidth,
178                 width: panelWidth,
179             });
180             totalWidth += panelWidth;               
181         }
182         $.log('panel:', this, $(this).css('left'));
183         $('.panel-toolbar select', this).val(
184             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
185         )
186     });   
187 }
188
189 Editor.prototype.savePanelOptions = function() {
190     var self = this;
191     var panels = [];
192     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
193         panels.push({
194             name: $('.panel-toolbar option:selected', this).attr('name'),
195             ratio: $(this).width() / self.rootDiv.width()
196         })
197     });
198     self.options.panels = panels;
199     $.log($.toJSON(self.options));
200     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
201 }
202
203 Editor.prototype.saveToBranch = function(msg) 
204 {
205         var changed_panel = $('.panel-wrap.changed');
206         var self = this;
207         $.log('Saving to local branch - panel:', changed_panel);
208
209     if(!msg) msg = "Zapis z edytora platformy.";
210
211         if( changed_panel.length == 0) {
212                 $.log('Nothing to save.');
213                 return true; /* no changes */
214         }
215
216         if( changed_panel.length > 1) {
217                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
218                 return false;
219         }
220
221         saveInfo = changed_panel.data('ctrl').saveInfo();
222     $.extend(saveInfo.postData, {'commit_message': msg});
223
224         $.ajax({
225                 url: saveInfo.url,
226                 dataType: 'json',
227                 success: function(data, textStatus) {
228                         if (data.result != 'ok')
229                                 $.log('save errors: ', data.errors)
230                         else {
231                                 self.refreshPanels(changed_panel);
232                 $('#toolbar-button-save').attr('disabled', 'disabled');
233                 $('#toolbar-button-commit').removeAttr('disabled');
234                 if(self.autosaveTimer)
235                     clearTimeout(self.autosaveTimer);
236
237                 self.showPopup('save-successful');
238             }
239                 },
240                 error: function(rq, tstat, err) {
241             self.showPopup('save-error');
242                 },
243                 type: 'POST',
244                 data: saveInfo.postData
245         });
246
247     return true;
248 };
249
250 Editor.prototype.autoSave = function() 
251 {
252     this.autosaveTimer = null;
253     // first check if there is anything to save
254     $.log('Autosave');
255     this.saveToBranch("Automatyczny zapis z edytora platformy.");
256 }
257
258 Editor.prototype.onContentChanged = function(event, data) {
259         var self = this;
260
261         $('#toolbar-button-save').removeAttr('disabled');
262         $('#toolbar-button-commit').attr('disabled', 'disabled');
263     
264         if(this.autosaveTimer) return;    
265         this.autosaveTimer = setTimeout( function() { self.autoSave(); }, 300000 );
266 };
267
268 Editor.prototype.refreshPanels = function(goodPanel) {
269         var self = this;
270         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
271
272         panels.each(function() {
273                 var panel = $(this).data('ctrl');
274                 $.log('Refreshing: ', this, panel);
275                 if ( panel.changed() )
276                         panel.unmarkChanged();
277                 else 
278                         panel.refresh();
279         });
280 };              
281
282
283 Editor.prototype.sendPullRequest = function () {
284     if( $('.panel-wrap.changed').length != 0)        
285         alert("There are unsaved changes - can't make a pull request.");
286
287     this.showPopup('not-implemented');
288 /*
289         $.ajax({
290                 url: '/pull-request',
291                 dataType: 'json',
292                 success: function(data, textStatus) {
293             $.log('data: ' + data);
294                 },
295                 error: function(rq, tstat, err) {
296                         $.log('commit error', rq, tstat, err);
297                 },
298                 type: 'POST',
299                 data: {}
300         }); */
301 }
302
303 Editor.prototype.showPopup = function(name) 
304 {
305     var self = this;
306     self.popupQueue.push(name)
307
308     if( self.popupQueue.length > 1) 
309         return;
310
311     $('#message-box > #' + name).fadeIn();
312  
313    self._nextPopup = function() {
314         var elem = self.popupQueue.pop()
315         if(elem) {
316             elem = $('#message-box > #' + elem);
317             elem.fadeOut(300, function() {
318                 if( self.popupQueue.length > 0) 
319                     $('#message-box > #' + self.popupQueue[0]).fadeIn();
320                     setTimeout(self._nextPopup, 1700);
321             });
322
323         }
324     }
325
326     setTimeout(self._nextPopup, 2000);
327 }
328
329
330 $(function() {
331         editor = new Editor();
332
333         // do the layout
334         editor.loadConfig();
335         editor.setupUI();
336 });