<?php
class Display
{
	/**
	 * The question if needed
	 *
	 * @var Question
	 */
	public $q;
	/**
	 * Connection to database
	 *
	 * @var db
	 */
	private $db;
	/**
	 * Engine that runs the questions
	 *
	 * @var Engine
	 */
	//1 for desktop, 2 for mobile
	public $device=0;


	/*
	 * I need this info also in main index file inside survey
	 */
	public $progressPct;


	/**
	 * If I search the name of next call, I got id_tel, must be transfered to dialer class
	 *
	 * @var int
	 */
	public $id_searched_tel;

	// array of all characters which should be replaced with space character in condition functions
	// 2014.09.18 Borut, add removal of a dot (.), dot can now be always after variable
	// 2014.09.26 this was not working... replace back, goint to returnConditionVariables() to find different solution
	// for now I'll replace ". " with " "
	private $cleanChars = array("!","=","<",">","|","&",")","(",",",". ","+","-","/","*","#");

	private $drawTemplate=0;

	public $engine;
	//array that holds the translated values for interface
	private $lngUserArr;

	private $S_call_num;
	private $S_last_call;
	private $S_call_time;
	private $S_app_time;

	private $manual_telselect;
	private $manual_telselect_lock;

	// save flag for handling the onLoad function
	private $warpitClientExecuteOnLoad;


	function __construct($db,$engine = null)
	{
		$this->db = $db;
		$this->db->LogWrite(print_r($_SESSION['telData'],1),true,"check SESSION[telData] in __construct of Display");

		$this->engine = $engine;
		unset( $_SESSION['mustAnswerCondition']);
		//let's fetch the interface multilangauge data!

		//20150904 Tanis
		if($_SESSION['nextQuestion'])
		{

			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$id_language = $_SESSION['id_selectedQuestionLng'] ? $_SESSION['id_selectedQuestionLng'] : $_SESSION['id_userLng'];

			//20151015 Tanis in preview language selection didn't work as it shoud. So I check if this is preview and read special variable for language if it is
			if($_GET['preview'])
			{
				$id_language = intval($_GET['id_language']);
			}
			//20151015 Tanis End

			$sql = "SELECT * FROM _LanguageUserInterface".
								" WHERE (id_language = $id_language OR id_language = {$_SESSION['id_defaultQuestionLng']})".
								" AND (id_project = {$_SESSION['id_project']} OR id_project = 0)".
								" AND id_question IN ({$_SESSION['nextQuestion'][0]['id']},0) ORDER BY id_project,id_question";
			$res = $this->db->SQLexecute($sql);
			while ($row = $this->db->fetchAssoc($res))
			{
				//becouse of the order, the project OR question data will override the defaults!
				if($id_language == $row['id_language'] || !$this->lngUserArr[ $row['id_text_type']  ])
					$this->lngUserArr[ $row['id_text_type'] ] = $row['lngText'];
				//WARNING: no collission detections! if more questions have different data ???
				/*print "<pre>";
				var_dump($this->lngUserArr);
	            print "</pre>";*/
			}
		}

		// I need a lot of data from index table and I will do this select once, not for each object separately
		if ($_SESSION['id_tel'] AND ($_SESSION['nextQuestion'][0]['q_name'] == "tStatus" OR $_SESSION['nextQuestion'][0]['q_name'] == "appointment")) {
			$sql = "SELECT call_num,last_call,call_time,app_time, app_koment, app_middle, app_call_this_num, status FROM ".$_SESSION['proj_name']."___telIndex WHERE id_tel=".$_SESSION['id_tel'];
			//echo $sql."<br>";
			$this->db->LogWrite($sql,true,"inside __construct Display class, getting info from index table");

			$res = $this->db->SQLexecute($sql);
			$row = $this->db->fetchAssoc($res);
			$this->S_call_num = ($row['call_num']+1);
			$this->S_last_call = $row['last_call'];
			$this->S_call_time = $row['call_time'];
			$this->S_app_time = $row['app_time'];


			// add by Borut 19.6.2012, problems with session appoinmtnets,
			// we temporary fix this with this unset and reset session?

			// in year 2013 at the end of August we found out that character ' imported into telephone table produce lower problems
			// lower code can be removed and reset as it was at the begining
			unset($_SESSION['app_exists']);
			unset($_SESSION['app_middle']);
			unset($_SESSION['app_call_this_num']);
			unset($_SESSION['app_koment']);
			//echo "app status: ".$row['status']."<br>";
			//echo print_r($_SESSION)."<br><br>";

			if ($_SESSION['telData']['status'] == 91) {
				$_SESSION['app_exists'] = true;
				$_SESSION['app_koment'] = $row['app_koment'];
				//echo "app komentar dam v session: ".$row['app_koment']."<br>";
				if($row['app_middle'])
				{
					$_SESSION['app_middle'] = $row['app_middle'];
				}
				if($row['app_call_this_num'])
				{
					$_SESSION['app_call_this_num'] = $row['app_call_this_num'];
				}
			}
			// end Borut

		}

	}

	public function getQuestion()
	{
		global $qVar;
		$id = $qVar['id'];
		if(isset($this->q[$id])) return $this->q[$id]; //returns if fake preview
		include_once '../_class/createQuestion/Question.php'; //otherwise creates a real question
		if($qVar['q_pos'] == -4)
		  	{//control questions (q_pos lt 0)
				$this->q[$id] = Question::createQuestion(1,$this->db,$qVar);
				$this->q[$id]->fields = array();
		  	}
		else
		{
	  		$this->q[$id] = Question::createQuestion($qVar['tip_sql'],$this->db,$qVar);
		}
	  	return $this->q[$id];

	}
	/**
	 * If telephone data or telephone id is set it returns/gets the telephone dta
	 *
	 *
	 * @return unknown
	 */
	public function getTelephoneData()
	{
		//preview doesn't have telephone data
		if($_GET['preview']) return;

		if(isset($this->telData)) return $this->telData;
		if(isset($_SESSION['telData']))
		{
			$this->id_tel = $_SESSION['id_tel'];
			$this->id_telname = $_SESSION['id_telname'];
			return $this->telData = $_SESSION['telData'];
		}

		$this->id_tel = $_SESSION['id_tel'];
		if(!$this->id_tel) return;

		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT a.name,b.id_telname FROM _TelephoneTables a INNER JOIN _Projects b ON a.id = b.id_telname WHERE b.id = ".$_SESSION['id_project'];
		$row = $this->db->fetchAssoc( $this->db->SQLexecute($sql) );
		$telName = 'tel___'.$row['name'];
		$_SESSION['telName'] = $telName;

		//$sql = "SELECT a.* FROM $telName a  INNER JOIN _AsteriskConnect b ON a.id = b.id_tel WHERE b.www_ids = ".$_SESSION['id_user'];
		$sql = "SELECT * FROM $telName WHERE id = $this->id_tel";
		$this->id_telname = $_SESSION['id_telname'] =  $row['id_telname'];

		$resTELdata = $this->db->SQLexecute($sql);
		$this->telData = $this->db->fetchAssoc($resTELdata);

		$this->db->LogWrite(print_r($this->telData,1),true,"tel data inside getTelephoneData called in function ");
		return $this->telData;

	}

	public function readXML($id,$projectId,$special = 0)
	{
		global $qVar;
		$type = $qVar['tip_sql'];
		if($special == 6 || $special == 7 )
		{
			$type .= '0'.$qVar['les_sql'];
			$q = $this->getQuestion();
			$type .= '0' . $q->getSpecialType();
		}
		$qPos = $qVar['q_pos'];
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT template_xml,id FROM _DesignerTemplates WHERE id =
		(SELECT id_template FROM _DesignerManager WHERE ((id_project = $projectId AND (id_question = $id OR id_question = 0 ))
													 OR id_type = $type OR (id_project = 0 AND id_type = 0 AND id_qpos = -999) OR id_qpos = $qPos)
													  AND id_special = $special
													  AND (type_device = $this->device OR type_device = 0 ) ORDER BY id_question DESC,id_qpos DESC,id_type DESC,id_project DESC,type_device DESC LIMIT 1)";
		//echo "XML sql: $sql<br>";
		if(!$rs = $this->db->SQLexecute($sql)) echo $this->db->GetError();
		$row = $this->db->fetchArray($rs);

        //DODANO 16.9. Če uporabljamo default template nam funckija ne vrne idja
        //vrne pa nam XML. Zato smo dodatno nastavili variablo idTemplateDefaul, ki jo lahko nato uporabimo preko metode getIdTemplate
        $this->idTemplateDefault = $row[1];
       // var_dump($row[1]);
		//print_r($row);
		if(!$row) { echo "ERROR: template not found!<br>SQL: $sql"; exit;}
		if($this->idTemplate && !$special)
			$this->idTemplate = $row[1];

		return $row[0];
	}

    public function getIdTemplate()
    {

       return $this->idTemplateDefault;
    }

	/**
	 * Function that fetches style attributes from database!
	 *
	 * @param unknown_type $classes
	 */
	public function getCssStyles($classes)
	{
				$clsArr = explode(',',$classes);
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				//print_r($clsArr);
				foreach ($clsArr as $cls)
				{
					if(isset($this->cls[$cls] ) )
					{
						$all .= $this->cls[$cls];
					}
					else
					{

						$sql = "SELECT a.name,b.prop_value FROM _DesignerCssProperties a INNER JOIN _DesignerClsPropLink b ON a.id = b.id_property WHERE id_class = ".$cls;

					  	$rs = $this->db->SQLexecute($sql);
					  	$styleStr = '';
					  	while ($row = $this->db->fetchAssoc($rs))
					  	{
					  		$this->cls[$cls] = $styleStr .= $row['name'].":".$row['prop_value'].';';
					  	}
					  	$all .= $styleStr;
					}
				}
			  	return $all;
	}

	function returnConditionVariables($aCond) {

		// if their is no condition or no character $ I return false
		if (trim($aCond) == '' || strpos($aCond,'$') === false ) return false;


		$varArray = array();
		// replacing condition string
		$_tmp1  = trim(str_replace($this->cleanChars," ",$aCond));
		// searching php script before first variable
		$_tmp1  = substr($_tmp1,strpos($_tmp1,'$'));

		// now we have only variables and values, we explode this by $, so we get variables in first item of array
		foreach (explode("$",$_tmp1) as $_tmpVars) {
			// we explode once more to get only variables
			$_tmp = explode(" ",$_tmpVars,2);
			// if their is any value in this variable we save it as variable name
			//we exclude the reserved name

			if ($_tmp[0] && $_tmp[0] != 'submit_error') $varArray[$_tmp[0]] = $_tmp[0];

		}

		// if condition doesn't include any variables I return false?!?!?!?
		if (count($varArray) == 0) return false;

		// return array with variables which are in condition string
		return $varArray;
	}


