var Dlg = 
{
	container:	$e('table', {className:'dlg_cnt'},$e('tbody',$e('tr', $e('td', {align:'center', id:'dlg_%_content',className:'dlg_cnt'})))),
	overlay:	$e('div',{className:"dlg_overlay"}),
	mask:		$e('div'),
	id: 0,
	zindex:1024,
	loaded:{},
	child: document.body.childNodes[document.body.childNodes.length-1],
	parent: window,
	scin:
	{
		full: function(dlg)
			{				
				var self=this;
				
				self.container = $e('div',{className:'dlg_fix_ie'},self.touch=$e('div',{className:"dlg_window"},
				[
					self.header=$e('div',{className:"dlg_header"},$e('div',{className:'dlg_row_cell dlg_border_bot'},
					[
						self.close=$e('input',{type:'image',className:"dlg_close",src:"/@/core/dialog/close.jpg",title:"Close window"}),
						self.restore=$e('input',{type:'image',className:"dlg_close",src:"/@/core/dialog/restore.jpg",title:"Restore window",accessKey:'r'}),
						self.title = $e('div',{className:"dlg_caption"}),
						$e('div',{className:'both'})
					])),
					$e('div',{className:"dlg_content_row"},self.content=$e('div',{className:'dlg_row_cell'})),
					$e('div',{className:'dlg_anker'},$e('div',{className:'dlg_row_cell'},
					[
						$e('div',{className:'dlg_border_bot1'}),
						self.resize=$e('div', {className:'dlg_anker_touch'}),
						$e('div',{className:'both'})
					]))
				]));
				
				(function(ev)
				{
					ev.preventDefault();
					dlg.show(false);
					
				}).attach('click',self.close);
				
				(function(ev)
				{
					ev.preventDefault();
					ev.stopPropagation();
					dlg.restore();
					
				}).attach('click',self.restore).attach('dblclick',self.header);
			},
		medium: function(dlg)
			{
				var self=this;
				
				self.container = $e('div',{className:'dlg_fix_ie'},self.touch=$e('div',{className:"dlg_window"},
				[
					self.header=$e('div',{className:"dlg_header"},$e('div',{className:'dlg_row_cell'},
					[
						self.close=$e('input',{type:'image',className:"dlg_close",src:"/@/core/dialog/close.jpg",title:"Close window"}),
						self.title = $e('div',{className:"dlg_caption"}),
						$e('div',{className:'both'})
					])),
					$e('div',{className:"dlg_content_row"},self.content=$e('div',{className:'dlg_row_cell'}))
				]));
				
				(function(ev)
				{
					ev.preventDefault();
					dlg.show(false);
					
				}).attach('click',self.close);
			},
		small: function(dlg)
		{
			var self=this;
			
			this.container = $e('div',{className:'dlg_fix_ie'},self.touch=$e('div',{className:"dlg_window",style:{border:'none'}},
			[
				$e('div',{className:"dlg_content_row"},self.content=$e('div',{className:'dlg_row_cell'}))
			]));
		}
	},
	
	create: function(arg,flag)
	{
		if(typeof(flag)=='undefined')
		flag = true;
		
		var loaded = !(!Dlg.loaded[arg.id]);
		
		if(!loaded)
		{
			var dlg = new Dlg.Dialog(arg.id, arg.scin || (!(arg.resizable || false) ? Dlg.scin.medium : Dlg.scin.full));
			
			Dlg.loaded[arg.id] = dlg;
		}
		else
		var dlg = Dlg.loaded[arg.id];
		
		dlg.set_title(arg.title || '');
		
		dlg.set_content(arg.content);
		
		dlg.show(flag);
		
		if(!loaded)
		{
			//установливаем ширину и высоту диалога
			dlg.set_width(arg.width || 0);
			dlg.set_height(arg.height || 0);
		}
		
		if(typeof(arg.draggable)=='undefined')	arg.draggable=true;
		
		dlg.set_draggable(arg.draggable);
		dlg.set_resizable(arg.resizable || false, arg.min_width || arg.width,arg.min_height || arg.height);
		dlg.location=arg.location;
		if(typeof(arg.fullscreen)!='undefined' && arg.fullscreen)
		dlg.restore();
		return dlg;
	},
	
	destroy: function(dlg)
	{
		dlg.container.parentNode.removeChild(dlg.container);
	},
	
	Dialog: function(id, scin)
	{
		var self=this;
		this.container = Dlg.container.cloneNode(true);
		this.overlay = Dlg.overlay.cloneNode(true);
		
		this.container.id='pop_uper'+id;
		
		this.show_event=function(ev)
		{
			ev = ev || event;
			
			if(!self.is_active) return;
			
			if (ev.keyCode == 27)
			{
				ev.stopPropagation();
				
				if(self.full_screen)
				return self.restore();
				
				return self.show(false);
			}
			
			if(!self.scin.header) return;
			
			if (ev.keyCode == 13 && ev.altKey)
			{
				ev.stopPropagation();
				ev.preventDefault();
				self.restore();
			}
		}
		
		this.show_event.attach('keydown',document);
		
		this.td = this.container.getElementsByTagName('td')[0];
		this.td.id = this.td.id.replace('%', Dlg.id);
		Dlg.id++;
		
		this.scin = new scin(this);
	
		$e(this.td, this.scin.container);
		Dlg.child = Dlg.child.nextSibling;
		Dlg.child.parentNode.insertBefore(this.container,Dlg.child);
		Dlg.child.parentNode.insertBefore(this.overlay,Dlg.child);
		
		
		
		this.full_screen=false;
		this.full_screen_last='dlg_cnt_full';
		
		this.restore = function()
		{
			var temp = this.container.className;
			this.container.className=this.full_screen_last;
			this.full_screen_last=temp;
			
			this.full_screen = !this.full_screen;
		}
		
		this.__destroy		= function()
		{
			if(this.drag) this.drag.__destroy();
			if(this.resize)	this.resize.__destroy();
			
			self=null;
		}
		
		this.set_content	= function(text){this.scin.content.innerHTML = text;}
		this.set_title		= function(text){if(this.scin.title)this.scin.title.innerHTML = text+' - Zero';}
		this.set_width		= function (width)
		{
			var w = parseInt(this.scin.touch.offsetWidth,10);
			
			if(width>w)	this.scin.touch.style.width='100%';
			
			this.scin.container.style.width = (width>w ? width : w)+'px';
		}
		
		this.set_height = function (height)
		{
			for(var h=0,i=0;h<24&&i<3;i++)
			{
				if(!i)
				{
					h = parseInt(this.scin.touch.offsetHeight,10);
					var tmp=this.scin.content;
					continue;
				}
				
				h = parseInt(tmp.offsetHeight,10);
				tmp = tmp.getElementsByTagName('div');
				
				if(!tmp.length) break;
				
				tmp=tmp[0];
			}
			
			var tmp = parseInt(height,10);
			if(i>1) h+=32;
			
			if((tmp==height && height>=h) || i>1) this.scin.touch.style.height='100%';
			height=tmp;
			this.scin.container.style.height = (height>h ? height : h)+'px';
		}
		
		this.show=function(flag)
		{
			if(this.display == flag) return;
			
			this.display=flag;
			this.overlay.style.display =
			this.container.style.display = (flag ? '' : 'none');
			
			if(!this.display)
			{
				Dlg.zindex -= 2;
				
				if(!this.parent)
				this.parent=Dlg.parent;
				
				Dlg.parent=this.parent;
				this.is_active = false;
				
				//уничтожаем все внутренние данные,
				//они нам могут помешать, точнее их идентификаторы
				//и более ненужны
				this.scin.content.innerHTML='';
				
				if(this.parent !== window)
				this.parent.is_active=true;
			}
			else
			{
				this.is_active=true;
				Dlg.zindex += 2;
				this.parent=Dlg.parent;
				Dlg.parent=this;
				
				if(this.parent !== window)
				this.parent.is_active=false;		
			}
			
			this.container.style.zIndex=Dlg.zindex;
			this.overlay.style.zIndex=Dlg.zindex-1;
		}
		
		var _l, _t, _cw, ch, _ow, _oh, _w, _h,x,y,w,h;
		
		this.part_tag=null;
		this.part_tag_flag=true;
		
		this.part_tag_show=function()
		{
			if(!this.part_tag_flag)
			{
				this.part_tag.style.visibility = 'visible';
				this.part_tag_flag=true;
			}
		}
		
		this.part_tag_hide=function()
		{
			if(this.part_tag_flag)
			{
				this.part_tag.style.visibility = 'hidden';
				this.part_tag_flag=false;
			}
		}
		
		this.drag_init=function()
		{
			//если диалог во весь экран запрещаем таскать его
			if(self.full_screen)
			{
				this.started=false;
				return;
			}

			var container	= self.container;
			
			var dlg_item	= self.scin.container;
			var touch		= self.scin.touch;
			
			//выбираем один из параметров указывающих на размеры диалога
			_ow = touch.offsetWidth;
			_oh = touch.offsetHeight;
			
			_w = parseInt(dlg_item.style.width || _ow,10);
			_h = parseInt(dlg_item.style.height || _oh,10);
			
			w=_ow;
			h=_oh;
			
			//ширина контейнера(table)
			_cw = container.offsetWidth;
			_ch = container.offsetHeight;
			
			if(!self.part_tag)
			{
				self.part_tag=Dlg.mask.cloneNode(true);
				
				$e(self.td, self.part_tag);
				
				self.part_tag.style.position='absolute';
				self.part_tag.setAttribute('onClick',"this.style.visibility='hidden'");
				self.part_tag.style.border='3px dotted gray';
				self.part_tag_hide();
			}
			
			if (container.className == 'dlg_cnt_normal')
			return;
			
			var td = self.td;
			
			x = _l = dlg_item.offsetLeft-td.offsetLeft;
			y = _t = ((container.offsetHeight - dlg_item.offsetHeight) / 2)-3;
			
			container.className = 'dlg_cnt_normal';
			
			dlg_item.style.top	= _t+'px';
			dlg_item.style.left	= _l+'px';
			
			self.part_tag.style.width	= w+'px';
			self.part_tag.style.height	= h+'px';
			self.part_tag.style.top		= _t+'px';
			self.part_tag.style.left	= _l+'px';
		}
		
		this.drag = null;
		
		this.set_draggable=function(flag)
		{
			if(!flag || this.is_dragabled || !this.scin.header) return;
			
			if(typeof(Drag)=='undefined')
			{
				alert('Отсутствует библиотека drag.js');
				return false;
			}
			
			this.drag = Drag.create(this.container,this.scin.header);
			this.drag.init();
			
			this.drag.onDragStart = this.drag_init;
			
			this.drag.onDrag = function()
			{
				self.part_tag_show();
				
				x = _l + this.dx - this.sx;
				y = _t + this.dy - this.sy;
				
				self.part_tag.style.left = x+'px';
				self.part_tag.style.top  = y+'px';
				//ограничение нельзя вытащить диалог за пределы окна
				
			}
			
			this.drag.onDragEnd = function()
			{
				x = (x+_ow > _cw ? _cw-_ow : (x < 0 ? 0 : x));
				y = (y+_oh > _ch ? _ch-_oh : (y < 0 ? 0 : y));
				
				if(y<0) y=0;
				if(x<0) x=0;
				
				self.scin.container.style.left	= x+'px';
				self.scin.container.style.top	= y+'px';
				
				_l = x;
				_t = y;
				self.part_tag.style.left		= x+'px';
				self.part_tag.style.top			= y+'px';
				self.part_tag_hide();
				//self.part_tag.style.visibility	= 'hidden';
			}
		}
		
		this.resize=null;
		
		this.set_resizable=function(flag,min_width,min_height)
		{
			if(!flag || this.resize || !this.scin.resize) return;
			
			if(typeof(Drag)=='undefined')
			{
				alert('Отсутствует библиотека drag.js');
				return false;
			}
			
			this.resize = Drag.create(this.container,this.scin.resize);
			this.resize.init();
			
			this.resize.onDragStart = this.drag_init;
			
			this.resize.onDrag = function()
			{
				self.part_tag_show();
				
				w = this.dx - this.sx + _w;
				h = this.dy - this.sy + _h;
				
				//self.part_tag.style.visibility	= 'visible';
				self.part_tag.style.width	= w-_w+_ow+'px';
				self.part_tag.style.height	= h-_h+_oh+'px';
				
				//ресайз с минимальным зачением
				//self.scin.container.style.width = (w < min_width ? min_width : (_l+w > _cw ? _cw-_l : w))+'px';
				//self.scin.container.style.height = (h < min_height ? min_height : (_t+h > _ch ? _ch-_t : h))+'px';
			}
			
			this.resize.onDragEnd = function()
			{
				w = (w < min_width ? min_width : (_l+w > _cw ? _cw-_l : w));
				h = (h < min_height ? min_height : (_t+h > _ch ? _ch-_t : h));
				
				self.scin.container.style.width		= w+'px';
				self.scin.container.style.height	= h+'px';
				
				var cntw = (_ow-_w);
				var cnth = (_oh-_h);
				
				_w = w;
				_h = h;
				w+=cntw;
				h+=cnth;
				
				self.part_tag_hide();
				self.part_tag.style.width		= w+'px';
				self.part_tag.style.height		= h+'px';
			}
		}
	},
	
	get: function(id)
	{
		if (typeof(id) != 'string')
		{
			while (id && !/pop_uper/.test(id.id)) id = id.parentNode;
			
			if(!id) return new Dlg.Dialog('test',Dlg.scin.small);
			id = /pop_uper(.*)/.exec(id.id)[1];
		}
		
		return (Dlg || parent.Dlg).loaded[id];
	},
	
	close: function(id)
	{
		Dlg.get(id).show(false);
	},
	
	loadScript:function()
	{
		if(Dlg.processScript)
		return;
		
		if(!Dlg.scripts.length)
		return progressLayer(false);
		
		var script = Dlg.scripts.splice(0,1)[0];
			
		if(!script[0])
		{
			eval.call(window, script[1]);
			
			return Dlg.loadScript();
		}
		
		var child = document.body.childNodes;
		child = child[child.length-1];
		
		var scripts=$e('SCRIPT', {type:'text/javascript', language:'javascript'});
		scripts.setAttribute('onload','if(this==Dlg.processScript){Dlg.processScript=false;Dlg.loadScript();}');
		scripts.src=script[1];
		Dlg.processScript=scripts;
		child.parentNode.insertBefore(scripts,child);
		
	},
	scripts:[],
	processScript:false
};

