Poprawiony ostatni panel ("prawy").
[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         if(!this.wrap.hasClass('changed') ) // TODO: is this needed ?
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 }
111
112 Editor.prototype.setupUI = function() {
113         // set up the UI visually and attach callbacks
114         var self = this;
115    
116         self.rootDiv.makeHorizPanel({}); // TODO: this probably doesn't belong into jQuery
117     self.rootDiv.css('top', ($('#header').outerHeight() ) + 'px');
118     
119         $('#panels > *.panel-wrap').each(function() {
120                 var panelWrap = $(this);
121                 $.log('wrap: ', panelWrap);
122                 panel = new Panel(panelWrap);
123                 panelWrap.data('ctrl', panel); // attach controllers to wraps
124         panel.load($('.panel-toolbar select', panelWrap).val());
125         
126         $('.panel-toolbar select', panelWrap).change(function() {
127             var url = $(this).val();
128             panelWrap.data('ctrl').load(url);
129             self.savePanelOptions();
130         });
131     });
132
133         $(document).bind('panel:contentChanged', function(event, data) {
134         $('#toolbar-button-save').removeAttr('disabled');
135         });
136     
137     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
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() {
204         var changed_panel = $('.panel-wrap.changed');
205         var self = this;
206         $.log('Saving to local branch - panel:', changed_panel);
207
208         if( changed_panel.length == 0) {
209                 $.log('Nothing to save.');
210                 return; /* no changes */
211         }
212
213         if( changed_panel.length > 1) {
214                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
215                 return;
216         }
217
218         saveInfo = changed_panel.data('ctrl').saveInfo();
219
220         $.ajax({
221                 url: saveInfo.url,
222                 dataType: 'json',
223                 success: function(data, textStatus) {
224                         if (data.result != 'ok')
225                                 $.log('save errors: ', data.errors)
226                         else 
227                                 self.refreshPanels(changed_panel);
228             $('#toolbar-button-save').attr('disabled', 'disabled');
229                 },
230                 error: function(rq, tstat, err) {
231                         $.log('save error', rq, tstat, err);
232                 },
233                 type: 'POST',
234                 data: saveInfo.postData
235         });
236 };
237
238 Editor.prototype.refreshPanels = function(goodPanel) {
239         var self = this;
240         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
241
242         panels.each(function() {
243                 var panel = $(this).data('ctrl');
244                 $.log(this, panel);
245                 if ( panel.changed() )
246                         panel.unmarkChanged();
247                 else 
248                         panel.refresh();
249         });
250 };              
251
252 $(function() {
253         editor = new Editor();
254
255         // do the layout
256         editor.loadConfig();
257         editor.setupUI();
258 });