
var mapviewer, searcher, loading, markers, search;
var by_address, search_address, search_point, bounding_box, min_distance, max_distance, distance_units, submitbtn;
var funcRef = resultsLoaded;
var pan_zoom_widget;
var bottomLeft;
var flagsubmit;
var address_select, address_selecttemp;

var rfs = ['client_id', 'name', 'street', 'town', 'pc', 'lat', 'lon'];

var by_address1_id = 'by_address1';

function initSearch () {

    flagsubmit = 'false';
    bottomLeft = new MMBox( undefined, undefined, 10, 10 );
    mapviewer = new MultimapViewer( document.getElementById( 'mapviewer' ) );
    cleanUp();
    searcher = new MMSearchRequester( funcRef );

    // Set return fields and maximum number of records to return from search:
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.count = 5;
    if (document.getElementById( 'address_select' ) != null) {
        address_select = document.getElementById( 'address_select' );
        if (address_select.options &&  address_select.options.length > 1) {
            var coords = address_select.options[address_select.selectedIndex].value.split(',');
            search.point = new MMLocation(new MMLatLon(coords[0], coords[1]));
            document.getElementById( '_flagforplace1' ).value = 'true';            
        } 
    }

    if (document.getElementById( 'address_selecttemp' ) != null) {
        address_selecttemp = document.getElementById( 'address_selecttemp' );
        if (address_selecttemp.options &&  address_selecttemp.options.length > 1) {
            var coords = address_selecttemp.options[address_selecttemp.selectedIndex].value.split(',');
            search.point = new MMLocation(new MMLatLon(coords[0], coords[1]));
             document.getElementById( '_flagforplace2' ).value = 'true';           
        } 
    }
    
    if (document.getElementById( by_address1_id )  != null) {
     if (document.getElementById( by_address1_id ).value != '') {
            by_address = document.getElementById( by_address1_id );
     }     
    } 
    if (document.getElementById( '_branchDropdown' )  != null) {
     if (document.getElementById( '_branchDropdown' ).value != '') {
            by_address = document.getElementById( '_branchDropdown' );
     }     
    }  
    if (document.getElementById( '_brDropdown' )  != null) {
     if (document.getElementById( '_brDropdown' ).value != '') {
            by_address = document.getElementById( '_brDropdown' );
     }     
    }       
    
    var tempPS = document.getElementById( '_txtPS' );
    if (tempPS != null) {
          if (document.getElementById( '_txtPS' ).value != '') {
                by_address = document.getElementById( '_txtPS' );
           }
    }
    if (by_address.value!= '') {
             search.address= new MMAddress({ qs :  by_address.value + ', UK' });
    } 
    search.max_distance = Number('100');
    search.min_distance = Number('');
    search.distance_units = 'miles';  
    searcher.search( search );
}

function cleanUp () {
    // Clean up the HTML containers
    var message = document.getElementById('message');
    if (message == null) {
    return;
    }    
    while (message.firstChild) {
        message.removeChild(message.firstChild);
    }
        
    message.style.display = 'none';
    var record_list = document.getElementById('recordListDiv');
    if (record_list != null ) {
      while (record_list.firstChild) {
        record_list.removeChild(record_list.firstChild);
       }       
    }
        
    if (mapviewer !=null) {  
    mapviewer.removeAllOverlays();
   }
   by_address = document.getElementById('by_address');
   bounding_box = document.getElementById( 'bounding_box' );  
   min_distance = document.getElementById( 'min_distance' );  
   max_distance = document.getElementById( 'max_distance' );  
   distance_units = document.getElementById( 'distance_units' ); 
   markers = new Array();    
}
        
function processGeocodingErrors (result_set) {

    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.value = displayName; 
        option.appendChild(document.createTextNode(displayName));
        if (address_select != null) {
        address_select.appendChild(option);
        address_select.selectedIndex=0;
        }
        if (address_selecttemp != null) {
        address_selecttemp.appendChild(option);
        address_selecttemp.selectedIndex=0;
        }
         
    }
    if (document.getElementById('address_select') !=null ) {
    document.getElementById('address_select').style.display = 'block';
    document.getElementById('by_address1').style.display = 'none';
    }
    if (document.getElementById('address_selecttemp') !=null ) {
    document.getElementById('address_selecttemp').style.display = 'block';
    document.getElementById('_txtPS').style.display = 'none';
    }
}    


//MMAttachEvent( window, 'load', onLoad);
function resultsLoaded ( ) {    
     
    var container = document.getElementById('recordListDiv');
    
    if ( searcher.error_code ) {
        var err =  '';
        if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
            processGeocodingErrors(searcher.result_set);
        } else if( searcher.error_explanation ) {
            err =  searcher.error_explanation;
        } else {
            err =  'Your request failed. Error code: ' + searcher.error_code;
        }
        alert(err);
        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 reccount = start_index_value + record_count;
                if (container != null) {
                if ( start_index_value+ record_count == 1 )
                  {
                    if (document.getElementById( '_neareststorepc' ) != null) {
                        document.getElementById( '_neareststorepc' ).value=record.pc;
                    }   
                                     
                    if (document.getElementById( '_neareststorepcone' ) != null) {
                        document.getElementById( '_neareststorepcone' ).value=record.pc;
                    }                  
                  }
                }

                var li = document.createElement('li');
                //li.style.background = 'url(../assets/img/multimap/storeIcon'+reccount+'.gif) no-repeat 0px 0px;';
                //li.style.listStyle = 'none';
                li.style.padding = '5px 0px 1px 5px';
                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 {
                el.appendChild ( document.createTextNode( 'No results returned' ) ); 
            }  
            results_returned = 0;
        }        
    }
    if (container != null) {    
        container.appendChild(el);                  
    }
}

function handleRecord(record, num){

    var anchorHREF = '';
    var anchor = document.createElement ( 'a' );

    var appPath = $('input[@type=hidden][@id*=_appPathHidden]').val();
    
    if (appPath.length > 0){
        if (appPath.lastIndexOf('/') == appPath.length - 1)
            anchorHREF = appPath + 'branches/branchdetails.aspx?postcode=' + encodeURI(record.pc);
        else
            anchorHREF = appPath + '/branches/branchdetails.aspx?postcode=' + encodeURI(record.pc);
    }else
        anchorHREF = '/branches/branchdetails.aspx?postcode=' + encodeURI(record.pc);
    
    anchor.href = anchorHREF;
    anchor.record_id = record.id;	
    anchor.appendChild(document.createTextNode(record.name + ': ' + record.distance.miles + ' miles'));
    anchor.appendChild(document.createElement('br'));
    anchor.appendChild(document.createTextNode(record.street  + ', ' + record.town  + ', ' + record.pc));
    anchor.appendChild(document.createElement('p'));

    return anchor;   
}

