google.load('search', '1');
var localSearch = null;
var geocoder = null;

// ---------------------------------------
// ---------------------------------------
//	Классы
// ---------------------------------------
// ---------------------------------------


function classBoundTiles(type, callback){ this.type = type; this.callback = callback; };
classBoundTiles.prototype = 
{
	status: 0,
	markers: new Array(),
	markersTiles: new Array(),
	tiles: new Array(),
	_tiles: new Array(),
	
	k: 1000,
	_stepLat: {"1": 5, "2": 20},
	_stepLng: {"1": 10, "2": 40},
	stepLat: 5,
	stepLng: 10,
	
	zoom: null,
	lat1: null,
	lat2: null,
	lng1: null,
	lng2: null,
	
	/**
	 *	округляем
	 */	
	round: function(n, dir, k, osn)
	{
		var intN = n * k;
		
		if(dir > 0)
		{
			return (Math.ceil(intN/osn))*osn;
		}
		
		return (Math.floor(intN/osn))*osn;	
	},
	
	/**
	 *	устанавливаем координаты
	 */
	reloadBound: function(bound, zoom)
	{
		this.status = 1;
		var f = {};
		
		this.zoom = this.getZoom(zoom);
		this.stepLat = this._stepLat[this.zoom];
		this.stepLng = this._stepLng[this.zoom];
				
		this.lat1 = bound.getNorthEast().lat();
		this.lat2 = bound.getSouthWest().lat(); 
		this.lng1 = bound.getSouthWest().lng();
		this.lng2 = bound.getNorthEast().lng();

		this.lat1 = this.round(this.lat1, 1, this.k, this.stepLat);
		this.lat2 = this.round(this.lat2, -1, this.k, this.stepLat);
		this.lng1 = this.round(this.lng1, -1, this.k, this.stepLng);
		this.lng2 = this.round(this.lng2, 1, this.k, this.stepLng);
		
		this.makeTiles();
	},
	
	getZoom: function(zoom)
	{
		if(zoom > 13) { return 1; }
		return 2;
	},
	
	clearAll: function()
	{
		this.status = 0;
		for(var key in this.tiles)
		{
			this.removeTile(key);
			delete this.tiles[key];
		}
	},
		
	/**
	 *	формируем новые плитки
	 */
	makeTiles: function()
	{
		this._tiles = new Array();
		
		for(var lng = this.lng1; lng < this.lng2; lng += this.stepLng)
		{
			for(var lat = this.lat1; lat > this.lat2; lat -= this.stepLat)
			{
				var box = {};
				box.lat = lat;
				box.lng = lng;
				box.id = lat+"_"+lng;
				this._tiles[box.id] = box;
				
				//var latlng = new GLatLng(box.lat/this.k, box.lng/this.k);
				//var mk = new GMarker(latlng);
				//map.addOverlay(mk);
			}
		}
	
		this.reloadTiles();
	},
	
	/**
	 *	перегружаем плитки
	 */
	reloadTiles: function()
	{
		/** remove tiles - если в новых координатах ее нет **/
		for(var key in this.tiles)
		{
			if(!this._tiles[key]) { this.removeTile(key); }
		}
	
		/** загружаем новые плитки **/
		for(var key in this._tiles)
		{
			if(this.tiles[key]) { continue; }
			else
			{
				var box = this._tiles[key];
				
				var f = {};
				var url = '/'+this.type+'/'+this.zoom+'/'+box.lat+'/'+box.lng+'/';
				
				$.getJSON(url, f, this.callback);
			}
		}
		
		this.tiles = this._tiles;
		delete this._tiles;
	},
	
	/**
	 *	Удаляем плитки и маркеры в ней
	 */
	removeTile: function(tileId)
	{
		/** remove marker **/
		for(var mId in this.markersTiles[tileId])
		{
			map.removeOverlay(this.markers[mId]); 
			delete this.markers[mId];
		}
		
		delete this.markersTiles[tileId];
	},
	
	/**
	 *	добавляем связь плитки с маркером
	 */
	addMarkerToTile: function(tileId, mId)
	{
		if(!this.markersTiles[tileId])
		{
			this.markersTiles[tileId] = new Array();
		}
		
		this.markersTiles[tileId][mId] = 1;
	}
}


// ------------------------------------
// ------------------------------------
//	
// ------------------------------------
// ------------------------------------

function CurrentPosition() {};
CurrentPosition.prototype = 
{ 
	groupID: 0,
	placeID: 0, 
	lat: 0, 
	lng: 0, 
	pov: { yaw: 0, pitch: 0, zoom: 0}, 
	isNoCheckPos: 0,
	isNoLoadMarkers: 0,
	lastPos: null,
	
	setLastPos: function(pos)
	{
		if(!this.lastPos)
		{
			this.lastPos = new CurrentPosition();
			this.lastPos.init(pos.placeID, pos.lat, pos.lng, pos.pov); 
		}	
	},
	
	setPlaceID: function(placeID)
	{
		this.placeID = placeID;
	},
	
	setPov: function(pov)
	{
		this.pov = pov;
	},
	
	setLatLng: function(lat, lng)
	{
		this.lat = lat;
		this.lng = lng;
	},
	
	init: function(placeID, lat, lng, pov)
	{
		this.setPlaceID(placeID);
		this.setLatLng(lat, lng);
		this.setPov(pov);
	}	
};

