/* ************************************************************************************************

	Copyright (c) 2005-2006, IGR
	All Rights Reserved.
	Licensed under the Apache License version 2.0 or above.
	For more information on licensing, see:
        http://www.apache.org/licenses/


************************************************************************************************
 Objet type RIALTO DD COMPOSER
 VERSION:0.85
 DATE:25/07/2006
************************************************************************************************
 Init parameter in objPar (object of parameter): 
************************************************************************************************/

rialto.utils.RialtoComposer=function(objPar){
	
	var oThis=this;
	//reccord the composer in rialto Session
	this.id='RialtoComposer';
	this.name='RialtoComposer';
	rialto.session.reccord(this,this.id);
	//Contextuel Menu		
    this.menuContex=new objMenuCont("men1",120);
    this.menuContex.createMenu(document.body);        
    this.menuContex.add("Remove",true,false,false,rialtoConfig.pathRialtoE + "images/croix.gif");
    this.menuContex.addSeparation();
    this.menuContex.add("Select",true,false,false,rialtoConfig.pathRialtoE + "images/Entoure.gif");    
    
    this.menuContex.itemClickApplicatif=function(ind){
  		//ind:index of selected item    
        //Remove element
        if (ind==0){
            if (this.srcEvent!=null){
                oThis.removeInstance(this.srcEvent.widgetLink)
            }
            return true;
        }
        //select component
        if (ind==1){  
	        oThis.multiSelect(this.srcEvent);          	            
            return true;
        } 
	}
	
	//init differents id
	this.maskId = 0;
	this.widgetId = 0;
	this.nameCpt = 0;
	//array of create component
	this.arrComponent=new Array;
	//array of instance variable reference
	this.arrComponentName={};	
	//array of component type (splitter,frame...)
	this.arrComponentType=new Array;
	//array for multiselect component
	this.arrMultiSelect=new Array;
	//rialto writer
	this.RW=new rialto.utils.RialtoWriter();
	//MODIFICATION ON PROTOTYPE COMPONENT TO MAKE THIS WORK
	rialto.widget.Tree.prototype.isContainer=true;
	rialto.widget.TreeNode.prototype.isContainer=true;
	rialto.widget.Alert.prototype.inContainer=document.body;
	
	
	/*AUTHORIZE D&D OBJECT 
		each propertie indicate for a component:
			-the dropAuth propertie:name of the component which can be drop in
			-the inAuth propertie:name of the component in which it can be drop in
	*/
	this.authDD={
		splitter:{dropAuth:'divSplitter'},
		treeview:{dropAuth:'treenode'},
		treenode:{dropAuth:'treenode',inAuth:'treenode,treeview'},
		tabfolder:{dropAuth:'tabitem'},
		tabitem:{inAuth:'tabfolder'},
		alert:{inAuth:'document.body'},
		popup:{inAuth:'document.body'}
	}
	
	//setup initialisation
	this.setupDD = 	{	
		bMUpAction:false,
		bRectLim 	: false,
		ghost		: {bIcone : true, aspect: 'icon'}						
	};
	
	//target
	this.setupTarget = {domain:'designZone.widgets'};
		
	//----- target behavior affect to body , to drop patterns on
	rialto.widgetBehavior.affect(document.body,'Target',this.setupTarget);
	//add attribute to make target behavior work
	this.arrComponentName['document.body']=document.body;
	document.body.componentName='document.body';
	document.body.name='document.body';
	document.body.widgetLink=document.body;
	document.body.oHtml=document.body;
	document.body.className     = 'maskWidgetInDesign';
	
	//----------------------------------------------------------
	
	document.body.receiveAfterDrop = function(oSpecs) {  				
		oThis.dropInstance(oSpecs,this);
	}	
	
	//GET THE XML DESCRIPTION
	this.remote=new rialto.io.AjaxRequest({
							//url:'rialtoModel.xml',
							url:'rialto.xsd',
							method: 'get', 
							callBackObjectOnSuccess:this,
							withWaitWindow:false,
							onSuccess: this.parseXmlForListValue
						}) 
	this.remote.load('');
}


//function use to parse the xml description to get the name component and there attribute
rialto.utils.RialtoComposer.prototype.parseXmlForListValue=function(request){ 
	//this.xmlDoc=request.responseXML;  
	//USE createDocumentFromString instead of request.responseXML
	//because request.responseXML doesn't work with ie and local file
	try{
	this.xmlDoc=rialto.utils.xml.createDocumentFromString(request.responseText);
	
	//array of tag

    this.objectsList={}
    var pref="";
    if(rialtoConfig.userAgentIsIE){
   		pref="xsd:";
   	}
    
    var complexTypeTag=rialto.utils.xml.getByTagName(pref+"complexType",this.xmlDoc);
	for(var i=0;i<complexTypeTag.length;i++){
		//get the complexTypeNode
		var element=complexTypeTag[i];
		//get the type name
		var name=element.getAttribute('name');		
		//remove "Type" at the end to have the component name
		var componentName=name.substr(0,name.length-4);
		this.objectsList[componentName]={};
		//get the attribute
	 	var attrTag=rialto.utils.xml.getByTagName(pref+"attribute",element);
	 	for(var j=0;j<attrTag.length;j++){
 	    	var attr=attrTag[j];
 	    	//gat attribute name
 	    	var nameAttr=attr.getAttribute('name');
 	    	//get base type
 	    	var type=attr.getAttribute('type');
 	    	//if boolean
 	    	this.objectsList[componentName][nameAttr]=new Array;
 	    	if(nameAttr=='position'){
	 	    	this.objectsList[componentName][nameAttr]=['absolute','relative'];
 	    	}
 	    	if(type=='xsd:boolean'){
	 	    	this.objectsList[componentName][nameAttr]=['true','false'];
 	    	}
 	    	else{
 	    		//if enumeration
 	    		var enumTag=rialto.utils.xml.getByTagName(pref+"enumeration",attr);
 	    		var arr=new Array;
 	    		for(var z=0;z<enumTag.length;z++){
 	    			//get the enumeration value
 	    			this.objectsList[componentName][nameAttr].push(enumTag[z].getAttribute('value')); 	    			
 	    		}
 	    	}
		}		
	}

	//GET THE XML DESCRIPTION
	this.remote.setUp({url:'rialtoModel.xml',onSuccess: this.parseXmlForComponent});
	this.remote.load('');
	}catch(e){alert(e);}
}

//function use to parse the xml description to get the name component and there attribute
rialto.utils.RialtoComposer.prototype.parseXmlForComponent=function(request){ 
	//this.xmlDoc=request.responseXML;  
	//USE createDocumentFromString instead of request.responseXML
	//because request.responseXML doesn't work with ie and local file
	this.xmlDoc=rialto.utils.xml.createDocumentFromString(request.responseText);
	
	//array of tag
    var rialtoTag=rialto.utils.xml.getByTagName("rialto",this.xmlDoc)[0];
    this.objects={}
    //constitue collection of object
    try{
	    for(var i=0;i<rialtoTag.childNodes.length;i++){
	        var child=rialtoTag.childNodes[i];
	        if(child.nodeType==1){
				var childName=child.nodeName;
	        	this.objects[childName]=rialto.utils.xml.parseAttribute(child);
	        	//save the name
	        	this.arrComponentType.push(childName);
	        }
	    }              
    }catch(e){alert(e.message);}    
    //sort the array by name
    rialto.array.sort(this.arrComponentType);
    //IHM
    this.createIHM();    
}


//function add or remove component when multiselect
rialto.utils.RialtoComposer.prototype.multiSelect=function(maskSelect){       
	//if not mask select release all the multi select
	if(!maskSelect){
		for(var i=0;i<this.arrMultiSelect.length;i++){
			this.arrMultiSelect[i].className='maskWidgetInDesign';
			rialto.effect.opacity(this.arrMultiSelect[i],0.5);
		}
		this.arrMultiSelect=new Array;
		//disable align button
		this.alignL.setEnable(false);
		this.alignR.setEnable(false);
		this.alignT.setEnable(false);
	}
	else{
		//if already selected unselect
		if(rialto.array.indexOf(this.arrMultiSelect,maskSelect)!=-1){
			maskSelect.className='maskWidgetInDesign';
			rialto.effect.opacity(maskSelect,0.5);
			maskSelect.style.background='';
			rialto.array.remove(this.arrMultiSelect,maskSelect);
			if(this.arrMultiSelect.length==0){
				//disable align button
				this.alignL.setEnable(false);
				this.alignR.setEnable(false);
				this.alignT.setEnable(false);			
			}
		}
		else{
			maskSelect.className='maskWidgetInDesignSel';
			rialto.effect.opacity(maskSelect,0.9);
			this.arrMultiSelect.push(maskSelect);
			//enable align button if more then 2 elements selected
			if(this.arrMultiSelect.length>1){
				this.alignL.setEnable(true);
				this.alignR.setEnable(true);
				this.alignT.setEnable(true);			
			}			
		}
	}
}


//function use to align (left,right or top) all selected component
rialto.utils.RialtoComposer.prototype.align=function(cAlign){       
	var value;
	switch (cAlign){
		case 'left':
			value=this.findBestVal('left');
			break;
		case 'right':
			value=this.findBestVal('left',true);
			break;
		case 'top':	
			value=this.findBestVal('top');
			break;
	}
	for(var i=0;i<this.arrMultiSelect.length;i++){
		var mask=this.arrMultiSelect[i];
		var instance=mask.widgetLink;
		//set top or left
		if(cAlign=='top'){			
			var top=value;
			var left=instance.left;
		}
		else{
			var top=instance.top;
			var left=value;
		}		
		//apply new position to instance and ghost
		this.setInstancePosition(instance,top,left,mask.parentNode,true);
		this.setGhostPosition(instance,mask.parentNode);
	}
	//remove selected comp
	this.multiSelect();

}

//check for all the selected component the best propertie
//the min of the style prop (ot the max if bMax=true)
rialto.utils.RialtoComposer.prototype.findBestVal=function(prop,bMax){       
	var saveValue=parseInt(this.arrMultiSelect[0].widgetLink[prop]);
	for(var i=1;i<this.arrMultiSelect.length;i++){
		var mask=this.arrMultiSelect[i];		
		var curValue=parseInt(mask.widgetLink[prop]);		
		if(!bMax){
			saveValue=(curValue<saveValue)?curValue:saveValue;
		}
		else{
			saveValue=(curValue>saveValue)?curValue:saveValue;
		}
	}
	return saveValue
}

/*
this function is call to check drop authorize of componentName in parentComponentName
according to AUTHORIZE D&D OBJECT
return true if drop is authorize false else
*/
rialto.utils.RialtoComposer.prototype.checkAuthorize= function (componentName,parentComponentName) {		
//******************CHECK IF THE DROP IS AUTHORIZE
	//check if the component is authorize in srcOnDropElement specification	
	if(this.authDD[parentComponentName]){		
		var str=this.authDD[parentComponentName].dropAuth;
		if(str && str.indexOf(componentName)==-1){
			return false;
		}	
	}
	
	//check if the srcOnDropElement is authorize in component specification
	if(this.authDD[componentName]){		
		var str=this.authDD[componentName].inAuth;
		if(str && str.indexOf(parentComponentName)==-1){
			return false;
		}	
	}	
	return true; 
}
	
/*
this function is call after a drop.There is 7 context of specificity 
-creation of the instance:createI
-creation of the ghost:createG
-drop of existing instance parameter before moving instance:dropI
-drop of existing instance parameter before moving ghost:dropG
-instanceRefresh
-createNode parameter before create the node 
-checkNode just to check drop authorize
*/
rialto.utils.RialtoComposer.prototype.specificProperties= function (context,componentName,srcOnDropElement,instance,objAttr) {		
	/*Get specific properties
		According to the component name we will set some properties
			cancel:abort
			parentI:parent of the component
			parentG:parent of the ghost
			boolSetPos:if true calculate the position
			top:top if fixed
			left:left if fixed
			toReturn:object to return if cancel the instance creation
	*/
	var oThis=this;
	var specProp={
				parentI:null,		//parent to use for the instance
				parentG:null,		//parent to use for the ghost
				noParentI:false,	//no parent for the instance
				noParentG:false,	//no parent for the ghost
				top:0,				//specify top
				left:0,				//specify left
				cancel:false,		//cancel 
				boolSetPos:true,	//if true the top left must be calculate
				boolResizable:true, //if true the mask is resizable
				boolDraggable:true, //if true the mask is draggable
				boolNodeDraggable:true, //if true the node of the instance is draggable				
				rsLimitHeight:10,		//min height when resize
				rsLimitWidth:10,		//min width when resize
				boolTarget:true,		//if true the mask is a target
				toReturn:true,			//object to return if cancel
				onclick:function(){		//onclick method of the node
					oThis.multiSelect();
					if(!instance.containerHidden){oThis.multiSelect(instance.ghostDesign);}
					oThis.componentProperties(instance.objAttr,instance.componentName)				
				}
				};
	//******************CHECK IF THE DROP IS AUTHORIZE
	if(context=="createI" || context=="dropI" || context=="checkNode"){
		if(!this.checkAuthorize(componentName,srcOnDropElement.widgetLink.componentName)){
			specProp.cancel=true;
			return specProp;		
		}
	}
	
	//******************SPECIFIC TREATEMENT **********************
	switch (componentName) {
			case 'alert' :
				//instance specificity
				if(context=='createG'){
					//change zindex (if not popup is modal)
					instance.fen.eltContainer.style.zIndex=1;
					instance.fen.cadreExterne.style.zIndex=1;
					instance.ghostDesign.style.zIndex=2;
					//parent is the body
					specProp.parentG=document.body;		
					specProp.boolResizable=false;
				}
				specProp.noParentI=true;
				break;		
			case 'popup' :
				//instance specificity
				if(context=='createG'){	
					//change zindex (if not popup is modal)
					instance.eltContainer.style.zIndex=1;
					instance.cadreExterne.style.zIndex=1;
					//add name attribute
					instance.name=instance.objAttr.name;
					//Set the oHtml propertie of the mask
					instance.inContainer.oHtml=instance.inContainer;
					//ghost zIndex to be on the popup
					instance.ghostDesign.style.zIndex=2;
					specProp.rsLimitHeight=50;
					specProp.rsLimitWidth=100;					
				}
				//parent is the body
				specProp.parentG=document.body;
				specProp.noParentI=true;			
				break;			
			case 'form' :
				//ghost specificity
				if(context=='createG'){					
					//resize the instance
					instance.oHtml.style.width=100;
					instance.oHtml.style.height=100;
				}
				break;
			case 'frame' :
				//instance specificity
				if(context=='createG'){									
					specProp.rsLimitHeight=40;
					specProp.rsLimitWidth=40;					
				}				
				if(instance && (instance.objAttr.open=='false' || instance.objAttr.open==false)){
					instance.showAscontainerHidden=true;
				}
				break;	
			case 'divSplitter' :		
				if(context=='createI' || context=='refreshI'){
					//get the splitter instance
					var split=srcOnDropElement.widgetLink;
					//look if we already treat a div split
					if(split.oneDivTreat){
						specProp.toReturn=split.div2;
					}
					else{
						split.oneDivTreat=true;
						specProp.toReturn=split.div1;
					}
					specProp.cancel=true;
				}
				//Div splitter node can't be draggable
				if(context=='createN'){
					specProp.boolNodeDraggable=true;
				}				
				break;	
			case 'grid' :
				//instance specificity
				if(context=='createI'){
					//display popup to get information on the header
					this.createPopupGrid(srcOnDropElement,objAttr);											
					specProp.cancel=true;					
				}
				if(context=='createG'){
					//add header tag to the node
					for(var i=0;i<instance.NbreCol;i++){
						var objHeader={title:instance.tabEntete[i],type:instance.tabTypeCol[i][0],width:instance.tabTypeCol[i][1]}
						var nodeHeader=new rialto.widget.TreeNode({name:'nodeH',text:'gridHeader',icon:'images/imTreeview/puce.gif',draggable:false});
						instance.node.addNode(nodeHeader);
						//display popup with  information on the header
						nodeHeader.onclick=function(){
							oThis.restoreIHM();
							oThis.createPopupGrid('',instance.objAttr,instance);
						}
						//create an instance like object
						nodeHeader.instance={};
						nodeHeader.instance.objAttr=objHeader;
					}
					specProp.boolResizable=false;
				}
				
				break;	
			case 'image' :
				//ghost specificity
				if(context=='createG'){
					//wait the image is laoding to give the good size to the mask
				    instance._imgImg.onload=function(){
				    	oThis.setGhostSize(instance);
				    }
					specProp.boolResizable=false;
				}
				break;
			case 'radio' :			
				//min width and height = instance width and height
				if(context=='createG'){							
					specProp.rsLimitWidth=instance.oHtml.offsetWidth;
				}
				break;
			case 'checkbox' :			
				//min width and height = instance width and height
				if(context=='createG'){					
					specProp.rsLimitWidth=instance.oHtml.offsetWidth;
				}
				break;				
			case 'text' :			
				if(context=='createG'){					
					specProp.rsLimitWidth=25;
				}
				break;																		
			case 'tabfolder' :			
				if(context=='createG'){					
					specProp.rsLimitHeight=40;
					specProp.rsLimitWidth=20;
				}
				break;
			case 'tabitem' :			
				//instance specificity					
				if(context=='createI'){
					specProp.boolSetPos=false;
					specProp.parentI=srcOnDropElement.widgetLink.objAttr.name;				
				}
				//ghost specificity
				//some applicative code
				if(context=='createG'){
					instance.name=instance.objAttr.name;
					instance.onDisableTab=function(){
						this.ghostDesign.style.display='none'
					};
					instance.onEnableTab=function(){
						this.ghostDesign.style.display='block'
					};
					instance.onresize=function(){						
						//set size for the ghost
					    var bord=_rum.$$getBorderLeftWidth(this.ghostDesign)*2;                
        				this.ghostDesign.style.width   = ria.utils.measures.$getWidth(this.oHtml,true)- bord; 
				        this.ghostDesign.style.height  = ria.utils.measures.$getHeight(this.oHtml,true)- bord; 
				        ria.utils.measures.$setSizeConformW3C(this.ghostDesign);
					};
					instance.onremove=function(){
			            //activate the last one
			            if (this.parentOnglet.arrTabItem.length>0){                                                
			                this.parentOnglet.activeTab(this.parentOnglet.arrTabItem.length-1);
			            }
					}
				}
				if(context=='createN'){
					specProp.onclick=function(){
						instance.activeOnglet();
						oThis.multiSelect();
						oThis.multiSelect(instance.ghostDesign);																
						oThis.componentProperties(instance.objAttr,instance.componentName)				
					}
				}
				specProp.boolDraggable=false;
				specProp.boolResizable=false;
				break;	
			case 'simpleWindow' :												
				//instance specificity							
					if(context=='createI'){
						//check if a simple window already exist (for the moment only one on the area)
						if(!this.bsW){		
							this.bsW=true;
							specProp.boolSetPos=false;
							specProp.boolDraggable=false;
						}
						else{
							var al=new rialto.widget.Alert("Only one simple window");
							specProp.cancel=true;
						}
					}
					//no positionalways 0 for a simple window
					if(context=='dropI'){
						specProp.boolSetPos=false;
					}
					if(context=='createG'){
						specProp.boolSetPos=true;
					}				
				break;												
			case 'splitter' :
				//instance specificity
				if(context=='createI' || context=='dropI'){					
					if(objAttr.autoResizableH=='true' && objAttr.autoResizableW=='true'){
						specProp.boolSetPos=false;
					}
				}
				if(context=='createG'){
					/* At this moment we kneed to set everything on
					div 1 and div2 of the splitter
					*/
					//add propertie on the div of the splitter
					instance.div1.name=instance.name+".div1";
					//reccord this instance
					this.arrComponentName[instance.div1.name]=instance.div1;
					instance.div1.componentName="divSplitter";
					instance.div1.oHtml=instance.div1;
					//Ghost for the div1 and div2
					var maskDiv1=document.createElement("DIV");
					maskDiv1.style.position='absolute';
					maskDiv1.className     = 'maskWidgetInDesign';	
					maskDiv1.isGhostOfWidget= true;  
					instance.div1.ghostDesign=maskDiv1;
					maskDiv1.widgetLink=instance.div1;
					//top left
					maskDiv1.style.top=instance.div1.style.top;
					maskDiv1.style.left=instance.div1.style.left;
					//size
					oThis.setGhostSize(instance.div1);
					instance.div1.inContainer=instance;
					//affect target behavior
					rialto.widgetBehavior.affect(maskDiv1,'Target',{domain:'designZone.widgets'});
					//implement receiveAfterDrop method
					maskDiv1.receiveAfterDrop = function(oSpecs) { 
						oThis.dropInstance(oSpecs,this);
					}
					//implement DDHover method			
					maskDiv1.DDHover = function(oSpecs) { 
						this.parentNode.style.border="2px solid blue";
						this.className='maskWidgetInDesignSel';
					}						
					//implement DDOuter method			
					maskDiv1.DDOuter = function(oSpecs) { 
						this.className='maskWidgetInDesign';
						this.parentNode.style.border="2px solid red";
					}
					instance.div2.name=instance.name+".div2";
					//reccord this instance
					this.arrComponentName[instance.div2.name]=instance.div2;
					instance.div2.componentName="divSplitter";					
					instance.div2.oHtml=instance.div2;										
					var maskDiv2=document.createElement("DIV");
					maskDiv2.style.position='absolute';
					maskDiv2.className     = 'maskWidgetInDesign';	
					maskDiv2.isGhostOfWidget= true;  
					instance.div2.ghostDesign=maskDiv2;
					maskDiv2.widgetLink=instance.div2;
					//top left
					maskDiv2.style.top=instance.div2.style.top;
					maskDiv2.style.left=instance.div2.style.left;
					//size
					oThis.setGhostSize(instance.div2);
					instance.div2.inContainer=instance;
					//affect target behavior
					rialto.widgetBehavior.affect(maskDiv2,'Target',{domain:'designZone.widgets'});
					//implement receiveAfterDrop method
					maskDiv2.receiveAfterDrop = function(oSpecs) { 
						oThis.dropInstance(oSpecs,this);
					}
					//implement DDHover method			
					maskDiv2.DDHover = function(oSpecs) { 
						this.parentNode.style.border="2px solid blue";
						this.className='maskWidgetInDesignSel';
					}						
					//implement DDOuter method			
					maskDiv2.DDOuter = function(oSpecs) { 
						this.className='maskWidgetInDesign';
						this.parentNode.style.border="2px solid red";
					}
					//TO DO RESIZE OF THE GHOST
					instance.onresizeDiv1=function(){							
						oThis.setGhostSize(this);
						var maskDiv1=this.div1.ghostDesign;
						maskDiv1.style.top=this.div1.style.top;
						maskDiv1.style.left=this.div1.style.left;
						oThis.setGhostSize(this.div1);
						var maskDiv2=this.div2.ghostDesign;
						maskDiv2.style.top=this.div2.style.top;
						maskDiv2.style.left=this.div2.style.left;
						oThis.setGhostSize(this.div2);
					}
					//Add the mask to the splitter mask
					instance.ghostDesign.appendChild(maskDiv1);
					instance.ghostDesign.appendChild(maskDiv2);			
					maskDiv1.style.border="0px solid red";		
					maskDiv2.style.border="0px solid red";		
					//instance.ghostDesign.style.border="0px solid red";
					//create the node in  the grid 
					this.createNode(instance.div1);	
					this.createNode(instance.div2);			
				}				
				if(context=='dropG'){
					instance.updateSize();
				}				
				specProp.boolTarget=false;
				break;				
			case 'treenode' :
				specProp.boolSetPos=false;
				//ghost specificity				
				if(context=='createG' || context=='dropG'){		
					var maskSelect=instance.ghostDesign;										
					//get the tree component
					var treeComp;
					//Look if drop in the tree or in a node
					if(srcOnDropElement.widgetLink.componentName=='treenode'){
						//DROP IN A NODE
						treeComp=srcOnDropElement.widgetLink.refTree;
					}
					else{
						//DROP IN THE TREE
						treeComp=srcOnDropElement.widgetLink;
						//just change the node link of the tree when there is no rootNode so this instance is the rootnode
						if(!treeComp.rootNode){
							treeComp.node=instance.node;
						}			
					}		
					//if ghost creation set position attribute
					if(context=='createG'){
						//treeComp.ghostDesign.appendChild(maskSelect);
						maskSelect.style.position='relative';
					}	
					//Reccursive insert
					this.insertMask(instance,treeComp.ghostDesign);
					//set the specific properties
					specProp.boolResizable=false;
					specProp.boolSetPos=false;
					specProp.noParentG=true;
				}
				if(instance && (instance.objAttr.open=='false' || instance.objAttr.open==false)){
					instance.showAscontainerHidden=true;
				}				
				break;				
			default: 
		}						
		
		return specProp;
}
//FOR THE TREENODE
//Function to insert all  ghost of childs of instance before maskToInsertBefore
rialto.utils.RialtoComposer.prototype.insertMask= function (instance,ghostParent,bAppend,nextGhost) {		
	//for the first instance element (for the child we will have a ghost to insert before or the bAppend set to true	
	if(!bAppend && ! nextGhost){
		//look for a next sibling of the node
		//if not look for the fatherNode
		var nextNode=null;
		var nextGhost=null;
		var curNode=instance;
		while(curNode!=instance.refTree.rootNode && nextNode==null){
			nextNode=curNode.next();
			curNode=curNode.fatherNode;
		}
		if(nextNode){nextGhost=nextNode.ghostDesign;}
		var bAppend=(nextGhost==null);
	}
	//if we have a nextGhost make an insert before
	var maskToInsert=instance.ghostDesign;
	if(nextGhost){
		ghostParent.insertBefore(maskToInsert,nextGhost);
	}
	else{
		//make an append
		ghostParent.appendChild(maskToInsert);		
	}
	//same for all the child
	for(var i=0;i<instance.arrChildNode.length;i++){		
        var node=instance.arrChildNode[i];
        this.insertMask(node,ghostParent,bAppend,nextGhost);
    }
}


