﻿YAHOO.namespace("Hollow.Widget");

(function() {
  
  var DISABLED_FIELD_CLASS = "Disabled";
  var HIDDEN_CLASS = "Hidden";
  
  YAHOO.Hollow.Widget.Hidable = function(container, cfg){
    cfg = (cfg) ? cfg : {};
    this.container = YAHOO.util.Dom.get(container);
    this.fields = YAHOO.util.Dom.getElementsBy(function(el){return true}, "INPUT", container);
    this.selects = YAHOO.util.Dom.getElementsBy(function(el){return true}, "SELECT", container);
  };

  YAHOO.Hollow.Widget.Hidable.prototype = {
    hide: function(item){
      YAHOO.util.Dom.addClass(this.container, HIDDEN_CLASS);
    },
    
    show: function(item){
      YAHOO.util.Dom.removeClass(this.container, HIDDEN_CLASS);
    },
    
    disable: function(){
      for(var i=0;i<this.fields.length;i++){
        this.fields[i].disabled = true;
      }
      
      for(var i=0;i<this.selects.length;i++){
        this.selects[i].disabled = true;
      }
    },
    
    enable: function(){
      for(var i=0;i<this.fields.length;i++){
        this.fields[i].disabled = false;
      }
      
      for(var i=0;i<this.selects.length;i++){
        this.selects[i].disabled = false;
      }
    },
    
    hideAndDisable: function(){
      this.hide();
      this.disable();
    },
    
    showAndEnable: function(){
      this.show();
      this.enable();
    }
    
  }; 
  
  YAHOO.Hollow.Widget.HidableController = function(hidable, field, checkedMeansShow){
    this.hidable = hidable;
    this.field = YAHOO.util.Dom.get(field);
    this.checkedMeansShow = checkedMeansShow;
    this.updateHidable();
    YAHOO.util.Event.addListener(this.field, "click", this.handleFieldClick, this, true);
  };

  YAHOO.Hollow.Widget.HidableController.prototype = {
    handleFieldClick: function(ev){
      this.updateHidable();
    },
    
    handleFieldChange: function(ev){
      this.updateHidable();
    },
    
    updateHidable: function(ev){
      if(this.checkedMeansShow){
        if(this.field.checked){
            this.hidable.showAndEnable();
        }else{
            this.hidable.hideAndDisable();
        }
      }else{
        if(this.field.checked){
            this.hidable.hideAndDisable();
        }else{
            this.hidable.showAndEnable();
        }
      }
    }
  }
  
  YAHOO.Hollow.Widget.HidableFactory = {
    
    buildFromCheckBox: function(field, container, checkedMeansShow, cfg){
      var cfg = (null == cfg) ? {} : cfg;
      
      var hidable = new YAHOO.Hollow.Widget.Hidable(container);
      return new YAHOO.Hollow.Widget.HidableController(hidable, field, checkedMeansShow)
    },
  };
})();
