<script type="text/javascript" src="/json2.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
	google.load('visualization', '1', {packages: ['geomap', 'table']});
	
	/*var wait=function(millisec){
		var date=new Date();
		var curDate= null;
		do{
			curDate= new Date();
			
		}while(curDate-date < millisec);
	
	};*/
	var refreshTime=180000;			//millisec time of the refresh here is set 3 minutes
	
function drawVisualization() {
	var updated=false;
	var currentSelected=null;
	
	function createCountryTable(){
		var countryT = new google.visualization.DataTable();
		
		countryT.addColumn('number', 'LATITUDE', 'Latitude');
		countryT.addColumn('number', 'LONGITUDE', 'Longitude');
		countryT.addColumn('number', 'Num Hosts', 'Value');
		countryT.addColumn('string', 'City', 'Hover');
		return countryT;
	}
	
		
	var data = new google.visualization.DataTable();	/*main table that retain information on each */
	var array= {};						/*associative array for countrycode->ObjTableCityForCountry */

	var emptyTable = createCountryTable();			/*empty table used for enabling the selection
						 		*(and the zooming) of countries with no traffic recorded 
						 		*/
	emptyTable.addRow( [0.000000, 0.000000, 0, 'None'] );
	
	data.addColumn('string', 'Code', 'Code');
	data.addColumn('number', 'Num Hosts', 'Num Hosts');
	data.addColumn('string', 'Country', 'Country');
	
% for key in countries:
<%
	country = countries[key]
	dizCities = country.getDictionaryCities()
	cod = country.getCode()
%>\

	data.addRow( ['${cod}', ${country.getTotal()}, "${country.getName()|h}" ] );

<%
	j=0
	found=False
	x=0
%>\
	var ${cod}Table = createCountryTable();
	${cod}Table.addRows([
	  % for key2 in dizCities:
<%		city=dizCities[key2] %>\
% if (j+1) != len(dizCities) :
		[${city.getLatitude()}, ${city.getLongitude()}, ${city.getTotalHosts()}, "${city.getName()|h}"],\
% else :
		[${city.getLatitude()}, ${city.getLongitude()}, ${city.getTotalHosts()}, "${city.getName()|h}"]\
% endif
% if city.getName() == 'Unknown' and (not found):
<%
	found=True
	x=j
%>\
% endif
<%
	  j += 1
%>
	% endfor
	]);	
% if found:

    	${cod}Table.setTableProperty('unk', ${x});
% endif

	array.${cod}=${cod}Table;					//assigns countrycode to countrytable "${country.getName().upper()}"
	
% endfor

	var geomap = new google.visualization.GeoMap(document.getElementById('GeoMappa'));

	var options={
	width: '900px', 
	height: '691px', 
	showLegend: true, 
	region: 'world', 
	dataMode: 'regions'
	};
	
	var table = new google.visualization.Table(document.getElementById('table'));

	var viewTable= new google.visualization.DataView(data);
	
	
	var table2 = new google.visualization.Table(document.getElementById('table2'));
	
	// draw all the objects of the page with the new data
	function paint(totalHosts, unkCountries, unkCities){
		if(updated){
			getElement('totalHosts').innerHTML=totalHosts;
			getElement('unknownCountries').innerHTML=unkCountries;
			getElement('unknownCities').innerHTML=unkCities;
			//alert("PAINT "+data.toJSON());
			var prop= table.getSortInfo();
			var numColSort=prop.column;
			var direction=prop.ascending;
			var tmpViewTable= new google.visualization.DataView(data);
			tmpViewTable.setColumns([2,1,0]);
			
			table.draw(tmpViewTable, { sortColumn: prop.column, sortAscending: prop.ascending} );			
			
			if(currentSelected){
				if(!array[currentSelected]){ 
				//there is no city table of the current selected region
				//remove the table if there is one and draw the map empty
					var temp=getElement('table2');
					temp.removeChild(temp.firstChild);
					
					geomap.draw(new google.visualization.DataView(emptyTable), options);
				}
				else{
					var tmpView= new google.visualization.DataView(array[currentSelected]);
					
					var toHide=(array[currentSelected]).getTableProperty('unk');
					
					if(toHide!==null){
						if(tmpView.getNumberOfRows()===1){
							tmpView=emptyTable;			//FIX if just one row and unknown
						}else{
							tmpView.hideRows([toHide]);
						}
					}
					tmpView.setColumns([3, 2]);
					prop=table2.getSortInfo();
					
					table2.draw(tmpView, { sortColumn: prop.column, sortAscending: prop.ascending});
				
					geomap.draw(new google.visualization.DataView(array[currentSelected]), options);
				}
				
			}else{
				geomap.draw(data, options);
				}
			updated=false;
		}	
	}
	
	/*update the objects data, array with the new jsonObj data received from ajax response */
	var updateData=function(jsonObj){
		if(jsonObj){
			data=new google.visualization.DataTable({ cols:[ {id: 'Code', label: 'Code', type:'string'},
			  												 {id: 'Num Hosts', label: 'Num Hosts', type:'number'},
			  												 {id: 'Country', label: 'Country', type:'string'} ], 
			  										  rows:jsonObj.rowsTCountries});
			array= {};
			listTCities=jsonObj.tablesCities;
			var actual=null;
			for(var i=0; i< listTCities.length; i++){
				actual=listTCities[i];
				array[actual.code]= new google.visualization.DataTable(	{cols: [	{id: 'Latitude', label: 'LATITUDE', type:'number'},
							{id: 'Longitude', label: 'LONGITUDE', type:'number'},
							{id: 'Value', label: 'Num Hosts', type:'number'},
							{id: 'Hover', label: 'City', type:'string'}	],
							 rows: actual.citiesRows.lista} );
				if(actual.citiesRows.unknown != -1){
					array[actual.code].setTableProperty('unk', actual.citiesRows.unknown);
				}
			}
			updated=true;
			paint(jsonObj['totalHosts'],jsonObj['unknownCountries'],jsonObj['unknownCities']);
			
		}
		
	};
	
	/*send a ajax post request with the json values of the table data in the page*/
	var sendData=function (){	
	    var request=getXMLHttpRequest();
		var url=window.location.href;
		
		url=url+'?update=true';  //for now there is no need
		
		request.open("POST", url, true);
		request.onreadystatechange= function (){
		if(request.readyState === 4 && request.status=== 200){
			var upData=null;
			try{
				//alert(request.responseText);
				if(request.responseText==='false'){
					throw "Updating problems on the serverside";
					return;
				}
				upData=JSON.parse(request.responseText);
				
			}catch(e){
				throw "Error parsing JSON update data! "+e;
			}
			updateData(upData);
		}
		}
		request.setRequestHeader("Content-Type","application/jsonrequest");
		request.send('requestUPDATE');
		window.setTimeout(sendData, refreshTime);
	};
	
	
	/*Called when clicking on the world map. Switch to the region and show table cities */
	function clickHandler(msg) {
		options.region = msg.region;
		options.showZoomOut=true;
		options.colors = [0x9999FF, 0x0000FF, 0x000066];
		options.dataMode = 'markers';
		currentSelected=msg.region;
		if(array[msg.region]){
			var view= new google.visualization.DataView(array[msg.region]);
			view.setColumns([3, 2]);
			var countryV=new google.visualization.DataView(array[msg.region]);
			var toHide=(array[msg.region]).getTableProperty('unk');
			if(toHide!==null){
				if(countryV.getNumberOfRows()===1){
					countryV=emptyTable;			//FIX if just one row and unknown
				}else{
					countryV.hideRows([toHide]);
				}
			}
		table2.draw(view,null);
		geomap.draw(countryV, options);	
		}else{
		  geomap.draw(emptyTable, options);
		  var temp=document.getElementById('table2');
		  temp.removeChild(temp.firstChild);
		}
	}
	/*Called when clicking on a table. recover the data from the row and call clickhandler*/
	function tableClick() {
		var temp=table.getSelection();
		var arrayAss={};
		arrayAss.region=data.getFormattedValue(temp[0].row, 0);
		clickHandler(arrayAss);
	}
	
	/*puts back all the options for visualizing the world map again*/
	function zoomOut(){
		currentSelected=null;
		options.region= 'world';
		options.showZoomOut=false;
		options.colors = [0xE0FFD4, 0xA5EF63, 0x50AA00, 0x267114];
		options.dataMode='regions';
		table.setSelection();
		geomap.setSelection();
		geomap.draw(data,options);
		var temp=getElement('table2');
		temp.removeChild(temp.firstChild);
	}
	google.visualization.events.addListener(geomap, 'regionClick', clickHandler);
	google.visualization.events.addListener(geomap, 'zoomOut', zoomOut);
	google.visualization.events.addListener(table, 'select', tableClick );
	
	viewTable.setColumns([2,1,0]);
	table.draw(viewTable, { sortColumn: 1, sortAscending: false} );
	
	geomap.draw(data, options);
	window.setTimeout(sendData, refreshTime);
}

	google.setOnLoadCallback(drawVisualization);
