var map;
var map;
var geo;
var _data = new Object();
var _markers = new Array();
var _huisid = '';
var _vpid = '';
var _showAll = false;
var fx;
var _loaded = false;
var type;
var _page = 0;
var items = new Array();

function google_load(){
  if (!_loaded) {
  	_loaded = true;
	var myOptions = {
		zoom: _center_zoom,
		center: new google.maps.LatLng(_center_lat, _center_lng),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN}

	}
	map = new google.maps.Map(document.getElementById("map"), myOptions);

	google.maps.event.addListener(map, 'dragend', updatePoints2);
	google.maps.event.addListener(map, 'zoom_changed', mapZoom);
	google.maps.event.addListener(map, 'tilesloaded', updatePoints2);
																 
	geo = new google.maps.Geocoder();
  }
}
function google_page(page)
{
	_page = page;
	clearOverlay();
	updatePoints2();
}
var overlayImage;
function clearOverlay()
{
	while(items.length > 0)
	{
		var item = items.pop();
		item.marker.setMap(null);
	}
	
	//if(!overlayImage) return;
	
}
function mapZoom()
{
	var newzoom = map.getZoom();
	if(newzoom > 12) {
		map.setZoom(12);
		return;
	}
	if($('houseabout') != null) $('houseabout').dispose();
	updatePoints2();
}

function updatePoints2()
{
    var bounds = map.getBounds();
	if(bounds == null) return;
    var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	
	var data = {
			ajax_function: 'get_locations_from_bounds',
			south: sw.lat(),
			west: sw.lng(),
			north: ne.lat(),
			east: ne.lng(),
			page: _page,
			huisid: _huisid,
			vpid: _vpid,
			van: _van,
			tot: _tot
		};
	
	if($('aantal_personen') != null)
	{
		data.volw = $('aantal_personen').value;
		data.kind = $('aantal_kinderen').value;
	}
	new Request({url:url,
		method: 'post',
		data: data,
		onComplete: showAllHouses2
	}).send();
}

function showAllHouses2(response)
{
	clearOverlay();
	var result = JSON.decode(response);
	if($('debug')!=null) $('debug').set('html', result.debug);
	if(result.found != null) $('google_found').set('html', result.found);
	if(result.paging != null) $('google_paging').set('html', result.paging);
	if(result.next != null) $('google_next').set('html', result.next);
	
	if($('vps') != null)
	{
		$$('#vps .locatie').each(function(el){
			el.dispose();
		});
		$('vps').set('html',  $('vps').innerHTML + result.html);
	}

	if(result.items != null)
	{
		for(var i=0; i<result.items.length; i++)
		{
			var item 			= result.items[i];
			var picIcon;
			if(item.huisid == null)
			{
				if(item.type == 'hotel')
				{
					picIcon 		= (item.vp_locatie_id == _vpid ? "http://www.dfb.nl/images/hotel.png" : "http://www.dfb.nl/images/hotel_blue.png");   
					item.selected 	= (item.vp_locatie_id == _vpid);
				} else
				{
					picIcon			= (item.vp_locatie_id == _vpid ? "http://www.dfb.nl/images/vp.png" : "http://www.dfb.nl/images/vp_blue.png");   
					item.selected 	= (item.vp_locatie_id == _vpid);
				}
			} else
			{
				picIcon 		= (item.huisid == _huisid ? "http://www.dfb.nl/images/house.png" : "http://www.dfb.nl/images/house_blue.png");   
				item.selected 	= (item.huisid == _huisid);
			}
			
			var marker = new google.maps.Marker({
				position:  new google.maps.LatLng(item.lat, item.lng), 
				map: map,
				icon: picIcon,
				zIndex: (item.selected ? 2 : 1)
			});  
			marker.data			= item;
			google.maps.event.addListener(marker, "mouseover", markerOver2);
			google.maps.event.addListener(marker, "mouseout", markerOut2);
			google.maps.event.addListener(marker, "click", markerClick2);	
			
			items[items.length] = {
				id: item.vp_locatie_id,
				marker: marker,
				lat: item.lat,
				lng: item.lng,
				naam: item.naam,
				prijs: item.va_prijs,
				plaats: item.plaats
			}; 
		}
	}
	addMouseOvers();
}
function markerOver2(event)
{
	var point = this.getPosition();
	var item = findItem2(point.lat(), point.lng());
	if(item && $('vp_'+item.id) != null) $('vp_'+item.id).fireEvent('mouseover');
	if(_current_url == 'zoeken' && item)
	{
		var div = new Element('div').set('id', 'houseInfo').addClass('houseInfo');
		var div_naam	= new Element("div").set('html', '<nobr>'+item.naam+'</nobr>').addClass('naam').inject(div);
		var div_plaats 	= new Element("div").set('html', '<nobr>'+item.plaats+'</nobr>').addClass('plaats').inject(div);
		var div_prijs 	= new Element("div").set('html', '<nobr>&euro; '+item.prijs+'</nobr>').addClass('prijs').inject(div);
					
		this.overlay = new DFBOverlay(point, div, map);
		var overlay = this.overlay;
		(function(){ overlay.onRemove() }).delay(2000);

	}
}

