var gmap = null;

var num_bw_polylines = 0;


var bw_polylines_array_marker = null;

var bw_icons_marker_array = null;

var bw_listeners_array = null;

var fa_marker = null;
var xmlHttp = null;
var xmlreceived = null;
var xmlreceived_1 = null;


poi_category_markers = new Array();
poi_category_markers_id = new Array();
poi_category_listeners = new Array();

var g_bw_points_step = 15;
var g_poi_x_size = 20;
var g_poi_y_size = 20;

var g_icon_x_size = 20;
var g_icon_y_size = 35;


var stop_url = "mapimages/ferm.gif";
var start_url = "mapimages/start.gif";
var end_url = "mapimages/end.gif";
var fa_url = "mapimages/fa.gif";


var g_poi_info_xml_url = "http://zurich.locator.it/xml/xmlpoi.asp";
var g_bwurl = "http://zurich.locator.it/xml/bwpoints.asp";
var g_poiurl = "http://zurich.locator.it/xml/nearest.asp";

var g_base_info = "";
var g_detail_info = "";
var g_category = "";

var g_sessionid = "";
var g_contextname = "";

var g_connect = false;

Number.prototype.toRad = function() { return this * Math.PI / 180; }

function LatLon_Distance( lat1, lon1, lat2, lon2 )
{
	var R = 6371; // km
	var dLat = (lat2 - lat1 ).toRad();
	var dLon = (lon2 - lon1 ).toRad(); 
	
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
	
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	
	var d = R * c;
	return( d );
}

/*********************************************************************************/
function createXMLHttpObject()
{

	xmlHttp = GXmlHttp.create();

	return( xmlHttp != null );
}

/*********************************************************************************/
function PostXmlRequest( url, xmltopost, b_use_1 )
{
	
	if ( xmlHttp == null )
		return( false );
		
	if ( xmltopost == "" )
	    {
	    xmlHttp.open("GET", url, false);
	    xmlHttp.send(null);
	    }
	    else
	        {
	        xmlHttp.open("POST", url, false);
	        xmlHttp.send(xmltopost);
	        }

	
	if ( xmlHttp.status == 200 )
		{
		if ( !b_use_1  )
		    xmlreceived = xmlHttp.responseXML;
		    else
		        xmlreceived_1 = xmlHttp.responseXML;
		return( true );
		}

	return( false );

}