// ------------------------------------
// ------------------------------------
//	
// ------------------------------------
// ------------------------------------

/**
 *	дебаг
 */
function lc_debug(msg)
{
	//$("#debug").append(msg + "<br/>");
}

// ------------------------------------------
// ------------------------------------------
//	
// ------------------------------------------
// ------------------------------------------

/**
 *	сохраняем место
 */
function lc_savePlace(mode)
{
	var f = {};
	f.mode = mode || 0;
	f.lat = man.getLatLng().lat();
	f.lng = man.getLatLng().lng();
	
	f.name = $("#npName").val();
	f.rating = npRating;
		
	f.cat_id = $("#npcat").val();
	f.group_id = $("#npGroup").val() ? $("#npGroup").val() : 0;
	f.tags = lc_getTags();
	f.city_id = cityID;
	f.type = $("#npType").val() ? 1 : 0;
	f.lang = langID;
	f.desc = $("#npDesc").val() ? $("#npDesc").val() : "";
	
	var pov = panorama.getPOV();
	f.yaw = pov.yaw;
	f.pitch = pov.pitch;
	f.zoom = pov.zoom;
		
	var data = ajax_postSContent("/tools/addplace.php", 1, f);
	var obj = eval('(' + data + ')');

	if(obj.errors) { alert(locStr.error); }
	else
	{
		lc_closeModal();
		var url = '/'+langID+'/map/'+obj.country_id+'/'+obj.city_id+'/'+obj.place_id+'/';		if(obj.group_id) { url += "?group="+obj.group_id; }
		location.href = url;
	}
}


// ------------------------------------------

/**
 *	сохраняем место
 */
function lc_setPlaceLocation(placeID)
{
	var f = {};
	f.place_id = placeID;
	f.lat = man.getLatLng().lat();
	f.lng = man.getLatLng().lng();
	
	var pov = panorama.getPOV();
	f.yaw = pov.yaw;
	f.pitch = pov.pitch;
	f.zoom = pov.zoom;
	f.city_id = cityID;
	
	ajax_postSContent("/tools/place.newloc.php", 1, f);
	alert("Thanks");
}


// ------------------------------------------

/**
 *	получаем строку с тегами
 */
function lc_getTags()
{
	var str = "";
	
	for(var tid in seltags)
	{
		str += seltags[tid].tgid + ":"+tid + "|||";
	}

	for(var tgid in tagsOnce)
	{
		str += tgid+":"+tagsOnce[tgid] + "|||";
	}

	for(var tgid in tagsText)
	{
		str += tgid+":"+tagsText[tgid] + "|||";
	}
	
	return str;
}

// ------------------------------------------

/**
 *	загрузчик
 */
function lc_initMapBoxs()
{
	var i = tb_getPageSize();
	var w = i[0]; var h = i[1];

	//alert(w);
	
	if(w > 1024)
	{
		var width = w - 479 - 43;
		var height = 450;		
		
		$("#page-box-main").css("min-width", (w - 50) + "px");
		
		$("#topplacebox_place").css("width", width + 43);
		$("#topplacebox_center").css("height", height + 230);
		
		$("#map_canvas").css("width", width);
		$("#pano").css("height", height);
		$("#pano").css("width", width);
		$("#birdsbox").css("height", height);
		
		$("#menubox").css("width", width - 12);
		$("#maxmapbox").css("width", width - 42);
		
		return;
		
		var mbh = $("#mapbox").height();
		if(mbh)
		{
			$("#framebox").css("height", mbh);
			$("#winPlaceInfo").css("height", mbh);			
		}
	}
}
	
// ------------------------------------------

/**
 *	загрузчик
 */
function lc_loadMainMap() 
{
	  lc_initMapBoxs();
	
	  geocoder = new GClientGeocoder();
	  
	  client = new GStreetviewClient();
      var latlng = new GLatLng(curPos.lat, curPos.lng);
	  map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(latlng , 15);
      
	  var mt = map.getMapTypes();
	  for (var i=0; i < mt.length; i++) 
	  {
	  	  mt[i].getMinimumResolution = function() { return 12; };
	      mt[i].getMaximumResolution = function() { return 17; };
	  }
    
	  map.addControl(new GSmallZoomControl ());
      map.addControl (new GScaleControl());
      
      /** icon **/
	  var guyIcon = new GIcon(G_DEFAULT_ICON);
	  guyIcon.image = "/images/man/man_arrow-0.png";
	  guyIcon.transparent = "/images/man/man-pick.png";
		
	  guyIcon.imageMap = [
	        26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
	        16,20, 16,14, 19,13, 22,8
	     ];
	    
	  guyIcon.iconSize = new GSize(49, 52);
	  guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
	  guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head
	
	  
	  man = new GMarker(latlng, {icon: guyIcon, draggable: true});
	  map.addOverlay(man);
	  lastMarkerLocation = latlng;
	  GEvent.addListener(man, "dragend", lcev_onDragEnd);

	  toggleOverlay();
	  
 	  panorama = new GStreetviewPanorama(document.getElementById("pano"));
      GEvent.addListener(panorama, "error", lc_panoramaError);  
  	  GEvent.addListener(panorama, "yawchanged", lcev_onYawChange);  	  
	  GEvent.addListener(map, "click", lcev_onMapClick);
  	  GEvent.addListener(panorama, "initialized", lcev_onLocChange); 
	  map.disableScrollWheelZoom();
	  map.disableContinuousZoom();
	  map.disableDoubleClickZoom();	  
	  
	  GEvent.addListener(map, "zoomend", lcev_mapZoomend);
	  GEvent.addListener(map, "moveend", lcev_mapMoveend);

	  panorama.setLocationAndPOV(latlng, curPos.pov);
	  
	  
	  localSearch = new google.search.LocalSearch();
	  localSearch.setCenterPoint(latlng); 
	  localSearch.setSearchCompleteCallback(this, lc_showSearchResult, null);  	  
  	  localSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
  	  loadMarkers();
}

