<?php
//include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.gridData.php");

class bqwcTreeDataMan extends TreeDataManipulator
{

    public function hasScriptAction()
    {
        $scriptSql = "SELECT * FROM " . DB_WARPIT_WEBCATI . ".". $_POST['RMtable'] . "_script WHERE script > ''";
        $scriptRes = $this->db->SQLexecute($scriptSql);
        return $this->db->NumRows($scriptRes) > 0;
    }

	public function attachCapiTableAction() {
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = 'UPDATE _Projects SET id_capiTable='.$_POST['dataType'].' WHERE id='.$_POST['id_project'];
		$this->db->SQLexecute($sql);

		try {
			$sql = "ALTER IGNORE TABLE ".$_POST['project']."_structure
						ADD id_capi_address int(10) AFTER t_diffs,
						ADD id_capi_table int(10) AFTER t_diffs,
						ADD id_capi_sample int(10) AFTER t_diffs,
						ADD CRCrec varchar(35) AFTER t_diffs,
						ADD INDEX (id_capi_address),
						ADD INDEX (id_capi_table),
						ADD INDEX (id_capi_sample)
					";
			$this->db->SQLexecute($sql);
		} catch (Exception $e) {
			$this->db->LogWrite($sql." --> ".$e->getMessage(),true,"attachCapiTableAction ERROR (only write to file...");
			return "{success:true,error:'".$e->getMessage()."'}";
		}

		return "{success:true}";
	}


	public function removeCapiTableAction() {
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "UPDATE _Projects SET id_capiTable='' WHERE id=".$_POST['id_project'];
		$this->db->SQLexecute($sql);

		try {
			$sql = "ALTER TABLE ".$_POST['project']."_structure
						DROP id_capi_address,
						DROP id_capi_table,
						DROP id_capi_sample,
						DROP CRCrec
					";
			$this->db->SQLexecute($sql);
		} catch (Exception $e) {
			$this->db->LogWrite($sql." --> ".$e->getMessage(),true,"removeCapiTableAction ERROR id_capi_address (only write to file...");
			return "{success:true,error:'".$e->getMessage()."'}";
		}

		return "{success:true}";
	}


   /* public function riptAction()
    {
        $scriptSql = "SELECT * FROM " . DB_WARPIT_WEBCATI . ".". $_POST['RMtable'] . "_script WHERE script > ''";
        $scriptRes = $this->db->SQLexecute($scriptSql);
        return $this->db->NumRows($scriptRes) > 0;
    }*/

	function selectAction()
	{

		require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');

		$parent = $_POST['node'];
		$sql = $_REQUEST['SQL'].' WHERE id_sup = '.$parent.' ';

		if(isset($_POST['filter']) && $_POST['filter'] != '')
		{
			$fil = $_POST['filter'];
			$sql.= "AND (idLab LIKE '%$fil%' OR is_leaf = 0)";
		}



		if (isset($_POST['RMorder'])) {
			$this->order[] = $_POST['RMorder'];
		} else {
			$this->order[] = 'orderBy';
		}
		if (isset($this->order))
		{
			$sql .= 'ORDER BY '.implode(',',$this->order);
		}

		If (!$res = $this->db->SQLexecute($sql))
		{
				return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		}
		else
		{
			// display each child
			while ($row = $this->db->fetchAssoc($res)) {
				// Response parameters.
				$path = array();

				if($_REQUEST['boldRoots'] && $parent == 0)
				{
					$path['cls']		= 'treeFontBold';
					//$path['children'][] = array(text=>'1');
					//$path['children'][] = array(text=>'2');
				}

				$path['text']		= html_entity_decode($row['idLab']);
				$path['qName'] = $row['idLab'];


				unset ($nameAtt);
				if($row['attachAnswers'])
				{
          //20160104 Bojan Orter - pri klicu $this->db->get sem dodal še 4-ti parameter da nastavim na pravo bazo DB_WARPIT_WEBCATI
					$ansAtt = $this->db->get($this->tableGrid,$row['attachAnswers'],'q_name', DB_WARPIT_WEBCATI);
					$nameAtt[] = "(->".$ansAtt.")";
				}

				if($row['hasScript'])
				{
				    if($this->hasScriptAction())
					   $nameAtt[] = "(S)";
				}
                if($row['hasPlugin'])
                {
                    $pluginName = $this->db->get("_Plugin",'id_plugin=' .$row['hasPlugin'],'short_name', DB_WARPIT_WEBCATI_BASE);
                    $nameAtt[] = "(P" . $pluginName[0] . ")";
                }
				if($nameAtt)
				{
					$path['text'] .= "<span style=color:red;>".implode('',$nameAtt)."</span>";
				}
				$path['id']			= $row['id'];
				$path['isQuestion'] = $row['is_leaf'];
                //$path['qtip '] = 'to je tooltip'; d

			//	$path['cls'] = 'textSize';
				// Check if node is a leaf or a folder.

				if(!$path['isQuestion']){
						$path['leaf']	= false;
						$path['showTogether'] = $row['showTogether'];
						//temporarly till order folder works!
						//$path['draggable'] = false;
						if(isset($_POST['filter']))
						{
							$_POST['node'] = $row['id'];
							if(!$path['children'] = json_decode( $this->selectAction(),true ))
							{
								continue;
							}
						}
					} else{

						$path['leaf']	= true;
						$path['editable'] = false;

						$path['q_id'] = $row['q_id'];
						if(isset($row['tip_sql']))
							$path['qType'] = $row['tip_sql'];
					}

				if(isset($row['node_img']) && $row['node_img']!= '')
				{
					$path['icon'] = $row['node_img'];
				}
				else
				{

					if(!$path['isQuestion']){
						//$path['iconCls']	= 'folder';

					} else{


					$q = Question::createQuestion($path['qType']);
					$path['iconCls'] = $q->getIconCls();

					}
				}

			//	if (isset($row['q_pos']))
	 		//		$path['q_pos'] = $row['q_pos'];
	 		//NOTE: the structure should now be always available, so there is no need to show red columns

			//	if($_POST['structure'] && $row['hasStructure'] == 0 && $path['isQuestion'])
	 		//		$path['cls'] = 'tree-text-red';
				// call this function again to display this
				// child's children
				$nodes[] = $path;
			}
			//return $nodes;
		}


		return json_encode($nodes);
	}

  function insertQuestionAction()
	{

		$parent = $_POST['parId'];
		$newId = $_POST['nodeId'];
		$text = $_POST['nodeText'];
      //  $text = $this->nodeText;
		$type = $_POST['nodeType'];
		$closed = $_POST['closed'];
		//$orderTree = $_POST['tPos'];
		//$orderGrid = $_POST['qPos'];
	$rs = $this->db->SQLexecute("SELECT id FROM $this->tableGrid WHERE q_name = '$text' ");
		if($this->db->fetchAssoc($rs) )
		{
			return "{success:false,error:'Name already exists!'}";
			return;
		}
		$idShowTogether = 0;
		if($newId == 0)
		{
			$orderGrid = 1;
			$orderTree = 1;
		}
		else
		{

				if (!$_POST['isTargetQ'])
				{
					//if target is folder, we add ad top of this folder or after it if it was closed
					if($closed == 'true')
					{
						//here we get the last childs position
						$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy desc LIMIT 1) WHERE $this->tableTree.id = $newId";
					}
					else
					{
						//here we get the first childs position
						$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy LIMIT 1) WHERE $this->tableTree.id = $newId";
					}

				}
				//we have moved the node above or below another question...we get the questions positions
				else
				{
					$closed = 'false';
					$getNewSql = "SELECT q_pos,orderBy,id_sup AS par FROM $this->tableGrid LEFT JOIN $this->tableTree ON $this->tableGrid.id = id_question WHERE $this->tableTree.id = $newId";
				}




				If (!$rs = $this->db->SQLexecute($getNewSql)) {


							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
							return;
						}
				if( !$row = $this->db->fetchAssoc($rs))
				{
					//I've used left JOIN so this error should not happen...ever!
							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
							return;
				}
				$orderGrid = $row['q_pos'];
				$orderTree = $row['orderBy'];


				if(!isset($orderGrid))
				{

					//if a folder doesn't have any childs, we can't find a valid q_pos, now can we?
					//if orderBy is 1, then we can add q_pos = 1, simple :)
					if($orderTree == 1)
					{
						$orderGrid = 1;
					}
					//else, we have to find a node above and use it's position(there must be one becouse orderBy!=1
					else
					{
						//we travel up until we find a folder or question, if we don't find any we can use q_pos = 1
						$curTreePos = $orderTree;
						while ($curTreePos--) {
							//the ULTIMATE select statement :) that got fucked up during the great shift :)
							$curSQL = "SELECT $this->tableGrid.q_pos from $this->tableTree LEFT JOIN $this->tableGrid on case when id_question = 0 then (select a.id_question from $this->tableTree a WHERE a.id_sup = $this->tableTree.id order by a.orderBy DESC limit 1  )=$this->tableGrid.id else id_question = $this->tableGrid.id end WHERE $this->tableTree.orderBy = $curTreePos AND $this->tableTree.id_sup = 0";
							If (!$rs = $this->db->SQLexecute($curSQL)) {


							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$curSQL.'"}';
						}
						$row = $this->db->fetchAssoc($rs);
						$orderGrid = $row['q_pos'];
						if(isset($orderGrid))
						{
							$orderGrid++;
							break;
						}

						}
						if(!isset($orderGrid))
							$orderGrid = 1;


					//	Echo '{success:false,error:"'.$newPosGrid.'" ,STATEMENT: "'.$curSQL.'"}';
					//	return;
					}
				}
				//if the folder is closed we have to increase the q pos!
				//else if is used, becouse if a closed folder has no children we already did the order increase
				elseif ($closed == 'true')
				{
					$orderGrid++;
				}

				if($_REQUEST['isTargetQ'])
				{
					$orderGrid++;
					$orderTree++;
				}
				elseif ($closed == 'true')
				{
					$orderTree++;
				}
				else
					$orderTree = 1;

		}

		//we increase positions of above questions
		$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos+1 WHERE q_pos >= $orderGrid";

		//we increase order in tree (!!!NEW!!!) for this parent only!!!!
		$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy+1 WHERE orderBy >= $orderTree AND id_sup = $parent";

		//we get the default values of some questions!!!
		require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');

		$this->db->LogWrite($type,true,"Question type send to createQuestion");
		$q = Question::createQuestion($type);
		$arr = $q->getDefaultValues();
		//if parent folder has shownTogether to true, we add the id_showTogether
		$stRes = $this->db->fetchRow( $this->db->SQLexecute( "SELECT showTogether FROM $this->tableTree WHERE id = $parent"));
		$idShowTogether = $stRes[0] ? $parent : 0;
		//we get the autoincrement of both tables
		$ai = max(array($this->db->getAutoIncVal($this->tableTree),$this->db->getAutoIncVal($this->tableGrid )));

		//we insert the value into the grid
		$sql[] = "INSERT INTO $this->tableTree(id,id_sup,orderBy,idLab,is_leaf) VALUES($ai, $parent ,$orderTree,'$text',true ) ";


		if (!$this->db->SQLbegin())
		{
			return '{success:false,error:"Transakcije niso omogočene!"}';
			return;
		}
		foreach ($sql as $sqlStatemens) {
			If (!$this->db->SQLexecute($sqlStatemens)) {

					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					return;
				}
		}
		//we retrive the value of the inserted question
		$treeID = $ai;
		$sqlTree = "INSERT INTO $this->tableGrid(id,q_pos,q_name,tip_sql,id_showTogether {$arr[0]} ) VALUES ($treeID,$orderGrid,'$text',$type,$idShowTogether {$arr[1]})";

		if (!$this->db->SQLexecute($sqlTree) )
		{
			$this->db->SQLrollback();
			return '{success:false,error:"'.$this->db->GetError().'"}';
		}
		//for backward compatibilty we update the id_question in tre anyway
		$this->db->SQLexecute("UPDATE $this->tableTree SET id_question = $treeID WHERE id = $treeID");

		$this->db->SQLcommit();
		$_POST['id'] = $treeID;
		$strucUpdate = new bqwcGridDataMan($this->db,$this->tableGrid);
		$strucUpdate->tableTree = $this->tableTree;
		$strucUpdate->tableGrid = $this->tableGrid;
		//$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$strucUpdate->addStructureAction();

		return '{success:true,insertId:'.$ai.'}';

	}

	function copyQuestionAction()
	{
		$data = $_POST['id_project']."|".$_POST['ids'];

		$this->db->ChangeDatabase(DB_WARPIT_MAIN);
		$sql = "INSERT INTO _WarpitClipboard VALUES(".$_SESSION['UserInfo']['id'].",1,'Questions','$data') ON DUPLICATE KEY UPDATE clipData='$data'";
		$this->db->SQLexecute($sql);
		return "{success:true}";
	}

	function pasteQuestionAction()
	{


		$parent = $_POST['parId'];
		$newId = $_POST['nodeId'];
		$text = $_POST['nodeText'];
		$type = $_POST['nodeType'];
		$closed = $_POST['closed'];
		//$orderTree = $_POST['tPos'];
		//$orderGrid = $_POST['qPos'];
	$rs = $this->db->SQLexecute("SELECT id FROM $this->tableGrid WHERE q_name = '$text' ");
		if($this->db->fetchAssoc($rs) )
		{
			return "{success:false,error:'Name already exists!'}";
			return;
		}
		$idShowTogether = 0;
		if($newId == 0)
		{
			$orderGrid = 1;
			$orderTree = 1;
		}
		else
		{

				if (!$_POST['isTargetQ'])
				{
					//if target is folder, we add ad top of this folder or after it if it was closed
					if($closed == 'true')
					{
						//here we get the last childs position
						$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy desc LIMIT 1) WHERE $this->tableTree.id = $newId";
					}
					else
					{
						//here we get the first childs position
						$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy LIMIT 1) WHERE $this->tableTree.id = $newId";
					}

				}
				//we have moved the node above or below another question...we get the questions positions
				else
				{
					$closed = 'false';
					$getNewSql = "SELECT q_pos,orderBy,id_sup AS par FROM $this->tableGrid LEFT JOIN $this->tableTree ON $this->tableGrid.id = id_question WHERE $this->tableTree.id = $newId";
				}




				If (!$rs = $this->db->SQLexecute($getNewSql)) {


							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
							return;
						}
				if( !$row = $this->db->fetchAssoc($rs))
				{
					//I've used left JOIN so this error should not happen...ever!
							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
							return;
				}
				$orderGrid = $row['q_pos'];
				$orderTree = $row['orderBy'];


				if(!isset($orderGrid))
				{

					//if a folder doesn't have any childs, we can't find a valid q_pos, now can we?
					//if orderBy is 1, then we can add q_pos = 1, simple :)
					if($orderTree == 1)
					{
						$orderGrid = 1;
					}
					//else, we have to find a node above and use it's position(there must be one becouse orderBy!=1
					else
					{
						//we travel up until we find a folder or question, if we don't find any we can use q_pos = 1
						$curTreePos = $orderTree;
						while ($curTreePos--) {
							//the ULTIMATE select statement :) that got fucked up during the great shift :)
							$curSQL = "SELECT $this->tableGrid.q_pos from $this->tableTree LEFT JOIN $this->tableGrid on case when id_question = 0 then (select a.id_question from $this->tableTree a WHERE a.id_sup = $this->tableTree.id order by a.orderBy DESC limit 1  )=$this->tableGrid.id else id_question = $this->tableGrid.id end WHERE $this->tableTree.orderBy = $curTreePos AND $this->tableTree.id_sup = 0";
							If (!$rs = $this->db->SQLexecute($curSQL)) {


							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$curSQL.'"}';
						}
						$row = $this->db->fetchAssoc($rs);
						$orderGrid = $row['q_pos'];
						if(isset($orderGrid))
						{
							$orderGrid++;
							break;
						}

						}
						if(!isset($orderGrid))
							$orderGrid = 1;


					//	Echo '{success:false,error:"'.$newPosGrid.'" ,STATEMENT: "'.$curSQL.'"}';
					//	return;
					}
				}
				//if the folder is closed we have to increase the q pos!
				//else if is used, becouse if a closed folder has no children we already did the order increase
				elseif ($closed == 'true')
				{
					$orderGrid++;
				}

				if($_POST['isTargetQ'])
				{
					$orderGrid++;
					$orderTree++;
				}
				elseif ($closed == 'true')
				{
					$orderTree++;
				}
				else
					$orderTree = 1;


		}

		//we now have the order in which we add the copied question
		//fetch all the question in the copy data
		$clipData = $this->db->get('_WarpitClipboard',"id_user = ".$_SESSION['UserInfo']['id']." AND id_type = 1",'clipData',DB_WARPIT_MAIN);
		$clipData = $clipData[0];
		$tmp = explode('|',$clipData);
		$projectId = $tmp[0];
		$copyTable = $this->db->get('_Projects',$projectId,'proj_name',DB_WARPIT_WEBCATI_BASE);
		$qIds = $tmp[1];
		$qArr =$this->db->get($copyTable.'_tree', "(id IN ($qIds) OR id_sup IN ($qIds)) AND is_leaf = 1",'id',DB_WARPIT_WEBCATI);
		$qnum = count($qArr);

		if($qnum == 0)
			return "{success:false,error:'No data!'}";

		//if we already send some changed names:
		$chgNames = $_POST['names'];
		//let's get the question info

		$res = $this->db->SQLexecute("SELECT * FROM $copyTable WHERE id IN (".implode(',',$qArr).") ORDER BY q_pos");
		while ($row = $this->db->fetchAssoc($res)) {
			if(isset($chgNames[$row['q_name']])) $row['q_name'] = $chgNames[$row['q_name']];
			$quests[] = $row;
			$qNames[] = $row['q_name'];
		}
		//let's find out if there are any duplicate names!
		$dups = $this->db->get($this->tableGrid,"q_name IN ('".implode("','",$qNames)."')",'q_name');
		if(count($dups) > 0)
		{
															//if names where already changed but are still duplicated, we send the original names!
			if($chgNames) $dups = array_keys($chgNames);
			return "{success:false,error:'dupNames',names:".json_encode($dups)."}";
		}


		//we increase positions of above questions
		$this->db->SQLexecute( "UPDATE $this->tableGrid SET q_pos = q_pos+$qnum WHERE q_pos >= $orderGrid");

		//we increase order in tree (!!!NEW!!!) for this parent only!!!!
		$this->db->SQLexecute("UPDATE $this->tableTree SET orderBy = orderBy+$qnum WHERE orderBy >= $orderTree AND id_sup = $parent");

		$strucUpdate = new bqwcGridDataMan($this->db,$this->tableGrid);
		$strucUpdate->tableTree = $this->tableTree;
		$strucUpdate->tableGrid = $this->tableGrid;

		foreach ($quests as $row) {
			$oldId = $row['id'];
			unset($row['q_pos']);
			unset($row['id_showTogether']);
			foreach ($row as &$col) {
				$col = addslashes($col);
			}


			$row['q_pos'] = $orderGrid;
			$orderGrid++;


			$treeRow['id_sup'] = $parent;
			$treeRow['orderBy'] = $orderTree;
			$orderTree++;
			$treeRow['idLab'] = "{$row['q_name']}";
			$treeRow['is_leaf'] = true;

			$this->db->SQLexecute("INSERT INTO $this->tableTree(".implode(',',array_keys($treeRow) ).") VALUES ( '".implode("','",$treeRow)."' ) " );


			$row['id'] = $this->db->GetLastInsertId();

			$this->db->SQLexecute("INSERT INTO $this->tableGrid(".implode(',',array_keys($row) ).") VALUES ( '".implode("','",$row)."' ) " );
			$this->db->SQLexecute("UPDATE $this->tableTree SET id_question = {$row['id']} WHERE id = ".$row['id']);

			//copy the language table!
			$sql = "INSERT INTO $this->tableGrid"."_language (id_language,id_question,id_text_type,lngText) SELECT id_language,{$row['id']},id_text_type,lngText FROM $copyTable"."_language WHERE id_question = $oldId";
			$this->db->SQLexecute($sql);
			//update the structure!!!
			$_POST['id'] = $row['id'];
			$strucUpdate->addStructureAction();
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		}






		return "{success:true}";
	}

	function deleteDialerAction()
	{

		$sql = "DELETE FROM $this->tableGrid WHERE tip_sql = 7 OR tip_sql = 8 OR tip_sql = 9 OR (tip_sql = 10 AND les_sql=2) OR q_pos = -1";
		if(!$this->db->SQLexecute($sql)) return $this->db->JsonError();

		return "{success:true}";
	}

	function insertGroupActionBCK()
	{
	//	$orderTree = $_POST['tPos'];
		$id = $_POST['nodeId'];

		if($id == 0)
		{

			$orderTree = 1;
		}
		else
		{

			$lastSQL = "SELECT orderBy FROM $this->tableTree WHERE id = $id";

			$rs = $this->db->SQLexecute($lastSQL);
			if($row = $this->db->fetchAssoc($rs) )
			{
				$orderTree = $row['orderBy']+1;
			}
			else
			{
				return '{success:false,error:"'.$this->db->GetError().'",statement:"'.$lastSQL.'"}';
				return;
			}
		}

		$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy+1 WHERE orderBy >= $orderTree AND id_sup = 0";

		$sql[] = "INSERT INTO $this->tableTree(id_sup,id_question,orderBy,idLab,is_leaf) VALUES( 0,0 ,$orderTree,'".$_POST['nodeText']."',false ) ";
		foreach ($sql as $sqlStatemens) {
				If (!$this->db->SQLexecute($sqlStatemens)) {

						$this->db->SQLrollback();
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
						return;
					}
			}

			return '{success:true,insertId:'.$this->db->GetLastInsertId() .'}';

	}
	function deleteGroupAction()
	{
		$id = $_POST['nodeId'];
		$deleteSql = "DELETE bt.*,b.* FROM $this->tableTree as bt left JOIN $this->tableGrid as b on b.id = bt.`id_question` WHERE id_sup = $id or bt.id = $id";
		If (!$this->db->SQLexecute($deleteSql)) {

						$this->db->SQLrollback();
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
						return;
					}

	/*	$res = $this->db->SQLexecute("SELECT id FROM $this->tableGrid order by q_pos" );
			$i = 0;
			while ($row = $this->db->fetchAssoc($res)) {
				$i++;
				$this->db->SQLexecute("update $this->tableGrid set q_pos = $i WHERE id=".$row['id'] );
				}

			$res = $this->db->SQLexecute("SELECT id FROM $this->tableTree order by orderBy" );
			$i = 0;
			while ($row = $this->db->fetchAssoc($res)) {
				$i++;
				$this->db->SQLexecute("update $this->tableTree set orderBy = $i WHERE id=".$row['id'] );
				}*/
		$this->db->SQLexecute("SET @cnt:=0");
		$this->db->SQLexecute("SET @prev:=-1");
		if(!$this->db->SQLexecute("UPDATE $this->tableTree SET orderBy = IF( @prev = (SELECT @prev := id_sup )
						,(SELECT @cnt := @cnt+1),(SELECT @cnt := 1))
						ORDER BY id_sup,orderBy"))
		{
			return '{success:false,error:"'.$this->db->GetError().',aaa:aaa"}';
			return;
		}
		$this->db->SQLexecute("SET @cnt:=0");
		if(!$this->db->SQLexecute("UPDATE $this->tableGrid SET q_pos = (SELECT @cnt := @cnt+1) WHERE q_pos > 0  ORDER BY q_pos"))
		{
			return '{success:false,error:"'.$this->db->GetError().',aaa:aaa"}';
			return;
		}

		return '{success:true}';

	}
	function moveNodeAction()
	{

		//id of the node that was dragged
		$oldId = $_POST['nodeId'];
		//id of the node that we dropped onto
		//there a 3 options: we dropped the not above this one, below or appended (see $point)
		$newId = $_POST['targetId'];
		//where the node was dropped according to the new node (later as the targeted note)
		$point = $_POST['movePoint'];

		$isNodeQ = $_POST['isNodeQ'];

		// we get the q_pos (position in questions table) and orderBy (position in the tree table) of the dragged node
		$getOldSql = "SELECT $this->tableGrid.id, q_pos,orderBy,id_sup FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = id_question WHERE $this->tableTree.id = $oldId";
		If (!$rs = $this->db->SQLexecute($getOldSql)) {

					return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getOldSql.'"}';
					return;
				}
		$row = $this->db->fetchAssoc($rs);
		$oldPosGrid = $row['q_pos'];
		$oldPosTree = $row['orderBy'];
		$oldParent = $row['id_sup'];
		$gridId = $row['id'];

		//if we dropped into the root, the pos is 1
		if($newId == 0)
		{
			$point = 'above'; //so we don't mix up ordering
			$newPosGrid = 1;
			$newPosTree = 1;
			$parent = 0;
		}
		else
		{

			//we find the new positions according to the $point
			if($point=='append')
			{
				//append means that we have moved the question into a folder (the target node is a folder)
				//we must find it's first child and replace it's position, so that the new node will take first place
				$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy LIMIT 1) WHERE $this->tableTree.id = $newId";

			}
			//if the target is not a question it means that we have moved to the root next to a folder
			//we do the same as above, only DIFFERENCE is that the parent is this node's parent and not the node itself!
			elseif (!$_POST['isTargetQ'])
			{
				if($point == 'below')
				//if point is below we order the childrend desc as to get the last child in this folder!!!
					$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy desc LIMIT 1) WHERE $this->tableTree.id = $newId";
				else
					$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy LIMIT 1) WHERE $this->tableTree.id = $newId";

			}
			//we have moved the node above or below another question...we get the questions positions
			else
			{
				$getNewSql = "SELECT q_pos,orderBy,id_sup AS par FROM $this->tableGrid LEFT JOIN $this->tableTree ON $this->tableGrid.id = id_question WHERE $this->tableTree.id = $newId";
			}

			//NOTE! later we adjust the position acording to the point of drop!!!



			If (!$rs = $this->db->SQLexecute($getNewSql)) {


						return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
						return;
					}
			if( !$row = $this->db->fetchAssoc($rs))
			{
				//I've used left JOIN so this error should not happen...ever!
						return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
						return;
			}
			$newPosGrid = $row['q_pos'];
			$newPosTree = $row['orderBy'];
			$parent = $row['par'];
		}


		if(!isset($newPosGrid))
		{
			//if a folder doesn't have any childs, we can't find a valid q_pos, now can we?
			//if orderBy is 1, then we can add q_pos = 1, simple :)
			if($newPosTree == 1)
			{
				$newPosGrid = 1;
			}
			//else, we have to find a node above and use it's position(there must be one becouse orderBy!=1
			else
			{

				//we travel up until we find a folder or question, if we don't find any we can use q_pos = 1
				$curTreePos = $newPosTree;
				while ($curTreePos--) {
					//the ULTIMATE select statement :)
					$curSQL = "SELECT $this->tableGrid.q_pos from $this->tableTree LEFT JOIN $this->tableGrid on case when id_question = 0 then (select a.id_question from $this->tableTree a WHERE a.id_sup = $this->tableTree.id order by a.orderBy DESC limit 1  )=$this->tableGrid.id else id_question = $this->tableGrid.id end WHERE $this->tableTree.orderBy = $curTreePos AND $this->tableTree.id_sup = 0";
					//echo $curSQL; return;
					If (!$rs = $this->db->SQLexecute($curSQL)) {


					return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$curSQL.'"}';
					return;
				}
				$row = $this->db->fetchAssoc($rs);
				$newPosGrid = $row['q_pos'];
				if(isset($newPosGrid))
				{
					$newPosGrid++;
					break;
				}

				}
				if(!isset($newPosGrid))
					$newPosGrid = 1;

			if($point == 'below')
			{
				$point = 'above';
				$newPosTree++;
			}

			//	Echo '{success:false,error:"'.$newPosGrid.'" ,STATEMENT: "'.$curSQL.'"}';
			//	return;
			}
		}


		//if we moved a node down, we must lower ALL indexes



		if($point == 'below')
		{	//we increase the position so that it's after the targeted note
			$newPosGrid++;
			$newPosTree++;
		}
		elseif ($point == 'append') {
			//new rule: append is first in folder so zero :)
			$newPosTree = 1;
		}



		if($isNodeQ)
		{
			if ($oldPosGrid < $newPosGrid  )
			{
				$newPosGrid--;
				if($parent == $oldParent)
					$newPosTree--;
			}
			//adding the showTogether ID if parent has it set!
			$stRes = $this->db->fetchRow( $this->db->SQLexecute( "SELECT showTogether FROM $this->tableTree WHERE id = $parent"));
			$idShowTogether = $stRes[0] ? $parent : 0;

			//we set the new position of the moved node
			$sql[] = "UPDATE $this->tableGrid SET q_pos = $newPosGrid,id_showTogether = $idShowTogether WHERE id = $gridId";
			//if we moved the node down, we decrease the position of all nodes inbetween
			//now we have 2 nodes with this new position and we lower the other one (id <> gridId)
			if ($oldPosGrid < $newPosGrid  )
			{
				$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos -1 WHERE q_pos > $oldPosGrid AND q_pos < $newPosGrid";
				$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos -1 WHERE q_pos = $newPosGrid AND id <> $gridId";
			}
			if ($oldPosGrid > $newPosGrid  )
			{//vice verse if we moved the node up
				$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos +1 WHERE q_pos < $oldPosGrid AND q_pos > $newPosGrid";
				$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos +1 WHERE q_pos = $newPosGrid AND id <> $gridId";
			}


		}
		else
		{
			$getQs = "SELECT g.id,q_pos FROM $this->tableGrid as g INNER JOIN $this->tableTree as t ON g.id = t.id_question WHERE t.id_sup = $oldId ORDER BY orderBy";

				If (!$rs = $this->db->SQLexecute($getQs)) {
								return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getQs.'"}';
								return;
							}
					while($row = $this->db->fetchAssoc($rs))
					{
						$moveQu[] = $row;
						$numQ++;
						$qWhere .= ' AND id <> '.$row['id'];

					}
					if($numQ)
					{
							$oldPosGrid = $moveQu[0]['q_pos'];
						if ($oldPosGrid < $newPosGrid  )
							{
								$newPosGrid-=$numQ;
								if($parent == $oldParent)
									$newPosTree--;
							}
						//we set the new position of the questions inside folder
						for ($i = 0;$i<$numQ;$i++)
						{
							$sql[] = "UPDATE $this->tableGrid SET q_pos = ".($newPosGrid+$i)." WHERE id = ". $moveQu[$i]['id'];
						}

						//if we moved the node down, we decrease the position of all nodes inbetween
						//now we have 2 nodes with this new position and we lower the other one (id <> gridId)
						if ($oldPosGrid < $newPosGrid  )
						{
							$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos -$numQ WHERE q_pos >= ".($oldPosGrid+$numQ)." AND q_pos < ".($newPosGrid+$numQ).$qWhere;

						}
						if ($oldPosGrid > $newPosGrid  )
						{//vice verse if we moved the node up
							$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos +$numQ WHERE q_pos < $oldPosGrid AND q_pos >= $newPosGrid".$qWhere;

						}

					}


		}
		//in tree table if parent is the same we do same as above
		$sql[] = "UPDATE $this->tableTree SET orderBy = $newPosTree, id_sup = $parent WHERE id = $oldId";
			if($parent == $oldParent)
			{
				if ($oldPosTree < $newPosTree  )
				{
					$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy -1 WHERE orderBy > $oldPosTree AND orderBy < $newPosTree AND id_sup = $parent ";
					$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy -1 WHERE orderBy = $newPosTree AND id <> $oldId AND id_sup = $parent";
				}
				if ($oldPosTree > $newPosTree  )
				{
					$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy +1 WHERE orderBy < $oldPosTree AND orderBy > $newPosTree AND id_sup = $parent";
					$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy +1 WHERE orderBy = $newPosTree AND id <> $oldId AND id_sup = $parent";
				}
			}
			//otherwise...we lower all indexes from old parent and increase all in new parent (similar to insert and delete!!!)
			else
			{
				$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy+1 WHERE orderBy > $newPosTree AND id_sup = $parent";
				$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy +1 WHERE orderBy = $newPosTree AND id <> $oldId AND id_sup = $parent";

				$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy-1 WHERE orderBy > $oldPosTree AND id_sup = $oldParent";
			}

		$this->db->SQLbegin();

		foreach ($sql as $sqlStatemens) {
			If (!$this->db->SQLexecute($sqlStatemens)) {

					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					return;
				}
		}

		$this->db->SQLcommit();

	global $qPos,$posArray;
	$qPos = 1;
	$posArray;
	orderPos(0);
	foreach ($posArray as $qId=>$qPos) {
		$sql = "UPDATE $this->tableGrid SET q_pos = $qPos WHERE id = $qId";
		$this->db->SQLexecute($sql);
	}

	//	echo "a $oldPosTree b $oldParent c $newPosTree d $parent e $point";

		//	return "{success:true,oldG:$oldPosGrid , oldT:$oldPosTree,newG:$newPosGrid , newT:$newPosTree,par:$parent,q_id:$gridId ,STATEMENT: '$getOldSql'}";

		//return "{success:true,SQL:'".$sql[3]."',SQLall:'".$sql[4]."',SQLold:'".$sql[5]."',GETold:$getNewSql}";
		return("{success:true,newpos:'$newPosTree',st:'$curSQL'}");
	}

