<?php

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");


include_once(PATH_TO_ROOT."_class/class.Extjs_tree.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");


$tabId = $_POST['uniqueTabId'];
$fieldLng = 250;


//the type! 0 is for data, 1 is for script
if($_POST['scriptExport'])
{
	$scriptExport = 1;
	$title = 'Export documents';
	$inclWebrecoded = "questions";
	$expControl = "typeSelect == 1";
}
else
{
	$scriptExport = 0;
	$title = 'Export data';
	$inclWebrecoded = "data";
	$expControl = "expSelect == 0";
}
	$projectId = $_POST['id_project'];


	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

	//let's get the default language of this project!
	$res = $db->SQLexecute("SELECT proj_name,language FROM _Projects WHERE id = $projectId");
	if(!$row = $db->fetchRow($res))
	{
		//maybe the project was deleted ?
		echo "removeSession('$tabId'); alert('Error! Cannot find project!');";
		return;
	}

	$tableName = $row[0];

	$defLng = $row[1];


	$treeWC = new MakeTree($tabId.'_tree');
	$treeWC->setMainTable($tableName,DB_WARPIT_WEBCATI)
	//->SetRootVisible("true","Questions")
	->region('west')
	->setWidth('200')
	->addConfig('enableDD','true')
	//we override the onInitDrag and disable node selection (this way our fields don't lose focus!)
	->addConfig('dragConfig',"{  onInitDrag : function(e){
        var data = this.dragData;
        //this.tree.getSelectionModel().select(data.node);
        this.tree.eventModel.disable();
        this.proxy.update(\"\");
        data.node.ui.appendDDGhost(this.proxy.ghost.dom);
        this.tree.fireEvent(\"startdrag\", this.tree, data.node, e);
    },ddGroup:'wcqbGroup' }  ")
	->baseParams = "checked:'leaf',id_project:$projectId";
	$treeWC->setReqUrl ('webcati/_ajax/ExImportData/ajax.ExImportData.php');


	//create the language combobox
	$res = $db->SQLexecute("SELECT id_language,country_code,cp_comment FROM _LanguageProjects INNER JOIN _LanguageCodepage a ON a.id = id_language WHERE id_project = $projectId");
		while ($row = $db->fetchRow($res))
		$sel[] = '['. $row[0].',"'.$row[1].' - '.$row[2].'"]';

	$lngSelect = $tabId.'_lngSelect';
	echo "var $lngSelect = new Ext.form.ComboBox({
			fieldLabel:'Language',
			store: [ ".implode(',',$sel)."],
			id:'$lngSelect',".
			(count($sel) > 1 ? '' : 'hidden:true,')
			."autoSelect: true,
			value:$defLng,
			width:$fieldLng,
			triggerAction: 'all'
		});
		";


	$form = new MakeForm($tabId.'_form');
	$exportSelect = $tabId.'_exportSelect';
	echo "var $exportSelect = new Ext.form.ComboBox({
		fieldLabel:'Export type',
		triggerAction: 'all',
		editable:false,
		width: $fieldLng,
		store: [[0,'--- please select ---'],
				[8,'Fixed (Ascii)'],
				[9,'Binary'],
				[1,'Fixed (SPSS 7)'],
				[2,'Freefield (SPSS 8)'],
				[7,'Freefield (SPSS 9)'],
				[5,'Freefield (SPSS 10,11)'],
				[3,'CSV (Excel,Access)'],
				[4,'Tab (Excel,Access)'],
				[6,'SPSS - Data List']
		],
		listeners: {
			select: function(cb,rec,ind){
				var val = cb.getValue();
				var p = Ext.getCmp('$tabId');
				var pEast = p.layout.east.panel;
				var f = $form.getForm();
				if(val == 8 )
				{
					var dm = Ext.getCmp('{$tableName}_DatamapAscii');
					if(!dm)
						CallScript('webcati/_forms/ExImportData/forms.dataMap.php',{
						project_id:$projectId,
						project : '$tableName',tabId:'$tabId',
						id_language: $lngSelect.getValue(),id_lngDef:$defLng
						,exportSelect:val});
					else
					{
						pEast.layout.setActiveItem(dm.id);
					//	dm.show();
						pEast.setWidth(330);
					}
					//lets show all forms fields that are neccesery and hide all others
					f.findField('dataSeparator').setVisible(false);
					//f.findField('onFilter').setVisible(false);

					//f.findField('typeOfExport').setVisible(true);
					//f.findField('onlyValidCases').setVisible(true);


				}
				else if(val == 9)
				{//binary
					var dm = Ext.getCmp('{$tableName}_DatamapBinary');
					if(!dm)
						CallScript('webcati/_forms/ExImportData/forms.dataMap.php',{
						project_id:$projectId,
						project : '$tableName',tabId:'$tabId',
						id_language: $lngSelect.getValue(),id_lngDef:$defLng
						,exportSelect:val});
					else
					{
						pEast.layout.setActiveItem(dm.id);
						//dm.show();
						pEast.setWidth(330);
					}
					//lets show all forms fields that are neccesery and hide all others
					f.findField('dataSeparator').setVisible(false);
					//f.findField('onFilter').setVisible(false);

				//	f.findField('typeOfExport').setVisible(false);
				//	f.findField('onlyValidCases').setVisible(true);

				}
				else
					{
						/*if(val == 5)
							f.findField('SS10typeOfExport').setVisible(true);
						else
							f.findField('SS10typeOfExport').setVisible(false);*/
						pEast.setWidth(0);
						if(val == 1 || val == 2 || val == 7 || val == 5 || val == 6)
						{
							//lets show all forms fields that are neccesery and hide all others
							f.findField('dataSeparator').setVisible(true);
						//	f.findField('onFilter').setVisible(true);

						//	f.findField('typeOfExport').setVisible(false);
						//	f.findField('onlyValidCases').setVisible(false);
						}
						else
						{
							//lets show all forms fields that are neccesery and hide all others
							f.findField('dataSeparator').setVisible(false);
						//	f.findField('onFilter').setVisible(true);

					//		f.findField('typeOfExport').setVisible(false);
					//		f.findField('onlyValidCases').setVisible(false);
						}
					}
				p.doLayout();
			}
		}
	}); ";
	if($scriptExport) //script is for SPSS labels
	{
		echo "$exportSelect.setValue(5);";
	}

