<!-- 
//<![CDATA[
var mapviewer, searcher, loading, markers, search, pre_search;
var address_qs, country_code, address_select, bounding_box, min_distance, max_distance, order_by_fields, order_by_order, count, start_index, filter1, filter2, filter3, 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', 'town', 'country', 'pc', 'telephone', 'lat', 'lon'];

function onLoad() {
    mapviewer = MMFactory.createViewer( document.getElementById( 'mapviewer' ) );
    mapviewer.goToPosition( new MMLocation( new MMLatLon( 51.518235, -0.111258 ) ,15 ) );
    $('mapviewer').hide();
    address_qs = document.getElementById('postalcode'); 
    radius = document.getElementById('radius'); 
    country_code = document.getElementById('mm_country_code');
    units = document.getElementById('mm_units');
    
    if (address_qs.value != ""){
        initSearch();
    }
    Event.observe('submitbtn',"click", function(){initSearch();});
    
    $('retailers').onsubmit = function(){
        initSearch();
        return false;
    }

    
}

function openInfoBox( type, target) {
    if( target.infoBoxOpened() ) {
        target.closeInfoBox();
    }
    else {
        target.openInfoBox( );
    }
}



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 () {

    cleanUp();
    searcher = MMFactory.createSearchRequester( funcRef );
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.radius_units = units;
    //search.route_modes  = 'walking,driving'; 
    search.max_distance = Number(radius.value);

    
    $('mapviewer').show();

    search.address = new MMAddress({ qs : address_qs.value, country_code : country_code.value});
 
        
    searcher.search( search );
}  

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');

    // If an error code has been produced, display the explanation:
    if ( searcher.error_code ) {
        var err =  '';
        if ( searcher.error_explanation ) {
            err =  searcher.error_explanation;
        } else {
		    handleError(searcher.error_code, container)
        }

	    document.getElementById('mapviewer').style.display = "none";
	
        return;
    } 

    var results_returned = 1;
    
       var el = document.createElement ( 'ol' );
    el.id = 'recordList';
    var  start_index_value = 1;      
     
    // Loop through each record set:
    for ( var count=0, l = searcher.record_sets.length; count < l; count++ ) {
        
        // If an error was returned for the record set, display details and return:
        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 not, check to see if individual records have been returned:
        if ( searcher.record_sets[count].records ) {
            // Loop through each record in the record set, and add it to the list below the map,
            //  and populate the infobox text:           
            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 anchor = handleRecord(record, start_index_value + record_count);
                var li = document.createElement('li');
                li.appendChild(anchor);
                el.appendChild ( li );
            }
            
        } else {
            // No records have been returned. If a record count has been returned, display it,
            // otherwise display a message noting that no records were returned by the search:        
            var total = searcher.record_sets[count].totalRecordCount; 
            el = document.createElement ('p');
            if ( total  > 0) {
                el.appendChild ( document.createTextNode( 'Total results found: ' + total ) );
            } else {
		    handleError('MM_GEOCODE_NO_MATCHES', container)
            }  
            results_returned = 0;
        }
        
    }
    container.appendChild( el );                    
    if ( results_returned == 1 ) {
        mapviewer.resize();
        mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) ); 
     }  
        
}
function handleRecord ( record, num ) {
    // Create marker text for the infobox for this record:    
    var markerText = "<p><b>Result #" + num + "</b></p>";
    markerText += "<h2>" + record.name + "</h2>"; 
    markerText += '<p>';  

    if (record.street.length > 0) {markerText += record.street += ", ";}
    if (record.town.length > 0) {markerText += record.town += ", ";}
    if (record.pc.length > 0) {markerText += record.pc;}
    markerText += "<br />";
    if (record.telephone.length > 0) {markerText += "Tel: " + record.telephone;}
    
    markerText += '<' + '/p>';
    
    if ( record.distance ) {
        markerText += '<p>Distance: ' + record.distance.km + ' km, ' + record.distance.miles + ' mi<' + '/p>'
    }
    if ( record.point ) {
        var marker = createMarker( record.point, markerText, num);
        markers.push(marker);
    } 
    // Show the name in our records list. When the name is clicked, open  our info box:  
    var myDiv = document.createElement ('div');
    var myAnchor = document.createElement ( 'a' );
    var myBold = document.createElement  ('strong');
    var myBreak = document.createElement  ('br');
    var myBreakTel = document.createElement  ('br');

    myAnchor.href = '#';
    myAnchor.record_id = record.id;
    myAnchor.onclick = function () { openInfoBox ( 'click', marker ); return false; };
    myBold.appendChild(document.createTextNode(record.name));
    
    myAnchor.appendChild(myBold);
    myDiv.appendChild(myAnchor);
    
    myDiv.appendChild(myBreak);
    if (record.street.length > 0) {myDiv.appendChild(document.createTextNode(record.street));}
    if (record.town.length > 0) {myDiv.appendChild(document.createTextNode(record.town));}
    if (record.pc.length > 0) {myDiv.appendChild(document.createTextNode(record.pc));}
    myDiv.appendChild(myBreakTel);
    if (record.telephone.length > 0) {myDiv.appendChild(document.createTextNode("Tel: " + record.telephone))}

    return myDiv;

}


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'; 
}

function handleError(err, el) {
	var myP = document.createElement("p");
	var myP2 = document.createElement("p");
	var myAnchor = document.createElement("a");
	
	if (err == 'MM_GEOCODE_MULTIPLE_MATCHES') {
		myP.appendChild(document.createTextNode($('txtError1').value));
	}
	else if (err == 'MM_GEOCODE_NO_MATCHES') {
		myP.appendChild(document.createTextNode($('txtError2').value));
	}
	else {
		myP.appendChild(document.createTextNode($('txtError3').value));
	}
	el.appendChild(myP);
}


MMAttachEvent( window, 'load', onLoad );
//]]> 
// -->

