/*
 * This software is mostly copyright (C) 2005, toEat.com, LLC.  All Rights
 Reserved.  There is some code that is copied out of the Google Maps API.
 That code is not copyrighted by toEat.com, LLC.  All toEatMap code is 
 copyrighted.  Please do not use this without permission.  We're nice people and
 will likely give you permission if you ask.
*/

var loadingImageDiv;
var loadingImage = new Image();
loadingImage.src = "/images/loading.gif";

var curMap; var useMap = true;
var tagList = new Array(); var availableTags = new Array();

var IconOn = new GIcon();
    IconOn.image = "/images/mapfiles/marker.png";
    IconOn.transparent = "http://www.google.com/mapfiles/markerTransparent.png";
    IconOn.shadow = "http://www.google.com/mapfiles/shadow50.png";
    IconOn.iconSize = new GSize(20,34);
    IconOn.iconAnchor =new GPoint(9,34);
    IconOn.shadowSize = new GSize(37,34);
    IconOn.infoWindowAnchor = new GPoint(9,2);
    IconOn.infoShadowAnchor = new GPoint(18,25);
    IconOn.printImage    = "http://www.google.com/mapfiles/markerie.gif";
    IconOn.mozPrintImage = "http://www.google.com/mapfiles/markerff.gif";
    IconOn.printShadow   = "http://www.google.com/mapfiles/dithshadow.gif";
    IconOn.imageMap=[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0];

var IconOff = new GIcon( IconOn );
    IconOff.image = "/images/mapfiles/markeron.png";

function buildMap( useControls, defCoords, defZoom, loadMessage ) {
    curMap = new toEatMap( 'map', null, null, defCoords, defZoom );
    if ( !loadMessage ) loadMessage = "Please wait while toEat.com loads...";
    curMap.infoNotice( loadMessage );

    if ( useControls ) {
        curMap.setupListeners();
        curMap.addControl('full');
    } else {
        curMap.addControl('small');
    }
}

function startClickerMap( point, useControls, defaultMarkerList ) {
    if ( !GBrowserIsCompatible() ) {
        return false;
    }
    if ( $("summaryList") && $("map") ) {
        $("summaryList").innerHTML = $("map").innerHTML;
        $("map").innerHTML = "&nbsp;";
    }
    curMap = new toEatMap( 'clickerMap' );
    curMap.gmap.centerAndZoom( point, 4 );
    if ( useControls )
        curMap.addControl('full');
    if ( typeof defaultMarkerList != "undefined" ) {
        for ( var i = 0; i < defaultMarkerList.length; i++ ) {
            var marker = new GMarker( defaultMarkerList[i].point, curMap.letterIcons[i]);
            curMap.gmap.addOverlay(marker);
        }
    }
    curMap.addControl("clicker");
}

function buildNoMap() {

}

function startLoad( defLoad, useControls, loadMessage, defCoords, defZoom ) {
    if ( !GBrowserIsCompatible() ) {
        useMap = false;
        return buildNoMap(defLoad, defCoords);
    }
    if ( $("panelDD") )
        $("panelDD").innerHTML = "Please wait while toEat.com loads";
    if ( $("summaryList") && $("map") ) {
        $("summaryList").innerHTML = $("map").innerHTML;
        $("summaryList").style.width    = "100%";
        $("map").innerHTML = "&nbsp;";
    }
    buildMap(useControls, defCoords, defZoom, loadMessage);
    
    if ( defLoad.indexOf('JS/') >= 0 ) {
        curMap.updatePanel();
        curMap.inlineLoad(defLoad);
    } else {
        if ( defLoad.indexOf('US/') >= 0 ) {
            // Don't post-process panel XML 
            curMap.loadXML(defLoad, false);
            // Load the panel explicitely
            curMap.updatePanel(defLoad);
        } else
            curMap.loadXML(defLoad, true);
    }
    if ( !defLoad || defLoad == '/' || defLoad == "" ) {
        curMap.searchAroundControl.openPopupWindow();
    }
}

function cityLoad( form ) {
    if ( form.elements[0].value )
        curMap.loadXML('Search/City/' + form.elements[0].value );
}

function openInfoWindow( pk1, type, lat, lng ) {
    if ( curMap )
        curMap.openInfoWindow( pk1, type, lat, lng );
}

function loadCity( url ) {
    document.location = url;
}

function toEatMap( mapContainer, width, height, defaultCoords, defaultZoom ) {
    this.markers = new Array();
    this.buildIcons();
    if ( mapContainer )
        this.mapContainer = document.getElementById(mapContainer);
    else 
        this.mapContainer = document.getElementById("map");

    var map = new GMap(this.mapContainer);
    GEvent.bindDom(window, "resize", map, map.onResize);
    if ( defaultCoords ) {
        map.centerAndZoom(defaultCoords, parseInt(defaultZoom || 14));
    } else {
        map.centerAndZoom(new GPoint(-113.421217627648, 40.7685850162875), 14);
    }
    this.selection(false);
    this.gmap = map;
    GEvent.bind(this.gmap, "click", this, this.mapClick);
    this.extendedFeatures = false;
    this.zoomLevelLabel   = 'States';
    this.defaultLoaded    = false;
    this.suppressMove     = 0;
    this.isMoving = 0;
    this.minLat = 300;  this.minLng = 300;
    this.maxLat = -300; this.maxLng = -300;
}

toEatMap.prototype.addControl = function( type ) {
    if ( type == 'full' ) {
        this.extendedFeatures = true;
        this.gmap.addControl(new GLargeMapControl());
        this.gmap.addControl(new GMapTypeControl());
        //this.gmap.registerKeyHandlers(window.document);
/*
        this.searchAroundControl = new GxControl("Search Around");
        this.searchAroundControl.setPosition(70,14);
        this.searchAroundControl.positionPopup( new GPoint( 125, 150 ) );
        this.searchAroundControl.setImages( "/images/controls/mapControl.png",
            "/images/controls/mapControlShadow.png" );
        this.searchAroundControl.setContentHTML(
            '<div class="mapPopup">' +
            '<h3>Search Around Any Address:</h3>' +
            '<form id="searchAround" method="post" action="/" onsubmit="processSearch(this); return false;"><input type="hidden" name="what" value=""/>' + 
            'Address: <input type="text" name="around"/><br/>' +
            '<input type="submit" value="Find"/>' +
            '</form>' +
            '</div>' +
            '<br/>'
        );
        this.gmap.addControl( this.searchAroundControl );
*/
        GEvent.bind(this.gmap, "click", this, this.singleFireClose );
    }
    else if ( type == "clicker" ) {
        this.selection(true);
        this.markerFromClick = null;
    }
    else if ( type == "small" ) {
        this.gmap.addControl(new GMapTypeControl());
        this.gmap.addControl(new GSmallMapControl());
    }
};

