var map;
var marker = new Array();
var punto = 0;

function load(mapa){
	if (GBrowserIsCompatible()){
		map = new GMap2(document.getElementById("map"));
		//map.setMapType(G_HYBRID_MAP);
		if(mapa == 'principal'){
			//$("#map").parent().css('background-color', '#CCCCCC');
			$("#mapa").corner("15px sc:#005DBA");
			$("#mapa").css('background-color', '#005DBA');
			map.addControl(new GMapTypeControl());
			map.addControl(new GLargeMapControl());
			busca_hostip();
			map.setCenter(new GLatLng(lat_pre,long_pre), zoom);
			busca_puntos_mapa();
		}
		else if(mapa == 'usuaris'){
			$("#mapa").corner("15px sc:#005DBA");
			$("#mapa").css('background-color', '#005DBA');
			map.addControl(new GSmallMapControl());
			GEvent.addListener(map, "click", clickAction);
			map.setCenter(new GLatLng(lat_pre,long_pre), zoom);
			if(readinputValue('coordenades')!=''){
				var coord = readinputValue('coordenades').split(",");
				lat_pre = coord[0].substr(1,coord[0].length);
				long_pre = coord[1].substr(0,coord[1].length -2);
				var p = new GLatLng(lat_pre,long_pre);
				map.setCenter(p, zoom);
				escribe_coord_marker(p)
			}
		}
		else if(mapa == 'mapa_oferta'){
			$("#mapa").corner("15px sc:#005DBA");
			$("#mapa").css('background-color', '#005DBA');
			map.addControl(new GSmallMapControl());
			map.setCenter(new GLatLng(lat_pre,long_pre), zoom);
			if(readinputValue('coordenades')!=''){
				var coord = readinputValue('coordenades').split(",");
				lat_pre = coord[0].substr(1,coord[0].length);
				long_pre = coord[1].substr(0,coord[1].length -2);
				var p = new GLatLng(lat_pre,long_pre);
				map.setCenter(p, zoom);
				escribe_coord_marker_oferta(p)
			}
		}
	}
}
function carga_mapa(){
	load('principal');
}
function mapa_peque(){
	load('usuaris');
}
function mapa_oferta(){
	load('mapa_oferta');
}
function busca_hostip(){
	var pagina = "busca_puntos.php?hostip=1";
	var coordenadas = 'not_found';
	var http = AJAXCrearObjeto();
	http.open("GET",pagina,true);
	http.onreadystatechange = function(){
		if(http.readyState == 1){
		}
		if((http.readyState == 4)&&(http.status == 200)){
			var doc = doc_parser(http);
			if(doc.getElementsByTagName('COORDENADAS').length){
				coordenadas = doc.getElementsByTagName('COORDENADAS')[0].firstChild.data;
			}
			if(coordenadas != 'not_found'){
				var coord = coordenadas.split(",");
				lat_pre = coord[1];
				long_pre = coord[0];
			}
		}
	}
	http.send('');
}

function dragAction(){
	var coord = marker.getPoint();
	coord = coord.toString();
	writeinputValue('coordenades',coord);
}

//funcion que se llama cuando se clica en el mapa para crear o eliminar markers
function clickAction(overlay, point){
	if(overlay){
		punto=0;
		map.removeOverlay(overlay);
		writeinputValue('coordenades','');
	}
	else if(point){
		escribe_coord_marker(point);
	}
}

