Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / ui / web / ui_networks_view.js @ a37c5497

History | View | Annotate | Download (34.6 kB)

1
// Copyright 2013 GRNET S.A. All rights reserved.
2
// 
3
// Redistribution and use in source and binary forms, with or
4
// without modification, are permitted provided that the following
5
// conditions are met:
6
// 
7
//   1. Redistributions of source code must retain the above
8
//      copyright notice, this list of conditions and the following
9
//      disclaimer.
10
// 
11
//   2. Redistributions in binary form must reproduce the above
12
//      copyright notice, this list of conditions and the following
13
//      disclaimer in the documentation and/or other materials
14
//      provided with the distribution.
15
// 
16
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
// POSSIBILITY OF SUCH DAMAGE.
28
// 
29
// The views and conclusions contained in the software and
30
// documentation are those of the authors and should not be
31
// interpreted as representing official policies, either expressed
32
// or implied, of GRNET S.A.
33
// 
34

    
35
;(function(root){
36
    
37
    // root
38
    var root = root;
39
    
40
    // setup namepsaces
41
    var snf = root.synnefo = root.synnefo || {};
42
    var models = snf.models = snf.models || {}
43
    var storage = snf.storage = snf.storage || {};
44
    var ui = snf.ui = snf.ui || {};
45
    var util = snf.util || {};
46
    var views = snf.views = snf.views || {}
47

    
48
    // shortcuts
49
    var bb = root.Backbone;
50
    
51
    // logging
52
    var logger = new snf.logging.logger("SNF-VIEWS");
53
    var debug = _.bind(logger.debug, logger);
54
    
55
    views.NetworkCreateView = views.Overlay.extend({
56
        view_id: "network_create_view",
57
        content_selector: "#networks-create-content",
58
        css_class: 'overlay-networks-create overlay-info',
59
        overlay_id: "network-create-overlay",
60

    
61
        title: "Create new private network",
62
        subtitle: "Networks",
63

    
64
        initialize: function(options) {
65
            views.NetworkCreateView.__super__.initialize.apply(this);
66

    
67
            this.create_button = this.$("form .form-action.create");
68
            this.text = this.$(".network-create-name");
69
            this.form = this.$("form");
70

    
71
            this.dhcp_select = this.$("#network-create-dhcp");
72
            this.type_select = this.$("#network-create-type");
73
            this.subnet_select = this.$("#network-create-subnet");
74
            this.subnet_custom = this.$("#network-create-subnet-custom");
75
                
76
            this.dhcp_form = this.$("#network-create-dhcp-fields");
77
            
78
            this.subnet_select.find(".subnet").remove();
79
            _.each(synnefo.config.network_suggested_subnets, function(subnet){
80
                this.subnet_select.append($('<option value='+subnet+' class="subnet">'+subnet+'</option>'));
81
            }, this);
82

    
83
            this.type_select.find(".subnet").remove();
84
            _.each(synnefo.config.network_available_types, function(name, value){
85
                this.type_select.append($('<option value='+value+' class="subnet">'+name+'</option>'));
86
            }, this);
87
            
88
            if (_.keys(synnefo.config.network_available_types).length <= 1) {
89
                this.type_select.closest(".form-field").hide();
90
            }
91

    
92
            this.check_dhcp_form();
93
            this.init_handlers();
94
        },
95

    
96
        reset_dhcp_form: function() {
97
          this.subnet_select.find("option")[0].selected = 1;
98
          this.subnet_custom.val("");
99
        },
100

    
101
        check_dhcp_form: function() {
102
            if (this.dhcp_select.is(":checked")) {
103
                this.dhcp_form.show();
104
            } else {
105
                this.dhcp_form.hide();
106
            }
107
            
108
            if (this.subnet_select.val() == "custom") {
109
                this.subnet_custom.show();
110
            } else {
111
                this.subnet_custom.hide();
112
            }
113
        },
114

    
115
        init_handlers: function() {
116

    
117
            this.dhcp_select.click(_.bind(function(e){
118
                this.check_dhcp_form();
119
                this.reset_dhcp_form();
120
            }, this));
121

    
122
            this.subnet_select.change(_.bind(function(e){
123
                this.check_dhcp_form();
124
                if (this.subnet_custom.is(":visible")) {
125
                    this.subnet_custom.focus();
126
                }
127
            }, this));
128

    
129
            this.create_button.click(_.bind(function(e){
130
                this.submit();
131
            }, this));
132

    
133
            this.form.submit(_.bind(function(e){
134
                e.preventDefault();
135
                this.submit;
136
                return false;
137
            }, this))
138

    
139
            this.text.keypress(_.bind(function(e){
140
                if (e.which == 13) {this.submit()};
141
            },this))
142
        },
143

    
144
        submit: function() {
145
            if (this.validate()) {
146
                this.create();
147
            };
148
        },
149
        
150
        validate: function() {
151
            // sanitazie
152
            var t = this.text.val();
153
            t = t.replace(/^\s+|\s+$/g,"");
154
            this.text.val(t);
155

    
156
            if (this.text.val() == "") {
157
                this.text.closest(".form-field").addClass("error");
158
                this.text.focus();
159
                return false;
160
            } else {
161
                this.text.closest(".form-field").removeClass("error");
162
            }
163
            
164
            if (this.dhcp_select.is(":checked")) {
165
                if (this.subnet_select.val() == "custom") {
166
                    var sub = this.subnet_custom.val();
167
                    sub = sub.replace(/^\s+|\s+$/g,"");
168
                    this.subnet_custom.val(sub);
169
                        
170
                    if (!synnefo.util.IP_REGEX.exec(this.subnet_custom.val())) {
171
                        this.subnet_custom.closest(".form-field").prev().addClass("error");
172
                        return false;
173
                    } else {
174
                        this.subnet_custom.closest(".form-field").prev().removeClass("error");
175
                    }
176
                };
177
            }
178

    
179
            return true;
180
        },
181
        
182
        get_next_available_subnet: function() {
183
            var auto_tpl = synnefo.config.automatic_network_range_format;
184
            if (!auto_tpl) {
185
                return null
186
            }
187
            var index = 0;
188
            var subnet = auto_tpl.format(index);
189
            var networks = synnefo.storage.networks;
190
            var check_existing = function(n) { return n.get('cidr') == subnet }
191
            while (networks.filter(check_existing).length > 0 && index <= 255) {
192
                index++;
193
                subnet = auto_tpl.format(index); 
194
            }
195
            return subnet;
196
        },
197

    
198
        create: function() {
199
            this.create_button.addClass("in-progress");
200

    
201
            var name = this.text.val();
202
            var dhcp = this.dhcp_select.is(":checked");
203
            var subnet = null;
204
            var type = this.type_select.val();
205

    
206
            if (dhcp) {
207
                if (this.subnet_select.val() == "custom") {
208
                    subnet = this.subnet_custom.val();
209
                } else if (this.subnet_select.val() == "auto") {
210
                    subnet = this.get_next_available_subnet()
211
                } else {
212
                    subnet = this.subnet_select.val();
213
                }
214
                
215
            }
216

    
217
            snf.storage.networks.create(name, type, subnet, dhcp, _.bind(function(){
218
                this.hide();
219
            }, this));
220
        },
221

    
222
        beforeOpen: function() {
223
            this.create_button.removeClass("in-progress")
224
            this.text.closest(".form-field").removeClass("error");
225
            this.text.val("");
226
            this.text.show();
227
            this.text.focus();
228
            this.subnet_custom.val("");
229
            this.subnet_select.val("auto");
230
            this.dhcp_select.attr("checked", true);
231
            this.type_select.val(_.keys(synnefo.config.network_available_types)[0]);
232
            this.check_dhcp_form();
233
        },
234

    
235
        onOpen: function() {
236
            this.text.focus();
237
        }
238
    });
239

    
240
    views.NetworkPortView = views.ext.ModelView.extend({
241
      tpl: '#network-port-view-tpl',
242
      
243
      vm_logo_url: function(vm) {
244
        if (!this.model.get('vm')) { return '' }
245
        return synnefo.ui.helpers.vm_icon_path(this.model.get('vm'), 'medium');
246
      },
247
      
248
      set_confirm: function() {
249
        var parent = this.parent_view.parent_view.el;
250
        parent.addClass("subactionpending");
251
      },
252

    
253
      unset_confirm: function() {
254
        var parent = this.parent_view.parent_view.el;
255
        parent.removeClass("subactionpending");
256
      },
257

    
258
      post_init_element: function() {
259
        this.in_progress = false;
260
        this.firewall = this.$(".firewall-content").hide();
261
        this.firewall_toggler = this.$(".firewall-toggle");
262
        this.firewall_apply = this.$(".firewall-apply");
263
        this.firewall_legends = this.firewall.find(".checkbox-legends");
264
        this.firewall_inputs = this.firewall.find("input");
265
        this.firewall_apply = this.firewall.find("button");
266
        this.firewall_visible = false;
267

    
268
        this.firewall_toggler.click(_.bind(function() {
269
          this.toggle_firewall();
270
        }, this));
271

    
272
        this.firewall.find(".checkbox-legends, input").click(
273
          _.bind(this.handle_firewall_choice_click, this));
274
        this.update_firewall();
275
      },
276
      
277
      toggle_firewall: function(e, hide, cb) {
278
          hide = hide === undefined ? false : hide;
279
          if (hide) {
280
            this.firewall.stop().hide();
281
          } else {
282
            if (!cb) { cb = function() {}}
283
            this.firewall.slideToggle(cb);
284
          }
285
          this.firewall_toggler.toggleClass("open");
286
          this.firewall_visible = this.firewall_toggler.hasClass("open");
287
          if (!this.firewall_visible) {
288
            this.firewall_apply.fadeOut(50);
289
          }
290
          this.update_firewall();
291
      },
292
    
293
      post_hide: function() {
294
        views.NetworkPortView.__super__.post_hide.apply(this);
295
        if (this.firewall_visible) {
296
          this.toggle_firewall({}, true);
297
        }
298
      },
299

    
300
      handle_firewall_choice_click: function(e) {
301
          var el = $(e.currentTarget);
302
          if (el.get(0).tagName == "INPUT") {
303
            el = el.next();
304
          }
305
          var current = this.model.get("firewall_status");
306
          var selected = el.prev().val();
307

    
308
          el.parent().find("input").attr("checked", false);
309
          el.prev().attr("checked", true);
310

    
311
          if (selected != current) {
312
            this.firewall_apply.show();
313
          } else {
314
            this.firewall_apply.hide();
315
          }
316
      },
317
      
318
      disconnect_port: function(model, e) {
319
        e && e.stopPropagation();
320
        var network = this.model.get("network");
321
        this.model.actions.reset_pending();
322
        this.model.disconnect(_.bind(this.disconnect_port_complete, this));
323
      },
324

    
325
      disconnect_port_complete: function() {
326
      },
327

    
328
      set_firewall: function() {
329
        var value = this.get_selected_value();
330
        this.firewall_apply.addClass("in-progress");
331
        this.model.set({'pending_firewall': value});
332
        this.model.set_firewall(value, this.set_firewall_complete, 
333
                                       this.set_firewall_complete);
334
        this.in_progress = true;
335
      },
336
      
337
      set_firewall_complete: function() {
338
        this.in_progress = false;
339
        this.toggle_firewall({}, false, _.bind(function() {
340
          this.firewall_apply.removeClass("in-progress").show();
341
        }, this));
342
      },
343

    
344
      get_selected_value: function() {
345
        return this.firewall_inputs.filter(":checked").val();
346
      },
347

    
348
      update_firewall: function() {
349
        var value = this.model.get("firewall_status");
350
        var value_selector = "[value=" + value + "]"
351
        var status_span = this.firewall_toggler.find("span span");
352
        var current_choice = this.firewall_inputs.filter(value_selector);
353

    
354
        if (_.contains(["PROTECTED", "ENABLED"], value)) {
355
          status_span.removeClass("firewall-off").addClass("firewall-on");
356
          status_span.text("On");
357
        } else {
358
          status_span.removeClass("firewall-on").addClass("firewall-off");
359
          status_span.text("Off");
360
        }
361
        
362
        this.firewall_inputs.attr("checked", false);
363
        this.firewall_legends.removeClass("current");
364
        current_choice.attr("checked", true)
365
        current_choice.next().addClass("current");
366
      },
367

    
368
      show_vm_details: function() {
369
        var vm = this.model.get('vm');
370
        if (vm) { snf.ui.main.show_vm_details(vm) }
371
      }
372
    });
373

    
374
    views.NetworkPortCollectionView = views.ext.CollectionView.extend({
375
      tpl: '#network-port-collection-view-tpl',
376
      model_view_cls: views.NetworkPortView,
377
      rivets_view: true,
378
      get_rivet_object: function() {
379
        return {
380
          model: this.collection.network
381
        }
382
      },
383
      resolve_storage_object: function() {
384
        return this.collection
385
      },
386

    
387
      show_connect_vms_overlay: function() {
388
        this.parent_view.show_connect_vms_overlay();
389
      }
390
    });
391

    
392
    views.NetworkView = views.ext.ModelView.extend({
393
      tpl: '#network-view-tpl',
394
      auto_bind: ['connect_vm'],
395
      post_init_element: function() {
396
        this.ports = this.$(".ports.nested-model-list");
397
        this.ports.hide();
398
        this.ports_toggler = this.$(".network-ports-toggler");
399
        this.ports_toggler.click(this.toggle_ports);
400
        this.ports_visible = false;
401
      },
402

    
403
      toggle_ports: function(e, hide) {
404
        hide = hide === undefined ? false : hide;
405
        if (hide) {
406
          this.ports.stop().hide();
407
        } else {
408
          this.ports.stop().slideToggle();
409
        }
410
        this.ports_toggler.find(".cont-toggler").toggleClass("open");
411
        this.ports_visible = this.ports_toggler.find(".cont-toggler").hasClass("open");
412
        if (this.ports_visible) {
413
          $(this.el).addClass("hovered");
414
        } else {
415
          $(this.el).removeClass("hovered");
416
        }
417
      },
418
      
419
      get_network_icon: function() {
420
        var ico = this.model.get('is_public') ? 'internet.png' : 'network.png';
421
        return synnefo.config.media_url + 'images/' + ico;
422
      },
423

    
424
      post_hide: function() {
425
        views.NetworkView.__super__.post_hide.apply(this);
426
        if (this.ports_visible) {
427
          this.toggle_ports({}, true);
428
        }
429
      },
430
      
431
      status_map: {
432
        'ACTIVE': 'Active',
433
        'CONNECTING': 'Connecting',
434
        'DISCONNECTING': 'Disconnecting',
435
        'REMOVING': 'Destroying'
436
      },
437

    
438
      status_cls_map: {
439
        'ACTIVE': 'status-active',
440
        'DISCONNECTING': 'status-progress',
441
        'CONNECTING': 'status-progress',
442
        'REMOVING': 'status-progress'
443
      },
444
      
445
      status_cls: function(status) {    
446
        return this.status_cls_map[this.model.get('ext_status')]
447
      },
448

    
449
      status_display: function(status) {
450
        var status;
451
        var cidr = this.model.get('cidr');
452
        var status = this.model.get('ext_status');
453
        if (status != 'REMOVING' && cidr) {
454
          return cidr
455
        }
456
        if (this.model.id == "snf-combined-public-network" && !_.contains(
457
          ["CONNECTING", "DISCONNECTING"], status)) {
458
          return "Internet"
459
        }
460

    
461
        return this.status_map[status];
462
      },
463
      
464
      connect_vms: function(vms, cb) {
465
        var finished = 0;
466
        var completed = function() {
467
          finished++;
468
          if (finished == vms.length) {
469
            cb();
470
          }
471
        }
472
        _.each(vms, function(vm) {
473
          this.model.connect_vm(vm, completed);
474
        }, this);
475
      },
476
      
477
      remove: function(model, e) {
478
        e && e.stopPropagation();
479
        this.model.actions.reset_pending();
480
        this.model.destroy({
481
          success: _.bind(function() {
482
            this.model.set({status: 'REMOVING'});
483
            this.model.set({ext_status: 'REMOVING'});
484
            // force status display update
485
            this.model.set({cidr: 'REMOVING'});
486
          }, this),
487
          silent: true
488
        });
489
      },
490

    
491
      show_connect_vms_overlay: function() {
492
        var view = new views.NetworkConnectVMsOverlay();
493
        vms = this.model.connectable_vms;
494
        var cb = _.bind(function(vms) {
495
          view.set_in_progress();
496
          var cbinner = function() {
497
            view.hide();
498
            delete view;
499
          }
500
          this.connect_vms(vms, cbinner);
501
        }, this);
502
        view.show_vms(this.model, vms, [], cb, "subtitle");
503
      }
504

    
505
    });
506
    
507
    views.NetworksCollectionView = views.ext.CollectionView.extend({
508
      collection: storage.networks,
509
      collection_name: 'networks',
510
      model_view_cls: views.NetworkView,
511
      create_view_cls: views.NetworkCreateView,
512
      
513
      init: function() {
514
        this.public_added = false;
515
        views.NetworksCollectionView.__super__.init.apply(this, arguments);
516
      },
517
      
518
      check_empty: function() {
519
        views.NetworksCollectionView.__super__.check_empty.apply(this, arguments);
520
        //if (this.$(".private").children().length == 0) {
521
          //this.$(".private").hide();
522
        //} else {
523
          //this.$(".private").show();
524
        //}
525
      },
526

    
527
      add_model: function(m) {
528
        if (m.get('is_public') && !this.public_added) {
529
          this.combined_public = new models.networks.CombinedPublicNetwork();
530
          this.combined_public_view = new views.NetworkView({
531
            model: this.combined_public
532
          });
533
          this.add_model_view(this.combined_public_view, this.combined_public, 0);
534
          this.public_added = true;
535
        }
536
        return views.NetworksCollectionView.__super__.add_model.call(this, m);
537
      },
538

    
539
      remove_model: function(m) {
540
        if (m.id == 'snf-combined-public-network') {
541
          return;
542
        } else {
543
          return views.NetworksCollectionView.__super__.remove_model.call(this, m);
544
        }
545
      },
546

    
547
      get_model_view_cls: function(m) {
548
        if (!this.public_added) {
549
        }
550
        if (m.get('is_public')) {
551
          return false;
552
        }
553
        return views.NetworksCollectionView.__super__.get_model_view_cls.apply(this, [m]);
554
      },
555
      
556
      parent_for_model: function(m) {
557
        if (m.get('is_public')) {
558
          return this.list_el.find(".public");
559
        } else {
560
          return this.list_el.find(".private");
561
        }
562
      }
563
    });
564

    
565
    views.NetworksPaneView = views.ext.PaneView.extend({
566
      id: "pane",
567
      el: '#networks-pane',
568
      collection_view_cls: views.NetworksCollectionView,
569
      collection_view_selector: '#networks-list-view'
570
    });
571
    
572
    views.VMSelectView = views.ext.SelectModelView.extend({
573
      tpl: '#vm-select-model-tpl',
574
      get_vm_icon: function() {
575
        return $(snf.ui.helpers.vm_icon_tag(this.model, "small")).attr("src")
576
      },
577

    
578
      status_cls: function() {
579
        return (views.IconView.STATE_CLASSES[this.model.get("state")] || []).join(" ") + " status clearfix"
580
      },
581
      status_display: function() {
582
        return STATE_TEXTS[this.model.get("state")]
583
      }
584
    });
585

    
586
    views.VMSelectView = views.ext.CollectionView.extend({
587
      init: function() {
588
        views.VMSelectView.__super__.init.apply(this);
589
      },
590
      tpl: '#vm-select-collection-tpl',
591
      model_view_cls: views.VMSelectView,
592
      
593
      trigger_select: function(view, select) {
594
        this.trigger("change:select", view, select);
595
      },
596

    
597
      post_add_model_view: function(view) {
598
        view.bind("change:select", this.trigger_select, this);
599
        if (!this.options.allow_multiple) {
600
          view.input.prop("type", "radio");
601
        }
602
      },
603

    
604
      post_remove_model_view: function(view) {
605
        view.unbind("change:select", this.trigger_select, this);
606
      },
607

    
608
      deselect_all: function(except) {
609
        _.each(this._subviews, function(view) {
610
          if (view != except) { view.deselect() }
611
        });
612
      },
613

    
614
      get_selected: function() {
615
        return _.filter(_.map(this._subviews, function(view) {
616
          if (view.selected) {
617
            return view.model;
618
          }
619
        }), function(m) { return m });
620
      }
621
    });
622

    
623
    views.NetworkConnectVMsOverlay = views.Overlay.extend({
624
        title: "Connect machine",
625
        overlay_id: "overlay-select-vms",
626
        content_selector: "#network-vms-select-content",
627
        css_class: "overlay-info",
628
        allow_multiple: true,
629

    
630
        initialize: function() {
631
            views.NetworkConnectVMsOverlay.__super__.initialize.apply(this);
632
            this.list = this.$(".vms-list ul");
633
            this.empty_message = this.$(".empty-message");
634
            // flag for submit handler to avoid duplicate bindings
635
            this.submit_handler_set = false;
636
            this.in_progress = false;
637

    
638
        },
639
        
640
        init_collection_view: function(collection) {
641
            this.collection_view = new views.VMSelectView({
642
              collection: collection,
643
              el: this.list,
644
              allow_multiple: this.allow_multiple
645
            });
646
            this.collection_view.show(true);
647
            this.list.append($(this.collection_view.el));
648
            if (!this.allow_multiple) {
649
              this.collection_view.bind("change:select", 
650
                                        function(view, selected) {
651
                if (!selected) { return }
652
                this.collection_view.deselect_all(view);
653
              }, this);
654
            }
655
        },
656

    
657
        handle_vm_click: function(el) {
658
            if (!this.allow_multiple) {
659
              $(el).closest("ul").find(".selected").removeClass("selected");
660
              $(el).addClass("selected");
661
            } else {
662
              $(el).toggleClass("selected");
663
            }
664
        },
665

    
666
        init_handlers: function() {
667
            var self = this;
668
            
669
            if (!this.submit_handler_set) {
670
                // avoid duplicate submits
671
                this.el.find(".create, .assign").click(_.bind(function() {
672
                  if (!this.in_progress) {
673
                    this.submit();
674
                  }
675
                }, this));
676
                this.submit_handler_set = true;
677
            }
678
        },
679
        
680
        reset: function() {},
681
        beforeOpen: function() {
682
            this.reset();
683
            this.update_layout();
684
        },
685
        
686
        get_selected: function() {
687
          return this.collection_view.get_selected();
688
        },
689

    
690
        update_layout: function() {
691
            this.unset_in_progress();
692
            this.in_progress = false;
693

    
694
            if (this.vms.length == 0) {
695
                this.empty_message.show();
696
            } else {
697
                this.empty_message.hide();
698
            }
699

    
700
            this.init_handlers();
701
        },
702

    
703
        set_in_progress: function() {
704
          this.$(".form-action").addClass("in-progress");
705
          this.in_progress = true;
706
        },
707

    
708
        unset_in_progress: function() {
709
          this.$(".form-action").removeClass("in-progress");
710
          this.in_progress = false;
711
        },
712

    
713
        show_vms: function(network, vms, selected, callback, subtitle) {
714
            this.init_collection_view(vms);
715
            this.network = network;
716
            this.reset();
717
            if (network) {
718
              this.set_subtitle(network.escape("name"));
719
            } else {
720
              this.set_subtitle(subtitle);
721
            }
722
            this.vms = vms;
723
            this.selected = selected;
724
            this.cb = callback;
725
            this.unset_in_progress();
726
            this.show(true);
727
        },
728
        
729
        onClose: function() {
730
          this.collection_view.hide(true);
731
          delete this.collection_view;
732
        },
733

    
734
        submit: function() {
735
            if (!this.get_selected().length) { return }
736
            this.cb(this.get_selected());
737
        }
738
    });
739
    
740
    views.NetworkSelectModelView = views.ext.SelectModelView.extend({});
741

    
742
    views.NetworkSelectNetworkTypeModelView = views.NetworkSelectModelView.extend({
743
      get_network_icon: function() {
744
        var ico = this.model.get('is_public') ? 'internet-small.png' : 'network-small.png';
745
        return synnefo.config.media_url + 'images/' + ico;
746
      },
747
      forced_title: 'You machine will be automatically connected ' +
748
                    'to this network.'
749
    });
750

    
751
    views.NetworkSelectPublicNetwork = views.NetworkSelectNetworkTypeModelView.extend({
752
      tpl: '#networks-select-public-item-tpl',
753
      classes: 'public-network',
754
      post_init_element: function() {
755
        views.NetworkSelectPublicNetwork.__super__.post_init_element.apply(this);
756
        //$(this.el).attr('title', 'Public network tooltip');
757
        //$(this.el).tooltip({
758
          //'tipClass': 'tooltip', 
759
          //'position': 'top center',
760
          //'offset': [-5, 0]
761
        //});
762

    
763
      }
764
    });
765

    
766
    views.NetworkSelectPrivateNetwork = views.NetworkSelectNetworkTypeModelView.extend({
767
      tpl: '#networks-select-private-item-tpl',
768
      classes: 'private-network'
769
    });
770
    
771
    views.NetworkSelectTypeView = views.ext.CollectionView.extend({});
772
    views.NetworkSelectPublicNetworks = views.NetworkSelectTypeView.extend({
773
      tpl: '#networks-select-public-tpl',
774
      model_view_cls: views.NetworkSelectPublicNetwork,
775
      get_floating_ips: function() {
776
        var ips = [];
777
        _.each(this._subviews, function(view) {
778
          _.each(view._subviews, function(view) {
779
            if (view.selected_ips) {
780
              _.each(view.selected_ips, function(m) {
781
                ips.push(m.id);
782
              }, this);
783
            }
784
          }, this);
785
        }, this);
786
        return ips;
787
      }
788
    });
789
    
790
    views.NetworkSelectFloatingIpView = views.NetworkSelectModelView.extend({
791
      tpl: '#networks-select-floating-ip-tpl'
792
    });
793

    
794
    views.NetworkSelectFloatingIpsView = views.ext.CollectionView.extend({
795
      tpl: '#networks-select-floating-ips-tpl',
796
      model_view_cls: views.NetworkSelectFloatingIpView,
797

    
798
      select_if_available: function() {
799
        var selected = false;
800
        if (this._subviews[0]) {
801
          this._subviews[0].select();
802
        }
803
      },
804

    
805
      deselect_all: function() {
806
        this.each_ip_view(function(v) { v.deselect() });
807
      },
808

    
809
      each_ip_view: function(cb) {
810
        _.each(this._subviews, function(view) {
811
          if (view instanceof views.NetworkSelectFloatingIpView) {
812
            cb(view);
813
          }
814
        })
815
      },
816

    
817
      post_init: function() {
818
        var parent = this.parent_view;
819
        var self = this;
820

    
821
        this.quota = synnefo.storage.quotas.get("cyclades.floating_ip");
822
        this.selected_ips = [];
823
        this.handle_ip_select = _.bind(this.handle_ip_select, this);
824
        this.create = this.$(".floating-ip.create");
825
        
826
        this.quota.bind("change", _.bind(this.update_available, this));
827
        this.collection.bind("change", _.bind(this.update_available, this))
828
        this.collection.bind("add", _.bind(this.update_available, this))
829
        this.collection.bind("remove", _.bind(this.update_available, this))
830

    
831
        parent.bind("change:select", function(view, selected) {
832
          if (selected) { this.show_parent() } else { this.hide_parent() }
833
        }, this);
834

    
835
        this.create.click(function(e) {
836
          e.preventDefault();
837
          self.create_ip();
838
        });
839
        this.update_available();
840
      },
841
      
842
      hide_parent: function() {
843
        this.parent_view.item.removeClass("selected");
844
        this.parent_view.input.attr("checked", false);
845
        this.parent_view.selected = false;
846
        this.deselect_all();
847
        this.hide(true);
848
      },
849

    
850
      show_parent: function() {
851
        var left = this.quota.get_available();
852
        var available = this.collection.length || left;
853
        if (!available) { 
854
          this.hide_parent();
855
          return;
856
        }
857
        this.parent_view.item.addClass("selected");
858
        this.parent_view.input.attr("checked", true);
859
        this.parent_view.selected = true;
860
        this.show(true);
861
        this.select_if_available();
862
      },
863

    
864
      update_available: function() {
865
        var left = this.quota.get_available();
866
        var available = this.collection.length || left;
867
        var available_el = this.parent_view.$(".available");
868
        var no_available_el = this.parent_view.$(".no-available");
869
        var create = this.$(".create.model-item");
870
        var create_link = this.$(".create a");
871
        var create_no_available = this.$(".create .no-available");
872

    
873
        if (!available) {
874
          // no ip's available to select
875
          this.hide_parent();
876
          available_el.hide();
877
          no_available_el.show();
878
        } else {
879
          // available floating ip
880
          var available_text = "{0} IP's available.".format(
881
            this.collection.length + this.quota.get_available());
882
          available_el.removeClass("hidden").text(available_text).show();
883
          available_el.show();
884
          no_available_el.hide();
885
        }
886

    
887
        if (left) {
888
          // available quota
889
          create.removeClass("no-available");
890
          create.show();
891
          create_link.show();
892
          create_no_available.hide();
893
        } else {
894
          // no available quota
895
          create.addClass("no-available");
896
          create.show();
897
          create_link.hide();
898
          create_no_available.show();
899
        }
900
        //
901
        this.update_selected();
902
      },
903
      
904
      update_selected: function() {
905
        if (this.selected_ips.length) {
906
          this.parent_view.input.attr("checked", true);
907
          this.parent_view.item.addClass("selected");
908
          this.parent_view.item.selected = true;
909
        } else {
910
          this.parent_view.input.attr("checked", false);
911
          this.parent_view.item.removeClass("selected");
912
          this.parent_view.item.selected = false;
913
        }
914
      },
915

    
916
      post_remove_model_view: function(view) {
917
        view.deselect();
918
        view.unbind("change:select", this.handle_ip_select)
919
      },
920

    
921
      handle_create_error: function() {},
922

    
923
      create_ip: function() {
924
        if (!this.quota.get_available()) { return }
925
        synnefo.storage.floating_ips.create({floatingip:{}}, {
926
          error: _.bind(this.handle_create_error, this),
927
          skip_api_error: true
928
        });
929
      },
930

    
931
      post_add_model_view: function(view, model) {
932
        view.bind("change:select", this.handle_ip_select)
933
        if (!this.selected_ips.length && this._subviews.length == 1) {
934
          this._subviews[0].select();
935
          if (!_.contains(this.selected_ips, model)) {
936
            this.selected_ips.push(model);
937
          }
938
        }
939
      },
940

    
941
      handle_ip_select: function(view) {
942
        if (view.selected) {
943
          if (!_.contains(this.selected_ips, view.model)) {
944
            this.selected_ips.push(view.model);
945
          }
946
        } else {
947
          this.selected_ips = _.without(this.selected_ips, view.model);
948
        }
949
        this.update_selected();
950
      },
951
      
952
      post_show: function() {
953
        this.update_available();
954
      },
955

    
956
      get_floating_ips: function() {
957
        return this.selected_ips;
958
      }
959
    });
960

    
961
    views.NetworkSelectPrivateNetworks = views.NetworkSelectTypeView.extend({
962
      tpl: '#networks-select-private-tpl',
963
      model_view_cls: views.NetworkSelectPrivateNetwork,
964
      get_networks: function() {
965
        return _.filter(_.map(this._subviews, function(view) {
966
          if (view.selected) { return view.model.id }
967
        }), function(id) { return id });
968
      }
969

    
970
    });
971

    
972
    views.NetworkSelectView = views.ext.ModelView.extend({
973
      rivets_view: true,
974
      tpl: '#networks-select-view-tpl',
975
      select_public: true,
976
      
977
      forced_values_title_map: {
978
        "SNF:ANY_PUBLIC_IPV6": "Public IPv6 Network",
979
        "SNF:ANY_PUBLIC_IPV4": "Public IPv4 Network"
980
      },
981

    
982
      initialize: function(options) {
983
        this.quotas = synnefo.storage.quotas.get('cyclades.private_network');
984
        options = options || {};
985
        options.model = options.model || new models.Model();
986
        this.private_networks = new Backbone.FilteredCollection(undefined, {
987
          collection: synnefo.storage.networks,
988
          collectionFilter: function(m) {
989
            return !m.get('is_public')
990
        }});
991

    
992
        this.public_networks = new Backbone.Collection();
993
        this.public_networks.comparator = function(m) {
994
          if (m.get('forced')) {
995
            return -1
996
          }  
997
          return 100;
998
        }
999
        
1000
        if (synnefo.config.forced_server_networks.length) {
1001
          _.each(synnefo.config.forced_server_networks, function(network) {
1002
            var forced = synnefo.storage.networks.get(network);
1003
            if (!forced) {
1004
              var name = this.forced_values_title_map[network];
1005
              if (!name) { name = "Forced network ({0})".format(network)}
1006
              forced = new models.networks.Network({
1007
                id: network,
1008
                name: name, 
1009
                subnets: [],
1010
                is_public: true,
1011
                forced: true
1012
              });
1013
            } else {
1014
              forced.set({'forced': true});
1015
            }
1016
            this.public_networks.add(forced);
1017
          }, this);
1018
        }
1019

    
1020
        // combined public
1021
        this.combined_public = new models.networks.CombinedPublicNetwork();
1022
        this.combined_public.set({noselect: true, name: 'Internet', forced: false});
1023
        this.public_networks.add(this.combined_public);
1024

    
1025
        model_attrs = {
1026
          public_collection: this.public_networks,
1027
          private_collection: this.private_networks,
1028
          floating_selected: true
1029
        }
1030

    
1031
        options.model.set(model_attrs);
1032
        this._configure(options);
1033
        return views.NetworkSelectView.__super__.initialize.call(this, options);
1034
      },
1035

    
1036
      get_selected_floating_ips: function() {
1037
        var ips = [];
1038
        _.each(this._subviews, function(view) {
1039
          if (view.get_floating_ips) {
1040
            ips = _.union(ips, view.get_floating_ips());
1041
          }
1042
        }, this);
1043
        return _.filter(
1044
          _.map(ips, function(ipid) { 
1045
          return synnefo.storage.floating_ips.get(parseInt(ipid))
1046
        }), function(ip) { console.log("IP", ip); return ip });
1047
      },
1048

    
1049
      get_selected_networks: function() {
1050
        var networks = [];
1051
        _.each(this._subviews, function(view) {
1052
          if (view.get_networks) {
1053
            networks = _.union(networks, view.get_networks());
1054
          }
1055
        }, this);
1056
        return _.filter(
1057
          _.map(networks, function(netid) { 
1058
          return synnefo.storage.networks.get(netid)
1059
        }), function(net) { return net });
1060
      }
1061
    });
1062
 
1063
})(this);