toEatMap.prototype.singleFireClose = function( ) {
    if ( this.searchAroundControl && !this.firedClose ) {
        this.searchAroundControl.closePopupWindow();
        this.firedClose = true;
    }
}

toEatMap.prototype.selection = function( newVal ) {
    if ( typeof newVal == "undefined" )
        return this.acceptSelection;
    if ( newVal )
        this.acceptSelection = true;
    else
        this.acceptSelection = false;
    return this.acceptSelection;
}

toEatMap.prototype.mapClick = function( overlay, point ) {
    if ( this.acceptSelection != true ) return;
    try {
        var updated = false;
        if ( overlay ) {
            // Highlighted click marker, nothing really to do here...
            if ( overlay.icon.image == "/images/mapfiles/clicker/markeron.png" ) {

            }
            // Unhighlighted click marker, clicking to activate it
            else if ( overlay.icon.image == "/images/mapfiles/clicker/marker.png" ) {
                updated = true;
                var newMarker = new GIcon( overlay.icon );
                newMarker.image = "/images/mapfiles/clicker/markeron.png";
                newMarker.shadow = "http://www.google.com/mapfiles/shadow50.png";
                overlay.icon = newMarker;
            }
            // Lettered marker
            else {
                var letter = overlay.icon.image.substr( overlay.icon.image.indexOf("marker") + 6, 1);
                // We're turned off, so highlight this marker
                if ( overlay.icon.image.indexOf("on.png") == -1 ) {
                    updated = true;
                    var newMarker = new GIcon( overlay.icon );
                    newMarker.image = "/images/mapfiles/clicker/marker" + letter + "on.png";
                    newMarker.shadow = "http://www.google.com/mapfiles/shadow50.png";
                    overlay.icon = newMarker;
                }
            }
            try {
                document.getElementById("latitude").value = overlay.point.y;
                document.getElementById("longitude").value = overlay.point.x;
            } catch(e) { }
        } else {
            /*if ( this.markerFromClick )
                this.gmap.removeOverlay(this.markerFromClick);*/

            var defaultIcon = new GIcon(this.baseIcon);
            defaultIcon.image = "/images/mapfiles/clicker/markeron.png";
            defaultIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            this.markerFromClick = new GMarker( point, defaultIcon );
            this.gmap.addOverlay( this.markerFromClick );
            overlay = this.markerFromClick;
            updated = true;
        }
        if ( updated ) {
            if ( this.highlightedMarker ) {
                if ( this.highlightedMarker.icon.image == "/images/mapfiles/clicker/markeron.png" ) {
                    var newMarker = new GIcon( this.highlightedMarker.icon );
                    newMarker.image = "/images/mapfiles/clicker/marker.png";
                    this.highlightedMarker.icon = newMarker;
                } else {
                    var letter = this.highlightedMarker.icon.image.substr( this.highlightedMarker.icon.image.indexOf("marker") + 6, 1);
                    var newMarker = new GIcon( this.highlightedMarker.icon );
                    newMarker.image = "/images/mapfiles/clicker/marker" + letter + ".png";
                    this.highlightedMarker.icon = newMarker;
                }
                this.highlightedMarker.icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
                this.gmap.removeOverlay(this.highlightedMarker);
                this.gmap.addOverlay(this.highlightedMarker);
            }
            this.gmap.removeOverlay(overlay);
            this.gmap.addOverlay(overlay);
        }
        if ( overlay )
            this.highlightedMarker = overlay;
        this.highlightedPoint  = point;
        GEvent.trigger(this, "pointupdate");
        try {
            document.getElementById("latitude").value = point.y;
            document.getElementById("longitude").value = point.x;
        } catch(e) { }
    } catch(e) { alert("Error processing action: " + e); }
}

toEatMap.prototype.getHighlightedPoint = function() {
    return this.highlightedPoint;
}

toEatMap.prototype.panelContent = function( caption, contentOrUrl, useAdverts ) {
    if ( typeof document.getElementById("panelDD") == "undefined" ) {
        return false;
    }

    if ( contentOrUrl.indexOf("/") == 0 ) {
        return this.remotePanelUpdate(caption, contentOrUrl, useAdverts );
    }
    try { 
        if ( $("panelContentTitle") )
            $("panelContentTitle").innerHTML = caption;
        if ( $("panelDD") ) {
            $("panelDD").innerHTML = contentOrUrl;
            if ( $("panelList") ) {
                $("panelList").style.height = parseInt($("map").offsetHeight + $("summaryList").offsetHeight) + "px";
            }
        } 
    } catch(e) {
        /* IE will sometimes throw DOM errors on links */
        if ( $("panelContentTitle") )
            $("panelContentTitle").innerHTML = caption;
        if ( $("panelDD") ) {
            $("panelDD").innerHTML = "Sorry, toEat.com failed to do the right thing.  Not to point fingers, but this error exists solely with Internet Explorer.  If you were using a standards compliant browser, this would be working.  We recommend Firefox or Opera.";
        }
    };
};

toEatMap.prototype.remotePanelUpdate = function( caption, url, useAdverts ) {
    var request  = GXmlHttp.create();
    var t=this;
    request.open('GET', '/Panel/' + url, true);
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            t.panelContent( caption, request.responseText, useAdverts );
        }
    }
    request.send(null);
};

var processMove = false;

toEatMap.prototype.clearListeners = function() {
    GEvent.clearListeners( this.gmap, "moveend" );
    GEvent.clearListeners( this.gmap, "zoom" );
    GEvent.clearListeners( this.gmap, "infowindowopen" );
    GEvent.clearListeners( this.gmap, "infowindowclose" );
    //GEvent.clearListeners( this.gmap, "zoomend" );
};


toEatMap.prototype.setupListeners = function() {
    //GEvent.bind(this.gmap, "zoom",    this, this.mapZoomedHandler);
    GEvent.bind(this.gmap, "infowindowopen",  this, this.openedWindow);
    GEvent.bind(this.gmap, "infowindowclose", this, this.closedWindow);
    GEvent.bind(this.gmap, "moveend", this, this.mapChangedHandler);
    GEvent.bind(this.gmap, "zoom", this, this.closeInfoWindows);
    if ( document.getElementById("message") ) {
        document.getElementById("message").innerHTML = "Attached moveend, zoom to this.mapChangedHandler";
    }
};

toEatMap.prototype.closeInfoWindows = function() {
    this.gmap.closeInfoWindow();
    this.mapChangedHandler();
}

toEatMap.prototype.openedWindow = function() {
    this.openWindow = true;
}

toEatMap.prototype.closedWindow = function() {
    this.openWindow = false;
}

toEatMap.prototype.reloadZoom = function() {
    processMove = true;
    /*if ( document.getElementById("message") )
        document.getElementById("message").innerHTML = "Zoom: " + this.gmap.getZoomLevel();*/
    this.reloadMap( true );
};