	/**
	 * Searches for all vars
	 *
	 * @param unknown_type $vars
	 * @return unknown
	 */
	public function readRequiredQuestionVariables($text)
	{
		//if(!$this->engine) return $text;

		if(!$vars = $this->returnConditionVariables($text)) return $text;

		$this->db->LogWrite(print_r($vars,true),false,"array za pridobitev vrednosti questlab");
		$questLabsVars = array();
		$finalArr = array();
        $pos = null;
        if($this->getQuestion()->id_incentive && !$this->getQuestion()->incentive_possibilites)
        {

            include_once(PATH_TO_ROOT . 'webcati/_class/class.WebPoints.php');
            $wp = new WebPoints($this->db);
            $selectedAmountOfPoints = getVar($_SESSION['prevQuestion']['q_name']);
            $selectedAmountOfPoints = $selectedAmountOfPoints[$_SESSION['prevQuestion']['q_name']];

            $coupon = $wp->getCouponsForPoints($this->getQuestion()->id_incentive, $selectedAmountOfPoints);

            $config = configLoader::loadConfig('incentive');
            $wp->addPointsToUser(array($_SESSION['id_user']), intval($config['payout_purpose_id']), intval($selectedAmountOfPoints), $_SESSION['id_project']);
            $wp->useCoupon($_SESSION['id_user'], $coupon['rows'][0]);
        }

		foreach ($vars as $key => &$variable)
		{

			if($variable == "pct_q_pos")
			{
				if(!$this->engine) continue;
				$variable = "'{$this->engine->getQuestionPosPercent()}%' AS pct_q_pos";
			}

            else if($variable == "quest_q_pos")
            {
                if(!$this->engine) continue;

                if(is_null($pos))
                    $pos = $this->engine->getQuestionPosition();

                $variable = "'" . $pos[0] ."' AS quest_q_pos";
            }
            else if($variable == "total_q_pos")
            {
                if(!$this->engine) continue;

                if(is_null($pos))
                    $pos = $this->engine->getQuestionPosition();

                $variable = "'" . $pos[1] . "' AS total_q_pos";
            }
			else if(substr($variable,0,8) == 'capilab_' )
			{
				if(!$this->engine) continue;
				$sampleVarTmp = explode('_',$variable,2);
				$sampleName = $sampleVarTmp[1];

				// get capi address table and record id
				$sqlCapiTbl = "SELECT a.id_capi_address,b.name,c.name AS addName
								FROM ".DB_WARPIT_WEBCATI_BASE.".".$this->engine->GetProjectName()."_structure a
								LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.".`_CapiTables` b
								ON a.id_capi_table=b.id
								LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.". `_CapiTablesAddon` c
								ON b.id=c.id_capiTable AND c.name='$sampleName'
								WHERE a.id=".$this->engine->id_record;
				//echo "$sqlCapiTbl<br>";
				$this->db->LogWrite($sqlCapiTbl,false,"get capi address table");
				$capiLabErr = 0;
				try {
					$resCapiTbl = $this->db->SQLexecute($sqlCapiTbl);
				} catch (Exception $e) {
					echo "You are probably trying to get the data from non existing capi sample<br>";
					$capiLabErr = 1;
				}

				if (!$capiLabErr) {
					$rowCapiTbl = $this->db->fetchAssoc($resCapiTbl);

					if ($rowCapiTbl['addName'] != NULL) $sampleName = "capi_".$sampleName;
					// go for the data inside capi adress table
					$sqlSampleVar = "SELECT $sampleName as capiSampleData FROM ".DB_WARPIT_WEBCATI_BASE.".capi___".$rowCapiTbl['name']." WHERE id=".$rowCapiTbl['id_capi_address'];
					//echo "$sqlSampleVar<br>";
					$this->db->LogWrite($sqlSampleVar,false,"get pool variable");
					$capiLabErr = 0;
					try {
						$resSampleVar = $this->db->SQLexecute($sqlSampleVar);
					} catch (Exception $e) {
						echo "ERROR: One of the capilab variables is not in address table: '".$sampleName."' <br>";
						$capiLabErr = 1;
					}

					if (!$capiLabErr) {
						$rowSampleVar = $this->db->fetchAssoc($resSampleVar);
					}
				}

				if (!$capiLabErr)
					$finalArr['$'.$variable] = $rowSampleVar['capiSampleData'];
				// clean $ varaibles out of replacement array
				unset($vars[$key]);
			}
			else if(substr($variable,0,9) == 'questlab_' )
			{
				if(!$this->engine) continue;
				$ql = explode('_',$variable);
				$qName = $ql[1];

				$get_sklic_q = "SELECT id,q_name,tip_sql,les_sql,anno_sql,drg_sql,open_sql FROM ".DB_WARPIT_WEBCATI.".".$this->engine->GetProjectName()." WHERE q_name='".$qName."'";
				$this->db->LogWrite($get_sklic_q,false,"check questlab variable");
				$result_get_sklic = $this->db->SQLexecute($get_sklic_q);
				$myrow_get_sklic = mysql_fetch_array($result_get_sklic);


				// if question is scale, I must take legend not answers
				$id_text_type = 3; // answers
				if ($myrow_get_sklic['tip_sql'] == 2) {
					$id_text_type = 4; // legend
				}

				$resAnsLng = "SELECT id_language,lngText FROM ".DB_WARPIT_WEBCATI.".".$this->engine->GetProjectName()."_language WHERE id_text_type = $id_text_type AND id_question='".$myrow_get_sklic['id']."' AND (id_language = '".$_SESSION['id_selectedQuestionLng']."' OR id_language = ".$_SESSION['id_defaultQuestionLng']." )";
				$this->db->LogWrite($resAnsLng,false,"potegnem labele iz tabele za pravi jezik");
				$resAnsLng = $this->db->SQLexecute($resAnsLng);

				// go through all labguages until I find the correct one
				while($rowAnsLng = $this->db->fetchRow($resAnsLng)) {
					$answer = $rowAnsLng[1];
					if($rowAnsLng[0] == $_SESSION['id_selectedQuestionLng'])
						break;
				}

				// pretvorim odgovore zaradi HTML kode
				$q = $this->getQuestion();
		  		$ansArr = $q->answerToArray($answer);
		  		$variable = substr($variable,9);



// #1 SECTION  ADDED 24.01.2013 - Soulskiner
		  		/**
		  		 * We check if question type is multiresponse (tip_sql = 3) .
		  		 * Other check is count($ql) == 2, which means that in questlab we have defined
		  		 * variable name and not just one item from it
		  		 * For example if we define $questlab_q1, then we would like to show all checked answers
		  		 * in this multiresponse question. If we define as $questlab_q1_1, we would like to show it only
		  		 * if first item is checked...
		  		 *
		  		 */
		  		if ($myrow_get_sklic['tip_sql'] == 3 && count($ql) == 3)
		  		{

		  			$resLegLng = "SELECT id_language,lngText FROM ".DB_WARPIT_WEBCATI.".".$this->engine->GetProjectName()."_language WHERE id_text_type = 4 AND id_question='".$myrow_get_sklic['id']."' AND (id_language = '".$_SESSION['id_selectedQuestionLng']."' OR id_language = ".$_SESSION['id_defaultQuestionLng']." )";
		  			$resLegLng = $this->db->SQLexecute($resLegLng);

		  			if ($this->db->NumRows($resLegLng)) {
						// go through all labguages until I find the correct one
						while($rowAnsLng = $this->db->fetchRow($resLegLng)) {
							$legend = $rowAnsLng[1];
							if($rowAnsLng[0] == $_SESSION['id_selectedQuestionLng'])
								break;
						}

						$legArr = $q->answerToArray($legend);


		  			}
		  			else
		  			{
		  				$questLabsVars[$variable] = $ansArr;
		  			}
		  		}
		  		elseif ($myrow_get_sklic['tip_sql'] == 3 && count($ql) == 2)
		  		{
		  			/**
		  			 *  we foeach all items in multiresponse question and
		  			 *  prepare structure array ($vars) in which we define whic variables needs
		  			 * to be read from _structure table
		  			 * in variable $multiTogetherCheck we define which variables are presenting main variable
		  			 *  When this was written I was not sure if this is needed because of showing more questions on one screen
		  			 *
		  			 */
		  			/*echo "<pre>";
		  				var_dump($ansArr);
		  			echo "</pre>";*/
		  			foreach ($ansArr as $keyAns => $ansArrVal) {
		  				// from array of answers we defined for each answer own array
		  				$questLabsVars[$variable."_".($keyAns+1)] = $ansArr[$keyAns];
		  				$vars[] = $variable."_".($keyAns+1);
		  				$multiTogetherCheck[$variable][$variable."_".($keyAns+1)] = $ansArrVal[1];

		  			}

		  			// we delete main multiresponse variable because it is not existing in _structure table and we don't need it
		  			unset($vars[$key]);

		  		}
// #1 END SECTION
		  		else
				{
		  			$questLabsVars[$variable] = $ansArr;
				}


		  		//$this->db->LogWrite($variable,false,"variabla za katero sem pridobil labele");
		  		//$this->db->LogWrite(print_r($ansArr,true),false,"array label za to varaiblo");
			}
			else if(substr($variable,0,6)=='image[')
			{
				$image = substr($variable,6,-1);
				$image = str_replace('\\','/',$image);

				// lets check if there are some parameters...
				$image_obj = $this->imageParameters($image);
				if ($image_obj) {
					$style_params = "style='".$image_obj['param']."'";
					$image = $image_obj['src'];
				}

				require_once(PATH_TO_ROOT."survey/predictive/class.RM_AsteriskManager_predictive.php");
  				$wpPath = configLoader::loadConfig('paths');
				$wpPath = $wpPath['warpit_webprojects_www'];


				$finalArr['$'.$variable] = "<img $style_params src='$wpPath/$image'/>";
				unset($vars[$key]);
			}
			else if(substr($variable,0,6)=='audio[')
			{
				$audio = substr($variable,6,-1);
				$audio = str_replace('\\','/',$audio);

				// lets check if there are some parameters...
				$audio_obj = $this->imageParameters($audio);
				if ($audio_obj) {
					$audio_attributes = $audio_obj['param'];
					$audio = $audio_obj['src'];
				}

				$wpPath = configLoader::loadConfig('paths');
				$wpPath = $wpPath['warpit_webprojects_www'];

				$finalArr['$'.$variable] = "<audio controls " . $audio_attributes . ">
  														<source src='" . $wpPath . "/" . $audio . "' type='audio/mpeg'>
															Your browser does not support the audio element.
															</audio>";
				unset($vars[$key]);
			}
			else if(substr($variable,0,6)=='video[')
			{
				$video = substr($variable,6,-1);
				$video = str_replace('\\','/',$video);

				// lets check if there are some parameters...
				$video_obj = $this->videoParameters($video);
				if ($video_obj)
				{
					$width = 320;
					$height = 240;

					if($video_obj['width']) $width = $video_obj['width'];
					if($video_obj['height']) $height = $video_obj['height'];

					$attributes = $video_obj['param'];
					$src = $video_obj['src'];
				}

				$wpPath = configLoader::loadConfig('paths');
				$wpPath = $wpPath['warpit_webprojects_www'];


				//$finalArr['$'.$variable] = "<img $style_params src='$wpPath/$image'/>";

				$finalArr['$'.$variable] = '<video width="' . $width .'" height="' . $height . '" controls ' . $attributes . '>
			  															<source src="' . $wpPath . '/' .  $src . '" type="video/mp4">
																			Your browser does not support the video tag.
																	</video>';
				unset($vars[$key]);
			}
			else if(substr($variable,0,3) == 'TP_')//we can find those in session!
			{
				//$this->db->LogWrite($_SESSION['telData'][substr($variable,3)],false,"SESSION TP variable:");
				$finalArr['$'.$variable] = $_SESSION['telData'][substr($variable,3)];
				unset($vars[$key]);
			}
			else if(substr($variable,0,5) == 'data[')//we can find those in session!
			{
				//$this->db->LogWrite($_SESSION['telData'][substr($variable,3)],false,"SESSION TP variable:");
				$finalArr['$'.$variable] = $_SESSION[substr($variable,5,-1)];
				unset($vars[$key]);
			}
            else if(substr($variable, 0,10) == 'incentive[')
            {
                preg_match_all("/\[([^\]]*)\]/", $variable, $matches);
                switch($matches[1][0])
                {
                    case 'webPoints':  $finalArr['$' . $variable] = $coupon['rows'][0]['incentive_points']; break;
                    case 'code':  $finalArr['$' . $variable] = $coupon['rows'][0]['incentive_code']; break;
                    case 'couponValue':  $finalArr['$' . $variable] = $coupon['rows'][0]['value_of_coupon']; break;
                    default: $finalArr['$' . $variable] = "Unknown variable";
                }
                unset($vars[$key]);
            }
            else if(substr($variable, 0,12) == 'interviewer[')
            {
              //  require(PATH_TO_ROOT . "/webcati/_ajax/telNumberManagment/ajax.interviewerStatistics.php");
                //$telData = telStatManipulator();
                preg_match_all("/\[([^\]]*)\]/", $variable, $matches);
                switch($matches[1][0])
                {
                    case 'salary':  $finalArr['$' . $variable] = 600; break;
                    default: $finalArr['$' . $variable] = "Unknown variable";
                }
                unset($vars[$key]);
            }

		}

		if($this->engine) {

			$finalArr = array_merge($finalArr, $this->readStructureVariables($vars));
			$this->db->LogWrite(print_r($finalArr,true),false,"array vrednosti iz baze za te variable");
		}

		//$this->db->LogWrite(print_r($questLabsVars,true),false,"vsi questlabi v arrayu pred izvrsitvijo");
		foreach ($questLabsVars as $key => &$ql) {
			//$this->db->LogWrite($key,false,"key for questlabs");
			//$this->db->LogWrite(print_r($ql,true),false,"ql item of questLabsVars");

			$ansValue = $finalArr['$'.$key];
			//$this->db->LogWrite($ansValue,false,"answer value to check");

			$found = false;
			for ($i=0;$i<count($ql);$i++) {
				//$this->db->LogWrite($ql[$i][0],false,"ql values for i");

				if($ql[$i][0] == $ansValue) {
					$finalArr['$questlab_'.$key] = $this->readRequiredQuestionVariables( $ql[$i ][1]);
					$found = true;
				}
			}
			if(!$found) $finalArr['$questlab_'.$key] = '';
		}

// #2 SECTION  ADDED 24.01.2013 - Soulskiner
		/**
		 * Here we build array of answeres in multiresponse which have been answered and then show it in questlab
		 */
		if ($multiTogetherCheck) {
			foreach ($multiTogetherCheck as $variable => $group) {
				$tmp = array();
				foreach ($group as $key=>$val) {
					if ($finalArr["$".$key] != "") $tmp[] = $val;
				}
				if ($tmp) $finalArr['$questlab_'.$variable] = implode(",",$tmp);
				else $finalArr['$questlab_'.$variable] = "";
			}
		}
// #2 END SECTION

		return  strtr($text,$finalArr);

	}


