Andes.setStaticUrl(brpMapImagePath);

function brpMapType(baseUrls){
	Andes.BasicMapType.call(this, "Jacana", new Andes.RdProjection(), baseUrls, [0.8,1.6,3.2,6.4,12.8,25.6,51.2,102.4,204.8,409.8], null, "Andes")
};
Class.inherit(brpMapType, Andes.BasicMapType);

function brpMapWidget(opts, container, infoWindow){

	// properties
	var me = this;
	me.opts = cpyObj(opts, {startLocation: new Andes.Coordinate(136729, 456014), startZoom: 8, maxZoomPois: 6, iconPath: './images/icons/map/'});
	me.container = $(container);
	me.infoWindow = $(infoWindow);
	me.roundTrip = false;
	me.map = null;
	me.locations = [];
	me.markers = [];
	me.polies = [];
	me.basePolies = [];
	me.routeLocations = [];
	me.onIconClicked = null;
	me.onUserIconClicked = null;
	me.onTempIconClicked = null;
	me.onShowInfo = null;
	me.onMapMove = null;
	me.onMapClick = null;
	
	me.userLocations = [];
	me.userMarkers = [];
	me.tempLocation = null;
	me.tempMarker = null;
	me.popInfo = {};
    me.panControl = null;
	
	// init map control
	var mapType = new brpMapType(brpTileServer);
	me.map = new Andes.Maps(me.container.get(0), [mapType]);
	me.panControl = new Andes.PanControl();
	me.map.addControl(me.panControl);
	me.map.getCurrentMapType().getCopyright = function() { return "&copy; " + (new Date()).getFullYear() + " Falkplan BV"	};
	me.map.addControl(new Andes.CopyrightControl());
	me.map.setCenter(opts.startLocation, opts.startZoom);
	me.map.enableScrollWheelZoom();
	me.map.enableDoubleClickZoom();
	// nodes
	me.popInfo.node = $('<div class="popInfo" title="Klik voor meer informatie." />');
	//me.popInfo.descrNode = $('<div class="mceContentBody" />').appendTo('#popup_description', infoWindow);
	me.popInfo.node.click(function(event){me.showPopupInfo(event)}).mouseout(function(){me.hidePopupInfoIcon()});
	//$('#mapzoom_close', infoWindow).click(function(){me.infoWindow.hide()});
	$(me.map.getLayer(Andes.Maps.LAYER_FLOAT)).append(me.popInfo.node);

//tijdelijk voor LF clikken weghalen voor publicatie
    $('#bar_enableclik').click(function(){me.enableClick();});   

	
	Andes.addListener(me.map, "moveend", function(){me.loadIcons()});
	Andes.addListener(me.map, "zoomend", function(){me.loadIcons()});
	Andes.addListener(me.map, "click", function(crd,pag){me.click(crd,pag)});
	me.mapClickEnabled = false;
	me.loadIcons();
}
brpMapWidget.prototype.enableClick = function(){
  var me = this;  
  //me.map.disableDrag();
  me.mapClickEnabled = true;
}
brpMapWidget.prototype.disableClick = function(){
  var me = this;  
  //me.map.enableDrag();
  me.mapClickEnabled = false;
}
brpMapWidget.prototype.click = function(crd,pag){

    if (!this.mapClickEnabled) 
        return;
    
    var latlon;
    //crd = this.map.fromDivPixelToCoord(this.map.mouseDownPos);
    latlon = this.map.currentMapType.getProjection().fromNativeToLatLng(crd);
    

    if (this.onMapClick)
        this.onMapClick(crd.x,crd.y,latlon.lat,latlon.lng);
    this.disableClick();        
    return;
/*tijdelijk
    var ret = new Object();
    var p = this.thePoi;
    
    ret.category = BRP_CAT_ADDRESS;
    ret.iconnr = "";
    ret.id = -1;
    ret.lat = latlon.lat;
    ret.lng = latlon.lng;
    ret.x = Math.round(crd.x);
    ret.y = Math.round(crd.y);
    ret.name = "LF steunpunt";   
    this.disableClick();         
    this.showTempMarker(ret);
//einde tijdelijk    
    //this.disableClick();     */   
}
brpMapWidget.prototype.loadIcons = function(){
	if (this.map.getZoomLevel() <= 6) {
		var me = this, mb = this.map.getViewportBounds(), categories = [BRP_CAT_JUNCTIONS];
		for (var id in brpCategories) if (brpCategories[id].visible) categories.push(id);
		$.getJSON(brpGetPoisUrl + '&format=json&callback=?', {
				'x1': mb.getSouthWest().x,
				'y1': mb.getSouthWest().y,
				'x2': mb.getNorthEast().x,
				'y2': mb.getNorthEast().y,
				'cat': categories.join('+')
			},  
			function(data, textStatus){me.iconsLoaded(data, textStatus)}
		);
	}
	else {
		this.locations.length = 0;
		this.drawIcons();
	}
};

