//------------------------------------------------------
// Start init vars
//------------------------------------------------------
// Toggle vars
var active_tools = 1;
var active_image = 0;
var active_search = 0;

// Google map vars
var map;
var gmarkers = [];
var gmarkersData = [];
var popupHTML = [];
var mouseHTML = [];
var bounds = '';
var openMarker = null;
var defaultLon = 4.50439453125;
var defaultLat = 52.80729197309426;
var backupLon = defaultLon;
var backupLat = defaultLat;
var searchLon = defaultLon;
var searchLat = defaultLat;
var dragLon = defaultLon;
var dragLat = defaultLat;

var jg;

// Poi types
var active_poitypes = 'kunstlocatie';
var radius = 10000;

var baseIcon = new GIcon();
baseIcon.shadow = "none";
baseIcon.iconSize = new GSize(60, 60);
baseIcon.shadowSize = new GSize(91,60);
baseIcon.iconAnchor = new GPoint(30, 60);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);
baseIcon.shadow = getBaseURL()+"gfx/shadow-poi.png";

var baseIconSmall = new GIcon();
baseIconSmall.shadow = "none";
baseIconSmall.iconSize = new GSize(15, 15);
baseIconSmall.shadowSize = new GSize(23,15);
baseIconSmall.iconAnchor = new GPoint(10, 18);
baseIconSmall.infoWindowAnchor = new GPoint(9, 2);
baseIconSmall.infoShadowAnchor = new GPoint(18, 25);
baseIconSmall.shadow = getBaseURL()+"gfx/accenten/schaduw.png";

//------------------------------------------------------
// End init vars
//------------------------------------------------------

function getBaseURL() {

    return "http://"+document.domain+"/";
}


//------------------------------------------------------
// Start google map functions
//------------------------------------------------------
//create the ToolTip overlay object
function ToolTip(marker,html,width) {
    this.html_ = html;
    this.width_ = (width ? width + 'px' : 'auto');
    this.marker_ = marker;
}
ToolTip.prototype = new GOverlay();
ToolTip.prototype.initialize = function(map) {
    var div = document.createElement("div");
    div.style.display = 'none';
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	
    this.map_ = map;
    this.container_ = div;
}
ToolTip.prototype.remove = function() {
    this.container_.parentNode.removeChild(this.container_);
}
ToolTip.prototype.copy = function() {
    return new ToolTip(this.html_);
}
ToolTip.prototype.redraw = function(force) {
    if (!force) return;
	
    var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
    this.container_.innerHTML = this.html_;
    this.container_.style.position = 'absolute';
    this.container_.style.left = pixelLocation.x + "px";
    this.container_.style.top = pixelLocation.y + "px";
    this.container_.style.width = this.width_;
    this.container_.style.font = 'normal 10px verdana, arial, sans';
    this.container_.style.border = '1px solid #000';
    this.container_.style.background = '#FFF';
    this.container_.style.padding = '4px';
	
    //one line to desired width
    this.container_.style.whiteSpace = 'nowrap';
    if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
    this.container_.style.display = 'block';
}
GMarker.prototype.ToolTipInstance = null;
GMarker.prototype.openToolTip = function(content) {
    //don't show the tool tip if there is acustom info window
    if(this.ToolTipInstance == null) {
	  this.ToolTipInstance = new ToolTip(this,content)
	  map.addOverlay(this.ToolTipInstance);
    }
}
GMarker.prototype.closeToolTip = function() {
    if(this.ToolTipInstance != null) {
	  map.removeOverlay(this.ToolTipInstance);
	  this.ToolTipInstance = null;
    }
}

//create the infoWindow overlay object
function infoWindow(marker,html,width) {
    this.html_ = html;
    this.width_ = (width ? width + 'px' : 'auto');
    this.marker_ = marker;
}
infoWindow.prototype = new GOverlay();
infoWindow.prototype.initialize = function(map) {
    var div = document.createElement("div");
    div.style.display = 'none';
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	
    this.map_ = map;
    this.container_ = div;
}
infoWindow.prototype.remove = function() {
    this.container_.parentNode.removeChild(this.container_);
}
infoWindow.prototype.copy = function() {
    return new infoWindow(this.html_);
}
infoWindow.prototype.redraw = function(force) {
    if (!force) return;
    this.container_.innerHTML = this.html_;
    bounds = map.getBounds();
    sw = bounds.getSouthWest();
    ne = bounds.getNorthEast();
    pixelLocation = map.fromLatLngToDivPixel(new GLatLng(parseFloat(ne.lat()), parseFloat(sw.lng())));
    new_left = pixelLocation.x + 171;
    new_top = pixelLocation.y - 3;
	
    this.container_.style.position = 'absolute';
    this.container_.style.left = new_left + "px";
    this.container_.style.top = new_top + "px";
    this.container_.style.width = '297px';
    this.container_.style.bgColor  = 'transparent';
    this.container_.style.display = 'block';
    this.container_.style.zIndex = '1000';

}
GMarker.prototype.infoWindowInstance = null;
GMarker.prototype.openinfoWindow = function(content) {
    //don't show the tool tip if there is acustom info window
    if(this.infoWindowInstance == null) {
	  this.infoWindowInstance = new infoWindow(this,content)
	  pixelLocation = map.fromLatLngToDivPixel(this.getPoint());
	  allowedBounds = map.getBounds();
	  //if(!allowedBounds.contains(map.fromDivPixelToLatLng(GPoint(pixelLocation.x, pixelLocation.y)))){
	  //resize
	  //}
	  map.addOverlay(this.infoWindowInstance);
    }
}
GMarker.prototype.closeinfoWindow = function() {
    if(this.infoWindowInstance != null) {
	  map.removeOverlay(this.infoWindowInstance);
	  this.infoWindowInstance = null;
    }
}

