<?php
set_time_limit(900);

include_once '_dirinfo.php';
include_once(PATH_TO_ROOT."_config/dbConfig.php");
include_once PATH_TO_ROOT.'_class/createQuestion/Question.php';

?>
<?php 
$projectId = $_GET['projectId'];
//echo $projectId;
$projData = $db->get('_Projects',$projectId,'proj_name,language',DB_WARPIT_WEBCATI_BASE);
$tableName = $projData['proj_name'];
$id_language = $projData['language'];
$tmpName = "warpitStatistic";


$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

$sql = "SELECT stat_show_var, stat_show_val, disablebasic,language FROM _Projects WHERE proj_name='$tableName'";

If (!$res = $db->SQLexecute($sql)) {
			Echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;	
	}
$projProps = $db->fetchAssoc($res);
$showVar = $projProps['stat_show_var'];

$id_language = $projProps['language'];

$sql = "DROP TEMPORARY TABLE IF EXISTS $tmpName";
$db->SQLexecute($sql);
if($db->IsError())
{
	Echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
	exit;
}
$db->SQLexecute("CREATE TEMPORARY TABLE $tmpName LIKE {$tableName}_structure");
if($db->IsError())
{
	Echo '{success:false,error:"'.$db->GetError().'"}';
	exit;
}
if (!isset($linkType))
{
	$linkType = 0;
	$confWhere = ""; 
}
	
if($linkType == 2) $confWhere = " AND flag_bad = 101";
$db->SQLexecute("INSERT INTO $tmpName SELECT * FROM {$tableName}_structure WHERE status = 1 AND status_rec = 1$confWhere");

if($db->IsError())
{
	Echo '{success:false,error:"'.$db->GetError().'"}';
	exit;
}

//tu bomo pol naredli SQL z WHERE za izbrane iz dreve in menija
$checkedIds = $_GET['checkedId'];

if( $checkedIds) {
	$whereArr[] = 'id in ( '.$checkedIds.')';
	
	//tu bomo pol naredli SQL z WHERE za neizbrane iz dreve 
	if(isset($_GET['unCheckedId']))
		$checkedIds = $_GET['unCheckedId'];
	else 	
		$checkedIds = "";
	if ($checkedIds ) {
		$whereArrNot[] = 'id not in ('.$checkedIds.')';		
	}	
}
//tu bomo pol naredli SQL z WHERE za izbrane iz menija
if(isset($_GET['checkedTypes']))
		$checkedIds = $_GET['checkedTypes'];
	else 	
		$checkedIds = "";
		
if ($checkedIds) {
	$whereArr[] = 'tip_sql in ('.$checkedIds.')';
}
if($whereArr)
{
	$whereTmp[] = '( '.implode(' OR ',$whereArr).' )';
}
if(isset($whereArrNot))
{
	$whereTmp[] = '( '.implode(' AND ',$whereArrNot).' )';
}

if($whereTmp)
{
	$where = 'WHERE '.implode(' AND ',$whereTmp);
}
//check if compare user is enabled
if(isset($_POST['compare_user']))
	if($user = $_POST['compare_user'])
	{
		if(substr($user,0,5) == 'admin')
		{
			$userFilter = "user_id = ".substr($user,6)." AND user_type = 1";
		}
		else 
			$userFilter = "user_id = ".$user." AND user_type = 0";
	}
else
	$userFilter = "";

$db->ChangeDatabase(DB_WARPIT_WEBCATI);
$sql = "SELECT * FROM $tableName $where ORDER BY q_pos";

If (!$res = $db->SQLexecute($sql)) {
			//Echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			echo "alert('SQL problem: '".$db->getError()." );";
			exit;	
	}
