<?php 
include '_dirinfo.php';
require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');

	class Scale extends Question 
	{
		public function __construct(db $db=null,$data=null)
		{
			parent::__construct($db,$data);
			$this->template_file = "SCtemplate.xml";
		}
		public function addQuestion(array $data)
		{
		
			parent::addQuestion($data);
			
		}
		public function supportedShowTypes()
		{
			return  array(1,2,5,7);
		}
		
	
		public function updateStructure()
		{
			include 'config.php';
	  		$this->db->ChangeDatabase($CATI_base);
	  		
			if ( $this->les_sql == 4 ) 
			{
				$legend_count = count(explode("/", $this->leg_sql));
			}
			
			$i=count(explode("/", $this->odg_sql) );
			
			$fields = array();
			for ($answer_no=1; $answer_no<=$i; $answer_no++) 
			{
				if( $this->les_sql == 4 )
				{
					for ( $n=1; $n<=$legend_count; $n++ ) 
						{
							//$SQLadd_filds = $SQLadd_filds.", ".$VAR."_".$answer_no."_".$n." $str_type_base($lenght_variable_base)";
							$fields[] = $this->q_name."_".$answer_no."_".$n." int(3)";
						}
				}
				elseif ( $this->les_sql == 3 )
				{
					$fields[] = $this->q_name."_".$answer_no." char(250)";
				}
				else 
				{
					$fields[] = $this->q_name."_".$answer_no." int(3)";
				}
			}
			
			
			$sql = "ALTER TABLE ".$this->project."_structure ADD (".implode(",",$fields).")";
	  		$this->db->SQLexecute($sql);
			if($this->db->IsError())
		  			{
		  				echo $this->db->GetError();
		  				return "Error";
		  			}
		}
		
		public function getStructureFields($row=null,$incOpen = true)
		{
			$q = $this->q_name;
			$str = array();
			/*$ans = str_replace("/","<*>",$this->odg_sql);
			$ans = str_replace("<<*>","</",$ans);
			$ans = str_replace("<*>>","/>",$ans);
		
			$ans = explode('<*>',$ans);*/
			$ans = $this->getAnswerArray();
			  		
			if($this->les_sql == 1 || $this->les_sql == 2 || $this->les_sql == 7)
			{
			    //Tanis 20150515 added or $this->les_sql == 1 becouse we want to have radio buttons
				if(($this->les_sql == 2 or $this->les_sql == 1) && trim( $this->atr_sql )  )//if comboboxes is selected and there are attributes configured
				{
					$atr = $this->answerToArray($this->atr_sql);
					for($i=1;$i<= count($ans);$i++ )
						{
							//$aId = explode(' ',$ans[$i-1],2);
							//we save the positions on which a certain ID is!
							$idToNum[ $ans[$i-1][0] ] = $i;
							for($j=1;$j<=count($atr);$j++)
							{			
								$str[] = trim( $q.'_'.$i.'_'.$j.' '.$this->typeBase );
							}
						}
					
				}
				else
				{
					for($i=1;$i<= count($ans);$i++ )
					{
						//$aId = explode(' ',$ans[$i-1],2);
						//we save the positions on which a certain ID is!
						$idToNum[ $ans[$i-1][0] ] = $i;
						$str[] = trim( $q.'_'.$i.' '.$this->typeBase);
					}
				}
				
				if($incOpen && $this->open_answers)
				{
				
					$openAns = explode(':',$this->open_answers);
					foreach ($openAns as $openAnsItem) {
						if(!$idToNum[ $openAnsItem  ]) return false;
						$str['o_'.$openAnsItem] = trim( $q.'_opn'.$idToNum[ $openAnsItem  ].' '.$this->typeOpen );
					}
				}
				
			}/*
			else if( $this->les_sql == 8)
			{//inverted radio has one field for each legend!
				require_once PATH_TO_ROOT.'_config/cartConfig.php';
				
				$inverse = $cartConfig[$_SESSION['id_project']][substr($_SESSION['questionFields'][0], 0, strrpos($_SESSION['questionFields'][0], "_"))]["inverse"];
				if ($inverse) $leg = $this->getLegendArray();
				else $leg = $this->getAnswerArray();
				
				for($i=1;$i<= count($leg);$i++ )
				{
					//$aId = explode(' ',$ans[$i-1],2);
					//we save the positions on which a certain ID is!
					$idToNum[ $ans[$i-1][0] ] = $i;
					$str[] = trim( $q.'_'.$i.' '.$this->typeBase);
				}
				
			}*/ elseif ($this->les_sql == 5) {
				
				$leg = $this->getLegendArray();
				for($i=1;$i<= count($leg);$i++ )
				{
					//$aId = explode(' ',$ans[$i-1],2);
					//we save the positions on which a certain ID is!
					$idToNum[ $ans[$i-1][0] ] = $i;
					$str[] = trim( $q.'_'.$i.' '.$this->typeBase);
				}
				
				if($incOpen && $this->open_answers)
				{
			
					$openAns = explode(':',$this->open_answers);
					foreach ($openAns as $openAnsItem) {
						//if(!$idToNum[ $openAnsItem  ]) return false;
						$str['o_'.$openAnsItem] = trim( $q.'_opn'.$openAnsItem.' '.$this->typeOpen );
					}
				}
				
				
			}
			else //if selection model are checkboxes or textboxes we have to create one field for each legend for each answer!!!
			{ //this shall not occur since multi checkboxes and multi open answers has been moved to mr and op!
				/*$leg = str_replace("/","<*>",$this->leg_sql);
				$leg = str_replace("<<*>","</",$leg);
				$leg = str_replace("<*>>","/>",$leg);
			
				$leg = explode('<*>',$leg);*/
				$leg = $this->getLegendArray();
				
				for($i=1;$i<= count($ans);$i++ )
				{
					//$aId = explode(' ',$ans[$i-1],2);
					//we save the positions on which a certain ID is!
					$idToNum[ $ans[$i-1][0] ] = $i;
					for($j=1;$j<=count($leg);$j++)
					{			
						$str[] = trim( $q.'_'.$i.'_'.$j.' '.$this->typeBase );
					}
				}
				
			}
			
			return $str;
			
		}
		
	public function getAnswersForSelect(&$data,&$idToNum)
			{
				if($this->les_sql == 5/* || $this->les_sql == 8*/)
					$ans = $this->getLegendArray();
				else
					$ans = $this->getAnswerArray();
				
				if($this->les_sql == 2 && trim( $this->atr_sql )  )//if comboboxes is selected and there are attributes configured
					{
						$atr = $this->answerToArray($this->atr_sql);
						foreach ($ans as $k=>$val)
							{
								//$aId = explode(' ',$ans[$i-1],2);
								//we save the positions on which a certain ID is!
								$idToNum[ $ans[$i-1][0] ] = $i;
								foreach ($atr as $kL => $legVal) {
									$finD[] = ($k+1).'_'.($kL+1).' '.$val[0].' '.$val[1].' - '.$legVal[0].' '.$legVal[1];
								}
							}
						
					}
				else
				{
					foreach ($ans as $k=>$val) {
						
		    			$finD[] = ($k+1).' '.$val[0].' '.$val[1];
		    			//we save the positions on which a certain ID is!
						//$idToNum[ $val[0] ] = $k+1;
		    		}
				}	
		    	if ($finD)	
		    		$data = implode('/',$finD);
		    	else
		    		return false;
				
				return true;
			}
		
	
	public function getQType()
		{
			return "Scale";
		}
		public function hasMultiAnswer()
		{
			return true;
		}	
		public function getIconCls()
		{
			return 'icon-question_sc';
		}
        
    public function drawMinMaxTable($arr, &$objPHPExcel, &$i)
    {
        $i++;
        $title = $arr[0];
        $data = $arr[1];
        
        $sheet = $objPHPExcel->getSheet(0);
        $sheet->SetCellValue('A' . $i, strip_tags($title));
        $sheet->getStyle('A'. $i . ':E'.$i)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('004AA0'); 
         $sheet->getStyle('A'.$i .':E' . $i)
                ->getFont()
                ->getColor()
                ->setRGB('FFFFFF');
                
        $i++;
        
        $styleArray =  array(
            'fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'c8ccc8')
                )
        );
        
        $sheet->SetCellValue('A' . $i, "Min: " . $data['graph_min'] . ", Max: " . $data['graph_max']);
        $sheet->getStyle('A' . $i)->applyFromArray($styleArray);
        
        $sheet->SetCellValue('B' . $i, "min");
        $sheet->getStyle('B'. $i)->applyFromArray($styleArray);
        
        $sheet->SetCellValue('C'. $i, "max");
        $sheet->getStyle('C'. $i)->applyFromArray($styleArray);
        
        $sheet->SetCellValue('D'. $i, "N");
        $sheet->getStyle('D'. $i)->applyFromArray($styleArray);
        
        $sheet->SetCellValue('E'. $i, "Mean");
        $sheet->getStyle('E'. $i)->applyFromArray($styleArray);
        $i++;
        
        foreach($data['mean_array'] as $dataRow)
        {
            $sheet->SetCellValue('A' . $i, $dataRow[5]);
            $sheet->SetCellValue('B' . $i, $dataRow[1]);
            $sheet->SetCellValue('C' . $i, $dataRow[2]);
            $sheet->SetCellValue('D' . $i, $dataRow[3]);
            $sheet->SetCellValue('E' . $i, $dataRow[4]);
            $i++;
        }
        
         
               
    }
        
    public function exportToExcel($rowQuestion ,$tmpName = 'warpitStatistic', &$objPHPExcel)
    {
            $meanArr = array();
          //$q = Question::createQuestion($rowQuestion['tip_sql']);
            $fields = $this->getStructureFields($rowQuestion,false);
            
            $openAns = $rowQuestion['open_answers'];
            
            //we get the answers as an array ordered sequentely (id is NOT the key)
            $answers = $this->answerToArray($rowQuestion['odg_sql']);
            
            //we get the legend keyed by id's
            $legend = $this->answerToArray($rowQuestion['leg_sql']);
            
            $title =  json_encode( ($this->showVar ? $rowQuestion['q_name'].': ' : '') . $rowQuestion['vpr_sql'] );//echo 'TITLE: '.$title;
            $k = 0;
            $graph_min = 999999;
            $graph_max = 0;
          //echo "Row question(les_sql): ".$rowQuestion['les_sql'];
            if($rowQuestion['les_sql'] != 4 )
            {
                $rowPos = 2;
            foreach ($fields as $ansField) {//gre skozi vsak odgovor
                $arr = array();
                //echo $ansField;
                //2015 Če ima odgovor vrednos 0 v statistiki pokaže kot da za ta odgvor ni v bazi zapisov čeprav so. Ta pogoj sem odstranil da stvar deluje
                $validAnsCond = "1";
            //    $validAnsCond = "$ansField>0";
				
                $struct = array();
                //for each field (answer) we count the freuqency of selected legend options
                //e.g if legend is 1 bad, 2 ,3 ,4 , 5 good : we count how many times 1 was selected for this answer.
                $sql = "SELECT $ansField AS variable,  count(*) AS freq, count(*)*$ansField AS multi_row FROM $tmpName WHERE $validAnsCond $this->filter GROUP BY $ansField";
                
                //echo $sql.' '.'<br/>';
                If (!$resStat = $this->db->SQLexecute($sql)) {
                    //  Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
                        echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
                        exit;   
                }
                $totalN = 0;
                $totalMean = 0;
                $min = 999999;
                $max = 0;
                while ($rowStat = $this->db->fetchArray($resStat)) //gre skozi eno legendo enega vpra?anja, zabele?i min, max ter totalN
                {
                    //$val is the id of the selected legend(3 good) has value of 3
                    $val = $rowStat[0];
                    //we count the total number of answers (this is valid only for normal scale and singleselect)
                    $totalN += $rowStat[1];
                    //we save the the freq in an array and use the id as key, so that we can fetch it up when we go trough the legend
                    $struct[ $val ] = $rowStat[1];
                    //we calculate the mean and save the min and max values!
                    $totalMean += $rowStat[2];
                    if($val < $min)
                        $min = $val;
                    if ($val > $max)
                        $max = $val;
                    if($min < $graph_min)
                        $graph_min = $min;
                    if($graph_max < $max)
                        $graph_max = $max;
                }       
            
                                //ump($struct);
                if($totalN == 0) {
                    $numerusLabel = 0;
                    $totalN = 1;
                } else 
                    $numerusLabel = $totalN;    
                        $minLegendVal = 999999;
                        $maxLegendVal = 0;
                        foreach ($legend as $item) {
                                $key = $item[0];
                                $ans = $item[1]; 
                        //now we go through the whole legend (so that we also show legend values that were never selected)
                        //the $legend arrays uses id as keys so we can use the key to fetch the freq from $struct   
                            $freq = $struct[$key];
                            if(!$freq)
                            {
                                $freq = 0;  
                            }
                            //$arr will be used as the data store for the grid and chart
                            $arr[] = array( $ans, $freq,$freq/$totalN*100 ,strip_tags( substr($ans,0,50)) );
                            
                            //we get the highest legend numeric value, used for graph lower and upper limit scale
                            if($key < $minLegendVal)
                                $minLegendVal = $key;
                            if($key > $maxLegendVal)
                                $maxLegendVal = $key;
                            
                        }//ump($arr);//v vsakem $arr so frekvence za (bad,good,very good ...) od enega odgovora in enega columna 
                        
                    $meanArr[] = array( $answers[$k][1] , $min ,$max , $totalN , $totalMean / $totalN ,strip_tags( substr($answers[$k][1],0,50))  );
                    //echo 'totalN: '.$totalN.' totalMean: '.$totalMean;//exit;
                    //ump($meanArr);
                    //this functions creates the grid and chart
                    $ansTitle = $answers[$k][1];
                  
                    parent::exportToExcel($rowQuestion, $tmpName, $objPHPExcel,array($arr,$ansTitle. " (N = $numerusLabel )"), $rowPos);
                    $k++;   
                    //ump($retGrids);exit;
                }
                //ump($meanArr);
                //ump($retGrids);
                foreach($answers as $answ)
                    $answ_arr[] = $answ[1];
                    
                    $data = array(
                        'graph_min' => $graph_min,
                        'graph_max' => $graph_max,
                        'mean_array' => $meanArr
                    );
                    $this->drawMinMaxTable(array('Answer the questions', $data), $objPHPExcel, $rowPos);
                    return;
                {//draw the min max table!!!
                    if (!$decimal_separator) $decimal_separator = "."; 
        
                        echo $htmlTitle1.'<td colspan="7"'.$htmlTitle2;
                     echo "<td width=350px Style=\"background-color : #c8ccc8; padding-left : 5px;
                        border-left-width : 1px; 
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-left-color : #989898; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-left-style : solid; 
                        border-right-style : none; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                                    echo "Min: $graph_min, Max: $graph_max";
                                                echo "</td>";
                                                echo "<td width=80px align=center Style=\"background-color : #c8ccc8; height : 25px;
                        border-left-width : 1px; 
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-left-color : #989898; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-left-style : solid; 
                        border-right-style : none; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                                    echo "mean";
                                                echo "</td>";
                                                echo "<td align=center Style=\"background-color : #c8ccc8; height : 25px;
                        border-left-width : 1px; 
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-left-color : #989898; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-left-style : solid; 
                        border-right-style : none; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                                    echo "min";
                                                echo "</td>";
                                                echo "<td align=center Style=\"background-color : #c8ccc8; height : 25px;
                        border-left-width : 1px; 
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-left-color : #989898; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-left-style : solid; 
                        border-right-style : none; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                                    echo "max";
                                                echo "</td>";
                                                echo "<td align=center Style=\"background-color : #c8ccc8;
                        border-left-width : 1px; 
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-left-color : #989898; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-left-style : solid; 
                        border-right-style : none; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                                    echo "N";
                                                echo "</td>";
                                                echo "<td align=center Style=\"background-color : #c8ccc8;
                        border-left-width : 1px; 
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-left-color : #989898; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-left-style : solid; 
                        border-right-style : solid; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                echo "mean";
                            echo "</td>";
                        echo "</tr>";
    
//                  echo "<pre>";
//                  print_r($meanArr);
                    foreach ($meanArr as $dataRow) {
                    if ($dataRow[4] > 0) {
                        echo "<tr>";
                            echo "<td Style=\"padding-left : 25px;
                          border-left-width : 1px; 
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-left-color : #989898; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-left-style : solid; 
                          border-right-style : none; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo $dataRow[5];
                          //                            $answer_number_array = explode(" ",$answer_label_array[0],2);
                          //                            $answer_number_item = $answer_number_array[0]; 
                                                echo "</td>";
                                                echo "<td align=center Style=\"height : 25px;
                          border-left-width : 1px; 
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-left-color : #989898; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-left-style : solid; 
                          border-right-style : none; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                            $answer_percent = ($dataRow[4] - $graph_min) * 100 / ($graph_max - $graph_min);
                                                            $answer_percent_1st = 100 - $answer_percent - 2;
                                                            $answer_percent_2st = 100 - $answer_percent_1st - 4;
                                                            echo "<table border=0 width=60px cellpadding=0 cellspacing=0><tr>";
                                                            echo "<td width=$answer_percent_2st%></td>";
                                                            echo "<td width=4% Style=\"font-size : 1px; height : 12px; background-color : #004AA0; 
                            border-left-width : 1px; 
                            border-right-width : 1px; 
                            border-top-width : 1px; 
                            border-bottom-width : 1px; 
                            border-left-color : #989898; 
                            border-right-color : #989898; 
                            border-top-color : #989898; 
                            border-bottom-color : #989898; 
                            border-left-style : solid; 
                            border-right-style : solid; 
                            border-top-style : solid; 
                            border-bottom-style : solid;
                            \">1</td>";
                                                            echo "<td width=$answer_percent_1st%></td></tr></table>";
                                                echo "</td>";
                                                echo "<td align=center Style=\"
                          border-left-width : 1px; 
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-left-color : #989898; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-left-style : solid; 
                          border-right-style : none; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo $dataRow[1];
                                                echo "</td>";
                                                echo "<td align=center Style=\"
                          border-left-width : 1px; 
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-left-color : #989898; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-left-style : solid; 
                          border-right-style : none; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo $dataRow[2];
                                                echo "</td>";
                                                echo "<td align=center Style=\"
                          border-left-width : 1px; 
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-left-color : #989898; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-left-style : solid; 
                          border-right-style : none; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo $dataRow[3];
                                                echo "</td>";
                                                echo "<td align=center Style=\"
                          border-left-width : 1px; 
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-left-color : #989898; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-left-style : solid; 
                          border-right-style : solid; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo str_replace(".",$decimal_separator,round($dataRow[4],2));
                                                echo "</td>";
                                            echo "</tr>";
                                                }
                    }
                    echo "</table><br><br><br><br>";    
                }
            }
return;
           // else //for scale with checkboxes!!!
            {   //Igor 31.5.2011 : this is now basicly multi response with legend!
                $numAns = count($answers);
                $numLeg = count($legend);
               
                $rowCount = 0;
                foreach ($fields as $ansField) {                

					//20150803 Če ima odgovor vrednos 0 v statistiki pokaže kot da za ta odgvor ni v bazi zapisov čeprav so. Ta pogoj sem odstranil da stvar deluje
	                $validAnsCond = "1";
    	        //    $validAnsCond = "$ansField>0";
        	    //  $ansField = $rowQuestion['q_name'];
            	    $sql = "SELECT $ansField AS variable,  count(*) AS freq, $ansField AS id, count(*)*$ansField AS multi_row FROM $tmpName WHERE $validAnsCond $this->filter GROUP BY $ansField";
                
                    If (!$resStat = $this->db->SQLexecute($sql)) {
                        //  Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
                            echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
                            exit;   
                    }
                    $totalN = 0;
                    
                    while ($rowStat = $this->db->fetchArray($resStat))
                    {
                        $val = $rowStat[0];
                        
                        $struct[$rowCount] = $rowStat[1];
            
                    }
                    //$struct[$rowCount]['tN'] = $totalN;
                    $rowCount++;
                    
                }
                //we get the totalN with an SQL statement
                
                //  print_r($struct); exit;
                    $legCount = 0;
                
                    foreach ($legend as $leg) {
                        $arr = array();
                        $totalOr = array();
                        foreach ($answers as $key=>$ansTmp) {
                            $totalOr[] = $fields[$key * $numAns + $legCount]." > 0";    
                            $freq = $struct[ $key * $numAns + $legCount ];
                            if(!$freq)
                            {
                                $freq = 0;  
                            }
                            $arr[] = array( $ansTmp[1], $freq,$freq*100 ,strip_tags( substr($ansTmp[1],0,50)) );
                        
                        }

                        $sqlTotalN =  "SELECT count(*) AS total_N FROM $tmpName WHERE ( ".implode(' OR ',$totalOr). " ) $this->filter"; 
                        If (!$resTotalN = $this->db->SQLexecute($sqlTotalN)) {
                            //  Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
                                echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
                                exit;   
                        }
                        $totalN = $this->db->fetchArray($resTotalN);
                        $totalN = $totalN[0]; 
                        
                        
                        if($totalN == 0) {
                            $numerusLabel = 0;
                            $totalN = 1;
                        } else 
                            $numerusLabel = $totalN;
                        
                        for ($i=0;$i<count($arr);$i++ )
                        {
                            $arr[$i][2] /= $totalN; 
                        }

                        $legCount++;
                    }//return $arr;
                
                                //ump($retGrids);
                                
                return "{title : '".$title."',items:[ " .implode(',',$retGrids)." 
                ]}
                  ";
            }
        
    }
    
	public function createStatistics($rowQuestion ,$tmpName = 'warpitStatistic' )	
	{
	  /*  print "<pre>";
        var_dump($this);
        print "</pre>";
		*/   
		   	$meanArr = array();
		  //$q = Question::createQuestion($rowQuestion['tip_sql']);
		   	$fields = $this->getStructureFields($rowQuestion,false);
		   	
		   	$openAns = $rowQuestion['open_answers'];
            //20150602 Tanis upoštevamo $missing_values
		    if(strlen($this->missing_values) > 0)
           	    $missing_values = explode(':', $this->missing_values);
		 /**/
		   	//we get the answers as an array ordered sequentely (id is NOT the key)
		   	$answers = $this->answerToArray($rowQuestion['odg_sql']);
		   	
		   	//we get the legend keyed by id's
		   	$legend = $this->answerToArray($rowQuestion['leg_sql']);
		  	//print_r($fields); exit;
		  	$k = 0; 
		  	if($this->HTMLstat)
		  	{
		  		$title =  ($this->showVar ? $rowQuestion['q_name'].': ' : '') . $rowQuestion['vpr_sql'] ;
		   	
		  	$htmlTitle1 =	"<table width=660 border=0 cellspacing=0 cellpadding=0>
  			<tr>";
	
			$htmlTitle2 = ' align="center" style="background-color : #004AA0; color : #ffffff; padding-left : 5px; height : 30px; 
			    border-left-width : 1px; 
			    border-right-width : 1px; 
			    border-top-width : 1px; 
			    border-bottom-width : 1px; 
			    border-left-color : #989898; 
			    border-right-color : #989898; 
			    border-top-color : #989898; 
			    border-bottom-color : #989898; 
			    border-left-style : solid; 
			    border-right-style : solid; 
			    border-top-style : solid; 
			    border-bottom-style : solid;
			    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
			    FONT-SIZE: 12px;
			    ">'.$title.'</td></tr>';
			echo $htmlTitle1.'<td colspan="5"'.$htmlTitle2;
		  	}
		  	
		  	$title =  json_encode( ($this->showVar ? $rowQuestion['q_name'].': ' : '') . $rowQuestion['vpr_sql'] );//echo 'TITLE: '.$title;
		   	$graph_min = 999999;
			$graph_max = 0;
		  //echo "Row question(les_sql): ".$rowQuestion['les_sql'];
		  	if($rowQuestion['les_sql'] != 4 )
		  	{
		  	    
             
			foreach ($fields as $ansField) {//gre skozi vsak odgovor
				$arr = array();
				//20150803 Če ima odgovor vrednos 0 v statistiki pokaže kot da za ta odgvor ni v bazi zapisov čeprav so. Ta pogoj sem odstranil da stvar deluje
                $validAnsCond  = "1";
			//	$validAnsCond = "$ansField > 0";
			     
				//echo $ansField;
				$struct = array();
				//for each field (answer) we count the freuqency of selected legend options
				//e.g if legend is 1 bad, 2 ,3 ,4 , 5 good : we count how many times 1 was selected for this answer.
				
				$missingCnd = "";
				//if($missing_values) $missingCnd = " AND $ansField NOT IN(" . implode(",", $missing_values) . ")";
				$sql = "SELECT $ansField AS variable,  count(*) AS freq, count(*)*$ansField AS multi_row FROM $tmpName WHERE $validAnsCond $missingCnd  $this->filter GROUP BY $ansField";
				
				//echo $sql.' '.'<br/>';
				If (!$resStat = $this->db->SQLexecute($sql)) {
					//	Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
						echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
						exit;	
				}
				$totalN = 0;
				$totalMean = 0;
				$min = 999999;
				$max = 0;
				while ($rowStat = $this->db->fetchArray($resStat)) //gre skozi eno legendo enega vpra?anja, zabele?i min, max ter totalN
				{
					//$val is the id of the selected legend(3 good) has value of 3
					$val = $rowStat[0];
					//we count the total number of answers (this is valid only for normal scale and singleselect)
					$totalN += $rowStat[1];
					//we save the the freq in an array and use the id as key, so that we can fetch it up when we go trough the legend
					$struct[ $val ] = $rowStat[1];
					//we calculate the mean and save the min and max values!
					$totalMean += $rowStat[2];
					if($val < $min)
						$min = $val;
					if ($val > $max)
						$max = $val;
					if($min < $graph_min)
						$graph_min = $min;
					if($graph_max < $max)
						$graph_max = $max;
				}		
			
				//ump($struct);
				if($totalN == 0) {
					$numerusLabel = 0;
					$totalN = 1;
				} else 
					$numerusLabel = $totalN;	
						$minLegendVal = 999999;
						$maxLegendVal = 0;
						foreach ($legend as $item) {
								$key = $item[0];
								$ans = $item[1]; 
						//now we go through the whole legend (so that we also show legend values that were never selected)
						//the $legend arrays uses id as keys so we can use the key to fetch the freq from $struct 	
							$freq = $struct[$key];
							if(!$freq)
							{
								$freq = 0;	
							}
							//$arr will be used as the data store for the grid and chart
							$arr[] = array( $ans, $freq,$freq/$totalN*100 ,strip_tags( substr($ans,0,50)) );
							
							//we get the highest legend numeric value, used for graph lower and upper limit scale
							if($key < $minLegendVal)
								$minLegendVal = $key;
							if($key > $maxLegendVal)
								$maxLegendVal = $key;
							
						}//ump($arr);//v vsakem $arr so frekvence za (bad,good,very good ...) od enega odgovora in enega columna 
					//20150602 Tanis to se sedaj izračuna posebaj 	
				//	$meanArr[] = array( $answers[$k][1] , $min ,$max , $totalN , $totalMean / $totalN ,strip_tags( substr($answers[$k][1],0,50))  );
					//echo 'totalN: '.$totalN.' totalMean: '.$totalMean;//exit;
					//ump($meanArr);
					//this functions creates the grid and chart
					$ansTitle = $answers[$k][1];
					if(!$this->HTMLstat)
						$ansTitle = substr( json_encode($answers[$k][1]),1,-1 );
					$retGrids[] = $this->createStatisticsGridChart($arr,'',$ansTitle. " (N = $numerusLabel ) ");
					$k++;	
					//ump($retGrids);exit;
				}
                //20150602 Tanis ponovno izračunamo vse, zato da tokrat upoštevamo še missing values
                $k = 0;
                foreach ($fields as $ansField) {//gre skozi vsak odgovor
                                $arr = array();
								//20150803 Če ima odgovor vrednos 0 v statistiki pokaže kot da za ta odgvor ni v bazi zapisov čeprav so. Ta pogoj sem odstranil da stvar deluje
                                $validAnsCond  = "1";
                                //$validAnsCond  = "$ansField>0";
                                //echo $ansField;
                                $struct = array();
                                //for each field (answer) we count the freuqency of selected legend options
                                //e.g if legend is 1 bad, 2 ,3 ,4 , 5 good : we count how many times 1 was selected for this answer.
                                
                                $missingCnd = "";
                                if($missing_values) $missingCnd = " AND $ansField NOT IN(" . implode(",", $missing_values) . ")";
                                $sql = "SELECT $ansField AS variable,  count(*) AS freq, count(*)*$ansField AS multi_row FROM $tmpName WHERE $validAnsCond $missingCnd  $this->filter GROUP BY $ansField";
                                
                                //echo $sql.' '.'<br/>';
                                If (!$resStat = $this->db->SQLexecute($sql)) {
                                    //  Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
                                        echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
                                        exit;   
                                }
                                $totalN = 0;
                                $totalMean = 0;
                                $min = 999999;
                                $max = 0;
                                while ($rowStat = $this->db->fetchArray($resStat)) //gre skozi eno legendo enega vpra?anja, zabele?i min, max ter totalN
                                {
                                	
                                    //$val is the id of the selected legend(3 good) has value of 3
                                    $val = $rowStat[0];
                                    //we count the total number of answers (this is valid only for normal scale and singleselect)
                                    $totalN += $rowStat[1];
                                    //we save the the freq in an array and use the id as key, so that we can fetch it up when we go trough the legend
                                    $struct[ $val ] = $rowStat[1];
                                    //we calculate the mean and save the min and max values!
                                    $totalMean += $rowStat[2];
                                    if($val < $min)
                                        $min = $val;
                                    if ($val > $max)
                                        $max = $val;
                                    if($min < $graph_min)
                                        $graph_min = $min;
                                    if($graph_max < $max)
                                        $graph_max = $max;
                                }       

								// Borut, variance, 2015.10.02
								$sql = "SELECT $ansField AS variable,  VAR_SAMP($ansField) AS variance_sample, VAR_POP($ansField) AS variance_population FROM $tmpName WHERE $validAnsCond $missingCnd  $this->filter";
                                //echo $sql.' '.'<br/>';
                                If (!$resStat = $this->db->SQLexecute($sql)) {
                                    //  Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
                                        echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
                                        exit;   
                                }
                                while ($rowStat = $this->db->fetchArray($resStat)) //gre skozi eno legendo enega vprasanja, zabelezi min, max ter totalN
								{
									$var_samp = $rowStat[1];
									$var_pop = $rowStat[2];
								}
								// Borut end variance
								                            
                                //ump($struct);
                                if($totalN == 0) {
                                    $numerusLabel = 0;
                                    $totalN = 1;
                                } else 
                                    $numerusLabel = $totalN;    
                                        $minLegendVal = 999999;
                                        $maxLegendVal = 0;
                                        foreach ($legend as $item) {
                                                $key = $item[0];
                                                $ans = $item[1]; 
                                        //now we go through the whole legend (so that we also show legend values that were never selected)
                                        //the $legend arrays uses id as keys so we can use the key to fetch the freq from $struct   
                                            $freq = $struct[$key];
                                            if(!$freq)
                                            {
                                                $freq = 0;  
                                            }
                                            //$arr will be used as the data store for the grid and chart
                                            $arr[] = array( $ans, $freq,$freq/$totalN*100 ,strip_tags( substr($ans,0,50)) );
                                            
                                            //we get the highest legend numeric value, used for graph lower and upper limit scale
                                            if($key < $minLegendVal)
                                                $minLegendVal = $key;
                                            if($key > $maxLegendVal)
                                                $maxLegendVal = $key;
                                            
                                        }//ump($arr);//v vsakem $arr so frekvence za (bad,good,very good ...) od enega odgovora in enega columna 
                                    //echo "pridem do tega arr?<br>";    
                                    $meanArr[] = array( $answers[$k][1] , $min ,$max , $totalN, $totalMean / $totalN ,strip_tags( substr($answers[$k][1],0,50)), $var_samp, $var_pop );
                                    //echo 'totalN: '.$totalN.' totalMean: '.$totalMean;//exit;
                                    //ump($meanArr);
                                    //this functions creates the grid and chart
                                    $ansTitle = $answers[$k][1];
                                    if(!$this->HTMLstat)
                                        $ansTitle = substr( json_encode($answers[$k][1]),1,-1 );
                                    //$retGrids[] = $this->createStatisticsGridChart($arr,'',$ansTitle. " (N = $numerusLabel ) ");
                                    $k++;   
                                    //ump($retGrids);exit;
                }
                //END 20150602 Tanis 

				//ump($meanArr);
				//ump($retGrids);
				foreach($answers as $answ)
					$answ_arr[] = $answ[1];
					
				if($rowQuestion['les_sql'] == 2)//if it is scale with (more) drop down columns per answer
					$graphLeg = $this->answerToArray($rowQuestion['atr_sql']); //extract column names
				else
				if($rowQuestion['les_sql'] == 5)// if it is scale with inverted scale 
					$graphLeg = $this->answerToArray($rowQuestion['leg_sql']);//extract column names
				else 	
					$graphLeg = null;	
					
				$statData = array(
					'title'  => $title, 
					'answers' => $answ_arr,
					'legend' => $graphLeg, 
					'series'   => $meanArr,
					'les_sql' => $rowQuestion['les_sql'], //to determine the subtype of scale question
					'numerusLabel' => 'N = '.$numerusLabel,
					'graphMax' => $maxLegendVal,
					'graphMin' => $minLegendVal
				);
				 
				if(!$this->HTMLstat)
					return $statData;
				//return $meanArr;
				//********************************************************************************************/////
				//********************************************************************************************/////
				//********************************************************************************************/////
				//********************************************************************************************/////
				//********************************************************************************************/////
				//********************************************************************************************/////
				
				
				//print_r($meanArr);
				//OLD EXTJS GRAPHS .... DEPRECATED
				if(!$this->HTMLstat)
				{//include_once (PATH_TO_ROOT."_class/class.Extjs_grid.php");
//						//we create an addition grid and chart for the minmax
//						$grid = new MakeGrid();
//							$grid->addColumn('variable'," Min Max ");
//							$grid->addColumn('min','min')->width(50);
//							$grid->addColumn('max','max')->width(50);
//							$grid->addColumn('totalN','N');
//							$grid->addColumn('mean','mean');
//							$grid->addColumn('varShort');
//							$grid->addConfig('autoHeight','true')
//								->addConfig('columnWidth','.5')
//								->setAutoExpand('variable')
//							;
//							$grid->dataArray = "". json_encode($meanArr)."" ;
//						//	$grid->dataArray = json_encode($arr) ;
//							
//							
//							echo $grid->createGrid();
//							
//							$numRows = count($meanArr);
//							$height = $numRows < 3 ? 80 : ( $numRows*21 + 25 );
//							
//						return "{title : ".$title.",items:[ " .implode(',',$retGrids)." 
//						]}, {
//							title : ".$title."+' - mean value' ,
//							items:[
//										{$grid->getName()} ,
//										{
//								            xtype: 'linechart',
//								            columnWidth: .5,
//								          // width:400,
//								           height:$height,
//								            store: {$grid->getStoreName()},
//								            yField: 'mean',
//								            xField: 'varShort',
//								            series: [{
//												style: {color:0x0094da, size:10}
//												}]
//										}
//											],
//										
//										layout:'column'
//						}
//						  ";
				}
				else 
				{//draw the min max table!!!
					if (!$decimal_separator) $decimal_separator = "."; 
		
						echo $htmlTitle1.'<td colspan="9"'.$htmlTitle2;
					 echo "<td width=350px Style=\"background-color : #c8ccc8; padding-left : 5px;
					    border-left-width : 1px; 
					    border-right-width : 1px; 
					    border-top-width : 1px; 
					    border-bottom-width : 1px; 
					    border-left-color : #989898; 
					    border-right-color : #989898; 
					    border-top-color : #989898; 
					    border-bottom-color : #989898; 
					    border-left-style : solid; 
					    border-right-style : none; 
					    border-top-style : none; 
					    border-bottom-style : solid;
					    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					    FONT-SIZE: 12px;
					    \">";
					    							echo "Min: $graph_min, Max: $graph_max";
					    						echo "</td>";
					    						echo "<td width=80px align=center Style=\"background-color : #c8ccc8; height : 25px;
					    border-left-width : 1px; 
					    border-right-width : 1px; 
					    border-top-width : 1px; 
					    border-bottom-width : 1px; 
					    border-left-color : #989898; 
					    border-right-color : #989898; 
					    border-top-color : #989898; 
					    border-bottom-color : #989898; 
					    border-left-style : solid; 
					    border-right-style : none; 
					    border-top-style : none; 
					    border-bottom-style : solid;
					    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					    FONT-SIZE: 12px;
					    \">";
					    							echo "mean";
					    						echo "</td>";
					    						echo "<td align=center Style=\"background-color : #c8ccc8; height : 25px;
					    border-left-width : 1px; 
					    border-right-width : 1px; 
					    border-top-width : 1px; 
					    border-bottom-width : 1px; 
					    border-left-color : #989898; 
					    border-right-color : #989898; 
					    border-top-color : #989898; 
					    border-bottom-color : #989898; 
					    border-left-style : solid; 
					    border-right-style : none; 
					    border-top-style : none; 
					    border-bottom-style : solid;
					    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					    FONT-SIZE: 12px;
					    \">";
					    							echo "min";
					    						echo "</td>";
					    						echo "<td align=center Style=\"background-color : #c8ccc8; height : 25px;
					    border-left-width : 1px; 
					    border-right-width : 1px; 
					    border-top-width : 1px; 
					    border-bottom-width : 1px; 
					    border-left-color : #989898; 
					    border-right-color : #989898; 
					    border-top-color : #989898; 
					    border-bottom-color : #989898; 
					    border-left-style : solid; 
					    border-right-style : none; 
					    border-top-style : none; 
					    border-bottom-style : solid;
					    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					    FONT-SIZE: 12px;
					    \">";
					    							echo "max";
					    						echo "</td>";
					    						echo "<td align=center Style=\"background-color : #c8ccc8;
					    border-left-width : 1px; 
					    border-right-width : 1px; 
					    border-top-width : 1px; 
					    border-bottom-width : 1px; 
					    border-left-color : #989898; 
					    border-right-color : #989898; 
					    border-top-color : #989898; 
					    border-bottom-color : #989898; 
					    border-left-style : solid; 
					    border-right-style : none; 
					    border-top-style : none; 
					    border-bottom-style : solid;
					    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					    FONT-SIZE: 12px;
					    \">";
					    							echo "N";
					    						echo "</td>";
					    						echo "<td align=center Style=\"background-color : #c8ccc8;
					    border-left-width : 1px; 
					    border-right-width : 1px; 
					    border-top-width : 1px; 
					    border-bottom-width : 1px; 
					    border-left-color : #989898; 
					    border-right-color : #989898; 
					    border-top-color : #989898; 
					    border-bottom-color : #989898; 
					    border-left-style : solid; 
					    border-right-style : solid; 
					    border-top-style : none; 
					    border-bottom-style : solid;
					    FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					    FONT-SIZE: 12px;
					    \">";
    							echo "mean";
    						echo "</td>";
                            // 20150602 Tanis  add missings
                            echo "<td align=center Style=\"background-color : #c8ccc8;
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-right-style : solid; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                echo "missings";
                            echo "</td>";
                             //END 20150602 Tanis  add missings
                             // 20151002 Tanis  add variances
                            echo "<td align=center Style=\"background-color : #c8ccc8;
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-right-style : solid; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                echo "variance sample";
                            echo "</td>";
                            echo "<td align=center Style=\"background-color : #c8ccc8;
                        border-right-width : 1px; 
                        border-top-width : 1px; 
                        border-bottom-width : 1px; 
                        border-right-color : #989898; 
                        border-top-color : #989898; 
                        border-bottom-color : #989898; 
                        border-right-style : solid; 
                        border-top-style : none; 
                        border-bottom-style : solid;
                        FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                        FONT-SIZE: 12px;
                        \">";
                                echo "variance population";
                            echo "</td>";
                             //END 20150602 Tanis  add variances
    					echo "</tr>";
    
//					echo "<pre>";
//					print_r($meanArr);
					foreach ($meanArr as $dataRow) {
					if ($dataRow[4] > 0) {
      					echo "<tr>";
      						echo "<td Style=\"padding-left : 25px;
					      border-left-width : 1px; 
					      border-right-width : 1px; 
					      border-top-width : 1px; 
					      border-bottom-width : 1px; 
					      border-left-color : #989898; 
					      border-right-color : #989898; 
					      border-top-color : #989898; 
					      border-bottom-color : #989898; 
					      border-left-style : solid; 
					      border-right-style : none; 
					      border-top-style : none; 
					      border-bottom-style : solid;
					      FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					      FONT-SIZE: 12px;
					      \">";
					      							echo $dataRow[5];
					      //							$answer_number_array = explode(" ",$answer_label_array[0],2);
					      //							$answer_number_item = $answer_number_array[0]; 
					      						echo "</td>";
					      						echo "<td align=center Style=\"height : 25px;
					      border-left-width : 1px; 
					      border-right-width : 1px; 
					      border-top-width : 1px; 
					      border-bottom-width : 1px; 
					      border-left-color : #989898; 
					      border-right-color : #989898; 
					      border-top-color : #989898; 
					      border-bottom-color : #989898; 
					      border-left-style : solid; 
					      border-right-style : none; 
					      border-top-style : none; 
					      border-bottom-style : solid;
					      FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					      FONT-SIZE: 12px;
					      \">";
					      									$answer_percent = ($dataRow[4] - $graph_min) * 100 / ($graph_max - $graph_min);
					      									$answer_percent_1st = 100 - $answer_percent - 2;
					      									$answer_percent_2st = 100 - $answer_percent_1st - 4;
					        								echo "<table border=0 width=60px cellpadding=0 cellspacing=0><tr>";
					        								echo "<td width=$answer_percent_2st%></td>";
					      									echo "<td width=4% Style=\"font-size : 1px; height : 12px; background-color : #004AA0; 
					        border-left-width : 1px; 
					        border-right-width : 1px; 
					        border-top-width : 1px; 
					        border-bottom-width : 1px; 
					        border-left-color : #989898; 
					        border-right-color : #989898; 
					        border-top-color : #989898; 
					        border-bottom-color : #989898; 
					        border-left-style : solid; 
					        border-right-style : solid; 
					        border-top-style : solid; 
					        border-bottom-style : solid;
					        \">1</td>";
					        								echo "<td width=$answer_percent_1st%></td></tr></table>";
					      						echo "</td>";
					      						echo "<td align=center Style=\"
					      border-left-width : 1px; 
					      border-right-width : 1px; 
					      border-top-width : 1px; 
					      border-bottom-width : 1px; 
					      border-left-color : #989898; 
					      border-right-color : #989898; 
					      border-top-color : #989898; 
					      border-bottom-color : #989898; 
					      border-left-style : solid; 
					      border-right-style : none; 
					      border-top-style : none; 
					      border-bottom-style : solid;
					      FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					      FONT-SIZE: 12px;
					      \">";
					      							echo $dataRow[1];
					      						echo "</td>";
					      						echo "<td align=center Style=\"
					      border-left-width : 1px; 
					      border-right-width : 1px; 
					      border-top-width : 1px; 
					      border-bottom-width : 1px; 
					      border-left-color : #989898; 
					      border-right-color : #989898; 
					      border-top-color : #989898; 
					      border-bottom-color : #989898; 
					      border-left-style : solid; 
					      border-right-style : none; 
					      border-top-style : none; 
					      border-bottom-style : solid;
					      FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					      FONT-SIZE: 12px;
					      \">";
					      							echo $dataRow[2];
					      						echo "</td>";
					      						echo "<td align=center Style=\"
					      border-left-width : 1px; 
					      border-right-width : 1px; 
					      border-top-width : 1px; 
					      border-bottom-width : 1px; 
					      border-left-color : #989898; 
					      border-right-color : #989898; 
					      border-top-color : #989898; 
					      border-bottom-color : #989898; 
					      border-left-style : solid; 
					      border-right-style : none; 
					      border-top-style : none; 
					      border-bottom-style : solid;
					      FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					      FONT-SIZE: 12px;
					      \">";
					      							echo $dataRow[3];
					      						echo "</td>";
					      						echo "<td align=center Style=\"
					      border-left-width : 1px; 
					      border-right-width : 1px; 
					      border-top-width : 1px; 
					      border-bottom-width : 1px; 
					      border-left-color : #989898; 
					      border-right-color : #989898; 
					      border-top-color : #989898; 
					      border-bottom-color : #989898; 
					      border-left-style : solid; 
					      border-right-style : solid; 
					      border-top-style : none; 
					      border-bottom-style : solid;
					      FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
					      FONT-SIZE: 12px;
					      \">";
					      							echo str_replace(".",$decimal_separator,round($dataRow[4],2));
					      						echo "</td>";
                                                //20150602 Tanis  add missings
                                                echo "<td align=center Style=\"
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-right-style : solid; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo str_replace(':', ',', $this->missing_values);
                                                echo "</td>";
                                                //END 20150602 Tanis  add missings
                                                //20151002 Tanis  add variances
                                                echo "<td align=center Style=\"
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-right-style : solid; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                echo str_replace(".",$decimal_separator,round($dataRow[6],2));
                                                echo "</td>";
                                                echo "<td align=center Style=\"
                          border-right-width : 1px; 
                          border-top-width : 1px; 
                          border-bottom-width : 1px; 
                          border-right-color : #989898; 
                          border-top-color : #989898; 
                          border-bottom-color : #989898; 
                          border-right-style : solid; 
                          border-top-style : none; 
                          border-bottom-style : solid;
                          FONT-FAMILY: Vardana, Arial, Helvetica, sans-serif;
                          FONT-SIZE: 12px;
                          \">";
                                                    echo str_replace(".",$decimal_separator,round($dataRow[7],2));
                                                echo "</td>";
                                                //END 20150602 Tanis  add varainces
					      					echo "</tr>";
												}
					}

			if ($this->stat_show_filter_in || $this->stat_show_filter_out) {
						$statDescFont = "style=font-family:Vardana;font-size:12px;";
						echo "<tr>";
							echo "<td colspan=9 Style=\"background-color:#c8ccc8;padding-left:5px;height:25px;border-left-width:1px;border-right-width:1px;border-top-width:1px;border-bottom-width:1px;border-left-color:#989898;border-right-color:#989898;border-top-color:#989898;border-bottom-color:#989898;border-left-style:solid;border-right-style:solid;border-top-style:none;border-bottom-style:solid;FONT-FAMILY:Vardana, Arial, Helvetica, sans-serif;FONT-SIZE:12px;\">";
								echo "<table border=0 align=left>";
									//20151009 Tanis I have add fields for displaying filters
									if($this->stat_show_filter_in)
										echo "<tr><td $statDescFont>Filter in: </td><td $statDescFont>" . $this->fil_sql . "</td></tr>";
									if($this->stat_show_filter_out)
										echo "<tr><td $statDescFont>Filter out: </td><td $statDescFont>" . $this->con_sql . "</td></tr>";
									//20151009 Tanis END
								echo "</table>";
							echo "</td>";
						echo "</tr>";
					}
					echo "</table><br><br><br><br>";	
				}
		  	}
		  	else //for scale with checkboxes!!!
		  	{	//Igor 31.5.2011 : this is now basicly multi response with legend!
		  		$numAns = count($answers);
		  		$numLeg = count($legend);
		       
		  		$rowCount = 0;
		  		foreach ($fields as $ansField) {
		  			
					//20150803 Če ima odgovor vrednos 0 v statistiki pokaže kot da za ta odgvor ni v bazi zapisov čeprav so. Ta pogoj sem odstranil da stvar deluje
					$validAnsCond = "1";				
//					$validAnsCond = "$ansField>0";				
				
				//	$ansField = $rowQuestion['q_name'];
					$sql = "SELECT $ansField AS variable,  count(*) AS freq, $ansField AS id, count(*)*$ansField AS multi_row FROM $tmpName WHERE $validAnsCond $this->filter GROUP BY $ansField";
				
					If (!$resStat = $this->db->SQLexecute($sql)) {
						//	Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
							echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
							exit;	
					}
					$totalN = 0;
					
					while ($rowStat = $this->db->fetchArray($resStat))
					{
						$val = $rowStat[0];
						
						$struct[$rowCount] = $rowStat[1];
			
					}
					//$struct[$rowCount]['tN'] = $totalN;
					$rowCount++;
					
		  		}
		  		//we get the totalN with an SQL statement
		  		
				//	print_r($struct); exit;
					$legCount = 0;
				
					foreach ($legend as $leg) {
						$arr = array();
						$totalOr = array();
						foreach ($answers as $key=>$ansTmp) {
							$totalOr[] = $fields[$key * $numAns + $legCount]." > 0"; 	
							$freq = $struct[ $key * $numAns + $legCount ];
							if(!$freq)
							{
								$freq = 0;	
							}
							$arr[] = array( $ansTmp[1], $freq,$freq*100 ,strip_tags( substr($ansTmp[1],0,50)) );
						
						}

						$sqlTotalN =  "SELECT count(*) AS total_N FROM $tmpName WHERE ( ".implode(' OR ',$totalOr). " ) $this->filter"; 
						If (!$resTotalN = $this->db->SQLexecute($sqlTotalN)) {
							//	Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
								echo "alert(\"SQL problem: ".$this->db->getError()."\" );";
								exit;	
						}
						$totalN = $this->db->fetchArray($resTotalN);
						$totalN = $totalN[0]; 
						
						
						if($totalN == 0) {
							$numerusLabel = 0;
							$totalN = 1;
						} else 
							$numerusLabel = $totalN;
						
						for ($i=0;$i<count($arr);$i++ )
						{
							$arr[$i][2] /= $totalN; 
						}
//						$grid = new MakeGrid();
//						$grid->addColumn('variable', $leg[1]. " (N = $numerusLabel ) ");
//						$k++;
//						$grid->addColumn('freq','N')->width(30);
//						$grid->addColumn('proc','%')->width(30)->type('int');
//						$grid->addColumn('varShort');
//						$grid->addConfig('autoHeight','true')
//							->addConfig('columnWidth','.5')
//							->setAutoExpand('variable')
//						;
//						$grid->dataArray = "". json_encode($arr)."" ;
					//	$grid->dataArray = json_encode($arr) ;
						//ump($arr);
						
						//echo $grid->createGrid();
						
//						$numRows = count($arr);
//						$height = $numRows < 3 ? 80 : ( $numRows*21 + 25 );
//						
//						$retGrids[] = "{ 
//						items:[
//						{$grid->getName()} ,
//						{
//				            xtype: 'barchart',
//				            columnWidth: .5,
//				          // width:400,
//				           height: $height,
//				            store: {$grid->getStoreName()},
//				            xField: 'freq',
//				            yField: 'varShort',
//				            series: [{
//								style: {color:0x0094da, size:10}
//								}]
//						}
//							],
//						
//						layout:'column'
//						}";
						$legCount++;
					}//return $arr;
				
								//ump($retGrids);
								
				return "{title : '".$title."',items:[ " .implode(',',$retGrids)." 
				]}
				  ";
		  	}
	}
	
	protected function designerDrawLegend($legRow,$legArray)
        {
            
            if($this->showLegend===false)
                return;
            //the width of the control must be divided by the number of legends
                    
                    $tbl .= "<tr>";
                    foreach ($legRow->children() as $child) {

                    $attr = $child->attributes();
                            switch ($attr['type'])
                            {
                                case 20:
                                    if($this->showVal)
                                        {
                                        $size = $this->legStyle[20];
                                        $tbl .= "<td $size>&nbsp;</td>";
                                        }
                                break;
                                case 21:
                                    $size = $this->legStyle[21];
                                    $tbl .= "<td $size>&nbsp;</td>";
                                    
                                break;
                                case 22:
                                     foreach ($legArray as $index => $ans) {
                                    $hmm = $ans[1];
                                    $size = $this->legStyle[22];
                                    //tanis 
                                    if($this->legArrCnt)
                                        $tbl .= "<td $size colspan='$this->legArrCnt'>$hmm</td>";
                                    else
                                        $tbl .= "<td $size>$hmm</td>";
                                    
                                    //$tbl .= "<td $size><table><tr><td>$hmm</td></tr></table></td>";
                                
                                }
                                            
                                break;
                            }
                    
                        
                    }
                    // 2014.11.12 Borut add this in case we have split answers (not a good idea without IF... correct it once)
                    $tbl .= "<td></td>";
                    
                    $tbl .= "</tr>";
                    return $tbl;
        }
	
	public function createAnswerGrid()
	{
		$this->createAnswerGridClass();
        
        //20150224 add by Tanis 
        $this->grid->addColumn('miss_val','Missings')->type('checkColumn')->width(60);
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		
		$row = $this->db->fetchAssoc($this->db->SQLexecute("SELECT les_sql FROM $this->tableName WHERE id = $this->id"));
		$this->les_sql = $row['les_sql'];
		if($this->les_sql == 5)//inverted grid have also nogo together column!
		{
			$this->grid->addColumn('nogo','Nogo Together')->type('checkColumn');
		 	$this->grid->addConfig('saveFunction',"function(close){
			var str = new Array();
			var ng = new Array();
			var hasFilter = false;
			var filter = new Array();
			var open = new Array();
			var grp = new Array();
			var miss_val = new Array();
			$this->grid.stopEditing();
			{$this->grid->getName()}.getStore().each(function(rec){
					str.push(rec.data.pos +' '  + rec.data.ans);
					if(rec.data.nogo)
					{
						ng.push(rec.data.pos);
					}
					if(rec.data.filCnd || rec.data.filter)
					{
						hasFilter = true;
					}
					filter.push( (rec.data.filter ? '1' : '0')+ (rec.data.filCnd ? rec.data.filCnd : '' )     );
					if(rec.data.open)
					{
						open.push(rec.data.pos);
					}
					
					if(rec.data.miss_val)
                    {
                        miss_val.push(rec.data.pos);
                    }
					
					grp.push(rec.data.group);	
					
				});
			Ext.Ajax.request(
							{url:'webcati/_ajax//buildQuestionare/ajax.buildQuestionnaire.php',params:{action:'updateAnswers',RMtable:'$this->tableName',
							id:$this->id,database:'".$this->dataBase."',dataIndex: '$this->dataIndex'
							,value:str.join('/'),nogo:ng.join() ,filter_answer : hasFilter ? filter.join('<!>'):'',
							open_data : open.join(':'),
							rotFrom:$this->grid.RMrotFrom,
							miss_val_data: miss_val.join(':'),
							rotTo:$this->grid.RMrotTo,
							groups:grp.join(),
							id_language:'".$_POST['id_language']."' }
							,success:function(resp,opt){
									successFunc(resp,opt,close);
							}});
			
			}")
			->addButton('Save',"function(){ $this->grid.saveFunction(false); }")
			->addButton('Save&amp;Close',"function(){ $this->grid.saveFunction(true); }")
			->addButton('Cancel',"function(){
				Ext.getCmp('wcbqTabPanel_$this->tableName').remove({$_POST['name']});
			}");
		 	$ng = $_POST['nogo_answers'];
		 	echo "
		 			var ng = '$ng'.split(',');
		 		//	var d = {$this->grid->dataArray}; 
		 			for(var i=0;i<d.length;i++)
		 			{
		 				if(d[i][0] == ng[0])
		 				{
		 					d[i].push(true);
		 					ng.shift();
						}
						else 
						{
							d[i].push(false);
						}
		 				//console.log(d[i]);
		 			}
		 			// {$this->grid->getName()}.getStore().loadData(d);
		 			"; 
			
		 	$this->createAnswerGridEcho();
		 	
		}
		else
		{
			$this->createAnswerGridButtons();
			$this->createAnswerGridEcho();
		}
		
		echo $this->grid->getName().".on('afteredit',function(e)
                {
                if(e.field == 'pos')
                {
                    var data = e.grid.getStore().getRange();
                    Ext.each(data, function(dat)
                    {
                        if(dat.get('pos') == e.value && e.record.id != dat.id)
                        {
                            Ext.Msg.show(
                            {
                                 title:'Info', 
                                 msg: 'Two answers can\'t have same value', 
                                 icon: Ext.MessageBox.INFO, 
                                 buttons: Ext.Msg.OK
                            });
                            e.record.set('pos', e.originalValue);
                        }
                    }    );
                }
                });";
		
		
	}
	
	
	/**
	 * Function for drawing the answers in a interview
	 *
	 * @return string
	 */
	
	public function designerDrawAnswers()
		{
			$dragValues = array();
			$dragScript = array();
				$fields = $this->getStructureFields();
			  		
			//	print_r($fields);
				$ansArr = $this->answerToArray( $this->odg_sql );
				$ansArr = $this->designerRotateAnswers($ansArr);
				$this->designerFilterAnswers($ansArr);
				
				
				
				//20150324 Added by Tanis: if we readRequiredQuestionVariables before ansToArray images doesn't show
				$legArr = $this->answerToArray($this->leg_sql);
				
				$tmpLegArr = array();
				foreach ($legArr as $leg)   
				{
				    // $leg[1] = $this->display->readRequiredQuestionVariables($leg[1]);
				     
				     $tmpLegArr[] = array("0" => $leg[0], "1" => $this->display->readRequiredQuestionVariables($leg[1])); 
			    }
				    
				$legArr = $tmpLegArr;
				$legArr = $this->designerRotateAnswers($legArr,true);
				   /* print "<pre>";
                var_dump($legArr);
                print "</pre>";*/
			
				$this->designerFilterAnswers($legArr,true);
				
				$atrArr = array(1); //array with one element so that the foreach statement will go around at least one time
				$openAns = explode(':',$this->open_answers);
				//for all other then comboboxes, we divide the control width number of legend ans
				if($this->les_sql != 2 && !(strlen($this->atr_sql) > 0 && $this->les_sql == 1))
					$divide = count($legArr);
				else if( trim( $this->atr_sql ))
				{
					//$atrArr = $this->answerToArray($this->display->readRequiredQuestionVariables( $this->atr_sql) );
					//20150324 Added by Tanis: if we readRequiredQuestionVariables before ansToArray images doesn't show
                    $atrArr = $this->answerToArray($this->atr_sql);
               
                    foreach ($atrArr as &$leg)  $leg[1] = $this->display->readRequiredQuestionVariables($leg[1]);
					$atrNum = count($atrArr);
					$atrArr = $this->designerRotateAnswers($atrArr,'atr');
					$this->designerFilterAnswers($atrArr,'atr');
					$divide = count( $atrArr );
					
				}
				else
				{
					$divide = 1;
					$atrNum = 1;
				}
				$this->designerDefineObjects($divide);
				$leaveQuestion = $this->display->engine->LeaveQuestion;
				//get field values so that we can reselect previously filled answers
				if( $leaveQuestion == false )
			  		$fieldsValues = $_POST['answers'];
			  	else
			  		$fieldsValues = $this->display->readStructureVariables($fields,'');
			  	
				
				$_SESSION['questionFields'] =array_merge($_SESSION['questionFields'], $fields);
				
			  	$tbl = "<table id=\"answTable_".$this->q_name."\" $this->mainStyle cellpadding=0 cellspacing=0 width=100%>";
			  	$counter = 1;
			  	//each but comboboxes have legend table (hmm...this will have to change when rotations come to play!)
			  	if(($this->les_sql != 2 &&  $this->les_sql != 7 && $this->les_sql != 8) || trim( $this->atr_sql) )
			  	{
			  		$this->legendCounter = -1;
			  		//the width of the control must be divided by the number of legends
			  		//tanis
			  		$this->legArrCnt = count($legArr);
			  		if($this->les_sql == 1 && trim($this->atr_sql))
			  		     $tbl .= $this->designerDrawLegend($this->legRow,$atrArr);
                    else
                        $tbl .= parent::designerDrawLegend($this->legRow, $this->les_sql == 2 ? $atrArr : $legArr);
			  		//$tbl .= $this->designerDrawLegend($this->legRow, $this->les_sql == 2 ? $atrArr : $legArr);
			  	      
                }
			  	else if($this->les_sql == 7)
			  	{
			  		//answers hold our data :)
  					$scData = explode('/',$this->leg_sql);
  					$leftData = explode(' ',$scData[0],2);
  					$minVal = $leftData[0];
  					$leftLabel = count($leftData) > 1 ? $leftData[1] : '';
  					
  					$rightData = explode(' ',$scData[1],2);
  					$maxVal = $rightData[0];
  					$rightLabel = count($rightData) > 1 ? $rightData[1] : '';
  					
  					
  					
			  		$tbl .= "<script type='text/javascript' src='javascript/wz_dragdrop.js'></script>
    					<script type='text/javascript' src='javascript/ratingscales.js'></script>";
			  	}
			  	else if($this->les_sql == 8)
			  	{
			  		
					// Drag ' n ' drop
					/*
					
		  		$pHeight = 100;
  				$pWidth = 100;
  				$pMargin = 10;	
  				$pBorder = 3;
				
				function compare_neutral($a, $b) {
					if (($a[0] > 100 && $b[0] > 100) || ($a[0] <= 100 && $b[0] <= 100)) {
						if ($a[0] == $b[0]) {
					        return 0;
					    }
					    return ($a[0] > $b[0]) ? -1 : 1;
					}
					else return ($a>100) ? -1 : 1;
				}
				$ansArr = array_reverse($ansArr);
				include PATH_TO_ROOT.'_config/cartConfig.php';
				
				$ddStyle = $this->evenStyle;
				$start = strpos($ddStyle[21], "\"") + 1;
				$end = strpos($ddStyle[21], "\"", $start);
				$str = substr($ddStyle[21], $start, $end - $start);
				
				$proj = $_SESSION['id_project'];
				$projId = substr($_SESSION['questionFields'][0], 0, strrpos($_SESSION['questionFields'][0], "_"));
				
				$boxWidth = isset($cartConfig[$proj][$projId]['cardProperties']['boxWidth']) ? $cartConfig[$proj][$projId]['cardProperties']['boxWidth'] : 120;
				$boxHeight = isset($cartConfig[$proj][$projId]['cardProperties']['boxHeight']) ? $cartConfig[$proj][$projId]['cardProperties']['boxHeight']: 90;
				// $fontSize = isset($cartConfig[$proj][$projId]['cardProperties']['fontSize']) ? $cartConfig[$proj][$projId]['cardProperties']['fontSize'] : 12;
				// $captionSize = isset($cartConfig[$proj][$projId]['basketProperties']['captionSize']) ? $cartConfig[$proj][$projId]['basketProperties']['captionSize'] : 14;
				$basketColor = isset($cartConfig[$proj][$projId]['basketProperties']['basketColor']) ? $cartConfig[$proj][$projId]['basketProperties']['basketColor'] : "E8DDCB";
				$neutralColor = isset($cartConfig[$proj][$projId]['basketProperties']['neutralColor']) ? $cartConfig[$proj][$projId]['basketProperties']['neutralColor'] : "CBE8D7";
				$shadowColor = isset($cartConfig[$proj][$projId]['cardProperties']['shadowColor']) ? $cartConfig[$proj][$projId]['cardProperties']['shadowColor'] : "888888";
				$baseColor = isset($cartConfig[$proj][$projId]['cardProperties']['baseColor']) ? $cartConfig[$proj][$projId]['cardProperties']['baseColor'] : "fcfcfc";
				$neutralPosition = isset($cartConfig[$proj][$projId]['basketProperties']['neutralPosition']) ? $cartConfig[$proj][$projId]['basketProperties']['neutralPosition'] : "right";
				
				$resetEnabled = isset($cartConfig[$proj][$projId]['resetEnabled']) ? $cartConfig[$proj][$projId]['resetEnabled'] : false;
				
				$layout = isset($cartConfig[$proj][$projId]["layout"]) ? $cartConfig[$proj][$projId]["layout"] : "vertical";	
				$cardType = isset($cartConfig[$proj][$projId]["cardsType"]) ? $cartConfig[$proj][$projId]["cardsType"] : 1;
				$cardDimension = isset($cartConfig[$proj][$projId]["cardDimension"]) ? $cartConfig[$proj][$projId]["cardDimension"] : array();
				$ansType = isset($cartConfig[$proj][$projId]["ansType"]) ? $cartConfig[$proj][$projId]["ansType"] : 1;
				// $inverse = isset($inverse[$proj]) ? $inverse[$proj] : false;
				
				$first = ($layout == "horizontal") ? "left" : "top";
				$second = ($layout == "horizontal") ? "right" : "bottom";
				
				if ($cardType == 1) $topHeight = $boxHeight+50;
				else if ($cardType == 2) $topHeight = $cardDimension['rows'] * $boxHeight + 50;
				// else if ($cardType == 3) $topHeight = $cardDimension['rows'] * $boxHeight + 20;
				
				$topWidth = ($cardType == 2) ? ($boxWidth * $cardDimension['columns'] + 50) : "";
				
				$BasketImage = $cartConfig[$proj][$projId]['basketProperties']['imagePath'];
				$BasketImageIE = $cartConfig[$proj][$projId]['basketProperties']['imageIEPath'];
				if ( $cartConfig[$proj][$projId]['basketProperties']['position'] == "right" ) $BasketPosition = "float: right;";
					elseif ($cartConfig[$proj][$projId]['basketProperties']['position'] == "center" ) $BasketPosition = "margin: 0 auto;";
				
				// $tbl .= "Layout: " . $layout . ", Card Type: " . $cardType . ", Card Dim: " . json_encode($cardDimension) . ", Answer Type: " . $ansType . "<br>";
				 
				$tbl .= '<script src='.PATH_TO_ROOT.'_support/jquery.ui.touch-punch.min.js></script>
				<style>
					#top { width:100%; height:'.$topHeight.'px;min-height:100px; }
					#bottom { width:100%;min-height:150px; }
					#left { width:210px;float:left; }
					#right { margin-left:50px;width:220px;float:left; }
					
					.outer { width:'.$topWidth.'px;height:'.$topHeight.'px; }
					.inner { float: left;width: '.$boxWidth.'px;height:'.$boxHeight.'px;margin-right: 5px;margin-bottom: 5px; }
					.inner li { list-style: none; }
					
					ul#app li { float:left; }
					#app { float:left;margin:10px auto 0;height:'.($boxHeight + 35).'px;background:url('.$BasketImage.');background-repeat: no-repeat; background-size: 100% 50px; background-position: left bottom; }
					.item { width:'.$boxWidth.'px;height:'.$boxHeight.'px;border:1px solid black;background-color:#'.$baseColor.';overflow:hidden;cursor:move;box-shadow: 5px 5px 2px #'.$shadowColor.'; }
					.box { '.$str.'padding:2px;padding-left:6px;width:92%;height:100%;text-align:left; }
					.caption { '.$str.'height:'.($boxHeight/2).'px; overflow: hidden; padding: 6px 3px; position: absolute; bottom:0; left:0; width:100%; background-color:#'.$basketColor.';-webkit-border-bottom-right-radius: 5px;-webkit-border-bottom-left-radius: 5px;-moz-border-radius-bottomright: 5px;-moz-border-radius-bottomleft: 5px;border-bottom-right-radius: 5px;border-bottom-left-radius: 5px; }
					.ncaption { '.$str.'height:'.($boxHeight/2).'px; overflow: hidden; padding: 6px 3px; position: absolute; bottom:0; left:0; width:100%; background-color:#'.$neutralColor.';-webkit-border-bottom-right-radius: 5px;-webkit-border-bottom-left-radius: 5px;-moz-border-radius-bottomright: 5px;-moz-border-radius-bottomleft: 5px;border-bottom-right-radius: 5px;border-bottom-left-radius: 5px; }
					
					.container { position: relative; width:'.($boxWidth+20).'px; float:left; margin:5px;padding:0px; }
					
					.cart { margin-left:0; height:'.($boxHeight+10).'px;padding:4px 2px;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;}
					ul.neutral{ list-style:none;padding:4px 8px; }
					ul.neutral li + li { margin-left:-'.($boxWidth+2).'px;}
					ul.neutral li { float:left; }
					ul.cart li { float:left; }
					ul.app { list-style:none; }
					ul.cart{ list-style:none;padding:4px 8px; }
					ul.cart li + li { margin-left:-'.($boxWidth+2).'px;}
					.delete { float:left;width:24px; margin-top:90px; height:24px; background-image: url(../_img/questions/delete.png);}
					.active { border: 1px solid #AAAAAA; }
					.test { position: absolute; }
				</style>
				<!--[if lte IE 8]>
				<style>
					#app { background-image: none !important;float:left;margin: 10px auto 0;height:'.($boxHeight + 35).'px;background:url('.$BasketImage.');background-repeat: no-repeat; background-size: 100% 50px; background-position: left bottom; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src="'.$BasketImageIE.'", sizingMethod="scale"); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\"'.$BasketImageIE.'\", sizingMethod=\"scale\")"; font-size: 1px; }
				</style>
				<![endif]-->
				<script>
					var App = {};
					App.items = [];
					App.cardType = "'.$cardType.'";
					App.ansType = "'.$ansType.'";
					App.inverse = "'.$inverse.'";
					App.width = "';
					
					$cnt = 52 + $boxWidth;
					
					if (count($ansArr) > 10) {
						$cnt += (count($ansArr)-11) *2;
						$cnt += 10 * 7;
					}
					else {
						$cnt += (count($ansArr)-1) * 7;
					}
					
					$tbl .= $cnt .'px";';
					
					if ($cardType == 2) {
						$tbl .= 'App.dimX=' . $cardDimension['columns'] . ';App.dimY='.$cardDimension['rows'].';';
					}
					
					$tbl .= '$(document).ready(function(){
					 	//cartdiv						
						//alert($("#cartdiv").width());
					 });
				</script>
				<div id="'.$first.'">';
				
				if ($cardType == 2) {
					$tbl .= '<div class="outer">';
					
					for ($i=0; $i<$cardDimension['rows']; $i++) {
						for ($j=0; $j<$cardDimension['columns']; $j++) {
							$tbl .= '<div id="row'.$i.'_'.$j.'" class="inner"></div>';
						}
					}
					
					$tbl .= '</div>';
				} else {
					$tbl .= '<ul id="app"></ul>';
				}
				
				if ($resetEnabled) $tbl .= '<div id="delete" class="delete"></div><div style="clear:both;"></div>';
				$tbl.= '</div>
				<div id="'.$second.'">';
				
				*/
		
			  	}
			  	if($this->les_sql == 5)
		  		{//we prepare the nogo tohether answer
		  			$nogoArr = explode(',',$this->multi_nogo_answers);
		  			$tbl .= "<script>
		  			function contains(a, obj) {
					  var i = a.length;
					  while (i--) {
					    if (a[i] === obj) {
					      return true;
					    }
					  }
					  return false;
					}
		  			var nogoArr = [".implode(',',$nogoArr)."] ;
		  			var names = [";
		  			foreach ($legArr as $index => $nvm) {

		  				$fldNames[] = "'answers[".trim( $fields[$index])."]'";
		  			}
		  			$tbl .= implode(',',$fldNames). "];
		  			var scaleInvert = {};
		  			 var f = document.forms['mainForm']; 
		  			if(typeof( scaleInvertNoGo) == 'undefined' ) scaleInvertNoGo = -1;
		  			function radioChecker(colInd,row,val) {
		  			var col = names[colInd];
		  			recodeClickEvents(f[col][row],1);
		  			if(f[col][row].disabled) return;
					f[col][row].checked = true;	";
		  		//we saved the previous selected
	  				//we disable all buttons in the folowing columns and enable all in the previous columns
	  				$testDis = true;
	  				if($testDis)
	  				{
	  				
	  					//WARNING!!! if a legend is hidden this does not work :(
	  						$tbl .= "
	  					if(contains(nogoArr,val)  )
	  					{ 
	  					for(var x=colInd+1;x<".count($legArr).";x++)
	  						for(var i=0;i<".count($ansArr). ";i++){
	  						
				  					f[names[x]][i].disabled=true;
				  					f[names[x]][i].checked=false;
	  					
	  						}
	  				scaleInvert[colInd] = -1; scaleInvertNoGo = row; return;}";
	  				
		  				$tbl .="if(typeof( scaleInvert[colInd] ) != 'undefined' &&  (scaleInvert[colInd]  == -1 || !f[ col ][ scaleInvert[colInd] ].disabled )   )
		  				{
		  				if(scaleInvert[colInd] != -1  )
		  				{ 
			  				 for(var x=colInd+1;x<".count($legArr).";x++)
			  				 { 
			  				     f[names[x] ][scaleInvert[colInd]].disabled=false;
			  							if(f[names[x] ][scaleInvert[colInd]].checked || x == scaleInvertNoGo) break;
	  						}	
			  							";
				  			$tbl .="}
	  					else //previous selected was a nogo together...we must enable all...almost all :(
	  					{";
	  						$tbl .= "
	  						for(var i=0;i<".count($ansArr). ";i++)
	  							//we go from trough all columns
	  							for(var x=0;x<".count($legArr).";x++)
		  						{
		  							if(x < colInd+1)//if lower column is checked, we must break the enabling!
		  							{
		  								if(f[ names[x] ][i].checked) break;
		  							}
		  							else	
				  					 f[names[x] ][i].disabled=false;
			  					
			  				}";
	  					$tbl .= "}
	  				}";
		  				$tbl .="
		  				for(var x=colInd+1;x<".count($legArr).";x++)
		  				{
		  					f[names[x] ][ row ].disabled=true;
		  				}"; 
	  					
		  				$tbl .="scaleInvert[colInd] = row;";
	  				
	  				}
								  				
					
					
		  			$tbl .= "} </script>";
		  		}
			  	
		  		if($this->headerDisplay)
		  		{
		  			
		  			//check if there are any answers to display!
		  			 foreach ($ansArr as $index => $ans) {
		  			 	if (!$this->groups[$index]) $this->groups[$index] = 0;
			  	 		if($this->groups[$index] == $this->group ) $displayH = true;;
		  			 }
		  			if($displayH)
					$tbl .= "<tr height=$this->headerHeight><td colspan=2 style='vertical-align:bottom;'>$this->headerTitle</td>"; 
		  		}
		  	
		  		//tanis
		  		if($this->les_sql == 1 and trim($this->atr_sql))
		  		{
		  		    $tbl .= "<tr><td $size></td>";
                     foreach($atrArr as $atrInd => $ans)
                     {
                         foreach($legArr as $legInd => $leg)
                         {
                             $tbl .= "<td $size >$leg[1]</td>"; 
                         }
                     }
                     $tbl .= "</tr>"; 
		  		}
		  		                
			  	 foreach ($ansArr as $index => $ans) {
			  	     
			  	 	if (!$this->groups[$index]) $this->groups[$index] = 0;
			  	 	if($this->groups[$index] != $this->group ) continue;
			  	
			  	 	//check if we have to draw legend again
			  	 	if($this->repeat_legend > 0)	
				  	 	if(($this->les_sql != 2 &&  $this->les_sql != 7 && $this->les_sql != 8) || trim( $this->atr_sql) )
					  	{
					  		$this->legendCounter++;
					  		if($this->legendCounter >= $this->repeat_legend)
					  		{
						  		$this->legendCounter = 0;
						  		//the width of the control must be divided by the number of legends
						  		
						  		//tanis
						  		if($this->les_sql == 1 && trim($this->atr_sql))
                                {
						  		      $tbl .= $this->designerDrawLegend($this->legRow, $atrArr);
                
                                }
                                else
                                      $tbl .= parent::designerDrawLegend($this->legRow, $this->les_sql == 2 ? $atrArr : $legArr);                     
                                        
						  		//$tbl .= $this->designerDrawLegend($this->legRow, $this->les_sql == 2 ? $atrArr : $legArr);
					  		}
					  	}
			  	 		
			  	 	//we go trough each answer/legend (depending on rotation)
			  		$value = $ans[0];
			  		$label = $this->display->readRequiredQuestionVariables( $ans[1]);
			  		$labelSplit = explode('|',$label,2);
			  		unset($labelEnd);
			  		if(count($labelSplit) > 1)
			  		{
			  			$label = $labelSplit[0];
			  			$labelEnd = $labelSplit[1];
			  		}
			  		
			  		
			  		if($this->les_sql == 8)
	  				{/*
	  					if ($cardType == 1 || $cardType == 3) {
							if ($fieldsValues[$this->q_name."_$value"]) {
								
									$li = '<li id="app_'.$ans[0].'" class="item"><div class="box">'.$this->display->readRequiredQuestionVariables($label).'</div>';
									if (!$inverse) $li .= '<input id="input_'.$ans[0].'" type="hidden" name="answers['.$this->q_name.'_'.$value.']" value="'.$fieldsValues[$this->q_name."_$value"].'" />';
									$li .= '</li>';
								
									$dragValues[$fieldsValues[$this->q_name."_$value"]][] .= $li;
								
								
								if ($inverse) {
									$dragScript[] = '$("#input_'.$value.'").val("'.$fieldsValues[$this->q_name."_$value"].'");';
								}
							} else {
								$tbl .= "<script>App.items.push(['" . $value . "', \"" . $this->display->readRequiredQuestionVariables($label) . "\", '".$this->q_name."_".$value."']);</script>";
							}
						}
						
						else if ($cardType == 2) {
							$set = ($fieldsValues[$this->q_name."_$value"]) ? $fieldsValues[$this->q_name."_$value"] : "";
							$tbl .= "<script>App.items.push(['" . $value . "', \"" . $this->display->readRequiredQuestionVariables($label) . "\", '".$this->q_name."_".$value."', ".$set."]);</script>";
						}*/
	  				}
	  				else
	  				{
				  	 	 if ($counter%2 == 1){ // odd rows
				  			$useRow = $this->oddRows;
				  			$useStyle = $this->oddStyle;}
				  		else{ 
				  			$useRow = $this->evenRows;
				  			$useStyle = $this->evenStyle;}
				  		
				  		$tbl .= "<tr>";
				  		//if must answer and show_type == 1 or 2
				  		//3 or 4 is set during legend for each
				  	 	if($this->les_sql == 1 && !trim($this->atr_sql))
				  		{
				  			$ansCnd = 'isset( $'.trim( $fields[$index]).')';
				  			//print "Ans cnd: " .  $ansCnd . " " . $index . " <br>"; 
				  			
				  		}
				  		else if($this->les_sql == 2 || $this->les_sql == 1 && trim($this->atr_sql) )
				  		{//combobox isset fails becouse it alwasy sents something MORS NEKI SER NARETEDE!
				  			$multiComboTmpCnd = array();
				  			foreach ($atrArr as $i=>$nimaVeze)
				  			{
								$multiComboTmpCnd[] = '$'.trim( $fields[$index*$atrNum+$i ]).' != ""';
				  			}
				  			$ansCnd = '('.implode(' AND ',$multiComboTmpCnd).')';
                                                                                    //print "tukaj sem";
				  			//$ansCnd = '( $'.trim( $fields[$index]).' != "" )';
				  		}
				  		
				  		
				  	 	foreach ($useRow->children() as $child) {
				  			$attr = $child->attributes();
				  				switch ($attr['type'])
					  			{
					  				case 20:
					  					if($this->showVal)
					  					{
						  					$size = $useStyle[20];
						  					$tbl .= "<td $size>$value</td>";
					  					}
					  				break;
					  				case 21:
					  					if($this->les_sql == 7) {
					  						$tbl .= "<td></td>";
					  					} else {
						  					$size = $useStyle[21];
						  					$size_right_style = $size; 
						  					$tbl .= "<td $size>$label";
                                            
						  					if( in_array($value,$openAns) )
						  					{ 
						  						$tbl .= " <input type='text' style='width:250;'  id='op_". $fields[$index]."' NAME='answers[". trim($fields['o_'.$value]) ."]' onclick='recodeClickEvents(this,1);' onblur='recodeClickEvents(this,2)' value='".
						  						$fieldsValues[trim($fields['o_'.$value]) ] ."'>";
						  						//if we have an open question we update the condition
						  						if($this->must_answer)
						  						{//if must answer is true for 1 or 2 (single checkbox)
						  						 //then either both must be filled or none!
						  						 //print $this->answers_filter . "to je ans filter";
							  						if($this->les_sql == 1 || $this->les_sql == 2)
                                                    {
                                                        //20150225 added by Tanis I have add this options so now you can check allow open answer and system will allow you to keep open field empty if you have select it so
                                                        /*if($this->answers_filter)
							  							    $ansCnd = '!('.$ansCnd. ' XOR strlen($'.trim($fields['o_'.$value]).')>=0 )';
                                                        else 
                                                            //$ansCnd = '!('.$ansCnd. ' XOR strlen($'.trim($fields['o_'.$value]).')>0 )';
                                                            $ansCnd = '(('.$ansCnd. ' AND strlen($'.trim($fields['o_'.$value]).')>0) OR !' . $ansCnd . ' )';*/
                                                          
                                                        /*  
                                                        if(!$this->answers_filter)
                                                            $ansCnd = '!('.$ansCnd. ' XOR strlen($'.trim($fields['o_'.$value]).')>0 )';
                                                        else 
                                                            $ansCnd = '(!'. $ansCnd .' XOR strlen($'.trim($fields['o_'.$value]).')>0 )';
														 */
														 
														// Borut made another change here 20150415
                                                        if($this->answers_filter)
							  							    $ansCnd = '(!('.$ansCnd. ' XOR strlen($'.trim($fields['o_'.$value]).')>=0) OR (!'.$ansCnd. ' AND strlen($'.trim($fields['o_'.$value]).')==0))';
                                                        else 
                                                            $ansCnd = '(('.$ansCnd. ' AND strlen($'.trim($fields['o_'.$value]).')>0) OR !' . $ansCnd . ' )';
                                                        
                                                       
														 														 
                                                    }

							  						
						  						}
						  						else
						  						{//the same aplies if must answer is false! only in this case we havent set conditions for non-open fields
					  								if($this->les_sql == 1)
                                                    {
											  			$openAnscnd[] = '!(isset( $'.trim( $fields[$index]).') XOR '. 'strlen($'.trim($fields['o_'.$value]).')>0)';
                                                    }
											  		else if($this->les_sql == 2)
											  		{
											  			$multiComboTmpCnd = array();
											  			foreach ($atrArr as $i=>$nimaVeze)
											  			{
						  									$multiComboTmpCnd[] = '$'.trim( $fields[$index*$atrNum+$i ]).' != ""';
											  			}
											  			$openAnscnd[] = '!(( '.implode(' OR ',$multiComboTmpCnd ).' ) XOR '. 'strlen($'.trim($fields['o_'.$value]).')>0)';
											  		}
						  						}
						  						if($this->les_sql == 4 || $this->les_sql == 3)
							  						{//in case of 3 or 4 we set open condition eitherway
							  							$ansCndOpen = 'strlen($'.trim($fields['o_'.$value]).')>0';
							  						}
						  					}
						  					$tbl .= '</td>';
					  					}
					  				break;
					  				case 22:
					  					$size = $useStyle[22];
					  					if($this->les_sql == 7)
								  		{
								  			if(isset( $fieldsValues[ trim( $fields[$index]) ] ) )
						  						$startVal = $fieldsValues[ trim( $fields[$index])];
						  					else
						  						$startVal = $scData[3];
								  			$tbl .= "<td><input type='hidden' name='answers[{$fields[$index]}]' id='value_{$fields[$index]}' />				    					
					    					  
											 <style>
											 	.ui-widget-header {/*range color*/
											 		background: #FF8235;
								  				}
								  				.ui-state-default,
												.ui-widget-content .ui-state-default,
												.ui-widget-header .ui-state-default {/*background of slider button*/
								  					background: url(".PATH_TO_ROOT."survey/slider/css/slider_img/diamond-slider.png) no-repeat;
								  					border: none;
												}
								  				.ui-slider-horizontal {/*thickness of slider scale*/
 											   		height: 4px;
												}
												.ui-slider .ui-slider-handle
												{
													width: 32px;
													height: 34px;
													background: url(".PATH_TO_ROOT."survey/slider/css/slider_img/diamond-slider.png) no-repeat;
								  				}
								  				.ui-slider-horizontal .ui-slider-handle
								  				{
								  					top: -10px;
								  				}
										  		.ui-state-hover,
												.ui-widget-content .ui-state-hover,
												.ui-widget-header .ui-state-hover,
												.ui-state-focus,
												.ui-widget-content .ui-state-focus,
												.ui-widget-header .ui-state-focus {
													border: 0px solid #999999/*{borderColorHover}*/;
													background: url(".PATH_TO_ROOT."survey/slider/css/slider_img/diamond-slider.png) no-repeat;/*#dadada{bgColorHover}*/ url(images/ui-bg_glass_75_dadada_1x400.png)/*{bgImgUrlHover}*/ 50%/*{bgHoverXPos}*/ 50%/*{bgHoverYPos}*/ repeat-x/*{bgHoverRepeat}*/;
													font-weight: normal/*{fwDefault}*/;
													color: #212121/*{fcHover}*/;
												}
															  				
											 </style>			    					
					    					 <label id=\"labelmin{$fields[$index]}\" style=\"float:left;width:250px;text-align:right;\">{$label}</label>					    					 
					    					 <div id=\"slider{$fields[$index]}\" style=\"width: 200px; margin:12px 14px; float:left;\"></div>
					    					 <label for=\"tb{$fields[$index]}\" style=\"float:left;width:200px;\">{$labelEnd}</label> 
					    					 <input type=\"hidden\" size=\"3\" maxLength=\"3\" name=\"answers[{$fields[$index]}]\" id=\"tb{$fields[$index]}\" value=\"0\"/>
					    					 
								  <script type=\"text/javascript\">
									  $(document).ready(function(){
									  
										  $(\"#slider{$fields[$index]}\").slider(
										  {
										  	range: 'min',
								  			min: 1,
								  			max: "; $tbl .= count($scData).",";
								  			if(is_integer($startVal))
								  				$tbl .= "value: ".$startVal.",";								  			
								  			$tbl .="
								  			orientation: 'horizontal',
								  			
								  			slide: function( event, ui ) {								  			
								  				$('#tb{$fields[$index]}').attr('value',ui.value);
								  				$('#labelmax{$fields[$index]}').text('Value: '+ui.value); 								  				 
								  			}
										  });
										  $('#tb{$fields[$index]}').change(function(){
										  		tbVal = $('#tb{$fields[$index]}').val();
										  		//alert(tbVal);
										  		if(tbVal > 100)tbVal = 100;										  		
										  		$(\"#slider{$fields[$index]}\").slider('value', tbVal);								  			
										  });
										  
										  $('#tb{$fields[$index]}').val(".$fieldsValues[$fields[$index]].");
											$('#tb{$fields[$index]}').change();
											
									  });
  	
								</script>
					    					 
					    					</td>";
								  		}
								  		else
					  					foreach ($atrArr as $atrInd => $atr) {
					  				  //this will only go for multi multi comoboboxes...each other will commit only once! (i hope :D)
					  					
					  					/*print "<pre>";
                                        //var_dump($fields);
                                        var_dump($atr);
                                        print "</pre>";*/
					  					//$tbl .= "<td $size><input type='checkbox' NAME='answers[".trim( $fields[$index])."]' value='$value'></td>";
					  						if($this->les_sql == 2)//combobox need special option tag
					  						{
									  				$tbl .= "<td $size>";
									  				if(!$leaveQuestion && !$fieldsValues[  trim( $fields[$index*$atrNum + $atrInd ]) ] && $this->must_answer )
									  					$tbl .= "<img src='../_img/noanswer_warrning.gif'>";
													//20151015 Tanis I have changed hardcoded -- select text wih the one fro language pack
													$selectLabel = $this->display->getLangLabel(6);
													if(strlen($selectLabel) <= 0) $selectLabel = "- - - select - - -";
									  				$tbl .="<SELECT id='ct_". $fields[$index*$atrNum + $atrInd]."' NAME='answers[".trim( $fields[$index*$atrNum + $atrInd])."]' onchange='recodeClickEvents(this,4)'><option value=''>" . $selectLabel  . "</option>";
													
									  				//$tbl .="<SELECT id='ct_". $fields[$index*$atrNum + $atrInd]."' NAME='answers[".trim( $fields[$index*$atrNum + $atrInd])."]' onchange='recodeClickEvents(this,4)'><option value=''>- - - prosim izberite - - -</option>";
					  						}
									  		else if ($this->les_sql == 4 || $this->les_sql == 3)
									  		{
									  			$legSize = count($legArr);
									  			$ansCndLeg = array();
									  		}
									  		$legIndex = 0;
					  						//we go trough each legend and draw it
									  		foreach ($legArr as $legInd => $leg) {
										  		$legVal = $leg[0];
										  		//the type of display depends on les_sql
										  		//Tanis
										  		if($this->les_sql == 1 && !trim($this->atr_sql))
										  		{
										  			
										  			if($this->multi_nogo_answers && $counter >= $this->multi_nogo_answers)//this questions are shown seperatly and have only one radio button (eg, have no opinion or shit like that)
										  			{
										  					$tbl .= "<td colspan=".count($legArr)." $size onClick=\"var d = document.forms['mainForm']['answers[". $fields[$index]."]'];d.checked = true;recodeClickEvents(d,1)\">";
									  						$tbl .="<input type='radio' id='ct_". $fields[$index]."_$legVal' NAME='answers[". $fields[$index]."]' value='$legVal'";
									  						if($legVal == $fieldsValues[  trim( $fields[$index]) ] ) $tbl .= ' checked';
									  						$tbl .="></td>";
									  						break;
										  			}
										  			
										  			//if there is only one radio button 'document.forms['mainForm']['answers[".$this->q_name."]']' doesn't return an array!!!
                                                    // Matej, 2015-07-21, added ids (like on <tr>s, see custom_inputs.php)
								  					if(count($legArr)>1)
                                                        $tbl .= "<td id='td_" . $fields[$index] . "_$legVal' $size onClick=\"var d = document.forms['mainForm']['answers[". $fields[$index]."]'][$legIndex];/*d.checked = true;recodeClickEvents(d,1)*/\">";
									  				else
                                                        $tbl .= "<td id='td_" . $fields[$index] . "_$legVal' $size onClick=\"var d = document.forms['mainForm']['answers[". $fields[$index]."]'];/*d.checked = true;recodeClickEvents(d,1)*/\">";
									  				
									  				//if($legIndex == 0 && !$leaveQuestion && !$fieldsValues[  trim( $fields[$index]) ] && $this->must_answer )
													// Borut change this on 2012 11 05
													// problem is on scale question that first column is onyl added with arrow, not all as in old system
									  				if(!$leaveQuestion && !$fieldsValues[  trim( $fields[$index]) ] && $this->must_answer )
								  						$tbl .= "<img src='../_img/noanswer_warrning.gif'>";

									  				$tbl .="<input type='radio' id='ct_". $fields[$index]."_$legVal' NAME='answers[". $fields[$index]."]' value='$legVal'";
									  				if($legVal == $fieldsValues[  trim( $fields[$index]) ] ) $tbl .= ' checked';
									  				$tbl .="></td>";
										  		}
                                                else if($this->les_sql == 1 && trim($this->atr_sql))
                                                {
                                                    $tbl .="<td $size>";
                                                     if(!$leaveQuestion && !$fieldsValues[  trim( $fields[$index*$atrNum + $atrInd ]) ] && $this->must_answer )
                                                        $tbl .= "<img src='../_img/noanswer_warrning.gif'>";
                                                    
                                                    $tbl .= "<input type='radio' id='ct_". $fields[$index*$atrNum + $atrInd]."' value='$legVal'  NAME='answers[".trim( $fields[$index*$atrNum + $atrInd])."]' onchange='recodeClickEvents(this,4)'" ;
                                                    if($legVal == $fieldsValues[  trim( $fields[$index*$atrNum + $atrInd]) ] ) $tbl .= ' checked';
                                                    $tbl .="></td>";
                                                }
									  			else if($this->les_sql == 5)
										  		{//inverted radio must have same name on legend fields!
										  			
									  				$tbl .= "<td $size onClick=\"radioChecker($legIndex, ".($counter-1).",$value );";
									  				
									  				
									  				$tbl .= "\">
									  				<input type='radio' id='ct_". $fields[$legInd]."_$legVal' NAME='answers[". $fields[$legInd]."]' value='$value'";
									  				
									  				if($testDis && $checkedFields[$counter]) $tbl .= ' disabled';
									  				//check the current values...and disable all in same row 8)
									  				if($value == $fieldsValues[  trim( $fields[$legInd]) ] ) {$tbl .= ' checked'; $checkedFields[$counter] = true;  }
									  				
									  				if(in_array($value,$nogoArr))
									  				{
									  					$nogoCnd[] = '$'.$fields[$legInd] ." == $value";
									  				}
									  				
									  				$tbl .="></td>";
									  				if(count($cnd) < count($fields))
									  				{
									  					 $cnd[] = 'isset( $'.trim( $fields[$legInd]).')';
									  				}
										  		}
									  			/*else if ($this->les_sql == 4)
									  			{//3 and 4 needs condition for every legend option
									  				$tbl .= "<td $size onClick=\"var tmp = document.forms['mainForm']['answers[".trim( $fields[$index*$legSize + $legIndex])."]']; tmp.checked = !tmp.checked\"
									  				><input type='checkbox'onClick='event.cancelBubble=true'
									  				 NAME='answers[".trim( $fields[$index*$legSize + $legIndex])."]' value='$legVal'";
									  				if( isset( $fieldsValues[  trim( $fields[$index*$legSize + $legIndex]) ] ) ) $tbl .= 'checked = true';
									  				$tbl .= "></td>";
									  				
									  				$ansCndLeg[] = "isset( $".trim( $fields[$index*$legSize + $legIndex]).")";
									  			}
									  			else if ($this->les_sql == 3)
									  			{
									  				$tbl .= "<td $size><input type='text' NAME='answers[".trim( $fields[$index*$legSize + $legIndex])."]'";
									  				if( isset( $fieldsValues[  trim( $fields[$index*$legSize + $legIndex]) ] ) ) $tbl .= 'value = "'. $fieldsValues[  trim( $fields[$index*$legSize + $legIndex]) ].'"';
									  				$tbl .="></td>";
									  				$ansCndLeg[] = "strlen( $".trim( $fields[$index*$legSize + $legIndex]).")>0";
									  			}*/
									  			else if ($this->les_sql == 2)
									  			{
									  				$tbl .= "<option value='$legVal'";
									  					if($legVal == $fieldsValues[  trim( $fields[$index*$atrNum + $atrInd]) ] ) $tbl .= ' selected=yes';
									  				$tbl .= ">{$leg[1]}</option>";
									  			}
								  				$legIndex++;	
									  		}
									  		if($this->les_sql == 2)
									  			$tbl .= "</SELECT></td>";
                                          
									  			
					  					}
								  				
				  					break;
					  			}
					  			
					  		}
					  		
		  				if($labelEnd && $this->les_sql == 1)//display the end label if it's set :)
					  		{
					  			$tbl .= "<td $size_right_style>$labelEnd</td>";
						  					
					  		}
				  	 	//if we have checkboxes we have an array of conditions for each checkbox and at least one must be checked
				  	 	$tbl .= "</tr>";
				  		if($this->les_sql == 4 || $this->les_sql == 3)
				  		{
				  			$ansCnd = '('.implode(' OR ',$ansCndLeg).')';
				  			//if open ansers is avaliable either both answers must be checked or none (!xor)
				  			if($ansCndOpen)
				  			{
				  				$ansCnd = '!('.$ansCnd.' XOR '.$ansCndOpen.')';
				  				unset($ansCndOpen);
				  				if(!$this->must_answer)
				  				{
				  					$openAnscnd[] = $ansCnd;
				  				}
				  			}
				  		}
	  				}
			  		$counter++;
			  		if($ansCnd)
			  			$cnd[] = $ansCnd;
			  			
			  		
					  		
			  			
			  	}
			  	
			 if($this->les_sql == 5)
			  		{
			  			$tbl .= "<script>
			  				for(var i=0;i<".count($ansArr). ";i++)
	  							//we go from trough all columns
	  							for(var x=0;x<".count($legArr).";x++)
		  						{
		  								if(f[ names[x] ][i].checked) 
		  									radioChecker(x,i, parseInt(f[ names[x] ][i].value) );
				  							
			  					
			  					}
			  			</script>";
			  		}
			else if($this->les_sql == 7)
				  	{
				  		$tbl .= "<script type='text/javascript' >scales.init()</script>";
				  	}
		  /*	else if($this->les_sql == 8)
  		{
  			//ump($fieldsValues);
  			
  			
  			//must answer condition for all answers...
  			foreach ($ansArr as $ansInd => $ans) {
  				$cnd[] = ' $'.trim( $fields[$ansInd]).' > 0 ';
  			}
  			//$dragCondition = array();
  			$tbl .= '<div style="clear:both;"></div>
  			<div id="cartdiv" style=" '.$BasketPosition.' display: table; text-align: center;">';
			// $first = true;
			
			// Sort baskets if neutral carts are on left or top
			if ($neutralPosition == "left" || $neutralPosition == "top") {
				usort($legArr, "compare_neutral");
			}
			
			$break = false; $offset = false;
			//array_reverse($legArr,true)
			foreach ($legArr as $legInd => $leg) {
				$ddName= "answers[$fields[$legInd]]";

				// Class for background color
				$cls = ($leg[0] < 100) ? "caption" : "ncaption";
				
				// New line if top or bottom
				if (($neutralPosition == 'bottom' && !$break && $leg[0] > 100) || ($neutralPosition == 'top' && !$break && $leg[0] <= 100)) {
					$tbl .= '<div style="clear:both;"></div>';
					$break = true;
				}
				
				$margin = "";

				// Offset if left or right
				if (($neutralPosition == 'left' && !$offset && $leg[0] <= 100) || ($neutralPosition == 'right' && !$offset && $leg[0] > 100)) {
					if ($cardType != 3) $margin = 'style="margin-left: 50px;"';
					//$margin = 'style="margin-right: 50px;"';
					$offset = true;
				}
				
				// $tbl .= $leg[0] . " __ " . $leg[1] . "<br>";
				// Added carts
				$tbl .= '<div class="container" '.$margin.'>
					<ul id="dropContainer_'.$leg[0].'" class="cart">'.implode(" ", $dragValues[$leg[0]]).'</ul>
					<div class="'.$cls.'">'.$leg[1];			
					
					if ($inverse) {
						$tbl .= '<input id="input_'.$leg[0].'" type="hidden" value="" name="answers['.$this->q_name.'_'.$leg[0].']" />';
					}
					
					$tbl .= '</div>
				</div>';
			}
			
			if (!empty($dragScript)) {
				$tbl .= '<script>'.implode(" ", $dragScript).'</script>';
			}
			$tbl .= '</div>
			<script>
			$(function () {
				
				for (var i = 0; i < App.items.length; i++) {
					
					var li = (App.inverse) ? "<li class=\"item\" id=app_" + App.items[i][0] + "><div class=\"box\">" + App.items[i][1] + "</div></li>" : "<li class=\"item\" id=app_" + App.items[i][0] + "><div class=\"box\">" + App.items[i][1] + "</div><input id=\"input_" + App.items[i][0] + "\" type=\"hidden\" value=\"\" name=\"answers[" + App.items[i][2] + "]\" /></li>";
					
					if (App.cardType == 1) {
						
					    $("#app").append(li);
					    if (i !== 0) {
					        if (i >= (App.items.length - 10)) $("#app_" + App.items[i][0]).css("margin-left", "-'.($boxWidth-5).'px");
					        else $("#app_" + App.items[i][0]).css("margin-left", "-'.$boxWidth.'px");
					    }
					
					    $("#app_" + App.items[i][0]).css("top", "10px");
					}
					
					else if (App.cardType == 2) {
							
						var x = Math.floor(i / App.dimX);
						var y = i % App.dimX;
							
						$("#row"+x+"_"+y).append(li);
					}
					
					else if (App.cardType == 3) {
					    $("#app").append(li);
					}
				}
		
				if (App.cardType == 2) {
					for (var i = 0; i < App.items.length; i++) {
						if (typeof App.items[i][3] !== "undefined") {
							$("#app_"+App.items[i][3]).appendTo($("#dropContainer_"+App.items[i][0]));
							$("#input_"+App.items[i][0]).val(App.items[i][3]);
						}
					}
				}
				
				
				    if (App.cardType == 1) {
				    	$("#app").width(App.width);
				    	$("#app").css("margin-left", "260px");
					} else if (App.cardType == 3) {
						var height = ('.$boxHeight.' * App.items.length) + 50;
						$("#app").height(height);
					}
				
				    $(".item").draggable({
				        appendTo: "#cartdiv",
				        revert: "invalid",
				        scroll: true,
				        refreshPositions: true,
				        cursorAt: {
				            top: '.($boxHeight / 2).',
				            left: '.(($cardType == 1) ? ($boxWidth) : ($boxWidth/2)).'
				        },
				        drag: function(event, ui) {
				        	var st = parseInt($(this).data("startingScrollTop"));
							ui.position.top -= $(this).parent().scrollTop() - st;
				        },
					    start: function() {
					    	$(this).data("startingScrollTop", $(this).parent().scrollTop());
					    	if (App.cardType == 1) {
						    	if ($(this).is(":last-child")) {
						        	$(this).hide();
								} else {
									return false;
								}
							}
					    },
					    stop: function() {
					        $(this).show();
					    },
				        helper: function (event, ui) {
				        	if (App.cardType == 1) {
					            if ($(event.currentTarget).is("li:first-child")) {
					                return $("<div class=\"test\"></div>").append($(this).clone().css("list-style", "none"));
					            } else {
					                return $("<div class=\"test\"></div>").append($(this).clone().css("margin-left", "-30px").css("list-style", "none"));
					            }
							} else {
								return $("<div class=\"test\"></div>").append($(this).clone().css("list-style", "none"));
							}
				        }
				    });
				
				    $(".cart,.neutral").droppable({
				        accept: ".item",
				        hoverClass: "active",
				        drop: function (event, ui) {
				
				            var dropped = ui.draggable;
				            var droppedOn = $(this);
							
							if (App.inverse && droppedOn.children(".item").length) {
								if (App.cardType == 1) {
									console.log("Todo revert type 1");
								}
								
								else if (App.cardType == 2) {
									for (var i=0; i<App.dimY; i++) {
										for (var j=0; j<App.dimX; j++) {
											if ($("#row"+i+"_"+j).children(".item").length == 0) {
												droppedOn.children(".item").first().appendTo($("#row"+i+"_"+j));
											}
										}
									}
								}
								
								else if (App.cardType == 3) {
									droppedOn.children(".item").first().appendTo("#app");
								}
							}
				
				            if (dropped.parent()[0] !== droppedOn[0]) {
				                $(dropped).detach().css({
				                    top: 0,
				                    left: 0
				                }).css("margin-left", "").appendTo(droppedOn);
				
				                App.len = $("#app").children(".item").length;
				                $("#app").children(".item").each(function (index) {
				                    if (index >= (App.len - 11) && App.len > 10 && index !== 0) {
				                        var id = $(this).attr("id");
				                        $("#" + id).css("margin-left", "-'.($boxWidth-5).'px");
				                    }
				                });
				
				                var item = droppedOn.attr("id");
				                item = item.split("_");
				                item = item.pop();
				
				                var name = dropped.attr("id");
				                name = name.split("_");
				                name = name.pop();
				
				                if (!App.inverse) {
				                	$("#input_" + name).val(item);
								} else {
									$("#input_" + item).val(name);
								}
				            }
				        }
				    });
				
				    $("#app").droppable({
				        accept: ".item",
				        drop: function (event, ui) {
				            var dropped = ui.draggable;
				            var droppedOn = $(this);
				
							if (App.cardType == 1) {
					            App.len = $("#app").children(".item").length;
					            var margin = (App.len > 0) ? "-'.$boxWidth.'px" : "";
							}
				
				            var name = dropped.attr("id");
				            name = name.split("_");
				            name = name.pop();
				
				            $("#input_" + name).val("");
				
				            $(dropped).detach().css({
				                top: 0,
				                left: 0,
				                "margin-left": margin
				            }).appendTo(droppedOn);
				
							if (App.cardType == 1) {
					            $("#app").children(".item").each(function (index) {
					                var id = $(this).attr("id");
									if (index !== 0){
						                if (index >= (App.len - 10) || App.len <= 10) {
						                    $("#" + id).css("margin-left", "-'.($boxWidth-5).'px");
						                } else if (index !== 0) {
						                    $("#" + id).css("margin-left", "-'.$boxWidth.'px");
						                }
									} else {
										$("#" + id).css("margin-left", "");
									}
									$("#" + id).css("top", "10px");
					            });
							}
				        }
				    })';
				    
					if ($cardType == 3) $tbl .= '.sortable({
						revert: true
					})';
					
				    $tbl .= ';
				});
				
				$("#delete").bind("click", function () {
			
				for (var i=1; i<=$(".item").length; i++) {
					var item = $("#app_"+i);
				
					if ($(item).parent().attr("id") !== "app") {
						
						if (App.cardType == 2) {
							for (var a=0; a<App.dimY; a++) {
								for (var b=0; b<App.dimX; b++) {
									if ($("#row"+a+"_"+b).children(".item").length == 0) {
										$(item).appendTo($("#row"+a+"_"+b));
									}
								}
							}
						} else {
						
			            	var droppedOn = $("#app");
							var margin = (App.cardType == 1) ? (!droppedOn.children().length) ? "" : "-115px" : "0px";
						
							$(item).detach().css({
								top: 0,
								left: 0,
								"margin-left": margin
							}).hide().appendTo(droppedOn).show("fast");
			
			            	var name = $(item).attr("id");
			            	name = name.split("_");
			            	name = name.pop();
			
			            	$("#input_" + name).val("");
			
				            try {
				                var a = $("#app").length - 10;
				                if (a > 1) {
			    	                var id = $("#app").children().eq(i).attr("id");
									if (App.cardType == 1) $("#" + id).css("margin-left", "-120px");
			        	        }
			            	} catch (err) {
			            	}
						}
		        	}
				};
			
				if (App.cardType == 1) {
				setTimeout(function() {
				
					App.len = $("#app").children(".item").length + 1;
		    		$("#app").children(".item").each(function (index) {
						var id = $(this).attr("id");
						if (index !== 0){
							if (index >= (App.len - 10) || App.len <= 10) {
								$("#" + id).css("margin-left", "-115px");
							} else if (index !== 0) {
								$("#" + id).css("margin-left", "-120px");
							}
						} else {
							$("#" + id).css("margin-left", "");
						}
						$("#" + id).css("top", "10px");
					});
				}, 200);
				}
			});
			
				</script>';
				}	  	
*/
               /*     print "<pre>";
                ump($openAnscnd);
                print "</pre>";*/
                
                
			  	if($this->must_answer)
			  	{
			  		
			  	/*print "<pre>";
                ump($openAnscnd);
                print "</pre>";*/
			  	if($nogoCnd)
			  		{
			  			for($key = 0;$key<count($nogoCnd)-1;$key++ )
			  			 {	
			  			 	$str = $nogoCnd[$key];
			  				$cnd[$key+1] = '('.$str.' OR '.$cnd[$key+1]  ;
			  				$close .= ')';
			  			}
			  			$cnd[$key] .= $close;
			  		}
			  		
			  		if(is_array($cnd))
			  			$finalCnd = '('. implode(' AND ',$cnd) . ')';
			  		else
			  			$finalCnd = 'true';
			  		
			  		if($_SESSION['mustAnswerCondition'])
			  			$_SESSION['mustAnswerCondition'] .= ' AND '.$finalCnd;
			  		else
			  			$_SESSION['mustAnswerCondition'] = $finalCnd;
			  	}
			  	else if($openAnscnd && !$this->answers_filter)
			  	{
			  		if($_SESSION['mustAnswerCondition'])
			  			$_SESSION['mustAnswerCondition'] .= ' AND ('. implode(' AND ',$openAnscnd) . ')';
			  		else
			  			$_SESSION['mustAnswerCondition'] = '('. implode(' AND ',$openAnscnd) . ')';
			  	}
               // print $_SESSION['mustAnswerCondition'];
			  	$tbl .= "</table>";
			  	return $tbl;
		}
	public function designerRequiresTemplate()
		{
			return true;
		}
	public function printAnswerTable()
	{
			echo "<div Style=\"margin-left : 20px; \">";
				$arr = $this->answerToArray($this->odg_sql); //explode("<*>", $odgovori);
				$i = count($arr);
				$legenda_lab= $this->answerToArray($this->leg_sql);  //explode("<*>", $legenda);
				$m=count($legenda_lab);
				$lestvica = $m;
				echo "<TABLE border='0'>";
				echo "<TR><TD width=50%></TD>";
				for($stevec_legenda=0;$stevec_legenda<$m;$stevec_legenda++) {
					echo "<TD align=\"center\" width=60>";
						//$dolzina_sp = strpos($legenda_lab[$stevec_legenda], " ");
						$legenda_show = $legenda_lab[$stevec_legenda][1]; //substr($legenda_lab[$stevec_legenda], $dolzina_sp+1);
	//					echo "<font size=1 face=arial>&nbsp;".$legenda_show."&nbsp;</font>";
						echo "<font class=tekst>&nbsp;".$legenda_show."&nbsp;</font>";
					echo "</TD>";
				}
				echo "</TR>";
				
				
				if($this->record_data)
					{
						$this->printGetRecValues();
					}
				
				for ($j=0; $j<$i; $j++) {
					echo "<TR><TD class=tekst width=50%>";
					//$dolzina_sp = strpos($arr[$j], " ");
					$answer_label = $arr[$j][1]; //substr($arr[$j], $dolzina_sp);
					$answer_val = $arr[$j][0];
					if (is_array($multi_nogo_answers) and in_array($answer_val,$multi_nogo_answers)) echo "* ";
					echo  $answer_val." ".$answer_label;
					$this->printFilterAnswer($j);  //include("./main/show_filter_answer.php");
	//				echo  "<font size=1 face=arial>".$answer_val." ".$answer_label."</font>";
					echo "</TD>";
					for ($l=0; $l<$lestvica; $l++) {
						$legValue = $legenda_lab[$l][0];
						if($this->dataValues )
						{
							$isAnswered = $this->dataValues[$j] == $legValue;
						}
						echo "<TD align=\"center\" width=60>";
						
						if($this->printEdit)
						{
							
							echo "<input type=radio name='editVal[{$this->fld[$j]}]' value=$legValue ".($isAnswered ? 'checked': '')." />";
						}
						
						if($isAnswered) echo "<span style='background:red'>";
							echo "<font class=tekst>$legValue</font>";
	//						echo "<font size=1 face=arial>$l</font>";
						if($isAnswered)
							echo "</span>";
						echo"</TD>";
					}

					if($this->dataValues )
						{
							
							
							if(isset($this->openValues[$j+1 ] ))
							{
								echo "<td>";
								if($this->printEdit)
									echo $this->printEditVarOpen($j,$this->openValues[ $j+1 ],$answer_val);
								else
									echo " <font color='gray'>". $this->openValues[ $j+1  ]." </font>";
								echo"</TD>";
							}
						}
					
					echo"</TR>";
				}
				echo "</TABLE>";
			echo "</div>";
	}
	public function printEditVar()
	{
		$blalba->gofuckyourself;
	}
	protected function printEditVarOpen($i,$value,$fldValue)
		{
			return "<textarea name='editVal[{$this->fld['o_'.$fldValue]}]'>$value </textarea>";
		}	
}

?>