function moveNodeBckAction()
	{

		//id of the node that was dragged
		$oldId = $_POST['nodeId'];
		//id of the node that we dropped onto
		//there a 3 options: we dropped the not above this one, below or appended (see $point)
		$newId = $_POST['targetId'];
		//where the node was dropped according to the new node (later as the targeted note)
		$point = $_POST['movePoint'];


		// we get the q_pos (position in questions table) and orderBy (position in the tree table) of the dragged node
		$getOldSql = "SELECT $this->tableGrid.id, q_pos,orderBy FROM $this->tableGrid JOIN $this->tableTree ON $this->tableGrid.id = id_question WHERE $this->tableTree.id = $oldId";
		If (!$rs = $this->db->SQLexecute($getOldSql)) {

					return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getOldSql.'"}';
					return;
				}
		$row = $this->db->fetchAssoc($rs);
		$oldPosGrid = $row['q_pos'];
		$oldPosTree = $row['orderBy'];
		$gridId = $row['id'];

		//if we dropped into the root, the pos is 1
		if($newId == 0)
		{
			$point = 'above'; //so we don't mix up ordering
			$newPosGrid = 1;
			$newPosTree = 1;
			$parent = 0;
		}
		else
		{

			//we find the new positions according to the $point
			if($point=='append')
			{
				//append means that we have moved the question into a folder (the target node is a folder)
				//we must find it's first child and replace it's position, so that the new node will take first place
				$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy LIMIT 1) WHERE $this->tableTree.id = $newId";

			}
			//if the target is not a question it means that we have moved to the root next to a folder
			//we do the same as above, only DIFFERENCE is that the parent is this node's parent and not the node itself!
			elseif (!$_POST['isTargetQ'])
			{
				$getNewSql = "SELECT q_pos,orderBy,$this->tableTree.id_sup AS par FROM $this->tableTree LEFT JOIN $this->tableGrid ON $this->tableGrid.id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $newId ORDER BY orderBy LIMIT 1) WHERE $this->tableTree.id = $newId";

			}
			//we have moved the node above or below another question...we get the questions positions
			else
			{
				$getNewSql = "SELECT q_pos,orderBy,id_sup AS par FROM $this->tableGrid LEFT JOIN $this->tableTree ON $this->tableGrid.id = id_question WHERE $this->tableTree.id = $newId";
			}

			//NOTE! later we adjust the position acording to the point of drop!!!



			If (!$rs = $this->db->SQLexecute($getNewSql)) {


						return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
						return;
					}
			if( !$row = $this->db->fetchAssoc($rs))
			{
				//I've used left JOIN so this error should not happen...ever!
						return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
						return;
			}
			$newPosGrid = $row['q_pos'];
			$newPosTree = $row['orderBy'];
			$parent = $row['par'];
		}


		if(!isset($newPosGrid))
		{
			//if a folder doesn't have any childs, we can't find a valid q_pos, now can we?
			//if orderBy is 1, then we can add q_pos = 1, simple :)
			if($newPosTree == 1)
			{
				$newPosGrid = 1;
			}
			//else, we have to find a node above and use it's position(there must be one becouse orderBy!=1
			else
			{
				//we travel up until we find a folder or question, if we don't find any we can use q_pos = 1
				$curTreePos = $newPosTree;
				while ($curTreePos--) {
					//the ULTIMATE select statement :)
					$curSQL = "SELECT $this->tableGrid.q_pos from $this->tableTree LEFT JOIN $this->tableGrid on case when id_question = 0 then (select a.id_question from $this->tableTree a WHERE a.id_sup = $this->tableTree.id order by a.orderBy limit 1  )=$this->tableGrid.id else id_question = $this->tableGrid.id end WHERE $this->tableTree.orderBy = $curTreePos";

					If (!$rs = $this->db->SQLexecute($curSQL)) {


					return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$curSQL.'"}';
					return;
				}
				$row = $this->db->fetchAssoc($rs);
				$newPosGrid = $row['q_pos'];
				if(isset($newPosGrid))
				{
					$newPosGrid++;
					break;
				}

				}
				if(!isset($newPosGrid))
					$newPosGrid = 1;


			//	Echo '{success:false,error:"'.$newPosGrid.'" ,STATEMENT: "'.$curSQL.'"}';
			//	return;
			}
		}


		//if we moved a node down, we must lower ALL indexes

		if ($oldPosGrid < $newPosGrid  )
		{
			$newPosGrid--;
			$newPosTree--;
		}
		if($point == 'below')
		{	//we increase the position so that it's after the targeted note
			$newPosGrid++;
			$newPosTree++;
		}
		elseif ($point == 'append') {
			//we increase the tree index, so that the order is after the parent
			$newPosTree++;
		}


		//we set the new position of the moved node
		$sql[] = "UPDATE $this->tableGrid SET q_pos = $newPosGrid WHERE id = $gridId";
		//if we moved the node down, we decrease the position of all nodes inbetween
		//now we have 2 nodes with this new position and we lower the other one (id <> gridId)
		if ($oldPosGrid < $newPosGrid  )
		{
			$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos -1 WHERE q_pos > $oldPosGrid AND q_pos < $newPosGrid";
			$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos -1 WHERE q_pos = $newPosGrid AND id <> $gridId";
		}
		if ($oldPosGrid > $newPosGrid  )
		{//vice verse if we moved the node up
			$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos +1 WHERE q_pos < $oldPosGrid AND q_pos > $newPosGrid";
			$sql[] = "UPDATE $this->tableGrid SET q_pos = q_pos +1 WHERE q_pos = $newPosGrid AND id <> $gridId";
		}

		//update TREE in the same way!
	$sql[] = "UPDATE $this->tableTree SET orderBy = $newPosTree, id_sup = $parent WHERE id = $oldId";

		if ($oldPosTree < $newPosTree  )
		{
			$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy -1 WHERE orderBy > $oldPosTree AND orderBy < $newPosTree";
			$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy -1 WHERE orderBy = $newPosTree AND id <> $oldId";
		}
		if ($oldPosTree > $newPosTree  )
		{
			$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy +1 WHERE orderBy < $oldPosTree AND orderBy > $newPosTree";
			$sql[] = "UPDATE $this->tableTree SET orderBy = orderBy +1 WHERE orderBy = $newPosTree AND id <> $oldId";
		}
		$this->db->SQLbegin();

		foreach ($sql as $sqlStatemens) {
			If (!$this->db->SQLexecute($sqlStatemens)) {

					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					return;
				}
		}

		$this->db->SQLcommit();

		//	return "{success:true,oldG:$oldPosGrid , oldT:$oldPosTree,newG:$newPosGrid , newT:$newPosTree,par:$parent,q_id:$gridId ,STATEMENT: '$getOldSql'}";

		//return "{success:true,SQL:'".$sql[3]."',SQLall:'".$sql[4]."',SQLold:'".$sql[5]."',GETold:$getNewSql}";
		return("{success:true}");
	}
	//function the get the TREE position for showing
	function getPosAction()
	{
		$id = $_POST['nodeId'];
		if($_POST['isQ'])
		{
			$sql = "SELECT q_pos FROM $this->tableGrid WHERE id = (SELECT id_question FROM $this->tableTree WHERE id = $id)";
		}
		else
		{
			$sql = "SELECT q_pos FROM $this->tableGrid WHERE id = (SELECT id_question FROM $this->tableTree WHERE id_sup = $id ORDER BY orderBy LIMIT 1)";
		}

			If (!$rs = $this->db->SQLexecute($sql)) {

						return '{success:false}'.$this->db->GetError().' STATEMENT: '.$sql;
					}

					$row = $this->db->fetchAssoc($rs);

					$pos = $row['q_pos']-1;
					if($pos<0)
						$pos = 0;

		/*if($id > 0)
			{//we check if there is a dialer or status in the grid, and increase the start accordingly!
				$dialerCheckSQL = "SELECT count(*) FROM $this->tableGrid WHERE q_pos < 0";
				$num = $this->db->fetchArray($this->db->SQLexecute($dialerCheckSQL) );
				$pos += $num[0];

			}*/

					return "{success:true,pos:$pos}";



	}

	function showTogetherAction()
	{
		$nodeId = $_POST['nodeId'];
		$showTog = $_POST['st'];
		$idShow = $showTog ? $nodeId : 0;

		$sql = "UPDATE $this->tableTree SET showTogether = $showTog WHERE id = $nodeId";
		If (!$this->db->SQLexecute($sql)) {	return '{success:false}'.$this->db->GetError().' STATEMENT: '.$sql;}
		$sql = "UPDATE $this->tableGrid a,$this->tableTree b SET id_showTogether = $idShow WHERE a.id = b.id_question AND b.id_sup = $nodeId";
		If (!$this->db->SQLexecute($sql)) {	return '{success:false}'.$this->db->GetError().' STATEMENT: '.$sql;}
		return "{success:true}";
	}

}