// ---------------------------------------------
// ---------------------------------------------
//	
// ---------------------------------------------
// ---------------------------------------------

var searchMarkers = new Array();
function lc_showSearchResult()
{
	lc_searchClearMarkers();
	
	if(localSearch.results.length == 0) { return; }
	
	var vp = localSearch.resultViewport;
	var bnd = new GLatLngBounds(new GLatLng(parseFloat(vp.sw.lat), parseFloat(vp.sw.lng)),  
							    new GLatLng(parseFloat(vp.ne.lat), parseFloat(vp.ne.lng)));
	map.setCenter(new GLatLng(parseFloat(vp.center.lat), parseFloat(vp.center.lng)));
	var zoom = map.getBoundsZoomLevel(bnd);
	map.setZoom(zoom);
							    
	for(var i = 0; i < localSearch.results.length; i++)
	{
		var html = '<div id="tooltipName">'+localSearch.results[i].title+'</div>';
		html += '<div id="tooltipText">'+localSearch.results[i].streetAddress+'</div>';
		
		var m = lc_searchCreateMarker(new GLatLng(parseFloat(localSearch.results[i].lat), parseFloat(localSearch.results[i].lng)), html);	
		map.addOverlay(m);
		searchMarkers.push(m);
	}
}

// ---------------------------------------------

/**
 *
 */
function lc_searchClearMarkers()
{
	for(var i = 0; i < searchMarkers.length; i++) 
	{	
		map.removeOverlay(searchMarkers[i]);
		delete searchMarkers[i];
	}
	
	searchMarkers = new Array();
}

// ---------------------------------------------

/**
 *
 */
function lc_searchCreateMarker(point, html)
{
	var options = {};
	
	var icon = new GIcon();
	icon.image = '/images/mm_20_red.png';
	icon.shadow = '/images/mm_20_shadow.png';
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 5);
	//icon.infoWindowAnchor = new GPoint(5, 0);
	
	options.icon = icon; 
	
	var sm = new GMarker(point, options);
	
	GEvent.addListener(sm, "mouseover", function() 
	{
  		lc_searchShowMarkerInfo(point, html + "");
	});       	
	
	GEvent.addListener(sm, "mouseout", function() 
	{
		lc_searchHideMarkerInfo();
	});  

	GEvent.addListener(sm, "click", function() 
	{ 
		lcev_searchMarkerClick(point); 
	});
	
		
	return sm;
}

// ---------------------------------------------

/**
 *
 */
function lc_searchShowMarkerInfo(latlng, html)
{
	var mapdiv = $gid("map_canvas");
	var p = map.fromLatLngToContainerPixel(latlng);
	var x = mapdiv.offsetLeft + p.x;
	var y = mapdiv.offsetTop + p.y;
	
	$("#maptooltip").css("left", x+12);
	$("#maptooltip").css("top", y-3);
	
	$("#maptooltip").html(html);
	$("#maptooltip").show();	
}

// ---------------------------------------------

/**
 *	кликаем по маркеру
 */
function lcev_searchMarkerClick(latlng)
{
	client.getNearestPanorama(latlng, lcev_onMapClickCallback);

	if(params.is_birds_eye == 1)
	{
		lcev_birdsEyeChangeLoc(latlng);
	}
};
  
// ---------------------------------------------

/**
 *
 */
function lc_searchHideMarkerInfo()
{
	$("#maptooltip").html("");
	$("#maptooltip").hide();
}

// ---------------------------------------------

/**
 *
 */
function lc_showAddress(address) 
{
	lc_searchClearMarkers();
	
	var addr = address + ", " + caddress;
		
	if (geocoder) 
	{
		geocoder.getLatLng(
			addr,
			function(point) 
			{
				if (!point) { alert(addr + " not found"); } 
				else 
				{
					var html = '<div id="tooltipName">'+address+'</div>';
				 	map.setCenter(point);
				  	var sm = lc_searchCreateMarker(point, address);
				  	map.addOverlay(sm);
				  	searchMarkers.push(sm);
				}
			}
		);
	}
}

// ---------------------------------------------

/**
 *
 */
function lc_callSearch(str, type)
{
	if(!str) { return; }
	
	if(type == 1) 
	{ 
		localSearch.setCenterPoint(map.getCenter());
		localSearch.clearResults(); 
		localSearch.execute(str); 
	}
	else { lc_showAddress(str);	}
}


// ------------------------------------------
// ------------------------------------------
//	
// ------------------------------------------
// ------------------------------------------


/**
 *	конец зуммирования
 */
function lcev_mapZoomend(prev, cur)
{
	lc_debug("map.lcev_mapZoomend");
	loadMarkers();
}

