﻿/*--
标题：弹出引擎
说明：处理鼠标弹出元素
设计：王集鹄
博客：http://blog.csdn.net/zswang
日期：2009年03月07日
--*/

if (!Common.scripts["PopupEngine"]) {
	Common.scripts["PopupEngine"] = true;
}

/// <summary>
/// 构造弹出引擎
/// </summary>
/// <param name="target">弹出元素</param>
function PopupEngine(target) {
	this.target = target;
	var self = this;
	this.documentKeydown = function(e) {
		if (!e) e = window.event;
		switch (e.keyCode | e.which | e.charCode) {
			case 27:
				self.close();
				break;
		}
	};
	this.documentMousedown = function(e) {
		var element = typeof event != "undefined" ? event.srcElement : e.target;
		var closed = true;
		while (element && closed) {
			closed = element != self.target;
			element = element.parentNode;
		}
		if (closed) self.close();
	};
}

PopupEngine.prototype.popup = function(x, y) {
	this.target.style.left = x + "px";
	this.target.style.top = y + "px";
	this.target.style.display = "";
	addEventHandler(document, "mousedown", this.documentMousedown);
	addEventHandler(document, "keydown", this.documentKeydown);
	if (typeof this.onpopup == "function") this.onpopup(this);
}

PopupEngine.prototype.close = function() {
	this.target.style.display = "none";
	removeEventHandler(document, "mousedown", this.documentMousedown);
	removeEventHandler(document, "keydown", this.documentKeydown);
	if (typeof this.onclose == "function") this.onclose(this);
}

/// <summary>
/// 释放弹出引擎
/// </summary>
PopupEngine.prototype.dispose = function() {
	removeEventHandler(this.target, "mousedown", this.targetMousedown);
	this.disposed = true;
	for (var i in this) {
		if (this[i].disposed) continue;
		if (typeof this[i].dispose == "function") this[i].dispose();
		if (typeof this[i].parentNode == "object")
			this[i].parentNode.removeChild(this[i]);
		delete this[i];
	}
};