~azzar1/unity/add-show-desktop-key

171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
1
/* IVLE - Informatics Virtual Learning Environment
2
 * Copyright (C) 2007-2008 The University of Melbourne
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 2 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program; if not, write to the Free Software
16
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
 *
18
 * Module: JavaScript Utilities
19
 * Author: Matt Giuca
20
 * Date: 11/1/2008
21
 *
22
 * Defines some generic JavaScript utility functions.
23
 */
24
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
25
/* Expects the following variables to have been declared by JavaScript in
26
 * the HTML generated by the server:
27
 * - root_dir
28
 * - username
29
 */
30
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
31
/** Removes all children of a given DOM element
32
 * \param elem A DOM Element. Will be modified.
33
 */
34
function dom_removechildren(elem)
35
{
36
    while (elem.lastChild != null)
37
        elem.removeChild(elem.lastChild);
38
}
39
40
/** Creates a DOM element with simple text inside it.
41
 * \param tagname String. Name of the element's tag (eg. "p").
42
 * \param text String. Text to be placed inside the element.
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
43
 * \param title String, optional. Tooltip for the text.
44
 *  (Note, title creates a span element around the text).
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
45
 * \return DOM Element object.
46
 */
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
47
function dom_make_text_elem(tagname, text, title)
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
48
{
188 by mattgiuca
browser.js: Can now (shakily) handle directory listings. (lots of code!)
49
    if (text == null) text = "";
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
50
    var elem = document.createElement(tagname);
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
51
    var textnode;
52
    if (title == null)
53
        textnode = document.createTextNode(text);
54
    else
55
    {
56
        textnode = document.createElement("span");
57
        textnode.setAttribute("title", title);
58
        textnode.appendChild(document.createTextNode(text));
59
    }
60
    elem.appendChild(textnode);
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
61
    return elem;
62
}
63
64
/** Creates a DOM element with hyperlinked text inside it.
65
 * \param tagname String. Name of the element's tag (eg. "p").
66
 * \param text String. Text to be placed inside the element.
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
67
 * \param title String, optional. Sets a tooltip for the link.
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
68
 * \param href String. URL the text will link to. This is a raw string,
69
 *  it will automatically be URL-encoded.
70
 * \param onclick Optional string. Will be set as the "onclick" attribute
71
 *  of the "a" element.
241 by mattgiuca
util.js: dom_make_link_elem: Added argument dontencode, necessary to sometimes
72
 * \param dontencode Optional boolean. If true, will not encode the href.
73
 *  if including query strings, you must set this to true and use build_url
74
 *  to escape the URI correctly.
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
75
 * \return DOM Element object.
76
 */
241 by mattgiuca
util.js: dom_make_link_elem: Added argument dontencode, necessary to sometimes
77
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
78
{
188 by mattgiuca
browser.js: Can now (shakily) handle directory listings. (lots of code!)
79
    if (text == null) text = "";
80
    if (href == null) href = "";
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
81
    var elem = document.createElement(tagname);
82
    var link = document.createElement("a");
241 by mattgiuca
util.js: dom_make_link_elem: Added argument dontencode, necessary to sometimes
83
    if (dontencode != true)
84
        href = urlencode_path(href);
85
    link.setAttribute("href", href);
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
86
    if (title != null)
87
        link.setAttribute("title", title);
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
88
    if (onclick != null)
89
        link.setAttribute("onclick", onclick);
90
    link.appendChild(document.createTextNode(text));
91
    elem.appendChild(link);
92
    return elem;
93
}
94
190 by mattgiuca
util: Added function dom_make_img, creates <img> elements.
95
/** Creates a DOM img element. All parameters are optional except src.
96
 * If alt (compulsory in HTML) is omitted, will be set to "".
97
 */