function markerOut2(event)
{
	var point = this.getPosition();
	var item = findItem2(point.lat(), point.lng());
	if(item && $('vp_'+item.id) != null) $('vp_'+item.id).fireEvent('mouseout');
	if(_current_url == 'zoeken' && this.overlay)
	{
		this.overlay.onRemove();
	}
}
function findItem2(lat, lng)
{
	var min_dist = 99999;
	var dist;
	var min_i;
	for(var i=0; i<items.length; i++)
	{
		if(items[i].lat == lat && items[i].lng == lng) return items[i];
		dist = Math.abs(items[i].lat - lat) + Math.abs(items[i].lng - lng);
		if(dist < min_dist) min_i = i;
	}
	if(min_i != null) return items[min_i];
}
function findItem2ById(id)
{
	for(var i=0; i<items.length; i++)
	{
		if(items[i].id == id) return items[i];
	}
}
var item_;
function markerClick2(event)
{
	var point = this.getPosition();
	var bounds = map.getBounds();
	var sw = bounds.getSouthWest();
	var center = new google.maps.LatLng( point.lat() + ((point.lat() - sw.lat()) / 2), point.lng() + ((point.lng() - sw.lng()) / 2)) ;
	map.setCenter(center);
	var item = findItem2(point.lat(), point.lng());
	if(!item) return;
	
	if($('vp_'+item.id) != null) 
	{
		$('vp_'+item.id).fireEvent('click');
	} else
	{
		if(item_) item_.onRemove();
		item_ = this.overlay;
		
		new Request({url:url,
			method: 'post',
			data: {
				ajax_function: 'get_house_info',
				huisid: this.data.huisid,
				vpid: this.data.vp_locatie_id
			},
			onComplete: function(response)
			{
				var div = new Element('div')
					.set('id', 'houseabout')
					.set('html', response)
					.setStyles({'position': 'absolute', 'background-image': 'url(/images/house_about.png)', 'width': 252, 'height': 236, 'z-index': 999999, 'background-repeat': 'no-repeat', 'margin-left': '-20px', 'margin-top': '-230px'});
					
				item_ = new DFBOverlay(point, div, map);	
			}
		}).send();		
	}
}

function closeHouse2(el)
{
	var div = el.parentNode.parentNode;
	if(div.get('id') == 'houseabout')
	{
		div.parentNode.removeChild(div);
	} else
	{
		div = el.parentNode.parentNode.parentNode;
		div.parentNode.removeChild(div);
	}
}

function DFBOverlay(point, div, map) 
{
  // Now initialize all properties.
  this.point_ = point;
  this.div_ = div;
  this.map_ = map;

  // We define a property to hold the image's
  // div. We'll actually create this div
  // upon receipt of the add() method so we'll
  // leave it null for now.
  // this.div_ = null;

  // Explicitly call setMap() on this overlay
  this.setMap(map);
}
DFBOverlay.prototype = new google.maps.OverlayView();


DFBOverlay.prototype.onAdd = function() {

  // Note: an overlay's receipt of onAdd() indicates that
  // the map's panes are now available for attaching
  // the overlay to the map via the DOM.

  // Set the overlay's div_ property to this DIV
  var div = this.div_;
  div.style.zIndex = 99;
  // We add an overlay to a map via one of the map's panes.
  // We'll add this overlay to the overlayImage pane.
  var panes = this.getPanes();
  overlayImage = panes.overlayImage;
  panes.overlayImage.appendChild(div);
}

DFBOverlay.prototype.draw = function() {

  // Size and position the overlay. We use a southwest and northeast
  // position of the overlay to peg it to the correct position and size.
  // We need to retrieve the projection from this overlay to do this.
  var overlayProjection = this.getProjection();

  // Retrieve the southwest and northeast coordinates of this overlay
  // in latlngs and convert them to pixels coordinates.
  // We'll use these coordinates to resize the DIV.
  var point = overlayProjection.fromLatLngToDivPixel(this.point_);

  // Resize the image's DIV to fit the indicated dimensions.
  var div = this.div_;
  if(div)
  {
	  div.style.left = point.x + 'px';
	  div.style.top = point.y + 'px';
  }
}
DFBOverlay.prototype.onRemove = function() {
  if(this.div_ && this.div_.parentNode)
  {
	  this.div_.parentNode.removeChild(this.div_);
	  this.div_ = null;
  }
}

function closeHouse(a)
{
	fx2.start('opacity', 0);
	$('houseabout').innerHTML = '';
}

