var Pfizer = Pfizer || {};
Pfizer.GMap.MenuControl = (function($, google) {
    'use strict';

    var MenuControl = function (categories, id, marker_overlay, initial_active) {
        this.categories = categories;
        this.marker_overlay = marker_overlay;
        this.enabled = initial_active;
        this.id = id;
        this.div = this._make_div(id)[0];
    };

    MenuControl.prototype.add_to_map = function (map) {
        map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(this.div);
        for (var i in this.categories) {
            this.set_dim_state(i);
        }
    };

    MenuControl.prototype.set_dim_state = function (i) {
        var $div = $("#" + this.id);
        var $a = $div.find("li a").eq(i);

        if (this.enabled[i]) {
            this.marker_overlay.show_category(i);
            $a.css({ opacity : 1.0 });
            $a.find('img').css({
                'border-style' : 'solid',
                'padding'      : 0
            });
        }
        else {
            this.marker_overlay.hide_category(i);
            $a.css({ opacity : 0.5 });
            $a.find('img').css({
                'border-style' : 'none',
                'padding'      : 1
            });
        }
    };

    MenuControl.prototype._make_div = function (id) {
        var $div = $('<div id="' + id + '"></div>');
        var $ul = $('<ul></ul>');

        var localthis = this;

        for (var i in this.categories) {
            var $li = $('<li></li>');
            // XXX don't hardcode /images/ here
            var $a = $('<a href="javascript:void(0)">'
                         + '<img src="/responsibility/global_health/img/menu_button' + i + '.png" />'
                         + this.categories[i]
                     + '</a>');

            // XXX should be able to use set_dim_state, but not working,
            // even if i delay the call
            if (this.enabled[i]) {
                $a.css({ opacity : 1.0 });
                $a.find('img').css({
                    'border-style' : 'solid',
                    'padding'      : 0
                });
            }
            else {
                $a.css({ opacity : 0.5 });
                $a.find('img').css({
                    'border-style' : 'none',
                    'padding'      : 1
                });
            }

            $a.click((function () {
                var menu = localthis;
                var idx  = i;
                return function () {
                    menu.enabled[idx] = !menu.enabled[idx];
                    menu.set_dim_state(idx);
                }
            })());
            $li.append($a);
            $ul.append($li);
        }

        $div.append($ul);

        return $div;
    };

    return MenuControl;
})(jQuery, google);
