Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (35.3 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
      show_connect_vms_overlay: function() {
387
        this.parent_view.show_connect_vms_overlay();
388
      }
389
    });
390

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

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

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

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

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

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

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

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

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

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

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

    
564
    views.NetworksPaneView = views.ext.PaneView.extend({
565
      id: "pane",
566
      el: '#networks-pane',
567
      collection_view_cls: views.NetworksCollectionView,
568
      collection_view_selector: '#networks-list-view'
569
    });
570

    
571
    views.NetworkConnectVMsOverlay = views.Overlay.extend({
572
        title: "Connect machine",
573
        overlay_id: "overlay-select-vms",
574
        content_selector: "#network-vms-select-content",
575
        css_class: "overlay-info",
576
        allow_multiple: true,
577

    
578
        initialize: function() {
579
            views.NetworkConnectVMsOverlay.__super__.initialize.apply(this);
580
            this.list = this.$(".vms-list ul");
581
            this.empty_message = this.$(".empty-message");
582
            // flag for submit handler to avoid duplicate bindings
583
            this.submit_handler_set = false;
584
            this.in_progress = false;
585
        },
586
        
587
        handle_vm_click: function(el) {
588
            if (!this.allow_multiple) {
589
              $(el).closest("ul").find(".selected").removeClass("selected");
590
              $(el).addClass("selected");
591
            } else {
592
              $(el).toggleClass("selected");
593
            }
594
        },
595

    
596
        init_handlers: function() {
597
            var self = this;
598
            this.list.find("li").click(function() {
599
                self.handle_vm_click($(this));
600
            });
601
            
602
            if (!this.submit_handler_set) {
603
                // avoid duplicate submits
604
                this.el.find(".create, .assign").click(_.bind(function() {
605
                  if (!this.in_progress) {
606
                    this.submit();
607
                  }
608
                }, this));
609
                this.submit_handler_set = true;
610
            }
611
        },
612

    
613
        reset: function() {
614
            this.list.find("li").remove();
615
        },
616

    
617
        beforeOpen: function() {
618
            this.reset();
619
            this.update_layout();
620
        },
621
        
622
        vm: function(vm) {
623
            if (vm.id) { var id = vm.id } else {var id = vm}
624
            return this.list.find(".vm-" + id);
625
        },
626

    
627
        get_selected: function() {
628
            return this.list.find(".selected").map(function() {return $(this).data('vm')})
629
        },
630

    
631
        update_layout: function() {
632
            this.unset_in_progress();
633
            this.in_progress = false;
634

    
635
            if (this.vms.length == 0) {
636
                this.empty_message.show();
637
            } else {
638
                this.empty_message.hide();
639
            }
640

    
641
            _.each(this.vms, _.bind(function(vm){
642
                var html = '<li class="vm option options-object vm-{0}">' +
643
                           '<div class="options-object-cont">' +
644
                           '{2}' + 
645
                           '<span class="title">{1}</span>' + 
646
                           '<span class="value">{3}</span></div>' + 
647
                           '</li>';
648
                var el = $(html.format(vm.id, 
649
                       util.truncate(_.escape(vm.get("name")), 23), 
650
                       snf.ui.helpers.vm_icon_tag(vm, "small", {'class':'os'}),
651
                       _.escape(vm.get_os())
652
                ));
653
                el.data({vm:vm, vm_id:vm.id});
654
                this.list.append(el);
655

    
656
                vm.bind("remove", function(){ el.remove()})
657
                vm.bind("change:name", function(i,v){el.find(".title").text(v)})
658
            }, this));
659
            
660
            this.init_handlers();
661
            this.set_selected();
662
        },
663

    
664
        set_selected: function() {
665
            _.each(this.selected, _.bind(function(el){
666
                this.vm(el).addClass("selected");
667
            }, this));
668
        },
669
        
670
        set_in_progress: function() {
671
          this.$(".form-action").addClass("in-progress");
672
          this.in_progress = true;
673
        },
674

    
675
        unset_in_progress: function() {
676
          this.$(".form-action").removeClass("in-progress");
677
          this.in_progress = false;
678
        },
679

    
680
        show_vms: function(network, vms, selected, callback, subtitle) {
681
            this.network = network;
682
            this.reset();
683
            if (network) {
684
              this.set_subtitle(network.escape("name"));
685
            } else {
686
              this.set_subtitle(subtitle);
687
            }
688
            this.vms = vms;
689
            this.selected = selected;
690
            this.cb = callback;
691
            this.unset_in_progress();
692
            this.show(true);
693
        },
694

    
695
        submit: function() {
696
            if (!this.get_selected().length) { return }
697
            this.cb(this.get_selected());
698
        }
699
    });
