<?php

include("_dirinfo.php");

include (PATH_TO_ROOT."init.php");
include (PATH_TO_ROOT."webcati/init.php");
include (PATH_TO_ROOT."_class/class.Extjs_tree.php");
include (PATH_TO_ROOT."_class/class.Extjs_grid.php");
include (PATH_TO_ROOT."_class/createQuestion/Question.php");

$ajaxUrl = 'webcati/_ajax/designerPanel/ajax.writeXML.php';
$ajaxDesUrl = 'webcati/_ajax/designerPanel/ajax.designerPanel.php';
$uniqeTab = $_POST['uniqueTabId'];
$templateId = $_POST['id'];


$idPreced = 'wcdpPanel_'.$templateId.'_';
$mainPanelId = 'wcdpPanel_'.$templateId.'_0';
$overViewPanelId = 'wcdpOverViewPanel_'.$templateId;
//urejanje grid properties


$gridEditPanel = 'wcdpDesignerPropertyGrid_'.$templateId;


?>
//property grid for the properties...if it already exist why not :)
var <?php echo $gridEditPanel?> = new Ext.grid.PropertyGrid({
        id: '<?php echo $gridEditPanel?>',
        title: 'Properties'
    });

<?php


//the tree that shows which components are on display!!!
$designTreeName = "wcdpDesignTree_".$templateId;
$designTree = new MakeTree($designTreeName);


//grid with all styles that the tree has (this is not customizable!!!)

$gridStyle = new MakeGrid();
$gridStyle->setMainTable(WC_DESIGNER_TEMPLATES,DB_WARPIT_WEBCATI_BASE);
$gridStyle->setTitle("Styles")
	->setReqUrl($ajaxUrl)
	->setClosable(false)
	->baseParams = "templateId : $templateId";
;

$gridStyle->addColumn('clsId');
$gridStyle->addColumn('idLab','Class')->hidden(true)->setProperty('groupRenderer',"function(v,n,r){
	var id = r.data.clsId.split('_');
	if(id.length > 1)
	{
		return id[0]+ ' Class: '+v;
	}
	return 'Class: '+v;
	
}");
$gridStyle->addColumn('name')->header('Style');
$gridStyle->addColumn('prop_value')->header('Value');

$gridStyle->setGrouping('idLab','{hideGroupedColumn: true,enableGroupingMenu:false,enableNoGroups:false,showGroupName:false}');

$gridStyle->addTbarItem("{text:'Delete',scope:this,iconCls:'icon-delete-record', handler:function(){
var sm = $gridStyle.getSelectionModel();if(sm.hasSelection()){

	var sel = sm.getSelected();
	//we get the path to reopen the tree after refresh
	Ext.Msg.show({ title:'Remove class',buttons: Ext.MessageBox.YESNO,msg:'Are you sure?',
	fn: function(btn){if(btn == 'yes'){
		$designTree.RMajax.request({params:{
				action:'removeClass',
				id: Ext.getCmp('$mainPanelId').selectedDesignPanel.designId,
				classId:sel.data.clsId
				},success:function(){ $gridStyle.getStore().reload(); }
				});
	}}
		});
		}
		}}");
	
echo $gridStyle->createGrid();




$gridBody = 'wcdpDesignerBodyForm_'.$templateId;
?>

//set properties for body
var <?php echo $gridBody ?> = new Ext.FormPanel({
		id: '<?php echo $gridBody ?>',
        title: 'Body',
        labelWidth: 35,
        bodyStyle: 'padding:1px 1px',
        url: '<?php echo $ajaxDesUrl; ?>',
        frame: true,
        baseParams: {
            id: '<?php echo $gridEditPanel?>',
            action: 'saveBodyProperties'
        },
        listeners: {
            beforeshow: function()
            {
                <?php echo $gridBody; ?>.getForm().load({
                    params:{
                        action: 'loadBodyProperties'
                    }
                });
            }
        },
        items: [{        
	        xtype     : 'textarea',
	        fieldLabel: 'Set body style',
	        grow      : true,
	        name      : 'body_properties',
	        anchor    : '100%'
	    }],
        buttons: [{
            text: 'Save',
            handler: function()
            {
               // console.log('<?php echo $gridEditPanel?>');
                <?php echo $gridBody; ?>.getForm().submit({
                    success: function(form, action) 
                    {
                        Ext.Msg.alert('Success', "Body properties are saved!");
                    }
                });
                
            }
        }]
    });

    <?php
    $gridControls = 'wcdpDesignerControlsForm_' . $templateId;
   ?>
   var <?php echo $gridControls ?> = new Ext.FormPanel({
        id: '<?php echo $gridControls ?>',
        title: 'Controls',
        autoScroll: true,
        labelWidth: 65,
        bodyStyle: 'padding:1px 1px',
        url: '<?php echo $ajaxDesUrl; ?>',
        frame: true,
        baseParams: {
            id: '<?php echo $gridEditPanel?>',
            action: 'saveControls'
        },
        listeners: {
            beforeshow: function()
            {
                <?php echo $gridControls; ?>.getForm().load({
                    params:{
                        action: 'loadControls'
                    },success: function(form, action) 
                    {
                        if(Ext.getCmp('custom_checkbox_enable').getValue() == 0)
                        {
                            Ext.getCmp('checkbox_checked_image').disable();
                            Ext.getCmp('checkbox_unchecked_image').disable();
                            Ext.getCmp('checkbox_disabled_image').disable();
                        }
                        else
                        {
                            Ext.getCmp('checkbox_checked_image').enable();
                            Ext.getCmp('checkbox_unchecked_image').enable();
                            Ext.getCmp('checkbox_disabled_image').enable();
                        }
                    }
                });
            }
        },
        items: [{
            xtype:'fieldset',
            title: 'Checkboxes',
            items:[{
                xtype:'checkbox',
                fieldLabel: 'Enable',
                name      : 'custom_checkbox_enable',
                id      : 'custom_checkbox_enable',
                anchor    : '100%',
                listeners:
                {
                    check: function(field){
                        if(field.getValue() == 0)
                        {
                            Ext.getCmp('checkbox_checked_image').disable();
                            Ext.getCmp('checkbox_unchecked_image').disable();
                            Ext.getCmp('checkbox_disabled_image').disable();
                        }
                        else
                        {
                            Ext.getCmp('checkbox_checked_image').enable();
                            Ext.getCmp('checkbox_unchecked_image').enable();
                            Ext.getCmp('checkbox_disabled_image').enable();
                        }
                    }
                }
                
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Checked image',
                name      : 'checkbox_checked_image',
                id      : 'checkbox_checked_image',
                disabled : true,
                anchor    : '100%',
                listeners: 
                {
                   render: function(field) {
                        field.getEl().on('dblclick',function(){
                            mcImageManager.browse({
                            'oninsert': function(rtn)
                            {
                                field.setValue(rtn.files[0].url);
                            },
                            'relative_urls' : true,
                        }); 
                        });
                    },
                }
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Unchecked image',
                disabled : true,
                name      : 'checkbox_unchecked_image',
                id      : 'checkbox_unchecked_image',
                anchor    : '100%',
                listeners: 
                {
                   render: function(field) {
                        field.getEl().on('dblclick',function(){
                            mcImageManager.browse({
                            'oninsert': function(rtn)
                            {
                                field.setValue(rtn.files[0].url);
                            },
                            'relative_urls' : true,
                        }); 
                        });
                    },
                }
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Disabled image',
                disabled : true,
                name      : 'checkbox_disabled_image',
                id      : 'checkbox_disabled_image',
                anchor    : '100%',
                listeners: 
                {
                   render: function(field) {
                        field.getEl().on('dblclick',function(){
                            mcImageManager.browse({
                            'oninsert': function(rtn)
                            {
                                field.setValue(rtn.files[0].url);
                            },
                            'relative_urls' : true,
                        }); 
                        });
                    },
                }
            }],
            
        },{
            xtype:'fieldset',
            title: 'Radio buttons',
            items:[{
                xtype:'checkbox',
                fieldLabel: 'Enable',
                name      : 'custom_radio_enable',
                id      : 'custom_radio_enable',
                anchor    : '100%',
                listeners:
                {
                    check: function(field){
                        if(field.getValue() == 0)
                        {
                            Ext.getCmp('radio_checked_image').disable();
                            Ext.getCmp('radio_unchecked_image').disable();
                            Ext.getCmp('radio_disabled_image').disable();
                        }
                        else
                        {
                            Ext.getCmp('radio_checked_image').enable();
                            Ext.getCmp('radio_unchecked_image').enable();
                            Ext.getCmp('radio_disabled_image').enable();
                        }
                    }
                }
                
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Checked image',
                name      : 'radio_checked_image',
                id      : 'radio_checked_image',
                disabled : true,
                anchor    : '100%',
                listeners: 
                {
                   render: function(field) {
                        field.getEl().on('dblclick',function(){
                            mcImageManager.browse({
                            'oninsert': function(rtn)
                            {
                                field.setValue(rtn.files[0].url);
                            },
                            'relative_urls' : true,
                        }); 
                        });
                    },
                }
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Unchecked image',
                disabled : true,
                name      : 'radio_unchecked_image',
                id      : 'radio_unchecked_image',
                anchor    : '100%',
                listeners: 
                {
                   render: function(field) {
                        field.getEl().on('dblclick',function(){
                            mcImageManager.browse({
                            'oninsert': function(rtn)
                            {
                                field.setValue(rtn.files[0].url);
                            },
                            'relative_urls' : true,
                        }); 
                        });
                    },
                }
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Disabled image',
                disabled : true,
                name      : 'radio_disabled_image',
                id      : 'radio_disabled_image',
                anchor    : '100%',
                listeners: 
                {
                   render: function(field) {
                        field.getEl().on('dblclick',function(){
                            mcImageManager.browse({
                            'oninsert': function(rtn)
                            {
                                field.setValue(rtn.files[0].url);
                            },
                            'relative_urls' : true,
                        }); 
                        });
                    },
                }
            }],
            
        }],
        buttons: [{
            text: 'Save',
            handler: function()
            {
                <?php echo $gridControls; ?>.getForm().submit({
                    success: function(form, action) 
                    {
                        Ext.Msg.alert('Success', "Controls are saved!");
                    }
                });
                
            }
        }]
    });
<?php

$designTree->SetTable(WC_DESIGNER_TEMPLATES, DB_WARPIT_WEBCATI_BASE)
	->setReqUrl($ajaxUrl);
$designTree ->addConfig('split',"true")
	->region('center')
	//let's add the RMajax class for calling trough our manipulator
	->addConfig('RMajax',"new RMajax({
		params:{templateId:$templateId},
		url:'$ajaxUrl'
	})")
	->loaderConfig = 'preloadChildren:true'
	 ;
$designTree->baseParams = "templateId:$templateId";
//we add a function that will recreate the panel from the tree
//this will be called only the first time the tree is loaded!
$designTree->addConfig('createPanels',"function(rootNode){
		$designTree.un('load',$designTreeName.createPanels);
	//first child is the main panel!!!
	$designTree.animate = false;
	$designTree.expandAll();
	$designTree.animate = true;
	$mainPanelId.removeAll();
	if(rootNode.firstChild)
	{
		var iMax = 0;
		rootNode.firstChild.cascade( function(node){
			if(node.id != 0)
			{
				var par = Ext.getCmp('$idPreced'+ node.parentNode.id);
				i_genPanel = parseInt(node.id);
				if(i_genPanel > iMax) iMax = i_genPanel;
			   genPanel( Ext.apply( { parent:par , hollow : true },node.attributes )   );
			  //par.doLayout();
			}
		});
		i_genPanel = iMax+1;
	}

	}")
	->listeners[] = "'click':function(node){
		var panId;
		if(node.id == 0)
		{
			panId = $mainPanelId.id;
			return;
		}
		else
			panId = '$idPreced'+node.id;
		Ext.getCmp(panId).onClick();
		
		
	} " ;
echo $designTree->CreateTree();


//reload function for property grid
echo "$gridEditPanel.reload = function(pan){
	$designTree.RMajax.request({
			params:{ 
				action:'select',RMcomp:'propGrid',id:pan.designId,type:pan.panelType,parentType:pan.ownerCt.panelType
			},
			success:function(resp){
				var r = Ext.decode(resp.responseText);
				$gridEditPanel.customEditors = r.editors;
				$gridEditPanel.setSource(r.object);
			}});
		             	
};
";

//listener for propertyGrid for updating the XML
echo $gridEditPanel.".on('beforepropertychange',function(src,recId,value,oldVal){
			var target = Ext.getCmp('{$idPreced}0').selectedDesignPanel;          
               	var p = {};
               	p['attr['+recId+']'] = value;               	
               	p.id = target.designId;
               	p.type = target.panelType;
               	p.parentType = target.ownerCt.panelType;
               	p.action = 'modifyAttributes';
               	
               
               	
				 $designTree.RMajax.request({
				 	params:p,
				 	success:function(resp){
				 		Ext.getCmp('$overViewPanelId').refresh();
				 		//now let's take some action if some special properties where changed
				 		switch (recId)
				 		{
						case 'position':
						{//we recalculate height and width to accustom to new position
								if(src.height)
								{
									var h;
									if(value == 'relative')
									{
										h = (src.height / target.ownerCt.body.getHeight()*100).toFixed(2);
										$gridEditPanel.setProperty('height',h); 
										target.RMheight = h;
									}
									else if(oldVal == 'relative')
									{
										h = (src.height /100 * target.ownerCt.body.getHeight() ).toFixed(0);
										$gridEditPanel.setProperty('height',h); 
										target.RMheight = h;
									}
									
								}
								if(src.width)
								{
									var w;
									if(value == 'relative')
									{
										w = (src.width / target.ownerCt.body.getWidth()*100).toFixed(2);
										$gridEditPanel.setProperty('width',w); 
										target.RMheight = w;
									}
									else if(oldVal == 'relative')
									{
										w = (src.width /100 * target.ownerCt.body.getWidth() ).toFixed(0);
										$gridEditPanel.setProperty('width',w); 
										target.RMheight = w;
									}
									
								}
			               		target.position = value;
			               	}
			               	break;
							case 'width':
							//target.width = src.position == 'relative' ? (value /100 * Ext.getCmp('$mainPanelId').getWidth() ) : parseInt(value);
								target.width = src.position == 'relative' ? (value /100 * target.ownerCt.getWidth() ) : parseInt(value);
								target.RMwidth = value;
								target.ownerCt.doLayout();
								 target.onRMResize();
							break;
							case 'height':
								target.height = src.position == 'relative' ? (value /100 * target.ownerCt.body.getHeight() ) : parseInt(value);
								target.RMheight = value;
								target.ownerCt.doLayout();
								 target.onRMResize();
							break;
							case 'x':
							case 'y':
								var pPos = target.ownerCt.getPosition() ;
								target.setPosition(  parseFloat(src.x), parseFloat( src.y ) );
								
							break;
							case 'zindex':
							
								target.getEl().dom.style['zIndex'] = value;
							break;  
				 		}
				 	}
				 });
});";

echo "$designTreeName.on('load',$designTreeName.createPanels);
var i_genPanel = 1;
var c_genPanel = false;

var genPanel = function( config,e ){
	config = config || {};
	//we define the panel config outside new Panel so that we can adjust it later
	var tempCls = 'RM_panel_designer_basic';
	var panelConfig = {
		id: '$idPreced'+i_genPanel,
		designId: i_genPanel,
		border: true,
		panelType:config.type,
		cls: tempCls,
		padding:'0 0 0 10', 
         listeners:{beforedestroy:function(cmp){
            	if(this.dd_tmp) this.dd_tmp.destroy();
            	if(this.dd_move) this.dd_move.destroy();
              }
             }
		//EOF PanelConfig
	};
	//we add special config depending on type
	var mainPanel = Ext.getCmp('$mainPanelId');
	//the display name of the panel!!!
	var name;
	panelConfig.position = config.position || 'auto';
	if (config.parent.panelType != 2 && config.parent.panelType != 5)
	{
		config.width = config.width || 100;
		panelConfig.width = panelConfig.position == 'relative' ? config.width/100 * config.parent.body.getWidth() :   parseInt( config.width || 100);
		//the original width as stated in the XML
		panelConfig.RMwidth = config.width;		
	}
	if (config.parent.panelType != 1 )
	{
		config.height = config.height || 100;
		panelConfig.height = panelConfig.position == 'relative' ? config.height/100 * config.parent.body.getHeight() :   parseInt( config.height );
		panelConfig.RMheight = config.height;
	}
	//let's set up all the parameters we want to write to the XML at startup!!!
	var p = {};
    p['attr[width]'] = 100;
   	p['attr[height]'] = 100;
   	p['attr[position]'] = 'auto';
		                	
	switch (config.type)
	{
		//horizontal box
		case '1':
			
			name = config.name || 'Hpanel';
			Ext.apply(panelConfig,{
				layout:'hbox',
				layoutConfig: { align:'stretch' }
				
			}); 
			
		break; 
		//vertical box
		case '2':		
			
			name = 'Vpanel';
			Ext.apply(panelConfig,{
				layout:'vbox',
				layoutConfig: { align:'stretch' }
				
			}); 
		break;
		case '3':
			
			name = 'Question';
		break;
		case '4':
			name = 'Instruction';
		break;
		case '5':
			
			name = 'window';
			config.width = config.width || 20;
			config.height = config.height || 20;
			Ext.apply(panelConfig,{
				layout:'vbox',
				layoutConfig: { align:'stretch' }
				
			}); 
			panelConfig.width = panelConfig.position == 'relative' ? config.width/100 * mainPanel.getWidth() :   parseInt( config.width || 100);
			panelConfig.height = panelConfig.position == 'relative' ? config.height/100 * mainPanel.getHeight() :   parseInt( config.height );
			if(e)
			{
				var mousePos = e.getXY();
				var mainPos = Ext.getCmp('$mainPanelId').getPosition();
				var winX = mousePos[0] - mainPos[0];
				var winY = mousePos[1] - mainPos[1];
			}
			var mainPar = Ext.getCmp('wcdp_main_absolute_$templateId');
			panelConfig.x = config.x || winX || 100;
			panelConfig.y = config.y || winY || 100;
			 p['attr[x]'] = panelConfig.x;
   			p['attr[y]'] = panelConfig.y;
   			p['attr[zindex]'] = 1;
   			panelConfig.style = {zIndex: config.zindex || 1  };
   
			config.parent = Ext.getCmp('wcdp_main_absolute_$templateId');
		break; 
		case '6':
			//for answers we add 3 additional rows
			name = 'Answer';
			Ext.apply(panelConfig,{
				layout:'vbox',
				layoutConfig: { align:'stretch' }
				
			});
		break;
		case '7':
			name = 'Variable';
		break;
		case '8':
			name = 'Image';
		break;
		case '9':
			name = 'Video';
		break;
		case '10':
			name = 'Submit';
		break;
		case '11':
			name = 'Back';
		break;
		case '12':
			name = 'Exit';
		break;
		case '13':
			name = 'Help button';
		break;
		case '14':
			name = 'Go to Start';
		break;
		case '15':
			name = 'Progress bar';
		break;
		case '16':
			name = 'Welcome text';
		break;
		case '17':
			name = 'Thanks text';
		break;
		case '18':
			name = 'Audio';
		break;
		case '19':
			name = '<div onclick=\\'Ext.getCmp(this.getAttribute(\"RMid\")).editClicked = true;\\' RMid = '+panelConfig.id+'  class=\\'ux-cell-action RMicon_edit_record\\'>&nbsp;</div>Text';
		break;
		case '20':
			name = 'Answer value';
		break;
		case '21':
			name = 'Answer label';
		break;
		case '22':
			name = 'Answer control';
		break;
		case '23':
			name = 'Dial button';
		break;
		case '24':
			name = 'Hangup button';
		break;
		case '25':
			name = 'Break interview and start new';
		break;
		case '26':
			name = 'Break interview and go idle';
		break;
		case '27':
			name = 'Quota unsuccessful';
		break;
		case '28':
			name = 'Interviewer ID';
		break;
		case '29':
			name = 'Project ID';
		break;
		case '30':
			name = 'Telephone structure data';
		break;
		case '31':
			if(mainPanel.dialerTemplate) {alert('Cannot add status to dialer template!'); return; }
			name = 'Telephone status';
			mainPanel.statusTemplate = true;
		break;
		case '32':
			name = 'Language selection';
		break;
		case '33':
			name = 'Appointment option';
			mainPanel.appointmentTemplate = true;
		break;
		case '34':
			name = 'Questionnaire confirmed text';
		break;
		case '35':
			if(mainPanel.statusTemplate) {alert('Cannot add dialer to status template!'); return; }
			name = 'Predictive dialer';
			mainPanel.dialerTemplate = true;
		break;
		case '36':
			if(mainPanel.statusTemplate) {alert('Cannot add dialer to status template!'); return; }
			name = 'Automatic dialer';
			mainPanel.dialerTemplate = true;
		break;
		case '37':
			name = 'Manual dialer';
			mainPanel.dialerTemplate = true;
		break;
		case '38':
			name = 'Telephone number';
		break;
		case '39':
			name = 'Caller name';
		break;
		case '40':
			name = 'Leave text';
		break;
		case '41':
			name = 'Goto Idle CheckBox';
		break;
		default:
			name = config.text;
		break;
	}
	//in the 3 layouts panels and answer panel we set title in other (non containers) we set html
	if(config.type == 1 || config.type == 2 || config.type == 5 || config.type == 6)
	{
		panelConfig.title = name+' '+ i_genPanel;
	 } 
	 else 
	 {
	 	panelConfig.html = name+' '+ i_genPanel;
	 }
	
	//we add a click event on the panel body! (later in afterrender)
    //here we add a class to mark the selected panel
    //we add a resizable to make it resizable
    //we show the property grid for this particular element
    //we undo all above for the previous selected item!
	panelConfig.onClick = function(){
						var prevSelected = Ext.getCmp('$mainPanelId').selectedDesignPanel;
						if(prevSelected)
		             	{
		             		if(prevSelected.id == this.id)
		             		{ 
		             			//check if the edit button was clicked and open z editor!
		             			if(this.editClicked) 
		             			{
		             				var cmp = this;
		             				var w = new Ext.Window({
		             					title:'Edit text',
		             					height:300,
		             					width:550,
		             					layout:'fit',
		             					modal:true,
		             					items: [{
		             						xtype:'htmleditor',
		             						value: $gridEditPanel.getSource().text,
		             						ref: 'htmlEditor'
		             					}],
		             					buttons:[
		             					{
		             						text:'Save',
		             						handler: function(){
		             							console.log(cmp.id);
		             							var target = Ext.getCmp( cmp.id );
		             							var p = {};
							                	p['attr[text]'] = w.htmlEditor.getValue();
							                	
							                	p.id = target.designId;
								               	p.type = target.panelType;
								               	p.parentType = target.ownerCt.panelType;
							                	p.action = 'modifyAttributes';
							                	
												 $designTree.RMajax.request({
												 	params:p,
												 	success:function(resp){
												 		var r = Ext.decode(resp.responseText);
												 		if(r.success)
												 			$gridEditPanel.setSource(r.object);
												 	}
												 });
												 w.close();
		             						}
		             					},{
		             						text:'Cancel',
		             						handler: function()
		             						{
		             							w.close();
		             						}
		             					}]
		             				});
		             				w.show();
		             			}
		             			return;
		             		}
		             		//we deselect previous panel if it exists!
		             		prevSelected.removeClass('RM_panel_selected');
		             		prevSelected.resizeClass.destroy();
		             		if(prevSelected.dd_move) prevSelected.dd_move.destroy();
		             	//	prevSelected.getEl().removeClass('RM_panel_body_selected');
		             	}
		             	var pan = Ext.getCmp( this.id )  ;
		             	//we refresh the attributes panel
						//we make an ajax call to get the property object!
						
						$gridEditPanel.reload(pan);
						$gridStyle.getStore().reload({ params:{id:pan.designId } });
						
		             	//we add the resizable for this panel
		             	pan.resizeClass = new Ext.Resizable(pan.getEl(),{
							dynamic:true,constrainTo:config.parent.getEl(),
							minWidth: 50,minHeight: 50,
							handles: config.parent.panelType == 1 ? 'e' : ( config.parent.panelType == 2 || config.parent.panelType == 5 ? 's' :'all' ),
							//the function  
							resizeElement: function() {
			                    var box = this.proxy.getBox();
			                    pan.updateBox(box);
			                    if (pan.layout) {
			                        pan.doLayout();
			                    }
			                    return box;
		                },
		                //we add a listener so that we can update the XML
		                listeners:{'resize':function(res,w,h){
		                	var target = Ext.getCmp( res.el.id );
		                	target.width = w;
		                	target.height = h;
		                	target.ownerCt.doLayout();
		                	var p = {};
		                	p['attr[width]'] = target.position == 'relative' ? (w / target.ownerCt.getWidth()*100).toFixed(2) : w;
		                	p['attr[height]'] = target.position == 'relative' ? (h / target.ownerCt.body.getHeight()*100).toFixed(2) : h;
		                	target.RMwidth = p['attr[width]'];
		                	target.RMheight = p['attr[height]']
		                	if(target.panelType == 5)
		                	{ //if window is rezised we also adjust x and y
		                		var pos = target.getPosition(true);
		                		p['attr[x]'] = pos[0];
		                		p['attr[y]'] = pos[1];
		                	
		                	}
		                	p.id = target.designId;
			               	p.type = target.panelType;
			               	p.parentType = target.ownerCt.panelType;
		                	p.action = 'modifyAttributes';
		                	
							 $designTree.RMajax.request({
							 	params:p,
							 	success:function(resp){
							 		var r = Ext.decode(resp.responseText);
							 		if(r.success)
							 			$gridEditPanel.setSource(r.object);
							 	}
							 });
							 target.onRMResize();
		                	
		                } }
		                }); //EO ext.Resizable
		             	//we add a DDproxy to this elemnt to make it dragable...jeeeej :D
		             				this.dd_move = new Ext.dd.DragSource(this.el,{ddGroup: 'window_move_designer'});
						Ext.apply(this.dd_move,{
		             		onStartDrag: function(x, y) { 
		             				//c_genPanel = true;
		             			
							        var dragEl = $('.x-panel',this.getDragEl() )  ;
							        var el = Ext.getCmp(this.id);
							       // dragEl.update(''  );
							       dragEl.removeClass('RM_panel_designer_basic');
							       dragEl.css('top',20);
							       dragEl.css('left',0);
							    }
		             	});
		             	
						//we add a class to mark the selected panel
						pan.addClass('RM_panel_selected');
						Ext.getCmp('$mainPanelId').selectedDesignPanel = pan;
						//tell the tree to select this node
						$designTree.getNodeById(this.designId).select();
						
						this.editClicked = false;
						
						
	}
	
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!EO onClick !!!!!!!!!!!!!!!!!!!!!!!!!
	var temp; // the variable that will hold this panel
	   // setup drop target after we're rendered  
	panelConfig.afterRender = function() {
			Ext.Panel.prototype.afterRender.apply(this, arguments);
			
			this.dropTarget = this.body;
			
			
			var dT = this.body;
			
		      		this.getEl().on('click',function(e){ 
		             	 Ext.getCmp( this.id ).onClick();
						//stopPropagation so parents don't recive the click events!
						e.cancelBubble = true;
						if (e.stopPropagation) e.stopPropagation();
				
             	});//EOF click listener
             //if hollow == true then we don't call the database to add (usualy at startup when we rebuild from XML)
             if(config.hollow !== true)
             	$designTree.getRootNode().reload(function(){ $designTree.animate = false;  $designTree.expandAll(); $designTree.animate = true; temp.onClick(); } );
           
           
			//EO after render
		};
	//a function that is called when a panel is resized! It will adjust it's children, those that have a % width or height
	panelConfig.onRMResize = function(){
		
		Ext.each(this.items.items,function(item){
				if(this.panelType == 1)
				{
					if(item.position == 'relative')
					{
						item.width = this.getWidth()* item.RMwidth/100 ;
					}
				}
				else 
				{
					if(item.position == 'relative')
					{
						item.height = this.body.getHeight()* item.RMheight/100 ;
					}
				}
				
				item.onRMResize(); 
		},this);
		this.doLayout();
	}
	panelConfig.bubbleEvents=[];
	
	temp = new Ext.Panel(panelConfig);
	if(config.hollow !==true)
	{
		p.action = 'insertPanel';
		p.parent = config.parent.designId;
		p.id = temp.designId;
		p.type = config.type;
		p.itemIndex = config.itemIndex;
		//if the object is a template, this is the ID of that template!
		p.objectTemplate = config.id_template;
		//we modify THE xml
		 $designTree.RMajax.request({
		 	params:p,
		 	success: function(){
		 		if(config.refreshOverview == true)
				{
					Ext.getCmp('$overViewPanelId').refresh();
				}
					 	
		 	}
		 });
		
	}
	if(config.itemIndex || config.itemIndex === 0)
		config.parent.insert( config.itemIndex,temp);
	else
		config.parent.add ( temp);
	config.parent.doLayout();
	i_genPanel++;
	//if we added answer we add odd and even rows with answer objects!!!
	if(config.type == 6 && config.hollow !== true)
	{
		
		var legR = genPanel( { parent:temp,type:'1',height:34,name:'Legend row',hollow:true } );
		
		genPanel( { parent: legR,type:'20',width:33,hollow:true } );
		genPanel( { parent: legR,type:'21',width:33,hollow:true } );
		genPanel( { parent: legR,type:'22',width:33,hollow:true } );
		
		var oddR = genPanel( { parent:temp,type:'1',height:33,name:'Odd rows',hollow:true } );
		
		genPanel( { parent: oddR,type:'20',width:33,hollow:true } );
		genPanel( { parent: oddR,type:'21',width:33,hollow:true } );
		genPanel( { parent: oddR,type:'22',width:33,hollow:true } );
		
		var evenR = genPanel( { parent:temp,type:'1',height:33,name:'Even rows',hollow:true } );		
		
		genPanel( { parent: evenR,type:'20',width:33,hollow:true } );
		genPanel( { parent: evenR,type:'21',width:33,hollow:true } );
		genPanel( { parent: evenR,type:'22',width:33,hollow:true } );
	}
	
	return temp;
};
";

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! EO genPanel !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


//loading a special class for droping node
if(!$_SESSION['loadedPlugin']['designerDropTarget'])
{
	$_SESSION['loadedPlugin']['designerDropTarget'] = true;

	//<script>
echo 	"Ext.ux.DesignDropTarget = Ext.extend(Ext.dd.DropTarget,{
		calculatePos:function(e,target,node)
		{
			if(node && node.node && node.node.cssDrag) return;
			var t = $('#'+ target.id);
			if(e.xy[0] - t.offset().left < 15)
				return 'left';
			if(e.xy[1] - t.offset().top < 15)
				return 'top';
			if( - e.xy[0] + t.offset().left + t.width() < 15)
				return 'right';
			if( -e.xy[1] + t.offset().top + t.height() < 15)
				return 'bottom';
		},
		isDropAllowed: function(cmp,dragSource,node,nearBorder)
		{
				if(dragSource || node.node.elementDrag)
				{
					//var cmp = Ext.getCmp( target.id );
					if(nearBorder)
					{
						cmp = cmp.ownerCt;
						if( !cmp || ((nearBorder == 'top' || nearBorder == 'bottom') && cmp.panelType == 1) ||  (nearBorder == 'left' || nearBorder == 'right') && cmp.panelType == 2)
							return Ext.dd.DropZone.prototype.dropNotAllowed;
					}
						//if we are dragging an object e.g hbox, instructions etc
						
						var attr;	
						if(node.node)
							attr = node.node.attributes;
						else 
						{
							var drCmp = dragSource;
							attr = { type : drCmp.panelType };
							//we check if target is child of...umm...draged item!
							var ch = drCmp.findBy(function(child){
								if(child.id == cmp.id)
									return true;
							} );
							if(ch.length) return Ext.dd.DropZone.prototype.dropNotAllowed;
						}
							
						{
							if( cmp.panelType == 1 || cmp.panelType == 2 || cmp.panelType == 5 || attr.type == 5)
							{
								if(cmp.panelType != attr.type)
									{
										return Ext.dd.DropZone.prototype.dropAllowed;
									}
									else
									{
										return Ext.dd.DropZone.prototype.dropNotAllowed;
									}
							}
							else 
								return Ext.dd.DropZone.prototype.dropNotAllowed;
						}	
					}		
						return Ext.dd.DropZone.prototype.dropAllowed;
		}
		});";
}
echo "var $mainPanelId = new Ext.Panel({
	
	bubbleEvents:['add'],//to cancel remove event bubbing!
	id:'$mainPanelId',
	//our XML id
	designId: 0,
	panelType:2,
	title:'Objects',
	//iconCls:'icon_build_questionnare',	
	//closable: true,
	autoScroll:true,
	region: 'center',
	anchor:'100% 100%',
	bodyStyle:{
              backgroundColor: '#000000'
           },
    layout: 'vbox',
    layoutConfig: { align:'stretch' },
    //function to calculate if we drag or drop near a border
	
	// setup drop target after we're rendered
	afterRender:function() {
		Ext.Panel.prototype.afterRender.apply(this, arguments);
		
		this.dropTarget = this.body;
		//drop target for adding items from tree
		this.dd_tmp = new Ext.ux.DesignDropTarget(this.dropTarget, {
			// must be same as for tree
			ddGroup:'t2div-webcati'
			// what to do when user drops a node here
			,notifyDrop:function(dragSource, e, node) { 
			var target = e.getTarget('div.RM_panel_designer_basic');
			if(target)
			{
				$('#'+ target.id ).removeClass('RM_panel_drag_over'+this.curNearBorder);
				if(this.curNearBorder == 'right')
								{
									$('.x-panel-body',this.curTarget ).css('width','+=9');
									
								}
				else if(this.curNearBorder == 'bottom')
					$('.x-panel-body',this.curTarget ).css('height','+=9');
				
				
				this.curTarget = null;
				var cmp = Ext.getCmp( target.id );	
				
				
						//if(node.node)
						{	//if we are dragging an object e.g hbox, instructions etc
							if(dragSource.ddGroup == 'window_move_designer' || node.node.elementDrag)
							{
								var nearBorder = this.calculatePos(e,target);
								if(nearBorder)
								{
									var itemIndex = cmp.ownerCt.items.indexOf(cmp);
									cmp = cmp.ownerCt;
									if( ((nearBorder == 'top' || nearBorder == 'bottom') && cmp.panelType == 1) ||  (nearBorder == 'left' || nearBorder == 'right') && cmp.panelType == 2)
										return false;
									if(nearBorder == 'right' || nearBorder == 'bottom')
										itemIndex++; 
										
								}
							if(node.node)
							{
								attr = node.node.attributes
							}
							else 
							{
								var drCmp = Ext.getCmp( dragSource.id);
								attr = { type : drCmp.panelType,id:drCmp.designId,parentId:drCmp.ownerCt.designId };
								//check if target is child of dragged element (dragging in on itself :D)
								var ch = drCmp.findBy(function(child){
										if(child.id == cmp.id)
											return true;
									} );
									if(ch.length) return false;
							}
							if( cmp.panelType == 1 || cmp.panelType == 2 || cmp.panelType == 5 || attr.type == 5)
								{
									if(cmp.panelType == attr.type)
										return false;
									
								if(node.node)
								{
									c_genPanel = false;		
									
														
										 genPanel( { parent: cmp,id_template:attr.id_template, 
										 	type:attr.type,text:node.node.text,
										 	itemIndex:itemIndex },e  );
						  				//cmp.doLayout();
						  				
							  			
							  			//alert('child - drop');
							  	}
								else//drop of a panel - we must reoerder
								{
									$designTree.RMajax.request({
										params:{
											action:'movePanel',
											newParent: cmp.designId,
											parent: attr.parentId,
											id: attr.id,
											itemIndex:itemIndex
										},
										success:function()
										{
											$mainPanelId.selectedDesignPanel = null; //so that the id is not recognized and the node can be clicked again!
											$designTreeName.on('load',$designTreeName.createPanels);
											$designTree.root.reload();
										}
									})
								}
							  	
								return true;
								}
							}
							else if(node.node.cssDrag)
							{
								if(node.node.attributes.leaf == 1)
								{
									$designTree.RMajax.request({params:{
										action:'addClass',
										id:cmp.designId,
										classId:node.node.id
										},success:function(){ 
										$gridStyle.getStore().reload(); }
									});
									return true;
								}
							}
						}
						return false;
			}
			
			
				if(node.node)
				{
					if( node.node.elementDrag)
					{	
						//vbox is not allowed in the main panel!
						if(node.node.attributes.type == 2)
							return false;	
						
							c_genPanel = false;		
							var qdwwc = Ext.getCmp('$mainPanelId');
							genPanel( { parent: qdwwc ,id_template:node.node.attributes.id_template, type:node.node.attributes.type,text:node.node.text },e );
					}
					else if(node.node.cssDrag)
							{
								if(node.node.attributes.leaf == 1)
								{
									$designTree.RMajax.request({params:{
										action:'addClass',
										id:0,
										classId:node.node.id
										}
									});
									return true;
								}
							}
	  			}
	  			else 
	  			{
	  				var cmp = Ext.getCmp(dragSource.id);
						if(cmp.panelType == 5)
						{	
							var mousePos = e.getXY();
							var mainPos = Ext.getCmp('$mainPanelId').getPosition();
							var winX = mousePos[0] - mainPos[0];
							var winY = mousePos[1] - mainPos[1];
							cmp.setPosition(winX,winY);
							
							//let's write the new coordinates
							var p = {};
		                	p['attr[x]'] = winX;
		                	p['attr[y]'] = winY;
		                	p.id = cmp.designId;
			               	p.type = cmp.panelType;
			               	p.parentType = cmp.ownerCt.panelType;
		                	p.action = 'modifyAttributes';
							 $designTree.RMajax.request({
							 	params:p,
							 	success:function(resp){
							 		var r = Ext.decode(resp.responseText);
							 		if(r.success)
							 			$gridEditPanel.setSource(r.object);
							 	}
							 });
							return true;
						}
						//false throws an error in IE...probably becouse of wierd created proxy!
						return true;
	  			}		
				
				
				return true;
			} // eo function notifyDrop
			,notifyOver:function(dragSource,e,node){ 
					
					var target = e.getTarget('div.RM_panel_designer_basic');
					
					if(target && this.curTarget)
					{
						var nearBorder = this.calculatePos(e,target,node) || '';
						if(target.id == this.curTarget.id && nearBorder == this.curNearBorder)
						{
							
						}
						else
						{
							
							$('#'+ target.id ).addClass('RM_panel_drag_over'+nearBorder);
							if(nearBorder)
								if(nearBorder == 'right')
								{
									$('.x-panel-body',target ).css('width','-=9');
								}
								else if(nearBorder == 'bottom')
									$('.x-panel-body',target ).css('height','-=9');
								if(this.curNearBorder == 'right')
								{
									$('.x-panel-body',this.curTarget ).css('width','+=9');
								}
								else if(this.curNearBorder == 'bottom')
									$('.x-panel-body',this.curTarget ).css('height','+=9');
									
							$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over'+this.curNearBorder);
						}
					}		
					else if(target)
					{
						var nearBorder = this.calculatePos(e,target,node) || '';
						$('#'+ target.id ).addClass('RM_panel_drag_over'+nearBorder);
						
						if(nearBorder == 'right')
								{
									$('.x-panel-body',target ).css('width','-=9');
								}
						else if(nearBorder == 'bottom')
							$('.x-panel-body',target ).css('height','-=9');
						
					}
					else if( this.curTarget )
					{
						
						$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over'+this.curNearBorder);
						
						if(this.curNearBorder == 'right')
								{
									$('.x-panel-body',this.curTarget ).css('width','+=9');
								}
						else if(this.curNearBorder == 'bottom')
							$('.x-panel-body',this.curTarget ).css('height','+=9');
						
					}
				
					this.curTarget = target;
					this.curNearBorder = nearBorder;
					
					if(target)
					{
						return this.isDropAllowed( Ext.getCmp( target.id),dragSource.ddGroup == 'window_move_designer' ? Ext.getCmp(dragSource.id):false,node,nearBorder );
						//if(node.node)
						
					}
					if(node.node)
					{
						if(node.node.attributes.type == 2)
							return Ext.dd.DropZone.prototype.dropNotAllowed;
						return Ext.dd.DropZone.prototype.dropAllowed;
					}
					else 
					{
						var cmp = Ext.getCmp(dragSource.id);
						if(cmp.panelType == 5)
							return Ext.dd.DropZone.prototype.dropAllowed;
						return Ext.dd.DropZone.prototype.dropNotAllowed;
					}
				
			},
			notifyOut :function(dds,e,node)
					{
						if(this.curTarget)
							$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over'+this.curNearBorder);
						this.curTarget = null;
					}
		});
		//drop target from moving objects around
		this.dd_move = new Ext.dd.DropTarget(this.dropTarget, {
			// must be same as for dragSource on click
			//zhis is very sthrange!
			//notify drop is always called from z other dropTarget! what a wierd thing...
			ddGroup:'window_move_designer'});
		
		
	} // eo function afterRender
	, listeners:{beforedestroy:function(cmp){
            	if(this.dd_tmp) this.dd_tmp.destroy();
            	if(this.dd_move) this.dd_move.destroy();
              }
              ,show:function(){
              if($mainPanelId.RMchanged)
              {
              	$mainPanelId.selectedDesignPanel.id = -1; //so that the id is not recognized and the node can be clicked again!
				$designTreeName.on('load',$designTreeName.createPanels);
				$designTree.root.reload();
				}
				else
              	this.doLayout();
              $mainPanelId.RMchanged = false;
              }
             }
});
";
//the tree with web cati objects
$treeWebCatiObjectName = "TreeWebCatiObjects_".$templateId;
$treeWebCatiObject = new MakeTree($treeWebCatiObjectName);
$treeWebCatiObject->SetTable(WC_DESIGNER_ELEMENTS, DB_WARPIT_WEBCATI_BASE, $treeWebCatiObjectName);
$treeWebCatiObject->SetRootVisible('true', 'Webcati objects')
	  ->activateDD('t2div-webcati')
	  ->setTextPadding('6px')
	  ->addConfig('containerScroll',"true")
	  ->addConfig('autoScroll',"true")
	  ->addConfig('border',"false")
	  ->addConfig('region',"'north'")
	  ->addConfig('height',"300")
	  ->addConfig('split',"true")
	  ->listeners[] = "startdrag : function(t,n){ n.elementDrag = true;  } " ;
