<?php
header ("Content-type: text/html; charset=utf-8");
header("Cache-Control: no-cache, must-revalidate"); 
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 

date_default_timezone_set('Europe/Ljubljana');

ini_set('display_errors', '1');     # don't show any errors...
error_reporting(E_ERROR | E_WARNING | E_PARSE);  # ...but do log them

include '_dirinfo.php';

include_once(PATH_TO_ROOT."_support/class.db.php");
include_once(PATH_TO_ROOT."webcati/_class/class.Display.php");
include_once(PATH_TO_ROOT."webcati/_class/class.Engine.php");
include_once(PATH_TO_ROOT."webcati/_class/class.SurveySession.php");
include_once(PATH_TO_ROOT."_support/class.configLoader.php");
include(PATH_TO_ROOT."/webcati/_class/class.RM_AsteriskManager.php");	
include_once (PATH_TO_ROOT.'survey/usrs_methods.php');


include (PATH_TO_ROOT.'_config/dbConfig.php');

include_once(PATH_TO_ROOT.'_support/convertVars.php');

$db->ChangeDatabase(DB_WARPIT_MAIN);
$customMethods = configLoader::loadConfig('paths');

include_once(PATH_TO_ROOT . $customMethods['usr_methods_custom']);

//7.1.2015 sqlinjection
if(class_exists('convert'))
{
    $_SERVER['PHP_SELF'] = convert::toId($_SERVER['PHP_SELF']);    
}

$db->setLogging(1);


//file_put_contents("/var/sandek/log/request_display.txt", "_REQUEST:".print_r($_REQUEST,true)."\n", FILE_APPEND | LOCK_EX);

$WebSession = new SurveySession($db,$_GET['loginSID'],$_GET['asteriskID']);
//$startTime = microtime(true);

//echo "<PRE>";
//print_r($_SESSION);
//print_r($_REQUEST);
//print_r($WebSession);
//echo "<font color=black>COUNTER index.php</font>";
//echo "</PRE>";


$db->LogWrite("\n\n\n\n\n\n\n\n\n\n\nNEW LOOP",true,"");
$db->LogWrite(print_r($_REQUEST,1),true,"POST variable...");

if ( $WebSession->GetLoginStatus() != 2 and  !$WebSession->IsReLogin() ) {
	echo "No login allowed!!! -> Login code ".$WebSession->GetLoginStatus();
	exit;
}

if(!$_SESSION['detectedDevice'])
{
	include (PATH_TO_ROOT.'_support/Mobile_Detect.php');
	$mobile = new Mobile_Detect();
	$_SESSION['detectedDevice'] = $mobile->isMobile() ? 2 : 0;
}


// because of TGI modul I add new session variable
// if this is set I will run always when body is loaded javascript to execute something in TGI portal
// once it should be written, to send any variable with external javascript function
// I should od it universal for any possible plugin to other modules 
if ($_GET['TGIclient'] == 1) $_SESSION['TGIclient'] = $_GET['TGIclient'];
if ($_SESSION['TGIclient'] == 1) {
	$dbConfigTGI = configLoader::loadConfig('tgi');
	define("DB_WARPIT_TGI", $dbConfigTGI['database'] );
}


$_SESSION['gotoIdle'] = $_POST['gotoIdle'];

// set the survey title
$titleConfig = configLoader::loadConfig('survey');
// I need constant for record_owner when questionnaire is finished
define("DB_RECORD_OWNER", $titleConfig['record_owner'] );
// define constant, if in config I set default value for multi
if(strlen($titleConfig['multiresponse_default_fill'])>0) define("MULTI_DEFAULT_VALUE", $titleConfig['multiresponse_default_fill']);

$surveyTitle = "Survey - ".$_SESSION['proj_name'];
if ($titleConfig['survey_title']) $surveyTitle = $titleConfig['survey_title'];

$questionnaire = new Engine($db,$WebSession);
// Borut added 15.5.2014, BUG... if this session was not set here, than at the end of the questionnaire 
// user_id was replaced with 0 for CAPI
if ($questionnaire->idGenStruc) { 
	$_SESSION['id_user_external'] = $questionnaire->idGenStruc;
}

