Merge branch 'master' of git@stigma: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         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      $('*.panel-wrap:last', this.rootDiv).addClass('last-panel');       
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(event, data) {
136         $('#toolbar-button-save').removeAttr('disabled');
137         });
138     
139     $('#toolbar-button-save').click( function (event, data) { self.saveToBranch(); } );
140     self.rootDiv.bind('stopResize', function() { self.savePanelOptions() });
141 }
142
143 Editor.prototype.loadConfig = function() {
144     // Load options from cookie
145     var defaultOptions = {
146         panels: [
147             {name: 'htmleditor', ratio: 0.5},
148             {name: 'gallery', ratio: 0.5}
149         ]
150     }
151     
152     try {
153         var cookie = $.cookie('options');
154         this.options = $.secureEvalJSON(cookie);
155         if (!this.options) {
156             this.options = defaultOptions;
157         }
158     } catch (e) {    
159         this.options = defaultOptions;
160     }
161     $.log(this.options);
162     
163     this.loadPanelOptions();
164 }
165
166 Editor.prototype.loadPanelOptions = function() {
167     var self = this;
168     var totalWidth = 0;
169     
170     $('.panel-wrap', self.rootDiv).each(function(index) {
171         var panelWidth = self.options.panels[index].ratio * self.rootDiv.width();
172         if ($(this).hasClass('last-panel')) {
173             $(this).css({
174                 left: totalWidth,
175                 right: 0,
176             });
177         } else {
178             $(this).css({
179                 left: totalWidth,
180                 width: panelWidth,
181             });
182             totalWidth += panelWidth;               
183         }
184         $.log('panel:', this, $(this).css('left'));
185         $('.panel-toolbar select', this).val(
186             $('.panel-toolbar option[name=' + self.options.panels[index].name + ']', this).attr('value')
187         )
188     });   
189 }
190
191 Editor.prototype.savePanelOptions = function() {
192     var self = this;
193     var panels = [];
194     $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
195         panels.push({
196             name: $('.panel-toolbar option:selected', this).attr('name'),
197             ratio: $(this).width() / self.rootDiv.width()
198         })
199     });
200     self.options.panels = panels;
201     $.log($.toJSON(self.options));
202     $.cookie('options', $.toJSON(self.options), { expires: 7, path: '/'});
203 }
204
205 Editor.prototype.saveToBranch = function() {
206         var changed_panel = $('.panel-wrap.changed');
207         var self = this;
208         $.log('Saving to local branch - panel:', changed_panel);
209
210         if( changed_panel.length == 0) {
211                 $.log('Nothing to save.');
212                 return; /* no changes */
213         }
214
215         if( changed_panel.length > 1) {
216                 alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
217                 return;
218         }
219
220         saveInfo = changed_panel.data('ctrl').saveInfo();
221
222         $.ajax({
223                 url: saveInfo.url,
224                 dataType: 'json',
225                 success: function(data, textStatus) {
226                         if (data.result != 'ok')
227                                 $.log('save errors: ', data.errors)
228                         else 
229                                 self.refreshPanels(changed_panel);
230             $('#toolbar-button-save').attr('disabled', 'disabled');
231                 },
232                 error: function(rq, tstat, err) {
233                         $.log('save error', rq, tstat, err);
234                 },
235                 type: 'POST',
236                 data: saveInfo.postData
237         });
238 };
239
240 Editor.prototype.refreshPanels = function(goodPanel) {
241         var self = this;
242         var panels = $('#' + self.rootDiv.attr('id') +' > *.panel-wrap', self.rootDiv.parent());
243
244         panels.each(function() {
245                 var panel = $(this).data('ctrl');
246                 $.log(this, panel);
247                 if ( panel.changed() )
248                         panel.unmarkChanged();
249                 else 
250                         panel.refresh();
251         });
252 };              
253
254 $(function() {
255         editor = new Editor();
256
257         // do the layout
258         editor.loadConfig();
259         editor.setupUI();
260 });