var mpCluster = false;
function MapCluster() {
	this.mapVernieuw   = true;
	this.mapPadding	   = 50;
	this.mapLoc		   = false;
	this.dragTimeout   = false;
	
	// Cache
	this.cacheTotLevel = false;
	this.cacheNegeren  = true;
	this.cacheData	   = {};
	
	this.filters	 = false;
	this.vasteMarker = false;
	
	this.cirkelArray   = new Array();
	this.cirkelKlikRef = false;
	this.itemlijst	   = false;
	
	this.historieArray = new Array();
	
	// Init
	this.init = function( args ) {
		this.vasteMarker  = ( args.vasteMarker ? args.vasteMarker : false );
		this.mapLoc       = args.mapLoc;
		this.mapPadding   = ( args.mapPadding ? args.mapPadding : this.mapPadding );
		this.filters      = ( args.filters ? '&filters='+args.filters : '' );
		this.filters     += ( args.type ? '&at='+args.type : '' );
		
		if ( args.cacheTotLevel ) {
			this.cacheTotLevel = args.cacheTotLevel;
		}
		
		if ( args.itemlijstId ) {
			this.itemlijst = new MapItemlijst( args.itemlijstId );
		}
		
		// Kaart laden
		mapInit( args );
		
		// Iconen laden
		mapInitIconen();
		
		// Content laden
		this.herlaad( 200 );
		
		GEvent.addListener( map, "dragend", function() {
			mpCluster.herlaad( 500 );
		} );
		GEvent.addListener( map, "zoomend", function() {
			mpCluster.herlaad( 500 );
		} );
	};
	
	this.cirkelMarkerEvent = function( Id, EType ) {
		if ( Id && ( cirkelMarker = this.getCirkelMarker( Id ) ) ) {
			GEvent.trigger( cirkelMarker, EType );
		}
		return false;
	};
	
	this.getCirkelMarker = function( Id ) {
		for ( var i = 0; i < this.cirkelArray.length; i++ ) {
			if ( this.cirkelArray[ i ].id == Id ) {
				return this.cirkelArray[ i ];
			}
		}
		return false;
	};
	
	this.herlaad = function( Tijdsduur ) {
		clearTimeout( this.dragTimeout );
		this.dragTimeout = setTimeout( function() { 
			mapUpdatePos();
			mpCluster.vernieuw();
		}, Tijdsduur, {} );
	};
	
	this.vernieuw = function() {
		if ( !this.mapVernieuw ) {
			return;
		}
		
		if ( this.cacheTotLevel ) {
			var mapZoom = parseInt( map.getZoom(), 10 );
			if ( mapZoom > this.cacheTotLevel ) {
				this.cacheNegeren = true;
			}
			if ( !this.cacheNegeren && this.cacheData ) {
				mpCluster.herteken( this.cacheData );
				return;
			}
			
			if ( mapZoom <= this.cacheTotLevel ) {
				this.cacheNegeren = false;
			}
		}
		
		var bounds = new GLatLngBounds( mapGetBoundSw( this.mapPadding ), mapGetBoundNe( this.mapPadding ) );  
		
		$.getJSON(
			'/jx.php',
			'map=canvas&maploc='+this.mapLoc+'&bbox='+bounds.getSouthWest().toUrlValue()+','+bounds.getNorthEast().toUrlValue()+'&lvl='+map.getZoom()+
			( this.vasteMarker ? '&hid='+this.vasteMarker.id : '' )+this.filters,
			function( Data ) {
				if ( mpCluster.cacheTotLevel ) {
					if ( !mpCluster.cacheNegeren ) {
						mpCluster.cacheData = Data;
					} else {
						mpCluster.cacheData = false;
					}
				}
				mpCluster.herteken( Data );
			}
		);
	};
	
	this.herteken = function( Data ) {
		map.clearOverlays();
		
		if ( this.itemlijst ) {
			this.itemlijst.reset();
		}
		
		this.cirkelArray = new Array();
		for ( var i = 0; i < Data.items.length; i++ ) {
			jxItem = Data.items[ i ];
			if ( jxItem.geo ) {
				jxItem.lat = jxItem.geo.lat;
				jxItem.lng = jxItem.geo.lng;
			}
			
			// Cirkel
			if ( jxItem.markerType == 'cirkel' ) {
				var cirkleGrootte = this.getCirkelGrootte( jxItem.aantal, map.getZoom() );
				var cirkelMarker = new LabeledMarker(
					new GLatLng( parseFloat( jxItem.lat ), parseFloat( jxItem.lng ) ), {
						icon: mapIcons["cirkels"][ cirkleGrootte ],
						clickable: true,
						labelText: jxItem.aantal,
						title: jxItem.titel
					}
				);
				cirkelMarker.url   = jxItem.url;
				cirkelMarker.id    = jxItem.id;
				cirkelMarker.ref   = jxItem.ref;
				cirkelMarker.zoom  = Data.zoom;
				
				GEvent.addListener( cirkelMarker, 'click', function() {
					if ( this.url ) {
						top.document.location = this.url;
					} else {
						mapToLatLng( this.getLatLng().lat(), this.getLatLng().lng(), this.zoom );
						mpCluster.cirkelKlikRef = this.ref+'-'+this.id;
					}
				} );
				GEvent.addListener( cirkelMarker, 'mouseover', function() {
					this.setImage( this.getIcon().hoverImage );
					$('#cirkellink-'+this.id).addClass('hover');
				} );
				GEvent.addListener( cirkelMarker, 'mouseout', function() {
					this.setImage( this.getIcon().image );
					$('#cirkellink-'+this.id).removeClass('hover');
				} );
				
				map.addOverlay( cirkelMarker );
				this.cirkelArray.push( cirkelMarker );
				
				if ( !this.cirkelKlikRef && this.itemlijst ) {
					this.itemlijst.voegMarkerItemToe( jxItem );
				}
			}
			
			// Cluster
			else if ( jxItem.markerType == 'cluster' ) {
				var marker = new HzMarker( new GLatLng( jxItem.lat, jxItem.lng ), { icon: mapIcons["markers"]["cluster"] } );
				marker.title = 'Groepering van '+jxItem.aantal+' woningen.';
				
				var bboxBound = jxItem.bbox.split(',');
				marker.clusterbound = new GLatLngBounds( new GLatLng( bboxBound[0], bboxBound[1] ), new GLatLng( bboxBound[2], bboxBound[3] ) );
				GEvent.addListener( marker, 'click', function() {
					map.setCenter( this.getLatLng(), map.getBoundsZoomLevel( this.clusterbound ) );
				} );
				
				marker.initSettings( 'cluster' );
				
				map.addOverlay( marker );
			}
			
			// Marker
			else {
				var marker = new HzMarker( new GLatLng( jxItem.lat, jxItem.lng ), { icon: mapIcons["markers"]["item"] } );
				marker.id = jxItem.nr;
				marker.title = jxItem.adres+( jxItem.prijs ? ', '+jxItem.prijs+( jxItem.prijssoort ? ' '+jxItem.prijssoort : '' ) : '' );
				marker.html = this.getMarkerHtml( jxItem );
				marker.initSettings( 'marker' );
				map.addOverlay( marker );
			}
		}
		
		if ( this.itemlijst ) {
			if ( this.cirkelKlikRef ) {
				$.getJSON(
					'/jx.php',
					'map=aantallenlijst&maploc='+this.mapLoc+'&klik='+this.cirkelKlikRef+this.filters,
					function( LijstData ) {
						mpCluster.laadItemLijst( LijstData );
					}
				);
				
				this.cirkelKlikRef = false;
			} else {
				this.itemlijst.setKopTitel( Data.titel );
				this.itemlijst.herteken();
			}
		}
		
		if ( this.vasteMarker ) {
			map.addOverlay( this.vasteMarker );
		}
	};
	
	this.getMarkerHtml = function( jxItem ) {
		jxItem.url = ( jxItem.url ? jxItem.url+( jxItem.url.indexOf( 'details.html' ) > 0 ? '' : 'details.html' ) : 'details.html' );
		var html = '<div id="marker"'+( jxItem.status ? ' class="label-'+jxItem.status+'"' : '' )+'><a class="foto" href="'+jxItem.url+'">';
		if ( jxItem.foto ) {
			html += '<img src="'+jxItem.foto+'" width="120" height="80" onerror="$(this).attr(\'src\', \'/images/misc/geen-foto-120.gif\' );" alt="" />';
		} else {
			html += '<img src="/images/misc/geen-foto-120.gif" width="120" height="80" alt="Geen foto" />';
		}
		html += '</a>';
		
		html += '<div class="info"><a class="titel" href="'+jxItem.url+'"><strong>';
		
		html += jxItem.adres+'</strong></a>';
		html += '<div class="subtitel">'+( jxItem.postcode ? jxItem.postcode+' ' : '' )+jxItem.plaats+'</div>';
		
		html += '<div class="prijs">';
		if ( jxItem.prijshistorie ) {
			html += '<em class="wijziging">'+jxItem.prijshistorie+'</em>';
		}
		if ( jxItem.prijs ) {
			html += '<br /><strong>'+jxItem.prijs+'</strong>';
			html += ( jxItem.prijssoort ? ' <em>'+jxItem.prijssoort+'</em>' : '');
		} else {
			html += '<strong>Prijs onbekend</strong>';
		}
		html += '</div>';
		html += '</div></div>';
		
		return html;
	};
	
	this.getCirkelGrootte = function( Aantal, Lvl ) {
		Aantal = parseInt( Aantal.replace( '.', '' ), 10 );
		
		var grootteArray = [ [ 100000, 80 ], [ 10000, 68 ], [ 1000, 58 ], [ 100, 46 ], [ 10, 38 ] ];
		var grootte = 30;
		for ( var g = 0; g < grootteArray.length; g++ ) {
			if ( Aantal >= grootteArray[ g ][0] ) {
				grootte = grootteArray[ g ][1];
				break;
			}
		}
		
		if ( Lvl >= 8 && Lvl <= 12 ) {
			grootte = this.vergrootCirkelGrootte( grootte );
			if ( Lvl == 9 || Lvl == 11 ) {
				grootte = this.vergrootCirkelGrootte( grootte );
			}
		}
		
		return grootte;	
	};
	
	this.vergrootCirkelGrootte = function( Grootte ) {
		var grootteArray = [ [ 68, 12 ], [ 58, 10 ], [ 46, 12 ], [ 38, 8 ], [ 30, 8 ] ];
		for ( var g = 0; g < grootteArray.length; g++ ) {
			if ( Grootte == grootteArray[ g ][0] ) {
				return ( Grootte + grootteArray[ g ][1] );
			}
		}
		
		return Grootte;
	};
	
	this.laadItemLijst = function( Data ) {
		for ( var c = 0; c < Data.items.length; c++ ) {
			jxItem = Data.items[ c ];
			jxItem.zoom = Data.zoom;
			
			if ( this.getCirkelMarker( jxItem.id ) ) {
				this.itemlijst.voegMarkerItemToe( jxItem );
			} else {
				this.itemlijst.voegLinkItemToe( jxItem );
			}
		}
		
		this.itemlijst.setKopTitel( Data.titel );
		this.itemlijst.herteken();
	};
}