/*This function will  be call after a pattern drop in srcOnDropElement
	- oSpecs is the object return by the receiveAfterDrop method of the srcOnDropElement
*/
rialto.utils.RialtoComposer.prototype.newInstanceafterDrop = function (componentName,top,left,srcOnDropElement,wObjAttr) {		
		var oThis=this;
		var instance;
		
		// ********************  JAVASCRIPT GENERATION USING RIALTO.WRITER	        			                  						 

		/*Get specific properties
		According to the component name we will could set some specific properties
			cancel:abort the drop
			parentI:parent of the component
			boolSetPos:if true calculate the position
			top:top if fixed
			left:left if fixed
		*/
		var context='createI';
		if(wObjAttr){
			context='refreshI';
			var objAttr=wObjAttr;
		}
		else{
			var objAttr={};
			//set the attribute with the default values of that kind of component
			for (prop in this.objects[componentName]){
				objAttr[prop]=this.objects[componentName][prop];
			}			
		}
		//if no name we generate one
		if(!objAttr.name){
			objAttr.name=componentName+(this.nameCpt++);
		}
		
		//if the name already exist we add a number
		if(this.arrComponentName[objAttr.name] && context!='refreshI'){
			objAttr.name=objAttr.name+(this.nameCpt++);
		}
		if(!srcOnDropElement.widgetLink.containerHidden && !srcOnDropElement.widgetLink.showAscontainerHidden){	
			//SPECIFIC PROPERTIES IN CREATE INSTANCE CONTEXT
			var specProp=this.specificProperties(context,componentName,srcOnDropElement,'',objAttr);
			if(specProp.cancel){return specProp.toReturn}
			//if no attribute object (refresh context) take the specific top and left
			if(!wObjAttr){			
				//set knows properties
				objAttr.top=specProp.top;
				objAttr.left=specProp.top;
			}						
			//parent	
			var parent;	
			if(!specProp.parentI){
				//PlaceIn
				parent=srcOnDropElement.widgetLink.name;
			}
			else{
				parent=specProp.parentI;
			}		
			//generate the xml
			var strXML="<rialto topParent=\"this.arrComponentName['"+parent+"']\"><"+componentName;	
			
			if(componentName=='divHtml'){
				strXML+=" name='"+objAttr.name+"'>";
				strXML+=this.innerText;
				strXML+="</"+componentName+">";
				strXML+="</rialto>";		
			}
			else{
				strXML+=rialto.utils.xml.parseObjectAsAttribute(objAttr);
				strXML+="/></rialto>";
			}	
			//transform in real xml node and use the rialto  writer to get javascript call
			var docXml=rialto.utils.xml.createDocumentFromString(strXML);		
			this.RW.loadComponents(docXml);
			//get the javscript call (removing the first character corresponding to 'var '
			//because we want global variable
			var js=this.RW.getJavascriptCall();//.substr(3);
			//create the component (combo1=new....)
			traceExec("JS:"+js,1);
			eval(js);
			//use a instance variable to point on this component (var instance=combo1;)
			var instance=eval(objAttr.name);
			//reccord this instance
			this.arrComponent.push(instance);
			this.arrComponentName[objAttr.name]=instance;
			//reccord some information attach to the instance
			//the component Name
			instance.componentName=componentName;		
			//the attribute
			instance.objAttr=objAttr;
			if(instance.getHtmlExt){
				instance.oHtml = instance.getHtmlExt();		
			}
			else{
				instance.oHtml = instance;		
			}		
	        instance.oHtml.id = componentName+(this.widgetId++);
	        if(specProp.boolSetPos && !wObjAttr){
				//set position
				this.setInstancePosition(instance,top,left,srcOnDropElement);
			}
			else{
				//set specific position
			 	this.setInstancePosition(instance,objAttr.top,objAttr.left,srcOnDropElement,true);
			}	
			//create the node in  the grid 
			this.createNode(instance);
			//create the ghost of the component (with RS and DD behavior)
			this.createGhostElement(instance,srcOnDropElement);	
		}
		else{
			var instance={componentName:componentName,
						  objAttr:objAttr,
						  containerHidden:true,
						  inContainer:srcOnDropElement.widgetLink,
						  ghostDesign:{}
						  };
			//simulate the reverse link
			instance.ghostDesign.widgetLink=instance;
			//create the node in  the grid 
			this.createNode(instance);		
		}
		//refresh output
		this.combSourceSelect.onclick(this.combSourceSelect.getSelValue(),this.combSourceSelect.getSelText());		
		return instance;
}	


/*This function will  be call after a drop in srcOnDropElement
	-it could be a pattern drop or an instance drop
	- oSpecs is the object return by the receiveAfterDrop method of the srcOnDropElement
*/
rialto.utils.RialtoComposer.prototype.createGhostElement= function (instance,srcOnDropElement) {		
				
		// ********************  GHOST ELEMENT
		var oThis=this;
		
		var maskSelect 			 = document.createElement('DIV');
		maskSelect.style.zIndex=2;
        maskSelect.id  			 = 'maskWidgetInDesign'+(this.maskId++);
        maskSelect.className     = 'maskWidgetInDesign';        
        maskSelect.isGhostOfWidget 		= true;       
 		rialto.effect.opacity(maskSelect,0.5);
		// links ghost - instance of widget
        maskSelect.widgetLink 	 	= instance; 	
		instance.ghostDesign 	= maskSelect;		
		
		/*Get specific properties
		According to the component name we will set some properties
			cancel:abort
			noParentG:don't add to parent
			parentG:parent of the ghost
			boolDraggable:if true the ghost had a D&D behavior
			boolResizable:if true the ghost had a RS behavior
			boolSetPos:if true calculate the position
			boolTarget:if true the ghost can be a target
			top:top if fixed
		    left:left if fixed
		*/

		//SPECIFIC PROPERTIES IN CREATE GHOST CONTEXT
		var specProp=this.specificProperties('createG',instance.componentName,srcOnDropElement,instance);
		if(specProp.cancel){return}				
		//LOOK FOR THE PARENT OF THE GHOST
		if(!specProp.noParentG){
			var parent 	 = srcOnDropElement; 	        			
		    //check a specific parent		
			if(specProp.parentG){
				 parent = specProp.parentG;
			}	
			//add to the parent
			parent.appendChild(maskSelect);	
		}
		//check specific position
		if(specProp.boolSetPos){
			//set position
			this.setGhostPosition(instance,srcOnDropElement);
		}
		else{
			//set specific position
		 	maskSelect.style.top   = specProp.top;
        	maskSelect.style.left  = specProp.left;
		}		
	    this.setGhostSize(instance);
		
		//RESIZE BEHAVIOR		
		if(specProp.boolResizable){
			var orient ='h';
			//no vertical resize if it is a simple component ????	NOT WORKING
			if(instance.isContainer){orient ='2D'};
			rialto.widgetBehavior.affect(maskSelect,'ReSize'
										,{sensitiveEdgeWidth  :3,
										  orientation : orient,
										  limitReDim:{heightMin:specProp.rsLimitHeight,widthMin:specProp.rsLimitWidth}
										  ,bRectLim : true});
										  
										  
			
			//Synchro on resize
			maskSelect.synchroRS = function (delta) {
			//------------------			
				var w = maskSelect.widgetLink;
				w.modHeight(delta.height);
				w.modWidth(delta.width);			
				w.moveBy(delta.top,delta.left);														
				//reccord on the atribute object
				w.objAttr.top=w.top;
				w.objAttr.left=w.left;
				w.objAttr.width=w.width;
				w.objAttr.height=w.height;		
				//refresh output
				oThis.combSourceSelect.onclick(oThis.combSourceSelect.getSelValue(),oThis.combSourceSelect.getSelText());	
			}
		}		
		
		
		//DRAG AND DROP BEHAVIOR
		if(specProp.boolDraggable){
	    	//ria.utils.event.genericAddEvent(maskSelect,'mousedown',this.mask_mousedown,this);
			//To make multiselect
			maskSelect.onmousedown=function(e){            
				if(!e) e=window.event;
				if(ria.utils.event.isLeftClick(e)){
					var ctrlPress=e.ctrlKey;							
					if(ctrlPress){
						oThis.multiSelect(this);
						stopEvent(e);
					}
					else{
						oThis.multiSelect();
					}
				}				
			};
		
			var setupDDInstance = 	{	
					bRectLim 	: false
					,ghost		: {aspect:	'rect'}
					,sensitiveEdgeWidth  :3
			};				
			rialto.widgetBehavior.affect(maskSelect,'DragAndDrop',setupDDInstance);
			var setupMissile = {domainTargets:'designZone.widgets.divHtml'};
			rialto.widgetBehavior.affect(maskSelect,'Missile',setupMissile);
		}
    
    	//contextual menu treatment
	    maskSelect.oncontextmenu =  function(e){
	        oThis.menuContex.srcEvent=this;        
	        oThis.menuContex.afficheMenu(e);        
	    }
					
		//TARGET BEHAVIOR
		//only if instance is kind of container 
		if (maskSelect.widgetLink.isContainer && specProp.boolTarget) {			
			//affect target behavior
			rialto.widgetBehavior.affect(maskSelect,'Target',{domain:'designZone.widgets'});
			//implement receiveAfterDrop method			
			maskSelect.receiveAfterDrop = function(oSpecs) { 
				oThis.dropInstance(oSpecs,this);
				this.style.border="2px solid red";
			}			
			//implement DDHover method			
			maskSelect.DDHover = function(oSpecs) {
				rialto.effect.opacity(maskSelect,0.8); 
				this.style.border="2px solid blue";
			}						
			//implement DDOuter method			
			maskSelect.DDOuter = function(oSpecs) { 
				rialto.effect.opacity(maskSelect,0.5);
				this.style.border="2px solid red";
			}	
		}
    }