toEatMap.prototype.addMatch = function( pk1, label, query, point ) {
    //var m = new GxMarker( point );
    var m = new GMarker( point );
    m.setTooltip( label );
    this.gmap.addOverlay(m);
    this.loadedMarkers["" + pk1] =  m;
    if ( point.y < this.minLat )
        this.minLat = point.y;
    else if ( point.y > this.maxLat )
        this.maxLat = point.y;
    if ( point.x < this.minLng )
        this.minLng = point.x;
    if ( point.x > this.maxLng )
        this.maxLng = point.x;

    var t = this;
    GEvent.addListener(m, "click", function( coords ) {
        //m.openInfoWindow(winDom);
        t.openInfoWindow( pk1, 'city', point.y, point.x );
    });
    return m;
};

toEatMap.prototype.suppressNextMove = function (count) {
    if ( count > 0 )
        this.suppressMove = count;
    else
        this.suppressMove = 0;
};

toEatMap.prototype.mapChangedHandler = function() {
    this.suppressMove--;
    if ( this.suppressMove >= 0 ) {
        return;
    }
    if ( this.openWindow ) {
        return;
    }
    this.suppressMove = 0;
    this.refreshView();
}

toEatMap.prototype.centerAndZoomOnBounds = function(bounds) {
    var center_lat = (bounds.getNorthEast().lat() +
        bounds.getSouthWest().lat()) / 2.0;
    var center_lng = (bounds.getNorthEast().lng() +
        bounds.getSouthWest().lng()) / 2.0;
    var center = new GLatLng(center_lat,center_lng)
    this.gmap.setCenter(center, this.gmap.getBoundsZoomLevel(bounds));
}

toEatMap.prototype.autoCenter = function() {
    var minX, maxX, minY, maxY;
    for ( var i in this.loadedMarkers ) {
        if ( !minX || this.loadedMarkers[i].getPoint().lat() < minX )
            minX = this.loadedMarkers[i].getPoint().lat();
        if ( !maxX || this.loadedMarkers[i].getPoint().lat() > maxX )
            maxX = this.loadedMarkers[i].getPoint().lat();
        if ( !minY || this.loadedMarkers[i].getPoint().lng() < minY )
            minY = this.loadedMarkers[i].getPoint().lng();
        if ( !maxY || this.loadedMarkers[i].getPoint().lng() > maxY )
            maxY = this.loadedMarkers[i].getPoint().lng();
    }
    if ( minX && minY && maxX && maxY ) {
        var bounds = new GLatLngBounds(
            new GLatLng(minX, minY), new GLatLng( maxX, maxY ));
        this.centerAndZoomOnBounds(bounds);
    }
}

toEatMap.prototype.refreshView = function() {
    if ( !this.lastMoved ) {
        this.reloadMapFromCurrentCoords();
    } else {
        var currentBounds = this.gmap.getBoundsLatLng();
        var spanX  = this.lastMoved.maxX - this.lastMoved.minX;
        var deltaX = Math.abs(this.lastMoved.minX - currentBounds.minX);
        var spanY  = this.lastMoved.maxY - this.lastMoved.minY;
        var deltaY = Math.abs(this.lastMoved.minY - currentBounds.minY);
        var movePercentage = new GSize( deltaX/spanX, deltaY/spanY );
        if ( movePercentage.width >= 0.10 || movePercentage.height >= 0.10 ) {
            this.reloadMapFromCurrentCoords();
        }
    }
}

toEatMap.prototype.reloadMapFromCurrentCoords = function(isRefresh) {
    var bounds = this.gmap.getBoundsLatLng();
    var latLngString =
            bounds.minY + "," + bounds.minX + "x" +
            bounds.maxY + "," + bounds.maxX + "@" +
            this.gmap.getZoomLevel();

    setCursor(this.mapContainer, "wait");
    this.lastMoved     = bounds;
    this.lastZoomLevel = parseInt(this.gmap.getZoomLevel());
    if ( isRefresh )
        latLngString += "?reload=1"
    try { this.inlineLoad("JS/" + latLngString); }
    catch(e) { alert("Inline load failed: " + e); }
}


toEatMap.prototype.refreshMapView = function() {
    if ( this.isMoving ) {
        return;
    }

    this.isMoving = true;
    var t = new Date;
    var process = false;
    //this.notice("Suppressing the movement: " + this.suppressMove + ";" + t.toString());
    if ( this.suppressMove > 0 ) {
        this.suppressMove--;
        this.isMoving = false;
        return;
    }
    try {
        if ( !this.lastMoved ) {
            this.lastMoved = this.gmap.getBoundsLatLng();
            this.isMoving = false;
            return false;
        }

        if ( typeof this.lastZoomLevel == "undefined" ) {
            this.lastZoomLevel = parseInt(this.gmap.getZoomLevel());
            this.isMoving = false;
            return false;
        }
        var bounds = this.gmap.getBoundsLatLng();

        if ( this.lastZoomLevel != this.gmap.getZoomLevel() ) {
            process = true;
        }
        else if ( this.lastZoomLevel > 13 && this.gmap.getZoomLevel > 13 ) {
            process = false;
        } else { 
            var dist = new Object();
            dist.x = Math.abs(this.lastMoved.maxX - bounds.maxX);
            dist.y = Math.abs(this.lastMoved.maxY - bounds.maxY);
            var scaleX = bounds.maxX - bounds.minX;
            var scaleY = bounds.maxX - bounds.minX;
            // this is not accurate, and is a hack [fixme] 
            if ( dist.x > scaleX * 0.10 )
                process = true;
            else if ( dist.y > scaleY * 0.10 )
                process = true;
        }
        if ( !process ) {
            this.isMoving = false;
            return;
        }
      
        this.reloadMapFromCurrentCoords();
        this.isMoving = false;
    } catch ( e ) {
        this.notice("Sorry, we encountered a system error: " + e);
        this.isMoving = false;
        //document.getElementById("message").innerHTML = "mapChangedHandler() Error: " + e;
    }
};

toEatMap.prototype.reloadMap = function( isZoom ) {
    var isZoom = false;
    return false;
    if ( !processMove || !lastZoomLevel ) 
        return false;
    if ( lastZoomLevel >= 12 && this.gmap.getZoomLevel() >= 12 ) {
        if ( this.zoomLevelLabel != 'States' ) {
            var center = this.gmap.getCenterLatLng();
            var latLngStr = center.y + ',' + center.x + '@' + this.gmap.getZoomLevel();
            this.zoomLevelLabel = 'States';
            this.loadXML(latLngStr);
            processMove = false;
        }
        lastZoomLevel = parseInt(this.gmap.getZoomLevel());
        processMove = false;
        return false;
    }
    if ( lastZoomLevel >= 5 && this.gmap.getZoomLevel() >= 5 && this.zoomLevelLabel == 'Metro' ) {
        lastZoomLevel = parseInt(this.gmap.getZoomLevel());
        processMove = false;
        return false;
    }
    if ( document.getElementById("message") )
        document.getElementById("message").innerHTML = "Checking if we should remap";
    if ( !isZoom && this.loadedMarkers.length < 50 )
        return false;

    var center = this.gmap.getCenterLatLng();
    var latLngStr = center.y + ',' + center.x + '@' + this.gmap.getZoomLevel();
    if ( this.gmap.getZoomLevel() > 12 )
        this.zoomLevelLabel = 'States';
    else if ( this.gmap.getZoomLevel() > 5 )
        this.zoomLevelLabel = 'Metro';
    else
        this.zoomLevelLabel = 'Restaurant';
    this.loadXML(latLngStr);
    processMove = false;
    lastZoomLevel = parseInt(this.gmap.getZoomLevel());
};

