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