<?php

	#  Author       :  Simon John Brookfield
	#  Date         :  September 2003
	#  Project      :  Vacatures
	#  Filename     :  class.avb.php
	#  Version      :  1.0
	#  Description  :  Vacaturebank

// Includes
require_once 'class.stdModule.php';

class Enquetes extends stdModule {

	var $vlst_id;
	var $vusr_id;

	var $q_progress;
	var $aResume;
	var $iTotDone;
	var $iHasDone;
	var $q_questions;
	var $q_skipped;
	var $curr_org;

	function Enquetes() {
		$this->stdModule('csur0100');
		$this->curr_org = $_SESSION['arr_cur_org']['ORG_ID'];

		/* templates */
		$this->_settings->templates->q_overview	 	= 'q_overview.tpl';
		$this->_settings->templates->preface	 	= 'preface.tpl';
		$this->_settings->templates->questions	 	= 'questions.tpl';
		$this->_settings->templates->finished	 	= 'finished.tpl';
		$this->_settings->templates->result_list 	= 'result_lists.tpl';
		$this->_settings->templates->list_results 	= 'list_results.tpl';
		$this->_settings->templates->login 			= 'login.tpl';

	}

	function _getGroups() {

		//return $_SESSION["arr_memberships"][$this->curr_org]["GROUPS"];

		global $g_obj_ti3a0365;
		if (!isset($_SESSION["csur_memberships"])) $_SESSION["csur_memberships"] = $g_obj_ti3a0365->getMemberships($_SESSION['session_usr_id'], '', array('gatt_org_url'), true);
		return $_SESSION["csur_memberships"][$this->curr_org]["GROUPS"];

	}

	function _getQCountForList($vlst_id) {
		$rs = $this->_db->Query("select count(vvrg_id) as COUNTED from sur_vragenlijst_vragen where vvrg_vlst_id = ".$vlst_id);
		$result = $rs->Row('COUNTED');
		$rs->Close();
		return $result;
	}

	function _hasAnswers($vusr_id) {
	    $rs = $this->_db->Query("select count(vaw_vvrg_id) as ANSWRS from sur_vragenlijst_antwoorden where vaw_vusr_id=".$vusr_id);
		$result = $rs->Row('ANSWRS');
		$rs->Close();
		return $result;
	}

	function _setVusr() {
		$rs = $this->_db->Query("select vusr_id from sur_vragenlijst_users where vusr_usr_id=".$this->_variables->public->usr_id." and vusr_vlst_id=".$this->vlst_id);
		$this->vusr_id = $rs->Row('VUSR_ID');
		$rs->Close();
	}

	function _checkReferer($vvrg_id,$iBack,$vopt_id="") {
    	if ($iBack) {
			$rs = $this->_db->Query("select vrd_vvrg_id from sur_vragenlijst_routing_done where vrd_to_vvrg_id=".$vvrg_id);
			$result =  $rs->Row('VRD_VVRG_ID');
			$rs->Close();
    	    return $result;
    	} else {
    	    if ($vopt_id=="") {
				$rs = $this->_db->Query("select vrou_to_vvrg_id from sur_vragenlijst_routing where vrou_vvrg_id=".$vvrg_id." and vrou_vopt_id is null");
				$result =  $rs->Row('VROU_TO_VVRG_ID');
				$rs->Close();
				return $result;
    	    } else {
    	        if ($vopt_id=="opn") {
					$rs = $this->_db->Query("select vrou_to_vvrg_id from sur_vragenlijst_routing where vrou_vvrg_id=".$vvrg_id." and vrou_open_opt='Y'");
					$result =  $rs->Row('VROU_TO_VVRG_ID');
					$rs->Close();
					return $result;
    	        } else {
					$rs = $this->_db->Query("select vrou_to_vvrg_id from sur_vragenlijst_routing where vrou_vvrg_id=".$vvrg_id." and vrou_vopt_id=".$vopt_id);
					$result =  $rs->Row('VROU_TO_VVRG_ID');
					$rs->Close();
					return $result;
    	        }
    	    }
        }
	}

	function _getQSkipped($vvrg_id, $to_vvrg_id) {

		if ($to_vvrg_id == '-1') {
			//return ;
		}
		# if $to_vvrg_id == '-1' *end of the list) we should get the final question instead...

	    $rs_from = $this->_db->Query("select v.vvrg_id, v.vvrg_index, v.vvrg_vlst_id, s.vsec_id, s.vsec_index from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where s.vsec_id(+)=v.vvrg_vsec_id and v.vvrg_id IN (".$vvrg_id.",".$to_vvrg_id.")");
	    while ($rs_from->Row()) {
			$row = $rs_from->Row();
    	    if ($row['VVRG_ID']==$vvrg_id) {
        	   #from data
           	   $from_vsec_index =$row['VSEC_INDEX'];
    	       $from_vvrg_index =$row['VVRG_INDEX'];
	        } else {
        	   #to data
   	           $to_vsec_index =$row['VSEC_INDEX'];
   	           $to_vvrg_index =$row['VVRG_INDEX'];
   	     	}
	        $vlst_id=$row['VVRG_VLST_ID'];
			$rs_from->MoveNext();
	   	}
		$rs_from->Close();

		/* get al other ids's to empty:' */

		if ($to_vvrg_id != '-1') {
			//van tot
	    	//Define from and to where clause
	    	if ($from_vsec_index=="" && $to_vsec_index=="") {
	        	$sFrom = "(v.vvrg_index > ".$from_vvrg_index.")";
	        	$sTo = "(v.vvrg_index < ".$to_vvrg_index.")";
	        	$sOrder= "v.vvrg_index";
	        	//Get records between the two:
	    	    $rs_skipped = $this->_db->Query("select v.vvrg_id from sur_vragenlijst_vragen v where (".$sFrom." and ".$sTo.") and v.vvrg_vlst_id=".$vlst_id." order by ".$sOrder);

	    	} else {
	        	$sFrom = "((s.vsec_index > ".$from_vsec_index.") or (s.vsec_index = ".$from_vsec_index." and v.vvrg_index > ".$from_vvrg_index."))";
	        	$sTo = "((s.vsec_index < ".$to_vsec_index.") or (s.vsec_index = ".$to_vsec_index." and v.vvrg_index < ".$to_vvrg_index."))";
	        	$sOrder= "s.vsec_index, v.vvrg_index";
	        	//Get records between the two:
	        	$rs_skipped = $this->_db->Query("select v.vvrg_id from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where s.vsec_id=v.vvrg_vsec_id and (".$sFrom." and ".$sTo.") and v.vvrg_vlst_id=".$vlst_id." order by ".$sOrder);
 	    	}

		} else {
			//alles tot einde
			if ($from_vsec_index=="" && $to_vsec_index=="") {
				$sOrder= " v.vvrg_index";
				$sFrom = "(v.vvrg_index > ".$from_vvrg_index.")";

				$rs_skipped = $this->_db->Query("select v.vvrg_id from sur_vragenlijst_vragen v where ".$sFrom." and v.vvrg_vlst_id=".$vlst_id." order by ".$sOrder);
			} else {
				$sOrder= "s.vsec_index, v.vvrg_index";
				$sFrom = "((s.vsec_index > ".$from_vsec_index.") or (s.vsec_index = ".$from_vsec_index." and v.vvrg_index > ".$from_vvrg_index."))";
				$rs_skipped = $this->_db->Query("select v.vvrg_id from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where s.vsec_id=v.vvrg_vsec_id and (".$sFrom.") and v.vvrg_vlst_id=".$vlst_id." order by ".$sOrder);
			}
		}

	    $aReturn="";
	    //Return array with the ids
	    $rec=0;
	    while($rs_skipped->Row()) {
	        $aReturn[$rec]= $rs_skipped->Row('VVRG_ID');
	        $rec++;
			$rs_skipped->MoveNext();
	    }
		$rs_skipped->Close();
	    return $aReturn;
	}