toEatMap.prototype.markerList = function( index ) {
    return this.loadedMarkers[index];
}

toEatMap.prototype.highlightMarker = function( index, tooltip ) {
    if ( this.loadedMarkers[index] ) {
        if ( tooltip ) 
            this.loadedMarkers[index].showTooltip();
        else
            this.loadedMarkers[index].hideTooltip();
    }
}

toEatMap.prototype.addMarker = function( type, name, id, lat, lng, overlay ) {
    //var m = new GxMarker( new GPoint( lng, lat ), this.iconMap[type], name );
    var m = new GMarker( new GPoint( lng, lat ), this.iconMap[type] );
    if ( type == "rated" )
        type = "restaurant";
    //m.setTooltip( name );
    this.gmap.addOverlay(m);
    this.loadedMarkers["" + id] = m;
    if ( lat < this.minLat )
        this.minLat = lat;
    else if ( lat > this.maxLat )
        this.maxLat = lat;
    if ( lng < this.minLng )
        this.minLng = lng;
    if ( lng > this.maxLng )
        this.maxLng = lng;

    if ( overlay ) {
        var t = this;
        var url = "/Map/Info/" + type + "/" + id + "?ll=" + lat + "," + lng;
        GEvent.addListener(m, "click", function( coords ) {
            t.suppressNextMove(1);
            var req = GXmlHttp.create();
            req.open("GET", url, true );
            req.onreadystatechange = function() {
                if ( req.readyState == 4 ) {
                    m.openInfoWindowHtml( req.responseText );
                }
            };
            req.send(null);
        });
    }
    return m;
};


toEatMap.prototype.zoomOnceAtPoint = function( lat, lng ) {
    var curZoom = parseInt(this.gmap.getZoomLevel());
    if ( curZoom > 0 ) 
        curZoom--;
    this.gmap.centerAndZoom(new GPoint(lng, lat), parseInt(curZoom));
}

toEatMap.prototype.zoomAtPoint = function( zoomInc, lat, lng ) {
    var curZoom = parseInt(this.gmap.getZoomLevel());
    if ( curZoom > 0 ) 
        curZoom -= parseInt(zoomInc);

    if ( curZoom < 0 ) curZoom = 0;
    this.gmap.centerAndZoom(new GPoint(lng, lat), parseInt(curZoom));
}

toEatMap.prototype.openInfoWindow = function( id, type, lat, lng ) {
    var req = GXmlHttp.create();
    req.open("GET", "/Map/Info/" + type + "/" + id, true);
    var t=this;
    req.onreadystatechange = function() {
        if ( req.readyState == 4 ) {
            t.suppressNextMove(1);
            t.gmap.openInfoWindowHtml( new GPoint(lng, lat), req.responseText );
        }
    };
    req.send(null);
};

toEatMap.prototype.addRegionMarker = function() {

};

toEatMap.prototype.addRestaurantMarker = function() {

};

toEatMap.prototype.addSpecialMarker = function() {

};

toEatMap.prototype.addRegionMarker = function() {

};

toEatMap.prototype.clearNotice = function( ) {
    if ( typeof document.getElementById("mapMessage") != "undefined" ) {
        document.getElementById("mapMessage").setAttribute("style", "");
        document.getElementById("mapMessage").innerHTML = "";
    }
}

toEatMap.prototype.errorNotice = function( message ) {
    GEvent.addListener(this.messageInfoWindow, "infowindowclose", function() {
        this.map.removeOverlay(messageMarker)
    });
}

var msgIcon = new GIcon();
msgIcon.image  = "/images/mapfiles/noticeMarker.png";
msgIcon.shadow = "/images/mapfiles/2x2.gif";
msgIcon.iconSize = new GSize(64,117);
msgIcon.shadowSize = new GSize(2,2);
//msgIcon.iconAnchor = new GPoint(-120, 180);
msgIcon.iconAnchor = new GPoint(0, 117);
msgIcon.infoWindowAnchor = new GPoint(35, 53);

toEatMap.prototype.popupCloseClick = function() {
    if ( this.popupWindow && this.popupWindow.isVisible() ) {
        this.popupWindow.hide();
    }
}

toEatMap.prototype.infoNotice = function( message ) {
    return;
    if ( !this.popupWindow ) {
        if ( !this.popupWinDiv ) {
            this.popupWinDiv = this.gmap.createPane();
            this.gmap.container.appendChild(this.popupWinDiv);
        }
        this.popupWindow = new GxPopupWindow( this.popupWinDiv, 6000, false );
        GEvent.bind(this.popupWindow, "closeclick", this, this.popupCloseClick);
        this.popupWindow.positionAt(125,150);
    } else if ( this.popupWindow.isVisible() ) {
        this.popupWindow.hide();
    }
    this.popupWindow.setContent(message);
    this.popupWindow.show();
    return;

    var center = this.gmap.getCenterLatLng();
    var bounds = this.gmap.getBoundsLatLng();
    /*var b = this.gmap.spec.getBitmapCoordinate(center.y, center.x, this.gmap.zoomLevel);
    var coord = this.gmap.getDivCoordinate( b.x - 64, b.y - 117 );
    var foo = this.gmap.getLatLng(coord.x, coord.y)
    alert(coord.x + ", " + coord.y);
    return false;*/
//    var messageMarker = new GMarker( new GPoint(bounds.minX, bounds.minY), msgIcon );
// shoot me for this:
    try { this.searchAroundControl.closePopupWindow(); } catch(e) { };
    var mLat = (bounds.maxY - bounds.minY) / 4;
    var mLng = (bounds.maxX - bounds.minX) / 4;
    this.infoNoticeMarker = new GMarker(
        new GPoint(center.x - mLng, center.y - mLat), msgIcon );
    this.gmap.addOverlay(this.infoNoticeMarker);
    this.infoNoticeMarker.openInfoWindowHtml("<div style=\"white-space: nowrap\">" + message + "</div>");

    var map = this.gmap; var marker = this.infoNoticeMarker;
    var closeIt = function() {
        map.closeInfoWindow(); map.removeOverlay(marker);
    };
    GEvent.addListener(this.infoNoticeMarker, "infowindowclose", closeIt);
    GEvent.addListener(this.infoNoticeMarker, "click", closeIt);
}

