var bounds = new GLatLngBounds();

var continents = [
    {
        "name": "Europe",
        "longitude":15.2551187,
        "latitude":54.5259614
    },
    {
        "name": "North-America",
        "longitude":-94.74609375,
        "latitude":49.467752846749285
    },
    {
        "name": "South-America",
        "longitude":  -57.12890625,
        "latitude":-15.374598279555933
    },
    {
        "name": "Africa",
        "longitude":21.26953125,
        "latitude": 0.009516708564666
    },
    {
        "name": "Asia",
        "longitude":86.30859375,
        "latitude":46.49435964694685
    },
    {
        "name": "Oceania",
        "longitude":124.27734375,
        "latitude":-15.035343235121386
    }
];
function getDivesiteContinentMarkers(map, iconPath) {
    var batch = [];
    for (var i = 0; i < continents.size(); i++) {
        var continent = continents[i];
        var marker = new GMarker(new GLatLng(continent.latitude, continent.longitude), {title:continent.name, icon: getYDBIcon('divespot_cont', iconPath) });
        GEvent.addListener(marker, 'click', function() {
            openContinentMarkerPopup(this, map);
        }
                );
        batch.push(marker);
    }
    return batch;
}
function getDivecenterContinentMarkers(map, iconPath) {
    var batch = [];
    for (var i = 0; i < continents.size(); i++) {
        var continent = continents[i];
        var marker = new GMarker(new GLatLng(continent.latitude, continent.longitude), {title:continent.name, icon: getYDBIcon('divercenter_cont', iconPath) });
        GEvent.addListener(marker, 'click', function() {
            openContinentMarkerPopup(this, map);
        }
                );
        batch.push(marker);
    }
    return batch;
}
function getDiverContinentMarkers(map, iconPath) {
    var batch = [];
    for (var i = 0; i < continents.size(); i++) {
        var continent = continents[i];
        var marker = new GMarker(new GLatLng(continent.latitude, continent.longitude), {title:continent.name, icon: getYDBIcon('divers_cont', iconPath) });
        GEvent.addListener(marker, 'click', function() {
            openDiverContinentMarkerPopup(this, map);
        }
                );
        batch.push(marker);
    }
    return batch;
}

function getContinentMarkers(map, iconPath) {
    var batch = [];
    for (var i = 0; i < continents.size(); i++) {
        var continent = continents[i];
        var marker = new GMarker(new GLatLng(continent.latitude, continent.longitude), {title:continent.name, icon: getYDBIcon('continent', iconPath) });
        GEvent.addListener(marker, 'click', function() {
            openContinentMarkerPopup(this, map);
        }
                );
        batch.push(marker);
    }
    return batch;
}

function getYDBIcon(name, iconPath) {
    var icon = new GIcon();
    icon.image = iconPath + "DA_ico_" + name + ".png";
    icon.shadow = iconPath + "DA_ico_" + name + "-shadow.png";
    if (name == 'divecenter') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(5, 6);
    }
    if (name == 'divers') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(5, 6);
    }
    if (name == 'diver') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(5, 6);
    }
    if (name == 'buddies') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(5, 6);
    }
    if (name == 'buddies_country') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(4, 6);
    }
    if (name == 'divers_country') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(4, 6);
    }
    if (name == 'country' || name == 'divespots_country') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(4, 6);
    }
    if (name == 'divespot') {
        icon.iconSize = new GSize(36, 30);
        icon.shadowSize = new GSize(36, 30);
        icon.iconAnchor = new GPoint(6, 24);
        icon.infoWindowAnchor = new GPoint(10, 6);
    }
    if (name == 'continent' || name == 'divespot_cont' || name == 'divers_cont' || name == 'divecenter_cont') {
        icon.iconSize = new GSize(54, 44);
        icon.shadowSize = new GSize(54, 44);
        icon.iconAnchor = new GPoint(18, 14);
        icon.infoWindowAnchor = new GPoint(13, 9);
    }
    return icon;
}

