var mapviewer, marker, geocoder, addresses;
var route_finder, route, loading;
var max_zindex = 1000;
var dealerName;
var dealerFullAddress;
var latTo, lonTo;
var directions_from;

    // Create an array of MMAddress objects for geocoding
    addresses = new Array;

function onLoad() {


        var map_node = document.getElementById('map');
        if ( MMIsSupportedBrowser() ) {
            //Add the map 
            mapviewer = MMFactory.createViewer( document.getElementById( 'map' ) );
            mapviewer.addWidget( new MMPanZoomWidget() );
            mapviewer.addWidget( new MMMapTypeWidget() );
            //mapviewer.goToPosition( new MMAddress( { 'qs' : 'London', 'country_code' : 'GB' } ) , 14 );

            // Create the geocoder
            geocoder = new MMGeocoder( handleGeocodeResults );

            geocodePostCodes();
            
            // Construct the route requester with our callback function:
            var funcRef = resultsLoaded;
            route_finder = MMFactory.createRouteRequester( funcRef, mapviewer );
            
            loading = document.getElementById( 'loading' );
        } else {
            var ns = mapviewer_node.getElementsByTagName('noscript')[0];
            mapviewer_node.innerHTML = ns.innerHTML;
            return true;
        }

    

}

function geocodePostCodes() {

    if (addresses.length > 0)
        geocoder.geocode( addresses );
}

function handleGeocodeResults( result_set ) {
    // Clear any old overlays from the map
    mapviewer.removeAllOverlays();

    var markers = new Array;
    var addresses = result_set;

    // Iterate the addresses and create a marker for each one
    for (var i = 0, j = addresses.length; i < j; i++) {
        var result = addresses[i];
        for (var k = 0, l = result.length; k < l; k++) {
            if (result[k] && result[k].coords) {
                
                var icon = new MMIcon( '/kia3Assets/img/multimap/marker.png' );
                icon.iconSize = new MMDimensions( 50, 34 );
                icon.iconAnchor = new MMPoint( 16, 16 );

                marker = mapviewer.createMarker( result[k].coords, {'label': 'Customized marker', 'icon' : icon} );                
                
                marker.setInfoBoxContent( getInfoBoxHtml(i, result[k].coords.lat, result[k].coords.lon) );

                markers.push( marker );
            }
        }
    }

    if (markers.length > 0) {
    // Auto scale the map
    var auto_scale = mapviewer.getAutoScaleLocation( markers );

    // autoscale not always zoomed out enough so zoom out an extra factor just to make sure.
    auto_scale.zoom_factor = auto_scale.zoom_factor - 1;
    mapviewer.goToPosition( auto_scale );
    }
    else {
        // No markers.
        mapviewer.goToPosition(new MMAddress({ 'country_code': 'GB' }), 5);

        // show message
        document.getElementById("directionsResults").innerHTML = "<li>Sorry, there was a problem looking up this dealer's location. Please use the address details below.";
    }
}

//html markup for the info box displayed when marke is clicked
function getInfoBoxHtml(i, lat, lon){

    var html;
    html = '<div class="MMinfoboxaddress">';
    html += '<img style="margin-bottom: 10px;" src="/kia3Assets/img/multimap/logo.png" />';
    html += '<div><span class="MMrecordName">' + dealerName + '</span><br />';
    html += dealerFullAddress[i][0] + '<br /><br />';
    html += '<span class="tel"><strong>Phone:</strong> ' + dealerFullAddress[i][1] + '</span>';
    html += '<div class="links">';
    html += '<a href="#" onclick="getDirectionsFromInfoBox(' + lat + ',' + lon  + '); return false;">Get directions</a>';
    html += '<div id="directionsWrapper" class="directions" action="" method="post" style="display: none">';
    html += '<label for="infoboxDir1">';
    html += 'From<br/>';
    html += '<input class="txt" type="text" value="" id="txtFrom" /><br/>';
    html += '</label>';
    html += '<input id="btnDirectionsSubmit" type="image" alt="Submit" value="submit" src="/kia3Assets/img/multimap/go_button.gif" class="submit" />';
    html += '<input class="txt" type="hidden" value="" id="txtLat" />';
    html += '<input class="txt" type="hidden" value="" id="txtLon" />';
    html += '</div>';
    html += '<a href="#" onclick="zoomToLocation( ' +  lat + ',' + lon  + ' ); return false;">Go to this location</a>';
    html += '</div>';
    html += '</div>';
    return html;

}

//zoom in on specified latitude and longitude
function zoomToLocation (lat, lon) {
    mapviewer.goToPosition( new MMLocation( new MMLatLon(lat, lon), 17 ) );
}

function getDirectionsFromInfoBox ( lat, lon){

    //set global long and lat coords for use when there are multiple locations found
    latTo = lat;
    lonTo = lon;
    
    directionsFormWrapperDiv = document.getElementById( 'directionsWrapper' );
    
    if ( directionsFormWrapperDiv.style.display == 'none' ) {
        directionsFormWrapperDiv.style.display = 'block';
        
        var btnSubmit = document.getElementById( 'btnDirectionsSubmit' );
        //var directions_from = document.getElementById( 'directions_from' );
        btnSubmit.onclick = function() {
            directions_from = document.getElementById( 'txtFrom' ).value;
            callRoute(lat, lon, directions_from);
            return false;
        }
    } else {
        directionsFormWrapperDiv.style.display = 'none';
        directionsFormWrapperDiv.onsubmit = function() {
            return false;
        }
    }
}

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

