/*  OpenLayersHeatmap
 *  Copyright (C) 2010 Felipe Barriga Richards
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This Program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with RTMPDump; see the file COPYING.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA  02110-1301, USA.
 *  http://www.gnu.org/copyleft/gpl.html
 *
 */
 
/*
 * Edited by Dennis Wagenaar
 */


<?php
function connectdb()
{
 mysql_connect("location", "username", "password")
  or die("Error connecting to mysql: " . mysql_error());
 mysql_select_db('database')
  or die("Error connecting to database: " . mysql_error());
}
connectdb();
$table = 'table';
?>


var layerMapnik = null;
var lastZoom = null;
var vectorStyleCache = null;

function addToVectorStyleCache(vectorStyle, hash) {
	if (vectorStyleCache == null)
		vectorStyleCache = new Array();
	vectorStyleCache[hash] = vectorStyle;
}


function getVectorStyle(size, color) {
	var vectorStyle = null;
	var hash = size + '_' + color;
	if ( (vectorStyleCache != null) && (vectorStyleCache[hash] != null) ) {
		vectorStyle = vectorStyleCache[hash];
	} else {
		vectorStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
		vectorStyle.graphicWidth  = size;
		vectorStyle.graphicHeight = size;
		vectorStyle.graphicXOffset = -size/2;
		vectorStyle.graphicYOffset = -size/2;
		vectorStyle.externalGraphic = 'images/marker_' + color + '.png';

		addToVectorStyleCache(vectorStyle, hash);
	}
	return vectorStyle;
}


function scaleRadius(radius) {
  var zoom = map.getZoom();
  var scaleFactor = 1 / (1.1 * Math.pow(2, 16 - zoom));
  radius *= scaleFactor;

  return radius;
}


function drawMarkers() {

	var points = new Array();
	var lonLat, vectorStyle, point, pointVector, color, size;
	
	layerVectors.destroyFeatures();

		<?php
		$result=mysql_query("SELECT longitude, latitude FROM ".$table." ");
		while($row=mysql_fetch_array($result))
		{ 
		echo "lonLat = new OpenLayers.LonLat(".$row['longitude'].", ".$row['latitude'].").transform(map.displayProjection,map.getProjectionObject());";
		echo "color = 'green';
		size = '25';
		size = scaleRadius(size);
		vectorStyle = getVectorStyle(size, color);
		point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
		pointVector= new OpenLayers.Feature.Vector(point, null, vectorStyle);
		points.push(pointVector);";
		}
		?>
	

	layerVectors.addFeatures(points);
}


function generateHeatmap() {
	var width		= layerVectors.renderer.canvas.canvas.width;
	var height		= layerVectors.renderer.canvas.canvas.height;

	var context		= layerVectors.renderer.canvas.canvas.getContext('2d');
	var myImageData	= context.getImageData(0, 0, width, height);
	var pix			= myImageData.data;

	for (var i = 0, n = pix.length; i < n; i += 4) {
		// i+3 is alpha (the fourth element)
		if (pix[i+3] <= 64) {
			pix[i+2] = 255;			// blue
			pix[i+1] = (255/64)*pix[i+3];	// green
			pix[i  ] = 0;			// red
		} else if (pix[i+3] <= 128) {
			pix[i+1] = 255;
			pix[i+2] = (255/64)*(128-pix[i+3]);
			pix[i  ] = 0;
		} else if (pix[i+3] <= 192) {
			pix[i+1] = 255;
			pix[i+2] = 0;
			pix[i  ] = (255/64)*(pix[i+3]-128);
		} else if (pix[i+3] <= 255) {
			pix[i+1] = (255/64)*(255-pix[i+3]);
			pix[i+2] = 0;
			pix[i  ] = 255;
		}
	}
	context.putImageData(myImageData, 0, 0);
}


function mapMoveEndEvent(event) {
	if (event.type == 'moveend') {
		if (lastZoom != map.getZoom()) {
			lastZoom = map.getZoom();
			onChangeParams(true);
		}
		Concurrent.Thread.create(function() {
			Concurrent.Thread.sleep(50);
			layerVectors.renderer.redraw();
		})
	}
}


function onChangeParams(_drawMarkers) {
	vectorStyleCache = null;
	if (_drawMarkers)
		drawMarkers();
}

function clearMarkers() {
	markers = new Array();
	vectorialMarkers = new Array();
	layerVectors.destroyFeatures();
}



function init() {  
	map = new OpenLayers.Map("heatmap", {
		eventListeners: {
			"moveend": mapMoveEndEvent
		},
		controls: [
			new OpenLayers.Control.Navigation(),
			new OpenLayers.Control.PanZoomBar(),
			new OpenLayers.Control.ScaleLine()
		],
		maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
		maxResolution: 156543.0399,
		numZoomLevels: 19,
		units: 'm',
		projection: new OpenLayers.Projection("EPSG:900913"),
		displayProjection: new OpenLayers.Projection("EPSG:4326")
	});

	layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
	map.addLayer(layerMapnik);
	
	layerVectors = new OpenLayers.Layer.Vector("Features", {renderers: ["Canvas"]});
	map.addLayer(layerVectors);

	var lon   = 4.4585017;
	var lat   = 52.1406583;
	var zoom  = 16;

	var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
	map.setCenter (lonLat, zoom);

	lastZoom = zoom;

}