// JavaScript Document

<!-- 
//<![CDATA[
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( 'loading' );
    loadingStatus( false );
	document.getElementById('mapviewer').style.display = "none";

	errorCount = 0; 
	if(document.quoteFrm.startPoint.value != '')
		getQuote();
}

function loadingStatus( bool ) {
    // If we're loading values we want to disable the form elements
    // and display a spinning icon to show activity
    document.getElementById('qs1').disabled = bool;
    document.getElementById('qs2').disabled = bool;
    //document.getElementById('qs3').disabled = bool;
    //document.getElementById('qs4').disabled = bool;
    document.getElementById('country_code1').disabled = bool;
    document.getElementById('country_code2').disabled = bool;
    //document.getElementById('country_code3').disabled = bool;
    //document.getElementById('country_code4').disabled = bool;
    //document.getElementById('lang').disabled = bool;
    //document.getElementById('driving').disabled = bool;
    //document.getElementById('walking').disabled = bool;
    //document.getElementById('quickest').disabled = bool;
    //document.getElementById('shortest').disabled = bool;
    //document.getElementById('exclude_highways').disabled = bool;

    //document.getElementById('select1').disabled = bool;
    //document.getElementById('select2').disabled = bool;
    //document.getElementById('select3').disabled = bool;
    //document.getElementById('select4').disabled = bool;
    //document.getElementById('submitbtn').disabled = bool; 
    //document.getElementById('submitbtn1').disabled = bool;  
    //loading.style.display = bool ? 'block' : 'none';
}

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)
    //addLocation(3, locations)
    //addLocation(4, locations)

    loadingStatus( true );
    route = new MMRoute( locations );

    //var shortest = document.getElementById('shortest').checked;
	var shortest = true;
	if (shortest == true) {
        route.optimize_for = 'distance';
    } else {
        route.optimize_for = 'time';
    } 


    //var walking = document.getElementById('walking').checked;
	walking = false;
    //if (walking == true) {
    //    route.mode = 'walking';
    //} else {
        route.mode = 'driving'; 
    //} 

    //var exclude_highways = document.getElementById('exclude_highways').checked;
	var exclude_highways = false;
    //if (exclude_highways) {
    //    route.exclude = 'highways';
    //} else {
        route.exclude = ''; 
    //} 

    //var lang = document.getElementById('lang').value;
	var lang = 'en_gb';
    if (lang != '' ) { route.lang = lang; }
    route_finder.request(route);
}
   
function cleanUp () {
    /*
	var stepsContainer = document.getElementById('routeSteps');
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    stepsContainer.style.display = 'none';
	*/
    //mapviewer.removeAllOverlays();
    markers = new Array();
}

function resetData () {
    cleanMultipleMatches(1);
    cleanMultipleMatches(2);
    cleanMultipleMatches(3);
    cleanMultipleMatches(4);
    //document.getElementById('driving').checked = true;
    //document.getElementById('quickest').checked = true; 
    //document.getElementById('exclude_highways').checked = false; 
}
    