toEatMap.prototype.notice = function( message ) {
    if ( document.getElementById("mapMessage") ) {
        document.getElementById("mapMessage").setAttribute("style", "border: 1px solid #555; border-bottom: none; padding: 0 1em;");
        document.getElementById("mapMessage").innerHTML = message;
    }
};

toEatMap.prototype.processXML = function( xmlDoc, updatePanel ) {
    if ( typeof updatePanel == "undefined" || updatePanel )
        updatePanel = 1;
    if ( !xmlDoc ) {
        this.notice("Unable to display any data!");
        return false;
    }
    var mk = xmlDoc.getElementsByTagName("markers");

    if ( !mk || mk.length < 0 )
        return false;
    if ( typeof mk[0].getAttribute("hits") != "undefined" && mk[0].getAttribute("hits") == "0" ) {
        if ( document.getElementById('searchForm') && mk[0].getAttribute("what") ) {
            var f = document.getElementById('searchForm');
            f.elements[0].value = mk[0].getAttribute("what");
            f.elements[1].value = mk[0].getAttribute("where");
        }
        if ( mk[0].getAttribute("hits") == "0" )
            this.infoNotice( "Sorry, there were no search results");
        else if ( mk[0].getAttribute("why") )
            this.infoNotice( mk[0].getAttribute("why") );
        else
            this.notice( "Search results for: " + mk[0].getAttribute("what") );
        return false;
    }

    if ( mk[0] && mk[0].getAttribute("suppress") ) {
        this.notice("Suppressing next move");
        this.suppressNextMove(mk[0].getAttribute("suppress"));
    }
    if ( mk[0] && mk[0].getAttribute("updatePanel") == "0" ) {
        updatePanel = 0;
    }

    if ( mk[0] && mk[0].getAttribute("lng") && mk[0].getAttribute("lat") ) {
        this.gmap.centerAndZoom(
            new GPoint(mk[0].getAttribute("lng"), mk[0].getAttribute("lat")),
            parseInt(mk[0].getAttribute("zoom"))
        );
        lastZoomLevel = parseInt(this.gmap.getZoomLevel());
    } else {
        this.notice("Sorry, there is no data to display.  This is likely a data problem.");
        return false;
    }
    this.gmap.clearOverlays();
    this.loadedMarkers = new Array();
    var markers = xmlDoc.getElementsByTagName("marker");
    this.hasRestaurants = false;
    this.loadedRestaurants  = 0;
    this.loadedStates       = 0;
    this.loadedMetros       = 0;
    this.loadedCities       = 0;
    
    for ( var i = 0; i < markers.length; i++ ) {
        if ( markers[i].getAttribute("type") == "restaurant" ) {
            this.hasRestaurants = true;
            this.loadedRestaurants++;
        } else if ( markers[i].getAttribute("type").toLowerCase() == "state" ) {
            this.loadedStates++;
        } else if ( markers[i].getAttribute("type").toLowerCase() == "metro" ) {
            this.loadedMetros++;
        } else if ( markers[i].getAttribute("type").toLowerCase() == "city" ) {
            this.loadedCities++;
        }
        if ( markers[i].getAttribute("type").toLowerCase() != "rural" ) {
            var useOverlay = true;
            if ( markers[i].getAttribute("overlay") &&
                 markers[i].getAttribute("overlay") == "false" )
                 useOverlay = false;
            this.addMarker(
                markers[i].getAttribute("type"),
                markers[i].getAttribute("title"),
                markers[i].getAttribute("pk1"),
                markers[i].getAttribute("lat"),
                markers[i].getAttribute("lng"),
                useOverlay
            );
        }
    }
    this.notice("Done loading, continue to zoom and pan around the map to find where you want to eat");
    whereBlur( document.getElementById("searchWhere") );

	if ( this.popupWindow ) this.popupWindow.hide();
    if ( updatePanel )
        curMap.updatePanel();
    return true;
};

var toggleTimeout; var useToggleActions = true;
function setToggleActions(enabled) { useToggleActions = !!enabled; }
function toggleTag( tag ) {
    if ( !useToggleActions ) return false;
    /* Reset if the user deselects _all_ tags */
    if ( tagList.length == 0 && tag.checked == false ) {
        tagList = availableTags;
    }
    if ( !tag.checked ) {
        for ( var i = 0; i < tagList.length; i++ ) {
            if ( tagList[i] == tag.name ) {
                tagList.splice(i, 1);
                continue;
            }
        }
    } else {
        tagList.push(tag.name);
    }
    if ( toggleTimeout )
        clearTimeout(toggleTimeout);
    toggleTimeout = setTimeout(
        function() { curMap.reloadMapFromCurrentCoords(true); }, 250
    );
}

function toggleOnlyTag( tag ) {
    if ( !useToggleActions ) return false;
    tagList = new Array(); tagList.push(tag);
    if ( toggleTimeout )
        clearTimeout(toggleTimeout);
    toggleTimeout = setTimeout(
        function() { curMap.reloadMapFromCurrentCoords(true); }, 250
    );
}

function toggleAllTags() {
    if ( !useToggleActions ) return false;
    tagList = availableTags;
    if ( toggleTimeout )
        clearTimeout(toggleTimeout);
    toggleTimeout = setTimeout(
        function() { curMap.reloadMapFromCurrentCoords(true); }, 250
    );

}

function clearAllTags() {
    var inputEl = document.getElementsByTagName("input");
    setToggleActions(false);
    if ( !inputEl ) return false;
    for ( var i = 0; i < inputEl.length; i++ ) {
        if ( inputEl[i].id.indexOf("tag-") == 0 ) {
            inputEl[i].checked = false;
        }
    }
    setToggleActions(true);
    tagList = new Array();
}

var hoverDefaultText;
function updateAddressHover(label) {
    if ( $("addressHover") )
        $("addressHover").innerHTML = label;
}
function clearAddressHover(previousText) {
    if ( previousText) hoverDefaultText = previousText;
    if ( typeof hoverDefaultText == "undefined" ) hoverDefaultText = "<a href=\"/My/Profile\">Edit Your Saved Locations</a>";
    try {
    if ( $("addressHover") )
        $("addressHover").innerHTML = hoverDefaultText;
    } catch(e) { };/* IE is stupid, and keeps throwing an eror */
}

function setCursor( container, cursor ) {
    try {
        container.style.cursor = cursor;
    }
    catch ( c ) {
        if ( cursor == "pointer" )
            setCursor("hand");
    }
};

