var Popup = Class.create({
  initialize: function(path, url) {
	this.path = path;
	this.url = url;
	this.cb = new Array;
	this.id = Math.floor(Math.random()*1000);
  },

  show: function() {
    Position.prepare();
	var layer = document.body;
    var tmp = Position.realOffset(document.body);
    var scroll_y = Position.deltaY; 
    var tmp = Element.getDimensions(document.body);
    var offset_x = tmp.width;

    var e = document.createElement('div');
	e.id = '_popup_' + this.id; 
	e._popup_obj = this;
    Element.hide(e);
    layer.appendChild(e);

	var img = document.createElement('img');
	img.border = '0';
	img.src = this.path + 'img/cross.gif';
	img._popup_obj = this;
	img.onclick = popup_close;
	var lnk = document.createElement('a');
	lnk.href = 'javascript:nop()';
	lnk.appendChild(img);
	e.appendChild(lnk);
    var c = document.createElement('div');
	c._popup_obj = this;
	e.appendChild(c);

	var obj = this;
	var handler = function(req) {
		c.innerHTML = req.responseText;
		c.innerHTML.evalScripts();
    	var orig = Element.getDimensions(e);
    	var xpos = (offset_x - orig.width)/2;
    	var ypos = scroll_y + 100;
    	Element.setStyle(e, { position:'absolute',
			border: '1px solid black',
			padding: '0.5em',
			background: '#ffffff',
        	top: ypos + 'px',
        	left: xpos + 'px'});

    	Element.show(e);
		new Draggable('_popup_' + obj.id);
	};
	var eHandler = function(req) {
		Element.remove(e);	
	}

	var url = this.url + '&p=' + this.path + '&pid=' + this.id
	    + '&dummy='+Math.floor(Math.random()*10000);
	var req = new Ajax.Request(url,
		{ method: 'get', onSuccess: handler, onError: eHandler});

	return e;
  },

  close: function() {
	var name = '_popup_' + this.id;
	Element.remove($(name));
  },

  notify: function(what) {
	var obj = this;
	for (i = 0; i < this.cb.length; i++) {
		var cb = this.cb[i][0]
		var arg = this.cb[i][1]
		cb(obj, what, arg);
	}
  },

  addNotify: function(cb, arg) {
	var tmp = new Array(2);
	tmp[0] = cb;
	tmp[1] = arg;
	this.cb.push(tmp);
  }
});

function popup_close()
{
	var obj = this._popup_obj;
	obj.close();
}

function popup_id2obj(id)
{
	var tmp = '_popup_' + id; 
	var div = $(tmp);
	obj = div._popup_obj;	
	return (obj);
}

function popup_cancel(id)
{
	var tmp = '_popup_' + id; 
	var div = $(tmp);
	obj = div._popup_obj;	
	obj.close();
}

function popup_return(id, what)
{
	var tmp = '_popup_' + id; 
	var div = $(tmp);
	obj = div._popup_obj;	
	obj.close();
	obj.notify(what);
}

function popup_show()
{
	var obj = this._popup_obj;
	obj.show();
}