// we add dropdown for selectiong the reason for going IDLE
// Added by Marko, 2014.11.05
$db->LogWrite($_POST['gotoIdleReason'],true,"setting questionnaire->gotoIdleReason inside index.php");
$questionnaire->gotoIdleReason = $_POST['gotoIdleReason'];
// *******************************************************

//<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
//<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
// at the moment there is HTML5 standard selected
?>
<!DOCTYPE html>

<head>
  <title><?php echo $surveyTitle; ?></title>
  <style type="text/css">
  td {
    	vertical-align: top;
     }
  </style>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php include PATH_TO_ROOT.'survey/javascript/head_includes_js.php';?>
</head>
<?php 

//log when we left the previous question!
$questionnaire->LoggingLeave();

//
//echo "test ".$_POST['RMquestionDuration'];


if($_SESSION['call_center'] or $_REQUEST['call_center'] == 1){	 
	$_SESSION['call_center'] = 1;
	$_REQUEST['call_center'] = 1;
	$call_center = 1;
	if(!is_numeric($_REQUEST['conferenceID']))
		$_REQUEST['conferenceID'] = '';
	$call_center_CallUniqueId = strip_tags($_REQUEST['call_center_CallUniqueId']);
	if(!preg_match('/^[0-9-]+(\.)([0-9]+)$/',$call_center_CallUniqueId)){
		$_REQUEST['call_center_CallUniqueId'] = '';
		$call_center_CallUniqueId = '';
	}		 
	$db->LogWrite("call_center:".$call_center,true,"call center je ali ni");
}
else 
	$_REQUEST['call_center'] = '';
//echo "<pre>answers:";
//print_r($_POST['answers']);
//echo "</pre>";

// because I have two different screens on dialer, first submit click if this is set must be ignored, 
// I added "AND !_POST['manual_dial_select']"

