Removed subversion files
[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: 53}, 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: 27}, 200);
158     });
159     $('.change-gallery-cancel', element).click(function() {
160         $('.gallery-image').animate({top: 27}, 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                 $('img', element).show();
273             },
274             
275             error: function(data) {
276                 element.data('images', []);
277                 pn.val(1);
278                 pn.change();
279                 $('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                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' + text + '</pre>');
305                 $.unblockUI();
306                 if (callback) {
307                     callback();
308                 }
309             }
310         });
311     }, 200);
312 };
313
314
315 function reverseTransform(editor, cont, errorCont, dontBlock) {
316     var serializer = new XMLSerializer();
317     if ($('#html-view .error').length > 0) {
318         if (errorCont) {
319             errorCont();
320         }
321         return;
322     }
323     if (!dontBlock) {
324         $.blockUI({message: 'Ładowanie...'});
325     }
326     setTimeout(function() {
327         html2xml({
328             xml: serializer.serializeToString($('#html-view div').get(0)),
329             success: function(text) {
330                 editor.setCode(text);
331                 if (!dontBlock) {
332                     $.unblockUI();
333                 }
334                 if (cont) {
335                     cont();
336                 }
337             }, error: function(text) {
338                 $('#source-editor').html('<p>Wystąpił błąd:</p><pre>' + text + '</pre>');
339                 if (!dontBlock) {
340                     $.unblockUI();
341                 }
342                 if (errorCont) {
343                     errorCont();
344                 }
345             }
346         });
347     }, 200);
348 }
349
350
351 // =============
352 // = HTML View =
353 // =============
354 function html(element) {
355     var element = $(element);
356     
357     function selectTheme(themeId)
358     {
359         var selection = window.getSelection();
360         selection.removeAllRanges();
361
362         var range = document.createRange();
363         var s = $(".motyw[theme-class='"+themeId+"']")[0];
364         var e = $(".end[theme-class='"+themeId+"']")[0];
365
366         if(s && e) {
367             range.setStartAfter(s);
368             range.setEndBefore(e);
369             selection.addRange(range);
370         }
371     };
372     
373     function verifyTagInsertPoint(node) {
374         if(node.nodeType == 3) { // Text Node
375             node = node.parentNode;
376         }
377
378         if (node.nodeType != 1) { 
379             return false;
380         }
381
382         node = $(node);
383         var xtype = node.attr('x-node');
384
385         if (!xtype || (xtype.search(':') >= 0) ||
386             xtype == 'motyw' || xtype == 'begin' || xtype == 'end') {
387             return false;
388         }
389         
390         // don't allow themes inside annotations
391         if( node.is('*[x-annotation-box] *') )
392             return false;
393
394         return true;
395     }
396     
397     function addAnnotation()
398     {
399         var selection = window.getSelection();
400         var n = selection.rangeCount;
401
402         if (n == 0) {
403             window.alert("Nie zaznaczono żadnego obszaru");
404             return false;
405         }
406
407         // for now allow only 1 range
408         if (n > 1) {
409             window.alert("Zaznacz jeden obszar");
410             return false;
411         }
412
413         // remember the selected range
414         var range = selection.getRangeAt(0);
415
416         if (!verifyTagInsertPoint(range.endContainer)) {
417             window.alert("Nie można wstawić w to miejsce przypisu.");
418             return false;
419         }
420
421         var text = range.toString();
422         var tag = $('<span></span>');
423         range.collapse(false);
424         range.insertNode(tag[0]);
425
426         xml2html({
427             xml: '<pr><slowo_obce>'+text+'</slowo_obce> --- </pr>',
428             success: function(text) {
429                 var t = $(text);
430                 tag.replaceWith(t);
431                 openForEdit(t);
432             },
433             error: function() {
434                 tag.remove();
435                 alert('Błąd przy dodawaniu przypisu:' + errors);                
436             }
437         })
438     }
439     
440     function addTheme()
441     {
442         var selection = window.getSelection();
443         var n = selection.rangeCount;
444
445         if(n == 0) {
446             window.alert("Nie zaznaczono żadnego obszaru");
447             return false;
448         }
449
450         // for now allow only 1 range
451         if(n > 1) {
452             window.alert("Zaznacz jeden obszar");
453             return false;
454         }
455
456         // remember the selected range
457         var range = selection.getRangeAt(0);
458
459         // verify if the start/end points make even sense -
460         // they must be inside a x-node (otherwise they will be discarded)
461         // and the x-node must be a main text
462         if (!verifyTagInsertPoint(range.startContainer)) {
463             window.alert("Motyw nie może się zaczynać w tym miejscu.");
464             return false;
465         }
466
467         if (!verifyTagInsertPoint(range.endContainer)) {
468             window.alert("Motyw nie może się kończyć w tym miejscu.");
469             return false;
470         }
471
472         var date = (new Date()).getTime();
473         var random = Math.floor(4000000000*Math.random());
474         var id = (''+date) + '-' + (''+random);
475
476         var spoint = document.createRange();
477         var epoint = document.createRange();
478
479         spoint.setStart(range.startContainer, range.startOffset);
480         epoint.setStart(range.endContainer, range.endOffset);
481
482         var mtag, btag, etag, errors;
483
484         // insert theme-ref
485                 
486         xml2html({
487             xml: '<end id="e'+id+'" />',
488             success: function(text) {
489                 etag = $('<span></span>');
490                 epoint.insertNode(etag[0]);
491                 etag.replaceWith(text);
492                 xml2html({
493                     xml: '<motyw id="m'+id+'"></motyw>',
494                     success: function(text) {
495                         mtag = $('<span></span>');
496                         spoint.insertNode(mtag[0]);
497                         mtag.replaceWith(text);
498                         xml2html({
499                             xml: '<begin id="b'+id+'" />',
500                             success: function(text) {
501                                 btag = $('<span></span>');
502                                 spoint.insertNode(btag[0])
503                                 btag.replaceWith(text);
504                                 selection.removeAllRanges();
505                                 openForEdit($('.motyw[theme-class=' + id + ']'));
506                             }
507                         });
508                     }
509                 });
510             }
511         });
512     }
513     
514     function openForEdit($origin)
515     {       
516         var $box = null
517     
518         // annotations overlay their sub box - not their own box //
519         if($origin.is(".annotation-inline-box")) {
520             $box = $("*[x-annotation-box]", $origin);
521         } else {
522             $box = $origin;
523         }
524         
525         var x = $box[0].offsetLeft;
526         var y = $box[0].offsetTop;
527         var w = $box.outerWidth();
528         var h = $box.innerHeight();
529     
530         if ($origin.is(".annotation-inline-box")) {
531             w = Math.max(w, 400);
532             h = Math.max(h, 60);
533         }
534         
535         // start edition on this node
536         var $overlay = $('<div class="html-editarea"><button class="accept-button">Zapisz</button><button class="delete-button">Usuń</button><textarea></textarea></div>').css({
537             position: 'absolute',
538             height: h,
539             left: x,
540             top: y,
541             width: w
542         }).appendTo($box[0].offsetParent || $box.parent()).show();
543         
544         if ($origin.is('.motyw')) {
545             $('textarea', $overlay).autocomplete(THEMES, {
546                 autoFill: true,
547                 multiple: true,
548                 selectFirst: true
549             });
550         }
551         
552         $('.delete-button', $overlay).click(function() {
553             if ($origin.is('.motyw')) {
554                 $('[theme-class=' + $origin.attr('theme-class') + ']').remove();
555             } else {
556                 $origin.remove();
557             }
558             $overlay.remove();
559             $(document).unbind('click.blur-overlay');
560             return false;
561         })
562         
563         
564         var serializer = new XMLSerializer();
565         
566         html2xml({
567             xml: serializer.serializeToString($box[0]),
568             inner: true,
569             success: function(text) {
570                 $('textarea', $overlay).val($.trim(text));
571                 
572                 setTimeout(function() {
573                     $('textarea', $overlay).elastic().focus();
574                 }, 50);
575                 
576                 function save(argument) {
577                     var nodeName = $box.attr('x-node') || 'pe';
578                     xml2html({
579                         xml: '<' + nodeName + '>' + $('textarea', $overlay).val() + '</' + nodeName + '>',
580                         success: function(element) {
581                             $box.html($(element).html());
582                             $overlay.remove();
583                         },
584                         error: function(text) {
585                             $overlay.remove();
586                             alert('Błąd! ' + text);
587                         }
588                     })
589                 }
590                 
591                 $('.accept-button', $overlay).click(function() {
592                     save();
593                 });
594                 
595                 $(document).bind('click.blur-overlay', function(event) {
596                     if ($(event.target).parents('.html-editarea').length > 0) {
597                         return;
598                     }
599                     save();
600                     
601                     $(document).unbind('click.blur-overlay');
602                 });
603                 
604             }, error: function(text) {
605                 alert('Błąd! ' + text);
606             }
607         });
608     }
609     
610     $('.edit-button').live('click', function(event) {
611         event.preventDefault();
612         openForEdit($(this).parent());
613     });
614     
615
616     
617     var button = $('<button class="edit-button">Edytuj</button>');
618     $(element).bind('mousemove', function(event) {
619         var editable = $(event.target).closest('*[x-editable]');
620         $('.active[x-editable]', element).not(editable).removeClass('active').children('.edit-button').remove();
621         if (!editable.hasClass('active')) {
622             editable.addClass('active').append(button);
623         }
624     });
625
626     $('.motyw').live('click', function() {
627         selectTheme($(this).attr('theme-class'));
628     });
629     
630     $('#insert-annotation-button').click(function() {
631         addAnnotation();
632         return false;
633     });
634     
635     $('#insert-theme-button').click(function() {
636         addTheme();
637         return false;
638     });
639 }
640
641
642 $(function() {
643     gallery('#sidebar', $('#document-meta .gallery').html());
644     html('#html-view');
645     
646     CodeMirror.fromTextArea('id_text', {
647         parserfile: 'parsexml.js',
648         path: STATIC_URL + "js/lib/codemirror/",
649         stylesheet: STATIC_URL + "css/xmlcolors.css",
650         parserConfig: {
651             useHTMLKludges: false
652         },
653         iframeClass: 'xml-iframe',
654         textWrapping: true,
655         tabMode: 'spaces',
656         indentUnit: 0,
657         initCallback: function(editor) {
658             $('#save-button').click(function(event) {
659                 event.preventDefault();
660                 $.blockUI({message: $('#save-dialog')});
661             });
662             
663             $('#save-ok').click(function() {
664                 $.blockUI({message: 'Zapisywanie...'});
665                 
666                 function doSave (argument) {
667                     var metaComment = '<!--';
668                     $('#document-meta div').each(function() {
669                         metaComment += '\n\t' + $(this).attr('class') + ': ' + $(this).html();
670                     });
671                     metaComment += '\n-->'
672
673                     var data = {
674                         name: $('#document-name').html(),
675                         text: metaComment + editor.getCode(),
676                         revision: $('#document-revision').html(),
677                         author: $('#username').html() || 'annonymous',
678                         comment: $('#komentarz').val()
679                     };
680
681                     $.ajax({
682                         url: document.location.href,
683                         type: "POST",
684                         dataType: "json",
685                         data: data,                
686                         success: function(data) {
687                             if (data.text) {
688                                 editor.setCode(data.text);
689                                 $('#document-revision').html(data.revision);
690                             } else {
691                                 alert(data.errors);
692                             }
693                             $.unblockUI();
694                         },
695                         error: function(xhr, textStatus, errorThrown) {
696                             alert('error: ' + textStatus + ' ' + errorThrown);
697                         },
698                     })
699                 }
700                 
701                 if ($('#simple-view-tab').hasClass('active')) {
702                     reverseTransform(editor, doSave);
703                 } else {
704                     doSave();
705                 }
706             });
707             
708             $('#save-cancel').click(function() {
709                 $.unblockUI();
710             });
711             
712             function changeTab(callback) {
713                 if ($('#simple-view-tab').hasClass('active')) {
714                     return;
715                 }
716                 $('#simple-view-tab').addClass('active');
717                 $('#source-view-tab').removeClass('active');
718                 $('#source-editor').hide();
719                 $('#simple-editor').show();
720                 transform(editor, callback);
721             }        
722             $('#simple-view-tab').click(function() { changeTab(); });
723             
724             $('#source-view-tab').click(function() { 
725                 if ($(this).hasClass('active')) {
726                     return;
727                 }
728                 $(this).addClass('active');
729                 $('#simple-view-tab').removeClass('active');
730                 $('#simple-editor').hide();
731                 $('#source-editor').show();
732                 reverseTransform(editor);    
733             });
734
735             $('#source-editor .toolbar button').click(function(event) {
736                 event.preventDefault();
737                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
738                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
739             });
740
741             $('.toolbar select').change(function() {
742                 var slug = $(this).val();
743
744                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
745                 $(window).resize();
746             });
747
748             $('.toolbar-buttons-container').hide();
749             $('.toolbar select').change();
750
751             changeTab(function() { $('#loading-overlay').fadeOut() }, function() { $('#loading-overlay').fadeOut() }, true)
752         }
753     });
754     
755     $(window).resize(function() {
756         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
757     });
758     
759     $(window).resize();
760     
761     $('.vsplitbar').click(function() {
762         if ($('#sidebar').width() == 0) {
763             $('#sidebar').width(480).css({right: 0}).show();
764             $('#source-editor, #simple-editor').css({right: 495});
765             $('.vsplitbar').css({right: 480}).addClass('active');
766         } else {
767             $('#sidebar').width(0).hide();
768             $('#source-editor, #simple-editor').css({right: 15});
769             $('.vsplitbar').css({right: 0}).removeClass('active');
770         }
771         $(window).resize();
772     });
773                 
774
775 });