No more js global variable platal_baseurl, use $.plURL() instead.
[platal.git] / htdocs / javascript / core.js
1 /***************************************************************************
2 * Copyright (C) 2003-2011 Polytechnique.org *
3 * http://opensource.polytechnique.org/ *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software *
17 * Foundation, Inc., *
18 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
19 ***************************************************************************/
20
21 // {{{ Assertion
22
23 // }}}
24 // {{{ jQuery object extension
25
26 (function($) {
27 function assert(condition, text) {
28 if ($.isFunction(condition)) {
29 condition = condition();
30 }
31 if (condition) {
32 return this;
33 }
34 if (!text) {
35 throw "Assertion failed";
36 } else {
37 throw "Assertion failed: " + text;
38 }
39 }
40
41
42 /* Add new functions to jQuery namesapce */
43 $.extend({
44 plURL: (function() {
45 var base;
46 return function(url) {
47 if (url.startsWith('http', true)) {
48 return url;
49 }
50 if (typeof base == 'undefined') {
51 base = $('head base');
52 if (base.length > 0) {
53 base = base.attr('href');
54 if (!base.endsWith('/')) {
55 base += '/';
56 }
57 } else {
58 base = '';
59 }
60 }
61 return base + url;
62 }
63 }()),
64
65 /* The goal of the following functions is to provide an AJAX API that
66 * take a different callback in case of HTTP success code (2XX) and in
67 * other cases.
68 */
69
70 xajax: function(source, method, data, onSuccess, onError, type) {
71 /* Shift argument */
72 if ($.isFunction(data)) {
73 type = type || onError;
74 onError = onSuccess;
75 onSuccess = data;
76 data = null;
77 }
78 if (onError != null && !$.isFunction(onError)) {
79 type = type || onError;
80 onError = null;
81 }
82
83 function ajaxHandler(data, textStatus, xhr) {
84 if (textStatus == 'success') {
85 if (onSuccess) {
86 onSuccess(data, textStatus, xhr);
87 }
88 } else if (textStatus == 'error') {
89 if (onError) {
90 onError(data, textStatus, xhr);
91 } else {
92 alert("Une error s'est produite lors du traitement de la requête.\n"
93 + "Ta session a peut-être expiré");
94 }
95 }
96 }
97 return $.ajax({
98 url: $.plURL(source),
99 type: method,
100 success: ajaxHandler,
101 data : data,
102 dataType: type
103 });
104 },
105
106 xget: function(source, data, onSuccess, onError, type) {
107 return $.xajax(source, 'GET', data, onSuccess, onError, type);
108 },
109
110 xgetJSON: function(source, data, onSuccess, onError) {
111 return $.xget(source, data, onSuccess, onError, 'json');
112 },
113
114 xgetScript: function(source, onSuccess, onError) {
115 return $.xget(source, null, onSuccess, onError, 'script');
116 },
117
118 xgetText: function(source, data, onSuccess, onError) {
119 return $.xget(source, data, onSuccess, onError, 'text');
120 },
121
122 xpost: function(source, data, onSuccess, onError, type) {
123 return $.xajax(source, 'POST', data, onSuccess, onError, type);
124 },
125
126 closeOnEsc: function() {
127 return $(window).keydown(function (e) {
128 if (e.keyCode == 27) {
129 window.close();
130 }
131 });
132 },
133
134 dynPost: function(action, key, value) {
135 var values;
136 if (!$.isArray(key)) {
137 values = { };
138 values[key] = value;
139 } else {
140 values = key;
141 }
142 var form = $('<form>', {
143 action: action,
144 method: 'post'
145 });
146 for (var k in values) {
147 $('<input>', {
148 type: 'hidden',
149 name: k,
150 value: values[k]
151 }).appendTo(form);
152 }
153 $('body').appendTo(form);
154 form.submit();
155 },
156
157 assert: assert
158 });
159
160 /* Add new functions to jQuery objects */
161 $.fn.extend({
162 tmpMessage: function(message, success) {
163 if (success) {
164 this.html("<img src='images/icons/wand.gif' alt='' /> " + message)
165 .css('color', 'green');
166 } else {
167 this.html("<img src='images/icons/error.gif' alt='' /> " + message)
168 .css('color', 'red');
169 }
170 return this.css('fontWeight', 'bold')
171 .show()
172 .delay(1000)
173 .fadeOut(500);
174 },
175
176 updateHtml: function(source, callback) {
177 var elements = this;
178 function handler(data) {
179 elements.html(data);
180 if (callback) {
181 callback(data);
182 }
183 }
184 $.xget(source, handler, 'text');
185 return this;
186 },
187
188 successMessage: function(source, message) {
189 var elements = this;
190 $.xget(source, function() {
191 elements.tmpMessage(message, true);
192 });
193 return this;
194 },
195
196 wiki: function(text, withTitle) {
197 if (text == '') {
198 return this.html('');
199 }
200 var url = 'wiki_preview';
201 if (!withTitle) {
202 url += '/notitile';
203 }
204 var $this = this;
205 $.post(url, { text: text },
206 function (data) {
207 $this.html(data);
208 }, 'text');
209 return this;
210 },
211
212 popWin: function(w, h) {
213 return this.click(function() {
214 window.open(this.href, '_blank',
215 'toolbar=0,location=0,directories=0,status=0,'
216 +'menubar=0,scrollbars=1,resizable=1,'
217 +'width='+w+',height='+h);
218 return false;
219 });
220 },
221
222 assert: assert,
223
224 assertLength: function(len) {
225 return this.assert(function() {
226 return $(this).length == len;
227 });
228 },
229
230 assertId: function(id) {
231 return this.assert(function() {
232 return $(this).attr('id') == id;
233 });
234 },
235
236 assertClass: function(clazz) {
237 return this.assert(function() {
238 return $(this).hasClass(clazz);
239 });
240 }
241 });
242 })(jQuery);
243
244 // }}}
245 // {{{ function RegExp.escape()
246
247 RegExp.escape = function(text) {
248 if (!arguments.callee.sRE) {
249 var specials = [
250 '/', '.', '*', '+', '?', '|',
251 '(', ')', '[', ']', '{', '}',
252 '\\', '^' , '$'
253 ];
254 arguments.callee.sRE = new RegExp(
255 '(\\' + specials.join('|\\') + ')', 'g'
256 );
257 }
258 return text.replace(arguments.callee.sRE, '\\$1');
259 }
260
261 // }}}
262 // {{{ String extension
263
264 String.prototype.startsWith = function(str, caseInsensitive) {
265 var cmp = this;
266
267 if (str.length > this.length) {
268 return false;
269 }
270 if (caseInsensitive) {
271 str = str.toLowerCase();
272 cmp = cmp.toLowerCase();
273 }
274 return cmp.substr(0, str.length) == str;
275 }
276
277 String.prototype.endsWith = function(str, caseInsensitive) {
278 var cmp = this;
279
280 if (str.length > this.length) {
281 return false;
282 }
283 if (caseInsensitive) {
284 str = str.toLowerCase();
285 cmp = cmp.toLowerCase();
286 }
287 return cmp.substr(cmp.length - str.length, str.length) == str;
288 }
289
290 String.prototype.htmlEntities = function() {
291 return this.replace(/&/g,'&amp;')
292 .replace(new RegExp('<','g'),'&lt;')
293 .replace(/>/g,'&gt;');
294 }
295
296 String.prototype.contains = function(str, caseInsensitive) {
297 var cmp = this;
298 if (str.length > this.length) {
299 return false;
300 }
301 if (caseInsensitive) {
302 str = str.toLowerCase();
303 cmp = cmp.toLowerCase();
304 }
305 return cmp.indexOf(str) >= 0;
306 }
307
308 // }}}
309 // {{{ PmWiki decoding
310
311 Nix = {
312 map: null,
313 convert: function(a) {
314 Nix.init();
315 var s = '';
316 for (i = 0; i < a.length ; i++) {
317 var b = a.charAt(i);
318 s += ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') ? Nix.map[b] : b);
319 }
320 return s;
321 },
322 init: function() {
323 if (Nix.map != null)
324 return;
325 var map = new Array();
326 var s='abcdefghijklmnopqrstuvwxyz';
327 for (i = 0; i < s.length; i++)
328 map[s.charAt(i)] = s.charAt((i+13)%26);
329 for (i=0; i<s.length; i++)map[s.charAt(i).toUpperCase()] = s.charAt((i+13)%26).toUpperCase();
330 Nix.map = map;
331 },
332 decode: function(a) {
333 document.write(Nix.convert(a));
334 }
335 }
336
337 // }}}
338 // {{{ preview wiki
339
340 function previewWiki(idFrom, idTo, withTitle, idShow)
341 {
342 $('#' + idTo).wiki($('#' + idFrom).val(), withTitle);
343 if (idShow != null) {
344 $('#' + idShow).show();
345 }
346 }
347
348 // }}}
349
350 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: