var map;
var bounds = new YMaps.GeoCollectionBounds(); 
var cnt=0;

(function ($){
    $.fn.renderMap = function (center, zoom, hie_id, typeid, cnt_start, depth) {
        return this.each(function () {
			typeid = typeid || 770;
			cnt = cnt_start || 0;
			cnt = cnt_start || 0;
			depth = depth || 1;

			var url_par=''; 
			var url = new String(window.location);
			if (url.indexOf("fields_filter") != -1) {
				url = url.split("?");
				url_par = url[1];
			}

            var $this = this;
			if(typeof map == "undefined") {
	            map = new YMaps.Map(YMaps.jQuery($this)[0]);
				map.setCenter(center, zoom);
				// map.addControl(new YMaps.TypeControl());
				map.addControl(new YMaps.Zoom());
				// map.addControl(new YMaps.MiniMap());
				map.addControl(new YMaps.SearchControl());
				//$.get('/udata://catalog/getAgencies/'+hie_id, {},
			}
			$.get('/udata/catalog/getAgencies/'+hie_id+'/'+typeid+'/?depth='+depth+'&'+url_par, {},  // 1 - если надо автоматом находить по адресу координаты и сохранять их в объекте
				function (response) {
					//$("#log").append(' ajax: ');
					render_agencies(map, response.getElementsByTagName('item'));
				}
			);
        })
    }
    
    
    var render_agencies = function (map, agencies) {
        var gCollection = new YMaps.GeoObjectCollection();       
        $.each(agencies, function (index, agency) {
			//$("#log").append(' latitude: '+$(agency).attr('latitude') + ' longitude: '+$(agency).attr('longitude')+'              ');
            var geo_point = new YMaps.GeoPoint(
                    parseFloat($(agency).attr('latitude')), parseFloat($(agency).attr('longitude')));
           var s = new YMaps.Style();
			s.iconStyle = new YMaps.IconStyle();
			s.iconStyle.offset = new YMaps.Point(-10, -10);
			s.iconStyle.size = new YMaps.Point(24, 30);

			// для автомасштабирования карты
			bounds.add(geo_point);
			 
			 // Создание шаблона для содержимого балуна
            var s = new YMaps.Style();
            s.balloonContentStyle = new YMaps.BalloonContentStyle(new YMaps.Template(
                "<b>$[name|объект]</b>\
                <div>$[description]</div>\
                <div>Читать <a href=\"$[metaDataProperty.moreLink]\" class='map-more-link'>подробнее</a></div></div>"
            ));
					
// Создание меток и добавление их на карту// Наследуемся от базового стиля
            var s = new YMaps.Style(s);
            s.iconStyle = new YMaps.IconStyle();
			s.iconStyle.size = new YMaps.Point(24, 30);
			var typeid = parseInt($(agency).attr('type_id'));
			if (typeid == 752) {
				s.iconStyle.href = "http://regrent.ru/images/regrent/_rrr.png";
				cnt++;
				var options = {
					style: s
				};	
			}
			else {
				s.iconStyle.href = "http://regrent.ru/images/regrent/rrr.png";
				var options = {
					zIndex: 130,
					style: s
				};	
			}
            //var placemark = new YMaps.Placemark(geo_point, {style: s});
			var placemark = new YMaps.Placemark(geo_point, options);
            placemark.name = $(agency).text();
            placemark.description = $(agency).attr('address');
			if (typeid == 752) {
				if ($(agency).attr('plowad'))
					placemark.description = placemark.description + '<br />Площадь: ' + $(agency).attr('plowad') + ' м<sup>2</sup>';
				if ($(agency).attr('cena')) {
					s0 = $(agency).attr('cena').toString();
					s0 = s0.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
					placemark.description = placemark.description + '<br />Цена: ' + s0 + ' руб.';
				}
			}
            placemark.metaDataProperty.moreLink = $(agency).attr('more_link');
            gCollection.add(placemark);
        });
		if (cnt>0) {
			map.setBounds(bounds);
		}
        map.addOverlay(gCollection);
    }
})(jQuery) 