/*********************************************************************************/
function create_bestway_overlay( bwname )
{
	
	if ( !createXMLHttpObject() )
		return( false );
	
	
	if ( !PostXmlRequest( g_bwurl + "?fname=" + bwname, "", false ) )
		return( false );
	
	
	if ( xmlreceived == null )
		return( false );
	
	
	var bw_polyline_list = xmlreceived.documentElement.getElementsByTagName( "polyline" );
	
	
	if ( bw_polyline_list == null )
		return( false );
	
	num_bw_polylines = bw_polyline_list.length;

	
	if ( num_bw_polylines == 0 )
		return( false );
	
	var line_info_nodes = xmlreceived.documentElement.getElementsByTagName( "lineinfo" );

	bw_polylines_array_marker = new Array();

	bw_listeners_array = new Array();

	var iter;
	
	var lat, lon;

	var bw_polyline_points_arr = new Array();
	var tmp_bw_polyline_points_arr = new Array();

	var num_points = 0;

	var iter_child;

	//var bw_point_attributes;
	
	var hex_red;
	var hex_green;
	var hex_blue;
	
	var polyline_color;

	
	
	var iter_k;
	var iter_j;
	var end_loop_index;
	var start_loop_index;
	
	var bw_marker;
	
	for ( iter = 0; iter < num_bw_polylines; iter++ )
		{
		
		hex_red = bw_polyline_list.item( iter ).getAttribute( "hexred" );
		if ( hex_red == "0" )
			hex_red = "00";
		
		hex_green = bw_polyline_list.item( iter ).getAttribute( "hexgreen" );
		if ( hex_green == "0" )
			hex_green = "00";
		
		hex_blue = bw_polyline_list.item( iter ).getAttribute( "hexblue" );
		if ( hex_blue == "0" )
			hex_blue = "00";
		
		polyline_color = "#" + hex_red + hex_green + hex_blue;
		//alert( polyline_color );
		if ( bw_polyline_list[ iter ].hasChildNodes )
			{
			var xml_polyline_points = bw_polyline_list[ iter ].childNodes;

			if ( xml_polyline_points != null )
				{
			
				
				for ( iter_child = 0; iter_child < xml_polyline_points.length; iter_child++ )
					{
					
					//bw_point_attributes = xml_polyline_points[ iter_child ].attributes;
			
					//if ( bw_point_attributes == null )
					//	{
						//alert( "KO" );
					//	break;
					//	}

				
					lat = xml_polyline_points[ iter_child ].getAttribute( "lat" );
					lon = xml_polyline_points[ iter_child ].getAttribute( "lon" );
					

					bw_polyline_points_arr.push( new GLatLng( lat, lon ) );
					}
				
				//18/03/2008 reverse points into smaller vectors
				if ( bw_polyline_points_arr.length > g_bw_points_step )
					{
					for ( iter_k = 0; iter_k < bw_polyline_points_arr.length; iter_k += g_bw_points_step )
						{
						tmp_bw_polyline_points_arr.length = 0;

						end_loop_index = iter_k + g_bw_points_step;
						if ( iter_k == 0 )
							start_loop_index = iter_k;
							else
								start_loop_index = iter_k - 1;//must include last previous point
						
						for ( iter_j = start_loop_index; iter_j < end_loop_index && iter_j < bw_polyline_points_arr.length; iter_j++ )
							tmp_bw_polyline_points_arr.push( bw_polyline_points_arr[ iter_j ] );
						

						if ( tmp_bw_polyline_points_arr.length > 0 )
							{
							bw_marker = new GPolyline( tmp_bw_polyline_points_arr ,polyline_color, 5, 0.7 );
							gmap.addOverlay( bw_marker );
							bw_polylines_array_marker.push( bw_marker );
							}
						}
					}
					else
						{

						//alert( bw_polyline_points_arr.length );
						bw_marker = new GPolyline( bw_polyline_points_arr ,polyline_color, 5, 0.7 );
						gmap.addOverlay( bw_marker );
						
						
						bw_polylines_array_marker.push( bw_marker );
						}
				
				//reset bwpoints array
				bw_polyline_points_arr.length = 0;
				
				}
			}

		}

	
	bw_icons_marker_array = new Array();
	//now add bw icons

	//retrieve start and end
	var xml_start_end_list = xmlreceived.documentElement.getElementsByTagName( "start" );
	if ( xml_start_end_list == null )
		return( false );

	if ( xml_start_end_list.length == 1 )
		{
		lat = xml_start_end_list[ 0 ].getAttribute( "lat" );
		lon = xml_start_end_list[ 0 ].getAttribute( "lon" );
		
		
		if ( lat != null && lon != null )
			{
			bw_hot_point_marker = create_bw_icon( lat, lon, start_url );
			bw_icons_marker_array.push( bw_hot_point_marker );
			gmap.addOverlay( bw_hot_point_marker );
			}

		}
	
	xml_start_end_list = xmlreceived.documentElement.getElementsByTagName( "end" );
	if ( xml_start_end_list == null )
		return;

	if ( xml_start_end_list.length == 1 )
		{
		lat = xml_start_end_list[ 0 ].getAttribute( "lat" );
		lon = xml_start_end_list[ 0 ].getAttribute( "lon" );
		
		
		if ( lat != null && lon != null )
			{
			bw_hot_point_marker = create_bw_icon( lat, lon, end_url );
			bw_icons_marker_array.push( bw_hot_point_marker );
			gmap.addOverlay( bw_hot_point_marker );
			}

		}

	//retrieve boundy box
	var bbox_element_list = xmlreceived.documentElement.getElementsByTagName( "bbox" );
	
	if ( bbox_element_list != null )
		{

		var sw_lat = bbox_element_list[ 0 ].getAttribute( "sw_lat" );
		var sw_lon = bbox_element_list[ 0 ].getAttribute( "sw_lon" );

		var ne_lat = bbox_element_list[ 0 ].getAttribute( "ne_lat" );
		var ne_lon = bbox_element_list[ 0 ].getAttribute( "ne_lon" );
		


		var bw_bounds = new GLatLngBounds( new GLatLng( sw_lat, sw_lon ), new GLatLng( ne_lat, ne_lon ) );
		var bounds_zoom_level = gmap.getBoundsZoomLevel( bw_bounds );
		gmap.setCenter(bw_bounds.getCenter(), bounds_zoom_level);
		}


	return( true );
}

