Type.registerNamespace("CZScripts");

CZScripts.Totaller = function(element) {
   CZScripts.Totaller.initializeBase(this, [element]);
}

CZScripts.Totaller.prototype = {

    initialize: function() 
    {       
      CZScripts.Totaller.callBaseMethod(this, 'initialize');

      // create delegate for event, so we get the right this pointer
      this.delegate = Function.createDelegate(this, this.onInputUpdated);
     
      // init our total to nothing
      //this.set_CO2(Number.NaN);      
      // init our total 
      this.onInputUpdated(null);
      
      // subscribe to input update events      
      this.addHandlers(this._inputs);
    },
    
    dispose: function() {
       this.removeHandlers(this._inputs);      
       delete this.delegate;
       CZScripts.Totaller.callBaseMethod(this, 'dispose');        
    },

    get_Inputs: function() { return ""; },
    set_Inputs: function(value)
    {
      this._inputs = value.split(";");
    },
    
    addHandlers: function(inputs)
    {
       if (inputs == null) 
       {
         alert("no inputs specified for totaller");            
         return;
       }

       for (var tbname in inputs)
       {
         $find(inputs[tbname]).add_updated(this.delegate);
       }
    },
    
    removeHandlers: function(inputs)
    {  
       if (inputs == null) 
       {
         alert("no inputs specified for totaller");            
         return;
       }
          
       for (var tbname in inputs)
       {
         var src = $find(inputs[tbname]);
         if (src != null) src.remove_updated(this.delegate);
       }
    },
    
    onInputUpdated: function(e) {
       var total = 0;
       for (var tbname in this._inputs)
       {
         var editor = $find(this._inputs[tbname]);
         if (editor.get_visible())
         {
            var co2 = editor.get_CO2();
            if (!isNaN(co2))
               total = total + co2;
         }
       }
       this.set_CO2(total);
    }
   
}

CZScripts.Totaller.registerClass('CZScripts.Totaller', CZScripts.CO2Editor);
