<?php
include '_dirinfo.php';

	class Question
	{
		/**
		 * Enter description here...
		 *
		 * @var db
		 */

		protected $db;
		//all columns to copy (without the settable)
		public $columns = "`nfn_sql`";
		public $project;

		public $q_name;
		public $id_mask;
		public $nav_sql;
		public $vpr_sql;
		public $odg_sql;
		public $leg_sql;
		public $les_sql = 1;



		protected $template_file;

		public function __construct(db $db=null,$data=null)
		{

			$this->db = $db;
			if($data)
				foreach ($data as $atr => $val)
				{
					$this->$atr = $val;
				}

		}

		/**
		 * Creates the appropriate class for the type!!!
		 *	1	 - Single response
		 *  2	 - Scale
		 *  3	 - Multi response
		 *  4	 - Open
		 *  5	 - Instruction
		 *  6	 - Time stamp
		 *  7	 -
		 *  71	 - Predictive dialer
		 *  72	 - Automatic dialer
		 *  73	 - Manual dialer
		 *  8	 - Status window
		 *  9	 - Appointment
		 *  10	 - Quota info
		 *  11	 - Custom mask
		 * @param string $type
		 * @param unknown_type $db
		 * @param unknown_type $data
		 * @return Question
		 */
		public static function createQuestion($type,$db=null,$data=null)
		{

				//var_dump($type);
				//var_dump($data);
		switch ($type) {
					case 1:
					include_once (PATH_TO_ROOT.'_class/createQuestion/SingleResponse.php');
					$q = new SingleResponse($db,$data);
					break;

					case 2:
						include_once (PATH_TO_ROOT.'_class/createQuestion/Scale.php');
						$q = new Scale($db,$data);
					break;
					case 3:
						include_once (PATH_TO_ROOT.'_class/createQuestion/MultiResponse.php');
						$q = new MultiResponse($db,$data);
					break;
					case 4:
						include_once (PATH_TO_ROOT.'_class/createQuestion/Open.php');
						$q = new Open($db,$data);
					break;
					case 5:
						include_once (PATH_TO_ROOT.'_class/createQuestion/Instruction.php');
						$q = new Instruction($db,$data);
					break;
					case 6:
						include_once (PATH_TO_ROOT.'_class/createQuestion/Timestamp.php');
						$q = new Timestamp($db,$data);
					break;
					case 7:
					case 8:
					case 9:
						include_once (PATH_TO_ROOT.'_class/createQuestion/SystemQuestion.php');
						$q = new SystemQuestion($db,$data);
					break;
					case 11:
						include_once (PATH_TO_ROOT.'_class/createQuestion/CustomMask.php');
						$q = new CustomMask($db,$data);
					break;
					default:
						$q = new Question($db,$data);
					break;
				}
			return $q;
		}
		/**
		 * With given project and question id it creates a question with all data filled!
		 *
		 * @param unknown_type $db
		 * @param unknown_type $project
		 * @param unknown_type $id
		 * @return Question
		 */
		public static function createQuestionFromTable($db,$project,$id)
		{
			$row = $db->get($project,$id,null,DB_WARPIT_WEBCATI);
			$q = Question::createQuestion($row['tip_sql'],$db,$row);
			$q->fill($project,$id);
			return $q;
		}
		public function fill($project,$id,$lng = null)
		{
			if(!$lng)
			{
				$lng = $this->db->get('_Projects',"proj_name = '$project'",'language',DB_WARPIT_WEBCATI_BASE);
				$lng = $lng[0];
			}
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$row = $this->db->get($project,$id);
			foreach ($row as $atr => $val)
			{
				$this->$atr = $val;
			}
			$this->fillLanguage($project,$id,$lng);

		}

		private function getProjectLanguage($project)
		{
				$lng = $this->db->get('_Projects',"proj_name = '$project'",'language',DB_WARPIT_WEBCATI_BASE);
				return $lng[0];
		}

		public function fillLanguage($project,$id,$lng= null)
		{

		//	ini_set("display_errors", "1");
			if(!$lng) $lng = $this->getProjectLanguage($project);

			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);

			$lngSql = "SELECT variable,lngText FROM ".$project."_language a INNER JOIN _LanguageText b ON a.id_text_type = b.id_text WHERE id_question = $id AND id_language = ".$lng;
			$lngRes = $this->db->SQLexecute($lngSql);

			if($this->db->NumRows($lngRes) <= 0)
			{
				$lng = $this->getProjectLanguage($project);
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
				$lngSql = "SELECT variable,lngText FROM ".$project."_language a INNER JOIN _LanguageText b ON a.id_text_type = b.id_text WHERE id_question = $id AND id_language = ".$lng;
				$lngRes = $this->db->SQLexecute($lngSql);
			}

			while ($lngRow = $this->db->fetchRow($lngRes))
			{
				$this->$lngRow[0] = $lngRow[1];
			}
		}

		public function setProject($projName)
		{
			$this->project = $projName;
		}

		public function addQuestion(array $data)
		{
			foreach ($data as $atr => $val)
			{
				$this->$atr = $val;
			}



			$this->writeQuestionRow($data);

			$this->updateStructure();
		}
		/**
		 * Returns the structure rows for the `project`_structure table
		 * each question type should overwrite this function (except info and timeStamp)
		 * E.g.: multiResponse q1: ",q1_1 int(3),q1_2 int(3) q1_opn varchar(250)" etc.
		 *
		 * @param array $row - the row returned by the SQL select statement
		 * @return String
		 */
		public function getStructureFields($row=null)
		{
			return array();

		}
		public function getSpecialType()
		{
			return 1;
		}
		/**
		 * Gets the default values for some fields
		 * e.g. Open has open_sql set to 1 and type_variable_base to 2 (varchar)
		 *
		 * @return array : first element a string of fields, second element a string of values!
		 */
		public function getDefaultValues()
		{
			$arr[] = ',variableTypeBase,les_sql,open_sql';
			$arr[] = ',4,1,1';
			return $arr;
		}
		/**
		 * on changing question type, we update the basic data type!
		 *
		 */
		public function changeDefaultDataType()
		{
			$this->variableTypeBase = 4;
			return $this->variableTypeBase;
		}

		public function supportedShowTypes()
		{
			return  array(0);
		}

		protected function writeQuestionRow()
		{

			include 'config.php';
			$this->db->ChangeDatabase($CATI);

			$max_qpos = "SELECT max(q_pos) FROM ".$this->project;
			$result = $this->db->SQLexecute($max_qpos);

			$row = $this->db->fetchArray($result);
			mysql_free_result($result);
			$set_q_pos = $row[0] + 1;

			$qID = $this->importQuestion("templates/$this->template_file");
			$sql = "UPDATE $this->project SET
					q_pos = \"$set_q_pos\",
					q_name = \"$this->q_name\",
					vpr_sql = \"$this->vpr_sql\",
					odg_sql = \"$this->odg_sql\",
					leg_sql = \"$this->leg_sql\",
					les_sql = \"$this->les_sql\"
					WHERE id = $qID";

			$this->db->SQLexecute($sql);
			if($this->db->IsError())
	  			{
	  				echo $this->db->GetError();
	  				return "Error";
	  			}
		}

		protected function importQuestion($template)
		{
			$rd = new XMLReader();
			$rd->XML(file_get_contents($template)   );

			$this->db->ChangeDatabase("RM_cati");
			while ($rd->read() )
			{
				if($rd->nodeType == XMLReader::ELEMENT)
				{

						$sm = new SimpleXMLElement( $rd->readOuterXml());
						$columns = array();
						$values = array();
						foreach ($sm as $col => $value)
						{
								$columns[] = $col;

								$values[] = $value;

						}
						$sql = "INSERT INTO $this->project (".implode(",",$columns).") VALUES ('".implode("','",$values)."')";
					//	echo $sql;
						$this->db->SQLexecute($sql);
						if($this->db->isError())
						{
							echo $this->db->GetError();
							return false;
						}

						return $this->db->GetLastInsertId();


				}
			}
			return false;

		}

		protected function updateStructure()
		{
			include 'config.php';
	  		$this->db->ChangeDatabase($CATI_base);

	  		$sql = "ALTER TABLE ".$this->project."_structure ADD $this->q_name int(3)";
	  		$this->db->SQLexecute($sql);
			if($this->db->IsError())
		  			{
		  				echo $this->db->GetError();
		  				return "Error";
		  			}
		}

	/**
	 * Cleans the answer string, so that any / may be shown
	 *
	 * @param unknown_type $str
	 */

		public static function cleanAnswerString($str)
		{
			$str = str_replace("/","<*>",$str);
			$str = str_replace("<<*>","</",$str);
			$str = str_replace("<*>>","/>",$str);
			$str = str_replace("<*> ","/ ",$str);
			//let's clean newlines in fornt or after delimiter!
			$str = str_replace("\n<*>","<*>",$str);
			$str = str_replace("<*>\n","<*>",$str);
			return $str;
		}
		/**
		 * Deciphrys the answer/legend string and returns an array of arrays which hold values and labels!
		 *
		 * @param unknown_type $str - the string with / delimited answers/legend
		 * @param unknown_type $sequentId - if true the array keys are answers ids, otherwise sequental
		 * @return unknown
		 */
		//20150219 Tanis i have changet this function and cleanAnswerString to static becouse sometimes is needed to parse outside of question
		public static function answerToArray($str)
		{
			if(!$str) return array();
			$str = self::cleanAnswerString($str);
			$ansArr = explode('<*>',$str);
			/*if($sequentId)
			{
				$k = 0;
				foreach ($ansArr as $ans) {
					$a = explode(' ',$ans,2);
					$arr[ $k ] = $a[1];
					$k++;
				}
			}
			else
			{
				foreach ($ansArr as $ans) {
					$a = explode(' ',$ans,2);
					$arr[ $a[0] ] = $a[1];
				}
			}*/
			//new logic -> an array of arrays with value label
			$ansArray = array();
			foreach ($ansArr as $ans) {

					$ansArray[] = explode(' ',$ans,2);
				}
			return $ansArray;
		}
		//sometimes we want to recalculate the structure becose of some changes
		public function resetStructure()
		{
			unset($this->fields);
			unset($this->ansArray);
			unset($this->legArray);
		}
		public function getAnswerArray()
		{
			if(is_array($this->ansArray) )
			{
				return $this->ansArray;
			}
			return $this->ansArray = $this->answerToArray($this->odg_sql);
		}

		public function getLegendArray()
		{
			if(is_array($this->legArray) )
			{
				return $this->legArray;
			}
			return $this->legArray = $this->answerToArray($this->leg_sql);
		}
		/**
		 * Function return data when question gets draged from tree to a field in order to select a variable
		 *
		 */
		public function getAnswersForSelect(&$data,&$idToNum)
		{
			return true;
		}
		//function to get number of open answers needed for auto record
		//it also gets the answer labels for sr and mr!
		public function getRecodeVars()
		{
			//open answer must override this at the moment
			return array();
		}
		/**
		 * In autorecode, single and multi have their answers displayed as labels!
		 *
		 */
		public function getRecodeAnswers()
		{
			return array();
		}

		public function getQType()
		{
			return "Not defined";
		}




	public function hasMultiAnswer()
	{
		return false;
	}

	public function getIconCls()
	{
		return 'icon-question_in';
	}

	/**
	 * Functions for creating detailed grid for entering answer and legend values!
	 * Used in forms.buildQuestionnaire upon clicking the actionIcon in answers/legend column!
	 *
	 */

	public function createAnswerGrid()
		{

			$this->createAnswerGridClass();
			$this->createAnswerGridButtons();
			$this->createAnswerGridEcho();

		}

		protected function createAnswerGridClass()
		{
			//include (PATH_TO_ROOT."init.php");
			include_once (PATH_TO_ROOT."_class/class.Extjs_grid.php");

			$this->name = $_POST['name'];
			$this->gridName = $_POST['gridName'];
			$this->tableName = $_POST['tableName'];
			$this->dataBase = $_POST['dataBase'];
			$this->data =  $_POST['data']  ;
			$this->data = json_encode( $this->cleanAnswerString($this->data));
			$tabName = stripcslashes( $_POST['tabName']);
			$title = $_POST['title'];
			$this->dataIndex = $_POST['dataIndex'];
			$this->id = $_POST['id'];
			$filter = $_POST['filter_answer'];
			$open = $_POST['open_data'];

			echo "
	 			var d = slashDelimitedToArray($this->data);
	 			var filTmp = '$filter';
	 			var opnTmp = '$open'.split(':');
	 			//var opnStTmp = opnTmp[0].split('-');
	 			if(filTmp != '')
	 			{
		 			var filArTmp = filTmp.split('<!>');
		 			//in case filter string is not updated and is shorter then questions!
		 			while(filArTmp.length < d.length)
		 				filArTmp.push('0');
		 			for(var i=0;i<d.length;i++)
		 			{
		 				if(filArTmp[i].substring(0,1)==1)
		 				{
		 					d[i].push(true);
						}
						else {d[i].push(false); }

						d[i].push( filArTmp[i].substring(1) );

						if(opnTmp[0] == d[i][0])
						{
							d[i].push(true);
							//d[i].push(opnStTmp[1]);
							opnTmp.shift();

						}
						else
						{
							d[i].push(false);
						//	d[i].push(0);
						}

		 			}
				}
				else
				{
				for(var i=0;i<d.length;i++)
		 			{
		 				d[i].push(false);

						d[i].push( '' );
						//duplicate code for performance!!! :)
							if(opnTmp[0] == d[i][0])
							{
								d[i].push(true);
								//d[i].push(opnStTmp[1]);
								opnTmp.shift();
							}
								else
								{
									d[i].push(false);
								//	d[i].push(0);
								}
		 			}

				}
	 			";
			$tbarName = $_POST['name'].'_tbar';

			$this->grid = new MakeGrid();

			$this->grid//->setGridName($_POST['name'])
			->setSortable(false)
			->setMainTable('ansGrid')
			->setReqUrl('webcati/_ajax/buildQuestionare/ajax.buildQuestionnaire.php')

			//->setTitle($title)
		//	->dataArray = "d";
			;

			$this->grid->addColumn('pos','Value','new Ext.form.NumberField()','int' )->defaultValue('"+ (tmpStore.getCount() == 0 ? 1 : ( parseInt(tmpStore.getAt(tmpStore.getCount()-1).data.pos) + 1 )) +"');
							  ;
			$this->grid->addColumn('ans','Answer','new Ext.form.TextField()')->defaultValue('')->setProperty('sortable','false');

		    //Section #1 20150306 Tanis added default value to column
			$this->grid->addColumn('group','Group','new Ext.form.NumberField()','int')->defaultValue('0');
			//End Section #1

			$this->grid->addColumn('filter','Filter')->type('checkColumn')->width(40);
			$this->grid->addColumn('filCnd','Condition',"new Ext.form.TextField({listeners:{
						blur:function(fld){
						if(Ext.isIE){
							$tbarName.fCaret = fld.getValue().length;


						}
						else{  $tbarName.fCaret = getCaretPosition(  fld.getId() );   }  }
						}
	})")->width(200);

			$this->grid->addColumn('open','Open')->type('checkColumn')->width(40);
	//		$this->grid->addColumn('lng','Length','new Ext.form.NumberField()');
			$this->grid->removeLocal = true;

			$this->grid//->setSort('pos')
			->setAutoExpand('ans')
			->activateAdd()->activateRemove()
			->addtBarItem("'-'")
			->addtBarItem("{
			text:'Set rotate from',name:'rotateFrom',handler:function(){
			var sel = $this->grid.selModel.getSelected();
			if(!sel) return;
			var str = $this->grid.getStore();
			$this->grid.RMrotFrom = str.indexOf( sel )+1;
			this.setText('Rotate from: <b>'+sel.data.pos + ' - '+sel.data.ans.substr(0,30)+'</b>');
		}
		}")
		->addtBarItem("'-'")
			->addtBarItem("{
			text:'Set rotate to',name:'rotateTo',handler:function(){
			var sel = $this->grid.selModel.getSelected();
			if(!sel) return;
			var str = $this->grid.getStore();
			$this->grid.RMrotTo = str.indexOf( sel )+1;
			this.setText('Rotate to: <b>'+sel.data.pos + ' - '+sel.data.ans.substr(0,30)+'</b>');
		}
		}")
			->addtBarItem("'-'")
			->addtBarItem("{
			text:'Cancel rotation',handler:function(){
			var sel = $this->grid.selModel.getSelected();
			var str = $this->grid.getStore();
			$this->grid.RMrotFrom = 0;
			$this->grid.RMrotTo = 0;
			$this->grid.getTopToolbar().find('name','rotateFrom')[0].setText('Set rotate from');
			$this->grid.getTopToolbar().find('name','rotateTo')[0].setText('Set rotate to');
			//console.log( $this->grid.getTopToolbar().find('name','rotateFrom')  );
		}
		}");
		if($this->dataIndex == 'odg_sql')
		{
			$this->grid->addtBarItem("'Up/down rotation:',{
			//xtype:'textfield',
			xtype:'combo',
			store:new Ext.data.JsonStore({
						url:'webcati/_ajax/buildQuestionare/ajax.buildQuestionnaire.php',
						baseParams: { action: 'qCombo',RMtable: '$this->tableName' },
						fields: ['id','q_name'],
						autoLoad: true,
						root: 'rows'
				}),
			ref: 'upDownRot',
			tpl:'<tpl for=\".\">' +
			'<div class=\"x-combo-list-item\">' +
			'{q_name}&nbsp;' +
			'</div></tpl>',
			forceSelection:true,
			triggerAction:'all',
			displayField:'q_name'
		}");
		}
		else if($this->dataIndex == 'leg_sql')
		{
			$this->grid->addtBarItem("'Repeat legend: ',{
				xtype:'textfield',
				ref:'repeatLegend'
		}");
		}

		$this->grid->addtBarItem("{ text:'Manage groups',
					iconCls:'RMicon_window_splitter',
					handler: function(){

				var grp = $this->grid.getStore().collect('group');
				var grpData = $this->grid.groupData.split('<*>');

				var items = new Array();
				items.push({
					xtype: 'combo',
					mode: 'local',
					triggerAction:'all',
					editable: false,
					value: $this->grid.groupLayout,
				    store: new Ext.data.ArrayStore({
				        fields: [
				            'myId',
				            'displayText'
				        ],
				        data: [[1, 'vertical'], [2, 'horizontal'],[3,'custom(template)']]
				    }),
				    value: $this->grid.groupLayout,
				    valueField: 'myId',
				    displayField: 'displayText',
				    fieldLabel: 'Layout'

					});
				var grpIndex = 0;
				Ext.each( grp,function(tmp){
						var grpTmpData = grpData[grpIndex] ? grpData[grpIndex].split(',') : [];
						items.push(
							{
							xtype: 'fieldset',
							title:'Group '+tmp,
							items:[{
								xtype: 'combo',
								mode: 'local',
								triggerAction:'all',
								editable: false,
								value: grpTmpData[0],
							    store: new Ext.data.ArrayStore({
							         fields: [
							            'myId',
							            'displayText'
							        ],
							        data: [[1, 'vertical'], [2, 'horizontal']]
							    }),
							    valueField: 'myId',
							    displayField: 'displayText',
							    fieldLabel: 'Layout'

							},{
								xtype:'textfield',
								fieldLabel:'Header',
								value: grpTmpData[2]
							},{
								xtype:'textfield',
								fieldLabel:'Spacing',
								value: grpTmpData[1]
							},{
								xtype:'checkbox',
								fieldLabel:'Repeat legend',
								checked: grpTmpData[3] == 1
							}]
							});
						grpIndex++;
				});


			var w= new Ext.Window({
				layout:'form', modal:true, padding:'10',
				items: items,
				width:items.length>6 ? 380 : 350, //to compensate the scroll bar
				height: items.length>6 ? 600 : undefined,
				autoScroll:true,
				buttons:[{
				text:'Save',
				handler: function(){
					$this->grid.groupLayout = w.items.items[0].getValue();
					var grpData = new Array();
					for(var i=0;i<grp.length;i++)
					{
						grpData.push( w.items.items[i+1].items.items[0].getValue() + ',' + w.items.items[i+1].items.items[2].getValue() + ',' + w.items.items[i+1].items.items[1].getValue()+',' + w.items.items[i+1].items.items[3].getValue() );
					}
					$this->grid.groupData = grpData.join('<*>');
					w.close();
			}
		}]
		}).show();
		}
		}")

		->addtBarItem("{iconCls:'x-tbar-loading', handler:function(){
			Ext.Msg.show({ title:'Restore changes' ,buttons: Ext.MessageBox.YESNO,msg:'Are you sure?',
			fn: function(btn){if(btn == 'yes'){
			 {$this->grid->getName()}.getStore().reload();
			 }}});
			} }"  )
			;
			$this->grid->firstEditableColumn = 1;
			$this->grid->setEditable(false)
			//->addConfig('enableDragDrop','true')
			->addConfig( "stopEditing" ,"function(cancel){
		        if(this.editing){
		            var ae = this.lastActiveEditor = this.activeEditor;
		            if(ae){
		                ae[cancel === true ? 'cancelEdit' : 'completeEdit']();
		                this.view.focusCell(ae.row, ae.col);



		                 if(cancel){
			        	if(ae.record.data.ans=='')
			        	{this.getStore().remove(ae.record);}}
		            }
		            this.activeEditor = null;
		        }
		        this.editing = false;

		    }"  )
			->addConfig("onEditComplete", "function(ed, value, startValue){

		        Ext.grid.EditorGridPanel.prototype.onEditComplete.call(this,ed,value,startValue);
		        var r = ed.record,
		            field = this.colModel.getDataIndex(ed.col);
		        value = this.postEditValue(value, startValue, r, field);
		        if((field == 'ans' || field == 'pos') && value=='')
		        {

		        	this.getStore().remove(ed.record);
		        }

		    }")
			->listeners[] = "beforeedit:function(e){
						if(e.column == 3){
								$tbarName.gRow = e.row;
								$tbarName.gCell =   e.column;
								$tbarName.cmp = 'grid';
							}
					}"
			;
			$this->grid->baseParams = "id:$this->id,projName:'$this->tableName',dataIndex:'$this->dataIndex',id:$this->id ,id_language:'".$_POST['id_language']."'";
			$this->grid->plugins[] = "this.orderDD = new Ext.ux.dd.GridDragDropRowOrder({scrollable:true})";

			$this->grid->addConfig('saveFunction',"function(close){

			var p = this.saveGetData();

			if( '$this->dataIndex' == 'odg_sql' )
			{
				var ud = this.getTopToolbar().upDownRot.getValue();
				if( ud )
				{
					p.upDownRot = ud;
				}
			}
			else if('$this->dataIndex' == 'leg_sql')
			{
				var repeatLegend = this.getTopToolbar().repeatLegend.getValue();
				if( repeatLegend )
				{
					p.repeatLegend = repeatLegend;
				}
			}
			Ext.Ajax.request(
							{url:'webcati/_ajax/buildQuestionare/ajax.buildQuestionnaire.php',params:Ext.apply(p, {action:'updateAnswers',RMtable:'$this->tableName',
							id:$this->id,database:'".$this->dataBase."',dataIndex: '$this->dataIndex'
							,
							rotFrom:$this->grid.RMrotFrom,
							rotTo:$this->grid.RMrotTo,
							miss_val_data: p.miss_val_data,
							groupLayout: $this->grid.groupLayout,
							groupData: $this->grid.groupData,
							id_language:'".$_POST['id_language']."'
							})
							,success: function(resp,opt){ successFunc(resp,opt,close); }
							});

			}");

		}

		protected function createAnswerGridEcho()
		{
			echo "var successFunc = function(resp,opt,close){
					var r = Ext.decode(resp.responseText);
						if(r.error)
						{
							if(r.error == 'hasData')
							{
								Ext.Msg.show({title:'Warning! Data exists',msg:'Do you want to:',buttons:{ ok:'Delete',yes:'Backup' },
						 			fn: function(btn){
						 				if(btn == 'ok') opt.params.updateConfirm = 'delete';
						 				else if(btn == 'yes') opt.params.updateConfirm = 'backup';
						 				else { e.record.set(e.field,e.originalValue);e.record.commit(); return;}
						 				Ext.Ajax.request(opt);
						 			}
						 		});
								return;
							}
						Ext.Msg.alert('Warning',r.error);

						}
					 Ext.getCmp('$this->gridName').getStore().reload();
					if(close)
						Ext.getCmp('wcbqTabPanel_$this->tableName').remove({$_POST['name']});
					else
						$this->grid.getStore().commitChanges();
				 };
		";
			echo $this->grid->createGrid();
			echo $this->grid.".store.on('load',function(){
					var groupData = this.reader.jsonData.groupData.split('<|>');
					$this->grid.groupLayout = groupData[0] || '';
					$this->grid.groupData = groupData[1] || '';

					";
		if($this->dataIndex == 'odg_sql')
		{
			echo "var updown = this.reader.jsonData.upDownRot;
					$this->grid.getTopToolbar().upDownRot.setValue(updown);";
		}else if($this->dataIndex == 'leg_sql')
		{
			echo "var rl = this.reader.jsonData.repeatLegend;
					$this->grid.getTopToolbar().repeatLegend.setValue(rl);";
		}

		if($rotFrom = $_POST['rotFrom'])
			{
				echo "var sel = $this->grid.getStore().getAt($rotFrom -1);
				if(sel)
				{
				//this.setText('Rotate from: '+sel.data.pos + ' - '+sel.data.ans.substr(0,30));
				$this->grid.RMrotFrom = $rotFrom;
				$this->grid.getTopToolbar().find('name','rotateFrom')[0].setText('Rotate from: <b>'+sel.data.pos + ' - '+sel.data.ans.substr(0,30)+'</b>');
				}";
			}
			if($rotTo = $_POST['rotTo'])
			{
				echo "var sel = $this->grid.getStore().getAt($rotTo -1);
				if(sel)
				{
				$this->grid.RMrotTo = $rotTo;
				$this->grid.getTopToolbar().find('name','rotateTo')[0].setText('Rotate to: <b>'+sel.data.pos + ' - '+sel.data.ans.substr(0,30)+'</b>');
				}";
			}

			echo  "});";
			$name = $this->grid->getName();

		//	$this->grid.getTopToolbar().find('name','rotateTo')[0].setText('Set rotate to');

			//ading drop target for condition of questions!!!
			echo "$name.on('afterrender',function(){
				$name.RMdd = new Ext.wc.DropQuestion($name.el,{RMconn:Ext.getCmp('$this->gridName').RMconn,grid:$name,field:$name,cmp:'grid' ,ddGroup:'wcqbGroup',textVar:'qName'
				,notifyDrop: function(dds,e,data) {
					if(dds.ddGroup == 'GridDD')
					{
						return $name.plugins[0].target.notifyDrop(dds,e,data);
					}
					elTargt =  e.getTarget('div.x-grid3-cell-inner');
					this.elTarget = elTargt;
					if(elTargt)
					{
						this.elTargCmp = 'cell';
						var gv = $name.getView();
						var row = gv.findRowIndex(elTargt);
						var cell = gv.findCellIndex(elTargt);
						var rec = $name.getStore().getAt(row);
						this.gRow=row;
						this.gCell = cell;
						if(gv.cm.getColumnId(cell) == 'filCnd')
						{
							//if column is condition we call the basic add data
							return this.myNotifyDrop(dds,e,data);

							var text = rec.get('filCnd');
							if(text.length != 0 && text.charAt(text.length - 1) != ' ')
							{
								text+=' ';
							}
							rec.set('filCnd',text+'$'+data.node.attributes.text);
							$name.startEditing(row,cell);

						}
						return true;
					}
					elTargt =  e.getTarget('input.x-form-text');
					if(elTargt)
					{
					var ae = $name.activeEditor;

					this.gRow = ae.row;
					this.gCell = ae.col;
					this.fCaret= getCaretPosition(  ae.field.getId() );
					this.elTargCmp = 'editor';
					return this.myNotifyDrop(dds,e,data);;

						field =  $name.activeEditor.field;
					var pos= getCaretPosition(  field.getId() );
					var t = field.getValue();
					var addT = ' $'+data.node. attributes.text+' ';

					field.setValue( t.substring(0,pos) +addT+t.substring(pos,t.length) );
					//field.setValue('aa');

					setCaretPosition(field.getId(),pos+addT.length);
					return true;
					}


					}
				,notifyOver: function(dds,e,data){
					if(dds.ddGroup == 'GridDD')
						{
							return $name.plugins[0].target.notifyOver(dds,e,data);
						}
					var elTargt = e.getTarget('div.x-grid3-cell-inner');
					if(	elTargt )
					{
						var cell = $name.getView().findCellIndex(elTargt);
						if(cell == 4)
							return Ext.dd.DropZone.prototype.dropAllowed;

					}
					return Ext.dd.DropZone.prototype.dropNotAllowed;



					},
		 updateField:function(dds,e,val){
				 	//elTargt =  e.getTarget('div.x-grid3-cell-inner');

					if(this.elTargCmp == 'cell')
					{
						var gv = $name.getView();
						var row = gv.findRowIndex(this.elTarget);
						var cell = gv.findCellIndex(this.elTarget);
						var rec = $name.getStore().getAt(row);
						if(gv.cm.getColumnId(cell) == 'filCnd')
						{
							var text = rec.get('filCnd');
							if(text.length != 0 && text.charAt(text.length - 1) != ' ')
							{
								text+=' ';
							}
							rec.set('filCnd',text+val);
							$name.startEditing(row,cell);

						}
						return true;
					}
					//elTargt =  e.getTarget('input.x-form-text');
					if(this.elTargCmp == 'editor')
					{


					wcbqAddTextField(this,val,true);

					return true;
					}
				 }

				}   ); });
				$name.on('beforedestroy',function(){
			$name.RMdd.destroy();
			$name.plugins[0].target.destroy();
				});";


			$tbarName = $_POST['name'].'_tbar';

			echo $this->grid->getName().".on('afteredit',function(e){
				//e.record.commit();
				if(e.field == 'pos')
                {
                    var data = e.grid.getStore().getRange();
                    Ext.each(data, function(dat)
                    {
                        if(dat.get('pos') == e.value && e.record.id != dat.id)
                        {
                            Ext.Msg.show(
                            {
                                 title:'Info',
                                 msg: 'Two answers can\'t have same value',
                                 icon: Ext.MessageBox.INFO,
                                 buttons: Ext.Msg.OK
                            });
                            e.record.set('pos', e.originalValue);
                        }
                    }    );
                }

				if(e.column == 1 && e.value != '')
				{
					if(e.originalValue  == '')
					{

						$name.RMaddRow.defer(100);
					}
				}


			} );
			var $tbarName = new Ext.ux.CalcTBar();
				$tbarName.grid = $name;
			var {$_POST['name']} = new Ext.Panel({
			title:'{$_POST['title']}',iconCls:'RMicon_edit_record',layout:'fit',closable:true,items:[$name ]
			,tbar:$tbarName ,id:'{$_POST['name']}'
			});
			";

			echo "Ext.getCmp('wcbqTabPanel_$this->tableName').add(".$_POST['name'].').show();';
		}
		protected function createAnswerGridButtons()
		{

			$this->grid->addConfig('saveGetData',"function(){
				var str = new Array();
			var hasFilter = false;
			var filter = new Array();
			var open = new Array();
			var grp = new Array();
            var miss_val = new Array();
			$this->grid.stopEditing();
			{$this->grid->getName()}.getStore().each(function(rec){
				if(rec.data.pos != '' && rec.data.ans != '')
				{
					str.push(rec.data.pos +' '  + rec.data.ans);
					if(rec.data.filCnd || rec.data.filter)
					{
						hasFilter = true;
					}
					filter.push( (rec.data.filter ? '1' : '0')+ (rec.data.filCnd ? rec.data.filCnd : '' )    );

					if(rec.data.miss_val)
                    {
                        miss_val.push(rec.data.pos);
                    }

					if(rec.data.open)
					{
						open.push(rec.data.pos);
					}
					grp.push(rec.data.group);
				}
				});

				p = {
					value:str.join('/'),
					filter_answer : hasFilter ? filter.join('<!>'):'',
					groups:grp.join(),
					miss_val_data: miss_val.join(':'),
					open_data : open.join(':')
				}
			return p;
		}");


			$this->grid->addButton('Save',"function(){ $this->grid.saveFunction(false); }")
			->addButton('Save&amp;Close',"function(){ $this->grid.saveFunction(true); }")
			->addButton('Cancel',"function(){
				Ext.getCmp('wcbqTabPanel_$this->tableName').remove({$_POST['name']});
			}")
			;
		}
		public function designerPrepareCondition()
		{

		}

		public function prepareAnswerGridData()
		{
			$di = $this->dataIndex;
			$answers = $this->answerToArray($this->$di );
			$fil = explode('<!>',$this->filter);
			$open = explode(':',$this->open);
			// 18.8.2014 Changed by Borut (add miss_val)
			$miss_val = explode(':',$this->miss_val);
			$nogo = explode(',',$this->nogo);
			$tmpGrp = explode('<|>',$this->groups,2);
			$groups = explode(',',$tmpGrp[0]);
			$this->groupData = $tmpGrp[1];
			$data = array();
			foreach ($answers as $key => &$val) {
				$ans['pos'] = $val[0];
				$ans['ans'] = $val[1];
				if($this->filter)
				{
					$ans['filter'] = substr($fil[$key],0,1);
					if(substr($fil[$key],1))
					   $ans['filCnd'] = substr($fil[$key],1);
                    else
                        $ans['filCnd'] = '';
				}
				else
				{
					$ans['filter'] = false;
					$ans['filCnd'] = '';
				}

				$ans['group'] = $groups[ $key ];
				$ans['open'] = in_array($val[0],$open );
				// 18.8.2014 Changed by Borut (add miss_val)
				$ans['miss_val'] = in_array($val[0],$miss_val );
				$ans['nogo'] = in_array($val[0],$nogo );
				$data[] = $ans;
			}
			return $data;


		}

        public function getStatisticData($rowQuestion ,$tmpName = 'warpitStatistic')
        {
            return false;
        }

        public function exportToExcel($rowQuestion ,$tmpName = 'warpitStatistic', &$objPHPExcel, $data = null, &$i = 2)
        {

            if($this->disable_question)
            {
                return false;
            }
            if($this->q_pos < 0)
                return false;

            if(is_null($data))
                $data = $this->getStatisticData($rowQuestion, $tmpName);

            $arr = $data[0];
            $descStat = $data[2];
         /*   print "<pre>";
            var_dump($data);
            print "</pre>";
           */ $styleArray =  array(
                'fill' => array(
                    'type' => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => 'c8ccc8')
                    )
            );
            if($i == 2)
            {
                $objPHPExcel->addSheet(new PHPExcel_Worksheet($objPHPExcel, $rowQuestion['q_name']),0);
                $sheet = $objPHPExcel->getSheet(0);
                $sheet->SetCellValue('A1', strip_tags($rowQuestion['vpr_sql']));
                $sheet->getColumnDimension('A')->setWidth(320);
                $sheet->getStyle('A1:C1')
                    ->getFill()
                    ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                    ->getStartColor()
                    ->setRGB('004AA0');
                $sheet->getStyle('A1:C1')
                    ->getFont()
                    ->getColor()
                    ->setRGB('FFFFFF');
            }

            $sheet = $objPHPExcel->getSheet(0);

            //$objPHPExcel->setActiveSheetIndex(0);

            $sheet->SetCellValue('A' . $i, $data[1]);
            $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
            $sheet->SetCellValue('B' . $i, "N");
            $sheet->getStyle('B'. $i)->applyFromArray($styleArray);
            $sheet->SetCellValue('C'. $i, "%");
            $sheet->getStyle('C'. $i)->applyFromArray($styleArray);
            $i++;
            foreach($arr as $dataRow)
            {
                //var_dump($dataRow); die;
                $answer_percent = round($dataRow[2],1);
                $sheet->SetCellValue('A' . $i, $dataRow[0]);
                $sheet->SetCellValue('B' . $i, $dataRow[1]);
                $sheet->SetCellValue('C' . $i, $answer_percent);
                $i++;
            }

            if(is_array($descStat))
            {

                $missStr = "0";
                if (strlen($descStat['missing']) > 0) $missStr = "0,".$descStat['missing'];

                $sheet->SetCellValue('A' . $i, "Mean");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['mean']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                $sheet->SetCellValue('A' . $i, "Std. Deviation");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['stddev']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                //20151001 Tanis we have different types of variances
/*                $sheet->SetCellValue('A' . $i, "Variance");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['variance']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;*/
                $sheet->SetCellValue('A' . $i, "Variance sample");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['variance_sample']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

				$sheet->SetCellValue('A' . $i, "Variance population");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['variance_population']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                //20151001 Tanis END

                $sheet->SetCellValue('A' . $i, "Minimum");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['min']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                $sheet->SetCellValue('A' . $i, "Maximum");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['min']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                $sheet->SetCellValue('A' . $i, "Sum");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['sum']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                $sheet->SetCellValue('A' . $i, "N");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $descStat['n']);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;

                $sheet->SetCellValue('A' . $i, "Mising(s)");
                $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
                $sheet->SetCellValue('B' . $i, $missStr);
                $sheet->getStyle('B' . $i)->applyFromArray($styleArray);
                $sheet->getStyle('C' . $i)->applyFromArray($styleArray);
                $i++;
            }


        }

		public function createStatistics($rowQuestion ,$tmpName = 'warpitStatistic' )
		{
			return false;
		}

		private function formatJSONforEye($arr){
		    $retStr = '<ul>';
		    if (is_array($arr)){
		        foreach ($arr as $key=>$val){
		            if (is_array($val)){
		                $retStr .= '<li>' . $key . ' => ' . $this->formatJSONforEye($val) . '</li>';
		            }else{
		                $retStr .= '<li>' . $key . ' => ' . $val . '</li>';
		            }
		        }
		    }
		    $retStr .= '</ul>';
		    return $retStr;
		}

		// 2014.08.17 add by Borut, $descStat
		protected function createStatisticsGridChart($arr,$title,$firstCol,$descStat = null)
		{
			if($this->HTMLstat) {
				// 2014.08.17 add by Borut, $descStat
				return $this->createStatisticsHTMLChart($arr,$title,$firstCol,$descStat);
			} elseif ($this->Graphstat) {
				return array($arr,$title,$firstCol);
			} else {
				return $this->createStatisticsExtjsChart($arr,$title,$firstCol);
			}

		}

		protected function createStatisticsExtjsChart($arr,$title,$firstCol)
		{

							$expander = false;
							foreach ($arr as $gridRow)
							{
								if(strlen($gridRow[0])>49  )
								{
									$expander = true;
									break;
								}
							}//include_once (PATH_TO_ROOT."_class/class.Extjs_grid.php");
								$grid = new MakeGrid();
							//	$grid->setTitle('neki');
								$grid->addColumn('variable',$firstCol);
								$grid->addColumn('freq','N')->width(30);
								$grid->addColumn('proc','%')->width(30)->type('int');
								$grid->addColumn('varShort');
								$grid->addConfig('autoHeight','true')
									->addConfig('columnWidth','.5')
									->setAutoExpand('variable')
								;
								if($expander)
								{
									$grid->setExpander("<div>{variable}</div>");
								}
								$grid->dataArray = "". json_encode($arr)."" ;
							//	$grid->dataArray = json_encode($arr) ;


								echo $grid->createGrid();

								$numRows = count($arr);
								$height = $numRows < 3 ? 80 : ( $numRows*21 + 25 );

								if($title && $this->showVar)
								{
									$title = $this->rowQuestion['q_name'].': '.$title;
								}

								return "{ title : ".json_encode($title).",
								items:[
								{$grid->getName()} ,
								{
						            xtype: 'barchart',
						            columnWidth: .5,
						          // width:400,
						           height:$height,
						            store: {$grid->getStoreName()},
						            xField: 'freq',
						            yField: 'varShort',
						            series: [{
										style: {color:0x0094da, size:10}
										}]
								}
									],

								layout:'column'
								}";
		}






		protected function createStatisticsGraph($arr,$title,$firstCol)
		{
			foreach ($arr as $val) {
				$labels[] = "'".$val[0]."'";
				$vals[] = $val[2];
			}
		}


		/**
		 * Function for drawing HTML stat charts
		 * Each subclass has a function for calculation data, this only draws data in $arr argument!
		 * Scale class also draws a seperate title and a table for min max values!
		 *
		 * @param unknown_type $arr
		 * @param unknown_type $title
		 * @param unknown_type $firstCol
		 */
		// 2014.08.17 add by Borut, $descStat
		protected function createStatisticsHTMLChart($arr,$title,$firstCol,$descStat = null) {
			$titleBorderColor = "#989898";
			if (!$decimal_separator) $decimal_separator = ".";

			if($title) {
				if($this->showVar)
				{
					$title = $this->rowQuestion['q_name'].': '.$title;
				}
				echo "<table width=660 border=0 cellspacing=0 cellpadding=0><tr>";

				echo '<td colspan="5" align="center" style="background-color : #004AA0; color : #ffffff; padding-left : 5px; height : 30px;
				    border-left-width : 1px;
				    border-right-width : 1px;
				    border-top-width : 1px;
				    border-bottom-width : 1px;
				    border-left-color : #989898;
				    border-right-color : #989898;
				    border-top-color : #989898;
				    border-bottom-color : #989898;
				    border-left-style : solid;
				    border-right-style : solid;
				    border-top-style : solid;
				    border-bottom-style : solid;
				    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
				    FONT-SIZE: 12px;
				    ">'.$title.'</td></tr>';
				}
				echo "<tr>";
				echo "<td colspan=2 Style=\"background-color:#c8ccc8;padding-left:5px;height:25px;border-left-width:1px;border-right-width:1px;border-top-width:1px;border-bottom-width:1px;border-left-color:#989898;border-right-color:#989898;border-top-color:#989898;border-bottom-color:#989898;border-left-style:solid;border-right-style:none;border-top-style:none;border-bottom-style:solid;FONT-FAMILY:Vardana, Arial, Helvetica, sans-serif;FONT-SIZE:12px;\">";
					echo "$firstCol";
				echo "</td>";
				echo "<td align=center Style=\"background-color:#c8ccc8;border-left-width:1px;border-right-width:1px;border-top-width:1px;border-bottom-width:1px;border-left-color:#989898;border-right-color:#989898;border-top-color:#989898;border-bottom-color:#989898;border-left-style:solid;border-right-style:none;border-top-style:none;border-bottom-style:solid;FONT-FAMILY:Arial,Helvetica,sans-serif;FONT-SIZE:12px;\">";
					echo "%";
				echo "</td>";
				echo"<td align=center Style=\"background-color:#c8ccc8;border-left-width:1px;border-right-width:1px;border-top-width:1px;border-bottom-width:1px;border-left-color:#989898;border-right-color:#989898;border-top-color:#989898;border-bottom-color:#989898;border-left-style:solid;border-right-style:none;border-top-style:none;border-bottom-style:solid;FONT-FAMILY:Vardana,Arial,Helvetica,sans-serif;FONT-SIZE:12px;\">";
					echo "N";
				echo "</td>";
				echo"<td align=center Style=\"background-color:#c8ccc8;border-left-width:1px;border-right-width:1px;border-top-width:1px;border-bottom-width:1px;border-left-color:#989898;border-right-color:#989898;border-top-color:#989898;border-bottom-color:#989898;border-left-style:solid;border-right-style:solid;border-top-style:none;border-bottom-style:solid;FONT-FAMILY:Vardana,Arial,Helvetica,sans-serif;FONT-SIZE:12px;\">";
					echo "%";
				echo "</td>";
				echo "</tr>";
				foreach ($arr as $dataRow) {
						$answer_percent = round($dataRow[2],1);
						$invert_answer_percent = 100 - $answer_percent;
						echo "<tr>";
    						echo "<td colspan=2 width=64% Style=\"padding-left : 25px; height : 25px;
							    border-left-width : 1px;
							    border-right-width : 1px;
							    border-top-width : 1px;
							    border-bottom-width : 1px;
							    border-left-color : #989898;
							    border-right-color : #989898;
							    border-top-color : #989898;
							    border-bottom-color : #989898;
							    border-left-style : solid;
							    border-right-style : none;
							    border-top-style : none;
							    border-bottom-style : solid;
							    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
							    FONT-SIZE: 12px;
							    \">";
							    							if ( $stat_show_val ) echo "$freq_index ";
							    							echo "$dataRow[0]";
							    						echo "</td>";
							    						echo "<td width=16% Style=\"padding-left : 5px;
							    border-left-width : 1px;
							    border-right-width : 1px;
							    border-top-width : 1px;
							    border-bottom-width : 1px;
							    border-left-color : #989898;
							    border-right-color : #989898;
							    border-top-color : #989898;
							    border-bottom-color : #989898;
							    border-left-style : solid;
							    border-right-style : none;
							    border-top-style : none;
							    border-bottom-style : solid;
							    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
							    FONT-SIZE: 12px;
							    \">";
							    							echo "<table border=0 width=140px cellpadding=0 cellspacing=0><tr>";
							    							echo "<td width=$answer_percent% Style=\"font-size : 1px; height : 12px; background-color : #004AA0;
							    border-left-width : 1px;
							    border-right-width : 1px;
							    border-top-width : 1px;
							    border-bottom-width : 1px;
							    border-left-color : #989898;
							    border-right-color : #989898;
							    border-top-color : #989898;
							    border-bottom-color : #989898;
							    border-left-style : solid;
							    border-right-style : solid;
							    border-top-style : solid;
							    border-bottom-style : solid;

							    \">1</td>";
							    							echo "<td width=$invert_answer_percent%></td></tr></table>";
							    						echo "</td>";
							    						echo "<td width=10% align=right Style=\"padding-right : 20px;
							    border-left-width : 1px;
							    border-right-width : 1px;
							    border-top-width : 1px;
							    border-bottom-width : 1px;
							    border-left-color : #989898;
							    border-right-color : #989898;
							    border-top-color : #989898;
							    border-bottom-color : #989898;
							    border-left-style : solid;
							    border-right-style : none;
							    border-top-style : none;
							    border-bottom-style : solid;
							    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
							    FONT-SIZE: 12px;
							    \">";
							    							echo $dataRow[1];
							    						echo "</td>";
							    						echo "<td width=10% align=right Style=\"padding-right : 20px;
							    border-left-width : 1px;
							    border-right-width : 1px;
							    border-top-width : 1px;
							    border-bottom-width : 1px;
							    border-left-color : #989898;
							    border-right-color : #989898;
							    border-top-color : #989898;
							    border-bottom-color : #989898;
							    border-left-style : solid;
							    border-right-style : solid;
							    border-top-style : none;
							    border-bottom-style : solid;
							    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
							    FONT-SIZE: 12px;
							    \">";
							    							echo str_replace(".",$decimal_separator,$answer_percent);
							    						echo "</td>";
							    					echo "</tr>";;
			}

			// 2014.08.17 add by Borut, $descStat
			//20151009 Tanis I have added some variables in condtion. We don't want to show filter here if there is a scale question. For scale question we print filters in _class/createQuestion/Scale.php file
			if ($descStat || $this->stat_show_filter_in || $this->stat_show_filter_out && $this->tip_sql != 2) {
				$statDescFont = "style=font-family:Vardana;font-size:12px;";
				$missStr = "0";
				if (strlen($descStat['missing']) > 0) $missStr = "0,".$descStat['missing'];
				echo "<tr>";
					echo "<td colspan=5 Style=\"background-color:#c8ccc8;padding-left:5px;height:25px;border-left-width:1px;border-right-width:1px;border-top-width:1px;border-bottom-width:1px;border-left-color:#989898;border-right-color:#989898;border-top-color:#989898;border-bottom-color:#989898;border-left-style:solid;border-right-style:solid;border-top-style:none;border-bottom-style:solid;FONT-FAMILY:Vardana, Arial, Helvetica, sans-serif;FONT-SIZE:12px;\">";
						echo "<table border=0 align=left>";
						//20151009 Tanis I want to show descStat only if exsists
						if($descStat)
						{
							echo "<tr><td $statDescFont>Mean:</td><td $statDescFont>".$descStat['mean']."</td></tr>";
							echo "<tr><td $statDescFont>Std. Deviation:</td><td $statDescFont>".$descStat['stddev']."</td></tr>";
							//20151001 Tanis we have different types of variances
							//echo "<tr><td $statDescFont>Variance:</td><td $statDescFont>".$descStat['variance']."</td></tr>";
							echo "<tr><td $statDescFont>Variance sample:</td><td $statDescFont>".$descStat['variance_sample']."</td></tr>";
							echo "<tr><td $statDescFont>Variance population:</td><td $statDescFont>".$descStat['variance_population']."</td></tr>";
							//20151001 Tanis END
							echo "<tr><td $statDescFont>Minimum:</td><td $statDescFont>".$descStat['min']."</td></tr>";
							echo "<tr><td $statDescFont>Maximum:</td><td $statDescFont>".$descStat['max']."</td></tr>";
							echo "<tr><td $statDescFont>Sum:</td><td $statDescFont>".$descStat['sum']."</td></tr>";
							//echo "<tr><td $statDescFont>&nbsp;</td><td $statDescFont>&nbsp;</td></tr>";
							echo "<tr><td $statDescFont>N:</td><td $statDescFont>".$descStat['n']."</td></tr>";
							echo "<tr><td $statDescFont>Missing(s):</td><td $statDescFont>".$missStr."</td></tr>";
						}
							//20151009 Tanis I have add fields for displaying filters
							if($this->stat_show_filter_in)
								echo "<tr><td $statDescFont>Filter in: </td><td $statDescFont>" . $this->fil_sql . "</td></tr>";
							if($this->stat_show_filter_out)
								echo "<tr><td $statDescFont>Filter out: </td><td $statDescFont>" . $this->con_sql . "</td></tr>";
							//20151009 Tanis END
						echo "</table>";
					echo "</td>";
				echo "</tr>";
			}




			//only scales special tables don't have title
			if($title) {
				echo "</table><br><br><br><br>";
			}


		}

		public function PluginGetAnswers() {
			$ansArr = $this->answerToArray( $this->odg_sql );
			$ansArr = $this->designerRotateAnswers($ansArr);
			$this->designerFilterAnswers($ansArr);
			return $ansArr;
		}


		public function designerDrawAnswers()
		{
			/*	$ansArr = $this->answerToArray($this->odg_sql);
			  	$tbl = "<table border=1>";
			  	foreach ($ansArr as $ans) {
			  		$value = $ans[0];
			  		$label = $ans[1];
			  		$tbl .= "<tr>";
			  		$tbl .= "<td><input type='radio' NAME='".$this->q_name."' value='$value'></td>";
			  		$tbl .= "<td>$value</td>";
			  		$tbl .= "<td>$label</td>";
			  		$tbl .= "</tr>";
			  	}
			  	$tbl .= "</table>";
			  	return $tbl;*/
		}
		protected function designerFilterAnswers(&$ansArr,$leg = false)
		{
			if(!$leg && $this->attachAnswers)
			{//we check if answerAttach is set!
				if($e = $this->display->engine)
				{
					global $db;
					// Borut, 20151128, change second parameter $this->display->engine->proj_name INTO $e->projname
					// there is no place in engine where we define proj_name property, I guess this is an old leftover, never corrected
					// because this part of the code is executed very rarely, we did not find it before, nobody using attach to... function
					$qAtt = Question::createQuestionFromTable($db,$e->projname,$this->attachAnswers);
					$selVals = $e->readDatabaseVariables( $qAtt->getStructureFields(null,false),false );

					foreach ($selVals as $valKey => $val) {
						if($val && is_numeric($val))
							$allselVals[] = $val;
					}


					$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

				}
			}

			$filterAnd = $leg === 'atr' ? $this->filter_attributes :  ($leg ? $this->filter_legend : $this->filter_answer);
			if($filterAnd || $allselVals)
			{
				if($e = $this->display->engine)
				{

					$condVariables = $e->readDatabaseVariables($e->returnConditionVariables($filterAnd));

					$condVariables['submit_error'] = '$submit_error = \''.!$e->LeaveQuestion .'\';';

					$filters = explode('<!>',$filterAnd);
					foreach ($ansArr as $key => $val) {
						$f = $filters[$key];
						if(substr($f,0,1) == 0 && $str = substr($f,1) )
						{
							if($e->ConditionSandBox($condVariables, $str )  )
							{
								unset($ansArr[$key]);
								continue;
							}
						}
                        //20150513 Tanis, če ni pogoja na funkcija substr vrne false in se ta veja ne izvede
						else if(substr($f,0,1) == 1 /*&& $str = substr($f,1)*/ )
						{//20160510 Tanis manjakl je ta del kode, ker je en krten po imenu Tanis to enostavno spregledal.
							// Pri testiranju ni bilo mogoče odkrti te napake, ker je v $str variabli ostaloa vrednost od prejšnje
							//iteracije zanke.
							//20160516 Tanis: če je bil prazen pogoj je funkcija substr vrnila false in condition je bil false namest o true
							if(strlen($f) > 1)
								$str = substr($f,1);
							else
								$str = true;

							if($e->ConditionSandBox($condVariables, $str )  )
							{//we "show" the answer...we show it so that we don't hide it under further conditions :D
								//unset($ansArr[$key]);
								continue;
							} 
							//20160516 Tanis če je pogoj false odstranimo odgovor
							else
							{
								unset($ansArr[$key]);
								continue;
							}

						}
						if(is_array($allselVals))
							{
								if($this->attachFalse)
								{
									if(!in_array($val[0],$allselVals))
										unset($ansArr[$key]);
								}
								else
								{
									if(in_array($val[0],$allselVals))
										unset($ansArr[$key]);
								}
							}

					}
				}
			}
		}
		protected function designerRotateAnswers(&$ansArr,$leg = false)
		{
			//if we already rotated array, or set it programaticly
			if(!$leg)
			{
				$sRot = $this->srot_sql;
				$eRot = $this->erot_sql;
				$sesName= 'ansRotation';
				$upDown = $this->rot_sql;
			}
			else if($leg === 'atr')
			{

				$sRot = $this->srotAttributes;
				$eRot = $this->erotAttributes;
				$sesName = 'atrRotation';
			}
			else
			{

				$sRot = $this->srotLegend;
				$eRot = $this->erotLegend;
				$sesName = 'legRotation';
			}

			if( isset($_SESSION[$sesName][$this->q_name])) return $_SESSION[$sesName][$this->q_name];

			if($sRot > 0 || $eRot > 0)
			{
				$beforeArr = array(); $endArr = array();
				foreach ($ansArr as $key => $val) {
					if($key +1 < $sRot)
					{
						//answers before srot stay unchanged
						$beforeArr[$key] = $val;
					}
					elseif ($key +1 <= $eRot || !$eRot )
					{
						//answers between go to the shuffled array

						$midArr[$key] = $val;
					}
					else
					{
						$endArr[$key] = $val;
					}

				}

				if ($upDown) {
					$midArr = $this->UpDownRotate($upDown,$midArr);
				} else {
					//shuffle($midArr);
					//storing my keys and values!!!
					$tmp = array();
				    foreach($midArr as $key => $value) {
				        $tmp[] = array('k' => $key, 'v' => $value);
				    }
				    shuffle($tmp);
				    $midArr = array();
				    foreach($tmp as $entry) {
				        $midArr[$entry['k']] = $entry['v'];
				    }
				}

				foreach ($beforeArr as $key => $val) {$finArr[$key] = $val;}
				foreach ($midArr as $key => $val) {$finArr[$key] = $val;}
				foreach ($endArr as $key => $val) {$finArr[$key] = $val;}
				$_SESSION[$sesName][$this->q_name] = $finArr;
				return $finArr;
			}
			elseif($upDown)
			{
				$ansArr = $this->UpDownRotate($upDown,$ansArr);
			}

			return $ansArr;
		}

		protected function UpDownRotate($upDown,$ansArr) {
			$bla = $this->display->readStructureVariables(array($upDown),'');

			if( $bla[$upDown] %2 == 1 )
			{
				$ansArr = array_reverse($ansArr);
			}

			return $ansArr;
		}

		protected function designerDrawLegend($legRow,$legArray)
		{
			if($this->showLegend===false)
				return;
			//the width of the control must be divided by the number of legends
					$tbl .= "<tr>";
					foreach ($legRow->children() as $child) {

					$attr = $child->attributes();
			  				switch ($attr['type'])
				  			{
				  				case 20:
				  					if($this->showVal)
					  					{
					  					$size = $this->legStyle[20];
					  					$tbl .= "<td $size>&nbsp;</td>";
					  					}
				  				break;
				  				case 21:
				  					$size = $this->legStyle[21];
				  					$tbl .= "<td $size>&nbsp;</td>";

				  				break;
				  				case 22:
						  			 foreach ($legArray as $index => $ans) {
						  			$hmm = $ans[1];
						  			$size = $this->legStyle[22];
						  			$tbl .= "<td $size>$hmm</td>";
						  		}

			  					break;
				  			}


					}
					// 2014.11.12 Borut add this in case we have split answers (not a good idea without IF... correct it once)
					$tbl .= "<td></td>";

			  		$tbl .= "</tr>";
			  		return $tbl;
		}

		/**
		 * Defines 3 row objects with 3 answer objects
		 * Objects for legend row, odd rows and even rows
		 * Each row object has an object for answer value, answer label and answer control (radio, checkbox etc)
		 *
		 * @param $divideControlWidth - if control is shown in multiple rows (legend), we can divide it's length!
		 */
		protected function designerDefineObjects($divideControlWidth = 1)
		{
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			//let's check if we are to show var labels!
			$this->showVal = $this->db->get('_Projects',$_SESSION['id_project'],'interview_show_ans_value');

			$mainAttr = $this->xmlObj->attributes();
			if($mainAttr['RMclass'])
				$this->mainStyle = 'style="'.$this->display->getCssStyles($mainAttr['RMclass']).'"';
			//for the sake of simplicity...only first rows width settings will be considered, becouse you can not set different column widths anyway
			foreach ($this->xmlObj->children() as $child)
				{
					//print_r( $child->children() );
					$attr = $child->attributes();
					if($attr['RMclass'])
						$baseStyle = $this->display->getCssStyles($attr['RMclass']);
					$objIndex = 0;
					foreach ($child->children() as $grChild)
						{
						$objIndex++;
			  			$grAttr = $grChild->attributes();

			  			if(!$commonRowWidth[ $objIndex  ] )
			  			{
				  			if($grAttr['type'] == '22' &&  $divideControlWidth > 0 )
								$commonWidth = "style=\"width:".($grAttr['width'] / $divideControlWidth );
							else
								$commonWidth = "style=\"width:".$grAttr['width'];
							  if($grAttr['position'] == 'relative')
							  {
							  	$commonWidth .= '%;';
							  }
							  else if($grAttr['position'] == 'absolute')
							  {
							  	$commonWidth .= 'px;';
							  }
							  else
							  {
							  	$commonWidth = 'style="';

							  }
							  $commonRowWidth[ $objIndex ] = $commonWidth;
			  			}
			  			$size = $commonRowWidth[ $objIndex ];
							if($grAttr['RMclass'])
							{
								 $size .=  $this->display->getCssStyles($grAttr['RMclass']);
							}
							$size .= '"';
						 $style[ trim( $grAttr['type'] ) ] = $size;
						}

					//settings for legend row
					if($attr['subType'] == 1)
					{
						$this->legStyle = $style;
						$this->legRow = $child;
					} //setting for odd rows
					else if($attr['subType'] == 2)
					{
						$this->oddStyle= $style;
						$this->oddRows = $child;
					}//setting for even rows
					else if($attr['subType'] == 3)
					{
						$this->evenStyle = $style;
						$this->evenRows = $child;
					}
				}
		}
		/**
		 * Function to tell if this question type requires templates!
		 * default to false, sr and others override to return true!
		 *
		 * @return unknown
		 */
		public function designerRequiresTemplate()
		{
			return false;
		}

		public function printQuestion()
		{
			global $print_filter,$print_jump,$print_answfilter,$print_condition;
			$goto_cond = $this->goto_sql;
		if ( $goto_cond AND $print_jump ) {
				echo "<table Style=\"border-color : black; border-width : 1px; border-style : solid;\">";
					$goto_cond_array = explode(",", $goto_cond);
					$goto_counter = 0;
					while ( $goto_cond_array[$goto_counter] ) {
						list($goto_condition,$goto_variable) = explode("#", $goto_cond_array[$goto_counter]);
						echo "<tr>";
							echo "<td>";
								echo "<font class=tekst>$goto_condition</font>";
		//						echo "<font size=1 face=arial>$goto_condition</font>";
							echo "</td>";
							echo "<td>";
		//						echo "<img src=\"./images/goto.gif\" border=0 height=10px>";
								echo "==>";
							echo "</td>";
							echo "<td>";
								echo "<font class=tekst>$goto_variable</font>";
		//						echo "<font size=1 face=arial>$goto_variable</font>";
							echo "</td>";
						echo "</tr>";
						$goto_counter++;
					}
				echo "</table>";
			}
			$filter = $this->fil_sql;
		if ( $goto_cond AND $print_jump AND $filter AND $print_filter ) {
					echo "<table border=0 cellpadding=0 cellspacing=0>";
							echo "<tr>";
								echo "<td height=2px>";
								echo "</td>";
							echo "</tr>";
					echo "</table>";
				}

				if ( $filter AND $print_filter ) {
					echo "<table Style=\"border-color : black; border-width : 1px; border-style : solid;\">";
						echo "<tr>";
							echo "<td>";
								echo "<font class=tekst>$filter</font>";
			//					echo "<font size=1 face=arial>$filter</font>";
							echo "</td>";
						echo "</tr>";
					echo "</table>";
				}
		if ( $this->nav_sql ) {
			echo "<div>";
	//			echo "<font size=2 face=arial><i>ANK: $navodilo</i></font><br>";
				echo "<font class=tekst><i>$this->nav_sql</i></font><br>";
			echo "</div>";
			}
			echo "<font class=tekst><B>$this->q_name</B>&nbsp;&nbsp;&nbsp;&nbsp;$this->vpr_sql</font>";

		if ($print_answfilter AND $this->filter_answer) {
				$this->filter_answer_array = explode("<!>",$this->filter_answer);
			}
		if($this->printEdit)
					{
				//		echo "<form action=#>";
						//echo $this->printEditParams();
					}
			$this->printAnswerTable();
		//print comment

		if($this->printEdit)
				{


					//	echo "<input type=hidden name=id_question value=".$this->id." />";

						echo  "<div>Comment: <textarea name=userComment[$this->id] >".$this->comments[ $this->id  ]."</textarea></div>";


				//	echo "<input type='submit' value='Save' />
				//	</form>";

				}
		else
		{
			if($this->comments[ $this->id  ])
					{
						echo  "<div>Comment: ".$this->comments[ $this->id  ]."</div>";
					}
		}

			if ( $this->con_sql AND $print_condition ) {
				echo "<table Style=\"border-color : black; border-width : 1px; border-style : solid;\">";
					echo "<tr>";
						echo "<td>";
		//					echo "<font size=1 face=arial>$condition</font>";
							echo "<font class=tekst>$this->con_sql</font>";
						echo "</td>";
					echo "</tr>";
				echo "</table>";
			}


		}
		protected function printAnswerTable()
		{
			//echo '<div>answers ere</div>';
		}
	protected function printGetRecValues()
		{

			$this->fld = $this->getStructureFields();
			foreach ($this->fld as $key => $field) {
				if(substr($key,0,1) == 'o' )
				{

					$opArr = explode('_',$key);
					$this->openValues[$opArr[1]] = $this->record_data[ $field  ];
				}
				else
				{
					$this->dataValues[] = $this->record_data[ $field ];
				}
			}



		}

		protected function printEditVar($i,$value,&$arr)
		{

		}
		protected function printEditParams()
		{
			echo "<input type=hidden name=id_language value=".$_REQUEST['id_language']." />";
			echo "<input type=hidden name=id_record value=".$_GET['id_record']." />";
			echo "<input type=hidden name=projectId value=".$_GET['projectId']." />";
			echo "<input type=hidden name=tableName value=".$_GET['tableName']." />";
			echo "<input type=hidden name=edit value=true />";
		}
		protected function printFilterAnswer($j)
		{
		 		if ($this->filter_answer_array[$j]) {
			  	$answfilter_flag = substr($this->filter_answer_array[$j],0,1);
			  	$answfilter_flag_str = "<font color=gray>{";
			  	if ($answfilter_flag) {
			  		$answfilter_flag_str .= " <b>S: </b>";
			  	} else {
			  		$answfilter_flag_str .= " <b>H: </b>";
			  	}
			  	$answfilter_str = substr($this->filter_answer_array[$j],1);
			  	if ($answfilter_str) {
			  		echo $answfilter_flag_str;
			  		echo $answfilter_str."}</font>";
			  	}
			  }
		}
		/**
		 * Function that chekcs if this type can recode data to the changed type
		 *
		 * @param unknown_type $toType
		 */
		public function changeTypeCanRecode($toType)
		{
			return false;
		}
		public function changeTypeRecode($toType)
		{

		}

}

?>