// ------------------------------------------

/**
 *	moveend event
 */
function lcev_mapMoveend()
{
	lc_debug("map.lcev_mapMoveend");
	loadMarkers();
}
// ------------------------------------------

/** показываем/убирем слой **/
function toggleOverlay() 
{
	if (!overlayInstance) 
	{
		overlayInstance = new GStreetviewOverlay();
		map.addOverlay(overlayInstance);
	} 
	else 
	{
		map.removeOverlay(overlayInstance);
		overlayInstance = null;
	}
}


// ------------------------------------------
// ------------------------------------------
//	
// ------------------------------------------
// ------------------------------------------


/**
 *  движение на панораме
 */
function lcev_onLocChange(newLoc)
{
	lc_debug("pan: lcev_onLocChange");
	if(curPos.isPreview == 1) { return; }
	
	map.panTo(newLoc.latlng);
	man.setLatLng(newLoc.latlng);
	
	lc_debug(newLoc.latlng + " - " + curPos.lat + " - " + curPos.lng);
	
	if(!curPos.isNoCheckPos && (newLoc.latlng.lat() != curPos.lat || newLoc.latlng.lng() != curPos.lng)) { curPos.placeID = 0; }
	if(curPos.isNoCheckPos) { curPos.isNoCheckPos = 0; return; }
	if(!curPos.placeID)
	{
		var frm = getFrame();
		frm.lc_changeLocation(newLoc.latlng.lat(), newLoc.latlng.lng(), 2);
	}	
}

// ------------------------------------

/**
 *  получаем фрейм
 */
function getFrame()
{
	var frm = $("#winPlaceInfo").get(0);
	
	if(frm.contentWindow) { return frm.contentWindow; }
	else { return frm.window; }
}

// ------------------------------------

/**
 *  получаем фрейм
 */
function getFrameByID(id)
{
	var frm = $("#"+id).get(0);
	
	if(frm.contentWindow) { return frm.contentWindow; }
	else { return frm.window; }
}

// ------------------------------------
// ------------------------------------

/**
 *	меняем направление просмотра 
 */
function lcev_onYawChange(newYaw) 
{
	var GUY_NUM_ICONS = 16;
	var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
	
	if (newYaw < 0) { newYaw += 360; }
	
	guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
	guyImageUrl = "/images/man/man_arrow-" + guyImageNum + ".png";
	man.setImage(guyImageUrl);
}

// ------------------------------------
// ------------------------------------

function lcev_onDragEnd() 
{
	lc_debug("pan: lcev_onDragEnd");
	
	
	var latlng = man.getLatLng();
	
	if (panorama) 
	{
		client.getNearestPanorama(latlng, lcev_onDragEndCallback);
	}
}

// ------------------------------------

/**
 *
 */
function lcev_onDragEndCallback(response) 
{
	if (response.code != 200) 
	{
		man.setLatLng(lastMarkerLocation);
	} 
	else 
	{
		var latlng = new GLatLng(response.Location.lat, response.Location.lng);
		man.setLatLng(latlng);
		lastMarkerLocation = latlng;
		panorama.setLocationAndPOV(man.getLatLng(), null);
	}
}

// ------------------------------------
// ------------------------------------

/**
 *	кликаем по карте (не по маркеру)
 */
function lcev_onMapClick(ov, latlng) 
{
	if(latlng)
	{	
		lc_debug("map: onMapClick");
		client.getNearestPanorama(latlng, lcev_onMapClickCallback);

		if(params.is_birds_eye == 1)
		{
			lcev_birdsEyeChangeLoc(latlng);
		}
	}	
	
}

// ------------------------------------

/**
 *	обрабатываем панораму при клике на карту
 */
function lcev_onMapClickCallback(response) 
{	
	if (response.code != 200) 
	{
		man.setLatLng(lastMarkerLocation);
	} 
	else 
	{
		var latlng = new GLatLng(response.Location.lat, response.Location.lng);
		man.setLatLng(latlng);
		lastMarkerLocation = latlng;
		lc_showPanorama(latlng, null);
	}
}

// ------------------------------------    
// ------------------------------------
//	markers ...
// ------------------------------------
// ------------------------------------


/**
 *	загрузка маркеров
 */
function loadMarkers()
{
	  if(curPos.groupID) { lc_loadGroupMarkers();  }
	  else { loadMarkers2(); }
}

/**
 *	загрузка маркеров
 */
function loadMarkers2()
{
	if(curPos.isNoLoadMarkers) { return; }
	
	var zoom = map.getZoom();
	
	if(zoom >= 14) 
	{ 
		var bound = map.getBounds();
		boundTiles.reloadBound(bound, zoom);
		boundTilesWiki.reloadBound(bound, zoom);
	}
	else
	{
		boundTiles.clearAll();
		boundTilesWiki.clearAll();
	}
		
};	

// --------------------------------------
// ---------------------------------------
// ---------------------------------------
// ---------------------------------------

/**
 *	
 */