	public function readStructureVariables($vars,$prefix = '$')
	{
		if(!$vars || !$this->engine) return array();
		try {
			$sql = "SELECT ".implode(",",$vars)." FROM ".DB_WARPIT_WEBCATI_BASE.".".$this->engine->GetProjectName()."_structure WHERE id = ".$this->engine->GetIdRecord();
			$res = $this->db->SQLexecute($sql);
			$zad = $this->db->fetchAssoc($res);


			foreach ($zad as $key => &$ansArr) {
				$finalArr[$prefix.$key] = str_replace("'","&#39;",$ansArr);
			}
		}
		catch (Exception $e)
		{
			echo "ERROR: One of the questlab variables is not in structure: '".implode(",",$vars)."' ";
		}
		return $finalArr;
	}

	//20151015 Tanis  added this function, becouse we need to get access to language property in SinleResponse and Scale calss
	public function getLangLabel($type)
	{
		return $this->lngUserArr[$type];
	}
	//20151015 Tanis END

	/**
	 * Main function! Goes trough XML recursevly and creates divs, tables, cells or rows depending on elements
	 *
	 * @param SimpleXMLElement $xmlObj the current child
	 * @param int $parType
	 * @param bool $lastChild
	 * @param int $parId
	 * @return unknown
	 */
	public function displayChilds($xmlObj,$parType,$lastChild,$parId = null)
	{

		global $qVar;
		global $call_center;
		global $call_center_CallUniqueId;

		global $projectId;
		foreach ($xmlObj->attributes() as $attr => $value) {
				$prop[$attr] = "$value";
			}
		  	//$prop['text'] = getLabel($prop['type']).' ';
		//floating windows get displayed seperately!
		if($prop['type'] == 5 )
		{
			$x = $prop['x'];
			$y = $prop['y'];
			$h = $prop['height'];
			$w = $prop['width'];
			$pos = $prop['position'] == 'relative' ? '%' : 'px';
			$html = "<div style=\"position:absolute;left:$x$pos;top:$y$pos;height:$h$pos;width:$w$pos;\">";
			$closeTags = "</div> ";
		}
	 	else
	 	{

			$html;
		//if parent is a horizontal box we calculate the width and set the height to 100%
		//this is because in some cases both width and height are set, altough only one should be considered
		  if($parType == 1)
		  {
		  	//for
			  	$mainSize = 'width';
			  	$secSize = 'height';

		  }//vice versa for vbox
		  else
		  {
		  	$mainSize = 'height';
		  	$secSize = 'width';

		  }


		$size = "style=\"$mainSize:".$prop[$mainSize];
		//we set the proper size style
		  if($prop['position'] == 'relative')
		  {//add percent if its relative
		  	$size .= '%;';
		  }
		  else if($prop['position'] == 'absolute')
		  {
		  	$size .= 'px;';
		  }
		  else
		  { // if size we auto we don't set the size and let the browser handle it
		  	$size = 'style="';
		  	if($parType == 2 && !$lastChild)
		  	{//for some reason this must be set otherwise browser messes up something...don't know what anymore :D
		  	 // TRY IF YOU DARE!!! MUAHAHAHAHA
		  		$size.=$mainSize.':1px;';
		  	}
		  }

		  $size.=";$secSize:100%;";
		//$size .= 'border:1px solid blue;';
			global $db;
			if($prop['RMclass'])
			{
				$size .=  $this->getCssStyles($prop['RMclass']);
			}

			$size .= '"';
		  //add the aling property if its set!
		  if($prop['align'])
		  	$size .= " align='{$prop['align']}'";

		  //dependent on parent we create a new cell or a new row
		  //if we are in a Horizontal panel, we create a new cell (items are one after another
		  $elId = 'id="desElementId'.$this->idTemplate.'_'.$prop['id'];
		  if($this->drawTemplate) $elId.= $this->drawTemplate;
		  $elId .= '" paneltype='.$prop['type'];
		  if($parType == 1)
		  {
			$html .= "<td $elId class=RM_panel_designer_basic$this->idTemplate $size>";
			$closeTags = "</td>";
		  }
		  else if($parType == 1012) //if we are in a Radio group we create a new radio row (items are one below another)
		  {
		  	$html .= "<br />";
			$closeTags = "";
		  }
		  else if($parType == 1013) //if we are in a Checkbox group we create a new checkbox row (items are one below another)
		  {
		  	$html .= "<br />";
			$closeTags = "";
		  }
		  else if($parType == 1014) //if we are in a Dropdown group we create a new dropdown object (items are in a dropdown)
		  {
		  	$html .= "";
			$closeTags = "";
		  }
	 	  else //if we are in a Vertical panel we create a new row (items are one below another)
		  {
			$html .= "<tr><td $elId class=RM_panel_designer_basic$this->idTemplate $size>";
			$closeTags = "</td></tr>";
		  }

		 //if position is absolute we include a div to make the cell harder, better, stronger, faster!!!
		  if($prop['position'] == 'absolute')
		  {
		  	$html .= "<div $size>";
		  	$closeTags = "</div>".$closeTags;
		  }
		//let's use the proper question (if there is one :)
	 	if($prop['question_num'] )
	  		{
	  			global $qVarCount;
	  			if( $this->drawTemplate)
	  				$qVar = $qVarCount[ $this->templateNumbering[ $this->drawTemplate  ][ $prop['question_num'] ] ];
	  			if(!$qVar)
	  			{
	  				$qVar = $qVarCount[ $prop['question_num'] -1 ];
	  			}
	  		}
  		if($filter = $qVar['filter'])
  		{
  			$qVar = array();
  		}
		//let's apply multilanguage translation!

		if($this->lngUserArr[$prop['type']])
		{
			$prop['text'] = $this->lngUserArr[$prop['type']];
		}
		$showObject = true;
  		//some conditions may hide object!
  		if($prop['catiOnly'] && $_SESSION['popUpQuestionnaire'])
			$showObject = false;

		  //lets write the proper text dependend on type
		  $db->LogWrite($prop['type'],true,"just before case xxx for drawing object in display class - object number type");
		  // 2014.11.3. Borut remove height:100% from <table... for Hpanel and Vpanel, problems inside IE8
		  if($showObject)
		  switch ($prop['type'])
		  {
		  	case 1: //Hpanel, we create a new panel
		  		$html .= "<table cellpadding=0px cellspacing=0px style=\"width:100%\"><tr>";
		  		//$html .= "HPanel";
		  		$closeTags = "</tr></table>";
		  	break;
		  	case 2: //Vpanel
		  		$html .= "<table cellpadding=0px cellspacing=0px style=\"width:100%\">";
		  		//$html .= "Vpanel";
		  		$closeTags = "</table>".$closeTags;
		  	break;
		  	case 3:
		  	//question
			  	if(isset($GLOBALS['userSetQuestion']))
			  	{
			  		$html .= $this->readRequiredQuestionVariables( $GLOBALS['userSetQuestion'] );
			  	}
			  	else
			  	{
			  		if(! $qVar['vpr_sql'])
			  		{
			  			$html = '';
			  			$closeTags = '';
			  		}
		  			else
			  	 		$html .=  $this->readRequiredQuestionVariables($qVar['vpr_sql']);
			  	}
		  	 //$qVar['vpr_sql'];
		  	break;
		  	case 4:
		  	//instruction
		  	if(isset($GLOBALS['userSetInstruction']))
		  	{
		  		$html .= $this->readRequiredQuestionVariables( $GLOBALS['userSetInstruction'] );
		  	}
		  	else
		  	{
		  		if(! $qVar['nav_sql'])
		  		{
		  			$html = '';
		  			$closeTags = '';
		  		}
		  		else
		  			$html .= $this->readRequiredQuestionVariables( $qVar['nav_sql']);
		  	}


		  	break;
		  	case 5: //Window
		  	break;
		  	case 6:
		  	//answers
		  	$q = $this->getQuestion(); //create question object (gets $this->q[id] - real or fake

		  	// 21.10.2014 Changed by Borut -> added multilanguage save for answer groups
			// text type for groups is defined under id=8
			// this require also change in database, Warpit_Webcati, table _LanguageText, id_text = 8
			if (isset($q->grp_sql)) $q->answerGroups = $q->grp_sql;

		  	$grTmp = explode('<|>',$q->answerGroups); //explode the field answerGroups at char <|>

		  	$q->groups = explode( ',' , $grTmp[0] ); //explode the first element at ,
		  	$numGrp = count( $grUniqe = array_unique($q->groups) );
			if($grTmp[1])
			{
				$groupLayout = $grTmp[1];
				$groupData = explode('<*>',$grTmp[2]);
			}
			else $groupLayout = 1;


		  	if($q->designerRequiresTemplate()) //if requires a designer template
		  	{

		  		if($qVar['tip_sql']!=11) //if not a custom mask question type
			  		if(!$qVar['odg_sql']) //and no answers
			  			break; //break



			  	$test = simplexml_load_string( $this->readXML($qVar['id'],$projectId,6)); //read template data


			  	if($test)
			  		$q->xmlObj = $test->ANSWER;
			  	else
			  		$q->xmlObj = $xmlObj;

			  	if($qVar['tip_sql']!=11) //if not a custom mask question type, require children in template XML
				  	if(! count ($q->xmlObj->children() )) //if no answers (children)
				  	{
				  		$html .= "Error: No answer template found!"; //complain
				  		break; //then break
				  	}
				  	// else go on, it is a custom mask, which has its own template XML
		  	}

			$q->display = $this;
			$grIndex = 0;

			if($groupLayout == 1) // field answerGroups is null
			{

				foreach ($grUniqe as $group) {
					//$html .= "This is group number $group";

					$q->group = $group;
					$q->headerDisplay = false;
					if($groupData[$grIndex])
					{
						$curGroupData = explode(',',$groupData[$grIndex]);
						$q->curLayout = $curGroupData[0];
						if($curGroupData[1] || $curGroupData[2])
						{
							$q->headerDisplay = true;
							$q->headerHeight = $curGroupData[1];
							$q->headerTitle = $curGroupData[2];
							$q->header = "<DIV style='height:{$curGroupData[1]}'>{$curGroupData[2]}</DIV>";

						}


						if(!$curGroupData[3])
							$q->showLegend = false;
						else
							$q->showLegend = true;
					}
						//20160323 Tanis s
						$html .= "<input type='hidden' name='submit_on_enter' value='" . $q->enter_submit . "' />";
				//		var_dump( "<input type='hidden' name='submit_on_enter' value='" . $q->enter_submit . "' />", $q);
						//20160323 Tanis END
				  	$html .= $q->designerDrawAnswers($xmlObj,$this);
				  	$grIndex++;
				}
			}
			else if($groupLayout == 2)
			{

				$html .= "<table style='width:100%;height:100%'><tr>";
				foreach ($grUniqe as $group) {
					$q->group = $group;
					if($groupData[$grIndex])
					{
						$curGroupData = explode(',',$groupData[$grIndex]);
						$q->curLayout = $curGroupData[0];
						if($curGroupData[1])
						{
							$html .= "<DIV style='height:{$curGroupData[1]}'>{$curGroupData[2]}</DIV>";

						}
					}
				  	$html .= "<td>". $q->designerDrawAnswers($xmlObj,$this) ."</td>" ;

				  	$grIndex++;
					}


				$html .= "</table></tr>";
			}
			$q->designerPrepareCondition(); //empty function in main question class, might be defined in subclasses

		  	break;
		  	case 7:
		  		//variable
		  		$showVar = $this->db->get('_Projects',$projectId,'interview_show_variable');
		  		if(! $qVar['q_name'] || !$showVar )
			  		{
			  			$html = '';
			  			$closeTags = '';
			  		}
		  			else
		  			$html .= $qVar['q_name'];
		  	break;
		  	case 8:
		  		//custom image
		  		$html .= "<img border='0'  src=\"".$prop['src']."\" alt='Alt'/>";
		  	break;
		  	case 10:
		  		//submit button
		  		//in general don't show on last question!
		  		//here maybe some rules can be aplied so that...I don't know what :)
		  		if( !($qVar['isFinal'] || $this->engine->hideForward ) || $qVar['q_pos'] == -8 )
		  		{
		  			if($prop['RMcls_input'])
		  			{
		  				$specStyle = 'style="'.$this->getCssStyles($prop['RMcls_input']).'"';
		  			}
		  			$html .= "<INPUT NAME='questSubmit' id='submitCallStatus' $specStyle TYPE='SUBMIT' ";
		  			//if($call_center)
		  				//$html .= 'style="visibility:hidden" ';
		  			$html .= "value='".$prop['text']."' onClick=\"recodeClickEvents(this,3);hideButton('submitCallStatus');\">";

		  		}
		  	break;
		  	case 11:
		  		//back button
		  		//in general don't whow on first question!
		  		//here maybe some rules can be aplied so that...I don't know what :)

		  		if( $qVar['id'] != $_SESSION['rotFirstQuestion'] && !$this->engine->hideBackward && !$_SESSION['hide_back_button'])
		  		{
			  		if($prop['RMcls_input'])
			  			{
			  				$specStyle = 'style="'.$this->getCssStyles($prop['RMcls_input']).'"';
			  			}


		  			$html .= "<INPUT NAME='questBack' id='questBack' $specStyle TYPE='SUBMIT' value='".( $prop['text'] )."'
		  			 onClick=\"recodeClickEvents(this,3);hideButton('questBack');\">";
		  		}
		  	break;
		  	case 15:
			  		//progress bar
			  		if($this->engine && $qVar['q_pos'] > 0) {
			  			$qPositionAndAll = $this->engine->getQuestionPosition();
			  			$qPosition = $qPositionAndAll[0];
			  			$qAll = $qPositionAndAll[1];
			  		}
			  		else if(!$this->engine) //question preview
			  		{
			  			$qPosition = 4;
			  			$qAll = 10;
			  		}
			  		else
			  			break;

		  			//$html .= $qPosition."/". $qAll;

		  			$pct_q_pos = $qPosition / $qAll;
		  			$bar_width = $prop['barWidth'];
		  			$bar_height = $prop['barHeight'];
					$bar_background_color = $prop['bar_background_color'];;
					$bar_border_width = $prop['bar_border_width'];
					$bar_border_color = $prop['bar_border_color'];
					$bar_border_style = $prop['bar_border_style'];

		  			$bar_width_fill=$bar_width*$pct_q_pos;
					$bar_width_rest=$bar_width-$bar_width_fill;
			  		if ( $bar_width_rest == 0 ) {
						$rest_back_color = $bar_background_color;
					} else {
						$rest_back_color = "#ffffff";
					}
					$text = $this->readRequiredQuestionVariables(  $prop['text'] );
					if($prop['RMcls_text']) $textStyle = 'style="'.$this->getCssStyles($prop['RMcls_text']).'"';
					$posText = $prop['text_position'];
					if($text && $posText == 'top')
		  				$html .= "<div class='RMprogressbar_text' $textStyle>$text</div>";

		  			if($text && $posText == 'left')
		  					$html .= "<table cellpadding=0 cellspacing=0 border=0><tr> <td class='RMprogressbar_text' $textStyle>$text </td><td style=vertical-align:middle;>";
					if($text && $posText == 'right')
						$html .= "<table cellpadding=0 cellspacing=0 border=0><tr><td style=vertical-align:middle;>";

		  			$html.= "<table cellpadding=0 cellspacing=0 border=0>";


						$html.= "<tr>";

							if ($txt_statusbar_array[0]) {
								$html.= "<td Style=\"$style_statusbar\">";
									$html.= $txt_statusbar_array[0];
								$html.= "</td>";
							}
							$html.= "<td Style=\"font-size : 1pt; background-color : $bar_background_color; width : ".$bar_width_fill."px; height : ".$bar_height."px; border-left-style : $bar_border_style; border-top-style : $bar_border_style; border-bottom-style : $bar_border_style; border-bottom-width : ".$bar_border_width."px; border-top-width : ".$bar_border_width."px; border-left-width : ".$bar_border_width."px; border-right-width : ".$bar_border_width."px; border-color : $bar_border_color; \">&nbsp;";
							$html.= "</td>";
							$html.= "<td Style=\"font-size : 1pt; background-color : $rest_back_color; width : ".$bar_width_rest."px; height : ".$bar_height."px; border-right-style : $bar_border_style; border-top-style : $bar_border_style; border-bottom-style : $bar_border_style; border-bottom-width : ".$bar_border_width."px; border-top-width : ".$bar_border_width."px; border-left-width : ".$bar_border_width."px; border-right-width : ".$bar_border_width."px; border-color : $bar_border_color; \">&nbsp;";
							$html.= "</td>";
							if ($txt_statusbar_array[0]) {
								$html.= "<td Style=\"$style_statusbar\">";
									$html.= $txt_statusbar_array[1];
								$html.= "</td>";
							}


						$html.= "</tr>";

					$html.= "</table>";

					if($text && $posText == 'left')
	  					$html .= "</td></tr></table>";
					if($text && $posText == 'right')
		  				$html .= "</td><td class='RMprogressbar_text' $textStyle>$text</td></tr></table>";

					if($text && $posText == 'bottom')
		  					$html .= "<div class='RMprogressbar_text' $textStyle>$text</div>";

		  			$html .= "<input type=hidden id=progressPct value=".$pct_q_pos.">";
		  			$this->progressPct = round($pct_q_pos*100);
		  			$db->LogWrite($this->progressPct,true,"inside display class - progress bar pct rounded");

		  	break;
		  	case 19:
		  		//simple text
		  		$html .= $this->readRequiredQuestionVariables($prop['text']);
		  	break;
		  	case 23:
		  		//dial button
		  		if(isset($prop['src']))
		  			$img = "<IMG src='".$prop['src']."'/>";
		  		if(isset($prop['text']))
		  			$text = $prop['text'];
		  		$p = $prop['text_position'];
		  		if($img && $text)
		  		{
			  		if($p == 'top')
			  			$html .= $text.'<br>'.$img;
			  		else if($p == 'left')
			  			$html .= $text.$img;
			  		else if($p == 'right')
			  			$html .= $img.$text;
			  		else if($p == 'bottom')
		  				$html .= $img.'<br>'.$text;
		  		}
		  		else
		  			$html .= $text.$img;
		  		/*if($prop['src'])
		  		{
		  			$html .= "<IMG src='".$prop['src']."'/>";
		  		}
		  		$html .= $prop['text'];*/
		  	break;
		  	case 24:
		  		//hangup button
		  		if(isset($prop['src']))
		  			$img = "<IMG src='".$prop['src']."'/>";
		  		if(isset($prop['text']))
		  			$text = $prop['text'];
		  		$p = $prop['text_position'];
		  		if($img && $text)
		  		{
			  		if($p == 'top')
			  			$html .= $text.'<br>'.$img;
			  		else if($p == 'left')
			  			$html .= $text.$img;
			  		else if($p == 'right')
			  			$html .= $img.$text;
			  		else if($p == 'bottom')
		  				$html .= $img.'<br>'.$text;
		  		}
		  		else
		  			$html .= $text.$img;
		  	break;
		  	case 25:
		  	//break up, start new

		  if($prop['RMcls_input'])
			  			{
			  				$specStyle = 'style="'.$this->getCssStyles($prop['RMcls_input']).'"';
			  			}
		  	$html .= "<INPUT NAME='startNew' TYPE='SUBMIT' $specStyle onClick=\"recodeClickEvents(this,3);\" value='".$prop['text']."'>";
			if($qVar['q_pos'] == -1 || $qVar['q_pos'] == -2)
				$html .= "<INPUT NAME='specialStat' TYPE='HIDDEN' value='". ($qVar['q_pos'] == -1 ? 52 : 51  ) ."'>";
		  	//	$html .= "<INPUT NAME='questSubmit' TYPE='HIDDEN' value='1'>";
		  	if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1)
		  	{
		  		$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
		  		if($_REQUEST['incoming'] == 'true')
					  			$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
		  		$html .= "<input type='hidden' name='call_center_CallUniqueId' value=''>";
		  		$_SESSION['call_center'] = 1;

		  	}

		  	break;
		  	case 41:

				if($prop['hidden'] == "true")
				{
						$html .= "<input type='hidden' name = 'gotoIdle' value='true'/>";
						$html .= "<input type='hidden' name ='gotoIdleReason' value='1'/>";
				}
				else {
				  	//checkbox for going to idle!
				  	$html .= "<INPUT type='checkbox' VALUE=1 ";
				  	if($_SESSION['gotoIdle']) $html .= "CHECKED = TRUE";
				  	$html .=" NAME='gotoIdle'>".$prop['text'];

				  	// we add dropdown for selectiong the reason for going IDLE
				  	// Added by Marko, 2014.11.05
			/*		$selected[1] = "";
					$selected[2] = "";
					$selected[3] = "";
					if($_POST['gotoIdleReason'] == 1){
					 $selected[1] = "selected='selected'";
					}elseif($_POST['gotoIdleReason'] == 2){
					 $selected[2] = "selected='selected'";
					}elseif($_POST['gotoIdleReason'] == 3){
					 $selected[3] = "selected='selected'";
				 }*/

				 $html .=  "<br><select name='gotoIdleReason'>";
				 $sql = "SELECT * FROM " . DB_WARPIT_WEBCATI_BASE . "._IdleReasons";
			 		if($res = $this->db->SQLexecute($sql))
			 		{
			 				while ($row = $this->db->fetchAssoc($res))
			 				{
			 						$html .= "<option value=" . $row['value'];

									if(intval($row['value']) == $_POST['gotoIdleReason'])
										$html .= " selected='selected' ";

									$html .= ">" . $row['label'] . "</option>";
							}
			 		}

					  /*  <option value=1 {$selected[1]}>5 min break</option>
					    <option value=2 {$selected[2]}>10 min WC</option>
					    <option value=3 {$selected[3]}>30 min lunch</option>*/
				  $html .= "</select>";
					// *******************************************************


			}

			if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1)
			{
				$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
				if($_REQUEST['incoming'] == 'true')
								$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
				$html .= "<input type='hidden' name='call_center_CallUniqueId' value=''>";
				$_SESSION['call_center'] = 1;
			}
		  	break;
		  	case 45:
		  	//checkbox for going to idle!
		  	if($_SESSION['layer_allowOther'])
		  		$html .= "<INPUT NAME='startOther' TYPE='SUBMIT' onClick=\"recodeClickEvents(this,3);\" value='".$prop['text']."'>";
		  	if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1)
		  	{
		  		$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
		  		if($_REQUEST['incoming'] == 'true')
					  			$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
		  		$html .= "<input type='hidden' name='call_center_CallUniqueId' value=''>";
		  		$_SESSION['call_center'] = 1;
		  	}
		  	break;

