	/* BERKSHIRE GROWN: INTERACTIVE MAP OF MEMBERS */
	/* ZENN NEW MEDIA 2007 */

	/* requires Prototype 1.6.0_rc0 */
	


// THIS SECTION EXECUTES IMMEDIATELY

	// start widgets after document completes loading
	// TO DO: this is leashed to protoype_1.6.0_rc0 until we fire the "contentloaded" event ourselves
	document.observe( "contentloaded", doMainLoad );
	



	
/* FUNCTIONS */

	// MAIN LOAD FUNCTION
	function doMainLoad()
	{			
		if ( !GBrowserIsCompatible() ) {
			return false; }							// browser cannot support Google Maps - bail completely

		initMapWidget();							// create, configure map object
		initHTMLTemplates();						// define templates for HTML generation
		initMarkerIconTypes(); 						// build icons for markers on map (e.g. red marker, blue marker, etc.)
		initProductIcons();							// build icons for product icons  (e.g. farmstand, pick-your-own, etc.)
		// initTagsAndFlags();							// load tags and flags from JSON, prepare flagged filters
		initAllItems();								// build items from JSON
		initSearchBehaviors();						// event handlers for GUI inputs			

		var searchString = window.location.search.parseQuery().search || "";
		displayMatchingItems( searchString );
	}

	function initMapWidget()
	{		
		// create global namespace for map widget
		ZENN.namespace( 'bg' );
		var bg = ZENN.bg;
	
		// widget setups
		bg.mapElementId 	= 'MapContainer';  // use $(Element) instead of ID here?
		bg.infobox 			= $( 'ItemInfoBox' );
		bg.sidelist			= $( 'Sidelist' );
		bg.selectedItem 	= {};
		bg.allItems 		= [];
		
		// create map object
		bg.map 					= 	new GMap2( $(ZENN.bg.mapElementId) );
		var map 				= 	bg.map;
		map.bounds 				= 	new GLatLngBounds();					
		map.frameAllMarkers 	= 	function()
									{
										this.setCenter( this.bounds.getCenter() );
										this.setZoom( this.getBoundsZoomLevel( this.bounds ) );
										/* the actual region, roughly:
											var min = new GLatLng( 42.95, -73.73 );
											var max = new GLatLng( 42.95, -72.32 );
										*/
									};

		// add user controls for navigating the map
		map.setCenter(  new GLatLng(0,0) ); // we must arbitrarily center map before adding overlays
		map.addControl( new GSmallMapControl() );
		map.addControl( new GMapTypeControl() );	
		

	}

//////////////////////////////////////////////////////////////////////

	// PARSE TAGS AND FLAGS
