/*
	JS Extending Library
	Windows functions.
	build 200810211630
*/

var windows = {
	openWindows: {},
	
	popup: function(url, name, width, height, x, y, attr, content, insertHTML) {
		/*
			Usage
			All of the paramaters are not obligatory. It means that you can pass none of them and the popup is going to open anyway.
			
			@url [STRING] - URI of the document to open.
			@name [STRING] - Name of the new window, which can be used in target for A and FORM tags.
			@width [STRING] - Width of the window.
			@height [STRING] - Height of the window.
			@x [STRING] - Location of the window for x axis.
			@y [STRING] - Location of the window for y axis.
			@attr [STRING] - attributes of the window:
				copyhistory   Копировать историю просмотра текущего окна.
				dependent     Создать окно, зависимое от родительского окна. Зависимые окна закрываются при закрытии родительского окна и не показываются в панели задач Windows.
				directories   Показывать панель каталогов обозревателя.
				height        Высота окна в пикселях.
				location      Показывать адресную строку обозревателя.
				menubar       Показывать меню обозревателя.
				resizable     Пользователь может изменять размеры окна.
				screenX       Расстояние в пикселях от левого края экрана по горизонтали.
				screenY       Расстояние в пикселях от верхнего края экрана по вертикали.
				left          Расстояние в пикселях от левого края экрана по горизонтали.
				top           Расстояние в пикселях от верхнего края экрана по вертикали.
				scrollbars    Показывать полосы прокрутки окна.
				status        Показывать строку состояния обозревателя.
				toolbar       Показывать панель кнопок обозревателя.
				width         Ширина окна в пикселях.
			@content [STRING] - Some HTML content that will be written to the window. Pass some HTML or an empty string or "auto" for auto filling with HTML. Additionaly view @insertHTML
			@insertHTML [STRING] - if you pass auto for @content, than this will be placed between BODY tags.
		*/

		if (empty(url)) var url = '';
		if (! isset(name)) var name = '';
		name = name.replace(/[^a-z0-9\_]+/igm, '_');
		if (isset(this.openWindows[name])) {
			try {
				this.openWindows[name].focus();
				return this.openWindows[name];
			} catch (exception) {
				delete this.openWindows[name];
			}
		}
		
		if (empty(width)) var width = '100';
		else {
			if (width == 'fullscreen') var width = screen.availWidth;
			else {
				width = width.toString();
				if (width.indexOf('%') != -1) var width = (Math.round(parseInt(width) * screen.availWidth / 100)).toString();
			}
		}
		
		if (empty(height)) var height = '100';
		else {
			if (height == 'fullscreen') var height = screen.availHeight;
			else {
				height = height.toString();
				if (height.indexOf('%') != -1) var height = (Math.round(parseInt(height) * screen.availHeight / 100)).toString();
			}
		}

		if (empty(x)   &&   width != 'fullscreen') var x = (Math.round(screen.availWidth / 2 - parseInt(width) / 2)).toString();
		else if (width == 'fullscreen') var x = '0';
		
		if (empty(y)   &&   height != 'fullscreen') var y = (Math.round(screen.availHeight / 2 - parseInt(height) / 2)).toString();
		else if (height == 'fullscreen') var y = '0';
		
		if (! isset(insertHTML)) var insertHTML = '';
		
		if (empty(attr)) {
			var attr = 'dependent=1,width='+ width +',height='+ height;
			if (x != '') attr += ',screenX='+ x +',left='+ x;
			if (y != '') attr += ',screenY='+ y +',top='+ y;
		} else {
			if (! isset(attr)) var attr = '';
			if (x != ''   &&   attr.indexOf('left=') == -1) attr += (attr != '' ? ',' : '') +'left='+ x;
			if (x != ''   &&   attr.indexOf('screenX=') == -1) attr += (attr != '' ? ',' : '') +'screenX='+ x;
			if (y != ''   &&   attr.indexOf('top=') == -1) attr += (attr != '' ? ',' : '') +'top='+ y;
			if (y != ''   &&   attr.indexOf('screenY=') == -1) attr += (attr != '' ? ',' : '') +'screenY='+ y;
			if (attr.indexOf('width=') == -1) attr += (attr != '' ? ',' : '') +'width='+ width;
			if (attr.indexOf('height=') == -1) attr += (attr != '' ? ',' : '') +'height='+ height;
		}

		if (empty(content)) var content = '';
		else {
			if (content == 'auto') var content = '<html><head><style>BODY{overflow:hidden;padding:0;margin:0;}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="imagetoolbar" content="no" /></head><body onLoad="window.moveTo('+ x +', '+ y +');self.focus()" bgcolor="#000000">%content%</body></html>';
		}

		var win = window.open(url, name, attr);
		this.openWindows[name] = win;
		if (content != '') {
			if (! isIE()) win.document.open();
			win.document.write(content.replace('%content%', insertHTML));
			win.document.close();
		}
		addEvent('beforeunload', win, 'delete windows.openWindows.'+ name);
		return win;
	},

	dynPopup: function(id, width, height, x, y, content, attr, onResizePos, closeWithClick) {
		/*
			Description: Opens DHTML popup in DIV tag.
			Usage: All of the paramaters are not obligatory. It means that you can pass none of them and the popup is going to open anyway.
			
			@id [STRING] - ID of the DIV.
			@width [STRING] - Width of the window.
			@height [STRING] - Height of the window.
			@x [STRING] - Location of the window for x axis. Leave blank for auto.
			@y [STRING] - Location of the window for y axis. Leave blank for auto.
			@content [STRING] - Some HTML content that will be written to the window. Pass some HTML.
			@attr [OBJECT] - Object which contains configuration for the window. Example:
				{
					'borderWidth' : '3px',
					'borderColor' : '#f00',
					'closeImg' : '/img/...gif',
					'closePos' : 'top-right'
				}
			@onResizePos [BOOLEAN] - Should the window be repositioned on main window resize.
			@closeWithClick [BOOLEAN] - Should the window be closabled by click at any place over it or not.
		*/
		
		if (empty(id)) var id = 'dWin'+ IDgen();
		if (empty(width)) var width = 10;
		if (empty(height)) var height = 10;
		if ($(id)) return false;
		if (! document.body) return false;
		
		if (empty(x)) var x = (Math.round((isIE() ? document.body.clientWidth : innerWidth) / 2 - parseInt(width) / 2) + parseInt(document.body.scrollLeft)).toString();
		if (empty(y)) var y = (Math.round((isIE() ? document.body.clientHeight : innerHeight) / 2 - parseInt(height) / 2) + parseInt(document.body.scrollTop)).toString();
		
		if (! isset(attr)) var attr = {};
		if (isset(onResizePos)) {
			if (onResizePos) {
				addEvent('resize', window, 'setTimeout("dynPopupMove(\''+ id +'\')", 50)');
				addEvent('scroll', window, 'setTimeout("dynPopupMove(\''+ id +'\')", 50)');
			}
		}
		
		var o = document.createElement("DIV");
		o.setAttribute('id', id);
		o = document.body.appendChild(o);
		o.style.display = 'none';
		o.style.position = 'absolute';
		o.style.backgroundColor = '#000';
		o.style.zIndex = 9999;
		o.style.left = x;
		o.style.top = y;
		o.style.width = width +'px';
		o.style.height = height +'px';
		
		if (isset(closeWithClick)) {
			if (closeWithClick) {
				addEvent('click', o, 'setTimeout("dynPopupClose(\''+ id +'\')", 50)');
				o.style.cursor = 'pointer';
			}
		}
		
		if (isset(attr['borderWidth'])   &&   isset(attr['borderColor'])) {
			o.style.borderWidth = attr['borderWidth'];
			o.style.borderColor = attr['borderColor'];
			o.style.borderStyle = 'solid';
		}
		
		if (! empty(content)) {
			var content = '<div style="position:relative;width:100%;height:100%;">'+ content;
			if (isset(attr['closeImg'])) {
				if (! isset(attr['closePos'])) attr['closePos'] = 'top-right';
				content += '<div style="position: absolute; ';
				switch (attr['closePos']) {
					default:
						content += 'top: 0; right: 0;';
					break;
					case 'top-left':
						content += 'top: 0; left: 0;';
					break;
					case 'bottom-left':
						content += 'bottom: 0; left: 0;';
					break;
					case 'bottom-right':
						content += 'bottom: 0; right: 0;';
					break;
				}
				content += '"><img src="'+ attr['closeImg'] +'" alt="Close" style="cursor:pointer" onClick="dynPopupClose(\''+ id +'\')" /></div>';
			}
			o.innerHTML = content +'</div>';
		}
		
		window.dynPopupMove(id);
		o.style.display = 'block';
		
		return o;
	},
		
	dynPopupClose: function(id) {
		if ($(id)) document.body.removeChild($(id));
	},

	dynPopupMove: function(id) {
		var o = $(id);
		if (o) {
			o.style.left = (Math.round((isIE() ? document.body.clientWidth : innerWidth) / 2 - parseInt(o.style.width) / 2) + parseInt(document.body.scrollLeft)).toString() +'px';
			o.style.top = (Math.round((isIE() ? document.body.clientHeight : innerHeight) / 2 - parseInt(o.style.height) / 2) + parseInt(document.body.scrollTop)).toString() +'px';
		}
	},
	
	winStatus: function(e, text) {
		if (isIE()) {
			var e = window.event;
			if (! isset(text)) var text = '';
			
			if (isset(window.statusbar)) {
				if (! window.statusbar) {
					e.returnValue = false;
					return false;
				}
			}
			
			window.status = (text != '' ? text : e.srcElement['innerText']);
			
			e.returnValue = true;
			return true;
		}
	},
	
	getWinInfo: function (o) {
		if (isIE()) return {
			'width' : o.document.body.offsetWidth,
			'height' : o.document.body.offsetHeight
		};
		 return {
			'width' : o.innerWidth,
			'height' : o.innerHeight
		};
	}

};