
var solrURL = "http://localhost:8983/solr/select";

var facetQueries = {
  '発売年':
    {'2009年以降':'pub_date:[20090101 TO *]'
     , '2008年':'pub_date:[20080101 TO 20081231]'
     , '2007年':'pub_date:[20070101 TO 20071231]'
     , '2006年':'pub_date:[20060101 TO 20061231]'
     , '2005年':'pub_date:[20050101 TO 20051231]'
     , '2004年以前':'pub_date:[* TO 20041231]'}
};

var facetLabels = {
  'genre':'ジャンル'
  , 'keyword':'キーワード'
  , 'author_facet':'著者'
};

var filters = new Array();

function resetFilters(){
  filters.length = 0;
}

function requestSolr(start,fq){
  if(fq != undefined){
    filters.push(fq);
  }
    var params = getstandardargs().concat(getquerystring());
    params = params.concat(getfacetqueriesarray());
    params = params.concat(getstartstring(start));
    params = params.concat(getfqstringarray());
    params = params.concat(getfacetfieldarray());
    var strData = params.join('&');
  $.getJSON(solrURL+'?'+strData, updatepage);
}


function getfacetqueriesarray(){
  var facetqueriesarray = new Array();
  for(var label in facetQueries){
    for(var key in facetQueries[label]){
      facetqueriesarray.push("facet.query="+facetQueries[label][key]);
    }
  }
  return facetqueriesarray;
}

function getfacetfieldarray(){
  var facetfieldarray = new Array();
  for ( var field in facetLabels) {
    facetfieldarray.push("facet.field=" + field);
  }
  return facetfieldarray;

}

function getstandardargs() {
    var params = [
            'wt=json'
            , 'json.wrf=?'
            , 'json.nl=map'
            , 'rows=10'
            , 'fl=url,title,price,author,pages,isbn'
            , 'hl=true'
            , 'hl.fl=title,summary,intended_reader,from_author,toc'
            , 'hl.snippets=1'
            , 'f.title.hl.alternateField=title'
            , 'f.summary.hl.alternateField=summary'
            , 'f.summary.hl.maxAlternateFieldLength=100'
            , 'hl.usePhraseHighlighter=true'
            , 'hl.simple.pre=<b style="background:aquamarine">'
            , 'hl.simple.post=</b>'
            , 'facet=on'
            , 'facet.limit=20'
            , 'facet.mincount=1'
            , 'facet.sort=count'
    ];

    return params;
}

function getfqstringarray(){
  fqstringarray = new Array();
  for(var fq in filters){
    fqstringarray.push("fq="+filters[fq]);
  }
  return fqstringarray;
}
function getstartstring(start){
  startstring = "";
  if(start != undefined){
    startstring = "start="+start;
  }else{
    startstring = "start=0";
  }
  return startstring;
}

function getquerystring() {
  var form = document.forms['f1'];
  var query = form.query.value;
  if( query ){
    qstr = 'q=' + (query);
  }else{
    qstr = 'q=*:*';
  }
  return qstr;
}

function updatepage(rsp){
  if (! rsp ) return null;
  var found = rsp.response.numFound;
  var start = (rsp.response.start) ? parseInt(rsp.response.start) : 0;
  var rows = (rsp.responseHeader.params.rows) ? parseInt(rsp.responseHeader.params.rows) : 10;
  // numFound
  resultHeader(rsp, found, start, rows);
  // result docs
  var resultHtml = "";
  if(found == 0){
    var form = document.forms['f1'];
  	resultHtml += "<b>"+form.query.value+"</b> は見つかりませんでした。他の検索語で試してください。";
    document.getElementById("facet").innerHTML = "";
    document.getElementById("page").innerHTML = "";
    document.getElementById("result").innerHTML = resultHtml;
  } else {
    for(i = 0; i <  rsp.response.docs.length; i++){
      var doc = rsp.response.docs[i];
      resultHtml += documentHtml(doc,rsp);
    }
    document.getElementById("result").innerHTML = resultHtml;

    // facet
    var facetHtml = "";

    // facet field
    for(var field in rsp["facet_counts"]["facet_fields"]){
      facetHtml += facetFieldHtml(rsp, field);
    }
    // facet query
    for(var label in facetQueries){
      facetHtml += facetQueriesHtml(rsp, label);
    }

    document.getElementById("facet").innerHTML = facetHtml;

    // pagination
    document.getElementById("page").innerHTML = paginationHtml(rsp, found, start, rows);
  }

}

function resultHeader(rsp, found, start, rows){
  var form = document.forms['f1'];
  var query = form.query.value;
  var headerHtml= "";
  if(query){
    headerHtml += "<b>"+query+"</b> の検索結果&nbsp;&nbsp;&nbsp;";
  }
  if(found > 0){
    headerHtml += "<b>"+found+"</b> 件中";
    headerHtml += "<b>"+(start+1)+"</b> - ";
    headerHtml += "<b>"+ ((start + rows > found) ? found : start + rows )+"</b>件目";
  }else{
    headerHtml += "<b>0</b> 件";
  }
  headerHtml += "( "+rsp.responseHeader.QTime/1000+" 秒 )"
  document.getElementById("result_header").innerHTML = headerHtml;

}

