Blame view

media/js/common.js 14.2 KB
janek37 authored
1
2
/* global $dj, before_save, paginer */
janek37 authored
3
4
var hash_interpreted = false;
janek37 authored
5
6
7
8
$(function () {
    "use strict";
    var tabs = $('.tabs');
    tabs.tabs({
janek37 authored
9
        activate: function () {
janek37 authored
10
            if (hash_interpreted)
janek37 authored
11
                common.update_hash();
janek37 authored
12
13
14
15
16
17
        }
    });
    $('button').button();
    $('input.datepicker').datepicker($.datepicker.regional.pl);
    $(document).on('mouseover', '.ui-state-default', function () {
        $(this).addClass('ui-state-hover');
janek37 authored
18
    });
janek37 authored
19
20
21
22
23
24
25
26
27
28
29
30
    $(document).on('mouseout', '.ui-state-default', function () {
        $(this).removeClass('ui-state-hover');
    });
    if ($dj.paginer || tabs.length > 0) {
        $(window).bind('hashchange', function () {
            var hash = location.hash.substr(1);
            interpret_hash(hash);
            hash_interpreted = true;
        });
        if (!$dj.paginer)
            $(window).trigger('hashchange');
    }
janek37 authored
31
32
});
janek37 authored
33
$.fn.disable = function() {
janek37 authored
34
35
    "use strict";
    return this.prop('disabled', true);
janek37 authored
36
37
};
janek37 authored
38
$.fn.enable = function() {
janek37 authored
39
40
    "use strict";
    return this.prop('disabled', false);
janek37 authored
41
42
};
janek37 authored
43
$.fn.value = function() {
janek37 authored
44
45
46
47
48
49
50
    "use strict";
    if (this.is(':checkbox'))
        return this.prop('checked');
    else if (this.is(':radio'))
        return this.prop('checked') ? this.val() : null;
    else
        return this.val();
janek37 authored
51
52
};
janek37 authored
53
$.fn.bind_hover = function(c) {
janek37 authored
54
55
56
57
58
59
60
61
62
63
    "use strict";
    var elem = this;
    this.hover(
        function () {
            elem.addClass(c);
        },
        function () {
            elem.removeClass(c);
        }
    );
janek37 authored
64
65
};
janek37 authored
66
function make_selected_text(list_num) {
janek37 authored
67
    "use strict";
janek37 authored
68
69
70
71
72
73
74
75
    return function(num, total, checked) {
        if (num > list_num)
            return num + ' wartości';
        var values = $.map(checked, function(elem) {
            return common.strip(elem.title);
        });
        return values.join(', ');
    };
janek37 authored
76
77
78
79
80
}

$.fn.multiSelect = function(params) {
    "use strict";
    if (!params) params = {};
janek37 authored
81
    var list_num = params.selectedList || 4;
janek37 authored
82
83
    var ms_params = {
        noneSelectedText: 'Wybierz',
janek37 authored
84
        selectedText: make_selected_text(list_num),
janek37 authored
85
86
87
88
89
90
91
        header: false,
        open: function () {
            common.multiselect_is_open = true;
        },
        close: function () {
            common.multiselect_is_open = false;
        }
janek37 authored
92
93
94
95
96
    };
    $.extend(ms_params, params);
    this.multiselect2(ms_params);
};
janek37 authored
97
var common = {
janek37 authored
98
    multiselect_is_open: false,
janek37 authored
99
100
101
102
103
104
105
106
107
108
109
110
111
    multiselect_toggle: function(select_el, option_value, enable) {
        "use strict";
        var select, widget, option;
        select = $(select_el);
        widget = select.multiselect2("widget");
        option = widget.find('[value="' + option_value + '"]');
        if (enable)
            option.enable();
        else
            option.disable();
        option.parent().toggleClass('ui-state-disabled', !enable);
        option.parent().parent().toggleClass('ui-multiselect-disabled', !enable);
    },
janek37 authored
112
janek37 authored
113
114
115
116
117
118
    multiselect_enable: function(select_el, option_value) {
        "use strict";
        var select, widget, option;
        select = $(select_el);
        widget = select.multiselect2("widget");
        option = widget.find('[value="' + option_value + '"]');
janek37 authored
119
        option.enable();
janek37 authored
120
121
122
        option.parent().removeClass('ui-state-disabled');
        option.parent().parent().removeClass('ui-multiselect-disabled');
    },
janek37 authored
123
janek37 authored
124
125
126
127
    error_alert: function(text) {
        "use strict";
        window.alert(text);
    },
janek37 authored
128
janek37 authored
129
130
131
132
133
134
135
136
137
138
139
140
141
    blank: function(str) {
        "use strict";
        var re = /^[\t\n ]*$/;
        return re.test(str);
    },

    strip: function(str) {
        "use strict";
        return str.replace(/^\s+|\s+$/g, '');
    }
};

