var mapviewer, route_finder, route, loading;
var max_zindex = 1000;
function onLoad() {
	
	getQuoteClicked = true; 
	mapviewer = new MultimapViewer( document.getElementById('mapviewer'));
    mapviewer.goToPosition( new MMLocation( new MMLatLon( 42.3508, -71.0717 ) ,15 ) );
	
    var funcRef = resultsLoaded;
    route_finder = new MMRouteRequester(funcRef );

    loading = document.getElementById('loadingImage');
    loadingStatus(false);
	document.getElementById('mapviewer').style.display = "none";
	errorCount = 0; 
	//if(document.quoteFrm.startPoint.value != '')
	getQuote();
}

function loadingStatus(bool) {
    
    document.getElementById('qs1').disabled = bool;
    document.getElementById('qs2').disabled = bool;
    document.getElementById('country_code1').disabled = bool;
    document.getElementById('country_code2').disabled = bool;
	
	
}

function createStepMarker(location, instruction, text, zindex) {
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
}        

function callRoute () {
	cleanUp();
    var locations = new Array();
    addLocation(1, locations)
    addLocation(2, locations)
    loadingStatus( true );
	
    route = new MMRoute( locations );
	var shortest = true;
	if (shortest == true) {
        route.optimize_for = 'distance';
    } else {
        route.optimize_for = 'time';
    } 
	walking = false;
    route.mode = 'driving'; 
	var exclude_highways = false;
    route.exclude = ''; 
	var lang = 'en_gb';
    if (lang != '' ) { route.lang = lang; }
    route_finder.request(route);
}
   
function cleanUp () {
    markers = new Array();
}

function resetData () {
    cleanMultipleMatches(1);
    cleanMultipleMatches(2);
    cleanMultipleMatches(3);
    cleanMultipleMatches(4);
    
}
    
function addLocation(num, locations) {
    var qs = document.getElementById('qs' + num);
    var country_code = document.getElementById('country_code' + num);
	var select = false;
    var address = new MMAddress();
    
    if (select && select.options &&  select.options.length > 1) {
        var coords = select.options[select.selectedIndex].value.split(',');
        locations.push(new MMLocation(new MMLatLon(coords[0], coords[1])));
    } else {
    	if (qs.value != '') {
        	address.qs = qs.value;
        	address.country_code = country_code.value;
        }
        locations.push(new MMLocation(address));
    } 
}     
    
function cleanMultipleMatches(num) {
    var qs = document.getElementById('qs' + num);
    var select = document.getElementById('select' + num);
    var addr = document.getElementById('addr' + num);
    var matches = document.getElementById('matches' + num); 
   
    while (select.firstChild) {
        select.removeChild(select.firstChild);
    }
    qs.value = '';
    matches.style.display = 'none';
    addr.style.display = 'block'; 
}     

function resultsLoaded() {
	if (route.error_code) {
		
		alert('Invalid Area Post Code. Please enter valid area post code to get accurate online quotation');
		/*
        if (route.error_code == 'MM_ROUTE_GEOCODING_ERRORS') 
		{
            processGeocodingErrors (route.geocoding_errors);
        } 
		else 
		{
            alert(route.error_code + ': ' + route.error_explanation);
        }
		*/
		errorCount++;
		GetMap();
    } else {
		//alert('success first');
		//mapviewer.goToPosition( mapviewer.getAutoScaleLocation( route.bounds ) );
	    displayStages(route);

	for( var i = 0, l = route.polyLine.length; i < l; ++i ) {
          mapviewer.addOverlay(route.polyLine[i]);
        }
    }
    loadingStatus(false);
}


function displayStages(route){
	if(!route)
	{
		alert('msn maps call');
		GetMap();
	}
	
	calculateQuote(route.distance.miles);

}
function processGeocodingErrors (errors) {
    for (var i = 0; i < errors.length; i++) {
        if (errors[i].error_code == 'MM_GEOCODE_NO_MATCHES') {
            alert('No matching locations for Location ' + errors[i].input_id);
        } else if (errors[i].error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
            var select  = document.getElementById('select' + errors[i].input_id);

            for (var j = 0; j < errors[i].results.length; j++) {
                var displayName = errors[i].results[j].address.display_name;
                var point = errors[i].results[j].coords; 
                var option = document.createElement('option');
                option.value = point.lat + ',' +point.lon; 
                option.appendChild(document.createTextNode(displayName));
                select.appendChild(option);
                select.selectedIndex=0; 
            }
            
            document.getElementById('matches' + errors[i].input_id).style.display = 'block';
            document.getElementById('addr' + errors[i].input_id).style.display = 'none';
        }
    }
}

//MMAttachEvent( window, 'load', onLoad );
//]]> 
// -->


	//MSN Maps Code
	var map = null;
	function GetMap()
	{
		//alert(errorCount);
		//alert('using msn');
		//if(document.quoteFrm.startPoint.value == '')
			//return true;
		
		/*if(!window.VEMap)
		{
			document.quoteFrm.action = 'booking.php';
			document.quoteFrm.mappingServiceStatus.value = '0';
			document.quoteFrm.submit();
			return true;
		}*/
		
		// alert(document.getElementById('mapviewer'));

		map = new VEMap('mapviewer');

		map.LoadMap();

		map.ShowDisambiguationDialog(false);
		
		var options = new VERouteOptions();
		//options.RouteOptimize = VERouteOptimize.MinimizeDistance;
		options.DistanceUnit = VERouteDistanceUnit.Mile;
		options.ShowDisambiguation = false;
		options.RouteCallback = getVEResponse;
		var form = document.getElementById("startpoint").value;
		var to = document.getElementById("endpoint").value;
		map.GetDirections([form+", UK",to+", UK"], options);
		//alert(3);
		return false;
	}
	
	
	function getVEResponse(route)
	{
		
		if(!route)
		{
			document.getElementById("loadingImage").style.display="none";
			alert('The quote calculator is currently unavailable');
			return false;
		}
		else{
			calculateQuote(route.Distance);
		}
		//calculateQuote(route.Distance); 
	 }
