ff0d626b8507531cb6db85edd8a88472845b827f
[redakcja.git] / platforma / static / js / main.js
1 // Serializuje XML, wstawiając odpowiednie ilości białych znaków między elementami
2 function serialize(element) {
3     if (element.nodeType == 3) { // tekst
4         return [$.trim(element.nodeValue)];
5     } else if (element.nodeType != 1) { // pomijamy węzły nie będące elementami XML ani tekstem
6         return [];
7     }
8     
9     var result = [];
10     var hasContent = false;
11     
12     result.push('<');
13     result.push(element.tagName);
14     
15     // Mozilla nie uważa deklaracji namespace za atrybuty
16     var ns = element.tagName.indexOf(':');
17     if (ns != -1 && $.browser.mozilla) {
18         result.push(' xmlns:');
19         result.push(element.tagName.substring(0, ns));
20         result.push('="');
21         result.push(element.namespaceURI);
22         result.push('"');
23     }
24     
25     if (element.attributes) {
26         for (var i=0; i < element.attributes.length; i++) {
27             var attr = element.attributes[i];
28             result.push(' ');
29             result.push(attr.name);
30             result.push('="');
31             result.push(attr.value);
32             result.push('"');
33             hasContent = true;
34         }
35     }
36     
37     if (element.childNodes.length == 0) {
38         result.push(' />');
39     } else {
40         result.push('>');
41
42         for (var i=0; i < element.childNodes.length; i++) {
43             result = result.concat(serialize(element.childNodes[i]));
44         }
45
46         result.push('</');
47         result.push(element.tagName);
48         result.push('>');
49     }
50     
51     if (element.tagName == 'akap' || element.tagName == 'akap_dialog' || element.tagName == 'akap_cd' || element.tagName == 'strofa') {
52         result.push('\n\n\n');
53     } else if (element.tagName == 'naglowek_rozdzial') {
54         result.push('\n\n');
55     } else if (element.tagName == 'rdf:RDF') {
56         result.push('\n\n\n\n\n');
57     } else if (element.tagName.indexOf('dc:') != -1) {
58         result.push('\n');
59     }
60     
61     return result;
62 };
63
64
65 // Teraz nieużywane
66 function highlight(colour) {
67     var range, sel;
68     if (window.getSelection) {
69         // Non-IE case
70         sel = window.getSelection();
71         if (sel.getRangeAt) {
72             range = sel.getRangeAt(0);
73         }
74         document.designMode = "on";
75         if (range) {
76             sel.removeAllRanges();
77             sel.addRange(range);
78         }
79         // Use HiliteColor since some browsers apply BackColor to the whole block
80         if ( !document.execCommand("HiliteColor", false, colour) ) {
81             document.execCommand("BackColor", false, colour);
82         }
83         document.designMode = "off";
84     } else if (document.selection && document.selection.createRange) {
85         // IE case
86         range = document.selection.createRange();
87         range.execCommand("BackColor", false, colour);
88     }
89 }
90
91 // function unselectThemes(themeId) {
92 //     $('.Apple-style-span').each(function() {
93 //         $(this).after($(this).html());
94 //         $(this).remove();
95 //     });
96 // }
97
98 function gallery(element) {
99     var element = $(element);
100     var imageDimensions = {};
101     
102     function changePage(pageNumber) {        
103         $('img', element).attr('src', element.data('images')[pageNumber - 1]);
104     }
105     
106     function normalizeNumber(pageNumber) {
107         // Numer strony musi być pomiędzy 1 a najwyższym numerem
108         var pageCount = element.data('images').length;
109         pageNumber = parseInt(pageNumber, 10);
110         
111         if (!pageNumber || pageNumber == NaN || pageNumber == Infinity || pageNumber == -Infinity) {
112             return 1;
113         } else if (pageNumber < 1) {
114             return 1;
115         } else if (pageNumber > pageCount) {
116             return pageCount;
117         } else {
118             return pageNumber;
119         }
120     }
121     
122     $.ajax({
123         url: '/gallery/sample',
124         type: 'GET',
125         dataType: 'json',
126     
127         success: function(data) {
128             element.data('images', data);
129             var pn = $('.page-number', element);
130             pn.change(function(event) {
131                 console.log('change!', $(this).val());
132                 event.preventDefault();
133                 var n = normalizeNumber(pn.val());
134                 pn.val(n);
135                 changePage(n);
136             });
137             $('.previous-page', element).click(function() {
138                 pn.val(normalizeNumber(pn.val()) - 1);
139                 pn.change();
140             });
141             $('.next-page', element).click(function() {
142                 pn.val(normalizeNumber(pn.val()) + 1);
143                 pn.change();
144             });
145             
146             
147             var image = $('img', element).attr('unselectable', 'on');
148             var origin = {};
149             var imageOrigin = {};
150             var zoomFactor = 1;
151             
152             $('.zoom-in', element).click(function() {
153                 zoomFactor = Math.min(2, zoomFactor + 0.2);
154                 zoom();
155             });
156             $('.zoom-out', element).click(function() {
157                 zoomFactor = Math.max(0.2, zoomFactor - 0.2);
158                 zoom();
159             });
160             
161             $('img', element).load(function() {
162                 image.css({width: null, height: null});
163                 imageDimensions = {
164                     width: $(this).width() * zoomFactor,
165                     height: $(this).height() * zoomFactor,
166                     originWidth: $(this).width(),
167                     originHeight: $(this).height(),
168                     galleryWidth: $(this).parent().width(),
169                     galleryHeight: $(this).parent().height()
170                 };
171                 console.log('load', imageDimensions)
172                 var position = normalizePosition(
173                     image.position().left,
174                     image.position().top, 
175                     imageDimensions.galleryWidth,
176                     imageDimensions.galleryHeight,
177                     imageDimensions.width,
178                     imageDimensions.height
179                 );
180                 image.css({left: position.x, top: position.y, width: $(this).width() * zoomFactor, height: $(this).height() * zoomFactor});
181             });
182
183             $(window).resize(function() {
184                 imageDimensions.galleryWidth = image.parent().width();
185                 imageDimensions.galleryHeight = image.parent().height();
186             });
187             
188             function bounds(galleryWidth, galleryHeight, imageWidth, imageHeight) {
189                 return {
190                     maxX: 0,
191                     maxY: 0,
192                     minX: galleryWidth - imageWidth,
193                     minY: galleryHeight - imageHeight
194                 }
195             }
196             
197             function normalizePosition(x, y, galleryWidth, galleryHeight, imageWidth, imageHeight) {
198                 var b = bounds(galleryWidth, galleryHeight, imageWidth, imageHeight);
199                 return {
200                     x: Math.min(b.maxX, Math.max(b.minX, x)),
201                     y: Math.min(b.maxY, Math.max(b.minY, y))
202                 }
203             }
204             
205             function onMouseMove(event) {
206                 var position = normalizePosition(
207                     event.clientX - origin.x + imageOrigin.left,
208                     event.clientY - origin.y + imageOrigin.top, 
209                     imageDimensions.galleryWidth,
210                     imageDimensions.galleryHeight,
211                     imageDimensions.width,
212                     imageDimensions.height
213                 );
214                 image.css({position: 'absolute', top: position.y, left: position.x});
215                 return false;
216             }
217             
218             function setZoom(factor) {
219                 zoomFactor = factor;
220             }
221             
222             function zoom() {
223                 imageDimensions.width = imageDimensions.originWidth * zoomFactor;
224                 imageDimensions.height = imageDimensions.originHeight * zoomFactor;
225                 var position = normalizePosition(
226                     image.position().left,
227                     image.position().top, 
228                     imageDimensions.galleryWidth,
229                     imageDimensions.galleryHeight,
230                     imageDimensions.width,
231                     imageDimensions.height
232                 );
233                 console.log(image.position(), imageDimensions, position);
234                 image.css({width: imageDimensions.width, height: imageDimensions.height,
235                     left: position.x, top: position.y});
236
237             }
238             
239             window.setZoom = setZoom;
240             
241             function onMouseUp(event) {
242                 $(document)
243                     .unbind('mousemove.gallery')
244                     .unbind('mouseup.gallery');
245                 return false;
246             }
247             
248             image.bind('mousedown', function(event) {
249                 origin = {
250                     x: event.clientX,
251                     y: event.clientY
252                 };
253                 imageOrigin = image.position();
254                 $(document)
255                     .bind('mousemove.gallery', onMouseMove)
256                     .bind('mouseup.gallery', onMouseUp);
257                 return false;
258             });
259         }
260     });
261 }
262
263
264 function html(element) {
265     var element = $(element);
266     
267     function selectTheme(themeId)
268     {
269         var selection = window.getSelection();
270
271         // remove current selection
272         selection.removeAllRanges();
273
274         var range = document.createRange();
275         var s = $(".motyw[theme-class='"+themeId+"']")[0];
276         var e = $(".end[theme-class='"+themeId+"']")[0];
277         // console.log('Selecting range:', themeId, range, s, e);
278
279         if(s && e) {
280             range.setStartAfter(s);
281             range.setEndBefore(e);
282             selection.addRange(range);
283             // highlight('yellow');
284             // selection.removeAllRanges();
285         }
286     };
287     
288     var button = $('<button class="edit-button">Edytuj</button>');
289     $(element).bind('mousemove', function(event) {
290         var editable = $(event.target).closest('*[x-editable]');
291         $('.active[x-editable]', element).not(editable).removeClass('active').children('.edit-button').remove();
292         if (!editable.hasClass('active')) {
293             editable.addClass('active').append(button);
294         }
295     });
296
297     $('.motyw').live('click', function() {
298         selectTheme($(this).attr('theme-class'));
299     });
300 }
301
302
303 $(function() {
304     gallery('#sidebar');
305     html('#html-view');
306     
307     CodeMirror.fromTextArea('id_text', {
308         parserfile: 'parsexml.js',
309         path: "/static/js/lib/codemirror/",
310         stylesheet: "/static/css/xmlcolors.css",
311         parserConfig: {
312             useHTMLKludges: false
313         },
314         iframeClass: 'xml-iframe',
315         textWrapping: true,
316         tabMode: 'spaces',
317         indentUnit: 0,
318         initCallback: function(editor) {
319             
320             function createXSLT(xsl) {
321                 var p = new XSLTProcessor();
322                 p.importStylesheet(xsl);
323                 return p;
324             }
325
326             function transform() {
327                 $('#simple-editor').block({message: 'Ładowanie...'});
328                 setTimeout(function() {
329                     $.ajax({
330                         url: '/static/xsl/wl2html_client.xsl',
331                         dataType: 'xml',
332                         success: function(data) {
333                             var doc = null;
334                             var parser = new DOMParser();
335                             var serializer = new XMLSerializer();
336                             var htmlXSL = createXSLT(data);
337
338                             doc = editor.getCode().replace(/\/\s+/g, '<br />');
339                             doc = parser.parseFromString(doc, 'text/xml');
340                             var error = $('parsererror', doc);
341                             console.log(error);
342                             if (error.length == 0) {
343                                 doc = htmlXSL.transformToFragment(doc, document);
344                                 error = $('parsererror', doc);
345                             }
346                             console.log('xml', doc);
347                             if (error.length > 0) {
348                                 console.log(error);
349                                 $('#html-view').html('<p class="error">Wystąpił błąd:</p><pre>' + error.text() + '</pre>');
350                             } else {
351                                 console.log('after transform', doc);
352                                 $('#html-view').html(doc.firstChild);                          
353                             }
354
355                             $('#simple-editor').unblock();
356                         },
357                         error: function() {alert('Error loading XSL!')}
358                     });
359                 }, 200);
360             };
361
362             function reverseTransform () {
363                 $('#source-editor').block({message: 'Ładowanie...'});
364                 setTimeout(function() {
365                     $.ajax({
366                         url: '/static/xsl/html2wl_client.xsl',
367                         dataType: 'xml',
368                         success: function(data) {
369                             var doc = null;
370                             var parser = new DOMParser();
371                             var serializer = new XMLSerializer();
372                             var xsl = createXSLT(data);
373
374                             if ($('#html-view .error').length > 0) {
375                                 $('#source-editor').unblock();
376                                 return;
377                             }
378                             doc = serializer.serializeToString($('#html-view div').get(0))
379                             doc = parser.parseFromString(doc, 'text/xml');
380                             console.log('xml',doc, doc.documentElement);
381                             // TODO: Sprawdzenie błędów
382                             var error = $('parsererror', doc.documentElement);
383                             console.log(error);
384                             if (error.length == 0) {
385                                 doc = xsl.transformToDocument(doc, document);
386                                 error = $('parsererror', doc.documentElement);
387                             }
388                             
389                             if (error.length > 0) {
390                                 console.log(error);
391                                 $('#source-editor').html('<p>Wystąpił błąd:</p>' + error.text());
392                             } else {
393                                 doc = serialize(doc.documentElement).join('');
394                                 editor.setCode(doc);                                
395                             }
396                             
397                             console.log('after transform', doc, doc.documentElement);
398                             $('#source-editor').unblock();
399                         },
400                         error: function() {alert('Error loading XSL!')}
401                     });                    
402                 }, 200);
403             };
404
405             $('#save-button').click(function(event) {
406                 event.preventDefault();
407                 $.blockUI({message: $('#save-dialog')});
408             });
409             
410             $('#save-ok').click(function() {
411                 $.blockUI({message: 'Zapisywanie...'});
412                 
413                 var data = {
414                     name: $('#document-name').html(),
415                     text: editor.getCode(),
416                     revision: $('#document-revision').html(),
417                     author: 'annonymous',
418                     comment: $('#komentarz').val()
419                 };
420                 
421                 console.log(data);
422                 
423                 $.ajax({
424                     url: document.location.href,
425                     type: "POST",
426                     dataType: "json",
427                     data: data,                
428                     success: function(data) {
429                         if (data.text) {
430                             editor.setCode(data.text);
431                             $('#document-revision').html(data.revision);
432                         } else {
433                             console.log(data.errors);
434                             alert(data.errors);
435                         }
436                         $.unblockUI();
437                     },
438                     error: function(xhr, textStatus, errorThrown) {
439                         alert('error: ' + textStatus + ' ' + errorThrown);
440                     },
441                 })
442             });
443             
444             $('#save-cancel').click(function() {
445                 $.unblockUI();
446             });
447
448             $('#simple-view-tab').click(function() {
449                 if ($(this).hasClass('active')) {
450                     return;
451                 }
452                 $(this).addClass('active');
453                 $('#source-view-tab').removeClass('active');
454                 $('#source-editor').hide();
455                 $('#simple-editor').show();
456                 transform();
457             });
458
459             $('#source-view-tab').click(function() {
460                 if ($(this).hasClass('active')) {
461                     return;
462                 }
463                 $(this).addClass('active');
464                 $('#simple-view-tab').removeClass('active');
465                 $('#simple-editor').hide();
466                 $('#source-editor').show();
467                 reverseTransform();
468             });
469
470             $('.toolbar button').click(function(event) {
471                 event.preventDefault();
472                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
473                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
474             });
475
476             $('.toolbar select').change(function() {
477                 var slug = $(this).val();
478
479                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
480                 $(window).resize();
481             });
482
483             $('.toolbar-buttons-container').hide();
484             $('.toolbar select').change();
485
486             $('#simple-view-tab').click();
487         }
488     });
489     
490     $(window).resize(function() {
491         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
492     });
493     
494     $(window).resize();
495     
496     $('.vsplitbar').click(function() {
497         if ($('#sidebar').width() == 0) {
498             $('#sidebar').width(480).css({right: 0}).show();
499             $('#source-editor, #simple-editor').css({right: 495});
500             $('.vsplitbar').css({right: 480}).addClass('active');
501             // $('#splitter').trigger('resize', [$(window).width() - 480]);
502         } else {
503             $('#sidebar').width(0).hide();
504             $('#source-editor, #simple-editor').css({right: 15});
505             $('.vsplitbar').css({right: 0}).removeClass('active');
506             // $('#splitter').trigger('resize', [$(window).width()]);
507         }
508         $(window).resize();
509     });
510                 
511
512 });