/*********************************************************************************/
function create_line_info_listener( bw_marker__, line_info_str )
{
	return( GEvent.addListener( bw_marker__,"click",function(param)
					{gmap.openInfoWindowHtml(param, "Linea:<h3>" + line_info_str + "</h3>")}) );
}


/*********************************************************************************/
function add_bw_overlay( bwname )
{
	
	
	if ( gmap == null )
		return( false );
	
	remove_bw_overlay();
	
	if ( !create_bestway_overlay( bwname ) )
		return( false );
	return( true );
}

/*********************************************************************************/
function add_nearest_overlay( poiname )
{

	if ( gmap == null )
		return( false );
	
	remove_nearest_overlay();
	
	if ( !create_nearest_overlay( poiname ) )
		return( false );
	
	return( true );
}

/*********************************************************************************/
function create_bw_icon( lat, lon, image_name )
{
	
	if ( gmap == null )
		return;
	
	
	//add bw
	var Icon = new GIcon();
	Icon.iconSize = new GSize(16, 16);
	Icon.iconAnchor = new GPoint(9, 16);

	
	Icon.image = image_name;
	markerOptions = { icon:Icon };
	
	var marker = new GMarker( new GLatLng( lat, lon ), markerOptions );
	
	return( marker );	
	

}


/*********************************************************************************/
function remove_bw_overlay()
{
	var jj;
	if ( bw_polylines_array_marker != null )
		{

		//alert( "Remove bw overlay:" + bw_polylines_array_marker.length );
		for ( jj = 0; jj < bw_polylines_array_marker.length; jj++ )
			gmap.removeOverlay( bw_polylines_array_marker[ jj ] );
		
		bw_polylines_array_marker.length = 0;
		bw_polylines_array_marker = null;
	
		
		if ( bw_icons_marker_array != null )
			{
			

			for ( jj = 0; jj < bw_icons_marker_array.length; jj++ )
				gmap.removeOverlay( bw_icons_marker_array[ jj ] );
			
			bw_icons_marker_array.length = 0;	
			bw_icons_marker_array = null;
			}
		}

	if ( bw_listeners_array != null )
		{
		for ( jj = 0; jj < bw_listeners_array.length; jj++ )
			{
			if ( bw_listeners_array[ jj ] != null )
				GEvent.removeListener( bw_listeners_array[ jj ] );
			}
		bw_listeners_array.length = 0;
		bw_listeners_array = null;
		}
	//return( false );
}
		
/*********************************************************************************/
function custom_load( lat, lon, start_zoom_level )
{
	if (GBrowserIsCompatible())
		{
		
		gmap = new GMap2(document.getElementById("map"), { mapTypes : [G_SATELLITE_MAP,G_HYBRID_MAP] } );
		/*gmap.addControl(new GLargeMapControl())*/
		gmap.setCenter(new GLatLng(lat, lon ), start_zoom_level );
		
		
		if ( bwurl != "none" )
			{
			add_bw_overlay( bwurl );
			}
		
		return( true );
		}
	
	return( false );
}

/*********************************************************************************/
function zoom_at( lat, lon, zoom_level )
{
	if ( gmap == null )
		return( false );

	gmap.setCenter(new GLatLng(lat, lon ), zoom_level );

}

/*********************************************************************************/
function load( lat, lon, start_zoom_level, bwname, poiname, category )
{
	if (GBrowserIsCompatible())
		{
		g_category = category;
		gmap = new GMap2(document.getElementById("map"), { mapTypes : [G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP] } );

		//gmap.addMapType(G_SATELLITE_3D_MAP);

		
		//this is for map click events
		//GEvent.addListener(gmap,"click", function(overlay,latlng)
		//	{    
		//	if (latlng)
		//		{   
		//		var myHtml = "The GLatLng value is: " + gmap.fromLatLngToDivPixel(latlng) + " at zoom level " + gmap.getZoom();
		//		gmap.openInfoWindow(latlng, myHtml);
		//		}
		//	} );

		gmap.addControl(new GLargeMapControl() );

		var maptype_control = new GMapTypeControl();
		gmap.addControl( maptype_control );
		
		if ( bwname != "" )
		    {
		    if ( !add_bw_overlay( bwname ) )
				gmap.setCenter(new GLatLng(lat, lon ), start_zoom_level );
			
		    }

		if ( poiname != "" )
			{
			if ( !add_nearest_overlay( poiname ) )
				gmap.setCenter(new GLatLng(lat, lon ), start_zoom_level );
			}
		
		gmap.enableScrollWheelZoom();
		
		}
	

}