/* 	function initTagsAndFlags()
	{
		if( typeof zInput_tagList == undefined )
		{	
			alert( "Tag structure data not found. Please contact your system administrator." );
			return false;
		}
		
		ZENN.bg.hiddenTags = [];
		ZENN.bg.hiddenTags = zInput_tagList.
		
	
	
	}
*/



	// BUILD ITEMS
	function initAllItems()
	{		
		// get JSON data
		// TO DO: verify data is successfully collected --- how to handle failure?
		if( typeof zInput_mapItems == undefined )
		{	
			alert( "Member data not found. Please contact your system administrator." );
			return false;
		}

		var bg 		= ZENN.bg;
		var map 	= bg.map;
		var items 	= zInput_mapItems;
		var txt = 'testing';
		
		for (var i = 0; i < items.length; i++)
		{
			var item 		= items[i];
			
			// get latitude and longitude
			var lat			= item.lat;
			var lng			= item.lng;
			var latlng 		= new GLatLng( lat, lng );
			
			if ( lat != 0 && lng != 0 ) // trap for geocoding errors at 0,0
			{					
				if ( lat > 41 && lat < 44 && lng < -72 && lng > -75) // trap for geocoding errors far outside the region
				{						
					if ( latlng )
					{
						// include this point in our framed region
						map.bounds.extend( latlng );
		
						// set itemtype
						if( item.tags.include( "farm" ) )
							item.itemtype = "farm";
						else if( item.tags.include( "shop/markets/retailer" ) )
							item.itemtype = "shop";
						else if( item.tags.include( "restaurant/cafe" ) )
							item.itemtype = "dining";
						else
							item.itemtype = "other";
						
						// product icons
						item.iconsHTML = "";
						bg.productIcons.each( function(product)
													{
														if( item.tags.include( product.name ) ) {
															item.iconsHTML += bg.iconTemplate.evaluate( product ); }
													});
						
						// nice tag list for display
						// TO DO: prep as categories
						item.nicetaglist = item.tags.without("pick-your-own", "BerkshireGrown member", "buyer", "producer").join(', ').gsub('pyo_', 'pick-your-own '); // or similar set of niceness transforms
						
						// infobox HTML
						item.infoHTML = bg.infoboxTemplate.evaluate( item );

						// create side listing
						item.listHTML = bg.itemlistingTemplate.evaluate( item );
						bg.sidelist.insert( item.listHTML );
						
						// after insertion, store a reference to the actual element
						var kids = bg.sidelist.childElements();
						item.sidelisting = kids[kids.length-1];
						
						// and store the child's reference to its own parent
						item.sidelisting.parentItem = item;

						// create marker
						item.marker = new GMarker( latlng, { icon: bg.icons[item.itemtype], title: item.itemname } );
						//item.marker = new GMarker( latlng, { title: item.itemname } );
						
						item.marker.parentItem = item;
						item.marker.originalImage = item.marker.getIcon().image;
						
						// marker events
						//GEvent.addListener( item.marker, "mouseover", function() {
						//											selectItem( this.parentItem ); });   
																	
						GEvent.addListener(item.marker, "click", function() {							//item.marker.openInfoWindowHtml(item.infoHTML);
							openItemInfoAndHighlight( this.parentItem );						});  
					
						bg.allItems[ bg.allItems.length ] = item;
						
						// yield the thread so browser can do some updating
						setTimeout("",0);
					}
				}
			}
		}
		
		map.frameAllMarkers();
		
		// create a movable "selected" marker
		map.highlightMarker = new GMarker( latlng, { icon: ZENN.bg.icons[ 'highlight' ] } );
		map.highlightMarker2 = new GMarker( latlng, { icon: ZENN.bg.icons[ 'highlight' ] } );
		map.smallHighlightMarker2 = new GMarker( latlng, { icon: ZENN.bg.icons[ 'highlight' ] } );
	}

////////////////////////////////////////////////////////////////////////////////////

	// DISPLAY MATCHING ITEMS
	function displayMatchingItems( queryString )
	{
		queryString 	= queryString.strip() || "";
		var niceQuery	= "All Berkshire Grown members";
		var items 		= ZENN.bg.allItems;
		var matched		= [];
		var i 			= 0;

		// remove any displayed items from the widgets
		clearSideList();
		clearMapMarkers();
		clearInfoBox();

		if( queryString.blank() )
		{
			matched = items; // display all items
		}
		else
		{
			// build nice query for display
			// TO DO: grep for certain pulldown values
			niceQuery = queryString;

			var queryPattern = new RegExp( queryString, "i"); // "i" = case-insensitive
			for ( i=0; i < items.length; i++ )
			{
				if (  Object.values(items[i]).grep( queryPattern ).size() ) {
					matched[ matched.length ] = items[i]; }
			}
		}
		
		// display items in map and sidelist
		niceQuery += " (" + matched.length + " items)";
		$("DisplayedQueryString").update( niceQuery );		
		for( var i = 0; i< matched.length; i++ )
		{
			var item = matched[i];
			ZENN.bg.map.addOverlay( item.marker );
			item.sidelisting.show();
			setTimeout("",0); // yield the thread to the browser
		}
	}

	// SELECT ITEM
	function selectItem( item )
	{
		// turn off previous selection
		deselectItem(item);

		// update info box
		$( ZENN.bg.infobox ).update( item.infoHTML );

		// enlarge marker
		//item.marker.setImage( "/img/map_icons/mm_20_yellow.png");
		//ZENN.bg.map.removeOverlay( item.marker ); // commented out to stop info window closing behavior
		item.marker.setImage( '/img/blank.png' );
		
		// set color, position, and visibility to display the highlight marker
		ZENN.bg.map.highlightMarker.setLatLng( item.marker.getLatLng() );		
		ZENN.bg.map.addOverlay( ZENN.bg.map.highlightMarker );
		ZENN.bg.map.highlightMarker.setImage( ZENN.bg.markerLargeIcons[ item.itemtype ] );
		
		// update info box
		//$( ZENN.bg.infobox ).update( item.infoHTML );
		
		// store this item for future de-selection

		ZENN.bg.selectedItem = item;
	}
	
