/* MAP *****************************/

function Map () {
}

Map.prototype.markerImages = {
    normal: BASE_URL + 'img/marker/red_20_normal.png',
    bookmarked: BASE_URL + 'img/marker/red_20_bookmarked.png',
    closed: BASE_URL + 'img/marker/red_20_closed.png',
    user: BASE_URL + 'img/marker/user_home.png'
}

Map.prototype.load = function (domElem) {
    var that = this;
    if (GBrowserIsCompatible()) {
        this.map = new GMap2(domElem);
        this.map.addControl(new GSmallMapControl());
        this.map.addControl(new GMapTypeControl());
        tooltip = document.createElement("div");
        tooltip.style.visibility="hidden";
        this.map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);

        that.center = new GLatLng(GMAPS_CONF.default_lat, GMAPS_CONF.default_lon);
        that.map.setCenter(that.center, GMAPS_CONF.default_zoomlevel);

        for (i in allLocations) {
            if (!allLocations[i]) continue;

            show = false;
            if (logic._currentTag == 'Favoriten' && allLocations[i].bookmarked) {
                show = true;
            } else if (logic._currentTag != 'Alle') {
                for (var j in allLocations[i].TAGS) {
                    if (formatURLFriendly(allLocations[i].TAGS[j]) == logic._currentTag) {
                        show = true;
                        break;
                    }
                }
            } else {
                show = true;
            }
            this.extendMap(allLocations[i], show);
        }
    }
};

Map.prototype.extendMap = function (loc, show) {
    var that = this;

    if (!loc) {
        alert("Keine Daten vorraetig ");
        return;
    }

    if (loc.GEO_LAT && loc.GEO_LON) {
        try {
            loc.point = new GLatLng(parseFloat(loc.GEO_LAT), parseFloat(loc.GEO_LON)); 
        } catch (e) {
            alert( 'fehler ...' + e);
        }
        this.createMarker(loc, show);
    } else {
        var address = this.getAddress(loc);
        if (!address) return;

        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(address , function(point) {
            if (point) {
                loc.point = point;
                that.createMarker(loc, show);
            } else {
                //alert("Geokoordinaten f&uuml;r " + address + " konnten nicht bestimmt werden");
            }
        });
    }
};

Map.prototype.createMarker = function (loc, show) {
    var that = this;

    var icon = (allLocations[loc.ID].closed ) ? this.newIcon(this.markerImages.closed) : this.newIcon();
    icon = allLocations[loc.ID].bookmarked ? this.newIcon(this.markerImages.bookmarked) : icon;
    var marker = new GMarker(loc.point, icon);
        marker.tooltip = '<div class="tooltip"><nobr>'+ allLocations[loc.ID].NAME +'<\/nobr><\/div>';
    this.map.addOverlay(marker);
    if (!show) marker.hide();

    allLocations[loc.ID].marker = marker;

    GEvent.addListener(marker, "click", function() {
        logic.selectTripMarker(loc.ID);
        that.openInfoWindow(loc);
    });

    GEvent.addListener(marker, "mouseover", function() {
        $("#trip_" + loc.ID).addClass("hover");
        showTooltip(marker);
    });

    GEvent.addListener(marker, "mouseout", function() {
        $("#trip_" + loc.ID).removeClass("hover");
        tooltip.style.visibility="hidden"
    });
}

    // ====== This function displays the tooltip ======
    // it can be called from an icon mousover or a side_bar mouseover
    function showTooltip(marker) {
      	tooltip.innerHTML = marker.tooltip;
	    var point=this.map.map.getCurrentMapType().getProjection().fromLatLngToPixel(this.map.map.fromDivPixelToLatLng(new GPoint(0,0),true),this.map.map.getZoom());
	    var offset=this.map.map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),this.map.map.getZoom());
	    var anchor=marker.getIcon().iconAnchor;
	    var width=marker.getIcon().iconSize.width;
	    var height=tooltip.clientHeight;
	    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	    pos.apply(tooltip);
	    tooltip.style.visibility="visible";
}


    // ===== This function is invoked when the mouse goes over an entry in the side_bar =====
    // It launches the tooltip on the icon      
    function mymouseover(i) {
        showTooltip(gmarkers[i])
    }
    // ===== This function is invoked when the mouse leaves an entry in the side_bar =====
    // It hides the tooltip      
    function mymouseout() {
        tooltip.style.visibility="hidden";
    }

    // This function picks up the side_bar click and opens the corresponding info window
    function myclick(i) {
        gmarkers[i].openInfoWindowHtml(htmls[i]);
    }