function setBounds(marker) {
    bounds.extend(marker.getLatLng());
}
function adaptZoom(map, mgr) {

    if (!bounds.isEmpty()) {
        //        alert('adaot2','adaot2');
        var newZoom = map.getBoundsZoomLevel(bounds);
        var numMarkers = mgr.getMarkerCount(newZoom);
        if (numMarkers > 1) {
            //            alert(numMarkers, numMarkers);
            map.setZoom(newZoom);
        }
        else if (numMarkers == 0) {
            map.setZoom(1);
        }
        else {
            map.setZoom(11);
        }
        // zusaetzlich soll die karte auch noch optimal zentriert werden
        var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
        var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
        if (map.getZoom() == 1) {
            map.setCenter(new GLatLng(30.00, 5.00));
        }
        else {
            //                alert('adaot','adaot');
            //            map.setCenter(bounds.mid());
            map.setCenter(new GLatLng(clat, clng));
        }
    }
}

function openContinentMarkerPopup(marker, map) {
    marker.openExtInfoWindow(
            map,
            "ydb_info_window",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxContinentinfo?continent=" + marker.getTitle() ,
        beakOffset: 10
    }
            );
}

function openDiverContinentMarkerPopup(marker, map) {
    marker.openExtInfoWindow(
            map,
            "ydb_info_window",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxDiverContinentinfo?continent=" + marker.getTitle() ,
        beakOffset: 10
    }
            );
}
function openDiverMarkerPopup(marker, diverId, map) {
    //    alert(diverId,diverId)
    marker.openExtInfoWindow(
            map,
            "ydb_info_window",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxDiverinfo?diverId=" + diverId,
        beakOffset: 10
    }
            );
}

function openBuddyCountryMarkerPopup(marker, countryId, map) {
    marker.openExtInfoWindow(
            map,
            "ydb_info_window_country",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxDiverCountryinfo?countryId=" + countryId,
        beakOffset: 10
    }
            );
}

function openCountryMarkerPopup(marker, countryId, map) {
    marker.openExtInfoWindow(
            map,
            "ydb_info_window_country",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxCountryinfo?countryId=" + countryId,
        beakOffset: 10
    }
            );
}

function openDivecenterMarkerPopup(marker, divecenterId, map) {
    marker.openExtInfoWindow(
            map,
            "ydb_info_window",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxDivecenterinfo?divecenterId=" + divecenterId,
        beakOffset: 10
    }
            );
}

function openDivespotMarkerPopup(marker, divesiteId, map, showDives) {
    marker.openExtInfoWindow(
            map,
            "ydb_info_window",
            "<div style=\"margin-left:10px;margin-top:5px;\"> Loading...</div>",
    {
        ajaxUrl: "../diveatlas/ajaxDivesiteinfo?divesiteId=" + divesiteId + '&showDives=' + showDives,
        beakOffset: 10
    }
            );
}

function getMarkerConnections(map, fromMarker, toMarkers) {
    var polyline;
    for (var i = 0; i < fromMarker.size(); i++) {
        for (var j = 0; j < toMarkers.size(); j++) {
            polyline = new GPolyline([fromMarker[i].getLatLng(),toMarkers[j].getLatLng()], "white", 1, 0.9);
            map.addOverlay(polyline);
        }
    }
}