700
    
701
    views.NetworkSelectModelView = views.ext.ModelView.extend({
702
      select: function() {
703
        if (!this.delegate_checked) {
704
          this.input.attr("checked", true);
705
          this.item.addClass("selected");
706
        }
707
        this.selected = true;
708
        this.trigger("change:select", this, this.selected);
709
      },
710

    
711
      deselect: function() {
712
        if (!this.delegate_checked) {
713
          this.input.attr("checked", false);
714
          this.item.removeClass("selected");
715
        }
716
        this.selected = false;
717
        this.trigger("change:select", this, this.selected);
718
      },
719
      
720
      toggle_select: function() {
721
        if (this.selected) { 
722
          this.deselect();
723
        } else {
724
          this.select();
725
        }
726
      },
727

    
728
      post_init_element: function() {
729
        this.input = $(this.$("input").get(0));
730
        this.item = $(this.$(".select-item").get(0));
731
        this.delegate_checked = this.model.get('noselect');
732
        this.deselect();
733

    
734
        var self = this;
735
        if (self.model.get('forced')) {
736
          this.select();
737
          this.input.attr("disabled", true);
738
          $(this.el).attr('title', this.forced_title);
739
          $(this.el).tooltip({
740
            'tipClass': 'tooltip', 
741
            'position': 'top center',
742
            'offset': [29, 0]
743
          });
744
        }
745
        
746
        $(this.item).click(function(e) {
747
          if (self.model.get('forced')) { return }
748
          e.stopPropagation();
749
          self.toggle_select();
750
        });
751
        
752
        views.NetworkSelectModelView.__super__.post_init_element.apply(this,
753
                                                                       arguments);
754
      }
755
    });
756

    
757
    views.NetworkSelectNetworkTypeModelView = views.NetworkSelectModelView.extend({
758
      get_network_icon: function() {
759
        var ico = this.model.get('is_public') ? 'internet-small.png' : 'network-small.png';
760
        return synnefo.config.media_url + 'images/' + ico;
761
      },
762
      forced_title: 'You machine will be automatically connected ' +
763
                    'to this network.'
764
    });
765

    
766
    views.NetworkSelectPublicNetwork = views.NetworkSelectNetworkTypeModelView.extend({
767
      tpl: '#networks-select-public-item-tpl',
768
      classes: 'public-network',
769
      post_init_element: function() {
770
        views.NetworkSelectPublicNetwork.__super__.post_init_element.apply(this);
771
        //$(this.el).attr('title', 'Public network tooltip');
772
        //$(this.el).tooltip({
773
          //'tipClass': 'tooltip', 
774
          //'position': 'top center',
775
          //'offset': [-5, 0]
776
        //});
777

    
778
      }
779
    });
780

    
781
    views.NetworkSelectPrivateNetwork = views.NetworkSelectNetworkTypeModelView.extend({
782
      tpl: '#networks-select-private-item-tpl',
783
      classes: 'private-network'
784
    });
785
    
786
    views.NetworkSelectTypeView = views.ext.CollectionView.extend({});
787
    views.NetworkSelectPublicNetworks = views.NetworkSelectTypeView.extend({
788
      tpl: '#networks-select-public-tpl',
789
      model_view_cls: views.NetworkSelectPublicNetwork,
790
      get_floating_ips: function() {
791
        var ips = [];
792
        _.each(this._subviews, function(view) {
793
          _.each(view._subviews, function(view) {
794
            if (view.selected_ips) {
795
              _.each(view.selected_ips, function(m) {
796
                ips.push(m.id);
797
              }, this);
798
            }
799
          }, this);
800
        }, this);
801
        return ips;
802
      }
803
    });
804
    
805
    views.NetworkSelectFloatingIpView = views.NetworkSelectModelView.extend({
806
      tpl: '#networks-select-floating-ip-tpl'
807
    });