//	function openItemInfoSideList( item )
//	{
//		// turn off previous selection
//		deselectItemAndLeaveLargeMarker(item);
//		
//		// enlarge marker
//		//item.marker.setImage( "/img/map_icons/mm_20_yellow.png");
//		ZENN.bg.map.removeOverlay( item.marker );
//		
//		
//		// enlarge marker
//		//item.marker.setImage( "/img/map_icons/mm_20_yellow.png");
//		ZENN.bg.map.removeOverlay( item.marker );
//		
//		// set color, position, and visibility to display the highlight marker
//		ZENN.bg.map.highlightMarker.setLatLng( item.marker.getLatLng() );		
//		ZENN.bg.map.addOverlay( ZENN.bg.map.highlightMarker );
//		ZENN.bg.map.highlightMarker.setImage( ZENN.bg.markerLargeIcons[ item.itemtype ] );
//
//		// update info box
//		$( ZENN.bg.infobox ).update( item.infoHTML );
//		
//		// store this item for future de-selection
//		ZENN.bg.selectedItem2 = item;
//		
//		// open info window
//		item.marker.openInfoWindowHtml(item.infoHTML);
//
//	}
	
	function openItemInfoAndHighlight( item )
	{
		// turn off previous selection
		//deselectItemAndLeaveLargeMarker(item);
		deselectItem();
		
		// enlarge marker
		//item.marker.setImage( "/img/map_icons/mm_20_yellow.png");
		ZENN.bg.map.removeOverlay( item.marker );
		
		// set color, position, and visibility to display the highlight marker
		ZENN.bg.map.highlightMarker.setLatLng( item.marker.getLatLng() );		
		ZENN.bg.map.addOverlay( ZENN.bg.map.highlightMarker );
		ZENN.bg.map.highlightMarker.setImage( ZENN.bg.markerLargeIcons[ item.itemtype ] );
		GEvent.addListener(ZENN.bg.map.highlightMarker, "click", function() {//		//item.marker.openInfoWindowHtml(item.infoHTML);
		ZENN.bg.selectedItem.marker.openInfoWindowHtml(ZENN.bg.selectedItem.infoHTML);		});  

		// update info box
		$( ZENN.bg.infobox ).update( item.infoHTML );
		
		// store this item for future de-selection
		ZENN.bg.selectedItem = item;
		
		// open info window
		item.marker.openInfoWindowHtml(item.infoHTML);
	}

	// DESELECT ITEM
	function deselectItem(item)
	{
		//revert marker image
		if( ZENN.bg.selectedItem.marker )
		{
			ZENN.bg.map.removeOverlay( ZENN.bg.map.highlightMarker );
			

// This is to keep the large and small markers from both showing
//				if (ZENN.bg.selectedItem.marker.getLatLng() != ZENN.bg.map.highlightMarker2.getLatLng())
//				{
//					ZENN.bg.map.addOverlay( ZENN.bg.selectedItem.marker );
//				}


			ZENN.bg.map.addOverlay( ZENN.bg.selectedItem.marker );



		//	}
		}
	}
	
	// DESELECT ITEM
	function deselectItemAndLeaveLargeMarker(item)
	{
		//revert marker image
		if( ZENN.bg.selectedItem.marker )
		{
			//alert ("ZENN.bg.selectedItem.marker.getLatLng(): " + ZENN.bg.selectedItem.marker.getLatLng() + "ZENN.bg.map.highlightMarker2.getLatLng(): " + ZENN.bg.map.highlightMarker2.getLatLng());

// 
//	This is where the small pin needs to be replaced
//
//			if (ZENN.bg.map.highlightMarker2)
//			{
//				//ZENN.bg.map.addOverlay( ZENN.bg.map.smallHighlightMarker2 );
//				
//				
//				markerToReplace = new GMarker( ZENN.bg.map.highlightMarker2.getLatLng());
//				
//				
//				ZENN.bg.map.addOverlay( ZENN.bg.selectedItem2.marker );
//			}
			
			ZENN.bg.map.highlightMarker2.setLatLng( item.marker.getLatLng() );
			ZENN.bg.map.removeOverlay( ZENN.bg.map.highlightMarker );
			ZENN.bg.map.addOverlay( ZENN.bg.map.highlightMarker2 );
			ZENN.bg.map.highlightMarker2.setImage( ZENN.bg.markerLargeIcons[ item.itemtype ] );

		}
	}

	// EMPTY SIDE LIST
	function clearSideList()
	{				
		// remove all items from list
		$$(".itemlisting").invoke( "hide" );
	}

	// EMPTY MAP MARKERS
	function clearMapMarkers()
	{				
		ZENN.bg.map.clearOverlays();		
	}

	// EMPTY MAP MARKERS
	function clearInfoBox()
	{				
		ZENN.bg.infobox.update('');		
	}