if ($_POST['questSubmit'] AND !$_POST['manual_dial_select'] ) {
	$db->LogWrite("call_center index:".$call_center,true,"call center v questSubmit");
	$questionnaire->SaveQuestions($_POST['answers']);
	$nextQuestion = $questionnaire->searchingNextQuestion();
	//$questionnaire->defineCurrentRotationString();
	//$nextQuestion = $questionnaire->searchingNextQuestion();
	
	$db->LogWrite(print_r($nextQuestion,1),true,"POST questSubmit");
} elseif ($_POST['questBack']) {

	//reset some sessions!
	unset($_SESSION['makeApp']);
	$nextQuestion = $questionnaire->searchingPreviusQuestion();
	
	$db->LogWrite(print_r($nextQuestion,1),true,"POST questBack");
} 
elseif($_POST['makeAppointment'])
{
	$_SESSION['makeApp'] = true;
	$questionnaire->makeApp=true;
	$questionnaire->SaveQuestions();
	$nextQuestion = $questionnaire->searchingNextQuestion();
	
	$db->LogWrite(print_r($nextQuestion,1),true,"POST makeAppointment");
}
elseif ($_POST['startNew']) {
	$db->LogWrite(print_r($_POST['predictive'],1),true,"POST startNew");
	
		//if predictive, we must remove user from queue!
		if($_POST['predictive'])
		{
			require_once(PATH_TO_ROOT."survey/predictive/class.RM_AsteriskManager_predictive.php");
					
	  				extract( configLoader::loadConfig('asterisk_dialing'));
					
//	  				$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($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  )) {
	  					$am_addqueue->RemoveFromQueue($_SESSION['asteriskID'],$_SESSION['id_project']);
	  				}
		}
		$questionnaire->finalStatus = $_POST['specialStat'] ? $_POST['specialStat'] : 54;
	//	$questionnaire->finalRecStatus = 1;
		if($_POST['qCommentText'])
			 {
			 	$sql = "INSERT INTO ".DB_WARPIT_WEBCATI."._QuestionComments (id_project,id_question,id_structure,qComment) VALUES ($questionnaire->id_project,{$questionnaire->nextQuestion[0]['id']},$questionnaire->id_record,'{$_POST['qCommentText']}') ON DUPLICATE KEY UPDATE qComment = '{$_POST['qCommentText']}'";
			 	$db->SQLexecute($sql);
			 }
		$questionnaire->FinishQuestionnaire();
} 
/* not used aymore becouse we have now submit, break bttons and gotoidle checkbox
elseif ($_POST['confirmStartNew']) {
	//simple confirm...this button will be avaliable on final questions only!
	$questionnaire->SaveQuestions($_POST['answers']);
	$nextQuestion = $questionnaire->searchingNextQuestion();
	
} 
elseif ($_POST['confirmGotoIdle']) {

	$questionnaire->gotoIdle = true;
	$questionnaire->SaveQuestions($_POST['answers']);
	$nextQuestion = $questionnaire->searchingNextQuestion();
	
} */
elseif($_POST['startOther'])
{
	//create new record
	$questionnaire->CreateEmptyRecord();
	 //v structure tabelo zapisemo vse podatke iz index tabele!!!!
	$idtelName = $_SESSION['id_telname'];
	$telData = $_SESSION['telData'];
	$id_selected_telnum = $_SESSION['id_tel'];
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$sql = "SELECT name FROM _TelephoneTblDefaultVar WHERE use_in_index = 1";
	if(!$res = $db->SQLexecute($sql)) return $db->JsonError();
	while($row = $db->fetchRow($res))
		$setFields[] = 'TP_'.$row[0]." = '".$telData[$row[0]]."'";		
	$sql = "SELECT name FROM _TelephoneTablesAddon WHERE id_telbaza = $idtelName";
	if(!$res = $db->SQLexecute($sql)) return $db->JsonError();
	while($row = $db->fetchRow($res))
	{
		$setFields[] = 'TP_'.$row[0]." = '".$telData['tel_'.$row[0]]."'";		
	}
 	$sql = "UPDATE ".$_SESSION['proj_name']."_structure SET status=1  , status_rec=99,id_tel= $id_selected_telnum,".implode(',',$setFields)." WHERE id = ".$_SESSION['id_record'];
 	//this is not ideal, that it is required to set seperatly...but otherwise it is overrriden :(
 	$_SESSION['finalStatus'] = 1;
	$db->SQLexecute($sql);
	$questionnaire->startOther = true;
	$questionnaire->SaveQuestions();
 	$nextQuestion = $questionnaire->searchingNextQuestion();
 	//somehow jump to first question ??? :S
 	
 	$db->LogWrite(print_r($nextQuestion,1),true,"POST startOther");
}
else if($_GET['autoDial'])
{
	$db->LogWrite(print_r($_SESSION['telData'],1),true,"GET autodial");
	
					/*
					// BORUT add for Mediana debug 19.3.2013
	  				// do some extra session save into separate table, just for debug...	
					$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	  				$SESsql = "SELECT ses_value FROM _tmpSES_dial WHERE id_user = ".$_SESSION['id_user'];
	  				$resSES = $db->SQLexecute($SESsql); 
					$rowSES = $db->fetchRow($resSES);
	  				$_SESSION['telData'] = unserialize(stripslashes($rowSES[0]));
					$db->LogWrite(print_r($_SESSION['telData'],1),true,"GET autodial, after BORUT read Mediana debug");
					$db->ChangeDatabase(DB_WARPIT_WEBCATI);
					*/
					
	  				//let's turn off session saving
	  				$WebSession->SetIgnoreSessionSave(true);
					$user_id = $_SESSION['id_user'];
					$_SESSION['lineEstablished'] = false;
					//$context = "local";
					//$callerID = "2342542";
					$Interna = $_SESSION['asteriskID'];
					if(!$Interna)
					{
						echo "INTERNA ERROR!";
					}
					//$Interna = "866";
					
						$oms = $_SESSION['telData']['oms'];
						$tel = $_SESSION['telData']['telephone'];
						$Number2Call = "0$oms$tel";
		  			
					$AsteriskManager = new RM_AsteriskManager($db);
					extract( configLoader::loadConfig('asterisk_dialing'));
					
					$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
					if ($AsteriskManager->LogOn($asterisk_username, $asterisk_password, $asterisk_ip, $asterisk_port, $Interna, $user_id)) {
						
						$LineStatus = $AsteriskManager->ExtensionStatus($Interna,$context);
						//echo "Line status: ".$LineStatus."<br>";
						
						
						if (true || $LineStatus == 0 || $LineStatus == -1 ) {
							//hangup first just in case
							$AsteriskManager->Hangup($Interna);
							sleep(1);
							
							$AsteriskManager->setTelLog($_SESSION['id_tellog']);
							$AsteriskManager->setProjectName($_SESSION['proj_name']);
							if ($AsteriskManager->Dial($Interna, $context, $callerID, $Number2Call)) {
								echo "Dial success!<br>";
								
							} else {
								echo "Dial failed!<br>";
							}
					 
						/*	sleep(2);
							if ($AsteriskManager->Hangup($Interna)) {
								echo "Hangup success!";
							} else {
								echo "Hangup failed!";
							}*/
						}
						
					} else {
						echo "LOGIN failure!<br>";
						exit;
					}
				
					//echo "Dial status: ".$AsteriskManager->DialStatus."<br>";
					$AsteriskManager->LogOff();
	  				if($AsteriskManager->DialStatus == 1)
	  				//we got an answer! go forth and show status menu!
	  				{
	  					 $_SESSION['autoDialer']['dialed'] = true;
		  				echo "
		  				<script>
		  				parent.document.forms['mainForm'].submit()
		  				</script>";
	  				}	
		  			else if($AsteriskManager->DialStatus == 2)
		  			{//we go forth, select status, and tell
		  				 $_SESSION['autoDialer']['statusSelected'] = '22_0';
		  				echo "dol je vrgo!
		  				<script>
		  				parent.document.forms['mainForm'].statusSelected.value = '22_0';
		  				parent.document.forms['mainForm'].submit()
		  				</script>";	
		  			}
					else if($AsteriskManager->DialStatus == 5)
		  			{//we go forth, select status, and tell
		  				 $_SESSION['autoDialer']['statusSelected'] = '9_1';
		  				echo "dol je vrgo!
		  				<script>
		  				parent.document.forms['mainForm'].statusSelected.value = '9_1';
		  				parent.document.forms['mainForm'].submit()
		  				</script>";	
		  			}
					else if($AsteriskManager->DialStatus == 8)
		  			{//we go forth, select status, and tell
		  				 $_SESSION['autoDialer']['statusSelected'] = '5_1';
		  				echo "dol je vrgo!
		  				<script>
		  				parent.document.forms['mainForm'].statusSelected.value = '5_1';
		  				parent.document.forms['mainForm'].submit()
		  				</script>";	
		  			}
					else if($AsteriskManager->DialStatus == 9)
		  			{//other telephone network problem
		  				 $_SESSION['autoDialer']['statusSelected'] = '25_9';
		  				echo "dol je vrgo!
		  				<script>
		  				parent.document.forms['mainForm'].statusSelected.value = '25_9';
		  				parent.document.forms['mainForm'].submit()
		  				</script>";	
		  			}
		  			else 
		  			{
		  					echo "Status: $AsteriskManager->DialStatus <br>
		  					<script>parent.document.location='".PATH_TO_ROOT."tel/index.php?RMerror=".urldecode("NAPAKA! Dial status: $AsteriskManager->DialStatus , interna:{$_SESSION['asteriskID']} ")."';</script> ";
		  			}
		  			exit;
}

