/**
 * @author Marco Alionso Ramirez, marco@onemarco.com
 * @url http://onemarco.com
 * @version 1.0
 * This code is public domain
 */

/**
 * The Tooltip class is an addon designed for the Google Maps GMarker class. 
 * @constructor
 * @param {GMarker} marker
 * @param {String} text
 * @param {Number} padding
 */
function Tooltip(marker, text, padding){
	this.marker_ = marker;
	this.text_ = text;
	this.padding_ = padding;
}

Tooltip.prototype = new GOverlay();

Tooltip.prototype.initialize = function(map){
	var div = document.createElement("div");
	div.innerHTML = this.text_;
	div.className = 'tooltip';
	div.style.position = 'absolute';
	div.style.visibility = 'hidden';
	$(div).fadeTo(0, 0.9);
	map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	this.map_ = map;
	this.div_ = div;
}

Tooltip.prototype.remove = function(){
	this.div_.parentNode.removeChild(this.div_);
}

Tooltip.prototype.copy = function(){
	return new Tooltip(this.marker_,this.text_,this.padding_);
}

Tooltip.prototype.redraw = function(force){
	if (!force) return;
	
	var markerIcon = this.marker_.getIcon();
	var markerPos = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
	var iconAnchor = markerIcon.iconAnchor;
	var xPos = Math.round(markerPos.x - this.div_.clientWidth / 2);
	var yPos = markerPos.y - iconAnchor.y - this.div_.clientHeight - this.padding_ - 2;

	var relLocation = this.map_.fromLatLngToContainerPixel(this.marker_.getPoint());
	
	// This is the tooltip y position relative to the map div
	// If this is negative, tooltip is off the reservation
	var relY = relLocation.y - markerIcon.iconSize.height - this.div_.offsetHeight;
	var relX = relLocation.x - Math.round( this.div_.offsetWidth / 2);

	if (relY < 0) {
		yPos += markerIcon.iconSize.height + this.div_.offsetHeight + 4;
	}

	if (relX < 0) {
		// Too far left
		xPos -= (relX-2); // -2 for border of map if exists
	} else {
		relX = this.map_.getSize().width - (relX + this.div_.offsetWidth);
		// Too far right
		if (relX < 0) {
			xPos += (relX-2);
		}
	}

	this.div_.style.top = yPos + 'px';
	this.div_.style.left = xPos + 'px';
}

Tooltip.prototype.show = function(){
	this.div_.style.visibility = 'visible';
}

Tooltip.prototype.hide = function(){
	this.div_.style.visibility = 'hidden';
}



















