﻿(function($) {

    $.GoogleMaps = function(parent, options) {
        $.GoogleMaps.impl.init(parent, options);
    };

    $.GoogleMaps.defaults = {
        latlong: '0,0',
        canvasId: 'map_canvas',
        address: '',
        infoWindow: false,
        iconImage: {
            url: '',
            height: 32,
            width: 32
        },
        iconShadow: {
            url: '',
            height: 32,
            width: 32
        },
        width: 500,
        height: 300
    };

    $.GoogleMaps.impl = {

        latlng: null,

        opts: null,

        canvas: {},

        init: function(parent, options) {

            this.opts = $.extend({}, $.GoogleMaps.defaults, options);

            // give the canvas a unique id to support multiple maps
            this.opts.canvasId = this.opts.canvasId + (Math.floor(Math.random() * 100 + 1));

            this.canvas.parent = parent;
            $(this.canvas.parent).empty()

            //create the map canvas
            this.create();

            this.open();

        },

        create: function() {
            this.canvas.container = $('<div/>')
                .attr('id', this.opts.canvasId)
                .css({
                    position: 'relative',
                    height: this.opts.height,
                    width: this.opts.width
                })
                .appendTo(this.canvas.parent);
        },

        open: function() {
            if (GBrowserIsCompatible()) {
                var ll = this.opts.latlong.split(',');
                this.latlng = new GLatLng(ll[0], ll[1]);

                if (GBrowserIsCompatible()) {
                    var map = new GMap2(document.getElementById(this.opts.canvasId));
                    map.setCenter(this.latlng, 13);

                    map.addControl(new GSmallMapControl());

                    if (this.opts.iconImage != '') {

                        var baseIcon = new GIcon();

                        baseIcon.image = this.opts.iconImage.url;
                        baseIcon.iconSize = new GSize(
                    this.opts.iconImage.width,
                    this.opts.iconImage.height);

                        baseIcon.shadow = this.opts.iconShadow.url;
                        baseIcon.shadowSize = new GSize(
                    this.opts.iconShadow.width,
                    this.opts.iconShadow.height);

                        baseIcon.iconAnchor = new GPoint(12, 54);

                        markerOptions = { icon: baseIcon };

                        var marker = new GMarker(this.latlng, markerOptions);
                        map.addOverlay(marker);
                    }

                    if (this.opts.infoWindow) {
                        map.openInfoWindowHtml(map.getCenter(), this.opts.address);
                    }
                }
            }
        }
    };
})(jQuery);



