<!-- 
//<![CDATA[

function get(id){
	return document.getElementById(id);
}
function toggle(id, id2){
	var box = document.getElementById(id);
	var box2 = document.getElementById(id2);
	if(box){
		if(box.style.display=='none'){
			box.style.display = 'inline';
		}else{
			box.style.display = 'none';
		}
	}
	if(box2){
		if(box2.style.display=='none'){
			box2.style.display = 'inline';
		}else{
			box2.style.display = 'none';
		}
	}
}

var pan_zoom_widget;
var small_pan_zoom_widget;
var small_zoom_widget;
var map_type_widget;
var location_widget;
var overview_widget;
var tools_widget;
var local_info_widget;
var container;

var mapviewer, searcher, loading, markers, search, pre_search;
var address_qs, country_code, address_select, max_distance, order_by_fields, order_by_order, count, start_index, return_fields, submitbtn, result_set_size;
var funcRef = resultsLoaded;
// Including the 'client_id' ensures that clicking on a result logs it as such within the reports:

var rfs = ['client_id', 'name', 'street', 'street_1', 'street_2', 'place', 'town', 'county', 'pc', 'lat', 'lon', 'telephone_aggregates', 'telephone_concrete', 'telephone_asphalt', 'sand_and_gravel', 'recycling', 'landfill', 'asphalt', 'contracting', 'crushed_rock', 'readymix', 'aboutsite', 'image', 'id'];

// ************ BEGIN WIDGET FUNCTIONS ***************

function addPanZoomWidget (outside) {
    //Add the Pan Zoom Widget
    if ( !outside ) {
        mapviewer.removeWidget ( pan_zoom_widget );
        mapviewer.removeWidget ( small_pan_zoom_widget );
        mapviewer.removeWidget ( small_zoom_widget );
        pan_zoom_widget = new MMPanZoomWidget ();
    } else {
        removeAllWidgets ();     
        pan_zoom_widget = new MMPanZoomWidget( new MMBox () ); 
        pan_zoom_widget.setContainer(container);
    }
    mapviewer.addWidget ( pan_zoom_widget );
}


function addMapTypeWidget (outside) {
    //Add the Small Pan Zoom Widget
    if ( !outside ) {
        mapviewer.removeWidget ( map_type_widget );
        map_type_widget = new MMMapTypeWidget ();
    } else {
        removeAllWidgets();
        map_type_widget = new MMMapTypeWidget ( undefined, new MMBox() );
        map_type_widget.setContainer ( container );
    }
    mapviewer.addWidget ( map_type_widget );
}

// ************ END WIDGET FUNCTIONS ***************


function onLoad() {
	// Load Map
	mapviewer = new MultimapViewer( document.getElementById( 'mapviewer' ) );
	
	mapviewer.goToPosition( new MMLocation( new MMLatLon( 51.897700,  -0.50350 ) ,16 ) );
	// Load Widget Container
	container = document.getElementById ('widgetcontainer');
	
	// Add an Event Handler to show info boxes when the markers are clicked
	//mapviewer.addEventHandler( 'click', defaultClick );
	address_qs = document.getElementById( 'address_qs' ); 
	address_select = document.getElementById( 'address_select' ); 
	country_code = document.getElementById( 'country_code' );
	max_distance = document.getElementById( 'max_distance' );
	order_by_fields = document.getElementById( 'order_by_fields' );  
	order_by_order = document.getElementById( 'order_by_order' );  
	count = document.getElementById( 'count' );  
	start_index = document.getElementById( 'start_index' );  
	result_set_size = document.getElementById( 'result_set_size' );   
	submitbtn = document.getElementById( 'submitbtn' ); 
	loading = document.getElementById( 'loading' );
	loadingStatus( false );
	
	// Add Widget(s)
	addMapTypeWidget();
	addPanZoomWidget();
	addMarker();
	
}

function openInfoBox(type, target, site_html) {
	document.getElementById('mapviewer').style.display = 'block';
	
	if( target.infoBoxOpened() ) {
		target.closeInfoBox();
	}
	
	else {
		target.openInfoBox();
	}
	
	// ******** HIDE RESULTS LIST ... *******
	document.getElementById('recordListDiv').style.display = 'none';
	
	// ******** SHOW SELECTED SITE DETAILS  *******
	document.getElementById('recordDetailsDiv').style.display = 'block';
	
	// ******** ... AND POPULATE SELECTED SITE DETAILS ******
	document.getElementById('recordDetailsDiv').innerHTML = site_html;
	
}

function backToResults() {
	// ******** AND HIDE SELECTED SITE DETAILS ******
	document.getElementById('recordDetailsDiv').style.display = 'none';

	// ******** SHOW RESULTS LIST  *******
	document.getElementById('recordListDiv').style.display = 'block';
}

