var map, projectenLayer;
var activeFeature;
var previousCenter;
OpenLayers.ProxyHost = "/proxy.php?url=";
var rssListId = "bgi_map_text";

function init()
{
    initTwitter();
    	
	if(jQuery("#map").length>0){

		// make sure the element is empty
		jQuery("#map").html("");
		// OpenLayers.ProxyHost = "http://www.brentjensgeoict.nl/proxy.php?url=";
		map = new OpenLayers.Map('map', {
			projection: new OpenLayers.Projection("EPSG:900913"),
			displayProjection: new OpenLayers.Projection("EPSG:4326"),
			units: "m",
			maxResolution: 156543.0339,
			maxExtent: new OpenLayers.Bounds(
			    -11593508, 5509847, -11505759, 5557774
			)
			/*,controls: [
			    	new OpenLayers.Control.PanZoom()
			]*/
		});

		var osm = new OpenLayers.Layer.OSM();
		map.addLayers([osm]);
	    var touchNav = new OpenLayers.Control.TouchNavigation({
            dragPanOptions: {
                // enableKinetic: true
            }
        })
        map.addControl(touchNav);

        // zoom in to layer with address
        if (jQuery("#map").hasClass("contactmap")) {
			jQuery('#map').css("width","750px");
			jQuery('#map').css("float","right");
			jQuery('#map').css("position","relative");           
            map.setCenter(new OpenLayers.LonLat(570274, 6816110), 12);
            
            // address
            var address = new OpenLayers.Layer.Vector("Adres",{
                styleMap: getStyleMap()            
            });
            // features: attributes.title, description, link
            var feature = new OpenLayers.Feature.Vector();
            feature.geometry = new OpenLayers.Geometry.Point(570274,6816110);
            var attr = {"title":"Bezoekadres","description":"Lange Nieuwstraat 10<br/> 3512PH Utrecht","link":"#"}
            feature.attributes = attr;
            address.addFeatures([feature]);
            map.addLayer(address);            

		    address.events.register("click", address, function(e) {
			    this.div.style.cursor = "pointer";
			    var feature = this.getFeatureFromEvent(e);
			    if (feature) {
			       // add a popup
			       onFeatureSelect(feature);
			    }
		    });

        } else {
		    projectenLayer = new OpenLayers.Layer.Vector("Projecten", {
			    strategies: [new OpenLayers.Strategy.Fixed()], 	// new OpenLayers.Strategy.BBOX()
			    extractAttributes: true,
			    styleMap: getStyleMap(),
			    projection: new OpenLayers.Projection("EPSG:4326"),
			    protocol: new OpenLayers.Protocol.WFS({
			        version: "1.0.0",
			        srsName: "EPSG:4326",
			        url: "http://188.40.75.212/geoserver/wfs",
			        featureNS :  "http://www.brentjensgeoict.nl",
			        featureType: "projectennieuws",
			        geometryName: "point"
			        // , schema: "http://188.40.75.212/geoserver/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typeName=bgi:projectennieuws"
			    })
		    }); 
		    projectenLayer.events.register("click", projectenLayer, function(e) {
			    this.div.style.cursor = "pointer";
			    var feature = this.getFeatureFromEvent(e);
			    if (feature) {
			       // add a popup
			       onFeatureSelect(feature);
			    }
		    });

		    if (jQuery("#"+rssListId).length>0) {
			    projectenLayer.htmlEltId = rssListId;
			    projectenLayer.events.register("loadend", projectenLayer, showFeatureList);
			    jQuery('#map').css("width","620px");
			    jQuery('#map').css("left","15px");
			    jQuery('#map').css("position","relative");
			    // jQuery('#map').css("bottom","370px");
		    }
		    map.addLayer(projectenLayer);
		    map.setCenter(new OpenLayers.LonLat(574000, 6825000), 9);
		}
		// end else, for normal map
	}
}


var showFeatureList = function ()
{
	jQuery("#"+this.htmlEltId).html("");
	// reference to the object this is the projectenLayer
	var features = this.features;
	var rss2html = "<div class='bgi_rss_item'><ul>";
	for (objCounter=features.length-1;objCounter>=0;objCounter--)
	{
		var item = features[objCounter];
		if (isEven(objCounter)){
			liClass="even";
		} else {
			liClass="odd";
		}
		rss2html+= "<li class='"+liClass+"'><h4 onclick='toggleRssPar(this, \""+item.fid+"\")'>"+ item.data.title + "</h4>"
//rss2html+="<p style='display:none' class='rssItemPar' id='rssItemPar_"+objCounter+"'>" + item.data.description + "<br/>Naar website: <a href='" + item.data.link + "' target='_new'>"+ item.data.title + "</a></p></li>";
	}
		rss2html = rss2html + "</div>";
	try
	{
		jQuery("#"+ this.htmlEltId).append(rss2html);
	} catch(e){
		alert(e);
	}
}