// AJAX
janek37 authored
142
janek37 authored
143
// parametry: method, url, data
janek37 authored
144
// error_callback, bad_data_callback, check_callback
janek37 authored
145
// description, dest, callback, callback_args
janek37 authored
146
// save, async
janek37 authored
147
148
149
150
151
152
153
154
155
$.ajaxJSON = function (params) {
    "use strict";
    var encoded_data = {};
    if (params.save && !before_save())
        return false;
    if (params.async === undefined)
        params.async = true;
    $.each(params.data, function (key, value) {
        encoded_data[key] = $.toJSON(value);
janek37 authored
156
    });
janek37 authored
157
    if (params.async === true) {
janek37 authored
158
        return $.ajax({
janek37 authored
159
160
161
162
163
            type: params.method,
            url: params.url,
            dataType: 'json',
            data: encoded_data,
            success: parse_result(params),
janek37 authored
164
            error: function(request, status, error) {
janek37 authored
165
                if (request.responseText && params.error_callback) {
janek37 authored
166
167
168
                    params.error_callback(request, status, error);
                }
            }
janek37 authored
169
170
171
172
173
174
175
176
177
178
        });
    } else {
        return $.parseJSON($.ajax({
            type: params.method,
            url: params.url,
            dataType: 'json',
            data: encoded_data,
            async: false
        }).responseText);
    }
janek37 authored
179
180
181
182
};

// parametry: description, dest, callback, callback_args
function parse_result(params) {
janek37 authored
183
184
185
186
    "use strict";
    return function (data, status) {
        if (data.result !== 'ok' || status === 'error') {
            if (data.result === 'logout')
janek37 authored
187
188
189
190
                common.error_alert(
                    "Sesja wygasła - zaloguj się i spróbuj ponownie.");
            else if (!params.bad_data_callback ||
                     params.bad_data_callback(data.result)) {
janek37 authored
191
192
                var msg = params.description + ' ' + "nie powiodło się:\n";
                msg += data.result;
janek37 authored
193
                common.error_alert(msg);
janek37 authored
194
            }
janek37 authored
195
        }
janek37 authored
196
        else { // OK
janek37 authored
197
198
            if (params.check_callback && !params.check_callback())
                return;
janek37 authored
199
200
201
202
203
204
205
206
207
208
209
            if (params.dest) {
                params.dest.html(data.html);
            }
            if (params.callback) {
                if (!params.callback_args)
                    params.callback_args = [];
                var args = [data].concat(params.callback_args);
                params.callback.apply({}, args);
            }
        }
    };
janek37 authored
210
}
janek37 authored
211
212

function debug(content) {
janek37 authored
213
214
215
216
217
    "use strict";
    var doc = $('#debug').contents().get(0);
    doc.open();
    doc.writeln(content);
    doc.close();
janek37 authored
218
}
janek37 authored
219
janek37 authored
220
221
222
223
224
225
226
227
function parse_error(event, request, settings) {
    "use strict";
    if (request.responseText) {
        debug(request.responseText);
        $('#show-debug').show();
    }
}
janek37 authored
228
229
230
$(function () {
    "use strict";
    var debug = $('#debug'), main_menu = $('#main_menu');
janek37 authored
231
    $('#show-debug').click(function() {
janek37 authored
232
233
        debug.toggle();
    });
janek37 authored
234
235
236
237
238
    $('#hide-debug').click(function(e) {
        $('#show-debug').hide();
        debug.hide();
        e.stopPropagation();
    });
janek37 authored
239
240
    debug.height($(window).height() - main_menu.height());
    debug.css('top', main_menu.height());
janek37 authored
241
    $(document).ajaxError(parse_error);
janek37 authored
242
243
});
janek37 authored
244
// hash
janek37 authored
245
janek37 authored
246
common.update_hash = function() {
janek37 authored
247
248
249
250
    "use strict";
    var new_hash = make_hash();
    old_hash = new_hash;
    location.href = '#' + new_hash;
janek37 authored
251
};
janek37 authored
252
253

function make_hash() {
janek37 authored
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    "use strict";
    var bottom_tabs, tabs, tab_path = [], query, id, data, original_data;
    var paginer_el;
    var are_tabs = $('.tabs').length > 0;
    if (are_tabs) {
        tabs = $('.tabs:visible').first();
        while (tabs.find('.tabs:visible').length > 0) {
            tabs = tabs.find('.tabs:visible').first();
        }
        bottom_tabs = tabs;
        do {
            tab_path.unshift(tabs.children('.ui-tabs-panel:visible')[0].id);
            tabs = tabs.parents('.tabs').first();
        } while (tabs.length > 0);
    } else
        tab_path = [''];
    paginer_el = $('.paginer:visible', bottom_tabs);
    if (paginer_el.length > 0) {
        id = paginer_el[0].id;
        data = $dj.paginer[id][1];
        original_data = $dj.original_paginer[id][1];
        query = [];
        if (data.order_by !== original_data.order_by)
            query.push('order_by=' + data.order_by);
        $.each(data.filters, function (i, filter) {
            if (i >= original_data.filters.length)
                query.push(filter[0] + '-' + filter[1] + '=' + filter[2]);
        });
        if (paginer.get_page_number(id) > 1)
            query.push('page=' + paginer.get_page_number(id));
        tab_path.push(query.join('&'));
    } else
        tab_path.push('');
    return tab_path.join('/');
janek37 authored
288
289
}
janek37 authored
290
291
292
293
294
295
296
function select_tab(name) {
    "use strict";
    var tabs = $('#' + name).parents('.tabs').first();
    var index = tabs.find('a[href="#' + name +'"]').parent().index();
    tabs.tabs('option', 'active', index);
}
janek37 authored
297
298
299
var old_hash = 'not gonna happen';