brpMapWidget.prototype.iconsLoaded = function(data, textStatus){
	this.locations = data["data"] || [];
	this.drawIcons();
};

brpMapWidget.prototype.specialIcon = function(loc){
    if (this.routeLocations && (this.routeLocations.length >0)) {
        for(var i=0; i < this.routeLocations.length; i++) {
            if (loc.id == this.routeLocations[i].id){
                var uri = this.opts.iconPath;
                var size,hot;
                if (i==0){
                    uri += 'start';
                    size = new Andes.Dimensions(32, 39);
                    hot = new Andes.Coordinate(16, 39);
                }
                else if (i == this.routeLocations.length-1){ 
                    uri += 'end';
                    size = new Andes.Dimensions(32, 39);
                    hot = new Andes.Coordinate(16, 39);
                 }
                 else { 
                    uri += 'this';
                    size = new Andes.Dimensions(27, 27);
                    hot  = new Andes.Coordinate(13, 13);
                }
                var cid = parseInt(loc.category);
                if (cid == BRP_CAT_JUNCTIONS)
			        uri += 'junction%0.png';
		        else if (cid == BRP_CAT_ADDRESS) {
                   size = new Andes.Dimensions(27, 27);
                   hot  = new Andes.Coordinate(13, 13);

                    if (i==0){
                        uri =  this.opts.iconPath + 'startpuntjunction.png';
                    }
                    else if (i == this.routeLocations.length-1){ 
                        uri =  this.opts.iconPath + 'starteindpunt.png';
                    }
                    else { 
  	                  uri =  this.opts.iconPath + 'tussenpunt.png';
                    }
			    }
			    else
			    {    
			        if ((i==0)||(i == this.routeLocations.length-1)){
			            uri += 'poi%0.png';
			            var c = cid || '00';
			            return  new Andes.Icon(uri.format(c.toLength(2)),size , hot);
			        }
			        else
			         return null;
			    }
		        var s = loc.iconnr || '00';
		        return  new Andes.Icon(uri.format(s.toLength(2)),size , hot);
		        
            }
        }
    }
    return null;
}
brpMapWidget.ICONS = {};
brpMapWidget.prototype.createIcon = function(loc){
    //draw route icons if available
    var icn = this.specialIcon(loc);
    if (icn) return icn;
    var fixedIcon =false;
	var cid = parseInt(loc.category), uri;
	icn = brpMapWidget.ICONS[loc.name];
	
	var dim =  new Andes.Dimensions(27, 27);
	var hot = new Andes.Coordinate(13, 13);
	if (icn) return icn; // cached icon
	if (icn = brpCategories[cid]){ // icon availabe in categories
		var icn = icn['mapIcon'];
		if (icn) {
		  var uri = this.opts.iconPath + 'poi%0.png';
          var c = cid || '00';
          size = new Andes.Dimensions(27, 27);
          hot  = new Andes.Coordinate(13, 13);
          uri = uri.format(c.toLength(2));  
		  icn = new Andes.Icon(uri, new Andes.Dimensions(icn['width'] || 0, icn['height'] || 0), new Andes.Coordinate(icn['offsetx'] || 0, icn['offsety'] || 0));
		}  
	}
	if (!icn) {
		uri = this.opts.iconPath;
		if (cid == BRP_CAT_JUNCTIONS)
			uri += 'junction%0.png';
		else if (cid == BRP_CAT_ADDRESS) {
		   if (this.tempMarker ==null) 
			    uri += 'address%0.png';
		   else {
		    fixedIcon = true;
		    if (this.routeLocations.length==0) {
	           dim =  new Andes.Dimensions(32, 39);
	           hot = new Andes.Coordinate(16, 39);		    
               uri += 'startpuntjunction.png';
            }
            else if (loc == this.routeLocations[this.routeLocations.length -1]){   
    	            dim =  new Andes.Dimensions(32, 39);
	                hot = new Andes.Coordinate(16, 39);		    
	                uri += 'starteindpunt.png';
	             }
	             else
	                uri += 'tussenpunt.png';		    		    
		   }	    
		}    	    
		var s = loc.iconnr || '00';
		if(!fixedIcon)
		    icn = new Andes.Icon(uri.format(s.toLength(2)), new Andes.Dimensions(27, 27), new Andes.Coordinate(13, 13));
		else
		    icn = new Andes.Icon(uri, dim ,hot);
	}
	brpMapWidget.ICONS[loc.icon] = icn;
	return icn
}