98
function dom_make_img(src, width, height, title, alt)
99
{
100
    var img = document.createElement("img");
234 by mattgiuca
browser/listing.js:
101
    img.setAttribute("src", urlencode_path(src));
190 by mattgiuca
util: Added function dom_make_img, creates <img> elements.
102
    if (width != null)
103
        img.setAttribute("width", width);
104
    if (height != null)
105
        img.setAttribute("height", height);
106
    if (title != null)
107
        img.setAttribute("title", title);
108
    if (alt == null) alt = "";
109
    img.setAttribute("alt", alt);
110
    return img;
111
}
112
180 by mattgiuca
util: Added function nice_filesize.
113
/** Given a number of bytes, returns a string representing the file size in a
114
 * human-readable format.
115
 * eg. nice_filesize(6) -> "6 bytes"
116
 *     nice_filesize(81275) -> "79.4 kB"
117
 *     nice_filesize(13498346) -> "12.9 MB"
118
 * \param bytes Number of bytes. Must be an integer.
119
 * \return String.
120
 */
121
function nice_filesize(bytes)
122
{
188 by mattgiuca
browser.js: Can now (shakily) handle directory listings. (lots of code!)
123
    if (bytes == null) return "";
180 by mattgiuca
util: Added function nice_filesize.
124
    var size;
125
    if (bytes < 1024)
188 by mattgiuca
browser.js: Can now (shakily) handle directory listings. (lots of code!)
126
        return bytes.toString() + " B";
180 by mattgiuca
util: Added function nice_filesize.
127
    size = bytes / 1024;
128
    if (size < 1024)
129
        return size.toFixed(1) + " kB";
130
    size = size / 1024;
131
    if (size < 1024)
132
        return size.toFixed(1) + " MB";
133
    size = size / 1024;
134
    return size.toFixed(1) + " GB";
135
}
136
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
137
/** Given a URL, returns an object containing a number of attributes
138
 * describing the components of the URL, similar to CGI request variables.
139
 * The object has the following attributes:
140
 * - scheme
141
 * - server_name
142
 * - server_port
143
 * - path
144
 * - query_string
145
 * - args
146
 * The first five of these are strings, which comprise the URL as follows:
147
 * <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
148
 * Any of these strings may be set to null if not found.
149
 *
150
 * "args" is an object whose attributes are the query_string arguments broken
151
 * up.
152
 * Args values are strings for single values, arrays of strings for values
153
 * whose names appear multiple times.
154
 * args is never null, though it may be empty.
155
 *
174 by mattgiuca
util: Fixed up URL encoding; documented properly.
156
 * All strings are decoded/unescaped. Reserved characters
225 by mattgiuca
util.js: Yet more fixes for encoding/decoding URIs. build_url and parse_url
157
 * (; , / ? : @ & = + * $) are not decoded except in args and path.
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
158
 *
159
 * \param url String. A URL. To read from the current browser window, use
160
 *  window.location.href.
161
 * \return The above described object.
162
 */
