var mapviewer
var geocoder;
var searcher
var search;
var searchTextString;
var isTextSearch;
var nearestBranchName = '';

// fields to be returned by the multimap search
var rfs = ['client_id', 'name', 'street', 'town', 'pc', 'lat', 'lon'];

// This is the search run from the index.aspx page when a user clicks submit
function runSearchBasic(){
    // Initialise multimap
    mapviewer = new MultimapViewer(document.getElementById('mapviewerHidden'));   
    searcher = new MMSearchRequester(resultsLoadedBasic);
    
    // Set return fields and maximum number of records to return from search
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.count = 1;
    
    // Get the data we are searching on
    var _addressMatchesDropdown = document.getElementById('_addressMatchesDropdown');
    if (_addressMatchesDropdown.selectedIndex == -1){
        isTextSearch = true;
        searchTextString = $('#_searchTextBox').val();
        search.address = new MMAddress({qs : searchTextString});
        search.address.country_code = 'GB';
    }else{
        isTextSearch = false;
        searchTextString = _addressMatchesDropdown.options[_addressMatchesDropdown.selectedIndex].value;
        var coords = searchTextString.split(',');
        search.point = new MMLocation(new MMLatLon(coords[0], coords[1]));
        isTextSearch = false;
    }    

    // Set serch distance parameters
    search.max_distance = Number('300');
    search.min_distance = Number('');
    search.distance_units = 'miles';  
    
    searcher.search( search );    
}

// function called after the basic search has run
function resultsLoadedBasic(){
    var res = false;
    
    if (searcher.error_code){
        var err = '';
        if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES'){
            err = 'Multiple matches were found for your location. Please select the correct one from the dropdown list.';
            processGeocodingErrorsBasic(searcher.result_set);
            $('#badSearchTerm').css("margin-top","120px");
        }else if (searcher.error_code == 'MM_GEOCODE_NO_MATCHES'){
            err = 'No results were found, please try a different search term.';
            $('#badSearchTerm').css("margin-top","0px");
        }else if(searcher.error_explanation){
            err = searcher.error_explanation;
            $('#badSearchTerm').css("margin-top","0px");
        }else{
            err = 'Your request failed. Error code: ' + searcher.error_code;
            $('#badSearchTerm').css("margin-top","0px");
        }
        document.getElementById('messageTop').innerHTML = err + '&nbsp;&nbsp;';
        var _addressMatchesDropdown = document.getElementById('_addressMatchesDropdown');
        var resetMessage = document.getElementById('resetMessage');
        
        _addressMatchesDropdown.style.display = (_addressMatchesDropdown.options.length == 0)? 'none' : 'block';
        resetMessage.style.display = _addressMatchesDropdown.style.display;
        
        $('#badSearchTerm').css("display","block");
    }else{
        // All is good, setup the hidden fields so that the redirection will work ok
        var record = searcher.record_sets[0].records[0]; 
        $('#_neareststorePostcode').val(record.pc);
        if (isTextSearch){
            $('#_hfCoords').val('');
            $('#_hfSearchtext').val(searchTextString);
        }
        else{
            $('#_hfCoords').val(searchTextString);
            $('#_hfSearchtext').val('');
        }
            
        res = true;
    }
    
    if (res){
        $('#_runSearchHidden').val('true');
        document.forms[0].submit();
    }
}

// Called if multiple matches have been found, will populate a select box with
// the matches so a user can choose which ones to select
function processGeocodingErrorsBasic(result_set){
    
    // Get the dropdown to populate
    var _addressMatchesDropdown = document.getElementById('_addressMatchesDropdown');
    while (_addressMatchesDropdown.options.length > 0)
        _addressMatchesDropdown.options[_addressMatchesDropdown.options.length - 1] = null;
    
    for (var i = 0; i < result_set.length; i++){    
        var option = document.createElement('option');
        var coords = result_set[i].coords;
        option.value = coords.lat + ',' + coords.lon;       
        option.appendChild(document.createTextNode(result_set[i].address.display_name));
        _addressMatchesDropdown.appendChild(option);
    }
    _addressMatchesDropdown.selectedIndex = 0;
    document.getElementById('_searchTextBox').style.display = 'none';
}   