/*
 This function just adds the overlays, but does not clear them.  Probably
 best to generalize the processXML function, but I figure at this point I
 will be editing this heavily and I don't want to modify or break the
 functionality of processXML.
*/
toEatMap.prototype.processInline = function( doc ) {
    var t = this;
    if ( this.popupWindow && this.popupWindow.isVisible() ) 
        this.popupWindow.hide();
    try { eval(doc); }
    catch ( e ) {
        alert("Sorry, there was a service error: " + e);
        this.notice("Sorry, there was a service error: " + e);
        return;
        //document.getElementById("message").innerHTML = "Error: " + e;
    }
    try { t.searchAroundControl.closePopupWindow(); } catch(e) { };
    if ( this.infoNoticeMarker ) {
        this.gmap.closeInfoWindow();
        this.gmap.removeOverlay(this.infoNoticeMarker);
        this.infoNoticeMarker = null;
    }
    setCursor( this.mapContainer, "auto");
    this.lastMoved     = this.gmap.getBoundsLatLng();
    this.lastZoomLevel = parseInt(this.gmap.getZoomLevel());
    this.notice("Thanks for waiting!");
    whereBlur( document.getElementById("searchWhere") );
    return;
};

toEatMap.prototype.inlineLoad = function( url, waitMessage, dontUseTags ) {
    if ( this.isMoving ) {
        //document.getElementById("urlMessage").innerHTML = "not processing xml - map is moving";
        return;
    }
    if ( 0 ) {/*!loadingImageDiv ) {*/
        loadingImageDiv = document.createElement("div");
        loadingImageDiv.style.position = "absolute";
        loadingImageDiv.style.zIndex   = "5500";
        var img = document.createElement("img");
        img.src = loadingImage.src;
        img.alt = "Loading...";
        loadingImageDiv.appendChild(img);
        loadingImageDiv.style.top = (this.gmap.container.offsetTop + this.gmap.container.offsetHeight + 2) + "px";
        loadingImageDiv.style.left = (this.gmap.container.offsetLeft + this.gmap.container.offsetWidth - 14) + "px";
        document.body.appendChild(loadingImageDiv);
    }
    //loadingImageDiv.style.display = "";
    if ( !waitMessage ) waitMessage = "Please wait while toEat.com loads...";
    this.infoNotice(waitMessage);
    var request = GXmlHttp.create();
    this.loadedMarkers    = new Array();
    this.availableMarkers = new Array();
    var t=this;
    if ( url ) 
        this.lastURL = url;
    else
        this.lastURL = '';
    if ( tagList.length > 0 && dontUseTags != true ) {
        if ( url.indexOf("?") >= 0 )
            url += '&tags=' + encodeURI(tagList.join(","));
        else
            url += '?tags=' + encodeURI(tagList.join(","));

    }
    request.open('GET', '/Map/' + url, true);
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            t.processInline( request.responseText );
            //loadingImageDiv.style.display = "none";
        }
    }
    request.send(null);
};

toEatMap.prototype.rpc = function( url, handler ) {
    var request  = GXmlHttp.create();
    request.open('GET', '/Map/' + url, true);
    request.onreadystatechange = function() {
        if ( request.readyState == 4 && handler ) {
            handlerprocessXML( request );
        }
    }
    request.send(null);
};

toEatMap.prototype.loadXML = function( url, postProcess ) {
    var request  = GXmlHttp.create();
    this.loadedMarkers    = new Array();
    this.availableMarkers = new Array();
    if ( typeof postProcess == "undefined" )
        postProcess = true;
    var t=this;
    if ( url ) 
        this.lastURL = url;
    else
        this.lastURL = '';
    if ( document.getElementById("urlMessage") )
        document.getElementById("urlMessage").innerHTML = "Loading /Map/" + url;
    request.open('GET', '/Map/' + url, true);
    if ( url != "" || url )
        try { t.searchAroundControl.closePopupWindow(); } catch(e) { };
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            t.processXML( request.responseXML, postProcess );
        }
    }
    request.send(null);
};

toEatMap.prototype.removeMarker = function() {

};

toEatMap.prototype.removeAllMarkers = function() {
    this.gmap.clearOverlays();
    /*
     Re-add static overlays
    */
};

toEatMap.prototype.updatePanel = function( where ) {
    var panel = document.getElementById("panel");
    if ( !panel ) 
        return false;
    var request  = GXmlHttp.create();
    var center = curMap.gmap.getCenterLatLng();
    if ( !where )
        where  = center.y + "," + center.x + "@" + curMap.gmap.getZoomLevel();

    request.open('GET', '/Panel/' + where, true);
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            panel.innerHTML = request.responseText;
            if ($("searchFilterList")) {
                //this.searchFilter = new AccordionList($("searchFilterList"));
            }
        }
    };
    request.send(null);
}

toEatMap.prototype.buildIcons = function() {
    this.iconMap  = new Array();
    this.baseIcon = new GIcon();
        var p="http://www.google.com/mapfiles/";
        this.baseIcon.image=p+"marker.png";
        this.shadow=p+"shadow50.png";
        this.baseIcon.iconSize=new GSize(20,34);
        this.baseIcon.shadowSize=new GSize(37,34);
        this.baseIcon.iconAnchor=new GPoint(9,34);
        this.baseIcon.infoWindowAnchor=new GPoint(9,2);
        this.baseIcon.infoShadowAnchor=new GPoint(18,25);
        this.baseIcon.transparent=p+"markerTransparent.png";
        this.baseIcon.imageMap=[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0];
        this.baseIcon.printImage    = p+"markerie.gif";
        this.baseIcon.mozPrintImage = p+"markerff.gif";
        this.baseIcon.printShadow   = p+"dithshadow.gif";
    this.iconMap["state"] = new GIcon(this.baseIcon);
    this.iconMap["metro"] = new GIcon(this.baseIcon);
    this.iconMap["city"]  = new GIcon(this.baseIcon);
    this.iconMap["rural"] = new GIcon(this.baseIcon);
    this.iconMap["restaurant"] = new GIcon(this.baseIcon);
        this.iconMap["restaurant"].image  = "/images/markers/rmarker.png";
        this.iconMap["restaurant"].shadow = p + "shadow50.png";
    this.iconMap["rated"] = new GIcon(this.baseIcon);
        this.iconMap["rated"].image  = "/images/markers/rmarker_rated.png";
        this.iconMap["rated"].shadow = p + "shadow50.png";
    this.iconMap["refinement"] = new GIcon(this.baseIcon);
        this.iconMap["refinement"].iconSize = new GSize(24,34);
        this.iconMap["refinement"].image  = "/images/markers/qmarker.png";
        this.iconMap["refinement"].shadow = "";

    this.iconMap["Block"] = new GIcon(this.baseIcon);
        this.iconMap["Block"].iconSize = new GSize(29,29);
        this.iconMap["Block"].image  = "/images/markers/zoom.png";
        this.iconMap["Block"].shadow = "/images/markers/zooms.png";
        this.iconMap["Block"].shadowSize = new GSize(29,29);
        this.iconMap["Block"].iconAnchor = new GPoint(12,10);
        this.iconMap["Block"].infoWindowAnchor = new GPoint(9,18);

    this.letterIcons = new Array();
    for ( var i = 0; i < 26; i++ ) {
        this.letterIcons[i] = new GIcon(this.baseIcon);
        var letter = String.fromCharCode("A" . charCodeAt(0) + i);
        this.letterIcons[i].image = "http://www.google.com/mapfiles/marker" + letter + ".png";
        this.letterIcons[i].shadow = "http://www.google.com/mapfiles/shadow50.png";
    }
};