// Functions to create an object with marker data 
function gmarkerData(label, id, type, soort, lon, lat, label, description, icon, smallicon){
    this.label=label;
    this.id=id;
    this.type=type;
    this.soort=soort;
    this.lon=lon;
    this.lat=lat;
    this.label=label;
    this.description=description;
    this.icon=icon;
    this.smallicon=smallicon;	
}

// Function to place POI's on the MAP
function createMarker(point, index, label, id, type, soort, lon, lat, description, icon, smallicon) {
    if(icon!=""){
	  if (icon.substr(0,4)=="[yt=")
	  {
		sm=smallicon.substr(0,1);
		customIcon = new GIcon(baseIcon,"images/poi/ytoverlay" + sm + ".png");
			
	  }
	  else
	  {
		customIcon = new GIcon(baseIcon,getBaseURL()+"files/uitgelicht_kaart/"+ id + "/" + icon + "/poi.png");
	  }
    }else{
	  customIcon = new GIcon(baseIconSmall,getBaseURL()+"gfx/accenten/" + smallicon + ".png");
    }
    var marker = new GMarker(point, customIcon);
    gmarkers[id] = marker;

	
    //alert(pixelLocation.x);
 
	
    popupHTML[id] = '';
    popupHTML[id] += '<div class="mapPop">';
    popupHTML[id] += '				<div class="popupContainer">';
    popupHTML[id] += '					<div class="titel">' + label + '</div>';
    popupHTML[id] += '					<div class="closeBut" onclick="poiClose(\'' + id + '\',\'' + lon + '\',\'' + lat + '\');">&nbsp;</div>';
	
    if (icon.substr(0,4)=="[yt=")
    {		
	  yt_code = icon.substr(4);
	  yt_code = yt_code.split("]")[0]; 
	  popupHTML[id] = popupHTML[id] + '<div id="poi_foto" class="photo" style="background-image:url(http://i4.ytimg.com/vi/'+yt_code+'/0.jpg); background-color:#000"><img src="/gfx/youtube.gif" class="cursorpointer" onclick="poi_lees_verder('+id+')" alt="Klik om deze video af te spelen"/></div>';
    }
    else
    {
	  popupHTML[id] = popupHTML[id] + '<div class="photo" style="background-image:url(/files/uitgelicht_kaart/'+id+'/'+icon+'/250.jpg)" id="poi_foto"></div>';
    }
    if(icon!=""){		
	  popupHTML[id] += '					<div class="poi_vorige_afb" onclick="poi_vorige_afb('+id+')"></div>';
	  popupHTML[id] += '					<div class="poi_volgende_afb" onclick="poi_volgende_afb('+id+')"></div>';
    }
    popupHTML[id] += '					<div class="text">' + description + '</div>';
    popupHTML[id] += '					<a href="#/uitgelicht-op-de-kaart/'+id+'/leesverder" onclick="poi_lees_verder('+id+')" class="readOn">lees meer &gt;</a> ';
    popupHTML[id] += '				</div>';
    popupHTML[id] += '			</div><div class="mapPopPijl"></div>';
	
	
    mouseHTML[id] = "<b>"+ soort + "</b>";
								 
    // Set the data for later reference
    var itemData = new gmarkerData(label, id, type, soort, lon, lat, label, description, icon, smallicon);
    gmarkersData[id] = itemData;
	
    // Laat popup zien als je klikt
    GEvent.addListener(marker,'click',function() {
	  if (id!=openMarker) {
		ajax_set_url('uitgelicht-op-de-kaart/'+id);
		poiClick(id,lon,lat);
	  }
    });

// Laat popup zien bij mouseover

// Laat tooltip zien bij mouseover
GEvent.addListener(marker,'mouseover',function() {
    poiMouseOver(id);
});
// Verwijder tooltip bij mouseouver
GEvent.addListener(marker,'mouseout',function() {
    poiMouseOut(id);
});
	
return marker;
}



