var map;
var layer;
var popup;
var selectedFeature;

function makeUserPopup(feature) {
    
    popup_data = JSON.parse(feature.attributes.data);

    result = "<h6>Ihre Position</h6>";

    popup = new OpenLayers.Popup.FramedCloud(
        "sewer",
	feature.geometry.getBounds().getCenterLonLat(),
	null,
	result,
	null, true, onPopupClose
        );
    return popup;
};

function makeHomePopup(feature) {
    
    popup_data = JSON.parse(feature.attributes.data);

    result = "<h6>Ihr Wohnort</h6>";
    result += "<p>" + popup_data["zip"] + " " + popup_data["city"] + ", " + popup_data["street"] + ", " + popup_data["house_number"] + "</p>";

    popup = new OpenLayers.Popup.FramedCloud(
        "sewer",
	feature.geometry.getBounds().getCenterLonLat(),
	null,
	result,
	null, true, onPopupClose
        );
    return popup;
};

function makePersonPopup(feature) {
    
    popup_data = JSON.parse(feature.attributes.data);

    result = "<h6>" + popup_data["first_name"] + " " + popup_data["last_name"] + "</h6>";

    popup = new OpenLayers.Popup.FramedCloud(
        "sewer",
	feature.geometry.getBounds().getCenterLonLat(),
	null,
	result,
	null, true, onPopupClose
        );
    return popup;
};


function makeSewerPopup(feature) {
    
    popup_data = JSON.parse(feature.attributes.data);

    id = popup_data.id;
    name = popup_data.name;
    affects = popup_data.affects;

    result = "<h6>Kanalschacht: " + name + " </h6>";
    result += "<p>" + popup_data.message;
    
    if (affects.length > 0 ) {
	result += " Betroffen sind die Grundstücke:";
	result += "<ul>";
	for (var i=0; i < affects.length; i++) {
	    result += "<li>" + affects[i].street + ", " + affects[i].house_number  +"</li>";
	};
	result += "</ul>";
    };
    result += "</p>";

    popup = new OpenLayers.Popup.FramedCloud(
        "sewer",
	feature.geometry.getBounds().getCenterLonLat(),
	null,
	result,
	null, true, onPopupClose
        );
    return popup;
};

function makeWebcamPopup(feature) {
    
    popup_data = JSON.parse(feature.attributes.data);

    result = "<h6>Wetterkamera: " + popup_data["name"] + "</h6>";
    if (popup_data["state"] == "error") {
	result += "<p>Kamera ist zur Zeit außer Betrieb.</p><p><img width='240' height='180' src='/img/testbild.png'></p>";
    } else {
	result += "<p><a target='_new' href=" + popup_data["img"] + "><img width='240' height='180' src='" + popup_data["img"]  + "'></a></p>";
    }

    popup = new OpenLayers.Popup.FramedCloud(
        "sewer",
	feature.geometry.getBounds().getCenterLonLat(),
	null,
	result,
	null, true, onPopupClose
        );
    return popup;
};

function makeSensorPopup(feature) {

    popup_data = JSON.parse(feature.attributes.data);

    id = popup_data.id;
    name = popup_data.name;
    affects = popup_data.affects;

    result = "<h6>Sensor: " + name + "</h6>";
    result += "<table>";

    if (popup_data.values.length == 0) {
	result += "<p>Keine Daten innerhalb der letzten Stunde vorhanden.</p>";
    } else {
	result += "<table>";
	for (var i=0; i < popup_data.values.length; i++) {

	    switch (popup_data.values[i].name) {
	    case "wind":
		direction = popup_data.values[i].direction;
		// Konvertierung Gradzahl in Buchstaben
		if (direction > 337.5 || direction <= 22.5) {
		    direction = 'N';
		};
		if (direction > 22.5 && direction <= 67.5) {
		    direction = 'NO';
		};
		if (direction > 67.5 && direction <= 112.5) {
		    direction = 'O';
		};
		if (direction > 112.5 && direction <= 157.5) {
		    direction = 'SO';
		};
		if (direction > 157.5 && direction <= 202.5) {
		    direction = 'S';
		};
		if (direction > 202.5 && direction <= 247.5) {
		    ;  direction = 'SW';
		}
		if (direction > 247.5 && direction <= 292.5) {
		    direction = 'W';
		};
		if (direction > 292.5 && direction <= 337.5) {
		    direction = 'NW';
		};
		result += "<tr>";
		result += "<td>" + popup_data.values[i].label + "</td>";
		result += "<td>" + popup_data.values[i].value + " " + popup_data.values[i].type + " " + direction + "</td>";
		result += "</tr>";
		break;
	    case "rain":
	    case "temperature":
	    case "air_pressure":
	    case "water_level":
		result += "<tr>";
		result += "<td>" + popup_data.values[i].label + "</td>";
		result += "<td>" + popup_data.values[i].value + " " + popup_data.values[i].type + "</td>";
		result += "</tr>";
		break;
	    case "hail_detection":
	    case "rain_detection":
		v = "Nein";
		if (popup_data.values[i].value > 0.0) {v = "Ja"};
		result += "<tr>";
		result += "<td>" + popup_data.values[i].label + "</td>";
		result += "<td>" + v + "</td>";
		result += "</tr>";
		break;
	    };
	};
	result += "</table>";
	};

    result += "<p><a target='_new' href='/graph?id=" + id +"'>Weitere Werte des Standortes</a></p>";

    popup = new OpenLayers.Popup.FramedCloud(
        "sensor",
	feature.geometry.getBounds().getCenterLonLat(),
	null,
	result,
	null, true, onPopupClose
        );
    return popup;
};


