<!-- 
//<![CDATA[
var geocoder;
var geocode_status, message, results_panel;
var results = new Array();
var markers = new Array();
var max_results = 5;
var mapviewer, searcher, loading, search, pre_search, route_finder, route;
var address_qs, country_code, bounding_box, min_distance, max_distance, order_by_fields, order_by_order, count, start_index, return_fields, submitbtn, result_set_size, opening_hours, openinghours_widget, widget_available;
var funcRef = resultsLoaded;
var max_zindex = 1000;
var local_info_widget;
var widget_available;
var recordForStoreDetail;   // this variable will hold the no.of stores found
var VpostcodeSatNav;     //this variable pass to '<p>' to display postcode for SatNav
// Including the 'client_id' ensures that clicking on a result logs it as such within the reports:
var rfs = ['client_id', 'name', 'street', 'town','pc', 'lat', 'lon', 'telephone', 'openinghoursmon', 'openinghourstue', 'openinghourswed', 'openinghoursthu', 'openinghoursfri', 'openinghourssat', 'openinghourssun'];function onLoad() {
    mapviewer = MMFactory.createViewer( document.getElementById( 'mapviewer' ) );
    mapviewer.goToPosition( new MMLocation( new MMLatLon( 52.66543,-1.28881 ) ,10 ) );
    // Add an Event Handler to show info boxes when the markers are clicked
    //mapviewer.addEventHandler( 'click', defaultClick );
    address_qs = document.getElementById( 'txtLocation' ); 
    address_qs.focus();
    submitbtn = document.getElementById( 'quicksearchbtn' );
    geocode_status = document.getElementById('geocodestatus');
    message = document.getElementById('message');
    results_panel = document.getElementById('resultspanel');
    loadingStatus( false );
    
    ShowHideDivs(false);
    
    // Set widget availability:
    widget_available = false;
    //getBranchList();
    
    //Create a new geocoder object specifying a callback function
    //geocoder = MMFactory.createGeocoder(processResults);
}
function ShowHideDivs(bool)
{
    if(bool)
    {
        document.getElementById('recordList').style.display = 'block';
        document.getElementById('ourBranchesHeading').style.display = 'block';
        document.getElementById('recordListWrapper').style.display = 'block';
        document.getElementById('storeDetail').style.display = 'block';
        document.getElementById('Panel1').style.display = 'none';
    }
    else
    {
        document.getElementById('recordList').style.display = 'none';
        document.getElementById('ourBranchesHeading').style.display = 'none';
        document.getElementById('recordListWrapper').style.display = 'none';
        document.getElementById('storeDetail').style.display = 'none';
        document.getElementById('Panel1').style.display = 'none';
    }
}
 // Create the variable that will contain the values of check boxes
 var checkBoxValues = "";
        
function GetCheckBoxes(containerDiv)
    {
        if(!containerDiv)
        {
            return '';
        }
      
        if(containerDiv && containerDiv.hasChildNodes()) {
        
            // Get the elements within the container elements
            var children = containerDiv.childNodes;
            
            // Loop through all the elements within the element
            for(var i = 0; i < children.length; i++) {
            
                // If the element is a check box
                if(children[i].type == "checkbox") {
                
                    // If the check box is checked
                    if(children[i].checked) {
                        // Concatenate the value
                        checkBoxValues += children[i].value + ",";
                    }
                }
                else
                {
                    if(children[i].hasChildNodes())
                    {
                        GetCheckBoxes(children[i]);
                    }
                }
            }
            
            // strip off the last comma to make it play nicely
            //if(checkBoxValues.length > 0){
                //checkBoxValues = checkBoxValues.substring(0,checkBoxValues.length-1 );
            //}
        }
        
        //return checkBoxValues;
    }
    
    String.prototype.endsWith = function(str) 
    {
        return (this.match(str+"$")==str);
    }
    
    function getCheckBox()
    {
    }