else if($_POST['lineEstablished'])
{//user pressed line established button
 	$_SESSION['autoDialer']['dialed'] = true;
	$_SESSION['gotoIdle'] = false;
	$_POST['gotoIdle'] = false;
	$_SESSION['lineEstablished'] = true;
	$questionnaire->gotoIdle = false;
	$questionnaire->SaveQuestions();
	$nextQuestion = $questionnaire->searchingNextQuestion();
	
	$db->LogWrite(print_r($nextQuestion,1),true,"POST lineEstablished");	
}
elseif ($_POST['gotoIdle']) {//grrrrr this should not be like that :)

	$questionnaire->gotoIdle = true;
	if( $_SESSION['nextQuestion'][0]['id'] == $_SESSION['rotLastQuestion'])
	{
		
		$questionnaire->SaveQuestions($_POST['answers']);
		$nextQuestion = $questionnaire->searchingNextQuestion();
	}
	else 
	{
		$questionnaire->finalStatus = 54;
		$questionnaire->finalRecStatus = 2;
		$questionnaire->FinishQuestionnaire();
	}
	
	$db->LogWrite(print_r($nextQuestion,1),true,"POST gotoIdle");
} 
else if($_GET['preview'])
{
	$nextQuestion[0]['id'] = $_GET['questionId'];
	$db->LogWrite(print_r($nextQuestion,1),true,"GET preview");
}
elseif ($questionnaire->isInitialization()) {
	$nextQuestion = $questionnaire->searchingNextQuestion();
	$db->LogWrite(print_r($nextQuestion,1),true,"isInitialization");
}
elseif (!$WebSession->IsReLogin()) {
	$nextQuestion = $questionnaire->BrowserBackButton();
	$db->LogWrite(print_r($nextQuestion,1),true,"isReLogin");
	
} 