function initGoogleMap(poi_id) {
    if (GBrowserIsCompatible()) {
	  if (document.getElementById("googleMap") != null) {
		
		set_dimensions();
			
		// Laad de kaart in de div
		map = new GMap2(document.getElementById("googleMap"));
		switchMapType('terrain');
			
		// Begin de kaart in een centraal punt
		map.setCenter(new GLatLng(parseFloat(defaultLat), parseFloat(defaultLon)), 9);
			
		// Laat de overview zien rechts onderin

		GEvent.addListener(map, "dblclick", function() {
		    map.setZoom(map.getZoom()-1);
		    return false;
		});
		// Zorgen dat je maar tot een bepaald niveau kunt zoomen
		GEvent.addListener(map, "zoomend", function() {
		    checkZoom();
		});
		// Verwijder de getekende lijn naar een poi als er gesleept wordt
		//			GEvent.addListener(map, "dragstart", function() { if(openMarker){ gmarkers[openMarker].closeinfoWindow();  } });
			
		//GEvent.addListener(map, "dragstart", function() { if(openMarker){ poiClose(openMarker);  } });			
			 			
		// Add scroll voor mouse wheel
		map.enableScrollWheelZoom();
		// Set Bounds
		bounds = map.getBounds();
			
		// Get initial pois
		getNewPois(poi_id);			
	  }
    }
}


overlay_kaart=false;

function add_overlay(kaart_id) 
{
    defaultLocation();
    remove_overlay();
    statische_kaart_return = current_cat;
    for (i=0;i<marker_list.length;i++)
    {
	  removeMarker(marker_list[i]);
	  if (openMarker==marker_list[i]) {
		poiClose(marker_list[i]);
	  }
    }
    var pointSW = new GLatLng(52.157529,4.457703);
    var pointNE = new GLatLng(53.197807,5.410767);
    ext='png';
    if (($.browser.msie)&&($.browser.version<7)) {
	  ext = 'gif';
    } 
    groundOverlay = new ProjectedOverlay ('files/statistische_kaart/'+kaart_id+'/kaart.'+ext, new GLatLngBounds(pointSW,pointNE));
	
    $(".kaart_overlay").show();
    $(".plus2").hide();
    $("#statistische_kaart_poi_titel").show().html(statistische_kaart_titel[kaart_id]);
	
    map.addOverlay(groundOverlay);
    groundOverlay.setOpacity(50);
    overlay_kaart=true;
    map.disableScrollWheelZoom();
}

function remove_overlay(mode)
{
    if (!overlay_kaart) {
	  return;
    }
    $(".kaart_overlay").hide();
    $(".plus2").show();
    $("#statistische_kaart_poi_titel").hide();
	
    if (mode=='direct') {
	  if (statische_kaart_return>0) {
		returnfromstatistische_kaart();
	  }
    }
	
map.removeOverlay(groundOverlay);	
map.enableScrollWheelZoom();
	
for (i=0;i<marker_list_active.length;i++)
{
    addMarker(marker_list_active[i]);
}
$("#legenda_content INPUT[type='checkbox']").attr("checked","checked");
overlay_kaart = false;
}


function switchMapType(type) {
    var newType;
    switch(type) {
	  case 'normal':
		newType = G_NORMAL_MAP;
		break;
	  case 'satellite':
		newType = G_SATELLITE_MAP;
		break;
	  case 'terrain':
		newType = G_PHYSICAL_MAP;
		break;
	  default:
		newType = null;
    }
    if (newType) {
	  map.addMapType(newType);
	  map.setMapType(newType);
    }
    if(openMarker){ 
	  //jg.clear();
	  var a = openMarker
	  //map.setCenter(gmarkers[openMarker].getPoint());
	  poiClose(openMarker);
	  poiClick(a);

    }	
}


