284fd197e4e97d012abfabb642d3dc55e0541b93
[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() {
115     CodeMirror.fromTextArea('id_text', {
116         parserfile: 'parsexml.js',
117         path: "/static/js/lib/codemirror/",
118         stylesheet: "/static/css/xmlcolors.css",
119         parserConfig: {
120             useHTMLKludges: false
121         },
122         iframeClass: 'xml-iframe',
123         textWrapping: true,
124         tabMode: 'spaces',
125         indentUnit: 0,
126         initCallback: function(editor) {
127             
128             function createXSLT(xsl) {
129                 var p = new XSLTProcessor();
130                 p.importStylesheet(xsl);
131                 return p;
132             }
133
134             function transform() {
135                 $.ajax({
136                     url: '/static/xsl/wl2html_client.xsl',
137                     dataType: 'xml',
138                     success: function(data) {
139                         var doc = null;
140                         var parser = new DOMParser();
141                         var serializer = new XMLSerializer();
142                         var htmlXSL = createXSLT(data);
143
144                         doc = editor.getCode().replace(/\/\s+/g, '<br />');
145                         doc = parser.parseFromString(doc, 'text/xml');
146                         console.log('xml', doc);
147                         doc = htmlXSL.transformToFragment(doc, document);
148                         console.log('after transform', doc);
149                         $('#html-view').html(doc.firstChild);
150                     },
151                     error: function() {alert('Error loading XSL!')}
152                 });        
153             };
154
155             function reverseTransform () {
156                 $.ajax({
157                     url: '/static/xsl/html2wl_client.xsl',
158                     dataType: 'xml',
159                     success: function(data) {
160                         var doc = null;
161                         var parser = new DOMParser();
162                         var serializer = new XMLSerializer();
163                         var xsl = createXSLT(data);
164
165                         doc = serializer.serializeToString($('#html-view div').get(0))
166                         doc = parser.parseFromString(doc, 'text/xml');
167                         console.log('xml',doc, doc.documentElement);
168                         // TODO: Sprawdzenie błędów
169                         doc = xsl.transformToDocument(doc);
170                         console.log('after transform', doc, doc.documentElement);
171                         doc = serialize(doc.documentElement).join('');
172                         // doc = serializer.serializeToString(doc.documentElement)
173                         editor.setCode(doc);
174                     },
175                     error: function() {alert('Error loading XSL!')}
176                 });
177             };
178
179             $('#save-button').click(function(event) {
180                 event.preventDefault();
181                 console.log(editor.getCode(), $('form input[name=text]').get(0));
182                 $('form textarea[name=text]').val(editor.getCode());
183                 $('form').ajaxSubmit(function() {
184                     alert('Udało się!');
185                 });
186             });
187
188             $('#simple-view-tab').click(function() {
189                 if ($(this).hasClass('active')) {
190                     return;
191                 }
192                 $(this).addClass('active');
193                 $('#source-view-tab').removeClass('active');
194                 $('#source-editor').hide();
195                 $('#simple-editor').show();
196                 transform();
197             });
198
199             $('#source-view-tab').click(function() {
200                 if ($(this).hasClass('active')) {
201                     return;
202                 }
203                 $(this).addClass('active');
204                 $('#simple-view-tab').removeClass('active');
205                 $('#simple-editor').hide();
206                 $('#source-editor').show();
207                 reverseTransform();
208             });
209
210             $('.toolbar button').click(function(event) {
211                 event.preventDefault();
212                 var params = eval("(" + $(this).attr('ui:action-params') + ")");
213                 scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
214             });
215
216             $('.toolbar select').change(function() {
217                 var slug = $(this).val();
218
219                 $('.toolbar-buttons-container').hide().filter('[data-group=' + slug + ']').show();
220                 $(window).resize();
221             });
222
223             $('.toolbar-buttons-container').hide();
224             $('.toolbar select').change();
225
226             var button = $('<button class="edit-button">Edytuj</button>');
227             $('#html-view').bind('mousemove', function(event) {
228                 var editable = $(event.target).closest('*[x-editable]');
229                 $('#html-view .active[x-editable]').not(editable).removeClass('active').children('.edit-button').remove();
230                 if (!editable.hasClass('active')) {
231                     editable.addClass('active').append(button);
232                 }
233             });
234
235             $('.motyw').live('click', function() {
236                 selectTheme($(this).attr('theme-class'));
237             });
238             
239             $('#simple-view-tab').click();
240             
241         }
242     });
243     
244     $(window).resize(function() {
245         $('iframe').height($(window).height() - $('#tabs').outerHeight() - $('#source-editor .toolbar').outerHeight());
246     });
247     
248     $(window).resize();
249     
250     $('.vsplitbar').click(function() {
251         if ($('#sidebar').width() == 0) {
252             $('#sidebar').width(480).show();
253             $('#source-editor, #simple-editor').css({right: 495});
254             $('.vsplitbar').css({right: 480})
255             // $('#splitter').trigger('resize', [$(window).width() - 480]);
256         } else {
257             $('#sidebar').width(0).hide();
258             $('#source-editor, #simple-editor').css({right: 15});
259             $('.vsplitbar').css({right: 0});
260             // $('#splitter').trigger('resize', [$(window).width()]);
261         }
262         $(window).resize();
263     });
264                 
265
266 });