72e218aa7cc6ce62df219663398535689e75e573
[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") | $origin.is('.reference-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
434         // start edition on this node
435         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({
436             position: 'absolute',
437             height: h,
438             left: x,
439             top: y,
440             width: w
441         }).appendTo($box[0].offsetParent || $box.parent()).show();
442         
443
444         if ($origin.is('*[x-edit-no-format]')) {
445             $('.akap-edit-button').remove();
446         }
447         
448         if ($origin.is('.motyw')) {
449             $.themes.autocomplete($('textarea', $overlay));
450         }
451
452         if ($origin.is('.motyw')){
453             $('.delete-button', $overlay).click(function(){
454                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten motyw?")) {
455                     $('[theme-class="' + $origin.attr('theme-class') + '"]').remove();
456                     $overlay.remove();
457                     $(document).unbind('click.blur-overlay');
458                     return false;
459                 };
460             });
461         }
462         else if($box.is('*[x-annotation-box]') || $origin.is('*[x-edit-attribute]')) {
463             $('.delete-button', $overlay).click(function(){
464                 if (window.confirm("Czy jesteś pewien, że chcesz usunąć ten przypis?")) {
465                     $origin.remove();
466                     $overlay.remove();
467                     $(document).unbind('click.blur-overlay');
468                     return false;
469                 };
470             });
471         }
472         else {
473             $('.delete-button', $overlay).html("Anuluj");
474             $('.delete-button', $overlay).click(function(){
475                 if (window.confirm("Czy jesteś pewien, że chcesz anulować zmiany?")) {
476                     $overlay.remove();
477                     $(document).unbind('click.blur-overlay');
478                     return false;
479                 };
480             });
481         }
482
483
484         var serializer = new XMLSerializer();
485
486         if($box.attr("x-edit-attribute")) {
487             source = $('<span x-pass-thru="true"/>');
488             source.text($box.attr("data-wlf-" + $box.attr("x-edit-attribute")));
489             source = source[0];
490         } else {
491             source = $box[0];
492         }
493         
494         html2text({
495             element: source,
496             stripOuter: true,
497             success: function(text){
498                 $('textarea', $overlay).val($.trim(text));
499
500                 setTimeout(function(){
501                     $('textarea', $overlay).elastic().focus();
502                 }, 50);
503
504                 function save(argument){
505                     var nodeName = $box.attr('x-node') || 'pe';
506                     var insertedText = $('textarea', $overlay).val();
507
508                     if ($origin.is('.motyw')) {
509                         insertedText = insertedText.replace(/,\s*$/, '');
510                     }
511
512                     if($box.attr("x-edit-attribute")) {
513                         xml = '<' + nodeName + ' ' + $box.attr("x-edit-attribute") + '="' + insertedText + '"/>';
514                     } else {
515                         xml = '<' + nodeName + '>' + insertedText + '</' + nodeName + '>';
516                     }
517
518                     
519                     xml2html({
520                         xml: xml,
521                         success: function(element){
522                             if (nodeName == 'out-of-flow-text') {
523                                 $(element).children().insertAfter($origin);
524                                 $origin.remove()
525                             }
526                             else if ($box.attr('x-edit-attribute')) {
527                                 $(element).insertAfter($origin);
528                                 $origin.remove();
529                             }
530                             else {
531                                 $origin.html($(element).html());
532                             }
533                             $overlay.remove();
534                         },
535                         error: function(text){
536                             alert('Błąd! ' + text);
537                         }
538                     })
539                     
540                     var msg = $("<div class='saveNotify'><p>Pamiętaj, żeby zapisać swoje zmiany.</p></div>");
541                     $("#base").prepend(msg);
542                     $('#base .saveNotify').fadeOut(3000, function(){
543                         $(this).remove(); 
544                     });
545                 }
546
547                 $('.akap-edit-button', $overlay).click(function(){
548                         var textAreaOpened = $('textarea', $overlay)[0];
549                         var startTag = "";
550                         var endTag = "";
551                         var buttonName = this.innerHTML;
552
553                         if(buttonName == "słowo obce") {
554                                 startTag = "<slowo_obce>";
555                                 endTag = "</slowo_obce>";
556                         } else if (buttonName == "wyróżnienie") {
557                                 startTag = "<wyroznienie>";
558                                 endTag = "</wyroznienie>";
559                         } else if (buttonName == "tytuł dzieła") {
560                                 startTag = "<tytul_dziela>";
561                                 endTag = "</tytul_dziela>";
562                         } else if(buttonName == "znak spec."){
563                             addSymbol();
564                             return false;
565                         }
566                         
567                         var myField = textAreaOpened;                   
568                         
569                         //IE support
570                         if (document.selection) {
571                             textAreaOpened.focus();
572                             sel = document.selection.createRange();
573                             sel.text = startTag + sel.text + endTag;
574                         }
575                         //MOZILLA/NETSCAPE support
576                         else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') {
577                             var startPos = textAreaOpened.selectionStart;
578                             var endPos = textAreaOpened.selectionEnd;
579                             textAreaOpened.value = textAreaOpened.value.substring(0, startPos)
580                                   + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length);
581                         }
582                 });
583
584                 $('.accept-button', $overlay).click(function(){
585                     save();
586                     $(document).unbind('click.blur-overlay');
587                 });
588
589                 $(document).bind('click.blur-overlay', function(event){
590                     if ($(event.target).closest('.html-editarea, #specialCharsContainer').length > 0) {
591                         return;
592                     }
593                     save();
594                     $(document).unbind('click.blur-overlay');
595                 });
596
597             },
598             error: function(text){
599                 alert('Błąd! ' + text);
600             }
601         });
602     }
603
604
605     function VisualPerspective(options){
606
607         var old_callback = options.callback;
608
609         options.callback = function(){
610             var element = $("#html-view");
611             var button = $('<button class="edit-button">Edytuj</button>');
612
613             if (!CurrentDocument.readonly) {
614                 $('#html-view').bind('mousemove', function(event){
615                     var editable = $(event.target).closest('*[x-editable]');
616                     $('.active', element).not(editable).removeClass('active').children('.edit-button').remove();
617
618                     if (!editable.hasClass('active')) {
619                         editable.addClass('active').append(button);
620                     }
621                     if (editable.is('.annotation-inline-box')) {
622                         $('*[x-annotation-box]', editable).css({
623                             position: 'absolute',
624                             left: event.clientX - editable.offset().left + 5,
625                             top: event.clientY - editable.offset().top + 5
626                         }).show();
627                     }
628                     else {
629                         $('*[x-annotation-box]').hide();
630                     }
631                 });
632
633                 $('#insert-reference-button').click(function(){
634                     addReference();
635                     return false;
636                 });
637
638                 $('#insert-annotation-button').click(function(){
639                     addAnnotation();
640                     return false;
641                 });
642
643                 $('#insert-theme-button').click(function(){
644                     addTheme();
645                     return false;
646                 });            
647
648                 $(document).on('click', '.edit-button', function(event){
649                     event.preventDefault();
650                     openForEdit($(this).parent());
651                 });
652
653             }
654
655             $(document).on('click', '.motyw', function(){
656                 selectTheme($(this).attr('theme-class'));
657             });
658
659             old_callback.call(this);
660         };
661
662         $.wiki.Perspective.call(this, options);
663     };
664
665     VisualPerspective.prototype = new $.wiki.Perspective();
666
667     VisualPerspective.prototype.freezeState = function(){
668
669     };
670
671     VisualPerspective.prototype.onEnter = function(success, failure){
672         $.wiki.Perspective.prototype.onEnter.call(this);
673
674         $.blockUI({
675             message: 'Uaktualnianie widoku...'
676         });
677
678         function _finalize(callback){
679             $.unblockUI();
680             if (callback)
681                 callback();
682         }
683
684         xml2html({
685             xml: this.doc.text,
686             success: function(element){
687                 var htmlView = $('#html-view');
688                 htmlView.html(element);
689                 htmlView.find('*[x-node]').dblclick(function(e) {
690                     if($(e.target).is('textarea'))
691                         return;
692                     var selection = window.getSelection();
693                     selection.collapseToStart();
694                     selection.modify('extend', 'forward', 'word');
695                     e.stopPropagation();
696                 });
697                 _finalize(success);
698             },
699             error: function(text, source){
700                 err = '<p class="error">Wystąpił błąd:</p><p>'+text+'</p>';
701                 if (source)
702                     err += '<pre>'+source.replace(/&/g, '&amp;').replace(/</g, '&lt;')+'</pre>'
703                 $('#html-view').html(err);
704                 _finalize(failure);
705             }
706         });
707     };
708
709     VisualPerspective.prototype.onExit = function(success, failure){
710         var self = this;
711
712         $.blockUI({
713             message: 'Zapisywanie widoku...'
714         });
715
716         function _finalize(callback){
717             $.unblockUI();
718             if (callback)
719                 callback();
720         }
721
722         if ($('#html-view .error').length > 0)
723             return _finalize(failure);
724
725         html2text({
726             element: $('#html-view').get(0),
727             stripOuter: true,
728             success: function(text){
729                 self.doc.setText(text);
730                 _finalize(success);
731             },
732             error: function(text){
733                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
734                 _finalize(failure);
735             }
736         });
737     };
738
739     $.wiki.VisualPerspective = VisualPerspective;
740
741 })(jQuery);