var AgentDirectory = {};

AgentDirectory.display_directory = function() {
  new Ajax.Request('/agent_directory/directory.json', {
    method: 'get',
    onSuccess: function(r) {
      var create_entry = function(data) {
        var agency = new Element('div').addClassName('agency-block-contents');

        ['Name of Agency', 'Address', ['%s, %s %s', 'City', 'State', 'Zip'], 'Phone Number', 'Web Address', 'E-Mail'].each(function(p) {
          var value;
          if (p instanceof Array) {
            var format = p.shift();
            p.each(function(v) { format = format.replace('%s', data[v]); });
            value = format;
          } else {
            value = data[p];
          }

          var element_type = 'div';

          if (value.search(/[a-z]/) != -1) {
            switch(p) {
              case 'Name of Agency':
                element_type = 'h3'; break;
              case 'Web Address':
                if (value.indexOf('http://') != 0) {
                  value = 'http://' + value;
                  value = new Element('a', { href: value, target: 'htm'}).update(value);
                }
                break;
              case 'E-Mail':
                value = new Element('a', { href: 'mailto:' + value }).update(value);
                break;
            }

            agency.insert(new Element(element_type).update(value));
          }
        });

        return new Element('div').addClassName('agency-block').update(agency);
      }

      var onclick = function(e) {
        Event.stop(e);

        $$('#agent-state-holder a').each(function(cur_a) {
          if (cur_a == e.target) {
            cur_a.addClassName('selected');
            cur_a.setOpacity(1);
          } else {
            cur_a.removeClassName('selected');
            cur_a.setOpacity(0.75);
          }
        });

        $('agent-viewer').innerHTML = '';
        e.target.data.each(function(data) {
          var d = create_entry(data).hide();
          $('agent-viewer').insert(d);
          new Effect.BlindDown(d, { duration: 0.25 });
        });
      };

      var first = null;
      var count = 0;
      $H(r.responseText.evalJSON()).each(function(p) {
        var a = new Element('a', { href: '#' }).update(p.key);
        a.data = p.value;
        count += p.value.length;

        a.observe('click',onclick);
        a.observe('agent:open',onclick);
        $('agent-state-holder').insert(a);
        $('agent-state-holder').insert(' ');
        
        if (first == null) { first = a; }
      });

      first.fire('agent:open');
      $('agent-count').update(count);
    }
  });
};