var mapviewer, searcher, loading, markers, search;
var funcRef = resultsLoaded;
var myInterval, myWait = 0;
// 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 loadMultimap() {
    if($("multimapResults")){		
		createMultimapContainers();
		// Construct Map Viewer and display default location:
		mapviewer = new MultimapViewer($("mapviewer"));
		
		if($("mapviewer")){
			$('mapviewer').style.display = "block";
		}
		
		myaddress = new MMAddress();
		myaddress.country_code = frmResults_country;
		myaddress.postal_code=frmResults_postalcode;
		myaddress.country=frmResults_country;
    	
		if(frmResults_postalcode.length > 0){			
			var mySearchResults = initSearch();
		}
	} 
}
   
function createMultimapContainers(){
	var recordListDiv, mapLoading, mapLoadingImage, mapViewer;
	
	recordListDiv = document.createElement("div");
	recordListDiv.id ="recordListDiv";
	
	mapViewer = document.createElement("div");
	mapViewer.id ="mapviewer";
	mapViewer.style.display = "none";
	
	mapLoading = document.createElement("div");
	mapLoading.id ="mapLoading";
	mapLoading.setAttribute("class", "clear");
	
	mapLoadingImage = document.createElement("img");
	mapLoadingImage.setAttribute("src", "/images/loading.gif");
	mapLoadingImage.setAttribute("alt", "Searching...");
	mapLoading.appendChild(mapLoadingImage);
	
	if($("multimapResults")){
		$("multimapResults").appendChild(mapViewer);
		$("multimapResults").appendChild(recordListDiv);
		$("multimapResults").appendChild(mapLoading);
	}
}
                            

function openInfoBox( type, target) {
    if( target.infoBoxOpened() ) {
        target.closeInfoBox();
    }
    else {
        target.openInfoBox( );
    }
}

function createMarker(location, display_name, num) {
    var marker = mapviewer.createMarker(location, {'text' : num});
    marker.setInfoBoxContent('<p>' + display_name + '<' + '/p>');
    return marker;
}
  
function initSearch () {
    cleanUp();
    searcher = new MMSearchRequester( funcRef );

    // Construct variables for use as starting location for search:    		

    search = new MMSearch(); 
    search.address = new MMAddress();
    
    search.address.postal_code=frmResults_postalcode;
    search.address.country=frmResults_postalcode;
    search.address.country_code = frmResults_country;
   
    // Set return fields and maximum number of records to return from search:

    search.return_fields = rfs;
    search.count = 10;
    
    search.max_distance = frmResults_max_distance;
    search.min_distance = 0;
    search.distance_units = "km";
    return searcher.search( search );
}

function cleanUp () {
    // Clean up the HTML containers
	if($("message")) {
    	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 ( ) {
    var container = document.getElementById('message');
    var recordContainer = document.getElementById('recordListDiv');
    // Results are now loaded, so re-enable form elements, and remove spinning icon:
	if($("mapLoading")){
		$("multimapResults").removeChild($("mapLoading"));
	}
    //loadingStatus( false );

    // 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;
        }
        
    }

    recordContainer.appendChild(el);
    //mapviewer.goToPosition(new MMLocation(myaddress));
    
	if ( results_returned > 0 ) {
		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  ('b');
    var myBreak = 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);
    
    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(myBreak);
    if (record.telephone.length > 0) {myDiv.appendChild(document.createTextNode("Tel: " + record.telephone))}

    return myDiv;

}

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("I'm sorry, your search has returned too many results for a location. Please try narrowing your search criteria."));
	}
	else if (err == 'MM_GEOCODE_NO_MATCHES') {
		myP.appendChild(document.createTextNode("I'm sorry, your search has returned no results. Please try widening your search criteria."));
	}
	else {
		myP.appendChild(document.createTextNode("I'm sorry, there seems to have been a problem with your search. Please try some different criteria."));
	}
	el.appendChild(myP);
}

function wait() {
	myWait += 1;
	if (myWait >= 20) {
		myInterval = window.clearInterval(myInterval);
		if ( markers.length > 0 ) {
			mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );
		}
	}
}