//This function is use to create a node in the treeview representing the components
rialto.utils.RialtoComposer.prototype.createNode =function(instance){
	//try{
		var oThis=this;
		//SPECIFIC PROPERTIES IN CREATE NODE CONTEXT
		var specProp=this.specificProperties('createN',instance.componentName,'',instance);
		if(specProp.cancel){return}
		
		//look for the parent node		
		if(instance.componentName=='popup'){
			var nodeP=document.body.node;
		}
		else{
			//first look for if the direct parent as a node reference (ex:splitter.div1)
			if(instance.parent && instance.parent.node){
				var nodeP=instance.parent.node;
			}
			else{
				//if not look for the rialto container
				var nodeP=instance.inContainer.node;
			}
		}
		var icon;
		
		if(!instance.isContainer){
			icon="images/imTreeview/puce.gif"
		}
		
		var nodeInstance=new rialto.widget.TreeNode({name:'nodeR',
														text:instance.componentName,
														icon:icon,
														draggable:specProp.boolNodeDraggable,
														//onclick:specProp.onclick,
														open:false});  
														
		nodeInstance.onclick=specProp.onclick;
		nodeP.addNode(nodeInstance);
		
		//Drop in rules												
		nodeInstance.beforeDropIn=function(node) {
			//SPECIFIC PROPERTIES IN CHECK DROP NODE CONTEXT
			return oThis.checkAuthorize(node.text,this.instance.componentName)
		}																											
		//reverse link between node and instance
		nodeInstance.instance=instance;
		instance.node=nodeInstance;	    
		
		//applicative code
		nodeInstance.onDropIn=function(node,oldParentNode) {
			if (this!=oldParentNode){
				var oSpecs={};
				oSpecs.pathMissile='';
				oSpecs.top=0;
				oSpecs.left=0;
				oSpecs.oHtml=node.instance.ghostDesign;
				oThis.dropInstance(oSpecs,this.instance.ghostDesign);
			}
		}
	//}
	//catch(e){alert(e);}
}


/*
This function is call after a drop
- it can be a pattern drop
- or an existing instance drop
*/
rialto.utils.RialtoComposer.prototype.dropInstance = function (oSpecs,srcOnDropElement) {	
	//reccord the drop information
	this.lastSpec=oSpecs;
	this.lastSpec.srcOnDropElement=srcOnDropElement;
	//drop a pattern to instanciate widget in another widget
	if (oSpecs.pathMissile.indexOf('.pattern') != -1) {
		//get name component
		var arr=oSpecs.pathMissile.split(".");
		var componentName=arr[arr.length-2];
		this.newInstanceafterDrop(componentName,oSpecs.top,oSpecs.left,srcOnDropElement);
	}
	//drop a widget as child 
	else {				
		//instance
		var instance = oSpecs.oHtml.widgetLink;
		if(!srcOnDropElement.widgetLink.containerHidden && !srcOnDropElement.widgetLink.showAscontainerHidden){	
			if(instance.containerHidden){
				instance.objAttr.top=oSpecs.top;
				instance.objAttr.left=oSpecs.left;
				this.refresh(instance,srcOnDropElement);
				return;
			}
		
			var maskSelect=oSpecs.oHtml;
			/*Get specific properties
			According to the component name we will set some properties
				cancel:abort
				parent:parent of the component
				boolSetPos:if true calculate the position
				top:top if fixed
				left:left if fixed
			*/		
	
			//SPECIFIC PROPERTIES FOR INSTANCE WHEN DROP EXISTING INSTANCE CONTEXT
			var specProp=this.specificProperties('dropI',instance.componentName,srcOnDropElement,instance,instance.objAttr);
			if(specProp.cancel){
				//to put the ghost on his old position
				this.setGhostPosition(instance,maskSelect.parentNode);
				return
			}
			//parent
			//put top and left 0 to prevent from overflow
			instance.setTop(0);
			instance.setLeft(0);		
			if(!specProp.noParentI){
				var parent;	
				if(!specProp.parentI){
					//PlaceIn
					parent=srcOnDropElement.widgetLink;
				}
				else{
					parent=specProp.parentI;
				}
				instance.placeIn(parent);
			}
			
			//Position
			if(specProp.boolSetPos){
				//set position
				this.setInstancePosition(instance,oSpecs.top,oSpecs.left,srcOnDropElement);
			}
			else{		
				//set specific position
			 	this.setInstancePosition(instance,specProp.top,specProp.left,srcOnDropElement,true);
			}
			//change node in treeview
			srcOnDropElement.widgetLink.node.addNode(instance.node);
	
			//SPECIFIC PROPERTIES FOR GHOST WHEN DROP EXISTING INSTANCE CONTEXT
			var specProp=this.specificProperties('dropG',instance.componentName,srcOnDropElement,instance);
			if(specProp.cancel){
				//to put the ghost on his old position
				this.setGhostPosition(instance,srcOnDropElement);
				return
			}
		 	maskSelect.style.top   = specProp.top;
	       	maskSelect.style.left  = specProp.left;	
			//place the instance (even if it is the same parent)
			if (srcOnDropElement != maskSelect.parentNode) {			
				if(!specProp.noParentG){
					// new parent for ghost		
					var parent =srcOnDropElement;					
					if(specProp.parentG){
						parent = specProp.parentG;
					}
					parent.appendChild(maskSelect);						
				}						
			}
			if(specProp.boolSetPos){
				//set position			
				this.setGhostPosition(instance,srcOnDropElement);			
			}		
		}
		else{
			instance.objAttr.top=oSpecs.top;
			instance.objAttr.left=oSpecs.left;
			this.refresh(instance,srcOnDropElement);
			//save instance properties
			/*var objAttr=instance.objAttr;
			var componentName=instance.componentName;
			//remove instance
			this.removeInstance(instance);
			//create new one
			var instance={componentName:componentName,
				  objAttr:objAttr,
				  containerHidden:true,
				  inContainer:srcOnDropElement.widgetLink,
				  ghostDesign:{}
		    };
			//simulate the reverse link
			instance.ghostDesign.widgetLink=instance;
			//create the node in  the grid 
			this.createNode(instance);*/
		}		
		//refresh output
		this.combSourceSelect.onclick(this.combSourceSelect.getSelValue(),this.combSourceSelect.getSelText());
						
	}						
}

//set the instance position
//if bSkipContCorection is not true a correction will be made according to the real place in the container
rialto.utils.RialtoComposer.prototype.setInstancePosition =function(instance,top,left,srcOnDropElement,bSkipContCorection){
 	if(!srcOnDropElement.widgetLink.containerHidden){
	 	//traceExec("set instance top:"+top+" left:"+left,1);
	 	
	 	//new position of the instance
		var topInParent=    parseInt(top)  
						 //+ _rum.$$getBorderTopWidth(srcOnDropElement.oHtml)
						 //- _rum.$$getBorderTopWidth(srcOnDropElement.widgetLink.oHtml);
		var leftInParent=	parseInt(left)  
						 //+ _rum.$$getBorderLeftWidth(srcOnDropElement.oHtml)
						 //- _rum.$$getBorderLeftWidth(srcOnDropElement.widgetLink.oHtml);
	 	//traceExec("topInParent:"+topInParent,1);
	 	//traceExec("leftInParent:"+leftInParent,1);
		//if drop in instance of a  container look for the delta top and left of the htmlcont 
	    if (!bSkipContCorection && srcOnDropElement.widgetLink.getHtmlCont) {
			var obPos=this.getPosInParent(instance);
			topInParent     -=obPos.deltaTop;
	   	    leftInParent    -=obPos.deltaLeft;
	    }
	    topInParent=Math.max(topInParent,0);
	    leftInParent=Math.max(leftInParent,0);
	
	    if(!instance.setTop){
		    instance.oHtml.style.top=topInParent;
	    	instance.oHtml.style.left=leftInParent;
	    }
	    else{    
		    instance.setTop(topInParent);
			instance.setLeft(leftInParent);
		}
		//reccord on the atribute object
		instance.objAttr.top=topInParent;
		instance.objAttr.left=leftInParent;
	}
}

//set top,left for the ghost
rialto.utils.RialtoComposer.prototype.setGhostPosition =function(instance,srcOnDropElement){
	if(!srcOnDropElement.widgetLink.containerHidden){
		var topInParent= instance.top 
						- _rum.$$getBorderTopWidth(srcOnDropElement.widgetLink.oHtml);;
		var leftInParent= instance.left 
						- _rum.$$getBorderTopWidth(srcOnDropElement.widgetLink.oHtml);;
		//must specify the top and left according to the instance				
		if (srcOnDropElement.widgetLink.getHtmlCont) {
			var obPos=this.getPosInParent(instance);
			topInParent     +=obPos.deltaTop;
	   	    leftInParent    +=obPos.deltaLeft;
	    }
		var bord=_rum.$$getBorderLeftWidth(srcOnDropElement);
		//exception for the splitter
		if(srcOnDropElement.widgetLink.componentName=='divSplitter')bord=2;
	    instance.ghostDesign.style.top = topInParent-bord;
		instance.ghostDesign.style.left =leftInParent-bord; 		
	}
}