class bqwcGridDataMan extends GridDataManipulator
{

	function selectAction()
	{
		if($this->table == 'ansGrid')
		{
			// 18.8.2014 Changed by Borut (add missing_values)
			$cols[] = 'tip_sql,rot_sql,missing_values as miss_val';

			$di = $_POST['dataIndex'];
			if( $di == 'odg_sql')
			{

				$cols[] = 'open_answers as open';
				$cols[] = 'filter_answer as filter';
				$cols[] = 'answerGroups as groups';
			}
			else if($di == 'leg_sql')
			{
				$cols[] = 'open_legend as open';
				$cols[] = 'filter_legend as filter';
				$cols[] = 'legendGroups as groups';
			}
			else if($di == 'atr_sql')
			{
				$cols[] = 'open_attributes as open';
				$cols[] = 'filter_attributes as filter';
				$cols[] = 'legendGroups as groups';
			}
			// 26.6.2014 Changed by Soulskiner
			// this is for Legend Nogo Checkboxes
			if ($di == 'leg_sql') $cols[] = 'multi_nogo_legends as nogo';
				else $cols[] = 'multi_nogo_answers as nogo';


			$cols[] = 'repeat_legend';
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$sql = $this->db->SQLexecute( "SELECT ".implode(',',$cols)." FROM ".$_POST['projName']." WHERE id = ".$_POST['id']);

			$data = $this->db->fetchAssoc($sql);
			require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
			$q = Question::createQuestion($data['tip_sql'],$this->db,$data);
			$q->fillLanguage($_POST['projName'],$_POST['id'],$_POST['id_language']);
			$q->dataIndex = $di;

			$this->arr = $q->prepareAnswerGridData();
			return "{success:true, rows: ". json_encode($this->arr) .",groupData:'$q->groupData' ,upDownRot:'$q->rot_sql',repeatLegend:'$q->repeat_legend'}";


		}
		else if($_POST['styleManager'])
		{
			return $this->styleManager();
		}

		if($_POST['system'] == 'true')
		{
			$this->addWhere("q_pos < 0");
			$_POST['start'] = 0;
		}
		else if($_POST['RMtable'] != '_QuestionTypes')
		{
				$this->addWhere("q_pos > 0");
		}
		//lets build the 4 subqueris to get the data from the language tables!
		$sql = $this->db->SQLexecute("SELECT * FROM _LanguageText");
		while($row = $this->db->fetchRow($sql))
		{
			$i=$row[0];
			$var = $row[1];
			$selVpr .= ",ifnull((SELECT lngText FROM ".$this->table."_language b WHERE id_question = $this->table.id AND id_language = {$_POST['id_language']} AND id_text_type = $i),ifnull((SELECT lngText FROM ".$this->table."_language b WHERE id_question = $this->table.id AND id_language = {$_POST['id_lngDef']} AND id_text_type = $i),'')) as $var";
		}
		if($_POST['rotations'])
		{
			$selVpr .= ",(SELECT cmp.orderBy FROM ".DB_WARPIT_WEBCATI_BASE."._QuestionRotation cmp WHERE id = g.id_complex) as id_complex".
						",(SELECT cmp.orderBy FROM ".DB_WARPIT_WEBCATI_BASE."._QuestionRotation cmp WHERE id = g.id_sup) as id_packet";
		}
        //20150603 Tanis zakomentiral $grid->selectSQL
		$_POST['SQL'] = /*$grid->selectSQL = */"Select $this->table.*,ifnull({$this->table}_tree.idLab,'/') as idLab ,f.name as templateName,ifnull( {$this->table}_tree.orderBy ,(SELECT c.orderBy FROM {$this->table}_tree c WHERE c.id_question = $this->table.id )   ) as group_id ".
		"$selVpr from $this->table LEFT JOIN {$this->table}_tree ON {$this->table}_tree.id = (SELECT id_sup FROM {$this->table}_tree b WHERE b.id_question = $this->table.id )"
			." LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerManager e ON $this->table.id = e.id_question AND id_project = {$_POST['id_project']} AND type_device = 0 AND id_special = 0 LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerTemplates f ON e.id_template = f.id";

		{
			 $_POST['SQL'] .= " LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._QuestionRotation g ON $this->table.id = g.id_question AND g.id_project = ".$_POST['id_project'];

		}

		$this->whereKeyword = "HAVING";

		$this->fetchSelect();
	/*	if($_POST['id_language'] > 0 )
		{//we get all the data from the language table
			$id_lngDef = $_POST['id_lngDef'];
			$id_language = $_POST['id_language'];
			$sql = "SELECT id_question,variable,id_language,lngText FROM ".$this->table."_language a INNER JOIN _LanguageText b ON a.id_text_type = b.id_text WHERE id_language = $id_lngDef OR id_language = ".$id_language ;
			$res = $this->db->SQLexecute($sql);
			while ($row = $this->db->fetchAssoc($res))
			{
				//we prepare a 3 dimensional array with text
				$lngArr[ $row['id_question'] ][ $row['variable'] ] [ $row['id_language']  ]  = $row['lngText'];
			}

			foreach ($this->arr as &$qst) {
				if( is_array(  $lngArr[ $qst['id'] ] ) )
				{
					 //we override the basic values!
					 foreach ($lngArr[ $qst['id'] ] as $var => $varArr) {
					 	if( $varArr[$id_language] )
					 		$qst[ $var ] = $varArr[$id_language];
					 	else
					 		$qst[ $var ] = $varArr[$id_lngDef];
					 }

				}
			}

		}*/

		//we go trough the data and encalculate the goto into in json array!
		for($i=0;$i<count($this->arr);$i++)
		{
				$gotoArr = array();
				$row = &$this->arr[$i];
		    	if($row['goto_sql'] != '')
			    {
			    	$gotos = explode(',',$row['goto_sql']);
			    	foreach ($gotos as $cndProj)
			    	{
			    		$gt = array();
			    		$cndParr = explode('#',$cndProj);
			    		$gt[] = $cndParr[0];
			    		$gtName = $cndParr[1];
			    		if($gtName[0] == '!')
			    		{
			    			$gt[] = true;
			    			$gtName = substr($gtName,1);
			    			$rsProjectName = $this->db->SQLexecute("SELECT idLab from ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree WHERE id = $gtName");

			    			$rowProjectName = $this->db->fetchAssoc($rsProjectName);
			    			$gt[] = $rowProjectName['idLab'];

			    		}
			    		else
			    		{
			    			$gt[] = false;
			    			$gt[] = $gtName;
			    		}
			    		$gt[] = '&#160;';

			    		$gotoArr[] = $gt;
			    	}
			    }
			    $row['gotoData'] = json_encode($gotoArr);

			    // 21.10.2014 Changed by Borut -> added multilanguage read for answer groups
			    if (isset($row['grp_sql'])) $row['answerGroups'] = $row['grp_sql'];

		}


		return parent::selectAction();
		return $result;
	}
	function updateAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);



		//we check if the user is updating in an other language (which is always :)
		$field = $_POST['field'];
		$_POST['value'] = trim( $_POST['value'] );

		if($_POST['id_language'] > 0)
		{
			//we add this record to the language table instead of updating the original table
			//checking if its one of the text types
			$res = $this->db->SQLexecute("SELECT id_text FROM _LanguageText WHERE variable = '".$_POST['field']."'");
			if($row = $this->db->fetchRow($res)) {


				if($_POST['id_language'] ==  $_POST['id_lngDef'] && ($_POST['field'] == 'odg_sql' || $_POST['field'] == 'leg_sql' || $_POST['field'] == 'atr_sql')) {
					$repError = 	$this->repairAnswerStructure();
				}
				// if count of answers changed, answerGroups need also update
				$this->repairAnswerGroup($_POST['value']);

				$_POST['value'] = addslashes($_POST['value']);
				$idText = $row[0];
				$idQ = $_POST['id'];
				$idL = $_POST['id_language'];
				$val = $_POST['value'];
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
				if(!$val) // we delete the record
					$sql = "DELETE FROM $this->table"."_language WHERE id_language = $idL AND id_question = $idQ AND id_text_type = $idText";
				else
					$sql = "INSERT INTO ".$this->table."_language ( `id_language`,`id_question`,`id_text_type`,lngText) VALUES ($idL,$idQ,$idText,'".$_POST['value']."') ON DUPLICATE KEY UPDATE lngText = '$val'";
				$this->db->LogWrite($sql,false,"update answers");
				$this->db->SQLexecute($sql);

				return "{success:true ". ($repError ? ",error: '$repError'" : '' )." }";
			}
		}

		if($_POST['field'] == 'odg_sql' || $_POST['field'] == 'leg_sql' || $_POST['field'] == 'atr_sql') {
			$repError = $this->repairAnswerStructure();
		}
		else if($field == 'fil_sql' || $field == 'con_sql')
		{//we check if the statement is valid and if contained variables in structure exist
			//return "{success:false, error:'test'}";
		}
		else if($field == "tip_sql")
		{//we update the structure and some common stuff (like default values and shit like that) :)
			$this->repairTypeStructure();
		}
		else if($field == 'les_sql')
		{
			$_POST['id_lngDef'] = $this->db->get('_Projects',"proj_name = '$this->table'",'language',DB_WARPIT_WEBCATI_BASE);
			$_POST['id_lngDef'] = $_POST['id_lngDef'][0];
			$_POST['id_language'] = $_POST['id_lngDef'];
			$_POST['value'] = addslashes($_POST['value']);
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$this->repairAnswerStructure();
		}
		else if($field == 'open_sql')
		{
			$_POST['id_lngDef'] = $this->db->get('_Projects',"proj_name = '$this->table'",'language',DB_WARPIT_WEBCATI_BASE);
			$_POST['id_lngDef'] = $_POST['id_lngDef'][0];
			$_POST['id_language'] = $_POST['id_lngDef'];
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$repError = $this->repairAnswerStructure();
		}
		else if($field == 'variableTypeBase')
		{
			$this->repairDataTypeStructure();
		}
		else if($field == 'id_mask') //if changing the mask, check for valid mask
		{
			$idP = $this->db->get("_Projects","proj_name = '$this->table'","id",DB_WARPIT_WEBCATI_BASE);
			$id_project = $idP[0];
			$idQ = $_POST['id'];
			$val = $_POST['value'];

			if($this->db->get(WC_MASK_MANAGER,"(id_mask = $val  AND ((id_project != $id_project AND id_question != $idQ) OR (id_project = $id_project AND id_question != $idQ)))","id",DB_WARPIT_WEBCATI_BASE))
			{
				return "{success:false, error:'Mask already in use. Make a copy and use that.'}";
			}

			if($mask_id = $this->db->get(WC_MASK_MANAGER,"id_project = $id_project AND id_question = $idQ","id_mask",DB_WARPIT_WEBCATI_BASE))
			{
				//echo "Project: ".$id_project." - Question: ".idQ." - Old mask: ".$mask_id[0]." - New mask: ". $val;
				//a previously assigned mask exists, this would be the place to call a cleanup method
				//a method to delete the current masks structure
				$this->dropStructureFromMask($id_project, $idQ, $mask_id[0]);
			}

			//check if question still exists, before assigning the mask
			if($this->db->get($this->table,"id = $idQ","id",DB_WARPIT_WEBCATI))
			{
				if($val == 0)
					$val = "NULL";
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$sql = "INSERT INTO ".WC_MASK_MANAGER." (id_project, id_question, id_mask) VALUES ('$id_project','$idQ',$val)".
					   " ON DUPLICATE KEY UPDATE id_mask = $val";
				if($this->db->SQLexecute($sql))
				{	//if mask assigned successfuly, do something

					//this would be a good place to call a build method to create the masks structure
					$this->createStructureFromMask($id_project, $idQ, $val);
				}
			}
			else
			{
				return "{success:false, error:'Question does not exist.'}";
			}
			//return "{success:false, error:'project_name: $_POST[RMtable] - $id_project, id_question: $idQ, id_mask: $val'}";
		}else if($field == 'id_incentive')
        {
           $value = intval($_POST['value']);
           if($_POST['value'] == 0)
           {
               $value = 'NULL';
           }

           $sql = "UPDATE " . DB_WARPIT_WEBCATI . "." . $this->table . " SET id_incentive = " . $value . ", incentive_possibilites = 0 WHERE id = " . intval($_POST['id']);
           If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';    }
           return "{success:true, STATMENT: '$sql' }";
        }


		$this->db->ChangeDatabase($_POST['database']);
		return parent::updateAction();
	}



	private function createStructureFromMask($id_project, $id_question, $id_mask)
	{
		include_once (PATH_TO_ROOT.'_class/createQuestion/CustomMask.php');

		$customMask = new CustomMask($this->db);
		$customMask->id_mask = $id_mask;
		if($qname = $this->db->get($this->table,"id = $id_question","q_name",DB_WARPIT_WEBCATI))
			$customMask->q_name = $qname[0];
		else
			return "{success:false, error:'Cannot create structure of mask.'}";

		$xml = $customMask->getMaskXML();

		if($xml)
		{
			//echo "XML JE";
			$str = $customMask->getChildrenRecursive($xml);

			foreach ($str as $tmp)
			{
				$fieldName = $tmp;
				$fields[] = 'ADD '. $fieldName;
			}

			//try to ALTER the structure (drop columns)
			try
			{
				//echo "trying: ". "ALTER TABLE $this->table"."_structure ".implode(',',$fields);
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$this->db->SQLexecute( "ALTER TABLE $this->table"."_structure ".implode(',',$fields) );
			}
			catch (Exception $e)
			{
				$error = "Structure repair failure!";
			}
		}
	}


	private function dropStructureFromMask($id_project, $id_question, $id_mask)
	{


		include_once (PATH_TO_ROOT.'_class/createQuestion/CustomMask.php');

		$customMask = new CustomMask($this->db);
		$customMask->id_mask = $id_mask;
		if($qname = $this->db->get($this->table,"id = $id_question","q_name",DB_WARPIT_WEBCATI))
			$customMask->q_name = $qname[0];
		else
			return "{success:false, error:'Cannot drop structure of mask.'}";

		$xml = $customMask->getMaskXML();

		if($xml)
		{
			//echo "XML JE";
			$str = $customMask->getChildrenRecursive($xml);

			foreach ($str as $tmp)
			{
				$fieldName = explode(" ",$tmp);
				$fields[] = 'DROP '. $fieldName[0];
				$fieldsBck[] = $tmp;
			}

			//the place to put in backup fields code
			if(!$conf = $_POST['deleteConfirm'])
			{//let's check if there is data in structure
				//echo "Checking if data exists!";
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$hasData = $this->db->get($this->table.'_structure','id') ? true : false;
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);

				if($hasData)
				{ //don't ask any questions, just make a backup
					$this->backupColumns($fieldsBck);
				}
			}


			//try to ALTER the structure (drop columns)
			try
			{
				//echo "trying: ". "ALTER TABLE $this->table"."_structure ".implode(',',$fields);
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$this->db->SQLexecute( "ALTER TABLE $this->table"."_structure ".implode(',',$fields) );
			}
			catch (Exception $e)
			{
				$error = "Structure repair failure!";
			}
		}

		//echo $id_project." ". $id_question." ". $id_mask;

	}

	public function hasScriptAction()
    {
        $scriptSql = "SELECT * FROM " . DB_WARPIT_WEBCATI . ".". $_POST['RMtable'] . "_script WHERE script > ''";
        $scriptRes = $this->db->SQLexecute($scriptSql);
        return $this->db->NumRows($scriptRes) > 0;
    }



	protected function repairAnswerGroup($val) {
		$val = str_replace("/ ","<*>",$val);
		$answerCount = count(explode("/",$val));
		$answerGroups = $this->db->get($this->table,"id = ".$_POST['id'],'answerGroups',DB_WARPIT_WEBCATI);
		//echo "/*";print_r($answerGroups);echo "*/";

		if ($answerGroups[0]) {
			$groupsArray = explode("<|>",$answerGroups[0]);
			if ($groupsArray[0]) {
				$groupAdd = array();
				$groupAnswerCount = count(explode(",",$groupsArray[0]));
				if ($answerCount > $groupAnswerCount) {
					for($n=0;$n<($answerCount - $groupAnswerCount);$n++) {
						$groupAdd[] = "0";
					}
					$groupsArray[0] = $groupsArray[0].",".implode(",",$groupAdd);
					$answerGroupsWrite = implode("<|>",$groupsArray);

					$sql = "UPDATE ".DB_WARPIT_WEBCATI.".".$this->table." SET answerGroups='".$answerGroupsWrite."' WHERE id=".$_POST['id'];
					$this->db->LogWrite($sql,false,"update group");
					$this->db->SQLexecute($sql);
				}
			}
		}
		return true;
	}


	function deleteAction()
		{
			if($this->table == 'ansGrid')
		{
			return "{success:true}";
		}

			if(!$_POST['id'])
			{
				return '{success:true}';
			}

			if(!$conf = $_POST['deleteConfirm'])
			{//let's check if there is data in structure
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

				/*20151110 Tanis Če je bila velik tabela je SQL pri preverjanju,
				* če obstajajo podatki padel.
				*/
			//	$hasData = $this->db->get($this->table.'_structure','id') ? true : false;
					$hasData = $this->db->get($this->table.'_structure','id LIMIT 1', "id") ? true : false;
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);

				if($hasData)
					return "{success:false, error: 'hasData'}";
			}
			$bckDate = date("YmdHis");
			$fields = array();
			include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
			include_once(PATH_TO_ROOT."config.php");
		foreach ($_POST['id'] as $id) {
				$gr[] = 'id = '.$id;
				$tr[] = 'id_question = '.$id;

				$q = Question::createQuestionFromTable($this->db,$this->table,$id);
				//we get current structure fields!
				$f = $q->getStructureFields();
				if($f)
				{

					if($conf == 'backup')
					{
						$q->typeBase = getDataType($q->variableTypeBase);
						$q->typeOpen = getDataType($q->variableTypeOpen);
						$q->resetStructure();
						$fieldsBck = $q->getStructureFields();

						$this->backupColumns($fieldsBck);

					}


					foreach ($f as $tmp) {
					 	$fieldName = explode(" ",$tmp);
						$fields[] = 'DROP '. $fieldName[0];
					}
				}

			//try to DELETE the template assignment from MaskManager
			try {
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$this->db->SQLexecute( "DELETE FROM ".WC_MASK_MANAGER." WHERE id_question=".$id." AND id_project=".$_POST['id_project']);
			}
			catch (Exception $e)
			{
				$error = "Structure repair failure!";
			}
		}



			//try to ALTER the structure (drop columns)
			try {
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$this->db->SQLexecute( "ALTER TABLE $this->table"."_structure ".implode(',',$fields) );
		}
			catch (Exception $e)
			{
				$error = "Structure repair failure!";
			}
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);

			//$this->db->SQLexecute("UNLOCK TABLES");
			$sql = 'DELETE FROM '.$_REQUEST['RMtable'].' WHERE '.implode(' OR ',$gr);
		//	return $sql;
			If (!$rs = $this->db->SQLexecute($sql)) {

					return '{success:false}'.$this->db->GetError().' STATEMENT: '.$sql;
					return;
				}
			$sql = "DELETE FROM {$this->table}_tree WHERE ".implode(' OR ',$tr);
			If (!$rs = $this->db->SQLexecute($sql)) {

					return '{success:false}'.$this->db->GetError().' STATEMENT: '.$sql;
					return;
				}
			//20150707 Tanis we delete question dependent texts from _language table
			$sql = "DELETE FROM {$this->table}_language WHERE ".implode(' OR ',$tr);
			If (!$rs = $this->db->SQLexecute($sql))
			{

					return '{success:false}'.$this->db->GetError().' STATEMENT: '.$sql;
					return;
			}
			$this->db->SQLexecute("SET @cnt:=0");
			$this->db->SQLexecute("SET @prev:=-1");
			if(!$this->db->SQLexecute("UPDATE $this->tableTree SET orderBy = IF( @prev = (SELECT @prev := id_sup )
							,(SELECT @cnt := @cnt+1),(SELECT @cnt := 1))
							ORDER BY id_sup,orderBy"))
			{
				return '{success:false,error:"'.$this->db->GetError().',aaa:aaa"}';
				return;
			}
			$this->db->SQLexecute("SET @cnt:=0");
			if(!$this->db->SQLexecute("UPDATE $this->tableGrid SET q_pos = (SELECT @cnt := @cnt+1) WHERE q_pos > 0 ORDER BY q_pos"))
			{
				return '{success:false,error:"'.$this->db->GetError().',aaa:aaa"}';
				return;
			}

				return '{success:true}';

		}
	function insertAction()
	{
		if($this->table == 'ansGrid')
		{
			return "{success: true}";
		}
		return parent::insertAction();
	}

	function updateNameAction()
	{
		$value = $_POST['value'];
		$rs = $this->db->SQLexecute("SELECT id FROM $this->table WHERE q_name = '$value' ");
		$id = $_POST['id'];
		if($this->db->fetchAssoc($rs) )
		{
			return "{success:false,error:'Name already exists!'}";
			return;
		}
		//update structure!!!
		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		include_once(PATH_TO_ROOT."config.php");
		$q = Question::createQuestionFromTable($this->db,$this->table,$_POST['id']);
		$oldName = $q->q_name;
		//we get current structure fields!
		$fieldsOld = $q->getStructureFields();

		$q->q_name = $value;
		$q->typeBase = getDataType($q->variableTypeBase);
		$q->typeOpen = getDataType($q->variableTypeOpen);
		$q->resetStructure();
		$fieldsNew = $q->getStructureFields();

		if($c = count($fieldsOld) )
		{
			foreach ($fieldsOld as $key => $val)

			{
				$chg[] = "CHANGE ".$val.' '.$fieldsNew[$key];
			}
			$sqlStruc = "ALTER TABLE $this->table"."_structure ".implode(',',$chg);
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			try{


			$this->db->SQLexecute($sqlStruc);
			}catch (Exception $e){
				$repError = "Structure update error!";
			}
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		}

		$sql[] = 'UPDATE '.$this->table." SET q_name = '$value' WHERE id = ".$id;
		$sql[] = "UPDATE $this->tableTree SET idLab = '$value' WHERE id_question = ".$id;



		foreach ($sql as $sqlStatemens) {
				If (!$this->db->SQLexecute($sqlStatemens)) {

						$this->db->SQLrollback();
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
						return;
					}
			}

		$searchFields = explode(',',"goto_sql,fil_sql,con_sql,filter_answer,filter_legend");
		foreach ($searchFields as $fld) {
			$updSql[] = $fld. " = REPLACE($fld,'".$oldName."_','".$value."_')";
			$updSql[] = $fld. " = REPLACE($fld,'".$oldName." ','".$value." ')";
		}

		//let's find fields that contains the questions in conditions!
		$sql = "UPDATE $this->table SET ".implode(',',$updSql);
		$this->db->SQLexecute($sql);

		return "{success:true ". ($repError ? ",error: '$repError'" : '' )." }";

	}


	function insertDialerAction()
	{

		$text = 'dialer';
		//we insert the dialer
		$values[] = "(-10,'$text',7,1,0,'','',0)";

		//we insert the status bar				status bar jumps to welcome template
		$values[] = "(-9,'tStatus',8,1,0,'\$status==1#-6,\$status==90#-8,true#-10','',0)";
		//we insert the appointment question
		$values[] = "(-8,'appointment',9,1,0,'','',1)";
		//question for emm...no telefone variables
		$values[] = "(-1,'noTelInfo',5,1,0,'','',1)";
		$sql = "INSERT INTO $this->tableGrid(q_pos,q_name,tip_sql,hasStructure,must_answer,goto_sql,fil_sql,isFinal ) VALUES ".implode(',',$values);
		if(!$this->db->SQLexecute($sql)) return $this->db->JsonError();
		$sql = "SELECT id FROM $this->tableGrid WHERE q_pos = -1";
		$idI = $this->db->fetchRow($this->db->SQLexecute($sql));
		$idI = $idI[0];
		$this->db->SQLexecute("INSERT INTO $this->tableGrid"."_language (id_language,id_question,id_text_type,lngText)".
								" VALUES ({$_POST['id_lngDef']},$idI,2,'There are no more numbers under current conditions!')");

		//we must increase the auto increment value of the tree so that we don't get duplicate IDs!
		$curAI = $this->db->getAutoIncVal($this->tableTree) + 4;
		$this->db->SQLexecute("ALTER TABLE $this->tableTree AUTO_INCREMENT = $curAI");


		// get project ID
		$id_array = $this->db->get('_Projects',"proj_name = '$this->tableGrid'",'id',DB_WARPIT_WEBCATI_BASE);
		$id_project = $id_array[0];


		if($telDb = $_POST['telDatabase'])
		{//let's set a database if already chosen
			//$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			//$this->db->SQLexecute("UPDATE _Projects SET id_telname = $telDb WHERE proj_name = '$this->tableGrid'");
			//we have to call all the events that happen on selecting database (createing tables fields etc!
			//we include the file as we would with change table!
			//prepare post data:
			$_POST['RMcomp'] = 'grid';
			$_POST['database'] = DB_WARPIT_WEBCATI_BASE;
			$_POST['action'] = 'changeDatabase';
			$_POST['id_project'] = $id_project;
			$_POST['projName'] = $this->tableGrid;
			$_POST['value'] = $telDb;
			$db = $this->db;
			include (PATH_TO_ROOT."webcati/_ajax/buildQuestionare/ajax.showVariables.php");

            print "/*" . $this->tableGrid ."*/";
			exit;
		}

		return "{success:true}";


	}

	function updateGotoAction()
	{
		//echo $_POST['goTo'];

		$goto = json_decode(stripslashes( $_POST['goTo']),true);

		$arr = array();
		foreach ($goto as $line) {
			//test if question or project exists :D
			$text = $line['question'];
			$cnd = $line['cnd'];
			if($line['toProject'])
			{
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				$rs = $this->db->SQLexecute("SELECT id FROM _ProjectsTree WHERE idLab = '$text' ");
				if($rw = $this->db->fetchAssoc($rs) )
				{
					$arr[] = $cnd.'#!'.$rw['id'];
				}
				else
				{
					return "{success:false,error:'Project $text does not exist!'}";
					return;
				}


			}
			else
			{
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
				if(is_numeric($text))
					$where = "q_pos = $text";
				else
				{
					$where = "q_name = '$text'";
					$rs = $this->db->SQLexecute("SELECT id FROM $this->table WHERE $where ");
				//	echo "SELECT id FROM $this->table WHERE q_name = '$text' "; return;
					if(!$this->db->fetchAssoc($rs) )
					{
						return "{success:false,error:'Question $text does not exist!'}";
					}
				}
				$arr[] = $cnd.'#'.$text;
			}

		}

		$value = implode(',',$arr);
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$this->db->SQLexecute("UPDATE ".$this->table." SET goto_sql = '".addslashes($value)."' WHERE id = ".$_REQUEST['id']);
		return '{success:true}';

	}

	function updateAnswersAction()
	{
		$dataIndex = $_POST['dataIndex'];
		$ans = $_POST['value'];
		$nogo = $_POST['nogo'];
		$fil_ans = $_POST['filter_answer'];
		$open_data = $_POST['open_data'];
		// 17.8.2014 Changed by Borut -> added missing value definition
		$miss_val_data = $_POST['miss_val_data'];
		$rotFrom = $_POST['rotFrom'];
		$rotTo = $_POST['rotTo'];
		$groups = $_POST['groups'].'<|>'.$_POST['groupLayout'].'<|>'.$_POST['groupData'] ;
		$id = $_POST['id'];
		//if structure table exist, let's try to update it
		$_POST['id_lngDef'] = $this->db->get('_Projects',"proj_name = '$this->table'",'language',DB_WARPIT_WEBCATI_BASE);
		$_POST['id_lngDef'] = $_POST['id_lngDef'][0];
		$_POST['field'] = $dataIndex;
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$repError = $this->repairAnswerStructure();
		if($_POST['id_language'] > 0)
		{
			$diSet = '';
			if($dataIndex == 'odg_sql')
				$idText = 3;
			else if($dataIndex == 'leg_sql')
				$idText = 4;
			else
				$idText = 5;

			$idL = $_POST['id_language'];

			$sql = "INSERT INTO ".$this->table."_language ( `id_language`,`id_question`,`id_text_type`,lngText) VALUES ($idL,$id,$idText,'".addslashes($ans)."')
					ON DUPLICATE KEY UPDATE lngText = '".addslashes($ans)."'";
			//echo "/*$sql*/";
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$this->db->SQLexecute($sql);

			// 21.10.2014 Changed by Borut -> added multilanguage save for answer groups
			// text type for groups is defined under id=8
			$sql = "INSERT INTO ".$this->table."_language ( `id_language`,`id_question`,`id_text_type`,lngText) VALUES ($idL,$id,8,'".addslashes($groups)."')
					ON DUPLICATE KEY UPDATE lngText = '".addslashes($groups)."'";
			//echo "/*$sql*/";
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$this->db->SQLexecute($sql);

		}
		else
		{
			$diSet = "$dataIndex = '$ans',";
		}
		if($dataIndex == 'odg_sql') {
			// 17.8.2014 Changed by Borut -> added missing values definition
			$sql = "UPDATE $this->table SET $diSet missing_values='$miss_val_data', multi_nogo_answers = '$nogo', answerGroups = '$groups',filter_answer = '$fil_ans',open_answers = '$open_data',srot_sql = '$rotFrom',erot_sql = '$rotTo',open_sql = '{$_POST['sliderData']}',rot_sql='{$_POST['upDownRot']}' WHERE id = ".$id;
		} else if($dataIndex == 'leg_sql')
			// 26.6.2014 Changed by Soulskiner -> added multi_nogo_legends
			// 02.06.2015 Changed by Tanis -> added missing values definition
			$sql = "UPDATE $this->table SET $diSet missing_values='$miss_val_data', multi_nogo_legends = '$nogo', filter_legend = '$fil_ans',legendGroups = '$groups',open_legend = '$open_data',srotLegend = '$rotFrom',erotLegend = '$rotTo' ,repeat_legend='{$_POST['repeatLegend']}' WHERE id = ".$id;
		else
			$sql = "UPDATE $this->table SET $diSet filter_attributes = '$fil_ans',open_attributes = '$open_data',srotAttributes = '$rotFrom',erotAttributes = '$rotTo' WHERE id = ".$id;

		If (!$res = $this->db->SQLexecute($sql)) {

			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			return;
		}
		return "{success:true ". ($repError ? ",error: '$repError'" : '' )." }";
	}

	function createStructureAction()
	{

		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		include_once(PATH_TO_ROOT."config.php");

		if(!$_POST['deleteConfirm'])
		{
			//let's check if there is data in structure
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			if($this->db->TableExists($this->table.'_structure'))
			{
				$sql = "SELECT id FROM $this->table"."_structure LIMIT 1";
				if($this->db->fetchRow( $this->db->SQLexecute($sql) ))
				{
					return "{success:false,error:'dataExist' }";
				}
			}
		}
		$projects = explode(',',$_POST['id_project']);
		foreach ($projects as $id_project) {


			// we delete all statsitics about which user has done interview.
			// so with existing link after recreate structure we can do again survey
			$sql = "DELETE FROM ".DB_WARPIT_WEBCATI_BASE."._www_interviewer_statistics WHERE id_project = ".$id_project;
			$this->db->SQLexecute($sql);

			$SQLadd_filds = "(id int(7) NOT NULL AUTO_INCREMENT, id_clien int(5), flag_cli int(1), user_id int(5),`user_type` tinyint, id_loginSID int(11), id_device tinyint, id_language tinyint UNSIGNED, smpl_var int(1), sp_adult int(1), sp_man int(1), id_site char(250),status int(8),status_rec int(8), flag_bad int(3) NOT NULL DEFAULT 99,t_status int(11) UNSIGNED, t_start int(11) UNSIGNED, t_stop int(11) UNSIGNED,d_status DATETIME, d_start DATETIME,d_stop DATETIME, t_pause int(11) NOT NULL default '0',t_diffs int(10) NOT NULL default '0', QT_user_id int(5) NULL";

			//if a database is selected we add the fields required
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$sql = "SELECT id_telname,language,proj_name, id_capiTable FROM _Projects WHERE id = $id_project";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			$row = $this->db->fetchRow($res);
			$oldTel = $row[0];
			$id_language = $row[1];
			$this->table = $row[2];
			$capiTel = $row[3];

			// add capi sample field into structure if project is also CAPI oriented
			// Borut - 2015.07.02, address and table
			if ($capiTel > 0) {
				$SQLadd_filds .= ',CRCrec varchar(35) NULL';
				$SQLadd_filds .= ',id_capi_address int(10) NULL';
				$SQLadd_filds .= ',id_capi_table int(10) NULL';
				$SQLadd_filds .= ',id_capi_sample int(10) NULL';
			}

			if($oldTel > 0)
			{//we have a database...let's add field
				//first the basic database fields
				$addFields[] = 'id_tel int(8)';
				$addFields[] = 'id_telname int(8)' ;
				$sql = "SELECT name FROM _TelephoneTblDefaultVar WHERE use_in_index = 1";
				if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
				while($row = $this->db->fetchRow($res))
					$addFields[] = 'TP_'.$row[0].' INT(10)';

				$sql = "SELECT name,type FROM _TelephoneTablesAddon WHERE id_telbaza = $oldTel";
				if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
				while($row = $this->db->fetchRow($res))
					$addFields[] = 'TP_'.$row[0].' '.getDataType($row[1]);
				if($addFields)
				{
					$SQLadd_filds .= ','.implode(',',$addFields);
				}
			}

			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			//let's get the answer data from the langauge table
			$sql = "SELECT id_question,variable,lngText FROM $this->table"."_language INNER JOIN _LanguageText ON id_text = id_text_type WHERE id_language = ".$id_language." AND (id_text_type = 3 OR id_text_type = 4 OR id_text_type = 5)";
			If (!$res = $this->db->SQLexecute($sql)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
			$lngArr = array();
		    while ($row = $this->db->fetchAssoc($res))
		    {
		    	$lngArr[ $row['id_question'] ][ $row['variable'] ] = $row['lngText'];
		    }

			$sql = "SELECT * FROM $this->table order by q_pos";

			If (!$res = $this->db->SQLexecute($sql)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}

		    while ($row = $this->db->fetchAssoc($res))
		    {
		    	$row['typeBase'] = getDataType($row['variableTypeBase']);
		    	$row['typeOpen'] = getDataType($row['variableTypeOpen']);

		    	if($lngArr[ $row['id'] ] )
		    	{
		    		foreach ($lngArr[ $row['id'] ] as $textType => $lngText) {
		    			$row[ $textType ] = $lngText ;
		    		}

		    	}


		    	$q = Question::createQuestion($row['tip_sql'],$this->db,$row);
		    	$fields = $q->getStructureFields();
		    	if(is_array($fields) && count($fields) )
		    	{
		    		$SQLadd_filds .= ','.implode(',',$fields);
		    	}
		    	if($row['use_for_quotas'])
		    	{
		    		$SQLadd_filds .= ',QT_'.$row['q_name']." INT(4)";
		    	}

		    }
		    //adding extra fields!
		    $this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

			$extraFields = $this->db->get('_ProjectExtraVariables','id_project = '.$id_project );
			if($extraFields)
				foreach ($extraFields as $exFld) {
					$SQLadd_filds .= ',EV_'.$exFld['var_name'].' '. getDataType( $exFld['var_type'] );
				}



			// Add by Borut 2015.01.26
			// in case of merged projects, sp_man column must be indexed
			$SQLadd_filds = $SQLadd_filds.", PRIMARY KEY (id),
											INDEX `user_id_type` (`user_id`,`user_type`),
											INDEX `status` (`status`,`status_rec`),
											INDEX `id_device` (`id_device`),
											INDEX `id_language` (`id_language`),
											INDEX `flag_bad` (`flag_bad`),
											INDEX `id_site` (`id_site`(5)),
											INDEX `id_loginSID` (`id_loginSID`),
											INDEX `sp_man` (`sp_man`)
											) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";


			// load backup properties from config table
			$bckDate = date("YmdHis");
			$backupOptions = configLoader::loadConfig('backup');


			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			if ($backupOptions['structure']) {
				$this->db->RenameTable($this->table.'_structure',$this->table.'_structure_C'.$bckDate);
			} else {
				$this->db->SQLexecute("DROP TABLE IF EXISTS {$this->table}_structure");
			}

			$SQLadd_filds = "CREATE TABLE ".$this->table."_structure ".$SQLadd_filds;
			$res_createStructure = $this->db->SQLexecute($SQLadd_filds);
			if($res_createStructure)
			{
				$sql = "UPDATE ".DB_WARPIT_WEBCATI.".$this->table SET hasStructure = 1";
				if(!$this->db->SQLexecute($sql)) {
					//$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
					return "{success:false,sql: '$sql',error:'{$this->db->getError()}' }";
				}


				if ($backupOptions['engine']) {
					$this->db->RenameTable($this->table.'___EngineLog',$this->table.'___EngineLog_C'.$bckDate);
				} else {
					$this->db->SQLexecute("DROP TABLE IF EXISTS {$this->table}___EngineLog");
				}

				//create the ___EngineLog table
				$sql =	"CREATE TABLE IF NOT EXISTS `".$this->table."___EngineLog` (
				  `id` int(11) NOT NULL auto_increment,
				  `id_structure` int(11) NOT NULL,
				  `id_question` smallint(6) NOT NULL,
				  `id_user` int(11) NOT NULL,
				  `user_type` tinyint(4) NOT NULL,
				  `id_language` SMALLINT NULL,
				  `q_name` varchar(25) collate utf8_unicode_ci NOT NULL,
				  `currentRotationString` text collate utf8_unicode_ci NOT NULL,
				  `questionnairePath` text collate utf8_unicode_ci NOT NULL,
				  `engineTime` int(11) NOT NULL,
				  `questStart` int(11),
				  `questEnd` int(11),
				  `arriveStatus` tinyint(4),
				  `eventLogger` text,
				  PRIMARY KEY  (`id`),
				  INDEX `id_structure` (`id_structure`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
				if(!$this->db->SQLexecute($sql)) return "{success:false,error:\"".$this->db->GetError()."\"}";

			}
			else
			{
				return "{success:false,sql: '$SQLadd_filds',error:'{$this->db->getError()}' }";
			}


			if($this->db->TableExists($this->table.'___telLog')) {
				if ($backupOptions['log']) {
					$this->db->RenameTable($this->table.'___telLog',$this->table.'___telLog_C'.$bckDate);


					// create new log table
					// get tel table name
					$telTable_array = $this->db->get('_TelephoneTables',"id=".$oldTel,'name',DB_WARPIT_WEBCATI_BASE);
					$telTable_name = $telTable_array[0];

					include_once (PATH_TO_ROOT.'webcati/_class/class.sampler.php');
					$clog = new sampler($id_project, $this->db, 0);

					$td = $this->db->describe("tel___".$telTable_name);
					if(substr($td['telephone']['type'],0,3) == 'int') {
						$telType = 'int';
					} else {
						$telType = 'varchar(30)';
					}

					$clog->createLogTable($this->table,$telType);
				} else {
					$this->db->SQLexecute('TRUNCATE TABLE '.$this->table.'___telLog');
				}
			}


			if($this->db->TableExists($this->table.'___quotaCalc'))
				$this->db->SQLexecute("TRUNCATE TABLE ".$this->table.'___quotaCalc');

		}
		return "{success:true}";
	}

	function addStructureAction()
	{
		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		include_once(PATH_TO_ROOT."config.php");

		$nodeId = $_POST['id'];

		//include "./main/create_qt_telephone_structure.php3";
		//if ($webuserspool_location) include "./main/create_qt_pool_structure.php";
		$sql = "SELECT * FROM $this->table  WHERE id = $nodeId";

		If (!$res = $this->db->SQLexecute($sql)) {

			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';

		}else{

		    if ($row = $this->db->fetchAssoc($res))
		    {
		    	$row['typeBase'] = getDataType($row['variableTypeBase']);
		    	$row['typeOpen'] = getDataType($row['variableTypeOpen']);

		   		$this->db->LogWrite($row['tip_sql'], true, "addStructure");
		    	$q = Question::createQuestion($row['tip_sql'],$this->db,$row);
		    	$q->fillLanguage($this->table,$nodeId);
		    	$fields = $q->getStructureFields();
		    	if(is_array($fields) && count($fields) )
		    	{
		    		$SQLadd_filds .= ','.implode(',',$fields);
		    	}
		    	else return "{success:true}";

			    if($row['use_for_quotas'])
		    	{
		    		$SQLadd_filds .= ',QT_'.$row['q_name']." INT(4)";
		    	}
		    }

		}

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

		//remove the first comma
		$tmp = explode(',',$SQLadd_filds,2);

		$tmp = explode(',',$tmp[1]);
		for ($i = 0;$i<count($tmp);$i++ )
		{
			$tmp[$i] = 'ADD '.$tmp[$i];
		}


		$SQLadd_filds = "ALTER TABLE ".$this->table."_structure " .implode(',',$tmp);
		$this->db->LogWrite($SQLadd_filds, true, "ALTER TABLE structure");

		if($this->db->SQLexecute($SQLadd_filds))
		{
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$sql = "UPDATE $this->table SET hasStructure = 1 WHERE id = $nodeId";
			if(!$this->db->SQLexecute($sql))
			{
				return "{success:false,sql: '$SQLadd_filds',error:'{$this->db->getError()}' }";
			}

			return "{success:true}";
		}
		else
		{
			return "{success:false,sql: '$SQLadd_filds',error:'{$this->db->getError()}' }";
		}
	}


	//if answer or legend field is changed, we update the structure accordingly
	function repairAnswerStructure()
	{

		//we do this only if we change the default language!
		if($_POST['id_language'] != $_POST['id_lngDef']) return;
		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		include_once(PATH_TO_ROOT."config.php");

		$id = $_POST['id'];
		$row = $this->db->get($this->table,$id );
		//add answer and legend from language!
		$sql = "SELECT id_question,variable,lngText FROM $this->table"."_language INNER JOIN _LanguageText ON id_text = id_text_type WHERE id_question = $id AND id_language = ".$_POST['id_lngDef']." AND (id_text_type = 3 OR id_text_type = 4 OR id_text_type = 5)";
		If (!$res = $this->db->SQLexecute($sql)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}

		$row['typeBase'] = getDataType($row['variableTypeBase']);
		$row['typeOpen'] = getDataType($row['variableTypeOpen']);


	    while ($lngRow = $this->db->fetchAssoc($res))
	    {
	    	$row[ $lngRow['variable'] ] = $lngRow['lngText'];
	    }

        //22.1.2015 Tanis added  to check if we have duplicate answer values
        if($row['tip_sql'] != 3)
        {
        	$input = Question::cleanAnswerString($_POST['value']);
            $ansLine = explode('<*>', $input);
            $valuesArray = array();
            foreach($ansLine as $line)
            {
                $exLine = explode(' ', $line, 2);
                if(!in_array($exLine[0], $valuesArray))
                {
                    $valuesArray[] = $exLine[0];
                }
                else
                {
                    echo "{success:false,error:'You can\'t have two same values for answers'}";
                    exit;
                }
            }
        }

		$q = Question::createQuestion($row['tip_sql'],null,$row);
		//we get current structure fields!
		$fieldsOld = $q->getStructureFields();
		$origName = $q->q_name;
		$q->q_name .= '_bck'.date("YmdHis");
		$q->resetStructure();
		$fieldsBck = $q->getStructureFields();

		$q->q_name = $origName;
		$q->$_POST['field'] = $_POST['value'];
		if($_POST['field'] == 'odg_sql' && isset($_POST['open_data']))
			$q->open_answers = $_POST['open_data'];
		$q->resetStructure();
		$fieldsNew = $q->getStructureFields();
		if($fieldsNew === false || $fieldsOld === false)
		{
			echo "{success:false,error:'Answers have open endings! Please use grid to update!'}";
			exit;
		}
		//if there are rows in structure we produce a warrning instead of adding/dropping



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






		$fields = array_diff($fieldsOld,$fieldsNew);

			echo "/*";
		print_r($fieldsOld);
		print_r($fieldsNew);
		print_r($fields);
	   echo "*/";

		try {
		if(count($fields)) //if fields are to be deleted, we check if data exists and ask for warning!
		{



			foreach ($fields as  &$tmp)
			{
				$tmp = explode(' ',$tmp);
				$tmp = $tmp[0];
			}
			//check if there are data and prevent drop!
			$getStrucRow = $this->db->SQLexecute("SELECT id FROM $this->tableGrid"."_structure");
			if($this->db->fetchRow($getStrucRow) && !$conf = $_POST['updateConfirm'])
			{
				echo "{success:false,error:'hasData',fields: ".json_encode( array_values( $fields )). " }";
				exit;
			}
			if($conf == 'backup')
			{

				foreach ($fields as $key => $val)
					{
						$testBck[] = $fieldsOld[$key];
					}
				$this->backupColumns($testBck);

				//$sql = "ALTER TABLE $this->table"."_structure ".implode(',',$sqlBck)."";
			}

				$sql = "ALTER TABLE $this->table"."_structure DROP ".implode(',DROP ',$fields)."";

			$this->db->SQLexecute($sql);

		}



		$fields = array_diff($fieldsNew,$fieldsOld);

		if(count($fields))
		{

			$sql = "ALTER TABLE $this->table"."_structure ADD (".implode(',',$fields).")";
			$this->db->SQLexecute($sql);
		}
		try {


			}
			catch (Exception $e){
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
				return "Structure update error!";
			}

		//print_r($fields);
		//echo "*/";

		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		}
		catch(Exception $e)
		{
			return "Structure repair error!";
		}

	}
	//if question type is changed we must update the strucutre...special procotion is made if data already exist!
	function repairTypeStructure()
	{

		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		include_once(PATH_TO_ROOT."config.php");

		$id = $_POST['id'];
		$row = $this->db->get($this->table,$id,null,DB_WARPIT_WEBCATI);

		$qOld = Question::createQuestion($row['tip_sql'],$this->db);
		$qOld->fill($this->table,$id);
		$oldFields = $qOld->getStructureFields();
		$newType = $_POST['value'];

		$qNew = Question::createQuestion($newType,$this->db);
		$qNew->fill($this->table,$id);



		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$hasData = $this->db->get($this->table.'_structure','id') ? true : false;

		if(!$hasData)//we change the default data type!
		{
			$dt = $qNew->changeDefaultDataType();
			if($dt != $qOld->variableTypeBase)
			{
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
				$this->db->SQLexecute("UPDATE $this->table SET variableTypeBase = $dt WHERE id = $id");
			}
		}
		//let's update the show type, so we don't get unsuported showtypes!
		$suportetTypes = $qNew->supportedShowTypes();

		if(!in_array($row['les_sql'],$suportetTypes))
		{
			$defShowType = $suportetTypes[0];
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$this->db->SQLexecute("UPDATE $this->table SET les_sql = $defShowType WHERE id = $id");
			$qNew->les_sql = $defShowType;
		}

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

		$qNew->typeBase = getDataType($qNew->variableTypeBase);
		$qNew->typeOpen = getDataType($qNew->variableTypeOpen);

        print "/*";
        //var_dump($qNew->changeDefaultDataType());
        var_dump($qNew->typeBase);
        var_dump($qNew->typeOpen);
        print "*/";

		$newFields = $qNew->getStructureFields();
		//lets get the old fields again with data type!
		$qOld->typeBase = getDataType($qOld->variableTypeBase);
		$qOld->typeOpen = getDataType($qOld->variableTypeOpen);
		$oldFields = $qOld->getStructureFields();

		if($newFields === false || $oldFields === false)
		{
			//update back the changed values!
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$this->db->SQLexecute("UPDATE $this->table SET variableTypeBase = {$row['variableTypeBase']},les_sql = '{$row['les_sql']}' WHERE id = $id");
			echo  "{success:false, error:'New type not compatible with answers' }"; exit;
		}


		$fieldsToAdd = array_diff($newFields,$oldFields);
		$fieldsToDelete = array_diff($oldFields,$newFields);



	   //fields to delete dont need the type
	   foreach ($fieldsToDelete as &$fldd) {
	   	$tmp = explode(' ',$fldd);
	   	$fldd = $tmp[0];
	   }

	   	echo "/*";
		print_r($fieldsToDelete);

	   echo "*/";
		if(count($fieldsToDelete) )
		{
			if(!($conf = $_POST['updateConfirm']))
			{

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

				if($hasData)
				{
					//check if this type change allows recode!
					$canRecode = $qOld->changeTypeCanRecode($newType) ? 'true' : 'false';

					echo "{success:false, error: 'hasData',canRecode:$canRecode, fields: ".json_encode(array_values($fieldsToDelete)). " }";
					exit;
				}
				else $conf = 'ok'; //so that the fields get dropped!
			}


		}
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		//we need to add fields first, so that we can recode :)  if we dont recode we need to delete fields first so that add some with same name
		if(count($fieldsToAdd) && $conf === 'recode')
		{
			$sql = "ALTER TABLE $this->table"."_structure ADD ".implode(',ADD ',$fieldsToAdd);
			$this->db->SQLexecute($sql);
		}
		if($conf)
		{
			if($conf == 'backup')
			{

					$qOld->typeBase = getDataType($qOld->variableTypeBase);
					$qOld->typeOpen = getDataType($qOld->variableTypeOpen);
					$qOld->resetStructure() ;
					$fieldsBck = $qOld->getStructureFields();

					$this->backupColumns($fieldsBck);

			}
			else if($conf == 'recode')
			{
				$qOld->changeTypeRecode($qNew,$this->table);
			}
			$sql = "ALTER TABLE $this->table"."_structure DROP ".implode(',DROP ',$fieldsToDelete);
			$this->db->SQLexecute($sql);
		}

		if(count($fieldsToAdd) && $conf != 'recode')
		{
			$sql = "ALTER TABLE $this->table"."_structure ADD ".implode(',ADD ',$fieldsToAdd);
			$this->db->SQLexecute($sql);
		}


		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
	}
	//repair structure if base type of structure is changed
	function repairDataTypeStructure()
	{
		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		include_once(PATH_TO_ROOT."config.php");

		$id = $_POST['id'];
		$q = Question::createQuestionFromTable($this->db,$this->table,$id);
		$fields = $q->getStructureFields();
		$newType = getDataType($_POST['value']);
		if(is_array($fields) && count($fields))
		{
			foreach ($fields as $key => $f) {
				if(substr($key,0,1) != 'o')
					$mod[] = "MODIFY $f $newType";
			}
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$this->db->SQLexecute("ALTER TABLE $this->table"."_structure ".implode(',',$mod));
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		}
	}
	public function backupColumns($fields)
	{
		echo "/*";
		print_r($fields);
		echo count($fields);
		echo "*/";



		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "CREATE TABLE IF NOT EXISTS $this->table"."___structure_bck (id int(7) NOT NULL,
		PRIMARY KEY  (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;";
		$this->db->SQLexecute($sql);

		$bckDate = date("YmdHis");

		foreach ($fields as $field)
		{
			$name = explode(' ',$field,2);
			$fieldsBckStr[] = $name[0].'_'.$bckDate.' '.$name[1];
			$fieldsBckNames[] = $name[0].'_'.$bckDate;
			$fieldsNames[] = $name[0];
			$onDuplicate[] = $name[0].'_'.$bckDate." = a.".$name[0];
		}

		$sql = "ALTER TABLE $this->table"."___structure_bck ADD ".implode(',ADD ',$fieldsBckStr);
		$this->db->SQLexecute($sql);

		$sql = "INSERT INTO $this->table"."___structure_bck (id,".implode(',',$fieldsBckNames). ") SELECT id, ".implode(',',$fieldsNames). " FROM $this->table"."_structure a
		ON DUPLICATE KEY UPDATE ".implode(',',$onDuplicate);
		if($this->db->SQLexecute($sql))
			return true;
		else
			return false;


	}

	function loadAction()
	{
	/*	$sql = "SELECT a.*,c.name as templateName FROM $this->table a LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerManager b ON a.id = b.id_question AND id_project = {$_POST['projId']} LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerTemplates c ON b.id_template = c.id WHERE a.id = ".$_REQUEST['id'];

		If (!$res = $this->db->SQLexecute($sql)) {

			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';

		}else{

			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			//so we can fetch project names!!!
		    If ($row = $this->db->fetchAssoc($res)) {


		    	$gotoArr = array();
		    	if($row['goto_sql'] != '')
			    {
			    	$gotos = explode(',',$row['goto_sql']);
			    	foreach ($gotos as $cndProj)
			    	{
			    		$gt = array();
			    		$cndParr = explode('#',$cndProj);
			    		$gt[] = $cndParr[0];
			    		$gtName = $cndParr[1];
			    		if(is_numeric($gtName))
			    		{
			    			$gt[] = true;
			    			$rsProjectName = $this->db->SQLexecute("SELECT idLab from _ProjectsTree WHERE id = $gtName");

			    			$rowProjectName = $this->db->fetchAssoc($rsProjectName);
			    			$gt[] = $rowProjectName['idLab'];

			    		}
			    		else
			    		{
			    			$gt[] = false;
			    			$gt[] = $gtName;
			    		}
			    		$gt[] = '';

			    		$gotoArr[] = $gt;
			    	}
			    }


		    	foreach ($row as $key => $val) {

		    		$nRow['podatki['.$key.']']=$val;
		    	}
		    	$nRow['gotoData'] = json_encode($gotoArr);


		    	return '{success: true, data:'.json_encode($nRow).'}';
		    }else{
		    	return '{success: false,error:"no data!"}';
		    }

		}*/
	}
	function getAnswerAction()
	{
		if(!$_POST['id_language'])
		{
			$_POST['id_lngDef'] = $this->db->get('_Projects',"proj_name = '$this->table'",'language',DB_WARPIT_WEBCATI_BASE);
			$_POST['id_lngDef'] = $_POST['id_lngDef'][0];
			$_POST['id_language'] = $_POST['id_lngDef'];
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		}

		    	require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');


		    	$q = Question::createQuestionFromTable($this->db,$this->table,$_POST['id']);



		    	if(!$q->getAnswersForSelect($data,$idToNum))	return '{success: false,error:"no data!"}';

		    	if(!$data && $q->hasMultiAnswer() )
		    	{
		    		$dArr = $q->getAnswerArray(); //explode('/',$row[0]);
		    		foreach ($dArr as $k=>$val) {
		    			$finD[] = ($k+1).'_x '.$val[0].' '.$val[1];
		    			//we save the positions on which a certain ID is!
						$idToNum[ $val[0] ] = $k+1;
		    		}

		    		$data = implode('/',$finD);

		    	}

		    	if($q->open_answers)
		    	{
		    		$openAns = explode(':',$q->open_answers);
		    		if($data == '')
		    		{
		    			//no data means (probably) single response
		    			$data.= ' normal/opn open';
		    		}
		    		else
		    		{
			    		foreach ($openAns as $openAnsItem)
			    		{
							$data .='/opn'.$idToNum[ $openAnsItem  ].' open '.$openAnsItem;
						}
		    		}

		    		//$data .= 'dr drugo';
		    	}
		    	$data = $q->cleanAnswerString($data);
		    		return '{success: true, data:'.json_encode($data).'}';



	}

	function exportXMLAction(){
		header( "Content-Type: text/csv" );
   		header( "Content-Disposition: attachment; filename=\"export.xml\";" );
   		include(PATH_TO_ROOT.'webcati/_class/ExportProjects.php');
   		$e = new ExportProjects($this->db);
   		return $e->export($_POST['project_id']);

	}

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	function exportXMLApiAction(){
   		include(PATH_TO_ROOT.'webcati/_class/ExportProjects.php');
   		$e = new ExportProjects($this->db);
   		return $e->export($_POST['project_id']);

	}

	function updateUseForQuotasAction(){
		$value = $_POST['value'];
		//we add QT_name in structure table!
		//first we check if structure exists
		$tableStruc = $this->table.'_structure';
		$name = $_POST['q_name'];
		$sql = "UPDATE $this->table SET use_for_quotas=$value WHERE id = ".$_POST['id'];
		$this->db->SQLexecute($sql);

		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		if($this->db->TableExists($this->table.'_structure' ))
		{
			if($value)
				$sql  = "ALTER TABLE $tableStruc ADD (QT_$name INT(4))";
			else
				$sql = "ALTER TABLE $tableStruc DROP QT_$name";
			$this->db->SQLexecute($sql);
		}
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);

		return "{success:true}";
	}

	function saveScriptAction()
	{
		$id = $_POST['id_question'];
		$value = $_POST['value'];
		$idEvent = $_POST['idEvent'];
		$sql = "REPLACE $this->table"."_script (id_question,id_event,script) VALUES  ($id,$idEvent,'".addslashes( $value )."') ";
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
        $rtn['success'] = true;
        $rtn['hasScript'] = $this->hasScriptAction();
		return json_encode($rtn);
	}

	function getScriptAction()
	{
		$idEvent = $_POST['idEvent'];
		$sql = "SELECT script FROM $this->table"."_script WHERE id_event = $idEvent AND id_question = ".$_POST['id'];
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		$row = $this->db->fetchRow($res);
		$arr['success'] = true;
		$arr['value'] = $row[0];
		//return "{success:true,value:'".addslashes($row[0])."' }";
		return json_encode($arr);
	}
	function selectScriptEventsAction()
	{
		$res = $this->db->SQLexecute( "SELECT * FROM $this->table");
		while($row = $this->db->fetchAssoc($res) )
		{
			$row['name'] = $row['name'].' ('.$row['parser'].')';
			$this->arr[] = $row;
		}
		return parent::selectAction();

	}

	function getAllLanguageAction()
	{
		$idProj = $_POST['id_project'];
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$res = $this->db->SQLexecute("SELECT * FROM _LanguageCodepage WHERE enable = 1");
		while ($row = $this->db->fetchAssoc($res))
			$this->arr[] = $row;

		$res = $this->db->SQLexecute("SELECT id_language FROM _LanguageProjects WHERE id_project = $idProj");
		while ($row = $this->db->fetchRow($res))
			$sel[$row[0]] = true;

		return "{success:true,rows:".json_encode($this->arr).", selectedLng:".json_encode($sel)." }";
	}

	function addLanguageAction()
	{



		$idProj = $_POST['id_project'];
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$_POST['lng'][] = $_POST['defLng'];
		foreach ($_POST['lng'] as $lng) {
			$insert[] = "($lng,$idProj)";
		}
		$this->db->SQLexecute("DELETE FROM _LanguageProjects WHERE id_project = $idProj");

		$sql = "INSERT INTO _LanguageProjects (id_language,id_project) VALUES ".implode(',',$insert);
		$this->db->SQLexecute($sql);

		$res = $this->db->SQLexecute("SELECT id_language,country_code,cp_comment FROM _LanguageProjects INNER JOIN _LanguageCodepage a ON a.id = id_language WHERE id_project = $idProj");
		while ($row = $this->db->fetchRow($res))
		{
			$sel[] = array( $row[0] , $row[1].' - '.$row[2]);
		}

		return "{success:true,data:".json_encode($sel). "}";
	}

	function getNextQuestionAction()
	{
		$tableName = $this->db->get('_Projects',$_POST['id_project'],'proj_name',DB_WARPIT_WEBCATI_BASE);
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);

		$sql = "SELECT id,q_name FROM $tableName WHERE disable_question = 0";
		switch ($_POST['qGet']) {
			case 'first':
			$sql .= " AND q_pos > 0  ORDER BY q_pos ASC";
			break;
			case 'last':
			$sql .= " ORDER BY q_pos DESC";
			break;
			case 'next':
				$qPos = $this->db->get($tableName,$_POST['qId'],'q_pos');
			$sql .= " AND q_pos > $qPos ORDER BY q_pos ASC";
			break;
			case 'previous':
				$qPos = $this->db->get($tableName,$_POST['qId'],'q_pos');
				if($qPos <= 1) $qPos = 2;
				$sql .= " AND q_pos < $qPos ORDER BY q_pos DESC";
			break;

			default:
				;
			break;
		}
		$sql .= " LIMIT 1";
		$row = $this->db->fetchAssoc($this->db->SQLexecute($sql));
		if(!$row)
		{
			$row['id'] = $_POST['qId'];
			$row['q_name'] = $this->db->get($tableName,$row['id'],'q_name');
		}
		return "{success:true, id:".$row['id'].",qName: '".$row['q_name']."' }";

	}

	function qComboAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$sql = "SELECT id,q_name FROM $this->table WHERE q_pos > 0 AND ( tip_sql = 1 OR tip_sql = 3 )  ORDER BY q_pos";
		$res = $this->db->SQLexecute($sql);
		$rows[] = array('id' => 0,'q_name' => '');
		while ($row = $this->db->fetchAssoc($res))
		{
			$rows[] = $row;
		}

		return "{success:true, rows: ".json_encode($rows)." }";
	}


	/*
	 * function returns an array of masks from css designer
	 */
	function maskComboAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT id,name FROM $this->table WHERE is_leaf = 1";
		//$sql = "SELECT A.id as id,A.name as name FROM Warpit_Webcati_base._MaskTemplates A " .
				"LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.".".WC_MASK_MANAGER." B ON (A.id=B.id_mask) " .
				"WHERE A.is_leaf = 1 AND B.id_project IS NULL";
		$res = $this->db->SQLexecute($sql);
		$rows[] = array('id' => 0,'name' => '');
		while ($row = $this->db->fetchAssoc($res))
		{
			$rows[] = $row;
		}

		return "{success:true, mask_rows: ".json_encode($rows)." }";
	}


	function getShowAsAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$sql = "SELECT id,showAs FROM $this->table";
		$res = $this->db->SQLexecute($sql);

		while ($row = $this->db->fetchAssoc($res))
		{

			switch ($row['id']) {
				case 1:
				$row['single'] = 1;
				$row['scale'] = 1;
				break;
				case 2:
				$row['single'] = 1;
				$row['scale'] = 1;
				break;
				case 3:
				$row['open'] = 1;
				break;
				case 4:
				$row['multi'] = 1;
				break;
				case 5:
				$row['scale'] = 1;
				break;
				case 6:
				$row['open'] = 1;
				break;
				case 7:
				$row['single'] = 1;
				$row['scale'] = 1;
				break;
				case 8:
				$row['single'] = 1;
				$row['multi'] = 1;
				$row['scale'] = 1;
				break;
				default:
					;
				break;
			}
			$rows[] = $row;
		}
		return "{success:true, rows: ".json_encode($rows)." }";
	}

	function styleManager($idP = NULL)
	{
		require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');

		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$designer = "_DesignerManager";
		if ($idP > 0) {
			$id_project = $idP;
		} else {
			$id_project = $_POST['id_project'];
		}

		//first, lets get the project default template!
		$projMain = $this->db->get($designer,"id_project = $id_project AND id_question = 0 AND id_type = 0 AND id_qpos = -999 AND id_special = 0 AND type_device = 0",'id_template');
		if(!$projMain)
		{
			//if not exist we use the system defualt!
			$projMain = $this->db->get($designer,"id_project = 0 AND id_question = 0 AND id_type = 0 AND id_qpos = -999 AND id_special = 0 AND type_device = 0",'id_template');
			$mainSet = 'system';
		}
		else
		{
			$mainSet = 'project';
		}
		//lets get all position and type defualts
		$sql = $this->db->SQLexecute("SELECT id_template,name,id_qpos FROM $designer a INNER JOIN _DesignerTemplates b ON a.id_template = b.id WHERE id_qpos > -998");
		while ($row = $this->db->fetchRow($sql))
		{
			$qposTemplates[$row[2]] = $row;
		}
		$sql = $this->db->SQLexecute("SELECT id_template,name,id_type FROM $designer a INNER JOIN _DesignerTemplates b ON a.id_template = b.id WHERE id_type > 0 AND id_project = 0");
		while ($row = $this->db->fetchRow($sql))
		{
			$typeTemplates[$row[2]] = $row;
		}
		$projMain = $projMain[0];
		$projMainName = $this->db->get('_DesignerTemplates',$projMain,'name');

		$sql = "SELECT a.id,a.q_name,b.id_template,c.name,a.q_pos,a.tip_sql,d.id_template AS id_ansTemp,e.name AS name_ansTemp FROM ".DB_WARPIT_WEBCATI.".$this->table AS a LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerManager AS b ON a.id = b.id_question AND b.id_project = $id_project AND b.id_special = 0 LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._DesignerTemplates AS c ON b.id_template = c.id ".
		"LEFT JOIN $designer AS d ON a.id = d.id_question AND d.id_project = $id_project AND d.id_special = 6 LEFT JOIN _DesignerTemplates AS e on d.id_template = e.id ORDER BY q_pos";
		$res = $this->db->SQLexecute($sql);
		$this->arr = array();
		while ($row = $this->db->fetchAssoc($res))
		{
			$q = Question::createQuestionFromTable($this->db,$this->table,$row['id']);
			$qSpecType = $row['tip_sql'].'0'.$q->les_sql .'0'. $q->getSpecialType();
			if($qps = $qposTemplates[ $row['q_pos'] ] )
			{
				$row['id_template'] =  $qps[0];
				$row['name'] = $qps[1];
				$row['tempFrom'] = 'position';
			}
			else if($typ = $typeTemplates[ $row['tip_sql'] ] )
			{
				$row['id_template'] =  $typ[0];
				$row['name'] = $typ[1];
				$row['tempFrom'] = 'type';
			}

			else if(!$row['id_template'])
			{
				$row['id_template'] = $projMain;
				$row['name'] = $projMainName;
				$row['tempFrom'] = $mainSet;
			}
			else
				$row['tempFrom'] = 'question';

			if(!$row['id_ansTemp'] && $typ = $typeTemplates[ $qSpecType ] )
			{
				$row['id_ansTemp'] =  $typ[0];
				$row['name_ansTemp'] = $typ[1];
				$row['tempFromAns'] = 'type';
			}
			else
				$row['tempFromAns'] = 'question';

			$this->arr[] = $row;
		}
        $rtnData['success'] = TRUE;
        $rtnData['SQL'] = $sql;
        $rtnData['rows'] = $this->arr;

        return json_encode($rtnData);

		//return "{\"success\":true,SQL:\"$sql\", rows:".json_encode($this->arr)."}";

	}

		function addDesignAction(){
		$tempId = $_POST['template_id'];
			$projId = $_POST['id_project'];
		if($_POST['isProject'] )
		{

			$sql = "INSERT INTO _DesignerManager (id_template,id_project,type_device) ".
			"VALUES ($tempId,$projId,{$_POST['forDevice']})"."ON DUPLICATE KEY UPDATE id_template=$tempId";
		}
		else
		{
			$templateType = $_POST['templateType'];
			if($_POST['selections'])
			{
				$ids = explode(',', $_POST['ids'] );
			}
			else
			{
				$sql = $this->createSelectSQL();
				if(!$res = $this->db->SQLexecute($sql)){return $this->db->JsonError();};
				while ($row = $this->db->fetchAssoc($res))
				{
					$tmp[] = $row['id'];
				}
				//$ids = implode(',',$tmp);
				$ids = $tmp;
			}
			foreach ($ids as $id) {

					$values[] = "($tempId,$projId,$id,{$_POST['forDevice']},$templateType)";
			}



			$sql = "INSERT INTO _DesignerManager (id_template,id_project,id_question,type_device,id_special) ".
			"VALUES ". implode(',',$values).
			"ON DUPLICATE KEY UPDATE id_template=$tempId";
		}
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		return "{success:true}";
	}
	function removeDesignAction()
	{
		$projId = $_POST['id_project'];
		$idDevice = $_POST['forDevice'];
		$templateType = $_POST['templateType'];
		if($_POST['isProject'])
			$sql = "DELETE FROM _DesignerManager WHERE id_project = $projId AND id_question =0 AND type_device = $idDevice AND id_special=0";
		else
			$sql = "DELETE FROM _DesignerManager WHERE id_project = $projId AND id_question IN ({$_POST['ids']}) AND type_device = $idDevice AND id_special=$templateType";
		$this->db->SQLexecute($sql);
		return "{success:true}";
	}

	public function incentiveComboAction()
	{
	    $sql = "SELECT * FROM " . DB_WARPIT_USERSPOOL . "._IncentiveGroups WHERE is_leaf = 1 AND deleted = 0";
	    If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';    }
	    $rows = array();
        $rows[] = array('id' => 0, 'idLab' => '(None)');
	    while($row = $this->db->fetchAssoc($res))
	    {
	        $rows[] = $row;
	    }

        $rtnData['success'] = TRUE;
        $rtnData['rows'] = $rows;
        $rtnData['STATEMENT'] = $sql;
        return json_encode($rtnData);
	}

}

?>