//lets get the language data
   	$sql = "SELECT * FROM $tableName"."_language INNER JOIN _LanguageText ON id_text_type = id_text WHERE id_language = $id_language";
	$resLng = $db->SQLexecute($sql);
	while ($rowLng = $db->fetchAssoc($resLng))
	{
		$lngArray[ $rowLng['id_question'] ][ $rowLng['variable'] ] = $rowLng['id_text_type'] == 2 ? addslashes( $rowLng['lngText']) : $rowLng['lngText'] ; 
	}
	
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);			
   while ($rowQuestion = $db->fetchAssoc($res)) 
   {
   	if($lngArray[ $rowQuestion['id'] ])
   	foreach ($lngArray[$rowQuestion['id']] as $lngKey => $lngVal) {
   		$rowQuestion[$lngKey] = $lngVal;
   	}
   	$struct = array();
   	$arr = array();   	
   	$q = Question::createQuestion($rowQuestion['tip_sql'],$db,$rowQuestion);
   	$questionType = $rowQuestion['tip_sql'];
   	$q->showVar = $showVar;
   	$q->rowQuestion = &$rowQuestion;
   	if($filter = $_GET['custom_filter'])
   	{
   			$q->filter = 'AND ('.stripslashes( $filter) .')';
   	}
   	if(isset($userFilter))
   	{
   		$q->compareFilter =  'AND ('.$userFilter .')';
   		$q->compareUser = true;
   	}
   	$q->Graphstat = true;
   	$q->HTMLstat = false;
   	
   	$statisticData = $q->createStatistics($rowQuestion,$tmpName);
   
   }
   //initialization:
   	//labels on x-axis
	$maxTextLength = 150; //the max text length in labels on x-axis and legend
	$firstPartTextLength = 115;
	$lastPartTextLength = -30;			
	
	//graph title
	$maxTitleLength = 600;
	$firstPartTitleLength = 450;
	$lastPartTitleLength = -100;
	$charsPerLineTitle = 68;
	
	//legend
	$minLegendWidth = 108;
	$maxLegendWidth = 600;
	$charsPerRow = 80; //chars per row, then <br /> is added
	$rowTextHeight = 20; //like lineHeight in CSS
			
   	switch($questionType)//every question type has it's own graph and graph has it's own calculated height, whether it has a legend or not
	{ 
		case 1: //single response calculations		
			$oneColumnFactor = 120; //bar type, how many pixels for one column
		
			$graphTitle = $statisticData[1];
			$graphTitle = str_replace(array("\n", "\r"), '', $graphTitle);
	        $graphTitle = addslashes($graphTitle);
	        
	        $numColumns_fact = 0;
	        foreach($statisticData[0] as $ser)	// get number of series (graph columns)
	        	if(!isset($ser[4])) //we eliminate openType
	        		$numColumns_fact++;
	        
			$totalGraphHeight = $numColumns_fact * $oneColumnFactor;		
			
			//calculate the width for legend
			$legendWidth = $minLegendWidth; //minimum legend width
			$legendHeight = 0;
			$legendRows = 0;
			$serLength = 0;
						
			foreach($statisticData[0] as $serie)	
			{
				if(!isset($ser[4])) //eliminate openType
				{
					if(strlen($serie[0]) > $serLength)//used for calculating width
						$serLength = strlen($serie[0]); 
						
					$tmp = $serie[0];
					if(strlen($tmp) > $maxTextLength)
	       			{
	       				$firstPart = substr($tmp,0,strpos($tmp,' ',$firstPartTextLength)); 	
						$secondPart = substr($tmp, strrpos($tmp, ' ',$lastPartTextLength)); //get last 30 chars, start at first occurence of ' '		
						$tmp = $firstPart.' /.../ '.$secondPart;	               			
	       			} 	
					$strTemp = wordwrap($tmp,$charsPerRow,'<br/>'); //used for calculating legend height, which will be added to total graph height
					$strArray = explode('<br/>',$strTemp);
					$legendRows += count($strArray);
				}
			}
			if(($legendRows * $rowTextHeight) > $legendHeight)// we assume that it is 20px per one line/row
				$legendHeight = $legendRows * $rowTextHeight;
				
			if($serLength > $charsPerRow)// if it is bigger than the answer length at which it is cut
				$legendWidth = $maxLegendWidth;
			else 
			if($serLength > 18) //assure that legend is never smaller than cca. 100px in width
				$legendWidth = $serLength * 9;

			break;
		case 2: //scale question type
			
				$graphTitle = $statisticData['title'];
				$graphTitle = str_replace(array("\n", "\r"), '', $graphTitle);
		        $graphTitle = addslashes($graphTitle);
		        $scale_sql_type = $statisticData['les_sql'];

		    if($scale_sql_type == 1)
		    {
		    	
		    }		    
		    else
		    if($scale_sql_type == 2) //simple scale and inverted scale
			{
		        //calculate the width for legend
				$legendWidth = $minLegendWidth; //minimum legend width
				$legendHeight;
				$legendRows = 0;
				$serLength = 0;
							
				foreach($statisticData['legend'] as $serie)	
				{
					if(strlen($serie[1]) > $serLength)//used for calculating width
						$serLength = strlen($serie[1]); 
	
					$tmp = $serie[1];
					if(strlen($tmp) > $maxTextLength)
	       			{
	       				$firstPart = substr($tmp,0,strpos($tmp,' ',$firstPartTextLength)); 	
						$secondPart = substr($tmp, strrpos($tmp, ' ',$lastPartTextLength)); //get last 30 chars, start at first occurence of ' '		
						$tmp = $firstPart.' /.../ '.$secondPart;	               			
	       			} 	
					$strTemp = wordwrap($tmp,$charsPerRow,'<br/>'); //used for calculating legend height, which will be added to total graph height
					$strArray = explode('<br/>',$strTemp);
					$legendRows += count($strArray);
				}
				if(($legendRows * $rowTextHeight) > $legendHeight)// we assume that it is 20px per one line/row
					$legendHeight = $legendRows * $rowTextHeight;
					
				if($serLength > $charsPerRow)// if it is bigger than the answer length at which it is cut
					$legendWidth = $maxLegendWidth;
				else 
				if($serLength > 18) //assure that legend is never smaller than cca. 100px in width
					$legendWidth = $serLength * 9; 	
			}
			else 
			if($scale_sql_type == 5)
			{
				//calculate the width for legend
				$legendWidth = $minLegendWidth; //minimum legend width
				$legendHeight;
				$legendRows = 0;
				$serLength = 0;
							
				foreach($statisticData['answers'] as $serie)	
				{
					if(strlen($serie) > $serLength)//used for calculating width
						$serLength = strlen($serie); 
	
					$tmp = $serie;
					if(strlen($tmp) > $maxTextLength)
	       			{
	       				$firstPart = substr($tmp,0,strpos($tmp,' ',$firstPartTextLength)); 	
						$secondPart = substr($tmp, strrpos($tmp, ' ',$lastPartTextLength)); //get last 30 chars, start at first occurence of ' '		
						$tmp = $firstPart.' /.../ '.$secondPart;	               			
	       			} 	
					$strTemp = wordwrap($tmp,$charsPerRow,'<br/>'); //used for calculating legend height, which will be added to total graph height
					$strArray = explode('<br/>',$strTemp);
					$legendRows += count($strArray);
				}
				if(($legendRows * $rowTextHeight) > $legendHeight)// we assume that it is 20px per one line/row
					$legendHeight = $legendRows * $rowTextHeight;
					
				if($serLength > $charsPerRow)// if it is bigger than the answer length at which it is cut
					$legendWidth = $maxLegendWidth;
				else 
				if($serLength > 18) //assure that legend is never smaller than cca. 100px in width
					$legendWidth = $serLength * 9; 								
			}
	        $totalGraphHeight += 400 + $legendHeight;
			break;
		case 3:
			if(array_key_exists('series',$statisticData)) //
			{					
				$graphTitle = $statisticData['rowQuest'];
				$graphTitle = str_replace(array("\n", "\r"), '', $graphTitle);
	        	$graphTitle = addslashes($graphTitle);
	        	
	        	$oneColumnFactor = 120; //bar type, how many pixels for one column
	        	$numColumns_fact = count($statisticData['series']); // get number of series (graph columns)
				$totalGraphHeight = $numColumns_fact * $oneColumnFactor;	
	        	
	        	//we calculate the factor height for graph for each individual element on the graph
				$numColumns_fact = 0;
				$numCategories_fact = 0;				
				$legend_fact = 0;
				
			}
			else // if we have more series	
			{ 			
				$graphTitle = $statisticData[0]['rowQuest'];
				$graphTitle = str_replace(array("\n", "\r"), '', $graphTitle);
	        	$graphTitle = addslashes($graphTitle);
	        	
				//we calculate the factor height for graph for each individual element on the graph
				$numColumns_fact = 0;
				$numCategories_fact = 0;				
				$legend_fact = 0;
				
				$numColumns_fact = count($statisticData[0]['series']);
				$numSeries_fact = count($statisticData);

				$totalGraphHeight = $numColumns_fact * 30 * $numSeries_fact;
				
				foreach($statisticData as $stData)
				{				
					if(strlen($stData['columnName']) > $maxTextLength) //if it is longer than this value, it will be truncated, so we have fixed factor
						$numCategories_fact += 70;
					else 					
						$numCategories_fact += round((strlen($stData['columnName']) / 95) * 10, 0);//for each sentence row we calculate the height					
				}

				$legendWidth = $minLegendWidth; //minimum legend width
				$legendHeight;
				$legendRows = 0;
				$serLength = 0;
							
				foreach($statisticData[0]['series'] as $serie)	
				{
					if(strlen($serie[0]) > $serLength)//used for calculating width
						$serLength = strlen($serie[0]); 
						
					$tmp = $serie[0];
					if(strlen($tmp) > $maxTextLength)
	       			{
	       				$firstPart = substr($tmp,0,strpos($tmp,' ',$firstPartTextLength)); 	
						$secondPart = substr($tmp, strrpos($tmp, ' ',$lastPartTextLength)); //get last 30 chars, start at first occurence of ' '		
						$tmp = $firstPart.' /.../ '.$secondPart;	               			
	       			} 	
					$strTemp = wordwrap($tmp,$charsPerRow,'<br/>'); //used for calculating legend height, which will be added to total graph height
					$strArray = explode('<br/>',$strTemp);
					$legendRows += count($strArray);					
				}
				//echo 'dolzina = '.$serLength;
				if(($legendRows * $rowTextHeight) > $legendHeight)// we assume that it is 20px per one line/row
					$legendHeight = $legendRows * $rowTextHeight;
					
				if($serLength > $charsPerRow)// if it is bigger than the answer length at which it is cut
					$legendWidth = $maxLegendWidth;
				else 
				if($serLength > 18) //assure that legend is never smaller than cca. 100px in width
					$legendWidth = $serLength * 9; //echo $legendWidth;
			}
			break;
		case 4: //open type question
			$graphTitle = $statisticData[1];
			$graphTitle = str_replace(array("\n", "\r"), '', $graphTitle);
        	$graphTitle = addslashes($graphTitle);
			break;
		default: 
			$graphTitle = "";
			break;
	}
		
	if(strlen($graphTitle) > $maxTitleLength) //format the graph title
	{
		//get first 450 chars, cut after first occurence of ' '
		$firstPart = substr($graphTitle,0,strpos($graphTitle,' ',$firstPartTitleLength)); 	
		$secondPart = substr($graphTitle, strrpos($graphTitle, ' ',$lastPartTitleLength)); //get last 100 chars, start at first occurence of ' '

		$graphTitle = $firstPart.' /.../ '.$secondPart;
	}	
		//calculating graph margin cause of dynamic graph title length (if u change the title )	
	$graphMarginTop = 75+15 * (ceil(strlen($graphTitle) / $charsPerLineTitle));  //get the number of lines in graph title (68chr/line) .... number of lines affects graph height
	$totalGraphHeight += $graphMarginTop;
	
	if($totalGraphHeight < 500)
		$totalGraphHeight = 500;