		  	case 27:
		  	//quota display
		  	//display all quotas
		  	$db = $this->db;
		 	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$sql = "SELECT a.* FROM quota_layer a INNER JOIN quota_layer_addon b ON b.id=a.layer WHERE id_project = $projectId AND interviewer_show = 1 ORDER BY layer,zap_st";
			//get all layers for quotas (TODO: filter layers!)
			$resLayers = $db->SQLexecute($sql);
			$curLayerId = 0;
			$allGrids = array();
			$projName = $_SESSION['proj_name'];
			$tableName = $projName;
			$tableLimits = $projName.'___quotaLimits';
			$tableCalc = $projName.'___quotaCalc';
			$layCount = 0;

			while (true)
			{
				$rowLayer = $db->fetchAssoc($resLayers);
				if($rowLayer['layer'] != $curLayerId)
				{

					if($curLayerId)//draw the table
					{
						$layCount++;
						$selectSQL = "SELECT a.*,(SELECT count(*) FROM $tableCalc b WHERE ".implode(' AND ',$countWhere). " ) AS q_done FROM $tableLimits a WHERE a.id_layer = ".$curLayerId . " ORDER BY " . implode(',', $columns);
						$quotaRes = $db->SQLexecute($selectSQL);
						//let's get the labels!

						$labelsSQL = $db->SQLexecute("SELECT a.q_name,b.rec_label,b.id_reconum FROM quota_layer a INNER JOIN recolabel b ON a.source = b.source AND a.id_question = b.id_question AND a.id_project = b.id_project WHERE a.layer = $curLayerId AND b.id_project = $projectId AND (".implode(' OR ',$fetchLabels).')' );
						$recodeLabels = array();
						while ($rowLabels = $db->fetchAssoc($labelsSQL) )
						{
							$recodeLabels[ $rowLabels['q_name'] ][ $rowLabels['id_reconum'] ] = $rowLabels['rec_label'];
						}


						//copied the basic styles from borut :)
						$table = "<table border=0 class=tekst_quotatbl cellpadding=0 cellspacing=0 ><TR>";
						$table .= '<td colspan=11 style="border:solid;border-color:000000;border-bottom-width:2px;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">
							<b>QUOTA system/Layer '.$layCount.'</b></td></tr>
							<tr class=tekst><td colspan=7 height=5px></td></tr>
							<tr>';
						$countCol = count($columns);

						for($i = 0;$i < $countCol; $i++)
						{
							$table .= '<td style="border:solid;border-color:000000;border-bottom-width:2px;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">
<b>&nbsp;'.$colDisplay[$i].'&nbsp;</b></td>';
						}
						$table .= '<td align=center style="border:solid;border-color:000000;border-bottom-width:2px;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">
<b>&nbsp;&nbsp;<br>&nbsp;(N)&nbsp;</b></td><td align=center style="border:solid;border-color:000000;border-bottom-width:2px;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">
<b>&nbsp;&nbsp;<br>&nbsp;(N)&nbsp;</b></td><td align=center style="border:solid;border-color:000000;border-bottom-width:2px;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">
<b>&nbsp;&nbsp;<br>&nbsp;(N)&nbsp;</b></td><tr class=tekst><td colspan=11 height=5px></td></tr></tr>';

						$countTotal = 0;
						$countDone = 0;

						while ($quotaRow = $db->fetchAssoc($quotaRes))
						{
							$table .= '<TR>';
							for($i = 0;$i < $countCol; $i++)
							{
								$table .= '<td align=left  style="border:solid;border-color:000000;border-bottom-width:0.01cm;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">'.$quotaRow[  $columns[$i] ].' '. $recodeLabels[ $colDisplay[$i] ][ $quotaRow[  $columns[$i] ] ] ."</TD>";
							}
							$table .= '<td align=center  style="border:solid;border-color:000000;border-bottom-width:0.01cm;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm">'.$quotaRow['q_value']."</TD>";
							$table .= '<td align=center  style="border:solid;border-color:000000;border-bottom-width:0.01cm;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm"><font color=gray>'.$quotaRow['q_done']."</TD>";
							$table .= '<td align=center  style="border:solid;border-color:000000;border-bottom-width:0.01cm;border-top-width:0cm;border-left-width:0cm;border-right-width:0cm"><font color=green>'.($quotaRow['q_value'] - $quotaRow['q_done'] )."</TD>";
							$countTotal += $quotaRow['q_value'];
							$countDone += $quotaRow['q_done'];

						}
						$countTodo = $countTotal - $countDone;

						$table .= '</tr><tr valign=bottom><td style="border:solid;border-color:000000;border-bottom-width:00cm;border-top-width:0.01cm;border-left-width:0cm;border-right-width:0cm" height=15px colspan='.$countCol.' align=left><font color=brown>&nbsp;&nbsp;</font></td>
<td style="border:solid;border-color:000000;border-bottom-width:00cm;border-top-width:0.01cm;border-left-width:0cm;border-right-width:0cm" align=center><font color=brown>&nbsp;'.$countTotal.'&nbsp;</font></td>
<td style="border:solid;border-color:000000;border-bottom-width:00cm;border-top-width:0.01cm;border-left-width:0cm;border-right-width:0cm" align=center><font color=brown>&nbsp;'.$countDone.'&nbsp;</font></td>
<td style="border:solid;border-color:000000;border-bottom-width:00cm;border-top-width:0.01cm;border-left-width:0cm;border-right-width:0cm" align=center><font color=brown>&nbsp;'.$countTodo.'&nbsp;</font></td></tr>';


						$table .= "</TABLE>";
						$html .= $table;
					}
					//array that holds the where clouse for inner select count
					$countWhere = array();
					$columns = array();
					$colDisplay = array();
					$fetchLabels = array();

					$curLayerId = $rowLayer['layer'];
				}
				if(!$rowLayer) break;
				if($rowLayer['source'] == 2 )
					$colName = 'QT_'.$rowLayer['q_name'];
				else
					$colName = 'TP_'.$rowLayer['q_name'];
				//the or statement for fetching labels
				$fetchLabels[] = '(b.id_question = '.$rowLayer['id_question'].' AND b.source = '.$rowLayer['source'].')';


				$countWhere[] = "a.$colName = b.$colName";
				$columns[] = $colName;
				$colDisplay[] = $rowLayer['q_name'];


			}
			if($curLayerId)//finish the grid
					{
						/*addFinalColumns($grid);
						$grid->selectSQL = "SELECT a.*,(SELECT count(*) FROM $tableCalc b WHERE ".implode(' AND ',$countWhere). " ) AS q_done FROM $tableLimits a";

						echo $grid->createGrid();
						$allGrids[] = $grid->getName();*/
					}

