cec5e22956c04d9699a8dc251518d8b9743fb0f4
[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                 // console.log(editor.getCode(), $('form input[name=text]').get(0));
384                 //                 $('form textarea[name=text]').val(editor.getCode());
385                 //                 $('form').ajaxSubmit(function() {
386                 //                     alert('Udało się!');
387                 //                 });
388             });
389             
390             $('#save-ok').click(function() {
391                 $.blockUI({message: 'Zapisywanie...'});
392                 
393                 var data = {
394                     name: $('#document-name').html(),
395                     text: editor.getCode(),
396                     revision: $('#document-revision').html(),
397                     author: 'annonymous',
398                     comment: $('#komentarz').val()
399                 };
400                 
401                 console.log(data);
402                 
403                 $.ajax({
404                     url: document.location.href,
405                     type: "POST",
406                     dataType: "html",
407                     data: data,                
408                     success: function() {
409                         $.unblockUI();
410                     },
411                     error: function(xhr, textStatus, errorThrown) {
412                         alert('error: ' + textStatus + ' ' + errorThrown);
413                     },
414                 })
415             });
416
417             $('#simple-view-tab').click(function() {
418                 if ($(this).hasClass('active')) {
419                     return;
420                 }
421                 $(this).addClass('active');
422                 $('#source-view-tab').removeClass('active');
423                 $('#source-editor').hide();
424                 $('#simple-editor').show();
425                 transform();
426             });
427
428             $('#source-view-tab').click(function() {
429                 if ($(this).hasClass('active')) {
430                     return;
431                 }
432                 $(this).addClass('active');
433                 $('#simple-view-tab').removeClass('active');
434                 $('#simple-editor').hide();
435                 $('#source-editor').show();
436                 reverseTransform();
437             });
438
439             $('.toolbar button').click(function(event) {
440                 event.preventDefault();
441                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
442                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
443             });
444
445             $('.toolbar select').change(function() {
446                 var slug = $(this).val();
447
448                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
449                 $(window).resize();
450             });
451
452             $('.toolbar-buttons-container').hide();
453             $('.toolbar select').change();
454
455             $('#simple-view-tab').click();
456         }
457     });
458     
459     $(window).resize(function() {
460         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
461     });
462     
463     $(window).resize();
464     
465     $('.vsplitbar').click(function() {
466         if ($('#sidebar').width() == 0) {
467             $('#sidebar').width(480).css({right: 0}).show();
468             $('#source-editor, #simple-editor').css({right: 495});
469             $('.vsplitbar').css({right: 480}).addClass('active');
470             // $('#splitter').trigger('resize', [$(window).width() - 480]);
471         } else {
472             $('#sidebar').width(0).hide();
473             $('#source-editor, #simple-editor').css({right: 15});
474             $('.vsplitbar').css({right: 0}).removeClass('active');
475             // $('#splitter').trigger('resize', [$(window).width()]);
476         }
477         $(window).resize();
478     });
479                 
480
481 });