function whereBlur( el ) {
    if ( !el )
        return false;

    if ( el.value == "" ) {
        //el.style.color = "#777;"
        if ( curMap.gmap.getZoomLevel() < 8 ) 
            el.value = "In the area displayed";
        else
            el.value = "Enter City and State";
    } else {
        //var newCenter = lookupAddress( el.value );
    }
}

var tabMapIndex = 0;
function Tab( label, isActive, container ) {
    this.container = container;
    this.item = document.createElement("li");
    this.span = document.createElement("span");
    this.link = document.createElement("a");
    if ( isActive )
        this.item.className = "tab active";
    else
        this.item.className = "tab";
    this.link.href = "javascript:void(0)";
    this.label = label;
    this.span.appendChild(document.createTextNode(label));
    this.link.appendChild(this.span);
    this.item.appendChild(this.link);
}

Tab.prototype.click = function() {
    this.container.switchTabs(this.label);
}

Tab.prototype.activate = function() {
    this.item.className = "tab active";
}

Tab.prototype.deactivate = function() {
    this.item.className = "tab";
}

function TabbedMap( element, properties ) {
    this.container = document.getElementById(element);
    this.tabs = new Array();
    var defaultTab;
    defaultTab = properties.selected || properties.modes[0] || 'map';
    defaultTab = defaultTab.toLowerCase();
    for ( var i in properties.modes ) {
        var isActive = defaultTab == properties.modes[i].toLowerCase()
            ? true : false;
        this.tabs.push(new Tab(properties.modes[i], isActive, this));
    }
    this.displayedElement = defaultTab;
    this.loader = properties.loader;
    this.properties = new Object();
    this.address = properties.address;
    this.properties.mapWidth     = properties.width || 300;
    this.properties.mapHeight    = properties.mapHeight || 300;
    this.properties.widgetWidth  = properties.width  || 300;
    this.properties.widgetHeight = properties.height || 300;
    if ( properties.onUpdate )
        this.properties.onUpdate = properties.onUpdate;
}

TabbedMap.prototype.rpc = function(url, handler) {
    try {
        this.mapObject.rpc(url,handler);
    } catch(e) { alert("You must initialize the tabmap before using RPC functions."); }
}

TabbedMap.prototype.initialize = function() {
    if ( !this.tabElement ) {
        this.tabElement = document.createElement("div");
        this.tabList = document.createElement("ul");
        this.tabElement.className = "tab-row";
        this.tabList.className = "tabs";
        for ( var i = 0; i < this.tabs.length; i++ ) {
            this.tabList.appendChild(this.tabs[i].item);
            GEvent.bindDom(this.tabs[i].link, "click",
                this.tabs[i], this.tabs[i].click);
        }
        this.tabElement.appendChild(this.tabList);
        this.container.appendChild(this.tabElement);
    }
    if ( !this.mapElement ) {
        this.mapElement = document.createElement("div");
        this.mapElement.id = "tabbedMap" + tabMapIndex++;
        this.mapElement.className = "gmap";
        this.mapElement.style.width  = this.properties.mapWidth + "px";
        this.mapElement.style.height = this.properties.mapHeight + "px";
        this.container.appendChild(this.mapElement);
        this.mapObject = new toEatMap(this.mapElement.id, false);
        GEvent.bind(this.mapObject, "pointupdate", this, this.updatedPoint);
        this.mapObject.addControl('small');
        this.mapObject.loadXML(this.loader);
        this.container.style.height = parseInt(this.tabElement.offsetHeight + this.mapElement.offsetHeight + 1) + "px";
        if ( this.displayedElement == 'directions' )
            this.mapElement.style.display = "none";
    }
    if ( !this.directionsElement ) {
        this.directionsElement = document.createElement("div");
        /*
         Please enter your starting address:
         Get directions through [Google, MapQuest, Yahoo, Microsoft]
          [Submit] (Opens in a new window)
        */
        var form    = document.createElement("form");
        form.id     = "directionsForm";
        form.method = "get";
        form.action = "javascript:void(0)";
        GEvent.bindDom(form, "submit", this, this.submitDirections);
        var content = document.createElement("p");
        content.style.padding = "0 1em 1ex 1em";

        var title   = document.createElement("h3");
        title.appendChild(document.createTextNode("Get directions"));
        content.appendChild(title);
        content.appendChild(document.createTextNode("Please enter your starting address: "));
        var input = document.createElement("input");
        input.type = "text"; input.name = "src";
        input.style.width = "100%";
        content.appendChild(input);

        content.appendChild(document.createElement("br"));
        content.appendChild(document.createTextNode("Get directions from: "));
        var select = document.createElement("select");
        select.name = "from";
        var sources = [ 'Google', 'Yahoo!' ];
        for ( var i in sources ) {
            var item = document.createElement("option");
                item.value = sources[i].toLowerCase();
                item.appendChild(document.createTextNode(sources[i]));
                select.appendChild(item);
        }
        content.appendChild(select);

        var submitButton = document.createElement("input");
        submitButton.type  = "submit";
        submitButton.name  = "submit";
        submitButton.value = "Get Directions";
        
        var btnCtn = document.createElement("p");
        btnCtn.style.textAlign = "center";
        btnCtn.appendChild(submitButton);
        btnCtn.appendChild(document.createElement("br"));
        btnCtn.appendChild(document.createTextNode("(This opens a new window)"));
        content.appendChild(btnCtn);

        form.appendChild(content);
        this.directionsElement.appendChild(form);
        this.directionsForm = form;

        this.directionsElement.className = "gmap";
        if ( this.displayedElement != 'directions' )
            this.directionsElement.style.display = "none";
        this.container.appendChild(this.directionsElement);
        this.currentForm = form;
    }
    if ( !this.updateElement ) {
        this.updateElement = document.createElement("div");

        this.updateElement.appendChild(document.createTextNode("Click anywhere on the map to update the location.  The highlighted marker is automatically saved.  There may be a delay before the change is active."));
        if ( this.displayedElement != 'update' )
            this.updateElement.style.display = "none";
        this.updateElement.style.position = "relative";
        this.updateElement.style.cssFloat = "left";
        this.updateElement.style.top = ((-1*this.properties.mapHeight)+23)+"px";
        this.updateElement.style.left   = "45px";
        //this.updateElement.style.bottom = "40px";
        this.updateElement.style.width = (this.properties.mapWidth - 51)+"px";
        this.updateElement.style.background = "#fff";
        this.updateElement.style.padding = "3px";
        this.updateElement.style.border = "1px solid #aaa";
        this.updateElement.style.zIndex = 5000;
        this.container.appendChild(this.updateElement);
    }
}

