Visual: allow paragraph split inside annotations.
[redakcja.git] / src / redakcja / static / js / wiki / view_editor_wysiwyg.js
1 (function($) {
2
3     /* Show theme to the user */
4     function selectTheme(themeId){
5         var selection = window.getSelection();
6         selection.removeAllRanges();
7
8         var range = document.createRange();
9         var s = $("[x-node='motyw'][theme-class='" + themeId + "']")[0];
10         var e = $("[x-node='end'][theme-class='" + themeId + "']")[0];
11
12         if (s && e) {
13             range.setStartAfter(s);
14             range.setEndBefore(e);
15             selection.addRange(range);
16         }
17     };
18
19     /* Verify insertion port for annotation or theme */
20     function verifyTagInsertPoint(node){
21         if (node.nodeType == 3) { // Text Node
22             node = node.parentNode;
23         }
24
25         if (node.nodeType != 1) {
26             return false;
27         }
28
29         node = $(node);
30         var xtype = node.attr('x-node');
31
32         if (!xtype || (xtype.search(':') >= 0) ||
33         xtype == 'motyw' ||
34         xtype == 'begin' ||
35         xtype == 'end') {
36             return false;
37         }
38
39         // don't allow themes inside annotations
40         if (node.closest('[x-node="pe"]').length > 0)
41             return false;
42
43         return true;
44     }
45
46     /* Convert HTML fragment to plaintext */
47     var ANNOT_FORBIDDEN = ['pt', 'pa', 'pr', 'pe', 'begin', 'end', 'motyw'];
48
49     function html2plainText(fragment){
50         var text = "";
51
52         $(fragment.childNodes).each(function(){
53             if (this.nodeType == 3) // textNode
54                 text += this.nodeValue;
55             else {
56                 if (this.nodeType == 1 &&
57                         $.inArray($(this).attr('x-node'), ANNOT_FORBIDDEN) == -1) {
58                     text += html2plainText(this);
59                 }
60             };
61         });
62
63         return text;
64     }
65
66
67     /* Insert annotation using current selection */
68     function addAnnotation(){
69         var selection = window.getSelection();
70         var n = selection.rangeCount;
71
72         if (n == 0) {
73             window.alert("Nie zaznaczono żadnego obszaru");
74             return false;
75         }
76
77         // for now allow only 1 range
78         if (n > 1) {
79             window.alert("Zaznacz jeden obszar");
80             return false;
81         }
82
83         // remember the selected range
84         var range = selection.getRangeAt(0);
85
86         if (!verifyTagInsertPoint(range.endContainer)) {
87             window.alert("Nie można wstawić w to miejsce przypisu.");
88             return false;
89         }
90
91         // BUG #273 - selected text can contain themes, which should be omitted from
92         // defining term
93         var text = html2plainText(range.cloneContents());
94         var tag = $('<span></span>');
95         range.collapse(false);
96         range.insertNode(tag[0]);
97
98         xml2html({
99             xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',
100             success: function(text){
101                 var t = $(text);
102                 tag.replaceWith(t);
103                 openForEdit(t);
104             },
105             error: function(){
106                 tag.remove();
107                 alert('Błąd przy dodawaniu przypisu:' + errors);
108             }
109         })
110     }
111
112
113     function addReference(){
114         var selection = window.getSelection();
115         var n = selection.rangeCount;
116
117         if (n == 0) {
118             window.alert("Nie zaznaczono żadnego obszaru");
119             return false;
120         }
121
122         // for now allow only 1 range
123         if (n > 1) {
124             window.alert("Zaznacz jeden obszar");
125             return false;
126         }
127
128         // remember the selected range
129         var range = selection.getRangeAt(0);
130
131         if (!verifyTagInsertPoint(range.endContainer)) {
132             window.alert("Nie można wstawić w to miejsce przypisu.");
133             return false;
134         }
135
136         var tag = $('<span></span>');
137         range.collapse(false);
138         range.insertNode(tag[0]);
139
140         xml2html({
141             xml: '<ref href=""/>',
142             success: function(text){
143                 var t = $(text);
144                 tag.replaceWith(t);
145                 openForEdit(t);
146             },
147             error: function(){
148                 tag.remove();
149                 alert('Błąd przy dodawaniu referncji:' + errors);
150             }
151         })
152     }
153
154
155
156
157     /* Insert theme using current selection */
158
159     function addTheme(){
160         var selection = window.getSelection();
161         var n = selection.rangeCount;
162
163         if (n == 0) {
164             window.alert("Nie zaznaczono żadnego obszaru");
165             return false;
166         }
167
168         // for now allow only 1 range
169         if (n > 1) {
170             window.alert("Zaznacz jeden obszar.");
171             return false;
172         }
173
174
175         // remember the selected range
176         var range = selection.getRangeAt(0);
177
178
179         if ($(range.startContainer).is('.html-editarea') ||
180         $(range.endContainer).is('.html-editarea')) {
181             window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie.");
182             return false;
183         }
184
185         // verify if the start/end points make even sense -
186         // they must be inside a x-node (otherwise they will be discarded)
187         // and the x-node must be a main text
188         if (!verifyTagInsertPoint(range.startContainer)) {
189             window.alert("Motyw nie może się zaczynać w tym miejscu.");
190             return false;
191         }
192
193         if (!verifyTagInsertPoint(range.endContainer)) {
194             window.alert("Motyw nie może się kończyć w tym miejscu.");
195             return false;
196         }
197
198         var date = (new Date()).getTime();
199         var random = Math.floor(4000000000 * Math.random());
200         var id = ('' + date) + '-' + ('' + random);
201
202         var createPoint = function(container, offset) {
203             var offsetBetweenCommas = function(text, offset) {
204                 if(text.length < 2 || offset < 1 || offset > text.length)
205                     return false;
206                 return text[offset-1] === ',' && text[offset] === ',';
207             }
208             var point = document.createRange();
209             offset = offsetBetweenCommas(container.textContent, offset) ? offset - 1 : offset;
210             point.setStart(container, offset);
211             return point;
212         }
213
214         var spoint = createPoint(range.startContainer, range.startOffset);
215         var epoint = createPoint(range.endContainer, range.endOffset);
216
217         var mtag, btag, etag, errors;
218
219         // insert theme-ref
220
221         xml2html({
222             xml: '<end id="e' + id + '" />',
223             success: function(text){
224                 etag = $('<span></span>');
225                 epoint.insertNode(etag[0]);
226                 etag.replaceWith(text);
227                 xml2html({
228                     xml: '<motyw id="m' + id + '"></motyw>',
229                     success: function(text){
230                         mtag = $('<span></span>');
231                         spoint.insertNode(mtag[0]);
232                         mtag.replaceWith(text);
233                         xml2html({
234                             xml: '<begin id="b' + id + '" />',
235                             success: function(text){
236                                 btag = $('<span></span>');
237                                 spoint.insertNode(btag[0])
238                                 btag.replaceWith(text);
239                                 selection.removeAllRanges();
240                                 openForEdit($('[x-node="motyw"][theme-class="' + id + '"]'));
241                             }
242                         });
243                     }
244                 });
245             }
246         });
247     }
248
249     function addSymbol(caret) {
250         let editArea;
251
252         if (caret) {
253             editArea = $("textarea", caret.element)[0];
254         } else {
255             editArea = $('div.html-editarea textarea')[0];
256         }
257
258         if(editArea) {
259             var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
260
261             var specialChars = [' ', 'Ą','ą','Ć','ć','Ę','ę','Ł','ł','Ń','ń','Ó','ó','Ś','ś','Ż','ż','Ź','ź','Á','á','À','à',
262             'Â','â','Ä','ä','Å','å','Ā','ā','Ă','ă','Ã','ã',
263             'Æ','æ','Ç','ç','Č','č','Ċ','ċ','Ď','ď','É','é','È','è',
264             'Ê','ê','Ë','ë','Ē','ē','Ě','ě','Ġ','ġ','Ħ','ħ','Í','í','Î','î',
265             'Ī','ī','Ĭ','ĭ','Ľ','ľ','Ñ','ñ','Ň','ň','Ó','ó','Ö','ö',
266             'Ô','ô','Ō','ō','Ǒ','ǒ','Œ','œ','Ø','ø','Ř','ř','Š',
267             'š','Ş','ş','Ť','ť','Ţ','ţ','Ű','ű','Ú','ú','Ù','ù',
268             'Ü','ü','Ů','ů','Ū','ū','Û','û','Ŭ','ŭ',
269             'Ý','ý','Ž','ž','ß','Ð','ð','Þ','þ','А','а','Б',
270             'б','В','в','Г','г','Д','д','Е','е','Ё','ё','Ж',
271             'ж','З','з','И','и','Й','й','К','к','Л','л','М',
272             'м','Н','н','О','о','П','п','Р','р','С','с',
273             'Т','т','У','у','Ф','ф','Х','х','Ц','ц','Ч',
274             'ч','Ш','ш','Щ','щ','Ъ','ъ','Ы','ы','Ь','ь','Э',
275             'э','Ю','ю','Я','я','ѓ','є','і','ї','ј','љ','њ',
276             'Ґ','ґ','Α','α','Β','β','Γ','γ','Δ','δ','Ε','ε',
277             'Ζ','ζ','Η','η','Θ','θ','Ι','ι','Κ','κ','Λ','λ','Μ',
278             'μ','Ν','ν','Ξ','ξ','Ο','ο','Π','π','Ρ','ρ','Σ','ς','σ',
279             'Τ','τ','Υ','υ','Φ','φ','Χ','χ','Ψ','ψ','Ω','ω','–',
280             '—','¡','¿','$','¢','£','€','©','®','°','¹','²','³',
281             '¼','½','¾','†','§','‰','•','←','↑','→','↓',
282             '„','”','„”','«','»','«»','»«','’','[',']','~','|','−','·',
283             '×','÷','≈','≠','±','≤','≥','∈'];
284             var tableContent = "<tr>";
285
286             for(var i in specialChars) {
287                 if(i % 14 == 0 && i > 0) {
288                     tableContent += "</tr><tr>";
289                 }
290                 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";
291             }
292
293             tableContent += "</tr>";
294             $("body").append(specialCharsContainer);
295
296
297              // localStorage for recently used characters - reading
298              if (typeof(localStorage) != 'undefined') {
299                  if (localStorage.getItem("recentSymbols")) {
300                      var recent = localStorage.getItem("recentSymbols");
301                      var recentArray = recent.split(";");
302                      var recentRow = "";
303                      for(var i in recentArray.reverse()) {
304                         recentRow += "<td><input type='button' class='specialBtn recentSymbol' value='"+recentArray[i]+"'/></td>";
305                      }
306                      recentRow = "<tr>" + recentRow + "</tr>";
307                  }
308              }
309             $("#tableSpecialChars").append(recentRow);
310             $("#tableSpecialChars").append(tableContent);
311
312             /* events */
313
314             $('.specialBtn').click(function(){
315                 var insertVal = $(this).val();
316
317                 // if we want to surround text with quotes
318                 // not sure if just check if value has length == 2
319
320                 if (caret) {
321                     caret.insertChar(insertVal);
322                     caret.focus();
323                 } else {
324                     if (insertVal.length == 2) {
325                         var startTag = insertVal[0];
326                         var endTag = insertVal[1];
327                         var textAreaOpened = editArea;
328                         //IE support
329                         if (document.selection) {
330                             textAreaOpened.focus();
331                             sel = document.selection.createRange();
332                             sel.text = startTag + sel.text + endTag;
333                         }
334                         //MOZILLA/NETSCAPE support
335                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
336                             var startPos = textAreaOpened.selectionStart;
337                             var endPos = textAreaOpened.selectionEnd;
338                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
339                                 + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
340                         }
341                     } else {
342                         insertAtCaret(editArea, insertVal);
343                     }
344                 }
345
346                 // localStorage for recently used characters - saving
347                 if (typeof(localStorage) != 'undefined') {
348                     if (localStorage.getItem("recentSymbols")) {
349                         var recent = localStorage.getItem("recentSymbols");
350                         var recentArray = recent.split(";");
351                         var valIndex = $.inArray(insertVal, recentArray);
352                         //alert(valIndex);
353                         if(valIndex == -1) {
354                             // value not present in array yet
355                             if(recentArray.length > 13){
356                                 recentArray.shift();
357                                 recentArray.push(insertVal);
358                             } else {
359                                 recentArray.push(insertVal);
360                             }
361                         } else  {
362                             // value already in the array
363                             for(var i = valIndex; i < recentArray.length; i++){
364                                 recentArray[i] = recentArray[i+1];
365                             }
366                             recentArray[recentArray.length-1] = insertVal;
367                         }
368                         localStorage.setItem("recentSymbols", recentArray.join(";"));
369                     } else {
370                         localStorage.setItem("recentSymbols", insertVal);
371                     }
372                 }
373                 $(specialCharsContainer).remove();
374             });
375             $('#specialCharsClose').click(function(){
376                 $(specialCharsContainer).remove();
377             });
378
379         } else {
380             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
381         }
382     }
383
384     function insertAtCaret(txtarea,text) {
385         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
386         var scrollPos = txtarea.scrollTop;
387         var strPos = 0;
388         var backStart = 0;
389         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
390         if (br == "ie") {
391             txtarea.focus();
392             var range = document.selection.createRange();
393             range.moveStart ('character', -txtarea.value.length);
394             strPos = backStart = range.text.length;
395         } else if (br == "ff") {
396             strPos = txtarea.selectionStart;
397             backStart = txtarea.selectionEnd;
398         }
399         var front = (txtarea.value).substring(0,strPos);
400         var back = (txtarea.value).substring(backStart,txtarea.value.length);
401         txtarea.value=front+text+back;
402         strPos = strPos + text.length;
403         if (br == "ie") {
404             txtarea.focus();
405             var range = document.selection.createRange();
406             range.moveStart ('character', -txtarea.value.length);
407             range.moveStart ('character', strPos);
408             range.moveEnd ('character', 0);
409             range.select();
410         } else if (br == "ff") {
411             txtarea.selectionStart = strPos;
412             txtarea.selectionEnd = strPos;
413             txtarea.focus();
414         }
415         txtarea.scrollTop = scrollPos;
416     }
417
418     /* open edition window for selected fragment */
419     function openForEdit($origin){
420         var $box = null
421
422         // annotations overlay their sub box - not their own box //
423         if ($origin.is(".annotation-inline-box")) {
424             $box = $("*[x-annotation-box]", $origin);
425         }
426         else {
427             $box = $origin;
428         }
429         var x = $box[0].offsetLeft;
430         var y = $box[0].offsetTop;
431
432         var w = $box.outerWidth();
433         var h = $box.innerHeight();
434
435         if ($origin.is(".annotation-inline-box")) {
436             w = Math.max(w, 400);
437             h = Math.max(h, 60);
438             if($('.htmlview div').offset().left + $('.htmlview div').width() > ($('.vsplitbar').offset().left - 480)){
439                 x = -(Math.max($origin.offset().left, $origin.width()));
440             } else {
441                 x = 100;
442             }
443         }
444         if ($origin.is('.reference-inline-box')) {
445             w = 400;
446             h = 32;
447             y -= 32;
448             x = Math.min(
449                 x,
450                 $('.htmlview div').offset().left + $('.htmlview div').width() - 400
451             );
452         }
453
454         // start edition on this node
455         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><button class="tytul-button akap-edit-button">tytuł dzieła</button><button class="wyroznienie-button akap-edit-button">wyróżnienie</button><button class="slowo-button akap-edit-button">słowo obce</button><button class="znak-button akap-edit-button">znak spec.</button><textarea></textarea></div>').css({
456             position: 'absolute',
457             height: h,
458             left: x,
459             top: y,
460             width: w
461         }).appendTo($box[0].offsetParent || $box.parent()).show();
462
463
464         if ($origin.is('*[x-edit-no-format]')) {
465             $('.akap-edit-button').remove();
466         }
467
468         if ($origin.is('[x-node="motyw"]')) {
469             $.themes.autocomplete($('textarea', $overlay));
470         }
471
472         if ($origin.is('[x-node="motyw"]')){
473             $('.delete-button', $overlay).click(function(){
474                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw?")) {
475                     $('[theme-class="' + $origin.attr('theme-class') + '"]').remove();
476                     $overlay.remove();
477                     $(document).unbind('click.blur-overlay');
478                     return false;
479                 };
480             });
481         }
482         else if($box.is('*[x-annotation-box]') || $origin.is('*[x-edit-attribute]') || $origin.is('*[x-node="uwaga"]')) {
483             let q;
484             switch ($origin.attr('x-node')) {
485             case 'uwaga':
486                 q = 'tę uwagę';
487                 break;
488             case 'ref':
489                 q = 'tę referencję';
490                 break
491             default:
492                 q = 'ten przypis';
493             }
494             $('.delete-button', $overlay).click(function(){
495                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć " + q + "?")) {
496                     $origin.remove();
497                     $overlay.remove();
498                     $(document).unbind('click.blur-overlay');
499                     return false;
500                 };
501             });
502         }
503         else {
504             $('.delete-button', $overlay).html("Anuluj");
505             $('.delete-button', $overlay).click(function(){
506                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
507                     $overlay.remove();
508                     $(document).unbind('click.blur-overlay');
509                     return false;
510                 };
511             });
512         }
513
514
515         var serializer = new XMLSerializer();
516
517         if($box.attr("x-edit-attribute")) {
518             source = $('<span x-pass-thru="true"/>');
519             source.text($box.attr("x-a-wl-" + $box.attr("x-edit-attribute")));
520             source = source[0];
521         } else {
522             source = $box[0];
523         }
524
525         html2text({
526             element: source,
527             stripOuter: true,
528             success: function(text){
529                 $('textarea', $overlay).val($.trim(text));
530
531                 setTimeout(function(){
532                     $('textarea', $overlay).elastic().focus();
533                 }, 50);
534
535                 function save(argument){
536                     var nodeName = $box.attr('x-node') || 'pe';
537                     var insertedText = $('textarea', $overlay).val();
538
539                     if ($origin.is('[x-node="motyw"]')) {
540                         insertedText = insertedText.replace(/,\s*$/, '');
541                     }
542
543                     if($box.attr("x-edit-attribute")) {
544                         xml = '<' + nodeName + ' ' + $box.attr("x-edit-attribute") + '="' + insertedText + '"/>';
545                     } else {
546                         xml = '<' + nodeName + '>' + insertedText + '</' + nodeName + '>';
547                     }
548
549
550                     xml2html({
551                         xml: xml,
552                         success: function(element){
553                             if (nodeName == 'out-of-flow-text') {
554                                 $(element).children().insertAfter($origin);
555                                 $origin.remove()
556                             }
557                             else if ($box.attr('x-edit-attribute')) {
558                                 $(element).insertAfter($origin);
559                                 $origin.remove();
560                             }
561                             else {
562                                 $origin.html($(element).html());
563                             }
564                             $overlay.remove();
565                         },
566                         error: function(text){
567                             alert('Błąd! ' + text);
568                         }
569                     })
570
571                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
572                     $("#base").prepend(msg);
573                     $('#base .saveNotify').fadeOut(3000, function(){
574                         $(this).remove();
575                     });
576                 }
577
578                 $('.akap-edit-button', $overlay).click(function(){
579                         var textAreaOpened = $('textarea', $overlay)[0];
580                         var startTag = "";
581                         var endTag = "";
582                         var buttonName = this.innerHTML;
583
584                         if(buttonName == "słowo obce") {
585                                 startTag = "<slowo_obce>";
586                                 endTag = "</slowo_obce>";
587                         } else if (buttonName == "wyróżnienie") {
588                                 startTag = "<wyroznienie>";
589                                 endTag = "</wyroznienie>";
590                         } else if (buttonName == "tytuł dzieła") {
591                                 startTag = "<tytul_dziela>";
592                                 endTag = "</tytul_dziela>";
593                         } else if(buttonName == "znak spec."){
594                             addSymbol();
595                             return false;
596                         }
597
598                         var myField = textAreaOpened;
599
600                         //IE support
601                         if (document.selection) {
602                             textAreaOpened.focus();
603                             sel = document.selection.createRange();
604                             sel.text = startTag + sel.text + endTag;
605                         }
606                         //MOZILLA/NETSCAPE support
607                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
608                             var startPos = textAreaOpened.selectionStart;
609                             var endPos = textAreaOpened.selectionEnd;
610                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
611                                   + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
612                         }
613                 });
614
615                 $('.accept-button', $overlay).click(function(){
616                     save();
617                     $(document).unbind('click.blur-overlay');
618                 });
619
620                 $(document).bind('click.blur-overlay', function(event){
621                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
622                         return;
623                     }
624                     save();
625                     $(document).unbind('click.blur-overlay');
626                 });
627
628             },
629             error: function(text){
630                 alert('Błąd! ' + text);
631             }
632         });
633     }
634
635     function createUwagaBefore(before) {
636         xml2html({
637             xml: '<uwaga/>',
638             success: function(element){
639                 let $element = $(element);
640                 $element.insertBefore(before);
641                 openForEdit($element);
642             }
643         });
644     }
645
646     function VisualPerspective(options){
647         perspective = this;
648
649         var old_callback = options.callback;
650
651         options.callback = function(){
652             var element = $("#html-view");
653             var button = $('<button class="edit-button active-block-button">Edytuj</button>');
654             var uwagaButton = $('<button class="uwaga-button active-block-button">Uwaga</button>');
655
656             if (!CurrentDocument.readonly) {
657
658                 $('#html-view').bind('mousemove', function(event){
659                     var editable = $(event.target).closest('*[x-editable]');
660                     $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove();
661
662                     if (!editable.hasClass('active')) {
663                         editable.addClass('active').append(button);
664                         if (!editable.is('[x-edit-attribute]') &&
665                             !editable.is('.annotation-inline-box') &&
666                             !editable.is('[x-edit-no-format]')
667                            ) {
668                             editable.append(uwagaButton);
669                         }
670                     }
671                     if (editable.is('.annotation-inline-box')) {
672                         $('*[x-annotation-box]', editable).css({
673                         }).show();
674                     }
675                 });
676
677                 perspective.caret = new Caret(element);
678                 
679                 $('#insert-reference-button').click(function(){
680                     addReference();
681                     return false;
682                 });
683
684                 $('#insert-annotation-button').click(function(){
685                     addAnnotation();
686                     return false;
687                 });
688
689                 $('#insert-theme-button').click(function(){
690                     addTheme();
691                     return false;
692                 });
693
694
695                 $(".insert-inline-tag").click(function() {
696                     perspective.insertInlineTag($(this).attr('data-tag'));
697                     return false;
698                 });
699
700                 $(".insert-char").click(function() {
701                     console.log('perspective', perspective);
702                     addSymbol(caret=perspective.caret);
703                     return false;
704                 });
705
706                 $(document).on('click', '.edit-button', function(event){
707                     event.preventDefault();
708                     openForEdit($(this).parent());
709                 });
710
711                 $(document).on('click', '.uwaga-button', function(event){
712                     event.preventDefault();
713                     createUwagaBefore($(this).parent());
714                 });
715             }
716
717             $(document).on('click', '[x-node="motyw"]', function(){
718                 selectTheme($(this).attr('theme-class'));
719             });
720
721             element.on('click', '.annotation', function(event) {
722                 event.preventDefault();
723                 $('[x-annotation-box]', $(this).parent()).toggleClass('editing');
724                 
725             });
726
727             old_callback.call(this);
728         };
729
730         $.wiki.Perspective.call(this, options);
731     };
732
733     VisualPerspective.prototype = new $.wiki.Perspective();
734
735     VisualPerspective.prototype.onEnter = function(success, failure){
736         $.wiki.Perspective.prototype.onEnter.call(this);
737
738         $.blockUI({
739             message: 'Uaktualnianie widoku...'
740         });
741
742         function _finalize(callback){
743             $.unblockUI();
744             if (callback)
745                 callback();
746         }
747
748         perspective = this;
749         xml2html({
750             xml: this.doc.text,
751             base: this.doc.getBase(),
752             success: function(element){
753
754                 var htmlView = $('#html-view');
755                 htmlView.html(element);
756
757                 _finalize(success);
758             },
759             error: function(text, source){
760                 err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
761                 if (source)
762                     err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
763                 $('#html-view').html(err);
764                 _finalize(failure);
765             }
766         });
767     };
768
769     VisualPerspective.prototype.onExit = function(success, failure){
770         var self = this;
771
772         self.caret.detach();
773
774         $.wiki.exitTab('#PropertiesPerspective');
775         
776         $.blockUI({
777             message: 'Zapisywanie widoku...'
778         });
779
780         function _finalize(callback){
781             $.unblockUI();
782             if (callback)
783                 callback();
784         }
785
786         if ($('#html-view .error').length > 0)
787             return _finalize(failure);
788
789         html2text({
790             element: $('#html-view').get(0),
791             stripOuter: true,
792             success: function(text){
793                 self.doc.setText(text);
794                 _finalize(success);
795             },
796             error: function(text){
797                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
798                 _finalize(failure);
799             }
800         });
801     };
802
803     VisualPerspective.prototype.insertInlineTag = function(tag) {
804         this.caret.detach();
805
806         let selection = window.getSelection();
807         var n = selection.rangeCount;
808         if (n != 1 || selection.isCollapsed) {
809             window.alert("Nie zaznaczono obszaru");
810             return false
811         }
812         let range = selection.getRangeAt(0);
813
814         // Make sure that:
815         // Both ends are in the same x-node container.
816         // TODO: That the container is a inline-text container.
817         let node = range.startContainer;
818         if (node.nodeType == node.TEXT_NODE) {
819             node = node.parentNode;
820         }
821         let endNode = range.endContainer;
822         if (endNode.nodeType == endNode.TEXT_NODE) {
823             endNode = endNode.parentNode;
824         }
825         if (node != endNode) {
826             window.alert("Zły obszar.");
827             return false;
828         }
829
830         // We will construct a HTML element with the range selected.
831         let div = $("<span x-pass-thru='true'>");
832
833         contents = $(node).contents();
834         let startChildIndex = node == range.startContainer ? 0 : contents.index(range.startContainer);
835         let endChildIndex = contents.index(range.endContainer);
836
837         current = range.startContainer;
838         if (current.nodeType == current.TEXT_NODE) {
839             current = current.splitText(range.startOffset);
840         }
841         while (current != range.endContainer) {
842             n = current.nextSibling;
843             $(current).appendTo(div);
844             current = n;
845         }
846         if (current.nodeType == current.TEXT_NODE) {
847             end = current.splitText(range.endOffset);
848         }
849         $(current).appendTo(div);
850         
851         html2text({
852             element: div[0],
853             success: function(d) {
854                 xml2html({
855                     xml: d = '<' + tag + '>' + d + '</' + tag + '>',
856                     success: function(html) {
857                         // What if no end?
858                         node.insertBefore($(html)[0], end);
859                     }
860                 });
861             },
862             error: function(a, b) {
863                 console.log(a, b);
864             }
865         });
866     };
867
868     $.wiki.VisualPerspective = VisualPerspective;
869
870 })(jQuery);