<% ids = "$$('#associated_#{field} input[type=hidden]').collect(function(element){return $F(element)})" %>
<div class="header">
  <div class="popup_close"><%= link_to t(:close), '#', :terbium_popup_close => true %></div>
  <ul class="navigation">
    <li<%= ' class="selected"' if params[:action] == "associated_#{field}" %>>
      <%= link_to t(:existing), '#', :ajax => resource_path(record, "associated_#{field}"), :ids => ids %>
    </li>
    <li<%= ' class="selected"' if params[:action] == "associated_#{field}_choosing" %>>
      <%= link_to t(:choosing), '#', :ajax => resource_path(record, "associated_#{field}_choosing"), :ids => ids %>
    </li>
    <li class="notab">
      <% form_tag '#', :class => 'associated_search', :ajax => current_path, :ids => ids do %>
        <%= text_field_tag :query, resource_session[:query] %>
        <%= submit_tag 'Search' %>
        <% if resource_session[:query].present? %>
          <%= link_to 'clear', '#', :ajax => current_path(:query => ''), :ids => ids %>
        <% end %>
      <% end %>
    </li>
  </ul>
</div>

<div class="pagination">
  <%= will_paginate associated, :renderer => AssociatedLinkRenderer, :ids => ids %>
</div>

<div class="popup_content">
  <table class="list_table">
    <thead>
      <tr>
      <% field.association_fields.each do |f| -%>
        <th><%= f.label %></th>
      <% end -%>
        <th class="actions">Actions</th>
      </tr>
    </thead>
    <tbody>
    <% associated.each do |association| -%>
      <tr id="<%= dom_id association %>">
      <% field.association_fields.each do |f| -%>
        <td><%= render_field association, f %></td>
      <% end -%>
        <td class="actions">
          <%= link_to t(:show), resource_path(association), :target => '_blank' if (resource_path(association) rescue nil) %>
          <% if params[:action] == "associated_#{field}" %>
            <%= link_to_function t(:remove), "$('associated_#{field}_#{association.id}').remove(); $('#{dom_id association}').remove()" %>
          <% else %>
            <%= link_to_function t(:add), "$('associated_#{field}').insert({bottom: \"#{escape_javascript hidden_field_tag("#{model_name}[#{field.to_s.singularize}_ids][]", association.id, :id => "associated_#{field}_#{association.id}")}\"}); $('#{dom_id association}').remove()" %>
            <%= link_to_function t(:add), "$('associated_#{field}').replace(\"#{escape_javascript render(:partial => "terbium/association/many", :object => @choosen + [association], :locals => {:field => field})}\"); Event.addBehavior.reload()" %>
          <% end %>
        </td>
      </tr>
    <% end -%>
    </tbody>
  </table>
</div>