<% content_for :right_nav do %>
  <ul class="nav nav-pills filter-nav pull-right">
    <% fields.keys.each do |field| %>
      <% org_field = field %>
      <% field = field.to_s.split(".").last %>
      <li class="accordion-group">
        <div class="accordion-heading">
          <a href="#collapse-<%= field %>" data-toggle="collapse" data-parent="#filter" class="accordion-toggle"><%= t(org_field) %></a>
        </div>
      </li>
    <% end %>
  </ul>
  <div class="filter-group accordion-group">
    <% fields.keys.each do |field| %>
      <% org_field = field %>
      <% field = field.to_s.split(".").last %>
      <div class="accordion-body collapse" id="collapse-<%= field %>">
        <div class="accordion-inner pagination-right" >
          <% if fields[org_field].class == String %>
            <%= fields[org_field].html_safe %>
          <% else %>
            <% fields[org_field].each do |val| %>
              <%= link_to (val[:title].blank? ? "" : val[:title]), "#", :onclick => "filter.addFilter('filters[#{field}][]=#{val[:id]}');$(this).toggleClass('active');return false;", :class => "btn btn-small #{is_filter_active?(field, val[:id])}", :id => "filter_#{val[:id]}" %>
            <% end %>
          <% end %>
        </div>
        <div class="filter-clear">
          <a href="#" onclick="filter.clearFilter();" class="btn btn-link btn-small"><i class="icons-cycle"></i> <%= t(:clear) %></a>
        </div>
      </div>
    <% end %>
  </div>
<% end %>
<script type="text/javascript">
  <% if !search_dom_id.nil?%>
  var interval = 0;
  var keyword;
  var searchLock=false;

  $("#filter-input").bind("input", function() {queueSearch();});
  $("#module-search-form").submit(function(){queueSearch(); return false; });

  var params = function(key){
    var result = {};
    var datas = window.location.search ? window.location.search.replace('?','').split('&') : []
    datas.map(function(data){
      tmp = data.split("=");
      tmp[1] = decodeURIComponent(tmp[1]);
      if(key){
        if(tmp[0]==key){
          if(tmp[0].indexOf('[]')>=0){
            if(!Array.isArray(result)) result = [];
            result.push(tmp[1]);
          }else{
            result = tmp[1];
          }
        }
      }else{
        if(tmp[0].indexOf('[]')>=0){
          if(typeof(result[tmp[0]]) == "undefined") result[tmp[0]] = [];
          result[tmp[0]].push(tmp[1]);
        }else{
          result[tmp[0]] = tmp[1];
        }
      }
    });
    return result;
  }

  var queueSearch = function(){
    if($("#filter-input").val()!=keyword){
      keyword = $("#filter-input").val();
      interval=500;
      if(!searchLock) moduleSearch();
    }
  }

  var moduleSearch = function(){
    $("#search-preloader").fadeIn();
    searchLock = true;
    if(interval==0){
      url = document.URL;
      url = url.replace('#','');
      if(url.indexOf("keywords=")>=0){
        url = url.replace("keywords="+encodeURIComponent(params("keywords")),"keywords="+keyword)
      }else{
        url = (url.indexOf("?")>=0) ? url+"&keywords="+keyword : url+"?keywords="+keyword
      }
      url = url.replace("page="+params("page"),"page=1");

      history.pushState(null, null, url);
      $.get(url,function(data){
        searchLock = false;
        $("#<%= search_dom_id %>").html(data);
        bindPagination();
        $("#search-preloader").fadeOut();
      });
    }else{
      interval -= 100;
      setTimeout(moduleSearch,100);
    }
  }
  <% end %>

  var bindPagination = function(){
    $(".pagination a").click(function(){
      filter.updateTable($(this).attr('href'),false,true);
      return false;
    });
  }


  var Filter = function(dom){
    var self = this;
    var makeFilters = function(){
      return (window.location.search ? window.location.search.replace('?','').split('&') : []);
    }
    var filters = makeFilters(),
          dom = $(dom),
          mainUrl = window.location.pathname;
    this.updateTable = function(url, goback, is_pagination){
      update = true;
      xurl = (url == null ? ( filters.length ?  mainUrl + "?" + filters.join('&') : mainUrl ) : url);
      $.ajax({
        url : xurl,
        type : "get",
        dataType : "html" 
      }).done(function(data){
        if(is_pagination){
          history.pushState(null, null, decodeURIComponent(xurl));
        }else{
          if(!goback) history.replaceState(null, null, decodeURIComponent(xurl));
        }
        filters = makeFilters();
        dom.html(data);
        bindPagination();
        update = false;
      })
    }
    this.addFilter = function(filter){
      filters = makeFilters();
      $.each(filters,function(idx,data){
        if(typeof(data)=="undefined") return true;
        if(data.indexOf("page=")>-1) filters.splice(idx,1);
      });

      if( (index = filters.indexOf(filter) ) > -1){
        mainUrl = mainUrl.replace(filter,'');
        filters.splice(index,1);
      }else{
        filters.push(filter);
      }

      self.updateTable();
      return false;
    };

    this.clearFilter = function(){
      $(".filter-group a.active").removeClass("active");
      filters = [];
      self.updateTable();
      return false;
    }

    window.onpopstate = function(event){
      if(!update){
        $("#filter-input").val( $.isEmptyObject(params('keywords')) ? "" : params('keywords') );
        self.updateTable(document.location, true);
        $(".filter-group .btn-small").removeClass('active');
        $.each(document.location.search.split('&'),function(key,filter){
          if(filter.split('=')[0].indexOf("keywords")>=0) return true;
          $('#filter_'+filter.split('=')[1]).addClass('active');
        });
      }
      update = false;
    }
  }

  var update = false;
  var filter;
  $(document).ready(function(){
    filter = new Filter("#<%= search_dom_id %>");
    bindPagination();
  });
</script>