~launchpad-pqm/launchpad/devel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
370
371
372
373
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
401
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
/**
 * Copyright 2011 Canonical Ltd. This software is licensed under the
 * GNU Affero General Public License version 3 (see the file LICENSE).
 *
 * DistroSeries related stuff.
 *
 * @module registry
 * @submodule distroseries
 */

YUI.add('lp.registry.distroseries.initseries', function(Y) {

Y.log('loading lp.registry.distroseries.initseries');

var namespace = Y.namespace('lp.registry.distroseries.initseries');


/**
 * A form row matching that which LaunchpadForm presents, containing a
 * field (defined in a subclass), and an optional label and
 * description.
 *
 * @class FormRowWidget
 */
var FormRowWidget = function() {
    FormRowWidget.superclass.constructor.apply(this, arguments);
};

Y.mix(FormRowWidget, {

    NAME: 'formRowWidget',

    ATTRS: {

        /**
         * The field name.
         *
         * @property name
         */
        name: {
            setter: function(value, name) {
                this.fieldNode.all("input, select").set("name", value);
            }
        },

        /**
         * The top label for the field.
         *
         * @property label
         */
        label: {
            getter: function() {
                return this.labelNode.get("text");
            },
            setter: function(value, name) {
                this.labelNode.set("text", value);
            }
        },

        /**
         * A dictionary {link:link, text:text} to populate
         * the pop-up help for the field.
         *
         * @property help
         */
        help: {
            getter: function() {
                return {link:this.helpNode.one('a')
                            .get("href"),
                        text:this.helpNode
                            .one('.invisible-link')
                            .get("text")};
            },
            setter: function(value, name) {
                if ((value.link !== undefined) &&
                    (value.text !== undefined)) {
                    this.helpNode.one('a').set("href", value.link);
                    this.helpNode.one('.invisible-link')
                        .set("text", value.text);
                    this.helpNode.removeClass('unseen');
                }
                else {
                    this.helpNode.addClass('unseen');
                }
            }
        },

        /**
         * A description shown near the field.
         *
         * @label description
         */
        description: {
            getter: function() {
                return this.descriptionNode.get("text");
            },
            setter: function(value, name) {
                this.descriptionNode.set("text", value);
            }
        }
    }

});

Y.extend(FormRowWidget, Y.Widget, {

    BOUNDING_TEMPLATE: "<tr></tr>",

    CONTENT_TEMPLATE: '<td colspan="2"></td>',

    initializer: function(config) {
        this.labelNode = Y.Node.create("<label />");
        this.helpNode = Y.Node.create(('<span class="helper unseen">'+
            '&nbsp;<a href=""' +
            'target="help" class="sprite maybe">&nbsp;' +
            '<span class="invisible-link"></span></a></span>'));
        this.fieldNode = Y.Node.create("<div></div>");
        this.descriptionNode = Y.Node.create('<p class="formHelp" />');
        this.spinnerNode = Y.Node.create(
            '<img src="/@@/spinner" alt="Loading..." />');
    },

    renderUI: function() {
        this.get("contentBox")
            .append(this.labelNode)
            .append(this.helpNode)
            .append(this.fieldNode)
            .append(this.descriptionNode);
    },

    /**
     * Show the spinner.
     *
     * @method showSpinner
     */
    showSpinner: function() {
        this.fieldNode.empty().append(this.spinnerNode);
    },

    /**
     * Hide the spinner.
     *
     * @method hideSpinner
     */
    hideSpinner: function() {
        this.spinnerNode.remove();
    },

    /**
     * Display an error.
     *
     * @method showError
     */
    showError: function(error) {
        var message = Y.Node.create('<p />').set("text", error);
        this.fieldNode.empty().append(message);
        Y.lazr.anim.red_flash({node: message}).run();
    }

});

namespace.FormRowWidget = FormRowWidget;

/**
 * A table to display, order, delete the selected parent series. Each parent
 * can also be made an overlay, and a component and a pocket selected.
 *
 */
var ParentSeriesListWidget = function() {
    ParentSeriesListWidget
        .superclass.constructor.apply(this, arguments);
};

Y.mix(ParentSeriesListWidget, {

    NAME: 'parentSeriesListWidget',

    ATTRS: {

        /**
         * The DistroSeries the choices in this field should
         * reflect. Takes the form of a list of ids,
         * e.g. ["4", "55"].
         *
         * @property parents
         */
        parents: {
            getter: function() {
                var series = [];
                this.fieldNode.all("tbody > tr.parent").each(
                    function(node) {
                        series.push(node.get('id').replace('parent-',''));
                    }
                );
                return series;
            }
        }
    }

});

Y.extend(ParentSeriesListWidget, FormRowWidget, {

    initializer: function() {
        ParentSeriesListWidget.superclass.initializer();
        this.client = new Y.lp.client.Launchpad();
        this.clean_display();
    },

    /**
     * Display a simple message when no parent series are selected.
     *
     * @method clean_display
     */
    clean_display: function() {
        this.fieldNode.empty();
        this.fieldNode.append(Y.Node.create("<div />")
            .set('text', '[No parent for this series yet!]'));
    },

    /**
     * Display the table header.
     *
     * @method init_display
     */
    init_display: function() {
        this.fieldNode.empty();
        this.fieldNode = Y.Node.create("<table />");
        var table_header = Y.Node.create(
            ["<thead><tr>",
             "<th>Order</th>",
             "<th>Parent name</th>",
             "<th>Overlay?</th>",
             "<th>Component</th>",
             "<th>Pocket</th>",
             "<th>Delete</th>",
             "</tr></thead>",
             "<tbody>",
             "</tbody>",
            ].join(""));
        this.fieldNode.append(table_header);
    },

    /**
     * Helper method to create a select widget from a list and add it
     * to a node.
     *
     * @method build_selector
     */
    build_selector: function(node, res_list, class_name) {
        var select = Y.Node.create('<select disabled="disabled"/>')
        res_list.forEach(
            function(choice) {
                select.appendChild('<option />').set('text', choice)
            });
        node.one('td.'+class_name).append(select);
        node.one('input').on('click', function(e) {
            var select = node.one('td.'+class_name).one('select');
            if (select.hasAttribute('disabled')) {
                select.removeAttribute('disabled');
            }
            else {
                select.setAttribute('disabled', 'disabled');
            }
        });
    },

    /**
     * Build a select widget from a list retrieved from the api.
     *
     * @method build_select
     */
    build_select: function(node, class_name, path) {
        var self = this;
        var on = {
            success: function(res_list) {
                self.build_selector(node, res_list, class_name);
            },
            failure: function() {
                var failed_node = Y.Node.create('<span />')
                    .set('text', 'Failed to retrieve content.');
                node.one('td.'+class_name).append(failed_node);
            }
        };
        this.client.get(path, {on: on});
     },


    /**
     * Move down a parent's line in the table.
     *
     * @method move_down
     */
    move_down: function(parent_id) {
        var node = this.fieldNode.one("tr#parent-" + parent_id);
        var other = node.next('tr.parent');
        if (other != null) { node.swap(other);}
        Y.lazr.anim.green_flash({node: node}).run();
    },

    /**
     * Move up a parent's line in the table.
     *
     * @method move_up
     */
    move_up: function(parent_id) {
        var node = this.fieldNode.one("tr#parent-" + parent_id);
        var other = node.previous('tr.parent');
        if (other != null) { node.swap(other);}
        Y.lazr.anim.green_flash({node: node}).run();
    },

    /**
     * Remove a parent series.
     *
     * @method add_parent
     */
    remove_parent: function(parent_id) {
        if (this.get('parents').length == 1) {
            this.clean_display();
            this.renderUI();
        }
        else {
            this.fieldNode.one('tr#parent-' + parent_id).remove();
        }
        Y.fire("parent_removed", parent_id);
     },

    /**
     * Add a parent series.
     *
     * @method add_parent
     */
    add_parent: function(parent) {
        if (this.get('parents').length == 0) {
            this.init_display();
            this.renderUI();
        }
        var item = this.fieldNode.one('tr#parent-' + parent.value);
        if (item != null) {
            Y.lazr.anim.red_flash({node: item}).run();
            return false;
        }
        item =  Y.Node.create("<tr />")
            .addClass('parent')
            .set('id', 'parent-' + parent.value)
            .append(Y.Node.create("<td />")
                .append(Y.Node.create('<a href="" title="Move parent up"/>')
                    .addClass('move-up')
                .set('innerHTML', '&uarr;'))
                .append(Y.Node.create('<a href="" title="Move parent down"/>')
                    .addClass('move-down')
                .set('innerHTML', '&darr;')))
            .append(Y.Node.create("<td />")
                .addClass('series')
                .set('text', parent.title))
            .append(Y.Node.create("<td />")
                .set('align', 'center')
                .append(Y.Node.create('<input type="checkbox" />')))
            .append(Y.Node.create("<td />")
                .addClass('component'))
            .append(Y.Node.create("<td />")
                .addClass('pocket'))
            .append(Y.Node.create("<td />")
                .set('align', 'center')
                .append(Y.Node.create('<span />')
                    .addClass('sprite')
                    .addClass('remove')));
        this.fieldNode.one('tbody').append(item);
        this.build_select(item, 'component',
            parent.api_uri + '/component_names');
        this.build_select(item, 'pocket',
            parent.api_uri + '/suite_names');
        item.one('.move-up').on('click', function(e) {
            this.move_up(parent.value);
            e.preventDefault();
            return false;
        }, this);
        item.one('.move-down').on('click', function(e) {
            this.move_down(parent.value);
            e.preventDefault();
            return false;
        }, this);
        item.one('.remove').on('click', function(e) {
            var parent_id = item.get('id').replace('parent-','');
            this.remove_parent(parent_id);
            e.preventDefault();
            return false;
        }, this);

        Y.lazr.anim.green_flash({node: item}).run();
        return true;
    }
});

namespace.ParentSeriesListWidget = ParentSeriesListWidget;


/**
 * A form row matching that which LaunchpadForm presents, containing a
 * list of checkboxes, and an optional label and description.
 *
 * @class ChoiceListWidget
 */
var ChoiceListWidget = function() {
    ChoiceListWidget.superclass.constructor.apply(this, arguments);
};

Y.mix(ChoiceListWidget, {

    NAME: 'choiceListWidget',

    ATTRS: {

        /**
         * An array of strings from which to choose.
         *
         * @property choices
         */
        choices: {
            getter: function() {
                return this.fieldNode.all("li > input").get("value");
            },
            setter: function(value, name) {
                var choices = Y.Array.unique(value).sort();
                var list = Y.Node.create("<ul />");
                var self = this;
                choices.forEach(
                    function(choice) {
                       var item = self._createChoice(choice);
                       list.append(item);
                    }
                );
                this.fieldNode.empty().append(list);
            }
        },

        /**
         * The current selection.
         *
         * @property choice
         */
        choice: {
            setter: function(value, name) {
                if (!Y.Lang.isArray(value)) {
                    value = [value];
                }
                this.fieldNode.all("li > input").each(
                    function(node) {
                        node.set(
                            "checked",
                            value.indexOf(node.get("value")) >= 0);
                    }
                );
            },
            getter: function() {
                var choice = [];
                this.fieldNode.all("li > input").each(
                    function(node) {
                        if (node.get("checked")) {
                            choice.push(node.get("value"));
                        }
                    }
                );
                if (this.get("type") == "radio") {
                    if (choice.length === 0) {
                        choice = null;
                    }
                    else if (choice.length == 1) {
                        choice = choice[0];
                    }
                    else {
                        choice = undefined;
                    }
                }
                return choice;
            }
        },

        /**
         * The input type to display. Choose from "checkbox" or "radio".
         *
         * @property type
         */
        type: {
            value: "checkbox",
            setter: function(value, name) {
                this.fieldNode.all("li > input").set("type", value);
            }
        }

    }

});

Y.extend(ChoiceListWidget, FormRowWidget, {

    /**
     * Helper method to create an entry for the select widget.
     *
     * @method _createChoice
     */
    _createChoice: function(choice, field_type, field_name) {
         var field_name = this.get("name");
         var field_type = this.get("type");
         var item = Y.Node.create(
            "<li><input /> <label /></li>");
        item.one("input")
            .set("type", field_type)
            .set("name", field_name)
            .set("value", choice);
        item.one("label")
            .setAttribute(
                "for", item.one("input").generateID())
            .setStyle("font-weight", "normal")
            .set("text", choice);
        return item;
    },

   /**
     * Remove a list of choices from the possible widget's choices.
     *
     * @method remove_choices
     */
    remove_choices: function(choices) {
        choices.forEach(
            function(choice) {
                this.fieldNode.all("select > option").each(
                    function(option) { options.push(option); });
                this.fieldNode.all(
                    "li input[value=" + choice + "]").each(
                        function(li_element) {
                            li_element.get('parentNode').remove();
                        }
                );
            },
            this
        );
        Y.lazr.anim.green_flash({node: this.fieldNode}).run();
     },

    /**
     * Add new choices (if they are not already present).
     *
     * @method add_choices
     */
    add_choices: function(new_choices) {
        new_choices.forEach(
            function(choice) {
                if (this.fieldNode.all(
                    "li > input[value=" + choice + "]").isEmpty()) {
                    var list = this.fieldNode.one('ul');
                    if (list == null) {
                        var list = Y.Node.create("<ul />");
                        this.fieldNode.empty().append(list);
                    }
                    list.append(this._createChoice(choice));
                }
            }, this
        );
        Y.lazr.anim.green_flash({node: this.fieldNode}).run();
    }

});


namespace.ChoiceListWidget = ChoiceListWidget;


/**
 * A special form of ChoiceListWidget for choosing architecture tags.
 *
 * @class ArchitecturesChoiceListWidget
 */
var ArchitecturesChoiceListWidget = function() {
    ArchitecturesChoiceListWidget
        .superclass.constructor.apply(this, arguments);
};

Y.mix(ArchitecturesChoiceListWidget, {

    NAME: 'architecturesChoiceListWidget',

    ATTRS: {
    }

});

Y.extend(ArchitecturesChoiceListWidget, ChoiceListWidget, {

    initializer: function(config) {
        this.client = new Y.lp.client.Launchpad();
        this.error_handler = new Y.lp.client.ErrorHandler();
        this.error_handler.clearProgressUI = Y.bind(this.hideSpinner, this);
        this.error_handler.showError = Y.bind(this.showError, this);
        this._distroseries = {};
        this.clean_display();
    },

    /**
     * Display a simple message when no parent series are selected.
     *
     * @method clean_display
     */
    clean_display: function() {
        this.fieldNode.empty();
        this.fieldNode.append(Y.Node.create("<div />")
            .set('text', '[No architectures to select from yet!]'));
        this.renderUI();
    },

    /**
     * Add a parent distroseries, add the architectures for this new
     * distroseries to the possible choices.
     *
     * @method add_distroseries
     */
    add_distroseries: function(distroseries) {
        var path = distroseries.api_uri + "/architectures";
        var distroseries_id = distroseries.value;
        var self = this;
        var on = {
            success: function (results) {
                self.add_distroarchseries(distroseries_id, results);
            },
            failure: this.error_handler.getFailureHandler(),
        };
        this.client.get(path, {on: on});
     },

    /**
     * Remove a parent distroseries, remove the architectures only
     * present in this parent series from the possible choices.
     *
     * @method remove_distroseries
     */
    remove_distroseries: function(distroseries_id) {
        // Compute which das is only in the distroseries to be removed.
        arch_to_remove = []
        var das = this._distroseries[distroseries_id];
        for (i=0; i<das.entries.length; i++) {
            remove_das = true;
            arch = das.entries[i].get('architecture_tag');
            for (var ds in this._distroseries) {
                if (ds !== distroseries_id) {
                   var other_das = this._distroseries[ds];
                   for (j=0; j<other_das.entries.length; j++) {
                       var other_arch = other_das.entries[j].get(
                           'architecture_tag');
                       if (other_arch == arch) {
                           remove_das = false;
                       }
                   }
                }
            }
            if (remove_das) {
                arch_to_remove.push(arch);
            }
        }
        delete this._distroseries[distroseries_id];
        this.remove_choices(arch_to_remove);
        if (this.fieldNode.all('input').isEmpty()) {
            this.clean_display();
        }
    },

    /**
     * Add a list of distroarchseries.
     *
     * @method add_distroarchseries
     */
    add_distroarchseries: function(distroseries_id, distroarchseries) {
        this._distroseries[distroseries_id] = distroarchseries;
        var choices = distroarchseries.entries.map(
            function(das) {
                return das.get("architecture_tag");
            }
        );
        this.add_choices(choices);
     }

});

namespace.ArchitecturesChoiceListWidget = ArchitecturesChoiceListWidget;


/**
 * A special form of FormRowWidget, containing a select control.
 *
 * @class SelectWidget
 */
var SelectWidget = function() {
    SelectWidget.superclass.constructor.apply(this, arguments);
};

Y.mix(SelectWidget, {

    NAME: 'selectWidget',

    ATTRS: {

        /**
         * An array of objects from which to choose. Each object
         * should contain a value for "value", "text" and "data".
         *
         * @property choices
         */
        choices: {
            getter: function() {
                /* I think this is a YUI3 wart; I can't see any way to
                   map() over a NodeList, so I must push the elements
                   one by one into an array first. */
                var options = Y.Array([]);
                this.fieldNode.all("select > option").each(
                    function(option) { options.push(option); });
                return options.map(
                    function(option) {
                        return {
                            value: option.get("value"),
                            text: option.get("text"),
                            data: option.getData("data")
                        };
                    }
                );
            },
            setter: function(value, name) {
                var select = Y.Node.create("<select />");
                select.set("name", this.get("name"))
                      .set("size", this.get("size"));
                if (this.get("multiple")) {
                    select.set("multiple", "multiple");
                }
                var choices = Y.Array(value);
                choices.forEach(
                    function(choice) {
                        var option = Y.Node.create("<option />");
                        option.set("value", choice.value)
                              .set("text", choice.text)
                              .setData("data", choice.data);
                        select.append(option);
                    }
                );
                if (choices.length > 0) {
                    this.fieldNode.empty().append(select);
                }
                else {
                    this.fieldNode.empty();
                }
            }
        },

        /**
         * The current selection.
         *
         * @property choice
         */
        choice: {
            setter: function(value, name) {
                if (!Y.Lang.isArray(value)) {
                    value = [value];
                }
                this.fieldNode.all("select > option").each(
                    function(node) {
                        node.set(
                            "selected",
                            value.indexOf(node.get("value")) >= 0);
                    }
                );
            },
            getter: function() {
                var choice = [];
                this.fieldNode.all("select > option").each(
                    function(node) {
                        if (node.get("selected")) {
                            choice.push(node.get("value"));
                        }
                    }
                );
                return choice;
            }
        },

        /**
         * The number of rows to show in the select widget.
         *
         * @property size
         */
        size: {
            value: 1,
            setter: function(value, name) {
                this.fieldNode.all("select").set("size", value);
            }
        },

        /**
         * Whether multiple rows can be selected.
         *
         * @property multiple
         */
        multiple: {
            value: false,
            setter: function(value, name) {
                value = value ? true : false;
                this.fieldNode.all("select").set("multiple", value);
                return value;
            }
        }

    }

});

Y.extend(SelectWidget, FormRowWidget, {

    /**
     * Add a choice to the picker.
     *
     * @method add_choice
     */
    add_choice: function(choice) {
        var select = this.init_select();
        var option = Y.Node.create("<option />");
        option.set("value", choice.value)
                .set("text", choice.text)
                .setData("data", choice.data);
        select.append(option);
    },

    /**
     * Choose a size for the select control based on the number of
     * choices, up to an optional maximum size.
     *
     * @method autoSize
     */
    autoSize: function(maxSize) {
        var choiceCount = this.fieldNode.all("select > option").size();
        if (choiceCount === 0) {
            this.set("size", 1);
        }
        else if (maxSize === undefined) {
            this.set("size", choiceCount);
        }
        else if (choiceCount < maxSize) {
            this.set("size", choiceCount);
        }
        else {
            this.set("size", maxSize);
        }
        return this;
    }

});

namespace.SelectWidget = SelectWidget;


/**
 * A special form of SelectWidget for choosing packagesets.
 *
 * @class PackagesetPickerWidget
 */
var PackagesetPickerWidget = function() {
    PackagesetPickerWidget
        .superclass.constructor.apply(this, arguments);
};

Y.mix(PackagesetPickerWidget, {

    NAME: 'packagesetPickerWidget',

    ATTRS: {

        /**
         * The DistroSeries the choices in this field should
         * reflect. Takes the form of a string, e.g. "ubuntu/hoary".
         *
         * @property distroSeries
         */
        distroSeries: {
            setter: function(value, name) {
                var distro_series_uri = Y.lp.client.get_absolute_uri(value);
                var on = {
                    start: Y.bind(this.showSpinner, this),
                    success: Y.bind(this.set, this, "packageSets"),
                    failure: this.error_handler.getFailureHandler(),
                    end: Y.bind(this.hideSpinner, this)
                };
                var config = {
                    on: on,
                    parameters: {
                        distroseries: distro_series_uri
                    }
                };
                this.client.named_get("package-sets", "getBySeries", config);
            }
        }
    }
});


Y.extend(PackagesetPickerWidget, SelectWidget, {

    /**
     * Add a distroseries: add it's packagesets to the packageset picker.
     *
     * @method add_distroseries
     */
    add_distroseries: function(distroseries) {
        var distro_series_uri = Y.lp.client.get_absolute_uri(distroseries.api_uri);
        var self = this;
        var on = {
            success: function (results) {
                self.add_packagesets(results, distroseries);
            },
            failure: this.error_handler.getFailureHandler(),
        };
        var config = {
            on: on,
            parameters: {
                distroseries: distro_series_uri
            }
        };
        this.client.named_get("package-sets", "getBySeries", config);
    },

    /**
     * Display a simple message when no parent series are selected.
     *
     * @method clean_display
     */
    clean_display: function() {
        this.fieldNode.empty();
        this.fieldNode.append(Y.Node.create("<div />")
            .set('text', '[No package sets to select from yet!]'));
        this.renderUI();
    },

    /**
     * Initialise the picket's select node.
     *
     * @method init_select
     */
    init_select: function() {
        var select = this.fieldNode.one('select');
        if (select == null) {
            var select = Y.Node.create("<select />");
            select.set("name", this.get("name"))
                    .set("size", this.get("size"));
            if (this.get("multiple")) {
                select.set("multiple", "multiple");
            }
            this.fieldNode.empty().append(select);
        }
        return select;
    },

    /**
     * Add choices (a set of packagesets) to the picker.
     *
     * @method add_packagesets
     */
    add_packagesets: function(packagesets, distroseries) {
        packagesets.entries.forEach(
            function(packageset) {
                var value = packageset.get("name")+'-'+distroseries.value;
                this.add_choice({
                    data: packageset,
                    value: value,
                    text: (
                        packageset.get("name") + ": " +
                        packageset.get("description") +
                        " (" + distroseries.title + ") ")
                });
            }, this);
        this.autoSize(10);
        Y.lazr.anim.green_flash({node: this.fieldNode}).run();
     },

    /**
     * Remove a distroseries: remove it's packagesets from the picker.
     *
     * @method remove_distroseries
     */
    remove_distroseries: function(distroseries_id) {
        this.fieldNode.all(
            'option[value$="\-' + distroseries_id + '"]').remove();
        Y.lazr.anim.green_flash({node: this.fieldNode}).run();
        if (this.fieldNode.all('option').isEmpty()) {
            this.clean_display();
        }
    },

    initializer: function(config) {
        this.client = new Y.lp.client.Launchpad();
        this.error_handler = new Y.lp.client.ErrorHandler();
        this.error_handler.clearProgressUI = Y.bind(this.hideSpinner, this);
        this.error_handler.showError = Y.bind(this.showError, this);
        this.clean_display();
    }

});

namespace.PackagesetPickerWidget = PackagesetPickerWidget;


/**
 * A widget to encapsulate functionality around the form actions.
 *
 * @class FormActionsWidget
 */
var FormActionsWidget = function() {
    FormActionsWidget
        .superclass.constructor.apply(this, arguments);
};

Y.mix(FormActionsWidget, {

    NAME: 'formActionsWidget',

    HTML_PARSER: {
        submitButtonNode: "input[type=submit]"
    }

});

Y.extend(FormActionsWidget, Y.Widget, {

    initializer: function(config) {
        this.client = new Y.lp.client.Launchpad();
        this.error_handler = new Y.lp.client.ErrorHandler();
        this.error_handler.clearProgressUI = Y.bind(this.hideSpinner, this);
        this.error_handler.showError = Y.bind(this.showError, this);
        this.submitButtonNode = config.submitButtonNode;
        this.spinnerNode = Y.Node.create(
            '<img src="/@@/spinner" alt="Loading..." />');
    },

    /**
     * Show the spinner, and hide the submit button.
     *
     * @method showSpinner
     */
    showSpinner: function() {
        this.submitButtonNode.replace(this.spinnerNode);
    },

    /**
     * Hide the spinner, and show the submit button again.
     *
     * @method hideSpinner
     */
    hideSpinner: function() {
        this.spinnerNode.replace(this.submitButtonNode);
    },

    /**
     * Display an error.
     *
     * @method showError
     */
    showError: function(error) {
        Y.Node.create('<p class="error message" />')
            .appendTo(this.get("contentBox"))
            .set("text", error);
    },

    /**
     * Remove all errors that have been previously displayed by showError.
     *
     * @method hideErrors
     */
    hideErrors: function(error) {
        this.get("contentBox").all("p.error.message").remove();
    }

});

namespace.FormActionsWidget = FormActionsWidget;


/**
 * A widget to encapsulate functionality around the form actions.
 *
 * @class DeriveDistroSeriesActionsWidget
 */
var DeriveDistroSeriesActionsWidget = function() {
    DeriveDistroSeriesActionsWidget
        .superclass.constructor.apply(this, arguments);
};

Y.mix(DeriveDistroSeriesActionsWidget, {

    NAME: 'deriveDistroSeriesActionsWidget'

});

Y.extend(DeriveDistroSeriesActionsWidget, FormActionsWidget, {

    initializer: function(config) {
        this.context = config.context;
        this.deriveFromChoices = config.deriveFromChoices;
        this.architectureChoice = config.architectureChoice;
        this.packagesetChoice = config.packagesetChoice;
        this.packageCopyOptions = config.packageCopyOptions;
    },

    /**
     * Display a success message then fade out and remove the form.
     *
     * @method success
     */
    success: function() {
        var message = [
            "The initialization of ", this.context.displayname,
            " has been scheduled and should run shortly."
        ].join("");
        var messageNode = Y.Node.create("<p />")
            .addClass("informational")
            .addClass("message")
            .set("text", message);
        var form = this.get("contentBox").ancestor("form");
        form.transition(
            {duration: 1, height: 0, opacity: 0},
            function() { form.remove(true); });
        form.insert(messageNode, "after");
    },

    /**
     * Call deriveDistroSeries via the API.
     *
     * @method submit
     */
    submit: function() {
        var self = this;
        var config = {
            on: {
                start: function() {
                    self.hideErrors();
                    self.showSpinner();
                },
                success: Y.bind(this.success, this),
                failure: this.error_handler.getFailureHandler(),
                end: Y.bind(this.hideSpinner, this)
            },
            parameters: {
                name: this.context.name,
                distribution: this.context.distribution_link,
                parents: this.deriveFromChoices.get("parents"),
                architectures: this.architectureChoice.get("choice"),
                packagesets: this.packagesetChoice.get("choice"),
                rebuild: this.packageCopyOptions.get("choice") == (
                    "Copy Source and Rebuild")
            }
        };
        this.client.named_post(
            this.context.self_link, "deriveDistroSeries", config);
    }

});

namespace.DeriveDistroSeriesActionsWidget = DeriveDistroSeriesActionsWidget;

/*
 * Show the "Add parent series" overlay.
 */
var show_add_parent_series_form = function(e) {

    e.preventDefault();
    var config = {
        header: 'Add a parent series',
        step_title: 'Search'
    };

    config.save = function(result) {
        add_parent_series(result);
    };

    parent_picker = Y.lp.app.picker.create('DistroSeriesDerivation', config);
    parent_picker.show();
};

namespace.show_add_parent_series_form = show_add_parent_series_form;

/*
 * Add a parent series.
 */
var add_parent_series = function(parent) {
    Y.fire("add_parent", parent);
};

namespace.add_parent_series = add_parent_series;


/**
 * Setup the widgets on the +initseries page.
 *
 * @function setup
 */
namespace.setup = function() {
    var form_container = Y.one("#initseries-form-container");
    var form_table = form_container.one("table.form");
    var form_table_body = form_table.append(Y.Node.create('<tbody />'));

    // Widgets.
    var add_parent_link = Y.Node.create('<a href="+add-parent-series">')
            .addClass("sprite")
            .addClass("add")
            .set("id", "add-parent-series")
            .set("text", "Add parent series")
    add_parent_link.appendTo(form_table_body);
    var parents_selection =
        new ParentSeriesListWidget()
            .set("name", "field.parent")
            .set("label", "Parent Series:")
            .set("description", (
                     "Choose and configure the parent series."))
            .render(form_table_body);
    var architecture_choice =
        new ArchitecturesChoiceListWidget()
            .set("name", "field.architectures")
            .set("label", "Architectures:")
            .set("description", (
                     "Choose the architectures you want to " +
                     "use from the parent series."))
            .render(form_table_body);
    var packageset_choice =
        new PackagesetPickerWidget()
            .set("name", "field.packagesets")
            .set("size", 5)
            .set("help", {link: '/+help/init-series-packageset-help.html',
                          text: 'Packagesets help'})
            .set("multiple", true)
            .set("label", "Package sets to copy from parent:")
            .set("description", (
                     "The package sets that will be imported " +
                     "into the derived distroseries."))
            .render(form_table_body);
    var package_copy_options =
        new ChoiceListWidget()
            .set("name", "field.package_copy_options")
            .set("type", "radio")
            .set("label", "Copy options:")
            .set("description", (
                     "Choose whether to rebuild all the sources you copy " +
                     "from the parent(s), or to copy their binaries too."))
            .set("choices", ["Copy Source and Rebuild",
                             "Copy Source and Binaries"])
            .set("choice", "Copy Source and Binaries")
            .render(form_table_body);
    var form_actions =
        new DeriveDistroSeriesActionsWidget({
            context: LP.cache.context,
            srcNode: form_container.one("div.actions"),
            deriveFromChoices: parents_selection,
            architectureChoice: architecture_choice,
            packagesetChoice: packageset_choice,
            packageCopyOptions: package_copy_options
        });

    // Wire up the add parent series link.
    var link = Y.one('#add-parent-series');
    if (Y.Lang.isValue(link)) {
        link.addClass('js-action');
        link.on('click', show_add_parent_series_form);
    }

    Y.on('add_parent', function(parent) {
        var added = parents_selection.add_parent(parent);
        if (added) {
            Y.fire("parent_added", parent);
        }
    });

    Y.on('parent_added', function(parent) {
        architecture_choice.add_distroseries(parent);
        packageset_choice.add_distroseries(parent);
    });

    Y.on('parent_removed', function(parent_id) {
        architecture_choice.remove_distroseries(parent_id);
        packageset_choice.remove_distroseries(parent_id);
    });

    // Wire up the form submission.
    form_container.one("form").on(
        "submit", function(event) {
            event.halt(); form_actions.submit(); });

    // Show the form.
    form_container.removeClass("unseen");
};


}, "0.1", {"requires": ["node", "dom", "io", "widget", "lp.client",
                        "lazr.anim", "array-extras", "transition",
                        "lp.app.picker"]});