var isReady = false;
var PageFrame, BodyElem, MaskLayer, WaitMsgLayer;
var btnShowPage, btnEditPage, lnkPreview, lnkDetail, lnkToolBox, lbPageName;

function Page_Init()
    {
	BodyElem = document.documentElement.childNodes[1];
	
	PageFrame = $('PageFrame');
	MaskLayer = $('MaskLayer');
	WaitMsgLayer = $('WaitMsgLayer');
	
	btnShowPage = $('btnShowPage');
	lnkPreview = $('lnkPreview');
	lnkDetail = $('lnkDetail');
	lnkToolBox = $('lnkToolBox');
	lbPageName = $('lbPageName');
    }

var EditPageWindow, EditPageDocument;
var PagePath, PageUrl, SiteRootUrl, FactoryRootUrl, SiteName;

//页面加载
function Page_Load()
    {
	SiteName = Common.GetQueryString('sitename');
	if( !SiteName ) return;
	
	PagePath = $('hfPagePath').value;
	SiteRootUrl = $('hfSiteRootUrl').value;
	FactoryRootUrl = $('hfFactoryRootUrl').value;    
	/*-------------为调试的代码----------------*/
	SiteRootUrl = SiteRootUrl.replace(/localhost(:\d+)?/i,'localhost');
	/*-----------------------------*/
	
	var page = new UrlText( SiteRootUrl, PagePath );
	PageUrl = page.Text;
	lnkPreview.href = PageUrl;
	_FreshPage( PageUrl );
    }
function Page_Resize()
    {
	var w, h;
	w = document.documentElement.clientWidth-0;
	if( w<0 ) w=0;
	h = document.documentElement.clientHeight-31;
	if( h<0 ) h=0;
	
	PageFrame.style.width = w;
	PageFrame.style.height = h;
	
	WaitMsgLayer.style.height = document.documentElement.clientHeight-31;
    }

// 刷新页面
function btnShowPage_Click()
    {
	_FreshPage( PageUrl );
    }
function _FreshPage( url )
    {
	if( !url ) return;//alert('_FreshPage url='+url);
	
	isReady = false;
	_LoadState = 0;
	CloseWaitingBox();
	    
	lbPageName.innerText = '正在加载"'+ PagePath +'"，请稍候...';
	btnShowPage.disabled = true;
	PageFrame.src = url + '?mode=edit&uin='+ Common.UniqueValue();
	PageFrame.onreadystatechange = PageFrame_Load.bind( PageFrame );
    }

function lnkDetail_Click()
    {
	if( !isReady ) return;
	
	var url = new UrlText( FactoryRootUrl, '~/Editor/PageDetail.aspx' );
	url.Add( ['SiteName', SiteName], ['PagePath', PagePath], 'uni' );

	var sMsg = Common.ShowDialog( 1, url.Text, null, {width:400,height:500} );
	if ( /^ok/i.test(sMsg) )
	    btnShowPage_Click();
    }
function lnkToolBox_Click()
    {
	if( isReady ) {
	    ToolBoxPanel.ShowHidden();
	}
    }

function CloseWaitingBox()
    {
	WaitMsgLayer.style.display = 'none';
    }
function ShowWaitingBox()
    {
	WaitMsgLayer.style.display = 'block';
    }
function PageFrame_Load()
    {
	if( this.readyState == 'complete' ){
	    _PageFrame_DomLoaded();
	}
    }
var _LoadState = 0;
function _PageFrame_DomLoaded()
    {
	if( _LoadState>0 ) return;
	_LoadState = 1;
	lbPageName.innerText = '['+ PagePath +']';
	DisableLink( this.contentWindow );
	btnShowPage.disabled = false;
	
	EditPageWindow = PageFrame.contentWindow;
	EditPageWindow.ParentWindow = window;
	EditPageWindow.CloseWaitingBox = CloseWaitingBox;
	EditPageWindow.ShowWaitingBox  = ShowWaitingBox;
	
	EditPageDocument = EditPageWindow.document;
	EditPageDocument.SiteName = SiteName;
	EditPageDocument.PagePath = PagePath;
	EditPageDocument.SiteRootUrl = SiteRootUrl;
	EditPageDocument.FactoryRootUrl = FactoryRootUrl;
	
	ToolBoxPanel.Load();
	
	IncludeStyle( EditPageDocument, SiteRootUrl+'~sys/style/PageEditor.css' );
	
	var load = new cLoadScript( EditPageDocument,
	                            [ FactoryRootUrl+'Script/Base.js',
	                              FactoryRootUrl+'Script/Common.js',
	                              FactoryRootUrl+'Script/EditorCore.js' ] );
	load.Start();
	
	isReady = true;
	_LoadState = 2;
    }
function DisableLink( win )
    {
	if( !win || !win.document ) return;
	
	var linkList = win.document.getElementsByTagName('A');
	var n = linkList.length;   //alert(n);
	for( var i=0; i<n; i++ ){
	    var link = linkList[i];
	    link.onclick = function(){return false};
	    link.onmousedown = function(){return false};
	    link.onmouseup = function(){return false};
	}
    }



