
function addAddress(geocoder, center, zoom, map, customimage, customtooltip, runtime) {
    geocoder.getLatLng(center, function(point) {
        if (!point) {
            //alert(center + " not found");
            if (runtime < 5) {
                window.setTimeout(function() { addAddress(geocoder, center, zoom, map, customimage, customtooltip, runtime + 1); }, 1000);
            }
        }
        else {
            //set center on the map
            map.setCenter(point, zoom);

            if (customimage == true) {
                //add the marker
                var customiconsize = new GSize(width, height);
                var customicon = new GIcon(G_DEFAULT_ICON, imageurl);
                customicon.iconSize = customiconsize;
                var marker = new GMarker(point, { icon: customicon });
                map.addOverlay(marker);
            } else {
                var marker = new GMarker(point);
                map.addOverlay(marker);
            }

            if (customtooltip == true) {
                marker.openInfoWindowHtml(tooltipinfo);
            }
        }
    });
}

function handleErrors(gdir) {
    var errorDiv = document.getElementById("directionsError");
    errorDiv.style.display = "block";
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
        errorDiv.innerHTML = "The address you entered was not found. This may be due to the fact that the address is relatively new, or it may be incorrect. Enter your address in a different format and try again";
    }
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
        errorDiv.innerHTML = "An unknown error occured when trying to process your location, please try again later. <b>Error code: </b>" + gdir.getStatus().code;
    }

    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
        errorDiv.innerHTML = "No address was entered, please enter a <b>FROM</b> address to get directions to this location. ";
    }

    else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
        errorDiv.innerHTML = "The given key is either invalid or does not match the domain for which it was given. <b>Error code: </b>" + gdir.getStatus().code;
    }

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        errorDiv.innerHTML = "A connection with Google Maps could not be established, please try again later or on a different browser.  <b>Error code: </b>" + gdir.getStatus().code;

    else {
        errorDiv.innerHTML = "No address was entered. Please enter a <b>FROM</b> address to get directions to this location. ";
    }

}


(function($) {

    $.GoogleMapObjectDefaults = {
        zoomLevel: 10,
        imagewidth: 50,
        imageheight: 50,
        center: '',
        start: '#start',
        end: '#end',
        directions: 'directions',
        submit: '#getdirections',
        tooltip: 'false',
        image: 'false'
    };


    function GoogleMapObject(elementId, options) {
        /* private variables */
        this._inited = false;
        this._map = null;
        this._geocoder = null;

        /* Public properties */
        this.ElementId = elementId;
        this.Settings = $.extend({}, $.GoogleMapObjectDefaults, options || '');
    }

    $.extend(GoogleMapObject.prototype, {
        init: function() {
            if (!this._inited) {
                if (GBrowserIsCompatible()) {
                    this._map = new GMap2(document.getElementById(this.ElementId));
                    this._map.addControl(new GSmallMapControl());
                    this._geocoder = new GClientGeocoder();
                }

                this._inited = true;
            }
        },
        load: function() {
            //ensure existence
            this.init();

            if (this._geocoder) {
                //"this" will be in the wrong context for the callback
                var zoom = this.Settings.zoomLevel;
                var center = this.Settings.center;
                var width = this.Settings.imagewidth;
                var height = this.Settings.imageheight;
                var map = this._map;

                if (this.Settings.tooltip != 'false') {
                    var customtooltip = true;
                    var tooltipinfo = this.Settings.tooltip;
                }

                if (this.Settings.image != 'false') {
                    var customimage = true;
                    var imageurl = this.Settings.image;
                }

                addAddress(this._geocoder, center, zoom, map, customimage, customtooltip, 1);

            }


            //make this available to the click element
            $.data($(this.Settings.submit)[0], 'inst', this);

            $(this.Settings.submit).click(function(e) {
                e.preventDefault();
                var obj = $.data(this, 'inst');
                var outputto = obj.Settings.directions;
                var directionsDiv = document.getElementById(outputto);
                var errorDiv = document.getElementById("directionsError");
                var from = $(obj.Settings.start).val();
                var to = $(obj.Settings.end).val();
                map.clearOverlays();
                errorDiv.style.display
                directionsDiv.innerHTML = "";
                errorDiv.innerHTML = "";
                var gdir = new GDirections(map, directionsDiv);
                //gdir.clear();
                gdir.load("from: " + from + " to: " + to);
                GEvent.addListener(gdir, "error", handleErrors);
                //open the google window
                //window.open("http://maps.google.com/maps?saddr=" + from + "&daddr=" + to, "GoogleWin", "menubar=1,resizable=1,scrollbars=1,width=750,height=500,left=10,top=10");
            });
            return this;
        }
    });

    $.extend($.fn, {
        googleMap: function(options) {
            // check if a map was already created
            var mapInst = $.data(this[0], 'googleMap');
            if (mapInst) {
                return mapInst;
            }

            //create a new map instance
            mapInst = new GoogleMapObject($(this).attr('id'), options);
            $.data(this[0], 'googleMap', mapInst);
            return mapInst;
        }
    });
})(jQuery);