163
function parse_url(url)
164
{
165
    var obj = {};
166
    var index;
167
    var serverpart;
168
    var args;
169
170
    /* Split scheme from rest */
171
    index = url.indexOf("://");
172
    if (index < 0)
173
        obj.scheme = null;
174
    else
175
    {
176
        obj.scheme = url.substr(0, index);
177
        url = url.substr(index+3);
178
    }
179
180
    /* Split server name/port from rest */
181
    index = url.indexOf("/");
182
    if (index < 0)
183
    {
184
        serverpart = url;
185
        url = null;
186
    }
187
    else
188
    {
189
        serverpart = url.substr(0, index);
187 by mattgiuca
util.js: Minor fix to parse_url: Path needs to begin with a '/'
190
        url = url.substr(index);
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
191
    }
192
193
    /* Split server name from port */
194
    index = serverpart.indexOf(":");
195
    if (index < 0)
196
    {
197
        obj.server_name = serverpart;
198
        obj.server_port = null;
199
    }
200
    else
201
    {
202
        obj.server_name = serverpart.substr(0, index);
203
        obj.server_port = serverpart.substr(index+1);
204
    }
205
206
    /* Split path from query string */
207
    if (url == null)
208
    {
209
        obj.path = null;
210
        obj.query_string = null;
211
    }
212
    else
213
    {
214
        index = url.indexOf("?");
215
        if (index < 0)
216
        {
217
            obj.path = url;
218
            obj.query_string = null;
219
        }
220
        else
221
        {
222
            obj.path = url.substr(0, index);
223
            obj.query_string = url.substr(index+1);
224
        }
225
    }
225 by mattgiuca
util.js: Yet more fixes for encoding/decoding URIs. build_url and parse_url
226
    obj.path = decodeURIComponent(obj.path);
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
227
228
    /* Split query string into arguments */
229
    args = {};
230
    if (obj.query_string != null)
231
    {
232
        var args_strs = obj.query_string.split("&");
233
        var arg_str;
234
        var arg_key, arg_val;
235
        for (var i=0; i<args_strs.length; i++)
236
        {
237
            arg_str = args_strs[i];
238
            index = arg_str.indexOf("=");
239
            /* Ignore malformed args */
240
            if (index >= 0)
241
            {
174 by mattgiuca
util: Fixed up URL encoding; documented properly.
242
                arg_key = decodeURIComponent(arg_str.substr(0, index));
243
                arg_val = decodeURIComponent(arg_str.substr(index+1));
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
244
                if (arg_key in args)
245
                {
246
                    /* Collision - make an array */
247
                    if (args[arg_key] instanceof Array)
248
                        args[arg_key][args[arg_key].length] = arg_val;
249
                    else
250
                        args[arg_key] = [args[arg_key], arg_val];
251
                }
252
                else
253
                    args[arg_key] = arg_val;
254
            }
255
        }
256
    }
257
    obj.args = args;
258
259
    return obj;
260
}
261
177 by mattgiuca
util: Split the creation of the query string in build_url into
262
/** Builds a query_string from an args object. Encodes the arguments.
263
 * \param args Args object as described in parse_url.
264
 * \return Query string portion of a URL.
265
 */
266
function make_query_string(args)
267
{
268
    var query_string = "";
269
    var arg_val;
270
    for (var arg_key in args)
271
    {
272
        arg_val = args[arg_key];
273
        if (arg_val instanceof Array)
274
            for (var i=0; i<arg_val.length; i++)
275
                query_string += "&" + encodeURIComponent(arg_key) + "=" +
276
                    encodeURIComponent(arg_val[i]);
277
        else
278
            query_string += "&" + encodeURIComponent(arg_key) + "=" +
279
                encodeURIComponent(arg_val);
280
    }
441 by drtomc
make_query_string - change the interface so that it no longer returns null.
281
    if (query_string != "")
177 by mattgiuca
util: Split the creation of the query string in build_url into
282
        /* Drop the first "&" */
283
        query_string = query_string.substr(1);
284
285
    return query_string;
286
}
287
172 by mattgiuca
util: Added buildurl function.
288
/** Given an object exactly of the form described for the output of parseurl,
174 by mattgiuca
util: Fixed up URL encoding; documented properly.
289
 * returns a URL string built from those parameters. The URL is properly
290
 * encoded.
172 by mattgiuca
util: Added buildurl function.
291
 * parseurl and buildurl are strict inverses of each other.
292
 * Note that either query_string or args may be supplied. If both are
293
 * supplied, query_string is preferred (because it keeps the argument order).
294
 * If you take a url from parseurl, modify args, and pass to buildurl,
295
 * you need to set query_string to null to use the new args.
296
 * \param obj Object as returned by parseurl.
297
 * \return String, a URL.
298
 */
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
299
function build_url(obj)
172 by mattgiuca
util: Added buildurl function.
300
{
301
    var url = "";
302
    var query_string = null;
303
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
304
    if (("scheme" in obj) && obj.scheme != null)
172 by mattgiuca
util: Added buildurl function.
305
        url = obj.scheme.toString() + "://";
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
306
    if (("server_name" in obj) && obj.server_name != null)
172 by mattgiuca
util: Added buildurl function.
307
        url += obj.server_name.toString();
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
308
    if (("server_port" in obj) && obj.server_port != null)
172 by mattgiuca
util: Added buildurl function.
309
        url += ":" + obj.server_port.toString();
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
310
    if (("path" in obj) && obj.path != null)
172 by mattgiuca
util: Added buildurl function.
311
    {
225 by mattgiuca
util.js: Yet more fixes for encoding/decoding URIs. build_url and parse_url
312
        var path = urlencode_path(obj.path.toString());
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
313
        if (url.length > 0 && path.length > 0 && path[0] != "/")
172 by mattgiuca
util: Added buildurl function.
314
            path = "/" + path;
315
        url += path;
316
    }
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
317
    if (("query_string" in obj) && obj.query_string != null)
225 by mattgiuca
util.js: Yet more fixes for encoding/decoding URIs. build_url and parse_url
318
        query_string = encodeURI(obj.query_string.toString());
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
319
    else if (("args" in obj) && obj.args != null)
177 by mattgiuca
util: Split the creation of the query string in build_url into
320
        query_string = make_query_string(obj.args);
172 by mattgiuca
util: Added buildurl function.
321
442 by drtomc
util.js: Small fix for make_query_string.
322
    if (query_string != "" && query_string != null)
172 by mattgiuca
util: Added buildurl function.
323
        url += "?" + query_string;
324
225 by mattgiuca
util.js: Yet more fixes for encoding/decoding URIs. build_url and parse_url
325
    return url;
172 by mattgiuca
util: Added buildurl function.
326
}
327
223 by mattgiuca
util.js: Added "urlencode_path" which is specially designed to encode paths.
328
/** URL-encodes a path. This is a special case of URL encoding as all
329
 * characters *except* the slash must be encoded.
330
 */
