var DWin={
	includePath: "DesignImages",
	imagefiles:{
		min: "min.gif",
		close: "close.gif",
		restore: "restore.gif",
		resize: "resize.gif",
		save: "",
		copy: "",
		drop: "",
		info: "",
		delimeter: ""
	},
	contents:{
	  minimize: "Свернуть/Minimize",
	  minimized: "minimized",
	  close: "Закрыть/Close",
	  restore: "Восстановить/Restore",
	  resize: "Размер/Resize",
	  save: "Сохранить/Save",
	  copy: "Копировать/Copy",
	  drop: "Удалить/Delete",
	  info: "Инфо/Info",
	  delimeter: "Разделитель/Delimeter",
	  undefined: "undefined",
	  title: "title",
	  div: "div",
	  iframe: "iframe"
	},
	title:{
	  id: "",
	  name: ""
	},
	document:{
	  id: "",
	  sourceID: null,
	  valueID: null,
	  textID: null
	},
  source: "",
	srcDefault: "empty.htm",
	
	minimizeorder: 0,
	zIndexvalue:100,
	tobjects: [], 
	lastactivet: {}, 
	
	$:function(id){
	  var ret=null;
    if(typeof(document.getElementById)==DWin.contents.undefined){
      if(typeof(document.all)!=DWin.contents.undefined){
        if(document.all!=null){ret=document.all[id];}
      }
    }else{
      if(document.getElementById==null){
        if(typeof(document.all)!=DWin.contents.undefined){
          if(document.all!=null){ret=document.all[id];}
        }
      }else{
    		ret=document.getElementById(id);
      }
    }
		return ret;
	},
	
	$$:function(tagName, context, condition){
		context = context?context:document;
		var coll = context.getElementsByTagName(tagName);
		if(condition){
			var condF = new Function("el", "with(el){return "+condition+";}");
			var res = [];
			for(var i=0;i<coll.length;i++){
				var el = coll[i];
				if(condF(el)){ res.push(el); }
			}
			return res;
		}
	},
	
	__:{
		buildWindow: function(id, buttons){
			buttons = buttons?buttons:{min:1, close:1};
			var domwindow=document.createElement("div");
			domwindow.id = id;
			domwindow.className="DWin"
			var html = [];
			html.push('<div class="DWinDragHandle">');
			html.push('DHTML Window ');
			html.push('<div class="DWinDragControls">');
			if(((buttons.close!=0)||(buttons.min!=0))&&(DWin.imagefiles.save.length>0)){
		    html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.save+'" '+DWin.contents.title+'="'+DWin.contents.save+'" border="0" hspace="2" />');
			}
			if(((buttons.close!=0)||(buttons.min!=0))&&(DWin.imagefiles.copy.length>0)){
		    html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.copy+'" '+DWin.contents.title+'="'+DWin.contents.copy+'" border="0" hspace="2" />');
			}
			if(((buttons.close!=0)||(buttons.min!=0))&&(DWin.imagefiles.drop.length>0)){
		    html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.drop+'" '+DWin.contents.title+'="'+DWin.contents.drop+'" border="0" hspace="2" />');
			}
			if(((buttons.close!=0)||(buttons.min!=0))&&(DWin.imagefiles.info.length>0)){
		    html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.info+'" '+DWin.contents.title+'="'+DWin.contents.info+'" border="0" hspace="2" />');
			}
			if(((buttons.close!=0)||(buttons.min!=0))&&(DWin.imagefiles.delimeter.length>0)){
		    html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.delimeter+'" '+DWin.contents.title+'="'+DWin.contents.delimeter+'" border="0" hspace="2" />');
			}
			if((buttons.min!=0)&&(DWin.imagefiles.min.length>0)){
				html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.min+'" '+DWin.contents.title+'="'+DWin.contents.minimize+'" border="0" />');
		  }
			if((buttons.close!=0)&&(DWin.imagefiles.close.length>0)){
		    html.push('<img src="'+DWin.includePath+'/'+DWin.imagefiles.close+'" '+DWin.contents.title+'="'+DWin.contents.close+'" border="0" />');
			}
			html.push('</div>');
			html.push('</div>');
			html.push('<div class="DWinDragContentarea"></div>');
			if(DWin.imagefiles.resize.length>0){
			  html.push('<div class="DWinDragStatusarea"><div class="DWinDragResizearea"><img src="'+DWin.includePath+'/'+DWin.imagefiles.resize+'" '+DWin.contents.title+'="'+DWin.contents.resize+'" border="0" /></div></div>');
			}
			html.push('</div>');
			domwindow.innerHTML = html.join("");
			DWin.$("DWinHolder").appendChild(domwindow)
			return DWin.$(id);
		},
		
		obtainWindowParts: function(wDiv){
			var divs=wDiv.getElementsByTagName("div");
			for (var i=0; i<divs.length; i++){
				if (/DWinDrag/.test(divs[i].className)){
					wDiv[divs[i].className.replace(/DWinDrag/, "").toLowerCase()]=divs[i];
				}
			}
		},
		
		rememberattrs:function(t){
			DWin.getviewpoint();
			if(t.style!=null){
			  t.lastx=parseInt((t.style.left || t.offsetLeft))-DWin.scroll_left;
			  t.lasty=parseInt((t.style.top || t.offsetTop))-DWin.scroll_top;
			  t.lastwidth=parseInt(t.style.width);
			}
		},
		
		getdistance:function(e){
			var d=DWin
			var etarget=d.etarget
			var e=window.event || e
			d.distancex=e.clientX-d.initmousex;
			d.distancey=e.clientY-d.initmousey;
			if (etarget.className=="DWinDragHandle"){
				d.move(etarget._parent, e);
			}else if (etarget.className=="DWinDragResizearea"){
				d.resize(etarget._parent, e);
			}
			return false;
		},
		
		setupdrag:function(e){
			var d=DWin;
			var t=this._parent;
			d.etarget=this;
			var e=window.event || e;
			d.initmousex=e.clientX;
			d.initmousey=e.clientY;
			d.initx=parseInt(t.offsetLeft);
			d.inity=parseInt(t.offsetTop);
			d.width=parseInt(t.offsetWidth);
			d.contentheight=parseInt(t.contentarea.offsetHeight);
			if (t.contentarea.datatype=="iframe"){
				t.style.backgroundColor="#ffffff";
				t.contentarea.style.visibility="hidden";
			}
			document.onmousemove=d.__.getdistance;
			document.onmouseup=function(){
			  if (t.contentarea.datatype=="iframe"){
				  t.contentarea.style.backgroundColor="#ffffff";
				  t.contentarea.style.visibility="visible";
			  }
			  d.stop();
			}
			return false;
		}
	},
	
	init:function(id, buttons, dlgButtons){
		var t = DWin.__.buildWindow(id, buttons);
		DWin.__.obtainWindowParts(t);
		t.handle._parent=t
		t.handle.onmousedown=DWin.__.setupdrag
		t.resizearea._parent=t
		t.resizearea.onmousedown=DWin.__.setupdrag
		t.controls._parent=t
		t.controls.onclick=DWin.enablecontrols
		t.onclose=function(){return true;}
		t.onmousedown=function(){DWin.setfocus(this);}
		t.show=function(){DWin.show(this);}
		t.hide=function(){DWin.hide(this);}
		t.close=function(){DWin.close(this);}
		t.setSize=function(w, h){DWin.setSize(this, w, h);}
		t.moveTo=function(x, y){DWin.moveTo(this, x, y);}
		t.isResizable=function(bol){DWin.isResizable(this, bol);}
		t.isScrollable=function(bol){DWin.isScrollable(this, bol);}
		t.load=function(contenttype, contentsource, title){DWin.load(this, contenttype, contentsource, title);}
		DWin.tobjects.push(t);
		if(dlgButtons){
			for(var i=0;i<dlgButtons.length;i++){
				var btn = dlgButtons[i];
				DWin.addButton(t, btn.title, btn.click);
			}
		}
		return t;
	},
	
	open:function(t, contenttype, contentsource, title, attr, recalonload, dlgButtons){
		var d=DWin;
		function getValue(Name){
			var mt = attr.match(new RegExp(Name+"=([^,]+)", "i"));
			if(/Button$/.test(Name)){
				return mt? parseInt(mt[1]) : 1;
			}
			return mt? parseInt(mt[1]) : 0;
		}
		var buttons = {
			min:getValue("minButton"),
			close: getValue("closeButton")
		};
		t=(d.$(t)==null)?d.init(t, buttons, dlgButtons):d.$(t);
		d.setfocus(t);
		t.setSize(getValue(("width")), (getValue("height")));
		var xpos=getValue("center")? "middle" : getValue("left");
		var ypos=getValue("center")? "middle" : getValue("top");
		if (typeof recalonload!=DWin.contents.undefined && recalonload=="recal" && this.scroll_top==0){
			if (window.attachEvent && !window.opera){
				this.addEvent(window, function(){setTimeout(function(){t.moveTo(xpos, ypos)}, 400)}, "load");
			}else{
				this.addEvent(window, function(){t.moveTo(xpos, ypos)}, "load");
			}
		}
		t.isResizable(getValue("resize"));
		t.isScrollable(getValue("scrolling"));
		t.style.visibility="visible";
		t.style.display="block";
		t.contentarea.style.display="block";
		t.moveTo(xpos, ypos);
		t.load(contenttype, contentsource, title);
		if ((t.state==DWin.contents.minimized) && (t.controls.firstChild.title==DWin.contents.restore)){
			t.controls.firstChild.setAttribute("src", DWin.includePath+'/'+DWin.imagefiles.min);
			t.controls.firstChild.setAttribute(DWin.contents.title, DWin.contents.minimize);
			t.state="fullview";
		}
		DWin.covered(t);
		return t;
	},
	
	setSize:function(t, w, h){
		t.style.width=Math.max(parseInt(w), 150)+"px";
		t.contentarea.style.height=Math.max(parseInt(h), 100)+"px";
	},
	
	moveTo:function(t, x, y){
		this.getviewpoint();
		t.style.left=(x=="middle")? this.scroll_left+(this.docwidth-t.offsetWidth)/2+"px" : this.scroll_left+parseInt(x)+"px";
		t.style.top=(y=="middle")? this.scroll_top+(this.docheight-t.offsetHeight)/2+"px" : this.scroll_top+parseInt(y)+"px";
	},
	
	isResizable:function(t, bol){
		t.statusarea.style.display=(bol)? "block" : "none";
		t.resizeBool=(bol)? 1 : 0;
	},
	
	isScrollable:function(t, bol){
		t.contentarea.style.overflow=(bol)? "auto" : "hidden";
	},
	
	load:function(t, contenttype, contentsource, title){
		if (t.isClosed){
			alert("Диалоговое окно закрыто. Попробуйте повторить операцию Open/Create еще раз.");
			return;
		}
		contenttype=contenttype.toLowerCase();
		if (typeof title!=DWin.contents.undefined){
			t.handle.firstChild.nodeValue=title;
		}
		if (contenttype=="inline"){
			t.contentarea.innerHTML=contentsource;
		}else if (contenttype=="div"){
			var inlinedivref=DWin.$(contentsource);
			t.contentarea.innerHTML=(inlinedivref.defaultHTML || inlinedivref.innerHTML);
			if (!inlinedivref.defaultHTML){
				inlinedivref.defaultHTML=inlinedivref.innerHTML;
			}
			inlinedivref.innerHTML="";
			inlinedivref.style.display="none";
		}else if (contenttype=="iframe"){
			t.contentarea.style.overflow="hidden";
			if (!t.contentarea.firstChild || (t.contentarea.firstChild.tagName!="IFRAME")){
				t.contentarea.innerHTML='<iframe style="border:0; margin:0; padding:0; width:100%; height: 100%" id="_iframe-'+t.id+'" name="_iframe-'+t.id+'" class="DWinDragIFrame" src=""></iframe>';
			  if(DWin.$("_iframe-"+t.id)){
			    DWin.$("_iframe-"+t.id).src=contentsource;
			  }
			}else{
			  if(DWin.$("_iframe-"+t.id)){
			    DWin.$("_iframe-"+t.id).src=contentsource;
			  }
			}
		}
		t.contentarea.datatype=contenttype;
	},
	
	getviewpoint:function(){var _=DWin;
		var ie=document.all && !window.opera;
		var domclientWidth=document.documentElement && parseInt(document.documentElement.clientWidth) || 100000;
		_.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body;
		_.scroll_top=(ie)? _.standardbody.scrollTop : window.pageYOffset;
		_.scroll_left=(ie)? _.standardbody.scrollLeft : window.pageXOffset;
		_.docwidth=(ie)? _.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(domclientWidth, window.innerWidth-16);
		_.docheight=(ie)? _.standardbody.clientHeight: window.innerHeight;
	},
	
	move:function(t, e){
		t.style.left=DWin.distancex+DWin.initx+"px";
		t.style.top=DWin.distancey+DWin.inity+"px";
		DWin.covered(t);
	},
	
	resize:function(t, e){
		t.style.width=Math.max(DWin.width+DWin.distancex, 150)+"px";
		t.contentarea.style.height=Math.max(DWin.contentheight+DWin.distancey, 100)+"px";
		DWin.covered(t);
	},
	
	enablecontrols:function(e){
		var d=DWin;
		var sourceobj=window.event? window.event.srcElement : e.target;
		if (new RegExp(DWin.contents.minimize,"i").test(sourceobj.getAttribute(DWin.contents.title))){
			d.minimize(sourceobj, this._parent);
		}else if (new RegExp(DWin.contents.restore,"i").test(sourceobj.getAttribute(DWin.contents.title))){
			d.restore(sourceobj, this._parent);
		}else if (new RegExp(DWin.contents.close,"i").test(sourceobj.getAttribute(DWin.contents.title))){
			d.close(this._parent);
		}
		return false;
	},
	
	minimize:function(button, t){
		DWin.__.rememberattrs(t);
		button.setAttribute("src", DWin.includePath+'/'+DWin.imagefiles.restore);
		button.setAttribute(DWin.contents.title, DWin.contents.restore);
		t.state=DWin.contents.minimized;
		t.contentarea.style.display="none";
		t.statusarea.style.display="none";
		if (typeof t.minimizeorder==DWin.contents.undefined){
			DWin.minimizeorder++;
			t.minimizeorder=DWin.minimizeorder;
		}
		t.style.left="10px";
		t.style.width="200px";
		var windowspacing=t.minimizeorder*10;
		t.style.top=DWin.scroll_top+DWin.docheight-(t.handle.offsetHeight*t.minimizeorder)-windowspacing+"px";
		DWin.covered(t);
	},
	
	restore:function(button, t){
		this.getviewpoint();
		button.setAttribute("src", DWin.includePath+'/'+DWin.imagefiles.min);
		button.setAttribute(DWin.contents.title, DWin.contents.minimize);
		t.state="fullview";
		t.style.display="block";
		t.contentarea.style.display="block";
		if (t.resizeBool){
			t.statusarea.style.display="block";
		}
		t.style.left=parseInt(t.lastx)+DWin.scroll_left+"px";
		t.style.top=parseInt(t.lasty)+DWin.scroll_top+"px";
		t.style.width=parseInt(t.lastwidth)+"px";
		DWin.covered(t);
	},
	
	
	close:function(t){
		try{
			var closewinbol=t.onclose();
		}
		catch(err){
			var closewinbol=true;
	 }
		finally{
			if (typeof closewinbol==DWin.contents.undefined){
				alert("Возникла ошибка в обработчике события \"onclose\" во время закрытия диалогового окна");
				var closewinbol=true;
			}
		}
		if (closewinbol){
		  if(t.state!=null){
			  if (t.state!=DWin.contents.minimized){
				  DWin.__.rememberattrs(t);
				 }
			}
			if (window.frames["_iframe-"+t.id]){
			  if(DWin.$("_iframe-"+t.id)){
			    DWin.$("_iframe-"+t.id).src=DWin.srcDefault;
			  }
			}else{ t.contentarea.innerHTML=""; }
			t.style.display="none";
			t.isClosed=true;
  		DWin.covered(t);
		}
		return closewinbol;
	},
	
	setopacity:function(targetobject, value){
		if (!targetobject){ return; }
		if (typeof targetobject.style.filter!=DWin.contents.undefined){
			targetobject.style.filter="alpha(opacity="+value*100+")";
		}else if (typeof targetobject.style.MozOpacity!=DWin.contents.undefined){
			targetobject.style.MozOpacity=value;
		}else if (typeof targetobject.style.opacity!=DWin.contents.undefined){
			targetobject.style.opacity=value;
		}
	},
	
	setfocus:function(t){
		this.zIndexvalue++;
		t.style.zIndex=this.zIndexvalue;
		t.isClosed=false;
		this.setopacity(this.lastactivet.handle, 0.5);
		this.setopacity(t.handle, 1);
		this.lastactivet=t;
	},
	
	
	show:function(t){
		if (t.isClosed){
			alert("DHTML диалогового окна было закрыто, поэтому показать его не возможно. Попробуйте выполнить операцию Open/Create еще раз.");
			return;
		}
		if (t.lastx){ DWin.restore(t.controls.firstChild, t);
		}else{ t.style.display="block"; DWin.covered(t); }
		this.setfocus(t);
		t.state="fullview";
	},
	
	hide:function(t){
		t.style.display="none";
		DWin.covered(t);
	},
	
	stop:function(){
		DWin.etarget=null;
		document.onmousemove=null;
		document.onmouseup=null;
	},
	
	addEvent:function(target, functionref, tasktype){
		var tasktype=(window.addEventListener)? tasktype : "on"+tasktype;
		if(target.addEventListener){ target.addEventListener(tasktype, functionref, false);
		}else if(target.attachEvent){ target.attachEvent(tasktype, functionref); }
	},
	
	cleanup:function(){
		for (var i=0; i<DWin.tobjects.length; i++){
			DWin.tobjects[i].handle._parent=DWin.tobjects[i].resizearea._parent=DWin.tobjects[i].controls._parent=null;
		}
		window.onload=null;
	},
	
	addButton:function(win, title, func){var _=DWin;
		function getPanel(){
			var pColl = _.$$("DIV", win, "className=='DWinDragButtons'");
			if(pColl.length>0){ return pColl[0]; }
			
			var statusbar = _.$$("DIV", win, "className=='DWinDragStatusarea'")[0];
			var pnl = document.createElement("DIV");
			win.insertBefore(pnl, statusbar);
			pnl.className = "DWinDragButtons";
			return pnl;
		}
		var pnl = getPanel();
		var bt = document.createElement("INPUT");
		bt.type = "button";
		bt.className="DWinDragInput";
		pnl.appendChild(bt);
		bt.value = title;
		bt.onclick = func;
	},
	
	closeDialog: function(srcButton){
		srcButton = (srcButton && srcButton.tagName)?srcButton:this;
		var dlg = srcButton.parentNode.parentNode;
		dlg.close();
	},

	covered: function(t){
	  function getVisibility(obj){
		  var value = obj.style.visibility;
		  if(!value){
			  if(document.defaultView && typeof(document.defaultView.getComputedStyle)=="function"){
          value=document.defaultView.getComputedStyle(obj, "").getPropertyValue("visibility");
        }else if(obj.currentStyle){
          value=obj.currentStyle.visibility;
        }else{
          value='';
        }
      }
      return value;
	  };
	  
	  getAbsolutePos=function(obj){
      var SL=0,ST=0;
      var is_div = /^div$/i.test(obj.tagName);
      if(is_div && obj.scrollLeft){
	      SL=obj.scrollLeft;
	    }
      if(is_div && obj.scrollTop){
	      ST=obj.scrollTop;
	    }
      var r={x:obj.offsetLeft - SL, y:obj.offsetTop - ST};
      if(obj.offsetParent){
	      var tmp = getAbsolutePos(obj.offsetParent);
	      r.x += tmp.x;
	      r.y += tmp.y;
      }
      return r;
	  };
	  
	  hasOwnerDialog=function(obj, own){
	    var el=obj.parentNode;
	    var r=false;
	    while(el!=null){
	      var p=el.parentNode;
	      if(el.id!=null){
	        if(el.id==own.id){ r=true; break; }
	        if(el.style.visibility!=null){
	          if(el.style.visibility=='hidden'){ r=true; break; }
	        }
	        if(el.style.dispaly!=null){
	          if(el.style.dispaly=='none'){ r=true; break; }
	        }
	      }
	      if(el.tagName.toUpperCase()=='BODY'){ break; }
	      el=p;
	    }
	    return r;
	  };

    var slct=null;
    var dd=getAbsolutePos(t);
    var dx1=dd.x;
    var dx2=t.offsetWidth+dx1;
    var dy1=dd.y;
    var dy2=t.offsetHeight+dy1;
    if(t.style.visibility=='hidden'){
      dx1=0;dx2=1;dy1=0;dy2=1;
    }
    for(var j=0;j<2;j++){
      if(j==0){
        slct=document.getElementsByTagName("select");
      }else if(j==1){
        slct=document.getElementsByTagName("object");
      }else{
        slct=null;
      }
      if(slct!=null){
        for(var i=0;i<slct.length;i++){
          var el=slct[i];
          if(!hasOwnerDialog(el, t)){
            var ee=getAbsolutePos(el);
            var ex1=ee.x;
            var ex2=el.offsetWidth+ex1;
            var ey1=ee.y;
            var ey2=el.offsetHeight+ey1;
            if((ex1>dx2) || (ex2<dx1) || (ey1>dy2) || (ey2<dy1)){
				      if(el.SavedVisibility==null){
					      el.SavedVisibility=getVisibility(el);
				      }
				      el.style.visibility=el.SavedVisibility;
            }else{
				      if(el.SavedVisibility==null){
					      el.SavedVisibility=getVisibility(el);
				      }
				      el.style.visibility='hidden';
            }
          }
        }
      }
    }
	}

}
window.onunload=DWin.cleanup;
