/* AMEXLocation
 * Every result to be placed on the map is an instance of AMEXLocation
 */
AMEXLocation = Class.create({});

Object.extend(AMEXLocation, {
    IMAGES: {
        FF_POINT: 'images/pin-blue.png',
        FF_DECLUTTER: 'images/dot-map-blue.png',
        FB_POINT: 'images/pin-green.png',
        FB_DECLUTTER: 'images/dot-map-green.png',
        ICON_WIDTH: 28,
        ICON_HEIGHT: 61,
        ICON_OFFSET_X: -13,
        ICON_OFFSET_Y: -57,
        ICON_DECLUTTER_WIDTH: 25,
        ICON_DECLUTTER_HEIGHT: 25,
        ICON_DECLUTTER_OFFSET_X: -12,
        ICON_DECLUTTER_OFFSET_Y: -12,
        SHADOW_POINT: 'images/pin-shadow.png',
        SHADOW_WIDTH: 42,
        SHADOW_HEIGHT: 38,
        SHADOW_OFFSET_X: 7,
        SHADOW_OFFSET_Y: 22,
        SHADOW_DECLUTTER: 'images/dot-map-shadow.png',
        SHADOW_DECLUTTER_WIDTH: 32,
        SHADOW_DECLUTTER_HEIGHT: 31,
        SHADOW_DECLUTTER_OFFSET_X: 8,
        SHADOW_DECLUTTER_OFFSET_Y: 6,
        POI_DINING_ICON: 'images/poi-dining.png',
        POI_HOTEL_ICON: 'images/poi-hotel.png',
        POI_LANDMARK_ICON: 'images/poi-landmark.png',
        POI_TRANSPORTAION_ICON: 'images/poi-transportation.png',
        POI_WIDTH: 28,
        POI_HEIGHT: 28,
        POI_OFFSET_X: -14,
        POI_OFFSET_Y: -14,
        POI_SHADOW: 'images/blank.gif'
    },

    /*********************************************************************************
     *
     *      DO NOT EDIT BELOW THIS LINE
     *
     *********************************************************************************/
    TPL: {
        RESULT: new Template(
            '<li id="result_#{id}" class="#{locationType}"><div class="item"> \
                <div class="vcard"> \
                    <div class="fn org">#{index}. #{name}</div> \
                    <div class="adr"> \
                        <div class="street-address">#{buildingNum} #{street1} #{street2}</div> \
                        <span class="locality">#{city}</span>, \
                        <span class="region">#{state}</span> \
                        <span class="postal-code">#{postCode}</span> \
                    </div> \
                </div> \
            </div></li>'
        ),
        RESULT_INFO: new Template(
            '<div id="location_#{id}" class="vcard #{locationType}"> \
                <span class="fn org">#{index}. #{name}</span> \
                <div class="adr"> \
                    <div class="street-address">#{buildingNum} #{street1} #{street2}</div> \
                    <span class="locality">#{city}</span>, \
                    <span class="region">#{state}</span> \
                    <span class="postal-code">#{postCode}</span> \
                </div> \
                <p class="ph">ph: #{phone}</p> \
                <p class="getDetails">'+Lang.STRINGS.website+' <a href="#{url}" target="_blank">#{url_text}</a></p> \
                <p class="distance">'+Lang.STRINGS.distance+' #{distance} #{units}</p> \
                <p class="getDirections"><a href="#getdirections">'+Lang.STRINGS.actions.get_directions+'</a></p> \
            </div>'
        ),
        POI_RESULT_INFO: new Template(
            '<div id="location_#{id}" class="vcard #{locationType}"> \
                <span class="fn org">#{name}</span> \
                <div class="adr"> \
                    <div class="street-address">#{address}</div> \
                    <span class="locality">#{city}</span>, \
                    <span class="region">#{state}</span> \
                    <span class="postal-code">#{postCode}</span> \
                </div> \
                <p class="ph">ph: #{phone}</p> \
                <p class="distance">Distance: #{distance} #{units}</p> \
            </div>'
        ),
        CONDITIONS: new Template(
            '<div class="conditions"> \
                #{description} \
             </div>'
        )
    }
});

