* Improved history view (still not there).
[redakcja.git] / platforma / static / js / main.js
1 if (!window.console) {
2     window.console = {
3         log: function() {}
4     }
5 }
6
7 THEMES = ['Alkohol', 'Ambicja', 'Anioł', 'Antysemityzm', 'Arkadia', 'Artysta', 'Bezdomność',
8 'Bezpieczeństwo', 'Bieda', 'Bijatyka', 'Błazen', 'Błądzenie', 'Błoto', 'Bogactwo', 'Bóg', 'Brat',
9 'Bunt', 'Buntownik', 'Burza', 'Car', 'Carpe diem', 'Ciemność', 'Cień', 'Cisza', 'Chciwość', 'Chleb',
10 'Chłop', 'Choroba', 'Chrystus', 'Chrzest', 'Ciało', 'Cierpienie', 'Cmentarz', 'Cnota', 'Córka', 'Cud',
11 'Czarownika', 'Czary', 'Czas', 'Czyn', 'Czyściec', 'Dama', 'Danse macabre', 'Deszcz', 'Diabeł',
12 'Dobro', 'Dom', 'Dorosłość', 'Drzewo', 'Duch', 'Dusza', 'Duma', 'Dworek', 'Dworzanin', 'Dwór',
13 'Dzieciństwo', 'Dziecko', 'Dziedzictwo', 'Dziewictwo', 'Dźwięk', 'Egzorcyzm', 'Elita', 'Emigrant',
14 'Fałsz', 'Filozof', 'Fircyk', 'Flirt', 'Głupiec', 'Głupota', 'Głód', 'Gospodarz', 'Gospodyni', 'Gość',
15 'Gotycyzm', 'Góra', 'Gra', 'Grób', 'Grzech', 'Grzeczność', 'Gwiazda', 'Handel', 'Hańba', 'Historia',
16 'Honor', 'Idealista', 'Imię', 'Interes', 'Jabłka', 'Jedzenie', 'Jesień', 'Kaleka', 'Kara', 'Karczma',
17 'Klęska', 'Kłamstwo', 'Kłótnia', 'Kobieta', 'Kobieta demoniczna', 'Kobieta "upadła"', 'Kochanek',
18 'Kochanek romantyczny', 'Kolonializm', 'Kondycja ludzka', 'Konflikt', 'Konflikt wewnętrzny', 'Koniec świata',
19 'Koń', 'Korzyść', 'Kot', 'Kradzież', 'Krew', 'Król', 'Krzywda', 'Ksiądz', 'Książka',
20 'Księżyc', 'Kuchnia', 'Kuszenie', 'Kwiaty', 'Labirynt', 'Las', 'Lato', 'Lekarz', 'Lenistwo', 'List',
21 'Liberat', 'Los', 'Lud', 'Lustro', 'Łzy', 'Małżeństwo', 'Marzenie', 'Maska', 'Maszyna', 'Matka',
22 'Matka Boska', 'Mądrość', 'Mąż', 'Melancholia', 'Mędrzec', 'Mężczyzna', 'Miasto', 'Mieszczanin',
23 'Miłosierdzie', 'Miłość', 'Miłość niespełniona', 'Miłość platoniczna', 'Miłość romantyczna', 
24 'Miłość silniejsza niż śmierć', 'Miłość spełniona', 'Miłość tragiczna', 'Mizoginia', 'Młodość', 'Moda',
25 'Modlitwa', 'Morderstwo', 'Morze', 'Motyl', 'Mucha', 'Muzyka', 'Narodziny', 'Naród', 'Natura',
26 'Nauczyciel', 'Nauczycielka', 'Nauka', 'Niebezpieczeństwo', 'Niedziela', 'Niemiec', 'Nienawiść',
27 'Nieśmiertelność', 'Niewola', 'Noc', 'Nuda', 'Obcy', 'Obłok', 'Obowiązek', 'Obraz świata', 'Obrzędy',
28 'Obyczaje', 'Obywatel', 'Odrodzenie przez grób', 'Odwaga', 'Ofiara', 'Ogień', 'Ogród', 'Ojciec',
29 'Ojczyzna', 'Oko', 'Okręt', 'Okrucieństwo', 'Omen', 'Opieka', 'Organizm', 'Otchłań', 'Pająk', 'Pamięć',
30 'Pan', 'Panna młoda', 'Państwo', 'Patriota', 'Piekło', 'Pielgrzym', 'Pieniądz', 'Pies', 'Piętno',
31 'Pijaństwo', 'Piwnica', 'Plotka', 'Pobożność', 'Pocałunek', 'Pochlebstwo', 'Poeta', 'Poetka', 'Poezja',
32 'Podróż', 'Podstęp', 'Pogrzeb', 'Pojedynek', 'Pokora', 'Pokusa', 'Polak', 'Polityka', 'Polowanie',
33 'Polska', 'Portret', 'Porwanie', 'Poświęcenie', 'Potwór', 'Powstanie', 'Powstaniec', 'Pozory',
34 'Pozycja społeczna', 'Pożar', 'Pożądanie', 'Praca', 'Praca u podstaw', 'Praca organiczna', 'Prawda', 'Prawnik',
35 'Prometeusz', 'Proroctwo', 'Prorok', 'Próżność', 'Przebranie', 'Przeczucie', 'Przedmurze chrześcijaństwa',
36 'Przekleństwo', 'Przekupstwo', 'Przemiana', 'Przemijanie', 'Przemoc', 'Przestrzeń',
37 'Przyjaźń', 'Przyroda nieożywiona', 'Przysięga', 'Przywódca', 'Ptak', 'Pustynia', 'Pycha', 'Raj',
38 'Realista', 'Religia', 'Rewolucja', 'Robak', 'Robotnik', 'Rodzina', 'Rosja', 'Rosjanin', 'Rośliny',
39 'Rozczarowanie', 'Rozpacz', 'Rozstanie', 'Rozum', 'Ruiny', 'Rycerz', 'Rzeka', 'Salon', 'Samobójstwo',
40 'Samolubstwo', 'Samotnik', 'Samotność', 'Sarmata', 'Sąsiad', 'Sąd', 'Sąd Ostateczny', 'Sen', 'Serce',
41 'Sędzia', 'Sielanka', 'Sierota', 'Siła', 'Siostra', 'Sława', 'Słońce', 'Słowo', 'Sługa', 'Służalczość',
42 'Skąpiec', 'Sobowtór', 'Społecznik', 'Spowiedź', 'Sprawiedliwość', 'Starość', 'Strach', 'Strój',
43 'Stworzenie', 'Sumienie', 'Swaty', 'Syberia', 'Syn', 'Syn marnotrawny', 'Syzyf', 'Szaleniec',
44 'Szaleństwo', 'Szantaż', 'Szatan', 'Szczęście', 'Szkoła', 'Szlachcic', 'Szpieg', 'Sztuka', 'Ślub',
45 'Śmiech', 'Śmierć', 'Śmierć bohaterska', 'Śpiew', 'Światło', 'Świętoszek', 'Święty', 'Świt',
46 'Tajemnica', 'Taniec', 'Tchórzostwo', 'Teatr', 'Testament', 'Tęsknota', 'Theatrum mundi', 'Tłum',
47 'Trucizna', 'Trup', 'Twórczość', 'Uczeń', 'Uczta', 'Uroda', 'Umiarkowanie', 'Upadek', 'Upiór',
48 'Urzędnik', 'Vanitas', 'Walka', 'Walka klas', 'Wampir', 'Warszawa', 'Wąż', 'Wdowa', 'Wdowiec',
49 'Wesele', 'Wiatr', 'Wierność', 'Wierzenia', 'Wieś', 'Wiedza', 'Wieża Babel', 'Więzienie', 'Więzień',
50 'Wina', 'Wino', 'Wiosna', 'Wizja', 'Władza', 'Własność', 'Woda', 'Wojna', 'Wojna pokoleń', 'Wolność',
51 'Wróg', 'Wspomnienia', 'Współpraca', 'Wygnanie', 'Wyrzuty sumienia', 'Wyspa', 'Wzrok', 'Zabawa',
52 'Zabobony', 'Zamek', 'Zaręczyny', 'Zaświaty', 'Zazdrość', 'Zbawienie', 'Zbrodnia', 'Zbrodniarz',
53 'Zdrada', 'Zdrowie', 'Zemsta', 'Zesłaniec', 'Ziarno', 'Ziemia', 'Zima', 'Zło', 'Złodziej', 'Złoty wiek',
54 'Zmartwychwstanie', 'Zwątpienie', 'Zwierzęta', 'Zwycięstwo', 'Żałoba', 'Żebrak', 'Żołnierz',
55 'Żona', 'Życie jako wędrówka', 'Życie snem', 'Żyd', 'Żywioły', 'Oświadczyny']
56
57
58 // Teraz nieużywane
59 function highlight(colour) {
60     var range, sel;
61     if (window.getSelection) {
62         // Non-IE case
63         sel = window.getSelection();
64         if (sel.getRangeAt) {
65             range = sel.getRangeAt(0);
66         }
67         document.designMode = "on";
68         if (range) {
69             sel.removeAllRanges();
70             sel.addRange(range);
71         }
72         // Use HiliteColor since some browsers apply BackColor to the whole block
73         if ( !document.execCommand("HiliteColor", false, colour) ) {
74             document.execCommand("BackColor", false, colour);
75         }
76         document.designMode = "off";
77     } else if (document.selection && document.selection.createRange) {
78         // IE case
79         range = document.selection.createRange();
80         range.execCommand("BackColor", false, colour);
81     }
82 }
83
84 // function unselectThemes(themeId) {
85 //     $('.Apple-style-span').each(function() {
86 //         $(this).after($(this).html());
87 //         $(this).remove();
88 //     });
89 // }
90
91 function gallery(element, url) {    
92     var element = $(element);
93     var imageDimensions = {};
94     element.data('images', []);
95     
96     function changePage(pageNumber) {        
97         $('.gallery-image img', element).attr('src', element.data('images')[pageNumber - 1]);
98     }
99     
100     function normalizeNumber(pageNumber) {
101         // Numer strony musi być pomiędzy 1 a najwyższym numerem
102         var pageCount = element.data('images').length;
103         pageNumber = parseInt(pageNumber, 10);
104         
105         if (!pageNumber || pageNumber == NaN || pageNumber == Infinity || pageNumber == -Infinity) {
106             return 1;
107         } else if (pageNumber < 1) {
108             return 1;
109         } else if (pageNumber > pageCount) {
110             return pageCount;
111         } else {
112             return pageNumber;
113         }
114     }
115     
116     var pn = $('.page-number', element);
117     pn.change(function(event) {
118         event.preventDefault();
119         var n = normalizeNumber(pn.val());
120         pn.val(n);
121         changePage(n);
122     });
123     $('.previous-page', element).click(function() {
124         pn.val(normalizeNumber(pn.val()) - 1);
125         pn.change();
126     });
127     $('.next-page', element).click(function() {
128         pn.val(normalizeNumber(pn.val()) + 1);
129         pn.change();
130     });
131     
132     
133     var image = $('.gallery-image img', element).attr('unselectable', 'on');
134     var origin = {};
135     var imageOrigin = {};
136     var zoomFactor = 1;
137     
138     $('.zoom-in', element).click(function() {
139         zoomFactor = Math.min(2, zoomFactor + 0.2);
140         zoom();
141     });
142     $('.zoom-out', element).click(function() {
143         zoomFactor = Math.max(0.2, zoomFactor - 0.2);
144         zoom();
145     });
146     $('.change-gallery', element).click(function() {
147         $('.chosen-gallery').val($('#document-meta .gallery').html() || '/platforma/gallery/');
148         $('.gallery-image').animate({top: 60}, 200);
149         $('.chosen-gallery').focus();
150     });
151     $('.change-gallery-ok', element).click(function() {
152         if ($('#document-meta .gallery').length == 0) {
153             $('<div class="gallery"></div>').appendTo('#document-meta');
154         }
155         $('#document-meta .gallery').html($('.chosen-gallery').val());
156         updateGallery($('.chosen-gallery').val());
157         $('.gallery-image').animate({top: 30}, 200);
158     });
159     $('.change-gallery-cancel', element).click(function() {
160         $('.gallery-image').animate({top: 30}, 200);
161     });
162     
163     $('.gallery-image img', element).load(function() {
164         image.css({width: null, height: null});
165         imageDimensions = {
166             width: $(this).width() * zoomFactor,
167             height: $(this).height() * zoomFactor,
168             originWidth: $(this).width(),
169             originHeight: $(this).height(),
170             galleryWidth: $(this).parent().width(),
171             galleryHeight: $(this).parent().height()
172         };
173         
174         if (!(imageDimensions.width && imageDimensions.height)) {
175             setTimeout(function() { $('.gallery-image img', element).load(); }, 100);
176         }        
177         var position = normalizePosition(
178             image.position().left,
179             image.position().top, 
180             imageDimensions.galleryWidth,
181             imageDimensions.galleryHeight,
182             imageDimensions.width,
183             imageDimensions.height
184         );
185         image.css({left: position.x, top: position.y, width: $(this).width() * zoomFactor, height: $(this).height() * zoomFactor});
186     });
187
188     $(window).resize(function() {
189         imageDimensions.galleryWidth = image.parent().width();
190         imageDimensions.galleryHeight = image.parent().height();
191     });
192     
193     function bounds(galleryWidth, galleryHeight, imageWidth, imageHeight) {
194         return {
195             maxX: 0,
196             maxY: 0,
197             minX: galleryWidth - imageWidth,
198             minY: galleryHeight - imageHeight
199         }
200     }
201     
202     function normalizePosition(x, y, galleryWidth, galleryHeight, imageWidth, imageHeight) {
203         var b = bounds(galleryWidth, galleryHeight, imageWidth, imageHeight);
204         return {
205             x: Math.min(b.maxX, Math.max(b.minX, x)),
206             y: Math.min(b.maxY, Math.max(b.minY, y))
207         }
208     }
209     
210     function onMouseMove(event) {
211         var position = normalizePosition(
212             event.clientX - origin.x + imageOrigin.left,
213             event.clientY - origin.y + imageOrigin.top, 
214             imageDimensions.galleryWidth,
215             imageDimensions.galleryHeight,
216             imageDimensions.width,
217             imageDimensions.height
218         );
219         image.css({position: 'absolute', top: position.y, left: position.x});
220         return false;
221     }
222     
223     function setZoom(factor) {
224         zoomFactor = factor;
225     }
226     
227     function zoom() {
228         imageDimensions.width = imageDimensions.originWidth * zoomFactor;
229         imageDimensions.height = imageDimensions.originHeight * zoomFactor;
230         var position = normalizePosition(
231             image.position().left,
232             image.position().top, 
233             imageDimensions.galleryWidth,
234             imageDimensions.galleryHeight,
235             imageDimensions.width,
236             imageDimensions.height
237         );
238         image.css({width: imageDimensions.width, height: imageDimensions.height,
239             left: position.x, top: position.y});
240
241     }
242     
243     function onMouseUp(event) {
244         $(document)
245             .unbind('mousemove.gallery')
246             .unbind('mouseup.gallery');
247         return false;
248     }
249     
250     image.bind('mousedown', function(event) {
251         origin = {
252             x: event.clientX,
253             y: event.clientY
254         };
255         imageOrigin = image.position();
256         $(document)
257             .bind('mousemove.gallery', onMouseMove)
258             .bind('mouseup.gallery', onMouseUp);
259         return false;
260     });
261     
262     function updateGallery(url) {
263         $.ajax({
264             url: url,
265             type: 'GET',
266             dataType: 'json',
267
268             success: function(data) {
269                 element.data('images', data);
270                 pn.val(1);
271                 pn.change();
272                 $('.gallery-image img', element).show();
273             },
274             
275             error: function(data) {
276                 element.data('images', []);
277                 pn.val(1);
278                 pn.change();
279                 $('.gallery-image img', element).hide();
280             }
281         });
282     }
283     
284     if (url) {
285         updateGallery(url);
286     }
287 }
288
289
290 function transform(editor, callback) {
291     if (!callback) {
292         $.blockUI({message: 'Ładowanie...'});
293     }
294     setTimeout(function() {
295         xml2html({
296             xml: editor.getCode(),
297             success: function(element) {
298                 $('#html-view').html(element);
299                 $.unblockUI();
300                 if (callback) {
301                     callback();
302                 }
303             }, error: function(text) {
304                                 var message = $('<pre></pre>');
305                                 message.text(text);
306                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' + 
307                                     message.html() + '</pre>');
308                                         
309                 $.unblockUI();
310                 if (callback) {
311                     callback();
312                 }
313             }
314         });
315     }, 200);
316 };
317
318
319 function reverseTransform(editor, cont, errorCont, dontBlock) {
320     var serializer = new XMLSerializer();
321     if ($('#html-view .error').length > 0) {
322         if (errorCont) {
323             errorCont();
324         }
325         return;
326     }
327     if (!dontBlock) {
328         $.blockUI({message: 'Ładowanie...'});
329     }
330     setTimeout(function() {
331         html2text({
332                         element: $('#html-view div').get(0),            
333             success: function(text) {
334                 editor.setCode(text);
335                 if (!dontBlock) {
336                     $.unblockUI();
337                 }
338                 if (cont) {
339                     cont();
340                 }
341             }, error: function(text) {
342                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
343                 if (!dontBlock) {
344                     $.unblockUI();
345                 }
346                 if (errorCont) {
347                     errorCont();
348                 }
349             }
350         });
351     }, 200);
352 }
353
354
355 // =============
356 // = HTML View =
357 // =============
358 function html(element) {
359     var element = $(element);
360     
361     function selectTheme(themeId)
362     {
363         var selection = window.getSelection();
364         selection.removeAllRanges();
365
366         var range = document.createRange();
367         var s = $(".motyw[theme-class='"+themeId+"']")[0];
368         var e = $(".end[theme-class='"+themeId+"']")[0];
369
370         if(s && e) {
371             range.setStartAfter(s);
372             range.setEndBefore(e);
373             selection.addRange(range);
374         }
375     };
376     
377     function verifyTagInsertPoint(node) {
378         if(node.nodeType == 3) { // Text Node
379             node = node.parentNode;
380         }
381
382         if (node.nodeType != 1) { 
383             return false;
384         }
385
386         node = $(node);
387         var xtype = node.attr('x-node');
388
389         if (!xtype || (xtype.search(':') >= 0) ||
390             xtype == 'motyw' || xtype == 'begin' || xtype == 'end') {
391             return false;
392         }
393         
394         // don't allow themes inside annotations
395         if( node.is('*[x-annotation-box] *') )
396             return false;
397
398         return true;
399     }
400         
401         var ANNOT_ALLOWED = ['wyroznienie'];
402         
403         function html2plainText(fragment) {
404                 var text = "";
405                 
406                 $(fragment.childNodes).each(function() {
407                         if(this.nodeType == 3) // textNode
408                             text += this.nodeValue;
409                         else if (this.nodeType == 1 
410                             && $.inArray($(this).attr('x-node'), ANNOT_ALLOWED) != -1 ){
411                                 text += html2plainText(this);                           
412                         }                       
413                 });
414                 
415                 return text;            
416         }
417     
418     function addAnnotation()
419     {
420         var selection = window.getSelection();
421         var n = selection.rangeCount;
422
423         if (n == 0) {
424             window.alert("Nie zaznaczono żadnego obszaru");
425             return false;
426         }
427
428         // for now allow only 1 range
429         if (n > 1) {
430             window.alert("Zaznacz jeden obszar");
431             return false;
432         }
433
434         // remember the selected range
435         var range = selection.getRangeAt(0);
436
437         if (!verifyTagInsertPoint(range.endContainer)) {
438             window.alert("Nie można wstawić w to miejsce przypisu.");
439             return false;
440         }
441
442                 // BUG #273 - selected text can contain themes, which should be omited from
443                 // defining term
444         var text = html2plainText( range.cloneContents() ); 
445                 
446         var tag = $('<span></span>');
447         range.collapse(false);
448         range.insertNode(tag[0]);
449
450         xml2html({
451             xml: '<pr><slowo_obce>'+text+'</slowo_obce> --- </pr>',
452             success: function(text) {
453                 var t = $(text);
454                 tag.replaceWith(t);
455                 openForEdit(t);
456             },
457             error: function() {
458                 tag.remove();
459                 alert('Błąd przy dodawaniu przypisu:' + errors);                
460             }
461         })
462     }
463     
464     function addTheme()
465     {
466         var selection = window.getSelection();
467         var n = selection.rangeCount;
468
469         if(n == 0) {
470             window.alert("Nie zaznaczono żadnego obszaru");
471             return false;
472         }
473
474         // for now allow only 1 range
475         if(n > 1) {
476             window.alert("Zaznacz jeden obszar.");
477             return false;
478         }
479                  
480
481         // remember the selected range
482         var range = selection.getRangeAt(0);
483                 
484                 
485                 if( $(range.startContainer).is('.html-editarea') 
486                  || $(range.endContainer).is('.html-editarea') ) {
487                         window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie.");
488             return false;
489                  }               
490
491         // verify if the start/end points make even sense -
492         // they must be inside a x-node (otherwise they will be discarded)
493         // and the x-node must be a main text
494         if (!verifyTagInsertPoint(range.startContainer)) {
495             window.alert("Motyw nie może się zaczynać w tym miejscu.");
496             return false;
497         }
498
499         if (!verifyTagInsertPoint(range.endContainer)) {
500             window.alert("Motyw nie może się kończyć w tym miejscu.");
501             return false;
502         }
503
504         var date = (new Date()).getTime();
505         var random = Math.floor(4000000000*Math.random());
506         var id = (''+date) + '-' + (''+random);
507
508         var spoint = document.createRange();
509         var epoint = document.createRange();
510
511         spoint.setStart(range.startContainer, range.startOffset);
512         epoint.setStart(range.endContainer, range.endOffset);
513
514         var mtag, btag, etag, errors;
515
516         // insert theme-ref
517                 
518         xml2html({
519             xml: '<end id="e'+id+'" />',
520             success: function(text) {
521                 etag = $('<span></span>');
522                 epoint.insertNode(etag[0]);
523                 etag.replaceWith(text);
524                 xml2html({
525                     xml: '<motyw id="m'+id+'"></motyw>',
526                     success: function(text) {                                           
527                         mtag = $('<span></span>');
528                         spoint.insertNode(mtag[0]);
529                         mtag.replaceWith(text);
530                         xml2html({
531                             xml: '<begin id="b'+id+'" />',
532                             success: function(text) {
533                                 btag = $('<span></span>');
534                                 spoint.insertNode(btag[0])
535                                 btag.replaceWith(text);
536                                 selection.removeAllRanges();
537                                 openForEdit($('.motyw[theme-class=' + id + ']'));
538                             }
539                         });
540                     }
541                 });
542             }
543         });
544     }
545     
546     function openForEdit($origin)
547     {       
548         var $box = null
549     
550         // annotations overlay their sub box - not their own box //
551         if($origin.is(".annotation-inline-box")) {
552             $box = $("*[x-annotation-box]", $origin);
553         } else {
554             $box = $origin;
555         }
556         
557         var x = $box[0].offsetLeft;
558         var y = $box[0].offsetTop;
559         var w = $box.outerWidth();
560         var h = $box.innerHeight();
561     
562         if ($origin.is(".annotation-inline-box")) {
563             w = Math.max(w, 400);
564             h = Math.max(h, 60);
565         }
566         
567         // start edition on this node
568         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><textarea></textarea></div>').css({
569             position: 'absolute',
570             height: h,
571             left: x,
572             top: y,
573             width: w
574         }).appendTo($box[0].offsetParent || $box.parent()).show();
575         
576         if ($origin.is('.motyw')) {
577             $('textarea', $overlay).autocomplete(THEMES, {
578                 autoFill: true,
579                 multiple: true,
580                 selectFirst: true
581             });
582         }
583         
584         $('.delete-button', $overlay).click(function() {
585             if ($origin.is('.motyw')) {
586                 $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
587             } else {
588                 $origin.remove();
589             }
590             $overlay.remove();
591             $(document).unbind('click.blur-overlay');
592             return false;
593         })
594         
595         
596         var serializer = new XMLSerializer();
597         
598         html2text({
599             element: $box[0],
600             stripOuter: true,
601             success: function(text) {
602                 $('textarea', $overlay).val($.trim(text));
603                 
604                 setTimeout(function() {
605                     $('textarea', $overlay).elastic().focus();
606                 }, 50);
607                 
608                 function save(argument) {
609                     var nodeName = $box.attr('x-node') || 'pe';
610                                         var insertedText = $('textarea', $overlay).val();
611                                         
612                                         if ($origin.is('.motyw')) {
613                                                 insertedText = insertedText.replace(/,\s*$/, '');
614                                         }
615                                         
616                     xml2html({
617                         xml: '<' + nodeName + '>' + insertedText + '</' + nodeName + '>',
618                         success: function(element) {
619                             $origin.html($(element).html());
620                             $overlay.remove();
621                         },
622                         error: function(text) {
623                             $overlay.remove();
624                             alert('Błąd! ' + text);
625                         }
626                     })
627                 }
628                 
629                 $('.accept-button', $overlay).click(function() {
630                     save();
631                 });
632                 
633                 $(document).bind('click.blur-overlay', function(event) {
634                     if ($(event.target).parents('.html-editarea').length > 0) {
635                         return;
636                     }
637                     save();
638                     
639                     $(document).unbind('click.blur-overlay');
640                 });
641                 
642             }, error: function(text) {
643                 alert('Błąd! ' + text);
644             }
645         });
646     }
647     
648     $('.edit-button').live('click', function(event) {
649         event.preventDefault();
650         openForEdit($(this).parent());
651     });
652     
653
654     
655     var button = $('<button class="edit-button">Edytuj</button>');
656     $(element).bind('mousemove', function(event) {
657         var editable = $(event.target).closest('*[x-editable]');
658         $('.active[x-editable]', element).not(editable).removeClass('active').children('.edit-button').remove();
659         if (!editable.hasClass('active')) {
660             editable.addClass('active').append(button);
661         }
662         if (editable.is('.annotation-inline-box')) {
663             $('*[x-annotation-box]', editable)
664                 .css({position: 'absolute', left: event.clientX - editable.offset().left + 5, top: event.clientY - editable.offset().top + 5})
665                 .show();
666         } else {
667             $('*[x-annotation-box]').hide();
668         }
669     });
670
671     $('.motyw').live('click', function() {
672         selectTheme($(this).attr('theme-class'));
673     });
674     
675     $('#insert-annotation-button').click(function() {
676         addAnnotation();
677         return false;
678     });
679     
680     $('#insert-theme-button').click(function() {
681         addTheme();
682         return false;
683     });
684 }
685
686 /*
687  * History
688  */
689
690 function refreshHistory(callback){
691         $.blockUI({
692                 message: 'Odświeżanie historii...'
693         });
694         
695         $.ajax({
696                 url: document.location.href + '/history',
697         dataType: 'json',
698                 error: function() {
699                         $('#history-view .message-box').html('Nie udało się odświeżyć historii').show();
700                         $.unblockUI();          
701                 },
702                 success: function(data) {
703                         $('#history-view .message-box').hide();
704                         var changes_list = $('#changes-list');
705                         changes_list.html('');
706                         
707                         $.each(data, function() {
708                                 var val = this[0];
709                                 changes_list.append('<tr>'
710                                         +'<td><input type="radio" name="rev_from" value="'+val+'">'
711                                                 + '<input type="radio" name="rev_to" value="'+val+'">'
712                                         +'<td>'+ this[0]+'</td>'
713                                         +'<td>'+ this[3]+'</td>'
714                                         +'<td>'+ this[2]+'</td>'
715                                         +'<td>'+ this[1]+'</td></tr>')                  
716                         });                                                     
717                         $.unblockUI();  
718                         if(callback) callback();
719                 }
720         });
721 };
722
723 function historyDiff(callback) {
724         var changelist = $('#changes-list');
725         var rev_a = $("input[name='rev_from']:checked", changelist);
726         var rev_b = $("input[name='rev_to']:checked", changelist);
727         
728         if (rev_a.length != 1 || rev_b.length != 1) {
729                 window.alert("Musisz zaznaczyć dwie wersje do porównania.");
730                 return false;
731         }
732         
733         if (rev_a.val() == rev_b.val()) {
734                 window.alert("Musisz zaznaczyć dwie różne wersje do porównania.");
735                 return false;
736         }
737                         
738         $.blockUI({
739                 message: 'Wczytywanie porównania...'
740         });
741         
742         $.ajax({
743                 url: document.location.href + '/diff/'+rev_a.val() + '/'+ rev_b.val(),
744         dataType: 'html',
745                 error: function() {
746                         $.unblockUI();
747                         window.alert('Nie udało się wykonać porównania :(.')                                        
748                 },
749                 success: function(data) {
750                         $.unblockUI();                  
751                         var diffview = $('#diff-view');                 
752                         diffview.html(data);
753                         diffview.show();                                                        
754                 }
755         });
756 }
757         
758
759 $(function() {
760     gallery('#sidebar', $('#document-meta .gallery').html());
761     html('#html-view');
762     
763     CodeMirror.fromTextArea('id_text', {
764         parserfile: 'parsexml.js',
765         path: STATIC_URL + "js/lib/codemirror/",
766         stylesheet: STATIC_URL + "css/xmlcolors.css",
767         parserConfig: {
768             useHTMLKludges: false
769         },
770         iframeClass: 'xml-iframe',              
771         textWrapping: true,
772                 lineNumbers: true, 
773                 width: "100%",
774         tabMode: 'spaces',
775         indentUnit: 0,
776         initCallback: function(editor) {
777             $('#save-button').click(function(event) {
778                 event.preventDefault();
779                 $.blockUI({message: $('#save-dialog')});
780             });
781             
782             $('#save-ok').click(function() {
783                 $.blockUI({message: 'Zapisywanie...'});
784                 
785                 function doSave (argument) {
786                     var metaComment = '<!--';
787                     $('#document-meta div').each(function() {
788                         metaComment += '\n\t' + $(this).attr('class') + ': ' + $(this).html();
789                     });
790                     metaComment += '\n-->'
791
792                     var data = {
793                         name: $('#document-name').html(),
794                         text: metaComment + editor.getCode(),
795                         revision: $('#document-revision').html(),
796                         author: $('#username').html() || 'annonymous',
797                         comment: $('#komentarz').val()
798                     };
799
800                     $.ajax({
801                         url: document.location.href,
802                         type: "POST",
803                         dataType: "json",
804                         data: data,                
805                         success: function(data) {
806                             if (data.text) {
807                                 editor.setCode(data.text);
808                                 $('#document-revision').html(data.revision);
809                             } else {
810                                 alert(data.errors);
811                             }
812                             $.unblockUI();
813                         },
814                         error: function(xhr, textStatus, errorThrown) {
815                             alert('error: ' + textStatus + ' ' + errorThrown);
816                         },
817                     })
818                 }
819                 
820                 if ($('#simple-view-tab').hasClass('active')) {
821                     reverseTransform(editor, doSave);
822                 } else {
823                     doSave();
824                 }
825             });
826             
827             $('#save-cancel').click(function() {
828                 $.unblockUI();
829             });
830                                 
831             var tabs = $('ol#tabs li');
832                         
833                         tabs.click(function(event, callback) {
834                                 tabs.removeClass('active');
835                                 $('.editor').hide();
836                                 $(this).addClass('active');
837                                 $('#' + $(this).attr('ui:related')).show();                             
838                                 $(this).trigger('wl:tabload', callback);                                                                
839                         });     
840                         
841                         
842             $('#simple-view-tab').bind('wl:tabload', function(event, callback) {
843                 transform(editor, callback);
844             });
845                         
846                         $('#source-view-tab').bind('wl:tabload', function(event, callback) {
847                 reverseTransform(editor, callback);
848             });                                 
849                         
850                         $('#history-view-tab').bind('wl:tabload', function(event, callback) {
851                                 refreshHistory(callback);                                                               
852                         }); 
853                         
854                         $('#make-diff-button').click(historyDiff);
855
856             $('#source-editor .toolbar button').click(function(event) {
857                 event.preventDefault();
858                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
859                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
860             });                 
861
862             $('.toolbar select').change(function(event) {
863                 var slug = $(this).val();
864
865                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
866                 $(window).resize();
867             });
868
869             $('.toolbar-buttons-container').hide();
870             $('.toolbar select').change();
871
872                         
873                         $('#simple-view-tab').trigger('click', 
874                                 function() { 
875                                         $('#loading-overlay').fadeOut();
876                                         return false; 
877                                 });            
878         }
879     });
880     
881     $(window).resize(function() {
882         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
883     });
884     
885     $(window).resize();
886     
887     $('.vsplitbar').click(function() {
888         if ($('#sidebar').width() == 0) {
889             $('#sidebar').width(480).css({right: 0}).show();
890             $('#editor .editor').css({right: 495});
891             $('.vsplitbar').css({right: 480}).addClass('active');
892         } else {
893             $('#sidebar').width(0).hide();
894             $('#editor .editor').css({right: 15});
895             $('.vsplitbar').css({right: 0}).removeClass('active');
896         }
897         $(window).resize();
898     });
899                 
900
901 });