TabbedMap.prototype.updatedPoint = function() {
    var p = this.mapObject.getHighlightedPoint();
    if ( this.properties.onUpdate )
        this.properties.onUpdate(p);
}

TabbedMap.prototype.submitDirections = function() {
    var from; var src;
    try {
        from = this.directionsForm.from.options[this.directionsForm.from.selectedIndex].value;
        src  = this.directionsForm.src.value;
    } catch(e) {
        src  = this.directionsForm.elements[0].value;
        from = this.directionsForm.elements[1].options[this.directionsForm.elements[1].selectedIndex].value;
    }

    var loc;
    /* MapQuest needs to get with the program, you can't send freeform
       addresses for parsing, so we don't send MapQuest anything.
    */
    if ( from == "mapquest" ) {
        loc = "http://www.mapquest.com/directions/main.adp?" +
            "1a="  + encodeURIComponent(src) +
            "&2a=" + encodeURIComponent(this.address);
    }
    else if ( from == "yahoo!" ) {
        loc = "http://maps.yahoo.com/beta/index.php#maxp=location" +
            "&q2=" + encodeURIComponent(this.address) + 
            "&q1=" + encodeURIComponent(src);
    }
    else if ( from == "msn maps" ) {
        // MSN Maps has the same problem as mapquest
    }
    else /* ( from == "google" ) */ {
        loc = "http://maps.google.com/maps?q=from%3A+" +
            encodeURIComponent(src) + "+to%3A+" +
            encodeURIComponent(this.address);
    }
    window.open(loc);
}

TabbedMap.prototype.switchTabs = function( newTab ) {
    for ( var i = 0; i < this.tabs.length; i++ ) {
        if ( this.tabs[i].label == newTab )
            this.tabs[i].activate();
        else
            this.tabs[i].deactivate();
    }
    if ( newTab.toLowerCase() == 'directions' ) {
        this.mapObject.selection(false);
        this.displayedElement = "directions";
        this.directionsElement.style.display = "";
        this.updateElement.style.display     = "none";
        this.mapElement.style.display        = "none";
    }
    else if ( newTab.toLowerCase() == 'update' ) {
        this.displayedElement = "update";
        this.mapObject.selection(true);
        this.directionsElement.style.display = "none";
        this.updateElement.style.display     = "";
        this.mapElement.style.display        = "";
    }
    // Just go back to the map 
    else {
        this.mapObject.selection(false);
        this.displayedElement = "map";
        this.directionsElement.style.display = "none";
        this.updateElement.style.display     = "none";
        this.mapElement.style.display        = "";
    }
}

var tooltipArray = new Array();
function styledTooltip( ctnId, title, content, width ) {
    var container = document.getElementById(ctnId);
    if ( !container ) {
        return false;
    }

    var tooltip;
    if ( tooltipArray[ctnId] ) {
        tooltip = tooltipArray[ctnId].div;
        tooltip.innerHTML     = "";
        tooltip.style.display = "";
    } else {
        tooltip = createFloatingWindow( container, "30%" );
        tooltip.className        = "awolTooltip";
        container.appendChild(tooltip);
        tooltipArray[ctnId] = new Object();
        tooltipArray[ctnId].div = tooltip;;
    }

    tooltip.style.opacity    = "1.0";
    tooltip.style.MozOpacity = "1.0";
    tooltip.style.filter = "alpha(opacity=100)";

    var tooltipHeader = document.createElement("h1");
    tooltipHeader.className = "awolTooltipHeader";
    tooltipHeader.innerHTML = title;
    tooltip.appendChild(tooltipHeader);

    var tooltipContent       = document.createElement("div");
    tooltipContent.className = "awolTooltipContent";
    tooltipContent.innerHTML  = content;
    tooltip.appendChild(tooltipContent);

    tooltip.onmouseout =
        function() { fadeTimeout(tooltip, 2000, 100); };
    tooltip.onmouseover =
        function() {
            if ( tooltip.timeout ) {
                clearTimeout(tooltip.timeout);
            }
            tooltip.style.opacity    = "1.0";
            tooltip.style.MozOpacity = "1.0";
            tooltip.style.filter     = "alpha(opacity=100)";
        };
 
    //GEvent.bindDom(tooltip, "mouseout",
    fadeTimeout(tooltip, 3000, 100);
}
function processSearch( form, extraWhereData ) {
    if ( !curMap ) { alert("No current map to use to search on"); return; }
    if ( form.elements[0].value || form.elements[1].value ) {
        var where = '';
        var what  = form.elements[0].value;
        if ( ( form.elements[1].value == "" || form.elements[1].value == "Enter City and State" ) ) {
            alert("Please enter a city, state, zipcode or address in the Where field first");
            return false;
        }
        if ( ( !form.elements[1].value || form.elements[1].value == "In the area displayed" ) && curMap.gmap.getZoomLevel() < 8 ) {
            var bounds = curMap.gmap.getBoundsLatLng();
            where =
                bounds.minY + "," + bounds.minX + "x" +
                bounds.maxY + "," + bounds.maxX + "@" +
                curMap.gmap.getZoomLevel();
        } else {
            where = form.elements[1].value;
        }
        searchMap(what, where, extraWhereData);
    }
}

function searchMap( what, where, extraWhereData ) {
    var url = "SearchV2/JS/?what=" + what + "&where=" + where;
    curMap.suppressNextMove(1);
    var forgetTags = false;
    if ( !what || what.length < 2 ) forgetTags = true;
    if ( extraWhereData )
        url += "&implied=" + extraWhereData;
    curMap.inlineLoad(url, "Please wait while we search", forgetTags );
}

function whereFocus( el ) {
    if ( el.value == "In the area displayed" ||
         el.value == "Enter City and State" )
    {
        el.value = '';
    }
}

function AccordionList(element) {
    this.list = element;
    this.initialize();
}

AccordionList.prototype.toggleFunction = function(item) {
    var t = this;
    return function() {
        try { t.toggleItem(item); }
        catch(e) { }
    }
}

AccordionList.prototype.toggleItem = function(item) {
    try {
        if ( this.activeItem )
            this.inputItems[this.activeItem].style.display = "none";
        this.activeItem = item.id;
        this.inputItems[item.id].style.display = "block";
    } catch(e) {
    }
}

AccordionList.prototype.initialize = function() {
    this.inputItems = new Array();
    var lastLabel;
    for ( var i = 0; i < this.list.childNodes.length; i++ ) {
        var item = this.list.childNodes.item(i);
        if ( item.nodeType == 1 && item.tagName == "DT" ) {
            setCursor(item, "pointer");
            lastLabel = item.id;
            GEvent.bindDom(item, "click", this, this.toggleFunction(item));
        }
        else if ( item.nodeType == 1 && item.tagName == "DD" ) {
            if ( lastLabel ) {
                this.inputItems[lastLabel] = item;
                item.style.display = "none";
                lastLabel = null;
            }
        }
    }
}


