/* GX - SearchResults
 * Author: paulm, markvc
 */

rows = 8;
currentPage = 1;
start = 0;
keyword = '';
searchCategory = 'consumenten';
textRefresh = true;
initial = true;
doScroll = false;
previousKeyWord = '';

window.dhtmlHistory.create({
  toJSON: function(o) {
    return JSON.stringify(o);
  },
  fromJSON: function(s) {
    return JSON.parse(s);
  }
});

/* JQuery init */
$(function(){

  dhtmlHistory.initialize();
  dhtmlHistory.addListener(historyNavigate);

    searchCategory = $('#site-search-category').val();

    // only if link is present (on searchpage)
  if ($('#ajaxcall').length > 0 && $('#ajaxcall').attr("href") != '') {

    // keyword is set for initiation
    if ($('#keywordresults').html() != '') {
      keyword = $('#keywordresults').html();
    }

    // no page refresh when already on searchresult page
      $('#site-search-submit').live("click",function () {
        currentPage = 1;
        event.preventDefault();
        keyword = $('#site-search-input').val();
        searchCategory = $('#site-search-category').val();
        textRefresh = true;
        search();
      });

      // searchresult paging navigation
      $('#search-navigation a').live("click",function () {
        doScroll = true;
        currentPage = parseInt($(this).attr('name'));
        textRefresh = false;
        search();
      });
      search('initial');
  }
});

/* historyNavigate function */
function historyNavigate(newLocation, historyData) {
  var hashData = newLocation.split(',');
  if (hashData.length == 3) {
    keyword = unescape(hashData[0]);
    searchCategory = unescape(hashData[1]);
    currentPage = parseInt(hashData[2]);
    search('history');
  }
}

/* search function */
function search(mode) {

  if (mode == 'initial') {
    $('#site-search-input').val(keyword);
  }

  if (textRefresh) {
    $('#keywordresults').val(keyword);
  }

  var ajaxUrl = $('#ajaxcall').attr("href");
  query = keyword;
  var base = '&query=' + query;
  base += '&rows=' + rows;
  base += '&category=' + searchCategory;

  if (currentPage > 1) {
      // not on firstpage
      start = (currentPage-1) * rows;
  } else {
      start = 0;
  }
  base += '&start=' + start;
  var url = ajaxUrl + base + '&retrieve=all'

  if (mode != 'history') {
    //dhtmlHistory.add(base, 'GX');
    var hash = keyword + ',' + escape(searchCategory) + ',' + currentPage;
    if (window.location.hash == '') {
      window.location.replace('#' + hash);
    } else if (mode != 'initial') {
      dhtmlHistory.add(hash, 'GX');
    }
  }

  // ajax call to get searchresults
  $.ajax({
      url: url,
      type: "GET",
      dataType: 'json',
      error:function (xhr, ajaxOptions, thrownError){
        //alert('DEBUG ERROR STATUS:\nError: ' + ajaxOptions + '\nReadystate: ' + xhr.readyState + '\nStatus: ' + xhr.statusText + '\nError thrown: ' + thrownError + '\nResponse:\n\n\n' + xhr. responseText);
      },
      success: fillResult
  });
}

/* ajaxcall succesfull, function called */
function fillResult(data) {

  //sitestat for each unique search term. 
  if (currentPage == 1 && previousKeyWord != keyword) { 
  sitestatForAjaxCall(data.count);
  previousKeyWord = keyword;
  }

  $('#searchresults').empty();
  $('#countresults').html(data.count);

  if (data.count != 0) {
    $('#showresults').css('display', 'block');
    $('#shownoresults').css('display', 'none');
    resultnr = 1;

    // fill searchresults
    contentData = '<dl>';
    $.each(data.results, function(i,r){
      contentData += '<dt><a href="' + r.location + '">' + r.title;
      contentData += '</a></dt><dd>';
      contentData += r.summary.replace(/<(.|\n)*?>/g, '').replace(/<([^>]|\n)*?$/, '');
      contentData += '</dd>';
      contentData += '<dd class="link-blue">' + r.location + '</dd>';
    });
    contentData += '</dl>';
    $('#searchresults').append(contentData);

    // paging blok
    if (data.count > rows) {
        // more items then per page
      // added paging div
      dataPaging = '<ul class="paging" id="search-navigation">';
        pages = parseInt(data.count / rows);
      if (data.count % rows != 0) {
        pages = pages + 1;
      }
      if (currentPage > pages) {
        // currentpage must be set to 1
        currentPage = 1;
      }
      previousPage = currentPage - 1;
      nextPage = currentPage + 1;

      if (currentPage == 1) {
        dataPaging += '<li class="inactive"><span>Vorige</span></li>';
      } else {
        dataPaging += '<li><a href="#" onclick="return false;"';
        dataPaging += ' name="' + previousPage + '">Vorige</a></li>';
      }

      startNav = currentPage - 2;
      endNav = currentPage + 2;

      startNav = (startNav <= 1) ? 1 : startNav;
      endNav = (endNav >= pages) ? pages : endNav;

        for (var i = startNav; i <= endNav; i++) {
          if (i == 1) {
            start = '1';
            end = rows;
          } else {
            start = ((i-1) * rows) + 1;
            end = i * rows;
          }
          if (end > data.count) {
            end = data.count;
          }
          range = '[' + start + '-' + end + ']';
           if (currentPage == i) {
            resultnr = parseInt(start);
            dataPaging += '<li class="current"><a href="#" onclick="return false;" name="' + i + '">' + i + '</a></li>';
            if (textRefresh) {
              $('#rangeresults').html(data.count);
            }
          } else {
            dataPaging += '<li><a href="#" onclick="return false;"';
            dataPaging += ' name="' + i + '">' + i + '</a></li>';
          }
        }
      if (currentPage == pages) {
        dataPaging += '<li class="inactive"><span>Volgende</span></li>';
      } else {
        dataPaging += '<li><a href="#" onclick="return false;"';
        dataPaging += ' name="' + nextPage + '">Volgende</a></li>';
      }
        dataPaging += '</ul>';
        $('#searchresults').append(dataPaging);

    } else {
    // no paging
    $('#rangeresults').html(data.count);
    }

    cufonRefresh = '<script type="text/javascript"> Cufon.replace("#rangeresults"); Cufon.replace("#keywordresults"); </script>';
    $('#searchresults').append(cufonRefresh);

  } else {
    // no results
    $('#showresults').css('display', 'none');
    $('#shownoresults').css('display', 'block');
  }

  if (initial) {
    initial = false;
    var hashData = window.location.hash.replace(/^#/, '');
    if (hashData.length > 0) {
      historyNavigate(hashData);
    }
  }

  if (doScroll) {
    doScroll = false;
    window.scrollTo(0, 0);
  }
 }