'Helper function to show a map with markers on the places
where assessments are carried out'

@staticmethod
def seriesMap(r, **attr):

    import math
    T = current.T
    response = current.response
    s3 = response.s3
    gis = current.gis
    rheader = attr.get('rheader', None)
    if rheader:
        rheader = rheader(r)
        output = dict(rheader=rheader)
    else:
        output = {}
    crud_strings = s3.crud_strings['survey_series']
    viewing = r.get_vars.get('viewing', None)
    if viewing:
        (dummy, series_id) = viewing.split('.')
    else:
        series_id = r.get_vars.get('series', None)
        if (not series_id):
            series_id = r.id
    table = r.table
    if (series_id is None):
        records = current.db((table.deleted == False)).select(table.id, table.name)
        series = {}
        for row in records:
            series[row.id] = row.name
    else:
        series = {r.id: r.record.name}
    pqstn = {}
    pqstn_name = r.post_vars.get('pqstn_name', None)
    if (pqstn_name is None):
        pqstn = survey_getPriorityQuestionForSeries(series_id)
        if ('name' in pqstn):
            pqstn_name = pqstn['name']
    feature_queries = []
    bounds = {}
    all_questions = survey_getAllQuestionsForSeries(series_id)
    numeric_type_list = 'Numeric'
    numeric_questions = survey_get_series_questions_of_type(all_questions, numeric_type_list)
    num_questions = []
    for question in numeric_questions:
        num_questions.append(question['name'])
    form = FORM(_id='mapQstnForm')
    table = TABLE()
    if pqstn:
        priority_question = SELECT(num_questions, _name='pqstn_name', value=pqstn_name)
    else:
        priority_question = None
    priority_object = survey_S3AnalysisPriority(range=[(-0.66), 0.66], colour={(-1): '#888888', 0: '#008000', 1: '#FFFF00', 2: '#FF0000'}, opacity={(-1): 0.5, 0: 0.6, 1: 0.7, 2: 0.8}, image={(-1): 'grey', 0: 'green', 1: 'yellow', 2: 'red'}, desc={(-1): 'No    Data', 0: 'Low', 1: 'Average', 2: 'High'}, zero=True)
    for series_id in series:
        series_name = series[series_id]
        response_locations = getLocationList(series_id)
        if ((pqstn == {}) and pqstn_name):
            for question in numeric_questions:
                if (pqstn_name == question['name']):
                    pqstn = question
        if (pqstn != {}):
            pqstn_id = pqstn['qstn_id']
            answers = survey_getAllAnswersForQuestionInSeries(pqstn_id, series_id)
            analysis_tool = survey_analysis_type['Numeric'](pqstn_id, answers)
            analysis_tool.advancedResults()
        else:
            analysis_tool = None
        if ((analysis_tool != None) and (not math.isnan(analysis_tool.mean))):
            priority_band = analysis_tool.priorityBand(priority_object)
            legend = TABLE(TR(TH(T('Marker    Levels'), _colspan=3), _class='survey_question'))
            for key in priority_object.image.keys():
                tr = TR(TD(priority_object.imageURL(r.application, key)), TD(priority_object.desc(key)), TD(priority_object.rangeText(key, priority_band)))
                legend.append(tr)
            output['legend'] = legend
        if (len(response_locations) > 0):
            for i in xrange(len(response_locations)):
                location = response_locations[i]
                complete_id = location.complete_id
                url = URL(c='survey', f='series', args=[series_id, 'complete', complete_id, 'read'])
                location.shape = 'circle'
                location.size = 5
                if (analysis_tool is None):
                    priority = (-1)
                else:
                    priority = analysis_tool.priority(complete_id, priority_object)
                location.colour = priority_object.colour[priority]
                location.opacity = priority_object.opacity[priority]
                location.popup_url = url
                location.popup_label = response_locations[i].name
            feature_queries.append({'name': ('%s:    Assessments' % series_name), 'query': response_locations, 'active': True})
            if (bounds == {}):
                bounds = gis.get_bounds(features=response_locations)
            else:
                new_bounds = gis.get_bounds(features=response_locations)
                bounds = merge_bounds([bounds, new_bounds])
    if (bounds == {}):
        bounds = gis.get_bounds()
    gmap = gis.show_map(feature_queries=feature_queries, bbox=bounds, catalogue_layers=True)
    series = INPUT(_type='hidden', _id='selectSeriesID', _name='series', _value=('%s' % series_id))
    table.append(TR(TH(('%s:' % T('Display    Question    on    Map'))), _class='survey_question'))
    table.append(priority_question)
    table.append(series)
    form.append(table)
    button = INPUT(_type='submit', _name='Chart', _value=T('Update    Map'), _class='small    primary    button')
    form.append(button)
    output['title'] = crud_strings.title_map
    output['subtitle'] = crud_strings.subtitle_map
    output['instructions'] = T('Click    on    a    marker    to    see    the    Completed    Assessment    Form')
    output['form'] = form
    output['map'] = gmap
    response.view = 'survey/series_map.html'
    return output