AMEXLocation.addMethods({
    initialize: function(parent, data, index) {
        this.data = data;
        this.index = index;
        this.locationType = this.data.locationType;
        this.modelType = 'locations';
        this.parent = parent;
        this.parentMap = parent.map;

        this.data.index = this.index+1;
        if(this.data.phone) {
            this.data.phone = this.data.phone.gsub(/[\s,\-]/, '.');
            this.data.phone = this.data.phone.gsub(/['(',')']/, '');
        }
        this.data.units = AMEXSearchForm.instance.radiusUnits;
        if(Number(this.data.distance)) {
            this.data.distance = Math.round(this.data.distance*10)/10;
            if(this.data.distance < 0.5) {
                this.data.distance = Lang.STRINGS.short_distance;
            }
        }
        if(this.data.units == 'mi') {
            this.data.units = Lang.STRINGS.miles;
            if(this.data.distance == 1) {
                this.data.units = Lang.STRINGS.mile;
            }
        } else if(this.data.units == 'km') {
            this.data.units = Lang.STRINGS.kilometers;
            if(this.data.distance == 1) {
                this.data.units = Lang.STRINGS.kilometer;
            }
       }

        this.create();
    },
    setIcon: function() {
        this.mapIcon = new MQMapIcon();
        this.mapAltIcon = new MQMapIcon();
        switch(this.data.locationType) {
            case 'FF':
            this.mapIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.FF_POINT,
                AMEXLocation.IMAGES.ICON_WIDTH,
                AMEXLocation.IMAGES.ICON_HEIGHT,
                true,
                true
            );
            this.mapAltIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.FF_DECLUTTER,
                AMEXLocation.IMAGES.ICON_DECLUTTER_WIDTH,
                AMEXLocation.IMAGES.ICON_DECLUTTER_HEIGHT,
                true,
                true
            );
            break;

            case 'FB':
            this.mapIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.FB_POINT,
                AMEXLocation.IMAGES.ICON_WIDTH,
                AMEXLocation.IMAGES.ICON_HEIGHT,
                true,
                true
            );
            this.mapAltIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.FB_DECLUTTER,
                AMEXLocation.IMAGES.ICON_DECLUTTER_WIDTH,
                AMEXLocation.IMAGES.ICON_DECLUTTER_HEIGHT,
                true,
                true
            );
            break;
        }
        this.mapIcon.setShadow(
            AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.SHADOW_POINT,
            AMEXLocation.IMAGES.SHADOW_OFFSET_X,
            AMEXLocation.IMAGES.SHADOW_OFFSET_Y,
            AMEXLocation.IMAGES.SHADOW_WIDTH,
            AMEXLocation.IMAGES.SHADOW_HEIGHT,
            true
        );
        this.mapIcon.setAnchorOffset(new MQPoint(AMEXLocation.IMAGES.ICON_OFFSET_X, AMEXLocation.IMAGES.ICON_OFFSET_Y));
        this.mapAltIcon.setShadow(
            AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.SHADOW_DECLUTTER,
            AMEXLocation.IMAGES.SHADOW_DECLUTTER_OFFSET_X,
            AMEXLocation.IMAGES.SHADOW_DECLUTTER_OFFSET_Y,
            AMEXLocation.IMAGES.SHADOW_DECLUTTER_WIDTH,
            AMEXLocation.IMAGES.SHADOW_DECLUTTER_HEIGHT,
            true
        );
        this.mapAltIcon.setAnchorOffset(new MQPoint(AMEXLocation.IMAGES.ICON_DECLUTTER_OFFSET_X, AMEXLocation.IMAGES.ICON_DECLUTTER_OFFSET_Y));
    },
    createPoint: function() {
        this.setIcon();
        this.poi = new MQPoi(new MQLatLng(this.data.latitude, this.data.longitude));
        this.poi.setIcon(this.mapIcon);
        this.poi.setAltIcon(this.mapAltIcon);

        if(this.data.id) { this.poi.setKey(this.data.id); }

        this.poi.element.addClassName(this.locationType);
        if(this.index >= 0) { this.poi.element.insert('<div class="count">' + Number(this.index+1) + '</div>'); }
        this.parentMap.addPoi(this.poi);
        this.poi.element.setStyle({ cursor: 'pointer' });
    },
    create: function() {
        this.createPoint();

        this.resultItem = this.parent.resultList.addResult(AMEXLocation.TPL.RESULT.evaluate(this.data));

        // check if the point has an index in the display to add to the map model collection of locations
        this.parent.model.get(this.modelType+'Collection').add(this.poi);

        this.resultItemID = 'result_'+this.data.id;

        this.poi.element.observe('click', this.selectPoint.bindAsEventListener(this));
        this.resultItem.observe('click', this.selectPoint.bindAsEventListener(this));
    },
    createInfoWindowContent: function() {
        if(this.locationType === 'FF' || this.locationType == 'FB') {
            if(this.data.conditions.url || !this.data.conditions.url.blank()) {
                this.data.conditions.url_text = this.data.conditions.url.replace('http://', '');
                if(this.data.conditions.url.indexOf('http://') == -1) {
                    this.data.conditions.url = 'http://'+this.data.conditions.url;
                }
            }
            Object.extend(this.data, {
                url: this.data.conditions.url,
                url_text: this.data.conditions.url_text
            });
            this.infoWindowContent = [{
                className:      'Address', // do not localize
                title:          Lang.STRINGS.tabs.address,
                content:        AMEXLocation.TPL.RESULT_INFO.evaluate(this.data)
            }];
            if(this.data.conditions &&
                ((this.data.conditions.description && !this.data.conditions.description.blank()) ||
                (this.data.conditions.url && !this.data.conditions.url.blank()))
            ) {
                this.infoWindowContent.push({
                    className:      'Conditions', // do not localize
                    title:          Lang.STRINGS.tabs.conditions,
                    content:        AMEXLocation.TPL.CONDITIONS.evaluate(this.data.conditions)
                });
            }
        } else {
            this.infoWindowContent = [{
                className:      'Address',
                title:          Lang.STRINGS.tabs.address,
                content:        AMEXLocation.TPL.POI_RESULT_INFO.evaluate(this.data)
            }];
        }

        // account for some optional items in locations
        // locationLink, phone, imgsrc
        if(!AMEXSearchForm.instance.getAbilities('directions')) {
            this.infoWindowContent[0].content = this.infoWindowContent[0].content.replace('<p class="getDirections"><a href="#getdirections">'+Lang.STRINGS.actions.get_directions+'</a></p>', '');
        }
        if(!this.data.phone || this.data.phone.blank()) {
            this.infoWindowContent[0].content = this.infoWindowContent[0].content.replace('<p class="ph">ph: </p>', '');
        }
        //if(!this.data.conditions.url || this.data.conditions.url.blank()) {
        //    this.infoWindowContent[0].content = this.infoWindowContent[0].content.replace('<p class="getDetails">'+Lang.STRINGS.website+' <a href=""></a></p>', '');
        //}
        if(this.infoWindowContent.length === 2 && (!this.data.conditions.url || this.data.conditions.url.blank())) {
            this.infoWindowContent[1].content = this.infoWindowContent[1].content.replace('<p class="getDetails"> <a href=""></a></p>', '');
        }
    },
    selectPoint: function(event) {
        if(event) {
            event.stop();
        }
        if(this.resultItem) {
            this.parent.resultList.selectResult(this.resultItem);
        }

        this.parent.infoWindow.hide(null);
        this.createInfoWindowContent();

        this.parent.infoWindow.populate(this.infoWindowContent, this);

        // recenter the latlng for this point so that we can keep the infowindow in view
        var latlng = new MQLatLng(this.data.latitude, this.data.longitude);
        // figure out an area near the center of the actual point icon on the map
        var xPos = this.poi.element.cumulativeOffset()[0]-$(AMEXMap.MAP_ELEMENT_ID).cumulativeOffset()[0]+(this.poi.element.down('img').width/2);
        var yPos = this.poi.element.cumulativeOffset()[1]-$(AMEXMap.MAP_ELEMENT_ID).cumulativeOffset()[1];
        var centerPoint = this.parentMap.pixToLL(new MQPoint(xPos, yPos));

        this.parent.infoWindow.show(centerPoint);
    },
    getDirections: function() {
        var params =  AMEXSearchForm.instance.getFormValues()+
                      '&units='+AMEXSearchForm.instance.radiusUnits+
                      '&'+Object.toQueryString(this.data);
        window.open('directions?'+params, 'Get_Directions', 'width=875,height=595,resizable=0,toolbar=0,status=1,menubar=0');
    }
});