function MapItemlijst( Id ) {
	this.eleKop = $('#'+Id+'-kop');
	this.titelKop = '';
	
	this.eleLijst = $('#'+Id+'-lijst');
	this.lijstArray = new Array();
	this.linkArray = new Array();
	
	this.reset = function() {
		this.titelKop = '';
		this.lijstArray = new Array();
		this.linkArray = new Array();
	};
	
	this.herteken = function() {
		this.eleKop.html( this.titelKop );
		
		if ( this.lijstArray.length ) {
			this.eleLijst.html('<ul class="maplijst"></ul>');
			for ( var i = 0; i < this.lijstArray.length; i++ ) {
				$('ul', this.eleLijst).append( this.lijstArray[ i ] );
			}
		} else {
			this.eleLijst.html('Geen resultaten gevonden.');
		}
	};
	
	this.setKopTitel = function( Titel ) {
		this.titelKop = Titel;
	};
	
	this.voegLinkItemToe = function( LinkItem ) {
		// Item NIET op de kaart.
		var aEle = document.createElement( 'a' );
		
		if ( LinkItem.url ) {
			$(aEle).attr( 'href', LinkItem.url );
		} else {
			this.linkArray.push( LinkItem.ref+','+LinkItem.id+','+LinkItem.lat+','+LinkItem.lng+','+LinkItem.zoom );
			$(aEle).attr( { href: '', id: 'cirkelindex-'+this.linkArray.length } ).click( function() {
				var linkInfo = mpCluster.itemlijst.linkArray[ parseInt( this.id.replace( 'cirkelindex-', '' ) ) - 1 ];
				if ( linkInfo ) {
					linkInfo = linkInfo.split(',');
					mpCluster.cirkelKlikRef = linkInfo[0]+'-'+linkInfo[1];
					mapToLatLng( parseFloat( linkInfo[2] ), parseFloat( linkInfo[3] ), linkInfo[4] );
					return false;
				}
			} );
		}
		
		$(aEle).html( LinkItem.titel );
		this.voegItemToe( aEle, LinkItem.aantal );
	};
	
	this.voegMarkerItemToe = function( MarkerItem ) {
		// Item WEL op de kaart.
		var aEle = document.createElement( 'a' );
		$(aEle).attr( { href: ( MarkerItem.url ? MarkerItem.url : '' ), id: 'cirkellink-'+MarkerItem.id } ).bind( 'mouseover mouseout click', function( e ) {
			mpCluster.cirkelMarkerEvent( this.id.replace( 'cirkellink-', '' ), e.type );
			return false;
		} ).html( MarkerItem.titel );
		
		this.voegItemToe( aEle, MarkerItem.aantal );
	};
	
	this.voegItemToe = function( Ele, Aantal ) {
		var liEle = document.createElement( 'li' );
		
		if ( Aantal == '0' ) {
			$(Ele).addClass( 'nonactief' );
		}
		
		$(liEle).append( Ele );
		if ( parseInt( Aantal ) > 0 ) {
			$(liEle).append( ' <span class="aantal">('+Aantal+')</span>' );
		}
		
		this.lijstArray.push( liEle );
	};
}
