62ee8ff6a60c93db5c493009d56c3c7080aa0765
[redakcja.git] / platforma / static / js / main.js
1 if (!console) {
2     console = {
3         log: function() {}
4     }
5 }
6
7 // Teraz nieużywane
8 function highlight(colour) {
9     var range, sel;
10     if (window.getSelection) {
11         // Non-IE case
12         sel = window.getSelection();
13         if (sel.getRangeAt) {
14             range = sel.getRangeAt(0);
15         }
16         document.designMode = "on";
17         if (range) {
18             sel.removeAllRanges();
19             sel.addRange(range);
20         }
21         // Use HiliteColor since some browsers apply BackColor to the whole block
22         if ( !document.execCommand("HiliteColor", false, colour) ) {
23             document.execCommand("BackColor", false, colour);
24         }
25         document.designMode = "off";
26     } else if (document.selection && document.selection.createRange) {
27         // IE case
28         range = document.selection.createRange();
29         range.execCommand("BackColor", false, colour);
30     }
31 }
32
33 // function unselectThemes(themeId) {
34 //     $('.Apple-style-span').each(function() {
35 //         $(this).after($(this).html());
36 //         $(this).remove();
37 //     });
38 // }
39
40 function gallery(element, url) {    
41     var element = $(element);
42     var imageDimensions = {};
43     element.data('images', []);
44     
45     function changePage(pageNumber) {        
46         $('img', element).attr('src', element.data('images')[pageNumber - 1]);
47     }
48     
49     function normalizeNumber(pageNumber) {
50         // Numer strony musi być pomiędzy 1 a najwyższym numerem
51         var pageCount = element.data('images').length;
52         pageNumber = parseInt(pageNumber, 10);
53         
54         if (!pageNumber || pageNumber == NaN || pageNumber == Infinity || pageNumber == -Infinity) {
55             return 1;
56         } else if (pageNumber < 1) {
57             return 1;
58         } else if (pageNumber > pageCount) {
59             return pageCount;
60         } else {
61             return pageNumber;
62         }
63     }
64     
65     var pn = $('.page-number', element);
66     pn.change(function(event) {
67         console.log('change!', $(this).val());
68         event.preventDefault();
69         var n = normalizeNumber(pn.val());
70         pn.val(n);
71         changePage(n);
72     });
73     $('.previous-page', element).click(function() {
74         pn.val(normalizeNumber(pn.val()) - 1);
75         pn.change();
76     });
77     $('.next-page', element).click(function() {
78         pn.val(normalizeNumber(pn.val()) + 1);
79         pn.change();
80     });
81     
82     
83     var image = $('img', element).attr('unselectable', 'on');
84     var origin = {};
85     var imageOrigin = {};
86     var zoomFactor = 1;
87     
88     $('.zoom-in', element).click(function() {
89         zoomFactor = Math.min(2, zoomFactor + 0.2);
90         zoom();
91     });
92     $('.zoom-out', element).click(function() {
93         zoomFactor = Math.max(0.2, zoomFactor - 0.2);
94         zoom();
95     });
96     $('.change-gallery', element).click(function() {
97         $('.chosen-gallery').val($('#document-meta .gallery').html() || STATIC_URL + 'gallery/');
98         $('.gallery-image').animate({top: 53}, 200);
99         $('.chosen-gallery').focus();
100     });
101     $('.change-gallery-ok', element).click(function() {
102         if ($('#document-meta .gallery').length == 0) {
103             $('<div class="gallery"></div>').appendTo('#document-meta');
104         }
105         $('#document-meta .gallery').html($('.chosen-gallery').val());
106         updateGallery($('.chosen-gallery').val());
107         $('.gallery-image').animate({top: 27}, 200);
108     });
109     $('.change-gallery-cancel', element).click(function() {
110         $('.gallery-image').animate({top: 27}, 200);
111     });
112     
113     $('img', element).load(function() {
114         image.css({width: null, height: null});
115         imageDimensions = {
116             width: $(this).width() * zoomFactor,
117             height: $(this).height() * zoomFactor,
118             originWidth: $(this).width(),
119             originHeight: $(this).height(),
120             galleryWidth: $(this).parent().width(),
121             galleryHeight: $(this).parent().height()
122         };
123         console.log('load', imageDimensions)
124         var position = normalizePosition(
125             image.position().left,
126             image.position().top, 
127             imageDimensions.galleryWidth,
128             imageDimensions.galleryHeight,
129             imageDimensions.width,
130             imageDimensions.height
131         );
132         image.css({left: position.x, top: position.y, width: $(this).width() * zoomFactor, height: $(this).height() * zoomFactor});
133     });
134
135     $(window).resize(function() {
136         imageDimensions.galleryWidth = image.parent().width();
137         imageDimensions.galleryHeight = image.parent().height();
138     });
139     
140     function bounds(galleryWidth, galleryHeight, imageWidth, imageHeight) {
141         return {
142             maxX: 0,
143             maxY: 0,
144             minX: galleryWidth - imageWidth,
145             minY: galleryHeight - imageHeight
146         }
147     }
148     
149     function normalizePosition(x, y, galleryWidth, galleryHeight, imageWidth, imageHeight) {
150         var b = bounds(galleryWidth, galleryHeight, imageWidth, imageHeight);
151         return {
152             x: Math.min(b.maxX, Math.max(b.minX, x)),
153             y: Math.min(b.maxY, Math.max(b.minY, y))
154         }
155     }
156     
157     function onMouseMove(event) {
158         var position = normalizePosition(
159             event.clientX - origin.x + imageOrigin.left,
160             event.clientY - origin.y + imageOrigin.top, 
161             imageDimensions.galleryWidth,
162             imageDimensions.galleryHeight,
163             imageDimensions.width,
164             imageDimensions.height
165         );
166         image.css({position: 'absolute', top: position.y, left: position.x});
167         return false;
168     }
169     
170     function setZoom(factor) {
171         zoomFactor = factor;
172     }
173     
174     function zoom() {
175         imageDimensions.width = imageDimensions.originWidth * zoomFactor;
176         imageDimensions.height = imageDimensions.originHeight * zoomFactor;
177         var position = normalizePosition(
178             image.position().left,
179             image.position().top, 
180             imageDimensions.galleryWidth,
181             imageDimensions.galleryHeight,
182             imageDimensions.width,
183             imageDimensions.height
184         );
185         console.log(image.position(), imageDimensions, position);
186         image.css({width: imageDimensions.width, height: imageDimensions.height,
187             left: position.x, top: position.y});
188
189     }
190     
191     function onMouseUp(event) {
192         $(document)
193             .unbind('mousemove.gallery')
194             .unbind('mouseup.gallery');
195         return false;
196     }
197     
198     image.bind('mousedown', function(event) {
199         origin = {
200             x: event.clientX,
201             y: event.clientY
202         };
203         imageOrigin = image.position();
204         $(document)
205             .bind('mousemove.gallery', onMouseMove)
206             .bind('mouseup.gallery', onMouseUp);
207         return false;
208     });
209     
210     function updateGallery(url) {
211         $.ajax({
212             url: url,
213             type: 'GET',
214             dataType: 'json',
215
216             success: function(data) {
217                 element.data('images', data);
218                 pn.val(1);
219                 pn.change();
220                 $('img', element).show();
221             },
222             
223             error: function(data) {
224                 element.data('images', []);
225                 pn.val(1);
226                 pn.change();
227                 $('img', element).hide();
228             }
229         });
230     }
231     
232     if (url) {
233         updateGallery(url);
234     }
235 }
236
237
238 function transform(editor) {
239     $.blockUI({message: 'Ładowanie...'});
240     setTimeout(function() {
241         xml2html({
242             xml: editor.getCode(),
243             success: function(element) {
244                 $('#html-view').html(element);
245                 $.unblockUI();
246             }, error: function(text) {
247                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' + text + '</pre>');
248                 $.unblockUI();
249             }
250         });
251     }, 200);
252 };
253
254
255 function reverseTransform(editor) {
256     var serializer = new XMLSerializer();
257     if ($('#html-view .error').length > 0) {
258         return;
259     }
260     $.blockUI({message: 'Ładowanie...'});
261     setTimeout(function() {
262         html2xml({
263             xml: serializer.serializeToString($('#html-view div').get(0)),
264             success: function(text) {
265                 editor.setCode(text);
266                 $.unblockUI();
267             }, error: function(text) {
268                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
269                 $.unblockUI();
270             }
271         });
272     }, 200);
273 }
274
275
276 function html(element) {
277     var element = $(element);
278     
279     function selectTheme(themeId)
280     {
281         var selection = window.getSelection();
282
283         // remove current selection
284         selection.removeAllRanges();
285
286         var range = document.createRange();
287         var s = $(".motyw[theme-class='"+themeId+"']")[0];
288         var e = $(".end[theme-class='"+themeId+"']")[0];
289
290         if(s && e) {
291             range.setStartAfter(s);
292             range.setEndBefore(e);
293             selection.addRange(range);
294         }
295     };
296     
297     // function openForEdit($origin)
298     // {       
299     //     // if(this.currentOpen && this.currentOpen != $origin) {
300     //     //     this.closeWithSave(this.currentOpen);
301     //     // }
302     //     
303     //     var $box = null
304     // 
305     //     // annotations overlay their sub box - not their own box //
306     //     if($origin.is(".annotation-inline-box"))
307     //         $box = $("*[x-annotation-box]", $origin);
308     //     else
309     //         $box = $origin;
310     //     
311     //     var x = $box[0].offsetLeft;
312     //     var y = $box[0].offsetTop;
313     //     var w = $box.outerWidth();
314     //     var h = $box.innerHeight();
315     // 
316     //     console.log("Edit origin:", $origin, " box:", $box);
317     //     console.log("offsetParent:", $box[0].offsetParent);
318     //     console.log("Dimensions: ", x, y, w , h);
319     // 
320     //     // start edition on this node
321     //     var $overlay = $('<div class="html-editarea"><textarea></textarea></div>');
322     // 
323     //     h = Math.max(h - 20, 2*parseInt($box.css('line-height')));
324     //     
325     //     console.log(h);
326     //     
327     //     $overlay.css({
328     //         position: 'absolute',
329     //         height: h,
330     //         left: x,
331     //         top: y,
332     //         right: 0
333     //     });
334     //     
335     //     $($box[0].offsetParent).append($overlay);
336     //     console.log($overlay);
337     // }
338     // 
339     // $('.edit-button').live('click', function() {
340     //     openForEdit($(this).parent());
341     // });
342     // 
343     var button = $('<button class="edit-button">Edytuj</button>');
344     $(element).bind('mousemove', function(event) {
345         var editable = $(event.target).closest('*[x-editable]');
346         $('.active[x-editable]', element).not(editable).removeClass('active').children('.edit-button').remove();
347         if (!editable.hasClass('active')) {
348             editable.addClass('active').append(button);
349         }
350     });
351
352     $('.motyw').live('click', function() {
353         selectTheme($(this).attr('theme-class'));
354     });
355 }
356
357
358 $(function() {
359     gallery('#sidebar', $('#document-meta .gallery').html());
360     html('#html-view');
361     
362     CodeMirror.fromTextArea('id_text', {
363         parserfile: 'parsexml.js',
364         path: STATIC_URL + "js/lib/codemirror/",
365         stylesheet: STATIC_URL + "css/xmlcolors.css",
366         parserConfig: {
367             useHTMLKludges: false
368         },
369         iframeClass: 'xml-iframe',
370         textWrapping: true,
371         tabMode: 'spaces',
372         indentUnit: 0,
373         initCallback: function(editor) {
374             $('#save-button').click(function(event) {
375                 event.preventDefault();
376                 $.blockUI({message: $('#save-dialog')});
377             });
378             
379             $('#save-ok').click(function() {
380                 $.blockUI({message: 'Zapisywanie...'});
381                 
382                 var metaComment = '<!--';
383                 $('#document-meta div').each(function() {
384                     metaComment += '\n\t' + $(this).attr('class') + ': ' + $(this).html();
385                 });
386                 metaComment += '\n-->'
387                 
388                 var data = {
389                     name: $('#document-name').html(),
390                     text: metaComment + editor.getCode(),
391                     revision: $('#document-revision').html(),
392                     author: 'annonymous',
393                     comment: $('#komentarz').val()
394                 };
395                 
396                 console.log(data);
397                 
398                 $.ajax({
399                     url: document.location.href,
400                     type: "POST",
401                     dataType: "json",
402                     data: data,                
403                     success: function(data) {
404                         if (data.text) {
405                             editor.setCode(data.text);
406                             $('#document-revision').html(data.revision);
407                         } else {
408                             console.log(data.errors);
409                             alert(data.errors);
410                         }
411                         $.unblockUI();
412                     },
413                     error: function(xhr, textStatus, errorThrown) {
414                         alert('error: ' + textStatus + ' ' + errorThrown);
415                     },
416                 })
417             });
418             
419             $('#save-cancel').click(function() {
420                 $.unblockUI();
421             });
422
423             $('#simple-view-tab').click(function() {
424                 if ($(this).hasClass('active')) {
425                     return;
426                 }
427                 $(this).addClass('active');
428                 $('#source-view-tab').removeClass('active');
429                 $('#source-editor').hide();
430                 $('#simple-editor').show();
431                 transform(editor);
432             });
433
434             $('#source-view-tab').click(function() {
435                 if ($(this).hasClass('active')) {
436                     return;
437                 }
438                 $(this).addClass('active');
439                 $('#simple-view-tab').removeClass('active');
440                 $('#simple-editor').hide();
441                 $('#source-editor').show();
442                 reverseTransform(editor);
443             });
444
445             $('#source-editor .toolbar button').click(function(event) {
446                 event.preventDefault();
447                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
448                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
449             });
450
451             $('.toolbar select').change(function() {
452                 var slug = $(this).val();
453
454                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
455                 $(window).resize();
456             });
457
458             $('.toolbar-buttons-container').hide();
459             $('.toolbar select').change();
460
461             $('#simple-view-tab').click();
462         }
463     });
464     
465     $(window).resize(function() {
466         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
467     });
468     
469     $(window).resize();
470     
471     $('.vsplitbar').click(function() {
472         if ($('#sidebar').width() == 0) {
473             $('#sidebar').width(480).css({right: 0}).show();
474             $('#source-editor, #simple-editor').css({right: 495});
475             $('.vsplitbar').css({right: 480}).addClass('active');
476         } else {
477             $('#sidebar').width(0).hide();
478             $('#source-editor, #simple-editor').css({right: 15});
479             $('.vsplitbar').css({right: 0}).removeClass('active');
480         }
481         $(window).resize();
482     });
483                 
484
485 });