function loadingStatus ( bool ) {
	// If we're loading values we want to disable the form elements
	// and display a spinning icon to show activity
	/*
	address_qs.disabled = bool;
	country_code.disabled = bool;
	address_select.disabled = bool;
	max_distance.disabled = bool;  
	order_by_fields.disabled = bool;  
	order_by_order.disabled = bool;  
	count.disabled = bool;
	start_index.disabled = bool;
	result_set_size.disabled = bool;
	submitbtn.disabled = bool;
	loading.style.display = bool ? 'block' : 'none';
	*/
}

function createMarker(location, display_name, num) {
	// Creates marker
	var marker = mapviewer.createMarker(location, {'text' : num});
	marker.setInfoBoxContent('<p>' + display_name + '<' + '/p>');
	return marker;
}

function initSearch () {
	// Hide the map
	document.getElementById('mapviewer').style.display='none';
	
	// Hide calculator buttons
	document.getElementById('calculatorButtons').style.display='none';
	
	// Hide site details if any
	document.getElementById('recordDetailsDiv').style.display='none';
	
	// ******** SHOW RESULTS LIST  *******
	document.getElementById('recordListDiv').style.display = 'block';

	cleanUp();
	searcher = new MMSearchRequester( funcRef );
	
	// ***** PERFORM PRODUCT FILTER SEARCH *******
	// If a product has been selected, filter the search by this
	if (document.getElementById('product').value != '') {
		search = new MMSearch( new MMSearchFilter(document.getElementById('product').value,'eq','yes')); 
	} else {
		search = new MMSearch();
	}
	search.return_fields = rfs;
	search.radius_units = 'miles';
	search.route_modes  = 'walking,driving'; 
    
// Activate the next line of code if you wish to configure the API to use data
// from one of your existing 'classic' Multimap services (such as XML Storefinder), 
// as described in the topic "Integration with Classic Multimap XML Products".  
// When doing so, please replace "[api_key]" with the appropriate service client name:
// search.data_source = 'mm.clients.[api_key]'



	if (address_select.options &&  address_select.options.length > 1) {
		var coords = address_select.options[address_select.selectedIndex].value.split(',');
		search.point = new MMLocation(new MMLatLon(coords[0], coords[1]));
	} else if (address_qs.value != '') {
		search.address = new MMAddress({ qs : address_qs.value, country_code : country_code.value});
	} else {
		search.point = mapviewer.getCurrentPosition(); 
	}
		
	if (max_distance.value != '') {
		search.max_distance = Number(max_distance.value);
	} 
	
	if (count.value != '') {
		search.count = Number(count.value);
	}    
	
	if (start_index.value != '') {
		search.start_index = Number(start_index.value);
	} 
	
	search.order_by_fields = order_by_fields.value;
	search.order_by_order = order_by_order.value;
	search.result_set_size = result_set_size.value;
	
	if (document.getElementById('address_qs').value != '') {
		loadingStatus( true );
		searcher.search( search );
	} else {
		alert('Please enter an address or post code');
		document.getElementById('address_qs').focus();
	}
}  


function cleanUp () {
	// Clean up the HTML containers
	var message = document.getElementById('message');
	
	while (message.firstChild) {
		message.removeChild(message.firstChild);
	}
	
	message.style.display = 'none';
	var record_list = document.getElementById('recordListDiv');
	
	while (record_list.firstChild) {
		record_list.removeChild(record_list.firstChild);
	}           
	 
	mapviewer.removeAllOverlays();
	
	markers = new Array(); 
}


