Galeria z przeciąganiem obrazków.
[redakcja.git] / platforma / static / js / main.js
1 function serialize(element) {
2     if (element.nodeType == 3) { // tekst
3         return [$.trim(element.nodeValue)];
4     } else if (element.nodeType != 1) { // pomijamy węzły nie będące elementami XML ani tekstem
5         return [];
6     }
7     
8     var result = [];
9     var hasContent = false;
10     
11     result.push('<');
12     result.push(element.tagName);
13     
14     // Mozilla nie uważa deklaracji namespace za atrybuty
15     var ns = element.tagName.indexOf(':');
16     if (ns != -1 && $.browser.mozilla) {
17         result.push(' xmlns:');
18         result.push(element.tagName.substring(0, ns));
19         result.push('="');
20         result.push(element.namespaceURI);
21         result.push('"');
22     }
23     
24     if (element.attributes) {
25         for (var i=0; i < element.attributes.length; i++) {
26             var attr = element.attributes[i];
27             result.push(' ');
28             result.push(attr.name);
29             result.push('="');
30             result.push(attr.value);
31             result.push('"');
32             hasContent = true;
33         }
34     }
35     
36     if (element.childNodes.length == 0) {
37         result.push(' />');
38     } else {
39         result.push('>');
40
41         for (var i=0; i < element.childNodes.length; i++) {
42             result = result.concat(serialize(element.childNodes[i]));
43         }
44
45         result.push('</');
46         result.push(element.tagName);
47         result.push('>');
48     }
49     
50     if (element.tagName == 'akap' || element.tagName == 'akap_dialog' || element.tagName == 'akap_cd') {
51         result.push('\n\n\n');
52     } else if (element.tagName == 'rdf:RDF') {
53         result.push('\n\n\n\n\n');
54     } else if (element.tagName.indexOf('dc:') != -1) {
55         result.push('\n');
56     }
57     
58     return result;
59 };
60
61 function highlight(colour) {
62     var range, sel;
63     if (window.getSelection) {
64         // Non-IE case
65         sel = window.getSelection();
66         if (sel.getRangeAt) {
67             range = sel.getRangeAt(0);
68         }
69         document.designMode = "on";
70         if (range) {
71             sel.removeAllRanges();
72             sel.addRange(range);
73         }
74         // Use HiliteColor since some browsers apply BackColor to the whole block
75         if ( !document.execCommand("HiliteColor", false, colour) ) {
76             document.execCommand("BackColor", false, colour);
77         }
78         document.designMode = "off";
79     } else if (document.selection && document.selection.createRange) {
80         // IE case
81         range = document.selection.createRange();
82         range.execCommand("BackColor", false, colour);
83     }
84 }
85
86 function selectTheme(themeId)
87 {
88     var selection = window.getSelection();
89     
90     // remove current selection
91     selection.removeAllRanges();
92
93     var range = document.createRange();
94     var s = $(".motyw[theme-class='"+themeId+"']")[0];
95     var e = $(".end[theme-class='"+themeId+"']")[0];
96     // console.log('Selecting range:', themeId, range, s, e);
97     
98     if(s && e) {
99         range.setStartAfter(s);
100         range.setEndBefore(e);
101         selection.addRange(range);
102         // highlight('yellow');
103         // selection.removeAllRanges();
104     }
105 };
106
107 // function unselectThemes(themeId) {
108 //     $('.Apple-style-span').each(function() {
109 //         $(this).after($(this).html());
110 //         $(this).remove();
111 //     });
112 // }
113
114 function gallery(element) {
115     var element = $(element);
116     
117     function changePage(pageNumber) {        
118         $('img', element).attr('src', element.data('images')[pageNumber - 1]);
119     }
120     
121     function normalizeNumber(pageNumber) {
122         // Numer strony musi być pomiędzy 1 a najwyższym numerem
123         var pageCount = element.data('images').length;
124         pageNumber = parseInt(pageNumber, 10);
125         
126         if (!pageNumber || pageNumber == NaN || pageNumber == Infinity || pageNumber == -Infinity) {
127             return 1;
128         } else if (pageNumber < 1) {
129             return 1;
130         } else if (pageNumber > pageCount) {
131             return pageCount;
132         } else {
133             return pageNumber;
134         }
135     }
136     
137     $.ajax({
138         url: '/gallery/sample',
139         type: 'GET',
140         dataType: 'json',
141     
142         success: function(data) {
143             element.data('images', data);
144             var pn = $('.page-number', element);
145             pn.change(function(event) {
146                 console.log('change!', $(this).val());
147                 event.preventDefault();
148                 var n = normalizeNumber(pn.val());
149                 pn.val(n);
150                 changePage(n);
151             });
152             $('.previous-page', element).click(function() {
153                 pn.val(normalizeNumber(pn.val()) - 1);
154                 pn.change();
155             });
156             $('.next-page', element).click(function() {
157                 pn.val(normalizeNumber(pn.val()) + 1);
158                 pn.change();
159             });
160             
161             var image = $('img', element).attr('unselectable', 'on');
162             var origin = {};
163             var imageOrigin = {};
164             var imageDimensions = {};
165             
166             function onMouseMove(event) {
167                 var delta = {
168                     x: event.clientX - origin.x,
169                     y: event.clientY - origin.y
170                 };
171                 
172                 var newTop = Math.min(0, Math.max(imageOrigin.top + delta.y, imageDimensions.galleryHeight - imageDimensions.height));
173                 var newLeft = Math.min(0, Math.max(imageOrigin.left + delta.x, imageDimensions.galleryWidth - imageDimensions.width));
174                 image.css({position: 'absolute', top: newTop, left: newLeft});
175                 return false;
176             }
177             
178             function onMouseUp(event) {
179                 $(document)
180                     .unbind('mousemove.gallery')
181                     .unbind('mouseup.gallery');
182                 return false;
183             }
184             
185             image.bind('mousedown', function(event) {
186                 origin = {
187                     x: event.clientX,
188                     y: event.clientY
189                 };
190                 imageOrigin = image.position();
191                 imageDimensions = {
192                     width: image.width(),
193                     height: image.height(),
194                     galleryWidth: image.parent().width(),
195                     galleryHeight: image.parent().height()
196                 };
197                 $(document)
198                     .bind('mousemove.gallery', onMouseMove)
199                     .bind('mouseup.gallery', onMouseUp);
200                 return false;
201             });
202         }
203     });
204 }
205
206 $(function() {
207     gallery('#sidebar');
208     
209     CodeMirror.fromTextArea('id_text', {
210         parserfile: 'parsexml.js',
211         path: "/static/js/lib/codemirror/",
212         stylesheet: "/static/css/xmlcolors.css",
213         parserConfig: {
214             useHTMLKludges: false
215         },
216         iframeClass: 'xml-iframe',
217         textWrapping: true,
218         tabMode: 'spaces',
219         indentUnit: 0,
220         initCallback: function(editor) {
221             
222             function createXSLT(xsl) {
223                 var p = new XSLTProcessor();
224                 p.importStylesheet(xsl);
225                 return p;
226             }
227
228             function transform() {
229                 $.ajax({
230                     url: '/static/xsl/wl2html_client.xsl',
231                     dataType: 'xml',
232                     success: function(data) {
233                         var doc = null;
234                         var parser = new DOMParser();
235                         var serializer = new XMLSerializer();
236                         var htmlXSL = createXSLT(data);
237
238                         doc = editor.getCode().replace(/\/\s+/g, '<br />');
239                         doc = parser.parseFromString(doc, 'text/xml');
240                         console.log('xml', doc);
241                         doc = htmlXSL.transformToFragment(doc, document);
242                         console.log('after transform', doc);
243                         $('#html-view').html(doc.firstChild);
244                     },
245                     error: function() {alert('Error loading XSL!')}
246                 });        
247             };
248
249             function reverseTransform () {
250                 $.ajax({
251                     url: '/static/xsl/html2wl_client.xsl',
252                     dataType: 'xml',
253                     success: function(data) {
254                         var doc = null;
255                         var parser = new DOMParser();
256                         var serializer = new XMLSerializer();
257                         var xsl = createXSLT(data);
258
259                         doc = serializer.serializeToString($('#html-view div').get(0))
260                         doc = parser.parseFromString(doc, 'text/xml');
261                         console.log('xml',doc, doc.documentElement);
262                         // TODO: Sprawdzenie błędów
263                         doc = xsl.transformToDocument(doc);
264                         console.log('after transform', doc, doc.documentElement);
265                         doc = serialize(doc.documentElement).join('');
266                         // doc = serializer.serializeToString(doc.documentElement)
267                         editor.setCode(doc);
268                     },
269                     error: function() {alert('Error loading XSL!')}
270                 });
271             };
272
273             $('#save-button').click(function(event) {
274                 event.preventDefault();
275                 console.log(editor.getCode(), $('form input[name=text]').get(0));
276                 $('form textarea[name=text]').val(editor.getCode());
277                 $('form').ajaxSubmit(function() {
278                     alert('Udało się!');
279                 });
280             });
281
282             $('#simple-view-tab').click(function() {
283                 if ($(this).hasClass('active')) {
284                     return;
285                 }
286                 $(this).addClass('active');
287                 $('#source-view-tab').removeClass('active');
288                 $('#source-editor').hide();
289                 $('#simple-editor').show();
290                 transform();
291             });
292
293             $('#source-view-tab').click(function() {
294                 if ($(this).hasClass('active')) {
295                     return;
296                 }
297                 $(this).addClass('active');
298                 $('#simple-view-tab').removeClass('active');
299                 $('#simple-editor').hide();
300                 $('#source-editor').show();
301                 reverseTransform();
302             });
303
304             $('.toolbar button').click(function(event) {
305                 event.preventDefault();
306                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
307                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
308             });
309
310             $('.toolbar select').change(function() {
311                 var slug = $(this).val();
312
313                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
314                 $(window).resize();
315             });
316
317             $('.toolbar-buttons-container').hide();
318             $('.toolbar select').change();
319
320             var button = $('<button class="edit-button">Edytuj</button>');
321             $('#html-view').bind('mousemove', function(event) {
322                 var editable = $(event.target).closest('*[x-editable]');
323                 $('#html-view .active[x-editable]').not(editable).removeClass('active').children('.edit-button').remove();
324                 if (!editable.hasClass('active')) {
325                     editable.addClass('active').append(button);
326                 }
327             });
328
329             $('.motyw').live('click', function() {
330                 selectTheme($(this).attr('theme-class'));
331             });
332             
333             $('#simple-view-tab').click();
334             
335         }
336     });
337     
338     $(window).resize(function() {
339         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
340     });
341     
342     $(window).resize();
343     
344     $('.vsplitbar').click(function() {
345         if ($('#sidebar').width() == 0) {
346             $('#sidebar').width(480).css({right: 0}).show();
347             $('#source-editor, #simple-editor').css({right: 495});
348             $('.vsplitbar').css({right: 480})
349             // $('#splitter').trigger('resize', [$(window).width() - 480]);
350         } else {
351             $('#sidebar').width(0).hide();
352             $('#source-editor, #simple-editor').css({right: 15});
353             $('.vsplitbar').css({right: 0});
354             // $('#splitter').trigger('resize', [$(window).width()]);
355         }
356         $(window).resize();
357     });
358                 
359
360 });