<?php
header("Content-type: text/html; charset=utf-8");
include '_dirinfo.php';

ini_set('display_errors', '0');     # don't show any errors...
error_reporting(E_ALL | E_STRICT);  # ...but do log them

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.'_config/dbConfig.php');


?>
<head>
  <title>Survey <?php echo $_SESSION['proj_name'];?></title>
  <style type="text/css">
  td {
    vertical-align: top;
     }

  </style>
   
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  
<?php include(PATH_TO_ROOT.'survey/javascript/head_includes_js.php') ?>

</head>
<?php 

//script for event logger!
echo "<script>
	function recodeClickEvents(aObj,eventType) {
	
}
	 </script>";

	 
/**
 * 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;
}

if($_REQUEST['questionId'] != 'fake')
{
$db->setLogging(1);

$projectId = $_REQUEST['projectId'];
$project = $_REQUEST['tableName'];

$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	//let's get the default language of this project!
	$res = $db->SQLexecute("SELECT proj_name,language FROM _Projects WHERE id = $projectId");
	$row = $db->fetchRow($res);
	$tableName = $row[0];
	$tableNameTree = $tableName.'_tree';
	
	$_SESSION['id_userLng'] = $row[1];
	$_SESSION['id_defaultQuestionLng'] = $row[1];
	
}
else 
{
	$projectId = 0;
	$_SESSION['id_userLng'] = 46;
	$_SESSION['id_defaultQuestionLng'] = 46;
}
//id of the question
$id = $_REQUEST['questionId'];
//if maskTemplateId in request, reassign it to a local variable
if($_REQUEST['maskTemplateId'])
	$maskTemplateId = $_REQUEST['maskTemplateId'];

if(!$id)
{//no question selected...give links for questionnaire :)
	$paths = ConfigLoader::loadConfig('paths');
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	//if id_site was send we show the created links...other wise the popup and cati link!
	if($_REQUEST['id_site'])
	{
		$sql = "SELECT loginSID,user_type FROM _www_ids WHERE id_project =$projectId AND (user_type = 4 ) AND id_site > ".$_REQUEST['id_site'];
		$res = $db->SQLexecute($sql);
		while ($row = $db->fetchRow($res))
		{
		
			echo $paths['warpit_www']."survey/index.php?loginSID=".$row[0]."<br>";
		}
	}
	else
	{
		$sql = "SELECT loginSID,user_type FROM _www_ids WHERE id_project =$projectId AND (user_type = 1 AND id_user = ".$_REQUEST['id_user']." OR user_type = 3)";
		$res = $db->SQLexecute($sql);
		while ($row = $db->fetchRow($res))
		{
			if($row[1] == 1)
			{
				echo "CATI link: <br>";	
			}
			else if($row[1] == 3)
				echo "Pop up link: <br>";
			
			echo "<a href='".$paths['warpit_www']."survey/index.php?loginSID=".$row[0]."&test=1' target='_new'>".$paths['warpit_www']."survey/index.php?loginSID=".$row[0]."</a><br>";
		}
	}
	exit;
	
}

$_SESSION['id_project'] = $projectId;
$_SESSION['proj_name'] = $project;
$_SESSION['nextQuestion'][0]['id'] = $id == 'fake' ? 1 : $id;
$_SESSION['questionFields'] = array();

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

$db->ChangeDatabase(DB_WARPIT_WEBCATI);


if($id == 'fake')
{
	if($maskTemplateId) //custom mask preview
	{
		$id = 0;
		$qVar['id'] = 0;
		$qVar['q_name'] = 'name';
		$qVar['id_mask'] = $maskTemplateId;
		$qVar['tip_sql'] = 11;
		$qVar['nav_sql'] = "Here is the instruction text";
		$qVar['vpr_sql'] = "Here is some sample question text! You can change this (somewhere), to make it feel more real";
		$qVar['odg_sql'] = "fake";//1 sample answer 1/2 sample answer 2/3 sample answer 3/4 sample answer 4/5 sample answer open";
		$qVar['open_answers'] = "fake";//'5';
		$qVar['les_sql'] = 1;
		$qVar['q_pos'] = 1;
	}
	else //other question designer template preview
	{
		$id = 1;
		$qVar['id'] = 1;
		$qVar['q_name'] = 'name';
		$qVar['tip_sql'] = 1;
		$qVar['nav_sql'] = "Here is the instruction text";
		$qVar['vpr_sql'] = "Here is some sample question text! You can change this (somewhere), to make it feel more real";
		$qVar['odg_sql'] = "1 sample answer 1/2 sample answer 2/3 sample answer 3/4 sample answer 4/5 sample answer open";
		$qVar['open_answers'] = '5';
		$qVar['les_sql'] = 1;
		$qVar['q_pos'] = 1;
	}
	
	include_once PATH_TO_ROOT.'_class/createQuestion/Question.php';
	$display->q[$id] = Question::createQuestion($qVar['tip_sql'],$db,$qVar);
	$qVarCount[] = $qVar;
} //if 
else 
{
	if($_REQUEST['id_showTogether'])
	{
		$sql = "SELECT * FROM $project WHERE id_showTogether = ".$_REQUEST['id_showTogether']." ORDER BY q_pos";
	}
	else
	{
		//this gets called on preview in Build Questionnaire
		$sql = "SELECT * FROM $project WHERE id=$id";
	}
	
	$i = 0;
	$_SESSION['id_selectedQuestionLng'] = $_REQUEST['id_language'];
	$_SESSION['questionFields'] = array();
	try {
	if(!$rs = $db->SQLexecute($sql)) echo $db->GetError();
		while($qVar = $db->fetchArray($rs))
		{
			//lets get the language data for the questions
			$lngSql = "SELECT variable,lngText FROM ".$project."_language a " .
					  "INNER JOIN _LanguageText b ON a.id_text_type = b.id_text WHERE " .
					  "id_question = {$qVar['id']} AND (id_language = ".$_REQUEST['id_language']." OR id_language = ".$_SESSION['id_defaultQuestionLng']." )";
				$lngRes = $db->SQLexecute($lngSql);
				while ($lngRow = $db->fetchRow($lngRes))
				{
					if($lngRow[2] == $qLng || !$res[ $lngRow[0] ])
						$qVar[ $lngRow[0] ] = $lngRow[1];					
				}
			$qVarCount[] = $qVar;
		}
	}
	catch (Exception $e)
	{
		echo "Error getting question!: <br>".$e;	
		exit;
	}
	
	$qVar = $qVarCount[0];
	$id = $qVarCount[0]['id'];

	//if this is a custom question let's find the mask template id
	if($qVarCount[0]['id_mask'])
		$maskTemplateId = $qVarCount[0]['id_mask']; //assign the maskTemplateId
	
}
    //in this variable we save id of template for selecting body_properties
    $idTemplate = 0;
    
	if($_REQUEST['templateId']) // designer
	{
		//echo "executing 1";
		$curXML = $db->get('_DesignerTemplates',$_REQUEST['templateId'],'template_xml',DB_WARPIT_WEBCATI_BASE);
		$display->idTemplate = $_REQUEST['templateId'];
		//$idTemplate = $_REQUEST['templateId'];
	}
	else if($maskTemplateId) // mask designer
	{
		//echo "executing 2, template ". $maskTemplateId;
		$curXML = '<?xml version="1.0"?><DIV id="0"><ANSWER id="5000" type="6" /></DIV>'; //empty template for previews
		  //$curXML = $db->get('_MaskTemplates',$maskTemplateId,'template_xml',DB_WARPIT_WEBCATI_BASE);
		//$curXML = $db->get('_DesignerTemplates',2,'template_xml',DB_WARPIT_WEBCATI_BASE);
		$display->idTemplate = $maskTemplateId;
	}
	else //normal question
	{
		//echo "executing 3";
		$curXML = $display->readXML($id,$projectId);
        $idTemplate = $display->getIdTemplate();		
	}
	
	if($curXML)
	{
		$xml = simplexml_load_string( $curXML );
		foreach ($xml->attributes() as $attr => $value) {
				$prop[$attr] = "$value";
			}
		if($prop['RMclass'])
		{
			$style = $display->getCssStyles($prop['RMclass']);
		}
        
        $bodyStyle = "Style=\"height:100%;border: 0 none;margin:0;padding:0;overflow:auto;$style \"";  
        if($idTemplate != 0)
        {
            $sqlBP = "SELECT * FROM _DesignerTemplates WHERE id = " . $idTemplate;
            $resBP = $db->SQLexecute($sqlBP);
            $rowBP = $db->fetchAssoc($resBP);
            
            if(strlen($rowBP['body_properties'])>0) 
            {
                $bodyStyle = $rowBP['body_properties'];
            }

            // 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");
        }
        
		echo "<body " . $bodyStyle ." \">
		<FORM style=\"height:100%;border: 0 none;margin:0;padding:0;width:100%; \" id='mainForm' METHOD='POST' onsubmit='return false;'>" . $anystretch . " <script>
            $(function()
            {
                "
                 .  $checkJquery .
                "
            });</script>";;
				
		$html = "<table cellpadding=0px cellspacing=0px style=\"width:100%;\">";
		 foreach($xml->children() as $child) {
		  $chAttr = $child->attributes();
		  if($chAttr['type'] == 5)
		  {
		  	$windows .= $display->displayChilds($child,0,false);
		  }
		  else
		  {
		  	$html .=  $display->displayChilds($child,0,false);
		  } 
		 }
		 $html .= "</table>";
		echo $html;
		//echo $windows;
		echo "<input type='hidden' class='preview_template' value=$display->idTemplate />";
	echo "</FORM>";
	}
//echo "<PRE>";
//print_r($_SESSION);
//echo "</PRE>";
?>

</body>
