var map;

jQuery(document).ready(function(){
	map = new YMaps.Map(YMaps.jQuery("#YMapsID")[0]);
	
	map.addControl(new YMaps.Zoom());
	
	map.setCenter(new YMaps.GeoPoint(103.682149,60.084965), 2);
	
	for (var i = 0; i < stations.length; i++) {
		map.addOverlay(createOverlay(stations[i]));
	}
});

function createOverlay (station)  {
	var link = document.createElement('a');
	var newOverlay = new SimpleOverlay(station.id, station.point, station.name, link);
	
	link.id = 'firm_java_link';
	link.href = 'javascript:void(0)';
	link.className = 'java';
	link.innerHTML = station.name;
	link.onclick = function () {
		if (link.className == "active") return;
		map.setCenter(station.point, 2);
		newOverlay.openBalloon();
	};
	
	document.getElementById('links').appendChild(link);
	return newOverlay;
}

function SimpleOverlay (id, geoPoint, name, link) {
	var map, _this = this, offset = new YMaps.Point(-7, -8);
	
	this.onAddToMap = function (pMap, parentContainer) {
		map = pMap;
		parentContainer.appendChild(getElement());
		this.onMapUpdate();
	};
	
	this.onRemoveFromMap = function () {
		if (getElement().parentNode) {
			getElement().parentNode.removeChild(getElement());
		}
	};
	
	this.onMapUpdate = function () {
		var position = map.converter.coordinatesToMapPixels(geoPoint).moveBy(offset);
		getElement().style.left = position.x + 'px';
		getElement().style.top = position.y + 'px';
	};
	
	this.openBalloon = function () {
		link.className = "active";
		getElement().style.display = "none";
		
		jQuery.ajax({
			url: core_url,
			type: "POST",
			data: "op=load_region_info&module_name=index&value="+id,
			dataType : "json",
			beforeSend: function() {
				jQuery('#load_process').html('<span style="color: #606060; font-size: 11px"><img src="/i/loading.gif" align="left">&nbsp;Загрузка данных...</span>');
				return php.beforeSend();
			},
			success: function(data, textStatus) {
				php.success(data, textStatus);
				map.openBalloon(geoPoint, '<div class="ballonishe">'+(jQuery('#bufer_data').html())+'</div>', {maxHeight: 150, onClose: function () {
					link.className = getElement().style.display = "";
				}});
			},
			error: function (xmlEr, typeEr, except) {
				jQuery('#load_process').html('<span style="color: red; font-size: 11px">Ошибка при загрузке</span>');
				return php.error(xmlEr, typeEr, except);                  
			},
			complete: function (XMLHttpRequest, textStatus) {
				jQuery('#load_process').html('');
				return php.complete(XMLHttpRequest, textStatus);
			}
		});
	};
	
	function getElement () {
		var element = document.createElement('div');
		element.className = 'overlay';
		element.onclick = function () {
			_this.openBalloon();
		}
		return (getElement = function () {return element})();
	}
}
