Atms.Calendar = function(container, anchor, show){
  container = Atms.Dom.getById(container);
  anchor = Atms.Dom.getById(anchor);
  
  if(container){
    this.container = container;
    
    var cal = this;
    
    if(anchor){
       this.anchor = anchor;
       Atms.Event.attachEvent(this.anchor, 'click', function(event){
         Atms.Event.stop(event);
         cal.toggle();
       });
       
       Atms.Event.attachEvent(window, 'resize', function(){
        cal.position();
        cal.adjustShim();
       });
    }
    
    this.hideOnDocClick = function(event){
      if(!Atms.Calendar.isChildOf(Atms.Event.getTarget(event), cal.container)){
        cal.hide();
      }
    }
    
    if(window.ActiveXObject){
      this.shim = Atms.Calendar.createShim(this.container);
    }
    
    if(show){
      this.show();
    }
  }
};

Atms.Calendar.prototype.adjustShim = function(){
  if(this.shim){
    var s = this.shim;
    var c = this.container;
    
    s.style.display = c.style.display;
    s.style.width = c.offsetWidth + "px";
    s.style.height = c.offsetHeight + "px";
    s.style.top = c.style.top;
    s.style.left = c.style.left;
    s.style.zIndex = c.style.zIndex - 1;
  }
}

Atms.Calendar.prototype.hide = function(){
  if(this.docClickAttached){
    Atms.Event.detachEvent(document, 'click', this.hideOnDocClick);
    this.docClickAttached = false;
  }
  
  this.container.style.display = 'none';
  this.adjustShim();
};

Atms.Calendar.prototype.position = function(){
  if(this.anchor){
    this.container.style.top = (this.anchor.offsetTop + this.anchor.offsetHeight) + "px";  
    this.container.style.left = ((this.anchor.offsetLeft + this.anchor.offsetWidth) - this.container.clientWidth) + "px";
  }
};

Atms.Calendar.prototype.show = function(){  
  this.container.style.display = 'block';
  this.position();
  this.adjustShim();
  
  if(!this.docClickAttached){
    Atms.Event.attachEvent(document, 'click', this.hideOnDocClick);
    this.docClickAttached = true;
  }
};

Atms.Calendar.prototype.toggle = function(){
   this.container.style.display == 'block' ? this.hide() : this.show();
};

Atms.Calendar.createShim = function(el){
  el = Atms.Dom.getById(el);
  var shim = null;
  if(el){
    shim = document.createElement('iframe');
    shim.style.position = 'absolute';
    shim.style.display = 'none';
    shim.src = '/atms/js/blank.htm';
    el.parentNode.appendChild(shim);
  }
  
  return shim;
}

Atms.Calendar.isChildOf = function(el, p){
  var parent = Atms.Dom.getById(el);
  p = Atms.Dom.getById(p);
  
  while(parent && parent != p){
    parent = parent.parentNode;
  }
    
  return parent != null;
};



