var Brands = new Class({
    initialize: function() {
        var show = -1;
        
        var brand_name = window.retrieve('brand_name');
        if (brand_name) {        
            var count = 0;
            $$('#brands .brand').each(function(elem) {
                if (elem.get('text') == brand_name) {
                    show = count;
                }
                count++;
            });
        }

        this.accordion = new Accordion($$('#brands .brand'), $$('#brands .categories'), {
            show: show,
            alwaysHide: true
        });
    }
});

var Distributors = new Class({
	initialize: function() {
        var _this = this;
        
		var hookEvent = function(element) {
            var state_id = _this.extract_state_id(element.get('href'));
            var content_div = $('distributor_content');
            var title_element = $('distributor_title');
            
            var request = new Request.JSON({
                url: 'state/' + state_id,
                onComplete: function(state) {
                    title_element.set('text', state.name);                    
                    content_div.set('html', '');
                    
                    if (!state.distributors) {
                        alert(state);
                    }
                    
                    state.distributors.each(function (distributor) {
                        var title = new Element('span', {
                            text: distributor.name,
                            'class': 'style3',
                            style: 'margin-top:0px;'
                        });
                        var description = new Element('div', {
                            html: distributor.description
                        });
                        var wrapper = new Element('div', {
                            style: 'width: auto; margin-bottom:2em'
                        });
                        title.inject(wrapper);
                        description.inject(wrapper);
                        
                        wrapper.inject(content_div);
                    });
                }
            });
            
			element.addEvent('click', function() {
				request.get();
			});
		};
		$$('#distributor_map a, map area').each(hookEvent);
	},
    
    extract_state_id: function(href) {
        var hash_index = href.lastIndexOf('#');
        var result = href.substr(hash_index+1);
        return result;
    }
});

window.addEvent('domready', function() {
    
    if (document.compatMode != 'CSS1Compat')
        alert('Warning, compatability mode is ' + document.compatMode);
    
    if ($('brands')) {
        var brands = new Brands();
    }
	
	if ($('distributor_map'))
		distributors = new Distributors();
});

