/**
 * Created by USER on 2017/10/27.
 */

// 搜索框
$('.findMoreBox').on('click', '.findmore', function (e) {
  e.stopPropagation();
  $('.findMoreBox').toggleClass('expandedFindMoreBox');
  $('.findmore').addClass('removeInput').removeClass('findmore');
  $('.find').addClass('findChange').focus();
  $('.navItemW').hide();
  $('.navItemW2').hide();
  $('.hotfindBox').show();
  // 选中
  var input = $('.findMoreBox input').focus();
  window.setTimeout(function () {
    if (input.val()) input.select();
  }, 100);
});
$('.findMoreBox').on('click', function (e) {
  e.stopPropagation();
});
$('.findmore').on('click', function (event) {
  event.preventDefault();
  searchDo();
});
function searchDo() {
  var value = $('.findChange').val();
  if (!value) {
    return;
  }
  //var src='/search/'+value+'/page/1/type/0';
  var src = '/pc/article/search?keyword=' + value;
  window.location.href = src;
}
$('body').click(function () {
  $('.find').val(''); //////input内容置空
  $('.navItemW').show();
  $('.findMoreBox').removeClass('expandedFindMoreBox');
  $('.removeInput').removeClass('removeInput').addClass('findmore');
  $('.find').removeClass('findChange');
  $('.hotfindBox').hide();
  setTimeout(function () {
    $('.navItemW2').show();
  }, 200);
});
// 之前的叉叉改成提交
$('.findMoreBox').on('click', '.removeInput', function () {
  $(this).prev().submit();
});

// 展开全文
var startTime = new Date();
var currentFixBottomBarParent;
var ContentItemMoreClickFunc = function (e) {
  e.preventDefault();
  e.stopPropagation();
  var $this = $(this);
  var p = $this.parent();
  p.data('shortContent', p.html()); // for restore
  p.html(p.data('content') || article_content_table[p.data('id')]);
  currentFixBottomBarParent = p.parent().siblings('.articleImg').hide().parent().addClass('expanded');

  // 一开始就显示收起栏
  decideShowBar($(p).parents('.articleBox'), p[0]);

  // 保存页面位置
  var st = getBodyScrollTop();
  p.data('pos-top', st);

  // CNZZ
  var pp = p.parent();

  // 自定义用户类型
};
$('.ContentItem-more').on('click', ContentItemMoreClickFunc);
function getBodyScrollTop() {
  var el = document.scrollingElement || document.documentElement;
  return el.scrollTop;
}
function decideShowBar(p, e) {
  if (p.hasClass('expanded') && isBlockBelowInViewport(e)) {
    var left = $('.container').css('margin-left');
    p.find('.articleInfBox').addClass('is-fixed').css('left', left);
  } else {
    p.find('.articleInfBox').removeClass('is-fixed').css('left', 0);
  }
}
$(window).on('scroll', function () {
  $('.articleContent').each(function (i, e) {
    var p = $(e).parents('.articleBox');
    decideShowBar(p, e);
  });
});
function isBlockBelowInViewport(el) {
  var rect = el.getBoundingClientRect();
  return (
    // rect.top >= 0 &&
    rect.top < (window.innerHeight || document.documentElement.clientHeight) && rect.bottom > (window.innerHeight || document.documentElement.clientHeight)
  );
}
function end() {
  var endTime = new Date();
  var timeDiff = endTime - startTime; //in ms
  // strip the ms
  timeDiff /= 1000;

  // get seconds
  var seconds = Math.round(timeDiff);
  startTime = new Date();
  return seconds;
}

// 绑定收起按钮
function bindShrinkBtn($el) {
  $el.click(function () {
    var $this = $(this);
    var p = $this.parent().prev();
    var h = p.data('shortContent');
    p.html(h);
    p.find('.ContentItem-more').on('click', ContentItemMoreClickFunc);
    p.parent().siblings('.articleImg').show().parent().removeClass('expanded');
    var top = p.data('pos-top');
    if (top !== '') {
      $('html, body').animate({ scrollTop: p.data('pos-top') }, 200);
    }
    $this.parent().removeClass('is-fixed');
    $('.articleInfBox').css('left', 0);

    // CNZZ
    var pp = p.parent();
  });
}