rialto.utils.RialtoComposer.prototype.setGhostSize =function(instance){
	//set size for the ghost
	var	maskSelect=instance.ghostDesign;
    var bord=_rum.$$getBorderLeftWidth(maskSelect)*2;  
//maskat start
    var width = ria.utils.measures.$getWidth(instance.oHtml,true)- bord; 
    maskSelect.style.width   = (width<0)?0:width;
//maskat end
    maskSelect.style.height  = ria.utils.measures.$getHeight(instance.oHtml,true)- bord; 
    ria.utils.measures.$setSizeConformW3C(maskSelect);
}

//Get for an instance, the delta between the external div of here parent and the div inside she is
//use because a instance is drop in the container of here parent
//and the ghost is in the external div so we kneed the delta
rialto.utils.RialtoComposer.prototype.getPosInParent =function(instance){
	var obPos={
		top:  _rum.$offsetTop(instance.oHtml),
		left: _rum.$offsetLeft(instance.oHtml),
		deltaTop:0,
		deltaLeft:0		
	}	
	var parentDivExt=instance.inContainer.oHtml;
	var curParent=instance.oHtml.parentNode;	
	while(curParent!=parentDivExt){
		//traceExec("curParent.offsetTop:"+curParent.offsetTop,1);
		if(curParent.nodeName=='DIV'){
			obPos.top+= _rum.$offsetTop(curParent);
			obPos.left+= _rum.$offsetLeft(curParent);	
		}
		//curParent=curParent.parentNode;
		curParent=curParent.offsetParent;
	}
	obPos.deltaTop  = obPos.top  - _rum.$offsetTop(instance.oHtml);
	obPos.deltaLeft = obPos.left - _rum.$offsetLeft(instance.oHtml);		
	return obPos;	
}

//This function is use to specify header properties of the grid
rialto.utils.RialtoComposer.prototype.createPopupGrid =function(srcOnDropElement,objAttr,instance){
		
	var oThis=this;
	//init parameter
	var arrEntete;
	var arrTypeCol;
	//popup
	var fen = new rialto.widget.PopUp('test',150,420,'350','200','',"Grid properties",'transparent');
	var lab=new rialto.widget.Label('lab',10,10,fen,'Rows number','libelle2');
	//number of column
	var text = new rialto.widget.Text('TEXT',10,100,50,'N',fen,{autoUp:true,isRequired:false,disable:false,rows:25,accessKey:'',tabIndex:'',initValue:""});
	//on blur create a line in the grid for each column to set header attribute
	text.onblur=function(){
		var n=this.getValue();		
		var arr=new Array;
		for(var i=1;i<=n;i++){
			arr.push(['column '+i,'col'+i,'string','100']);				
		}
		//Clear the grid and fill it with new properties
		this.grid.deleteLines();
		this.grid.fillGrid(arr);
	}	
	
	var grid=text.grid=new  rialto.widget.Grid({
			top:40,
			left:5,
			height:100,
			TabEntete:["","title","type","width"],
			tabTypeCol:[["string",70],
						["string",80],
						["string",50,[['string',''],['date',''],['number','']]],
						["number",50]],
			parent:fen,
			cellActive:false,
			sortable:true,
			multiSelect:false,
			lineHeight:16,
			boolPrint:true,
			switchable:true,
			actifClic:true,
			autoResizableW:false,
			writable:true});
	
	
	
	var buttonR=new rialto.widget.Button(150,50,"Cancel","cancel",fen,{enable:true});
	var buttonA=new rialto.widget.Button(150,160,"Add","Add to grid",fen,{enable:true});
	
	buttonR.onclick=function(){
		fen.closeFen(); 
	}
			
	buttonA.onclick=function(){
		//get the header information
		var arrEntete=new Array();
		var arrTypeCol=new Array();
		for(var i=0;i<grid.NbreLig;i++){
			arrEntete.push(grid.tabData[i][1]);
			arrTypeCol.push([grid.tabData[i][2],grid.tabData[i][3]]);
		}		
		//add prpperties to the grid object propertie		
		objAttr.top=oThis.lastSpec.top;
		objAttr.left=oThis.lastSpec.left;
		objAttr.TabEntete=arrEntete;
		objAttr.tabTypeCol=arrTypeCol;
		oThis.newInstanceafterDrop('grid',oThis.lastSpec.top,oThis.lastSpec.left,srcOnDropElement,objAttr);
		fen.closeFen(); 
	}
	
	
	//if already entete it is a update of an existing grid
	if(instance && instance.tabEntete){
		var arr=new Array;
		for(var i=0;i<instance.tabEntete.length;i++){
			arr.push(['column '+i,instance.tabEntete[i],instance.tabTypeCol[i][0],instance.tabTypeCol[i][1]]);				
		}
		grid.deleteLines();
		grid.fillGrid(arr);
		buttonA.setTitle("Refresh");
		buttonA.onclick=function(){		
			//get the header information
			var arrEntete=new Array();
			var arrTypeCol=new Array();
			for(var i=0;i<grid.NbreLig;i++){
				arrEntete.push(grid.tabData[i][1]);
				arrTypeCol.push([grid.tabData[i][2],grid.tabData[i][3]]);
			}		
			//add prpperties to the grid object propertie					
			instance.objAttr.TabEntete=arrEntete;
			instance.objAttr.tabTypeCol=arrTypeCol;
			oThis.refresh(instance);
			fen.closeFen(); 
		}
	}	
	
	
	
	
}