function showHouse(item, show)
{
	if($('debug2')!=null)
	{
		$('debug2').set('html', 'showHouse');
	}
	for(var i=_markers.length-1; i<=0; i--)
	{
		if((item.huisid == _markers[i].data.huisid && _markers[i].data.vp_locatieid == null) || (item.vp_locatieid == _markers[i].data.vp_locatieid && _markers[i].data.huisid == null))
		{
			if(show)
			{
				_markers[i].show();
			} else
			{
				_markers[i].hide();
			}
			return;
		}
	}
	var point 			= new GLatLng(item.lat, item.lng);
	var picIcon 		= new GIcon(G_DEFAULT_ICON);
	if(item.huisid == null)
	{
		if($('debug2')!=null)
		{
			$('debug2').set('html', 'type: '+item.type);
		}
		if(item.type == 'hotel')
		{
			picIcon.image 		= (item.vp_locatie_id == _vpid ? "http://www.dfb.nl/images/hotel.png" : "http://www.dfb.nl/images/hotel_blue.png");   
			item.selected 		= (item.vp_locatie_id == _vpid);
		} else
		{
			picIcon.image 		= (item.vp_locatie_id == _vpid ? "http://www.dfb.nl/images/vp.png" : "http://www.dfb.nl/images/vp_blue.png");   
			item.selected 		= (item.vp_locatie_id == _vpid);
		}
	} else
	{
		picIcon.image 		= (item.huisid == _huisid ? "http://www.dfb.nl/images/house.png" : "http://www.dfb.nl/images/house_blue.png");   
		item.selected 		= (item.huisid == _huisid);
	}
	picIcon.shadow		= "http://www.dfb.nl/images/house_shadow.png";    	
	picIcon.iconSize 	= new GSize(24, 30);
	picIcon.shadowSize	= new GSize(27, 27);
	var marker			= new GMarker(point, {icon: picIcon, zIndexProcess: zOrder});
	_markers[_markers.length] = marker;
	marker.data			= item;
	
	GEvent.addListener(marker, "click", houseClick);
	//GEvent.addListener(marker, "mouseover", houseOver);
	//GEvent.addListener(marker, "mouseout", houseOut);
	map.addOverlay(marker);	
	if((item.huisid == _huisid || item.vp_locatie_id == _vpid) && !_showAll)
	{
		GEvent.trigger(marker, "click");
	} else if(!show)
	{
		marker.hide();
	}
}

function zOrder(marker, b)
{
	var selected = (marker.data.selected ? 9 : 0);
	return GOverlay.getZIndex(marker.getPoint().lat()) + selected*1000000;
}

var fx2;

function toggleShowAll(a)
{
	return;
	//$('fetchingProductsDiv').setStyles({'visibility': 'visible'});
	//fx.start('opacity', .8);
	//_showAll = !_showAll;
	a.innerHTML = (_showAll ? 'Laat alleen huidige huis zien' : 'Laat alle huizen zien');
	_markers = new Array();
	map.clearOverlays();
	mapMove();
}

function  findHouse(point)
{
	if(point == null && _data.trypostcode && _data.tryplaats && _data.trybigpostcode)
	{
		var lat = 0;
		var lng = 0;
		_data.trypostcode = false;
		_data.trybigpostcode = false;
		_data.tryplaats = false;
		type = 'notfound';
	}else if(point == null && _data.trypostcode && _data.tryplaats)
	{
   		type = 'postcode';
		_data.trybigpostcode = true;
   		geo.getLatLng(_data.postcode+', '+_data.land, findHouse);
		return;		
    } else if(point == null && _data.trypostcode)
	{
   		type = 'plaats';
		_data.tryplaats = true;
   		geo.getLatLng(_data.plaats+','+_data.land, findHouse);
   		return;
	} else if(point == null)
	{
   		type = 'straat';
    	_data.trypostcode = true;
   		geo.getLatLng(_data.adres+', '+_data.postcode+', '+_data.land, findHouse);
		return;
	} else
	{
		var lat = point.lat();
		var lng = point.lng();
	}
	//map.setCenter(point, 13); 
	//map.addOverlay(new GMarker(point));

	new Ajax(url, {
		method: 'post',
		data: { 
			ajax_function: 'get_vw',
			lat: lat,
			lng: lng,
			huisid: _data.huisid,
			type: type,
			acco: _data.acco
		},
		onComplete: mapMove
	}).request();
}

function foundHouse(response)
{
		//$('json').innerHTML = response;
		_data = Json.evaluate(response);
		if(_data.adres != '')
		{
	   		type = 'straat';
			geo.getLatLng(_data.adres+', '+_data.plaats+', '+_data.land, showHouse);
		} else
		{
			type = 'plaats';
    	_data.trypostcode = true;
		_data.tryplaats = true;
    	$('debug').innerHTML = _data.plaats+', '+_data.land;
			geo.getLatLng(_data.plaats+', '+_data.land, showHouse);
		}
}