/*
Copyright 2005-2007 James Tolley - http://www.bitperfect.com | http://www.gmaptools.com
All rights reserved.
This software is released under the LGPL. (http://www.opensource.org/licenses/lgpl-license.php)

0.1 -- needs quite a bit more testing for some things

todo:
  tests
  add support for int'l dateline

*/
function setupZoomToMarkers(map) {
	if(typeof(map.zoomToMarkers) == 'function')
		return;

  setupGetMarkers(map);

	map.zoomToMarkers = function(margin, points, maxZoom) {
		// if there are no points specified, use the mapped markers' points
	  if(!points) {
		  var m = this.getMarkers();
		  if(m.length == 0)
		  	return; // return if we don't know where to zoom

			// get the points of the markers
	    points = [];
	    for(var i = 0; i < m.length; i++)
        if (!m[i].isHidden())
  	      points.push(m[i].getPoint());
	  } else if(points.length && typeof(points[0].getPoint) == 'function') {
			// there are markers specified, so get their points
	    var p = [];
	    for(var i = 0; i < points.length; i++)
	      p.push(points[i].getPoint());
	    points = p;
	  }

		if(points.length == 0 || !points[0])
			return;

		margin = margin || 0; // set the default (a percentage of the span)

		// create the bounds to zoom to
		var bounds = new GLatLngBounds(points[0]);
		for(var i = 1; i < points.length; i++) {
			bounds.extend(points[i]);
		}
		
		// manage margin
    if (margin > 0) {
      var span = bounds.toSpan();
      var ne = bounds.getNorthEast();
      var sw = bounds.getSouthWest();
      var newNE = new GLatLng(ne.lat()+margin*span.lat(), ne.lng()+margin*span.lng());
      bounds.extend(newNE);
      var newSW = new GLatLng(sw.lat()-margin*span.lat(), sw.lng()-margin*span.lng());
      bounds.extend(newSW);
    }

    var span = bounds.toSpan();
    var centerLat = bounds.getSouthWest().lat() + .5 * span.lat();
    var centerLng = bounds.getSouthWest().lng() + .5 * span.lng();
    var center = new GLatLng(centerLat, centerLng);

		var zoom = this.getBoundsZoomLevel(bounds);
	  if(arguments.length > 2 && zoom > maxZoom)
	    zoom = maxZoom;

		this.setCenter(center, zoom);
	};
}
setupZoomToMarkers.version = 0.1;
