/*
Popup block class
Requires Common.js

Author: Stepan Reznikov (stepan@design.ru)
24.12.2007
*/

function PopupBlock(oContainer, oLink){

	this.bInit = null;
	this.bKeep = false;

	var me = this;

	// контейнер с содержимым блока
	this.oContainer = oContainer;
	if (this.oContainer) {
		Common.Event.add(this.oContainer, 'click', function(evt){ me.keep(evt); });
	}

	// ссылка активирующая блок
	this.oLink = oLink;
	if (this.oLink) {
		Common.Event.add(this.oLink, 'click', function(evt){ if ( me.toggle(evt) ){ return Common.Event.cancel(evt); } });
	}
}

PopupBlock.prototype.isInit = function(){
	if (this.bInit == null) {
		this.bInit = this.oContainer && this.oLink;
	}
	return this.bInit;
}

PopupBlock.prototype.toggle = function(evt){
	if (this.isInit()) {
		if (Common.Class.match(this.oContainer, 'hidden')) {
			this.show(evt);
		} else {
			this.hide(evt);
		}
		return true;
	} else {
		return false;
	}
}

PopupBlock.prototype.show = function(evt){
	if (this.isInit()) {
		Common.Class.remove(this.oContainer, 'hidden');
		var me = this;
		this.documentClickHandler = function(evt){ me.hide(evt); }
		this.documentKeyDownHandler = function(evt){ me.cancel(evt); }
		Common.Event.add(document, 'click', this.documentClickHandler);
		Common.Event.add(document, 'keydown', this.documentKeyDownHandler);
	}
}

PopupBlock.prototype.keep = function(evt){
	if (this.isInit()) {
		this.bKeep = true;
	}
}

PopupBlock.prototype.hide = function(evt){
	if (this.isInit()) {
		if (this.bKeep) {
			this.bKeep = false;
			return;
		}
		Common.Class.add(this.oContainer, 'hidden');
		Common.Event.remove(document, 'click', this.documentClickHandler);
		Common.Event.remove(document, 'keydown', this.documentKeyDownHandler);
	}
}

PopupBlock.prototype.cancel = function(evt){
	if (this.isInit()) {
		if ((evt = Common.Event.normalize(evt))){
			var code = evt.keyCode ? evt.keyCode : evt.which ? evt.which : null;
			if (code == 27) {
				this.hide(evt);
			}
		}
	}
}