var TileManager = new Class({
    Implements: [Options, Events],
    
    options: {
        item_types: ['tile', 'object', 'space', 'graphic', 'label'],
        tile_parent_element_id: 'grid',
        fade_duration: 150
    },
    
    initialize: function(options) {
        this.setOptions(options);
        this.somethingHasBeenClicked = false;
    },
    
    clickedItem: function(itemType) {
		this.deselectAllMenuItems();
		this.selectMenuItem(itemType);
        this.fadeAllTilesExcept(itemType);
        if(this.somethingHasBeenClicked) {
            this.unfadeTiles(itemType);
        }
        this.somethingHasBeenClicked = true;
    },
	
	deselectAllMenuItems: function() {
		var menuItems = $('menu').getChildren();
		menuItems.each(function(thisItem) {
			thisItem.removeClass('menu_selected');
		});
	},
	
	selectMenuItem: function(itemType) {
		var menuItem = $('menu_' + itemType);
		if(menuItem) {
			menuItem.addClass('menu_selected');
		}
	},
    
    unfadeTiles: function(itemType) {
        var grid = $(this.options.tile_parent_element_id);
        var tiles = grid.getChildren('.' + itemType);
        tiles.each(function(thisTile) {
            thisTile.removeClass('faded');
            var thisFiller = thisTile.getChildren()[1];
            var myFx = new Fx.Tween(thisFiller, {
                duration: this.options.fade_duration
            });
            myFx.start('opacity', 0);
        }, this);

    },
    
    fadeAllTilesExcept: function(itemType) {
        var grid = $(this.options.tile_parent_element_id);
        var allTiles = grid.getChildren();
        var exceptions = grid.getChildren('.' + itemType);
        var matchTiles = allTiles.filter(function(item) {
           return (!exceptions.contains(item));
        });
        
        matchTiles.each(function(thisTile) {
            thisTile.addClass('faded');
            var thisFiller = thisTile.getChildren()[1];
            if(thisFiller.getStyle('opacity') == 1) {
                thisFiller.setStyle('opacity', 0);
            }
            var myFx = new Fx.Tween(thisFiller, {
                duration: this.options.fade_duration
            });
            myFx.start('opacity', 0.8);
            
        }, this);
    }
 
});
