/*var categories = ["appartement", "maison", "stationnement", "atypique", "prestige", "investissement", "terrain-immeuble", "commerce", "bureaux", "industrie", "prestation", "location", "achat"];*/

var poiTypes = ["velo", "commerce", "creche", "parking"];

document.write('<link rel="stylesheet" href="weezmap/css/styles.css" type="text/css" />');  
document.write('<link rel="stylesheet" href="weezmap/css/styles2.css" type="text/css" />'); 

function WeezControl() {
}

function conv_type(num){
	switch (num) {
		case '1':return "Appartement";
		case '2':return "Maison";
		case '3':return "Terrain";
		case '4':return "Immeuble";
		case '5':return "Local";
		case '6':return "FDC";
		case '7':return "Parking";
		case '11':return "Appartement";
		case '12':return "Maison";
		case '13':return "Bureau";
		case '14':return "Parking";
		default : return "Annonce";
	}
}

function capitalize(strObj){
	return (strObj.charAt(0).toUpperCase() + strObj.substr(1).toLowerCase());
}

function addSpaces(nStr)
{
	nStr += '';
	x = nStr.split(',');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}

WeezControl.prototype = new GControl();

WeezControl.prototype.initialize = function(map){
	var container = document.createElement("div");
	
	var zoomInImg = document.createElement("img");
   	zoomInImg.id = "zoomin";
	zoomInImg.src = "weezmap/css/zoomin.png";
	GEvent.addDomListener(zoomInImg, "click", function() {
		if (map.getZoom() < 16){
      	  map.zoomIn();
        }
   	});
   	container.appendChild(zoomInImg);
   	
   	var zoomOutImg = document.createElement("img");
   	zoomOutImg.id = "zoomout";
	zoomOutImg.src = "weezmap/css/zoomout.png";
	GEvent.addDomListener(zoomOutImg, "click", function() {
		if (map.getZoom() > 11){
        	map.zoomOut();
        }
   	});
   	container.appendChild(zoomOutImg);
   	
   	var leftImg = document.createElement("img");
   	leftImg.id = "left";
	leftImg.src = "weezmap/css/left.png";
	GEvent.addDomListener(leftImg, "click", function() {
        map.panBy(new GSize(200, 0));
   	});
    container.appendChild(leftImg);

   	var rightImg = document.createElement("img");
   	rightImg.id = "right";
	rightImg.src = "weezmap/css/right.png";
	GEvent.addDomListener(rightImg, "click", function() {
        map.panBy(new GSize(-200, 0));
   	});
    container.appendChild(rightImg);
    
    var topImg = document.createElement("img");
   	topImg.id = "top";
	topImg.src = "weezmap/css/up.png";
	GEvent.addDomListener(topImg, "click", function() {
        map.panBy(new GSize(0, 200));
   	});
    container.appendChild(topImg);

   	var downImg = document.createElement("img");
   	downImg.id = "down";
	downImg.src = "weezmap/css/down.png";
	GEvent.addDomListener(downImg, "click", function() {
        map.panBy(new GSize(0, -200));
   	});
    container.appendChild(downImg);
   	
   	var centerImg = document.createElement("img");
   	centerImg.id = "recenter";
	centerImg.src = "weezmap/css/center.png";
	GEvent.addDomListener(centerImg, "click", function() {
        map.returnToSavedPosition();
   	});
    container.appendChild(centerImg);

	container.style.width = "63px";
	container.style.height = "100px";

	map.getContainer().appendChild(container);
    return container;
}

WeezControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(2, 3));
}