function setupMarkers(map, iconPath, setOptimalZoom, center_site_connection, diver_buddy_connection, continentMaxzoom, countryMaxzoom, divesiteMaxzoom, divecenterMaxzoom, diverMaxzoom, otherdiversMaxzoom, markers, continentmarkers, divercontinentmarkers, divecentercontinentmarkers, divesitecontinentmarkers, showDives) {
    var mgr = new MarkerManager(map);
    if (continentmarkers == 'show') {
        mgr.addMarkers(getContinentMarkers(map, iconPath), continentMaxzoom, 1);
    }
    if (divercontinentmarkers == 'show') {
        mgr.addMarkers(getDiverContinentMarkers(map, iconPath), continentMaxzoom, 1);
    }
    if (divecentercontinentmarkers == 'show') {
        mgr.addMarkers(getDivecenterContinentMarkers(map, iconPath), continentMaxzoom, 1);
    }
    if (divesitecontinentmarkers == 'show') {
        mgr.addMarkers(getDivesiteContinentMarkers(map, iconPath), continentMaxzoom, 1);
    }
    var divecenterBatch = [];
    var otherdiversBatch = [];
    var divesiteBatch = [];
    var countryBatch = [];
    var diverCountryBatch = [];
    var buddyCountryBatch = [];
    var buddiesBatch = [];
    var diverBatch = [];
    var marker;
    for (var i = 0; i < markers.size(); i++) {
        var item = markers[i];
        if (item.latitude && item.longitude) {
            try {
                if (item.klasse == 'Divecenter') {
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('divecenter', iconPath) });
                    GEvent.addListener(marker, 'click', function() {
                        openDivecenterMarkerPopup(this, this.id, map);
                    });
                    divecenterBatch.push(marker);
                } else if (item.klasse == 'OtherDivers') {
                    //                                        alert(item.name, item.name);
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('divers', iconPath) });
                    GEvent.addListener(marker, 'click', function() {
                        openDiverMarkerPopup(this, this.id, map);
                    });
                    otherdiversBatch.push(marker);
                } else if (item.klasse == 'Diver') {
                    //                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('buddies', iconPath) });
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('diver', iconPath) });
                    GEvent.addListener(marker, 'click', function() {
                        openDiverMarkerPopup(this, this.id, map);
                    });
                    diverBatch.push(marker);
                } else if (item.klasse == 'Buddy') {
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('buddies', iconPath) });
                    GEvent.addListener(marker, 'click', function() {
                        openDiverMarkerPopup(this, this.id, map);
                    });
                    buddiesBatch.push(marker);
                } else if (item.klasse == 'BuddyCountry') {
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('buddies_country', iconPath)});
                    GEvent.addListener(marker, 'click', function() {
                        openBuddyCountryMarkerPopup(this, this.id, map);
                    });
                    buddyCountryBatch.push(marker);
                } else if (item.klasse == 'DiverCountry') {
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('divers_country', iconPath)});
                    GEvent.addListener(marker, 'click', function() {
                        openBuddyCountryMarkerPopup(this, this.id, map);
                    });
                    diverCountryBatch.push(marker);
                } else if (item.klasse == 'DiveSite') {
                    marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id:item.id,title:item.name, icon: getYDBIcon('divespot', iconPath) });
                    GEvent.addListener(marker, 'click', function() {
                        openDivespotMarkerPopup(this, this.id, map, showDives);
                    });
                    divesiteBatch.push(marker);
                } else if (item.klasse == 'DivesiteCountry') {
                    if (item.numberOfDivecenter || item.numberOfDivespots) {
                        marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id: item.id, title:item.name, icon: getYDBIcon('divespots_country', iconPath) });
                        GEvent.addListener(marker, 'click', function() {
                            openCountryMarkerPopup(this, this.id, map);
                        });
                        countryBatch.push(marker);
                    }
                } else if (item.klasse == 'Country') {
                    if (item.numberOfDivecenter || item.numberOfDivespots) {
                        marker = new GMarker(new GLatLng(item.latitude, item.longitude), {id: item.id, title:item.name, icon: getYDBIcon('country', iconPath) });
                        GEvent.addListener(marker, 'click', function() {
                            openCountryMarkerPopup(this, this.id, map);
                        });
                        countryBatch.push(marker);
                    }
                }
                if (setOptimalZoom.indexOf(item.klasse) > -1) {
                    //                    alert(setOptimalZoom, setOptimalZoom);
                    setBounds(marker);
                }
            }
            catch (exception) {
                //                println
                //                exception;
            }
        }

    }
    mgr.addMarkers(diverBatch, diverMaxzoom);
    mgr.addMarkers(buddyCountryBatch, countryMaxzoom);
    mgr.addMarkers(diverCountryBatch, 2);
    mgr.addMarkers(otherdiversBatch, otherdiversMaxzoom);
    mgr.addMarkers(divecenterBatch, divecenterMaxzoom);
    mgr.addMarkers(divesiteBatch, divesiteMaxzoom);
    mgr.addMarkers(countryBatch, countryMaxzoom);
    mgr.addMarkers(buddiesBatch, diverMaxzoom);
    mgr.refresh();

    //    var multipleMarkers = new Boolean(divecenterBatch.size() > 0 && divesiteBatch.size() > 0);
    if (setOptimalZoom.size() > 0) {
        if (center_site_connection && (new Boolean(divecenterBatch.size() > 0 && divesiteBatch.size() > 0))) {
            getMarkerConnections(map, divecenterBatch, divesiteBatch);
        }
        if (diver_buddy_connection && (new Boolean(diverBatch.size() > 0 && buddiesBatch.size() > 0))) {
            getMarkerConnections(map, diverBatch, buddiesBatch);
        }
        if (diver_buddy_connection && (new Boolean(diverBatch.size() > 0 && buddyCountryBatch.size() > 0))) {
            getMarkerConnections(map, diverBatch, buddyCountryBatch);
        }
        adaptZoom(map, mgr);
    }
}

