var shops = [];

function addShop(id, nom, latlong, adresse, telephone, texte)
{
	var i = latlong.indexOf(', ');
	var lat = latlong.substring(0, i);
	var long = latlong.substring(i +2,latlong.length);
	
	latlong  = (latlong != '') ? new google.maps.LatLng(lat, long) : '';
	
	var s = {};
	s.id = id;
	s.nom = nom;
	s.latlong = latlong;
	s.adresse = adresse;
	s.telephone = telephone;
	s.texte = texte;
	
	shops.push(s);
	
}

var markers=  [];

function zoomAdresse()
{
	var from = EL('cli_adresse').value;
	
	if( from == '' )
	{
		alert("Veuillez saisir votre adresse pour visualiser les commerces près de chez vous");
		return false;
	}
	
	getLatitudeLongitude(from + " lyon", function (p) {map.setCenter(p, 16); });
	
}

function showShops(nofit)
{
	for(var i = 0; i < shops.length; i++)
	{
		var shop = shops[i];
		
		if( shop.latlong != '' )
		{
			var marker = new google.maps.Marker({'position' : shop.latlong, map: map});
			markers[shop.id] = marker;
			marker.stban = {};
			marker.shop = shop;
			
			bounds.extend(shop.latlong);
		
			eval('google.maps.event.addListener (marker, "click", function() { openInfo ('+shop.id+'); });');
		}
		
		/*
		if(debug && shop.latlong == '')
		{
			eval('getLatitudeLongitude(shop.adresse + " lyon", function (p) {coord(p, ' + shop.id + ', ' + debug + ');});');
		}
		*/
		
	}	
	if( nofit == null )
	{
		map.fitBounds(bounds);	
	}
}

function openInfo(id)
{
	var marker = markers[id];
	
	var s = "<b>"+marker.shop.nom+"</b>";
	s += "<br />" + marker.shop.adresse;
	if( marker.shop.telephone != '' )
	{
		s += "<br />Tél. " + marker.shop.telephone;
	}
	if( marker.shop.texte != '' )
	{
		s += "<br /><br />" + marker.shop.texte;
	}
	
	//marker.openInfoWindowHtml (s);
	
	 var infowindow = new google.maps.InfoWindow({
        content: s
    });
    
    infowindow.open(map,marker);
}

function getLatitudeLongitude(adresse, func)
{
 	geoCoder.getLatLng(adresse, func);
}

var ko = '';

function coord(point, id, debug)
{
	if( point == null )
	{
		var marker = markers[id];
		if( marker == null )
		{
			return;
		}
		
		ko += "\r\n" + marker.shop.id;
		ko += "\r\n" + marker.shop.nom;
		ko += "\r\n" + marker.shop.adresse;
		ko += "\r\n";
		return;
	}
	
	var s = "UPDATE annuaire SET latlong = '" + point.lat() + ", " + point.lng() + "'";
	s += " WHERE annuaireid = " + id + ";";
	liste += "\r\n";
	liste += s;
}

function debugLatitudeLongitune()
{
	var t = document.createElement('textarea');
	t.style.width = '600px';
	t.style.height = '100px';
	t.value = liste;
	EL('debug').appendChild(t);		
}

var liste = '';