function documentHtml(doc, rsp){
  var hi =rsp ["highlighting"][doc.url];
  var tempHtml = "";
  tempHtml += "<h2><a href=\""+doc.url+"\">"+hi.title+"</a></h2>";
  tempHtml += "<div class=\"articles\">";
  // highlighting text in result docs
  var snippets = [];
  var tmpArray = ["summary","intended_reader","from_author","toc"];
  for(var i in tmpArray){
    if(hi[tmpArray[i]]){
      snippets = snippets.concat(hi[tmpArray[i]]);
    }
  }
  tempHtml += snippets.join("...");
  tempHtml += "</div><br/>"
  tempHtml += "<div class=\"articles\">";
  if(doc.author){
    tempHtml += "著者：";
    tempHtml += doc.author.join(", ");
  }
  tempHtml += "</div>"
  tempHtml += "<div class=\"articles\">";
  if(doc.price){
    tempHtml += "定価："+doc.price+"円";
  }
  if(doc.pages){
    tempHtml += " | "+doc.pages+"ページ";
  }
  if(doc.isbn){
    tempHtml += " | "+doc.isbn;
  }
  tempHtml += "</div>"
  tempHtml += "<hr/>";
  return tempHtml;
}

function facetLabel(field){
  return (facetLabels[field]) ? facetLabels[field] : field;
}

function facetFieldHtml(rsp, facetField ){
  facetHtml = "";
  if(rsp["facet_counts"]["facet_fields"][facetField]){
    facetHtml += "<h2>"+facetLabel(facetField)+"</h2><div id=\""+facetField+"\">";
    for(var field in rsp["facet_counts"]["facet_fields"][facetField]){
      var field_count = rsp["facet_counts"]["facet_fields"][facetField][field];
      if(field_count > 0){
        facetHtml += "<a href=\"javascript:requestSolr(0,'"+facetField+":"+field+"');\">"+field+"("+field_count+")"+"</a><br>";
      }
    }
    facetHtml += "</div>";
  }
  return facetHtml;
}

function facetQueriesHtml(rsp, facetTitle){
  facetHtml = "";
  if(rsp["facet_counts"]["facet_queries"]){
    facetHtml += "<h2>"+facetTitle+"</h2><div>";
    for(var key in facetQueries[facetTitle]){
      var facet_count = rsp["facet_counts"]["facet_queries"][facetQueries[facetTitle][key]];
      if(facet_count > 0){
        facetHtml += "<a href=\"javascript:requestSolr(0,'"+facetQueries[facetTitle][key]+"');\">"+key+"("+facet_count+")"+"</a><br>";
      }
    }
    facetHtml += "</div>";
  }
  return facetHtml;
}

function paginationHtml(rsp, found, start, rows){
  var pageHtml = "";

  var p_head = '|&lt;&lt;先頭ページへ';
  var p_prev = '&lt;前へ';
  var p_next = '次へ&gt;';
  var p_tail = '末尾ページへ&gt;&gt;|';

  var wsiz = 10;
  var w1 = 5;
  var w2 = 5;

  // 全ページ数
  var pcnt = Math.ceil(found / rows);

  // 現在のページ番号
  var cpag = start / rows + 1;

  // ウィンドウ開始・終了（ページ番号）
  var wbgn = cpag - w1;
  var wend = cpag + w2;
  if( wbgn < 1 ){
    wbgn = 1;
    wend = wbgn + wsiz;
    if( wend > pcnt + 1 ){
      wend = pcnt + 1;
    }
  }
  if( wend > pcnt + 1 ){
    wend = pcnt + 1;
    wbgn = wend - wsiz;
    if( wbgn < 1 ){
      wbgn = 1;
    }
  }
  if( pcnt > 1 ){
    pageHtml += "<strong>Page</strong>：";
    if( cpag > 1 ){
      pageHtml += "<a href=\"javascript:requestSolr(0,null);\">"+p_head+"</a>&nbsp;&nbsp;&nbsp;";
      pageHtml += "<a href=\"javascript:requestSolr("+((cpag-2)*rows)+",null);\">"+p_prev+"</a>&nbsp;&nbsp;&nbsp;";
    }
    pageHtml += "&nbsp;";
    for(i=wbgn;i<wend;i++){
    if(cpag == i){
      pageHtml += ""+i+"&nbsp;&nbsp;&nbsp;"
    }else{
      pageHtml += "<a href=\"javascript:requestSolr("+((i-1)*rows)+",null);\">"+i+"</a>&nbsp;&nbsp;&nbsp;";
    }
    }
    pageHtml += "&nbsp;";
    if( cpag < pcnt ){
      pageHtml += "<a href=\"javascript:requestSolr("+(cpag*rows)+");\">"+p_next+"</a>&nbsp;&nbsp;&nbsp;";
      pageHtml += "<a href=\"javascript:requestSolr("+((pcnt-1)*rows)+");\">"+p_tail+"</a>&nbsp;&nbsp;&nbsp;";
    }
    pageHtml += "</div>";
  }
  return pageHtml;
}

