var rfs = ['client_id', 'name', 'street', 'town','pc', 'lat', 'lon'];
var homeGeocodeLocation;

/**
 * sets up the mapviewer element and binds it to the chosen div element
 */
function initialiseMap (id) 
{  
	mapviewer = MMFactory.createViewer( document.getElementById( id ) );
	mapviewer.goToPosition( new MMLocation( new MMLatLon( MULTIMAP_DEFAULT_LAT, MULTIMAP_DEFAULT_LON ) ,15 ) );
	var pan_zoom_widget = new MMPanZoomWidget ();
	mapviewer.addWidget ( pan_zoom_widget );
	markers = new Array();	
}

/**
 * sets up the mapviewer element and binds it to the chosen div element
 */
function initialiseDealershipMap (id) 
{  
	dealerMapViewer = MMFactory.createViewer( document.getElementById( id ) );
	dealerMapViewer.goToPosition( new MMLocation( new MMLatLon( MULTIMAP_DEFAULT_LAT, MULTIMAP_DEFAULT_LON ) ,15 ) );
	var pan_zoom_widget = new MMPanZoomWidget ();
	dealerMapViewer.addWidget ( pan_zoom_widget );
	markers = new Array();
}

function initialiseAmbiguousMap (id)
{
	ambiguousMap = MMFactory.createViewer( document.getElementById( id ) );
	ambiguousMap.goToPosition( new MMLocation( new MMLatLon( MULTIMAP_DEFAULT_LAT, MULTIMAP_DEFAULT_LON ) ,15 ) );
	markers = new Array();
}

/**
 * performs the search for dealerships according to user's location (which
 * can be either their postcode or a location name) and distance they're
 * prepared to travel. Query object is passed to multimap and the specified
 * callback method is invoked when we get a response. This method will be
 * responsible for updating the map object and populating the results table.
 */
function search (location, region, servicesarray)
{		
	cachedLocation = location;

	searcher = MMFactory.createSearchRequester(resultsLoaded);
	search = new MMSearch();
	search.data_source = MULTIMAP_CLIENT_KEY;	
	search.address = new MMAddress({ qs : location, country_code : region});
	
	search.radius_units = MULTIMAP_DISTANCE_UNIT;
	search.route_modes  = 'walking,driving';
	search.max_distance = Number(MULTIMAP_MAXIMUM_DISTANCE);
	search.min_distance = Number(MULTIMAP_MINIMUM_DISTANCE);
	search.count = Number(MULTIMAP_RESULTS_COUNT);
	search.start_index = Number(1);
	search.order_by_fields = 'driving_distance';
	search.order_by_order = 'asc';
	search.result_set_size = MULTIMAP_RESULTS_COUNT;
	search.filters = new Array();

	// Search through our array of Services selected
	for (i = 0; i < servicesarray.length; i++) {
		// Add each MMSearchFilter to the search.filters array
		// Add each 1st dimension of the array as the "field", "eq" (denoting equals) as the "operation" and the 2nd dimension of the array as the "value"
		search.filters.push( new MMSearchFilter( servicesarray[i][0], 'eq', servicesarray[i][1] ) );
	}

	searcher.search( search );
}

function searchAgain (location, region, servicesarray)
{	
	searcher = MMFactory.createSearchRequester(resultsLoaded);
	search = new MMSearch();
	search.data_source = MULTIMAP_CLIENT_KEY;
	
	var coords = new String(location).split(',');
	search.point = new MMLatLon(coords[0], coords[1]);
	search.address = new MMAddress({country_code : region});

	search.radius_units = MULTIMAP_DISTANCE_UNIT;
	search.route_modes  = 'walking,driving';
	search.max_distance = Number(MULTIMAP_MAXIMUM_DISTANCE);
	search.min_distance = Number(MULTIMAP_MINIMUM_DISTANCE);
	search.count = Number(MULTIMAP_RESULTS_COUNT);
	search.order_by_fields = 'driving_distance';
	search.order_by_order = 'asc';
	search.result_set_size = MULTIMAP_RESULTS_COUNT;
	search.filters = new Array();

	// Search through our array of Services selected
	for (i = 0; i < servicesarray.length; i++) {
		// Add each MMSearchFilter to the search.filters array
		// Add each 1st dimension of the array as the "field", "eq" (denoting equals) as the "operation" and the 2nd dimension of the array as the "value"
		search.filters.push( new MMSearchFilter( servicesarray[i][0], 'eq', servicesarray[i][1] ) );
	}
	
	searcher.search( search );
}

