WR.obriens = {
    /**
     * Initialize all common page things
     */
    init: function() {
        this.initScheduleScroll();
        this.makeScheduleEllipsis();
        this.initMap();
        this.initPubMap();
        this.fixLanguageToggler();
    },

    initScheduleScroll: function() {
        var c = $('#header-schedule'),
                prev = $('a.prev-button', c),
                next = $('a.next-button', c),
                ul = $('ul', c),
                lis = $('li', c).size();

        if (lis > 3)
            next.show();

        $(next).click(function(e) {
            e.preventDefault();
            $(this).blur();

            lis -= 3;
            ul.animate({ marginTop: '-=190' });

            if (prev.is(':hidden'))
                prev.show();

            if (lis <= 3)
                next.hide();
        });

        $(prev).click(function(e) {
            e.preventDefault();
            $(this).blur();

            lis += 3;
            ul.animate({ marginTop: '+=190' });

            if (next.is(':hidden'))
                next.show();

            if (lis >= $('li', c).size())
                prev.hide();
        });
    },

    makeScheduleEllipsis: function() {
        $('#header-schedule ul li span, #header-schedule ul li a').each(function() {
            if ($(this).width() > $(this).parent().width()) {
                var text = $(this).text(), len = text.length;

                do {
                    $(this).text(text.substr(0, len--));
                } while ($(this).width() > $(this).parent().width())

                $(this).html(text.substr(0, len--) + '&hellip;');
            }
        });
    },

    /**
	 * Initialize map block
	 */
    initMap: function() {
		//================ Init show/hide buttons ================
		$('#show-interactive-map').click(function(e) {
			$('.pub-map-first-floor, .pub-map-second-floor', '.map-and-features').hide();
            $('#interactive-map').show().css({ visibility: 'visible' });
            $('#show-interactive-map').hide();
            $('#hide-interactive-map').show();
            e.preventDefault();

			if (placemark) {
                // Yandex.Maps - open balloon
                if (typeof placemark.openBalloon == "function")
				    placemark.openBalloon();
                // Google.Maps - open balloon
                if (typeof placemark.openInfoWindow == "function")
                    placemark.openInfoWindow(map.obriensTextEl);
            }
		});

        $('#close-map, #hide-interactive-map').click(function(e) {
			$('#interactive-map').css({ visibility: 'hidden' }).hide();
            $('#hide-interactive-map').hide();
            $('#show-interactive-map').show();
            $('.map-and-features .pub-map-first-floor').fadeIn();
            e.preventDefault();
		});

		//==================== Map info and variables ===================
		var map, placemark, getMapImage = $.noop,
                bt = { x: 30.521223, y: 50.453762 },
				addr = WR.obriens.ADDRESS;

		if (window.YMaps) {
            //==================== Init Yandex Map ===================
			map = new YMaps.Map($('#interactive-map')[0]);
			map.setCenter(new YMaps.GeoPoint(bt.x, bt.y), 16);

			placemark = new YMaps.Placemark(
				new YMaps.GeoPoint(bt.x, bt.y),
				{ balloonOptions: { maxWidth: 160 } }
			);
			placemark.name = "O'Brien's";
			placemark.description = addr;
			map.addOverlay(placemark);

			map.addControl(new YMaps.TypeControl());
			map.addControl(new YMaps.ToolBar());
			map.addControl(new YMaps.Zoom());

			getMapImage = function() {
				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.obriens.YMAPS_KEY /* <- set inside 'base.html' */
			}
        } else if (window.google && window.google.maps) {
            //==================== Init Google Map ===================
            // Prevent print/close disappearing
            var cpEl = $('#interactive-map .close-or-print').detach();

            map = new google.maps.Map2($('#interactive-map')[0]);
            map.setCenter(new google.maps.LatLng(bt.y, bt.x), 16);
            var customUI = map.getDefaultUI();
            customUI.controls.scalecontrol = false;
            map.setUI(customUI);

            $('#interactive-map').append(cpEl);
            placemark = new google.maps.Marker(map.getCenter());

            map.obriensTextEl = $(
                    '<div class="gmaps-balloon">' +
                        '<h3 style="font-weight:bold;">O\'Brien\'s</h3>' +
                        '<span>' + addr + '</span>' +
                    '</div>'
                    )[0];
            placemark.bindInfoWindow(map.obriensTextEl);
            map.addOverlay(placemark);

            getMapImage = function(){
                var static_type;
                var current_map_type = map.getCurrentMapType();
                if (current_map_type == G_NORMAL_MAP)
                    static_type = 'roadmap';
                else if (current_map_type == G_SATELLITE_MAP)
                    static_type = 'satellite';
                else if (current_map_type == G_HYBRID_MAP)
                    static_type = 'hybrid';
                else if (current_map_type == G_PHYSICAL_MAP)
                    static_type = 'terrain';
                    
                return 'http://maps.google.com/maps/api/staticmap?center=' + map.getCenter() +
						'&size=650x450&zoom=' + map.getZoom() +
						'&maptype=' + static_type +
						'&markers=color:red|label:O|' + bt.y + ',' + bt.x +
						'&sensor=false&language=' + WR.obriens.GOOGLE_MAP_LANGUAGE;
			}
        } else { // Maps may be blocked somehow
			getMapImage = function(){
				return $('#interactive-map img.map-static').attr('src');
			}
		}

		// Init printing functionality
		$('#print-map').click(function(e) {
			e.preventDefault();

			var win = open('', 'printme', 'width=' + 800 + ',height=' + 600);
			win.document.open();
			win.document.write(
				'<div style="text-align:center;padding-top:20px;">' +
                    '<h3 style="padding: 10px;">O\'Brien\'s Irish Pub</h3>' +
                    '<img alt="" src="' + getMapImage() + '" />' +
					'<div style="padding: 10px; font-size: 14px;">' + addr + '</div>' +
				'</div>'
			);
			win.document.close();

            win.focus();

            var _printAndClose = function(){
				win.print();
                win.blur();
                win.close();
			}

            if ($.browser.opera)
                win.onload = _printAndClose;
            else
                $(win).ready(_printAndClose);

			delete win;
		});

		this.initYandexMap = $.noop;
	},

    fixLanguageToggler: function() {
        $('.languages').find('.language-link, .language-image-link').click(function(e) {
            e.preventDefault();
            location.href = this.href + location.hash;
        });
    },

    initPubMap: function() {
        $('.map-and-features .pub-map-first-floor .go-to-floor-2-link').click(function(e) {
            e.preventDefault();
            $('.map-and-features .pub-map-first-floor').hide();
            $('.map-and-features .pub-map-second-floor').fadeIn();
        });

        $('.map-and-features .pub-map-second-floor .go-to-floor-1-link').click(function(e) {
            e.preventDefault();
            $('.map-and-features .pub-map-second-floor').hide();
            $('.map-and-features .pub-map-first-floor').fadeIn();
        });

        $('body').append(
            '<div class="table-tooltip' +
            ($.browser.msie ? ' table-tooltip-ie' : '') +
            '"></div>'
        );

        $(".map-and-features .floor-item-table").hover(
            function() {
                var pos = $(this).offset();
                var title = $(this).attr('title');
                if (title) {
                    $(this).data('title', title).attr('title', '');
                } else {
                    title = $(this).data('title');
                }

                var num = title.split(':'),
                    capacity = num[1],
                    num = num[0];

                if ($('.table-tooltip:animated'))
                    $('.table-tooltip').stop().css({ opacity: 1 });

                $('.table-tooltip')
                    .css({
                        top: pos.top - $('.table-tooltip').height(),
                        left: pos.left + ($(this).width() - $('.table-tooltip').width()) / 2
                    })
                    .html('<strong>' + num + '</strong><span>' + capacity + '</span>')
                    .fadeIn();
            },
            function() {
                $('.table-tooltip').hide();
            }
        );
    }
}

$(function() {
    WR.obriens.init();
})
