$(function() {
    // CORS support in IE8+
    if ('XDomainRequest' in window && window.XDomainRequest !== null) {
        // override default jQuery transport
        jQuery.ajaxSettings.xhr = function() {
            try {
                return new XDomainRequest();
            }
            catch (e) {
            }
        };
        // also, override the support check
        jQuery.support.cors = true;
    }

    var config = {
        map: 'cube-map',
        host: 'cube.navalny.ru'
    };
    ymaps.ready(function() {
        var map = new ymaps.Map(
                config.map,
                {
                    center: [55.76, 37.64],
                    zoom: 12
                },
        {
            autoFitToViewport: 'always'
        }
        );

        map.controls.add('zoomControl', {left: '20px', top: '20px'});
        map.behaviors.disable('dblClickZoom');

        $.get('//' + config.host + '/pickets', function(data) {
            var today = new Date;
            $(data).each(function(idx, picket) {
                if ('coordinates' in picket) {
                    var preset = 'twirl#blueIcon';

                    var placemark = new ymaps.Placemark(
                        [picket.coordinates.latitude, picket.coordinates.longitude],
                        {
                            iconContent: picket.participant_count ? '<span>' + picket.participant_count + '</span>' : '',
                            hintContent: picket.address
                        },
                        {
                            preset: preset,
                            balloonAutoPan: true
                        }
                    );
                    placemark.events.add('click', function() {
                        var date = today;
                        document.location = '//' + config.host + '/#cubes/' + date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getFullYear() + '/' + picket.id;
                    })

                    map.geoObjects.add(placemark);
                }
            });
            var bounds = map.geoObjects.getBounds();
            if (bounds) {
                map.setBounds(bounds, {
                    checkZoomRange: true,
                    zoomMargin: [20]
                });
            }
        }, 'json');
    });
})
