//  $Id: search_results.js,v 1.11 2009/09/17 04:40:33 sgruenholz Exp $


// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
// 	SETUP GLOBAL VARIABLES
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

var map; // map object
var minimap; // holds minimap control object
var IMG_BASE_URL = "/images/gmap/";

var LISTING_MARKERS = new Object(); // js object acts as an associative array - indexed by listing_id (mls_id + "_" + mls_no)

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon();
baseIcon.shadow = IMG_BASE_URL+"marker_shdw.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);




// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
// 	NORMAL PAGE FUNCTIONS
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 


/**
 * converts the current GET string into an array of name/value pairs (since
 *    javascript doesn't support associative arrays).
 */
function parse_get_string()
{
	var params = [];
	var regex = /[\?&]([^=]+)=([a-z0-9_]*)/ig;
	while( ( results = regex.exec( window.location.href ) ) != null )
		params.push( [results[1], results[2]] );
	return params;
}


// reorders the listing data according to a new "sort by" and reloads the page
function sortSearchResults(sortby) 
{
	
	var found_sort = false;
	var get_string_values;
	var outstring = "?";
		
	get_string_values = parse_get_string();
	for (var i=0; i<get_string_values.length; i++)
	{
		if (get_string_values[i][0] == 'SORT_order')
		{
			outstring += "SORT_order=" + sortby + "&";
			found_sort = true;
		}
		else {
			outstring += get_string_values[i][0] + "=" +  get_string_values[i][1] + "&";
		}
	}
	if (!found_sort) {
		outstring += "SORT_order=" +  sortby;
	}
	
	//alert(outstring);
	
	window.location = outstring;
}

// this attaches events to all the elements on the results page (onload)
function attachSearchResultsEvents() {
	$$('.submit_on_change').each(function(selectobj) {
		selectobj.observe('change', function () {
			//this.form.submit();
			//var sortby = selectobj.id;
			//var sortby = document.getElementById(selectobj.id);
			
			var sortby = $(selectobj).getValue();
			sortSearchResults(sortby);
		});
	});
	
    // select box for featured order by
	if ($("featured_order_by")) {
		$("featured_order_by").observe('change', function() {
			$("featured_order_form").submit();
		});
	}
	
	// contact and visit buttons pop up the same email form
	$$('.btn_contact, .btn_visit').each( function(s) {
		$(s).observe('click', function(event) {
			popWindow(s);
			Event.stop(event); // prevent the regular link from firing
		});
	});
}



// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
// 	MAP FUNCTIONS
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 


// creates a listing marker object
function createListingMarker(letter, mls_id, mls_no, point, page, lpp, index_on_page, total_listings, featured_order_by, listing_id, content_index) {
	// initialize these optional params if they are not set
	if (!page) {page = null;}
	if (!lpp) {	lpp = null;}
	if (!index_on_page) {index_on_page = null;}
	if (!total_listings) {total_listings = null;}
	
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = IMG_BASE_URL + "marker" + letter + ".png";
	markerOptions = { icon:letteredIcon };
	var listingmarker = new GMarker(point, markerOptions);
	
	if ($("FeaturedMap")) {
		listingmarker.id = listing_id;
	} else {
		listingmarker.id = mls_id + "_" + mls_no;
	}
	
	listingmarker.active = false;
	
	
	// attach events to the marker
	GEvent.addListener(listingmarker, "mouseover", function() {
		if(listingmarker.active != true) {
			listingmarker.setImage(IMG_BASE_URL + "marker" + letter + "_teal.png");
			//highlightListing(listingmarker.id);
		}
	});
	GEvent.addListener(listingmarker, "mouseout", function() {
		if(listingmarker.active != true) {
			listingmarker.setImage(IMG_BASE_URL + "marker" + letter + ".png");
			//deselectListing(listingmarker.id);
		}
	});
	// build the html to go in the info window
	GEvent.addListener(listingmarker, "click", function() {
		if(listingmarker.active != true) {
			CURRENT_LISTING_ID = listingmarker.id;
			listingmarker.active = true;
			listingmarker.setImage(IMG_BASE_URL + "marker" + letter + "_green.png");
			//selectListing(listingmarker.id);
			// populate info window with summary content
			var infowindow_html;
			var infowindow_url="?";
			
			if ($("FeaturedMap")) {
				new Ajax.Request(infowindow_url,
				{
					method:'post',
					parameters:{	controller: 'FeaturedListings',
									product: 'web',
									action: 'details',
									acnt: ACNT,
									listing_id: listing_id,
									featured_order_by: featured_order_by,
									content_index: content_index,
									infowindow: 1
					},
					onSuccess: function(transport) {
						infowindow_html = transport.responseText;
						listingmarker.openInfoWindowHtml(infowindow_html);
					},
					onFailure: function() {
						alert("The ajax request failed - was trying to retrieve this listing's information to show in the info window.");
					}
				});
			}
			else{
				new Ajax.Request(infowindow_url,
				{
					method:'post',
					parameters:{	controller: 'ListingSearch',
									product: 'web',
									action: 'details',
									acnt: ACNT,
									mls_id: mls_id,
									mls_no: mls_no,
									page: page,
									lpp: lpp,
									index: index_on_page,
									total_listings: total_listings,
									infowindow: 1
					},
					onSuccess: function(transport) {
						infowindow_html = transport.responseText;
						listingmarker.openInfoWindowHtml(infowindow_html);
					},
					onFailure: function() {
						alert("The ajax request failed - was trying to retrieve this listing's information to show in the info window.");
					}
				});
			}
		}
	});
	GEvent.addListener(listingmarker, "infowindowclose", function() {
		if(listingmarker.active == true) {
			listingmarker.active = false;
			listingmarker.setImage(IMG_BASE_URL + "marker" + letter + ".png");
			//deselectListing(listingmarker.id);
			// this listing has been deselected - hide details tab
			//$("MS_TabDetails").hide();
		} else {
			listingmarker.active = false;
		}
	});
	
	return listingmarker;
}


