/**
 * @param {Object} options
 * @return {GMap2}
 */
var gmap = function( options ) {
	/** {Object} */
	this.options = options;

	/** {String} ID контейнера с картой */
	this.gMapId = this.options.gMapId;

	/** {HTMLElement} контейнер карты */
	this.gMapContainer = document.getElementById( this.gMapId );
	if( !this.gMapContainer ) {
		//console.log("EXIT: Can't find gMap container");
		return false;
	};

	/** {GMap2} */
	this.gMap = null;

	/** {Array} Массив точек */
	this.points = options.points || [];

	/** {GMarkerManager} */
	this.gMarkerManager = null;

	/** {Array} Массив маркеров добавляемых средствами gMarkerManager */
	this.markers = [];

	/** {Array} Координаты центра карты [fLat, fLang, nZoom] */
	var gMapCenter = this.options.gMapCenter || this.points[0].xyz || [55.759617, 37.678267, 9];

	//
	// Параметры инициализации объектов
	//

	// TODO: Базовые настройки карты
	var GMAP_SETTINGS = {
		controls: new GSmallMapControl(),
		center: new GLatLng(
			parseFloat(gMapCenter[0]),
			parseFloat(gMapCenter[1])
		),
		zoom: parseInt( gMapCenter[2] ),
		bounds: this.options.autozoom ? new GLatLngBounds() : null,
		magerOpts: {
			minZoom: 0,
			maxZoom: 17
		}
	};

	/**
	 * Инициализация
	 */
	this.initialize = function() {
		if( !GBrowserIsCompatible() ) {
			//console.log("EXIT: Browser is not compatible");
			return false;
		}

		this.gMap = new GMap2( this.gMapContainer );
//marker менеджер
//		this.mgr = new MarkerManager(this.gMap);

//console.log(this.options.gMapCenter);
		this.gMap.enableScrollWheelZoom();
		this.gMap.addControl( GMAP_SETTINGS.controls );
		this.gMap.setCenter( GMAP_SETTINGS.center, GMAP_SETTINGS.zoom );

		var pointsLen = this.points.length;

		if( !pointsLen ) {
			//console.log("EXIT: No points to display");
			return false;
		}

		for( var i = 0; i < pointsLen; i++ ) {
			this.markers.push( this.createMarker(this.points[i], GMAP_SETTINGS.bounds) );
		}
//console.log(GMAP_SETTINGS.bounds);
		if( this.markers.length > 1 ) {
			this.gMarkerManager = new GMarkerManager(this.gMap);
			this.setPointsMM( this.markers, GMAP_SETTINGS.magerOpts );

			//console.log("Manager");

			this.gMarkerManager.refresh();
		} else {
			//console.log("Single");
			this.setPoint( this.markers[0] );
		}

		if( GMAP_SETTINGS.bounds ) {
			// Auto zoom
			this.gMap.setZoom( this.gMap.getBoundsZoomLevel(GMAP_SETTINGS.bounds)-1 );
			// Auto center
			this.gMap.setCenter( GMAP_SETTINGS.bounds.getCenter() );
			
		}

		/*
		var map = this.gMap;
		GEvent.addListener( this.gMap, 'singlerightclick', function(point) {
			var p = map.fromContainerPixelToLatLng(point);

			GLog.write( p.lat() + ', ' + p.lng() + ', ' + map.getZoom() );
		});
		*/

		return this.gMap;
	};

	/**
	 * @param {Object} point
	 * @param {GLatLngBounds} [bounds]
	 *
	 * @return {GMarker} marker
	 */
	this.createMarker = function( point, bounds ){
		var latlng = new GLatLng( parseFloat(point.xyz[0]), parseFloat(point.xyz[1]) );

		var markerB = new GIcon(G_DEFAULT_ICON);
	
		markerB.image = "/_pic/marker.png";
		markerB.shadow = "/_pic/marker_shadow.png";
		markerB.transparent = "/_pic/marker-transparent.png";
		markerB.iconSize = new GSize(43, 33);
		markerB.shadowSize = new GSize(49, 33);

		markerB.printImage = "/_pic/marker-print.png";
		markerB.printShadow = "/_pic/p.gif";
		markerB.imageMap = [0,11,0,21,43,21,16,31,15,21,25,21,43,11,31,4,21,1,10,4];

//		markerB.infoWindowAnchor = new GPoint(25, -50);

	
		markerB.iconAnchor = new GPoint(15, 31);	
//		markerB.infoWindowAnchor = new GPoint(40, 5);

			
	// Настройка объекта GMarkerOptions
		markerOptions = { icon:markerB, title: point.title, clickable:point.clickable};

		var marker = new GMarker( latlng, markerOptions );

/*GEvent.addListener(gmap, "click", function(marker, point) {
  if (marker) {
  map.removeOverlay(marker);
  } else {
    map.addOverlay(new GMarker(point));
  }
});
*/
		if( bounds ) {
			// Расширяем видимую область до текущей точки
			bounds.extend( latlng );
		}

		var sPointHref = point.url;
		
		if( sPointHref.length ) {
			GEvent.addListener(marker, 'click', function() {
				window.location = sPointHref;
			});
		}

		//this.setPoint( p );



		return marker ;
	};

	/**
	 * Добавить одну точку на карту
	 *
	 * @param {GMarker} point
	 */
	this.setPoint = function(point) {
		this.gMap.addOverlay(point);
	};

	/**
	 * Добавить множество точек в менеджер
	 *
	 * @param {GMarker[]} points
	 * @param {Object} opts
	 */
	this.setPointsMM = function(points, opts) {

			var maxZoom = new Array();
			var minZoom = new Array();
						
			for( var i = 0; i < points.length; i++ ) {
			//	this.markers.push( this.createMarker(this.points[i], GMAP_SETTINGS.bounds) );

				minZoom[i] = (this.points[i].max_zoom == 0 ? this.points[i].xyz[2] : this.points[i].min_zoom ) || opts.minZoom;
				maxZoom[i] = (this.points[i].max_zoom > 0 ? this.points[i].max_zoom : 17 ) || opts.maxZoom;
	//	console.log(maxZoom[i], ' ' ,this.points[i].max_zoom, ' ' ,this.points[i].min_zoom, ' ' ,this.points[i].xyz[2], ' ' ,this.points[i].title);		
		
			this.gMarkerManager.addMarkers([points[i]], minZoom[i], maxZoom[i]);
		}

/*
maxZoom[i] = (this.points[i].max_zoom > 0 ? this.points[i].max_zoom : 17 ) || opts.maxZoom;

this.gMarkerManager.addMarkers([points[i]], this.points[i].xyz[2], maxZoom[i]);

console.log(maxZoom[i], ' ' ,this.points[i].max_zoom, ' ' ,this.points[i].min_zoom, ' ' ,this.points[i].xyz[2], ' ' ,this.points[i].title);		

*/


	};

	return this.initialize();
};

window.onunload = GUnload;