		  	break;
		  	case 28:
		  	//Interviewer id
		  	$html .= 'Interviewer id: '. $_SESSION['id_user'];
		  	break;
		  	case 29:
		  	//Project id
		  	$html .= 'Project ID: '.$projectId.'<br>Interview ID: '.$_SESSION['id_record'].'<br>Telephone number ID: '.$_SESSION['id_tel'].'<br>Number of calls: '.$this->S_call_num;
		  	break;
		  	case 30:
			  	//tel structure data
			  	$this->getTelephoneData();
			  	if(!$this->id_tel) return;

		  		$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

		  		//let's display all data set to whow from the common telephone base variables
		  		//$sql = "SELECT name FROM _TelephoneTblAddonProject a INNER JOIN _TelephoneTblDefaultVar b on a.id_var = b.id AND is_addon = 0 AND show_var = 1 AND id_project = ".$_SESSION['id_project']." ORDER BY b.id";
		  		$sql = "SELECT a.id as id_var,a.name,b.show_var FROM  _TelephoneTblDefaultVar a LEFT JOIN _TelephoneTblAddonProject b ON is_addon = 0 AND b.id_var = a.id AND id_project = ".$_SESSION['id_project']." ORDER BY a.id";
		  		$res = $this->db->SQLexecute($sql);
		  		while ($row = $this->db->fetchAssoc($res))
		  		{
		  			if($row['show_var'] OR $row['show_var'] == NULL )
		  				$html .= $row['name'].': '. $this->telData[ $row['name']  ].'<br>';
		  		}
		  		//lets display all the added variables
		  		//echo $this->id_telname;
		  		$res = $this->db->SQLexecute("SELECT name FROM _TelephoneTblAddonProject a INNER JOIN _TelephoneTablesAddon b on a.id_var = b.id AND is_addon = 1 AND show_var = 1 AND id_telbaza = $this->id_telname AND id_project = ".$_SESSION['id_project']." ORDER BY b.id");
		  		while ($row = $this->db->fetchAssoc($res))
		  		{
		  			$html .= $row['name'].': '. $this->telData['tel_'. $row['name']  ].'<br>';
		  		}

		  	break;
		  	case 31:
		  	//telephone status
		  		//echo "call center flag:".$_SESSION['call_center']."<br>";

		  		//if we have automatic dialing we check if status is already selected (busy, no answer etc)
		  		if( $_POST['statusSelected'] )
		  		{
		  			//echo "autoDialerSelectStatus";
		  			if($_POST['gotoIdle'])
		  			{
		  				$addHIdle = "<input type='hidden' name='gotoIdle' value=true >";
		  			}
		  			$html .= "<input type='hidden' name='questSubmit' value=true >
	  				<input type='hidden' name='status_telnum' value= {$_POST['statusSelected']} >$addHIdle";
			  		if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1 or $call_center)
				  	{
				  		$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
				  		if($_REQUEST['incoming'] == 'true')
					  			$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
				  		$html .= "<input type='hidden' name='call_center_CallUniqueId' value='".$_REQUEST['call_center_CallUniqueId']."'>";
				  		$_SESSION['call_center'] = 1;
				  	}
	  				$html .= "<script>
	  					document.forms['mainForm'].submit()
	  				</script>";

