e4fd74daa7eb7a74f6ea8860a6aae5b9882ead61
[wolnelektury.git] / wolnelektury / static / js / ordered_select_multiple.js
1 (function($) {
2   $.fn.orderedSelectMultiple = function(options) {
3     var settings = {
4       choices: []
5     };
6     $.extend(settings, options);
7     
8     var input = $(this).hide();
9     var values = input.val().split(',');
10     
11     var container = $('<div></div>').insertAfter($(this));
12     var choicesList = $('<ol class="choices connectedSortable"></ol>').appendTo(container).css({
13       width: 200, float: 'left', minHeight: 200, backgroundColor: '#eee', margin: 0, padding: 0
14     });
15     var valuesList = $('<ol class="values connectedSortable"></ol>').appendTo(container).css({
16       width: 200, float: 'left', minHeight: 200, backgroundColor: '#eee', margin: 0, padding: 0
17     });
18     var choiceIds = [];
19     $.each(settings.choices, function() {
20       choiceIds.push('' + this.id);
21     });
22     
23     function createItem(hash) {
24       return $('<li>' + hash.name + '</li>').css({
25         backgroundColor: '#cff',
26         display: 'block',
27         border: '1px solid #cdd',
28         padding: 2,
29         margin: 0
30       }).data('obj-id', hash.id);
31     }
32     
33     $.each(settings.choices, function() {
34       if ($.inArray('' + this.id, values) == -1) {
35         choicesList.append(createItem(this));
36       }
37     });
38     
39     $.each(values, function() {
40       var index = $.inArray('' + this, choiceIds); // Why this[0]?
41       if (index != -1) {
42         valuesList.append(createItem(settings.choices[index]));
43       }
44     });
45     
46     choicesList.sortable({
47                 connectWith: '.connectedSortable'
48         }).disableSelection();
49         
50         valuesList.sortable({
51                 connectWith: '.connectedSortable',
52                 update: function() {
53                   values = [];
54                   $('li', valuesList).each(function(index) {
55           values.push($(this).data('obj-id'));
56           console.log($(this).data('obj-id'));
57                   });
58                   console.log('update', values.join(','), input);
59                   input.val(values.join(','));
60                 }
61         }).disableSelection();
62   };
63 })(jQuery);