function resultsLoaded ( ) {
	// Process search results
	var container = document.getElementById('recordListDiv');
	loadingStatus( false );
	
	if ( searcher.error_code ) {
		if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
			processGeocodingErrors(searcher.result_set);
		} else if (searcher.error_code == 'MM_GEOCODE_NO_MATCHES') {
			alert("No matches could be found for your input address.");      
		} else {
			alert(searcher.error_code + ': ' + searcher.error_explanation);
		}       
		return;
	} 
	
	var results_returned = 1;
	
	//  Create table and table header     
	var el = document.createElement ( 'table' );
	el.id = 'recordList';
	
	var tbody = document.createElement ( 'tbody' );
	el.appendChild ( tbody );
	
	var  start_index_value = 1;
	if  (search.start_index && Number (search.start_index) > 0 ) {
		start_index_value = Number (search.start_index);
	}
	
	var tr_first = document.createElement ( 'tr' );
	var ths = [ 
		document.createTextNode ( 'Location' ), 
		document.createTextNode ( 'Products' )
	]; 
	for ( i  = 0; i < ths.length; i++) {
		var th = document.createElement ( 'th' ); 
		th.appendChild( ths [ i ] );
		tr_first.appendChild ( th );
	}

	tbody.appendChild ( tr_first );
	


	// for each record set
	for ( var count=0, l = searcher.record_sets.length; count < l; count++ ) {
		
		// for each record
		if ( searcher.record_sets[count].error ) {
			var err =  '';
			if ( searcher.record_sets[count].error.error_explanation ) {
				err =  searcher.record_sets[count].error.error_explanation;
			} else {
				err =  'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
			}
			alert( err );
			return;  
		} 
	
		if ( searcher.record_sets[count].records ) {
			for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
				var record = searcher.record_sets[count].records[record_count];                  
				var tr = handleRecord(record, start_index_value + record_count); 
				tbody.appendChild ( tr );
			}
		} else {
			var total = searcher.record_sets[count].totalRecordCount; 
			el = document.createElement ('p');
			
			if ( total  > 0) {
				el.appendChild ( document.createTextNode( 'Total results found: ' + total ) );
			} else {
				el.appendChild ( document.createTextNode( 'No results returned' ) ); 
			}
			
			results_returned = 0;
		}
	}
	
	var message = document.createElement ( 'div' );
	message.id = 'message';
	message.appendChild (document.createTextNode('Our nearest sites to your location are listed below. For more details, and to view a map of the site location, please click on the site name.'));
	
	container.appendChild( message );                    
	container.appendChild( el );                    
	if ( results_returned == 1 ) {
		mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ),15); 
	}
}

function formatInt ( num, min_width ) {
	// Format Integer to specified width (adding leading zeros)
	var str = num.toString ();
	while ( str.length < min_width ) {
		str = '0' + str;
	} 
	return str;
}
  
function processGeocodingErrors (result_set) {
	
	for (var j = 0; j < result_set.length; j++) {
		var displayName = result_set[j].address.display_name;
		var point = result_set[j].coords; 
		var option = document.createElement('option');
		option.value = point.lat + ',' +point.lon; 
		option.appendChild(document.createTextNode(displayName));
		address_select.appendChild(option);
		address_select.selectedIndex=0; 
	}
	
	document.getElementById('address_matches').style.display = 'block';
	document.getElementById('address_text').style.display = 'none';
} 

function cleanMultipleMatches() {
	while (address_select.firstChild) {
		address_select.removeChild(address_select.firstChild);
	}
	address_qs.value = '';
	document.getElementById('address_matches').style.display = 'none';
	document.getElementById('address_text').style.display = 'block'; 
}



// ###### NEW FUNCTION FOR HALFEN ######## //

function addMarker() {
    mapviewer.removeAllOverlays(); 
    var pos = mapviewer.getCurrentPosition();  
    var marker = mapviewer.createMarker( pos, {'label': 'Default marker', 'text' : '1'} );
    var el = document.createElement('h1');
	var ad1 = document.createElement('p');
	var ad2 = document.createElement('p');
	var adTown = document.createElement('p');
	var adCounty = document.createElement('p');
	
	var infoBoxContentContent = document.createElement('div');
	
    el.appendChild ( document.createTextNode ('Halfen UK'));
	ad1.appendChild (document.createTextNode('Unit 31, Humphrys Rd'));
	ad2.appendChild (document.createTextNode('Woodside Est,'));
	adTown.appendChild (document.createTextNode('Dunstable,'));
	adCounty.appendChild (document.createTextNode('Bedfordshire. LU5 4TP'));
	
	infoBoxContentContent.appendChild(el);
	infoBoxContentContent.appendChild(ad1);
	infoBoxContentContent.appendChild(ad2);
	infoBoxContentContent.appendChild(adTown);
	infoBoxContentContent.appendChild(adCounty);
	
    marker.setInfoBoxContent(infoBoxContentContent);
}

function createMarker(location, number, mapcenter) {
    var icon = MM_DEFAULT_ICON.copy();
    var marker = mapviewer.createMarker(location, {'label' : 'Marker #' + number, 'icon' : icon, 'text' : number});
    var distance_miles =  mapviewer.getGreatCircleDistance( mapcenter, location).toFixed(2); 
    var distance_km =  mapviewer.getGreatCircleDistance( mapcenter, location, 'km' ).toFixed(2);  
    var html = '';  
    html += '<h1>Marker #' + number + ' was clicked<' + '/h1>';
    html += '<p>Distance from circle: ' + distance_miles + 'm (' + distance_km + 'km)<' + '/p>';
    marker.setInfoBoxContent(html);
}  


MMAttachEvent( window, 'load', onLoad );
//]]> 
// -->