		  			break;
		  		}
		  		if($_SESSION['autoDialing'])
		  			$autoCnd = 'WHERE autodial_disable = 0';
		  		$this->getTelephoneData();
		  		$this->db->ChangeDatabase(DB_WEBCATI_WARPIT_BASE);
		  		$html .= $prop['text'];
		  		$radio = $prop['displayAs'] == 'radio buttons';
			  	$sql = "SELECT a.status,a.status_rec,a.opis ,b.show_status,a.show_default FROM  _TelephoneStatus a LEFT JOIN _TelephoneStatusProject b ON b.id_status = a.id AND id_project = ".$_SESSION['id_project']." $autoCnd ORDER BY orderBy";
				if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
				if(!$radio)
						$html .= "<select name='status_telnum'>";
				while ($row = $this->db->fetchAssoc($res))
				{
					//if show is net set, the default is true
					if($row['show_status'] == NULL) $row['show_status'] = $row['show_default'];
			/*	}
		  		$sql = "SELECT * FROM _TelephoneStatus ORDER BY order_num";
		  		$rs = $this->db->SQLexecute($sql);
		  		while ($row = $this->db->fetchAssoc($rs))
		  		{*/

		  			if($row['show_status'])
		  			{
			  			$idStat = $row['status'];
			  			$recStat = $row['status_rec'];
			  			$value = $idStat.'_'.$recStat;
			  			if($radio){
			  				$html .= "<br><input type='radio'".($idStat == 1 ? "checked='true'" : '' ). " id='st_$value' name = 'status_telnum' value ='$value'><label for='st_$value'>".$row['opis']."</label>";
			  			}

			  			else
			  			{
			  				$html .= "<option ".($idStat == 1 ? "selected" : '' ). " value ='$value'>".$row['opis'];
			  			}



		  			}
		  		}
		  		if(!$radio)
						$html .= "</select>";

			  	// add text box, if specified to be shown
			  	if ($prop['statusCommentShow'] == "yes")
			  	{
			  		$styleStatus = "Style=\"width:".$prop['statusCommentW'].";height:".$prop['statusCommentH'].";";
			  		$styleStatus .= "font:".$prop['statusCommentFont']."\"";

			  		$html .= "<br>";
			  		if ($prop['statusCommentText']) $html .= $prop['statusCommentText']."<br>";
			  		if ($prop['statusComment'] == 'textbox')
			  			$html .= "<input ".$styleStatus." type=textbox name=statusComment value=\"\">";
			  		else
			  			$html .= "<textarea ".$styleStatus." name=statusComment></textarea>";
			  	}


			  	/**
			  	 * if I make call inside call center manager, I do this with new call center to conference method
			  	 * calling function to create unique call first
			  	 */
		  		//echo "<PRE>".print_r($this->telData)."</PRE>";
		  		if ($_SESSION['call_center'] or $_REQUEST['call_center'] == 1 or $call_center) {
			  		//include_once('/opt/sors/api/api.php');
			  		//$conferenceID = $_POST['conferenceID'];

	    		    //$apiCallManager = new apiAkcije();
	        		$telNumberToCAll = "0".$this->telData['oms'].$this->telData['telephone'];
	            	//$apiCallManager->callNumberToConference($telNumberToCAll, $conferenceID);
	            	if($_REQUEST['incoming'] == 'true'){
	            		$html .= "<script type=\"text/javascript\">
	            					$('#st_1_0').attr('checked', true);
	            					$('#submitCallStatus').click();
	            		</script>";
	            	}
	            	else
	            	$html .= "<script type=\"text/javascript\">
	            					var tryToCallInterval = 0;
	            					var callStarted = 'busy';
	            					var outDoc = window.parent;
	            					var internalCallStatusInterval = 0; //checks the state of call and then checks the right radio button status call
	            					outDoc.statusAutoCall = 0;

	            					function tryToCall(){
	            						callStarted = window.parent.startAutoCalling('$telNumberToCAll',".$_SESSION['id_telname'].",".$_SESSION['telData']['id'].",'".$_SESSION['proj_name']."',".$_SESSION['id_project'].");
	            						if(callStarted == true)
	            							clearInterval(tryToCallInterval);
		  							}

	            					tryToCallInterval = setInterval(tryToCall,1000);

            						var checkBusyInterval = setInterval(function(){
		            					if(callStarted == true)
		            					{
		            						clearInterval(tryToCallInterval);
		            						tryToCallInterval = 0;
		            						clearInterval(checkBusyInterval);
		            						checkBusyInterval = 0;

		            						if(internalCallStatusInterval == 0)
				            					internalCallStatusInterval = setInterval(function(){
					  								if(outDoc.statusAutoCall != 0)
					  								{
					  									clearInterval(internalCallStatusInterval);
					  									internalCallStatusInterval = 0;
					  									switch(outDoc.statusAutoCall){
					  										case 1:
					  											$('#st_1_0').attr('checked', true);
					  											$('input[name=call_center_CallUniqueId]').val(outDoc.activeCalls[1]);
					  											outDoc.activeOutboundProjectId = ".$_SESSION['id_project']."
					  											$('input[name=call_center]').val('1');
					  										break;
					  										case 9:
					  											$('#st_9_0').attr('checked', true);
					  											outDoc.makeAgentFree('autooutbound');
					  										break;
					  										case 22:
					  											$('#st_22_0').attr('checked', true);
					  											outDoc.makeAgentFree('autooutbound');
					  										break;
					  										case 25:
					  											$('#st_25_0').attr('checked', true);
					  											outDoc.makeAgentFree('autooutbound');
					  										break;
					  										case 33:
					  											$('#st_33_0').attr('checked', true);
					  											outDoc.makeAgentFree('autooutbound');
					  										break;
					  										default:
					  											alert('Unknown call status!');
					  											$('#st_9_0').attr('checked', true);
					  											outDoc.makeAgentFree('autooutbound');
					  										break;
					  									}
					  									outDoc.statusAutoCall = 0;
					  									alert('submit bi mogo bit!');
					  									$('#submitCallStatus').click();
					  								}
				            					},200);
			  							}
		  							},500);

	            			  </script>";

		  		}

		  	break;
		  	case 32:
		  	//language selection
		  	$html .= $qVar['vpr_sql'];
		  	break;
		  	case 33:
				//appointment options table

					$inputFont = array();

					//font-weight: bold; font-size: 20px; font-family: Verdana;

					if(strlen($prop['font_style'])) $inputFont[] = "font-style:" .$prop['font_style'];
					if(strlen($prop['font_color'])) $inputFont[] = "color:" .$prop['font_color'];

					if(strlen($prop['font_family'])) $inputFont[] = "font-family:" .$prop['font_family'];
					else $inputFont[] = "font-family:Verdana";

					if(strlen($prop['font_size'])) $inputFont[] = "font-size:" .$prop['font_size'];
					else $inputFont[] = "font-size:20px";

					if(strlen($prop['font_weight'])) $inputFont[] = "font-weight:" .$prop['font_weight'];
					else $inputFont[] = "font-weight:bold";

		  		$html .= '<table cellspacing="2" cellpadding="0" border="0">
		  			<tbody><tr><td><font size="2" face="arial"></font></td><td><font size="2" face="arial">Call again at&nbsp;</font></td><td>';
		  		$html .= $this->getTimeSelector($inputFont);
		  		if($_SESSION['app_call_this_num'])
		  		{
		  			$numArr = explode('/',$_SESSION['app_call_this_num']);
		  			$numOms = $numArr[0];
		  			$numNum = $numArr[1];
		  		}
		  		$html .= '</td></tr>
		  			 <tr><td></td><td align="right"><font size="2" face="arial">Comment:<br>(max 250 chars)</font></td><td><textarea cols="40" rows="5" name="dogovor_komentar" style="width: 600px; height: 200px;' . implode(';', $inputFont) . '">'.$_SESSION['app_koment'].'</textarea></td></tr>
						 <tr><td></td><td valign="bottom" align="right"><font size="2" face="arial">New tel. number:</font></td><td><input type="text" style="' . implode(';', $inputFont). '" value="'.$numOms.'" name="dogovor_oms" size="3" maxlenght="10">&nbsp;/&nbsp;<input type="text" style="' . implode(';', $inputFont). '" value="'.$numNum.'" name="dogovor_telnum" size="10" maxlenght="20"></td></tr>

						 <tr><td></td><td><font size="2" face="arial">Email:</font></td><td><input type="text" style="' . implode(';', $inputFont). ';width:600px"  name="dogovor_email" size="10" ></td></tr>
						 </tbody></table>';
	  		break;
		  	case 46:
		  		if ($prop['show_app_type'] == 'yes' AND ($_SESSION['telData']['status'] == 22 OR $_SESSION['telData']['status'] == 25 OR $_SESSION['telData']['status'] == 91))
		  			$html .= $prop['show_app_type_text'].$_SESSION['telData']['status']."<br>";

		  		//appointment comment (displays only if appointment)
		  		if($_SESSION['app_exists'])
		  		{

		  			if($_SESSION['app_middle']) {
		  				$html .= $prop['text_app_middle'];
		  			} else {
		  				$html .= $prop['text'];
		  			}

		  			$html .= $this->NewLine2HTML($_SESSION['app_koment']);
		  		}
		  		elseif ($_POST['preview'] == 1) {
		  			$html .= $prop['text_app_middle'];
		  			$html .= "Example of appointment text<br>in two lines";
		  		}

		  	break;
		  	case 50:
		  		//status comment
		  		if ($_SESSION['id_tel'])
		  			$statusComment = $this->db->get($_SESSION['proj_name'].'___telIndex','id_tel='.$_SESSION['id_tel'],'status_comment',DB_WEBCATI_WARPIT_BASE);
		  		elseif ($_POST['preview'] == 1)
		  			$statusComment[0] = "Simple fake status comment\r\nin two lines.";

		  		if ($statusComment[0])
		  		{
  					$html .= $prop['text'];
		  			$html .= $this->NewLine2HTML($statusComment[0]);
		  		}
		  	break;
		  	case 51:
		  		//additional telephones

		  		if ($_SESSION['id_tel']) {
		  			$field_name = true;
		  			try {
		  				$telephones = $this->db->get($_SESSION['telName'],$_SESSION['id_tel'],$prop['telephones_field_name'],DB_WEBCATI_WARPIT_BASE);
		  			}
		  			catch (Exception $e) {
		  				$no_field_name = false;
		  			}

		  			if ($field_name) {
			  				$html .= $prop['text'];
			  				$combined_telephone = $_SESSION['telData']['oms']."/".$_SESSION['telData']['telephone'];


			  				$telephones_arr = explode("*", $telephones);
			  				unset($arr_telephones);
			  				foreach ($telephones_arr AS $keyt => $itemt) {
			  					$arr_telephones[] = $itemt;
			  					if ($itemt) $iframe_telephones .= ($keyt+1).". - <b>".$itemt."</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			  				}
			  				$html .= "<IFRAME name=add_telephones src=\"show_telephones.php?arr_telephones=".implode("*",$arr_telephones)."&field_t2=".$prop['telephones_field_name']."&id_tel=".$_SESSION['id_tel']."&telName=".$_SESSION['telName']."&iframe_telephones=$iframe_telephones&combined_telephone=$combined_telephone\" width=1000 height=25 scrolling=no frameborder=0 MARGINWIDTH=0 MARGINHEIGHT=0></IFRAME>";
		  			}
		  		}
		  		elseif ($_POST['preview'] == 1) {
		  			$html .= $prop['text'];
		  			$html .= "1. 01/1234567<br>2. 01/1234567<br>3. 01/1234567<br>4. 01/1234567<br>";
		  		}
		  	break;
		  	case 52:
		  		//last call time
		  		if ($_SESSION['id_tel']) {
		  			if ($this->S_last_call) {
		  				$html .= $prop['text'];
		  				$html .= $this->HumanDate($this->S_last_call);
		  			}
		  		}
		  		elseif ($_POST['preview'] == 1)
		  			$html .= "1970.01.01 00:00:00";
		  	break;
		  	case 53:
		  		//next call time
		  		if ($_SESSION['id_tel']) {
		  			if ($this->S_call_time) {
		  				$html .= $prop['text'];
		  				$html .= $this->HumanDate($this->S_call_time);
		  			}
		  		}
		  		elseif ($_POST['preview'] == 1)
		  			$html .= "1970.01.01 00:00:00";
		  	break;
		  	case 54:
		  		//app call time
		  		if ($_SESSION['id_tel']) {
		  			if ($this->S_app_time) {
		  				$html .= $prop['text'];
		  				$html .= $this->HumanDate($this->S_app_time);
		  			}
		  		}
		  		elseif ($_POST['preview'] == 1)
		  			$html .= "1970.01.01 00:00:00";
		  	break;
		  	case 42:
		  		//appointment button
		 	  if($prop['RMcls_input'])
			  			{
			  				$specStyle = 'style="'.$this->getCssStyles($prop['RMcls_input']).'"';
			  			}
		  		$html .= "<INPUT NAME='makeAppointment' $specStyle TYPE='SUBMIT' onClick=\"recodeClickEvents(this,3);\" value='".$prop['text']."'>";
		  	break;
	  		case 35:
	  			$this->db->LogWrite("case = 35",true,"jump into dialer");

	  			$sql = "SELECT * FROM _Projects WHERE id = ".$_SESSION['id_project'];
				if(!$myrow_id_project = $this->db->fetchAssoc($this->db->SQLexecute($sql))){	return false;}

	  			//dialer
	  			//BIG TIME WARNING!!!!
	  			//add user type when checking user data!!! added 20.05.2011, Igor Golob
	  			$dialerType = $qVar['les_sql'];
	  			if($myrow_id_project['use_predictive'] ) { //predictive

	  				unset($_SESSION['id_tel']);
					unset($_SESSION['id_tellog']);

	  				require_once(PATH_TO_ROOT."survey/predictive/class.RM_AsteriskManager_predictive.php");
					$_SESSION['autoDialing'] = true;
					$_SESSION['predictiveDialing'] = true;
	  				extract( configLoader::loadConfig('asterisk_dialing'));
					//$_SESSION['gotoIdle'] = true;
//	  				$asterisk_connect = explode(",", $telephone_asterisk_dialing);
//					$asterisk_ip_port = $asterisk_connect[0];
//					$asterisk_ip_port_array = explode(":",$asterisk_ip_port);
//					$asterisk_ip = $asterisk_ip_port_array[0];
//					$asterisk_port = $asterisk_ip_port_array[1];
//
//					$asterisk_username = $asterisk_connect[1];
//					$asterisk_password = $asterisk_connect[2];

   					$am_addqueue = new RM_AsteriskManager_predictive($this->db);
	  				$interna_stevilka = $_SESSION['asteriskID'];
	  				$id_user = $_SESSION['id_user'];

	  				if ($am_addqueue->LogOn($asterisk_username, $asterisk_password, $asterisk_ip, $asterisk_port, $interna_stevilka , $id_user  )) {
			      		$ExtensionStatus = $am_addqueue->ExtensionStatus($interna_stevilka, $context);
						$am_addqueue->AM_LogWrite_predictive("Extension status before add to queue - $interna_stevilka: ".$ExtensionStatus);

			      		if ($ExtensionStatus == 0) {
			      			$callResult = $am_addqueue->DialInside($interna_stevilka, $context, $callerID, $PredictiveExt);
			      		} else {
							echo "<font color=red>Error! Softphone not ready.<br>";
							echo "</font>";
			      		}

						if ($callResult == true) {
					  		$am_addqueue->AddToQueue($interna_stevilka, $_SESSION['id_project'], $id_user, $this->db);
				  			$am_addqueue->AM_LogWrite_predictive("User added to the queue. SIP=".$interna_stevilka."[".$id_user."] ID project=".$_SESSION['id_project']);

			     	 		//$ExtensionStatus = $am_addqueue->ExtensionStatus($interna_stevilka, $Context);
							$am_addqueue->AM_LogWrite_predictive("Extension status after add to queue - $interna_stevilka: ".$ExtensionStatus);

				  			// vstavim ajax klic
			  				$html .= "
				  				<input type='hidden' name='predictive' value=1 />
					  			<script>
									function ajaxRequest(){
									 var activexmodes=[\"Msxml2.XMLHTTP\", \"Microsoft.XMLHTTP\"] //activeX versions to check for in IE
									 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
									  for (var i=0; i<activexmodes.length; i++){
									   try{
									    return new ActiveXObject(activexmodes[i])
									   }
									   catch(e){
									    //suppress error
									   }
									  }
									 }
									 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
									  return new XMLHttpRequest()
									 else
									  return false
									}

									function intFunc(){
					  					var mypostrequest=new ajaxRequest();
					  					mypostrequest.onreadystatechange=function(){
					  					 if (mypostrequest.readyState==4){
					  					 	if (mypostrequest.status==200 || window.location.href.indexOf(\"http\")==-1){
					  					 	if(mypostrequest.responseText != 0 && !isNaN(mypostrequest.responseText)){
					  					 	var f = document.forms[\"mainForm\"];
					  					 	 var e = document.createElement(\"input\");
					  					 	f.innerHTML += \"<input type='hidden' value=true name='questSubmit' />\";
					  					 	 f.submit();
					  							}else{   }
					  					   }  else{ alert(\"An error has occured making the request\");  }	 }	};
					  					   var parameters=\"id_SIP=\"+\"$interna_stevilka\"+\"&id_project=\"+{$_SESSION['id_project']};
					  					   mypostrequest.open(\"POST\", \"predictive/pDialer.php\", true);
					  					   mypostrequest.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");
					  					   mypostrequest.send(parameters);
									}

									setInterval('intFunc()',3000);
					  			</script>";

						} else {
							echo "<font color=red>Error registering local extension to the queue.<br>";
							echo "Please check your phone or conntact system administrator.<br>";
							echo "</font>";
						}
						$am_addqueue->LogOff();
			      	}

	  			}
	  			else if($myrow_id_project['set_use_autodial'])
	  			{ //automatic dialer
	  				$this->db->LogWrite($myrow_id_project['set_use_autodial'],true,"using auto dialer myrow_id_project['set_use_autodial']");

	  				unset($_SESSION['id_tel']);
	  				unset($_SESSION['id_telname']);
	  				unset($_SESSION['telData']);

	  				unset($_SESSION['autoDialer']);

	  				$_SESSION['autoDialing'] = true;

					$callTime = $myrow_id_project['call_time_length']*1000;
					include_once (PATH_TO_ROOT.'webcati/_class/class.Dialer.php');
					$d = new Dialer($this->db);

					$this->db->LogWrite($callTime,true,"before getTelId I have callTime");
					$this->id_tel = $d->getTelId( $_SESSION['id_project'] ,$_SESSION['id_user'],$_SESSION['user_type'], 1, $this->id_searched_tel);

					$this->db->LogWrite($this->id_tel,true,"did I get correct ID of the teleohnoe back (id_tel)");
					$_SESSION['id_tel'] = $this->id_tel;

					$this->db->LogWrite($this->id_tel,true,"before getTelephoneData() I have IDtel");
	  				$this->getTelephoneData();


	  				/*
	  				// BORUT add for Mediana debug 19.3.2013
	  				// do some extra session save into separate table, just for debug...
	  				$SESvalue = addslashes(serialize($_SESSION['telData']));
	  				$SESsql = "REPLACE _tmpSES_dial (id_user,ses_value) VALUES ('".$_SESSION['id_user']."','$SESvalue')";
	  				$this->db->SQLexecute($SESsql);
	  				*/


	  				if($this->id_tel) {
	  					$this->db->LogWrite($this->id_tel,true,"I actualy go inside for seting hangup script on Asterisk");

	  					echo "<script>
			  				function ajaxRequest(){
							 var activexmodes=[\"Msxml2.XMLHTTP\", \"Microsoft.XMLHTTP\"] //activeX versions to check for in IE
							 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
							  for (var i=0; i<activexmodes.length; i++){
							   try{
							    return new ActiveXObject(activexmodes[i])
							   }
							   catch(e){
							    //suppress error
							   }
							  }
							 }
							 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
							  return new XMLHttpRequest()
							 else
							  return false
							}

				  			setTimeout('var mypostrequest=new ajaxRequest();'+
							'var parameters=\"id_user=\"+{$_SESSION['id_user']}+\"&dialerHangUp=true\";'+
							'mypostrequest.open(\"POST\", \"aDialer.php\", true);'+
							'mypostrequest.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");'+
							'mypostrequest.send(parameters)',$callTime );
				  		</script>
				  		";

				  		// to avoid loading iframe before end of page, I load code for iframe after the page is loaded
		  				//echo "<iframe id=\"ID_autoDial\" src=index.php?autoDial=true></iframe>";
		  				echo "<iframe id=\"ID_autoDial\" src=\"\"></iframe>";


		  				// disabling default function and write new function needed in case 35 (dialer)
		  				$this->set_warpitClientExecuteOnLoad(false);
		  				$html .= "<script>function warpitClientExecuteOnLoad() {
		  							document.getElementById('ID_autoDial').src = 'index.php?autoDial=true';
	  							}</script>";


		  				$html .="<input type='submit' value='Linija je vzpostavljena!' onclick=\"document.forms['mainForm'].lineEstablished.value=true;document.forms['mainForm'].questSubmit.value=null; ;\">
		  					<input type='hidden' name='dialerHangUp'>
		  					<input type='hidden' name='lineEstablished'>
		  					<input type='hidden' name='statusSelected'>
			  				<input type='hidden' name='questSubmit' value=true >";
		  				if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1 or $call_center)
					  	{
					  		$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
					  		if($_REQUEST['incoming'] == 'true')
					  			$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
					  		$html .= "<input type='hidden' name='call_center_CallUniqueId' value='".$_REQUEST['call_center_CallUniqueId']."'>";
					  		$_SESSION['call_center'] = 1;
					  	}
	  				}
	  				else {
	  					$this->db->LogWrite("document.forms['mainForm'].submit()",true,"I have no id_tel, just autosumbit the page...");
	  					if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1 or $call_center)
					  	{
					  		$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
					  		if($_REQUEST['incoming'] == 'true')
					  			$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
					  		$html .= "<input type='hidden' name='call_center_CallUniqueId' value='".$_REQUEST['call_center_CallUniqueId']."'>";
					  		$_SESSION['call_center'] = 1;
					  	}
	  					$html .= "<input type='hidden' name='questSubmit' value=true >
		  				<script>
		  				document.forms['mainForm'].submit()
		  				</script>";
	  				}
	  			}
	  			else { //manual dialer

	  				$_SESSION['autoDialing'] = false;

	  				//we clear the question and select a new one!
	  				unset($_SESSION['id_tel']);
	  				unset($_SESSION['id_telname']);
	  				unset($_SESSION['telData']);



					if ($myrow_id_project['telselect'] AND !$_POST['manual_dial_select']) {
						$this->setTelSelect(true);
						if ($myrow_id_project['strictlock_manual']) $this->setTelSelectLock(true);

						$html .= "<input type=hidden name='manual_dial_select' value='1'>";

					}
	  				else {
	  					// if I have manual selection of conditions for selectiong telephone number
	  					if ($_POST['manual_select_combos']) {
	  						$combos_manual = explode(";",$_POST['manual_select_combos']);
	  						foreach ($combos_manual AS $manualCombo) {
	  							unset($where_combo);
	  							//echo "manualCombo: $manualCombo<br>POST manual combo:".$_POST[$manualCombo]."<br>";
	  							if ($_POST[$manualCombo]) {
		  							foreach ($_POST[$manualCombo] AS $item_combo) {
		  								$where_combo[] = $manualCombo."=".$item_combo;;
		  							}
	  							}
	  							if ($where_combo) $where_all_combo[] = "(".implode(" OR ",$where_combo).")";
	  						}
	  						if ($where_all_combo) $where_manual_select = "(".implode(" AND ",$where_all_combo).")";
	  					}
	  					//echo "where manual select:".$where_manual_select."<br>";

		  				include_once (PATH_TO_ROOT.'webcati/_class/class.Dialer.php');
						$d = new Dialer($this->db);

						// set, if I use special manual selection of some quota layers
						$d->setManualTelephoneSelection($where_manual_select);

						$this->id_tel = $d->getTelId( $_SESSION['id_project'] ,$_SESSION['id_user'],$_SESSION['user_type'], 1, $this->id_searched_tel);

						$_SESSION['id_tel'] = $this->id_tel;
		  				$this->getTelephoneData();



		  				// avto form submit
		  				$this->db->LogWrite($this->id_tel,true,"Before auto submit when manual dialer... id_tel");

		  				if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1 or $call_center)
					  	{
					  		$html .= "<INPUT NAME='call_center' TYPE='HIDDEN' value='1'>";
					  		if($_REQUEST['incoming'] == 'true')
					  			$html .= "<INPUT NAME='incoming' TYPE='HIDDEN' value='true'>";
					  		$html .= "<input type='hidden' name='call_center_CallUniqueId' value='".$_REQUEST['call_center_CallUniqueId']."'>";
					  		$html .= "<input type='hidden' name='conferenceID' value='".$_REQUEST['conferenceID']."'>";
					  		$_SESSION['call_center'] = 1;
					  	}

		  				//file_put_contents("/tmp/post_display.txt", "dialer:".print_r($call_center,true)."\n", FILE_APPEND | LOCK_EX);
		  				//file_put_contents("/tmp/post_display.txt", "dialerREQUEST:".print_r($_REQUEST,true)."\n", FILE_APPEND | LOCK_EX);
		  				$html .= "<input type='hidden' name='questSubmit' value=true >
			  				<script>
			  					document.forms['mainForm'].submit()
			  				</script>";

	  				}
	  			}

	  			$html .= $qVar['vpr_sql'];
	  		break;
		  	case 55:
		  	// manual telephone selection
		  		$telselect = $this->getTelSelect();
				if ($telselect) {
					$telselectlock = $this->getTelSelectLock();
					//echo "inside module manual telephone selection<br>telselect:$telselect<br>telselectlock:$telselectlock<br>";


					$sql = "SELECT q_name, id_question, source FROM quota_layer WHERE id_project = ".$projectId." AND source IN (0,1) ORDER BY zap_st";
					//echo $sql;
					$res =  $db->SQLexecute($sql);
					while ($row = $db->fetchAssoc($res)) {
						$LayerType[$row['id_question']."_".$row['source']] = $row['source'];
						$LayerName[$row['id_question']."_".$row['source']] = $row['q_name'];
					}

					$html .= "<table><tr>";
					foreach ($LayerType AS $key_layer => $item_layer) {
						$html .= "<td>";
						$tmpkey = explode("_",$key_layer);
						$id_question = $tmpkey[0];
						$source = $item_layer;
						$sql_lab = "SELECT id_reconum, rec_label, id_question, source FROM recolabel WHERE id_project=".$projectId." AND id_question=".$id_question." AND source=".$source." ORDER BY id_reconum";
						//echo $sql_lab."<br>";

						$comboName = $LayerName[$key_layer];
						$real_comboName = $comboName;

						// check an prepare lock kvotas, if checkbox for lock quotas on manual dial is set
						$checkLock = array();
						if ($telselectlock) {
							$sql_qtLock = "SELECT `TP_".$real_comboName."`,count(*) FROM `".$_SESSION['proj_name']."___quotaLock`
											WHERE id IN
											(SELECT id FROM ".$_SESSION['proj_name']."___quotaLock WHERE `isLocked`=0)
											GROUP BY `TP_".$real_comboName."`";
							//echo $sql_qtLock."<br>";
							$res_qtLock = $db->SQLexecute($sql_qtLock);
							while ($row_qtLock = $db->fetchRow($res_qtLock)) {
								$checkLock[] = $row_qtLock[0];
							}
						}

						if ($source == 1) $real_comboName = "tel_".$real_comboName;
						$all_comboNames[] = $real_comboName;
						$html .= "<span style='font-family:Verdana;font-weight:bold;'>$comboName</span><br><select Style='width:200px;' id='id_".$real_comboName."' name='".$real_comboName."[]' multiple size=10>";
						$html .= "<option style='font-family:Verdana;' value=0>- - - - - - - select item - - - - - - -</option>";

						$res_lab = $db->SQLexecute($sql_lab);
						while ($row_lab = $db->fetchAssoc($res_lab)) {
							$layer_combo_value = $row_lab['id_reconum'];
							if ((in_array($layer_combo_value, $checkLock) AND $telselectlock) OR !$telselectlock) {
								if ($row_lab['rec_label']) $layer_combo_value .= " - ".$row_lab['rec_label'];
								$html .= "<option style='font-family:Verdana;' value ='".$row_lab['id_reconum']."'>".$layer_combo_value."</option>";
							}
						}
						$html .= "</select>";
						$html .= "</td>";
					}
					$html .= "<tr></table>";
					$html .= "<input type=hidden name='manual_select_combos' value='".implode(";",$all_comboNames)."'>";
				}

		  	break;
	  		case 36:
		  	//automatic dialer

		  	break;
		  	case 37:
		  	//manual dialer

		  	break;
		  	case 38:
		  		$prop_callCenter = configLoader::loadConfig('call_center');

			  	//telephone number (oms + telephone)
			  	$this->getTelephoneData();

			  	if($_SESSION['app_call_this_num'])
			  		$html .= 'Telephone number: ' .$_SESSION['app_call_this_num'];
			  	else
			  		$html .= 'Telephone number: <span id=main_telephone>' .$this->telData['oms'].'/'.$this->telData['telephone']."</span>";

			  	// Zavarovalnica Triglav, connect over CISCO client to Telekom IP telephony
			  	if ($prop_callCenter['iframe_tel_dial'] == 1) {
			  		// for dialing to other countries 00 must be dialed, I must replace 99 from oms field to 00
			  		$oms_external = $this->telData['oms'];
			  		if (substr($oms_external,0,2) == "99") $oms_external = substr_replace($oms_external,"0",0,2);
					echo "<iframe name=\"dial_external\" src=\"tel:00".$oms_external.$this->telData['telephone']."\" width=1px height=1px  scrolling=no frameborder=0 MARGINWIDTH=0 MARGINHEIGHT=0>";
					echo "</iframe>";
			  	}

				// IMAS server CATI, easydial for Alcatel telephone central
			  	if ($prop_callCenter['iframe_tel_dial'] == 2) {
			  		$EasyDial_server = $prop_callCenter['iframe_tel_dial_server'];
					$dialPrefix = $prop_callCenter['dial_prefix'];
					$interna_stevilka = $_SESSION['asteriskID'];

					$full_tel_number = $dialPrefix."0".$this->telData['oms'].$this->telData['telephone'];
					echo "<iframe name=\"easydial_button\" src=\"easydial_button.php?EasyDial_server=$EasyDial_server&interna_stevilka=$interna_stevilka&full_tel_number=$full_tel_number\" width=1px height=1px  scrolling=no frameborder=0 MARGINWIDTH=0 MARGINHEIGHT=0>";
					echo "</iframe>";
			  	}
			  	break;

		  	case 39:
		  	//telephone name
		  	$this->getTelephoneData();
		  	$html .= 'Name: ' .$this->telData['name'];
		  	break;
	  		case 40:
	  		//simple text
	  		if($this->engine->LeaveQuestion == false)
	  			$html .= $prop['text'];
		  	break;
		  	//!!!! displaying other templates!!!
	  		case 47:
	  			//global $qVarCount;
	  			//if($prop['question_num'])
	  			//	$qVar = $qVarCount[ $prop['question_num'] -1 ];
		 		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

		 		if($filter) break;
	  			$sql = "SELECT template_xml,id FROM _DesignerTemplates WHERE id = ".$prop['id_template'];
				if(!$rs = $this->db->SQLexecute($sql)) echo $this->db->GetError();
				if(!$row = $this->db->fetchRow($rs))
				{
					$html .= 'Error! Template not found!';
					break;
				}
				$templateXml = simplexml_load_string( $row[0] );
				$html .= '<table width=100% height=100%>';
				$closeTags = '</table>'.$closeTags;
	/**
	 * Explanation of templateNumbering and drawTemplate:
	 * Each template can support multiple questions! On objects like Answers, Question, Instruction we can set witch questien we want
	 * to show by setting the question_num property!
	 * The template exported as an object has multiple question_num properties (question_num_1, question_num_2...) becouse
	 * when we use a subtemplate, we don't always want to show the question that is set on the objects in the template!
	 * If we use 2 same templates for example, we want the first to show q1 and the second q2! So we set question_num_1 on the
	 * second template to 2 and it will show question 2 altough all of its objects have question_num property set to 1!
	 * Becouse we can have more levels of subtemplates we build a multidimensional array templateNumbering which holds the
	 * corresponding numbers of each suptemplate in such a complex way that you would not understand it either way, so it's
	 * no use for me explaining it (kidding...I don't get it either, so I can't explain) :)
	 */
				if($this->idTemplate)
				{
					$this->templateNumberingId[$this->drawTemplate] = $this->idTemplate;
					$this->idTemplate= $prop['id_template'];
				}
				$this->drawTemplate++;
				foreach ($xmlObj->attributes() as $tmpAtr => $tmpVal) {
					if( substr($tmpAtr,0,13) == 'question_num_' )
					{
						if($prevTemp = $this->drawTemplate - 1)
						{
							$val = $this->templateNumbering[ $prevTemp  ][ $prop['question_num'] ];
						}
						else
							$val = (int)$tmpVal - 1;

						$this->templateNumbering[$this->drawTemplate][ substr($tmpAtr,13) ] = $val;
					}
				}

				   foreach($templateXml->children() as $child) {
					  $chAttr = $child->attributes();
					  if($chAttr['type'] == 5)
					  {
					  	//$windows .= $this->displayChilds($child,0,false);
					  }
					  else
					  	$html .=  $this->displayChilds($child,0,false);
					  }
				$this->drawTemplate--;
				$this->idTemplate = $this->templateNumberingId[$this->drawTemplate];

	  		break;
	  		case 48:
	  			//language chooser combobox!
	  			//we show it only if language wasn't chosen already and there are more then one language to chose from
	  			//(and  later maybe some other options )
		 		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

	  			if(!$_SESSION['id_selectedQuestionLng'])
	  			{
	  				$sqlLng = $this->db->SQLexecute("SELECT id_language,cp_comment FROM _LanguageProjects INNER JOIN _LanguageCodepage ON id = id_language WHERE id_project = ".$_SESSION['id_project']);
	  				if($this->db->numRows($sqlLng) > 1 )
	  				{
	  					$html .= "<SELECT name='languageChooser'>";
	  					while ($row = $this->db->fetchRow($sqlLng)) {
	  						$o = "<OPTION value=".$row[0];
	  						if($row[0] == $_SESSION['id_defaultQuestionLng'])
	  							$o .= " selected=true";
	  						$o.= ">".$row[1];
	  						$html .= $o;
	  					}
	  					$html .= "</SELECT>";

	  				}
	  			}
	  		break;

	  		case 49:
		  	//Project id
		  	if($_SESSION['id_record'])
		  		$com = $this->db->get('_QuestionComments',"id_project = $projectId AND id_question = {$qVar['id']} AND id_structure = {$_SESSION['id_record']}",'qComment',DB_WARPIT_WEBCATI);

		  	if($prop['RMcls_text']) $textStyle = 'style="'.$this->getCssStyles($prop['RMcls_text']).'"';
		  	$html .= $prop['text'].':<br><textarea name="qCommentText" '.$textStyle.'>'.$com[0].'</textarea>';
		  	break;

		  	case 56:
		  		// WEBCATI PLUGIN CONTAINTER
		 		include("../webcati/_plugins/_support/class.webcati-plugin.php");
		  	break;

		  	case 57:
		  	// custom scripts
		  		if ($_REQUEST['preview'] == 1) {
		  			$html .= WARPIT_WEBPROJECTS.$prop['path']."<br>";
		  		} elseif (strlen($prop['path']) > 5 ) {
		  			$filename_cs = WARPIT_WEBPROJECTS.$prop['path'];
		  			if (file_exists($filename_cs)) {
		  				include($filename_cs);
		  			}
		  		}
		  	break;
            case 58:
                $html .= $this->readRequiredQuestionVariables($prop['text']);
            break;
            case 59:
                include(PATH_TO_ROOT . "webcati/_javascript/javascript.resetFormObject.php");
            break;
            case 60:
							if(isset($_SESSION['allow_listening']))
							{

                if($_SESSION['allow_listening'])
                    $html .= "<img height='" . $prop['height'] . "' src='" . $prop['allow_listening_image'] . "' >";
                else
                    $html .= "<img height='" . $prop['height'] . "' src='" . $prop['not_allow_listening_image'] . "' >";
							}
            break;
            case 61:
               $html .= $this->readRequiredQuestionVariables($prop['text']);
                //$html .= "Tvoja plača je toliko in toliko :D";
			break;
        case 62:
			   	// iframe for readnig inbound calls from the system
				$html .=  "<iframe name=\"inbound_calls\" src=\"inbound_calls.php?\" width=250px height=103px  scrolling=auto frameborder=0 MARGINWIDTH=0 MARGINHEIGHT=0>";
				$html .=  "</iframe>";
			break;

			case 63:

				if($_SESSION['id_user'])
				{
					$sql = 'SELECT username FROM ' . DB_WARPIT_WEBCATI_BASE . '._Interviewer WHERE id = ' . $_SESSION['id_user'] . ' LIMIT 1';
					$res = $this->db->SQLexecute($sql);
					$row = $this->db->fetchAssoc($res);
					$html .= $row['username'] . "_" . $_SESSION['id_record'];

				}
				else {
					$html .= "sampleUser1_0001";
				}

			break;
		  }


	 	}
		  $objHasChild=0;
		  $numCh = count($xmlObj->children());
		  $curCh = 0;
		  $childHtml = null;
		  if($prop['type'] != 6)
			  foreach($xmlObj->children() as $child) {
			  	$curCh++;
			    $childHtml .= $this->displayChilds($child,$prop['type'],$numCh == $curCh, $prop['id']);
			    $objHasChild = true;
			  }
		  if(!$objHasChild) // if there aren't any children
		  { //if a hbox and vbox don't have any children we create an empty cell
		  	if($prop['type'] == 1)
		  	{
		  		$html .= "<td $size></td>";
		  	}
		  	else if($prop['type'] == 2)
		  	{
		  		$html .= "<tr><td></td></tr>";
		  	}
		  }
		  else if(!$childHtml)//if all children of the element are hidden, we don't show it either
			return '';
		  else $html .= $childHtml;
		  $html .= $closeTags;

		  return $html;
	}


	public function getTimeSelector($fontStyle = null)
	{

		$dogovor_trenutni_date = getdate();
		$dogovor_tren_year = $dogovor_trenutni_date['year'];
		$dogovor_tren_mon = $dogovor_trenutni_date['mon'];
		$dogovor_tren_mday = $dogovor_trenutni_date['mday'];
		$dogovor_tren_hours = $dogovor_trenutni_date['hours'];
		$dogovor_tren_min = $dogovor_trenutni_date['minutes'];

		$style = "";

		if($fontStyle) $style .= 'style="' .  implode(';', $fontStyle)  . '"';

		$ts = '<select name="dogovor_dan" ' . $style . ' >';
		$ts .= "<optgroup " . $style .">";

		for($i = 1;$i<=31;$i++)
		{
			if($dogovor_tren_mday == $i)
				$ts .= "<option selected='true ' value=$i>$i</option>";
			else
				$ts .= "<option value=$i>$i</option>";
		}
		$ts .= "</optgroup>";
		$ts .= '</select>';

		$ts .= '.<select name="dogovor_mes" ' . $style . '>';
		$ts .= "<optgroup " . $style .">";
		for($i = 1;$i<=12;$i++)
		{
			if($dogovor_tren_mon == $i)
				$ts .= "<option selected='true' value=$i>$i</option>";
			else
				$ts .= "<option value=$i>$i</option>";
		}
		$ts .= "</optgroup>";
		$ts .= '</select>';

		$ts .='. <select name="dogovor_year" ' . $style . '>';
		$ts .= "<optgroup " . $style .">"
			."<option value=$dogovor_tren_year selected='true'>$dogovor_tren_year</option>"
			."<option value=".($dogovor_tren_year+1) .">".($dogovor_tren_year+1) ."</option></optgroup></select>";
		//set the hours
		$ts .= 'at <select name="dogovor_ura" ' . $style . '>';
		$ts .= "<optgroup " . $style .">";
		for($i = 6;$i<=22;$i++)
		{
			if($dogovor_tren_hours == $i)
				$ts .= "<option selected='true' value=$i>$i</option>";
			else
				$ts .= "<option value=$i>$i</option>";
		}
		$ts .= "</optgroup>";
		$ts .= '</select>';
		//set the minutes
		$ts .= ':<select name="dogovor_min" ' . $style . '>';
		$ts .= "<optgroup " . $style .">";
		for($i = 0;$i<=55;$i+=5)
		{
			if($dogovor_tren_min < $i && $dogovor_tren_min + 5 >= $i)
				$ts .= "<option selected='true' value=$i>$i</option>";
			else
				$ts .= "<option value=$i>$i</option>";
		}
		$ts .= "</optgroup>";
		$ts .= '</select>';
		 return $ts;
		}


		private function imageParameters($image) {
			//echo "$image";
			$parameters_arr = explode(";", $image);
			if (is_array($parameters_arr)) {
				$src_image = array_shift($parameters_arr);
				$image_obj['src'] = $src_image;
				$image_obj['param'] = implode(";",$parameters_arr);
				return $image_obj;
			}
			return false;
		}

		private function videoParameters($video) {
			//echo "$image";
			$parameters_arr = explode(";", $video);
			if (is_array($parameters_arr))
			{
				$video_obj['src'] = array_shift($parameters_arr);;
				$video_obj['width'] = array_shift($parameters_arr);;
				$video_obj['height'] = array_shift($parameters_arr);;
				$video_obj['param'] = implode(" ",$parameters_arr);
				return $video_obj;
			}
			return false;
		}


		private function NewLine2HTML($str) {
			$str = str_replace("\n","<br>",$str);
			$str = str_replace("\r","<br>",$str);
			$str = str_replace("<br><br>","<br>",$str);

			return $str;
		}

		private function HumanDate($timestamp) {
			return date('Y.m.d H:i:s', $timestamp);
		}


		private function setTelSelect($flag) {
			$this->manual_telselect = $flag;
			return true;
		}


		private function getTelSelect() {
			return $this->manual_telselect;
		}


		private function setTelSelectLock($flag) {
			$this->manual_telselect_lock = $flag;
			return true;
		}


		private function getTelSelectLock() {
			return $this->manual_telselect_lock;
		}


		public function set_warpitClientExecuteOnLoad($flag) {
			$this->warpitClientExecuteOnLoad = $flag;
		}


		public function get_warpitClientExecuteOnLoad() {
			return $this->warpitClientExecuteOnLoad;
		}

}

?>
