var PlaceMapView = Backbone.View.extend({
    tagName: "div",
    id: "google_map",
    
    lat: 54.924676,    // центр карты
    lng: 37.413082,    // цента карты
    zoom: 12,          // увеличение карты
    map: null,         // карта
    user_marker: null, // метка пользователя
    infowindow: new google.maps.InfoWindow(),
    
    initialize: function(){
        this.settings = settings;
        
        this.init_map(); // инициализируем карту
        // this.try_to_show_user_current_position(); // показываем пользователя на карте
        this.render_markers(); // показываем маркеры мест на карте
        
        return this;
    },
    
    init_map: function(){
        // инициализация карты google
        var latlng = new google.maps.LatLng(this.lat, this.lng);
        var myOptions = {
            zoom: this.zoom,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        
        this.map = new google.maps.Map(document.getElementById(this.id), myOptions);
    },
    
    try_to_show_user_current_position: function(){
        // пробует показать текущее положение пользователя
        // если не возможно определить, то возвращает false
        var THIS = this;
        
        // определяем иконку
        var user_position_icon = null;
        if (THIS.settings.user_position_icon) {
            user_position_icon = new google.maps.MarkerImage(THIS.settings.user_position_icon);
        }
        
        if (navigator.geolocation){
            var info_window = new google.maps.InfoWindow();
            
            navigator.geolocation.getCurrentPosition(
                function(position){
                    var user_point = new google.maps.LatLng(position.coords.latitude, 
                                                            position.coords.longitude);
                    
                    THIS.user_marker = new google.maps.Marker({
                        position: user_point,
                        map: THIS.map,
                        icon: user_position_icon,
                        title: "Вы здесь"
                    });
                    
                    // добавляем окошко
                    google.maps.event.addListener(THIS.user_marker, 'click', function() {
                        var html = "Это вы =)";

                        THIS.infowindow.setContent(html);
                        THIS.infowindow.open(THIS.map, this);
                    });
                },
                null,
                {maximumAge:600000}
            );
        }else{
            // если браузер не поддерживает геолокацию, вернем false
            return false;
        }
    },
    
    render_markers: function(){
        // вывод маркеров на карту
        var THIS = this;
        
        var icon = new google.maps.MarkerImage(THIS.settings.place_map_icon);
        
        // итерируем по коллекциям
        this.collection.each(function(place){
            var position = new google.maps.LatLng(place.get("lat"), place.get("lng"));
            
            // создаем маркер
            var marker = new google.maps.Marker({
                map: THIS.map,
                position: position,
                icon: icon,
                title: place.get("full_name")
                // zIndex: Number(place.get("lat")) * (-1)
            });
            
            // добавляем всплывающее окно при клике
            // google.maps.event.addListener(marker, 'click', function() {
            //     var data = {
            //         icon_url:       place.get("icon_url"),
            //         place_address:  place.get("address"),
            //         place_phones:   place.get("phones"),
            //         place_url:      place.get("absolute_url"),
            //         place_name:     place.get("full_name")
            //     }
            //     // рендеринг шаблона
            //     html = ich.place_infowindow_template(data)[0];
            //     
            //     THIS.infowindow.setContent(html);
            //     THIS.infowindow.open(THIS.map, this);
            // });
            
            var data = {
                icon_url:       place.get("icon_url"),
                place_address:  place.get("address"),
                place_phones:   place.get("phones"),
                place_url:      place.get("absolute_url"),
                place_name:     place.get("full_name")
            }
            // рендеринг шаблона
            html_el = ich.place_infowindow_template(data)[0];
            a = window.$("head").append(html_el);

    		var myOptions = {
    			 content: html_el,
    			 disableAutoPan: false,
    			 maxWidth: 0,
                 pixelOffset: new google.maps.Size(-145, -180),
    			 zIndex: null,
                 // boxStyle: { 
                 //  background: "url('tipbox.gif') no-repeat",
                 //  width: "280px"
                 // },
                 closeBoxMargin: "12px 12px",
    			 closeBoxURL: "/static/img/close.gif/",
    			 infoBoxClearance: new google.maps.Size(10, 30),
    			 isHidden: false,
    			 pane: "floatPane",
    			 enableEventPropagation: false,
    		};

    		google.maps.event.addListener(marker, "click", function (e) {
                $(".infoBox").hide();

                ib.open(THIS.map, this);
//                console.log(a.width());
                // console.log($(html_el).height());
                // that = this;
                // ib.fadeTo("slow", 0.8);
                // console.log(ib.fadeOut());
                // ib.css("opacity", 0.8);
    		});

    		var ib = new InfoBox(myOptions);
            
            place.set({"marker": marker});
        });
        
        var markerCluster = new MarkerClusterer(this.map, this.collection.pluck("marker"), {
            gridSize: 30,
            maxZoom: 18,
            styles: [{
                url: THIS.settings.place_map_group_icon, // url иконки
                height: 49,
                width: 52,
                anchor: [12, 0], // расположение текста (y, x)
                textColor: "#FFFFFF",
                textSize: 12
            }]
            // minimumClusterSize: 3
        });
    }
});

