<?php
			unset($totalCondition);
	 		/*echo "<pre>";
				var_dump($scoreFactors);
			echo "<pre>";*/
			//echo "multi";
			
			foreach ($colTypesStructure[$key] as $key_code => $keyVar) {
				
				$sqlUnion = array();
		
				foreach ($grp[$grKey] as $proj1) {
					$sql = "SELECT count(*) as n , ".$keyVar." as varName FROM ".$proj1."_structure WHERE flag_bad=101 AND ".$keyVar." > 0 ";
					if ($filter) $sql .=" AND ( ".$filter." )";	
					$sql .= " GROUP BY ".$keyVar;
					$sqlUnion[] = $sql;		
				}
				
				$sql = "(".implode(") UNION ALL (",$sqlUnion)." ) ";
				//if ($specialLogging) echo $sql."<br>";
				//echo $_SERVER['REMOTE_ADDR'];
				$res = $db->SQLexecute($sql);
				//$zad = $db->fetchAssoc($res);
				$n = 0;
				while ($zad = $db->fetchAssoc($res)) $n += $zad['n'];
				//$freq[$keyVar] = $zad['n'];	
				 $freq[$keyVar] = $n;
				$totalCondition[$keyVar] = $keyVar." > 0 ";
				
				if ($_GET['showPonders']) {
					if (!$scoreFactors[$key][$zad['varName']]) $scoreFactors[$key][$zad['varName']] = 1;				
					$freqPonder[$keyVar] =  $n * $scoreFactors[$key][$zad['varName']] ;	
				}
												
			}
			
				$sqlUnion = array();
			
				foreach ($grp[$grKey] as $proj1) {
					$sql = "SELECT count(*) as n  FROM ".$proj1."_structure WHERE flag_bad=101 AND ( ";
					$sql .= implode(" OR ",$totalCondition);
					$sql .= " ) ";
					if ($filter) $sql .=" AND ( ".$filter." )";	
					$sqlUnion[] = $sql;
				}
				$sql = "(".implode(") UNION ALL (",$sqlUnion)." ) ";
				//echo $sql;
				$res = $db->SQLexecute($sql);
				/*$zad = $db->fetchAssoc($res);
				$total = $zad['n'];	*/
				while ($zad = $db->fetchAssoc($res)) $total += $zad['n'];
				
				//if ($specialLogging) echo $sql."<br>";
				
				$Graph['titel'] = $val;
				foreach ($colAns[$key] as $labVal) {
					$Graph['labels'][] = $labVal[1];
					$Graph['values'][] =  round( ($freq[$key."_".$labVal[0]]/$total) * 100,2);	
				}
				
				if ($_GET['showPonders']) {
					$GraphPonder['titel'] = $val."<br />* \"weighted\"";
					foreach ($colAns[$key] as $labVal) {
						$GraphPonder['labels'][] = $labVal[1];
						$GraphPonder['values'][] =  round( ($freqPonder[$key."_".$labVal[0]]/$total) * 100,2);
					}	
				}
				
				if ($_GET['showTable']) {
				
					echo "<table class=\"reportTable\" cellpadding=\"5\" cellspacing=\"0\" width=\"600\" align=\"center\">";
						echo "<tr>
									<td class=\"TableHeader\">".($_GET['showVarName'] ? $key." " : "" ).$val."</td>
							 		<td class=\"TableHeader\" width=20>N</td>
							 		<td class=\"TableHeader\" width=20>%</td>";
						if ($_GET['showPonders']) {
							echo 	   "<td class=\"TableHeader\" width=20>N<br><small>(ponder)</small></td>
							 			<td class=\"TableHeader\" width=20>%</td>";
						}
						echo	"</tr>";
						foreach ($colAns[$key] as $labVal) {
							echo "<tr>";
								echo "<td>".$labVal[1]."</td>";
								echo "<td align=\"center\">";
									if (!$freq[$key."_".$labVal[0]]) echo "0";
										else echo $freq[$key."_".$labVal[0]];
								echo "</td>";
								echo "<td align=\"center\">";
									if (!$freq[$key."_".$labVal[0]]) echo "0";
										else {							
											echo number_format(( round( ($freq[$key."_".$labVal[0]]/$total) * 100,2)),1);
										}
									
								echo "</td>";
							if ($_GET['showPonders']) {
								echo "<td align=\"center\">";
									if (!$freqPonder[$key."_".$labVal[0]]) echo "0";
										else echo $freqPonder[$key."_".$labVal[0]];
								echo "</td>";
								echo "<td align=\"center\">";
									if (!$freqPonder[$key."_".$labVal[0]]) echo "0";
										else {							
											echo number_format(( round( ($freqPonder[$key."_".$labVal[0]]/$total) * 100,2)),1);
										}
									
								echo "</td>";
							}
							echo "</tr>";
						}
						echo "<tr>";
							echo "<td class=\"TableHeader\" style=\"text-align:right\">TOTAL</td>";
							echo "<td class=\"TableHeader\">".$total."</td>";
							echo "<td class=\"TableHeader\" >100%</td>";
							if ($_GET['showPonders']) {
								echo "<td class=\"TableHeader\">".$total."</td>";
								echo "<td class=\"TableHeader\" >100%</td>";
							}
						echo "</tr>";
					echo "</table>";
				}
				
				if ($_GET['showGraph']) {
					// control if we have max % over 100 and not ponders to fix the scale not to go over 100%
					if (max($Graph['values']) > 90 && !$_GET['showPonders']) $max = 100; else $max = 0;
					
					
					if ( count($Graph['labels']) * 50 < 400 ) $GraphHeight = 400; else $GraphHeight = count($Graph['labels']) * 50;
					
					echo  "<script type=\"text/javascript\">
					$(function () {
					    
					    $(document).ready(function() {
					         new Highcharts.Chart({
					            chart: {
					                renderTo: 'container".$key."x".$grKey."',
					                type: 'bar'
					            },
					            title: false,
					            tooltip: {
					                formatter: function() {
					                //console.log(this);
					                    return this.key +': '+ this.y + '%';
					                }
				            	},
					            credits: {
								    enabled: false
								},
					            xAxis: {
				                	categories: ['".implode("','",$Graph['labels'])."']
					            },
					            yAxis: {
				              		min: 0,
				              		".($max ? "max:100," : "")."
					          	   
					                title: {
					                	text: '%'
					           		}
				            	},
				            	 legend: {
						           	enabled: false
						         },
				            	  plotOptions: {
						                bar: {
						                    dataLabels: {
						                        enabled: true,
						                         formatter: function(a,val) {
							                    	//console.log(a);
							                       return  this.y + ' %';
							               		 }
						                    }
						                }
						            },
	
						         series: [{
					               
					                name: ' ',
					                data: [";
					                 	unset($tmp);
										foreach ($Graph['labels'] as $key1=>$val) $tmp[] = "['".$val."',".round($Graph['values'][$key1],1)."]";
										echo implode(",",$tmp);
									
									echo "]
						         }";
								if ($_GET['showPonders']) {
									echo ",{ name: ' ', data: [ ";
									unset($tmp);
									foreach ($GraphPonder['labels'] as $key1=>$val) $tmp[] = "['".$val." * \"weighted\" ',".round($GraphPonder['values'][$key1],1)."]";
									echo implode(",",$tmp);
									echo "]}";
						         
								}
									
							echo "
					            ]
					        });
					    });
					    
					});
					</script>	
						<div class=\"graphTitel\">".$Graph['titel']."</div>
						<div id=\"container".$key."x".$grKey."\" style=\"width: 600px;  height: ".$GraphHeight."px; padding-top:20px; margin: 0 auto\"></div>";
				} // end if  ($_GET['showGraph']) 
				else echo "<div  style=\"width: 600px;  height: 50px; \"></div>";
?>