Map.prototype.addUserLocation = function (data) {
    if (!data.geo_lat || !data.geo_lon)
        return;

    var that = this;

    var icon = this.newIcon(this.markerImages.user, [18, 16]);
    var point = new GLatLng(parseFloat(data.geo_lat), parseFloat(data.geo_lon));
    var marker = new GMarker(point, { icon: icon, zIndexProcess: function() { return -999999999 } });
    this.map.addOverlay(marker);

    GEvent.addListener(marker, "click", function() {
        var text = "<p>";
        text += "Dieser Pin stellt Ihren Standort<br />anhand der angegebenen Adressdaten dar:<br />";
        text += "<br />";
        text += "<strong>" + data.street + "</strong><br />";
        text += "<strong>" + data.zip + " " + data.city + (data.region != "" ? ", " + data.region : "") + "</strong><br />";
        text += "<br />";
        text += "Sind die Daten nicht korrekt?<br />"
        text += "<a href=\"" + SITE_URL + "register/edit\">Hier k&ouml;nnen Sie sie &auml;ndern.</a>";
        text += "</p>"
        marker.openInfoWindowHtml(text );
    });
}

Map.prototype.newIcon = function (image, size) {
    size = size || [12, 20];

    var icon = new GIcon();
    icon.image = image || this.markerImages.normal;
    icon.iconSize = new GSize(size[0], size[1]);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);

    return icon;
};

Map.prototype.getAddress = function(loc) {
    if (!loc.ORT) return null;

    return loc.STRASSE + " " + loc.PLZ + " " + loc.ORT + ",Germany";
}

Map.prototype.openInfoWindow = function (loc) {
    if (!loc.marker) return;

    var text = '';
    var index;
    if(INDEX_PAGE !== '') {
    	index = '/'+INDEX_PAGE;
    } else {
    	index = '';
    }
    text += '<div class="mapInfo">';

    text += '<h4><a href="' + BASE_URL + allLocations[loc.ID].SEO_NAME + index + '/ausflug/' + loc.ID + '">' ;
    text += loc.NAME + '</a></h4>';

    // add the images only if not in detail view for a trip
    if (loc.IMAGE) {
        text += '<p><a class="image" href="' + BASE_URL + allLocations[loc.ID].SEO_NAME + index + '/ausflug/' + loc.ID + '">' ;
        text += '<img border="0" height="70" width="96" src="' + loc.IMAGE + '">';
        text += '</a></p>';
    }
    else {
        text += '<p><a class="image" href="' + BASE_URL + allLocations[loc.ID].SEO_NAME + index + '/ausflug/' + loc.ID + '">' ;
        text += '<img border="0" height="70" width="96" src="http://www.100ausfluege.de/img/default.jpg">';
        text += '</a></p>';
    }

    /*
    text += '<p class="tags">';
    text += loc.TAGS.join("&nbsp;/ ");
    text += "</p>";
    */

/*    text += '<a href="' + SITE_URL + 'ausflug/' + loc.ID + '" class="detail_link"' ;
    text += ' onclick="logic.showTrip(' + loc.ID + ', true); return false;">';
    text += 'zur Detailansicht</a>';*/

    text += "</div>";

    loc.marker.openInfoWindow( text );
    this.infoLoc = loc.ID;
}

Map.prototype.highlightTag = function(tag) {
    for (var i in allLocations) {
        var loc = allLocations[i];
        var show = (tag == 'Alle' || (tag == 'Favoriten' && loc.bookmarked));

        if (!show) {
            for (var i in loc.TAGS) {
                if (formatURLFriendly(loc.TAGS[i]) == tag) {
                    show = true;
                    break;
                }
            }
        }

        this.showLocation(loc, show);
    }
}

Map.prototype.showLocation = function(loc, show) {
    if (!loc.marker) return;

    if (show) {
        loc.marker.show();
    } else {
        loc.marker.hide();
        if (this.infoLoc == loc.ID) 
            this.map.closeInfoWindow();
    }
}

Map.prototype.showDetail = function(id) {
    this.map.setCenter(allLocations[id].point, GMAPS_CONF.detail_zoomlevel);
}

Map.prototype.showOverview = function() {
    this.map.setCenter(this.center, GMAPS_CONF.default_zoomlevel);
}

Map.prototype.markTrip = function(id) {
    allLocations[id].bookmarked = true;
    if (allLocations[id].marker)
        allLocations[id].marker.setImage(this.markerImages.bookmarked);
}

Map.prototype.unmarkTrip = function(id) {
    allLocations[id].bookmarked = false;
    if (allLocations[id].marker){
        if(allLocations[id].closed)
            allLocations[id].marker.setImage(this.markerImages.closed);
        else 
            allLocations[id].marker.setImage(this.markerImages.normal);
    }
    if (logic._currentView == 'list' && logic._currentTag == 'Favoriten') {
        if (this.infoLoc == id) 
            this.map.closeInfoWindow();
        if (allLocations[id].marker)
            allLocations[id].marker.hide();
    }
}