function lc_showMarkersTiles(obj)
{
	if(obj.ignore == 1) { return; }
	if(boundTiles.status == 0) { return; }
	
	var zoom = map.getZoom();
	
	for(var i = 0; i < obj.markers.length; i++)
	{
		var mId = obj.markers[i].place_id;
		if(!boundTiles.markers[mId] && !groupMarkers[mId])
		{
			boundTiles.addMarkerToTile(obj.tileid, mId);
			boundTiles.markers[mId] = lc_createMarker(zoom, obj.markers[i]);
			boundTiles.markers[mId].info_ = obj.markers[i];
			GEvent.addListener(boundTiles.markers[mId], "click", function() { lcev_markerClick(this); } );
	
			map.addOverlay(boundTiles.markers[mId]);
		}
	}	
}

// ---------------------------------------

/**
 *	
 */
function lc_showWikiTiles(obj)
{
	if(obj.ignore == 1) { return; }
	if(boundTilesWiki.status == 0) { return; }
	
	var zoom = map.getZoom();
	
	for(var i = 0; i < obj.markers.length; i++)
	{
		var mId = obj.markers[i].place_id;
		if(!boundTilesWiki.markers[mId] && !groupMarkers[mId])
		{
			boundTilesWiki.addMarkerToTile(obj.tileid, mId);
			boundTilesWiki.markers[mId] = lc_createMarker(zoom, obj.markers[i]);
			boundTilesWiki.markers[mId].info_ = obj.markers[i];
			GEvent.addListener(boundTilesWiki.markers[mId], "click", function() { lcev_markerClick(this); } );
	
			map.addOverlay(boundTilesWiki.markers[mId]);
		}
	}	
}

// ---------------------------------------

function lc_loadGroupMarkers()
{
	if(curPos.groupID)
	{
		$.getJSON('/group/'+curPos.groupID+'/', {}, lc_loadGroupMarkersCbk);
	}
}

// ---------------------------------------

function lc_loadGroupMarkersCbk(obj)
{
	if(obj.ignore == 1) { loadMarkers(); return; }
	var zoom = map.getZoom();
	
	for(var i = 0; i < obj.markers.length; i++)
	{
		var mId = obj.markers[i].place_id;
		if(!groupMarkers[mId])
		{
			groupMarkers[mId] = lc_createMarker(zoom, obj.markers[i], curPos.groupID);
			groupMarkers[mId].info_ = obj.markers[i];
			GEvent.addListener(groupMarkers[mId], "click", function() { lcev_markerClick(this); } );
	
			map.addOverlay(groupMarkers[mId]);
		}
	}
	
	//loadMarkers2();
}

// ---------------------------------------

/**
 *	кликаем по маркеру
 */
function lcev_markerClick(marker)
{
	curPos.isNoCheckPos = 1;
	var i = marker.info_;
	var latlng = new GLatLng(i.lat, i.lng);
	var pov = {yaw: i.pov_yaw, pitch: i.pov_pitch, zoom: i.pov_zoom };
	
	client.getNearestPanorama(latlng, function(response)
	{
	 	if (response.code != 200) 
		{
			man.setLatLng(lastMarkerLocation);
			if(i.cat_id == 100)
			{
				curPos.isPreview = 0;
				var url = '/'+langID+'/map/'+countryID+'/'+cityID+'/'+i.place_id+'/description/';
				if(curPos.groupID) { url += '?group='+curPos.groupID; }
				$("#winPlaceInfo").attr("src", url);		
				if(params.is_birds_eye == 1) { lcev_birdsEyeChangeLoc(latlng); }
			}
		} 
		else 
		{
			curPos.isPreview = 0;
			curPos.init(i.place_id, i.lat, i.lng, pov);
			
			lc_showPanorama(response.location.latlng, pov);
			lastMarkerLocation = response.location.latlng;
	
			var url = '/'+langID+'/map/'+countryID+'/'+cityID+'/'+curPos.placeID+'/description/';
			if(curPos.groupID) { url += '?group='+curPos.groupID; }
			$("#winPlaceInfo").attr("src", url);
			
			if(params.isFullScreen == 1) { lc_fullScreen();	}
			if(params.is_birds_eye == 1) { lcev_birdsEyeChangeLoc(response.location.latlng); }
		}
	});
};
  
// ---------------------------------------

function lc_getRadiusLatLng(lat, lng, yaw)
{
	var lat2 = lat + 0.0003*Math.cos(2*Math.PI*yaw/360);
	var lng2 = lng + 0.0004*Math.sin(2*Math.PI*yaw/360);
	
	return new GLatLng(lat2, lng2);
}

// ---------------------------------------

/**
 *	показываем маркеры мест
 */
function lc_createMarker(zoom, obj, groupID) 
{
	var grID = groupID || 0;
	var marker2 = null;

	// -----------------------------------------------
	
	/** показываем маркеры с иконками **/

	var options = {}; 
	
	var icon = new GIcon();
	if(grID) { icon.image = "/static/icons/group.gif"; }
	else { icon.image = "/static/icons/"+obj.cat_id+".gif"; }
	icon.shadow = "";
	
	var x = obj.cat_id == 100 || grID ? 10 : 8;
	var y = obj.cat_id == 100 || grID ? 10 : 8;
	
	icon.iconSize = new GSize(x, y);
	icon.iconAnchor = new GPoint(x/2, y/2);
	icon.imageMap= new Array(0, 0, x, 0, x, y, 0, y);
	options.icon = icon; 
	
	var latlng = lc_getRadiusLatLng(parseFloat(obj.lat), parseFloat(obj.lng), parseFloat(obj.pov_yaw));
	marker2 = new GMarker(latlng, options);
	
	GEvent.addListener(marker2, "mouseover", function() 
	{
  		lc_showMarkerInfo(latlng, {id: obj.place_id, lang: langID});
	});       	
	
	GEvent.addListener(marker2, "mouseout", function() 
	{
		lc_hideMarkerInfo();
	});  		
	
	return marker2;
};