if ($questionnaire->isFinished()) {
	exit;
}



$projectId = $questionnaire->GetIdProject();
$project = $questionnaire->GetProjectName();

$db->LogWrite($projectId." - ".$project,true,"get project name and ID");

/**
 * Lets get the language the questionnaire will be shown in
 * If the user has chosen the language trough a combobox the id will be stored in 'selectedQuestionLng'
 * if not, the default
 * 
 * Borut dodal, da lahko language pride preko WEB link kot parameter, 25.2.2012 $_GET['languageID']
 */
if($_SESSION['id_selectedQuestionLng'])
{
	$qLng = $_SESSION['id_selectedQuestionLng'];
}
else if($_POST['languageChooser'])
{
	$qLng = $_POST['languageChooser'];
	/**
	 * Borut, BUG fixed? 2014/02/25 01:21
	 * when selecting busy or any other then confirmed call,
	 * lanugage dropdown was not shown again to reselect
	 * lower IF.... is possible solution... set only if I go forward into interview, time will tell...
	 */
	if (substr($_POST['status_telnum'],0,2) == "1_" OR !isset($_POST['status_telnum'])) $_SESSION['id_selectedQuestionLng'] = $_POST['languageChooser'];
	$questionnaire->updateLanguage($qLng);
}
else if($_GET['languageID'])
{
	$qLng = $_SESSION['id_selectedQuestionLng'] = $_GET['languageID'];
	$questionnaire->updateLanguage($qLng);
}
else if($_SESSION['id_defaultQuestionLng'])
{
	$qLng = $_SESSION['id_defaultQuestionLng'];
}
$idQuestDefLng = $_SESSION['id_defaultQuestionLng'];



$display = new Display($db,$questionnaire);

// if I found address, I store id_tel of the number
$db->LogWrite($_GET['id_searched_tel'],true,"GET iz forme za searched id_tel");
if ($_GET['id_searched_tel']) $display->id_searched_tel = $_GET['id_searched_tel'];


$display->device = $_SESSION['detectedDevice'];

$questionnaire->display = $display;

$db->ChangeDatabase(DB_WARPIT_WEBCATI);
foreach ($nextQuestion as $nqCount) {

	$id = $nqCount['id'];

	// read all question properties from selected project
	$sql = "SELECT * FROM $project WHERE id=$id";
	$db->LogWrite($sql,true,"get question properties...:");
	
	try {
		if(!$rs = $db->SQLexecute($sql)) echo $db->GetError();
		$res = $db->fetchAssoc($rs);
		
		if($nqCount['filter'])
			$res['filter'] = true;
		$lngSql = "SELECT variable,lngText,id_language FROM ".$project."_language a INNER JOIN _LanguageText b ON a.id_text_type = b.id_text WHERE id_question = {$res['id']} AND (id_language = $qLng OR id_language = $idQuestDefLng)";

		$lngRes = $db->SQLexecute($lngSql);
		while ($lngRow = $db->fetchRow($lngRes))
		{
			//we write the language only if it is the selected one (regardless if we override the default)
			//or if it is not set yet (preventing default from overriding selected
			//this is neccesery becouse we do not know in what order we get the languages!
			if($lngRow[2] == $qLng || !$res[ $lngRow[0] ])
				$res[ $lngRow[0] ] = $lngRow[1];
			
		}
			
		$qVarCount[] = $res;
	}
	catch (Exception $e)
	{
		echo "Error getting question!: <br>".$e;	
		exit;
	}

}

/**
 * Extract URLs from CSS text.
 */