function toggleRssPar(obj, fid) {
	var open = true;
	var thisId = $(obj).first('p').id;

	removePopups(projectenLayer);

	$(obj).parentsUntil('div').find('.rssItemPar').each(function (thisId) {
								if ($(this).id == thisId) {
									$(this).hide();
								}
							})
	// now show the correct one
	var feature = projectenLayer.getFeatureByFid(fid);
	featureToggleSelect(feature);
	onFeatureSelect(feature);
}


function onPopupClose(evt) {
	feature = activeFeature;
	if (feature) {
		map.removePopup(feature.popup);
		feature.popup.destroy();
		feature.popup = null;
	    	feature.renderIntent='default';
		feature.layer.drawFeature(feature);
		map.panTo(previousCenter);
	}
}

function onFeatureSelect(feature) {
	removePopups(feature.layer);
	activeFeature = feature;
	text = '';
	if (feature.cluster) {
	    for (var i in feature.cluster){
		var feat = feature.cluster[i];
		text += "<h4>"+feature.attributes.title + "</h4><div>" + feature.attributes.description;
		text += "<br/>Naar website: <a href='" + feature.attributes.link + "' target='_new'>"+ feature.attributes.title + "</a></div>";
	    }
	} else {
		text += "<h4><a href='" + feature.attributes.link + "' target='_new'>"+ feature.attributes.title + "</a></h4><div>" + feature.attributes.description+"</div>";
	}
	var popupSize = new OpenLayers.Size(250, 130);
	popup = new OpenLayers.Popup(feature.attributes.title, 
		             feature.geometry.getBounds().getCenterLonLat(),
		             popupSize,
		             text,
		             true, onPopupClose);
	feature.popup = popup;
	feature.renderIntent='select';
	feature.layer.drawFeature(feature);


	popup.setOpacity(1.0);
	// popup.closeOnMove = true;
	// popup.panMapIfOutOfView = true;
	// calculate new Mapcenter to zoom to (custom function, because default function doesn't account for controls in the map, causing popups to be hidden)
	previousCenter = map.getCenter();
	var popupCenter = feature.geometry.getBounds().getCenterLonLat();
	var dX = map.getResolution()*0.5*popupSize.w;
	var dY = map.getResolution()*0.5*popupSize.h;
	var newCenter = new OpenLayers.LonLat(popupCenter.lon + dX, popupCenter.lat - dY); 
	map.panTo(newCenter);

	// popup.keepInMap = true;
	map.addPopup(popup);

}

/*
function onFeatureMouseOver(feature) {
    activeFeature = feature;
    text = '';
    if (feature.cluster) {
	    for (var i in feature.cluster){
		var feat = feature.cluster[i];
		text += '<h3>'+feat.attributes.title + "</a></h3><br/>";
	    }
    } else {
	text += '<h3>'+feature.attributes.title + "</a></h3>";
    }

    popup = new OpenLayers.Popup(feature.attributes.title, 
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(200, 50),
                             text,
                             true, onPopupClose);
    feature.popup = popup;
    popup.setOpacity(0.7);
    // popup.closeOnMove = true;
    // popup.panMapIfOutOfView = true;
    // popup.keepInMap = true;
    map.addPopup(popup);
}*/

function getStyleMap() {

	var defaultStyle = new OpenLayers.Style({
	  'pointRadius': 10,
	  // graphicwidth/height fail in IE...
	  //'graphicWidth':'16',
	  //'graphicHeight':'19',
	  'externalGraphic': 'http://www.brentjensgeoict.nl/images/marker_20.png',
  	  'graphicYOffset':-20,
	  'fillColor':'#ffffff',
	  'fillOpacity':'1.0',
	  'strokeColor':'#FF5C00',
	  'strokeWidth':'3'
	});

	var selectStyle = new OpenLayers.Style({
	  'pointRadius': 12,
          'externalGraphic': 'http://www.brentjensgeoict.nl/images/marker_selected_24.png',
	  'fillOpacity':'1.0',
	  // graphicwidth/height fail in IE...
	  //'graphicWidth':'20',
	  //'graphicHeight':'24',
  	  'graphicYOffset':-24
	});

	var styleMap = new OpenLayers.StyleMap({'default': defaultStyle,
			         'select': selectStyle});
	return styleMap;
}

function openFeaturePopup(fid) {
	var feature = projectenLayer.getFeatureByFid(fid);
	onFeatureSelect(feature); //feature.popup.show();
}

function removePopups(layer) {
	for (var i=0;i<layer.features.length;i++) {
		var ft = layer.features[i];
		if (ft.popup!=null) {
			// close the popup first
			map.removePopup(ft.popup);
			ft.renderIntent='default';
			ft.layer.drawFeature(ft);
			ft.popup.destroy();
			ft.popup = null;
		}
	}
}

// change from select-> default or defualt->select
function featureToggleSelect(feature) {
	if (feature.renderIntent!='select') {
		feature.renderIntent='select';
	} else {
		feature.renderIntent='default';
	}
	feature.layer.drawFeature(feature);
}