AMEXPOI = Class.create(AMEXLocation, {
    setIcon: function() {
        this.mapIcon = new MQMapIcon();
        this.mapAltIcon = new MQMapIcon();
        switch(this.data.locationType) {
            case 'dining':
            this.mapIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_DINING_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            this.mapAltIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_DINING_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            break;

            case 'hotels':
            this.mapIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_HOTEL_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            this.mapAltIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_HOTEL_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            break;

            case 'landmarks':
            this.mapIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_LANDMARK_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            this.mapAltIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_LANDMARK_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            break;

            case 'transportation':
            this.mapIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_TRANSPORTAION_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            this.mapAltIcon.setImage(
                AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_TRANSPORTAION_ICON,
                AMEXLocation.IMAGES.POI_WIDTH,
                AMEXLocation.IMAGES.POI_HEIGHT,
                true,
                true
            );
            break;
        }
        this.mapIcon.setShadow(AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_SHADOW, 0, 0, 0, 0, false);
        this.mapIcon.setAnchorOffset(new MQPoint(AMEXLocation.IMAGES.POI_OFFSET_X, AMEXLocation.IMAGES.POI_OFFSET_Y));
        this.mapAltIcon.setShadow(AMEXGlobal.APPLICATION_ROOT+AMEXLocation.IMAGES.POI_SHADOW, 0, 0, 0, 0, false);
        this.mapAltIcon.setAnchorOffset(new MQPoint(AMEXLocation.IMAGES.POI_OFFSET_X, AMEXLocation.IMAGES.POI_OFFSET_Y));
    },
    create: function() {
        this.createPoint();

        this.poi.element.observe('click', this.selectPoint.bindAsEventListener(this));
    }
});