331
function urlencode_path(path)
332
{
333
    /* Split up the path, URLEncode each segment with encodeURIComponent,
334
     * and rejoin.
335
     */
336
    var split = path.split('/');
337
    for (var i=0; i<split.length; i++)
338
        split[i] = encodeURIComponent(split[i]);
339
    path = path_join.apply(null, split);
232 by mattgiuca
common/util.js: Fixed urlencode_path - empty paths no longer get a mysterious
340
    if (split[0] == "" && split.length > 1) path = "/" + path;
223 by mattgiuca
util.js: Added "urlencode_path" which is specially designed to encode paths.
341
    return path;
342
}
343
651 by mattgiuca
util.js: Added write_cookie and read_cookie functions for JavaScript,
344
/** Writes a JSONable object to the cookie under a particular key
345
 * (JSON encoded and URL encoded).
346
 */
347
function write_cookie(key, value)
348
{
349
    var sendstr = encodeURIComponent(key) + "="
350
        + encodeURIComponent(JSON.stringify(value));
351
    /* This actually just assigns to the key, not replacing the whole cookie
352
     * as it appears to. */
353
    document.cookie = sendstr;
354
}
355
/** Reads a cookie which has a JSONable object encoded as its value.
356
 * Returns the object, parsed from JSON.
357
 */
358
function read_cookie(key)
359
{
360
    var cookies = document.cookie.split(";");
361
    var checkstart = encodeURIComponent(key) + "=";
362
    var checklen = checkstart.length;
363
    for (var i=0; i<cookies.length; i++)
364
    {
365
        var cookie = cookies[i];
366
        while (cookie[0] == ' ')
367
            cookie = cookie.substr(1);
368
        if (cookie.substr(0, checklen) == checkstart)
369
        {
370
            var valstr = cookie.substr(checklen);
371
            valstr = decodeURIComponent(valstr);
372
            return JSON.parse(valstr);
373
        }
374
    }
375
}
376
171 by mattgiuca
Added "util.js" in common. Contains useful utility functions.
377
/** Given an argument map, as output in the args parameter of the return of
378
 * parseurl, gets the first occurence of an argument in the URL string.
379
 * If the argument was not found, returns null.
380
 * If there was a single argument, returns the argument.
381
 * If there were multiple arguments, returns the first.
382
 * \param args Object mapping arguments to strings or arrays of strings.
383
 * \param arg String. Argument name.
384
 * \return String.
385
 */