function extract_css_urls( $text )
{
    $urls = array( );
 
    $url_pattern     = '(([^\\\\\'", \(\)]*(\\\\.)?)+)';
    $urlfunc_pattern = 'url\(\s*[\'"]?' . $url_pattern . '[\'"]?\s*\)';
    $pattern         = '/(' .
         '(@import\s*[\'"]' . $url_pattern     . '[\'"])' .
        '|(@import\s*'      . $urlfunc_pattern . ')'      .
        '|('                . $urlfunc_pattern . ')'      .  ')/iu';
    if ( !preg_match_all( $pattern, $text, $matches ) )
        return $urls;
 
    // @import '...'
    // @import "..."
    foreach ( $matches[3] as $match )
        if ( !empty($match) )
            $urls['import'][] = 
                preg_replace( '/\\\\(.)/u', '\\1', $match );
 
    // @import url(...)
    // @import url('...')
    // @import url("...")
    foreach ( $matches[7] as $match )
        if ( !empty($match) )
            $urls['import'][] = 
                preg_replace( '/\\\\(.)/u', '\\1', $match );
 
    // url(...)
    // url('...')
    // url("...")
    foreach ( $matches[11] as $match )
        if ( !empty($match) )
            $urls['property'][] = 
                preg_replace( '/\\\\(.)/u', '\\1', $match );
 
    return $urls;
}

$id = $qVarCount[0]['id'];
$qVar = $qVarCount[0];
$qType = $res['tip_sql'];