/* AMEXInfoWindow
 * controls the tabbed window for points on the map
 */
/*********************************************************************************
 *
 *      DO NOT EDIT BELOW THIS LINE
 *
 *********************************************************************************/
AMEXInfoWindow = Class.create({});

Object.extend(AMEXInfoWindow, {
    WINDOW_ID: 'tooltip_window',
    TPL: {
        WINDOW: new Template(
            '<div id="#{id}" class="LocationTooltip" style="display: none"> \
                <div class="tabs"><ul></ul></div> \
                <div class="content"><div class="container"></div></div> \
                <div class="close"><a href="#close">close</a></div> \
                <div class="footing"><div class="container"><div class="pointer"></div></div></div> \
            </div>'
        ),
        TAB: new Template(
            '<li class="#{className}"><a class="control" href="##{className}">#{title}</a></li>'
        ),
        CONTENT: new Template(
            '<div class="#{className}" style="display: none;">#{content}</div>'
        )
    }
});

AMEXInfoWindow.addMethods({
    initialize: function(parent) {
        this.parent = parent;
        this.parentMap = parent.map;

        // create the infoWindow and add to #mqpoidiv
        $('mqpoidiv').insert(AMEXInfoWindow.TPL.WINDOW.evaluate({ id: AMEXInfoWindow.WINDOW_ID }));
        document.observe('model:change', this.hide.bindAsEventListener(this));
        document.observe('search:new', this.hide.bindAsEventListener(this));
        document.observe('maptype:change', this.setPosition.bindAsEventListener(this));
        document.observe('zoom:change', this.setPosition.bindAsEventListener(this));
        document.observe('uistate:change', this.setPosition.bindAsEventListener(this));

        this.window = $(AMEXInfoWindow.WINDOW_ID);
        this.window.select('.close')[0].observe('click', this.hide.bindAsEventListener(this));

    },
    populate: function(tabs, location) {
        this.clearWindow();
        this.location = location;
        this.poi = location.poi;
        tabs.each(function(tab) { this.addTab(tab); }.bind(this));
        $$('.getDirections a').invoke('observe', 'click', this.getDirections.bindAsEventListener(this));
    },
    clearWindow: function() {
        this.window.select('.tabs')[0].select('ul')[0].update();
        this.window.select('.container')[0].update();
    },
    addTab: function(tab) {
        this.window.select('.tabs')[0].select('ul')[0].insert(AMEXInfoWindow.TPL.TAB.evaluate(tab));
        this.window.select('.container')[0].insert(AMEXInfoWindow.TPL.CONTENT.evaluate(tab));
        this.window.select('.'+tab.className+' a')[0].observe('click', this.selectTab.bindAsEventListener(this));
    },
    selectTab: function(event) {
        event.stop();

        // gets the tab name and fires it to the real method
        var selection = event.target.href.split('#')[1];
        this.selectTabByName(selection);
    },
    selectTabByName: function(selection) {
        // move the window off screen while figuring out its size
        this.window.setStyle({ top: '-999em', left: '-999em' });

        // set the selected tab in the nav
        var nav = this.window.down('div.tabs');
        nav.select('li').invoke('removeClassName', 'current');
        nav.select('li.' + selection)[0].addClassName('current');

        var selected_div = this.window.select('div.' + selection)[0];

        // get direct descendent divs
        var panels = this.window.select('.content>div>div');
        panels.invoke('hide');

        if(this.window.select('.servicehelp a')[0]) {
            this.window.select('.servicehelp a')[0].observe('click', AMEXGlobal.instance.showServiceHelp);
        }

        // set the selected tab in the content
        selected_div.show();

        // hack the widths of certain elements to make them display correctly in IE
        var content = selected_div.down('div');
        var windowWidth = Number(content.getWidth())+Number(this.window.down('.content .container').getStyle('padding-left').replace('px', ''))+Number(this.window.down('.content .container').getStyle('padding-right').replace('px', ''))+2;

        this.window.select('.tabs, .tabs ul, .footing, .close').each(function(el) {
            el.setStyle({
                width: windowWidth+'px'
            });
        });

        this.setPosition();
    },
    setPosition: function() {
        if(!this.poi) { return; }
        Element.clonePosition(this.window, this.window.up(), {
            setWidth:     false,
            setHeight:    false,
            offsetLeft:   (this.poi.element.getStyle('left').replace('px', '') - (this.window.offsetWidth/2)) + 13,
            offsetTop:    (this.poi.element.getStyle('top').replace('px', '')  - (this.window.offsetHeight))
        });
    },
    show: function(latlng) {
        this.parentMap.panToLatLng(latlng);

        //this.window.setStyle({ top: '-999em', left: '-999em' });
        this.window.show();
        this.selectTabByName('Address');
        this.setPosition();
    },
    hide: function(event) {
        if(event) { event.stop(); }
        this.window.hide();
    },
    getDirections: function(event) {
        event.stop();
        this.location.getDirections();
    }
});


