//*************************
//creation d'un marker avec bulle et ajout de fonction suite action
//*************************

function createMarkerB(point, number, message, map, pid) 
{
	var myHtml = "";
	//*****************************
	var iconred = new GIcon(G_DEFAULT_ICON);
	iconred.image = icoMarkerOn;
	iconred.iconSize = new GSize(32, 32);	
	
	gmarkersON[number] = new GMarker(point, iconred);	
	map.addOverlay(gmarkersON[number]);
	gmarkersON[number].hide();	
	GEvent.addListener
	(
		gmarkersON[number], 
		"click",
		function() 
		{
			myHtml 		= message;
			gmarkersON[number].openInfoWindowHtml(myHtml,{maxWidth:575});		
	  		showEditFromMap(pid, number);
			//dsp_markerON(gmarkers, gmarkersON, number);
		}
	);
	//*****************************
	
	
	var icon = new GIcon(G_DEFAULT_ICON);
	icon.image = icoMarker;
	icon.iconSize = new GSize(32, 32);

	gmarkers[number] = new GMarker(point, icon);
	gmarkers[number].value = number;
	GEvent.addListener
	(
		gmarkers[number], 
		"click",
		function() 
		{
			myHtml 		= message;
			gmarkers[number].openInfoWindowHtml(myHtml,{maxWidth:GinfoWindowWidth});
	  		showEditFromMap(pid, number);
			dsp_markerON(gmarkers, gmarkersON, number);
		}
	);
	map.addOverlay(gmarkers[number]);
}


//*************************
// reverse geocoding
//*************************
function addAddressToMap(response) 
{
  //map.clearOverlays();
  if (!response || response.Status.code != 200) 
  {
	var address = "User address"
    //alert("\"" + address + "\" not found");
  }
  else 
  {
    place = response.Placemark[0];
    initLon = place.Point.coordinates[0];
    initLat = place.Point.coordinates[1];
    if(initLat && initLon)
		map.setCenter(new GLatLng(initLat, initLon), zoom);
  	point = new GLatLng(initLat, initLon);
    var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";                    
    markerOptions = { icon:blueIcon };
    marker = new GMarker(point, markerOptions);
    map.addOverlay(marker);
    GEvent.addListener
	(
		marker, 
		"click",
		function() 
		{
			var txt = "User Home: <br />" + place.address + '<br />' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode;
			marker.openInfoWindowHtml(txt,{maxWidth:GinfoWindowWidth});
			//map.removeOverlay(marker);
			var center = map.getCenter();
		}
	);    
  }
}

//*************************
// getLAlong from address
//*************************
 function locateAddress(address, number, message, pid) 
 {      
      var geocoder = new GClientGeocoder();
      if (geocoder) 
	  {
        geocoder.getLatLng(
          address,
          function(point) 
		  {
            if (!point) {
              ;//alert(address + " not found");
            } else {              
              	/*****************************/
				var iconred = new GIcon(G_DEFAULT_ICON);
				iconred.iconSize = new GSize(32, 32);
				iconred.image = icoMarkerOn;
				gmarkersON[number] = new GMarker(point, iconred);	
				map.addOverlay(gmarkersON[number]);
				gmarkersON[number].hide();
				GEvent.addListener
				(
					gmarkersON[number], 
					"click",
					function() 
					{
						myHtml 		= message;
						gmarkersON[number].openInfoWindowHtml(myHtml,{maxWidth:GinfoWindowWidth});		
				  		showContactFromMap(pid, number);
						//dsp_markerON(gmarkers, gmarkersON, number);
					}
				);
				/*****************************/
				
				
				var icon = new GIcon(G_DEFAULT_ICON);
				icon.iconSize = new GSize(32, 32);
				icon.image = icoMarker;
				var myHtml = "";
				gmarkers[number] = new GMarker(point, icon);
				gmarkers[number].value = number;
				GEvent.addListener
				(
					gmarkers[number], 
					"click",
					function() 
					{
						myHtml 		= message;
						gmarkers[number].openInfoWindowHtml(myHtml,{maxWidth:GinfoWindowWidth});	
				  		showContactFromMap(pid, number);
						dsp_markerON(gmarkers, gmarkersON, number);
					}
				);
				map.addOverlay(gmarkers[number]);
				if(gmarkers.length && number == 0)
				{
					map.panTo(gmarkers[0].getLatLng());dsp_markerON(gmarkers, gmarkersON, 0);	
				}
            }
          }
        );
      }
   }


function showLocation(address) {
      geocoder.getLocations(address, addAddressToMap);
}