function addLocation(num, locations) {
    var qs = document.getElementById('qs' + num);
    var country_code = document.getElementById('country_code' + num);
    //var select =  document.getElementById('select' + 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) {
		/*
        if (route.error_code == 'MM_ROUTE_GEOCODING_ERRORS') 
		{
            processGeocodingErrors (route.geocoding_errors);
        } 
		else 
		{
            alert(route.error_code + ': ' + route.error_explanation);
        }
		*/
		errorCount++;
		GetMap();
    } else {
//		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) {

	//alert(route.distance.miles);
	if(!route)
		GetMap();
		
	calculateQuote(route.distance.miles);

	/*
    var curr_step = 1;
    var stages = route.stages; 
    var container = document.getElementById('routeSteps');

    var h2 = document.createElement('h2');
    h2.appendChild(document.createTextNode('Travel directions'));
    container.appendChild(h2);
    
    var summary = '';
    summary += 'Start: ' + stages[0].start_address;
    summary += '<br />End: ' + stages[stages.length - 1].end_address;
    summary += '<br />Total Distance: ' + route.distance.miles + ' mile(s)';
    summary += '<br />Estimated Total Time: ';
    if (route.duration.days > 0) { summary += route.duration.days + ' day(s) '; }
    if (route.duration.hours > 0) { summary += route.duration.hours + ' hour(s) '; }
    if (route.duration.minutes > 0) { summary += route.duration.minutes + ' minute(s) '; }
    var p = document.createElement('p');
    p.innerHTML = summary;
    container.appendChild(p);
    
    for (var count=0; count < stages.length; count++) {
    
        var stage_summary = '';
        stage_summary += '<strong>Stage ' + (count + 1) + '<' + '/strong>';
        stage_summary += '<br />Start: ' + stages[count].start_address;
        stage_summary += '<br />End: ' + stages[count].end_address;
        stage_summary += '<br />Stage Distance: ' + stages[count].distance.miles + ' mile(s)';
        stage_summary += '<br />Estimated Stage Time: ';
        if (stages[count].duration.days > 0) { stage_summary += stages[count].duration.days + ' day(s) '; }
        if (stages[count].duration.hours > 0) { stage_summary += stages[count].duration.hours + ' hour(s) '; }
        if (stages[count].duration.minutes > 0) { stage_summary += stages[count].duration.minutes + ' minute(s) '; }
        stage_summary += '<br />Summary: ' + stages[count].summary;
        var p = document.createElement('p');
        p.innerHTML = stage_summary;
        container.appendChild(p);
        
        var ol = document.createElement('ol');
        ol.id = 'stage_' + count;
        ol.start = curr_step;

        var steps = stages[count].steps;

        for (var stepCount=0; stepCount < steps.length; stepCount++) {
            var text = curr_step;
            var zindex = max_zindex - curr_step + 1;
            if (count == stages.length - 1 && stepCount  == steps.length - 1) {
                zindex = max_zindex; 
            }                
          
            var instruction = steps[stepCount].instruction;
            var roadname = steps[stepCount].road_name;
            var roadnumber = steps[stepCount].road_number; 

            if (roadname && roadnumber) {
                instruction += ' ' + roadname + ' (' + roadnumber + ') ';
            } else if (roadname) {
                instruction += ' ' + roadname + ' ';
            } else if (roadnumber) {
                instruction += ' ' + roadnumber + ' ';
            }
            
            var distance = '';                    
            if (steps[stepCount].distance.miles > 0) { distance += steps[stepCount].distance.miles + ' mile(s) '; }
            if (distance != '') { distance = ' - ' + distance };
            
            var li = document.createElement('li');
            li.innerHTML = instruction + distance;
            ol.appendChild(li);
            
            createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
            
            ++curr_step;
        }
        container.appendChild(ol);
    }            
    
    container.style.display = 'block'; 
    var copyright = '';
    if (route.copyright) {copyright += 'Copyright: ' + route.copyright; }
    if (route.disclaimer)  {copyright += '<br />Disclaimer:  <a href="' + route.disclaimer +'">' + route.disclaimer +'<' + '/a>'; }
    
    var p = document.createElement('p');
    p.innerHTML = copyright;
    container.appendChild(p);            
	*/
}

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;
		f = document.quoteFrm;
		map.GetDirections([f.startPoint.value+", UK", f.endPoint.value+", UK"], options);
		//alert(3);
		return false;
	}
	
	
	function getVEResponse(route)
	{
		/*
		if(!route)
		{
			document.quoteFrm.action = 'booking.php';
			document.quoteFrm.mappingServiceStatus.value = '0';
			document.quoteFrm.submit();
			return true;
		}
		*/
	 	//alert(route.Distance);
		calculateQuote(route.Distance)
		 
	 }

