// Set Global Event Handlers
Event.observe(window, 'load', initialize);
Event.observe(window, 'unload', GUnload);

/**
 * Start Google Maps
 **/
var route = null;
var jar = null;
var debug = null;

function initialize()
{
    // Save zoom levels
    jar = new CookieJar({
        path: '/'
    });

    // Browser Compatibility
    if (GBrowserIsCompatible()) {
        
        var map = new GMap2($(data.setting.canvas_id));

        // Map options
        if (data.setting.GSmallMapControl == 1) {
            map.addControl(new GSmallMapControl());
        }
        
        if (data.setting.GLargeMapControl == 1) {
            map.addControl(new GLargeMapControl());
        }

        if (data.setting.GLargeMapControl3D == 1) {
            map.addControl(new GLargeMapControl3D());
        }

        if (data.setting.GSmallZoomControl == 1) {
            map.addControl(new GSmallZoomControl());
        }

        if (data.setting.GSmallZoomControl3D == 1) {
            map.addControl(new GSmallZoomControl3D());
        }
        
        if (data.setting.GScaleControl == 1) {
            map.addControl(new GScaleControl());
        }
        
        if (data.setting.GMapTypeControl == 1) {
            map.addControl(new GMapTypeControl());
        }
        
        if (data.setting.GHierarchicalMapTypeControl == 1) {
            map.addControl(new GHierarchicalMapTypeControl());
        }
        
        if (data.setting.GOverviewMapControl == 1) {
            map.addControl(new GOverviewMapControl());
        }
        
        if (data.setting.GNavLabelControl == 1) {
            map.addControl(new GNavLabelControl());
        }
        
        if (data.setting.enableScrollWheelZoom == 1) {
            map.enableScrollWheelZoom();
        }
        
        if (data.setting.CustomZoomControl == 1) {
            map.addControl(new CustomZoomControl());
        }

        if (data.setting.CustomLogo.length > 3) {
            map.addControl(new CustomLogo());
        }
        
        map.setMapType(eval(data.setting.map_type));

        // Static Form Fields!
        data.setting.search_field_id  = 'gmap-search-field';
        data.setting.search_button_id = 'gmap-search-button';
        data.setting.route_container  = 'gmap-search-route';
        //data.setting.route_from       = 'nieuwstraat 11 baarn'; // Eerste punt pakken als A

        if ($(data.setting.route_container) != null) {
            route = new GDirections(map, $(data.setting.route_container));
        } else {
            route = new GDirections(map);
        }

        GEvent.addListener(route, "error", function() {
            var fieldLength = $(data.setting.search_field_id).value.length;
            var suffixLength = data.setting.no_route_suffix.length;

            if (($(data.setting.search_field_id) != null) && ($(data.setting.search_field_id).value.substr(fieldLength - suffixLength) != data.setting.no_route_suffix)) {
                $(data.setting.search_field_id).value += ' ' + data.setting.no_route_suffix;
            } else {
                alert('Geen route gevonden.');
            }
        });
        
        setMarkers(map, data.points, data.setting);

        // Form events
        if ($(data.setting.search_field_id) != null && $(data.setting.search_button_id) != null) {
            function showRoute()
            {
                var zipcode = /^(\d{4})\s*(\w{2})\s*$/;
                
                var match = $(data.setting.search_field_id).value.match(zipcode);
                
                if (match) {
                    $(data.setting.search_field_id).value = '';
                    $(data.setting.search_field_id).value = match[1] + match[2] + ' NL';
                }

                GDirectionsOptions  = { preserveViewport: false };
                
                var plan = [$(data.setting.search_field_id).value];
                
                plan.push(new GLatLng(data.points[0].latitude, data.points[0].longitude));
                
                route.loadFromWaypoints(plan, GDirectionsOptions);
				
            }

            Event.observe($(data.setting.search_button_id), 'click', function() {
                showRoute();
				setTimeout("fitHeight();",1000);
            });

            Event.observe($(data.setting.search_field_id), 'keypress', function(event) {
                if (Event.KEY_RETURN == event.keyCode) {
                    showRoute();
					setTimeout("fitHeight();",1000);
                }
            });
        }
    }
}

/**
 * Set Markers
 **/