function showLocation2(address, msg, nb) {
	var  txt = msg;
	var number = nb;
      geocoder.getLocations(address, function(response)
		  {
			if (!response || response.Status.code != 200) {;}
			else 
			{
				place = response.Placemark[0];
				initLon = place.Point.coordinates[0];
				initLat = place.Point.coordinates[1];
				if(initLat && initLon)
					map.setCenter(new GLatLng(initLat, initLon), zoom);
				point = new GLatLng(initLat, initLon);
				var iconred = new GIcon(G_DEFAULT_ICON);
				iconred.iconSize = new GSize(32, 32);
				iconred.image = icoMarkerOn;
				markerOptions = { icon:iconred };
				gmarkersON[number] = new GMarker(point, markerOptions);
				map.addOverlay(gmarkersON[number]);
				gmarkersON[number].openInfoWindowHtml(txt,{maxWidth:GinfoWindowWidth});						
				map.getCenter();
				
			}
		  }
	  );
}
//*************************
// fin reverse geocoding
//*************************



function init() 
{
	if (GBrowserIsCompatible()) 
	{
		/*var map = new GMap2(document.getElementById("map_canvas"));	
		map.setCenter(new GLatLng(48.8599, 2.3454), 13);			
		map.removeMapType(G_HYBRID_MAP);
		var mapControl = new GMapTypeControl();
		map.addControl(mapControl);
		map.addControl(new GLargeMapControl());


	/*
		var str="";
		// Add 10 red markers to the map at random locations 
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var lngSpan = northEast.lng() - southWest.lng();
		var latSpan = northEast.lat() - southWest.lat();
		for (var i = 0; i < 10; i++) 
		{
			newlat = southWest.lat() + latSpan * Math.random();
			newlong = southWest.lng() + lngSpan * Math.random();
			//str += "<br />lat "+newlat+" long "+newlong;
			var point = new GLatLng(			
				newlat,
				newlong
			);
			//map.addOverlay(new GMarker(point));
			map.addOverlay(createMarker(point, i + 1, map));		
			
		}
		/*
		var bounds =map.getBounds(); // bordure
		var zoom = map.getZoom();
		alert(bounds);
		alert(zoom);
		*/
		//map.disableDragging(); // click and drag
		//map.openInfoWindow(map.getCenter(), document.createTextNode("Hello, world")); //affiche bulle
		
		
		//EVENT
		
		//sur un click
		
		
		//sur click recupere les XY
		/*
		GEvent.addListener
		(
			map,"click", 
			function(overlay,point) 
			{     
				var myHtml = "The GPoint value is: " + map.fromLatLngToDivPixel(point) + " at zoom level " + map.getZoom();
				map.openInfoWindow(point, myHtml);
			}
		);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		*/
		
		/*
		GEvent.addListener
		(
			map, "click", 
			function() 
			{
				alert("You clicked the map.");
			}
		);
		*/
		
		
		
		//a la fin d'nu drag n drop recupere le XY
		/*
		GEvent.addListener
		(
			map, "moveend", 
			function() 
			{
				var center = map.getCenter();
		  		document.getElementById("message").innerHTML = center.toString()+"<hr />";
			}
		);		
		map.setCenter(new GLatLng(48.8599, 2.3454), 13);
		*/
	}
}
/*********************************************************************
*
*	Ici se trouve le contenu de MyActionGoogle.js
*
*********************************************************************/
//==============================================================================
// display box infos above a marker
//==============================================================================
function myclick(i, txt)
{
	txt = (!txt)? "No information":txt;
	if(gmarkers[i])
	{
		gmarkers[i].openInfoWindowHtml(txt,{maxWidth:GinfoWindowWidth});	
		//map.panTo(gmarkers[i].getLatLng());		
	}
	dsp_markerON(gmarkers, gmarkersON, i);
}

function dsp_markerON(markersOFF, markersON, id)
{
	for(var i =0; i<markersON.length; i++)
	{
		if(markersOFF[i] && markersON[i])
		{
			markersOFF[i].show();
			markersON[i].hide();
		}
	}
	if(markersOFF[id] && markersON[id])
	{
		markersOFF[id].hide();
		markersON[id].show();
	}
}


function addExport(dom, pid)
{
	document.getElementById(dom).innerHTML = '<a href="#"  onclick="window.open(\'xml_intermed.php?do=exp&contactId='+pid+'\');"><img src="'+imgpath+'btn_export.gif" border="0" alt="Export"></a>';
}


//==============================================================================
// display infos on map and form
//==============================================================================
function showContactFromList(pid, idMarker)
{
	changeBgColor('theList', idMarker);
	typeAction		= "showContactFromList";
	markerID		= idMarker;
	document.getElementById('form_contact').contactId.value = pid;	
	makeRequest(xmlFileGetInfoContact, "itemId="+pid);
	showDom("form");
	addExport('export', pid);
}
function showContactFromMap(pid, idMarker)
{
	changeBgColor('theList', idMarker);
	typeAction		= "showContactFromMap";
	markerID		= idMarker;
	document.getElementById('form_contact').contactId.value = pid;	
	makeRequest(xmlFileGetInfoContact, "itemId="+pid);	
	showDom("form");
	addExport('export', pid);
}


