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

include_once (PATH_TO_ROOT."init.php");
include (PATH_TO_ROOT."webcati/init.php");
//recursive function to get all XML elements!

class MaskPanelXMLManipulator {
	/**
	 * the sm
	 *
	 * @var SimpleXMLElement
	 */
	public $xml;
	
	public $parentId;
	public $panelType;
	public $panelId;
	private $fields = array();
	private $fieldsBck = array(); 
	
	function __construct($db,$xml) 
	{
		$this->db = $db;
		$this->xml = $xml;
		$this->parentId = $_POST['parent'];
		$this->panelType = $_POST['type'];
		$this->panelId = $_POST['id'];
		
	}
	
	private function getIcon($type)
	{
		$sql = "SELECT node_img FROM ".WC_MASK_ELEMENTS." WHERE type = ".$type;
		if(!$rs = $this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			if ($row = $this->db->fetchArray($rs))
			{
				return $row[0];
			}
	}
	
	private function getLabel($type,$idTemplate)
	{
		if($type)
		{
		$sql = "SELECT idLab FROM ".WC_MASK_ELEMENTS." WHERE type = ".$type;
		if($idTemplate)
		{
			$sql.= " AND id_template = ".$idTemplate;
		}
		if(!$rs = $this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			if ($row = $this->db->fetchArray($rs))
			{
				return $row[0];
			}
		}
		return 'Panel';
		
	}
	/**
	 * function recursively finds children in an XML object
	 *
	 * @param unknown_type $xmlObj
	 * @param unknown_type $id
	 * @return SimpleXMLElement
	 */
	private function findChildrenById($xmlObj,$id) {
		$attr = $xmlObj->attributes();
	  	if($attr['id'] == $id )
	  	{
	  		return $xmlObj;
	  	}
	  foreach($xmlObj->children() as $child) {
	    if($res = $this->findChildrenById($child,$id))
	    	return $res;
	  }
	  return false;
	}
	
	private function templateInUse($idTemplate)
	{
		$sql = "SELECT id_project,id_question FROM ".WC_MASK_MANAGER." WHERE id_mask = ".$idTemplate;
		
		if(!$rs = $this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			if ($row = $this->db->fetchArray($rs))
			{
				return $row;
			}
			return false;
	}
	
	
	/**
	 * 
	 * function inserts a Panel to the Mask panel (Objects, Overview)
	 * @author RMplus
	 * 
	 */
	public function insertPanelAction()
	{
		
			/*foreach ($xml as $key => $val) {
				echo $key;
				print_r($val);
			}*/
			$attr = array();
		/*	$attr['height'] = 20;
			$attr['width'] = 20;
			$attr['position'] = 'relative';*/
			if(is_array( $_POST['attr'] ))
				$attr = $_POST['attr']; 	
			
			//let's fetch all the default values for this type
			$sql =	"SELECT properties_name,`default_value` FROM _MaskProperties a "
				  . "INNER JOIN _MaskElemPropLink b ON a.id = b.id_property "
				  . "WHERE object_type = $this->panelType AND default_value != ''";
				  
			if(!$rs = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			while ($row = $this->db->fetchAssoc($rs))
			{
				if(!isset($attr[$row['properties_name']]))
					$attr[$row['properties_name']] = $row['default_value'];
			}
			
			switch ($this->panelType) {
				//horizontal panel
				case 1:
					$type = 'DIV';
				break;
				//vertical panel
				case 2:
					$type = 'DIV';
				break;
				//window
				case 5:
					$type = 'WINDOW';
				break;
				//text field
				case 1006:
					$type = 'TEXTFIELD';
				break;
				//radio button item
				case 1007:
					$type = 'RADIOBUTTON';
				break;
				//checkbox item
				case 1008:
					$type = 'CHECKBOX';
				break;
				//dropdown item
				case 1009:
					$type = 'DROPDOWN';
				break;
				//radio button group
				case 1012:
					$type = 'RADIOBUTTONGROUP';
				break;
				//checkbox group
				case 1013:
					$type = 'CHECKBOXGROUP';
				break;
				//dropdown group
				case 1014:
					$type = 'DROPDOWNGROUP';
				break;
				
				//label item
				case 1015:
					$type = 'LABEL';
				break;
				
				default:
					$type = "DIV";
				break;
			}
			 
			$par = $this->findChildrenById($this->xml,$this->parentId);
			if($par)
			{
				$itemIndex = $_POST['itemIndex'];
				if($itemIndex || $itemIndex === '0')
				{
					//$parDom = dom_import_simplexml($par);
					$ind = 0;
					foreach ($par->children() as $chr) {
						$ind++;
						if($ind > $itemIndex) // all those nodes need to be deleted and reAdded :)
							$tmp[] = $chr;
						
					}
					if($tmp)
					foreach ($tmp as $chr) {
						$dom = dom_import_simplexml( $chr );
						$dom->parentNode->removeChild($dom);
					}
					
					
				}
				$new = $par->addChild($type);
				if($tmp)
				{
					$parDom = dom_import_simplexml($par);
					foreach ($tmp as $chr) {
							$parDom->appendChild( dom_import_simplexml ($chr ) );
						}
				}
				$new->addAttribute('id',$this->panelId);
				$new->addAttribute('type',$this->panelType);
				foreach ($attr as $name => $val) {
					$new->addAttribute($name,$val);
				}
				
				
				$curXML = $this->xml->asXML();
				$sql = "UPDATE ".WC_MASK_TEMPLATES." SET template_xml = '$curXML' $templateType WHERE id = " . $_POST['templateId'];
				if(!$this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				
				
				//this is the place to add building structure method
				if($row = $this->templateInUse($_POST['templateId']))
				{
					//template in use
					$id_project = $row[0];
					$id_question = $row[1];
					
					$idP = $this->db->get("_Projects","id = '$id_project'","proj_name",DB_WARPIT_WEBCATI_BASE);
					$project_name = $idP[0];
					
					include_once (PATH_TO_ROOT.'_class/createQuestion/CustomMask.php');
		
					$customMask = new CustomMask($this->db);
					$customMask->id_mask = $id_mask;
					if($qname = $this->db->get($project_name,"id = $id_question","q_name",DB_WARPIT_WEBCATI))
						$customMask->q_name = $qname[0];
					else
						return "{success:false, error:'Cannot create structure of mask.'}";
					
					switch ($this->panelType) {
						//text field
						case 1006:
							$structure = $customMask->q_name."_".$this->panelId." text";
						break;
						//radio button item
						case 1007:
							$structure = false;
						break;
						//checkbox item
						case 1008:
							$structure = $customMask->q_name."_".$this->parentId."_".$this->panelId." varchar(50)";
						break;
						//dropdown item
						case 1009:
							$structure = false;
						break;
						//radio button group
						case 1012:
							$structure = $customMask->q_name."_".$this->panelId." varchar(50)";
						break;
						//checkbox group
						case 1013:
							$structure = false;
						break;
						//dropdown group
						case 1014:
							$structure = $customMask->q_name."_".$this->panelId." varchar(50)";
						break;
						default:
							$structure = false;
						break;
					}
					
					if($structure !== false)
					{
						//alter the table
						$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
						$this->db->SQLexecute( "ALTER TABLE $project_name"."_structure ADD ".$structure );
					}
				}
				
				return "{success:true}";
			}
			else {
				return "{success:false, error:'Warning! $this->parentId not found in ".$this->xml->asXML()."'}" ;
			}
	}
	
	
	
	public function movePanelAction()
	{
		$templateId = $_POST['templateId'];
		if($_POST['type']==1008) //checkbox item
		{
			if($this->templateInUse($templateId))
			{
				if(!isset($_POST['confirmed']))
				{
					return '{success:false}'; //ask what to do in forms.questionnaireMaskPanel? backup or delete?
				}
				/*elseif(isset($_POST['confirmed']) && $_POST['confirmed']=="backup")
				{
					//backup the data before moving the checkbox
				}
				elseif(isset($_POST['confirmed']) && $_POST['confirmed']=="delete")
				{
					//do not backup the data before moving the checkbox
				}*/
			}
		}
		
		$target = $this->findChildrenById($this->xml,$this->panelId);
		
		$par = $this->findChildrenById($this->xml,$_POST['newParent']);
		$itemIndex = $_POST['itemIndex'];
		
		if($itemIndex || $itemIndex === '0')
		{
					$ind = 0;
					foreach ($par->children() as $chr) {
						$ind++;
						$attr = $chr->attributes();
						if($ind > $itemIndex && $attr['id'] != $this->panelId) // all those nodes need to be deleted and reAdded :)
							$tmp[] = $chr;
						
					}
					if($tmp)
					foreach ($tmp as $chr) {
						$dom = dom_import_simplexml( $chr );
						$dom->parentNode->removeChild($dom);
					}
		}
		//we remove the child
		$this->removeAction();
		//we add the child
		$parDom = dom_import_simplexml($par);
		$parDom->appendChild( dom_import_simplexml( $target));
		
		if($tmp)
		{
			
			foreach ($tmp as $chr) {
					$parDom->appendChild( dom_import_simplexml ($chr ) );
				}
		}
		
		$curXML = $this->xml->asXML();
		$sql = "UPDATE ".WC_MASK_TEMPLATES." SET template_xml = '$curXML' $templateType WHERE id = " . $_POST['templateId'];
		if(!$this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		
		
		return '{"success":true}';
	}
	
	public function removeAction()
	{
		$par = $this->findChildrenById($this->xml,$this->parentId);
		$templateId = $_POST['templateId'];
		
		if($par)
		{
			if($template_in_use = $this->templateInUse($_POST['templateId']))
			{
				//template in use
				$id_project = $template_in_use[0];
				$id_question = $template_in_use[1];
				
				$idP = $this->db->get("_Projects","id = '$id_project'","proj_name",DB_WARPIT_WEBCATI_BASE);
				$project_name = $idP[0];
				
				include_once (PATH_TO_ROOT.'_class/createQuestion/CustomMask.php');
				include_once (PATH_TO_ROOT.'webcati/_ajax/buildQuestionare/class.buildQuestionnaire.php');
	
				$customMask = new CustomMask($this->db);
				$questionnaireObject = new bqwcGridDataMan($this->db,$project_name); 
				$customMask->id_mask = $id_mask;
				$hasData = $this->db->get($project_name.'_structure','id') ? true : false;
				if($qname = $this->db->get($project_name,"id = $id_question","q_name",DB_WARPIT_WEBCATI))
					$customMask->q_name = $qname[0];
				else
					return "{success:false, error:'Cannot create structure of mask.'}";
			}
			
			foreach($par->children() as $seg)
			{
				
			    if($seg['id'] == $this->panelId) { //located the top child panel (first child of a parent)
			        $dom=dom_import_simplexml($seg);
			        
			    	if($template_in_use) //if template is in use, take care of backups
					{
						//place for a recursive function to iterate through all children of the object $seg
						$this->recursiveRemovalOfNestedChildren($seg,$customMask,$par['id']);
						
						//backup fields from existing structure table
				
						$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
						
						if($hasData)
						{ //don't ask any questions, just make a backup
							if($questionnaireObject->backupColumns($this->fieldsBck)===true)
							{
								echo "backed up";
							}
						}		
						
						//remove fields from structure
						//try to ALTER the structure (drop columns)
						try
						{
							//echo "trying: ". "ALTER TABLE $this->table"."_structure ".implode(',',$fields);
							$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
							//echo "ALTER TABLE $project_name"."_structure ".implode(',',$this->fields);
							$this->db->SQLexecute( "ALTER TABLE $project_name"."_structure ".implode(',',$this->fields) );
						}
						catch (Exception $e)
						{
							$error = "Structure repair failure!";
						}
						
					} //end if templateInUse
			        
					$dom->parentNode->removeChild($dom); //remove a node from the parent
			    }
			}
		}
		else
		{
			return "{success:false, error:'Warning! $this->parentId not found in ".$this->xml->asXML()."'}" ;
		}
		$curXML = $this->xml->asXML();
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$sql = "UPDATE ".WC_MASK_TEMPLATES." SET template_xml = '$curXML' WHERE id = " . $_POST['templateId'];
			if(!$this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			
			return "{success:true}";
	}
	
	private function recursiveRemovalOfNestedChildren($seg_subparent,$customMaskObject,$parId=null)
	{
		
		//echo $customMaskObject->q_name;
		
		//check the type of the child, if any of below, backup and remove from structure
		switch($seg_subparent['type'])
		{
			case 1006: 
			{
				//backup a text field item
				//echo "removing a text field: ". $customMaskObject->q_name."_".$seg_subparent['id'];
				$fieldName = $customMaskObject->q_name."_".$seg_subparent['id'];
				$this->fields[] = 'DROP '. $fieldName;
				$this->fieldsBck[] = $fieldName." text";
				//remove a text field item
			}	
			break;
			
			case 1008: //checkbox item
			{
				//backup a checkbox field item
				//echo "removing a checkbox field:". $customMaskObject->q_name."_".$parId."_".$seg_subparent['id'];
				$fieldName = $customMaskObject->q_name."_".$parId."_".$seg_subparent['id'];
				$this->fields[] = 'DROP '. $fieldName;
				$this->fieldsBck[] = $fieldName." varchar(50)";
				//remove a checkbox field item
			}
			break;
			
			case 1012://radio group
			case 1014://dropdown group
			{
				//backup a radio group
				//echo "removing a radio or dropdown group: ". $customMaskObject->q_name."_".$seg_subparent['id'];
				$fieldName = $customMaskObject->q_name."_".$seg_subparent['id'];
				$this->fields[] = 'DROP '. $fieldName;
				$this->fieldsBck[] = $fieldName." varchar(50)";
				//remove a radio group item
			}
			break;
				
		}


		//check if there are any children of this node (child) and explore them
		$numCh = count($seg_subparent->children());
		if($numCh>0) //children exist, let's explore
		{
			foreach($seg_subparent->children() as $child)
			{
				$this->recursiveRemovalOfNestedChildren($child,$customMaskObject,$seg_subparent['id']);
			}
		}
		
	} //end private function recursiveRemovalOfNestedChildren()
	
	public function modifyAttributesAction()
	{
		$xml = $this->findChildrenById($this->xml,$this->panelId);
		if($xml)
		{
			foreach ($_POST['attr'] as $name => $value) {
				$xml[$name] = $value;
			}
			
		}
		else
		{
			return "{success:false, error:'Warning! $this->parentId not found in ".$this->xml->asXML()."'}" ;
		}
		$curXML = $this->xml->asXML();
			$sql = "UPDATE ".WC_MASK_TEMPLATES." SET template_xml = '$curXML' WHERE id = " . $_POST['templateId'];
			if(!$this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			
			//return "{success:true}";
			$_POST['RMcomp'] = 'propGrid';
			return $this->selectAction();
	}
	/**
	 * Adding class to elements
	 * We add comma separted id values of classes in property RMcls
	 *
	 */
	public function addClassAction()
	{
		$xml = $this->findChildrenById($this->xml,$this->panelId);
		$rmClass = $_POST['specStyle'] ? 'RMcls_'.$_POST['specStyle'] : 'RMclass';
	if($xml)
		{
			if($xml[$rmClass])
			{
				$clsArr = explode(',',$xml[$rmClass]);
				{
					if(!in_array($_POST['classId'],$clsArr ) )
						$xml[$rmClass] .= ','.$_POST['classId'];
				}
			}
			else 
				$xml[$rmClass] = $_POST['classId'];
			
		}
		else{return "{success:false, error:'Warning! $this->parentId not found in ".$this->xml->asXML()."'}" ;}
		$curXML = $this->xml->asXML();
		$sql = "UPDATE ".WC_MASK_TEMPLATES." SET template_xml = '$curXML' WHERE id = " . $_POST['templateId'];
		if(!$this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		
		return "{success:true}";
	}
	public function removeClassAction()
	{
		$clsId = $_POST['classId'];
		$specId = explode('_',$clsId);
		if(count($specId) > 1 )
		{
			$clsId = $specId[1];
			$RMcls = 'RMcls_'.$specId[0];
		}
		else 
			$RMcls = 'RMclass';
		$xml = $this->findChildrenById($this->xml,$this->panelId);
		if($xml)
		{
			if($xml[$RMcls])
			{
				$clsArr = explode(',',$xml[$RMcls]);
				foreach ($clsArr as $key => $val)
				{
					if($val == $clsId)
						unset($clsArr[$key] );
				}
				if(count($clsArr) > 0)
					$xml[$RMcls] = implode(',',$clsArr);
				else 
					unset($xml[$RMcls]);
			}
			
		}
		else{return "{success:false, error:'Warning! $this->parentId not found in ".$this->xml->asXML()."'}" ;}
		$curXML = $this->xml->asXML();
		$sql = "UPDATE ".WC_MASK_TEMPLATES." SET template_xml = '$curXML' WHERE id = " . $_POST['templateId'];
		if(!$this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		
		return "{success:true}";
	}
	
	private function countTemplateQuestions($xmlObj)
	{
		$count = 0;
		foreach ($xmlObj->attributes() as $attr => $value) {
			if( substr($attr,0,12) == 'question_num')
			{
				 if( (int)$value > $count )
				 	$count = (int)$value;
			}
		}
		foreach($xmlObj->children() as $child) {
		    $cC =$this->countTemplateQuestions($child);
		    if($cC > $count)
		    	$count = $cC;
		  }
		return $count;
	}
	
	private function buildJsonTree($xmlObj) {
		foreach ($xmlObj->attributes() as $attr => $value) {
			$prop[$attr] = "$value";
		}
	  	$prop['text'] = $this->getLabel($prop['type'],$prop['id_template'] ).' '.$prop['id'];
	  	if($prop['type'])
	  		$prop['iconCls'] = $this->getIcon( $prop['type'] );
	  	
	  $prop['children'] = array();
	  foreach($xmlObj->children() as $child) {
	    $prop['children'][] =$this->buildJsonTree($child);
	  }
	  return $prop;
	}
	
	/**
	 * 
	 * function is called when an object in the Mask designer is selected, to update the view and hierarchy tree
	 */
	
	public function selectAction()
	{
		if($_POST['RMcomp'] == 'tree')
			return '['.json_encode( $this->buildJsonTree($this->xml) ).']';
		else if ($_POST['RMcomp'] == 'propGrid')
		{
			
			
			$sql = "SELECT properties_name,properties_value FROM ".WC_MASK_PROPERTIES." a INNER JOIN ".WC_MASK_ELEM_PROP_LINK
					." b ON a.id = b.id_property WHERE object_type = $this->panelType OR object_type = 0";
			if(!$rs = $this->db->SQLexecute($sql)) return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			$attr = array();
			while ($row = $this->db->fetchRow($rs))
			{
				$attr[] = $row;
			} 
			//we create an object for the property grid!!!
			$rows = array();
			if($this->panelId)
			{
				$xml = $this->findChildrenById($this->xml,$this->panelId);
				$panAtr = $xml->attributes();
				foreach ($attr as $name) {
				//	$r['name'] = $name;
					//because value is actualy a simpleXmlElement we convert it to string
					$value = $panAtr[$name[0]];
					$rows[$name[0]] = "$value";
				//	$rows[] = $r ;
					if($name[1])
					{//we set up a combobox
						if(is_array($propValues = explode(',',$name[1])  ) )
							$editors[] = $name[0].":new Ext.grid.GridEditor (new Ext.form.ComboBox({store:['".implode("','",$propValues)."'],triggerAction:'all',editable:false}))"; 
						//$editors[$name[0]] = "new Ext.grid.GridEditor (new Ext.form.DateField())";
					}
					
					if($name[0]=="filterIN" || $name[0]=="filterOUT")
					{
						$editors[] = $name[0].":new Ext.grid.GridEditor(new Ext.form.TextArea())";
					}

					
				}
				//if parent is of type
				if($_POST['parentType'] == 1 ) // Horizontal panel
				{
					unset($rows['height']); //disable height parameter
				}
				else if($_POST['parentType'] == 2 || $_POST['parentType'] == 1012 || $_POST['parentType'] == 1013 || $_POST['parentType'] == 1014) // Vertical panel or containers
				{
					unset($rows['width']); //disable width parameter
				}
			}
				
				return "{success:true,object:".json_encode($rows).",editors:{".implode(',',$editors)."}}";
			
		}
		else if($_POST['RMcomp'] == 'grid')
		{
			$this->arr = array();
			if($this->panelId)
			{
			$xml = $this->findChildrenById($this->xml,$this->panelId);
			if($xml)
				{
					if($xml['RMclass'])
					{
						$sql = "SELECT c.id as clsId,c.idLab,a.name,b.prop_value FROM ".WC_DESIGNER_CSS_PROPERTIES." a INNER JOIN ".WC_DESIGNER_CLS_PROP_LINK." b ON a.id = b.id_property INNER JOIN ".WC_DESIGNER_CSS." c ON c.id = b.id_class WHERE c.id IN (".$xml['RMclass'].") ORDER BY c.id";
						If (!$this->rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
						while($obj = $this->db->fetchAssoc($this->rs)){
							$this->arr[] = $obj;
						}
						
					}
					if($xml['RMcls_input'])
					{
					$sql = "SELECT c.id as clsId,c.idLab,a.name,b.prop_value FROM ".WC_DESIGNER_CSS_PROPERTIES." a INNER JOIN ".WC_DESIGNER_CLS_PROP_LINK." b ON a.id = b.id_property INNER JOIN ".WC_DESIGNER_CSS." c ON c.id = b.id_class WHERE c.id IN (".$xml['RMcls_input'].") ORDER BY c.id";
						If (!$this->rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
						while($obj = $this->db->fetchAssoc($this->rs)){
							$obj['clsId'] = 'input_'.$obj['clsId'];
							$this->arr[] = $obj;
						}
					}
					if($xml['RMcls_text'])
					{
					$sql = "SELECT c.id as clsId,c.idLab,a.name,b.prop_value FROM ".WC_DESIGNER_CSS_PROPERTIES." a INNER JOIN ".WC_DESIGNER_CLS_PROP_LINK." b ON a.id = b.id_property INNER JOIN ".WC_DESIGNER_CSS." c ON c.id = b.id_class WHERE c.id IN (".$xml['RMcls_text'].") ORDER BY c.id";
						If (!$this->rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
						while($obj = $this->db->fetchAssoc($this->rs)){
							$obj['clsId'] = 'text_'.$obj['clsId'];
							$this->arr[] = $obj;
						}
					}
							
					$echo = '{success:true';
					
						$echo.= ', STATEMENT: "'.$sql.'",rows: '.json_encode($this->arr);
						$echo.='}';
						return $echo;
					
				}
			}
			return "{success:true,rows:[] }";
			
		}
	}
	public function createObjectAction()
	{
		
		$id_template = $_POST['templateId'];
		$sql = "SELECT * FROM _MaskElements WHERE id_template = $id_template";
		//if template is already in, we just update text...whatever 8)
		if($this->db->fetchRow($this->db->SQLexecute($sql)))
		{
			$sql = "UPDATE _MaskElements SET idLab = '{$_POST['text']}' WHERE id_template = $id_template";
			$this->db->SQLexecute($sql);
		}
		else
		{
			$sql = "SELECT orderBy from _MaskElements WHERE id_sup = 52 ORDER BY orderBy DESC LIMIT 1";
			$ord = $this->db->fetchRow($this->db->SQLexecute($sql));
			$ord = $ord[0]+1;
			$sql = "INSERT INTO _MaskElements (id_sup,type,idLab,orderBy,id_template) VALUES(52,47,'{$_POST['text']}',$ord,{$_POST['templateId']})";
			$this->db->SQLexecute($sql);
		}
		return "{success:true }";
	}
	
}
	

	/**
	 * this runs every time
	 */


	/**
	 * get the xml of the template from the database
	 */

	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$sql = "SELECT template_xml FROM ".WC_MASK_TEMPLATES." WHERE id = ".$_POST['templateId'];
	$rs = $db->SQLexecute($sql);
	$row = $db->fetchArray($rs);
	$curXML = $row[0];
	if($curXML)
		$xml = simplexml_load_string( $curXML );
	else 
	{
		/*$xml = new SimpleXMLElement("<DIV></DIV>");
		//$xml->addChild('DIV');
		$xml->addAttribute('id',$parentId);*/
		/**
		 * 
		 * failsafe - load empty template
		 */
		$xml = simplexml_load_string('<DIV id="0"></DIV>');
	}
	
	// run some action of DesignerPanelXMLManipulator class
	$manipulator = new MaskPanelXMLManipulator( $db,$xml );
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm)) //if the action exists
		echo $manipulator->$comm(); //output JSON result
	else 
		echo '{success:false,error:"Unknown action!"}';	//fail with JSON error
	

?>