// 首页 推荐作者 绑定是否关注
function bindIsFollow(selector) {
  $(selector).click(function (e) {
    e.preventDefault();
    followAuthor(this);
  });
  if (!_uid) {
    $(selector).each(function (i, elem) {
      $(elem).data('value', 0);
    });
    return;
  }
  var ids = $(selector).map(function (i, elem) {
    return $(elem).data('author');
  });
  $.get(
    '/pc/author/is_follow',
    { ids: Array.prototype.join.call(ids, ',') },
    function (ret) {
      $.each(ret.return_data, function (i, e) {
        var elem_ = $(selector + '[data-author=' + i + ']').data('value', e);
        if (e) {
          elem_.text('已关注').addClass('hasFollow');
        }
      });
    },
    'json'
  );
}
// 关注作者
function followAuthor(el) {
  var uid = UID;
  if (!uid) loginInit();

  // location.href='https://account.niaogebiji.com/account/login?redirect='+encodeURIComponent(location.href);
  var value = $(el).data('value');
  var author_id = $(el).data('author');
  var $this = $(el);
  $.post(
    '/pc/author/follow?author=' + author_id + '&value=' + (1 - value),
    function (ret) {
      $this.data('value', 1 - value);
      if (ret.return_code === '0') {
        if (1 - value) {
          $this.text('已关注').addClass('hasFollow');
        } else {
          $this.text('关注').removeClass('hasFollow');
        }
        let p_num = $this.parent().find('.promoteAuthorFocusNumNum');
        p_num.text(parseInt(p_num.text()) + (value ? -1 : 1));
      } else {
        alert(ret.return_msg);
      }
    },
    'json'
  );
}
// 绑定是否点赞
function bindIsUp(selector) {
  $(selector).click(function (e) {
    e.preventDefault();
    followAuthor(this);
  });
  if (!_uid) {
    $(selector).each(function (i, elem) {
      $(elem).data('value', 0);
    });
    return;
  }
  var ids = $(selector).map(function (i, elem) {
    return $(elem).data('id');
  });
  $.get(
    '/pc/article/is_up',
    { ids: Array.prototype.join.call(ids, ',') },
    function (ret) {
      $.each(ret.return_data, function (i, e) {
        var elem_ = $(selector + '[data-id=' + i + ']').data('value', e);
        if (e) {
          elem_.addClass('hasUp');
        }
      });
    },
    'json'
  );
}
// 点赞文章
function upArticle(el) {
  var value = $(el).data('value');
  var id = $(el).data('id');
  var $this = $(el);
  $.post(
    '/pc/article/up?id=' + id + '&value=' + (1 - value),
    function (ret) {
      $this.data('value', 1 - value);
      if (ret.return_code === '0') {
        if (1 - value) {
          $this.addClass('hasUp');
        } else {
          $this.removeClass('hasUp');
        }
      } else {
        alert(ret.return_msg);
      }
    },
    'json'
  );
}

var ispc = IsPC();
var words = Cookies.get('ngbjsearch');
var historywords,
  cookieWord,
  str = '';
