var modalBox = null;
var backDrop = null;
var numModalBoxes = 0;
var modalBoxes = [];

ModalBox = Class.create();

ModalBox.prototype = {
  modalBoxElement: null,
  backDropElement: null,
  containerElement: null, // contains all the modal boxes
  width: null,
  height: null,
  initialize: function(displayHTML) {
    this.backDropElement = $('backdrop');
    this.containerElement = $('modalboxcontainer');
    this.modalBoxElement = new Element('div', {
      'class': 'modalbox',
      'style': 'display:none'
    }).update(displayHTML);
    this.modalBoxElement.addClassName('modalbox');
    this.containerElement.insert(this.modalBoxElement, {
      position: 'bottom'
    });
    this.modalBoxElement.select('.close').each( function(doneButton) {
      Event.observe(doneButton, 'click', this.close.bindAsEventListener(this));
    }.bind(this));
    this.open();
  },
  reposition: function() {
    this.width = this.modalBoxElement.getWidth();
    this.height = this.modalBoxElement.getHeight();
    var offset = numModalBoxes * 10;
    this.modalBoxElement.setStyle({
      marginLeft:'-'+ (this.width / 2)-offset +'px',
      marginTop:'-'+ (this.height / 2)-offset +'px'
    });
  },
  close: function() {
//    console.log('closing');
    numModalBoxes--;
    if (numModalBoxes == 0) {
      this.backDropElement.fade( {
        duration: 0.5,
        from: 0.6,
        to: 0
      } );
    }
    this.modalBoxElement.fade( {
      duration: 0.5
    } );
    setTimeout(function() {
      this.modalBoxElement.innerHTML = '';
    }.bind(this), 1000)
//    console.log('closed');
  },
  open: function() {
    this.reposition();
    numModalBoxes++;
    this.modalBoxElement.appear({
      duration: 0.3
    });
    if (!this.backDropElement.visible()) {
      setTimeout(function() {
        this.backDropElement.appear( { 
          duration: 0.3,
          from: 0.1,
          to: 0.7
        });
        this.backDropElement.zIndex = 1000;
      }.bind(this),100);
    }
  }
}

function showModalBox(html) {
  modalBoxes.push(new ModalBox(html));
}

function closeTopMostModalBox() {
  //console.log('close called');
  if (numModalBoxes > 0) {
    var mb = modalBoxes[numModalBoxes-1];
    mb.close.bind(mb)();
    modalBoxes.pop();
  }
}

function repositionModalBoxes() {
  modalBoxes.each( function(box) {
    box.reposition.bind(box)();
  });
}

Event.observe(document, 'keydown', function(evt) {
  if (Event.KEY_ESC == evt.keyCode) {
    closeTopMostModalBox()
  }
});