function setMarkers(map, points, settings)
{
    if (settings.map_latitude != null && settings.map_longitude != null) {
        map.setCenter(new GLatLng(settings.map_latitude, settings.map_longitude), settings.zoomlevel_on_start);
    } else {
        map.setCenter(new GLatLng(points[0].latitude, points[0].longitude), settings.zoomlevel_on_start);
    }

    // if pa mode
    if (settings.adminMode == 1) {
        edit = jar.get('currentView');

        if (edit != null && edit.center != null && edit.zoom != null) {
             map.setCenter(new GLatLng(edit.center[0], edit.center[1]), edit.zoom);
        }
    }

    mgr = new MarkerManager(map);
    
    if (points.length == 0 && settings.map_latitude != null && settings.map_longitude != null) {
        var marker = new GMarker(new GLatLng(settings.map_latitude, settings.map_longitude));

        mgr.addMarkers([marker], 0, null);
    }

    var waypoints = [];

    for (var i = 0; i < points.length; i++) {
        // Waypoints: Via, via, via
        waypoints.push(new GLatLng(points[i].latitude, points[i].longitude));
        
        if (settings.connect_markers == 1) {
            // Polyline
            if ((points[i + 1] != null)) {
                var polyline = new GPolyline([new GLatLng(points[i].latitude, points[i].longitude), new GLatLng(points[i + 1].latitude, points[i + 1].longitude)], "red", 5);

                map.addOverlay(polyline);
            }
        }
        
        // Icon settings
        var newPositionIcon = new GIcon(G_DEFAULT_ICON);

        newPositionIcon.image = points[i].icon;
        newPositionIcon.iconSize = new GSize(points[i].icon_size[0], points[i].icon_size[1]);
        newPositionIcon.shadowSize = new GSize(0, 0); // No shadow
        newPositionIcon.iconAnchor = new GPoint(points[i].icon_anchor[0], points[i].icon_anchor[1]);
        newPositionIcon.infoWindowAnchor = new GPoint(points[i].info_anchor[0], points[i].info_anchor[1]);

        newPositionIcon.imageMap = [0,0, points[i].icon_size[0],0, points[i].icon_size[0],points[i].icon_size[1], 0,points[i].icon_size[1]];

        var marker = new GMarker(new GLatLng(points[i].latitude, points[i].longitude), { icon: newPositionIcon, draggable: settings.adminMode })

        mgr.addMarkers([marker], points[i].zoom_levels[0], points[i].zoom_levels[1]);

        // Marker events
        GEvent.addListener(marker, "dragend", function(event, pushpin, point) {
            var LatLng = pushpin.getLatLng();
            
            var saveMarkerPosition = 1;
            if (settings.confirm_save == 1) {
                saveMarkerPosition = confirm('Wilt u dit punt opslaan op: ' + Math.round(LatLng.x * 10000000) / 10000000 + ', ' + Math.round(LatLng.y * 10000000) / 10000000 + '?');
            }
            
            if (saveMarkerPosition) {
                new Ajax.Request('/edit/files/googlemaps-save.php', {
                    postBody: 'speid=' + point.name + '&latitude=' + (Math.round(LatLng.x * 10000000) / 10000000) + '&longitude=' + (Math.round(LatLng.y * 10000000) / 10000000),

                    onFailure: function(transport) {
                        alert('Opslaan mislukt.');
                    },
                    
                    onSuccess: function() {
                        var center = map.getCenter();
                        var zoom = map.getZoom();
                        
                        currentView = {
                            'center': [center.y, center.x],
                            'zoom': zoom
                        };

                        // Save zoom levels
                        jar = new CookieJar({
                            expires:20,   // seconds
                            path: '/'
                        });

                        jar.put('currentView', currentView);

                        location.reload(true);
                    }
                });
            } else {
                pushpin.setLatLng(new GLatLng(point.latitude, point.longitude));
            }
        }.bindAsEventListener('', marker, points[i]));

        GEvent.addListener(marker, "dragstart", function(event, pushpin, point) {
            pushpin.closeInfoWindow();
        }.bindAsEventListener('', marker, points[i].name));

        if (points[i].markerEvent != 0) {            
            if (points[i].markerEvent == 1) {
                GEvent.addListener(marker,"click", function(event, pushpin, information) {
                    pushpin.openInfoWindowHtml(information);
                }.bindAsEventListener('', marker, points[i].info));
            }

            if (points[i].markerEvent == 2) {
                GEvent.addListener(marker,"click", function(event, pushpin, zoomlevel) {
                    map.setCenter(pushpin.getLatLng());
                    map.setZoom(zoomlevel);
                }.bindAsEventListener('', marker, points[i].markerSetZoomLevel));
            }
        }
    }

    if (settings.connect_markers == 2) {
        route.loadFromWaypoints(waypoints);
    }

    mgr.refresh();
}

