WR.util.namespace('WR.bogushtime');

WR.bogushtime.contacts = {
    popup: null,

    init: function() {
        this.initPopup();
    },

    initPopup: function() {
        this.popup = $('#company-contacts').appendTo('body');
        //WR.ui.overlay.container = $('.bt-container')[0]; // already set in "common.js"

        // Bind popup to window scroll
        $(window).scroll($.proxy(this, 'scrollPopupIntoView'));

        // Enable popup hide
        WR.ui.overlay.bind('hide', $.proxy(this, 'hidePopup'));
        this.popup.find('.bt-close-btn').click(function(e) {
            e.preventDefault();
            WR.ui.overlay.hide();
        });

        // Enable popup show
        var self = this;
        $('#on-map, #more-contacts').click(function(e) {
            e.preventDefault();

            WR.ui.overlay.show();
            self.showPopup();
            self.scrollPopupIntoView();

            if (!self.mapInited)
                self.initMap();
        });
    },

    showPopup: function() {
        this.popup.show();
    },

    hidePopup: function() {
        this.popup.hide();
    },

    scrollPopupIntoView: function() {
        if (this.popup.css('display') == 'block')
            this.popup.stop(true).animate({ top: $(window).scrollTop() + 80 });
    },

    mapInited: false,
    map: null,
    addresses: null, // this will be just a jQuery collection of LI elements. But each LI will have own .data("info")
    currentAddress: null,

    initMap: function() {
        var self = this,
            getMapImage = $.noop;

        this.initAddresses();

        //==================== Init Yandex Map ===================
        if (window.YMaps) {
            YMaps.load(function(){
                var map = self.map = new YMaps.Map($('#bt-active-map')[0]);
                map.addControl(new YMaps.TypeControl());
                map.addControl(new YMaps.ToolBar());
                map.addControl(new YMaps.Zoom());
                self.showAddress();
            });
            self.getMapImage = self.getDynamicMapImage;
        } else { // Maps may be blocked somehow
            self.getMapImage = self.getStaticMapImage;
        }

        this.initPrintMap();

        this.mapInited = true;
    },

    // Fill in offices info
    initAddresses: function() {
        var self = this;

        this.addresses = $(this.popup).find('ul.bt-offices-list li')
            .each(function() {
                var geo = $(this).attr('title');
                $(this).removeAttr('title');

                var latitude = geo.match(/Широта:\s+([^,]+),?/)[1];
                var longitude = geo.match(/Долгота:\s+([^,]+),?/)[1];

                var nameEl = $('h5', this),
                    name = nameEl.attr('title');
                nameEl.removeAttr('title');

                var description = $('p', this).text();

                var info = {
                    name: name,
                    description: description,
                    x: parseFloat(longitude),
                    y: parseFloat(latitude)
                };

                $(this).data('info', info);
            })
            .click(function() {
                var li = $(this);
                self.addresses.removeClass('bt-selected-item');
                li.addClass('bt-selected-item');
                self.showAddress(li);
            });

        this.addresses.find('a').click(function(e) {
            e.preventDefault();
        });
    },

    showAddress: function(li) {
		if (!li)
            li = this.addresses.eq(0);

        this.currentAddress = li;

		var bt = li.data("info") || { name: 'Где-то', description: 'в Атлантическом океане...' },
            c = new YMaps.GeoPoint(bt.x, bt.y);

		this.map.setCenter(c, 16);
		this.map.closeBalloon();
		this.map.openBalloon(c, '<strong>' + bt.name + '</strong><div>' + bt.description + '</div>', { maxWidth: 160, hasCloseButton: false });
	},

    getMapImage: $.noop,

    getStaticMapImage: function() {
        return $('#bt-active-map img').attr('src');
    },

    getDynamicMapImage: function() {
        var map = this.map,
            bt = $(this.currentAddress).data("info");

        return 'http://static-maps.yandex.ru/1.x/?ll=' + map.getCenter() +
            '&size=650,450&z=' + map.getZoom() +
            '&l=' + map.getType().getLayers().join(',') +
            '&pt=' + bt.x + ',' + bt.y + ',pmrdm' +
            '&key=' + WR.bogushtime.YMapsKey /* <- set inside 'template.html' */
    },
    // Init printing functionality
    initPrintMap: function() {
        var self = this;

        $('#print-map').click(function(e){
            e.preventDefault();

            var win = open(null, 'printme', 'width=' + 800 + ',height=' + 600),
                addr = self.map.getBalloon().getContent();

            win.document.open();
            win.document.write(
                '<div style="text-align:center;padding-top:20px;">' +
                    '<img alt="Карта проезда к оффису BogushTime" src="' + self.getMapImage() + '" />' +
                    '<div style="padding: 10px; font-size: 14px;">' + addr + '</div>' +
                '</div>'
            );
            win.document.close();
            win.focus();
            $(win).ready(function(){
                win.print();
                win.blur();
                win.close();
            });

            delete win;
        });
    }
};

$(function() {
    WR.bogushtime.contacts.init();
});