// This is the search functions run whichi will display the results on 
// the main map
function runMainSearch(){

    // Setup the multimap search
    mapviewer = new MultimapViewer(document.getElementById('mapviewer'));   
    searcher = new MMSearchRequester(resultsLoadedMain);
    
    // Set return fields and maximum number of records to return from search:
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.count = 5;
    
    if ($('#_searchTextHidden').val().length > 0){
        search.address = new MMAddress({ qs : $('#_searchTextHidden').val()});
        search.address.country_code = 'GB';
    }else{
        var coords = $('#_searchTextCoords').val().split(',');
        search.point = new MMLocation(new MMLatLon(coords[0], coords[1]));
    }   
     
    search.max_distance = Number('300');
    search.min_distance = Number('');
    search.distance_units = 'miles';  
    searcher.search(search);  
}

function resultsLoadedMain(){

    // 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('recordListDiv');
    
    if (searcher.error_code){ // error occurred, this shouldn't happen from this search but check anyway
        var err = '';
        if (searcher.error_explanation){
            err =  searcher.error_explanation;
        }else{
            err =  'Your request failed. Error code: ' + searcher.error_code;
        }
        alert(err);
        return;
    } 
    
    var start_index_value = 1;       
    var results_returned = 1;
    
    var el = document.createElement ( 'ol' );
    el.id = 'recordList';
    
    markers = new Array();
        
    var _nearestBranchName = document.getElementById('_nearestBranchName');
    if (_nearestBranchName)
        nearestBranchName = _nearestBranchName.value;
        
    // 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;
                var anchor = handleRecord(record, start_index_value + record_count);
                
                if (reccount !=1) {
                    var li = document.createElement('li');
                    li.style.background = 'url(../assets/img/multimap/storeIcon'+reccount+'.png) no-repeat 0px 0px';
                    li.style.listStyle = 'none';
                    li.style.padding = '5px 0px 1px 40px';
                    li.appendChild(anchor);
                    el.appendChild ( li );
                }else{
                    var nearestStoreSpan = document.getElementById('_nearestStoreSpan');
                    if (nearestStoreSpan){
                        nearestStoreSpan.appendChild(anchor);
                    }
                }
            }
        } 
    }
    
    if (container != null){    
        container.appendChild(el);                    
    }
    // circle the start point
    circleStartLocation();
}

function autoScale(){
    mapviewer.goToPosition (mapviewer.getAutoScaleLocation(markers));
}

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( '../assets/img/multimap/red-circle.png' );
    icon.iconSize = new MMDimensions(32, 32);
    var marker = mapviewer.createMarker(location, {'icon' : icon});
    markers.push(marker);
    
    autoScale();
}

function startLocationResult(){
    if (geocoder.result_set.length > 0){
        var coords = geocoder.result_set[0].coords;
        circleStartLocation(new MMLocation(new MMLatLon(coords.lat, coords.lon)));
    }else{
        autoScale();
    }
}

function customMarker (location, display_name,num) {
    
    var icon = new MMIcon( '../assets/img/multimap/storeIcon'+num+'.png' );
    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>', { className : 'altinfobox', min_width : 170 });

    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 (j > 0)
                    markerText += '<br /> ';
            }
            markerText += record[rfs[i]];
            j++;
        }
    }
    
    markerText +='<br /><a href=branchdetails.aspx?postcode=' + escape(record.pc) + '>View Store Details' + '<' + '/a>'; 
    if (record.name != nearestBranchName)
        markerText +='<br /><br /><a href=' + document.location + '&setnearest=' + escape(record.pc) + '>Remember this as my local branch' + '<' + '/a>';    
    else
        markerText +='<br /><br />This is your nearest branch';
        
    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('p'));
    }
    anchor.onclick = function(){openInfoBox('click', marker); return false;};

    return anchor;
}

function openInfoBox(type, target) {
    if(target.infoBoxOpened()){
        target.closeInfoBox();
    }else{
        target.openInfoBox();
    }
}

function resetSearch(){
    var _addressMatchesDropdown = document.getElementById('_addressMatchesDropdown');
    var messageTop = document.getElementById('messageTop');
    var resetLink = document.getElementById('resetLink');
    var _searchTextBox = document.getElementById('_searchTextBox');

    while (_addressMatchesDropdown.options.length > 0)
        _addressMatchesDropdown.options[_addressMatchesDropdown.options.length - 1] = null;

    messageTop.innerHTML = '';
    $('#badSearchTerm').hide();
    $('#errorMessages').css("margin-top","0px");
    _searchTextBox.style.display = 'inline';
    _searchTextBox.value = '';
}

