/**
 * Created with JetBrains PhpStorm.
 * User: sidchik
 * Date: 04.07.13
 * Time: 2:08
 * To change this template use File | Settings | File Templates.
 */
ymaps.ready(init);

var myMap;
var map_ready = false;
var doInit = false;

function init(){
    doInit=true;
}

function vdump(obj) {
    var out = "";
    if(obj && typeof(obj) == "object"){
        for (var i in obj) {
            out += i + ": " + obj[i] + "\n";
        }
    } else {
        out = obj;
    }
    alert(out);
}


$("document").ready(function(){

    function checkMap(){
        if (!doInit){
            setTimeout(checkMap, 30);
            return false;
        }
        var active_city = $('#active_city');
        ymaps.geocode(active_city.attr('data-region')+' '+active_city.text(), { results: 1 }).then(function (res) {
            var firstGeoObject = res.geoObjects.get(0);

            if (myMap===undefined){
                myMap = new ymaps.Map ("map-view", {
                    center: firstGeoObject.geometry.getCoordinates(),
                    zoom: 11,
                    behaviors: ['default', 'scrollZoom']
                });
                myMap.controls
                    // Кнопка изменения масштаба.
                    .add('zoomControl', { left: 5, top: 5 })
                map_ready = true;
            }else{
                myMap.setCenter(firstGeoObject.geometry.getCoordinates());
                myMap.setZoom(11);
            }

        });
    }
    checkMap();


    if ($(".offices").length){

        $("#map-view").bind('set_active', function(){
           myMap.container.fitToViewport();
        });

        function change_filter(){
            var url = window.location +'';
            data = {
                'id_city': $(".city_selector .city_select").select2('val')
            };

            $(".filters input[type='checkbox']:checked").each(function(){
                data[$(this).attr('id')] = 1;
            });
            $.ajax({
                data: data,
                url: url,
                success: function(data){
                    $("#list_items").html(data);
                    redraw_map();
                }
            });
        }

        var balloons = [];
        function redraw_map(){
            if (!map_ready){
                setTimeout(redraw_map, 20);
                return false;
            }
            if (myMap.geoObjects===undefined){
                setTimeout(redraw_map, 20);
                return false;
            }
            var x = 0;
            var url = window.location +'';
            balloons = [];
            myMap.geoObjects.each(function (geoObject) {myMap.geoObjects.remove(geoObject);});
            $("#list_items .item").each(function(){
                var balloonWidth = (url.indexOf('atm')== -1 )?420:240;

                x++;
                var address = $(this).find('.address_cell').text();
                var content = '<p>'+address+'</p>';
                content +='<p>'+ $(this).find('.time_cell').html() +'</p>';
                if (url.indexOf('atm')== -1 ){
                    var phones = [];
                    $(this).find('.phone_cell p').each(function(){
                        phones.push($(this).html().replace('<br>', " "));
                    });
                    phones = phones.join(', ');
                    if (phones){
                        content +='<p>Телефоны: '+ phones +'</p>';
                    }
                }else if($(this).find('.phone_cell').text()){
                    content +='<p>'+ $(this).find('.phone_cell').text() +'</p>';
                }
                var metka = new ymaps.Placemark([$(this).attr('data-lat'), $(this).attr('data-lon')], {
                    // Свойства.
                    // Содержимое иконки, балуна и хинта.
                    iconContent: x,
                    balloonContent: content,
                    hintContent: address

                }, {
                    // Опции.
                    // Стандартная фиолетовая иконка.
                    preset: 'twirl#blueIcon',
                    balloonMinWidth: balloonWidth
                });
                myMap.geoObjects.add(metka);
                balloons.push(metka);

            })

        }

        $(".city_select").on('change', function(){
            $("#active_city").html($(this).select2('data').text);
            $("#active_city").attr('data-region', $($(this).select2('data').element).attr('region'));
            checkMap();
            change_filter();
            window.location = '/city/'+$(this).select2('data').text;
        });
        $(".filters input[type='checkbox']").change(function(){
            change_filter();
        });

        $("#list-view").on('click', '.go_map', function(){
            var par = $(this).parent().parent();
            var lat = par.attr('data-lat');
            var lon = par.attr('data-lon');
            $("[data-tab]").trigger('click');
            myMap.setCenter([lat, lon], 16);
            var ind = $(this).index("#list-view .go_map");
            balloons[ind].balloon.open();
        });

        redraw_map();
    }

});