function showEditFromList(pid, idMarker)
{
	changeBgColor('theList', idMarker);
	typeAction		= "showEditFromList";
	markerID		= idMarker;
	document.getElementById('form_edit').realid.value = pid;	
	makeRequest(xmlFileGetInfo, "id="+pid);
	showDom("form");
}
function showEditFromMap(pid, idMarker)
{
	changeBgColor('theList', idMarker);
	typeAction		= "showEditFromMap";
	markerID		= idMarker;
	document.getElementById('form_edit').realid.value = pid;	
	makeRequest(xmlFileGetInfo, "id="+pid);	
	showDom("form");
}

//==============================================================================
// get info from a place/geotags/marker
//==============================================================================
function getInfoFrom(xmlobject)
{
	var idMarker = markerID;
	// get the XML root item
	var root = xmlobject.getElementsByTagName('infos').item(0);
	try
	{
		var items;
		try {items = root.getElementsByTagName("place");}
		catch(e){items= new Array("");}
		var dsp_str = "";
		for (var i = 0 ; i < items.length ; i++) 
		{
			// get one item after another
			var item 		= items[i];
			
			var id			= tryGetElement("realid", item);
			var ele			= tryGetElement("ele", item);		
			var author		= tryGetElement("author", item);	
			var title		= tryGetElement("title", item);			
			var comment		= tryGetElement("comment", item);			
			var rating		= tryGetElement("rating", item);
			var address		= tryGetElement("address", item);
			var zipcode		= tryGetElement("zipcode", item);
			var city		= tryGetElement("city", item);
			var state		= tryGetElement("state", item);
			var country		= tryGetElement("country", item);			
			var picture		= tryGetElement("picture", item);
			var sound		= tryGetElement("sound", item);

			var keywords	= tryGetElement("keywords", item);
			var category	= tryGetElement("category", item);					
			var latitude	= tryGetElement("latitude", item);
			var longitude	= tryGetElement("longitude", item);					
			var attribute	= tryGetElement("attributes", item);
			var date		= tryGetElement("date", item);	
			
			var radioId 	= testerRadio(document.getElementById('form_edit').attribute, attribute);
			var selectId 	= testerRadio(document.getElementById('form_edit').category, category);			

			var dsp_pictBig 	= (picture)?displayHtmlImage(picturePath+dirname(picture)+"th150_"+basename(picture,''), 100):"";
			var dsp_pictSmall 	= (picture)?displayHtmlImage(picturePath+dirname(picture)+"th150_"+basename(picture,''), 70):"";
			var dsp_sound		= (sound)?displayHtmlSound(soundPath+sound, sound):"";
			var marker_content = "Date : "+date+"<br />";
			marker_content += (title)?"Title: "+htmlentities(title)+"<br />Comment: "+htmlentities(comment)+"<br />"+dsp_pictSmall+"<br />":"No information";
			
			if(typeAction == "showEditFromList")
				myclick(idMarker, marker_content);
			
			//
			// INSERT INTO THE FORM 
			//
			document.getElementById('edit_date').innerHTML					= date;
			
			document.getElementById('author').innerHTML						= author;
			document.getElementById("coordonnee").innerHTML 				= "Lat: " + latitude + "<br />Long: " + longitude;

			document.getElementById('edit_picture').innerHTML				= dsp_pictBig;
			document.getElementById('edit_sound').innerHTML					= dsp_sound;
			if(dsp_sound) displayFlashReader(soundPath+sound, "edit_sound");
			
			var str_rating = (rating)? toFixed(rating, 2) + "/10" : "";
			document.getElementById('edit_rating').innerHTML				= str_rating;
			dspRate(rating);
			
			document.getElementById('form_edit').title.value				= title;
			document.getElementById('form_edit').element.value				= ele;			
			
			document.getElementById('form_edit').address.value				= address;
			document.getElementById('form_edit').zipcode.value				= zipcode;
			document.getElementById('form_edit').city.value					= city;
			document.getElementById('form_edit').state.value				= state;
			document.getElementById('form_edit').country.value				= country;			
			
			document.getElementById('form_edit').keywords.value				= keywords;
			document.getElementById('form_edit').category.value				= category;
			document.getElementById('form_edit').comment.value				= comment;
			
			try{document.getElementById('form_edit').attribute[radioId].checked = true;	} catch(e){;}
			if(selectId)
				document.getElementById('form_edit').category[selectId].selected = "selected";
			else
				testerSelect(document.getElementById('form_edit').category, '');
		}
	}
	catch(e)
	{
		if(typeAction == "showEditFromList")
			myclick(idMarker, "");
			//alert(e.message);
	}
}