// ------------------------------------
// ------------------------------------

/**
 *
 */
function lc_showMarkerInfo(glatlng, o)
{
	var html = '<img src="/images/loading2.gif" width="16" height="16"/>';
	
	var mapdiv = $gid("map_canvas");
	var p = map.fromLatLngToContainerPixel(glatlng);
	var x = mapdiv.offsetLeft + p.x;
	var y = mapdiv.offsetTop + p.y;
	
	$("#maptooltip").css("left", x+12);
	$("#maptooltip").css("top", y-3);
	
	$("#maptooltip").html(html);
	$("#maptooltip").show();
  	$("#maptooltip").load("/tools/markerinfo.php", o);	
}

// ------------------------------------

/**
 *
 */
function lc_hideMarkerInfo()
{
	$("#maptooltip").html("");
	$("#maptooltip").hide();
}

// ------------------------------------
// ------------------------------------

/**
 *	показать место, по координатамы
 */
function lc_showPlace(lat, lng, yaw, pitch, zoom)
{
	var latlng = new GLatLng(lat, lng);
	var pov = {yaw: yaw, pitch: pitch, zoom: zoom };
	
	client.getNearestPanorama(latlng, function(response)
	{
	 	if (response.code != 200) 
		{
			alert(locStr.nopano);
			man.setLatLng(lastMarkerLocation);
		} 
		else 
		{
			map.panTo(response.location.latlng);
			lc_showPanorama(response.location.latlng, pov);
			lastMarkerLocation = response.location.latlng;
			man.setLatLng(response.location.latlng);
		}
   });	
}

// ------------------------------------

/**
 *	!!!fix: mozilla требует 2х, chrome 1
 */
function lc_showPanorama(latlng, pov)
{
	//	event: 
	///panorama.remove();
	
	//panorama.setContainer($gid("pano"));
	panorama.setLocationAndPOV(latlng, pov);
}

// ------------------------------------

function lc_getMan()
{
	return man;
}

// ------------------------------------

function lc_getPano()
{
	return panorama;
}

// ------------------------------------
// ------------------------------------
// ------------------------------------
// ------------------------------------

/**
 *
 */
function lc_npChangeCat(catId)
{
	var f = {};
	f.cid = catId;
	
	var data = ajax_postSContent("/tools/tagsforcat.php", 1, f);	
	
	$("#npTagRowCnt").html(data);
	$("#npTagRow").show();
}


// ------------------------------------
// ------------------------------------
//	Tags ...
// ------------------------------------
// ------------------------------------

/**
 *	добавляем тег
 */
function lc_npAddTag(tCatID, selPref)
{
	var sel = $gid('npAddTagSel' + tCatID);
	
	var val = sel.value;
	var text = sel.options[sel.selectedIndex].text;
	
	if(val)
	{
		sel.options[sel.selectedIndex] = null;
		delete sel.options[sel.selectedIndex];
		
		if(sel.options.length == 1)
		{
			sel.disabled = true;
		}
		
		seltags[val] = {tgid: tCatID, text: text};
		var html = '<span id="npTag'+val+'">'+text+'&#xA0;[<a href="#" onclick="lc_npRemoveTag('+val+', \''+selPref+'\'); return false;">x</a>]&#xA0;</span>';
		$("#npTagBox"+tCatID).append(html);
	}	
}

// ------------------------------------

/**
 *	удаляем тег
 */
function lc_npRemoveTag(tid, selPref)
{
	if(!seltags[tid]) { return; }
	var o = seltags[tid];

	var sel = $gid('npAddTagSel' + o.tgid);
	sel.disabled = false;
	sel.options[sel.options.length] = new Option(o.text, tid);
	
	$("#npTag"+tid).remove();
	seltags[tid] = null;
	delete seltags[tid];
}

// ------------------------------------

/**
 *	текстовый тег
 */
function lc_npAddTagText(tgid, val)
{
	tagsText[tgid] = val;
}

// ------------------------------------

/**
 *	одиночный тег
 */
function lc_npAddTagOnce(tgid, val)
{
	tagsOnce[tgid] = val;
}

// ------------------------------------
// ------------------------------------
// ------------------------------------
// ------------------------------------

function lc_setNpPlaceRating(rat)
{
	npRating = rat;
}


// ------------------------------------
// ------------------------------------
// ------------------------------------
// ------------------------------------


function lc_showPlaceMarker(lat, lng, pan)
{
	var latlng = new GLatLng(lat, lng);
	
	if(!placeMarker)
	{
		placeMarker = new GMarker(latlng);
		map.addOverlay(placeMarker);
	}
	else
	{
		placeMarker.setLatLng(latlng);
		placeMarker.show();
	}
	
	curPos.isNoLoadMarkers = 1;
	
	if(pan) { map.panTo(latlng); }
}

// ------------------------------------

function lc_hidePlaceMarker()
{
	placeMarker.hide();
	map.panTo(man.getLatLng());
	curPos.isNoLoadMarkers = 0;
}

// ------------------------------------
// ------------------------------------