808

    
809
    views.NetworkSelectFloatingIpsView = views.ext.CollectionView.extend({
810
      tpl: '#networks-select-floating-ips-tpl',
811
      model_view_cls: views.NetworkSelectFloatingIpView,
812

    
813
      select_if_available: function() {
814
        var selected = false;
815
        if (this._subviews[0]) {
816
          this._subviews[0].select();
817
        }
818
      },
819

    
820
      deselect_all: function() {
821
        this.each_ip_view(function(v) { v.deselect() });
822
      },
823

    
824
      each_ip_view: function(cb) {
825
        _.each(this._subviews, function(view) {
826
          if (view instanceof views.NetworkSelectFloatingIpView) {
827
            cb(view);
828
          }
829
        })
830
      },
831

    
832
      post_init: function() {
833
        var parent = this.parent_view;
834
        var self = this;
835

    
836
        this.quota = synnefo.storage.quotas.get("cyclades.floating_ip");
837
        this.selected_ips = [];
838
        this.handle_ip_select = _.bind(this.handle_ip_select, this);
839
        this.create = this.$(".floating-ip.create");
840
        
841
        this.quota.bind("change", _.bind(this.update_available, this));
842
        this.collection.bind("change", _.bind(this.update_available, this))
843
        this.collection.bind("add", _.bind(this.update_available, this))
844
        this.collection.bind("remove", _.bind(this.update_available, this))
845

    
846
        parent.bind("change:select", function(view, selected) {
847
          if (selected) { this.show_parent() } else { this.hide_parent() }
848
        }, this);
849

    
850
        this.create.click(function(e) {
851
          e.preventDefault();
852
          self.create_ip();
853
        });
854
        this.update_available();
855
      },
856
      
857
      hide_parent: function() {
858
        this.parent_view.item.removeClass("selected");
859
        this.parent_view.input.attr("checked", false);
860
        this.parent_view.selected = false;
861
        this.deselect_all();
862
        this.hide(true);
863
      },
864

    
865
      show_parent: function() {
866
        var left = this.quota.get_available();
867
        var available = this.collection.length || left;
868
        if (!available) { 
869
          this.hide_parent();
870
          return;
871
        }
872
        this.parent_view.item.addClass("selected");
873
        this.parent_view.input.attr("checked", true);
874
        this.parent_view.selected = true;
875
        this.show(true);
876
        this.select_if_available();
877
      },
878

    
879
      update_available: function() {
880
        var left = this.quota.get_available();
881
        var available = this.collection.length || left;
882
        var available_el = this.parent_view.$(".available");
883
        var no_available_el = this.parent_view.$(".no-available");
884
        var create = this.$(".create.model-item");
885
        var create_link = this.$(".create a");
886
        var create_no_available = this.$(".create .no-available");
887

    
888
        if (!available) {
889
          // no ip's available to select
890
          this.hide_parent();
891
          available_el.hide();
892
          no_available_el.show();
893
        } else {
894
          // available floating ip
895
          var available_text = "{0} IP's available.".format(
896
            this.collection.length + this.quota.get_available());
897
          available_el.removeClass("hidden").text(available_text).show();
898
          available_el.show();
899
          no_available_el.hide();
900
        }
901

    
902
        if (left) {
903
          // available quota
904
          create.removeClass("no-available");
905
          create.show();
906
          //create_link.show();
907
          create_no_available.hide();
908
        } else {
909
          // no available quota
910
          create.addClass("no-available");
911
          create.show();
912
          //create_link.hide();
913
          create_no_available.show();
914
        }
915
        //
916
        this.update_selected();
917
      },
918
      
919
      update_selected: function() {
920
        if (this.selected_ips.length) {
921
          this.parent_view.input.attr("checked", true);
922
          this.parent_view.item.addClass("selected");
923
          this.parent_view.item.selected = true;
924
        } else {
925
          this.parent_view.input.attr("checked", false);
926
          this.parent_view.item.removeClass("selected");
927
          this.parent_view.item.selected = false;
928
        }
929
      },
930

    
931
      post_remove_model_view: function(view) {
932
        view.deselect();
933
        view.unbind("change:select", this.handle_ip_select)
934
      },
935

    
936
      handle_create_error: function() {},
937

    
938
      create_ip: function() {
939
        if (!this.quota.get_available()) { return }
940
        synnefo.storage.floating_ips.create({floatingip:{}}, {
941
          error: _.bind(this.handle_create_error, this),
942
          skip_api_error: true
943
        });
944
      },
945

    
946
      post_add_model_view: function(view, model) {
947
        view.bind("change:select", this.handle_ip_select)
948
        if (!this.selected_ips.length && this._subviews.length == 1) {
949
          this._subviews[0].select();
950
          if (!_.contains(this.selected_ips, model)) {
951
            this.selected_ips.push(model);
952
          }
953
        }
954
      },
955

    
956
      handle_ip_select: function(view) {
957
        if (view.selected) {
958
          if (!_.contains(this.selected_ips, view.model)) {
959
            this.selected_ips.push(view.model);
960
          }
961
        } else {
962
          this.selected_ips = _.without(this.selected_ips, view.model);
963
        }
964
        this.update_selected();
965
      },
966
      
967
      post_show: function() {
968
        this.update_available();
969
      },
970

    
971
      get_floating_ips: function() {
972
        return this.selected_ips;
973
      }
974
    });