/* AMEXResultList
 * Controls locations on a paged basis
 * Reports search errors
 * Requires AMEXMap
 */
/*********************************************************************************
 *
 *      DO NOT EDIT BELOW THIS LINE
 *
 *********************************************************************************/
AMEXResultList = Class.create({});

Object.extend(AMEXResultList, {
    RESULTS_PER_PAGE: 10,
    MAX_RESULTS: 100,
    SIDEBAR_ID: 'Sidebar',
    PREVIOUS_ID: 'PreviousPage',
    NEXT_ID: 'NextPage',
    RESULTS_HEADER_ID: 'Query',
    RESULTS_SCROLLER_ID: 'Results',
    RESULTS_LIST_ID: 'locations',
    PAGES_ID: 'ResultsPages',
    RESULTS_HEAD_TPL: new Template('<span>#{search}</span>'),
    ERROR_HEAD_TPL: new Template('<span>#{header}</span>'),
    ERROR_MSG_TPL: new Template('<p>#{content}</p>'),
    HELPFUL_HINTS_TPL: new Template('<h3>#{help_header}</h3><p>#{help_content}</p>'),
    PAGES_TPL: new Template('<strong>#{firstresult}-#{lastresult}</strong> '+Lang.STRINGS.page_of+' #{pages}'),
    MULTIPLE_RESULTS_HEAD_TPL: new Template('<li class="header"><h2>#{header}</h2></li>'),
    MULTIPLE_RESULT_TPL: new Template(
        '<li><h3>#{id}. <a id="location_#{key}" href="#location_#{key}">#{address}</a></h3></li>'
    ),
    WARNING_TPL: new Template('<li class="warning"><p>#{content}</p></li>')
});