function lc_showBirdBox()
{
	var x = tb_getPageSize();
	var latlng = man.getLatLng();
	var add = 'lang='+'ru'+'&lat=' + latlng.lat() + '&lng=' + latlng.lng() +'&city_id='+cityID;
	lc_showModal('/tools/birdseye.php', {w: (x[0] - 90), h: (x[1] - 60), add: add});
}

// ------------------------------------
// ------------------------------------
//	Translate
// ------------------------------------
// ------------------------------------

/**
 *	получаем, переводим, сохраняем, показываем
 */
function lc_translateBlock(opts, oID, userLang, placeLang, objUpd)
{
	var f = {};
	f.t = opts.get;
	f.o_id = oID;
	
	/** get text **/
	$.post("/tools/text.php", f, function(text) 
	{
		if(!text) { return; }

		/** translate text **/
		google.language.translate(text, placeLang, userLang, function(result) 
		{
			if (result.translation) 
		    {
		    	var f = {};
				f.t = opts.put;
				f.o_id = oID;
				f.text = result.translation;
				f.lang_id = userLang;
			
				/** save translate **/
				$.post("/tools/text.php", f, function(res)
				{
					if(res != 1) { return; }					
					
					var f = {};
					f.t = opts.get;
					f.lang_id = userLang;
					f.o_id = oID;
					
					/** get translated html **/
					$.post('/tools/getblock.php', f, function(resHtml)
					{
						objUpd.html(resHtml);	
					});	
				});
		    }
		});
	});
}

// ------------------------------------
// ------------------------------------

var centerWidth = [575, 675];

/**
 *
 */
function lc_maxMap()
{
	if(!params.isMapMax || params.isMapMax == 0)
	{		
		params.map_height = $("#map_canvas").height();
		params.center_height = $("#topplacebox_center").height();
		var addSize = 200;

		$("#topplacebox_center").height(params.center_height + addSize);
		$("#maxmapimg").attr("src", "/images/sv_box_bot2_btn2.gif");
		
		params.isMapMax = 1;
		$("#map_canvas").height(params.map_height + addSize);
		map.checkResize();
		loadMarkers();		
	}
	else
	{
		$("#map_canvas").height(params.map_height);
		$("#topplacebox_center").height(params.center_height);
		$("#maxmapimg").attr("src", "/images/sv_box_bot2_btn.gif");
		map.checkResize();
		params.isMapMax = 0;
	}
}

// ------------------------------------
// ------------------------------------

function lc_resizeMapBox(width, height, mode, add)
{
	/** full **/
	if(mode == 0)
	{
		$("#topplacebox_place").css("width", width);
		$("#topplacebox_center").css("height", $("#topplacebox_center").height() + add);
	}	
	
	$("#pano").css("height", height);
	$("#pano").css("width", width - 43);
	$("#birdsbox").css("height", height);
	$("#birdsbox").css("width", width - 43);
	$("#map_canvas").css("width", width - 43);
	$("#menubox").css("width", width - 55);
	$("#maxmapbox").css("width", width - 85);
	
	
	/** small **/
	if(mode == 2)
	{
		$("#topplacebox_center").css("height", $("#topplacebox_center").height() - add);
		$("#topplacebox_place").css("width", width);
	}	
}


// ------------------------------------
// ------------------------------------

/**
 *	show full screen ...
 */
function lc_fullScreen()
{
	if(!params.isFullScreen || params.isFullScreen == 0)
	{
		var x = tb_getPageSize();
		var width = x[0] - 60;
		var height = 450;
		
		$("#winPlaceInfo").hide();
		
		params.mapbox_width = $("#topplacebox_place").width();
		params.pano_height = $("#pano").height();
		params.add_height = height - params.pano_height;

		lc_resizeMapBox(width, height, 0, params.add_height);
		
		map.checkResize();
		
		if(params.is_birds_eye == 1) 
		{ 
			var frm = getFrameByID("birdframe");
			frm.lc_resizeMap(); 
		}
		else
		{
			panorama.checkResize();
		}
		
		params.isFullScreen = 1;
		map.panTo(man.getLatLng());
		
		$("#link_fullscreen").html(locStr.fullscrback);
	}
	else
	{
		lc_resizeMapBox(params.mapbox_width, params.pano_height, 2, params.add_height);

		map.checkResize();
		
		if(params.is_birds_eye == 1) 
		{  
			var frm = getFrameByID("birdframe");
			frm.lc_resizeMap(); 
		}
		else
		{
			panorama.checkResize();
		}
		
		$("#winPlaceInfo").show();
		
		params.isFullScreen = 0;
		map.panTo(man.getLatLng());
		
		$("#link_fullscreen").html(locStr.fullscr);
	}
}

// ------------------------------------
// ------------------------------------