function addYdbOverlay(map, iconPath) {
    // Erstellt die Copyright Informationen
    //      alert(iconPath,iconPath);
    var hasOverlay = false;
    var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 1, "(c) 2009 Yourdivebook.com");
    var copyrightCollection = new GCopyrightCollection('YDB-Map:');
    copyrightCollection.addCopyright(copyright);
    var tileLayerOverlay = new GTileLayerOverlay(
            new GTileLayer(copyrightCollection, 0, 1, {
                tileUrlTemplate: iconPath + "ydb_map_{X}_{Y}_{Z}.jpg",
                isPng:true,
                opacity:1.0
            })
            );
    if (map.getZoom() < 2 && !hasOverlay) {
        map.addOverlay(tileLayerOverlay);
        hasOverlay = true;
    }
    map.addControl(new addZoomcontrol(iconPath));
    GEvent.addListener(map, "zoomend", function() {
        if (map.getZoom() < 2) {
            if (!hasOverlay) {
                map.addOverlay(tileLayerOverlay);
                hasOverlay = true;
            }
        }
        else {
            map.removeOverlay(tileLayerOverlay);
            hasOverlay = false;
        }
    });

        GEvent.addListener(map, "zoomCommit", function() {
        if (map.getZoom() < 2) {
            if (!hasOverlay) {
                map.addOverlay(tileLayerOverlay);
                hasOverlay = true;
            }
        }
        else {
            map.removeOverlay(tileLayerOverlay);
            hasOverlay = false;
        }
    });

    GEvent.addListener(map, "zoomstart", function() {
        if (hasOverlay) {
            map.removeOverlay(tileLayerOverlay);
            hasOverlay = false;
        }
    });
}

function addZoomcontrol(iconPathIn) {
    var iconPath = iconPathIn;
}
addZoomcontrol.prototype = new GControl();