brpMapWidget.prototype.drawIcons = function(){
	if(lsw)
	    this.routeLocations = lsw.locations;
	//buienradar
    if(ww)
       ww.initBuien(true);
       
	// clear all markers		
	for (var i = 0; i<this.markers.length; i++)
		this.map.removeOverlay(this.markers[i]);
	this.markers.length = 0;

	// add new markers
	var zoomlevel = this.map.getZoomLevel();
	if (zoomlevel <= this.opts.maxZoomPois) {
		var me = this;
		for (var i = 0; i<this.locations.length; i++) {
			var loc = this.locations[i], idx = i, 
				mrkr = new Andes.Marker(new Andes.Coordinate(loc.x, loc.y), this.createIcon(loc), { "title": (loc.name=='nn')? '' : loc.name });
			Andes.addListener(mrkr, "click", me.createIconClickHandler(idx));
			if (parseInt(loc.category) > BRP_CAT_JUNCTIONS && loc.description){
				Andes.addListener(mrkr, "mouseover", aplyArgs(me, me.markerMouseOver, i));
				Andes.addListener(mrkr, "mouseout", aply(me, me.markerMouseOut))
			}
			this.map.addOverlay(mrkr);
			this.markers.push(mrkr);
		}
	}
	if (this.onMapMove)
	    this.onMapMove();            
}

brpMapWidget.prototype.markerMouseOver = function(idx){
	var pi = this.popInfo;
	if (pi.timer) {
		clearTimeout(pi.timer);
		pi.timer = null
	}
	pi.index = idx;
	pi.timer = setTimeout(aply(this, this.showPopupInfoIcon), 500)
}

brpMapWidget.prototype.markerMouseOut = function(evt){
	var pi = this.popInfo;
	if (pi.timer) {
		clearTimeout(pi.timer);
		pi.timer = null
	} else {
		// if element we move onto is the info icon then enable; otherwise hide info icon
		if ((evt.relatedTarget || evt.toElement) == pi.node[0]){
			
		}else{
			this.hidePopupInfoIcon()
		}
	}
}

brpMapWidget.prototype.showPopupInfoIcon = function(){
	var pi = this.popInfo;
	pi.timer = null;
	var mrkr = (pi.index == -1)? this.tempMarker : this.markers[pi.index], pxc = this.map.fromCoordToDivPixel(mrkr.getCoordinate()),
		dim = mrkr.getIcon().getDimensions(), anchor = mrkr.getIcon().getImageAnchor();
	pi.node.css({'left': parseInt(pxc.x) + dim.width - anchor.x - 1,'top': parseInt(pxc.y) - anchor.y - 4}).show()
}

brpMapWidget.prototype.hidePopupInfoIcon = function(){
	this.popInfo.node.hide()
}

brpMapWidget.prototype.showPopupInfo = function(event){

    if ( event.pageX == null && event.clientX != null ) { 
                        var e = document.documentElement, b = document.body; 
                        event.pageX = event.clientX + (e && e.scrollLeft || b.scrollLeft || 0); 
                        event.pageY = event.clientY + (e && e.scrollTop || b.scrollTop || 0); 
                } 

    if ((event.pageX)&&(this.onShowInfo)){
        var X,Y;
        X = event.pageX;
        Y = event.pageY;    	
	    var loc =(this.popInfo.index ==-1) ? this.tempLocation : this.locations[this.popInfo.index];
	    this.onShowInfo(X,Y,loc);

	}
}

brpMapWidget.prototype.createIconClickHandler = function(idx){
	var me = this;
	return function(event){me.iconClicked(event,idx);};
}

brpMapWidget.prototype.iconClicked = function(event,i){
	if (i==-1){
		if (this.onTempIconClicked){
		    if (parseInt(this.tempLocation.category) > BRP_CAT_JUNCTIONS && this.tempLocation.description){
		        this.popInfo.index =i;
		        this.showPopupInfo(event);
		    }
		    else   
			  this.onTempIconClicked(this.tempLocation);
		}	
	}
	else if (i<1000) {
		if (this.onIconClicked){
		    if (parseInt(this.locations[i].category) > BRP_CAT_JUNCTIONS && this.locations[i].description){
		        this.popInfo.index =i;
		        this.showPopupInfo(event);
		    }
		    else
			  this.onIconClicked(this.locations[i]);
		}
	}
	else {
		if (this.onUserIconClicked){
			this.onUserIconClicked(this.userLocations[i-1000]);
		}
	}
};

brpMapWidget.prototype.zoomTo = function(loc, zoom){
	this.map.setCenter(new Andes.Coordinate(loc.x, loc.y), zoom);
}
 