function openInfoBox( type, target) 
{
    if( target.infoBoxOpened() ) {
        target.closeInfoBox();
    }
    else {
        target.openInfoBox( );
    }
}
function loadingStatus ( bool ) 
{
    // If we're loading values we want to disable the form elements
    // and display a spinning icon to show activity
    //address_qs.disabled = bool;
    //submitbtn.disabled = bool;
}
function createMarker(location, display_name, num) 
{
    // Creates marker
    var marker = mapviewer.createMarker(location, {'text' : num});
    marker.setInfoBoxContent('<p>' + display_name + '<' + '/p>');
    return marker;
}
function createStepMarker(location, instruction, text, zindex) 
{
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
} 
function PerformSearch(addressValue)
{
    route = null;
    // inform the user a geocode is occurring
    updateGeocodeStatus('startGeocode');
    
    
    ShowHideRoutes(false);
    
    cleanUp();
    searcher = MMFactory.createSearchRequester( funcRef );
    search = new MMSearch(); 
    search.logic = 'OR';
    search.return_fields = rfs;
    search.count = 5;
    search.max_distance = Number('300');
    search.min_distance = Number('');
    search.radius_units = 'miles';
    search.route_modes  = 'walking,driving'; 
    
// Activate the next line of code if you wish to configure the API to use data
// from one of your existing 'classic' Multimap services (such as XML Storefinder), 
// as described in the topic "Integration with Classic Multimap XML Products".  
// When doing so, please replace "[api_key]" with the appropriate service client name:
// search.data_source = 'mm.clients.[api_key]'
        
    if (addressValue != '') 
    {
        search.address = new MMAddress({qs : addressValue.display_name, country_code : 'GB'});
    }
   
        search.filters = new Array();
        search.filters.push( new MMSearchFilter('BusinessArea', 'eq', 'Travel' ));
       
    loadingStatus( true );
    searcher.search( search );
    
    
    //NA - assign search location to Plan route text box
    var searchBox = document.getElementById('TextBox1');
    searchBox.value = addressValue.display_name;
}
 function updateGeocodeStatus( type ) {
    if( type == 'startGeocode' ) {
        // if the geocode is starting, disable the form inputs and inform the user
        geocode_status.style.display = 'block';
        disableFields(true);
    } else {
        // if the geocode is ending, enable the form inputs and inform the user
        geocode_status.style.display = 'none';
        disableFields(false);
    }
}
function disableFields( bool ) {
    // disable the user input fields
    address_qs.disabled = bool; 
    submitbtn.disabled = bool;  
}
 
 function processResults() {
    // callback function registered with the geocoder to handle geocoding results
    
    // inform the user a geocode has finished
    updateGeocodeStatus('endGeocode');
    // if an error occurred, inform the user
    if (geocoder.error_code && geocoder.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
        message.innerHTML = 'We are sorry but we could find no matches for your query. Please try again.';
        return false;
    }
    results = geocoder.result_set;
    var ol = document.createElement('ol');
    
    ShowHideDivs(false);
     
    if(results.length == 1)
    {
        PerformSearch(results[0].address);    
        return;   
    }
    
    //loop through the result set
    for (var count=0; count < results.length; count++) {
        var address = results[count].address;
        var li = document.createElement('li');
        //add a link for each result
        var anchor = document.createElement('a');
        anchor.href = "#";
        anchor.result_count = count;
        anchor.address = address;
        anchor.onclick = function () { PerformSearch(this.address);    return false; };
        anchor.appendChild(document.createTextNode(address.display_name));
        li.appendChild(anchor);
        ol.appendChild(li);
        //add a marker for each result
        var marker = mapviewer.createMarker(results[count], { 'label' : address.display_name, 'text' : (count+1) });
        //add an infobox for each result
        marker.setInfoBoxContent('<p>' + address.display_name + '<' + '/p>');
        markers.push(marker);
    }
        if    (results.length > 1)
        {
            var p = document.createElement('p');
            p.innerHTML = 'We have found more than one match for your query. Please narrow down your search by choosing one of the options below or be more specific with your search terms (for example try searching for "Burton Upon Trent" instead of "Burton"';
            results_panel.appendChild(p);
        }
    results_panel.appendChild(ol);
    results_panel.style.display = 'block';
    //if there were multiple matches, display all the results
    if (geocoder.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
        var location = mapviewer.getAutoScaleLocation( markers );
        mapviewer.goToPosition( location ); 
        
        
    //otherwise show the only match at the optimal zoom factor
    } else {
        mapviewer.goToPosition( results[0] );
    }
}
 function moveToResult (count) {
    //move the map specified location and open the info box
    mapviewer.goToPosition(results[count]);
    markers[count].openInfoBox();
}

 
function initSearch () 
{
    if(address_qs.value == '')
    {
        alert('Please enter location or post code');
        return false;
    }
    // inform the user a geocode is occurring
    updateGeocodeStatus('startGeocode');

    var storeDiv = document.getElementById('storeDetail');
    while (storeDiv.firstChild) 
    {
        storeDiv.removeChild(storeDiv.firstChild);
    }
    //Create a new geocoder object specifying a callback function
    geocoder = MMFactory.createGeocoder(processResults);
    cleanUp();
    var fields = {'qs' : address_qs.value, 'country_code' : 'GB'}; 
        
    var address = new MMAddress();
    address.country_code = fields.country_code;
    address.qs = fields.qs;
    
    // clear any existing items from previous geocoding requests
    cleanUp();
    // perform the geocode
    geocoder.count = 5;
    geocoder.geocode(address);
}  
function callRoute () 
{
    cleanUp();
    // inform the user a geocode is occurring
    updateGeocodeStatus('startGeocode');
    isPlanRouteButtonClicked = true;
    // Add each of the selected waypoints. The addLocation function will only add
    //  a location if a selection was made from the corresponding select box:
    var locations = new Array();
    route_finder = MMFactory.createRouteRequester(funcRef, mapviewer); 
    //addLocation(1, locations)
    //Add the endpoint last:
    //addLocation(2, locations)
    ShowHideDivs(true);
    
    var textboxvalue =  document.getElementById('TextBox1').value;
    
    if (textboxvalue != '') {
            var address = new MMAddress();
            address.qs = textboxvalue;
            address.country_code = 'GB';
            locations.push(new MMLocation(address));
        }
    
    var select =  document.getElementById('select2');
    // Check the value of the dropdown, and add a location if applicable:
    if (select.options[select.selectedIndex].value) {
         if (select.options[select.selectedIndex].value != '') {
            var address = new MMAddress();
            address.qs = select.options[select.selectedIndex].value;
            address.country_code = 'GB';
            locations.push(new MMLocation(address));
        }
    } 
   // loadingStatus( true );
    route = new MMRoute( locations );
    route_finder.request(route);
   // mapviewer.goToPosition( new MMLocation( new MMAddress( { qs: select.options[select.selectedIndex].value } ), 50 ) );
}