/*********************************************************************************/
function add_fa_overlay( lat, lon )
{
	
	if ( gmap == null )
		return( false );
	
	remove_fa_overlay();
	//add find address icon
	var faIcon = new GIcon();
	faIcon.iconSize = new GSize(20, 20);
	//baseIcon.shadowSize = new GSize(37, 34);
	faIcon.iconAnchor = new GPoint(9, 20);

	
	//var letteredIcon = new GIcon(baseIcon);
	faIcon.image = fa_url;
	markerOptions = { icon:faIcon };
	
	fa_marker = new GMarker( new GLatLng( lat, lon ), markerOptions );
	
	gmap.addOverlay( fa_marker );	
	

}

/*********************************************************************************/
function remove_fa_overlay()
{
	if ( fa_marker != null )
		{
		gmap.removeOverlay( fa_marker );
				
		fa_marker = null;
		}
}

/*********************************************************************************/
function remove_all_overlay()
{
	remove_fa_overlay();
	remove_bw_overlay();
	remove_nearest_overlay();
}


/*********************************************************************************/
function remove_nearest_overlay()
{
	
	var jj;

	for ( jj = 0; jj < poi_category_markers.length; jj++ )
		gmap.removeOverlay( poi_category_markers[ jj ] );

	for ( jj = 0; jj < poi_category_listeners.length; jj++ )
		GEvent.removeListener( poi_category_listeners[ jj ] );
	
	
	poi_category_markers.length = 0;
	poi_category_listeners.length = 0;
	poi_category_markers_id.length = 0;
	
}

/*********************************************************************************/
function get_poi_info( poi_id )
{
	var xmlstring;

	g_base_info = "";
	g_detail_info = "";
	
	xmlstring = '<?xml version="1.0" encoding="ISO-8859-1" ?>';
	xmlstring += "<poirequest>";
	xmlstring += "<poi_id>" + poi_id + "</poi_id>";
	xmlstring += "<sessionid>" + g_sessionid + "</sessionid>";
	xmlstring += "<contextname>" + g_contextname + "</contextname>";
	xmlstring += "</poirequest>";
	
	//alert( g_poi_info_xml_url );
	if ( !createXMLHttpObject() )
		return( false );
	
	//alert( xmlstring );
	if ( !PostXmlRequest( g_poi_info_xml_url, xmlstring, false ) )
		return( false );
	
	if ( xmlreceived == null )
		return( false );


	//alert( xmlreceived != null );
    var geninfo_node = xmlreceived.documentElement.getElementsByTagName( "geninfo" );
	
	
	if ( geninfo_node == null )
	    return( false );
    
	//alert( geninfo_node[ 0 ].hasChildNodes );
	if ( geninfo_node[ 0 ].hasChildNodes )
        g_base_info = geninfo_node[ 0 ].childNodes[ 0 ].nodeValue;


    var detinfo_node = xmlreceived.documentElement.getElementsByTagName( "detinfo" );
	
	
	if ( detinfo_node == null )
	    return( true );
    
	
	if ( detinfo_node[ 0 ].hasChildNodes )
        g_detail_info = detinfo_node[ 0 ].childNodes[ 0 ].nodeValue;
    
	
	return( true );
    
    
}

/*********************************************************************************/
function find_poi( poiid )
{
	var i;

	for ( i = 0; i < poi_category_markers_id.length; i++ )
	{
		if ( poiid == poi_category_markers_id[ i ] )
			return( i );
	}
	return( -1 );
}

/*********************************************************************************/
function showpoiinfo( poiid )
{
	var	 p_p = find_poi( poiid );

	if ( p_p == -1 )
		return( false );

	var marker = poi_category_markers[ p_p ];
	
	if ( marker != null && get_poi_info( poiid ) )
		{
		marker.openInfoWindowHtml( g_base_info );
	
		var obj_html = document.getElementById("poi_detail_info");
	
		//var rec_detail_html = get_poi_detail( poi_id );
		
		if ( obj_html != null && g_detail_info != "" )
			obj_html.innerHTML = g_detail_info;
			else
				{
				if ( obj_html != null )
					obj_html.innerHTML = "";
				}
		}

}