function clearMarkers ()
{
	mapviewer.removeAllOverlays();
	markers = new Array();
}

/**
 * callback method invoked from the search procedure, this function gets
 * called when we receive a response from MultiMap. This callback is
 * responsible for error checking and invoking the user's handleResults
 * function (which should contain the user's own specific results rendering
 * implementation).
 */ 
function resultsLoaded () 
{
	var s = searcher;

	// check for errors
	if ( searcher.error_code ) 
	{
		if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') 
		{
				$('#duplicate-place-names').show();
				processGeocodingErrors(searcher.result_set);
		} 
		else if (searcher.error_code == 'MM_GEOCODE_NO_MATCHES') 
		{
				alert("No matches could be found for your input address.");
				history.back();
		} 
		else 
		{
				alert(searcher.error_code + ': ' + searcher.error_explanation);
		}
		return;
	}

	// initialise the map
	$('#results-container').show();
	init();

	// call the custom results render
	reOrderResults(searcher.record_sets[0].records, cachedLocation, cachedLocation, false);	
	if (markers.length > 0) {	
		mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );	
	}
}

function addMarker (location, visibility, pinImage, content)
{
	var icon = new MMIcon( pinImage );
	icon.iconSize = new MMDimensions( 46, 42 );
	icon.iconAnchor = new MMPoint( 46, 42 );
	var marker = mapviewer.createMarker(location, {'icon': icon});
	marker.setVisibility(visibility);		
	marker.setInfoBoxContent(content);
	markers[markers.length] = marker;
}

function addHomeMarker (location, geocoding)
{
	
	if ( (geocode != null) && (geocode != "") ) {
		var coords = new String(geocode).split(",");	
		var icon = new MMIcon(MULTIMAP_ROOT+'_assets/presentation/location.gif');
		icon.iconSize = new MMDimensions( 16, 23 );
		icon.iconAnchor = new MMPoint( 16, 23 );
		var marker = mapviewer.createMarker(new MMLocation(new MMLatLon(coords[0], coords[1])), {'icon': icon});
		marker.setVisibility(true);	
		markers.push(marker);
		if (markers.length > 0) {
			mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );	
		}
		return;
	}
	
	if (geocoding) {
		if (region == "IM") {			
			// for Isle of Man don't use entered location, otherwise geocoding fails
			homeGeocoder.geocode(new MMAddress({country_code: region}));
		} else {
			homeGeocoder.geocode(new MMAddress({qs: location, country_code: region}));
		}
	}
	else
	{
		var coords = new String(location).split(",");
	
		var icon = new MMIcon(MULTIMAP_ROOT+'_assets/presentation/location.gif');
		icon.iconSize = new MMDimensions( 16, 23 );
		icon.iconAnchor = new MMPoint( 16, 23 );
		var marker = mapviewer.createMarker(new MMLocation(new MMLatLon(coords[0], coords[1])), {'icon': icon});
		marker.setVisibility(true);	
		markers.push(marker);
		if (markers.length > 0) {
			mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );
		}
	}
}

function handleHomeGeoCodingResponse() {	
	geocode_results = homeGeocoder.result_set;	
	var icon = new MMIcon(MULTIMAP_ROOT+'_assets/presentation/location.gif');
	icon.iconSize = new MMDimensions( 16, 23 );
	icon.iconAnchor = new MMPoint( 16, 23 );
	var marker = mapviewer.createMarker(new MMLocation(new MMLatLon(geocode_results[0].coords.lat, geocode_results[0].coords.lon)), {'icon': icon});
	marker.setVisibility(true);	
	markers.push(marker);		
	if (markers.length > 0) {
		mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );
	}
}