var map = null;
var geoXml = null; 
var geocoder = null;
var marker_nuovo = null;
var	img_dir="http://www.domino.bo.it/img/map/";
var casa_on='';

var baseIcon = new GIcon();
baseIcon.shadow = "http://www.domino.bo.it/img/map/casa_ombra.png";
baseIcon.iconSize = new GSize(35, 35);
baseIcon.shadowSize = new GSize(52, 35);
baseIcon.iconAnchor = new GPoint(17, 35);
baseIcon.infoWindowAnchor = new GPoint(17, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

function initialize() {
	if (GBrowserIsCompatible()) {
//		geoXml = new GGeoXml("http://www.domino.bo.it/case.kml");

		map = new GMap2(document.getElementById("map_canvas"));
		
		map.addControl(new GLargeMapControl());
        map.addControl(new GHierarchicalMapTypeControl());

//		map.enableScrollWheelZoom();

		var center = new GLatLng(44.494638, 11.342354);
		map.setCenter(center, 13);
		
		map.setMapType(G_HYBRID_MAP);
//		map.addMapType(G_SATELLITE_3D_MAP);
	
		geocoder = new GClientGeocoder();
		
		GDownloadUrl("./annunci.php", GDownloadUrlCallback);
	}
	
	$("input[name='IDannunci_tipo']").click(function(){
		switch($(this).attr('value')){
			case '1':
				tipo_annuncio='Immobile di proprieta\'';
				file='casa_verde_triangolo.png';
			break;

			case '2':
				tipo_annuncio='Immobile abbandonato';
				file='casa_rossa_triangolo.png';
			break;

			default:
				tipo_annuncio='Immobile abbandonato';
				file='casa_rossa_triangolo.png';
			break;
		}
		
		if(casa_on==''){
			addMArker(undefined,'',tipo_annuncio,marker_nuovo);

			lat = marker_nuovo.getPoint().lat();
			lng = marker_nuovo.getPoint().lng(); 
			
			$('#annunci #lat').get(0).value=lat;
			$('#annunci #lng').get(0).value=lng;

			GEvent.addListener(marker_nuovo, "dragstart", function() {
				map.closeInfoWindow();
			});
			
			GEvent.addListener(marker_nuovo, "dragend", function() {
				lat = marker_nuovo.getPoint().lat();
				lng = marker_nuovo.getPoint().lng(); 
				
				$('#annunci #lat').get(0).value=lat;
				$('#annunci #lng').get(0).value=lng;
			});
		}else if(casa_on!=tipo_annuncio){
			marker_nuovo.setImage(img_dir+file);
		}
		
		casa_on=tipo_annuncio;
	});
}

function GDownloadUrlCallback(data) {
	var xml = GXml.parse(data);
	
	var Placemark = xml.getElementsByTagName("Placemark");
	for (var i = 0; i < Placemark.length; i++) {
		name=Placemark[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
		description=Placemark[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;

		Point=Placemark[i].getElementsByTagName("Point");
		coordinates=Point[0].getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;

		ExtendedData=Placemark[i].getElementsByTagName("ExtendedData");
		Data=ExtendedData[0].getElementsByTagName("Data");
		ico_value=Data[0].getElementsByTagName("value")[0].childNodes[0].nodeValue;
		
		lat_lng=coordinates.split(',');
		
		text='';
		text+='<div class="infoWindow">';
		text+='<strong>'+name+'</strong>';
		text+='<br />';
		text+=description;
		text+='</div>';

		var latlng = new GLatLng(parseFloat(lat_lng[1]),parseFloat(lat_lng[0]));
		addMArker(latlng,text,ico_value);
	}
}
		
function addMArker(latlng,text,tipo_icona,marker_alt){
	if(typeof latlng=='undefined')
		latlng=map.getCenter();
	
	switch(tipo_icona){
		case 'Immobile di proprieta\'':
			file='casa_verde.png';
		break;

		case 'Immobile abbandonato':
			file='casa_rossa.png';
		break;

		default:
			file='casa_rossa.png';
		break;
	}
	
	if(typeof marker_alt!='undefined')
		file=file.replace('.png','_triangolo.png');
	
	var casaIcon = new GIcon(baseIcon);
	casaIcon.image = img_dir+file;
	
	// Set up our GMarkerOptions object
	markerOptions={
		draggable: true,
		icon: casaIcon
	};
	
	var marker = new GMarker(latlng, markerOptions);

	if(typeof marker_alt!='undefined')
		marker_nuovo = marker;
	else
		marker.disableDragging();

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(text);
	});

	map.addOverlay(marker);
}

function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " non trovato");
				} else {
					map.setCenter(point, 16);
					if(marker_nuovo!=null)
						marker_nuovo.setPoint(point);
				}
			}
		);
	}
}

$(document).ready(function(){
	initialize();
/*
	$('#annunci').ajaxForm({
		dataType:  'json',
		target: '#editBlock .bloccoForm', 
		success: ajaxFormCallback
	});
*/
	// validate signup form on keyup and submit
	var validator = $("#annunci").validate({
		rules: {
			IDannunci_tipo: "required",
			indirizzo: "required",
		},
		messages: {
			IDannunci_tipo: "Devi scegliere un tipo di immobile",
			indirizzo: "Devi inserie un indirizzo",
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().parent().parent() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.next() );
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				dataType:  'json',
				target: '#editBlock .bloccoForm', 
				success: ajaxFormCallback
			});
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}
	});

	function ajaxFormCallback(data, statusText){
		html='';
		
		data.descrizione
		switch(data.IDannunci_tipo){
			case '1':
				file='casa_verde.png';
			break;
	
			case '2':
			default:
				file='casa_rossa.png';
			break;
		}
		
		html+='                    <div class="nota">';
		html+='                        <img src="img/map/'+file+'" width="35" height="35" align="left" />';
		html+='                        <p class="inEvidenza">'+data.indirizzo+'</p>';
		html+='                        <p>'+data.descrizione+'</p>';
		html+='                        <br clear="all" />';
		html+='                    </div>';
		html+='                    <p>&nbsp;</p>';
		
		$('#giaInseriti').append(html);
		
		alert('L\'immobile da te indicato è stato registrato, grazie per la segnalazione!')
	}
});