//This function is use to create the components of the rialto composer
rialto.utils.RialtoComposer.prototype.createIHM =function(){
	try{
	
	var oThis=this;
	//External frame
	this.frame= new rialto.widget.Frame(
			{name:'Dashboard',
			 top:10,
			 left:10,
			 width:400,
			 height:530,
			 title:"Rialto composer",
			 dynamic:true,
			 draggable:true,
			 resizable:true,
			 parent:document.body});	
	this.frame.setStyle({border:'1px outset white',zIndex:10001});
	this.frame.linkToRC = this;  // for debug
	//this.frame.placeInTop();
	//Switch Mode
	var swImg=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/preview.png',100,4,'','Switch to preview mode');
	// for try : swImg.onclick =  rialto.composer.toogleMode;
	swImg.onclick =  function (e) {
//maskat start マスカットプレビュー機能
        var previewWin = window.open("preview.html","maskat_preview_window");
        previewWin.focus();
        previewWin.opener = window;
/*		rialto.composer.toogleMode(e);
		var divM=document.createElement('DIV');
		var divCss=divM.style;
		divCss.zIndex=10000;
		divCss.position='absolute';
		divCss.width='100%';
		divCss.height='100%';
		divM.onclick=function(){
			var al=new rialto.widget.Alert("This is only a preview. You can't interact with the components");
		}
		document.body.appendChild(divM);
		document.body.divM=divM;
		oThis.frame.setVisible(false);
		oThis.frameMinTryMode.setVisible(true);*/
//maskat end
	}
	//External frame
	this.frameMinTryMode= new rialto.widget.Frame(
			{name:'DashboardMin',
			 top:10,
			 left:10,
			 width:270,
			 height:25,
			 title:"Rialto composer - Switch back to design mode ->  ",
			 dynamic:'buttonLess',
			 draggable:true,
			 resizable:false,
			 parent:document.body});
	this.frameMinTryMode.setVisible(false);
		
	this.frameMinTryMode.setStyle({border:'1px outset white',zIndex:10001});
	var imgToogleDesignMode =new rialto.widget.Image(
								rialtoConfig.pathRialtoE+'images/edit.png'
								,247,4,'','Switch back to design mode');

	imgToogleDesignMode.onclick =  function (e) {
		document.body.divM.onclick=null;
		document.body.removeChild(document.body.divM);
		rialto.composer.toogleMode(e);
		oThis.frameMinTryMode.setVisible(false);
		oThis.frame.setVisible(true);
	}
	this.frameMinTryMode.addButton(imgToogleDesignMode);

	// end to try
	
	//align left
	this.alignL=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/fleches/flechplus_g_off.gif',120,4,'',
										'Align left selected component',
										rialtoConfig.pathRialtoE+'images/fleches/flechplus_g_on.gif',
										{imageDisabled:rialtoConfig.pathRialtoE+'images/fleches/flechplus_g_sob_off.gif'});


	this.alignL.onclick = function(){
		oThis.align('left');
	};
	//align right
	this.alignR=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/fleches/flechplus_d_off.gif',140,4,'',
										'Align right selected component',
										rialtoConfig.pathRialtoE+'images/fleches/flechplus_d_on.gif',
//										{imageDisabled:rialtoConfig.pathRialtoE+'images/fleches/fleche_haut_sob.gif'});
										{imageDisabled:rialtoConfig.pathRialtoE+'images/fleches/flechplus_d_sob_off.gif'});
	this.alignR.onclick = function(){
		oThis.align('right');
	};
	//align top
	this.alignT=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/fleches/fleche-haut.gif',160,4,'',
										'Align top selected component',
										rialtoConfig.pathRialtoE+'images/fleches/fleche-haut.gif',
										{imageDisabled:rialtoConfig.pathRialtoE+'images/fleches/fleche-haut_sob.gif'});
	this.alignT.onclick = function(){
		oThis.align('top');
	};
	
	//new
	var nImg=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/new.png',320,4,'','new');
	nImg.onclick = function(){
		oThis.filePath=null;
		oThis.clear();	
	};

	//save
	var svImg=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/save.png',340,4,'','save');

	svImg.onclick = function(){
		//the save option is available only in a local context
		if(rialtoConfig.isFilePath){
			oThis.saveLoadFile(false);					
		}
		else{
			var al=new rialto.widget.Alert("The save option is available only in a local context");		
		}
	};
	//Load
	var loImg=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/imTreeview/pict_synthetik_off.gif',360,2,'',
										'load',
										rialtoConfig.pathRialtoE+'images/imTreeview/pict_synthetik_on.gif');
	loImg.onclick = function(){
		//the load option is available only in a local context
		if(rialtoConfig.isFilePath){
			oThis.saveLoadFile(true);
		}
		else{
			var al=new rialto.widget.Alert("The load option is available only in a local context");		
		}
	};
	
	this.frame.addButton(swImg);
	this.frame.addButton(this.alignL);
	this.frame.addButton(this.alignR);
	this.frame.addButton(this.alignT);
	this.frame.addButton(nImg);
	this.frame.addButton(svImg);
	this.frame.addButton(loImg);
	this.alignL.setEnable(false);
	this.alignR.setEnable(false);
	this.alignT.setEnable(false);
	//TAB
	this.tabs = new rialto.widget.TabFolder(
			{name:'myTabs',
			 top:'5',
			 left:'5',
			 width:'390',
			 height:'495',
			 parent:this.frame,
			 widthTabName:100,
			 autoRedimTab:false,
			 isClosable:false,
			 draggableItem:false});
	
	this.tabDesign=this.tabs.addTabItem("Design");
	this.tabTree=this.tabs.addTabItem("Tree");
	this.tabSource=this.tabs.addTabItem("Source");
	this.tabs.activeTab(0);
	
	this.tabDesign.onEnableTab=function(){
		//restore all
		oThis.restoreIHM();
		oThis.treeTab=false;
		oThis.propertiesFrame.setVisible(true);
	}
	this.tabTree.onEnableTab=function(){
		//restore all
		oThis.restoreIHM();	
		oThis.treeTab=true;
		oThis.propertiesFrame.setVisible(true);
	}
	
	this.tabSource.onEnableTab=function(){
		//restore all
		oThis.restoreIHM();
		oThis.treeTab=false;	
		oThis.propertiesFrame.setVisible(false);
	}
	
	
	//TAB DESIGN CONTENT
	this.componentsFrame= new rialto.widget.Frame(
			{name:'components',
			 top:10,
			 left:10,
			 position:'relative',
			 width:370,
			 height:205,
			 title:"Rialto components",
			 dynamic:false,
			 parent:this.tabDesign});
	
			 
	this.propertiesFrame= new rialto.widget.Frame(
			{name:'properties',
			 position:'relative',
			 top:255,
			 left:18,
			 width:370,
			 height:230,
			 title:"COMPONENT:",
			 dynamic:false,
			 parent:this.frame});	
			 
	//COMPONENTS
	var top=5;
	var left=5;
	this.arrImgComponent=new Array;
	for(var i=0;i<this.arrComponentType.length;i++){
		var prop=this.arrComponentType[i];	
		//image representing one component
		var imgC=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/imTreeview/icone_box_ptit_off.gif',left,top,this.componentsFrame,prop,rialtoConfig.pathRialtoE+'images/imTreeview/icone_box_ptit_on.gif',{position:'absolute',boolFloatLeft:false,boolFloaRight:false,imageDisabled:''});
		//name of the component		
		var labC=new rialto.widget.Label(prop,top,left+20,this.componentsFrame,prop,'libelle2');
		//delta for top and left
		left+=120;
		if(left>300){
			left=5;
			top+=25;
		}		
		//--- set Drag and Drop behavior
		rialto.widgetBehavior.affect(imgC.getHtmlExt(),'DragAndDrop',this.setupDD);
		this.arrImgComponent.push(imgC);
		var setupMissile = {domainTargets:'designZone.widgets.'+prop+".pattern"};
		rialto.widgetBehavior.affect(imgC.getHtmlExt(),'Missile'	,setupMissile);		
		imgC.getHtmlExt().afterClic=function(e){                        
            oThis.componentProperties(oThis.objects[this.title],this.title);       
        };
	}
	
	//PROPERTIES GRID
	this.propertiesGrid = new rialto.widget.Grid({
			top:5,
			left:5,
			height:220,
			TabEntete:["name","Value"],
			tabTypeCol:[["string",150],["string",150]],
			parent:this.propertiesFrame,
			cellActive:false,
			sortable:true,
			multiSelect:false,
			lineHeight:16,
			boolPrint:true,
			switchable:true,
			actifClic:true,
			autoResizableW:false,
			writable:true});

	this.propertiesGrid.onCellEdit=function(indLine,indCell,oldVal,newVal){		
		//ok if the value change
		return  (oldVal!=newVal);
	}
				
	//TAB TREE
	//treeview
	this.tree=new rialto.widget.Tree({name:'treeGrid',
    					top:'5',
    					left:'5',
    					width:330,
    					height:210,
    					parent:this.tabTree,
    					boolSelActive:true,
    					rootOpen:true,
    					withRoot:true,
    					withT:true,
    					draggableNode:true,
    					position:'absolute'}
    				);
    				
	//ROOT NODE    				
	this.rialtoNode =this.tree.createAndAddNode(this.tree.id,{name:'nodeR',
						text:'rialto',
						icon:'images/imTreeview/icone_box_ptit_on.gif',
						icon2:'',
						onclick:"",
						open:true,						
						typeInfo:''}
						);  
													
	
	//Drop in rules												
	this.rialtoNode.beforeDropIn=function(node) {
		//SPECIFIC PROPERTIES FOR INSTANCE WHEN DROP EXISTING INSTANC CONTEXT
		var specProp=oThis.specificProperties("checkNode",node.text,document.body,'');			
		return !specProp.cancel;
	}																											
	//reverse link between node and instance
	document.body.node=this.rialtoNode;
	this.rialtoNode.instance=document.body;		
	//applicative code
	this.rialtoNode.onDropIn=function(node,oldParentNode) {
		if (this!=oldParentNode){
			var oSpecs={};
			oSpecs.pathMissile='';
			oSpecs.top=0;
			oSpecs.left=0;
			oSpecs.oHtml=node.instance.ghostDesign;
			oThis.dropInstance(oSpecs,document.body);
		}
	}
	
	
		
	//DASH
	this.dash=new rialto.widget.Image(rialtoConfig.pathRialtoE+'images/trash.png',340,10,this.tabTree,'Remove component',rialtoConfig.pathRialtoE+'images/trashFull.png');

	var oHtml=this.dash.getHtmlExt();	
	rialto.widgetBehavior.affect(oHtml,'Target',{domain:'tree.node'});
	oHtml.receiveAfterDrop = function(oSpecs) { 
		var instance=oSpecs.oHtml.oCiu.instance;		
		oThis.removeInstance(instance);
	}
	//reproduce swap effect
	oHtml.DDOuter = function (missile) {            
        oThis.dash.$$loadImage();
    }
        
	oHtml.DDHover = function ( missile) { 
        oThis.dash.$$loadImage(true);
    }   
 		
	//TAB SOURCE			
	var labC=new rialto.widget.Label('lab',10,10,this.tabSource,"output type:",'libelle2');
	//combo to choose the output type
	this.combSourceSelect=new rialto.widget.Combo('','source',10,80,72,this.tabSource,{suggest:true,enable:true});
	this.combSourceSelect.addItem("xml","xml");
	this.combSourceSelect.addItem("javascript","javascript");
	
	this.combSourceSelect.onclick=function(value,text){
		var str="";
		switch (value) {
		   case "xml":		   
			   	str=oThis.generateXML2();//maskat maskatXML仕様のアウトプット
				break;
		   case "javascript":
	 		    str=oThis.generateXML();
			   	oThis.RW.loadComponents(str);
				str=oThis.RW.getJavascriptCall();
				break;		 
		   default:
		}		
		oThis.output.setValue(str);
	}
	
	//TEXTAREA
    this.output = new rialto.widget.Text('TEXT',30,10,375,'T',this.tabSource,{autoUp:true,isRequired:false,disable:false,rows:25,accessKey:'',tabIndex:'',initValue:""});
	}
catch(e){alert("erreur:"+e.message)}				
}

//Param of object
rialto.utils.RialtoComposer.prototype.restoreIHM=function () {
	this.propertiesFrame.setTitle("COMPONENT:");
	this.propertiesGrid.deleteLines();
	this.multiSelect();
}

