var markers = [];
var arrInfoWindows = [];
var arrListeners = [];
var map = null;

function clean_map()
{
	if (arrListeners)
	{
		for (i in arrListeners) {
			google.maps.event.removeListener(arrListeners[i]);
		}
	}

	 if (markers) {
		for (i in markers) {
		  markers[i].setMap(null);
		}
	 }
	if (map)
	{
		map.unbindAll();
	}
}
function save_street_view(v_pano, profile_id, formlet_id, item_id, lang_id)
{
	p_pano = v_pano.getPano();
	p_params = v_pano.getPov();
	var params = $.extend(p_params, {pano: p_pano});
	$.ajax(
	{
		type: "POST",
		dataType:"json",
		url: "./media/geo_services.php?action=set_street_view",
		data: { params: params, profile_id: profile_id, formlet_id: formlet_id, item_id: item_id, lang_id: lang_id }
 	});
}
function init_map(map_class, profile_id,formlet_id, item_id,lang_id,is_edit_mode)
{
	clean_map();
	markers = [];
	arrInfoWindows = [];
	arrListeners = [];
	map = null;

	$(".map").empty();
	var myBounds = new google.maps.LatLngBounds();
	var myOptions = { zoom:4, center: new google.maps.LatLng(48,2), mapTypeId: google.maps.MapTypeId.TERRAIN, noClear:false };
	map = new google.maps.Map($("."+map_class)[0], myOptions);
	var service_url = "./media/geo_services.php?action=get_locations&profile_id="+profile_id+"&formlet_id="+formlet_id+"&item_id="+item_id+"&lang_id="+lang_id;
	var panorama = map.getStreetView();

	$.getJSON(service_url, function(json)
	{
		if (json && json.Locations.length>0)
		{
			// get the zoom level
			var zoom = json.Zoom;
			if (zoom < 0 || zoom > 50) zoom = 4;

			if (is_edit_mode)
			{
			// handle zoom change
				google.maps.event.addListener( map, 'maptypeid_changed', function()
				{
					$.ajax(
					{
						type: "POST",
						dataType:"json",
						url: "./media/geo_services.php?action=set_view_mode",
						data: { zoom: map.getMapTypeId(), profile_id: profile_id, formlet_id: formlet_id, item_id: item_id, lang_id: lang_id }
				 	});
				});
				google.maps.event.addListener( panorama, 'visible_changed', function()
				{
					if(panorama.getVisible())
					{
						save_street_view(panorama, profile_id, formlet_id, item_id, lang_id);
						//window.setTimeout("save_street_view('" + profile_id +"','"+ formlet_id+"','"+item_id +"','"+lang_id +"')", 1500);
					}
					else
					{
						// delete street view data
						$.ajax(
						{
							type: "POST",
							dataType:"json",
							url: "./media/geo_services.php?action=set_view_mode",
							data: { zoom: map.getMapTypeId(), profile_id: profile_id, formlet_id: formlet_id, item_id: item_id, lang_id: lang_id }
					 	});
					}
				} );

				google.maps.event.addListener(map, 'zoom_changed', function()
				{
					if (panorama.getVisible() == false)
					{
						var zoom = map.getZoom();
						var service_url = "./media/geo_services.php?action=set_zoom_level&profile_id="+profile_id+"&formlet_id="+formlet_id+"&item_id="+item_id+"&lang_id="+lang_id+"&zoom="+zoom;
						$.getJSON(service_url, function(json){});
					}
				});

				google.maps.event.addListener(panorama, 'pano_changed', function()
				{
						save_street_view(panorama, profile_id, formlet_id, item_id, lang_id);
				});

				google.maps.event.addListener(panorama, 'position_changed', function()
				{
					if (this && this.getPosition)
					{
						var test = this.getPosition().toString();
						test = test.replace(")","");
						test = test.replace("(","");
						test = test.split(",");
						$.ajax(
						{
							type: "POST",
							dataType:"json",
							async: true,
							url: "./media/geo_services.php?action=set_street_position",
							data: { params: test, profile_id: profile_id, formlet_id: formlet_id, item_id: item_id, lang_id: lang_id }
					 	});
 					}
						//save_street_position(this.getPosition(), profile_id, formlet_id, item_id, lang_id);
						//save_street_view2(panorama, profile_id, formlet_id, item_id, lang_id);
				});

				google.maps.event.addListener(panorama, 'pov_changed', function()
				{
						save_street_view(panorama, profile_id, formlet_id, item_id, lang_id);
				});
			}

			// fist iteration, collect all locations and build the arrays for markers and info-windows
			for (i=0; i<json.Locations.length; i++)	{
    				var location = json.Locations[i];
    				var marker = new google.maps.Marker({
					position: new google.maps.LatLng(location.lat, location.lng),
					map: map,
					title: location.attachment_name
				});
				markers[i] = marker;
				myBounds.extend(new google.maps.LatLng(location.lat, location.lng));
			}
			// second iteration handle the UI evets.
			// DO NOT combine interations into a single look!
//			$("#geo_gallery_list").empty();
 			$(markers).each(function(i,marker){
				// add the location to the list AND hande the on_click event
				//.click(function(){  openInfoBox(map, marker, i); displayPoint(map, marker.getPosition(), i);})
				// <span class="location_name">dkdk</span>
				var xName = $("<a />") 	.attr("href","#")
							.attr("class","location_title")
							.text(json.Locations[i].attachment_name)
							.click(function(){  openInfoBox(map, marker, i); displayPoint(map, marker.getPosition(), i);});
				var xDesc = $("<span />")	.addClass("location_desc")
								.text(json.Locations[i].attachment_desc);

				var xAddress = $("<span />")	.addClass("location_address")
								.text(json.Locations[i].geo_address);

				var xRemove = null;

				if (json.Locations[i].del_url != "x" )
				{
					del_url = json.Locations[i].del_url;
					// alert("<"+json.Locations[i].del_url+">");
					xRemove = $("<a />")
								.attr("class","location_remove")
								.attr("href", "javascript:"+del_url)
								.text(" ");
//					alert(xRemove.html());
				}

				var xModify = null;

				if (json.Locations[i].modify_url != "x" )
				{
					// alert("<"+json.Locations[i].del_url+">");
					xModify = $("<a />")
								.attr("class","location_modify")
								.attr("href", "javascript:"+json.Locations[i].modify_url)
								.text(" ");
//					alert(xRemove.html());
				}
				var xChild = ($("<div id='gmaps_info_window' style=' overflow: visible;'/>")
						.append(xName)
						.append(xDesc)
						.append(xAddress)
						.append(xRemove)
						.append(xModify));
				var infoWinHtml = ($("<div/>").append(xChild).html());


				// Create info window
				var infowindow = new google.maps.InfoWindow({
					//maxWidth: 200,
					content: infoWinHtml });
				arrInfoWindows[i] = infowindow;

				// Handle when users clicks on the Marker
				arrListeners[i] = google.maps.event.addListener(marker, "click", function(){
					displayPoint(map, marker.getPosition(), i);
					openInfoBox(map, marker, i);
				});

			});

  		}
		if (json.Locations.length == 0)
		{
			map.setZoom(zoom);
		}
		else if (json.Locations.length == 1)
		{
			map.panTo(new google.maps.LatLng(json.Locations[0].lat, json.Locations[0].lng));
			//map.panTo(myBounds);
			map.setZoom(zoom);
		}

		// If there are two or more points, don't interfere with the zoom, it makes no sense.
		else
		{
			map.fitBounds(myBounds);
		}

/*
		alert('go street view');
		var go_street_view = true;
		if (go_street_view)
		{
			var fenway = new google.maps.LatLng(42.345573,-71.098326);
			var panoramaOptions = {
				position: fenway, //new google.maps.LatLng(json.Locations[0].lat, json.Locations[0].lng),
				pov: {
					heading: 0,
					pitch: 10,
					zoom: 4	}
				};

				alert($("."+map_class)[0]);
				var panorama = new google.maps.StreetViewPanorama($("."+map_class)[0], panoramaOptions);
//				map.setStreetView(panorama);
		}
*/
		//map.setMapTypeId(google.maps.MapTypeId.HYBRID);

		google.maps.event.trigger(map, 'resize');
  	});
		$.ajax(
		{
			type: "POST",
			dataType:"json",
			url: "./media/geo_services.php?action=get_view_mode",
			data: { profile_id: profile_id, formlet_id: formlet_id, item_id: item_id, lang_id: lang_id },
			success: function (e)
			{
				if (e.view_mode == "street")
				{
					var cafe = new google.maps.LatLng(e.street_position[0], e.street_position[1]);
					/*
					var panoramaOptions = {
					      position: cafe,
					      pov: {
					        heading: parseInt(e.street_params.heading.toString()),
					        pitch:  parseInt(e.street_params.pitch.toString()),
					        zoom: 1
					      },
					      visible: true
					    };
					var panorama1 = new google.maps.StreetViewPanorama(null, panoramaOptions);
					alert(e.toSource());
					panorama1.setPano(e.street_params.pano.toString());*/
					panorama.setPano(e.street_params.pano.toString());
					panorama.setPosition(cafe);
					panorama.setPov({
					        heading: parseInt(e.street_params.heading.toString()),
					        pitch:  parseInt(e.street_params.pitch.toString()),
					        zoom: 1
					      });
					panorama.setVisible(true);
					map.setStreetView(panorama);
				}
				else if (e.view_mode != "")
				{
					map.setMapTypeId(e.view_mode);
				}
				//alert(e.toSource());
			}
 		});


  	function on_location_name_click(map, marker, i)
  	{
  		openInfoBox(map, marker, i);
  		displayPoint(map, marker.getPosition(), i);
  	}

	function displayPoint(map, latlng, index)
	{
		$("#message").hide();

            var moveEnd = google.maps.event.addListener(map, "moveend", function() {
			var markerOffset = map.fromLatLngToDivPixel(latlng);
			$("#message").fadeIn().css({ top:markerOffset.y, left:markerOffset.x });

			google.maps.event.removeListener(moveEnd);
		});
		map.panTo(latlng);
	}

	function openInfoBox(map, marker, index)
	{
		for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
		arrInfoWindows[index].open(map, marker);
	}
}