function ShowHideRoutes(bool)
{
    var stepsContainer = document.getElementById('routeSteps');
    
    if(bool)
    {
        stepsContainer.style.display = 'block';
    }
    else
    {
        while (stepsContainer.firstChild) {
            stepsContainer.removeChild(stepsContainer.firstChild);
        }
        stepsContainer.style.display = 'none';
    }
    
}
function cleanUp () 
{
  // Clean up the HTML containers
            message.innerHTML = '';
            while (results_panel.firstChild) {
                results_panel.removeChild(results_panel.firstChild);
            }
            //remove any markers
            mapviewer.removeAllOverlays();
            markers = new Array();

    // Clean up the HTML containers
    var stepsContainer = document.getElementById('routeSteps');
    var record_list = document.getElementById('recordList');
    while (record_list.firstChild) {
        record_list.removeChild(record_list.firstChild);
    }            
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    stepsContainer.style.display = 'none';
    mapviewer.removeAllOverlays();
//   markers = new Array(); 
}
function addLocation(num, locations) 
{
    var select =  document.getElementById('select2');
    // Check the value of the dropdown, and add a location if applicable:
    if (select.options[select.selectedIndex].value) {
       // var coords = select.options[select.selectedIndex].value.split(',');
        locations.push(new MMLocation(new MMAddress(select.options[select.selectedIndex].value)));
    } 
}
function resultsLoaded () 
{
    // inform the user a geocode has finished
    updateGeocodeStatus('endGeocode');
    ShowHideDivs(true);
    // Process search results
    // add the pan zoom widget
    var bottomLeft = new MMBox(10, 10, undefined, undefined);
    var pan_zoom_widget = new MMPanZoomWidget (bottomLeft);
    mapviewer.addWidget(pan_zoom_widget);
    
    var container = document.getElementById('recordList');
    loadingStatus( false );
    if ( searcher.error_code ) 
    {
        if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
            processGeocodingErrors(searcher.result_set);
        } else if (searcher.error_code == 'MM_GEOCODE_NO_MATCHES') {
            alert("No matches could be found for your input address.");      
        } else {
            alert(searcher.error_code + ': ' + searcher.error_explanation);
        }       
        return;
    } 
    
    if (route)
    {
        if (route.error_code) {
            // Display an error message, if applicable:
            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]);
            }
       }
    }
    
    var  start_index_value = 1;
    var results_returned = 1;
    
    var el = document.createElement ( 'ol' );
    el.id = 'recordLists';
    
    markers = new Array();
        
    // 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:           
           
            var counting=0; // this variable helps to get 1st address
            var nearestAddress = '';
            
            var select =  document.getElementById('select2');
            var i;
            for(i=select.options.length-1;i>=0;i--)
            {
                select.remove(i);
            }
            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];     
                
                //NA -  will use this record detail to display 1st nearest store detail in 'storeDetailDiv'            
                recordForStoreDetail = record; 
                
                var anchor = handleRecord(record, start_index_value + record_count);
                var reccount = start_index_value + record_count;
                
                //if (reccount != 1)
                //{
                    var li = document.createElement('li');
                   // li.style.background = 'url(/images/storeIcon'+reccount+'.gif) no-repeat 0px 0px;';
                       li.className = reccount;
                    li.style.background = 'url(/images/storeIcon'+reccount+'.gif) no-repeat';
                    li.style.listStyle = 'none';
                    li.style.padding = '5px 0px 1px 45px';
                    //style="width: 850px; height: 500px"
                    
                    //NA - this set color alternatively for 'li'
                   /* if(reccount % 2 == 0) 
                        {
                        li.style.backgroundColor = '#DDDDFF';
                        }
                   */ 
                        if (counting == 0){
                           nearestAddress = record.street + ', ' + record.town + ', ' + record.pc + '<br/> Tel: ' + record.telephone;
                           counting++;  
                           storeDetail();
                        }
                    anchor.setAttribute('title','click for more details');    
                    li.appendChild(anchor);
                    if (li.className > 1)
                    {
                            el.appendChild (li);
                      }
               //}
               /* else
                {
                    var nearestStoreSpan = document.getElementById('_nearestStoreSpan');
                    if (nearestStoreSpan){
                            nearestStoreSpan.appendChild(anchor);
                            }
                } */    
                // add it to the second select box as well
                var option = document.createElement('option');
                option.text = record.name + ', ' + record.street;
                option.value = record.pc;
                select.options.add(option);
                }
            }
        } 
     
    if (container != null)
    {    
        container.appendChild(el);                    
    }
    // circle the start point
    circleStartLocation();   
    
    
    if (route)
    {
        ShowHideRoutes(true);
    }
    else
    {
        ShowHideRoutes(false);
    }
}
//NA - this function is pulling detail for 'storeDetailDiv' and dynamically selecting the store as per search
function storeDetail(){
        // Create marker text for the infobox for this record
        var markerText = ''; 
        var storeDetailContainer = document.getElementById('storeDetail');
        var openHours = '';
        var searchLocation;
        
        if (address_qs != '')
            {
            searchLocation =  address_qs.value.toUpperCase();
            }
        else
            {
            searchLocation = "search location";
            }
        markerText += '<h2>Your nearest travel store is:</h2>';  
        for (i = 1, j = 0; i < rfs.length; i++){
            if (recordForStoreDetail[rfs[i]]){
                if (i == 2){
                    if (j > 0)
                        markerText = '<div id="storeIcon"><img src="/images/storeIcon1.png" alt="nearest store" style="float:left;margin-top:0px;" /></div><strong>' + markerText + '<' + '/strong>';
                }
                else if (i == 7){
                    if (j > 0)
                        markerText+= '<br /><strong>Telephone <' + '/strong>' + '<br />';
                }
          /*      else if (i == 8){
                    if (j > 0)
                        markerText+= '<br /><br /><strong>Opening Hours <' + '/strong>' + '<br />';
                }
                else{
                    if (j > 0)
                        markerText += '<br />';
                }*/
                
               
                if (i >= 8 && i <= 14){
                    //  markerText += recordForStoreDetail[rfs[i]];
                      if(i = 8)
                        openHours += "Mon: "+ recordForStoreDetail[rfs[i]] + '<br/>';
                      if(i = 9)
                        openHours += "Tue: "+ recordForStoreDetail[rfs[i]] + '<br/>';
                      if(i = 10)
                        openHours += "Wed: "+ recordForStoreDetail[rfs[i]] + '<br/>';
                      if(i = 11)
                        openHours += "Thu: "+ recordForStoreDetail[rfs[i]] + '<br/>';                                        
                      if(i = 12)
                        openHours += "Fri: "+ recordForStoreDetail[rfs[i]] + '<br/>';                                        
                      if(i = 13)
                        openHours += "Sat: "+ recordForStoreDetail[rfs[i]] + '<br/>';
                      if(i = 14)
                        openHours += "Sun: "+ recordForStoreDetail[rfs[i]] + '<br/>'; 
                }
                else{
                    markerText += recordForStoreDetail[rfs[i]] + '<br/>';
                }
                j++;
            }
        }
        markerText += '</p>';
        /*markerText += "<p id='pOpenHours'>"; */
        markerText += "<p>"; 
        markerText+= '<strong>Opening Hours </strong><br />';
        markerText += openHours ;
        markerText += '</p>'; 
                
        markerText += '<p><strong>Distance from '+  searchLocation +'</strong> <br/>' + recordForStoreDetail.distance.miles + ' miles';
        /*if (VpostcodeSatNav !='') {
            markerText += '<br/><br/><strong>Postcode for SatNav</strong><br> ' + VpostcodeSatNav.toUpperCase() ;
        }*/
        /*markerText += "<hr><p id='pSearchAgain'><b><a href='/locations/' title='Search again'>Search again</a></b></p>"*/
        markerText += '<p><strong><a href="#" onclick="addLocalInfoWidget( undefined, undefined, undefined, false ); return false;">Show/Hide local info.</a></strong></p>'
        /*markerText += '<p><b><a id="planYourRoute" href="#PlanRoute" title="Plan your route">Plan your route</a></b></p>'*/
       // markerText += '<b><a id="printRoute" href="javascript:window.print();" title="Print">Print</a></b><br/>'
       // markerText += '<b><a id="printerLink" href="javascript:printerFriendly();" title="Print Friendly">Printer Friendly</a></b>'
       
        storeDetailContainer.innerHTML+= markerText;
       // document.getElementById('printRoute').style.display ='none';
     //   document.getElementById('printerLink').style.display ='none';
        
        //NA - assign search location to Plan route text box
        //var searchBox = document.getElementById('ctl00_cphContent_TextBox1');
        //searchBox.value = searchLocation;
}
function displayStages(route) 
{
        var storeDiv = document.getElementById('storeDetail');
        while (storeDiv.firstChild) 
    {
        storeDiv.removeChild(storeDiv.firstChild);
    }
   // document.getElementById('storeDetailDiv').style.display = 'none'; 
    var curr_step = 1;
    var stages = route.stages; 
    var container = document.getElementById('routeSteps');
    //var h1 = document.createElement('h1');
    //h1.appendChild(document.createTextNode('Travel directions'));
    //container.appendChild(h1);
    
    var printerLink = document.createElement('a');
        printerLink.id = 'printerLink';
        printerLink.href = 'javascript:printerFriendly();';
        printerLink.title = 'printer friendly';
 
        var printerIcon = document.createElement('img');
        printerIcon.title = 'printer friendly'; 
        printerIcon.src = '/images/printer.jpg';
        printerIcon.width = '15';
        printerIcon.height = '15';
        printerLink.appendChild(document.createTextNode('printer friendly '));
        printerLink.style.fontWeight = 'bold';
        printerLink.appendChild(printerIcon);
    container.appendChild(printerLink);
   
    
     
    var summary = '';
    // Show the total route distance in miles:
    summary += '<br /><b>Total Distance:</b> ' + route.distance.miles + ' mile(s)';
    // Show the total duration of trip. Note that we display the days, hours, and minutes by
    //  accessing each property: 
    summary += '<br /><b>Estimated Total Time:</b>';
    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) '; }
    container.appendChild(document.createElement('br'));
    var p = document.createElement('p');
    p.innerHTML = summary;
    container.appendChild(p);
    container.appendChild(document.createElement('hr'));
    
    // 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++) 
    {
        // Show some summary information about each stage:
        var stage_summary = '';
//        The below code gave a title and summary of the steps. In theory, we should only have one.
//        stage_summary += '<strong>Stage ' + (count + 1) + '<' + '/strong>';
//        // Show the stage distance, in miles:
//        stage_summary += '<br />Stage Distance: ' + stages[count].distance.miles + ' mile(s)';
//        // Show the stage duration, in days, hours and minutes:
//        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) '; }
        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;
    
        // 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 li = document.createElement('li');
            li.innerHTML = instruction + distance;
            ol.appendChild(li);
            ol.style.paddingLeft = '50px';
            
            // 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(ol);
    }      
    container.appendChild(document.createElement('hr'));      
    container.style.display = 'block'; 
    
    // Add copyright and disclaimer, as required:
    var copyright = '';
    if (route.copyright) {copyright += '<br/>Copyright: ' + route.copyright; }
    if (route.disclaimer)  {copyright += '<br />Disclaimer:  <a href="' + route.disclaimer +'">' + route.disclaimer +'<' + '/a><br/>'; }
    
    var p = document.createElement('p');
    p.innerHTML = copyright;
    container.appendChild(p);  
    
    container.innerHTML = '<p><h1>Travel directions</h1>' + container.innerHTML + '</p>';
}
function autoScale()
{
    mapviewer.goToPosition (mapviewer.getAutoScaleLocation(markers));
}
var yesNo; //yesNo variable will help to switch map view, first search, then show route stages and finally show last step in printer friendly page.
function circleStartLocation(location)
{       
    if (!location){
        if (search.address)
        {
            geocoder = new MMGeocoder(startLocationResult);
            geocoder.geocode(search.address);
            return;
        }
        else if (search.point)
        {
            location = new MMLocation(new MMLatLon(search.point.coords.lat, search.point.coords.lon));
        }
    }
    var icon = new MMIcon( '/images/red-circle.png' );
    icon.iconSize = new MMDimensions(32, 32);
    var marker = mapviewer.createMarker(location, {'icon' : icon});
    markers.push(marker);
    
    //do autoscale only if map is searched first time
    if (yesNo== undefined || yesNo == true) 
        {
         autoScale();
         yesNo = false;
        }
}
function startLocationResult()
{
    if (geocoder.result_set.length > 0)
    {
        var coords = geocoder.result_set[0].coords;
        circleStartLocation(new MMLocation(new MMLatLon(coords.lat, coords.lon)));
        mapviewer.goToPosition (mapviewer.getAutoScaleLocation(markers));
    }
    else
    {
        autoScale();
    }
}
function customMarker (location, display_name,num) 
{
    var icon = new MMIcon( '/images/storeIcon'+num+'.png' );
    //icon.cssClass = 'iconBG';
    if (num == 1){
        icon.iconSize = new MMDimensions(40,42);
    }else{
        icon.iconSize = new MMDimensions(34, 34);
    }
    icon.iconAnchor = new MMPoint(16, 16);
    var marker = mapviewer.createMarker(location, '', icon);
    marker.setInfoBoxContent('<p>' + display_name + '</p>', { min_width : 250 });
    return marker;
}
function handleRecord ( record, num ) 
{
    // Create marker text for the infobox for this record
    var markerText = ''; 
    markerText += '<p>';  
    for (i = 1, j = 0; i < rfs.length; i++){
        if (record[rfs[i]]){
            if (i == 2){
                if (j > 0)
                    markerText = '<b>' + markerText + '<' + '/b>' + '<br />';
            }
            else if (i == 7){
                if (j > 0)
                    markerText+= '<br /><b>Telephone: <' + '/b>' + '<br />';
            }
            else if (i == 8){
                if (j > 0)
                    markerText+= '<br /><b>Opening Hours: <' + '/b>' + '<br />';
            }
            else{
                if (j > 0)
                    markerText += '<br /> ';
            }
            markerText += record[rfs[i]];
            j++;
        }
    }
    
    //markerText +='<br /><a href=branchdetails.aspx?postcode=' + escape(record.pc) + '>View Store Details' + '<' + '/a>'; 
        
    markerText += '<' + '/p>';    
    if (record.point)
    {
        var marker = customMarker(record.point, markerText, num);
        markers.push(marker);
    } 
    
    var anchor = document.createElement ('a');
    anchor.href = '#';
    anchor.record_id = record.id;    
    anchor.appendChild(document.createTextNode(record.name + ': ' + record.distance.miles + ' miles'));
    if (num > 1){
        anchor.appendChild(document.createElement('br'));
        anchor.appendChild(document.createTextNode(record.street + ', ' + record.town + ', ' + record.pc));
        anchor.appendChild(document.createElement('br'));
        anchor.appendChild(document.createTextNode('Tel: ' + record.telephone));
        anchor.appendChild(document.createElement('p'));
    }
    anchor.onclick = function(){openInfoBox('click', marker); return false;};
    return anchor;
}
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) 
{
    //NA - these lines will hide plan route fieldset, submit button and display no search found message.
   document.getElementById('Panel1').style.display = 'none';
   document.getElementById('btnGetRoute').style.display = 'none';
   document.getElementById('recordList').innerHTML = '<br/>&nbsp;&nbsp;&nbsp;We are sorry, no match found.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><a href="/locations/" title="Search again">Search again</a></b>';
          
    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));
        
       //NA - these variable were creating runtime error if no match found so i commented them.
       // address_select.appendChild(option);
       // address_select.selectedIndex=0; 
    }
    //NA - these variable were creating runtime error if no match found so i commented them.
    //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'; 
}
/*
//this function is loading the branch name and town for 'Combo Box'
function getBranchList() {
   // cleanUp();
    var searcherBranch,searchBranch;
    searcherBranch = MMFactory.createSearchRequester();
    searchBranch = new MMSearch(); 
   
    var rfs1 = ['client_id', 'name', 'town'];
    
    // When doing so, please replace "[api_key]" with the appropriate service client name:
    searchBranch.data_source = 'mm.clients.midcoop'
    searchBranch.return_fields = rfs1;
    searchBranch.filters = new Array();
    searchBranch.filters.push( new MMSearchFilter('town','startswith', 'a') );
    // Order search results appropriately:
   // searchBranch.order_by_fields = 'town';
   // searchBranch.order_by_order = 'asc';  
    searcherBranch.search( searchBranch );
}
*/  
/*
function branchResultsLoaded ( ) {
   alert(searcherBranch.record_sets.length);
    // If an error code has been produced, display the explanation:
    if ( searcher.error_code ) {
        var err =  '';
        if ( searcherBranch.error_explanation ) {
            err =  searcher.error_explanation;
        } else {
            err =  'Your request failed. Error code: ' + searcherBranch.error_code;
        }
        alert( err );
        return;
    } 
    var results_returned = 1;
    var select = document.createElement ( 'branchSelect' );
    for ( var count=0, l = searcherBranch.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 ( searcherBranch.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 ( searcherBranch.record_sets[count].records ) {
            // Loop through each record in the record set, and add it to the list below the map,
            for (var record_count = 0, rl = searcherBranch.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 option = document.createElement('option');
                option.text = record.name + ' ' + record.town;
                option.value = record.name;
                select.options.add(option);
            }
            
        } else {
            // No records have been returned. If a record count has been returned, display it,
                var option = document.createElement('option');
                option.text = 'No branch available';
                select.options.add(option);
        }
      }
        document.getElementById('branchListDiv').style.display = "block";
}
*/ 
//NA - this function display local info widget on the map when user click the link.
function addLocalInfoWidget(use_custom_datasources, outside, header, add_wikipedia) {
    var datasources, position;
    // these are different datasources categories showing local information, we can add or remove datasources from here
    datasources = 'mm.poi.global.general.railwaystation,mm.poi.global.general.atm,mm.poi.global.general.publictransport,mm.poi.global.general.trafficinformation,mm.poi.global.general.parking';
    // Add the Local Info Widget:
    if (widget_available) 
     { 
         mapviewer.removeWidget(local_info_widget);  
         widget_available = false;
     }
    else
    {    
        local_info_widget  = new MMLocalInfoWidget ( datasources, 'click on the check box to show on the map', position );
        mapviewer.removeWidget(local_info_widget);  
        mapviewer.addWidget(local_info_widget);
        widget_available = true;
    }
}
function removeAllWidgets() {
    // Remove widgets:
    mapviewer.removeWidget (local_info_widget);  
    mapviewer.removeAllOverlays ( ); 
    widget_available = false;
} 
//NA - creates printer friendly page by removing unnecessary information from travelling direction
function printerFriendly(){
     var storeDiv = document.getElementById('storeDetail');
     storeDiv.style.left = '400px'; 
     storeDiv.style.width = '275px'; 
     document.getElementById('search').style.display = 'none';
     document.getElementById('navigation').style.display = 'none';
     document.getElementById('header').appendChild(document.createElement('br'));
   //  document.getElementById('header').style.display = 'none';
     document.getElementById('footer').style.display = 'none';
     document.getElementById('printerLink').style.display = 'none';
     document.getElementById('planYourRoute').style.display = 'none'; 
     document.getElementById('planYourRoute').style.visibility = 'hidden'; 
    // document.getElementById('printRoute').style.display = 'block'; 
     var mapDiv = document.getElementById('mapviewer');
     mapDiv.style.width = '385px';
     mapDiv.style.height = '300px';
     
     var select =  document.getElementById('select2');
     var addr = new MMAddress();
     addr.qs = select.options[select.selectedIndex].value;
     mapviewer.goToPosition (new MMLocation(addr));
     mapviewer.resize();
     window.print();
 }
MMAttachEvent( window, 'load', onLoad );
//]]>