/*	$exportType = "{$tabId}_typeSelect";
	echo "var $exportType = new Ext.form.ComboBox({
		name:'typeOfExport',
		fieldLabel:'Type',
		editable:false,
		hidden:true,
		triggerAction: 'all',
		width: $fieldLng,
		store: [[1,'program, datamap'],
				[2,'Data']
		],
		autoSelect:true
	});
	$exportType.setValue(1);";
	*/
	$SS10exportType = "{$tabId}_SS10typeSelect";
	echo "var $SS10exportType = new Ext.form.ComboBox({
		name:'SS10typeOfExport',
		fieldLabel:'Type',
		editable:false,
		triggerAction: 'all',
		width: $fieldLng,
		store: [[1,'--- please select ---'],
				[2,'SPSS Labels'],
				[3,'SPSS Frequencies'],
				[4,'XML labels']
		],
		autoSelect:true
	});
	$SS10exportType.setValue(1);";

	$form->addItem($lngSelect);
	if(!$scriptExport)
	$form->addItem($exportSelect);
	$form->addItem("{
							xtype:'combo',
							store: new Ext.data.ArrayStore({
								        fields: [
								            'myId'
								        ],
								        data: [ ['iso-8859-1'],['iso-8859-2'],['iso-8859-3'],['iso-8859-4'],['iso-8859-5'],['iso-8859-6'],['iso-8859-7'],['iso-8859-8'],['iso-8859-9'],['iso-8859-10'],['iso-8859-11'],['iso-8859-12'],['iso-8859-13'],['iso-8859-14'],['iso-8859-15'],['windows-1250'],['windows-1251'],['windows-1252'],['windows-1256'],['windows-1257'],['koi8-r'],['big5'],['gb2312'],['utf-16'],['utf-8'],['utf-7'],['x-user-defined'],['euc-jp'],['ks_c_5601-1987'],['tis-620'],['SHIFT_JIS']
								         ]
											}),
									fieldLabel:'Encoding',displayField:'myId',mode:'local',
						triggerAction:'all',width: 140,valueField:'myId',editable:false,
						name:'encoding',ref:'RMencoding',
						value:'utf-8'

						}");
	if(!$scriptExport)
	{
		//$form->addField('onFilterBCK','Filter (MySQL syntax)','textfield')->width($fieldLng);
		$form->addField('onFilter','Filter (MySQL syntax)','twintrigger')->setProperty('id',"'expImpFilter_$tableName'")->setProperty('width',$fieldLng)
	->setProperty('trigger1Class',"'icon-saveas-field-t'")->setProperty('trigger2Class',"'icon-open-folder-field-t'")
	->setProperty('onTrigger1Click',"function(e){


	 new Ext.Window({title:'Save Filter',modal:true,width:'280px',
		items:{
		xtype:'form', buttonAlign:'center',
		frame:true,
		items: [

		//a combobox which shows all the stored filter for this user/project
		{xtype:'textfield',id:'wcbqComboPrompt',fieldLabel:'Name',
		width: 140 },
		{xtype:'checkbox',fieldLabel:'Public',id:'wcbqCheckPrompt' },
		{xtype:'checkbox',fieldLabel:'Common',id:'wcbqCheckPromptCommon' }
		]//eof form items
		 ,
		keys: [{
               key: [Ext.EventObject.ENTER], fn: function(){
                   Ext.getCmp('promptOKBtn').fireEvent('click');
               }
      		 }],
		buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
		click: function(){
					var text = Ext.getCmp('wcbqComboPrompt').getValue();
					if(text)
					{
					$treeWC.RMconn.request({
						url: 'webcati/_forms/_ajax/ajax.statistics.php',
						params: {database: '".DB_WARPIT_MAIN."', table: '_userStatFilters',
								action:'saveFilter', name:text, value: Ext.getCmp('expImpFilter_$tableName').getValue(),
								isPublic: Ext.getCmp('wcbqCheckPrompt').getValue(),
								isCommon: Ext.getCmp('wcbqCheckPromptCommon').getValue(),
								filterType: 1,
								projectId : $projectId
						}
							});

						this.findParentByType('window').close();
					}


			}
	}
			  },
		{
		text:'Cancel',handler:function(){
		this.findParentByType('window').close();

		 }
		 }
			  ] },
		defaultButton:'promptOKBtn'
				   } ).show();



	}")
	->setProperty('onTrigger2Click',"function(e){
		  new Ext.Window({title:'Load Filter',modal:true,width:'280px',
		items:{
		xtype:'form', buttonAlign:'center',
		frame:true,
		items: [

		//a combobox which shows all the stored filter for this user/project
		{xtype:'combo',id:'wcbqComboPrompt', store: new Ext.data.JsonStore({
			url: 'webcati/_forms/_ajax/ajax.statistics.php',
			baseParams: { projectId : $projectId,filterType: 1,action:'showFilter'  },
			autoLoad : true , root:'rows', fields:['id','name','filter' ]

		}) ,fieldLabel:'Filter',displayField:'name',mode:'local',
		triggerAction:'all',width: 140,valueField:'id',editable:false}
		]//eof form items
		 ,
		keys: [{
               key: [Ext.EventObject.ENTER], fn: function(){
                   Ext.getCmp('promptOKBtn').fireEvent('click');
               }
      		 }],
		buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
		click: function(){
					var cb = Ext.getCmp('wcbqComboPrompt');
					if(cb.selectedIndex >= 0)
					{
						var text = cb.getStore().getAt(cb.selectedIndex).data.filter;
						Ext.getCmp('expImpFilter_$tableName').setValue(text);

						this.findParentByType('window').close();
					}


			}
	}
			  },
		{
		text:'Cancel',handler:function(){
		this.findParentByType('window').close();

		 }
		 }
			  ] },
		defaultButton:'promptOKBtn'
				   } ).show();
	}");
		$form->addField('dataSeparator','Data separator','textfield')->setProperty('value',"'#'")->width(17);

		//$form->addItem($exportType);
		$form->addField('onlyValidCases','Valid cases only','checkbox');

	}
	if($scriptExport)
		$form->addItem($SS10exportType);
	if(!$scriptExport)
	{
		$form->addField('dateFrom','From date','datetimefield')->width($fieldLng);
		$form->addField('dateTo','To date','datetimefield')->width($fieldLng);
	}
	$form->addField('removeNewline','Remove lines','checkbox')->setProperty('checked','1');

	$form->addField('exportRecode','Include WEBrecoded '.$inclWebrecoded,'checkbox');

	/*$form->addItem("new Ext.Button({
			text:'Export',
			handler: function(){
				var bf = $form.getForm();
				var dfFrom = bf.findField('dateFrom').getValue();
				var dfTo = bf.findField('dateTo').getValue();
				Ext.util.FileOps.downloadFile('webcati/_ajax/ExImportData/ajax.ExImportData.php',{
						action:'export',
						exportSelect : $exportSelect.getValue(),
						exportFileType: $exportType.getValue(),
						SS10exportFileType: $SS10exportType.getValue(),
						id_language: $lngSelect.getValue(),
						id_lngDef:$defLng,
						ids: $treeWC.checkedId.join(','),
						dataSeparator:bf.findField('dataSeparator').getValue(),
						RMtable: '$tableName',
						projectId:$projectId,
						dateFrom: dfFrom ? dfFrom.format('U') : '' ,
						dateTo: dfTo ? dfTo.format('U') : '',
						validOnly : bf.findField('onlyValidCases').getValue(),
						exportRecode : bf.findField('exportRecode').getValue(),
						dataFilter: bf.findField('onFilter').getValue()
					} );
			}
	})");*/
	$form->addField('fieldSetSellabels','','fieldset')->setProperty('text',"'All'")
		->setProperty('title',"'Selected field(s)'")
		->setProperty('items',"{
			RMfieldName:'selFieldsLabel',
			xtype:'container',
			html:'All'
		}");

	$tbarButtons = "[{
			text:'Export',
			iconCls:'RMicon_export',
			handler: function(){
				var expSelect = $exportSelect.getValue();
				var typeSelect = $SS10exportType.getValue();
				if($expControl) return;


				if(typeSelect == 4)
				{
					//we make normal question export
					Ext.util.FileOps.downloadFile( 'webcati/_ajax/buildQuestionare/ajax.buildQuestionnaire.php',
						{
							RMcomp:'grid',
							action:'exportXML',
							project_id : $projectId
						}
					);
					return;
				}

				var bf = $form.getForm();
				var dfFrom = bf.findField('dateFrom') ? bf.findField('dateFrom').getValue() : 0;
				var dfTo = bf.findField('dateTo')? bf.findField('dateTo').getValue() : 0;
				//
				Ext.util.FileOps.downloadFile('webcati/_ajax/ExImportData/ajax.ExImportData.php',{
						action:'export',
						exportSelect : $exportSelect.getValue(),
						//exportFileType: $exportType.getValue(),
						SS10exportFileType: ".($scriptExport ? "$SS10exportType.getValue()" : '1' ) .",
						id_language: $lngSelect.getValue(),
						id_lngDef:$defLng,
						ids: $treeWC.checkedId.join(','),
						systemIds: $treeWC.systemId.join(','),
						qFieldsIds: $treeWC.qFields.join(','),
						telIds: $treeWC.telId.join(','),
						telFolder: $treeWC.telChecked ,
						sysChecked: $treeWC.sysChecked,
						dataSeparator: bf.findField('dataSeparator') ? bf.findField('dataSeparator').getValue() : '',
						RMtable: '$tableName',
						projectId:$projectId,
						dateFrom: dfFrom ? dfFrom.format('U') : '' ,
						dateTo: dfTo ? dfTo.format('U') : '',
						validOnly : bf.findField('onlyValidCases') ? bf.findField('onlyValidCases').getValue() : '',
						exportRecode : bf.findField('exportRecode').getValue(),
						removeNewline: bf.findField('removeNewline').getValue(),
						dataFilter: bf.findField('onFilter') ? bf.findField('onFilter').getValue() : '',
						encoding: $form.RMencoding.getValue()
					} );
			}
	}]";

	$form->region('center')
		->addConfig('padding',"10")
		->labelWidth(180)

		->addConfig('layoutConfig','{trackLabels:true}');

	if($scriptExport)
		$form->addConfig('tbar',$tbarButtons);
	else
		$form->addConfig('tbar',"{                        // configured using the vbox layout
            xtype    : 'container',
            layout   : {
                type  : 'vbox',
                pack  : 'start',
                align : 'stretch'
            },
            height   : 27 * 2,
            defaults : { flex : 1 },

            items    : [
                new Ext.Toolbar({
                    items : $tbarButtons
                }),
                new Ext.ux.CalcTBar({cmp : 'field',ref:'calcBar',showStyle:'SQL'})
            ]
        }
		");


      $treeWC->spCheck = true;//normal check
	echo $treeWC->CreateTree();
	echo $form->createForm();

	//listener for tree!
	if(!$scriptExport)
	echo $form. ".on('afterlayout',function(){
	//afterlayout get's called multiple times so we have a safety pin!
		if($form.hasDDTarget)
		{
			return;
			}
		$form.hasDDTarget = true;

		var field = $form.form.findField('onFilter');
		//we add the new special DropQuestion (_plugins/DropQuestion.js)
		$form.RMdd = new Ext.wc.DropQuestion(field.getId(),{RMconn: //we setup an ajax connection to buildQuestionnare where the function iz!
		new RMajax({url:'webcati/_ajax/buildQuestionare/ajax.buildQuestionnaire.php',
	 	params:{'RMtable':'$tableName',database:'".DB_WARPIT_WEBCATI."',RMcomp:'grid'
		}})
		,field:field,cmp:'field',addSign:''});

		if(Ext.isIE)
		{//we add special listeners to keep the caret position in IE (becouse IE has serious problems with caret positioning!!!)
			field.fCaret = 99999;
			field.el.on('keyup',function(fld){
				field.fCaret = getCaretPosition(  field.getId() );

			});
			field.el.on('click',function(fld){
				field.fCaret = getCaretPosition(  field.getId() );
			});
		}
		 $form.getTopToolbar().calcBar.field = $form.form.findField('onFilter');

	  } );

	  $form.on('beforedestroy',function(cmp)
		{
			if(cmp.RMdd) cmp.RMdd.destroy();
		});";

	echo "
	$treeWC.checkedId = new Array();
	$treeWC.checkedText = new Array();
	$treeWC.systemId = new Array();
	$treeWC.telId = new Array();
	$treeWC.qFields = new Array();
	$treeWC.telChecked = 0;
	$treeWC.sysChecked = 1;

	$treeWC.setSelectedFieldsText = function(){
		var s = '';

		if($treeWC.telId.length || $treeWC.telChecked)
		{
			s += 'System: ';
			if($treeWC.telId.length)
				s += $treeWC.telId.join(',');
			else
				s += 'all';
			s+='<br>';
		}

		if($treeWC.systemId.length || $treeWC.sysChecked)
		{
			s += 'System: ';
			if($treeWC.systemId.length)
				s += $treeWC.systemId.join(',');
			else
				s += 'all';
			s+='<br>';
		}
		s += 'Questions: ' + (this.checkedText.length ? this.checkedText.join(',') : 'All');

		if($treeWC.qFields.length )
		{

			s += '<br>Fields: ';

			s += $treeWC.qFields.join(',');

		}

		var lb = $form.find('RMfieldName','selFieldsLabel')[0];
		lb.update(s);

	};
	$treeWC.RMcheckHandler = function(node,stat){
		var lb = $form.find('RMfieldName','selFieldsLabel')[0];
		//lb.setText( $treeWC.getChecked('text').join(',')  );
		if(node.attributes.dataType == 'question')
		{
			if(stat)
			{
				this.checkedId.push(node.id);
				this.checkedText.push(node.text);
			}
			else
			{
				this.checkedId.remove(node.id);
				this.checkedText.remove(node.text);
			}
			//lb.setText( this.checkedText.length ? this.checkedText.join(',') : 'All');
			if(node.childNodes.length)
			{
				for(i=0;i<node.childNodes.length;i++)
					node.childNodes[i].ui.toggleCheck(stat);

			}
			else
			{
				$treeWC.RMconn.request({params:{
					action:'getFields',
					qId:node.id
				},
				success:function(res,opt){
					res = Ext.decode(res.responseText);
                    
                    //20150514 Tanis, If question is instruction type we don't have fields so we have to check if fields exist first so we don't add empty string in array
                    if(res.fields.length > 0)
                    {
                        var fldArr = res.fields.split(',');
                        for(var l=0;l<fldArr.length;l++)
                        if(stat)
                        {
                            $treeWC.qFields.remove(fldArr[l]); //ce je slucajno ze od prej not :)
                            $treeWC.qFields.push(fldArr[l]);
                        }
                        else
                            $treeWC.qFields.remove(fldArr[l]);
    
                        $treeWC.setSelectedFieldsText();
                    }
					
				}
				});
			}
		}
		else if(node.attributes.dataType == 'qFields')
		{
			if(stat)
			{
				this.qFields.push(node.text);
			}
			else
			{
				this.qFields.remove(node.text);
			}
		}
		else if(node.attributes.dataType == 'system')
		{
			if(stat)
				{
				this.systemId.push('a.'+node.text);
				}
			else
			{
				this.systemId.remove('a.'+node.text);
			}
		}
		else if(node.attributes.dataType == 'telephone')
		{
			if(stat)
				{
				this.telId.push('c.'+node.text);
				}
			else
			{
				this.telId.remove('c.'+node.text);
			}
		}
		else if(node.attributes.dataType == 'tel_index')
		{
			if(stat)
				{
				this.telId.push('d.'+node.text);
				}
			else
			{
				this.telId.remove('d.'+node.text);
			}
		}
		else if(node.id == 'telephoneFolder')
			$treeWC.telChecked = stat ? 1 : 0;
		else if(node.id == 'system')
			$treeWC.sysChecked = stat ? 1 : 0;

		$treeWC.setSelectedFieldsText();
	};
	$treeWC.on('checkchange',$treeWC.RMcheckHandler );
	$treeWC.on('beforeload',function(){
		var l = this.getLoader().baseParams;
		l.ids = $treeWC.checkedId.join(',');
		l.telFolder = $treeWC.telChecked;
		l.sysChecked = $treeWC.sysChecked;

		l.systemIds = $treeWC.systemId.join(',');
		l.telIds = $treeWC.telId.join(',');
		l.qFieldsIds = $treeWC.qFields.join(',');


	});
	";


	$templateGrid  = new MakeGrid($tabId.'_templates');
	$templateGrid->setMainTable('_ExportTemplate',DB_WARPIT_WEBCATI_BASE)
	->baseParams = "projectId :$projectId,tableName: '$tableName',templateType: '$scriptExport'";
	$templateGrid->reqUrl = 'webcati/_ajax/ExImportData/ajax.ExImportData.php';

	$templateGrid->addColumn('id');
	$templateGrid->addColumn('questionsOnly');
	$templateGrid->addColumn('templateName','Template');
	$templateGrid->addColumn('varNames','Variables');
	$templateGrid->addColumn('variables');
	$templateGrid->setAutoExpand('varNames')
		->setTitle('Templates')
		->setHeight(200)
		->region('south')
	;
	$templateGrid->addTbarItem("{text:'Load',iconCls:'RMicon_open_folder',handler:function(){
		var rec = $templateGrid.getSelectionModel().getSelected();
		var t = $treeWC;
		if(!rec) return;
		if(!rec.data.variables)
		{
			var ids = [];
			var sys = [];
			var tel = [];
			var qFields = [];
		}
		else
		{
			var loadData = rec.data.variables.split('|');
			var ids = loadData[0].split(',');
			var sys = loadData[1].split(',');
			var tel = loadData[2].split(',');
			var qFields = loadData[3].split(',');
			t.telChecked = parseInt( tel[0] );
			tel.shift();
			t.telId = tel.slice(0);
			for(var i = 0; i < tel.length; i++) tel[i] = tel[i].split('.')[1];
			t.sysChecked = parseInt( sys[0] );
			sys.shift();
			t.systemId = sys.slice(0);
			for(var i = 0; i < sys.length; i++) sys[i] = sys[i].split('.')[1];

		}

		//we deactivate the listener, so it doesnt change on every toggleCheck
		t.un('checkchange',t.RMcheckHandler);
		t.checkedId = ids.slice(0);


		t.qFields = qFields.slice(0);
		$treeWC.getRootNode().cascade( function(n){
			var ch = false;
			if(n.id == 'system')
				ch = t.sysChecked;
			else if(n.id == 'telephoneFolder')
				ch = t.telChecked;
			else if(n.id != 0 && n.id != 'question')
			{
				if(n.id == 'region') debugger;
				var testArray;
				if(n.attributes.dataType == 'question')
					testArray = ids;
				else if(n.attributes.dataType == 'system')
					testArray = sys;
				else if(n.attributes.dataType == 'telephone' || n.attributes.dataType == 'tel_index')
					testArray = tel;
				else if(n.attributes.dataType == 'qFields')
					testArray = tel;
				for(var i = 0; i < testArray.length; i++) {
		   			if(testArray[i] == n.id){
		   				ch = true;

		   				testArray.splice(i,1);
		   				break;
		   			}
		   		}

    		}



    		n.ui.toggleCheck(ch);
		} );
		t.on('checkchange',t.RMcheckHandler);


		if(t.checkedId.length)
		{
			t.checkedText = rec.data.questionsOnly.split(',');
		}
		else
		{
			t.checkedText = [];
		}
		t.setSelectedFieldsText();
		//we sent all the checked nodes to the server so that we can display them checked on load
		t.getLoader().baseParams['checkedIds'] = ids.join(',');

	}}")
				->addTbarItem("'Template name:'")
				 ->addTbarItem("{xtype:'textfield',width:150,name:'templateNameTF' },'-'")
				 ->addTbarItem("{text:'Save',iconCls:'icon_save_document', handler:function(){
				 var nameTF = this.ownerCt.find('name','templateNameTF')[0];
				 var name  = nameTF.getValue();
				 if(!name)
				 {
				 	Ext.Msg.alert('Warning','Please enter name!');
				 	return;
				 }
				 $templateGrid.RMconn.request({
				 	params:{
				 	action:'saveTemplate',
				 	name:this.ownerCt.find('name','templateNameTF')[0].getValue(),
				 	ids: $treeWC.checkedId.join(','),
					systemIds: $treeWC.systemId.join(','),
					telIds: $treeWC.telId.join(','),
					qFieldsIds: $treeWC.qFields.join(','),
					telFolder: $treeWC.telChecked ,
					sysChecked: $treeWC.sysChecked
					 },
				 	success:function(resp){
				 		var rO = Ext.decode(resp.responseText);
				 		if(rO.success)
				 		{
				 			nameTF.setValue('');
				 			$templateGrid.getStore().reload();
				 		}
				 	}
				 });
				 }}")
				 ->activateRemove()
				 ;


	echo $templateGrid->createGrid();
	$eastPanel = $tabId.'_eastPanel';
	echo "var $eastPanel = new Ext.Panel({
		width:200,
		region:'south'
	});
	mainTabPanel.add(
		new Ext.Panel({
			id:'$tabId',
			iconCls:'RMicon_export',
			closable:true,
			title : '$title - $tableName',
			layout:'border',
			items:[$treeWC,{
				layout: 'border',
				region: 'center',
				items:[$form ,$templateGrid]
			},{
				region:'east',
				width:0,
				layout:'card'
			} ]
		})
	).show(); ";


?>