AMEXResultList.addMethods({
    initialize: function() {
        this.prevLink = $(AMEXResultList.PREVIOUS_ID);
        this.nextLink = $(AMEXResultList.NEXT_ID);
        this.resultsHeader = $(AMEXResultList.RESULTS_HEADER_ID);
        this.resultsContent = $(AMEXResultList.RESULTS_SCROLLER_ID);
        this.resultList = $(AMEXResultList.RESULTS_LIST_ID);
        this.pages = $(AMEXResultList.PAGES_ID);

        this.prevLink.observe('click', this.prevPage.bindAsEventListener(this));
        this.nextLink.observe('click', this.nextPage.bindAsEventListener(this));
        this.prevLink.addClassName('hide');
        this.nextLink.addClassName('hide');
        this.bypassMultipleResults = false;
        this.bypassNumber = 0;
    },
    prevPage: function(event) {
        event.stop();
        AMEXMap.instance.messageBox.showLoading();
        var page = AMEXMap.MODEL.get('page')-1;
        this.updatePages();
        AMEXMap.instance.model.set('page', page);
        document.fire('model:change');
    },
    nextPage: function(event) {
        event.stop();
        AMEXMap.instance.messageBox.showLoading();
        var page = AMEXMap.MODEL.get('page')+1;
        this.updatePages();
        AMEXMap.instance.model.set('page', page);
        document.fire('model:change');
    },
    updatePages: function() {

        var first = (AMEXMap.instance.model.get('page') * AMEXResultList.RESULTS_PER_PAGE);
        var last = Math.min(
            (first + AMEXResultList.RESULTS_PER_PAGE),
            AMEXMap.instance.model.get('currentLocations').length
        );
        var total = AMEXMap.instance.model.get('currentLocations').length;

        if(first === 0) { this.prevLink.addClassName('hide'); } else { this.prevLink.removeClassName('hide'); }
        if(last == total) { this.nextLink.addClassName('hide'); } else { this.nextLink.removeClassName('hide'); }

        var pages = {
            firstresult: first+1,
            lastresult: last,
            pages: total
        };
        this.pages.update(AMEXResultList.PAGES_TPL.evaluate(pages));

        $(AMEXResultList.RESULTS_HEADER_ID).update(
            AMEXResultList.RESULTS_HEAD_TPL.evaluate({ search: AMEXMap.instance.model.get('searchterms').truncate(70, '&hellip;') })
        );
        $(AMEXResultList.RESULTS_HEADER_ID).addClassName('results');
        if(last == total && total == AMEXResultList.MAX_RESULTS) {
            this.addWarning(AMEXResultList.WARNING_TPL.evaluate({ content: Lang.STRINGS.warnings.max_results.interpolate({ max_results: AMEXResultList.MAX_RESULTS }) }));
        }

        if(!AMEXSearchForm.instance.getAbilities('poi') && !$(AMEXResultList.SIDEBAR_ID).hasClassName('noPOI')) {
            $(AMEXResultList.SIDEBAR_ID).addClassName('noPOI');
        } else if(AMEXSearchForm.instance.getAbilities('poi') && $(AMEXResultList.SIDEBAR_ID).hasClassName('noPOI')) {
            $(AMEXResultList.SIDEBAR_ID).removeClassName('noPOI');
        }
        if($(AMEXResultList.SIDEBAR_ID).hasClassName('searchError')) {
            $(AMEXResultList.SIDEBAR_ID).removeClassName('searchError');
        }
        if($(AMEXResultList.SIDEBAR_ID).hasClassName('multipleResults')) {
            $(AMEXResultList.SIDEBAR_ID).removeClassName('multipleResults');
        }
    },
    clearResults: function() {
        $(AMEXResultList.RESULTS_LIST_ID).removeClassName('multipleResults');
        $(AMEXResultList.RESULTS_SCROLLER_ID).select('p, h3').each(function(item) { item.remove(); });
        $(AMEXResultList.PAGES_ID).update('');
        $(AMEXResultList.RESULTS_HEADER_ID).update('');
        //$(AMEXResultList.RESULTS_HEADER_ID).removeClassName('results');
        this.resultList.update('');
        this.prevLink.addClassName('hide');
        this.nextLink.addClassName('hide');
        this.bypassMultipleResults = false;
        this.bypassNumber = 0;
    },
    selectResult: function(result) {
        this.resultList.select('.active').each(function(item) {
            item.removeClassName('active');
        });
        result.down('div').addClassName('active');

        // scroll the list to this item
        this.resultsContent.scrollTop = result.cumulativeOffset().top - this.resultsContent.cumulativeOffset().top;
    },
    selectMultipleResult: function(event) {
        event.stop();
        $$('.multipleResults a').invoke('stopObserving', 'click');
        this.clearResults();

        var resultIndex = Number(event.target.id.replace('location_', ''));

        AMEXSearchForm.instance.setValuesFromQuery(this.coll.getAt(resultIndex));
        this.bypassMultipleResults = true;
        this.bypassNumber = resultIndex;
        document.fire('search:submit');
    },
    addResult: function(result) {
        this.resultList.insert(result);
        var result = this.resultList.select('li').last();

        result.observe('mouseover', function(event) { result.addClassName('hover'); });
        result.observe('mouseout', function(event) { result.removeClassName('hover'); });
        result.observe('click', function(event) {
            this.selectResult(result);
        }.bindAsEventListener(this));

        return(result);
    },
    addWarning: function(warning) {
        this.resultList.insert(warning);
    },
    showError: function(error, mapObject) { // mapObject is optional
        if(!error) {
            // throw a general map error with the message box if one wasn't provided
            AMEXMap.instance.messageBox.showMessage({
                header: AMEXMap.STRINGS.general_error.header,
                content: AMEXMap.STRINGS.general_error.content,
                action: AMEXMap.STRINGS.actions.continue_link,
                action_link: '#'
            });
            return;
        }
        // on page load, if there is an error, AMEXMap.instance is tough to find for some reason.
        if(mapObject) { AMEXMap.instance = mapObject; }

        $(AMEXResultList.SIDEBAR_ID).addClassName('searchError');

        this.clearResults();
        this.prevLink.addClassName('hide');
        this.nextLink.addClassName('hide');

        // update the header of the result area
        $(AMEXResultList.RESULTS_HEADER_ID).update(
            AMEXResultList.RESULTS_HEAD_TPL.evaluate({ search: AMEXMap.instance.model.get('searchterms').truncate(70, '&hellip;') })
        );
        $(AMEXResultList.RESULTS_SCROLLER_ID).insert(
            AMEXResultList.ERROR_MSG_TPL.evaluate({
                content: error.content.interpolate({
                    search_terms: AMEXMap.instance.model.get('searchterms'),
                    search_radius: AMEXMap.instance.model.get('radius').value+' '+AMEXMap.instance.model.get('radius').units
                })
            })+AMEXResultList.HELPFUL_HINTS_TPL.evaluate(error)
        );
    },
    showMultipleResults: function(collection) {
        this.clearResults();
        this.coll = collection;

        $(AMEXResultList.RESULTS_LIST_ID).addClassName('multipleResults');

        $(AMEXResultList.RESULTS_LIST_ID).insert(
            AMEXResultList.MULTIPLE_RESULTS_HEAD_TPL.evaluate(Lang.STRINGS.multiple_results)
        );

        for(var i = 0; i < collection.getSize(); i++) {
            var add_str = '';
            add_str += ((!collection.getAt(i).getStreet().blank()) ? collection.getAt(i).getStreet()+'<br />' : '');
            add_str += ((!collection.getAt(i).getCity().blank()) ? collection.getAt(i).getCity() : '');
            add_str += ((!collection.getAt(i).getState().blank()) ? ', '+collection.getAt(i).getState() : '');
            add_str += ((!collection.getAt(i).getPostalCode().blank()) ? ', '+collection.getAt(i).getPostalCode()+'' : '');
            $(AMEXResultList.RESULTS_LIST_ID).insert(AMEXResultList.MULTIPLE_RESULT_TPL.evaluate({ key: i, id: i+1, address: add_str }));
        }

        $(AMEXResultList.SIDEBAR_ID).addClassName('multipleResults');

        $$('.multipleResults a').invoke('observe', 'click', this.selectMultipleResult.bindAsEventListener(this));
    }
});