function interpret_hash(hash) {
janek37 authored
300
301
302
303
304
305
306
307
    "use strict";
    var data = hash.split('/'), children;
    if (hash === old_hash)
        return;
    var id, paginer_data, original_data, new_order_by, new_filters, new_page;
    var paginer_container, paginer_el;
    if (hash !== '')
        $.each(data.slice(0, data.length - 1), function (i, part) {
janek37 authored
308
309
310
            if (part) {
                select_tab(part);
            }
janek37 authored
311
        });
janek37 authored
312
313
314
315
    else {
        paginer_container = $('.ui-tabs-panel').first();
        //hash_interpreted = false; // HACK
        while (paginer_container.length > 0) {
janek37 authored
316
            select_tab(paginer_container[0].id);
janek37 authored
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
            children = $('.ui-tabs-panel', paginer_container);
            if (children.length > 0)
                paginer_container = children.first();
            else
                paginer_container = children;
        }
        hash_interpreted = true; // HACK
    }
    if (window.paginer) {
        if (data[0] !== '')
            paginer_container = $('#' + data[data.length - 2]);
        else { // nie ma tabów (lub pusty hash...)
            paginer_container = $(document.body);
            do {
                children = $('.ui-tabs-panel:visible', paginer_container);
                if (children.length)
                    paginer_container = children[0];
            } while (children.length);
        }
        paginer_el = $('.paginer', paginer_container);
        if (paginer_el.length > 0) {
            id = paginer_el[0].id;
            paginer_data = $dj.paginer[id][1];
            original_data = $dj.original_paginer[id][1];
            new_order_by = original_data.order_by;
            new_page = 1;
            new_filters = $.extend([], original_data.filters);
            if (data[data.length - 1])
                $.each(data[data.length - 1].split('&'), function (i, pair) {
                    if (pair) {
                        var p = pair.split('=', 2);
                        var field_lookup = p[0].split('-', 2), value = p[1];
                        var field = field_lookup[0], lookup = field_lookup[1];
                        if (value === 'false')
                            value = false;
                        if (value === 'true')
                            value = true; // nieodporne na tekstowe filtry (jeśli będą)
                        if (p[0] === 'order_by') {
                            new_order_by = value;
                        } else if (p[0] === 'page') {
                            new_page = window.parseInt(value);
                        } else { // jakieś sprawdzanie poprawności? w sumie serwer to zrobi...
                            new_filters.push([field, lookup, value]);
                        }
                    }
                });
            paginer_data.order_by = new_order_by;
            paginer_data.filters = new_filters;
            paginer.page_numbers[id] = new_page;
            paginer.update_list(id, true); // protect hash
            paginer.show_order(id);
            paginer.reload_panel(id);
        }
janek37 authored
370
    }
janek37 authored
371
    old_hash = hash;
janek37 authored
372
}
janek37 authored
373
janek37 authored
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400

// skopiowane z http://jsfiddle.net/DkHyd/
$.fn.togglepanels = function () {
    "use strict";
    return this.each(function () {
        $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset")
            .find("h3")
            .addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom")
            .hover(function () {
                $(this).toggleClass("ui-state-hover");
            })
            .prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>')
            .click(function () {
                $(this)
                    .toggleClass("ui-accordion-header-active ui-state-active ui-state-default ui-corner-bottom")
                    .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e ui-icon-triangle-1-s").end()
                    .next().slideToggle();
                return false;
            })
            .next()
            .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom")
            .hide();
    });
};

// CSRF Ajax fix
janek37 authored
401
$(document).ajaxSend(function (event, xhr, settings) {
janek37 authored
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
    "use strict";
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(
                        cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

// http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/2117698#2117698
(function ($) {
    "use strict";
    $.fn.textMetrics = function () {
        var h, w, el = this;
        var div = document.createElement('div');
        document.body.appendChild(div);
        $(div).css({
            position: 'absolute',
            left: -1000,
            top: -1000,
            display: 'none'
        });
        $(div).html($(el).html());
        var styles = [
            'font-size', 'font-style', 'font-weight', 'font-family',
            'line-height', 'text-transform', 'letter-spacing'];
        $(styles).each(function () {
            var s = this.toString();
            $(div).css(s, $(el).css(s));
        });
        h = $(div).outerHeight();
        w = $(div).outerWidth();
        $(div).remove();
        return {
            height: h,
            width: w
        };
    };
})(jQuery);