//Param of object
rialto.utils.RialtoComposer.prototype.componentProperties=function (objParam,componentName) {
	var oThis=this;
	var arr=new Array;
	
	//change the frame title
	this.propertiesFrame.setTitle("COMPONENT: "+componentName);
	//Get the init properties	
	for(propA in objParam){
		traceExec(componentName+"."+propA,1);	
//maskat start
//		traceExec("this.objectsList[componentName][propA].length:"+this.objectsList[componentName][propA].length,1);
		if(this.objectsList[componentName][propA]!=null && this.objectsList[componentName][propA].length>0){
//maskat end
			var arrL=new Array;
			var arrValue=this.objectsList[componentName][propA];
			traceExec("arr:"+arrValue,1);
			for(var i=0;i<this.objectsList[componentName][propA].length;i++){
				arrL.push([this.objectsList[componentName][propA][i],this.objectsList[componentName][propA][i]]);
			}
//maskat start
			arr.push([propA,{value:objParam[propA],authValue:arrL}]);
//			arr.push([propA,arrL]);
//maskat end
		}		
		else{
			arr.push([propA,objParam[propA]]);
		}
	}
	//Clear the grid and fill it with new properties
	this.propertiesGrid.deleteLines();
	this.propertiesGrid.fillGrid(arr);
	
	this.propertiesGrid.onCellWrite=function(indLine,indCell,newVal){
		objParam[this.tabData[indLine][0]]=newVal;
		if(oThis.treeTab){
			//get the sel node
			var instance=oThis.tree.currentSelNode.instance;
			//refresh it
			if(!instance.containerHidden){oThis.refresh(instance);}			
		}		

	}
		
}



//This function is use to transform a xml document with the xsl stylesheet
rialto.utils.RialtoComposer.prototype.transformXml =function(request){
	try{
		var xDoc=rialto.utils.xml.createDocumentFromString(this.generateXML());
		var resDoc=rialto.utils.xml.XSLTransform(request.responseXML,xDoc);
		str=rialto.utils.xml.outerNode(resDoc);	
		this.output.setValue(str);
	}
	catch(e){alert("erreur:"+e.message)}	
}

//This function is use to generate the xml output
rialto.utils.RialtoComposer.prototype.generateXML =function(node){
	if(!node){var node=this.rialtoNode;}
	var firstShift = '';
	return this.nodeToXml(node,firstShift);	
}



//This function is use to generate the xml output
rialto.utils.RialtoComposer.SHIFT_WIDTH_FOR_PRETTY_LAYOUT = '  ';
rialto.utils.RialtoComposer.prototype.nodeToXml =function(node,shift){
	var strXML="";	
	shift = shift + rialto.utils.RialtoComposer.SHIFT_WIDTH_FOR_PRETTY_LAYOUT;
	strXML += (shift || '');
	strXML+="<"+node.text;
	if(node.instance){
		strXML+=rialto.utils.xml.parseObjectAsAttribute(node.instance.objAttr);	
	}
	strXML+=">\n";
	if(node.hasChild()){
		for (var i=0;i<node.arrChildNode.length;i++){
			var nodeC=node.arrChildNode[i];				
			strXML+=this.nodeToXml(nodeC,shift);
		}
	}
	strXML+= shift; 
	strXML+="</"+node.text+">\n";			
	return strXML;	
}

//This function is use load elements from an xml string description
rialto.utils.RialtoComposer.prototype.refreshFromXml =function(xmlDesc){
	//clear the work area
	this.clear();
	//regenerate
	var xDoc=rialto.utils.xml.createDocumentFromString(xmlDesc);
	this.refreshOneNode(xDoc.firstChild,document.body)
}

//This function is use to generate an instance
rialto.utils.RialtoComposer.prototype.refresh =function(instance,srcOnDropElement){
	//xml
	var xmlDesc=this.generateXML(instance.node);
	//save information
	if(!srcOnDropElement){var srcOnDropElement=instance.ghostDesign.parentNode;}
	//remove the instance
	this.removeInstance(instance);
	//regenerate
	var xDoc=rialto.utils.xml.createDocumentFromString(xmlDesc);
	this.refreshOneNode(xDoc.firstChild,srcOnDropElement)
}

//This recursive function is use to generate one instance and her child
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);
	//create a new instance
	if(componentName!='rialto'){		
		var instance=this.newInstanceafterDrop(componentName,objAttr.top,objAttr.left,srcOnDropElement,objAttr);
		srcOnDropElement=instance.ghostDesign;
	}
	//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);
			}
		}
	}
}

//This function is use to load a test file
rialto.utils.RialtoComposer.prototype.loadFile =function(filePath){	
	
	//save file path
	this.filePath=filePath;
	
	var content=rialto.utils.DataManager.loadFile(filePath);
	this.clear();
	this.file=rialto.utils.xml.createDocumentFromString(content);
	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);
}

//POP UP TO SELECT FILE TO SAVE/LOAD
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);
	}
	
	
	this.loadsaveFilepopup=new rialto.widget.PopUp('popup0',172,465,330,80,'',curFile,'transparent');
//maskat start
/*	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);*/
	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);
    }
//maskat end
	//get the input fiel 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.loadFile(path);
			oThis.loadsaveFilepopup.closeFen();
		}
	}
	
	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(oThis.generateXML(),path);
			oThis.loadsaveFilepopup.closeFen();
		}				
	}

}


//clear work area
rialto.utils.RialtoComposer.prototype.clear=function (){	
	//restore all
	this.restoreIHM();
	for(var i=this.arrComponent.length-1;i>=0;i--){
		var cp=this.arrComponent[i];
		this.removeInstance(cp);
	}	
}


//Remove function 
rialto.utils.RialtoComposer.prototype.remove=function (){
	try{
		this.dash.receiveAfterDrop=null;
		document.body.name=null;
		document.body.widgetLink=null;
		document.body.oHtml=null;
		document.body.receiveAfterDrop = null;
		rialto.widgetBehavior.desaffect(this.dash.getHtmlExt(),'Target');
		rialto.widgetBehavior.desaffect(document.body,'Target');
		//remove component image d&d behavior
		for(var i=0;i<this.arrImgComponent.length;i++){
			var imgC = this.arrImgComponent[i];
			rialto.widgetBehavior.desaffect(imgC.getHtmlExt(),'Missile');		
		}
		//remove mask
		/*for(var i=document.body.childNodes.length-1;i>=0;i--){
			var child=document.body.childNodes[i];
			if(child && child.nodeType==1 && child.id.indexOf('maskWidgetInDesign')!=-1){
				this.removeMask(child);
			}
		}*/
		for(var i=this.arrComponent.length-1;i>=0;i--){
			var cp=this.arrComponent[i];
			this.removeInstance(cp);
		}
		//remove all
		rialto.session.cleanObj(this);
	}
	catch(e){alert("erreur:"+e.message)}
}

//thisfunction allow to remove a instance of the workspace
rialto.utils.RialtoComposer.prototype.removeInstance= function (instance) {			
		traceExec("REMOVE instance.name:"+instance.name+" instance.componentName:"+instance.componentName,1);
		
		//if curent node sel delete grid
		if(this.tree.currentSelNode && this.tree.currentSelNode.instance==instance){
			this.propertiesGrid.deleteLines();
		}		
		//flag for the simple window		
		if(instance.componentName=='simpleWindow'){this.bsW=false;}		
		//if instance is not in a container hidden
		if(!instance.containerHidden){
			//remove the child
			if(instance.arrChild || instance.arrChildNode){
				//get the good array
				var arrC=instance.arrChild?instance.arrChild:instance.arrChildNode;
				for(var i=0;i<arrC.length;i++){
					//if it is an instance
					if(rialto.array.indexOf(this.arrComponent,arrC[i])!=-1){
						this.removeInstance(arrC[i]);
					}
			    }
			}
			//remove the node
			if(instance.node){instance.node.remove();}		
			rialto.array.remove(this.arrComponent,instance);	
			if(instance.objAttr && instance.objAttr.name){this.arrComponentName[instance.objAttr.name]=null};		
			//remove the ghost
			if(instance.ghostDesign){this.removeMask(instance.ghostDesign)};
			//instance.remove
			if(instance.remove){instance.remove();}
			else{
				if(instance.parentNode){instance.parentNode.removeChild(instance);}
			}
		}
		else{
			//remove the node
			if(instance.node){instance.node.remove();}			
		}		
		//refresh output
		this.combSourceSelect.onclick(this.combSourceSelect.getSelValue(),this.combSourceSelect.getSelText());
		
}


rialto.utils.RialtoComposer.prototype.removeMask=function (maskSelect){       
        if(maskSelect){
	        //remove child mask
	        for(var i=maskSelect.childNodes.length-1;i>=0;i--){
				var child=maskSelect.childNodes[i];
				if(child.nodeType==1 && child.id.indexOf('maskWidgetInDesign')!=-1){
					this.removeMask(child);
				}
			}	        	        	
			if(maskSelect.dragAnDrop){rialto.widgetBehavior.desaffect(maskSelect,'DragAndDrop');}
			if(maskSelect.reSize){rialto.widgetBehavior.desaffect(maskSelect,'ReSize');}
			//FOr the moment only target desaffect because do the 3 desaffect funtion does the same thing
			if(maskSelect.specsTarg){rialto.widgetBehavior.desaffect(maskSelect,'Target');}
			maskSelect.parentNode.removeChild(maskSelect);
	   	}
}