function lc_showBirdBox2()
{
	if(!params.is_birds_eye || params.is_birds_eye == 0)
	{
		var isFirst = 0;
		if(!$("#birdsbox").html())
		{
			isFirst = 1;
			params.is_birds_exists = 1;
			var latlng = man.getLatLng();
			var url = 'lat='+latlng.lat()+'&lng='+latlng.lng()+'&lang='+langID+'&city_id='+cityID;
			
			//var html = '<iframe id="birdframe" name="birdframe" frameborder="0" width="100%" scrolling="No" height="100%" src="/tools/birdseye.php?t=showsat&amp;'+url+'"></iframe>';
			
			var html = '<iframe id="birdframe" name="birdframe" frameborder="0" width="100%" scrolling="No" height="100%" src="/tools/birdseye.php?t=showbird&amp;'+url+'"></iframe>';
			
			$("#birdsbox").html(html);
		}
		else
		{

			// координаты установить
		}
					
		panorama.hide();
		$("#pano").hide();
		$("#birdsbox").show();		
		params.is_birds_eye = 1;	
		$("#link_birds").html(locStr.show_sv);
		
		if(!isFirst) 
		{  
			var frm = getFrameByID("birdframe");
			frm.lc_resizeMap(); 
			
			lcev_birdsEyeChangeLoc(man.getLatLng());
		}
	}
	else
	{
		params.is_birds_eye = 0;
		$("#birdsbox").hide();
		$("#pano").show();
		panorama.show();
		$("#link_birds").html(locStr.show_birds);
		
		panorama.checkResize();
	}
}

// ------------------------------------

function lcev_birdsEyeChangeLoc(latlng)
{
	var frm = getFrameByID("birdframe");
	frm.lc_changeLocation(latlng.lat(), latlng.lng()); 
}

// ------------------------------------
// ------------------------------------

function lc_linkToPlace(mode)
{
	var p = man.getLatLng();
	var pov = panorama.getPOV();
	var add = 'lang='+langID+'&lat='+p.lat()+'&lng='+p.lng()+'&place_id='+curPos.placeID;
		add += '&yaw='+pov.yaw+'&pitch='+pov.pitch+'&zoom='+pov.zoom;
		add += '&c_id='+countryID+'&city_id='+cityID+'&m='+mode;
		
	lc_showModal('/tools/linktoplace.php', {w: 500, h:300, add:add});
}


// ------------------------------------
// ------------------------------------

var filterCats = {
	
	type: 0,
	catall: 1,
	
	cats: new Array(),
	tagscats: new Array(),
	tags: new Array(),
	
	reload : function()
	{
		this.type = $("#filterType").val();
		this.catall = $gid("filterCatall").checked ? 1 : 0;
		
		this.cats = new Array();
		var cats = $("INPUT.filter-cat:checked");
		
		for(var i = 0; i < cats.length; i++)
		{
			this.cats.push(cats[i].value);
		}
		
		this.tagscats = new Array();
		var tagscats = $("INPUT.filter-tagcat");
		
		for(var i = 0; i < tagscats.length; i++)
		{
			if(!tagscats[i].disabled && !tagscats[i].checked)
			{
				this.tagscats.push(tagscats[i].value);
			}	
		}		
		
		this.tags = new Array();
		var tags = $("INPUT.filter-tag:checked");
		for(var i = 0; i < tags.length; i++)
		{
			this.tags.push(tags[i].value);
		}		
	}
};

// ------------------------------------

function lc_filterRestore()
{
	$("#filterType option[@value="+filterCats.type+"]").attr("selected", "selected");
	
	if(filterCats.catall == 0) 
	{ 
		$("#filterCatall").attr("checked", "")
		lc_filterEnableCats(0); 
	}
	else { return; }
	
	for(var i = 0; i < filterCats.cats.length; i++)
	{
		var val = filterCats.cats[i];
		$("#filter-cat-"+val).attr("checked", "checked");	
		lc_filterEnableCat(1, val);
	}
	
	for(var i = 0; i < filterCats.tagscats.length; i++)
	{	
		var val = filterCats.tagscats[i];
		$("#filter-tagcat-"+val).attr("checked", "");	
		lc_filterEnableTags(0, 'filter-tag-'+val);
	}	
	
	for(var i = 0; i < filterCats.tags.length; i++)
	{
		var val = filterCats.tags[i];
		$("#filter-tag-"+val).attr("checked", "checked");	
	}	
}

// ------------------------------------

function lc_filterReload()
{
	filterCats.reload();
}

// ------------------------------------

function lc_filterEnableCats(checked)
{
	if(checked)
	{
		$("div.filterTags input[type=checkbox]").attr("checked", "");
		$("div.filterTags input[type=checkbox]").attr("disabled", "disabled");
	}
	else
	{
		$("input.filter-cat").attr("disabled", "");
	}
}

// ------------------------------------

/** устанавливаем для тегов **/
function lc_filterEnableCat(checked, catID)
{
	if(checked)
	{
		/** если выбираем категорию, включаем "все теги" **/
		$("input.filter-cat-"+catID).attr("disabled", "");
		$("input.filter-cat-"+catID).attr("checked", "checked");
	}
	else
	{
		$("div.filterBox-"+catID+" input[type=checkbox]").attr("checked", "");
		$("div.filterBox-"+catID+" input[type=checkbox]").attr("disabled", "disabled");
	}
}

// ------------------------------------

/** устанавливаем для тегов **/
function lc_filterEnableTags(checked, className)
{
	if(checked)
	{
		$("input."+className).attr("disabled", "disabled");
		$("input."+className).attr("checked", "");
	}
	else
	{
		$("input."+className).attr("disabled", "");
	}	
}

// ------------------------------------

function lc_filterAccept()
{
	lc_filterReload();
	lc_closeModal();	
}


// ------------------------------------
// ------------------------------------
// ------------------------------------
// ------------------------------------