function checkDrag() {
    // If a marker was left open, check if it is not dragged of the map
    if(openMarker){
	  // Get the poi location an init vars

	  gmarkers[openMarker].closeinfoWindow(); //custom popup sluiten bij slepen
	  poi_location = map.fromLatLngToContainerPixel(gmarkers[openMarker].getPoint());
	  map_locatie = map.fromLatLngToContainerPixel(map.getCenter());
	  new_center_x = map_locatie.x;
	  new_center_y = map_locatie.y;
	  //check wich parts are to far and Calculate the new center location
	  //		if(poi_location.y > 493) new_center_y = map_locatie.y + (poi_location.y - 493);
	  //		if(poi_location.y < 0) new_center_y = map_locatie.y + (poi_location.y) - 20;
	  //		if(poi_location.x > 873) new_center_x = map_locatie.x + (poi_location.x - 873);
	  //		if(poi_location.x < 180) new_center_x = map_locatie.x - (180 - poi_location.x) - 10;
		
		
	  // Set the new center location
	  //		newlocation = new GPoint(new_center_x, new_center_y);
	  //		new_map_center = map.fromContainerPixelToLatLng(newlocation);
	  //		map.setCenter(new_map_center);
	  poiClick(openMarker);
    }
//getNewPois(); //custom disabled
}

function checkZoom() {
	
    // Get the list of map types      
    var mt = map.getMapTypes();
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i=0; i<mt.length; i++) {
	  mt[i].getMinimumResolution = function() {
		return 8;
	  }
    }
	
    // If a marker was left open, center the map at this point
	
    if(openMarker){ 
	  //jg.clear();
	  var a = openMarker
	  //map.setCenter(gmarkers[openMarker].getPoint());
	  poiClose(openMarker);
	  poiClick(a);

    }

//	getNewPois();
//overlay();
}

function legenda(mode)
{
    if (mode=='open'){
	  $(".openLeg").hide();
	  $("#legenda").css('top','30px');
    }
    else{
	  $(".openLeg").show();
	  $(".openZoek").hide();
	  $("#legenda").css('top','27px');
    }
}

function zoeken_op_kaart(mode)
{
    if (mode=='sluit'){
	  $(".openZoek").hide();
	  $("#legenda").css('top','29px');
    }
    else{
	  $(".openZoek").show();
	  $(".openLeg").hide();
	  $("#legenda").css('top','-123px');
    }
}

function getNewPois(poi_id) {
    //	alert('poi');
    marker_accenten = [];
    for (i=0;i<50;i++) {
	  marker_accenten[i]=[];
    } //3d array declareren
    marker2id = [];
    marker_used = [];
    marker_list = [];
    marker_list_active = [];
    marker_visible = [];
    map.clearOverlays();
    gmarkers = [];
    gmarkersData = [];
    popupHTML = [];
    mouseHTML = [];
    //document.getElementById('mapLoading').style.visibility="visible";
    new_center = map.getCenter();
	
    GDownloadUrl(getBaseURL() + "/xml/poixml.xml", function(data, responseCode) {
	  var xml = GXml.parse(data);
	  var markers = xml.documentElement.getElementsByTagName("marker");
	  for (var i = 0; i < markers.length; i++) {
		var type = '';
		var id = '';
		var label = '';
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
		type = markers[i].getAttribute("type");
		soort = GXml.value(markers[i].getElementsByTagName("soort")[0]);
		id = markers[i].getAttribute("id");
		accentid = markers[i].getAttribute("accentid");			
		op_kaart = markers[i].getAttribute("o");
		lat = markers[i].getAttribute("lat");
		lon = markers[i].getAttribute("lng");
		label = markers[i].getAttribute("label");
		description = GXml.value(markers[i].getElementsByTagName("description")[0]);
		icon = markers[i].getAttribute("icon");
		smallicon = markers[i].getAttribute("smallicon");
		newmarker = createMarker(point, i, label, id, type, soort, lon, lat, description, icon, smallicon);
		if (op_kaart==1) {
		    map.addOverlay(newmarker);
		    marker_visible[id]=true;
		    marker_list_active.push(id);
		} 
		else {
		    marker_visible[id]=false;
		}
		marker_list.push(id);
		marker_accenten[accentid].push(id);
		marker2id[id]=newmarker;
		marker_used[id]=true;
	  }
		
	  $('#loader_wrapper').hide();
	  //load ajax controller (must be loaded after markers are done)
	  setTimeout(check_hash,500);
		
	  //document.getElementById('mapLoading').style.visibility="hidden";
	  if(gmarkers[poi_id]){
		poiClick(poi_id);
	  }
	  // Redraw marker if it was left open
	  if(openMarker != poi_id){
		poiClick(openMarker);
	  }
    });
}


/////// JONGERENKAART ///////////


