// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
// map. It has a border of the given weight and color and can optionally
// have a semi-transparent background color.


var theRectangle = null;

function Rectangle(marker, bounds, opt_weight, opt_color, opt_fillcolor, opt_opacity) {
	this.map_ = null;
	this.marker_ = marker;
	this.bounds_ = bounds;
	this.weight_ = opt_weight || 2;
	this.color_ = opt_color || "#000000";
	this.fillcolor_ = opt_fillcolor || "#FFFFFF";
	this.opacity_ = opt_opacity || 0.0;
	this.listener_ = null;
	theRectangle = this;
}

Rectangle.prototype = new GOverlay();

// Creates the DIV representing this rectangle.
Rectangle.prototype.initialize = function(map) {
	this.map_ = map;
	var me = this;
	// Create the DIV representing our rectangle
	var div = document.createElement("div");

	div.style.border = this.weight_ + "px solid " + this.color_;
	div.style.position = "absolute";

	div.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+ (this.opacity_*100) + ");";
	div.style.KHTMLOpacity = this.opacity_;
	div.style.MozOpacity = this.opacity_;
	div.style.opacity = this.opacity_;
  
	div.style.backgroundColor = this.fillcolor_;

	map.getPane(G_MAP_MARKER_PANE).appendChild(div);

	this.listener_ = GEvent.addListener(map, 'click', function(overlay, latlng){
		if(me.bounds_.containsLatLng(latlng)){
			GEvent.removeListener(me.listener_);
			me.map_.setCenter(me.marker_.getLatLng(), me.map_.getZoom()+1);
			GEvent.trigger(me.marker_, 'click', me.marker_.getLatLng());
		}
	});

	// Mouseover behaviour for the cursor.
	div.style.cursor = "pointer";

	this.map_ = map;
	this.div_ = div;
}


// Remove the main DIV from the map pane
Rectangle.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
	if(theRectangle && theRectangle.listener_){
		setTimeout( "GEvent.removeListener(theRectangle.listener_);theRectangle=null;",300);
	}
}

// Copy our data to a new Rectangle
Rectangle.prototype.copy = function() {
	return new Rectangle(this.bounds_, this.weight_, this.color_,
			   this.backgroundColor_, this.opacity_);
}

// Redraw the rectangle based on the current projection and zoom level
Rectangle.prototype.redraw = function(force) {
	// We only need to redraw if the coordinate system has changed
	if (!force) return;

	// Calculate the DIV coordinates of two opposite corners of our bounds to
	// get the size and position of our rectangle
	var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

	// Now position our DIV based on the DIV coordinates of our bounds
	this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
	this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
	this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
	this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
}