brpMapWidget.prototype.drawRoute = function(route){

	// clear all polies
	for (var i = 0; i<this.polies.length; i++)
		this.map.removeOverlay(this.polies[i]);
	this.polies.length = 0;
	
	// add route
	if (route){
		var zoomlevel = this.map.getZoomLevel();
		var coords = new Array();
		$(route.sections).each(function(){
			$(this.coordinates).each(function(){
				coords.push(new Andes.Coordinate(this.x, this.y));
			});
		});
		if (coords.length>0) {
		    var polyline;
		    //if ((this.basePolies)&&(this.basePolies.length >0))
		    //    polyline = new Andes.Polyline(coords, "#1901FF", (14-zoomlevel)/2.0);
            //else                    
			    polyline = new Andes.Polyline(coords, "blue", (14-zoomlevel)/2.0);
			this.map.addOverlay(polyline);
			this.polies.push(polyline);
		}
	}
}

brpMapWidget.prototype.drawBaseCoords = function(baseCoords){

	// clear all base polies
	for (var i = 0; i<this.basePolies.length; i++)
		this.map.removeOverlay(this.basePolies[i]);
	this.basePolies.length = 0;
	
	// add base 
	var me = this;
	if (baseCoords){
	    var data = null;
	    try { 
         data = $.parseJSON(baseCoords);
        }
        catch(err){
            data = null;
        } 
        if (data){
		    var zoomlevel = this.map.getZoomLevel();
		    var coords = new Array();
		    $(data).each(function(){
			    $(this).each(function(){
				    coords.push(new Andes.Coordinate(this.x, this.y));
			    });
			
			    if (coords.length>0) {
                    
                    var polyline;
			        if ((me.routeLocations)&&(me.routeLocations.length >0))
			            polyline = new Andes.Polyline(coords, "#FFFF00", (24-zoomlevel)*1.5 , 0.5);
                    else                    
			            polyline = new Andes.Polyline(coords, "blue", (14-zoomlevel)/2.0);
			
			        me.map.addOverlay(polyline);
			        me.basePolies.push(polyline);
			        coords.length =0;
		        }
			    
		    });
		    
		}
	}
}


brpMapWidget.prototype.showTempMarker = function(loc){
	var me = this;
	if (this.tempMarker)
		this.map.removeOverlay(this.tempMarker);


    var c= parseInt(loc.category), uri = "";
	if (c > BRP_CAT_JUNCTIONS)
	{
	    uri = this.opts.iconPath + 'poi%0.png';
        uri = uri.format(c.toLength(2));  
	}
    else 
    {
        loc.icon = brpTempMarkerIcon;
	    uri = this.opts.iconPath +"address00.png";        
    }

		
		
	var icn = new Andes.Icon(uri , new Andes.Dimensions(27, 27), new Andes.Coordinate(13, 13));
	var mrkr = new Andes.Marker(new Andes.Coordinate(loc.x, loc.y), icn , { "title": loc.name});
	Andes.addListener(mrkr, "click", me.createIconClickHandler(-1));
	if (parseInt(loc.category) > BRP_CAT_JUNCTIONS && loc.description){
		Andes.addListener(mrkr, "mouseover", aplyArgs(me, me.markerMouseOver, -1));
		Andes.addListener(mrkr, "mouseout", aply(me, me.markerMouseOut))
	}
	mrkr.enableDragging();                    
	this.map.addOverlay(mrkr);
	this.tempMarker = mrkr;
	this.tempLocation = loc;
}

brpMapWidget.prototype.hideTempMarker = function(){
	if (this.tempMarker){
		this.map.removeOverlay(this.tempMarker);
		this.tempMarker = null;
		this.tempLocation = null;
	}
}

brpMapWidget.prototype.addUserMarker = function(loc){
	var me = this;
	var n = this.userMarkers.length + 1;
	loc.iconnr = n < 10 ? '0' + n : '' + n;
	loc.id = 1000 + n;
	var mrkr = new Andes.Marker(new Andes.Coordinate(loc.x, loc.y), this.createIcon(loc), { "title": loc.name});
	Andes.addListener(mrkr, "click", me.createIconClickHandler(1000+this.userLocations.length));                    
	this.map.addOverlay(mrkr);
	this.userMarkers.push(mrkr);
	this.userLocations.push(loc);
}

brpMapWidget.prototype.resize = function(){
	this.map.checkResize();
}
brpMapWidget.prototype.showPancontrol = function(){
    var me = this;
    if(!me.panControl)
    {
  	    me.panControl = new Andes.PanControl();
	    me.map.addControl(me.panControl);
	}
}
brpMapWidget.prototype.hidePancontrol = function(){
    var me = this;
    if(me.panControl)
    {
	    me.map.removeControl(me.panControl);
	    me.panControl =null;
	}
}

brpMapWidget.prototype.clearMarkers = function(loc){
	
	if (this.tempMarker){
		this.map.removeOverlay(this.tempMarker);
		this.tempMarker = null;
		this.tempLocation = null;
	}
	
	var me = this;
	for(var n=0; n < this.userMarkers.length; n++) {
	    this.map.removeOverlay(this.userMarkers[n]);
    }
	this.userMarkers.length =0;
	this.userLocations.length =0;
}