		function _setAnswer($values) {
			// if no values then no insert / update
			if (count($values)==0) return "";
			$test = false;

	    // set vars (= niet nodig) (= maar waarom staat het hier dan?)
	    $vvrg_id   		=	$values["vvrg_id"];
	    $vtyp_id   		=	$values["vtyp_id"];
	    $vlst_id   		=	$values["vlst_id"];
	    $vrg_id    		=	$values["vrg_id"];
	    $multiple  		=	$values["multiple"];

	    $vusr_id   		=	$values["vusr_id"];
	    $openopt   		=	$values["openopt"];
	    $a_number  		=	$values["a_number"];
	    $a_open    		=	$values["a_open"];
	    $bCompleet 		=	$values["bCompleet"];
	    $iBack     		=	$values["iBack"];
			$vrg_default	=	$values["vrg_default"];

	    // Clean prior answers:
	    $this->_db->Execute("delete from sur_vragenlijst_antwoorden where vaw_vlst_id=".$vlst_id." and vaw_vvrg_id=".$vvrg_id." and vaw_vusr_id=".$vusr_id);
	    $this->_db->Execute("delete from sur_vlijst_antwoorden_open where vao_vusr_id=".$vusr_id." and vao_vvrg_id =".$vvrg_id);

	    // niet compleet:
			if ($bCompleet=="N") {
				$this->_db->Execute("insert into sur_vlijst_antwoorden_open (vao_vusr_id,vao_vvrg_id) values (".$vusr_id.",".$vvrg_id.")");
			}

			// Standaard vraag? leeg dan huidige waarde en bewaar dit antwoord:
			if ($vrg_default=="Y") {
				$this->_db->Execute("delete from sur_standaard_antwoorden where vaw_usr_id=".$this->_variables->public->usr_id." and vaw_vrg_id=".$vrg_id);
			}

	    // save given answers:
			if ($vtyp_id==1 ||
	    		$vtyp_id==2 ||
	    		$vtyp_id==5 ||
	    		$vtyp_id==6 ||
	    		$vtyp_id==11)
	    	{
	    	// multiple options
	    	if ($multiple) {

    	  	while (list($key,$value) = each($multiple) ) {

						// multiple_x is freetext that belongs with a selected option (for "o yes because [....] o no, because [....]" type questions)
						if ($values["multiple_x"]) {
							$multiple_x =	$values["multiple_x"][$value];
						} else {
							unset($multiple_x);
						}

    	    	// Loop thru selected options
						// save option to table
    	    	if ($value=="opn")
						{

    	      	// if one possible answer: set for referer
    	        if ($vtyp_id==5) {
    	        	$vopt_id="opn";
							}

    	        if ($openopt!="") {
        	    	$sSQL="insert into sur_vragenlijst_antwoorden (
              	      vaw_id,
              	      vaw_vlst_id,
              	      vaw_vrg_id,
              	      vaw_open,
              	      vaw_vusr_id,
              	      vaw_vvrg_id
              	  ) values (
              	      sur_vragenlijst_antwoorden_seq.nextval,
              	      ".$vlst_id.",
              	      ".$vrg_id.",
              	      '".substr($this->str2db($openopt),0,2000)."',
              	      ".$vusr_id.",
              	      ".$vvrg_id."
              	  )";

								// bewaar huidig antwoord:
								if ($vrg_default=="Y") {
									 $sDefSQL="insert into sur_standaard_antwoorden (
	                	                vaw_id,
	                  	              vaw_vrg_id,
	                    	            vaw_open,
	                      	          vaw_usr_id
	                        	    ) values (
	                          	      sur_standaard_antwoorden_seq.nextval,
	                            	    ".$vrg_id.",
	                              	  '".substr($this->str2db($openopt),0,2000)."',
	                                	".$this->_variables->public->usr_id."
	                            	)";
								}
							}
    	      } else {

							/*
								if one possible answer: set for referer

								type 11 has a selected option as well as an accompanying open text
							*/
							if ($vtyp_id == 1 ||
									$vtyp_id == 5 ||
									$vtyp_id == 11) {
								$vopt_id = $value;
							}


        	    $sSQL="insert into sur_vragenlijst_antwoorden (
        	    	         vaw_id,
        	    	         vaw_vlst_id,
        	    	         vaw_vrg_id,
        	    	         vaw_vopt_id,
        	    	         vaw_vusr_id,
        	    	         vaw_vvrg_id".
        	    	         ($vtyp_id == 11 && $multiple_x ? ",vaw_open" : "" ).
        	    	         "
        	    	     ) values (
        	    	         sur_vragenlijst_antwoorden_seq.nextval,
        	    	         ".$vlst_id.",
        	    	         ".$vrg_id.",
        	    	         ".$value.",
        	    	         ".$vusr_id.",
        	    	         ".$vvrg_id.
        	    	         ($vtyp_id == 11 && $multiple_x ? ",'".substr($this->str2db($multiple_x),0,2000) ."'" : "" ).
        	    	     ")";

							// bewaar huidig antwoord:
							if ($vrg_default=="Y") {

								$sDefSQL="insert into sur_standaard_antwoorden (
	        	                vaw_id,
	        	                vaw_vrg_id,
	        	                vaw_vopt_id,
	        	                vaw_usr_id
	        	    	        ) values (
	        	                sur_standaard_antwoorden_seq.nextval,
	        	                ".$vrg_id.",
	        	                ".$value.",
	        	                ".$this->_variables->public->usr_id."
	        	      	      )";

							}

        	  }

    	      $this->_db->Execute($sSQL);

						if ($vrg_default=="Y") {
							$this->_db->Execute($sDefSQL);
						}

    	  	}
	    	}
	    }


	    if ($vtyp_id==3) {
	        #Numerieke vraag
	        #save option
	        if ($a_number!="") {
    	        $sSQL="insert into sur_vragenlijst_antwoorden (
                    vaw_id,
                    vaw_vlst_id,
                    vaw_vrg_id,
                    vaw_nummeric,
                    vaw_vusr_id,
                    vaw_vvrg_id
                ) values (
                    sur_vragenlijst_antwoorden_seq.nextval,
                    ".$vlst_id.",
                    ".$vrg_id.",
                    ".$a_number.",
                    ".$vusr_id.",
                    ".$vvrg_id."
                )";
                if ($test) echo $sSQL."<br>";
                $this->_db->Execute($sSQL);

				if ($vrg_default=="Y") {

					$sSQL="insert into sur_standaard_antwoorden (
	                    vaw_id,
	                    vaw_vrg_id,
	                    vaw_nummeric,
	                    vaw_usr_id
	                ) values (
	                    sur_standaard_antwoorden_seq.nextval,
	                    ".$vrg_id.",
	                    ".$a_number.",
	                    ".$this->_variables->public->usr_id."
	                )";
					$this->_db->Execute($sSQL);

				}
	        }
	    }
	    if ($vtyp_id==4 || $vtyp_id==9) {

	        #Open vraag
	        if ($a_open!="") {
    	        #save option
    	        $sSQL="insert into sur_vragenlijst_antwoorden (
                    vaw_id,
                    vaw_vlst_id,
                    vaw_vrg_id,
                    vaw_open,
                    vaw_vusr_id,
                    vaw_vvrg_id
                ) values (
                    sur_vragenlijst_antwoorden_seq.nextval,
                    ".$vlst_id.",
                    ".$vrg_id.",
                    '".substr($this->str2db($a_open),0,2000)."',
                    ".$vusr_id.",
                    ".$vvrg_id."
                )";
                if ($test) echo $sSQL."<br>";
                $this->_db->Execute($sSQL);

				if ($vrg_default=="Y") {
					#save option
	    	        $sSQL="insert into sur_standaard_antwoorden (
	                    vaw_id,
	                    vaw_vrg_id,
	                    vaw_open,
	                    vaw_usr_id
	                ) values (
	                    sur_standaard_antwoorden_seq.nextval,
	                    ".$vrg_id.",
	                    '".substr($this->str2db($a_open),0,2000)."',
	                    ".$this->_variables->public->usr_id."
	                )";
					$this->_db->Execute($sSQL);
				}

            }
	    }

	    if ($vtyp_id==10) {

        $a_length = $values["a_length"];
        $a_weight = $values["a_weight"];

	        #Body Mass Index standard
	        if ($a_length!="" && $a_weight!="") {

              $a_length = str_replace('.','',str_replace(',','',$a_length));
              $a_weight = str_replace(',','.',$a_weight);

              $BMI = round(($a_weight / ($a_length * $a_length)) * 10000,2);

    	        #save option
    	        $sSQL = "insert into sur_vragenlijst_antwoorden (vaw_id,vaw_vlst_id,vaw_vrg_id,vaw_open,vaw_vusr_id,vaw_vvrg_id,VAW_NUMMERIC) ".
                        "values (sur_vragenlijst_antwoorden_seq.nextval,".$vlst_id.",".$vrg_id.",'".$a_length.';'.$a_weight."',".$vusr_id.",".$vvrg_id.",".$BMI.")";
                $this->_db->Execute($sSQL);

				if ($vrg_default=="Y") {
					 #save option
	    	        $sSQL = "insert into sur_standaard_antwoorden (vaw_id,vaw_vrg_id,vaw_open,vaw_usr_id,VAW_NUMMERIC) ".
	                        "values (sur_standaard_antwoorden_seq.nextval,".$vrg_id.",'".$a_length.';'.$a_weight."',".$this->_variables->public->usr_id.",".$BMI.")";
	                $this->_db->Execute($sSQL);
				}
            }
	    }

	    if (($vtyp_id==7 || $vtyp_id==8) && $values[matrix]) {

            #process matrix
            while (list($key,$value1) = each($values[matrix])) {
                #save option combi to table
                if ($key=="opn") {
                    $sSQL="insert into sur_vragenlijst_antwoorden (
                        vaw_id,
                        vaw_vlst_id,
                        vaw_vrg_id,
                        vaw_open,
                        vaw_sub_vopt_id,
                        vaw_vusr_id,
                        vaw_vvrg_id
                    ) values (
                        sur_vragenlijst_antwoorden_seq.nextval,
                        ".$vlst_id.",
                        ".$vrg_id.",
                        '".substr($this->str2db($openopt),0,2000)."',
                        ".$value1.",
                        ".$vusr_id.",
                        ".$vvrg_id."
                    )";

					if ($vrg_default=="Y") {
						$sDefSQL="insert into sur_standaard_antwoorden (
	                        vaw_id,
	                        vaw_vrg_id,
	                        vaw_open,
	                        vaw_sub_vopt_id,
	                        vaw_usr_id
	                    ) values (
	                        sur_standaard_antwoorden_seq.nextval,
	                        ".$vrg_id.",
	                        '".substr($this->str2db($openopt),0,2000)."',
	                        ".$value1.",
	                        ".$this->_variables->public->usr_id."
	                    )";

					}

                } else {
        	        $sSQL="insert into sur_vragenlijst_antwoorden (
    	                vaw_id,
    	                vaw_vlst_id,
    	                vaw_vrg_id,
    	                vaw_vopt_id,
    	                vaw_sub_vopt_id,
    	                vaw_vusr_id,
    	                vaw_vvrg_id
    	            ) values (
    	                sur_vragenlijst_antwoorden_seq.nextval,
    	                ".$vlst_id.",
    	                ".$vrg_id.",
    	                ".$key.",
    	                ".$value1.",
    	                ".$vusr_id.",
    	                ".$vvrg_id."
    	            )";

					if ($vrg_default=="Y") {

						$sDefSQL="insert into sur_standaard_antwoorden (
	    	                vaw_id,
	    	                vaw_vrg_id,
	    	                vaw_vopt_id,
	    	                vaw_sub_vopt_id,
	    	                vaw_usr_id
	    	            ) values (
	    	                sur_standaard_antwoorden_seq.nextval,
	    	                ".$vrg_id.",
	    	                ".$key.",
	    	                ".$value1.",
	    	                ".$this->_variables->public->usr_id."
	    	            )";

					}
                }
	            if ($test) echo $sSQL."<br>";
	            $this->_db->Execute($sSQL);
				if ($vrg_default=="Y") {
					$this->_db->Execute($sDefSQL);
				}
            }
        }

		if ($test)echo "inserted!<br><br>";

		/* Leeg evt. huidige referer */
		$this->_db->Execute("delete from sur_vragenlijst_routing_done where vrd_vusr_id=".$vusr_id." and vrd_vvrg_id=".$vvrg_id);
		if ($test) echo "delete from sur_vragenlijst_routing_done where vrd_vusr_id=$vusr_id and vrd_vvrg_id=$vvrg_id<br><br>";

		/* check voor actieve verwijzing */
		$to_vvrg_id = $this->_checkReferer($vvrg_id,$iBack,$vopt_id);


		/* check verwijzing nodig */
		$do_to_vvrg_id = $this->_checkReferer($vvrg_id,0,$vopt_id);

		/*
		if ($to_vvrg_id==-1 || $do_to_vvrg_id==-1) {
			$this->_db->Execute("insert into sur_vragenlijst_routing_done (vrd_vvrg_id, vrd_to_vvrg_id, vrd_vusr_id) values (".$vvrg_id.",-1,".$vusr_id.")");
			if ($test) echo "insert into sur_vragenlijst_routing_done (vrd_vvrg_id, vrd_to_vvrg_id, vrd_vusr_id) values (".$vvrg_id.",-1,".$vusr_id.")<br><br>";
		}
		*/
				// indien niet back:
        if ($do_to_vvrg_id!="") {

            	#delete evt. tussenliggende vraag-antwoorden en routing_done:
            	$aSkipped = $this->_getQSkipped($vvrg_id, $do_to_vvrg_id);
            	if ($aSkipped!="") {
	                while (list($key,$value)= each($aSkipped)) {
	                    $sQuestions.= $value.",";
	                }
                }
                $sQuestions = substr($sQuestions,0,strlen($sQuestions)-1);
                if ($sQuestions!="") {

					$this->_db->Execute("delete from sur_vlijst_antwoorden_open where vao_vusr_id=".$vusr_id." and vao_vvrg_id IN (".$sQuestions.")");
          $this->_db->Execute("delete from sur_vragenlijst_antwoorden where vaw_vusr_id= ".$vusr_id." and vaw_vvrg_id IN (".$sQuestions.")");
          $this->_db->Execute("delete from sur_vragenlijst_routing_done where vrd_vusr_id=".$vusr_id." and vrd_vvrg_id IN (".$sQuestions.")");

					#schrijf huidige routing weg:
					if  ($do_to_vvrg_id==-1) {
						if ($test) echo "insert into sur_vragenlijst_routing_done (vrd_vvrg_id, vrd_to_vvrg_id, vrd_vusr_id) values (".$vvrg_id.",-1,".$vusr_id.")<br><br>";
						$this->_db->Execute("insert into sur_vragenlijst_routing_done (vrd_vvrg_id, vrd_to_vvrg_id, vrd_vusr_id) values (".$vvrg_id.",-1,".$vusr_id.")");

					} else {
						if ($test) echo "insert into sur_vragenlijst_routing_done (vrd_vvrg_id, vrd_to_vvrg_id, vrd_vusr_id) values (".$vvrg_id.",".$do_to_vvrg_id.",".$vusr_id.")<br><br>";
						$this->_db->Execute("insert into sur_vragenlijst_routing_done (vrd_vvrg_id, vrd_to_vvrg_id, vrd_vusr_id) values (".$vvrg_id.",".$do_to_vvrg_id.",".$vusr_id.")");
					}
				}
		}

	    #return the referer if exists
	    return $to_vvrg_id;
	}

	function getQuestionairs() {

		$this->_smrt->clear_all_assign();


		$arr_grps = $this->_getGroups();
		if (count($arr_grps)>0) {

			while(list($grp_id,$grp_name)= each($arr_grps)){
				$subsel_grps .= "'".$grp_id."',";
			}
			unset($arr_grps);
			$subsel_grps = substr($subsel_grps,0,-1);

			$sSQL = ' select distinct v.VLST_ID, v.VLST_TITEL, v.VLST_INLEIDING, v.VLST_DOORLOOPTIJD, u.vusr_id, TO_CHAR (v.VLST_SLUITDATUM,\'dd month yyyy\',\'NLS_DATE_LANGUAGE=Dutch\') as sluitingsdatum '.
				' from sur_vragenlijsten v, sur_vragenlijst_users u, sur_vragenlijst_groepen g '.
				' where v.vlst_id=u.vusr_vlst_id '.
				' and u.vusr_usr_id ='.$this->_variables->public->usr_id.
				' and u.vusr_submitted=\'N\' '.
				' and v.vlst_verwijderd=\'N\' '.
				' and not v.vlst_parent is null '.
				' and v.vlst_org_id = '.$this->curr_org.
				' and (to_char(SYSDATE,\'YYYYMMDD\') BETWEEN to_char(v.VLST_PUBDATUM,\'YYYYMMDD\') and to_char(v.VLST_SLUITDATUM,\'YYYYMMDD\'))'.
				' and g.vgrp_vlst_id = u.vusr_vlst_id'.
				' and g.vgrp_grp_id in ('.$subsel_grps.')'.
				' order by sluitingsdatum desc, v.vlst_titel';
			// echo $sSQL;
			$rs_lists = $this->_db->Query($sSQL);
			$i=0;
			while($rs_lists->Row()){
				$row = $rs_lists->Row();

				//check if allready started:
				if($this->_hasAnswers($row['VUSR_ID'])!=0){
					$s_initlabel ='Verder gaan';
					$s_init	= '/?p=csur0100&option=questions&vlst_id='.$row['VLST_ID'].'&bResume=true';

				} else {
					$s_initlabel ='Start';
					$s_init	= '/?p=csur0100&option=preface&vlst_id='.$row['VLST_ID'];
				}

				$lists[$i++] = array(
					'vlst_id'		=> $row['VLST_ID'],
					'titel'	 		=> $row['VLST_TITEL'],
					'sluiting' 		=> $row['SLUITINGSDATUM'],
					'inleiding' 	=> $row['VLST_INLEIDING'],
					'doorlooptijd' 	=> $row['VLST_DOORLOOPTIJD'],
					'vragen'		=> $this->_getQCountForList($row['VLST_ID']),
					'init'			=> $s_init,
					'initlabel'		=> $s_initlabel
				);
				$rs_lists->MoveNext();
			}
			$rs_lists->Close();

		}

		//zet array
		$q_lists = array (
			'lists' => $lists
		);


		$this->_smrt->assign_by_ref('q_lists', $q_lists);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->q_overview);
	}

	function _getQIndex() {

		$sSQL="select v.vvrg_id
			, 	vr.vrg_vraag
			,	ao.vao_vvrg_id
			,	r.vrd_to_vvrg_id
			,	s.vsec_label
			,	s.vsec_id
			from sur_vragenlijst_vragen v
			,	sur_vlijst_antwoorden_open ao
			,	sur_vragenlijst_routing_done r
			,	sur_vragenlijst_secties s
			,	sur_vragen vr
			where 	vr.vrg_id=v.vvrg_vrg_id
			and		s.vsec_id(+)=v.vvrg_vsec_id
			and		ao.vao_vvrg_id(+) = v.vvrg_id
			and    	ao.vao_vusr_id(+) = ".$this->vusr_id."
			and		r.vrd_vvrg_id(+) = v.vvrg_id
			and    	r.VRD_VUSR_ID(+) = ".$this->vusr_id."
			and		v.vvrg_vlst_id=".$this->vlst_id."
			order by s.vsec_index, v.vvrg_index";

   		$rs_questionair = $this->_db->Query($sSQL);

		$iQue = 0;
	    $iADone = 0;
	    $iSkipped = 0;
	    $show_vsec_id = 0;
		$i_vragen =0;
		while($rs_questionair->Row()) {
			$que = $rs_questionair->Row();

			#get answers
	        $iAnswers = 0;

	        if ($iSkipTill == "" || $iSkipTill == $que["VVRG_ID"]) {

	            if ($iSkipTill == $que["VVRG_ID"]) $iSkipTill = "";

	            $iAnswers = 0;
	            if (!$que["VAO_VVRG_ID"]) {

					$sSQL = "select count(vaw_vvrg_id) as QCOUNT from ".
							" sur_vragenlijst_antwoorden ".
							" where vaw_vvrg_id=".$que["VVRG_ID"]." and vaw_vusr_id = ".$this->vusr_id;

					$rs = $this->_db->Query($sSQL);
					$iAnswers = $rs->Row('QCOUNT');
					$rs->Close();
	            }

	            // sectie change
	            if ($show_vsec_id != $que["VSEC_ID"]) {
	                $show_vsec_id =$que["VSEC_ID"];
					$arr_index[$show_vsec_id]['label'] = $que["VSEC_LABEL"];
	            }

	            $iQue++;
	            $bCurrent = false;

	            if ($iAnswers != 0) {
	                $q_status = "done";
	                $iADone++;
	            } else {
	                 $q_status = "open";
	                 if (!$que["VAO_VVRG_ID"]) {

	                     if ($last=="") {
	                        $q_status = "current";
	                        $last = $que["VVRG_ID"];
	                        $lastindex = $iQue;
	                        $bCurrent = true;

	                     }
	                 } else {

	                    if ($first=="") {
	                        $first = $que["VVRG_ID"];
	                        $firstindex = $iQue;
	                    }

	                 }

	            }
				$arr_index[$show_vsec_id]['q'][$iQue] = array (
					'vlst_id'	=> $this->vlst_id,
					'status' 	=> $q_status,
					'nr'		=> $iQue,
					'vvrg_id'	=> $que['VVRG_ID'],
					'vraag'		=> $que['VRG_VRAAG'],
					'init'		=> '/?p=csur0100&option=questions&vlst_id='.$this->vlst_id.'&go_vvrg_id='.$que['VVRG_ID'].'&set_index='.$iQue
				);
	            $i_vragen++;

	          	if ($que["VRD_TO_VVRG_ID"]!="" && $iAnswers != 0) {
					$iSkipTill = $que["VRD_TO_VVRG_ID"];
	          	}
	        } else {
				$iSkipped++;
	        }
			$rs_questionair->MoveNext();
	    }

		//bereken progress
	    $qCount = $rs_questionair->RowCount;
	    if ($qCount == 0) $qCount = 1;

		$rs_questionair->Close();

	    $this->q_progress = ceil((($iADone + $iSkipped) / $qCount)* 100);

		$this->q_questions = $i_vragen;
		$this->q_skipped = $iSkipped;
		#zet progress
	    $this->iHasDone = ($iADone + $iSkipped);

		#quick n dirty
		$this->iTotDone = $iADone;

		if ($first) {
	        $aResume[0] = $first;
	        $aResume[1] = $firstindex;
	    }elseif ($last) {
	        $aResume[0] = $last;
	        $aResume[1] = $lastindex;
	    }
		$this->aResume = $aResume;
		return $arr_index;
	}

	function _getVlist($vlst_id) {
		return $this->_db->Query("select v.*, TO_CHAR(v.VLST_SLUITDATUM,'dd month yyyy','NLS_DATE_LANGUAGE=Dutch') as sluitingsdatum from sur_vragenlijsten v where vlst_id=".$vlst_id);
	}

	function _getQCount($vlst_id) {
		$rs = $this->_db->Query("select count(vvrg_id) as QCOUNT from sur_vragenlijst_vragen where vvrg_vlst_id=".$vlst_id);
		$result = $rs->Row('QCOUNT');
		$rs->Close();
		return $result;
	}

	function getPreface($vlst_id) {

		$this->vlst_id = $vlst_id;
		$this->_setVusr();

		$this->_smrt->clear_all_assign();

		$s_script = '<script>function closeIndex(){document.getElementById(\'overzichtcontainer\').style.display = \'none\';}'.
			'function showIndex() { document.getElementById(\'overzichtcontainer\').style.display = \'\';}</script>';
		$indexblockid = 'overzichtcontainer';

		$rs_vlst = $this->_getVlist($this->vlst_id);
		$lst = $rs_vlst->Row();

		$preface = array(
			'vlst_id'	=> $this->vlst_id,
			'script' 	=> $s_script,
			'indexblockid' => $indexblockid,
			'index'		=> $this->_getQIndex(),
			'titel'		=> $lst['VLST_TITEL'],
			'sluiting'	=> $lst['SLUITINGSDATUM'],
			'doorloop'	=> $lst['VLST_DOORLOOPTIJD'],
			'inleiding'	=> $lst['VLST_INLEIDING'],
			'vragen'	=> $this->_getQCount($this->vlst_id),
			'init'		=> '/?p=csur0100&option=questions&vlst_id='.$this->vlst_id
		);

		unset($lst);
		$rs_vlst->close();

		$submit_test = $this->_db->Query('select vusr_submitted
				 from sur_vragenlijst_users
				where vusr_vlst_id = '.$this->vlst_id.'
					and vusr_usr_id ='.$this->_variables->public->usr_id);

		$preface['previously_submitted']=$submit_test->Row('VUSR_SUBMITTED');

		$this->_smrt->assign_by_ref('preface', $preface);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->preface);
	}

	function _closeList($opmerking) {
       #update vragenlijst_users
       $this->_db->Execute("update sur_vragenlijst_users set vusr_opmerking='".$opmerking."', vusr_submitted='Y' where vusr_id=".$this->vusr_id);
       #clear vragenlijst walkthru
       $this->_db->Execute("delete from sur_vlijst_antwoorden_open where vao_vusr_id=".$this->vusr_id);
       $this->_db->Execute("delete from sur_vragenlijst_routing_done where vrd_vusr_id=".$this->vusr_id);
    }

	function getQuestions($vlst_id) {
		global $HTTP_POST_VARS;

		$this->_smrt->clear_all_assign();

		//get post values
		$values = $HTTP_POST_VARS;

		//set main vars:
		$this->vlst_id = $vlst_id;
		if ($values['vusr_id']) {
			$this->vusr_id = $values['vusr_id'];
		} else {
			$this->_setVusr();
		}

		if(!$values['iVragen']) {
			$values['iVragen'] = $this->_getQCount($this->vlst_id);
			// bepaal dat de pagina nu start!		ja! laten we dat doen!
			$bStart = true;
		}

		if (!$values['iDoorlooptijd']) {
			$rs = $this->_getVlist($this->vlst_id);
			$rs_vlst = $rs->Row();
			$rs->Close();
			$values['iDoorlooptijd'] = $rs_vlst['VLST_DOORLOOPTIJD'];
			$values['bOpmerking']	= $rs_vlst['VLST_OPMERKINGEN'];
			$values['sTitel'] = $rs_vlst['VLST_TITEL'];
		}

		// update / insert answer
		if (count($HTTP_POST_VARS)>0 && $values['vvrg_id']!='') {
			$to_vvrg_id = $this->_setAnswer($HTTP_POST_VARS);
	  }

		//zet index and global vars!!:   jaa!!! laten we dat gaan doen! met z'n allen!
		$arr_index = $this->_getQIndex();

		//check wel of ook echt einde
		if ($this->iTotDone < $this->q_questions && $values['bFinish']=='Y') {

			//$values['bFinish']='N';
			$values['bShowFinish']='Y';
			$bNotEnd=true;

		} else {

			// Finish questionlist
			if ($values['bFinish']=="Y" && ($values['bOpmerking']=='N' || ($values['bOpmerking']=='Y' && $values['eind_opmerking']!=""))) {
				$this->_closeList($values['eind_opmerking']);
				$bShowEnd=true;
				return $this->showEnd();
			}

		}


		// set navigation
		if (!$values['iTotIndex']) {
	  	$values['iTotIndex']=0;
	  }

	  $values['iTotIndex']++;

    if ($values['iBack']) {
       $values['iTotIndex']=$values['iTotIndex']-2;
    }

		// When resume get first question to display
	  // this is the last question or when walked thru all the first open:
	  if ($_GET['bResume']==true && $bStart) {
			if ($this->aResume[0]) {
				$to_vvrg_id = $this->aResume[0];
	        	$iSetIndex 	= $this->aResume[1];
	        	$values['iTotIndex']= $iSetIndex;
			} else {
				$iSetIndex = 1;
	        	$values['iTotIndex'] = 1;
			}
	  } elseif ($bStart && $_GET['go_vvrg_id']!="") {
	        $to_vvrg_id = $_GET['go_vvrg_id'];
	        $iSetIndex =  $_GET['set_index'];
	        $values['iTotIndex'] = $iSetIndex;
	  }

		 // hack
		if ($to_vvrg_id=='-1' || $values['bShowFinish']=='Y') {
			$values['bFinish']="Y";
		}
		//check wel of ook echt einde
		//if (($values['iTotIndex']-1) < $this->q_questions) $values['bFinish']='N';

		if ($values['bFinish']!="Y") {

			if ($values['iVragen'] > 0) {
				$aQuestion = $this->getNextQuestion($HTTP_POST_VARS,$to_vvrg_id,$iSetIndex);
				$aTheQuestion = $aQuestion[0];
			}

    } else {

			if (($values['bShowFinish']=='Y' || $to_vvrg_id ==-1) && (($values['iTotIndex']-1) > $this->iTotDone)) {
				$bNotEnd=true;
			}

   		if ($values['bOpmerking']=="Y" && !$bNotEnd) {

				$aTheQuestion['vars'] = "<script>bProceed=true;</script>";
				$aTheQuestion['sec_label'] = "";
				$aTheQuestion['vraag'] = "Opmerkingen:";
				$aTheQuestion['toelichting'] = "Plaats hier uw eventuele opmerkingen over de vragenlijst:";
				$aTheQuestion['control'] = "<textarea name=eind_opmerking class=Q_txainput></textarea>";

   		} else {

				$aTheQuestion['vars'] = "<script>
				bProceed=true;
				</script>";
				$aTheQuestion['sec_label'] = "";
				$aTheQuestion['vraag'] = "Einde van de vragenlijst!";
//				$aTheQuestion['toelichting'] = ((($values['iTotIndex']-1) > $this->iTotDone) ? "<br>U bent aan het einde van de vragenlijst, echter niet alle vragen zijn beantwoord.<br>" : "<br>Bedankt voor uw medewerking.<br>" );
//				$aTheQuestion['toelichting'] = (($this->q_questions > $this->iTotDone) ? "<br>U bent aan het einde van de vragenlijst, echter niet alle vragen zijn beantwoord.<br>" : "<br>Bedankt voor uw medewerking.<br>" );
				$aTheQuestion['toelichting'] = (($this->q_questions > $this->iTotDone) ? "<br>U bent aan het einde van de vragenlijst, echter niet alle vragen zijn beantwoord.<br>" : "<br>Klik op 'Indienen' om de vragenlijst af te ronden.<br>" );
				//$aTheQuestion['control'] = "<textarea name=eind_opmerking class=Q_txainput></textarea>";

   		}
		}

		//check of gehele vraag naar einde lijst moet:
		$is_last = false;
		if ($aQuestion[2]!='') {
			$rs = $this->_db->Query("select VROU_TO_VVRG_ID from SUR_VRAGENLIJST_ROUTING where vrou_vvrg_id= ".$aQuestion[2]." and VROU_OPEN_OPT = 'Y'");
			if ($rs->Row('VROU_TO_VVRG_ID') == -1) {
			    $is_last = true;
			}
			$rs->Close();
		}

		if ($is_last) {
		    $s_js_navigate = "
				openError('alert','U heeft deze vraag niet volledig beantwoord!');
			";
		} else {
			$s_js_navigate ="
			var sMsg='U heeft deze vraag niet volledig beantwoord.<p>Wilt u alsnog doorgaan?';
		    openError('confirm',sMsg);
			";
		}


		$s_script = "<script>
		    //This var determines if question is answered
		    var bProceed = false;
		    var bScreenOpen = false;

		    function gonavigate(bShowEnd) {
		        //If not answered ask if proceed
		        if (!bProceed) {
		            ".$s_js_navigate."
		        }
				//zet op show finish (ook als niets ingevuld)
				if (bShowEnd==true) {
					document.csur_questionair.bShowFinish.value='Y';
				}
		        //when proceed navigate back or forward
		        if (bProceed==true) {
					document.csur_questionair.submit();
		        }
		    }

		    function goFinish() {
		        if (bProceed==true) {
		            document.csur_questionair.bFinish.value='Y';
		            document.csur_questionair.submit();
		        } else {
		            var sMsg='U heeft deze vraag niet volledig beantwoord.<p>De toets kan niet afgesloten worden!';
		            openError('alert',sMsg);
		        }
		    }

		    function openError(show,msg) {
		        //state
		        if (bScreenOpen==false) {
		            bScreenOpen=true;
		            //Open layer and show type of error:
		            document.getElementById('errorcontainer').style.display = '';
		            document.getElementById('msgcontainer').style.display = '';
					document.getElementById('errorcontainer').style.visibility = 'visible';
					document.getElementById('msgcontainer').style.visibility = 'visible';
		            document.getElementById('msgcontainer').innerHTML=msg;
		            if (show=='confirm') {
						document.getElementById('alertcontainer').style.display='none';
						document.getElementById('alertcontainer').style.visibility = 'hidden';
		                document.getElementById('confirmcontainer').style.display='';
						document.getElementById('confirmcontainer').style.visibility = 'visible';
		            } else {
		                document.getElementById('confirmcontainer').style.display='none';
						document.getElementById('confirmcontainer').style.visibility = 'hidden';
						document.getElementById('alertcontainer').style.display='';
						document.getElementById('alertcontainer').style.visibility = 'visible';
		            }
		            //document.getElementById('errorcontainer').scrollIntoView();
		        }
		    }
		    function closeError() {
		        //state
		        bScreenOpen=false;
		        //Close error layer
		        document.getElementById('errorcontainer').style.display = 'none';
				document.getElementById('errorcontainer').style.visibility = 'hidden';
		        document.getElementById('msgcontainer').style.display = 'none';
				document.getElementById('msgcontainer').style.visibility = 'hidden';
		        document.getElementById('confirmcontainer').style.display = 'none';
				document.getElementById('confirmcontainer').style.visibility = 'hidden';
		        document.getElementById('alertcontainer').style.display = 'none';
				document.getElementById('alertcontainer').style.visibility = 'hidden';
		    }

			function closeIndex(){
				document.getElementById('overzichtcontainer').style.display = 'none';
				document.getElementById('overzichtcontainer').style.visibility = 'hidden';
			}
			function showIndex() {
				document.getElementById('overzichtcontainer').style.display = '';
				document.getElementById('overzichtcontainer').style.visibility = 'visible'
			}
		</script>";

		$indexblockid = 'overzichtcontainer';
		$errorblockid = 'errorcontainer';
		$errormsg = '<div id=msgcontainer style="display:none;"></div>';
		$erroryesnoid = 'confirmcontainer';
		$errorokid	= 'alertcontainer';


		$s_form_open = '<form method=post name=csur_questionair> '.
			' <input type=hidden name="vlst_id" value="'.$this->vlst_id.'">'.
			' <input type=hidden name="sTitel" value="'.htmlentities($values['sTitel']).'">'.
			' <input type=hidden name="vusr_id" value="'.$this->vusr_id.'">'.
			' <input type=hidden name="iTotIndex" value="'.$values['iTotIndex'].'">'.
			' <input type=hidden name="iDoorlooptijd" value="'.$values['iDoorlooptijd'].'">'.
			' <input type=hidden name="bOpmerking" value="'.$values['bOpmerking'].'">'.
			' <input type=hidden name="iVragen" value="'.$values['iVragen'].'">'.
			' <input type=hidden name="iBack" value="">'.
			' <input type=hidden name="bShowFinish" value="">'.
			' <input type=hidden name="bFinish" value="">'.
			' <input type=hidden name="bCompleet" value="">';

		$s_form_close = '</form>';

		//buttons
		if ($values['bFinish']!="Y") {

			//evt. overgeslagen
			$rs = $this->_db->Query("select count(vao_vvrg_id) as QCOUNT from sur_vlijst_antwoorden_open where vao_vusr_id=".$this->vusr_id." and vao_vvrg_id!=".$aQuestion[2]);
			$i_skipped = $rs->Row('QCOUNT');
			$rs->Close();

			if ($aQuestion[1] > 1) {
			    $btn_vorige = "javascript:document.csur_questionair.iBack.value=1;gonavigate();";
		    }

	if ($aQuestion[0]["type_id"]==11) {
			if ($aQuestion[1] == $this->q_questions && ( $this->q_progress==100 || (($this->q_questions -1) == $this->iTotDone && ($this->aResume[1]==$aQuestion[1])))) {
			    //alleen indienen!
				//test uitzondering:
				$btn_volgende = "javascript:if(checkType11()){document.csur_questionair.iBack.value=0;gonavigate(true);}";
			} else {

				$btn_volgende = "javascript:if(checkType11()){document.csur_questionair.iBack.value=0;gonavigate();}";
				if (($aQuestion[1] == $this->q_questions) && ($this->q_questions >  $this->iTotDone)) {
					$btn_volgende = "javascript:if(checkType11()){document.csur_questionair.iBack.value=0;gonavigate(true);}";
				}
			}
	} else {
			if ($aQuestion[1] == $this->q_questions && ( $this->q_progress==100 || (($this->q_questions -1) == $this->iTotDone && ($this->aResume[1]==$aQuestion[1])))) {
			    //alleen indienen!
				//test uitzondering:
				$btn_volgende = "javascript:document.csur_questionair.iBack.value=0;gonavigate(true);";
			} else {

				$btn_volgende = "javascript:document.csur_questionair.iBack.value=0;gonavigate();";
				if (($aQuestion[1] == $this->q_questions) && ($this->q_questions >  $this->iTotDone)) {
					$btn_volgende = "javascript:document.csur_questionair.iBack.value=0;gonavigate(true);";
				}
			}
	}


			if ($this->q_progress==100 && $values['bFinish']) {
				$btn_indienen = "javascript:goFinish();";
			}
/*
				elseif ($this->aResume[1]==$aQuestion[1] && ($this->q_questions - $this->iTotDone)==1) {
 				$btn_indienen = "javascript:goFinish();";
 			}
*/

		} else {
            //indienen met opmerking: of zonder
			if ($values['bOpmerking']=="Y" && !$bNotEnd) {
				$btn_indienen = "javascript:if (document.csur_questionair.eind_opmerking.value=='') {document.csur_questionair.eind_opmerking.value=' ';};goFinish();";
			} else {
				//hack;
				//if (($values['iTotIndex']-1) > $this->iTotDone) {
				if ($this->q_questions > $this->iTotDone)  {
					$btn_verder = "window.location.href='/?p=csur0100&option=questions&vlst_id=".$this->vlst_id."&bResume=true'";
				} else {
					$btn_indienen = "javascript:goFinish();";
				}
		}
		}

		if ($this->q_progress!=100) {
			$btn_onderbreken = "javascript:location.href='/?p=csur0100'";
		} else {
			$btn_onderbreken = "";
		}

		$err['yes'] = "javascript:bProceed=true;csur_questionair.bCompleet.value='N';document.getElementById('errorcontainer').style.visibility='hidden';gonavigate();";
		$err['no']  = "closeError();";
		$err['ok']  = "closeError();";

		$question = array (
			'open'		=> $s_form_open,
			'close'		=> $s_form_close,
			'vlst_id'	=> $this->vlst_id,
			'vvrg_id'	=> '',
			'script'	=> $s_script,
			'index'		=> $arr_index,
			'progress'	=> $this->q_progress,
			'todo'		=> (100 - $this->q_progress),
			'question'	=> $aTheQuestion,
			'titel'		=> $values['sTitel'],
			'doorloop'	=> $values['iDoorlooptijd'],
			'vragen'	=> $values['iVragen'],
			'totindex'	=> $values['iTotIndex'],
			'go_vorige'	=> $btn_vorige,
			'go_volgende'=> $btn_volgende,
			'go_onderbreken'=> $btn_onderbreken,
			'go_indienen'=> $btn_indienen,
			'go_verder'	=>	$btn_verder,
			'err'		=> $err,
			'indexblockid'=> $indexblockid,
			'errorblockid'=> $errorblockid,
			'errormsg'	=> $errormsg,
			'erroryesnoid'=> $erroryesnoid,
			'errorokid'=> $errorokid
		);

		$this->_smrt->assign_by_ref('question', $question);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->questions);
	}

	function _getOpenLabel($vrg_id) {
	    #get label for open option
	    $rs = $this->_db->Query("select vopn_label from sur_vraag_open where vopn_vrg_id=".$vrg_id);
		$sLabel = $rs->Row('VOPN_LABEL');
		$rs->Close();
	    return ($sLabel) ? $sLabel : "Anders, nl:";
	}


	function getNextQuestion($values, $to_vvrg_id="",$iSetIndex="") {


	    #set vars:
	    $vsec_id=$values["VSEC_ID"];
	    $vsec_que=$values[vsec_que];
	    $vsec_label=$values["VSEC_LABEL"];
	    //del $vsec_count=$values[vsec_count];
	    $vsec_index=$values[vsec_index];
	    $iIndex=$values[iIndex];
	    $iListIndex=$values[iListIndex];
	    $iTotIndex=$values[iTotIndex];
	    $iBack= $values[iBack];
	    $vvrg_id= $values[vvrg_id];
	    //$vusr_id = $values[vusr_id];


	    #set index:
	    if (!$iIndex) {
	        $iIndex=0;
	        $iTotIndex=0;
	        $iListIndex=0;
	    }
	    if ($iBack) {
	        #Back option:
	        #check if question has been refered to:
	        if ($to_vvrg_id=="") {
                #not refered so index back
                $iIndex=$iIndex-1;
                $iListIndex=$iListIndex-1;
            }

            #set display index -1
            $iTotIndex=$iTotIndex-1;
        } else {
            $iIndex++;
            $iListIndex++;
            $iTotIndex=$iTotIndex+1;
        }


	    #Redirect:
	    if ($to_vvrg_id!="") {
	        #bepaal volgende

	        $rs_next = $this->_db->Query("select vvrg_vsec_id, vvrg_index from sur_vragenlijst_vragen where vvrg_id=".$to_vvrg_id);
	        $ref_vsec_id = $rs_next->Row('VVRG_VSEC_ID');

	        #index in volgende sectie
	        $iIndex= $rs_next->Row('VVRG_INDEX');

	        #set listindex to index and at check section the prior questions will be added:
	        $iListIndex = $iIndex;

	        #set index when specified
	        if ($iSetIndex!="") {
	            $iTotIndex=$iSetIndex;
	        }
			$rs_next->Close();
	    }

	    #SECTION NAV -----------------
	    #check sections:
	    if ($vsec_id=="" || $ref_vsec_id!="") {
	        #Set refered section or first
	        $sWhere= ($ref_vsec_id!="") ? " and s.vsec_id=".$ref_vsec_id : " and s.vsec_index=1";
	        $rs =  $this->_db->Query("select v.vvrg_vsec_id, count(v.vvrg_id) as questions, s.vsec_index, s.vsec_label from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where s.vsec_id(+) = v.vvrg_vsec_id and v.vvrg_vlst_id=".$this->vlst_id." ".$sWhere." group by v.vvrg_vsec_id, s.vsec_index, s.vsec_label");
			$rs_section = $rs->Row();
			$rs->Close();

	        $vsec_id=$rs_section[VVRG_VSEC_ID];
	        $vsec_que = $rs_section[QUESTIONS];
	        $vsec_label = htmlentities(stripslashes($rs_section["VSEC_LABEL"]));
	        $vsec_index=$rs_section[VSEC_INDEX];

             if ($vsec_index) {
	        	if ($ref_vsec_id && $vsec_index!=1) {
		            #voeg aantal evt. vorige sectie toe:
					$rs =  $this->_db->Query("select count(v.vvrg_id) from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where v.vvrg_vsec_id=s.vsec_id and s.vsec_vlst_id=".$this->vlst_id." and s.vsec_index<".$vsec_index);
		            $iPriorQuestions = $rs->Row('VVRG_ID');
					$rs->Close();
		            $iListIndex = $iListIndex + $iPriorQuestions;
	        	}
	        }
	        $ref_vsec_id="";
	    }

	    if ($vsec_id=="") {
	        $vsec_id=0;
	        $rs = $this->_db->Query("select count(vvrg_id) as QCOUNT from sur_vragenlijst_vragen where vvrg_vlst_id=".$this->vlst_id);
			$vsec_que = $rs->Row('QCOUNT');
			$rs->Close();
	        $vsec_label  = "";
	        $vsec_index  = 1;
	        $ref_vsec_id = "";
	    }

	    #end of section

	    if ($iIndex>$vsec_que) {

	         #get next section by index
	         $vsec_index++;
	         #set section info

	         $rs=  $this->_db->Query("select s.vsec_id, count(v.vvrg_id) as questions, s.vsec_label  from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where  v.vvrg_vlst_id=".$this->vlst_id." and s.vsec_id = v.vvrg_vsec_id and s.vsec_index=".$vsec_index." group by s.vsec_label, s.vsec_id");
	         $row = $rs->Row();
			 $rs->Close();
			 $vsec_id=$row["VSEC_ID"];
	         $vsec_que = $row[QUESTIONS];
	         $vsec_label = $row["VSEC_LABEL"];
	         //echo "end of section";
	         #reset internal index:
	         $iIndex=1;
	    }
	    #begin of current
	    if ($iIndex==0 && $vsec_index>1) {

	        $vsec_index=$vsec_index-1;
	        #set section info
	        $rs =  $this->_db->Query("select s.vsec_id, count(v.vvrg_id) as questions, s.vsec_label  from sur_vragenlijst_vragen v, sur_vragenlijst_secties s where v.vvrg_vlst_id=".$this->vlst_id." and s.vsec_id = v.vvrg_vsec_id and s.vsec_index=".$vsec_index." group by s.vsec_label, s.vsec_id");
	        $row = $rs->Row();
			$rs->Close();
			$vsec_id=$row["VSEC_ID"];
	        $vsec_que = $row[QUESTIONS];
	        $vsec_label = $row["VSEC_LABEL"];
	        //echo "begin of current";
	        #set index to last of section:
	        $iIndex=$vsec_que;
	    }

	    //GENERATE QUESTION-----------------------------------


			// get question
	    $rs =  $this->_db->Query("select v.*, vv.vvrg_id from sur_vragen v, sur_vragenlijst_vragen vv where v.vrg_id=vv.vvrg_vrg_id and vv.vvrg_vsec_id=".$vsec_id." and vv.vvrg_vlst_id=".$this->vlst_id." and vv.vvrg_index=".$iIndex);
	    $rs_que = $rs->Row();
	    $rs->Close();

	    // get question options
	    $rs_options = $this->_db->Query("select * from sur_vraag_opties where vopt_vrg_id=".$rs_que["VRG_ID"]."  and vopt_verwijderd='N' order by vopt_sub desc, vopt_index");


			// get standaard
			if ($rs_que["VRG_DEFAULT"]=="Y") {
				// get any given answers
		    if ($rs_que["VRG_VTYP_ID"]==3  ||
		    		$rs_que["VRG_VTYP_ID"]==4  ||
		    		$rs_que["VRG_VTYP_ID"]==9  ||
		    		$rs_que["VRG_VTYP_ID"]==10 ||
		    		$rs_que["VRG_VTYP_ID"]==11)
		    {

		    	$rs = $this->_db->Query("select * from sur_standaard_antwoorden
		    														where vaw_usr_id = ".$this->_variables->public->usr_id."
		    														  and vaw_vrg_id = ".$rs_que["VRG_ID"]);
					$rs_asw = $rs->Row();
					$rs->Close();

		    } else {

		        $rs_asw = $this->_db->Query("select * from sur_standaard_antwoorden
		        															where vaw_usr_id=".$this->_variables->public->usr_id."
		        															  and vaw_vrg_id= ".$rs_que["VRG_ID"]);

		  	}

			} else {

				// get any given answers
		    if ($rs_que["VRG_VTYP_ID"]==3 ||
		    		$rs_que["VRG_VTYP_ID"]==4 ||
		    		$rs_que["VRG_VTYP_ID"]==9 ||
		    		$rs_que["VRG_VTYP_ID"]==10)
		    {
		    	$rs = $this->_db->Query("select * from sur_vragenlijst_antwoorden where vaw_vusr_id=".$this->vusr_id." and  vaw_vlst_id=".$this->vlst_id." and vaw_vvrg_id= ".$rs_que[VVRG_ID]);
					$rs_asw = $rs->Row();
					$rs->Close();

		    } else {

		        $rs_asw = $this->_db->Query("select * from sur_vragenlijst_antwoorden where vaw_vusr_id=".$this->vusr_id." and vaw_vlst_id=".$this->vlst_id." and vaw_vvrg_id= ".$rs_que[VVRG_ID]);

		    }
			}


	    // generate control:
	    if ($rs_que["VRG_VTYP_ID"]==1 ||
	    		$rs_que["VRG_VTYP_ID"]==2 ||
	    		$rs_que["VRG_VTYP_ID"]==5 ||
	    		$rs_que["VRG_VTYP_ID"]==6 ||
	    		$rs_que["VRG_VTYP_ID"]==11) {

	      // Multiple options
	      // set array of given answers
				while ($rs_asw->Row()) {
					$row = $rs_asw->Row();
	        if ($row["VAW_VOPT_ID"]!="") {
	        	$aSet[$row["VAW_VOPT_ID"]]="Y";
	        	$multiple_x[$row["VAW_VOPT_ID"]]=$row["VAW_OPEN"];
	        } else {
	          // set var for open option
	          $sOpenOpt=$row["VAW_OPEN"];
	          $aSet["opn"]="Y";
	        }
					$rs_asw->MoveNext();
	      }

				if (count($aSet)>0) {
	      	$sRunRegister="bProceed=true;";
	        if ($aSet[opn]=="Y") $sRunRegister .="\n bOpen=true;";
	      }

				// Select 1 = checkbox, select more = radio
        $sControl = "
                <script>
                //Keep count of valued checks:
                var aDone = ".count($aSet).";
                var bOpen = false;

                function checkType11() {

                	positive_11_match = false;
                	x = 0;

   								for(i=0; i<document.csur_questionair.elements.length; i++){
   									if (document.csur_questionair.elements[i].id.charAt(0)=='x') {
 											if (document.csur_questionair.elements[i].value.length>0) {
 												dummy = document.getElementById('y'+document.csur_questionair.elements[i].id.substr(1));
 												x++;
 												if (!positive_11_match) {
													positive_11_match = dummy.checked;
												}
 											}
   									}
   								}

   								if (x==0) {
   									positive_11_match=true;
   								}

   								if (!positive_11_match) {
   									alert('U kunt alleen een verklaring bij een gekozen antwoord geven.');
   								}

   								return positive_11_match;
                }

                function register(val,opn) {

                    //Add or substract valued checks
                    if (val) {
                        aDone++;
                        //when open option: value is mandatory
                        if (opn==1) {
                            bOpen=true;
                            if (csur_questionair.openopt.value.length==0) {
                                bProceed=false;
                            } else {
                                bProceed=true;
                            }
                        } else {
                            bProceed=true;
                        }
                    } else {
                        if (opn==1) {
                            bOpen=false;
                            bProceed=true;
                        }
                        aDone = aDone-1;
                        //if back to 0 checked, proceed is false
                        if (aDone==0) {
                            bProceed=false;
                        }
                    }
                }
                function registeropen(val) {
                    if (bOpen==true) {
                        if (val=='') {
                            bProceed=false;
                        } else {
                            bProceed=true;
                        }
                    }
                }
                ".$sRunRegister."
                </script>
                <table border=0 cellspacing=0 cellpadding=0>
            ";

        while($rs_options->Row()) {
					$row = $rs_options->Row();

          if ($rs_que["VRG_VTYP_ID"]==1 ||
          		$rs_que["VRG_VTYP_ID"]==5
          		) {

	        	$sControl.= '
	        		<tr>
	          		<td class=Q_chkcol>
	          			<input type=radio name=multiple[] value="'.$row["VOPT_ID"].'" class=Q_rdoinput '.(($aSet[$row["VOPT_ID"]]=="Y")? "checked" : "").' onClick="bProceed=true;">
	          		</td>
	          		<td class=Q_optname>'.
	          			$row["VOPT_LABEL"].
	          		'</td>
	          	 </tr>';

           } elseif ($rs_que["VRG_VTYP_ID"]==11) {

	        	$sControl.= '
	        		<tr>
	          		<td class=Q_chkcol>
	          			<input type=radio name=multiple[] value="'.$row["VOPT_ID"].'" class=Q_rdoinput '.(($aSet[$row["VOPT_ID"]]=="Y")? "checked" : "").' id=y'.$row["VOPT_ID"].' onClick="bProceed=true;">
	          		</td>
	          		<td class=Q_optname>'.
	          			$row["VOPT_LABEL"].
	          		'</td>
	          		<td class=Q_optname>
									&nbsp;&nbsp;&nbsp;<input type=text name=multiple_x['.$row["VOPT_ID"].'] value="'.(($aSet[$row["VOPT_ID"]]=="Y")? $multiple_x[$row["VOPT_ID"]] : "").'" class=Q_txtinputbigger id=x'.$row["VOPT_ID"].'>
	          		</td>
	          	</tr>';

           } else  {

           	$sControl.= "
	          	<tr>
	          		<td class=Q_chkcol>
	          			<input type=checkbox name=multiple[] value=\"".$row["VOPT_ID"]."\" class=Q_chkinput ".(($aSet[$row["VOPT_ID"]]=="Y")? "checked" : "")." onClick=\"javascript:register(this.checked);\">
	          		</td>
	          		<td class=Q_optname>".
	          			$row["VOPT_LABEL"]."
	          		</td>
	          	</tr>
	            ";

           }
				$rs_options->MoveNext();
            }
            #Has open option Y/N
            #set open answer:
            $sOpenLabel =  $this->_getOpenLabel($rs_que["VRG_ID"]);
            if ($rs_que["VRG_VTYP_ID"]==5) {
                $sControl .="
                 <tr><td class=Q_chkcol><input type=radio id=\"multiple_openopt\" name=multiple[] value=\"opn\" class=Q_rdoinput ".(($aSet[opn]=="Y")? "checked" : "")." onClick=\"javascript:if (this.form.openopt.value==''){bProceed=false;bOpen=true;} else {bProceed=true};\"></td><td class=Q_optname>".$sOpenLabel."</td></tr>
                 <tr><td>&nbsp;</td><td align=left><textarea name=openopt id=openopt class=Q_txainput onkeydown=\"document.getElementById('multiple_openopt').checked=(this.value.length > 0); register(document.getElementById('multiple_openopt').value,1);\" onBlur=\"javascript:if (bOpen==true){if (this.value.length!=0){bProceed=true} else {bProceed=false}};\">".$sOpenOpt."</textarea></td></tr>
                ";
            } elseif ($rs_que["VRG_VTYP_ID"]==6){
                $sControl .="
                <tr><td class=Q_chkcol><input type=checkbox id=\"multiple_openopt\" name=multiple[] value=\"opn\" class=Q_chkinput ".(($aSet[opn] == "Y") ? "checked" : "")." onClick=\"register(this.checked,1);\"></td><td class=Q_optname>".$sOpenLabel."</td></tr>
                <tr><td>&nbsp;</td><td align=left><textarea name=openopt id=openopt class=Q_txainput onkeydown=\"document.getElementById('multiple_openopt').checked=(this.value.length > 0); register(document.getElementById('multiple_openopt').checked,1);\" onBlur=\"registeropen(this.value);\">".$sOpenOpt."</textarea></td></tr>
                ";
            }
            $sControl.= "
                </table>
            ";
	    }
	    if ($rs_que["VRG_VTYP_ID"]==3) {
	        #get given answer
	        if ($rs_asw["VAW_NUMMERIC"]!="") {
	            $sRunRegister="bProceed=true;";
	        }
	        $iNum = ($rs_asw["VAW_NUMMERIC"]!="") ? floatval($rs_asw["VAW_NUMMERIC"]) : "";
	        $sControl ="
	        <script>
    	        function register(obj) {
    	            bProceed=false;
    	            if (obj.value!='') {
        	            if (isNaN(obj.value)) {
        	                //Show error
            	            openError('alert','U moet een numerieke waarde invullen!');
            	            obj.value='';
        	                //obj.focus();
        	            } else {
        	                bProceed=true;
        	            }
        	        }
    	        }
    	        ".$sRunRegister."
	        </script>
	        <input type=text name=a_number value=\"".$iNum."\" class=Q_txtinput onBlur=\"javascript:register(this);\">
	        ";
	    }
	    if ($rs_que["VRG_VTYP_ID"]==4) {
	        #get given answer
	        if ($rs_asw["VAW_OPEN"]!="") {
	            $sRunRegister="
	            <script>
	            bProceed=true;
	            </script>";
	        }
	        #Open option
	        $sControl = "
	            ".$sRunRegister."
                <textarea name=a_open class=Q_txainput onblur=\"javascript:if (this.value.length==0){bProceed=false;}else{bProceed=true;};\">".$rs_asw["VAW_OPEN"]."</textarea>
            ";
	    }

	    if ($rs_que["VRG_VTYP_ID"]==9) {
	        #get given answer
	        if ($rs_asw["VAW_OPEN"]!="") {
	            $sRunRegister="
	            <script>
	            bProceed=true;
	            </script>";
	        }
	        #Open option
	        $sControl = $sRunRegister."<input name=a_open class=Q_txtinputbigger maxlength=50 value=\"".$rs_asw["VAW_OPEN"]."\" onblur=\"javascript:if (this.value.length==0){bProceed=false;}else{bProceed=true;};\">";
	    }

	    if ($rs_que["VRG_VTYP_ID"]==10) {
          	$boom = explode(';',$rs_asw["VAW_OPEN"]);
          	$length = $boom[1];
          	$weight = $boom[0];
	        #get given answer
	        if ($rs_asw["VAW_OPEN"]!="") {
	            $sRunRegister="
	            <script>
	            bProceed=true;
	            </script>";
	        }
	        #Open option
	        $sControl = $sRunRegister.
                      "<table>".
	                    "<tr><td>Uw lengte</td><td><input type=text name=a_length class=Q_txtinput maxlength=3 onblur=\"javascript:if ((this.value.length==0) || (a_weight.value.length==0)) {bProceed=false} else {bProceed=true};\" value=\"".$weight."\"></td><td><b>cm</b></td></tr>".
            	        "<tr><td>Uw gewicht</td><td><input type=text name=a_weight class=Q_txtinput maxlength=3 onblur=\"javascript:if ((this.value.length==0) || (a_length.value.length==0)) {bProceed=false} else {bProceed=true};\" value=\"".$length."\"></td><td><b>kg</b></td></tr>".
            	        "</table>";
	    }

	    if ($rs_que["VRG_VTYP_ID"]==7 || $rs_que["VRG_VTYP_ID"]==8) {
	        #Matrix

	        #set answers to array:
	        while($rs_asw->Row()) {
				$row = $rs_asw->Row();
	            if ($row["VAW_VOPT_ID"]!="") {
	                $aSet[$row["VAW_VOPT_ID"]."-".$row["VAW_SUB_VOPT_ID"]]="Y";
	            } else {
	                #set var for open option
	                $sOpenOpt=$row["VAW_OPEN"];
	                $aSet["opn-".$row["VAW_SUB_VOPT_ID"]]="Y";
	            }
				$rs_asw->MoveNext();
	        }

            #Has open option Y/N
            $i=1;
            $mrow=1;
            $regrow=0;
            while($rs_options->Row()) {
                #Generate top options:
				$row =$rs_options->Row();
                if ($row["VOPT_SUB"]=='Y') {
                    $sTop .="<td class=Q_matrixtop>".$row["VOPT_LABEL"]."</td>";
                    $aIDs[$i]=$row["VOPT_ID"];
                    $i++;
                } else {
                #generate rows:
                    reset($aIDs);
                    $sRowOpt="";
                    while (list($key, $value)= each($aIDs)) {
                        if ($aSet[$row["VOPT_ID"]."-".$value]=='Y') {
                            $sChecked="checked";
                            #bewaar rijen welke al gezet waren om te registeren:
                            $aRegister[$regrow]=$mrow;
                            $regrow++;
                        } else {
                            $sChecked="";
                        }
                        $sRowOpt .="<td class=Q_matrixrow><input type=radio onclick=\"javascript:register(".$mrow.");\" name=matrix[".$row["VOPT_ID"]."] value=\"".$value."\" class=Q_rdoinput ".$sChecked."></td>";
                    }
                    $sRows .= "<tr><td class=Q_matrixtitle>".$row["VOPT_LABEL"]."</td>".$sRowOpt."</tr>";
                    $mrow++;
                }
				$rs_options->MoveNext();
            }

            #has open option Y/N
            if($rs_que["VRG_VTYP_ID"]==8) {
                reset($aIDs);
                $sRowOpt="";
                while (list($key, $value)= each($aIDs)) {
                    if ($aSet["opn-".$value]=='Y') {
                        $sChecked="checked";
                    } else {
                        $sChecked="";
                    }
                    $sRowOpt .="<td class=Q_matrixrow><input type=radio name=matrix[opn] value=\"".$value."\" class=Q_rdoinput ".$sChecked."></td>";
                }
                $sOpenLabel= $this->_getOpenLabel($rs_que["VRG_ID"]);
                $sRows .= "<tr><td class=Q_matrixtitle>".$sOpenLabel."<br><input type=text name=openopt class=Q_txtinput value=\"".$sOpenOpt."\" style=\"width:175px;\";></td>".$sRowOpt."</tr>";
            }

            #maak script om eerder gezette waarden te registeren
            for ($rec=0;$rec<=$regrow;$rec++) {
                $sRunRegister .= "register(".$aRegister[$rec].")\n";
            }

            $sControl = "
            <script>
            //Save answered rows in array:
    	    var aDone = new Array(".$mrow.");

    	    function register(row) {
    	        //set row to true
    	        aDone[row]='Y';
    	        var iCount =1;

    	        //check if nr of answered rows == total rows
    	        for (i=1;i<=aDone.length;i++) {
    	            if (aDone[i]=='Y') {
    	                iCount++;
    	            }
    	        }
    	        //if all rows set bProceed to true
    	        if (iCount==".$mrow.") {
    	           bProceed=true;
    	        }
    	    }

    	    </script>
            <table cellpadding=5 cellspacing=0 width=80%>
                <tr>
                    <td class=Q_matrixempty>&nbsp;</td>".$sTop."
                </tr>
                ".$sRows."
            </table>
            <script>
            //default:
            ".$sRunRegister."
            </script>
            ";
	    }

	    #printQuestion
	    $s_vars="
	    <!-- question spec vars -->
	    <input type=hidden name=vtyp_id value=\"".$rs_que["VRG_VTYP_ID"]."\">
        <input type=hidden name=vsec_id value=\"".$vsec_id."\">
        <input type=hidden name=vrg_id value=\"".$rs_que["VRG_ID"]."\">
        <input type=hidden name=vvrg_id value=\"".$rs_que[VVRG_ID]."\">
        <input type=hidden name=vsec_label value=\"".$vsec_label."\">
        <input type=hidden name=vsec_que value=\"".$vsec_que."\">
        <input type=hidden name=vsec_index value=\"".$vsec_index."\">
        <input type=hidden name=iIndex value=\"".$iIndex."\">
        <input type=hidden name=iListIndex value=\"".$iListIndex."\">
        <input type=hidden name=sReferers value=\"".$sReferers."\">
		<input type=hidden name=vrg_default value=\"".$rs_que["VRG_DEFAULT"]."\">

        <!-- end question spec vars -->
        ";

		$aQuestion['vars'] = $s_vars;
		$aQuestion['sec_label'] = $vsec_label;
		$aQuestion['vraag'] = $iTotIndex.". ".nl2br($rs_que["VRG_VRAAG"]);
		$aQuestion['toelichting'] =  nl2br($rs_que["VRG_TOELICHTING"]);
		$aQuestion['control'] = $sControl;
		$aQuestion['type_id'] = $rs_que["VRG_VTYP_ID"];

	    $aReturn[0]=$aQuestion;
	    //$aReturn[1]=$iListIndex;
		$aReturn[1]=$iTotIndex;
	    $aReturn[2]=$rs_que[VVRG_ID];
	    return $aReturn;

	}

	function showEnd() {
		$this->_smrt->clear_all_assign();

		$rs_vlst = $this->_db->Query("select vlst_titel, vlst_afsluiting from sur_vragenlijsten where vlst_id=".$this->vlst_id);
		$list = array (
			'titel' 	 => $rs_vlst->Row('VLST_TITEL'),
			'afsluiting' => $rs_vlst->Row('VLST_AFSLUITING')
		);

		$this->_smrt->assign_by_ref('list', $list);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->finished);
	}

	function str2db($sString,$bHTML=0) {
	  	$sString=stripslashes($sString);
	  	//if ($bHTML==1) {
	  	//	$sString=htmlspecialchars($sString,ENT_QUOTES);
	  	//}
	  	$sString=str_replace("'","''",$sString);
		return $sString;
	}



	function getResults() {

		$this->_smrt->clear_all_assign();

		# get request vars:
		$values = $_REQUEST;

		# tmp hack
		$hack = ($_GET['hack']==true) ? true : false;

		#set indexing:
		$max_rows= 50;
		$curr_row = $values['curr_row'];
		$tot_rows = $values['tot_rows'];
		if (!$curr_row) $curr_row = 1;


		$arr_grps = $this->_getGroups();


		if (count($arr_grps)>0) {

			while(list($grp_id,$grp_name)= each($arr_grps)){
				$subsel_grps .= $grp_id.",";
			}
			unset($arr_grps);

			$subsel_grps = substr($subsel_grps,0,-1);

			$sSQL = ' select distinct v.VLST_ID, v.VLST_TITEL, v.VLST_INLEIDING, v.VLST_DOORLOOPTIJD, TO_CHAR (v.VLST_SLUITDATUM,\'dd month yyyy\',\'NLS_DATE_LANGUAGE=Dutch\') as sluitingsdatum, TO_CHAR (v.VLST_PUBDATUM,\'dd month yyyy\',\'NLS_DATE_LANGUAGE=Dutch\') as publicatiedatum '.
				' from sur_vragenlijsten v, sur_vragenlijst_groepen g '.
				' where v.vlst_verwijderd=\'N\''.
				' and v.vlst_openbaar = \'Y\' '.
				' and not v.vlst_parent is null '.
				' and v.vlst_org_id = '.$this->curr_org.
				' and (to_char(SYSDATE,\'YYYYMMDD\') >= to_char(v.VLST_SLUITDATUM,\'YYYYMMDD\'))'.
				' and g.vgrp_vlst_id = v.vlst_id'.
				' and g.vgrp_grp_id in ('.$subsel_grps.')'.
				' order by sluitingsdatum desc, v.vlst_titel';

			if ($hack==true) {
			    $sSQL = ' select distinct v.VLST_ID, v.VLST_TITEL, v.VLST_INLEIDING, v.VLST_DOORLOOPTIJD, TO_CHAR (v.VLST_SLUITDATUM,\'dd month yyyy\',\'NLS_DATE_LANGUAGE=Dutch\') as sluitingsdatum, TO_CHAR (v.VLST_PUBDATUM,\'dd month yyyy\',\'NLS_DATE_LANGUAGE=Dutch\') as publicatiedatum '.
				' from sur_vragenlijsten v, sur_vragenlijst_groepen g '.
				' where v.vlst_verwijderd=\'N\''.
				' and not v.vlst_parent is null '.
				' and v.vlst_org_id = '.$this->curr_org.
				' and g.vgrp_vlst_id = v.vlst_id'.
				' and g.vgrp_grp_id in ('.$subsel_grps.')'.
				' order by sluitingsdatum desc, v.vlst_titel';
			}

			#set indexing:
			if (!$tot_rows) {
				$rs_lists = $this->_db->Query($sSQL);
				$tot_rows = $rs_lists->RowCount;
			} else {
				$rs_lists = $this->_db->Query($sSQL,($curr_row-1),$max_rows);
			}


			$rowi = 1;
			$start_row = $curr_row;

			$iz=0;
			while($rs_lists->Row()){
				$row = $rs_lists->Row();
				if ($rowi <= $max_rows) {
					$lists[$iz]['title'] 	= htmlentities($row['VLST_TITEL']);
					$lists[$iz]['pub']	  	= $row['PUBLICATIEDATUM'];
					$lists[$iz]['end']		= $row['SLUITINGSDATUM'];
					$lists[$iz]['detailurl']= "/?p=csur0100&option=listresults&vlst_id=".$row['VLST_ID'];
				}
				$rs_lists->MoveNext();
				$iz++;
				$rowi++;
			}
			$rs_lists->Close();
		}

		#navigate opt:
		if ($tot_rows > $max_rows) {
		    $navigate = true;
			if ($curr_row > 1) {
			    $frm_back	= "document.frm_csur0100.curr_row.value=".($curr_row - $max_rows).";document.frm_csur0100.submit();";
			}
			if (($curr_row + $max_rows) < $tot_rows) {

			 	$frm_next	= "document.frm_csur0100.curr_row.value=".($curr_row + $max_rows).";document.frm_csur0100.submit();";
			}
			# index
			for($i=1;$i<=ceil($tot_rows/$max_rows);$i++) {
				$go = (($i==1) ? 0 : (($i-1) * $max_rows))+1;
				$page_select[$i] = array(
					'number'	=> $i,
					'row'		=> $go,
					'goto'		=> "document.frm_csur0100.curr_row.value=".$go.";document.frm_csur0100.submit();"
				);
			}
		}

		$open 	= "<form name=\"frm_csur0100\" method=\"post\"><input type=\"hidden\" id=\"curr_row\" name=\"curr_row\" value=\"".$curr_row."\"><input type=\"hidden\" id=\"tot_rows\" name=\"tot_rows\" value=\"".$tot_rows."\">";
		$close 	= "</form>";

		$rlists  = array (
			'open'			=> $open,
			'close'			=> $close,
			'lists'			=> $lists,
			'navigate'		=> $navigate,
			'movenext'		=> $frm_next,
			'moveback'		=> $frm_back,
			'curr_row'		=> $curr_row,
			'tot_rows'		=> $tot_rows,
			'page_select'	=> $page_select
		);

		$this->_smrt->assign_by_ref('lists', $rlists);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->result_list);
	}


	function _getRIndex($current_sec,$current_idx) {

		$sSQL="select v.vvrg_id
			, 	v.vvrg_index
			, 	vr.vrg_vraag
			,	s.vsec_label
			,	s.vsec_id
			from sur_vragenlijst_vragen v
			,	sur_vragenlijst_secties s
			,	sur_vragen vr
			where 	vr.vrg_id=v.vvrg_vrg_id
			and		s.vsec_id(+)=v.vvrg_vsec_id
			and		v.vvrg_vlst_id=".$this->vlst_id."
			order by s.vsec_index, v.vvrg_index";

   		$rs_questionair = $this->_db->Query($sSQL);

		$idx = 1;

		while($rs_questionair->Row()) {
			$que = $rs_questionair->Row();
			if (!$current_sec) $current_sec = $que["VSEC_ID"];
			#sectie change
            if ($show_vsec_id != $que["VSEC_ID"]) {
	        	$show_vsec_id =$que["VSEC_ID"];
				$arr_index[$show_vsec_id]['label'] = $que["VSEC_LABEL"];
	        }
			//if no sections set to 0
			if (!$show_vsec_id) $show_vsec_id = 0;
			//bewaar laaste vraag van actieve sectie
			if ($current_idx==-1 && $show_vsec_id == $current_sec) {
				$last_vvrg_index = $que['VVRG_INDEX'];
			}

			$arr_index[$show_vsec_id]['q'][$que['VVRG_INDEX']] = array (
				'vlst_id'	=> $this->vlst_id,
				'current'	=> (($current_idx == $que['VVRG_INDEX'] && $current_sec==$show_vsec_id)? true : false),
				'nr'		=> $que['VVRG_INDEX'],
				'vvrg_id'	=> $que['VVRG_ID'],
				'vraag'		=> $que['VRG_VRAAG'],
				'init'		=> 'javascript:frm_csur0100.go_idx.value='.$que['VVRG_INDEX'].';frm_csur0100.go_vsec_id.value='.$show_vsec_id.';frm_csur0100.submit();'
			);

			$rs_questionair->MoveNext();
			$idx++;
	    }
		//zet laaste vraag van actieve sectie op actief wanneer $current_idx = -1;
		if ($current_idx==-1) $arr_index[$current_sec]['q'][$last_vvrg_index]['current'] = true;

		$rs_questionair->Close();
		return $arr_index;
	}


	function getListResults($vlst_id){
		
		require_once 'htmlcontrols-1.0/class.htmlcontrols.php';
		//init ctrl class
		$this->_ctrl = new htmlControls (strtolower($this->_variables->public->lng_code), $this->_settings->general->paths->virtual->style.'controls.css');


		$this->_smrt->clear_all_assign();

		//zet main vars:
		$this->vlst_id = $vlst_id;

		if ($_REQUEST['vsec_id']!='') {
		    $go_vsec_id 	= $_REQUEST['go_vsec_id'];
			$vsec_id		= $_REQUEST['vsec_id'];
			$go_idx			= $_REQUEST['go_idx'];
			$idx			= $_REQUEST['idx'];
		}

		//reset idx and set section on post:
		if ($go_vsec_id!=$vsec_id) {
		    $vsec_id = $go_vsec_id;
			$idx = 1;
		}
		//reset vraag
		if ($go_idx!=$idx) {
		    $idx = $go_idx;
		}


		//current:
		//if -1 then set last
		if ($idx=='') $idx = 1;
		//set index and current
		$a_index = $this->_getRIndex($vsec_id,$idx);

		//extract sections from index and make dropdown
		while(list($sec,$lbl) = each($a_index)){
			$a_secs[$sec]= $lbl['label'];
			//volgende moet geregistreerd worden en dit is nog niet gebeurd
			if ($get_next == true && !$next_vsec_id) {
			    $next_vsec_id = $sec;
			}
			if (!$vsec_id) {
				//geen sectie, zet eerste:
				$vsec_id = $sec;
				$get_next = true;
			} elseif ($vsec_id == $sec) {
				// huidige sectie is actief zet voorlaatste
				// geef aan dat volgende geregistreerd met worden
				$get_next = true;
				$prev_vsec_id = $last_sec;
			}
			$last_sec = $sec;
		}
		$a_sections['options'] = $a_secs;
		$a_sections['javascript'] = "onchange=\"javascript:frm_csur0100.go_vsec_id.value=frm_csur0100.cmb_vsec_id.value;frm_csur0100.submit();\"";
		unset($a_secs);

		//if no sections set to 0
		if (!$vsec_id) $vsec_id = 0;

		//get questions from index for current section
		while(list($k,$vrg) = each($a_index[$vsec_id]['q'])){
			$a_vrgn[$vrg['nr']] = array($vrg['nr'],$vrg['vraag']);
			$max_vrgn = $vrg['nr'];
		} // while
		$a_vragen['options'] = $a_vrgn;
		$a_vragen['javascript'] = "onchange=\"javascript:frm_csur0100.go_idx.value=frm_csur0100.idx.value;frm_csur0100.submit();\"";
		$a_vragen['widths'] = array(20,250);
		unset($a_vrgn);
		//if -1 then last
		if ($idx==-1) {
		    $idx = $max_vrgn;
		}

		//get question:
		$sSQL = 'select  v.vrg_id, v.vrg_vraag, v.vrg_toelichting,v.vrg_vtyp_id, l.vlst_titel, vv.vvrg_id'.
			' from sur_vragenlijsten l, sur_vragenlijst_vragen vv, sur_vragen v'.
			' where v.vrg_id = vv.vvrg_vrg_id '.
			' and vv.vvrg_vlst_id = l.vlst_id'.
			' and l.vlst_id = '.$this->vlst_id.
			' and vv.vvrg_vsec_id = '.$vsec_id.
			' and vv.vvrg_index = '.$idx;


		$rs_vrg =  $this->_db->Query($sSQL);
		$s_titel = $rs_vrg->Row('VLST_TITEL');
		$s_vraag = $rs_vrg->Row('VRG_VRAAG');
		$s_toelichting = $rs_vrg->Row('VRG_TOELICHTING');
		$vtyp_id = $rs_vrg->Row('VRG_VTYP_ID');
		$vvrg_id  = $rs_vrg->Row('VVRG_ID');
		$vrg_id  = $rs_vrg->Row('VRG_ID');
		$rs_vrg->Close();



		if ($vtyp_id!=7 && $vtyp_id!=8 && $vtyp_id!=3 && $vtyp_id!=4 && $vtyp_id!=10) {
            	$colspan=3;

            	$rs_opt = $this->_db->Query("select v.vopt_id, v.vopt_label, count(a.vaw_vopt_id) as topt from sur_vraag_opties v, sur_vragenlijst_antwoorden a where v.vopt_vrg_id=".$vrg_id." and a.vaw_vopt_id(+)=v.vopt_id and a.vaw_vvrg_id(+)=".$vvrg_id." and a.vaw_vlst_id(+)=".$this->vlst_id." group by v.vopt_id, v.vopt_label");

                $iRow=0;
                while ($rs_opt->Row()) {
					$opt = $rs_opt->Row();

					#string array voor chart
                    //$sdata .=$opt["TOPT"].":";

					$slegend .=$opt["VOPT_LABEL"].":";

					#array to print in lijst:
                    $a_options[$iRow]['lbl']=$opt["VOPT_LABEL"];
                    $a_options[$iRow]['opt']=$opt["TOPT"];
                    $iAnswers = $iAnswers + $opt["TOPT"];
        			$rs_opt->MoveNext();
		            $iRow++;
                }
				$rs_opt->Close();
                #add open option:
                if ($vtyp_id==5 || $vtyp_id==6) {
                    $rs = $this->_db->Query("select count(a.vaw_id) as AANTAL from sur_vragenlijst_antwoorden a where a.vaw_vopt_id is null and a.vaw_vvrg_id=".$vvrg_id);
					$iOpen = $rs->Row('AANTAL');
					$rs->Close();
                    $sOpenLabel=$this->_getOpenLabel($vrg_id);

                    #string array voor chart
                    //$sdata .= $iOpen.":";
                    $slegend .= "Open:";
                    #array to print in lijst:
                    $a_options[$iRow]['lbl']="(Open) ".$sOpenLabel;
                    $a_options[$iRow]['opt']=$iOpen;
                    $iAnswers = $iAnswers + $iOpen;
                    $iRow++;
                }
		} elseif ($vtyp_id==7 || $vtyp_id==8) {
				$colspan=3;

                $rs_subs = $this->_db->Query("select vopt_id, vopt_label ".
									" from sur_vraag_opties ".
									" where vopt_sub='Y' ".
									" and vopt_vrg_id=".$vrg_id.
									" order by vopt_index");

				while($rs_subs->Row()){
					$a_subopt[$rs_subs->Row('VOPT_ID')]= $rs_subs->Row('VOPT_LABEL');
					$rs_subs->MoveNext();
				}
				$rs_subs->Close();


                $rs_opts = $this->_db->Query("select vopt_id, vopt_label ".
								" from sur_vraag_opties ".
								" where vopt_sub='N' ".
								" and vopt_vrg_id=".$vrg_id.
								" order by vopt_index");

                $iRow=0;
                $iAnswers=0;
				while($rs_opts->Row()){
					$opt =$rs_opts->Row();

                    reset($a_subopt);
                    while (list($subopt,$sublabel) = each($a_subopt)) {

                        #query answers
                        $rs = $this->_db->Query("select count(vaw_vvrg_id) as AANTAL from sur_vragenlijst_antwoorden where vaw_vvrg_id=".$vvrg_id." and vaw_vopt_id=".$opt["VOPT_ID"]." and vaw_sub_vopt_id=".$subopt);
						$iAantal = $rs->Row('AANTAL');
						$rs->Close();

                        #string array voor chart
                        //$sdata .= $iAantal.":";
                        $slegend .= $opt["VOPT_LABEL"]." /_n_".$sublabel.":";

                        #array to print in lijst:
                        $a_options[$iRow]['lbl']=$opt["VOPT_LABEL"]." / ".$sublabel;
                        $a_options[$iRow]['opt']=$iAantal;
                        $iAnswers= $iAnswers + $iAantal;
                        $iRow++;
                    }
					$rs_opts->MoveNext();
                }
				$rs_opts->Close();

				if ($vtyp_id==8) {
               		#open optie
                	$sOpenLabel = $this->_getOpenLabel($vrg_id);
                	reset($a_subopt);
                	while (list($subopt,$sublabel) = each($a_subopt)) {
                    	#query answers
                    	$rs = $this->_db->Query("select count(vaw_vvrg_id) as AANTAL from sur_vragenlijst_antwoorden where vaw_vvrg_id=".$vvrg_id." and vaw_vopt_id is null and vaw_sub_vopt_id=".$subopt);
						$iAantal = $rs->Row('AANTAL');
						$rs->Close();

	                    #string array voor chart
	                   // $sdata .= $iAantal.":";
	                    $slegend .= "Open /_n_".$sublabel.":";

	                    #array to print in lijst:
   	    	            $a_options[$iRow]['lbl']="(Open) ".$sOpenLabel." / ".$sublabel;
   		                $a_options[$iRow]['opt']=$iAantal;
	                    $iAnswers= $iAnswers + $iAantal;
    	                $iRow++;
        	        }
				}

		} elseif ($vtyp_id==3 || $vtyp_id==10) {
			$colspan = 3;

		    $rs_opts = $this->_db->Query("select vaw_nummeric, count(vaw_vvrg_id) as topt ".
                                          " from sur_vragenlijst_antwoorden, sur_vragenlijst_users ".
                                          " where vaw_vvrg_id= ".$vvrg_id.
                                          " and vusr_id = VAW_VUSR_ID ".
                                          " group by vaw_nummeric ".
                                          " order by vaw_nummeric");
			$iRow=0;
			while($rs_opts->Row()){
				$opt = $rs_opts->Row();
				#string array voor chart
                //$sdata .=$opt["TOPT"].":";
	           	$slegend .=$opt["VAW_NUMMERIC"].":";
                #array to print in lijst:
                $a_options[$iRow]['lbl']=$opt["VAW_NUMMERIC"];
                $a_options[$iRow]['opt']=$opt["TOPT"];
                $iAnswers = $iAnswers + $opt["TOPT"];
                $iRow++;
				$rs_opts->MoveNext();
			}
			$rs_opts->Close();




		}

		#matrix open optie:
        if ($vtyp_id==8) {

			#show open answers:
			$rs_open = $this->_db->Query("select vaw_open, vaw_sub_vopt_id from sur_vragenlijst_antwoorden where vaw_vvrg_id=".$vvrg_id." and vaw_sub_vopt_id is not null and vaw_open is not null order by vaw_vusr_id");
	       	$i=0;
       		while($rs_open->Row()) {
				$open = $rs_open->Row();

				$a_opn_mtx_options[$i]['lbl'] = $open["VAW_OPEN"];
				$a_opn_mtx_options[$i]['opt'] = $a_subopt[$open["VAW_SUB_VOPT_ID"]];
				$rs_open->MoveNext();
				$i++;
        	}
			$rs_open->Close();


        }


		if ($vtyp_id==9 ||
				$vtyp_id==4 ||
				$vtyp_id==5 ||
				$vtyp_id==6) {
			if ($vtyp_id==9 ||
					$vtyp_id==4) {
			    $colspan=1;
			}
            #show open answers:
            $rs_open = $this->_db->Query("select vaw_open, vaw_vusr_id ".
				" from sur_vragenlijst_antwoorden ".
				" where vaw_vvrg_id= ".$vvrg_id.
				(($vtyp_id==5 || $vtyp_id==6) ?  " and vaw_vopt_id is null" : "" ).
				" order by vaw_vusr_id");

			$i=0;
			while($rs_open->Row()){

				$a_opn_options[$i++] = $rs_open->Row('VAW_OPEN');
				$rs_open->MoveNext();
			}
			$rs_open->Close();


        }
		//wanneer % deze berekenen met $iAnswers!
		if ($colspan==3) {
		    for ($iPrint=0;$iPrint<$iRow;$iPrint++) {
                if ($a_options[$iPrint]['opt']!=0 && $iAnswers!=0) {
                    $a_options[$iPrint]['prc'] = floor(($a_options[$iPrint]['opt']/$iAnswers) * 100);
                } else {
                    $a_options[$iPrint]['prc'] = 0;
                }
				$sdata .= $a_options[$iPrint]['prc'].":";
			}
		}

		//script
		$s_script="<script>
		function closeIndex(){
				document.getElementById('overzichtcontainer').style.display = 'none';
				document.getElementById('overzichtcontainer').style.visibility = 'hidden';
			}
			function showIndex() {
				document.getElementById('overzichtcontainer').style.display = '';
				document.getElementById('overzichtcontainer').style.visibility = 'visible'
			}
		</script>";
		$indexblockid = 'overzichtcontainer';

		//form
		$s_form_open = '<form method=post name=frm_csur0100> '.
			' <input type=hidden name="vlst_id" value="'.$this->vlst_id.'">'.
			' <input type=hidden name="vsec_id" value="'.$vsec_id.'">'.
			' <input type=hidden name="go_vsec_id" value="'.$vsec_id.'">'.
			' <input type=hidden name="go_idx" value="">';

		$s_form_close = '</form>';

		//nav btns:
		if ($idx > 1) {
		    $btn_back = "javascript:frm_csur0100.go_idx.value=".($idx-1).";frm_csur0100.submit();";
		} elseif($prev_vsec_id) {
			$btn_back_section = "javascript:frm_csur0100.go_idx.value=-1;frm_csur0100.go_vsec_id.value=".$prev_vsec_id.";frm_csur0100.submit();";
		}
		if ($idx < $max_vrgn) {
			$btn_next = "javascript:frm_csur0100.go_idx.value=".($idx+1).";frm_csur0100.submit();";
		} elseif ($next_vsec_id) {
			$btn_next_section = "javascript:frm_csur0100.go_vsec_id.value=".$next_vsec_id.";frm_csur0100.submit();";
		}

		//chart options
		if (($vtyp_id!=9 && $vtyp_id!=4)) {

			if (str_replace("0","",str_replace(":","",$sdata))!="") {

				#strip last char:
	            if ($sdata) $sdata=substr($sdata,0,-1);
	            if ($slegend) $slegend=substr($slegend,0,-1);

				$s_chart = "csur0100_barchart.php?sdata=".$sdata."&slegend=".$slegend;

			}

		}



		$results =  array (
			'titel'			=> $s_titel,
			'vraag'			=> $idx.": ".$s_vraag,
			'toelichting'	=> $s_toelichting,
			'idx'			=> $idx,
			'open'			=> $s_form_open,
			'close'			=> $s_form_close,
			'script' 		=> $s_script,
			'indexblockid'	=> $indexblockid,
			'index' 		=> $a_index,
			'vsec_id'		=> $vsec_id,
			'sections' 		=> $this->_ctrl->{cmb}("Sectie","cmb_vsec_id",$vsec_id,255,$a_sections,''),
			'vragen' 		=> $this->_ctrl->{cmb}("","idx",$idx,255,$a_vragen,''),
			'volgende'		=> $btn_next,
			'vorige'		=> $btn_back,
			'volgende_sectie' => $btn_next_section,
			'vorige_sectie'	=> $btn_back_section,
			'colspan'		=> $colspan,
			'options'		=> $a_options,
			'open_options'  => $a_opn_options,
			'mtx_open_options' => $a_opn_mtx_options,
			'chart'			=> $s_chart
		);


		$this->_smrt->assign_by_ref('results', $results);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->list_results);

	}

	function getLogin($redirect) {

		$this->_smrt->clear_all_assign();
		$this->_smrt->assign('redirect', "/?".$redirect);
		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->login);

	}

}

?>