//
//  InfiniteLoading.js
//  InfiniteLoading for Movable Type
//
//  Created by isloop on 2015/03/09.
//  Copyright (c) @isloop. All rights reserved.
//

<$mt:Include module="<__trans phrase="Common Variables">" strip_linefeeds="1"$>

$(function(){

  const LIMIT       = <mt:var name="entries_per_page">;
  const MT_PATH     = "<mt:AdminCGIPath>";
  const LOADING_DIV = "#pagination";
  const APPEND_DIV  = "#block-entries";
  const SCRIPT_ID   = "#loading";

  var mode  = $(SCRIPT_ID).data('mode');
  var style = $(SCRIPT_ID).data('style');
  var page  = 1;
  var max   = 0;
  var fire  = false;

  <mt:IfArchiveTypeEnabled archive_type="Author">
  var authors = {
  <mt:ArchiveList archive_type="Author">"<mt:ArchiveTitle>":"<mt:ArchiveLink>",
  <mt:If name="__last__">};</mt:If></mt:ArchiveList>
  </mt:IfArchiveTypeEnabled>

  $(LOADING_DIV).fadeOut("fast");

  $(window).on("scroll" , function(){
    var bottomPos = 3072;
    var scrollHeight = $(document).height();
    var scrollPosition = $(window).height() + $(window).scrollTop();

    if (scrollPosition > scrollHeight - bottomPos){
      $(LOADING_DIV).fadeIn("fast");
      if (max >= ((page * LIMIT) - LIMIT) && fire == true
        || max == 0 && page == 1 && fire == false){
        fire = false;
        getDataAPI();
        page++;
      }
      else if (max < ((page * LIMIT) - LIMIT) && max > 0) {
        $(LOADING_DIV).remove();
      }
    }
  });

  function getDataAPI(){
    $.ajax({
      type: "GET",
      url: choiceURL(),
      dataType: 'json',
      success: function(res){
        appendHTML(res);
        $(LOADING_DIV).fadeOut();
      },
      error:function(){},
      complete:function(){fire = true;}
    });
  }

  function appendHTML(res){
    max = res.totalResults;
    for (var i = 0; i < res.items.length; i++) {
      html = indexStyle(res.items[i]);
      $(APPEND_DIV).append(html);
    }
  }

  function choiceURL(){
    var uri = new String();
    if (mode == "category") {
      var categoryid = $(SCRIPT_ID).data('categoryid');
      uri = MT_PATH + "mt-data-api.cgi/v3/sites/<mt:BlogId>/categories/" + categoryid + "/entries?limit=" + LIMIT + '&offset=' + page*LIMIT;
    }
    else {
      uri = MT_PATH + "mt-data-api.cgi/v3/sites/<mt:BlogId>/entries?limit=" + LIMIT + '&offset=' + page * LIMIT;
    }
    return uri;
  }

  function indexStyle(res) {

    var category  = res.categories.shift();
    var date      = dateFromStr(res.createdDate);
    var authorUrl = removeProtocol(res.author.userpicUrl);
    var entryUrl  = removeProtocol(res.permalink);
    var imageUrl  = removeProtocol(imageURLFromStr(res));

    var html = new String();
    html += "<li>";
    html += "  <article>";
    html += "    <figure class=\"entry-image\">";
    html += "      <a href=\"" + entryUrl + "\" class=\"image\"><img src=\"" + imageUrl + "\" alt=\"\" width=\"448\"></a>";
    if ( category ) {
      html += "      <a href=\"#\" class=\"label category\">" + category.label + "</a>";
    }
    html += "    </figure>";
    html += "    <div class=\"entry-detail clearfix\">";
    html += "      <div class=\"entry-meta clearfix\">";
    html += "        <div class=\"entry-author\">";
    html += "          <figure><a href=\"" + authors[res.author.displayName] + "\"><img src=\"" + authorUrl + "\" alt=\"" + res.author.displayName + "\"></a></figure>";
    html += "          <p><a href=\"" + authors[res.author.displayName] + "\">" + res.author.displayName + "</a></p>";
    html += "        </div>";
    html += "        <div class=\"entry-date\">";
    html += "          <time datetime=\"" + res.date + "\">" + date + "</time>";
    html += "        </div>";
    html += "      </div>";
    html += "      <div class=\"entry-title\">";
    html += "        <a href=\"" + entryUrl + "\">" + res.title + "</a>";
    html += "      </div>";
    html += "    </div>";
    html += "  </article>";
    html += "</li>";
    return html;
  }

  function dateFromStr(str){
    var dateFromStr = Date.parse(str);
    var date = new Date(dateFromStr);
    var year = date.getFullYear();
    var month = ("" + (date.getMonth()+1)).slice(-2);
    var day = (" " + date.getDate()).slice(-2);
    var dateStr = year + "年" + month + "月" + day + "日";
    return dateStr;
  }

  function removeProtocol(str) {
    var text = str;
    text = String(text).replace( /https?\:/g, '' );
    return text
  }

  function imageURLFromStr(obj){

    // Read from CustomFields
    if ( obj.customFields.length > 0 ) {
      var cfImage;
      for ( var cf of obj.customFields ) {
        if ( cf.basename === "blog_entry_ogp_image" && cf.value ) {
          cfImage = obj.customFields[0].value.match(/http[s]?\:\/\/[\w\+\$\;\?\.\%\,\!\#\~\*\/\:\@\&\\\=\_\-]+/g);
          if ( cfImage ) {
            break;
          }
        }
      }
      if ( cfImage ) {
        return cfImage;
      }
    }

    // Next, read from entry assets
    if ( obj.assets.length > 0 ) {
      return obj.assets[0].url;
    }

    // otherwise, return default.
    return "<$mt:BlogURL encode_html="1"$>images/noimage-448.png";
  }

  function getCaregoryArchive(cat){
    return cat;
  }
});
