75e3746fef3c91232280380755d24a7da047890f
[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                             console.log('xml', doc);
341                             doc = htmlXSL.transformToFragment(doc, document);
342                             console.log('after transform', doc);
343                             $('#html-view').html(doc.firstChild);
344                             $('#simple-editor').unblock();
345                         },
346                         error: function() {alert('Error loading XSL!')}
347                     });
348                 }, 200);
349             };
350
351             function reverseTransform () {
352                 $('#source-editor').block({message: 'Ładowanie...'});
353                 setTimeout(function() {
354                     $.ajax({
355                         url: '/static/xsl/html2wl_client.xsl',
356                         dataType: 'xml',
357                         success: function(data) {
358                             var doc = null;
359                             var parser = new DOMParser();
360                             var serializer = new XMLSerializer();
361                             var xsl = createXSLT(data);
362
363                             doc = serializer.serializeToString($('#html-view div').get(0))
364                             doc = parser.parseFromString(doc, 'text/xml');
365                             console.log('xml',doc, doc.documentElement);
366                             // TODO: Sprawdzenie błędów
367                             doc = xsl.transformToDocument(doc);
368                             console.log('after transform', doc, doc.documentElement);
369                             doc = serialize(doc.documentElement).join('');
370                             // doc = serializer.serializeToString(doc.documentElement)
371                             editor.setCode(doc);
372                             $('#source-editor').unblock();
373                         },
374                         error: function() {alert('Error loading XSL!')}
375                     });                    
376                 }, 200);
377             };
378
379             $('#save-button').click(function(event) {
380                 event.preventDefault();
381                 $.blockUI({message: $('#save-dialog')});
382             });
383             
384             $('#save-ok').click(function() {
385                 $.blockUI({message: 'Zapisywanie...'});
386                 
387                 var data = {
388                     name: $('#document-name').html(),
389                     text: editor.getCode(),
390                     revision: $('#document-revision').html(),
391                     author: 'annonymous',
392                     comment: $('#komentarz').val()
393                 };
394                 
395                 console.log(data);
396                 
397                 $.ajax({
398                     url: document.location.href,
399                     type: "POST",
400                     dataType: "json",
401                     data: data,                
402                     success: function(data) {
403                         if (data.text) {
404                             editor.setCode(data.text);
405                             $('#document-revision').html(data.revision);
406                         } else {
407                             console.log(data.errors);
408                             alert(data.errors);
409                         }
410                         $.unblockUI();
411                     },
412                     error: function(xhr, textStatus, errorThrown) {
413                         alert('error: ' + textStatus + ' ' + errorThrown);
414                     },
415                 })
416             });
417             
418             $('#save-cancel').click(function() {
419                 $.unblockUI();
420             });
421
422             $('#simple-view-tab').click(function() {
423                 if ($(this).hasClass('active')) {
424                     return;
425                 }
426                 $(this).addClass('active');
427                 $('#source-view-tab').removeClass('active');
428                 $('#source-editor').hide();
429                 $('#simple-editor').show();
430                 transform();
431             });
432
433             $('#source-view-tab').click(function() {
434                 if ($(this).hasClass('active')) {
435                     return;
436                 }
437                 $(this).addClass('active');
438                 $('#simple-view-tab').removeClass('active');
439                 $('#simple-editor').hide();
440                 $('#source-editor').show();
441                 reverseTransform();
442             });
443
444             $('.toolbar button').click(function(event) {
445                 event.preventDefault();
446                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
447                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
448             });
449
450             $('.toolbar select').change(function() {
451                 var slug = $(this).val();
452
453                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
454                 $(window).resize();
455             });
456
457             $('.toolbar-buttons-container').hide();
458             $('.toolbar select').change();
459
460             $('#simple-view-tab').click();
461         }
462     });
463     
464     $(window).resize(function() {
465         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
466     });
467     
468     $(window).resize();
469     
470     $('.vsplitbar').click(function() {
471         if ($('#sidebar').width() == 0) {
472             $('#sidebar').width(480).css({right: 0}).show();
473             $('#source-editor, #simple-editor').css({right: 495});
474             $('.vsplitbar').css({right: 480}).addClass('active');
475             // $('#splitter').trigger('resize', [$(window).width() - 480]);
476         } else {
477             $('#sidebar').width(0).hide();
478             $('#source-editor, #simple-editor').css({right: 15});
479             $('.vsplitbar').css({right: 0}).removeClass('active');
480             // $('#splitter').trigger('resize', [$(window).width()]);
481         }
482         $(window).resize();
483     });
484                 
485
486 });