// recording on screen events, what interviewer does on the screen
include_once("javascript/event_loger.php");

	/*if($qType==11) //custom mask type - load mask instead
	{
		$curXML = $db->get('_MaskTemplates',$res['id_mask'],'template_xml',DB_WARPIT_WEBCATI_BASE);
		$display->idTemplate = $res['id_mask'];
	}
	else //other types, load designer template*/
		$curXML = $display->readXML($id,$projectId);
	$db->LogWrite($curXML,true,"if I have XML for this question...");
	if($curXML)
	{
		$xml = simplexml_load_string( $curXML );
		foreach ($xml->attributes() as $attr => $value) {
				$prop[$attr] = "$value";
			}
		if($prop['RMclass'])
		{
			$style = $display->getCssStyles($prop['RMclass']);
		}
		
		$db->LogWrite($style,true,"before write <body to the page");
        
        $sqlBP = "SELECT * FROM _DesignerTemplates WHERE id = " . $display->getIdTemplate();
        $resBP = $db->SQLexecute($sqlBP);
        $rowBP = $db->fetchAssoc($resBP);
        
        if(strlen($rowBP['body_properties'])>0) {
            $bodyStyle = $rowBP['body_properties'];
        } else {
            $bodyStyle = "Style=\"height:100%;border: 0 none;margin:0;padding:0;overflow:auto;$style \"";     
        }
        
        // This script is used to replace standard cheboxes and radiobuttons with custom images. To do that we just hide standard controls and add images instead
        $checkJquery = "";
        
        include_once(PATH_TO_ROOT . "survey/javascript/custom_inputs.php");
        
     //   $bodyStyle = $row['body_properties']:"height:100%;border: 0 none;margin:0;padding:0;overflow:auto;$style";
        
		echo "<body onLoad=\"warpitClientExecuteOnLoad();\" $bodyStyle>" . $anystretch . " <script>
            $(function()
            {
                "
                 .  $checkJquery .
                "
            });</script>";
		
		if($_GET['capiTablet'] or $_SESSION['capiTablet']) //if it is mobile device, the value is 1, else empty
		{
			
			//$GLOBALS['userName'] = $_SESSION['UserInfo']['Firstname'].' '.$_SESSION['UserInfo']['Surname'];
			$_SESSION['capiTablet'] = 1;
			if($_GET['id_site'])
				$_SESSION['id_site'] = $_GET['id_site'];
			include PATH_TO_ROOT."capi_html/_forms/menuMobileDevice.php";			
			echo "<input type=\"hidden\" name=\"idSite\" value=\"".$_SESSION['id_site']."\"/>";	
		}
		
		echo "<FORM style=\"height:100%;border: 0 none;margin:0;padding:0;width:100%; \" id='mainForm' METHOD='POST' action='".htmlspecialchars($_SERVER['PHP_SELF'])."'>";
		//hidden variable for clickEventLogger!
		echo "<input type='hidden' name='RMclickLogger'>";
		echo "<input type='hidden' name='RMquestionDuration'>";
		
	
		
		echo "<input type='hidden' name='call_center' value='".$call_center."'>";
		echo "<input type='hidden' name='call_center_CallUniqueId' value='".$call_center_CallUniqueId."'>";
		//file_put_contents("/tmp/post_display.txt", "indexreq:".$call_center_CallUniqueId." ".print_r($call_center,true)."\n", FILE_APPEND | LOCK_EX);
		// set to true to load empty function (just for no error)
		$display->set_warpitClientExecuteOnLoad(true);
		
		$html = "<table cellpadding=0px cellspacing=0px style=\"width:100%;\">";
			//beforedisplay event ???
			//read the script for this question!
			if($source = $GLOBALS['scriptEvent'][2]) {	
				eval( $source);	
			}
		
			$db->LogWrite("in attributes I find which type of window should I draw",true,"With display->displayChilds I draw to screen all objects from template");
			foreach($xml->children() as $childKey => $child) {
				$chAttr = $child->attributes();
				if($chAttr['type'] == 5)
				{
					$windows .= $display->displayChilds($child,0,false);
				}
				else {
					$html .=  $display->displayChilds($child,0,false); 
				}
				
				$db->LogWrite($html,true,"index.php(line 522): html build from display class");
			}
			//afterdisplay event
	
		$html .= "</table>";
		
		// function must exist but maybe because of something I want to change default to some other and I set a flag if this should or should not be loaded
		// display childs function load all display object and inside this object I load this function
		if ($display->get_warpitClientExecuteOnLoad()) {
			$html .= "<script>function warpitClientExecuteOnLoad() {";
				if ($_SESSION['TGIclient'] == 1) {
					// updatnem tudi TGI s progress statistiko
					// ker nimam warpit userja, ge pridobim iz TGI tabel 
					if ($display->progressPct > 0) {
						$sqlTGIusr = "SELECT * FROM ".DB_WARPIT_TGI.".TGI_projects_links WHERE id_link=".$_SESSION['id_loginSID'];
						$db->LogWrite($sqlTGIusr,true,"TGI fill pct (GET user)");
						$resTGIusr = $db->SQLexecute($sqlTGIusr);
						$rowTGIusr = $db->fetchAssoc($resTGIusr);
					
					 	$sqlPctUpdate = "UPDATE ".DB_WARPIT_TGI.".TGI_warpit_projects_users SET `done`='".$display->progressPct."' 
					 			WHERE `TGI_project`='".$rowTGIusr['TGI_project']."' AND `warpit_project`='".$rowTGIusr['warpit_project']."' AND 
					 					`id_user`='".$rowTGIusr['id_user']."' AND `type_user`='".$rowTGIusr['type_user']."'";
					 	$db->LogWrite($sqlPctUpdate,true,"TGI fill pct (write)");
						$db->SQLexecute($sqlPctUpdate);
					
						$html .= "var pct = document.getElementById('progressPct').value;";
						$html .= "parent.updateProgressPct(pct,".$_SESSION['id_project'].");";
					}
				}
			$html .= "}</script>";
		}
		
		if ($_REQUEST['call_center'] == 1) {
			$html .= "<input type='hidden' name='call_center' value='1'>";
			$html .= "<input type='hidden' name='call_center_CallUniqueId' value='".$call_center_CallUniqueId."'>";
			$html .= "<input type='hidden' name='conferenceID' value='".$_REQUEST['conferenceID']."'>";
			$_SESSION['call_center'] = 1;
		}	
		echo $html;
		//echo $windows;
		
		echo "</FORM>";
		$sql = "SELECT script FROM $project"."_script WHERE id_event = 3 AND id_question =".$qVar['id'];
		$db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$rs = $db->SQLexecute($sql);
		$row = $db->fetchRow($rs);
		if($source = $row[0]) {
			echo "<script>".$source."</script>";
		}
	}
	
/*
echo "<PRE>";
print_r($_SESSION);
echo "</PRE>";
*/

//	$endTime =  microtime(true) - $startTime;
//	echo $endTime;
?>

<script>
Mousetrap.bind('enter', function() {execSubmit()});
function execSubmit() { 
	$("input[name = 'questSubmit']").trigger('click');
}

</script>
</body>
</html>