﻿(function(){
var count=0;
var prefix = "_win";
var zIndex = 1000;
var contenerZIndex = 100000;
var all={};
var focusid=null;
var isIE= navigator.appName=="Microsoft Internet Explorer";
function getPath(){
	var scripts=document.getElementsByTagName("script");
	for(var i=scripts.length-1;i>-1;i--){
		if(/window.js($|\?|#)/.test( scripts[i].src )){
			var path = scripts[i].src.replace(/[^\\\/]+$/,"");
			if( path =="")
				path = "./";
			return path;
			
		}
	}
	return "";
}
var selfPath = getPath();
function MdiWindow(arg , src , userData){
	var id = count ++;
	this.userData = userData;

	this._childWindows=[];
	this.id = prefix + id; ;
	this.parent = null;
	all[ this.id ] = this;
	var tmp = document.createElement( "div");
	var csstext="";
	if(!arg){
		arg = {};
	}
	
	tmp.innerHTML = winHtml.replace(/#id/g , this.id)
			.replace(/#maincsstext/, MdiWindow._getcsstext( arg ) )
			.replace(/#wintitle/,arg.title || "");
	tmp.firstChild.style.zIndex = zIndex ++ ;
	var div = getCntnr().appendChild( tmp.firstChild );
	this.focus();
	drag( this.id );
	if( src ){
		this.load( src );
	}
	


}
window.MdiWindow =MdiWindow;

MdiWindow.all=function(id){
	return all[id];
}
MdiWindow.setUserData=function(userData){
	this.userData = userData;
}
MdiWindow._getcsstext=function(arg){
	var css=[];
	if( !isNaN( arg.width)){
		css.push( "width:"+ arg.width +"px");
	}
	if( !isNaN( arg.height)){
		css.push( "height:"+ arg.height +"px");
	}
	if( !isNaN( arg.top)){
		css.push( "top:"+ arg.top +"px");
	}
	if( !isNaN( arg.left)){
		css.push( "left:"+ arg.left +"px");
	}
	return css.join(";");
}
var winHtml='\
<div class="win" id="#id" ondrag="stopEvent(event);"  ondragstart="MdiWindow.stopEvent(event);"  ondragdrop="stopEvent( event);" onselect="MdiWindow.stopEvent(event);"   onselectstart="MdiWindow.stopEvent(event);" style="#maincsstext" >\
	<div class="win-frmbg" id="#id-frmbg"><iframe frameborder="no" src="blank.html" width="100%" height="100%"></iframe></div>\
	<div class="win-cover" id="#id-cover"><iframe frameborder="no" src="blank.html" width="100%" height="100%"></iframe><div>&nbsp;</div></div>\
	<div class="win-main" id="#id-main"></div>\
	<div class="win-border" id="#id-border">\
		<div class="lt "></div>\
		<div class="t "></div>\
		<div class="rt "></div>\
		<div class="l"></div>\
		<div class="lb "></div>\
		<div class="r"></div>\
		<div class="rb "></div>\
		<div class="b"></div>\
	</div>\
	<div class="win-btns" id="#id-btns">\
		<a href="" class="win-btns-min"  id="#id-btns-min"  onmousedown="MdiWindow.stopPragation(event)" ></a>\
		<a href="" class="win-btns-toggle" id="#id-btns-toggle"  onmousedown="MdiWindow.stopPragation(event)"></a>\
		<a href="" class="win-btns-close" id="#id-btns-close" onmousemove="MdiWindow.stopPragation(event)" onmousedown="MdiWindow.stopPragation(event)" onclick="MdiWindow.all(\'#id\').close();return false;"></a>\
	</div>\
	<div class="win-icon" id="#id-btns-icon"></div>\
	<div class="win-resizer-rb" id="#id-resizer-rb"></div>\
	<div class="win-title" id="#id-title"   onselect="MdiWindow.stopEvent(event);"  onselectstart="MdiWindow.stopEvent(event);" >#wintitle</div>\
</div>';


MdiWindow.prototype.close=function(){
	if(typeof this.onClose =="function"){
		var b = this.onClose();
		if( b===false){//阻止关闭
			return;
		}
	}
	E(prefix+"-bg").style.display="none";
	if(focusid == this.id){
		focusid = null;
	}
	var obj = document.getElementById( this.id );
	obj.parentNode.removeChild( obj );
	
	//alert([this.parent , this.parent._childWindows]);
	//断开父窗口的连接
	if( this.parent && this.parent._childWindows){
		
		var wins = this.parent._childWindows;
		for(var i=wins.length-1;i>-1;i--)
		{
			if(wins[i]==this)
			{
				wins.splice(i,1);
			}
		}
		this.parent = null;
	}
	this.isClosed=true;
	delete all[ this.id ] ;
}

MdiWindow.prototype.focus=function(){
	var pWin = this;

	while( pWin._isModal && pWin.parent ){//本窗口为模式窗口，同时提升父窗口
		pWin = pWin.parent;
		var obj = E( pWin.id );
		if( !obj)
			break;
		obj.style.zIndex = zIndex ++;
		
	}
	if( this._childWindows.length>0){//如果有模式子窗口，模式子窗口激活
		
		for(var i= this._childWindows.length-1 ; i>-1 ; i-- ){
			if(this._childWindows[i]._isModal ){
				this._childWindows[i].focus();
				return false;
			};
		}
	}
	if( focusid )
	{
		all[ focusid ].blur();
	}
	this._selected = true;
	if(typeof this.onFocus =="function"){
		var b = this.onFocus();
	}
	focusid= this.id;
	this._hideCover();
}
MdiWindow.prototype.blur=function(){

	if(typeof this.onBlur =="function"){
		var b = this.onBlur();
	}
	this._selected = false;
	this._showCover();

}
MdiWindow.prototype._hideCover=function(){
	var objMain = E(this.id );
	objMain.className = (objMain.className|| "").replace(/win\-focus/ig,"").replace(/\s{2,}/g,"")	+ " win-focus"  ;
	objMain.style.zIndex = zIndex ++;
	
}
MdiWindow.prototype._showCover=function(){
	var objMain = E(this.id );
	objMain.className =(objMain.className||"").replace(/win\-focus/ig,"").replace(/\s{2,}/g,"");
	
}
MdiWindow.prototype.setTitle=function(sTitle){
	E(this.id+"-title").innerHTML = sTitle;
}
MdiWindow.prototype.load = function( href ,doc){
	
	if(!(/(^\w+:\/\/)|(^\/)/.test(href))  ){
		doc = doc||document;
		var base = doc.URL.replace(/[^\\\/]+$/,"");
		href = base + href;
	}
	this.src = href;
	
	E( this.id +"-main" ).innerHTML = "<iframe src='"+selfPath+"loader.html#" + this.id + "' border='0' frameborder='0' style='width:100%;height:100%;border:none;'></iframe>";
}
MdiWindow.prototype.setHTML=function(html){
	E( this.id +"-main" ).innerHTML = html;
	
}
MdiWindow.prototype.initPageDiv=function(objDiv){
	if( objDiv.parentNode)
		objDiv.parentNode.removeChild( objDiv );
	E( this.id +"-main" ).innerHTML = ""
	E( this.id +"-main" ).appendChild( objDiv );
	
}
MdiWindow.prototype._resetbgframe=function( rect ){
	rect = rect ||  this._getborderrect();
	
	var divfrm = document.getElementById(this.id+"-frmbg");
	divfrm.style.left = rect.left +"px";
	divfrm.style.top = rect.top +"px";
	divfrm.style.width = rect.width +"px";
	divfrm.style.height = rect.height +"px";
}
MdiWindow.prototype.moveTo=function(left,top){
	var objMain = E(this.id );
	objMain.style.left = left+"px";
	objMain.style.top = top+"px";
	this.left =left;
	this.top = top;
}
MdiWindow.prototype.show=function(evt){
	var objMain = E(this.id );
	objMain.style.display="block";
	this.coverAll();
	if(evt ){
		
	}
}
MdiWindow.prototype.coverAll=function(){
	var obj = E(prefix+"-bg");
	obj.style.display="block";
	obj.style.zIndex = E(this.id ).style.zIndex - 1;
	obj.style.width = Math.max(document.body.scrollWidth , document.documentElement.scrollWidth )+"px";
	obj.style.height = Math.max(document.body.scrollHeight , document.documentElement.scrollHeight )+"px";
}
MdiWindow.prototype.hide=function(evt){
	var objMain = E(this.id );
	objMain.style.display="none";
	if(evt ){
		
	}
	E(prefix+"-bg").style.display="none";
}
MdiWindow.prototype.moveToCenter=function(){
	this.show();
	var width = Math.min(document.body.clientWidth,document.documentElement.clientWidth);
	var height = Math.min(document.body.clientHeight,document.documentElement.clientHeight);
	var objMain = E(this.id );
	var top = Math.floor(Math.max(document.body.scrollTop,document.documentElement.scrollTop) + (height - objMain.offsetHeight )/2);
	var left = Math.floor(Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) +(width- objMain.offsetWidth )/2);
	
	this.moveTo(left ,top);
}
MdiWindow.prototype._getborderrect=function(){
	var border = document.getElementById(this.id+"-border");
	var nodes = border.childNodes;
	var top=0;
	var left=0;
	var width=0;
	var height=0;
	for(var i=nodes.length-1;i>-1;i--){
		var node = nodes[i];
		if(nodes[i].nodeType!=1)
			continue;
		
		left = Math.min( left, node.offsetLeft );
		width = Math.max( width , node.offsetLeft + node.offsetWidth );
		top = Math.min( top , node.offsetTop );
		height = Math.max( height , node.offsetTop + node.offsetHeight );
	}
	var contenerWidth =  border.offsetParent.offsetWidth;
	var contenerHeight =  border.offsetParent.offsetHeight;
	return {
		left:left,
		top:top,
		right:contenerWidth - width ,/*右框最右边距离main右边，为负值*/
		bottom:contenerHeight - height ,
		width:width - left,
		height:height - top
	}
}
function getCntnr(){
	var div = E( prefix + "cntnr" );
	if( div == null )
		return globalinit();
	return div;
}
function globalinit(){
	var div = document.createElement("div");
	div.id = prefix + "cntnr";
	document.body.appendChild( div );
	div.style.position="absolute";
	div.style.top="0px";
	div.style.left="0px";
	div.style.zIndex = contenerZIndex;


	div.innerHTML ="<div id='" + prefix+ "-dragproxy' class='win-dragproxy'><div>&nbsp;</div></div>"+
		"<div id='"+prefix+"-bg' class='win-contener-bg'></div>";
	if( isIE)
		div.className+=" ie";
	return div;
}

function drag( id ){
	var clickX,clickY;
	var preOffset={top:0,left:0};
	var dragid = id;
	var proxyid = prefix + "-dragproxy";
	var bDrg = false;
	var type=0;
	var rect;
	E( dragid ).onmousedown = function(evt){
		evt = evt || window.event;
		var src = ( evt.target|| evt.srcElement);
		if(/^(input|select|button|textarea|label|p|a|span)$/i.test(src.tagName))
		{
			return;
		}	
 		 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
		var o = this;
		all[id].focus();
		if( src.className =='win-cover' || src.parentNode.className =="win-cover"){
			return ;
		}
		//o=document.body;
		
		clickX = evt.pageX|| evt.clientX;
		clickY = evt.pageY|| evt.clientY;
		//document.title = clickX +" "+ clickY;

		initDrgProxy(evt , this); 
		
		startDrag();
		if( evt.stopProgation )
		{
			evt.stopProgation();
		}
		else{
			evt.cancelBubble = true;
		}	
		//document.title = (evt.target|| evt.srcElement).className;
		if( src.className=='win-resizer-rb' )
		{
			type = 2;
		}
		else{
			type = 0;
		}
		if(window.captureEvents)
			window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
		else if(document.documentElement.setCapture)
			o.setCapture();
		stopEvent(evt);
		return false;
	}

	function startDrag(){
		
		document.documentElement.onmousemove=function(evt){
			evt = evt || event;
			//document.title = evt.button +" "+ evt.which + " "+evt.pageX ;
			//window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
			var x = evt.pageX || evt.clientX;
			var y = evt.pageY || evt.clientY;
			var proxy = document.getElementById( proxyid );
			if( type==0)//移动
			{
				var left =  preOffset.left + ( x - clickX );
				var top = preOffset.top + ( y - clickY  );
				if( left<0)left = 0;
				if( top<0) top = 0;
				proxy.style.left =left +"px";
				proxy.style.top = top +"px";
			}
			else if( type == 2 )
			{
				proxy.style.width = preOffset.width + ( x - clickX ) +"px";
				proxy.style.height = preOffset.height + ( y - clickY  ) +"px";
			}
			if(!bDrg){
				proxy.style.display = "block";
				bDrg = true;

			}
			stopEvent(evt);
			return false;
		}
		document.documentElement.onmouseup = function(evt){
			evt = evt || event;
			var x = evt.pageX || evt.clientX;
			var y = evt.pageY || evt.clientY;
			var o = E( dragid );
			if(window.releaseEvents){
				window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP);
				
			}else if(document.documentElement.releaseCapture)
				o.releaseCapture();
			var proxy = E( proxyid );
			if( bDrg && proxy)
			{
				if( type==0)//移动
				{
					o.style.top = proxy.offsetTop - rect.top +"px";
					o.style.left = proxy.offsetLeft - rect.left +"px";
				}else if( type== 2){//缩放
					if( proxy.offsetWidth>50 && proxy.offsetHeight>20)
					{
						o.style.width = proxy.offsetWidth - rect.deltaWidth +"px";
			
						o.style.height = proxy.offsetHeight - rect.deltaHeight +"px";
					}
				}
			}
			//document.title = [o.style.top,o.offsetTop];
			
			clear( evt );
			stopEvent(evt);
		}
		document.documentElement.onmouseout = function(evt){
			//clear( evt );
		}
		function clear(evt){
			all[id]._resetbgframe();
			document.documentElement.onmousemove = new Function();
			document.documentElement.onmouseup = new Function();
			E( proxyid ).style.display = "none";
			proxy = null;
			bDrg = false;
		}

		
	}
	function initDrgProxy(evt,obj){
		
		rect = all[id]._getborderrect();
		var obj = E( dragid );
		var proxy = E( proxyid );
		preOffset.top = obj.offsetTop + rect.top;
		preOffset.left = obj.offsetLeft + rect.left;
		preOffset.width = rect.width;
		rect.deltaWidth = rect.width - obj.offsetWidth;
		preOffset.height = rect.height;
		rect.deltaHeight = rect.height - obj.offsetHeight;
		



		//var border = E( id +"-border");


		var style = proxy.style;
		style.width = preOffset.width +"px";
		style.height = preOffset.height +"px";
		
		style.top = preOffset.top + "px";
		style.left = preOffset.left +"px";

		
	}

}
/***
 * 取window
 ****/
function W( id ){

	return all[ id ] ;
}
function E(id){
	return document.getElementById( id );
}
function stopEvent(evt){
	if( !evt)
		return;
	if( evt.stopPragation){
		evt.stopPragation();
		evt.preventDefault();
	}
	else{
		 evt.cancelBubble = true;
		 evt.returnValue = false;
	}
}
MdiWindow.stopEvent = stopEvent;
function stopPragation(evt){
	if(evt.stopPragation)evt.stopPragation();else evt.cancelBubble = true;
}
MdiWindow.stopPragation = stopPragation;
})();
//MdiWindow.