var aIcons = new Array();
function switch_jongerenkaart()
{
    poi_return=false;
    statische_kaart_return=false;
	
    if (jongerenkaart==1)
    {
	  if (openMarker) {
		poiCloseJongerenkaart(openMarker);
	  }
		
	  $(".jongerenkaart_item").hide();
	  $(".cultuur_item").show();
		
	  var active_poitypes = 'kunstlocatie';
	  var radius = 10000;
		
	  var baseIcon = new GIcon();
	  baseIcon.shadow = "none";
	  baseIcon.iconSize = new GSize(60, 60);
	  baseIcon.shadowSize = new GSize(91,60);
	  baseIcon.iconAnchor = new GPoint(30, 60);
	  baseIcon.infoWindowAnchor = new GPoint(9, 2);
	  baseIcon.infoShadowAnchor = new GPoint(18, 25);
	  baseIcon.shadow = getBaseURL()+"gfx/shadow-poi.png";
		
	  var baseIconSmall = new GIcon();
	  baseIconSmall.shadow = "none";
	  baseIconSmall.iconSize = new GSize(15, 15);
	  baseIconSmall.shadowSize = new GSize(23,15);
	  baseIconSmall.iconAnchor = new GPoint(10, 18);
	  baseIconSmall.infoWindowAnchor = new GPoint(9, 2);
	  baseIconSmall.infoShadowAnchor = new GPoint(18, 25);
	  baseIconSmall.shadow = getBaseURL()+"gfx/accenten/schaduw.png";
	  jongerenkaart=false;
	  getNewPois();
		
    }
    else
    {
	  if (openMarker) {
		poiClose(openMarker);
	  }
		
	  $(".jongerenkaart_item").show();
	  $(".cultuur_item").hide();
				
	  var active_poitypes = 'jongeren';
	  var radius = 10000;
		
	  var baseIcon2 = new GIcon();
	  baseIcon2.shadow = "none";
	  baseIcon2.iconSize = new GSize(18, 18);
	  baseIcon2.shadowSize = new GSize(18,18);
	  baseIcon2.iconAnchor = new GPoint(10, 18);
	  baseIcon2.infoWindowAnchor = new GPoint(9, 2);
	  baseIcon2.infoShadowAnchor = new GPoint(18, 25);
	
	  aIcons['jongeren'] = new GIcon(baseIcon2,"gfx/iconJongeren.png");
	  jongerenkaart=1;
		
	  getNewPoisJongerenkaart();
    }
    gotohome();
}


function getNewPoisJongerenkaart(poi_id) 
{ 
    map.clearOverlays();
    gmarkers = [];
    gmarkersData = [];
    popupHTML = [];
    mouseHTML = [];
    //document.getElementById('mapLoading').style.visibility="visible";
    new_center = map.getCenter();

    GDownloadUrl(getBaseURL() + "xml/jong_poixml.xml", function(data, responseCode) {
	  var xml = GXml.parse(data);
	  var markers = xml.documentElement.getElementsByTagName("marker");
	  for (var i = 0; i < markers.length; i++) {
		var id = '';
		var titel = '';
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
		naam = markers[i].getAttribute("naam");
		email = markers[i].getAttribute("email");
		locatie = markers[i].getAttribute("locatie");
		id = markers[i].getAttribute("objectid");
		lat = markers[i].getAttribute("lat");
		lon = markers[i].getAttribute("lng");
		titel = markers[i].getAttribute("titel");
		beschrijving = markers[i].getAttribute("beschrijving");
		datum = markers[i].getAttribute("datum");
			
		map.addOverlay(createMarkerJongerenkaart(point, i, titel, id, naam, email, locatie, lon, lat, beschrijving, datum));
	  }
		
	  //load ajax controller (must be loaded after markers are done)
	  setTimeout(check_hash,500);
		
	  $('#loader_wrapper').hide();
		
	  //		return
	  // Add the pois that were added manually in memory through the form
	  /*
		for (var added_marker in addmarkers) {
			gmarkers[added_marker] = addmarkers[added_marker];
			gmarkersData[added_marker] = addmarkersData[added_marker];
			popupHTML[added_marker] = addedpopupHTML[added_marker];
			mouseHTML[added_marker] = addedmouseHTML[added_marker];
			map.addOverlay(addmarkers[added_marker]);
		}
		*/
	  //document.getElementById('mapLoading').style.visibility="hidden";
	  if(gmarkers[poi_id]){
		poiClick(poi_id);
	  }
	  // Redraw marker if it was left open
	  if(openMarker){
		poiClick(openMarker);
	  }
    });
}