/* cLoadScript 类 / 应用类 / 处理脚本的运行期加载事务
/* -------------------------------------------------------------------------------------------- */
cLoadScript = Class.create();
cLoadScript.prototype = {
    initialize : function( doc, urls ){
	this._Urls = urls || [];
	this._Index = 0;
//	this._XmlHttp = (new XML.Base()).CreateXmlHttp();
	this._Doc = doc || document;
	this._CurUrl = '';
    },
    SetUrls : function( urls ){
	this._Urls = urls || [];
    },
    Start : function(){
	this._XmlHttp = (new XML.Base()).CreateXmlHttp();   //alert();
	var l = this._Urls.length;
	if( l <= 0 ) return;
	if( this._Index < l )
	    this._Load();
    },
    _Load : function(){
	this._CurUrl = this._Urls[ this._Index ];
	this._XmlHttp.OnReadyStateChange = this._Response.bind(this);
	this._XmlHttp.open( 'GET', this._CurUrl, false );
	this._XmlHttp.send( null );
    },
    _Response : function(){
	var xh = this._XmlHttp;
	if( xh.readyState == 4 ){
	    if( xh.status == 200 || xh.status == 304 ){
	        this._Insert( xh.responseText );
	    } else{
	        throw new Error( 'Load scrpit error: ' + xh.statusText + ' (' + xh.status + ')' ) ;
	    }
	}
    },
    _Insert : function( text ){
	var doc = this._Doc;//doc || document;
	var id = this._CurUrl;
	if( !doc.getElementById(id) ){
	    var head = doc.getElementsByTagName('head')[0];
	    var script = doc.createElement('script');
	    script.language = 'javascript';
	    script.type = 'text/javascript';
	    script.defer = true;
	    script.id = id;     // 防止重复加载
            script.text = text;
	    head.appendChild( script );
	}
	this._Index ++;
	this.Start();
    }
};

function IncludeStyle( doc, url )
    {
	doc = doc || document;
	doc.createStyleSheet( url );
    }
/* */


/* ============================================================================================ */
/*					ToolBoxPanel 命名空间					*/
/* ============================================================================================ */
var ToolBoxPanel = {
    PanelBox : null,
    ChildBox : null,
    ToolBox : null,
    Load : function(){
	if( this.ToolBox && this.ToolBox.IsReady ){
	    this.ToolBox.Show();
	    return;
	}	
	this.ToolBox = new ToolBoxPanel.Panel( BodyElem, 'SolidPanel' );//alert('1-0  '+BodyElem);

	var CtrlSrc = new XML.Source();// {IsDebug:false, DebugOutput:$('testXML')} );
	CtrlSrc.Load( FactoryRootUrl + 'Script/Toolbox.xml' );//document.
	CtrlRd = new XML.NodeReader( CtrlSrc );
	CtrlRd.SelectRoot();

	if( CtrlRd.ToChild() ){ do{

	    if( CtrlRd.Name == 'toolFolder' )
	        new ToolBoxPanel.FolderButton();
	        
	    else if( CtrlRd.Name == 'toolNode' )
	        new ToolBoxPanel.NodeButton();

	}while( CtrlRd.ToNext() )};
    },
    ShowHidden : function(){
	if( this.ToolBox ){
	    if(　this.ToolBox.isShowed )
	        this.ToolBox.Hidden();
	    else
	        this.ToolBox.Show();
	}
    }
};

/* Panel 类 / 应用类
/* -------------------------------------------------------------------------------------------- */
ToolBoxPanel.Panel = Class.create();
ToolBoxPanel.Panel.prototype = {
    initialize : function( parElem, id, parWnd ){
	if( !parElem ) return false;
	this.parentDoc = (parWnd || window).document;
	this.elem = this.parentDoc.createElement('div');
	this.elem.id = id;
	this.elem.innerHTML = '<h1><span>部件工具箱</span><a href="#"></a></h1> <h2></h2>';
	parElem.appendChild( this.elem );
	
	this.boxElem = this.elem.childNodes[1];
	ToolBoxPanel.PanelBox = this.boxElem;  //alert('1-1  '+ToolBoxPanel.PanelBox);
	
	this.elem.childNodes[0].childNodes[1].onclick = this.Move.bind( this );
	this.isRight = true;
	this.IsReady = true;
	this.isShowed = true;
    },
    AddItem : function(){
	;
    },
    Move : function(){
	event.srcElement.blur();
	if( this.isRight ){
	    this.elem.style.left = '8px';
	    this.elem.style.right = '';
	    this.isRight = false;
	} else{
	    this.elem.style.left = '';
	    this.elem.style.right = '8px';
	    this.isRight = true;
	}
    },
    Show : function(){
	if( this.elem && this.elem.style ){
	    this.elem.style.display = 'block';
	    this.isShowed = true;
	}
    },
    Hidden : function(){
	if( this.elem && this.elem.style ){
	    this.elem.style.display = 'none';
	    this.isShowed = false;
	}
    }
};


