Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (35.2 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
        this.model.actions.reset_pending();
321
        this.model.disconnect(_.bind(this.disconnect_port_complete, this));
322
      },
323

    
324
      disconnect_port_complete: function() {
325
      },
326

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

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

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

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

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

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

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

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

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

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

    
447
      status_display: function(status) {
448
        var status;
449
        if (this.model.id == "snf-combined-public-network") {
450
          return "Internet"
451
        }
452

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
777
      }
778
    });
779

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
935
      handle_create_error: function() {},
936

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

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

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

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

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

    
984
    });
985

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

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

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

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

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

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

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

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