// Function to place POI's on the MAP
function createMarkerJongerenkaart(point, i, titel, id, naam, email, locatie, lon, lat, beschrijving, datum) {
    var marker = new GMarker(point, aIcons['jongeren']);
    gmarkers[id] = marker;
	
    //alert(pixelLocation.x);
    t = '<div class="mapPopJong">';
    t += '<div class="popupContainer">';
    t +=  '<div class="closeBut" onclick="poiCloseJongerenkaart();">&nbsp;</div>';
    t +=  '<div class="titel" id="poi_titel">' + titel + '</div>';
    t +=  '<div class="descr" id="poi_locatie">' + locatie + '</div>';
    t +=  '<div class="author" id="poi_naam">Door '+ naam + ' op ' + datum + '</div>';
    t +=  '<div class="comments">' + beschrijving + '</div><div class=\"jong_photo_wrapper\">';
    t +=  '<div class="jongerenkaart_leesverder cursorpointer noselect" onclick="jongerenkaart_leesverder('+id+')">Lees verder &gt;&gt;</div>';
    t +=  '<img src="/images/buttons/91_l_disabled.gif" style="float:left;"/>';
    t +=  '<div style="height:91px;width:130px;float:left;background-image:url(/files/jongerenkaart/'+id+'/1/130.jpg)"></div>';
    t +=  '<img src="/images/buttons/91_r_disabled.gif" class="poi_volgende_afb_disabled"/></div>';	
    t +=  '</div>';
    t +=  '<div class="reactie">';
    t +=  '<div class="bekijk_reacties" onclick="toggle_reacties()">Bekijk reacties (<span id="jong_aantal_reacties">0</span>)</div>';		
    t +=  '<div class="closedReactie" onclick="toggle_reacties()"></div>';
    t +=  '<div class="openReactie" id="openReactie">';
    t +=  '<a href="#" class="linkReactieOpen" onclick="toggle_reacties()"></a>';
    t +=  '<div id="reactie_content"></div><a href="#" onclick="$(\'#reageerPoi\').show()" id="plaatsreactie">Plaats reactie >></a>';	
    t +=  '</div>';	
    t +=  '</div>';
    t +=  '</div>';	
	
    mouseHTML[id] = "<b>" + titel + "</b>";
	
    popupHTML[id] = t;
    // Set the data for later reference
    var itemData = new gmarkerData(titel, id, naam, email, lon, lat, beschrijving); 
    gmarkersData[id] = itemData;
	
    // Laat popup zien als je klikt
    GEvent.addListener(marker,'click',function() {
	  if (id!=openMarker) {
		poiClickJongerenkaart(id,lon,lat);
	  }
    });
// Laat tooltip zien bij mouseover
GEvent.addListener(marker,'mouseover',function() {
    poiMouseOver(id);
});
// Verwijder tooltip bij mouseouver
GEvent.addListener(marker,'mouseout',function() {
    poiMouseOut(id);
});

return marker;
}



function poiCloseJongerenkaart()
{
    if (!openMarker) {
	  return;
    }
    if(gmarkers[openMarker])
    {
	  //banner terugzetten
	  //$(".jongerenkaart_banner").show();
		
	  map.enableDragging();
	  map.enableScrollWheelZoom();
		
	  if(gmarkers[openMarker].infoWindowInstance) 
	  {
		// Clear line
		//jg.clear();
		// Clear infowindow
		gmarkers[openMarker].closeinfoWindow();
		openMarker = null;
	  // enable scrolling again
	  //map.enableScrollWheelZoom();
	  } 
    }
}



count_reacties = [];
function poiClickJongerenkaart(id,lon,lat) {
    if(gmarkers[id])
    {
	  ajax_set_url('jongerenkaart/'+target_id);
	  //banner verbergen
	  //$(".jongerenkaart_banner").hide();

	  map.disableDragging();
	  map.disableScrollWheelZoom();
	  if(openMarker){
		//jg.clear(); 
		gmarkers[openMarker].closeinfoWindow();
	  }			
			
	  // Open info window
	  gmarkers[id].openinfoWindow(popupHTML[id]);
	  openMarker = id;
		
	  // Get location of marker to draw a line
	  pixelLocation = map.fromLatLngToContainerPixel(gmarkers[id].getPoint());
	  location_x = pixelLocation.x;
	  location_y = pixelLocation.y - 21;
			
	  //ophalen aantal reacties
	  $("#jong_aantal_reacties").load("/ajax/jongerenkaart_reacties.php?type=count&id="+openMarker);

	  $("#reactie_content").html('');
	  $("#reactie_titel2").html($("#poi_titel").html());
	  // Set base height for shorter popups
	  baseHeight = 116;
	  // Start Drawing functions
	
		
	  resize_infowindow();
		
    } else {
	  map.setCenter(new GLatLng(parseFloat(searchLon), parseFloat(searchLat)));
	  getNewPois(id);
		
    }
}

/// EINDE JONGERENKAART



function removeMarker(id)
{
    if(marker_visible[id])
    {
	  marker_visible[id]=false;
	  map.removeOverlay(marker2id[id]);
    }
}

function addMarker(id)
{	
    if(!marker_visible[id])
    {
	  marker_visible[id]=true;
	  map.addOverlay(marker2id[id]);
    } 
}