// sets up a listing marker for each listing on the results page that has lat/lng data
// (up to 20 listings)
function setupListingMarkers() {
	
	var bounds = new GLatLngBounds();
	var index;
	
	// the locate button will only exist if the listing has lat/lng data
	var locate_buttons = $$('a.btn_locate');
	locate_buttons.each( function(s) {
		// but just in case...
		if (s.rel != '') {
		
			// get the parameters out of the rel attribute of the button
			var params = s.rel.split(",");
			var letter = params[0];
			var mls_id = params[1];
			var mls_no = params[2];
			var lat = params[3];
			var lng = params[4];
			var page = params[5];
			var lpp = params[6];
			var index_on_page = params[7];
			var total_listings = params[8];
			
			// variables for featured listings version only
			var featured_order_by = params[9];
			var listing_id = params[10];
			var content_index = params[11];
			
			
			var listing_point = new GLatLng(parseFloat(lat), parseFloat(lng));
			
			// check if the point is in the existing bounds
			// if not, extend teh bounds to contain it
			if (!bounds.containsLatLng(listing_point)) {
				bounds.extend(listing_point);
			}
			
			// create a marker object and...
			var marker = createListingMarker(letter, mls_id, mls_no, listing_point, page, lpp, index_on_page, total_listings, featured_order_by, listing_id, content_index);
			
			// store the marker obj in a global obj (associative array) for future reference from outside the map
			
			
			var listing_index = "";
			if ($("FeaturedMap")) {
				listing_index = listing_id;
			} else {
				listing_index = mls_id + "_" + mls_no;
			}
			
			LISTING_MARKERS[listing_index] = marker;
			
			// add it to the map
			map.addOverlay(marker);
			
			// onclick: open the info window for this listing on the map and pan to it.
			$(s).observe('click', function(event) {
										   
				GEvent.trigger(LISTING_MARKERS[listing_index], "click");
				//alert("locating this listing: " + letter + " on the map");
				//Event.stop(event); // stop the href from resolving
				// allow href to resolve to the bookmark anchor tag just above the map
			});
			$(s).up(1).next('a.btn_locate_marker').observe('click', function(event) {
				GEvent.trigger(LISTING_MARKERS[listing_index], "click");
			});
		}
	});
	
	if (locate_buttons) {
		var bounds_center = bounds.getCenter();
		var bounds_zoom = map.getBoundsZoomLevel(bounds);
		map.setCenter(bounds_center, bounds_zoom);
	}
}


// initializes the map, calls setupListingMarkers
function load() {
	if (GBrowserIsCompatible()) {
		// show loading message while map initializes
		//$("MS_LoadingMsg").update("Map is loading... please wait.");
		//$("MS_Loading").show();
		
		// Starting point is determined in the Map Search Controller
		// calculated average of MLS Data available
		var starting_centerpoint = $F("starting_centerpoint"); // the avg lat,lng value of the 20 listings on this page
		// set this to a reasonable level for now, and then when cities load,
		// it will adjust the map to fit all the city data in.
		var starting_zoom = 8;
		//var starting_type = G_HYBRID_MAP;
		var starting_type = G_NORMAL_MAP;
		
		// get number values for lat, lng from the string
		var ctrpt = starting_centerpoint.split(",");
		
		
		// initialize the map object
		map = new GMap2($("Map"));
		
		// set the starting centerpoint and zoom level for the map
		// this needs to be done before any thing else with the map
		map.setCenter(new GLatLng(parseFloat(ctrpt[0]), parseFloat(ctrpt[1])), starting_zoom, starting_type);
		
		// add map controls
		map.addControl(new GLargeMapControl()); // regular large zoom/pan control
		//map.addControl(new GMenuMapTypeControl());
		map.addControl(new GMapTypeControl()); // control buttons for map view type: eg. Map, Hybrid, Satellite
		
		//minimap = new GOverviewMapControl();
		//map.addControl(minimap); // the minimap box in the lower right
		//minimap.hide(); //start with the minimap collapsed
		
		// add the listing markers after a 3 second delay
		// gives the map time to load (map tile graphics may still be loading)
		setupListingMarkers.delay(3);
	}	
}



// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
// 	ONLOAD
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

Event.observe(window, 'load', function() {
	attachSearchResultsEvents();
	
	// only load the map scripts if there is a map
	if ($("Map")) {
		load();
	}
	
	// run a png fix on the map marker icons and any sold graphics
	$$('a.btn_locate_marker').invoke('pngFix');
	
	
});

Event.observe(window, 'unload', function() {
	GUnload();
});