///////////////////////////////////////////////////////////////////////////////


	// PRODUCT ICONS
	// store list of allowable icons (we don't have icons for every single farm attribute)
	function initProductIcons()
	{
		ZENN.bg.productIcons = [ 	{ name: "farm"						, file: "farm.gif",				title: "Yes we're a Farm!" }, 
									{ name: "farm stand"				, file: "farmstand.gif",		title: "We have a Farm Stand!" }, 
									{ name: "pick-your-own" 			, file: "pick_your_own.gif", 	title: "Offering Pick-Your-Own products" }, 
									{ name: "C.S.A."					, file: "csa.gif",				title: "This farm is a CSA: Community Supported Agriculture" }, 
									{ name: "plants/flowers"			, file: "flowers.gif", 			title: "Offering Flowers and Plants" }, 
									{ name: "producer"					, file: "producers.gif", 		title: "BerkshireGrown Producer" }, 
									{ name: "restaurant/cafe"	 		, file: "dining.gif",			title: "Dining on premises" },
									{ name: "shop/market/retailer"		, file: "shop.gif", 			title: "Shopping available" }, 
									{ name: "inn"						, file: "lodging.gif", 			title: "Lodging available" }
								];
	}
 
	// MAP ICON TYPES
	function initMarkerIconTypes()
	{
		ZENN.bg.markerLargeIcons = [];
		ZENN.bg.markerLargeIcons['other'] 	= "/img/map_icons/mm_40_blue.png";
		ZENN.bg.markerLargeIcons['farm'] 	= "/img/map_icons/mm_40_green.png";		
		ZENN.bg.markerLargeIcons['shop'] 	= "/img/map_icons/mm_40_orange.png";		
		ZENN.bg.markerLargeIcons['dining'] 	= "/img/map_icons/mm_40_red.png";	

		var icon;
		ZENN.bg.icons 			= [];
		
		// default = 'other'
		icon 						= new GIcon();
		icon.image 					= "/img/map_icons/mm_20_blue.png";
		icon.shadow 				= "/img/map_icons/mm_20_shadow.png";
		icon.originalImage 			= icon.image;
		icon.iconSize 				= new GSize(12, 20);
		icon.shadowSize 			= new GSize(22, 20);
		//icon.iconAnchor 			= new GPoint(6, 20);
		//icon.infoWindowAnchor 		= new GPoint(200, 200);
		
		icon.iconAnchor 			= new GPoint(6, 20);
		icon.infoWindowAnchor 		= new GPoint(15, -15);
		
		ZENN.bg.icons['other'] 	= icon;

		// farm
		icon 						= Object.clone( icon );
		icon.image 					= "/img/map_icons/mm_20_green.png";
		ZENN.bg.icons['farm'] 		= icon;

		// store
		icon 						= Object.clone( icon );
		icon.image 					= "/img/map_icons/mm_20_orange.png";
		ZENN.bg.icons['shop'] 		= icon;

		// dining
		icon 						= Object.clone( icon );
		icon.image 					= "/img/map_icons/mm_20_red.png";
		ZENN.bg.icons['dining'] 	= icon;

		// selected - for temporary highlighting
		icon 						= new GIcon();
		icon.image 					= "/img/map_icons/mm_40_yellow.png";
		icon.shadow 				= "/img/map_icons/mm_20_shadow.png";
		icon.originalImage 			= icon.image;
		icon.iconSize 				= new GSize(24, 40);
		icon.shadowSize 			= new GSize(44, 40);
		icon.iconAnchor 			= new GPoint(12, 40);
		icon.infoWindowAnchor 		= new GPoint(200, 200);

		
		ZENN.bg.icons['highlight'] = icon;
	}

	// HTML TEMPLATES
	function initHTMLTemplates()
	{
		// template for icon images
		ZENN.bg.iconTemplate = new Template('<img src="../img/bg_product_icons/#{file}" alt="" title="#{title}" />');
		
		// template for info blocks
		var str  = "";
		str  	 = '<div class="item_infobox">';
		str 	+= '<div class="infofield itemiconsfield">#{iconsHTML}</div>';
		str 	+= '<div class="infofield itemnamefield"><strong>#{itemname}</strong></div>';
		str 	+= '<div class="infofield">#{nicetaglist}</div><br />';
		str 	+= '<div class="infofield">#{proprietor}</div>';
		str 	+= '<div class="infofield">#{street}<br />#{city}, #{state} #{zipcode}</div>';
		str 	+= '<div class="infofield itemurlfield"><a href="http://#{url}" target="_blank">#{url}</a></div>';
		str 	+= '<div class="infofield">#{phone}</div>';
		str 	+= '</div>';
		ZENN.bg.infoboxTemplate = new Template( str );

		// template for item listings
		// has obtrusive onmouseover handler for performance/brevity
		str 	 = "";
		str		+= '<div class="itemlisting" onclick="openItemInfoAndHighlight( this.parentItem );" onmouseover="selectItem( this.parentItem );">#{itemname}</div>';
		ZENN.bg.itemlistingTemplate = new Template( str );
	}
	
	// SEARCH BEHAVIORS
	function initSearchBehaviors()
	{
		
		// text field for keyword query

		Event.observe( $("keywords"), "keypress", 	function(event)
												{
													if(event.keyCode == Event.KEY_RETURN || event == "blur")
													{
														displayMatchingItems( $("keywords").value );
														ZENN.bg.selectedItem = {};
														document.getElementById("keywords").blur();
													}
													
												});



		// text field for keyword query
		Event.observe( $("keywords"), "blur", 	function()
												{
													displayMatchingItems( $("keywords").value );
													ZENN.bg.selectedItem = {};
												});

		// pulldowns for keyword query
		$('PickYourOwn', 'NowInSeason').each( 	function( pulldown )
														{		
															Event.observe( pulldown, "change", 	function()
																								{
																									displayMatchingItems( pulldown.value );
																									ZENN.bg.selectedItem = {};
																								});
														});	
	}




	