</script>


<center>	
<p class="nobottomgap">Click on a region of the map or on a row of the table to see the information collected on that region</p>
<p>&nbsp;</p>
<table cellspacing="5">
	<tr>
	<td colspan="2"><div id="GeoMappa" style="width: 920px; height: 720px;"></div>
</td>
	</tr>
<tr>

	<td height="50" colspan="2">&nbsp;</td>
	</tr>
<tr>
	<td valign="top"><div id="table" style="width: 300px;"></div>
	</td>

	<td valign="top">
	<table width="100%" border="0" cellpadding="0" cellspacing="0">
	<tr>
	<td></td>
	</tr>
	</table>

<div id="table2" style="width: 220px;"> </div></td>
</tr>
</table>
<p>&nbsp;</p>
<table width="60%" border="1" cellpadding="2" cellspacing="0" >
	<tr><th colspan='3' scope="col" bgcolor="#F3F3F3">Geolocation Summary</th>
</tr>
<tr onMouseOver="this.bgColor = '#EDF3FE'" onMouseOut ="this.bgColor = '#FFFFFF'">
	<th width="80%" scope="row" bgcolor="#FFFFFF" align="left">Hosts considered for analysis</th>
	<td width="20%" align="right" scope="row" id="totalHosts" >${totalHosts}</td>
</tr>

<tr onMouseOver="this.bgColor = '#EDF3FE'" onMouseOut ="this.bgColor = '#FFFFFF'">
	<th width="80%" scope="row" bgcolor="#FFFFFF" align="left">Hosts located in unknown countries</th>
	<td width="20%" align="right" scope="row" id="unknownCountries" >${unknownCountries}</td>
</tr>

<tr onMouseOver="this.bgColor = '#EDF3FE'" onMouseOut ="this.bgColor = '#FFFFFF'">
	<th width="80%" scope="row" bgcolor="#FFFFFF" align="left">Hosts located in unknown cities</th>
	<td width="20%" align="right" scope="row" id="unknownCities" >${unknownCities}</td>
</tr>


</table>
	<p>&nbsp;</p>

</center>