function checkPostcode(textbox, branchSelect, addressMatchesDropdown){
	
    $('#invalidSearch').hide();
    
    // Check that they have not entered both search text and selected a branch
    if (branchSelect.selectedIndex != 0){
        if (addressMatchesDropdown.selectedIndex != -1){
            $('#invalidSearch').text('Please either select your matching location or select a branch, not both.');
            $('#invalidSearch').show();
            return;
        }else if (textbox.value.length > 0){
            $('#invalidSearch').text('Please either enter some search text or select a branch, not both.');
            $('#invalidSearch').show();
            return;
        }
    }

    var res = true;
    if (branchSelect.selectedIndex == 0){
        if (addressMatchesDropdown.selectedIndex == -1){
            var postcode = textbox.value;
            while(postcode.indexOf(' ') != -1){
                postcode = postcode.replace(' ', '');
            }  
            res = (postcode.length > 0)
        }
    }else{
        $('#_runSearchHidden').val('true');
        document.forms[0].submit();
    }

    if (!res){
        $('#invalidSearch').text('Please enter some search text or select a branch from the dropdown list.');
        $('#invalidSearch').show();
        textbox.focus();
    }else{
        runSearchBasic();
    }
}

////IDs required to show the results of nearest branch search
//var containerDivID = '';
//var loadingDivID = '';
//var loadingTimeout = 3000;
//var primaryImageID = '';
//var OKImage = '';
//var errorImage = ''

//function checkPostcode2(postcode, containerDiv, loadingDiv, primaryImage, postcodeOKImage, postcodeErrorImage){
//    
//    //Save the element IDs to the global object
//    containerDivID = containerDiv;
//    loadingDivID = loadingDiv;
//    primaryImageID = primaryImage;    
//    OKImage = postcodeOKImage; 
//    errorImage = postcodeErrorImage;
//    
//	//Initialise multimap
//    //mapviewer = new MultimapViewer(document.getElementById('mapviewerHidden'));   
//    searcher = new MMSearchRequester(resultsLoadedShopping);
//    
//    // Set return fields and maximum number of records to return from search
//    search = new MMSearch(); 
//    search.return_fields = rfs;
//    search.count = 1;
//    
//    // Get the data we are searching on
//	isTextSearch = true;
//	searchTextString = postcode;
//	search.address = new MMAddress({qs : searchTextString});
//	search.address.country_code = 'GB';

//    // Set serch distance parameters
//    search.max_distance = Number('300');
//    search.min_distance = Number('');
//    search.distance_units = 'miles';  
//            
//    searcher.search( search );      
//}

//function resultsLoadedShopping(){

//    var res = false;
//    
//    //Create the script calls
//    var clearString = "$('#" + containerDivID + "').empty();"; //Clear the current HTML content
//    var messageString = "$('#" + containerDivID + "').html('" + errorHTML + "');"; //Add the error HTML
//    var removeString = "$('#" + loadingDivID + "').remove();"; //Remove the loading div
//    var showString = "$('#" + containerDivID + "').show();"; //Show the results div
//    
//    if (searcher.error_code)
//    {                        
//        var errorHTML;
//        
//        switch (searcher.error_code)
//        {                        
//            case 'MM_GEOCODE_NO_MATCHES':
//                errorHTML = 'Sorry, we are unable to locate your postcode, please check your input and try again.';
//                break;
//                
//            default:
//                alert(searcher.error_code);
//                break;
//        }
//        
//        if (errorHTML)       
//        {          
//            var imagePopulateString = "$('#" + primaryImageID + "').attr('src', '" + errorImage + "');";
//                        
//            //Use a timeout to avoid a blink if the request only takes a few milliseconds
//            setTimeout(clearString + messageString + removeString + showString + imagePopulateString + imageShowString, loadingTimeout);
//        }
//    }
//    else
//    {            
//        // All is good, setup the hidden fields so that the redirection will work ok
//        var record = searcher.record_sets[0].records[0]; 
//        var postcode = record.pc;
//        var branchName = record.name;
//        var distance = record.distance.miles;
//        
//        res = true;
//        
//        $('.nearestBranchName').text(branchName);        
//        $('.nearestBranchMiles').text(distance) + ' miles';
//                
//        var imagePopulateString = "$('#" + primaryImageID + "').attr('src', '" + OKImage + "');";        
//            
//        //Use a timeout to avoid a blink if the request only takes a few milliseconds
//        setTimeout(removeString + showString + imagePopulateString + imageShowString, loadingTimeout);
//    }
//}