if (ispc && words) {
  historywords = words.split(',').slice(0, 5);
  $(historywords).each(function (index, value) {
    str += '<a href="/pc/article/search?keyword=' + value + '" class="hotContent">' + value + '</a>';
  });
}
$('.historyWordBox').append(str);
$('.find').keydown(function (event) {
  var _this = this;
  var e = event || window.event;
  var keyword = $(_this).val();
  cookieWord = words ? keyword + ',' + words : keyword;
  if (e && e.keyCode == 13 && keyword != '') {
    Cookies.set('ngbjsearch', cookieWord, { expires: 365, path: '/' });
    history.replaceState(null, document.title, '/pc/article/search?keyword=' + keyword);
    location.replace('');
  }
});
$('.clearfind').click(function () {
  Cookies.remove('ngbjsearch');
  $('.historyWordBox').hide();
});
(function ($) {
  $.extend({
    Request: function (m) {
      var sValue = location.search.match(new RegExp('[?&]' + m + '=([^&]*)(&?)', 'i'));
      return decodeURI(sValue ? sValue[1] : '');
    },
    UrlUpdateParams: function (url, name, value) {
      var r = url;
      if (r != null && r != 'undefined' && r != '') {
        value = encodeURIComponent(value);
        var reg = new RegExp('(^|)' + name + '=([^&]*)(|$)');
        var tmp = name + '=' + value;
        if (url.match(reg) != null) {
          r = url.replace(eval(reg), tmp);
        } else {
          if (url.match('[?]')) {
            r = url + '&' + tmp;
          } else {
            r = url + '?' + tmp;
          }
        }
      }
      return r;
    },
  });
})(jQuery);
function formatDate(now, hms) {
  var d = new Date(now * 1000);
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  var date = d.getDate();
  var hour = d.getHours();
  var minute = d.getMinutes();
  var second = d.getSeconds();
  var data = year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
  if (!hms) {
    data = year + '-' + month + '-' + date;
  }
  return data;
}
function IsPC() {
  var userAgentInfo = navigator.userAgent;
  var Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
  var flag = true;
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
}
$('.noState').on('click', function (event) {
  event.preventDefault();
  history.replaceState(null, document.title, this.href.split('#')[0] + '#');
  location.replace('');
});

$('.back').click(function () {
  history.go(-1);
});
/*$('.mobileSearch').click(function(){
    event.preventDefault();
    history.replaceState(null, document.title, this.href.split('#')[0] + '#');
    location.replace('');
});*/

// 收藏按钮
function bindFavBtn($root, login_url) {
  var btns = $root.find('.collectJsBtn').click(function () {
    var _this = this;
    var $this = $(this);
    var title = $(this).data('title');
    var aid = $(this).data('id');

    // 重复发送会取消（这个接口竟然不幂等！
    $.ajax({
      url: '/pc/center/addfavorite/',
      dataType: 'JSON',
      data: { id: aid, title: title, type: 1 },
      success: function (res) {
        if (res.return_code == '200') {
          if ($(_this).hasClass('collected')) {
            $(_this).removeClass('collected');
          } else {
            $(_this).addClass('collected');
          }
          $('.collect').toggleClass('checked');
          $this.toggleClass('fav-done');
          toggleText($this, '收藏', '已收藏');
        } else {
          swal(
            {
              title: res.return_msg,
              type: 'warning',
              showCancelButton: true,
              confirmButtonText: '去登录',
              cancelButtonText: '取消',
              closeOnConfirm: true,
              closeOnCancel: true,
            },
            function (isConfirm) {
              if (isConfirm) {
                window.location.href = login_url;
              }
            }
          );
        }
      },
      error: function () {
        swal('网络异常');
      },
    });
  });
}
function toggleText($el, a, b) {
  if ($el.text() === a) $el.text(b);
  else $el.text(a);
}
function initFavBtn() {
  var aids = $('.collectJsBtn').map(function (i, e) {
    return $(e).data('id');
  });
  $.get(
    '/pc/article/getFav',
    { ids: Array.prototype.join.call(aids, ',') },
    function (ret) {
      if (ret.return_code !== '0') {
        alert(ret.return_msg);
      } else {
        $.each(ret.return_data, function (k, v) {
          if (v) {
            $('.collectJsBtn[data-id=' + k + ']')
              .addClass('fav-done')
              .text('已收藏');
          }
        });
      }
    },
    'json'
  );
}
function rebindArticleList($lst) {
  // bindFavBtn($lst, ACCOUNT_DOMAIN+'/account/login?redirect='+location.href);
  // 分享按钮事件绑定
  bindShareBtn($lst);
  $lst.find('.ContentItem-more').on('click', ContentItemMoreClickFunc);
  bindShrinkBtn($lst.find('.shrinkThisBtn'));
  return $lst;
}
function bindShareBtn($el) {
  $el.find('.shareThis').click(function (e) {
    e.stopPropagation();
    var left = $('.shareThis').offset().left - $('.shareThis').parent().offset().left - $(this).width() / 2 - 20;
    $(this).next().css('left', left).toggle();

    var pp = $(this).parents('.article');
  });
}