386
function arg_getfirst(args, arg)
387
{
388
    if (!(arg in args))
389
        return null;
390
    var r = args[arg];
391
    if (r instanceof Array)
392
        return r[0];
393
    else
394
        return r;
395
}
396
397
/** Given an argument map, as output in the args parameter of the return of
398
 * parseurl, gets all occurences of an argument in the URL string, as an
399
 * array.
400
 * If the argument was not found, returns [].
401
 * Otherwise, returns all occurences as an array, even if there was only one.
402
 * \param args Object mapping arguments to strings or arrays of strings.
403
 * \param arg String. Argument name.
404
 * \return Array of strings.
405
 */
406
function arg_getlist(args, arg)
407
{
408
    if (!(arg in args))
409
        return [];
410
    var r = args[arg];
411
    if (r instanceof Array)
412
        return r;
413
    else
414
        return [r];
415
}
173 by mattgiuca
util.build_url: Added _ for consistency. Fixed logic concerning missing
416
175 by mattgiuca
dispatch.html: HTML headers for all pages now include a JavaScript
417
/** Joins one or more paths together. Accepts 1 or more arguments.
418
 */
419
function path_join(path1 /*, path2, ... */)
420
{
421
    var arg;
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
422
    var path = "";
423
    for (var i=0; i<arguments.length; i++)
175 by mattgiuca
dispatch.html: HTML headers for all pages now include a JavaScript
424
    {
425
        arg = arguments[i];
426
        if (arg.length == 0) continue;
427
        if (arg[0] == '/')
428
            path = arg;
429
        else
430
        {
200 by mattgiuca
fileservice.listing: Now returns a nicer date format for mtime_nice.
431
            if (path.length > 0 && path[path.length-1] != '/')
175 by mattgiuca
dispatch.html: HTML headers for all pages now include a JavaScript
432
                path += '/';
433
            path += arg;
434
        }
435
    }
436
    return path;
437
}
438
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
439
440
/** Builds a multipart_formdata string from an args object. Similar to
441
 * make_query_string, but it returns data of type "multipart/form-data"
442
 * instead of "application/x-www-form-urlencoded". This is good for
443
 * encoding large strings such as text objects from the editor.
444
 * Should be written with a Content-Type of
445
 * "multipart/form-data, boundary=<boundary>".
446
 * All fields are sent with a Content-Type of text/plain.
447
 * \param args Args object as described in parse_url.
448
 * \param boundary Random "magic" string which DOES NOT appear in any of
449
 *  the argument values. This should match the "boundary=" value written to
450
 *  the Content-Type header.
451
 * \return String in multipart/form-data format.
452
 */
453
function make_multipart_formdata(args, boundary)
454
{
455
    var data = "";
456
    var arg_val;
457
    /* Mutates data */
458
    var extend_data = function(arg_key, arg_val)
459
    {
460
        /* FIXME: Encoding not supported here (should not matter if we
461
         * only use ASCII names */
308 by mattgiuca
util.js: Multipart/form-data output: Newlines are \r\n instead of \n.
462
        data += "--" + boundary + "\r\n"
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
463
            + "Content-Disposition: form-data; name=\"" + arg_key
308 by mattgiuca
util.js: Multipart/form-data output: Newlines are \r\n instead of \n.
464
            + "\"\r\n\r\n"
465
            + arg_val + "\r\n";
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
466
    }
467
468
    for (var arg_key in args)
469
    {
470
        arg_val = args[arg_key];
471
        if (arg_val instanceof Array)
472
            for (var i=0; i<arg_val.length; i++)
473
            {
474
                extend_data(arg_key, arg_val[i]);
475
            }
476
        else
477
            extend_data(arg_key, arg_val);
478
    }
479
    /* End boundary */
308 by mattgiuca
util.js: Multipart/form-data output: Newlines are \r\n instead of \n.
480
    data += "--" + boundary + "--\r\n";
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
481
482
    return data;
483
}
484
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
485
/** Converts a list of directories into a path name, with a slash at the end.
486
 * \param pathlist List of strings.
487
 * \return String.
488
 */