(function()
{	
	var child = document.body.childNodes[0];
	var dlg_css = $e('link',{rel:"stylesheet",type:"text/css",href:"/@/core/dialog/_dialog.css"});
    child.parentNode.insertBefore(dlg_css,child);
    
	window.U_dialog=function()
	{
		var url = arguments[0];
		var i = 1;
		var method  = typeof(arguments[i]) == 'string' ? arguments[i++] : 'GET';
		var params1  = typeof(arguments[i]) == 'object' ? arguments[i++] : null;
		var params2  = typeof(arguments[i]) == 'object' ? arguments[i++] : null;
		//var handler = typeof(arguments[i]) == 'function' ? arguments[i++] : false;
		
		var handler = function(text)
		{
			progressLayer(false);
			
			if (!/<!--[^\{]*(\{(?:.(?!\}\s*-->))*.\})\s*-->/.test(text))
			return;
			var header;
			//перенсим заголовок ответа в параметры диалогов
			//перенсим заголовок ответа в параметры диалогов
			text.replace(/<!--[^\{]*(\{(?:.(?!\}\s*-->))*.\})\s*-->/g,
			function( $0, $1)
			{
				if(header) return $0;
				var tmp = json_decode( $1);
				
				if(tmp['title']) header=tmp;
				return $0;
			});
			
			if(!header)	return;
			
			//выполняем скрипты в теле ответа в контексе окна
			text = text.replace
			(
				/(?:<script .*?(?:src="(.*?)")?>)((\n|\r|.)*?)(?:<\/script>)/img,
				function ($0, $1, $2)
				{
					if($1)
					Dlg.scripts.push([1,$1]);
					else if($2)
					Dlg.scripts.push([0,$2]);
					
					return '';
				}
			);
			
			header.content 	= text;
			header.location	= url;
			var dlg = Dlg.create(header);
			
			progressLayer(true);
			Dlg.loadScript();
		}
		
		progressLayer(true);
		AC.simple(url,method,params1,params2,handler);
	}
	
	window.U_alert=function(text,handler)
	{
		text = '<div class="dlg_common"><div class="dlg_common_text">'+text+'</div><div>';
		text += '<input type="button" value="OK" style="width:70px;" id="alert_window"/></div></div>';
		
		var header=
		{
			content : text,
			width	: 300,
			id		:'alert'
		};
		
		var dlg = Dlg.create(header);
		
		(function()
		{
			Dlg.close(this);
			
			if(typeof(handler) == 'function')
			handler();
			
		}).attach('click',$('alert_window')).attach('click',dlg.scin.close);
		
		$('alert_window').focus();
	}
	
	window.U_confirm=function(text,handler)
	{
		text =  '<div class="dlg_common"><div class="dlg_common_text">'+text+'</div><div>';
		text += '<input type="button" value="Ок" style="width:70px;" id="confirm_yes"/><span>  </span>';
		text += '<input type="button" value="Отменить" style="width:70px;" id="confirm_no"/></div></div>';
		
		var header=
		{
			content : text,
			title	: 'Вы согласны?',
			width	: 300,
			id		: 'confirm'
		};
		
		var dlg = Dlg.create(header);
		
		(function()
		{
			var val=false;
			
			if(dlg.scin.close==this)
			val=null;
			
			Dlg.close(this);
			if(handler)	handler(val);
			
		}).attach('click',$('confirm_no')).attach('click',dlg.scin.close);
		
		(function()
		{
			Dlg.close(this);
			if(handler) handler(true);
			
		}).attach('click',$('confirm_yes'));
		
		$('confirm_yes').focus();
	};
	
	window.progressLayer=function(flag)
	{
		var header=
		{
			content : '<div class="dlg_common" style="background: yellow url(/@/core/dialog/progress.gif) no-repeat scroll 8px 7px">&nbsp;</div>',
			scin 	: Dlg.scin.small,
			width	: 110,
			height	: '15px',
			id		: 'progresslayer',
			draggable:false
		};
		
		Dlg.create(header,flag);
		
		header=null;
	};
	
	/*(function()
	{
		Dlg.child.parentNode.insertBefore(Dlg.overlay,Dlg.child);
		//Dlg.child.style.zIndex=1000;
	}).attach('onbeforeunload');*/
	
	if (window.attachEvent)
	{
		window.attachEvent
		(
			'onunload',
			function ()
			{
				for(var k in Dlg.loaded)
				{
					Dlg.loaded[k].__destroy();
					delete Dlg.loaded[k];
				}
				
				Dlg=null;
			}
		);
	}
})();