function zoomMapIn() {
    map.zoomIn();
}
function zoomMapOut() {
    map.zoomOut();
}
function defaultLocation() {
    map.setCenter(new GLatLng(parseFloat(defaultLat), parseFloat(defaultLon)), 9);
    checkDrag();
}
function poiMouseOver(id) {
    if(gmarkers[id]){
	  if(openMarker != gmarkers[id]){
		gmarkers[id].openToolTip(mouseHTML[id]);
	  }
    }
}
function poiMouseOut(id) {
    if(gmarkers[id]){
	  gmarkers[id].closeToolTip();
    }
}

function poiClose(id)
{
    //jg.clear();	
    gmarkers[id].closeinfoWindow();
    gmarkers[id].openinfoWindow(popupHTML[id]);
    gmarkers[openMarker].closeinfoWindow();
    openMarker = null;
    if (poi_return) {
	  returnfrompoi();
    }
	
}

function poiClick(id,lon,lat) {	
    if (marker_visible[id]==false) {
	  marker_list_active.push(id);
	  addMarker(id);
    }
    //map.panTo(gmarkers[id].getLatLng()) ;
    if(gmarkers[id]){
	  
	  legenda_closed=false;
	  if (openMarker) { 
		poi_location = map.fromLatLngToContainerPixel(gmarkers[openMarker].getPoint());
	  }
	  if(gmarkers[id].infoWindowInstance) {
		// Clear infowindow
		poi_location = map.fromLatLngToContainerPixel(gmarkers[id].getPoint());
		gmarkers[id].closeinfoWindow();
		gmarkers[id].openinfoWindow(popupHTML[id]);
		openMarker = id;
		//if (!location_x) {
		 //   return;
		//}
		location_x = poi_location.x;
		location_y = poi_location.y - 11;

			
		//ajax request om de lijst met afbeeldingen bij deze poi op te halen
		poi_get_imgs(id);
			
	  // enable scrolling again
	  //map.enableScrollWheelZoom();
	  //if (poi_location) { map.setCenter(new GLatLng(parseFloat(poi_location.x), parseFloat(poi_location.y))); }
	  } else {
						
		if(openMarker){
		    gmarkers[openMarker].closeinfoWindow();
		}	
			
		// Open info window
		gmarkers[id].openinfoWindow(popupHTML[id]);
		openMarker = id;
			
		poi_get_imgs(id);
			

		//infowindow op juiste plaats zetten		
		resize_infowindow();
		
		
	  }
    } else {
	  map.setCenter(new GLatLng(parseFloat(searchLon), parseFloat(searchLat)));
	  getNewPois(id);
    }
}

//------------------------------------------------------
//End google map functions
//------------------------------------------------------




//------------------------------------------------------
// Search functions
//------------------------------------------------------

// Get the URL basis for the AJAX requests

function enterSubmit(e) {
    var evt=(e)?e:(window.event)?window.event:null;
    if(evt){
	  var key=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
	  if(key=="13") searchContent();
    }
}

function searchContent() {
    var locationinput = document.getElementById('toolLocationField').value;
    var getlocation_url = '';
    var location_result = '';
    var locationparts = [];
    var lon = '';
    var lat = '';
    var locationstring = '';
	
    // Remove previous errors and close the extended search div
    document.getElementById('toolSearchError').style.display="none";
    closeSearchFields();
	
    // Check if a location was filled in
    if(locationinput.length!=0){
	  getlocation_url = getBaseURL() + '/ajax/getlocation.php?location=' + locationinput;
	  location_result = handleUrl(getlocation_url);
	  // Check if the lon/lat could be retrieved
	  if(location_result!=false){
		// Get the location from the return string and show it
		locationparts = location_result.split('^');
		lon = locationparts[0];
		lat = locationparts[1];
		locationstring = locationparts[2];
		document.getElementById('toolLocationString').innerHTML = "<strong>Waar ben je?</strong> " + locationstring;
			
		// show search result div and get search results to fill the results div
		document.getElementById('toolSearchResult').style.visibility = "visible";
		document.getElementById('toolSearchResultContent').innerHTML = '<img src="gfx/loading.gif" />';
		searchpois_url = getBaseURL() + '/ajax/searchpois.php?lon=' + lon + '&lat=' + lat + '&poitypes=' + active_poitypes + '&radius=' + radius;
		searchpois_result = handleUrl(searchpois_url);
		if(searchpois_result!=false){
		    document.getElementById('toolSearchResultContent').innerHTML = searchpois_result;
		}else{
		    document.getElementById('toolSearchResultContent').innerHTML = 'Geen locaties gevonden.';
		}
		// get results and fill the image slider div
		getNewImages(lon, lat);
					
		// Backup search location, Center map, get the new pois and set location string header
		searchLon = parseFloat(lat);
		searchLat = parseFloat(lon);
		map.setCenter(new GLatLng(searchLon, searchLat));
		getNewPois();
	  }else{
		document.getElementById('toolSearchError').innerHTML="De locatie is niet gevonden.";
		document.getElementById('toolSearchError').style.display="block";
	  }
    }else{
	  document.getElementById('toolSearchError').innerHTML="Voer een locatie in om te zoeken.";
	  document.getElementById('toolSearchError').style.display="block";
    }
}