$treeWebCatiObject->baseParams = "attr:'type,id_template'";
echo $treeWebCatiObject->CreateTree();




?>

var <?php echo $uniqeTab ?> = new Ext.Panel({

	id:'<?php echo $uniqeTab ?>',
	title:'Designer - <?php echo $_POST['name'] ?>',
	defaults:{split:true,border:false},
	iconCls:'RMicon_designer',
	layout:'border',
	border: false,
	closable:true,
	items:[
		
		new Ext.Panel({
			defaults:{border:true},
			iconCls:'icon-webcati-tab',
			layout:'border',
			width:230,
			border: false,
			region: 'west',
			items: [
				<?php echo $treeWebCatiObjectName; ?>
				,
				<?php echo $designTreeName; ?>
				,
				<?php echo "{
					xtype:'tabpanel',
					title:'Settings',
					activeItem:0,
			        height: 250,
			        region:'south',
			        split:true,
					items:[
					$gridEditPanel,$gridStyle,$gridBody,$gridControls
					]
					}";?>
				
			
			]
		}),
		//we create a wrapper panel with absolute layout to attach windows on it		
		{
		<?php echo "id:'wcdp_main_absolute_$templateId',
		designId:0,
		xtype:'tabpanel',
		bubbleEvents:[],//to cancel remove event bubbing!
		region:'center',
		activeTab:0,
		items : [$mainPanelId,
		{
		
		title:'Overview',
		layout:'fit',
		items:
		new Ext.Panel({
			id:'$overViewPanelId',
			refresh: function(){
				if(this.rendered)
				Ext.Ajax.request({
					scope:this,	
					scripts:true,
					url:'survey/preview.php',
					params:{
						templateId:$templateId,
						//id_language:46,
						//id_user:5,
						preview:1,
						//projectId:173,
						questionId:'fake'
						
					},
					success:function(r){
						this.update(r.responseText,true);
					}
				});
			}
			/*,autoLoad:
				{
					
					scripts:true,
					url:'survey/preview.php',
					params:{
						templateId:$templateId,
						//id_language:46,
						//id_user:5,
						preview:1,
						//projectId:173,
						questionId:'fake'
						
					}
				}*/
			,listeners:{
				
              afterrender:function(){
              	this.refresh();
              	this.ownerCt.ovCh = this;
              	lastActiveDesignerOverviewWindow = this;
              	
              }
			}
			
		}),
		afterRender:function() {
		Ext.Panel.prototype.afterRender.apply(this, arguments);
		
		this.dropTarget = this.body;
		//drop target for adding items from tree
		this.dd_tmp = new Ext.ux.DesignDropTarget(this.dropTarget, {
			// must be same as for tree
			ddGroup:'t2div-webcati'
			// what to do when user drops a node here
			,notifyDrop:function(dragSource, e, node) { 
				var target =  e.getTarget('td.RM_panel_designer_basic$templateId');
				if(target)
				{
					$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over_overview');
					this.curTarget = null;
					var cmp = Ext.getCmp('$idPreced' + target.id.split('_')[1]);	
					
							{	//if we are dragging an object e.g hbox, instructions etc
								if(dragSource.ddGroup == 'window_move_designer' || node.node.elementDrag)
								{
									if(dragSource.ddGroup == 'window_move_designer' || node.node.elementDrag)
									{
										var nearBorder = this.calculatePos(e,target);
										if(nearBorder)
										{
											var itemIndex = cmp.ownerCt.items.indexOf(cmp);
											cmp = cmp.ownerCt;
											if(!cmp || ((nearBorder == 'top' || nearBorder == 'bottom') && cmp.panelType == 1) ||  ((nearBorder == 'left' || nearBorder == 'right') && cmp.panelType == 2) )
												return false;
											if(nearBorder == 'right' || nearBorder == 'bottom')
												itemIndex++; 
												
										}
									}
									if(node.node)
									{
										attr = node.node.attributes
									}
									else 
									{
										var drCmp = Ext.getCmp( '$idPreced' + dragSource.id.split('_')[1] );
										attr = { type : drCmp.panelType,id:drCmp.designId,parentId:drCmp.ownerCt.designId };
										//check if target is child of dragged element (dragging in on itself :D)
										var ch = drCmp.findBy(function(child){
												if(child.id == cmp.id)
													return true;
											} );
											if(ch.length) return false;
									}
									
									if( cmp.panelType == 1 || cmp.panelType == 2 || cmp.panelType == 5 || attr.type == 5)
									{
										if(cmp.panelType == attr.type)
											return false;
										if(node.node)
										{
											c_genPanel = false;		
											
												 genPanel( { parent: cmp,id_template:attr.id_template, 
												 	type:attr.type,text:node.node.text,
												 	itemIndex:itemIndex,refreshOverview:true },e  );
								  				//Ext.getCmp('$overViewPanelId').refresh();
									  	}
										else//drop of a panel - we must reoerder
										{
											$designTree.RMajax.request({
												params:{
													action:'movePanel',
													newParent: cmp.designId,
													parent: attr.parentId,
													id: attr.id,
													itemIndex:itemIndex
												},
												success:function()
												{
													$mainPanelId.RMchanged = true;
													Ext.getCmp('$overViewPanelId').refresh();
												}
											})
										}
										
										return true;
									}
									
								}
								else if(node.node.cssDrag)
								{
									var specStyle;
									if(cmp.panelType == 10 || cmp.panelType == 11 || cmp.panelType == 25 || cmp.panelType == 42)//for back or submit button!
									{
										if(e.getTarget('input')) //if we drag over the button we add style for the button...otherwise for the object!
										{
											specStyle = 'input';
										}
									}
									else if(cmp.panelType == 15 && (e.getTarget('div.RMprogressbar_text') || e.getTarget('td.RMprogressbar_text') ))
									{
										specStyle = 'text';
									}
									else if(cmp.panelType == 49 && e.getTarget('textarea') )
									{
										specStyle = 'text';
									}
									
									if(node.node.attributes.leaf == 1)
									{
										$designTree.RMajax.request({params:{
											action:'addClass',
											id:cmp.designId,
											specStyle: specStyle,
											classId:node.node.id
											},success:function(){ $gridStyle.getStore().reload();
																Ext.getCmp('$overViewPanelId').refresh();	
											}
										});
										
										
										
										return true;
									}
								}
							}
							return false;
				}
				
			
				
				
				return true;
			} // eo function notifyDrop
			,notifyOver:function(dragSource,e,node){ 
					
					var target = e.getTarget('td.RM_panel_designer_basic$templateId');
					if(target && this.curTarget)
					{
						var nearBorder = this.calculatePos(e,target,node) || '';
						if(target.id == this.curTarget.id && nearBorder == this.curNearBorder)
						{
							
						}
						else
						{
							
							$('#'+ target.id ).addClass('RM_panel_drag_over_overview'+nearBorder);
								
							$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over_overview'+this.curNearBorder);
							
						}
					}		
					else if(target)
					{
						var nearBorder = this.calculatePos(e,target,node) || '';
						$('#'+ target.id ).addClass('RM_panel_drag_over_overview'+nearBorder);
						
						
						
					}
					else if( this.curTarget )
					{
						
						$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over_overview'+this.curNearBorder);
						
					}
					this.curTarget = target;
					this.curNearBorder = nearBorder;
					
					if(target )	return this.isDropAllowed(Ext.getCmp('$idPreced' + target.id.split('_')[1]),dragSource.ddGroup == 'window_move_designer' ? Ext.getCmp('$idPreced' + dragSource.id.split('_')[1]) : false ,node,nearBorder);//Ext.dd.DropZone.prototype.dropAllowed;
			},
			notifyOut :function(dds,e,node)
					{
						if(this.curTarget)
							$('#'+ this.curTarget.id ).removeClass('RM_panel_drag_over_overview'+this.curNearBorder);
						this.curTarget = null;
					}
		});
		
		this.getEl().on('click',function(e){ 
		             	 var target = e.getTarget('td.RM_panel_designer_basic$templateId');
		             	 if(target)
		             	 {
							if(this.prevSelected)
							{
								if(target.id == this.prevSelected.id) return;
								$('#'+ this.prevSelected.id ).removeClass('RM_panel_selected_overview');
							}
							$('#'+ target.id ).addClass('RM_panel_selected_overview');
							
							this.prevSelected = target;
							
							Ext.getCmp('$idPreced' + target.id.split('_')[1]).onClick();
						}
						if(this.dd_moveSrc) this.dd_moveSrc.destroy();
						this.dd_moveSrc = new Ext.dd.DragSource(target,{ddGroup: 'window_move_designer'});
						Ext.apply(this.dd_moveSrc,{
		             		onStartDrag: function(x, y) { 
		             				//c_genPanel = true;
							        var dragEl = $('.x-panel',this.getDragEl() );
							        var el = Ext.getCmp(this.id);
							       // dragEl.update(''  );
							       dragEl.removeClass('RM_panel_designer_basic');
							       dragEl.css('top',20);
							       dragEl.css('left',0);
							    }
		             	});
             	});
		//drop target from moving objects around
		this.dd_moveTrg = new Ext.dd.DropTarget(this.dropTarget, {
			// must be same as for dragSource on click
			//zhis is very sthrange!
			//notify drop is always called from z other dropTarget! what a wierd thing...
			ddGroup:'window_move_designer'});
		
		
	} // eo function afterRender
	, listeners:{beforedestroy:function(cmp){
            	if(this.dd_tmp)
					this.dd_tmp.destroy();
				if(this.dd_moveTrg) this.dd_moveTrg.destroy();
				if(this.dd_moveSrc) this.dd_moveSrc.destroy();
              },show:function(){
              	if(this.ovCh) 
              	{
              		this.ovCh.refresh();
              		lastActiveDesignerOverviewWindow = this.ovCh;
              	}
              }
             }
		}
	
		], 
		//add a tbar for deleting!
		tbar:[{
		text:'Delete',
		iconCls:'icon_red_delete',
		handler:function(){
			var prevSelected = Ext.getCmp('$mainPanelId').selectedDesignPanel;
             	if(prevSelected)
             	{
             			var t = prevSelected.panelType;
             			if(t == 35 || t == 36 || t == 37)
             				Ext.getCmp('$mainPanelId').dialerTemplate = false;
             			if(t == 31)
             				Ext.getCmp('$mainPanelId').statusTemplate = false;
             			if(t == 33)
             				Ext.getCmp('$mainPanelId').appointmentTemplate = false;
						$designTree.RMajax.request({
							params:{ action:'remove',
							parent: prevSelected.ownerCt.designId, id:prevSelected.designId,type:1
						}, success:function(resp){
							$designTree.getRootNode().reload(function(){ $designTree.animate = false;  $designTree.expandAll(); $designTree.animate = true; } );
             				if(Ext.getCmp('wcdp_main_absolute_$templateId').getActiveTab().items.items[0].id == '$overViewPanelId')
             					Ext.getCmp('$overViewPanelId').refresh();
             				$gridEditPanel.getStore().removeAll();
             				$gridStyle.getStore().removeAll();
						 }
						});
					var parTmp = prevSelected.ownerCt;
             		parTmp.remove(prevSelected);
             		parTmp.doLayout();
             		delete Ext.getCmp('$mainPanelId').selectedDesignPanel;
             		
             	}
		}
	},{
		text:'Use as',
		iconCls:'RMicon_organizer_edit',
		handler:function(){
			//show a window to select the template as a default
			var items = new Array();
			if(Ext.getCmp('$mainPanelId').dialerTemplate)
			{
				items.push( {xtype:'checkbox',fieldLabel:'Dialer default',name:'selectTypeSp[7]',inputValue:7 } );
			 }
			 else if( Ext.getCmp('$mainPanelId').statusTemplate)
			 {
			 	items.push( {xtype:'checkbox',fieldLabel:'Status default',name:'selectTypeSp[8]',inputValue:8 } );
			 }
			 else if( Ext.getCmp('$mainPanelId').appointmentTemplate)
			 {
			 	items.push( {xtype:'checkbox',fieldLabel:'Appointment default',name:'selectTypeSp[9]',inputValue:9 } );
			 }
			 else 
			 {
			 	items.push({xtype:'checkbox',fieldLabel:'System default',name:'selectDefault',inputValue:99 });
				";
				$db->ChangeDatabase(DB_WARPIT_WEBCATI);
				$stSQL = $db->get('_ShowAsTypes');
				foreach ($stSQL as $stTmp) {
					$stArr[$stTmp['id']] = $stTmp['showAs'];
				}
				
				$sql = "SELECT * FROM _QuestionTypes";
				$res = $db->SQLexecute($sql);
				while ($row = $db->fetchAssoc($res))
				{
					$q= Question::createQuestion($row['id']);
					$st= $q->supportedShowTypes();
					foreach ($st as $showType) {
						$name = $row['name'].' - '.$stArr[$showType];
						echo "items.push( {xtype:'checkbox',fieldLabel:'".$name."',name:'selectType[{$row['id']}0{$showType}01]',inputValue:{$row['id']}0{$showType}01});\n";
						if($row['id'] == 3 && $showType == 4)
							echo "items.push( {xtype:'checkbox',fieldLabel:'multi ".$name."',name:'selectType[{$row['id']}0{$showType}01]',inputValue:{$row['id']}0{$showType}01});\n";
						
					}
					
					//echo "items.push( {xtype:'checkbox',fieldLabel:'".$row['name']."',name:'selectType[{$row['id']}]',inputValue:{$row['id']}});";
				}
			echo "
			 }
			 
			  items.push( { xtype:'fieldset',title:'Use answer template for',items: [{ xtype:'radio',fieldLabel:'Design',name:'ansType',inputValue:6,checked:true },
			  { xtype:'radio',fieldLabel:'Control',name:'ansType',inputValue:7 }] } );
			 
			 items.push( { xtype:'fieldset',title:'Use for device',items: [{ xtype:'radio',fieldLabel:'Default',checked:true,name:'deviceDesktop',inputValue:0 },
			  { xtype:'radio',fieldLabel:'Mobile',name:'deviceDesktop',inputValue:2 }] } );
			 
			new Ext.Window({
				layout:'form',modal:true,
				width:300,
				
				title:'Set as default for',
				items:[
				{xtype:'form',id:'selectDefaultTempForm',frame:true,labelWidth:200,
				items: items }],
	buttons:[{
		text:'OK',
		handler:function(){
			Ext.getCmp('selectDefaultTempForm').getForm().submit({
				url:'$ajaxDesUrl',
				params:{
					action:'templateDefaults',
					templateId:'$templateId'
				},
				success: function(){
					this.ownerCt.ownerCt.close();
				},scope:this
			});
		}
	}]
	}).show();
		}
	},
	//button for making this template as a object
	{
		text: 'Export',
		handler:function(){
		Ext.Msg.prompt('Create object','Object name',function(btn,val){
			if(btn == 'ok')
			{
				$designTree.RMajax.request({params:{action:'createObject',text:val},
				success:function(){
					$treeWebCatiObject.getLoader().load( $treeWebCatiObject.getNodeById('52'));
				}
				});
			}
		}
		,this,false,'{$_POST['name']}');
		}
	}
	
	
	]
		}
	
	 ]
			
});

mainTabPanel.add($uniqeTab)";
if(!$_POST['uniqueNotShow'])
	echo  ".show();";?>