function createmarkers(http){
	map.clearOverlays();
	var doc = doc_parser(http);
	var cicles_marker_icon;
	var coord;
	var coord_marker = new Array();
	var coord_lat;
	var coord_lng;

	var anuncis_id = new Array();
	var anuncis_timestamp = new Array();
	var anuncis_descripcio = new Array();
	var anuncis_id_usuari = new Array();
	var anuncis_data_inici = new Array();
	var usuari_nom = new Array();
	var usuari_coordenades = new Array();
	var cicles_marker = new Array();
	
	if(doc.getElementsByTagName('punto').length>0){
		for(var i=0;i<doc.getElementsByTagName('punto').length;i++){
			anuncis_id[i] = doc.getElementsByTagName('anuncis_id')[i].firstChild.data;
			anuncis_timestamp[i] = doc.getElementsByTagName('anuncis_timestamp')[i].firstChild.data;
			anuncis_descripcio[i] = doc.getElementsByTagName('anuncis_descripcio')[i].firstChild.data;
			anuncis_id_usuari[i] = doc.getElementsByTagName('anuncis_id_usuari')[i].firstChild.data;
			anuncis_data_inici[i] = doc.getElementsByTagName('usuari_data_inici')[i].firstChild.data;
			usuari_nom[i] = doc.getElementsByTagName('usuari_nom')[i].firstChild.data;
			usuari_coordenades[i] = doc.getElementsByTagName('usuari_coordenades')[i].firstChild.data;
			cicles_marker[i] = doc.getElementsByTagName('cicles_marker')[i].firstChild.data;
		}
/*
Filtro los datos para poder poner más de un anuncio en un punto del mapa
*/
		var x = 0;
		var n;
		var anuncis_id_usuari_filtrado = new Array();
		var anuncis_descripcio_filtrado = new Array();
		var usuari_coordenades_filtrado = new Array();
		var cicles_marker_filtrado = new Array();
		
		for(var i=0;i<anuncis_id.length;i++){
			x = 0;
			for(var j=0;(j < anuncis_id_usuari_filtrado.length) && (x == 0);j++){
				if(anuncis_id_usuari_filtrado[j] == anuncis_id_usuari[i]){
					x = 1;
				}
			}
			var img = '<img id="foto" src="imatges/icons/'+ cicles_marker[i] +'" alt="'+ cicles_marker[i] +'" />';
			if(x == 0){
				n = anuncis_id_usuari_filtrado.length;
				cicles_marker_filtrado[n] = cicles_marker[i];
				usuari_coordenades_filtrado[n] = usuari_coordenades[i];
				anuncis_id_usuari_filtrado[n] = anuncis_id_usuari[i];
				
				anuncis_descripcio_filtrado[n] = '<br /><table align="center" width="100%" cellpadding="0" cellspacing="0">';
				anuncis_descripcio_filtrado[n] += '<tr>';
				anuncis_descripcio_filtrado[n] += '<td class="td_titol_l"></td>';
				anuncis_descripcio_filtrado[n] += '<td class="td_titol_c">'+ usuari_nom[i] +'</td>';
				anuncis_descripcio_filtrado[n] += '<td class="td_titol_r"></td>';
				anuncis_descripcio_filtrado[n] += '</tr>';
				anuncis_descripcio_filtrado[n] += '</table>';
				anuncis_descripcio_filtrado[n] += '<table align="center" cellpadding="0" cellspacing="0" width="100%" border="0" class="resultat_consulta">';
				anuncis_descripcio_filtrado[n] += '<tr>';
				anuncis_descripcio_filtrado[n] += '<td><a href="index.php?seccio=user&opcio=of&item='+ anuncis_id[i] + '">' + img +'</a></td>';
				anuncis_descripcio_filtrado[n] += '<td>'+ anuncis_data_inici[i] +'</td>';
				anuncis_descripcio_filtrado[n] += '<td>'+ anuncis_descripcio[i] +'</td>';
				anuncis_descripcio_filtrado[n] += '</tr>';
			}
			else{
				n = j-1;
				anuncis_descripcio_filtrado[n] += '<tr>';
				anuncis_descripcio_filtrado[n] += '<td><a href="index.php?seccio=user&opcio=of&item='+ anuncis_id[i] + '">' + img +'</a></td>';
				anuncis_descripcio_filtrado[n] += '<td>'+ anuncis_data_inici[i] +'</td>';
				anuncis_descripcio_filtrado[n] += '<td>'+ anuncis_descripcio[i] +'</td>';
				anuncis_descripcio_filtrado[n] += '</tr>';
			}
		}
		anuncis_descripcio_filtrado[n] += '</table>';

		for(var i=0;i<anuncis_descripcio_filtrado.length;i++){
			cicles_marker_icon = new GIcon();
			cicles_marker_icon.image = "imatges/icons/"+cicles_marker_filtrado[i];
			//cicles_marker_icon.iconSize = new GSize(20, 20);
			cicles_marker_icon.iconAnchor = new GPoint(6, 20);
			cicles_marker_icon.infoWindowAnchor = new GPoint(5, 1);
			//cicles_marker_icon.shadow = "imatges/icons/"+cicles_marker[i];
			//cicles_marker_icon.shadowSize = new GSize(22, 20);
			
			coord = usuari_coordenades_filtrado[i].split(',');
			coord_lat = coord[0].substr(1,coord[0].length);
			coord_lng = coord[1].substr(0,coord[1].length -2);
			coord_marker[i] = new GLatLng(coord_lat,coord_lng);
			customizemarker(coord_marker[i], cicles_marker_icon, anuncis_descripcio_filtrado[i], i);
			map.addOverlay(marker[i]);
		}
	}
}

function customizemarker(coord,icono,html,index){
	marker[index] = new GMarker(coord,icono);
	var opts = { maxWidth : 300 };
	GEvent.addListener(marker[index], "click", function(){
		marker[index].openInfoWindowHtml(html,opts);
	});
}

function buscar_centro_mapa(){
	var ruta = readinputValue('direccio')+","+readinputValue('codi_postal')+","+readselectText('id_poblacio')+","+readselectText('id_provincia');
	showAddress(ruta);
}

function showAddress(address){
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(address,
		function(point) {
			if (!point) {
				//alert(address + " not found");
			}
			else{
				punto=0;
				map.clearOverlays();
				map.setCenter(point, zoom);
				escribe_coord_marker(point);
			}
		}
	);
}

function escribe_coord_marker_oferta(point){
	if(!punto){
		marker=new GMarker(point,{draggable: false});
		punto=1;
		map.addOverlay(marker);
	}
}
function escribe_coord_marker(point){
	if(!punto){
		marker=new GMarker(point,{draggable: true});
		writeinputValue('coordenades','('+point.y+','+point.x+')');
		punto=1;
		GEvent.addListener(marker, "dragend", dragAction );
		map.addOverlay(marker);
	}
	else{
		alert(string['google_nomes_un_punt']);
	}
}