489
function pathlist_to_path(pathlist)
490
{
491
    ret = path_join.apply(null, pathlist);
492
    if (ret[ret.length-1] != '/')
493
        ret += '/';
494
    return ret;
495
}
496
175 by mattgiuca
dispatch.html: HTML headers for all pages now include a JavaScript
497
/** Given a path relative to the IVLE root, gives a path relative to
498
 * the site root.
499
 */
500
function make_path(path)
501
{
502
    return path_join(root_dir, path);
503
}
504
224 by mattgiuca
util.js: Removed urlencoding support from "encoded_app_path" (now called
505
/** Shorthand for make_path(path_join(app, ...))
506
 * Creates an absolute path for a given path within a given app.
223 by mattgiuca
util.js: Added "urlencode_path" which is specially designed to encode paths.
507
 */
224 by mattgiuca
util.js: Removed urlencoding support from "encoded_app_path" (now called
508
function app_path(app /*,...*/)
223 by mattgiuca
util.js: Added "urlencode_path" which is specially designed to encode paths.
509
{
224 by mattgiuca
util.js: Removed urlencoding support from "encoded_app_path" (now called
510
    return make_path(path_join.apply(null, arguments));
223 by mattgiuca
util.js: Added "urlencode_path" which is specially designed to encode paths.
511
}
512
208 by mattgiuca
dispatch.html, ivle.css: "apptabs" is now an ID, not a class.
513
/** Given a path, gets the "basename" (the last path segment).
514
 */
515
function path_basename(path)
516
{
517
    segments = path.split("/");
518
    if (segments[segments.length-1].length == 0)
519
        return segments[segments.length-2];
520
    else
521
        return segments[segments.length-1];
522
}
523
524
/** Given a string str, determines whether it ends with substr */
525
function endswith(str, substring)
526
{
527
    if (str.length < substring.length) return false;
528
    return str.substr(str.length - substring.length) == substring;
529
}
530
214 by mattgiuca
util.js: Added 'repr' function.
531
/** Equivalent to Python's repr.
532
 * Gets the JavaScript string representation.
533
 * Actually just calls JSON.stringify.
534
 */
535
function repr(str)
536
{
537
    return JSON.stringify(str);
538
}
539
238 by mattgiuca
util.js: Added Array method "removeall".
540
/** Removes all occurences of a value from an array.
541
 */
542
Array.prototype.removeall = function(val)
543
{
544
    var i, j;
239 by mattgiuca
browser.js: Fixed array loop, made normal for loop (for each loops break
545
    var arr = this;
238 by mattgiuca
util.js: Added Array method "removeall".
546
    j = 0;
547
    for (i=0; i<arr.length; i++)
548
    {
549
        arr[j] = arr[i];
550
        if (arr[i] != val) j++;
551
    }
552
    arr.splice(j, i-j);
553
}
554
602 by mattgiuca
util.js: Added shallow_copy_object function.
555
/** Shallow-clones an object */
556
function shallow_clone_object(obj)
557
{
558
    o = {};
559
    for (k in obj)
560
        o[k] = obj[k];
561
    return o;
562
}
563
556 by mattgiuca
util.js: Made a function new_xmlhttprequest, for a more browser agnostic
564
/** Returns a new XMLHttpRequest object, in a somewhat browser-agnostic
565
 * fashion.
566
 */
567
function new_xmlhttprequest()
568
{
569
    try
570
    {
571
        /* Real Browsers */
572
        return new XMLHttpRequest();
573
    }
574
    catch (e)
575
    {
576
        /* Internet Explorer */
577
        try
578
        {
579
            return new ActiveXObject("Msxml2.XMLHTTP");
580
        }
581
        catch (e)
582
        {
583
            try
584
            {
585
                return new ActiveXObject("Microsoft.XMLHTTP");
586
            }
587
            catch (e)
588
            {
589
                throw("Your browser does not support AJAX. "
590
                    + "IVLE requires a modern browser.");
591
            }
592
        }
593
    }
594
}
595
559 by mattgiuca
Major JavaScript refactor: util.ajax_call is now asynchronous, not
596
/** Makes an asynchronous XMLHttpRequest call to the server.
597
 * Sends the XMLHttpRequest object containing the completed response to a
598
 * specified callback function.
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
599
 *
559 by mattgiuca
Major JavaScript refactor: util.ajax_call is now asynchronous, not
600
 * \param callback A callback function. Will be called when the response is
601
 *      complete. Passed 1 parameter, an XMLHttpRequest object containing the
602
 *      completed response.
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
603
 * \param app IVLE app to call (such as "fileservice").
604
 * \param path URL path to make the request to, within the application.
605
 * \param args Argument object, as described in parse_url and friends.
606
 * \param method String; "GET" or "POST"
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
607
 * \param content_type String, optional. Only applies if method is "POST".
608
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
609
 *      Defaults to "application/x-www-form-urlencoded".
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
610
 */
559 by mattgiuca
Major JavaScript refactor: util.ajax_call is now asynchronous, not
611
function ajax_call(callback, app, path, args, method, content_type)
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
612
{
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
613
    if (content_type != "multipart/form-data")
614
        content_type = "application/x-www-form-urlencoded";
225 by mattgiuca
util.js: Yet more fixes for encoding/decoding URIs. build_url and parse_url
615
    path = app_path(app, path);
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
616
    var url;
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
617
    /* A random string, for multipart/form-data
618
     * (This is not checked against anywhere else, it is solely defined and
619
     * used within this function) */
620
    var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
556 by mattgiuca
util.js: Made a function new_xmlhttprequest, for a more browser agnostic
621
    var xhr = new_xmlhttprequest();
559 by mattgiuca
Major JavaScript refactor: util.ajax_call is now asynchronous, not
622
    xhr.onreadystatechange = function()
623
        {
624
            if (xhr.readyState == 4)
625
            {
626
                callback(xhr);
627
            }
628
        }
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
629
    if (method == "GET")
630
    {
631
        /* GET sends the args in the URL */
632
        url = build_url({"path": path, "args": args});
559 by mattgiuca
Major JavaScript refactor: util.ajax_call is now asynchronous, not
633
        /* open's 3rd argument = true -> asynchronous */
634
        xhr.open(method, url, true);
182 by mattgiuca
browser.js: Now correctly implements do_action and navigate. Able to perform
635
        xhr.send(null);
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
636
    }
637
    else
638
    {
639
        /* POST sends the args in application/x-www-form-urlencoded */
640
        url = encodeURI(path);
559 by mattgiuca
Major JavaScript refactor: util.ajax_call is now asynchronous, not
641
        xhr.open(method, url, true);
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
642
        var message;
643
        if (content_type == "multipart/form-data")
644
        {
645
            xhr.setRequestHeader("Content-Type",
646
                "multipart/form-data, boundary=" + boundary);
647
            message = make_multipart_formdata(args, boundary);
648
        }
649
        else
650
        {
651
            xhr.setRequestHeader("Content-Type", content_type);
652
            message = make_query_string(args);
653
        }
441 by drtomc
make_query_string - change the interface so that it no longer returns null.
654
        xhr.setRequestHeader("Content-Length", message.length);
176 by mattgiuca
util: Rewrote pathlist_to_path in terms of path_join (more robust and
655
        xhr.send(message);
656
    }
657
}
178 by mattgiuca
util: Added multipart/form-data option for ajax calls.
658