function onPopupClose(evt) {
    onFeatureUnselect(selectedFeature);
};


function onFeatureUnselect(feature) {
    
    // remove the popup from the map
    map.removePopup(feature.popup);

    // destroy the popup
    if (feature.popup) {
	feature.popup.destroy();
	feature.popup = null;
    };
    
    // set selected feature to null
    selectedFeature = null;
};

function onFeatureSelect(feature) {

    if (selectedFeature) {
	onFeatureUnselect(selectedFeature)
    };

    // set the selected feature
    selectedFeature = feature;

    // create new popup
    switch (feature.attributes.type) {
    case "user":
	popup = makeUserPopup(feature);
	break;
    case "home":
	popup = makeHomePopup(feature);
	break;
    case "person":
	popup = makePersonPopup(feature);
	break;    
    case "sewer":
	popup = makeSewerPopup(feature);
	break;
    case "sensor":
	popup = makeSensorPopup(feature);
	break;
    case "webcam":
	popup = makeWebcamPopup(feature);
	break;
    }
    feature.popup = popup;

    // add the popup to the map
    map.addPopup(popup);
};


function init_map()
{
    map = new OpenLayers.Map ("map", {
	    controls:[
		      new OpenLayers.Control.Navigation(),
                      new OpenLayers.Control.PanZoom(),
                      new OpenLayers.Control.Attribution(),
                      new OpenLayers.Control.MousePosition()
                      //new OpenLayers.Control.LayerSwitcher()
		      ],
	    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")
	}
	);

    // create OSM layer (Tiles@Home)
    var osmarender = new OpenLayers.Layer.TMS(
        "OpenStreetMap",
	"http://tile.openstreetmap.org/",
	{
	    type: 'png', getURL: osm_getTileURL,
	    displayOutsideMaxExtent: true,
	    attribution: '<a href="http://www.openstreetmap.org/">OpenStreetMap</a>'
	}
    );

    map.addLayer( osmarender );

    // create OSM layer
    //map.addLayer(new OpenLayers.Layer.OSM.Osmarender("Openstreetmap"));
    
    function osm_getTileURL(bounds) {
	var res = this.map.getResolution();
	var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
	var z = this.map.getZoom();
	var limit = Math.pow(2, z);
	
	if (y < 0 || y >= limit) {
	    return OpenLayers.Util.getImagesLocation() + "404.png";
	} else {
	    x = ((x % limit) + limit) % limit;
	    return this.url + z + "/" + x + "/" + y + "." + this.type;
	}
    };
    

    var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    lon = lonLat.lon;
    lat = lonLat.lat;

    map.setCenter(lonLat, zoom);

    wmsLayer = new OpenLayers.Layer.WMS(
        "Warnungen",
	"/wms/safemobile/servlet/map?",
	{layers: 'regions.orange,cells.orange,sensors.orange', format: 'image/png'}, 
	{'buffer':0,projection: map.displayProjection}
    );
    wmsLayer.setIsBaseLayer(false);
    wmsLayer.setOpacity(1);
    map.addLayer(wmsLayer);

    var context = {
	getImg: function(feature) {
	    
	    feature_data = JSON.parse(feature.attributes.data);
	    
	    switch (feature.attributes.type) {
	    case "user":
		return "/img/user.png";
		break;
	    case "home":
		return "/img/home.png";
		break;
	    case "person":
		if (feature_data["gender"] == "m") {
		    return "/img/user_male.png";
		} else {
		    return "/img/user_female.png";
		};
		break;    
	    case "sewer":
		current = feature_data["warninglevel"]["current"];
		predicted = feature_data["warninglevel"]["predicted"];
		return "/img/sewer-" + predicted + "-" + current + ".png";
		break;
	    case "sensor":
		return "/img/sensor-blau.png";
		break;
	    case "webcam":
		state = feature_data["state"];
		if (state == "error") {
		    return "/img/webcam-error.png";
		} else {
		    return "/img/webcam.png";
		}
		break;
	    }
	}
    };
    
    var template = {
	fillOpacity: 1,
	pointRadius: 10,
	externalGraphic: "${getImg}"
    };

    var style = new OpenLayers.Style(template, {context: context});

    layer = new OpenLayers.Layer.WFS(
				     "Alles",
				     "/wfs/composed?",
				     {},
				     {
					 projection: new OpenLayers.Projection("EPSG:900913"),
					 extractAttributes: true,
					 styleMap: new OpenLayers.StyleMap(style)
	}
				     );
    map.addLayer(layer);

    
    popup = new OpenLayers.Control.SelectFeature(
        layer,
	{
	    onSelect: onFeatureSelect,
	    //onUnselect: onFeatureUnselect,
            hover: true
	}
    );
    map.addControl(popup);
    popup.activate();

    window.setInterval("reload_layer()", 120000)
};


function reload_layer()
{
    if (layer.visibility)
    {
        layer.refresh();
    };
};
