﻿$(document).ready(function() {
    Map.init();
});

var Map = {
    //--------------------------------------------------------------
    gmap: null,
    markers: [],
    infowindow: null,
    initialized: false,
    //--------------------------------------------------------------
    init: function() {
        //Map.initEvents();
        Map.initMap();
    },
    //--------------------------------------------------------------
    initMap: function() {
        // Map container
        var container = $("div#map");
        if (container.length > 0) {

            // Only initialize once on each page
            if (!this.initialized) {
                this.initialized = true;

                // Center
                var latlng = new google.maps.LatLng(56.239506, 10.160965);
                var initialZoom = 7;

                // Options for the map object
                var mapOptions = {
                    center: latlng,
                    zoom: initialZoom,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                // Setup map
                var map = this.gmap = new google.maps.Map(document.getElementById("map"), mapOptions);

                // Setup Infowindow
                this.infowindow = new google.maps.InfoWindow({
                    //maxWidth: 230,
                    content: 'Loading...'
                });

                // Close infowindow when map is clicked
                google.maps.event.addListener(map, 'click', function() {
                    Map.closeInfoWindow();
                });

                // Iterate Places and setup Markers
                $.each(places, function(index, place) {

                    // Set Lattitude and Longtitude
                    var position = new google.maps.LatLng(place.Position.Lat, place.Position.Lng);

                    // Icon
                    var iconUrl = '/data/images/marker.png';
                    var icon = new google.maps.MarkerImage(iconUrl, new google.maps.Size(50, 50), new google.maps.Point(0, 0), new google.maps.Point(23, 42));

                    // Shape (Clickable area)
                    var shape = { coord: [18, 0, 28, 0, 38, 12, 38, 24, 24, 42, 8, 24, 8, 12], type: 'poly' };

                    // Image for Infowindow
                    var image = !place.Image ? '' : '<img src="{0}" alt="{1}" style="border-style: solid;border-width: 1px;height: 75px; width: 100px;float:right; margin: 0 0 5px 5px;" />'.format(place.Image, place.Name);

                    // HTML for Infowindow
                    var info = [
						'<div>',
                            '<a href="{0}" style="color:#000; text-decoration: none;">'.format(place.Url),
                            '<strong style="color: #000;">{0}</strong>'.format(place.Name),
                            '<p>{0}{1}</p>'.format(image, place.Description),
                            '</a>',
						'</div>'
						].join('');

                    // Create Marker
                    var marker = new google.maps.Marker({
                        map: map,
                        position: position,
                        info: info,
                        icon: icon,
                        shape: shape
                    });

                    // Store each marker (for zoom)
                    Map.markers.push(marker);

                    // Open Infowindow when marker is clicked
                    google.maps.event.addListener(marker, 'click', function() {
                        Map.openInfoWindow(map, this);
                    });
                });
            }

            //console.info(places.length)
            if (places.length > 0) {
                this.zoomBounds();
                //console.info("Z");
            }
        }
    },
    //--------------------------------------------------------------
    zoomBounds: function() {
        // Create Bounds object for size calculation
        var bounds = new google.maps.LatLngBounds();

        // Extend Bounds for each Marker
        $.each(this.markers, function(index, marker) {
            //console.log(marker.position.lat(), marker.position.lng());
            if (!isNaN(marker.position.lat()) && !isNaN(marker.position.lng()))
                bounds.extend(marker.position);
        });

        // Only zoom/pan the map if bounds has changed (avoid flicker)
        if (!bounds.equals(this.gmap.getBounds())) {
            this.gmap.fitBounds(bounds);

            var MAX_ZOOM = 16;
            // When map has zoomed, change zoom level if higher than level 15
            google.maps.event.addListenerOnce(this.gmap, 'bounds_changed', function() {
                if (this.getZoom() > MAX_ZOOM) {
                    this.setZoom(MAX_ZOOM);
                }
            });
        }
    },
    //--------------------------------------------------------------
    openInfoWindow: function(map, marker) {
        // Fetch HTML from Marker and create DOM Node
        var domNode = $(marker.info)[0];

        // Set content and show Infowindow
        this.infowindow.setContent(domNode);
        this.infowindow.open(map, marker);
    },
    //--------------------------------------------------------------
    closeInfoWindow: function() {
        // If in doubt - Take a break and come back =)
        this.infowindow.close();
    }
}

//--------------------------------------------------------------

// .format() extension to String (alá c#)
// "{0} is {1}".format("beer", "good");
String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != 'undefined' ? args[number] : '{' + number + '}';
    });
};