// get directions
function callRoute (lat, lon, from) {
    cleanUp();
    
    var locations = new Array();

    locations.push(new MMAddress( { 'qs' : from, 'country_code' : 'GB' } ));
    //Add the endpoint last:    
    locations.push( new MMLocation(new MMLatLon(lat, lon)) );

    route = new MMRoute( locations );
        
    route_finder.request(route);
}

// Remove any existing route and directions, in preparation for displaying a new one:    
function cleanUp () {
    var stepsContainer = document.getElementById('directionsResults');
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    //stepsContainer.style.display = 'none';
    mapviewer.removeAllOverlays();
    markers = new Array();
}


//callback function for createRouteRequester
// handles geocode errors for rounting
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);
        }
    } else {
        // use getAutoScaleLocation to show the entire route on the map, with the route bounds:
        mapviewer.goToPosition( mapviewer.getAutoScaleLocation( route.bounds ) );
        displayStages(route);
        // Show the route on the map with PolyLines, by adding each polyline returned:
        for( var i = 0, l = route.polyLine.length; i < l; ++i ) {
          
          mapviewer.addOverlay(route.polyLine[i]);
        }
    }
}

//display routing stages
function displayStages(route) {
    var curr_step = 1;
    var stages = route.stages; 
    var container = document.getElementById('directionsResultsHolder');
   
    
    // The route will be returned in stages. Each stage goes from one specified 'location' to the next:
    for (var count=0; count < stages.length; count++) { 
        var ul = document.getElementById('directionsResults');

        var steps = stages[count].steps;
    
        // Now we will display each step instruction within this stage:
        for (var stepCount=0; stepCount < steps.length; stepCount++) {
            // Label the current marker with the step number:
            var text = curr_step;
            // Make the higher numbered step markers appear 'on top of' lower ones:
            var zindex = max_zindex - curr_step + 1;
            
            // Use 'S' as marker text if this is the first step of the entire route:
            if (count == 0 && stepCount  == 0) {
                text = 'S';
            }        
            // Use 'F' as marker text if this is the last step of the entire route:      
            if (count == stages.length - 1 && stepCount  == steps.length - 1) {
                text = 'F';
                zindex = max_zindex; 
           }                
            // Create a written 'instruction' using the roadname and/ or roadnumber:
            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 + ' ';
            }
            
            // Show the distance of this particular step:
            var distance = '';                    
            if (steps[stepCount].distance.miles > 0) { distance += steps[stepCount].distance.miles + ' mile(s) '; }
            if (distance != '') { distance = ' - ' + distance };
            
            var turndirection = steps[stepCount].turn_direction;
            var element = '<img class="routeImg" src="http://www.multimap.com/demos/turn_';
            element += turndirection;
            element += '.png" border = "0" />';
            element += '<span><strong>' + curr_step + '.&nbsp;</strong>' ; //+ steps[stepCount].instruction;
            if ( instruction ) {
                element += instruction + 'for <strong>' + steps[stepCount].distance.miles + '</strong> miles</span>';
            } else {
                element += '</span>';
            }            
            
            var li = document.createElement('li');
            li.innerHTML = element;
            li.setAttribute('class', 'MMresultRoot');
            ul.appendChild(li);
            
            // Create the step marker, using the instruction and marker text we previously created:
            createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
            
            ++curr_step;
        }
        //container.appendChild(ul);
    }            
    
    container.style.display = 'block'; 
             
}

//function to handle geocode errors for directions
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 anchor, title, div;
            div = document.createElement( 'div' );
            title = document.createElement( 'h3' );
            title.innerHTML = 'Multiple locations were found for: ' + directions_from;
		    title.className = 'MMalert';
            div.appendChild( title );
            for (var j = 0; j < errors[i].results.length; j++) {
                anchor = document.createElement( 'a' );
                anchor.href = '#';
                anchor.className = 'geoResult';
                anchor.innerHTML = errors[i].results[j].address.display_name;
                anchor.result = errors[i].results[j];
                var point = errors[i].results[j].coords; 
                anchor.onclick = 
                        function callRouteLatLon (lat, lon ) {
                            //cleanUp();
                            var locations = new Array();
                            locations.push( new MMLocation(new MMLatLon(point.lat, point.lon)) );
                            //Add the endpoint last:    
                            locations.push( new MMLocation(new MMLatLon(latTo, lonTo)) );
                            route = new MMRoute( locations );
                            route_finder.request(route);
                            closeGeocodingErrors();
                            return false;
                        }
                div.appendChild( anchor );
                
            }                        
            
        }
    }
    
    // make error elements visible
    var container  = document.getElementById('geoError'); 
    container.appendChild(div);
    container.style.display = 'block';       
    document.getElementById('geoClose').style.display = 'block';
    
}

// close the geocode errors display
function closeGeocodingErrors(){

    //hide error elements
    var container  = document.getElementById('geoError');     
    container.innerHTML = ''; 
    container.style.display = 'none';
    
    document.getElementById('geoClose').style.display = 'none';
    
    return false;
}

MMAttachEvent( window, 'load', onLoad );

