// create a popover object as soon as the page loads
Event.observe(document, 'dom:loaded', function(){
  cropperpopover = new CropperPopover();
});

// displays the given element in a popover shell 
function cropper_pop_over(elm){cropperpopover.display(elm)}
function cropper_pop_over_close(){cropperpopover.close()}

var CropperPopover = Class.create(
{
  initialize : function() {
    // things to manipulate
    this.po = $('cropper-pop-over');
    this.poc = $('cropper-pop-over-content');
    this.pen = $('holding-pen');
    this.blanker = $('page-blanker');

    // tracking of state
    this.displaying_content = false;
    this.events_attached = false;
  },
  
  // display the given content in the pop_over
  display : function(elm) {
    this.clear_current();
    // insert our element
    this.poc.appendChild(elm);
    elm.show();
    // display the pop-over (otherwise we can't get the dimensions)
    this.po.show();
	 
	 // Set the top pos 
	  if (!this.displaying_content) {
      // we need to position vertically the first time round

      // find the dimensions of the view area
      var page_height = document.viewport.getHeight();

      // find the height of the pop-over
      var elm_height = this.po.getHeight();

      // calculate the pop-over position
      var top = parseInt((page_height-elm_height)/4);
      if (top < 0)
        top = 0;

      // offset for the scroll 
      top += document.viewport.getScrollOffsets()[1];

      // position the pop-over accordingly
      this.po.setStyle({ top:top.toString()+'px' });
    }
	 
	 // declare we have content
	 this.displaying_content = true;
    // redraw now just to make sure thing everything is where it should be
    this.redraw();
  },
  
  // display blanker
  display_blanker : function() {
    this.blanker.show();
  },
  
  clear_current : function() {
    // clear out the old pop-over
    this.poc.immediateDescendants().each(function(old_elm){
      old_elm.remove();
      // need to keep the old stuff safe
      this.pen.appendChild(old_elm);
    }.bind(this));
  },
  
  redraw : function() {
    // make sure the blanker fits
    this.display_blanker();
  },
  
  close : function() {
    this.po.hide();
    this.blanker.hide();
    // update the internal state
    this.displaying_content = false;
  }
}
);