/*********************************************************************************/
function create_poi_icon( poi_id, lat, lon, poinumber )
{
	
	if ( gmap == null )
		return;
	
	//add poi icon
	var Icon = new GIcon();
	Icon.iconSize = new GSize(g_icon_x_size, g_icon_y_size);
	Icon.iconAnchor = new GPoint(9, 16);

	Icon.infoWindowAnchor = new GPoint( 9, 2);
	
	if ( g_connect == false )
		Icon.image = "markers/" + poinumber + ".gif";
	else
		Icon.image = "cmarkers/" + poinumber + ".gif";
	markerOptions = { icon:Icon };
	
	//var marker = new LabeledMarker( new GLatLng( lat, lon ), markerOptions );
	var marker = new GMarker( new GLatLng( lat, lon ), markerOptions );


	poi_category_markers.push( marker );
	poi_category_markers_id.push( poi_id );

	var event_listener = GEvent.addListener( marker, "click", 
	     	function() {

			if ( get_poi_info( poi_id ) )
				{
				marker.openInfoWindowHtml( g_base_info );
	        
				var obj_html = document.getElementById("poi_detail_info");
	        
				//var rec_detail_html = get_poi_detail( poi_id );
				
				if ( obj_html != null && g_detail_info != "" )
					obj_html.innerHTML = g_detail_info;
					else
						{
						if ( obj_html != null )
						    obj_html.innerHTML = "";
						}
				}
			
			} );


	if ( event_listener != null )
		poi_category_listeners.push( event_listener );

	
	return( marker );	
	

}


/*********************************************************************************/
function create_nearest_overlay( poiname )
{
	if ( !createXMLHttpObject() )
		return( false );
	
	
	if ( !PostXmlRequest( g_poiurl + "?fname=" + poiname, "", false ) )
		return( false );
	
	
	if ( xmlreceived == null )
		return( false );
	
	var poi_list = xmlreceived.documentElement.getElementsByTagName( "poi" );

	if ( poi_list == null )
		return( false );

	var num_poi = poi_list.length;
	
	if ( num_poi == 0 )
		return( false );
	
	var iter;
	
	
	var lat, lon;

	
	var poi_marker;
	var poi_id;
	var poi_info;
	var poi_number;
	
	for ( iter = 0; iter < num_poi; iter++ )
		{
		
	
		lat = poi_list[ iter ].getAttribute( "lat" );
		lon = poi_list[ iter ].getAttribute( "lon" );
		
		
		poi_id = poi_list[ iter ].getAttribute( "strid" );
	
		poi_number = poi_list[ iter ].getAttribute( "number" );
		
		//if ( poi_list[ iter ].hasChildNodes )
		//	info_record = poi_list[ iter ].childNodes[ 0 ].nodeValue;
		//	else
		//		info_record = "";
	
		poi_marker = create_poi_icon( poi_id, lat, lon, poi_number );

		gmap.addOverlay( poi_marker );
		}

	
	//retrieve boundy box
	var bbox_element_list = xmlreceived.documentElement.getElementsByTagName( "bbox" );
	
	if ( bbox_element_list != null )
		{

		var sw_lat = bbox_element_list[ 0 ].getAttribute( "sw_lat" );
		var sw_lon = bbox_element_list[ 0 ].getAttribute( "sw_lon" );

		var ne_lat = bbox_element_list[ 0 ].getAttribute( "ne_lat" );
		var ne_lon = bbox_element_list[ 0 ].getAttribute( "ne_lon" );
		


		var bw_bounds = new GLatLngBounds( new GLatLng( sw_lat, sw_lon ), new GLatLng( ne_lat, ne_lon ) );
		var bounds_zoom_level = gmap.getBoundsZoomLevel( bw_bounds );
		gmap.setCenter(bw_bounds.getCenter(), bounds_zoom_level);
		}

	//add origin
	var origin_list = xmlreceived.documentElement.getElementsByTagName( "origin" );

	if ( origin_list == null )
		return( true );

	lat = origin_list[ 0 ].getAttribute( "lat" );
	lon = origin_list[ 0 ].getAttribute( "lon" );

	add_fa_overlay( lat, lon );
	
	return( true );


}