function updateLegenda(poitype,checked) {
    updatePoiTypes(poitype,checked);
    getNewPois();
}

function updatePoiTypes(poitype,checked) {
    var poitypes = active_poitypes.split(',');
    var found = false;
    var new_types = '';
	
    // Uncheck all checkboxes
    document.getElementById('toolPoitype_' + poitype).checked=checked;
    document.getElementById('legendPoitype_' + poitype).checked=checked;
	
    // Check if it is already in the list
    for (var i = 0; i < poitypes.length; i++) {
	  if(poitypes[i]==poitype){
		found = true;
	  }
    }
    // Remove if it was in the list but the checkbox is false
    if(found==true && checked==false){
	  for (var i = 0; i < poitypes.length; i++) {
		if(poitypes[i]!=poitype){
		    new_types = new_types + poitypes[i] + ',';
		}
	  }
	  active_poitypes = new_types.substr(0,new_types.length-1);
    // Add poitype if it is not in the list but should be
    }else if(found==false && checked==true){
	  for (var i = 0; i < poitypes.length; i++) {
		new_types = new_types + poitypes[i] + ',';
	  }
	  new_types = new_types + poitype + ',';
	  active_poitypes = new_types.substr(0,new_types.length-1);
    }
}

function updateRadius() {
    radius = document.getElementById('toolRadius').options[document.getElementById('toolRadius').selectedIndex].value;
}


//------------------------------------------------------
// End search functions
//------------------------------------------------------


//------------------------------------------------------
// Ajax functions
//------------------------------------------------------
var xmlhttp = false;

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
}

function handleUrl(fragment_url) {
    var returnVal = '';
    var returnStatus = false;
  
    if (window.XMLHttpRequest) {
  
	  //onreadystatechange doesnt work in firefox when xmlhttp.open is synchronous
	  xmlhttp.open("GET", fragment_url + "&ajaxcachebust="+new Date().getTime(), false);
	  xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	  xmlhttp.send(null);
	  returnVal = xmlhttp.responseText.replace(/^\s*|\s*$/g,"");
	  if(returnVal != 'false') {
		// Return document values
		returnStatus = returnVal;
	  } else {
		// The document had an error
		returnStatus = false;
	  }
	  return returnStatus;
          
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
	  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  xmlhttp.onreadystatechange = function() {

		if (xmlhttp.readyState == 4 && ((xmlhttp.status == 200)||(xmlhttp.status == 0))) {
		    returnVal = xmlhttp.responseText.replace(/^\s*|\s*$/g,"");
    
		    if(returnVal != 'false') {
			  // Return document values
			  returnStatus = returnVal;
		    } else {
			  // The document had an error
			  returnStatus = false;
		    }
		}
	  }
	  xmlhttp.open("GET", fragment_url + "&ajaxcachebust="+new Date().getTime(),false);
	  xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	  xmlhttp.send(' ');
	  return returnStatus;

    }

}


function showAddress(address) {
	poi_map.clearOverlays();
	var c=0;
	poi_map.setCenter(new GLatLng(52.380629,4.762573), 7);
  if (poi_geocoder) {
	poi_geocoder.getLatLng(
	  address,
	  function(poi_point) {
		if (!poi_point) {
		  alert("'"+address + "' kon niet worden gevonden");
		} else {			
		 $("#disableMap").hide();
		 $(".gmnoprint").hide();
		 	var marker_poi = new GMarker(poi_point, {icon: aIcons['jongeren'], draggable: false});
		  $("#toevoegen_poi_lat").val(poi_point['y']); $("#toevoegen_poi_lng").val(poi_point['x']); $("#toevoegen_poi_locatie").val(address);
		
		  poi_map.addOverlay(marker_poi);
		  
		  poi_map.setCenter(poi_point, 10);
		  GEvent.addListener(marker_poi, "click", function() {
			if (c==1) { poi_map.setCenter(poi_point, 10); }
			if (c==2) { poi_map.setCenter(poi_point, 14);  }	
			if (c>2) { poi_map.setCenter(new GLatLng(52.649729,5.075439), 8); c=0; }
			c++;
		  });
		GEvent.trigger(marker_poi, "click");
		}
	  }
	);
  }
}
//------------------------------------------------------
// END Ajax functions
//------------------------------------------------------


