Pokazywanie przypisów w odpowiednim miejscu i ustalenie dla nich minimalnych rozmiarów.
[redakcja.git] / platforma / static / js / main.js
1 if (!window.console) {
2     window.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         event.preventDefault();
68         var n = normalizeNumber(pn.val());
69         pn.val(n);
70         changePage(n);
71     });
72     $('.previous-page', element).click(function() {
73         pn.val(normalizeNumber(pn.val()) - 1);
74         pn.change();
75     });
76     $('.next-page', element).click(function() {
77         pn.val(normalizeNumber(pn.val()) + 1);
78         pn.change();
79     });
80     
81     
82     var image = $('img', element).attr('unselectable', 'on');
83     var origin = {};
84     var imageOrigin = {};
85     var zoomFactor = 1;
86     
87     $('.zoom-in', element).click(function() {
88         zoomFactor = Math.min(2, zoomFactor + 0.2);
89         zoom();
90     });
91     $('.zoom-out', element).click(function() {
92         zoomFactor = Math.max(0.2, zoomFactor - 0.2);
93         zoom();
94     });
95     $('.change-gallery', element).click(function() {
96         $('.chosen-gallery').val($('#document-meta .gallery').html() || '/platforma/gallery/');
97         $('.gallery-image').animate({top: 53}, 200);
98         $('.chosen-gallery').focus();
99     });
100     $('.change-gallery-ok', element).click(function() {
101         if ($('#document-meta .gallery').length == 0) {
102             $('<div class="gallery"></div>').appendTo('#document-meta');
103         }
104         $('#document-meta .gallery').html($('.chosen-gallery').val());
105         updateGallery($('.chosen-gallery').val());
106         $('.gallery-image').animate({top: 27}, 200);
107     });
108     $('.change-gallery-cancel', element).click(function() {
109         $('.gallery-image').animate({top: 27}, 200);
110     });
111     
112     $('img', element).load(function() {
113         image.css({width: null, height: null});
114         imageDimensions = {
115             width: $(this).width() * zoomFactor,
116             height: $(this).height() * zoomFactor,
117             originWidth: $(this).width(),
118             originHeight: $(this).height(),
119             galleryWidth: $(this).parent().width(),
120             galleryHeight: $(this).parent().height()
121         };
122         
123         if (!(imageDimensions.width && imageDimensions.height)) {
124             setTimeout(function() { $('img', element).load(); }, 100);
125         }        
126         var position = normalizePosition(
127             image.position().left,
128             image.position().top, 
129             imageDimensions.galleryWidth,
130             imageDimensions.galleryHeight,
131             imageDimensions.width,
132             imageDimensions.height
133         );
134         image.css({left: position.x, top: position.y, width: $(this).width() * zoomFactor, height: $(this).height() * zoomFactor});
135     });
136
137     $(window).resize(function() {
138         imageDimensions.galleryWidth = image.parent().width();
139         imageDimensions.galleryHeight = image.parent().height();
140     });
141     
142     function bounds(galleryWidth, galleryHeight, imageWidth, imageHeight) {
143         return {
144             maxX: 0,
145             maxY: 0,
146             minX: galleryWidth - imageWidth,
147             minY: galleryHeight - imageHeight
148         }
149     }
150     
151     function normalizePosition(x, y, galleryWidth, galleryHeight, imageWidth, imageHeight) {
152         var b = bounds(galleryWidth, galleryHeight, imageWidth, imageHeight);
153         return {
154             x: Math.min(b.maxX, Math.max(b.minX, x)),
155             y: Math.min(b.maxY, Math.max(b.minY, y))
156         }
157     }
158     
159     function onMouseMove(event) {
160         var position = normalizePosition(
161             event.clientX - origin.x + imageOrigin.left,
162             event.clientY - origin.y + imageOrigin.top, 
163             imageDimensions.galleryWidth,
164             imageDimensions.galleryHeight,
165             imageDimensions.width,
166             imageDimensions.height
167         );
168         image.css({position: 'absolute', top: position.y, left: position.x});
169         return false;
170     }
171     
172     function setZoom(factor) {
173         zoomFactor = factor;
174     }
175     
176     function zoom() {
177         imageDimensions.width = imageDimensions.originWidth * zoomFactor;
178         imageDimensions.height = imageDimensions.originHeight * zoomFactor;
179         var position = normalizePosition(
180             image.position().left,
181             image.position().top, 
182             imageDimensions.galleryWidth,
183             imageDimensions.galleryHeight,
184             imageDimensions.width,
185             imageDimensions.height
186         );
187         image.css({width: imageDimensions.width, height: imageDimensions.height,
188             left: position.x, top: position.y});
189
190     }
191     
192     function onMouseUp(event) {
193         $(document)
194             .unbind('mousemove.gallery')
195             .unbind('mouseup.gallery');
196         return false;
197     }
198     
199     image.bind('mousedown', function(event) {
200         origin = {
201             x: event.clientX,
202             y: event.clientY
203         };
204         imageOrigin = image.position();
205         $(document)
206             .bind('mousemove.gallery', onMouseMove)
207             .bind('mouseup.gallery', onMouseUp);
208         return false;
209     });
210     
211     function updateGallery(url) {
212         $.ajax({
213             url: url,
214             type: 'GET',
215             dataType: 'json',
216
217             success: function(data) {
218                 element.data('images', data);
219                 pn.val(1);
220                 pn.change();
221                 $('img', element).show();
222             },
223             
224             error: function(data) {
225                 element.data('images', []);
226                 pn.val(1);
227                 pn.change();
228                 $('img', element).hide();
229             }
230         });
231     }
232     
233     if (url) {
234         updateGallery(url);
235     }
236 }
237
238
239 function transform(editor) {
240     $.blockUI({message: 'Ładowanie...'});
241     setTimeout(function() {
242         xml2html({
243             xml: editor.getCode(),
244             success: function(element) {
245                 $('#html-view').html(element);
246                 $.unblockUI();
247             }, error: function(text) {
248                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' + text + '</pre>');
249                 $.unblockUI();
250             }
251         });
252     }, 200);
253 };
254
255
256 function reverseTransform(editor, cont) {
257     var serializer = new XMLSerializer();
258     if ($('#html-view .error').length > 0) {
259         return;
260     }
261     $.blockUI({message: 'Ładowanie...'});
262     setTimeout(function() {
263         html2xml({
264             xml: serializer.serializeToString($('#html-view div').get(0)),
265             success: function(text) {
266                 editor.setCode(text);
267                 $.unblockUI();
268                 if (cont) {
269                     cont();
270                 }
271             }, error: function(text) {
272                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
273                 $.unblockUI();
274             }
275         });
276     }, 200);
277 }
278
279
280 // =============
281 // = HTML View =
282 // =============
283 function html(element) {
284     var element = $(element);
285     
286     function selectTheme(themeId)
287     {
288         var selection = window.getSelection();
289         selection.removeAllRanges();
290
291         var range = document.createRange();
292         var s = $(".motyw[theme-class='"+themeId+"']")[0];
293         var e = $(".end[theme-class='"+themeId+"']")[0];
294
295         if(s && e) {
296             range.setStartAfter(s);
297             range.setEndBefore(e);
298             selection.addRange(range);
299         }
300     };
301     
302     function verifyTagInsertPoint(node) {
303         if(node.nodeType == 3) { // Text Node
304             node = node.parentNode;
305         }
306
307         if (node.nodeType != 1) { 
308             return false;
309         }
310
311         console.log('Selection point:', node);
312         
313         node = $(node);
314         var xtype = node.attr('x-node');
315
316         if (!xtype || (xtype.search(':') >= 0) ||
317             xtype == 'motyw' || xtype == 'begin' || xtype == 'end') {
318             return false;
319         }
320         
321         // don't allow themes inside annotations
322         if( node.is('*[x-annotation-box] *') )
323             return false;
324
325         return true;
326     }
327     
328     function addAnnotation()
329     {
330         var selection = window.getSelection();
331         var n = selection.rangeCount;
332
333         console.log("Range count:", n);
334         if (n == 0) {
335             window.alert("Nie zaznaczono żadnego obszaru");
336             return false;
337         }
338
339         // for now allow only 1 range
340         if (n > 1) {
341             window.alert("Zaznacz jeden obszar");
342             return false;
343         }
344
345         // remember the selected range
346         var range = selection.getRangeAt(0);
347
348         if (!verifyTagInsertPoint(range.endContainer)) {
349             window.alert("Nie można wstawić w to miejsce przypisu.");
350             return false;
351         }
352
353         var text = range.toString();
354         var tag = $('<span></span>');
355         range.collapse(false);
356         range.insertNode(tag[0]);
357
358         xml2html({
359             xml: '<pr><slowo_obce>'+text+'</slowo_obce> --- </pr>',
360             success: function(text) {
361                 tag.replaceWith(text);
362             },
363             error: function() {
364                 tag.remove();
365                 alert('Błąd przy dodawaniu przypisu:' + errors);                
366             }
367         })
368     }
369
370     function addTheme()
371     {
372         var selection = window.getSelection();
373         var n = selection.rangeCount;
374
375         console.log("Range count:", n);
376         if(n == 0) {
377             window.alert("Nie zaznaczono żadnego obszaru");
378             return false;
379         }
380
381         // for now allow only 1 range
382         if(n > 1) {
383             window.alert("Zaznacz jeden obszar");
384             return false;
385         }
386
387         // remember the selected range
388         var range = selection.getRangeAt(0);
389         console.log(range.startContainer, range.startOffset, range.endContainer, range.endOffset);
390
391         // verify if the start/end points make even sense -
392         // they must be inside a x-node (otherwise they will be discarded)
393         // and the x-node must be a main text
394         if (!verifyTagInsertPoint(range.startContainer)) {
395             window.alert("Motyw nie może się zaczynać w tym miejscu.");
396             return false;
397         }
398
399         if (!verifyTagInsertPoint(range.endContainer)) {
400             window.alert("Motyw nie może się kończyć w tym miejscu.");
401             return false;
402         }
403
404         var date = (new Date()).getTime();
405         var random = Math.floor(4000000000*Math.random());
406         var id = (''+date) + '-' + (''+random);
407
408         var spoint = document.createRange();
409         var epoint = document.createRange();
410
411         spoint.setStart(range.startContainer, range.startOffset);
412         epoint.setStart(range.endContainer, range.endOffset);
413
414         console.log('spoint', spoint.startContainer, spoint.startOffset, spoint.endContainer, spoint.endOffset);
415         console.log('epoint', epoint.startContainer, epoint.startOffset, epoint.endContainer, epoint.endOffset);
416
417         var mtag, btag, etag, errors;
418
419         // insert theme-ref
420                 
421         xml2html({
422             xml: '<end id="e'+id+'" />',
423             success: function(text) {
424                 etag = $('<span></span>');
425                 epoint.insertNode(etag[0]);
426                 etag.replaceWith(text);
427                 xml2html({
428                     xml: '<motyw id="m'+id+'">motyw</motyw>',
429                     success: function(text) {
430                         mtag = $('<span></span>');
431                         spoint.insertNode(mtag[0]);
432                         mtag.replaceWith(text);
433                         xml2html({
434                             xml: '<begin id="b'+id+'" />',
435                             success: function(text) {
436                                 btag = $('<span></span>');
437                                 spoint.insertNode(btag[0])
438                                 btag.replaceWith(text);
439                                 selection.removeAllRanges();
440                             }
441                         });
442                     }
443                 });
444             }
445         });
446     }
447     
448     function openForEdit($origin)
449     {       
450         var $box = null
451     
452         // annotations overlay their sub box - not their own box //
453         if($origin.is(".annotation-inline-box")) {
454             $box = $("*[x-annotation-box]", $origin);
455             console.log('annotation!', $box);
456         } else {
457             $box = $origin;
458         }
459         
460         var x = $box[0].offsetLeft;
461         var y = $box[0].offsetTop;
462         var w = $box.outerWidth();
463         var h = $box.innerHeight();
464     
465         if ($origin.is(".annotation-inline-box")) {
466             w = Math.max(w, 400);
467             h = Math.max(h, 60);
468         }
469         
470         console.log('width:', w, 'height:', h);
471
472         // start edition on this node
473         var $overlay = $('<div class="html-editarea"><textarea></textarea></div>').css({
474             position: 'absolute',
475             height: h,
476             left: x,
477             top: y,
478             width: w
479             // right: 0
480         }).appendTo($box[0].offsetParent || $box.parent()).show();
481         
482         console.log($overlay, $box[0].offsetParent || $box.parent());
483         
484         var serializer = new XMLSerializer();
485     
486         console.log($box.html());
487         html2xml({
488             xml: serializer.serializeToString($box[0]),
489             inner: true,
490             success: function(text) {
491                 $('textarea', $overlay).val($.trim(text));
492                 console.log($.trim(text));
493                 
494                 setTimeout(function() {
495                     $('textarea', $overlay).focus();
496                 }, 100);
497                 
498                 $('textarea', $overlay).one('blur', function(event) {
499                     var nodeName = $box.attr('x-node') || 'pe';
500                     xml2html({
501                         xml: '<' + nodeName + '>' + $('textarea', $overlay).val() + '</' + nodeName + '>',
502                         success: function(element) {
503                             $box.html($(element).html());
504                             $overlay.remove();
505                         },
506                         error: function(text) {
507                             $overlay.remove();
508                             alert('Błąd! ' + text);
509                         }
510                     })
511                 });
512             }, error: function(text) {
513                 alert('Błąd! ' + text);
514             }
515         });
516     }
517     
518     $('.edit-button').live('click', function(event) {
519         event.preventDefault();
520         openForEdit($(this).parent());
521     });
522     
523     var button = $('<button class="edit-button">Edytuj</button>');
524     $(element).bind('mousemove', function(event) {
525         var editable = $(event.target).closest('*[x-editable]');
526         $('.active[x-editable]', element).not(editable).removeClass('active').children('.edit-button').remove();
527         if (!editable.hasClass('active')) {
528             editable.addClass('active').append(button);
529         }
530     });
531
532     $('.motyw').live('click', function() {
533         selectTheme($(this).attr('theme-class'));
534     });
535     
536     $('#insert-annotation-button').click(function() {
537         addAnnotation();
538         return false;
539     });
540     
541     $('#insert-theme-button').click(function() {
542         addTheme();
543         return false;
544     });
545 }
546
547
548 $(function() {
549     gallery('#sidebar', $('#document-meta .gallery').html());
550     html('#html-view');
551     
552     CodeMirror.fromTextArea('id_text', {
553         parserfile: 'parsexml.js',
554         path: STATIC_URL + "js/lib/codemirror/",
555         stylesheet: STATIC_URL + "css/xmlcolors.css",
556         parserConfig: {
557             useHTMLKludges: false
558         },
559         iframeClass: 'xml-iframe',
560         textWrapping: true,
561         tabMode: 'spaces',
562         indentUnit: 0,
563         initCallback: function(editor) {
564             $('#save-button').click(function(event) {
565                 event.preventDefault();
566                 $.blockUI({message: $('#save-dialog')});
567             });
568             
569             $('#save-ok').click(function() {
570                 $.blockUI({message: 'Zapisywanie...'});
571                 
572                 function doSave (argument) {
573                     var metaComment = '<!--';
574                     $('#document-meta div').each(function() {
575                         metaComment += '\n\t' + $(this).attr('class') + ': ' + $(this).html();
576                     });
577                     metaComment += '\n-->'
578
579                     var data = {
580                         name: $('#document-name').html(),
581                         text: metaComment + editor.getCode(),
582                         revision: $('#document-revision').html(),
583                         author: 'annonymous',
584                         comment: $('#komentarz').val()
585                     };
586
587                     console.log(data);
588
589                     $.ajax({
590                         url: document.location.href,
591                         type: "POST",
592                         dataType: "json",
593                         data: data,                
594                         success: function(data) {
595                             if (data.text) {
596                                 editor.setCode(data.text);
597                                 $('#document-revision').html(data.revision);
598                             } else {
599                                 console.log(data.errors);
600                                 alert(data.errors);
601                             }
602                             $.unblockUI();
603                         },
604                         error: function(xhr, textStatus, errorThrown) {
605                             alert('error: ' + textStatus + ' ' + errorThrown);
606                         },
607                     })
608                 }
609                 
610                 if ('#simple-view-tab.active') {
611                     reverseTransform(editor, doSave);
612                 } else {
613                     doSave();
614                 }
615             });
616             
617             $('#save-cancel').click(function() {
618                 $.unblockUI();
619             });
620
621             $('#simple-view-tab').click(function() {
622                 if ($(this).hasClass('active')) {
623                     return;
624                 }
625                 $(this).addClass('active');
626                 $('#source-view-tab').removeClass('active');
627                 $('#source-editor').hide();
628                 $('#simple-editor').show();
629                 transform(editor);
630             });
631
632             $('#source-view-tab').click(function() {
633                 if ($(this).hasClass('active')) {
634                     return;
635                 }
636                 $(this).addClass('active');
637                 $('#simple-view-tab').removeClass('active');
638                 $('#simple-editor').hide();
639                 $('#source-editor').show();
640                 reverseTransform(editor);
641             });
642
643             $('#source-editor .toolbar button').click(function(event) {
644                 event.preventDefault();
645                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
646                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
647             });
648
649             $('.toolbar select').change(function() {
650                 var slug = $(this).val();
651
652                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
653                 $(window).resize();
654             });
655
656             $('.toolbar-buttons-container').hide();
657             $('.toolbar select').change();
658
659             $('#simple-view-tab').click();
660         }
661     });
662     
663     $(window).resize(function() {
664         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
665     });
666     
667     $(window).resize();
668     
669     $('.vsplitbar').click(function() {
670         if ($('#sidebar').width() == 0) {
671             $('#sidebar').width(480).css({right: 0}).show();
672             $('#source-editor, #simple-editor').css({right: 495});
673             $('.vsplitbar').css({right: 480}).addClass('active');
674         } else {
675             $('#sidebar').width(0).hide();
676             $('#source-editor, #simple-editor').css({right: 15});
677             $('.vsplitbar').css({right: 0}).removeClass('active');
678         }
679         $(window).resize();
680     });
681                 
682
683 });