/*
 * Copyright 2006-2007 Maskat Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var maskatIDE={};
try{
//firefoxではcreateDocumentの処理は非同期なので、先にロードしておかないと
maskatIDE.MTRXSLT = rialto.utils.xml.createDocument('maskatToRialto.xsl');
maskatIDE.RTMXSLT = rialto.utils.xml.createDocument('rialtoToMaskat.xsl');
}catch(e){
    alert("xsltファイルロードに失敗しましたので、ロード・セーブは正常に機能しない可能性があります。");
}

rialto.utils.RialtoComposer.prototype.refreshOneNode =function(node,srcOnDropElement){
	//Type of component
	var componentName=node.nodeName
	//Get the attributes
	var objAttr=rialto.utils.xml.parseAttribute(node);
//maskat start:process some special tag
	if (componentName=='alert'){
	    if (objAttr.top==null)
	        objAttr.top = 200;
	    if (objAttr.left==null)
	        objAttr.left = 300;
	}
	if (componentName=='tabitem'){
	    if (objAttr.enable==null)
	        objAttr.enable = "true";
	    if (objAttr.top==null)
	        objAttr.top = 0;
	    if (objAttr.left==null)
	        objAttr.left = 0;
	}
	if (componentName=='treenode'){
	    objAttr.top = 0;
	    objAttr.left = 0;
	    if (objAttr.open == null || objAttr.open == "")
	        objAttr.open="true"; // デフォルトはopen状態
	}
	if (componentName=='frame'){
	    if (objAttr.open==null || objAttr.open==""){
	        objAttr.open="true";
	    }
	}
	if (componentName=='grid'){
	    if (objAttr.TabEntete==null || objAttr.TabEntete=="" || objAttr.tabTypeCol==null || objAttr.tabTypeCol==""){
	        var tabEntete = "[";
	        var tabTypeCol = "[";
	        if (node.hasChildNodes()){
	            for (var cIdx = 0;cIdx<node.childNodes.length;cIdx++){
	                var aChildNode = node.childNodes[cIdx];
	                if (aChildNode.nodeName=="gridHeader" && aChildNode.attributes!=null){
	                    var titleAttrib = aChildNode.attributes.getNamedItem("title");
	                    if (titleAttrib!=null){
	                        tabEntete+="'"+titleAttrib.nodeValue+"',";
	                    }
	                    var type = "string";//デフォルト
	                    var typeAttrib = aChildNode.attributes.getNamedItem("type");
	                    if (typeAttrib!=null){
	                        type = typeAttrib.nodeValue;
	                    }
	                    var width = "80";//デフォルト
	                    var widthAttrib = aChildNode.attributes.getNamedItem("width");
	                    if (widthAttrib!=null){
	                        width = widthAttrib.nodeValue;
	                    }
	                    tabTypeCol+="['" + type + "'," + width + "],";
	                }
	            }
	        }
	        if (tabEntete.length>1)
    	        tabEntete = tabEntete.slice(0,tabEntete.length-1);
    	    if (tabTypeCol.length>1)
    	        tabTypeCol = tabTypeCol.slice(0,tabTypeCol.length-1);
	        tabEntete+="]";
	        tabTypeCol+="]";
	        objAttr.TabEntete = tabEntete;
	        objAttr.tabTypeCol = tabTypeCol;
	    }
	}
	//create a new instance
	if(componentName!='rialto' && componentName!='layoutDef' && componentName!='layout'){
		var instance=this.newInstanceafterDrop(componentName,objAttr.top,objAttr.left,srcOnDropElement,objAttr);
		srcOnDropElement=instance.ghostDesign;
	}
//maskat end
	//child
	if(componentName!='grid' ){
		for(var i=0;i<node.childNodes.length;i++){
			var child=node.childNodes[i];
			if(child.nodeType ==1){
				this.refreshOneNode(child,srcOnDropElement);
			}
		}
	}
	return instance;
}

rialto.utils.RialtoComposer.prototype.loadFile =function(filePath){	
    //save file path
	this.filePath=filePath;
	if (rialtoConfig.userAgentIsIE){
    	this.file=rialto.utils.xml.createDocument(filePath);
	}
	if (rialtoConfig.userAgentIsGecko){
    	var content=rialto.utils.DataManager.loadFile(filePath);
    	this.file=rialto.utils.xml.createDocumentFromString(content);
	}

	//コンバーターをかける
	if (maskatIDE.MTRXSLT==null){
    	maskatIDE.MTRXSLT = rialto.utils.xml.createDocument('maskatToRialto.xsl');
	}
	this.clear();
	var xsltResult = rialto.utils.xml.XSLTransform(maskatIDE.MTRXSLT,this.file);

	if (rialtoConfig.userAgentIsIE){
    	this.file = rialto.utils.xml.createDocumentFromString(xsltResult);
	}
	if (rialtoConfig.userAgentIsGecko){
	    this.file = xsltResult;
	}

	var xmlDoc=rialto.utils.xml.getByTagName("rialto",this.file)[0];	
	//top level parent
	var srcOnDropElement=xmlDoc.getAttribute('topParent');	
	if(!srcOnDropElement){srcOnDropElement=document.body};
	this.refreshOneNode(xmlDoc,srcOnDropElement);
}

rialto.utils.RialtoComposer.prototype.generateXML2 =function(node){
	if(!node){var node=this.rialtoNode;}
	var firstShift = '';
	var rialtoStudioStr = this.nodeToXml(node,firstShift);
	var obXML = null;
	if(rialtoConfig.userAgentIsIE){
        obXML = new ActiveXObject('microsoft.XMLDOM');
        obXML.async = false;
        obXML.resolveExternals = false;
        obXML.validateOnParse = false;
        obXML.preserveWhiteSpace=true;
        obXML.loadXML(rialtoStudioStr);
	}
	if(rialtoConfig.userAgentIsGecko){
	    //mozillaの場合
	    obXML = rialto.utils.xml.createDocumentFromString(rialtoStudioStr);
	}
    if (maskatIDE.RTMXSLT==null){
	   maskatIDE.RTMXSLT = rialto.utils.xml.createDocument('rialtoToMaskat.xsl');
    }
    var xsltResult = rialto.utils.xml.XSLTransform(maskatIDE.RTMXSLT,obXML);
	if(rialtoConfig.userAgentIsIE){
        return xsltResult;//文字列
	}
	var xmlSerializer = new XMLSerializer();
	return xmlSerializer.serializeToString(xsltResult);//xsltResult is a dom object
}

rialto.utils.RialtoComposer.prototype.saveLoadFile=function (bLoad){
	var oThis=this;
	
	var curFile="no current file";
	if(this.filePath){
		var curFile=rialto.utils.DataManager.getFileName(this.filePath);
	}
	if (!bLoad){
	    //save
    	//IEの場合
    	if(rialtoConfig.userAgentIsIE){
    	    saveXMLForRialtoStudioOnIE("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r"+oThis.generateXML2(),this.filePath);
    	    return;
    	}
	}
	
	this.loadsaveFilepopup=new rialto.widget.PopUp('popup0',172,465,330,80,'',curFile,'transparent');

	if (this.iFilePath==null){
    	var divHtml3=document.createElement('DIV');
    	divHtml3.innerHTML="<input id='filePath' type='file' name='datafile' size='30'/>";
    	divHtml3.style.position='absolute';
    	divHtml3.style.top=10;
    	divHtml3.style.left=10;
    	this.loadsaveFilepopup.add(divHtml3);
	}else{
    	this.loadsaveFilepopup.add(this.iFilePath);
    }

	//get the input file path
	this.iFilePath=document.getElementById('filePath');	
	//button load and save
	var lButton=new rialto.widget.Button(40,5,'load','this is a button',this.loadsaveFilepopup,{enable:bLoad});
	var sButton=new rialto.widget.Button(40,115,'save','this is a button',this.loadsaveFilepopup,{enable:!bLoad});

	lButton.onclick=function(){		
		var path=oThis.iFilePath.value;
		if(path=="" && !oThis.filePath){
			var al=new rialto.widget.Alert("You must specify a file path");
		}
		else{
			if(path=="" && oThis.filePath){
				path=oThis.filePath;
			}
			oThis.loadsaveFilepopup.closeWindow();
			oThis.loadFile(path);
		}
	}
	
	sButton.onclick=function(){
		var path=oThis.iFilePath.value;
		if(path=="" && !oThis.filePath){
			var al=new rialto.widget.Alert("You must specify a file path");
		}
		else{
			if(path=="" && oThis.filePath){
				path=oThis.filePath;
			}
			rialto.utils.DataManager.saveInFile("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r"+oThis.generateXML2(),path);
			oThis.loadsaveFilepopup.closeWindow();
		}				
	}
	this.iFilePath.focus();

}

function saveXMLForRialtoStudioOnIE(strXML,path){
 if (path==null){
     path="layout.xml";
 }
 var ind=path.lastIndexOf(".");
 path = path.substring(0,ind);
 var w = window.frames.hiddenIFrameForSaveXml;
 if( !w ) {
  w = document.createElement( 'iframe' );
  w.id = 'hiddenIFrameForSaveXml';
  w.style.display = 'none';
  document.body.insertBefore( w );
  if( !w ) {
   w = window.open( '', '_temp', 'width=100,height=100' );
   if( !w ) {
    window.alert( 'Sorry, could not create file.' ); return false;
   }
  }
 }

  var d = w.document;

  d.open( 'text/plain', 'replace' );
  d.charset = "UTF-8";
  d.write( strXML );
  d.close();
  if( ! d.execCommand( "SaveAs", false, path+".txt" ) ){
      
  }
}