function WeezMap(){

	var self = this;
	
	self.firstUpdate = true;

	self.searchLocation = null;
	self.pin = null;
	self.circle = null;

	self.props = new Array();
	self.groups = new Array();
	self.markers = new Array();
	
	self.listItems = null;

	self.pois = new Array();		
	self.poiMarkers = new Array();

	self.infoWindowPoint = null;

	self.init = function(){
	
		if (GBrowserIsCompatible()) {
		
			self.map = new GMap2($("#map")[0]);
			

			
			//self.map.setCenter(new GLatLng(45.76985796144351, 4.824886322021484), 15);
			self.map.setCenter(new GLatLng(document.getElementById("lat").value, document.getElementById("lng").value), parseInt(document.getElementById("zoom").value));
			
			self.setPin(new GLatLng(document.getElementById("lat").value, document.getElementById("lng").value), parseInt(document.getElementById("zoom").value));
			
			self.map.disableDoubleClickZoom();
			
			var ctrl = new WeezControl();
			self.map.addControl(ctrl);
			
			var mapTypeCtrl = new GMapTypeControl();
			self.map.addControl(mapTypeCtrl);			
			
        	self.geocoder = new GClientGeocoder();
			
			
			self.icons = new Object();
			self.greenIcons = new Object();
			
			for (i = 1; i < 100; i++){
			
				if (i > 6){
					index = 6;
				}else{
					index = i;
				}
			
				self.icons[i] = new GIcon();
	    		self.icons[i].shadow = "weezmap/markers/shadow.png";
	    		self.icons[i].shadowSize = new GSize(40, 33);
		        self.icons[i].image = "weezmap/markers/" + index + ".png";
	    		self.icons[i].iconSize = new GSize(24, 33);
	    		self.icons[i].iconAnchor = new GPoint(13, 33);
	    	}
	    	
			for (i = 1; i < 100; i++){
			
				if (i > 6){
					index = 6;
				}else{
					index = i;
				}
			
				self.greenIcons[i] = new GIcon();
	    		self.greenIcons[i].shadow = "weezmap/markers/shadow.png";
	    		self.greenIcons[i].shadowSize = new GSize(40, 33);
		        self.greenIcons[i].image = "weezmap/markers/" + index + "green.png";
	    		self.greenIcons[i].iconSize = new GSize(24, 33);
	    		self.greenIcons[i].iconAnchor = new GPoint(13, 33);
	    	}
			
			
			GEvent.addListener(self.map, "moveend", function() {
				var bounds = self.map.getBounds();
				$('#bounds').attr("value", bounds.toString());
				var center = self.map.getCenter();
				$('#center').attr("value", center.toString());
        	});
        	
        	//$('#adresse').change(function(){
			//	self.showAddress($('#addresse').val());
        	//});

        	
         	GEvent.addListener(self.map, "zoomend", function() {
         		self.map.getInfoWindow().hide();
          		self.updateProps();
          		self.updatePois();
         	});
         	
         	GEvent.addListener(self.map, "moveend", function() {
          		self.updateProps();
          		self.updatePois();
         	});
         	
         	
         	for (i = 1; i <= 12; i++){
         		$('#type' + i).click(function(){self.map.getInfoWindow().hide(); self.updateProps()});
         	}

         	$.each(poiTypes, function(i, poiType){
         		$('#' + poiType).click(function(){self.updatePois()});
         	});

         	for (i = 1; i <= 5; i++){
         		$('#' + i + 'c').click(function(){self.map.getInfoWindow().hide(); self.filterGroups(); self.updateGroupsDisplay()});
         		$('#' + i + 'p').click(function(){self.map.getInfoWindow().hide(); self.filterGroups(); self.updateGroupsDisplay()});
         	}
 
          	//$('#radius').change(function(){self.updateCircle()});  
         	$('#neuf').change(function(){self.map.getInfoWindow().hide(); self.updateProps()});          	      	

         	$('#minbudget_').change(function(){self.updateDisplay()});
         	$('#prixmax').change(function(){self.updateDisplay()});

         	$('#minsurface_').change(function(){self.updateDisplay()});
         	$('#maxsurface_').change(function(){self.updateDisplay()});

        	$('#alln').change(function(){self.map.getInfoWindow().hide(); self.filterGroups(); self.updateGroupsDisplay()});
        	$('#7n').change(function(){self.map.getInfoWindow().hide(); self.filterGroups(); self.updateGroupsDisplay()});
         	$('#15n').change(function(){self.map.getInfoWindow().hide(); self.filterGroups(); self.updateGroupsDisplay()});

         	$('#annee').change(function(){self.map.getInfoWindow().hide(); self.filterGroups(); self.updateGroupsDisplay()});
 
   	
         	if ($("#adresse").val() != ''){
         		//self.showAddress($("#adresse").val());
         	}
         	
         	self.updateProps();
         	self.updatePois();
      	}
  	};

	self.updateDisplay = function(){
		if (self.map.getInfoWindow().isHidden() == false){
			self.searchLocation = self.map.getInfoWindow().getPoint();
		}
		//self.groupProps();
		self.updateGroupsDisplay();
	}
  	
  	self.updatePois = function(){
		var bounds = self.map.getBounds();
		$.getJSON("weezmap/ajaxbridgenew.php",
			{what: "pois", minLat: bounds.getSouthWest().lat(), minLng: bounds.getSouthWest().lng(), maxLat: bounds.getNorthEast().lat(), maxLng: bounds.getNorthEast().lng()},
    	function(data){
    		self.pois = data;
			self.updatePoisDisplay();
        });
  	};
  	
  	self.typesList = function(){
  		var types = '';
		for (i = 1; i <= 12; i++){
			if ($('#type' + i).attr('checked')){
				if (types != ''){
					types += ',';
				}
				types += i;
			}
		}
		return types;
	}

  	self.updateProps = function(){
		var bounds = self.map.getBounds();

		var requestArray = {what: "BIENS", minLat: bounds.getSouthWest().lat(), minLng: bounds.getSouthWest().lng(), maxLat: bounds.getNorthEast().lat(), maxLng: bounds.getNorthEast().lng(), types: self.typesList(), neuf: $('#neuf').attr('checked'), grouping: "map", vendu: $("#vendus").val()};
		

		
		$.getJSON(
			"weezmap/ajaxbridgenew.php",
			requestArray,
    		function(data){

    			self.groups = data;
    			self.filterGroups();
				self.updateGroupsDisplay();
				
				if (self.firstUpdate == true){
					self.firstUpdate = false;
					
					$.each(self.groups, function(i,item){

        				var point = new GLatLng(item[0]['lat'], item[0]['lng']);
        					

        				
						if (parseFloat(item[0]['lat']) == parseFloat(document.getElementById("infowindow-lat").value)){
							self.showInfoWindow(item);
						}
        			});
 
					
				}
        	}
        );
  	};
  	
  	
  	self.updateList = function(){
		var bounds = self.map.getBounds();

		var requestArray = {what: "BIENS", minLat: bounds.getSouthWest().lat(), minLng: bounds.getSouthWest().lng(), maxLat: bounds.getNorthEast().lat(), maxLng: bounds.getNorthEast().lng(), types: self.typesList(), neuf: $('#neuf').attr('checked'), grouping: "list", vendu: $("#vendus").val()};
		
		$("#liste").html('');
		$("#navigation_grise")[0].style.display = "block";
		$("#diamtre_grise")[0].style.display = "block";
		$.getJSON(
			"weezmap/ajaxbridgenew.php",
			requestArray,
    		function(data){

    			self.listItems = data;
    			self.updateListDisplay();
        	}
        );
  	};
  	
  	self.updateListDisplay = function(){
  		
  		listHtml = '';

  		
		$.each(self.listItems, function(i,item){
			if (self.matchFilters(item) == true){
			    var point = new GLatLng(item['lat'], item['lng']);
			    if (self.pin != null && ($("#radius").val() != 0) && (point.distanceFrom(self.pin.getLatLng()) > $("#radius").val()*1000)){
			    }else{
					listHtml += self.itemHtml(item);
				}
			}
		});
		
		$("#liste").html(listHtml);
  	}
  	
  	self.matchFilters = function(item){
  	
  		//return true;
  	
		var includeItem = true;
		
		/*$.each(categories, function(i,category){
			if ($('#' + category).attr('checked') != true) {
				if (item['CATEGORIE'] == category){
					includeItem = false;
				}
			}
		});*/
		
		var skip = true;
     	for (i = 1; i <= 5; i++){
     		if (self.params['NB_PIECES'][i] == true){
				skip = false;
     		}
     	}
     	
     	if (skip == false){
	     	for (i = 1; i <= 5; i++){
				if (self.params['NB_PIECES'][i] == false) {
					if (i == 5 && item['NB_PIECES'] >= 5){
						includeItem = false;
					}
					if (item['NB_PIECES'] == i){
						includeItem = false;
					}
				}
			}
		}

		skip = true;
     	for (i = 1; i <= 5; i++){
     		if (self.params['NB_CHAMBRES'][i] == true){
				skip = false;
     		}
     	}
     	if (skip == false){
	     	for (i = 1; i <= 5; i++){			
				if (self.params['NB_CHAMBRES'][i] == false) {
					if (i == 5 && item['NB_CHAMBRES'] >= 5){
						includeItem = false;
					}
					if (item['NB_CHAMBRES'] == i){
						includeItem = false;
					}
				}
			}
		}
		
		var maxprice = self.params['PRIX_MAX'];
		if (maxprice == 1000000){
			maxprice = 10000000000;
		}

		if (parseInt(item['PRIX']) > maxprice){
			includeItem = false;
		}

		if (parseInt(item['LOYER']) > self.params['LOYER_MAX']){
			includeItem = false;
		}

		if (parseInt(self.params['ANNEE']) > 0 && parseInt(item['ANNEE']) != parseInt(self.params['ANNEE'])){
			includeItem = false;
		}
	
		var minsurface = self.params['SURF_MIN'];
		var maxsurface = self.params['SURF_MAX'];

		if (parseInt(item['SURF_HAB']) < minsurface || parseInt(item['SURF_HAB']) > maxsurface){
			includeItem = false;
		}
		
		if (parseInt(item['DPE_VAL2']) > self.params['CARBONE_MAX']){
			includeItem = false;
		}
		
		if (parseInt(item['DPE_VAL1']) > self.params['ENERGIE_MAX']){
			includeItem = false;
		}
		
		if ($("#alln").attr('checked') == false){
			if ($("#7n").attr('checked') == true){
				maxDays = 7;
			}
			if ($("#15n").attr('checked') == true){
				maxDays = 15;
			}
			if (parseInt(item['since']) > maxDays){
				includeItem = false;
			}
		}
		
		/*point = new GLatLng(item['lat'], item['lng']);
        if (self.pin != null && ($("#radius").val() != 0) && (point.distanceFrom(self.pin.getLatLng()) > $("#radius").val()*1000)){
        	includeItem = false;
        }*/

		return includeItem;
  	}
  	
  	self.orderByPrice = function(items){
  		rv = new Array();

  		  		//return items;
  			for (i = 0; i < items.length; i++){
  				items[i]['ordered'] = false;
  			}
  		for (j = 0; j < items.length; j++){
			candidate = {PRIX : 999999999999999999};
  			for (i = 0; i < items.length; i++){
  				if (items[i]['ordered'] == false && items[i]['PRIX'] < candidate['PRIX']){
					candidate = items[i];
					
  				}
  			}
  			candidate['ordered'] = true;
  			rv[j] = candidate
  		}
  		
  		  		return rv;
  		
  	}
  	
  	
  	self.groupProps = function(){
  		self.groups = new Array();
  		
  		listHtml = '';
		$.each(self.props, function(i,item){
			if (self.matchFilters(item) == true){
				if (self.groups.length == 0){
					self.groups[0] = new Array();
					self.groups[0]['lat'] = item['lat'];
					self.groups[0]['lng'] = item['lng'];
					self.groups[0]['props'] = new Array();
					self.groups[0]['props'][0] = item;
				}else{
					var foundGroup = false;
					var j = 0;
					while(j < self.groups.length){
						//itemPixels = self.map.fromLatLngToContainerPixel(new GLatLng(item['lat'], item['lng']));
						//groupPixels = self.map.fromLatLngToContainerPixel(new GLatLng(self.groups[j]['lat'], self.groups[j]['lng']));
						if (Math.abs(item['lat'] - self.groups[j]['lat']) + Math.abs(item['lng'] - self.groups[j]['lng']) < 0.001){
							self.groups[j]['props'].push(item);
							foundGroup = true;
							break;
						}
						
						j++;
					}
					if (foundGroup == false){
						var newGroup = new Array();
						newGroup['lat'] = item['lat'];
						newGroup['lng'] = item['lng'];
						newGroup['props'] = new Array();
						newGroup['props'][0] = item;
						self.groups.push(newGroup);
					}
				}
			}
		});
		
  		//$("#liste").html(listHtml);
  	};
  	

  	self.updatePoisDisplay = function(){
		$.each(self.poiMarkers, function(i,item){
			self.map.removeOverlay(item);
		});
		poiMarkers = new Array();
		$.each(self.pois, function(i,item){

        	var point = new GLatLng(item['lat'], item['lng']);
        	
		    //if (self.pin != null && ($("#radius").val() != 0) && (point.distanceFrom(self.pin.getLatLng()) > $("#radius").val()*1000)){
        	if ($("#" + item['type']).attr('checked') == true){
				marker = new GMarker(point);
				var icon = new GIcon();
	    		icon.shadow = "weezmap/markers/shadow.png";
	    		icon.iconSize = new GSize(40, 33);
		        icon.image = "weezmap/markers/" + item['type'] + ".png";
	    		icon.iconSize = new GSize(24, 33);
	    		icon.iconAnchor = new GPoint(13, 33);
	    		
				var markerOptions = { icon: icon, clickable: true };
	      		var marker = new GMarker(point, markerOptions);
	      		
	      		GEvent.addListener(marker, 'click', 
					function(){
						html = '<div class="poi"><img class="poiicon" src="weezmap/markers/' + item['type'] + '.png"/>';
						type =  item['type'];
						
						if (type == "creche"){
							type = "Ecole/crêche";
						}
						
						html += "<div class=\"poicontent\">" + "<div class=\"poititle\">" + type + "</div>" + item['description'].replace(/\n/g,'<br />') + '<br/><br/><a href="http://dismoiou.fr" target="_blank"><img src="weezmap/css/dismoiou.png" /></a></div></div>';
	      				self.map.openInfoWindowHtml(point, html, {pixelOffset:new GSize(0, 0)});

					}
				);
	      		

				
				self.map.addOverlay(marker);
				self.poiMarkers.push(marker);
			}
		});	
  	};
  	
  	self.filterGroups = function(){
  	
  		self.params = new Object();
  	
  		self.params['NB_PIECES'] = new Object();
  		self.params['NB_CHAMBRES'] = new Object();
		for (i = 1; i <= 5; i++){
			self.params['NB_PIECES'][i] = $('#' + i + 'p').attr('checked');
			self.params['NB_CHAMBRES'][i] = $('#' + i + 'c').attr('checked');
     	}
  	
  		self.params['SURF_MIN'] = parseInt($('#surfacemin').val());
  		self.params['SURF_MAX'] = parseInt($('#surfacemax').val());
  		self.params['PRIX_MAX'] = parseInt($('#prixmax').val());
  		self.params['LOYER_MAX'] = parseInt($('#budgetmax').val());
   		self.params['CARBONE_MAX'] = parseInt($('#gazmax').val());
   		if (self.params['CARBONE_MAX'] == 82){
   			self.params['CARBONE_MAX'] == 999999999999;
   		}
   		self.params['ENERGIE_MAX'] = parseInt($('#enermax').val());
   		if (self.params['ENERGIE_MAX'] == 455){
   			self.params['ENERGIE_MAX'] == 999999999999;
   		}
 
    	self.params['ANNEE'] = $("#annee").val();
  	
  		$.each(self.groups, function(i, group){
  			$.each(group, function(j, item){
  	    		item['active'] = self.matchFilters(item);
  			});
  		});
  		
  		
  		
  		self.updateGroupsDisplay();
  	}
  	
  	self.updateGroupsDisplay = function(){
  	
		$.each(self.markers, function(i, marker){
			marker.deleteMe = true;
			//self.map.removeOverlay(item);
		});
		//self.markers = new Array();
		
		$.each(self.groups, function(i,item){

        	var point = new GLatLng(item[0]['lat'], item[0]['lng']);
        	
        	if (self.pin != null && ($("#radius").val() != 0) && (point.distanceFrom(self.pin.getLatLng()) > $("#radius").val()*1000)){
        	}else{

				/*var icon = new GIcon();
	    		icon.shadow = "weezmap/markers/shadow.png";
	    		icon.shadowSize = new GSize(40, 33);
		        icon.image = "weezmap/markers/" + item.props.length + ".png";
	    		icon.iconSize = new GSize(24, 33);
	    		icon.iconAnchor = new GPoint(13, 33);*/
	    		
	    		var count = 0;
	    		
	    		$.each(item, function(j, item2){
	    			//item2['active'] = self.matchFilters(item2);
	    			if (item2['active'] == true){
	    				count++;
	    			}
	    		});
	    		
	    		if (count != 0){
	    		

	    		
	    			var newMarker = true;
	    			
					$.each(self.markers, function(i, marker){
						if (marker['id'] == item[0]['id']){
							if ('' + marker.getIcon().image == '' + self.icons[count].image){
								newMarker = false;
								marker['deleteMe'] = false;
							}
						}
					});
	    		
	    			if (newMarker == true){
						var markerOptions = { icon: self.icons[count]};
	      				var marker = new GMarker(point, markerOptions);
	      				marker['id'] = item[0]['id'];
						marker['deleteMe'] = false;
				
						GEvent.addListener(marker, 'click', 
							function(){

							
								self.searchLocation = null;
							    self.hideRollover(item);
								self.showInfoWindow(item);

							}
						);
						
						GEvent.addListener(marker, 'mouseover', 
							function(){
							    self.showRollover(item);
							}
						);
						
						GEvent.addListener(marker, 'mouseout', 
							function(){
							    self.hideRollover(item);
							}
						);
						
						self.markers.push(marker);
						self.map.addOverlay(marker);
					}
				}
			}			
      	});
      	
		for (var i = 0; i < self.markers.length; i++){
			var marker = self.markers[i];
			if (marker.deleteMe == true){
				self.map.removeOverlay(marker);
				self.markers.splice(i, 1);
				i--;
			}
		}
  	};
  	
  	self.showRollover = function(item){
  
  		item2 = [];
  	
  		for (k = 0; k < item.length; k++){
  			if (this.matchFilters(item[k])){
  				item2.push(item[k]);
  			}
  		}


  	
  	
  						$.each(self.markers, function(i, marker){
						if (marker['id'] == item[0]['id']){
							marker.setImage("weezmap/markers/high" + Math.min(item2.length, 6) + ".png");
						}
					});
  	
  	
  		document.getElementById("map-rollover-container").style.display = "block";
  	   	var point = new GLatLng(item[0]['lat'], item[0]['lng']);
 		var p = self.map.fromLatLngToContainerPixel(point);
		document.getElementById("map-rollover-container").style.top = (p['y'] - 49) + "px";
		document.getElementById("map-rollover-container").style.left = (p['x'] - 100) + "px";
		
		document.getElementById("map-rollover").innerHTML = self.rolloverHtml(item2[0], 120);
		
		if (item2.length == 1){
			document.getElementById("map-rollover").style.backgroundImage = "url(weezmap/css/rollover1.png)";
		}else if (item2.length == 2){
			document.getElementById("map-rollover").style.backgroundImage = "url(weezmap/css/rollover2.png)";
		}else{
			document.getElementById("map-rollover").style.backgroundImage = "url(weezmap/css/rollover3.png)";
		}
		
		if (item2.length > 1){
			document.getElementById("map-rollover").innerHTML = '<div id="more-ads">' + (item2.length) + " annonces</div>" + document.getElementById("map-rollover").innerHTML
		}
  	}
  	
  	self.hideRollover = function(item){
    	item2 = [];	
  	  	for (k = 0; k < item.length; k++){

  			if (this.matchFilters(item[k])){
  				item2.push(item[k]);
  			}
  		}
  	
 		$.each(self.markers, function(i, marker){
 			if (marker['id'] == item[0]['id']){
				marker.setImage("weezmap/markers/" + Math.min(item2.length, 6) + ".png");
			}
		});
		document.getElementById("map-rollover-container").style.display = "none";
  	}

  	self.rolloverHtml = function(item2, width){
  			
  			var html = '';
  			
			if (item2['nombre_images'] > 0){
				html += '<img class="thumb" src="weezmap/thumb.php?id=' + item2['CODE_SOCIETE'] + '-' + item2['CODE_SITE'] + '-' + item2['NO_ASP'] + '"/><br/>';
			}else{
				html += '<img class="thumb" src="weezmap/css/no-img.png"/><br/>';

			}

			
			//html += capitalize(item2['CATEGORIE']);
			html += conv_type(item2['TYPE_OFFRE']);
			
			if (item2['NB_PIECES'] != 0){
				html += ' ' + item2['NB_PIECES'] + ' pièces';
			}
			if (item2['SURF_HAB'] != 0){
				html +=  ' de ' + item2['SURF_HAB'] + ' m2';
			}
			html += '<br/>';
			
			if (item2['LOYER'] > 0){
				html += '<strong>' + addSpaces(item2['LOYER']) + " € / mois</strong>";
				html += addSpaces(item2['CHARGES']) + ' € de charges / mois';			
			}else{
				html += '<strong>' + addSpaces(item2['PRIX']) + " €</strong>";
			}


			return html;
  	}

  	
  	self.itemHtml = function(item2, width){
  			
  			sold = false;
  			if ($("#vendus").val() == 'oui'){
  				sold = true;
  			}
  	
  			//$.get("weezhits.php", {ajaxhit: item2['id']});
  	
			html = '<div class="infowindowitem" style="width: ' + width + '">';
			if (item2['statut'] == 'compromis' && sold==false ){
				html += '<img src="weezmap/css/compromis.png" class="exclu"/>';
			}else if (item2['TYPE_MANDAT'] != 'SIMPLE' && sold==false){
				html += '<img src="weezmap/css/exclu.png" class="exclu"/>';
			}
			if (item2['nombre_images'] > 0 && sold==false){
				if (item2['statut'] != 'compromis' && sold==false){
					html += '<a href="fiche.php?id_annonce=' + item2['id'] + '">';
				}
				html += '<img class="thumb" src="weezmap/thumb.php?id=' + item2['CODE_SOCIETE'] + '-' + item2['CODE_SITE'] + '-' + item2['NO_ASP'] + '"/>';
				if (item2['statut'] != 'compromis'){
					html += '</a>';
				}
			}else{
				if (sold==false){
					html += '<img class="thumb" src="weezmap/css/noimage.jpg"/>';
				}else{
					html += '<img class="thumb" src="weezmap/css/picto_vendu.png"/>';
				}

			}
			html += '<div class="description">';

			html += '<a href="fiche_agence.php?societe=' + item2['CODE_SOCIETE'] + '&site=' + item2['CODE_SITE'] + '" >';

			html += '<img src="stock/' + item2['CODE_SOCIETE'] + '.jpg" class="agency"/>';
			html += '</a>';

			if ($('#typeid').val() != 4){
				if (item2['statut'] != 'compromis' && sold == false){
					html += '<a href="fiche.php?id_annonce=' + item2['id'] + '" class="moreinfo"><img src="weezmap/css/plus-detail.png"/></a>';
				}
			}


			
			//html += capitalize(item2['CATEGORIE']);
			if (item2['NB_PIECES'] != 0){
				html += ' ' + item2['NB_PIECES'] + ' pièces';
			}
			if (item2['SURF_HAB'] != 0 && sold==false){
				html +=  ' de ' + item2['SURF_HAB'] + ' m2';
			}
			html += '<br/>';
			
			if (item2['LOYER'] > 0){
				html += '<strong>' + addSpaces(item2['LOYER']) + " € / mois</strong><br/>";
				html += addSpaces(item2['CHARGES']) + ' € de charges / mois';			
			}else{
			
			
				html += '<strong>' + addSpaces(item2['PRIX']) + " €</strong><br/>";
			
				if (item2['SURF_HAB'] != 0 && item2['PRIX'] != 0 && sold==false){
					html += addSpaces(Math.round(item2['PRIX'] / item2['SURF_HAB'])) + " €/m2";
				}
			}
			if (sold){
				html += "Vendu en " + item2['MOIS'] + ' / ' + item2['ANNEE'];
			}
			html += '</div>';
			html += '</div>';

			return html;
  	}
  	
  	self.rememberView = function(){
  		center = self.map.getCenter();
  		document.getElementById("lat").value = center.lat();
  		document.getElementById("lng").value = center.lng();
  		document.getElementById("zoom").value = self.map.getZoom();
  	}
  		
    self.rememberInfowindow = function(items){		
  		point = new GLatLng(items[0]['lat'], items[0]['lng']);
  		document.getElementById("infowindow-lat").value = point.lat();
  		document.getElementById("infowindow-lng").value = point.lng();
  	}
  	
	self.showInfoWindow = function(items){
	
		self.rememberView();
		self.rememberInfowindow(items);


		
		var width = "";
	
		var html = '<div id="infowindowtabs">';
		html += '<div id="infowindowtab1" class="infowindowtabon"><a href="#1">Annonces</a></div>';
		html += '<div id="infowindowtab2" class="infowindowtaboff"><a href="#1">Vue de la rue</a></div>';
		html += '</div>';

		html += '</div>';

		
		var pageIndex = 0;
		var previousGroup = 0;
		var pagesHtml = '<div id="infowindow-list">Chargement en cours';
		
		/*$.each(items, function(j,item){
			if (self.matchFilters(item)){
				if (item.groupe == 0 || previousGroup != item.groupe){
					pageIndex++;
					if (pageIndex == 1){
						pagesHtml += '<div class="infowindowpage" id="page' + pageIndex + '" style="display: block">';
					}else{
						pagesHtml += '</div>';
						pagesHtml += '<div class="infowindowpage" id="page' + pageIndex + '" style="display: none">';
					}
					previousGroup = item.groupe;
				}
				pagesHtml += self.itemHtml(item, width);
			}
		});*/

		var groupsList = '';

		$.each(items, function(j,item){
			if (self.matchFilters(item)){
				if (item.groupe == 0 || previousGroup != item.groupe){
					pageIndex++;
					if (pageIndex == 1){

					}else{
						groupsList += "-";
					}
					previousGroup = item.groupe;
				}else{
					groupsList += ",";
				}
				groupsList += item['id'];
			}
		});
		
		//alert (groupsList);
				
		pagesHtml += '</div>';
		
		if (pageIndex == 1){
			nextClass = "off";
		}else{
			nextClass="on";
		}
		
	
		html += '<div id="infowindowlist">';

		html += '<div id="infowindowpagenav"><a href="#1" id="infowindowprevious" class="off"><img src="weezmap/css/previous.png">&nbsp;&nbsp;Bien précédent </a> <a href="#1" class="' + nextClass + '" id="infowindownext">Bien suivant&nbsp;&nbsp;<img src="weezmap/css/next.png"></a>Annonce(s) bien <span id="pageindex">1</span> / <span id="pagetotal">' + pageIndex + '</span> </div>'; 
		
		html += '<div id="infowindowlistcontent">Chargement en cours</div>';
		
		html += '</div>';
		html += "<div id='streetview' style='display: none'></div>";
		
        var point = new GLatLng(items[0]['lat'], items[0]['lng']);
        self.infoWindowPoint = point;
		self.map.openInfoWindowHtml(point, html, {pixelOffset:new GSize(0, 0)});
 					
		self.initInfoWindow(groupsList);
		
	};

	self.initInfoWindow = function(groupsList){
				

		if ($("#streetview")[0] == null){
		   setTimeout(function(){self.initInfoWindow(groupsList)}, 10);
		   return;
		}
				
				var requestArray = {groupsList: groupsList};
		

		
		$("#infowindowlistcontent").load(
			"weezmap/infowindow.php",
			requestArray,
			function (responseText, textStatus, XMLHttpRequest) {
  				this;
			}
        );
				

				
		panoramaOptions = {"latlng":self.infoWindowPoint};
		myPano = new GStreetviewPanorama($("#streetview")[0], panoramaOptions);
				
		$('#infowindowtab2').click(function() {
				
		    $(this).removeClass('infowindowtaboff');
        	$(this).addClass('infowindowtabon');
            		
        	$("#infowindowtab1").removeClass('infowindowtabon');
        	$("#infowindowtab1").addClass('infowindowtaboff');
            		
			$('#streetview')[0].style.display = "block";
			$('#infowindowlist')[0].style.display = "none";
		});
				
  		$('#infowindowtab1').click(function() {
				
		    $(this).removeClass('infowindowtaboff');
        	$(this).addClass('infowindowtabon');
            		
        	$("#infowindowtab2").removeClass('infowindowtabon');
        	$("#infowindowtab2").addClass('infowindowtaboff');
            		
			$('#streetview')[0].style.display = "none";
			$('#infowindowlist')[0].style.display = "block";
		});
		
		$('#infowindownext').click(function() {
			index = parseInt($('#pageindex').html());
			total = parseInt($('#pagetotal').html());
			newIndex = Math.min(index + 1, total)
			$('#pageindex').html(newIndex);
			
			for (i = 1; i <= total; i++){
				$('#page' + i)[0].style.display='none';
			}
			$('#page' + newIndex)[0].style.display='block';
			
			if (newIndex == total){
				$('#infowindownext')[0].className="off";
			}else{
				$('#infowindownext')[0].className="on";
			}
			if (newIndex == 1){
				$('#infowindowprevious')[0].className="off";
			}else{
				$('#infowindowprevious')[0].className="on";
			}
		});

		$('#infowindowprevious').click(function() {
			index = parseInt($('#pageindex').html());
			newIndex = Math.max(index - 1, 1)
			$('#pageindex').html(newIndex);
			
			for (i = 1; i <= total; i++){
				$('#page' + i)[0].style.display='none';
			}
			$('#page' + newIndex)[0].style.display='block';
			
			if (newIndex == 1){
				$('#infowindowprevious')[0].className="off";
			}else{
				$('#infowindowprevious')[0].className="on";
			}
			if (newIndex == total){
				$('#infowindownext')[0].className="off";
			}else{
				$('#infowindownext')[0].className="on";
			}
		});

	};


  	self.updateCircle = function(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa){

		if (self.pin != null){
			center = self.pin.getLatLng();
		}
		radius = $("#radius").val();
		nodes = 40;

	
  	
  		var bounds = new GLatLngBounds();
  		
		var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
		var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

		//Loop 
		var points = [];
		var step = parseInt(360/nodes)||10;
		for(var i=0; i<=360; i+=step){
			var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
			points.push(pint);
			bounds.extend(pint); //this is for fit function
		}
		points.push(points[0]); // Closes the circle, thanks Martin
		fillColor = fillColor||liColor||"#d50000";
		liColor = "#d50000";
		liWidth = liWidth||1;

		self.updateGroupsDisplay();
		

		self.circle2 = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
		this.map.addOverlay(self.circle2);
		if (self.circle != null){
        	self.map.removeOverlay(self.circle);
        }
        self.circle = self.circle2;
	};
  	
  	self.setPin = function(point){
  	
  	   if (self.pin != null){
       		self.map.removeOverlay(self.pin);
       }	
        			
   		var icon = new GIcon();
		icon.shadow = null;
		icon.dragCrossImage = "";
		icon.dragCrossSize = new GSize(0, 0);
		icon.iconSize = new GSize(30, 30);
		icon.iconAnchor = new GPoint(15, 15);
        icon.image = "weezmap/markers/pin.png";
        icon.maxHeight = 0;
		var markerOptions = { icon: icon, draggable: true};
  		var marker = new GMarker(point, markerOptions);
  		
  		GEvent.addListener(marker, "drag", function() {
			self.updateCircle();
		});
			
		self.pin = marker;
		self.map.addOverlay(self.pin);
  	
  	}
  	
	self.showAddress = function(address) {
		if (self.geocoder) {
			self.geocoder.getLatLng(
      			address + ", 69, france",
     			function(point) {
					if (!point) {
						alert(address + " introuvable");
        			} else {
        				self.setPin(point);
        				self.updateCircle(point, 1, 30);
						self.map.setCenter(point, 15);
						self.searchLocation = point;
        			}
      			}
    		);
  		}
	};
	
	self.init();

	}

