Tighter editor layout with icons.
[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 = $(".motyw[theme-class='" + themeId + "']")[0];
10         var e = $(".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($('.motyw[theme-class="' + id + '"]'));
241                             }
242                         });
243                     }
244                 });
245             }
246         });
247     }
248
249     function addSymbol() {
250         if($('div.html-editarea textarea')[0]) {
251             var specialCharsContainer = $("<div id='specialCharsContainer'><a href='#' id='specialCharsClose'>Zamknij</a><table id='tableSpecialChars' style='width: 600px;'></table></div>");
252                         
253             var specialChars = [' ', 'Ą','ą','Ć','ć','Ę','ę','Ł','ł','Ń','ń','Ó','ó','Ś','ś','Ż','ż','Ź','ź','Á','á','À','à',
254             'Â','â','Ä','ä','Å','å','Ā','ā','Ă','ă','Ã','ã',
255             'Æ','æ','Ç','ç','Č','č','Ċ','ċ','Ď','ď','É','é','È','è',
256             'Ê','ê','Ë','ë','Ē','ē','Ě','ě','Ġ','ġ','Ħ','ħ','Í','í','Î','î',
257             'Ī','ī','Ĭ','ĭ','Ľ','ľ','Ñ','ñ','Ň','ň','Ó','ó','Ö','ö',
258             'Ô','ô','Ō','ō','Ǒ','ǒ','Œ','œ','Ø','ø','Ř','ř','Š',
259             'š','Ş','ş','Ť','ť','Ţ','ţ','Ű','ű','Ú','ú','Ù','ù',
260             'Ü','ü','Ů','ů','Ū','ū','Û','û','Ŭ','ŭ',
261             'Ý','ý','Ž','ž','ß','Ð','ð','Þ','þ','А','а','Б',
262             'б','В','в','Г','г','Д','д','Е','е','Ё','ё','Ж',
263             'ж','З','з','И','и','Й','й','К','к','Л','л','М',
264             'м','Н','н','О','о','П','п','Р','р','С','с',
265             'Т','т','У','у','Ф','ф','Х','х','Ц','ц','Ч',
266             'ч','Ш','ш','Щ','щ','Ъ','ъ','Ы','ы','Ь','ь','Э',
267             'э','Ю','ю','Я','я','ѓ','є','і','ї','ј','љ','њ',
268             'Ґ','ґ','Α','α','Β','β','Γ','γ','Δ','δ','Ε','ε',
269             'Ζ','ζ','Η','η','Θ','θ','Ι','ι','Κ','κ','Λ','λ','Μ',
270             'μ','Ν','ν','Ξ','ξ','Ο','ο','Π','π','Ρ','ρ','Σ','ς','σ',
271             'Τ','τ','Υ','υ','Φ','φ','Χ','χ','Ψ','ψ','Ω','ω','–',
272             '—','¡','¿','$','¢','£','€','©','®','°','¹','²','³',
273             '¼','½','¾','†','§','‰','•','←','↑','→','↓',
274             '„','”','„”','«','»','«»','»«','’','[',']','~','|','−','·',
275             '×','÷','≈','≠','±','≤','≥','∈'];
276             var tableContent = "<tr>";
277             
278             for(var i in specialChars) {
279                 if(i % 14 == 0 && i > 0) {
280                     tableContent += "</tr><tr>";
281                 }              
282                 tableContent += "<td><input type='button' class='specialBtn' value='"+specialChars[i]+"'/></td>";              
283             }
284             
285             tableContent += "</tr>";                                   
286             $("body").append(specialCharsContainer);
287             
288             
289              // localStorage for recently used characters - reading
290              if (typeof(localStorage) != 'undefined') {
291                  if (localStorage.getItem("recentSymbols")) {
292                      var recent = localStorage.getItem("recentSymbols");
293                      var recentArray = recent.split(";");
294                      var recentRow = "";
295                      for(var i in recentArray.reverse()) {
296                         recentRow += "<td><input type='button' class='specialBtn recentSymbol' value='"+recentArray[i]+"'/></td>";              
297                      }
298                      recentRow = "<tr>" + recentRow + "</tr>";                              
299                  }
300              }            
301             $("#tableSpecialChars").append(recentRow);
302             $("#tableSpecialChars").append(tableContent);
303             
304             /* events */
305             
306             $('.specialBtn').click(function(){
307                 var editArea = $('div.html-editarea textarea')[0];
308                 var insertVal = $(this).val();
309                 
310                 // if we want to surround text with quotes
311                 // not sure if just check if value has length == 2
312                 
313                 if (insertVal.length == 2) {
314                     var startTag = insertVal[0];
315                     var endTag = insertVal[1];
316                                 var textAreaOpened = editArea;                                                  
317                                 //IE support
318                                 if (document.selection) {
319                                     textAreaOpened.focus();
320                                     sel = document.selection.createRange();
321                                     sel.text = startTag + sel.text + endTag;
322                                 }
323                                 //MOZILLA/NETSCAPE support
324                                 else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
325                                     var startPos = textAreaOpened.selectionStart;
326                                     var endPos = textAreaOpened.selectionEnd;
327                                     textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
328                                           + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
329                                 }                
330                 } else {
331                     // if we just want to insert single symbol
332                     insertAtCaret(editArea, insertVal);
333                 }
334                 
335                 // localStorage for recently used characters - saving
336                 if (typeof(localStorage) != 'undefined') {
337                     if (localStorage.getItem("recentSymbols")) {
338                         var recent = localStorage.getItem("recentSymbols");
339                         var recentArray = recent.split(";");
340                         var valIndex = $.inArray(insertVal, recentArray);
341                         //alert(valIndex);
342                         if(valIndex == -1) {
343                             // value not present in array yet
344                             if(recentArray.length > 13){
345                                 recentArray.shift();
346                                 recentArray.push(insertVal);
347                             } else {
348                                 recentArray.push(insertVal);
349                             }
350                         } else  {
351                             // value already in the array
352                             for(var i = valIndex; i < recentArray.length; i++){
353                                 recentArray[i] = recentArray[i+1];
354                             }
355                             recentArray[recentArray.length-1] = insertVal;
356                         }
357                         localStorage.setItem("recentSymbols", recentArray.join(";"));
358                     } else {
359                         localStorage.setItem("recentSymbols", insertVal);
360                     }
361                 }
362                 $(specialCharsContainer).remove();
363             });         
364             $('#specialCharsClose').click(function(){
365                 $(specialCharsContainer).remove();
366             });                   
367             
368         } else {
369             window.alert('Najedź na fragment tekstu, wybierz "Edytuj" i ustaw kursor na miejscu gdzie chcesz wstawić symbol.');
370         }
371     }
372
373     function insertAtCaret(txtarea,text) { 
374         /* http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ */
375         var scrollPos = txtarea.scrollTop; 
376         var strPos = 0; 
377         var backStart = 0;
378         var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
379         if (br == "ie") { 
380             txtarea.focus();
381             var range = document.selection.createRange(); 
382             range.moveStart ('character', -txtarea.value.length); 
383             strPos = backStart = range.text.length; 
384         } else if (br == "ff") {
385             strPos = txtarea.selectionStart; 
386             backStart = txtarea.selectionEnd;
387         }
388         var front = (txtarea.value).substring(0,strPos); 
389         var back = (txtarea.value).substring(backStart,txtarea.value.length); 
390         txtarea.value=front+text+back; 
391         strPos = strPos + text.length; 
392         if (br == "ie") { 
393             txtarea.focus(); 
394             var range = document.selection.createRange(); 
395             range.moveStart ('character', -txtarea.value.length); 
396             range.moveStart ('character', strPos); 
397             range.moveEnd ('character', 0); 
398             range.select(); 
399         } else if (br == "ff") { 
400             txtarea.selectionStart = strPos; 
401             txtarea.selectionEnd = strPos; 
402             txtarea.focus(); 
403         } 
404         txtarea.scrollTop = scrollPos; 
405     } 
406
407     /* open edition window for selected fragment */
408     function openForEdit($origin){
409         var $box = null
410
411         // annotations overlay their sub box - not their own box //
412         if ($origin.is(".annotation-inline-box")) {
413             $box = $("*[x-annotation-box]", $origin);
414         }
415         else {
416             $box = $origin;
417         }
418         var x = $box[0].offsetLeft;
419         var y = $box[0].offsetTop;        
420         
421         var w = $box.outerWidth();
422         var h = $box.innerHeight();
423
424         if ($origin.is(".annotation-inline-box")) {
425             w = Math.max(w, 400);
426             h = Math.max(h, 60);
427             if($('.htmlview div').offset().left + $('.htmlview div').width() > ($('.vsplitbar').offset().left - 480)){
428                 x = -(Math.max($origin.offset().left, $origin.width())); 
429             } else {
430                 x = 100;
431             }
432         }
433         if ($origin.is('.reference-inline-box')) {
434             w = 400;
435             h = 32;
436             y -= 32;
437             x = Math.min(
438                 x,
439                 $('.htmlview div').offset().left + $('.htmlview div').width() - 400
440             );
441         }
442
443         // start edition on this node
444         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({
445             position: 'absolute',
446             height: h,
447             left: x,
448             top: y,
449             width: w
450         }).appendTo($box[0].offsetParent || $box.parent()).show();
451         
452
453         if ($origin.is('*[x-edit-no-format]')) {
454             $('.akap-edit-button').remove();
455         }
456         
457         if ($origin.is('.motyw')) {
458             $.themes.autocomplete($('textarea', $overlay));
459         }
460
461         if ($origin.is('.motyw')){
462             $('.delete-button', $overlay).click(function(){
463                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw?")) {
464                     $('[theme-class="' + $origin.attr('theme-class') + '"]').remove();
465                     $overlay.remove();
466                     $(document).unbind('click.blur-overlay');
467                     return false;
468                 };
469             });
470         }
471         else if($box.is('*[x-annotation-box]') || $origin.is('*[x-edit-attribute]')) {
472             $('.delete-button', $overlay).click(function(){
473                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
474                     $origin.remove();
475                     $overlay.remove();
476                     $(document).unbind('click.blur-overlay');
477                     return false;
478                 };
479             });
480         }
481         else {
482             $('.delete-button', $overlay).html("Anuluj");
483             $('.delete-button', $overlay).click(function(){
484                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
485                     $overlay.remove();
486                     $(document).unbind('click.blur-overlay');
487                     return false;
488                 };
489             });
490         }
491
492
493         var serializer = new XMLSerializer();
494
495         if($box.attr("x-edit-attribute")) {
496             source = $('<span x-pass-thru="true"/>');
497             source.text($box.attr("data-wlf-" + $box.attr("x-edit-attribute")));
498             source = source[0];
499         } else {
500             source = $box[0];
501         }
502         
503         html2text({
504             element: source,
505             stripOuter: true,
506             success: function(text){
507                 $('textarea', $overlay).val($.trim(text));
508
509                 setTimeout(function(){
510                     $('textarea', $overlay).elastic().focus();
511                 }, 50);
512
513                 function save(argument){
514                     var nodeName = $box.attr('x-node') || 'pe';
515                     var insertedText = $('textarea', $overlay).val();
516
517                     if ($origin.is('.motyw')) {
518                         insertedText = insertedText.replace(/,\s*$/, '');
519                     }
520
521                     if($box.attr("x-edit-attribute")) {
522                         xml = '<' + nodeName + ' ' + $box.attr("x-edit-attribute") + '="' + insertedText + '"/>';
523                     } else {
524                         xml = '<' + nodeName + '>' + insertedText + '</' + nodeName + '>';
525                     }
526
527                     
528                     xml2html({
529                         xml: xml,
530                         success: function(element){
531                             if (nodeName == 'out-of-flow-text') {
532                                 $(element).children().insertAfter($origin);
533                                 $origin.remove()
534                             }
535                             else if ($box.attr('x-edit-attribute')) {
536                                 $(element).insertAfter($origin);
537                                 $origin.remove();
538                             }
539                             else {
540                                 $origin.html($(element).html());
541                             }
542                             $overlay.remove();
543                         },
544                         error: function(text){
545                             alert('Błąd! ' + text);
546                         }
547                     })
548                     
549                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
550                     $("#base").prepend(msg);
551                     $('#base .saveNotify').fadeOut(3000, function(){
552                         $(this).remove(); 
553                     });
554                 }
555
556                 $('.akap-edit-button', $overlay).click(function(){
557                         var textAreaOpened = $('textarea', $overlay)[0];
558                         var startTag = "";
559                         var endTag = "";
560                         var buttonName = this.innerHTML;
561
562                         if(buttonName == "słowo obce") {
563                                 startTag = "<slowo_obce>";
564                                 endTag = "</slowo_obce>";
565                         } else if (buttonName == "wyróżnienie") {
566                                 startTag = "<wyroznienie>";
567                                 endTag = "</wyroznienie>";
568                         } else if (buttonName == "tytuł dzieła") {
569                                 startTag = "<tytul_dziela>";
570                                 endTag = "</tytul_dziela>";
571                         } else if(buttonName == "znak spec."){
572                             addSymbol();
573                             return false;
574                         }
575                         
576                         var myField = textAreaOpened;                   
577                         
578                         //IE support
579                         if (document.selection) {
580                             textAreaOpened.focus();
581                             sel = document.selection.createRange();
582                             sel.text = startTag + sel.text + endTag;
583                         }
584                         //MOZILLA/NETSCAPE support
585                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
586                             var startPos = textAreaOpened.selectionStart;
587                             var endPos = textAreaOpened.selectionEnd;
588                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
589                                   + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
590                         }
591                 });
592
593                 $('.accept-button', $overlay).click(function(){
594                     save();
595                     $(document).unbind('click.blur-overlay');
596                 });
597
598                 $(document).bind('click.blur-overlay', function(event){
599                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
600                         return;
601                     }
602                     save();
603                     $(document).unbind('click.blur-overlay');
604                 });
605
606             },
607             error: function(text){
608                 alert('Błąd! ' + text);
609             }
610         });
611     }
612
613
614     function VisualPerspective(options){
615
616         var old_callback = options.callback;
617
618         options.callback = function(){
619             var element = $("#html-view");
620             var button = $('<button class="edit-button">Edytuj</button>');
621
622             if (!CurrentDocument.readonly) {
623                 $('#html-view').bind('mousemove', function(event){
624                     var editable = $(event.target).closest('*[x-editable]');
625                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
626
627                     if (!editable.hasClass('active')) {
628                         editable.addClass('active').append(button);
629                     }
630                     if (editable.is('.annotation-inline-box')) {
631                         $('*[x-annotation-box]', editable).css({
632                             position: 'absolute',
633                             left: event.clientX - editable.offset().left + 5,
634                             top: event.clientY - editable.offset().top + 5
635                         }).show();
636                     }
637                     else {
638                         $('*[x-annotation-box]').hide();
639                     }
640                 });
641
642                 $('#insert-reference-button').click(function(){
643                     addReference();
644                     return false;
645                 });
646
647                 $('#insert-annotation-button').click(function(){
648                     addAnnotation();
649                     return false;
650                 });
651
652                 $('#insert-theme-button').click(function(){
653                     addTheme();
654                     return false;
655                 });            
656
657                 $(document).on('click', '.edit-button', function(event){
658                     event.preventDefault();
659                     openForEdit($(this).parent());
660                 });
661
662             }
663
664             $(document).on('click', '.motyw', function(){
665                 selectTheme($(this).attr('theme-class'));
666             });
667
668             old_callback.call(this);
669         };
670
671         $.wiki.Perspective.call(this, options);
672     };
673
674     VisualPerspective.prototype = new $.wiki.Perspective();
675
676     VisualPerspective.prototype.freezeState = function(){
677
678     };
679
680     VisualPerspective.prototype.onEnter = function(success, failure){
681         $.wiki.Perspective.prototype.onEnter.call(this);
682
683         $.blockUI({
684             message: 'Uaktualnianie widoku...'
685         });
686
687         function _finalize(callback){
688             $.unblockUI();
689             if (callback)
690                 callback();
691         }
692
693         xml2html({
694             xml: this.doc.text,
695             success: function(element){
696                 var htmlView = $('#html-view');
697                 htmlView.html(element);
698                 htmlView.find('*[x-node]').dblclick(function(e) {
699                     if($(e.target).is('textarea'))
700                         return;
701                     var selection = window.getSelection();
702                     selection.collapseToStart();
703                     selection.modify('extend', 'forward', 'word');
704                     e.stopPropagation();
705                 });
706                 _finalize(success);
707             },
708             error: function(text, source){
709                 err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
710                 if (source)
711                     err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
712                 $('#html-view').html(err);
713                 _finalize(failure);
714             }
715         });
716     };
717
718     VisualPerspective.prototype.onExit = function(success, failure){
719         var self = this;
720
721         $.blockUI({
722             message: 'Zapisywanie widoku...'
723         });
724
725         function _finalize(callback){
726             $.unblockUI();
727             if (callback)
728                 callback();
729         }
730
731         if ($('#html-view .error').length > 0)
732             return _finalize(failure);
733
734         html2text({
735             element: $('#html-view').get(0),
736             stripOuter: true,
737             success: function(text){
738                 self.doc.setText(text);
739                 _finalize(success);
740             },
741             error: function(text){
742                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
743                 _finalize(failure);
744             }
745         });
746     };
747
748     $.wiki.VisualPerspective = VisualPerspective;
749
750 })(jQuery);