addZoomcontrol.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var zoomInDiv = document.createElement("div");
    var zoominPic = document.createElement("img");
    zoomInDiv.style.height = "30px";
    var img = document.createAttribute("src");
    img.nodeValue = iconPath + "zoomIn.png";
    zoominPic.setAttributeNode(img);
    container.appendChild(zoomInDiv);
    zoomInDiv.appendChild(zoominPic);
    GEvent.addDomListener(zoomInDiv, "click", function() {
        map.zoomIn();
    });
    var zoomoutDiv = document.createElement("div");
    var zoomoutPic = document.createElement("img");
    var img2 = document.createAttribute("src");
    img2.nodeValue = iconPath + "zoomOut.png";
    zoomoutPic.setAttributeNode(img2);
    container.appendChild(zoomoutDiv);
    zoomoutDiv.appendChild(zoomoutPic);
    GEvent.addDomListener(zoomoutDiv, "click", function() {
        map.zoomOut();
    });
    map.getContainer().appendChild(container);
    return container;

};
addZoomcontrol.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
};

function addboxZoom(map, iconPath) {
    var otherOpts = {
        buttonStartingStyle: {Top:'50px'},
        buttonHTML: '<img title=\"Drag Zoom In\" src=\"' + iconPath + '/zoomInDrag.png\">',
        buttonStyle: {width:'33px', height:'33px'},
        buttonZoomingHTML: '<img title=\"Reset\" src=\"' + iconPath + '/zoomInReset.png\">',
        buttonZoomingStyle: {width:'33px', height:'33px'},
        backButtonEnabled: false,
        overlayRemoveTime: 1500
    };
    map.addControl(new DragZoomControl({}, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 70)));
}

function addEditormarker(map, iconPath, marker) {
    var autodetectionDiv = document.getElementById("autodetection");
    var resetDiv = document.getElementById("resetMarker");
    GEvent.addListener(marker, "dragend", function() {
        var point = marker.getLatLng();
        map.panTo(point);
        renderCoords(point.lat(), point.lng());
        autodetectionDiv.style.visibility = "hidden";
        resetDiv.style.visibility = "visible";
    });
    GEvent.addListener(map, "click", function(overlay, point) {
        if (point) {
            marker.setLatLng(point);
            marker.show()
            renderCoords(point.lat(), point.lng());
            autodetectionDiv.style.visibility = "hidden";
            resetDiv.style.visibility = "visible";
        }
    });
}

function gcoordsAutodetection(map, marker, street, city, country) {
    var autodetectionDiv = document.getElementById("autodetection");
    var resetDiv = document.getElementById("resetMarker");
    GEvent.addDomListener(autodetectionDiv, "click", function() {
        var address = '';
        if (street) {
            address = address + street;
        }
        if (city) {
            address = address + ' ' + city;
        }
        if (country) {
            address = address + ' ' + country;
        }
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(address, function(coords) {
            if (!coords) {
                alert("Could not find \"" + street + ", " + city + ", " + country + "\"");
            }
            else {
                map.setCenter(coords);
                marker.setLatLng(coords);
                marker.show();
                map.setZoom(11);
                renderCoords(coords.lat(), coords.lng());
                autodetectionDiv.style.visibility = "hidden";
                resetDiv.style.visibility = "visible";
            }
        }
                );
    });

    GEvent.addDomListener(resetDiv, "click", function() {
        var middle = new GLatLng(0, 0);
        map.setCenter(middle);
        marker.setLatLng(middle);
        marker.hide();
        map.setZoom(2);
        document.getElementById("longitude").value = null;
        document.getElementById("longitude_text").firstChild.data = '...';
        document.getElementById("latitude").value = null;
        document.getElementById("latitude_text").firstChild.data = '...';
        autodetectionDiv.style.visibility = "visible";
        resetDiv.style.visibility = "hidden";
    });
}
function renderCoords(latitude, longitude) {
    var decimalSeparator = document.getElementById("decimalSeparator").firstChild.data;
    document.getElementById("longitude").value = longitude.toString().replace('.', decimalSeparator);
    document.getElementById("longitude_text").firstChild.data = longitude.toString();
    document.getElementById("latitude").value = latitude.toString().replace('.', decimalSeparator);
    document.getElementById("latitude_text").firstChild.data = latitude.toString();
}