/**
 * Find location
 **/
var newLocationMarker = 'very defined'; // Bug?

// Icon settings
var newLocationIcon = new GIcon(G_DEFAULT_ICON);

function showAddress(map, address, search, settings)
{
    var geocoder = new GClientGeocoder();
    
    if (geocoder) {
        geocoder.getLatLng(address, function(point) {

            if (!point) {
                alert(address + " niet gevonden");
            } else {
                newLocationIcon.image = search.icon;
                newLocationIcon.iconSize = new GSize(search.icon_size[0], search.icon_size[1]);
                newLocationIcon.iconAnchor = new GPoint(search.icon_anchor[0], search.icon_anchor[1]);
                newLocationIcon.shadowSize = new GSize(0, 0);

                map.setCenter(point, settings.zoomlevel_on_search);
                map.removeOverlay(newLocationMarker);

                newLocationMarker = new GMarker(point, { icon: newLocationIcon, draggable: settings.draggable_markers });

                map.addOverlay(newLocationMarker);

                // Drag event ends
                GEvent.addListener(newLocationMarker, "dragend", function() {
                    $(settings.latitude_field).value = Math.round(newLocationMarker.ra.x * 10000000) / 10000000;
                    $(settings.longitude_field).value = Math.round(newLocationMarker.ra.y * 10000000) / 10000000;
                });

                // NOTE: Global
                $('point_latitude').value = point.x;
                $('point_longitude').value = point.y;
            }
        });
    }
}

/**
 * Custom Controls
 **/
function CustomZoomControl() {}

CustomZoomControl.prototype = new GControl();

CustomZoomControl.prototype.initialize = function(map)
{
    var container = document.createElement("div");

    // Zoom in control
    var zoomInDiv = document.createElement("div");

    this.setButtonStyle_(zoomInDiv);
    container.appendChild(zoomInDiv);
    zoomInDiv.innerHTML = '<img src="' + data.setting.CustomZoomInImg + '" />';

    GEvent.addDomListener(zoomInDiv, "click", function() {
        map.zoomIn();
    });

    // Zoom out control
    var zoomOutDiv = document.createElement("div");

    this.setButtonStyle_(zoomOutDiv);
    container.appendChild(zoomOutDiv);
    zoomOutDiv.innerHTML = '<img src="' + data.setting.CustomZoomOutImg + '" />';

    GEvent.addDomListener(zoomOutDiv, "click", function() {
        map.zoomOut();
    });

    // Append
    map.getContainer().appendChild(container);

    return container;
}

// Control position
CustomZoomControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

// CSS
CustomZoomControl.prototype.setButtonStyle_ = function(button) {
    button.style.marginBottom = "3px";
    button.style.cursor = "pointer";
}

/**
 * Logo
 **/
function CustomLogo() {}

CustomLogo.prototype = new GControl();

CustomLogo.prototype.initialize = function(map)
{
    var container = document.createElement("div");

    var zoomInDiv = document.createElement("div");

    this.setButtonStyle_(zoomInDiv);
    container.appendChild(zoomInDiv);
    zoomInDiv.innerHTML = '<a target="_blank" href="' + data.setting.CustomLogoLink + '"><img style="border: 0;" src="' + data.setting.CustomLogo + '" /></a>';

    // Append
    map.getContainer().appendChild(container);

    return container;
}

// Control position
CustomLogo.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(data.setting.CustomLogoX, data.setting.CustomLogoY));
}

// CSS
CustomLogo.prototype.setButtonStyle_ = function(button) {
    button.style.marginBottom = "3px";
    button.style.cursor = "pointer";
}