/* Folder Button 类 / 应用类 / 继承 Button.Link 类
/* -------------------------------------------------------------------------------------------- */
ToolBoxPanel.FolderButton = Class.create();
ToolBoxPanel.FolderButton.prototype = Object.extend( (new Button.Link()), {
    initialize : function( parElem, parWnd ){
	parElem = parElem || ToolBoxPanel.PanelBox;//alert('2-2  '+ToolBoxPanel.PanelBox);
	this._init_( parElem, parWnd, null, false );//alert('2-3');
	this.Id = CtrlRd.AttrBy('id');
	this.Caption = CtrlRd.AttrBy('caption');
	this.elemRef.className = 'toolFolder';
	this.elemRef.innerHTML = '<b></b><span>' + CtrlRd.AttrBy('caption') + '</span>';
	this.ChildBox = this.parentDoc.createElement('div');
	ToolBoxPanel.ChildBox = this.ChildBox; //alert('2-3');
	this.parentElem.appendChild( this.ChildBox );
	this.isOpened = true;
	//alert('2-5');
	this.CallBack = function(){
	    if( !this.ChildBox ) return;
	    if( this.isOpened ){
	        this.ChildBox.style.display = 'none';
	        this.elemRef.firstChild.style.backgroundPosition = '0 -9px';
	        this.isOpened = false;
	    } else{
	        this.ChildBox.style.display = 'block';  
	        this.isOpened = true;
	        this.elemRef.firstChild.style.backgroundPosition = '0 0';
	    }
	};//alert('2-9');
    },
    GetChildBox : function(){
	return this.ChildBox;
    }
});


/* Node Button 类 / 应用类 / 继承 Button.Link 类
/* -------------------------------------------------------------------------------------------- */
ToolBoxPanel.NodeButton = Class.create();
ToolBoxPanel.NodeButton.prototype = Object.extend( (new Button.Link()), {
    initialize : function( parElem, parWnd ){
	parElem = parElem || ToolBoxPanel.ChildBox;
	this._init_( parElem, parWnd, null, false );
	this.Id      = CtrlRd.AttrBy('id');
	this.Type    = CtrlRd.AttrBy('type');
	this.Caption = CtrlRd.AttrBy('caption');
	this.elemRef.className = 'toolNode';
	this.elemRef.innerHTML = '<b></b><span>' + this.Caption + '</span>';
	
	this.elemRef.onmousemove = this.OnMouseMove.bind(this);
	this.elemRef.ondragstart = this.OnDragStart.bind(this);

	this.CallBack = function(){};
    },
    SetShow : function( _set ){
	switch( _set ){ //'normal','over','down','disable'
	  case'normal':
	    this.elemRef.className = 'toolNode';    return;
	  case'over':
	    this.elemRef.className = 'toolNodeOv';  return;
	  default :
	    return;
	}
    },
    OnMouseMove :  function(){
	if( event.button == 1 ){
	    this.elemRef.dragDrop();
	}
    },
    OnDragStart : function(){
	var msg = 'NewPart;'+ this.Id +';'+ this.Type +';'+ this.Caption;
//	alert( msg );
	event.dataTransfer.setData( 'text', msg );
    }
});
/* -------------------------------------------------------------------------------------------- */



//	OperLayer = $('OperLayer');
//	btnEditPage = $('btnEditPage');
//	OperLayer.style.height = document.documentElement.clientHeight-31;
//	OperLayer.style.filter = 'alpha(opacity=30)';
/*
//	btnEditPage.disabled = true;
//	PageFrame.onreadystatechange = PageFrame_Load.bind( PageFrame );
function PageFrame_Load()
    {
//	if( this.readyState == 'loading' ){
//	    alert( this.readyState );	
//	}
	if( this.readyState == 'interactive' ){
	    alert( this.readyState );
	    
	EditPageWindow = PageFrame.contentWindow;   //alert(EditPageWindow)
	EditPageDocument = EditPageWindow.document;   alert(EditPageDocument.documentElement.outerHTML)
	
	    EditPageDocument.write('<script src="'+FactoryRootUrl+'Script/Base.js"><\/scr'+'ipt>' );
	    EditPageDocument.write('<script src="'+FactoryRootUrl+'Script/Common.js"><\/scr'+'ipt>' );
	    
	    EditPageDocument.write('<script id="__ie_onload" defer src="'+FactoryRootUrl+'Script/EditorCore.js"><\/scr'+'ipt>' );
	    
	    alert(EditPageDocument.documentElement.outerHTML);
	    
                var script = EditPageDocument.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
	                _PageFrame_Loaded();
                };	    
	}
	
	if( this.readyState == 'complete' ){
	    alert( this.readyState );
	    _PageFrame_Loaded();
//	    lbPageName.innerText = '['+ PagePath +']';
//	    DisableLink( this.contentWindow );
//	    btnShowPage.disabled = false;
//	    isReady = true;
//	    btnEditPage_Click();
//	    btnEditPage.disabled = false;
	}
    }
//	btnEditPage_Click();
//	    btnEditPage.disabled = false;
//    }
//function btnEditPage_Click()
//    {
/**/