?>

<head>
  <title>Basic Statistic</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <style type="text/css">
  table
	{ 
	margin-left: auto;
	margin-right: auto;
	}
	
	div#graphContainer{
		 width: 800px; 
		 height: <?php echo $totalGraphHeight?>px; 
		 margin: 0 auto;
	}
	
	button#changeGraphType
	{
		visibility: hidden;
	}
  </style>
   <script type="text/javascript" src="<?php echo PATH_TO_ROOT;?>_support/jquery.js"></script>
   <script type="text/javascript" src="<?php echo PATH_TO_ROOT;?>_plugins/charts/js/highcharts.js"></script>
   <script type="text/javascript" src="<?php echo PATH_TO_ROOT;?>_plugins/charts/js/modules/exporting.js"></script>
   <script type="text/javascript">	
   var chart1; // globally available	   

   function changeChartType() {
		chart = chart1;			
		series = chart1.series;  	
		currType = series[0].type.toLowerCase();
		barChartHeight = <?php echo $totalGraphHeight?>;		
		pieChartHeight = <?php 
//			if(($totalGraphHeight+$legendHeight)>900)
//		 		echo 900;
//		 	else 
		 	if(($totalGraphHeight+$legendHeight) < 700)
		 		echo 700;
		 	else
		 		echo $totalGraphHeight + $legendHeight;
		 	?>;	
		
	    if(series[0].options.data.length < 9)
	    {
	    	if(currType == 'pie')
			{
				newType = 'bar'; //we switched to bar type, so we have to turn off legend		
				$('.highcharts-legend', chart1.container).hide();	
				//$('#graphContainer').height(barChartHeight);
					
			}
			else
			{
				chart.xAxis.setVisible(false);		
				$('.highcharts-container', chart1.container).hide();
				chart.yAxis.setVisible(false);	
			
				newType = 'pie';//we switched to pie type, so we have to turn on legend
				$('.highcharts-legend', chart1.container).show();
			}
	  	    for (var i = 0; i < series.length; i++) {
	  	        var srs = series[0];
	  	        if(newType == 'bar') 
	  	        {//we set bar color to blue, that other colors does not appear
		   	        	srs.color = '#4572A7';
		   	        	srs.yaxis = null;
	  	        }
	  	        else
		        if(newType == 'pie')
		        {	        	
		        	srs.color = ['#4572A7','#AA4643','#89A54E','#80699B','#3D96AE','#DB843D','#92A8CD','#A47D7C','#B5CA92'];		        
		        } 
	  	        try {
	  	            srs.chart.addSeries({
	  	                type: newType,
	  	                stack: srs.stack,
	  	                yaxis: srs.yaxis,
	  	                name: srs.name,
	  	                color: srs.color,
	  	                data: srs.options.data
	  	            },
	  	            false);
	  	            series[0].setVisible(false);//chart1.xAxis.setVisible(false);
	  	         series[0].remove(true);
	  	         chart.redraw();
	  	        } catch (e) {
		   	        	alert('Error: '+e.message);break;
	  	        }
	  	    }
	  	  if(currType == 'pie')
			{
				chart.setSize(800,barChartHeight);	
				
			}
			else
			{
				chart.setSize(800,pieChartHeight);
				chart.xAxis.setVisible(false);		
				chart.yAxis.setVisible(false);
			}
  	  	
  	    	return newType;
	    }
	    else
	   	    alert('Too many answers to show pie chart.');	   	    
	}

	   
	   $(document).ready(function() { //a function for switching between bar and pie chart	
		   $('#changeGraphType').click(function(){
			   type = changeChartType();			
			});		 
	<?php 
	switch($questionType)
	{
		case 1: //single response				 
				$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'bar',
	               plotShadow: false,
	               marginTop:$graphMarginTop";									
				$chartConf.="	                                        
	            },
	            credits:{enabled: false}, 
	            legend: {
	            	id:'singleResponseGraph',
	            	enabled: true,	            	
					width: $legendWidth,
					height: $legendHeight,
	            	layout: 'vertical',
	            	marginTop: 500,
	            	itemWidth: 50,
	            	labelFormatter: function(){
	            		width = 80;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.name; 	            		
						if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
		            	{
							str1 = str.substr(0,115); //how many first chars
							str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
				
							str2 = str.substr((str.length-30)); //how many last chars 
							str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
							str = str1 + ' /../ ' + str2;
						}						
					    	    					 	
					    if (!str) { return str; }				 
						//next 20 lines of code was copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return output.join(brk);
	            	}
				},	     
	            title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            		},
	            },
	            plotOptions:{
					bar:{
						groupPadding: 0.01,
						dataLabels:{
							formatter: function() {		            	
				            	width = 90;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.series.name; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /.rrrrrr./ ' + str2;
								}						
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code was copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return output.join(brk);				 
				            },
						},
					},
					pie:{
						dataLabels:{
							formatter: function() {		
							    multiplier = Math.pow(10, 2);
							    proc = Math.round(this.percentage * multiplier) / multiplier;   								                
							    return '<b>'+ proc+'%</b>';					 
				            },
				            connectorPadding: 10,
				            softConnector: true,				            			            
				            overflow: 'justify'
						},
						//center: ['50%', '50%'],
						showInLegend: true,
						size: 300,
						cursor: 'pointer',
						allowPointSelect: true,
					}
	            },
	            xAxis: {
	               categories: [";
	               	foreach($statisticData[0] as $data)
	               	{
	               		if(!isset($data[4])) //eliminate openType fields
	               		{
	               			$tmp = $data[0];
	               			$tmp = str_replace(array("\n", "\r"), '', $tmp);
	            			$tmp = addslashes($tmp); 		               				
			               	$chartConf .= "'$tmp',";
	               		}
	               	}
   				$chartConf .="],	               	
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '13px'
						},
						align: 'right',
						formatter: function() {				            					            	
				            	width = 37;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.value; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}					
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);
				            },
					},
					showEmpty: false					
   				},
   				yAxis: {
	               title: {
	                  text: '$statisticData[2]',
	                  style: {	            		
							color: '#575859',
							fontSize: '10px'		
	            		},
	            		align: 'high',
	            		margin: 30
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}},
	               showEmpty: false
	            },
				tooltip:{
					formatter: function() {
            			width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.point.name;   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return  '<b>Answer: </b>'+output.join(brk)+'<br /><b>Value: </b>'+this.y+'%';									   			 
		            }
				},
	            series: [{          
	            	type: '"; 
	            	if(count($statisticData[0]) < 9)
	            		$chartConf .="pie',";
	            	else 
	            		$chartConf .="bar',";
	            	$chartConf .="
	            	name: '$statisticData[2]',	 
	            	data: [";
				            foreach($statisticData[0] as $data)
				            	if(!isset($data[4])) //eliminate openType fields
				            	{
							        $tmp = $data[0];
			               			$tmp = str_replace(array("\n", "\r"), '', $tmp);
			            			$tmp = addslashes($tmp);
				   					$chartConf .= "['$tmp',".round($data[2],2)."],";
				            	}				            
			   						            
	            $chartConf .= "]}]";
   				
   				
   				echo $chartConf;
			break;
		case 2:	//scale
			if($scale_sql_type == 1) //simple scale
			{
				$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'line',
	               marginTop: $graphMarginTop";								
				$chartConf.="	                             
	            },
	            credits:{enabled: false},
	            legend: {enabled: false},
	            //colors:['#4572A7','#4572A7','#4572A7','#4572A7','#4572A7'],
	            
				title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            		},
	            },
	            xAxis: {
	               categories: [";
	               		foreach($statisticData['answers'] as $data)
	               		{
	               			$tmp = $data;
	               			$tmp = str_replace(array("\n", "\r"), '', $tmp);
	            			$tmp = addslashes($tmp);	               				 
	               			$chartConf .= "'$tmp',";
	               		}
	               			
   				$chartConf .= "],
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '14px',
   							//wrap: 'hard'
						},
						rotation: 0,
                		align: 'center',
                		formatter: function() {				            					            	
				            	width = 15;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.value; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}					
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);
				            },
					}
   				},
   				yAxis: {
	               title: {
	                  text: 'Mean values (".$statisticData['numerusLabel'].")',
	                  style: {	            		
						color: '#575859',
						fontSize: '11px'						
	            		},
	            		align: 'middle'
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}},
	               min: ".$statisticData['graphMin'].",
	               max: ".$statisticData['graphMax']."
	            },
	            tooltip: {
		            formatter: function() {
		            	width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.x;   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return  '<b>Answer: </b>'+output.join(brk)+'<br /><b>Mean value: </b>'+this.y;					 
		            }
		        },
	            series: [{data:[";   					
   					foreach($statisticData['series'] as $serie)   					
   						$chartConf .= round($serie[4],2).',';
	   					
	   				$chartConf .= "]},";
   									            
	            $chartConf .= "], marker:{lineColor: 'red'}";
   				
   				
   				echo $chartConf;
			}
			else
			if($scale_sql_type == 2) //scale with columns (for each answer, we have more options(drop-downs))
			{
				$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'line',
	               marginTop: $graphMarginTop";				
				$chartConf.="	                             
	            },
	            credits:{enabled: false},
	            legend: {
	            	enabled: true,
	            	layout: 'vertical',
	            	width: $legendWidth,
					height: $legendHeight,
	            	layout: 'vertical',
	            	itemWidth: 300,
					labelFormatter: function(){
	            		width = 80;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.name; 	            		
						if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
		            	{
							str1 = str.substr(0,115); //how many first chars
							str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
				
							str2 = str.substr((str.length-30)); //how many last chars 
							str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
							str = str1 + ' /../ ' + str2;
						}						
					    	    					 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return output.join(brk);
	            	}	            	
				},
	            //colors:['#4572A7','#4572A7','#4572A7','#4572A7','#4572A7'],
	            
				title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            		},
	            },
	            xAxis: {
	               categories: [";
	               		foreach($statisticData['answers'] as $data)
	               		{
	               			$tmp = $data;
	               			$tmp = str_replace(array("\n", "\r"), '', $tmp);
	            			$tmp = addslashes($tmp);
	               			$chartConf .= "'$tmp',";
	               		}
	               			
   				$chartConf .= "],
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '14px'
						},
						rotation: 0,
                		align: 'center',
                		formatter: function() {
				            	str = this.value;				            	
								width = 15;  //the length of row, where to split
			            		brk = '<br />'; //the break chars			            		   
			            		if(str.length > 150)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}		 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);	
				            }
					}
   				},
   				yAxis: {
	               title: {
	                  text: 'Mean values (".$statisticData['numerusLabel'].")',
	                  style: {	            		
						color: '#575859',
						fontSize: '11px'						
	            		},
	            		align: 'middle'
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}},
	               min: ".$statisticData['graphMin'].",
	               max: ".$statisticData['graphMax'].",	               
	               tickInterval: 1
	            },
	            tooltip: {
		            formatter: function() {
		            	str = this.x;				            	
						width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars            		   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}					   		                
					    return '<b>Answer:</b> ' + output.join(brk) + '<br/><b>Mean value:</b> '+ this.y;					 
		            }
		        },
	            series: [";   					
   					$j=0;
   					foreach($statisticData['legend'] as $leg)
   					{    
   						$leg[1] = str_replace(array("\n", "\r"), '', $leg[1]);
	            		$leg[1] = addslashes($leg[1]);
	            		
	            		$tmp = $leg[1];
   						$chartConf .= "{name: '".$tmp."',
   										data:[";
	   					foreach($statisticData["answers"] as $an)
	   					{
		   					$chartConf .= round($statisticData['series'][$j][4],2).",";
		   					$j++;
	   					}
	   					$chartConf .= "]},";
   					}				            
	            $chartConf .= "], marker:{lineColor: 'red'}";
   				
   				
   				echo $chartConf;
			}
			else //if it is inverted scale (les_sql = 5)
				if($scale_sql_type == 5)
				{
					$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'bar',
	               marginTop:$graphMarginTop";				
				$chartConf.="	                             
	            },
	            credits:{enabled: false},
	            legend: {
	            	enabled: true,
	            	layout: 'vertical',
	            	width: $legendWidth,
					height: $legendHeight,	            
	            	itemWidth: 300,
					labelFormatter: function(){
	            		width = 80;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.name; 	            		
						if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
		            	{
							str1 = str.substr(0,115); //how many first chars
							str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
				
							str2 = str.substr((str.length-30)); //how many last chars 
							str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
							str = str1 + ' /../ ' + str2;
						}						
					    	    					 	
					    if (!str) { return str; }				 
						//next 20 lines of code was copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return output.join(brk);
	            	}	            		
				},
	            //colors:['#4572A7','#4572A7','#4572A7','#4572A7','#4572A7'],
	            
				title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            		},
	            },
	            plotOptions:{
					bar:{
						groupPadding: 0.01						
					}
	            },
	            xAxis: {
	               categories: [";
	               		foreach($statisticData['legend'] as $leg)
	               		{
	               			$tmp = $leg[1];
	               			$tmp = str_replace(array("\n", "\r"), '', $tmp);
	            			$tmp = addslashes($tmp);
	               			$chartConf .= "'$tmp',";
	               		}
	               			
   				$chartConf .= "],
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '14px'
						},
						rotation: 0,
                		align: 'right',
                		formatter: function() {				            					            	
				            	width = 37;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.value; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}					
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);
				            },
					}
   				},
   				yAxis: {
	               title: {
	                  text: '".$statisticData['numerusLabel']."',
	                  style: {	            		
						color: '#575859',
						fontSize: '10px'						
	            		},
	            		align: 'high',
	            		margin: 30
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}}
	            },
	            tooltip: {
		            formatter: function() {
		            	str = this.series.name;				            	
						width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars            		   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}					   		                
					    return '<b>Answer:</b> ' + output.join(brk) + '<br/><b>Value:</b> '+ this.y;					 
		            }
		        },
	            series: [";
   					//$numSeries = count($statisticData["series"]) / count($statisticData["answers"]);
   					$j=0;
   					foreach($statisticData['answers'] as $an)
   					{
   						$chartConf .= "{name: '".$an."',
   										data:[";
	   					foreach($statisticData["legend"] as $leg)
	   					{
		   					$chartConf .= round($statisticData['series'][$j][4],2).",";
		   					$j++;
	   					}
	   					$chartConf .= "]},";
   					}				            
	            $chartConf .= "], marker:{lineColor: 'red'}";
   				
   				
   				echo $chartConf;				
				}
			break;
		case 3: //multiresponse
			if(array_key_exists('series',$statisticData)) //if we have one serie array
			{
				//if(strlen($statisticData['rowQuest']) > 500) $statisticData['rowQuest'] = substr($statisticData['rowQuest'],0,strpos($statisticData['rowQuest'],' ',500)).' ...'; 
				$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'bar',
	               marginTop: $graphMarginTop";				
				$chartConf.="	                             
	            },
	            credits:{enabled: false},
	            legend: {enabled: false},
	            colors:['#4572A7','#4572A7','#4572A7','#4572A7','#4572A7'],
	            
				title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            	},
	            		
	            },
	            plotOptions:{
					bar:{
						groupPadding: 0.01
					}
	            },
	            xAxis: {
	               categories: [";
	               		foreach($statisticData['series'] as $data)
	               		{
	               			$data[0] = str_replace(array("\n", "\r"), '', $data[0]);
	            			$data[0] = addslashes($data[0]);
	            			$tmp = $data[0];	
	               			$chartConf .= "'$data[0]',";
	               		}               			
	               			
   				$chartConf .= "],
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '13px'
						},
                		align: 'right',
                		formatter: function() {				            					            	
				            	width = 37;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.value; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}					
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);
				            },
					}
   				},
   				yAxis: {
	               title: {
	                  text: '".$statisticData["answN"]."',
	                  style: {	            		
						color: '#575859',
						fontSize: '10px'						
	            	  },
	            	  align: 'high',
	            	  margin: 30
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}}
	            },
	             tooltip: {
		            formatter: function() {
		            	width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.x;   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return  '<b>Answer: </b>'+output.join(brk)+'<br /><b>Value: </b>'+this.y;					 
		            }
		        },
	            series: [
	            	{
	            		name: '".$statisticData["answN"]."', 
	            		data: [";
				            foreach($statisticData["series"] as $data)
			   					$chartConf .= "$data[1],";
			   						            
	            $chartConf .= "], marker:{lineColor: 'red'}}]";
   				
   				
   				echo $chartConf;
			}
			else // if we have more series in array (more categories for one answer)
			{				 
				$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'bar',
	               //height: 800,
	               marginTop: $graphMarginTop";								
				$chartConf .="	                             
	            },
	            credits:{enabled: false},
	            legend: {
	            	enabled: true,
	            	width: $legendWidth,
	            	height: $legendHeight,
	            	layout: 'vertical',
	            	itemWidth: 100,
	            	reversed: true,
					labelFormatter: function(){
	            		width = 80;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.name; 	            		
						if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
		            	{
							str1 = str.substr(0,115); //how many first chars
							str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
				
							str2 = str.substr((str.length-30)); //how many last chars 
							str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
							str = str1 + ' /../ ' + str2;
						}						
					    	    					 	
					    if (!str) { return str; }				 
						//next 20 lines of code was copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return output.join(brk);
	            	}
				},
	            //colors:['#4572A7','#4572A7','#4572A7','#4572A7','#4572A7'],
	            
				title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            		},
	            },
	            plotOptions:{
					bar:{
						groupPadding: 0.01						
					}
	            },
	            xAxis: {
	               categories: [";					
						foreach($statisticData as $data)
						{							 
							$data['columnName'] = str_replace(array("\n", "\r"), '', $data['columnName']);
	            			$data['columnName'] = addslashes($data['columnName']);	            				
		               		$chartConf .= "'".$data['columnName']."',";	
						}               			
	               			
   				$chartConf .= "],
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '13px'
						},
                		align: 'right',
                		formatter: function() {				            					            	
				            	width = 37;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.value; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}					
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);
				            },
					}					
   				},
   				yAxis: {
	               title: {
	                  text: '".$statisticData[0]["answN"]."',
	                  style: {	            		
						color: '#575859',
						fontSize: '10px'						
	            	  },
	            	  align: 'high',
	            	  margin: 30
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}}
	            },
	            tooltip:{
					formatter: function() {
            			width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.series.name;   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
					    return  '<b>Answer: </b>'+output.join(brk)+'<br /><b>Value: </b>'+this.y;									   			 
		            }
				},
	            series: [";   	
   					$series = array();
   					foreach($statisticData as $ser)
   						$series[] = $ser["series"];
   					$i = 0;
	            	foreach($statisticData[0]["series"] as $val)
	            	{	        
	            		$val[0] = str_replace(array("\n", "\r"), '', $val[0]);
	            		$val[0] = addslashes($val[0]); 
	            		$chartConf .= "{
	            		name: '".$val[0]."', 
	            		data: [";   							    								
			   			foreach($series as $data)			   					
	            			$chartConf .= $data[$i][1].",";
			   			$chartConf .= "]},";
			   			$i++;	
	            	}
	            $chartConf .= "],
	            	marker:{lineColor: 'red'}";
	            
   				echo $chartConf;
			}
				
			break;
		case 4: //open type question
			$chartConf = "chart1 = new Highcharts.Chart({ chart: {
	               renderTo: 'graphContainer',
	               type: 'bar',
	               marginTop: $graphMarginTop";				
				$chartConf.="	                             
	            },
	            credits:{enabled: false},
	            legend: {enabled: false},
	            colors:['#4572A7','#4572A7','#4572A7','#4572A7','#4572A7'],
	            
				title: {
	            	text: '$graphTitle',
	            	style: {	            		
						color: '#575859',
						fontSize: '16px',
						width: '600'										
	            	},
	            		
	            },
	            plotOptions:{
					bar:{
						groupPadding: 0.01
					}
	            },
	            xAxis: {
	               categories: [";
	               		foreach($statisticData[0] as $data)
	               		{
	               			$data[0] = str_replace(array("\n", "\r"), '', $data[0]);
	            			$data[0] = addslashes($data[0]);
	            			$tmp = $data[0];	
	               			$chartConf .= "'$data[0]',";
	               		}               			
	               			
   				$chartConf .= "],
   					lineColor: '#666666',
   					tickColor: '#666666',
   					labels: {
   						style:{
   							color: '#666666', 
   							fontSize: '13px'
						},
                		align: 'right',
                		formatter: function() {				            					            	
				            	width = 37;  //the length of row, where to split
			            		brk = '<br />'; //the break chars
			            		str = this.value; 	            		
								if(str.length > 150) //if it is too long, make it shorter (aprox. 150 chars)
				            	{
									str1 = str.substr(0,115); //how many first chars
									str1 = str1.substr(0,str1.lastIndexOf(' ')); //cut nicely at ' '
						
									str2 = str.substr((str.length-30)); //how many last chars 
									str2 = str2.substr(str2.indexOf(' ')); //cut nicely at ' '
									str = str1 + ' /../ ' + str2;
								}					
							    	    					 	
							    if (!str) { return str; }				 
								//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
								words = str.split(' ');						
								lengths = [];
								for (var i = 0; i < words.length; i++)
								  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
								
								line = [], offset = 0, output = [];
								for (var i = 0; i < words.length; i ++) {
								  if (offset + (lengths[i] + line.length - 1) < width) {
								    line.push(words[i]);
								    offset += lengths[i];
								  }
								  else {
								    output.push(line.join(' '));
								    offset = 0; line = [], i -= 1;
								  }
								  if (i == words.length - 1)
								    output.push(line.join(' '));
								}
							    return  output.join(brk);
				            },
					}
   				},
   				yAxis: {
	               title: {
	                  text: '".$statisticData[2]."',
	                  style: {	            		
						color: '#575859',
						fontSize: '10px'						
	            	  },
	            	  align: 'high',
	            	  margin: 30
	               },
	               labels: {style:{color: '#666666', fontSize: '13px'}}
	            },
	             tooltip: {
		            formatter: function() {
		            	width = 100;  //the length of row, where to split
	            		brk = '<br />'; //the break chars
	            		str = this.x;   
	            				 	
					    if (!str) { return str; }				 
						//next 20 lines of code were copied, but WORKS!!! RegExp didn't work in that charts!'
						words = str.split(' ');						
						lengths = [];
						for (var i = 0; i < words.length; i++)
						  lengths.push(words[i].replace(/<.+>/g, '').replace(/&.+;/g, ' ').length);
						
						line = [], offset = 0, output = [];
						for (var i = 0; i < words.length; i ++) {
						  if (offset + (lengths[i] + line.length - 1) < width) {
						    line.push(words[i]);
						    offset += lengths[i];
						  }
						  else {
						    output.push(line.join(' '));
						    offset = 0; line = [], i -= 1;
						  }
						  if (i == words.length - 1)
						    output.push(line.join(' '));
						}
						multiplier = Math.pow(10, 2);
						proc = Math.round(this.y * multiplier) / multiplier;
					    return  '<b>Answer: </b>'+output.join(brk)+'<br /><b>Value: </b>'+proc+'%';					 
		            }
		        },
	            series: [
	            	{
	            		name: '".$statisticData[2]."', 
	            		data: [";
				            foreach($statisticData[0] as $data)
			   					$chartConf .= "$data[2],";
			   						            
	            $chartConf .= "], marker:{lineColor: 'red'}}]";
   				
   				
   				echo $chartConf;
			break;
		default:
				echo "alert('Error: No question type defined!');";
			break;
	}			
		?>	           
	         });
       <?php 
       	if($questionType == 1)
       		echo "if(chart1.series[0].type == 'bar') //we have to hide the legend for bar chart type
		   $('.highcharts-legend', chart1.container).hide();";
       ?>
      // alert($('.highcharts-legend-item').width());
	
	   if(chart1.series[0].type == 'pie')
		   	if($('#graphContainer').height() < 800)
		   		chart1.setSize(800,800);
	   		        
	      });
	      

	   
   </script>
   
  
</head>
<body>
<div id="graphContainer"></div>
<?php 
	if($questionType == 1)
		echo "<button id=\"changeGraphType\" visibility=\"hidden\">Switch graph type</button>"; 
?>

<?php 
		 function formatJSONforEye($arr){
		    $retStr = '<ul>';
		    if (is_array($arr)){
		        foreach ($arr as $key=>$val){
		            if (is_array($val)){
		                $retStr .= '<li>' . $key . ' => ' . formatJSONforEye($val) . '</li>';
		            }else{
		                $retStr .= '<li>' . $key . ' => ' . $val . '</li>';
		            }
		        }
		    }
		    $retStr .= '</ul>';
		    return $retStr;
		}
//echo $questionType.' type.';
//echo formatJSONforEye($statisticData); 

?>	

</body>
</html>