975

    
976
    views.NetworkSelectPrivateNetworks = views.NetworkSelectTypeView.extend({
977
      tpl: '#networks-select-private-tpl',
978
      model_view_cls: views.NetworkSelectPrivateNetwork,
979
      get_networks: function() {
980
        return _.filter(_.map(this._subviews, function(view) {
981
          if (view.selected) { return view.model.id }
982
        }), function(id) { return id });
983
      }
984

    
985
    });
986

    
987
    views.NetworkSelectView = views.ext.ModelView.extend({
988
      rivets_view: true,
989
      tpl: '#networks-select-view-tpl',
990
      select_public: true,
991
      
992
      forced_values_title_map: {
993
        "SNF:ANY_PUBLIC_IPV6": "Public IPv6 Network",
994
        "SNF:ANY_PUBLIC_IPV4": "Public IPv4 Network"
995
      },
996

    
997
      initialize: function(options) {
998
        this.quotas = synnefo.storage.quotas.get('cyclades.private_network');
999
        options = options || {};
1000
        options.model = options.model || new models.Model();
1001
        this.private_networks = new Backbone.FilteredCollection(undefined, {
1002
          collection: synnefo.storage.networks,
1003
          collectionFilter: function(m) {
1004
            return !m.get('is_public')
1005
        }});
1006

    
1007
        this.public_networks = new Backbone.Collection();
1008
        this.public_networks.comparator = function(m) {
1009
          if (m.get('forced')) {
1010
            return -1
1011
          }  
1012
          return 100;
1013
        }
1014
        
1015
        if (synnefo.config.forced_server_networks.length) {
1016
          _.each(synnefo.config.forced_server_networks, function(network) {
1017
            var forced = synnefo.storage.networks.get(network);
1018
            if (!forced) {
1019
              var name = this.forced_values_title_map[network];
1020
              if (!name) { name = "Forced network ({0})".format(network)}
1021
              forced = new models.networks.Network({
1022
                id: network,
1023
                name: name, 
1024
                subnets: [],
1025
                is_public: true,
1026
                forced: true
1027
              });
1028
            } else {
1029
              forced.set({'forced': true});
1030
            }
1031
            this.public_networks.add(forced);
1032
          }, this);
1033
        }
1034

    
1035
        // combined public
1036
        this.combined_public = new models.networks.CombinedPublicNetwork();
1037
        this.combined_public.set({noselect: true, name: 'Internet', forced: false});
1038
        this.public_networks.add(this.combined_public);
1039

    
1040
        model_attrs = {
1041
          public_collection: this.public_networks,
1042
          private_collection: this.private_networks,
1043
          floating_selected: true
1044
        }
1045

    
1046
        options.model.set(model_attrs);
1047
        this._configure(options);
1048
        return views.NetworkSelectView.__super__.initialize.call(this, options);
1049
      },
1050

    
1051
      get_selected_floating_ips: function() {
1052
        var ips = [];
1053
        _.each(this._subviews, function(view) {
1054
          if (view.get_floating_ips) {
1055
            ips = _.union(ips, view.get_floating_ips());
1056
          }
1057
        }, this);
1058
        return _.filter(
1059
          _.map(ips, function(ipid) { 
1060
          return synnefo.storage.floating_ips.get(parseInt(ipid))
1061
        }), function(ip) { console.log("IP", ip); return ip });
1062
      },
1063

    
1064
      get_selected_networks: function() {
1065
        var networks = [];
1066
        _.each(this._subviews, function(view) {
1067
          if (view.get_networks) {
1068
            networks = _.union(networks, view.get_networks());
1069
          }
1070
        }, this);
1071
        return _.filter(
1072
          _.map(networks, function(netid) { 
1073
          return synnefo.storage.networks.get(netid)
1074
        }), function(net) { return net });
1075
      }
1076
    });
1077
 
1078
})(this);