//==============================================================================
// get info from a contact
//==============================================================================
function handleContactFrom(xmlobject)
{
	var idMarker = markerID;
	// get the XML root item
	var root = xmlobject.getElementsByTagName('infos').item(0);
	try
	{
		var items;
		try {items = root.getElementsByTagName("contact");}
		catch(e){items= new Array("");}
		var dsp_str = "";
		for (var i = 0 ; i < items.length ; i++) 
		{
			// get one item after another
			var item 			= items[i];
			var id				= tryGetElement("id", item);
			var name			= tryGetElement("name", item);
			var organization	= tryGetElement("organization", item);	
			var title			= tryGetElement("title", item);	
			var email			= tryGetElement("email", item);	
			var url				= tryGetElement("url", item);	
			
			var phone1			= tryGetElement("phone1", item);	
			var phone2			= tryGetElement("phone2", item);	
			var phone3			= tryGetElement("phone3", item);	
			var sip				= tryGetElement("sip", item);	
			var fax				= tryGetElement("fax", item);
			
			var address		= tryGetElement("address", item);
			var zipcode		= tryGetElement("zipcode", item);
			var city		= tryGetElement("city", item);
			var state		= tryGetElement("state", item);
			var country		= tryGetElement("country", item);			
			
			var date		= tryGetElement("date", item);	
			
			//document.getElementById('edit_date').innerHTML					= date;
			document.getElementById('form_contact').title.value					= title;
			document.getElementById('form_contact').name.value					= name;	
			document.getElementById('form_contact').organization.value			= organization;
			document.getElementById('form_contact').email.value					= email;
			document.getElementById('form_contact').url.value					= url;
			
			document.getElementById('form_contact').phone1.value				= phone1;
			document.getElementById('form_contact').phone2.value				= phone2;
			document.getElementById('form_contact').phone3.value				= phone3;
			document.getElementById('form_contact').sip.value					= sip;
			document.getElementById('form_contact').fax.value					= fax;
			
			document.getElementById('form_contact').address.value				= address;
			document.getElementById('form_contact').zipcode.value				= zipcode;
			document.getElementById('form_contact').city.value					= city;
			document.getElementById('form_contact').state.value					= state;
			document.getElementById('form_contact').country.value				= country;
			document.getElementById('form_contact').contactEdit.value			= 'update';			
			var dsp_addr = address+" "+zipcode+" "+city+" "+state+" "+country;
			
			var marker_content = "";//"Date : "+date+"<br />";
			marker_content += (name)?"Name :"+htmlentities(name)+"<br />Title: "+htmlentities(title)+"<br />Organization: "+htmlentities(organization)+"<br/>Address: "+htmlentities(dsp_addr):"No information";
			
			if(typeAction == "showContactFromList")
				myclick(idMarker, marker_content);
		}
	}
	catch(e)
	{
		if(typeAction == "showContactFromList")
			myclick(idMarker, "");
			//alert(e.message);
	}
}

//==============================================================================
// return the checked radio number
//==============================================================================
function testerRadio(radio, val)
{
	if(val != "")
		for (var j=0; j<radio.length;j++) 
		{
			if ( radio[j].value == val) 
			{
				return j;
			}
		}
	else
		for (var j=0; j<radio.length;j++) 
		{
			radio[j].checked = false;
		}
}

//==============================================================================
// return the selected field number
//==============================================================================
function testerSelect(select, val)
{
	if(val != "")
		for (var j=0; j<select.length;j++) 
		{
			if ( select[j].value == val) 
			{
				return j;
			}
		}
	else	
		select[0].selected = 'selected';
		
}

//==============================================================================
// return the value from a DOM element
//==============================================================================
function tryGetElement(name, item)
{	
	try 
	{
		if(item.getElementsByTagName(name))
			return item.getElementsByTagName(name)[0].firstChild.nodeValue;
		else
			return "";
	}
	catch(err){return "";}
}

//==============================================================================
// change a background color in the list
//==============================================================================
function changeBgColor(dom, gid)
{
	var element 	= document.getElementById(dom);
	var childs		= element.getElementsByTagName("TR");
	for(var i=0; i<childs.length; i++)
	{		
		var rowid 	= childs[i].getAttribute("id");
		var id		= 0;
		if(rowid)
		{
			id = rowid.match(/^row(\d+)$/);
			if( id[1] == gid )
			{
				document.getElementById(rowid).className = "selectedGeotags";
			}
			else
			{
				document.getElementById(rowid).className = "";
			}
		}
	}
}

