$(function(){
  var centerLeft = $(window).width() / 2;//$('#content').width() / 2 - 150;
  var document_body = $(document.body);
  var isMouseOn = false;
  var doneList = null;
  
  function imgMouseOverFunc(e) {
    isMouseOn = true;
    var img = $(this);
    if (!img.data('mid')) {
      var y = e.pageY + document_body.scrollTop();
      makeTooltip({
        id: img.data('id'),
        src: img.data('mid_path'),
        title: img.attr('alt'),
        y: y <= 300 ? y + 30 : y - 300,
        width: img.data('mid_width'),
        height: img.data('mid_height'),
        img: img
      }).show(100);
      $('img.photo-tooltip').each(function(i, v) {
        if (!isMouseOn) return; 
//        var opacity = i == img.data('num') ? 1 : i - 1 == img.data('num') || i + 1 == img.data('num') ? 0.4 : 0.1;
        var sa = Math.abs(i - img.data('num'));
        var opacity = sa < 4 ? (4 - sa) / 7 : 0;
        $(this).css({
          opacity: opacity
        });        
      }); 
    }
  }
  
  function imgMouseOutFunc(e) {
    isMouseOn = false;
    var img = $(this);
    if (img.data('mid')) {
      img.data('mid').hide(150, function(){
        $(this).remove();
        if (!isMouseOn) {
          $('img.photo-tooltip').css({opacity: 1});
//          $('img.photo-tooltip').each(function() {
//            $(this).animate({opacity: 1}, 150);
//          });      
        }
      });
      img.removeData('mid');        
    }
  }
  
  function makeTooltip(opt) {
    var tooltip = $(document.createElement('div')).addClass('photo-tooltip').attr({
      id: 'photo_tooltip_'+ opt.id
    }).append(
      $(document.createElement('img')).attr({src: opt.src, alt: opt.title}).width(opt.width).height(opt.height).css({
        display: "block",
        margin: "auto"
      })
    ).append(
      $(document.createElement('h4')).addClass('title').text(opt.title)
    ).css({
      top: opt.y, 
      left: $(window).width() / 2 - opt.width / 2, 
      width: Number(opt.width) + 20,
      height: Number(opt.height) + 20,
      position: 'absolute' 
    }).hide();
    opt.img.data('mid', tooltip);
    document_body.append(tooltip);   
    return tooltip; 
  }
  
  function permaImgById(id) {
    $('#outside').remove();
    $('img.photo-tooltip').css({opacity: 1});
    if (id.length == 0) {
      $('div.photo-tooltip').remove();
      if (!isSmartPhone()) $('img.photo-tooltip').mouseover(imgMouseOverFunc).mouseout(imgMouseOutFunc);
    } else if (!id.match(/^\d+$/)){
      document.location.hash = '';
    } else {
      $('div.photo-tooltip').each(function(){
        if ($(this).attr('id').match(/(\d+)$/) && RegExp.$1 != id) $(this).remove();
      });
      $('img.photo-tooltip').removeData('mid');
      if (!isSmartPhone()) $('img.photo-tooltip').unbind('mouseover', imgMouseOverFunc).unbind('mouseout', imgMouseOutFunc);
      var tooltipImg = $('#photo_'+ id);
      if (tooltipImg.length == 0) {
        var articleInfo = getArticleInfoFromRemote(id);
        if (articleInfo) {
          tooltipImg = $(document.createElement('div')).data('img_width', articleInfo.media.img.width)
            .data('img_height', articleInfo.media.img.height)
            .data('img_path', articleInfo.media.img.media_path)
            .data('good_score', articleInfo.good_score)
//            .data('good_is_done', String(articleInfo.good_is_done ? 1 : 0))
            .data('updated_at', articleInfo.updated_at)
            .data('content', articleInfo.content)
            .data('alt', articleInfo.title)
            .data('id', id);        
        } else {
          document.location.hash = '';
          return;
        }
      }
      var tooltip = $('#photo_tooltip_'+ id);
      if (tooltip.length == 0) {
        tooltip = makeTooltip({
          id: id,
          src: tooltipImg.data('img_path'),
          title: tooltipImg.attr('alt'),
          y: 0,
          width: 0,
          height: 0,
          img: tooltipImg
        });
      }
      permaImgByOpt({
        img_width: tooltipImg.data('img_width'),
        img_height: tooltipImg.data('img_height'),
        img_path: tooltipImg.data('img_path'),
        good_score: tooltipImg.data('good_score'),
//        good_is_done: tooltipImg.data('good_is_done'),
        updated_at: tooltipImg.data('updated_at'),
        content: tooltipImg.data('content'),
        id: tooltipImg.data('id'),
        tooltip: tooltip,
        title: tooltipImg.attr('alt')
      });
      if (typeof pageTracker != 'undefined') {
        pageTracker._trackPageview('/photo#'+ id);
      }
      $.history.load(id);
    }
  }
    
  function permaImgByOpt(opt) {
    var outside = makeOutside(opt.id);
    opt.tooltip.before(outside).animate({
      top: 0,
      left: $(window).width() / 2 - opt.img_width / 2,
      width: Number(opt.img_width) + 20,
      height: Number(opt.img_height) + 100,
      padding: 10
    }, 150);
    outside.exFixed();

    var nextAndPrev = getNextAndPrevTooltip(opt.id);

    $('img:first', opt.tooltip).attr(
      {src: opt.img_path}
    ).animate({
      width: opt.img_width,
      height: opt.img_height
    }, 70//).after(
//      $(document.createElement('p')).addClass('good_score').attr({id: 'good_score_'+ opt.id}).text(
//        getScoreText(Number(opt.good_score))
//      )
    ).click(function(tooltip, nx){
      return function() {
        tooltip.remove();
        document.location.hash = nx ? nx.data('id') : '';
      };
    }(opt.tooltip, nextAndPrev.next)).before(prevAndNextLink(nextAndPrev.prev ? nextAndPrev.prev.data('id') : null, nextAndPrev.next ? nextAndPrev.next.data('id') : null));
    opt.tooltip.append(opt.content).append(makeItemFooter(opt));
    gapi.plusone.go('photo_tooltip_'+ opt.id);
    outside.click(closeMax); 
  }
  
  function closeMax(delay) {
    if ($('div.photo-tooltip').length > 0) {
//      $('img.photo-tooltip').mouseover(imgMouseOverFunc).mouseout(imgMouseOutFunc);
      $('div.photo-tooltip').hide(300, function () {
        $('img.photo-tooltip').css({opacity: 1});
        $('#outside').remove();
        $(this).remove;
        document.location.hash = '';
      });
    }
  }
  
  function prevAndNextLink(prev, next) {
    var res = $(document.createElement('ul')).addClass('prev-and-next-link');
    if (prev) {
      res.append(
        $(document.createElement('li')).append(
          $(document.createElement('a')).attr({
            href: '#'+ prev
          })
          .text('prev')
          .click(removeAllTooltip)
        )
      );
    } else {
      res.append($(document.createElement('li')).append('prev'));
    }
    res.append(
      $(document.createElement('li')).append(
        $(document.createElement('a')).attr({
          href: '#'
        })
        .text('close')
        .click(removeAllTooltip)
      )
    );
    if (next) {
      res.append(
        $(document.createElement('li')).append(
          $(document.createElement('a')).attr({
            href: '#'+ next
          })
          .text('next')
          .click(removeAllTooltip)        
        )
      )    
    } else {
      res.append($(document.createElement('li')).append('next'));
    }  
    return res
  }
  
  function removeAllTooltip() {
    $('div.photo-tooltip').remove();
  }
  
  function getArticleInfoFromRemote(id) {
    var res = null;
    $.ajax({
      url: '/article_info/photo/'+ id + '.js',
      success: function(data) {
        if (data.article_id) res = data;
      },
      error: function() {
        alert('エラーが発生しました');
      },
      async: false,
      dataType: 'json'          
    });
    return res;
  }
  
  function getNextAndPrevTooltip(id) {
    var prev = null;
    var next = null;
    var isNowDone = false;
    $('img.photo-tooltip').each(function(){
      if ($(this).data('id') == id) {
        isNowDone = true;
      } else if (isNowDone) {
        next = $(this);
        return false;
      } else {
        prev = $(this);
      }
    });
    if (!isNowDone) prev = null;
    return {next: next, prev: prev};
  }
  
  function makeOutside(id) {
    return $(document.createElement('div')).width($(window).width()).height($(window).height()).attr({
      id: 'outside'
    }).css({
      width: 3333,
      height: 3333
    }).append(
      $(document.createElement('a')).attr({name: id})
    );  
  }
  
  function makeGoodBtn(opt) {
    return $(document.createElement('input')).attr({
      type: 'button', id: 'good_button_'+ opt.id, value: GOOD_BTN_MSG
    }).addClass('good_button').click(function(id){
      var img = $('#photo_'+ id);
      return function() {
        goodButtonClickFunc.call(this);
        if (img.length > 0) {
          img.data('good_score', Number(img.data('good_score')) + 1);
          doneList[id] = true;
        }
      }
    }(opt.id));
  }
  
  function makeItemFooter(opt) {
    var permaUrl = '/photo/'+ opt.id + '/';
    var res = $(document.createElement('p')).css({textAlign: 'right'}).addClass('item-footer');
    appendTweetButton(res, permaUrl, "k456 #photo "+ opt.title);
    appendPlusOneButton(res, permaUrl);
//    if (doneList && !doneList[opt.id]) {
////      res.append(
////        makeGoodBtn(opt)
////      ).append($(document.createElement('br')));   
//      res.append($(document.createElement('br')));   
//    } else if (!doneList) {
//      getDoneList(
//        function(re, op) {
//          return function(list) {
//            doneList = list;
//            if (!doneList[op.id]) {
////              re.prepend(
////                makeGoodBtn(op).after($(document.createElement('br')))
////              );
//              re.prepend(
//                $(document.createElement('br'))
//              );
//            }
//          };
//        }(res, opt),
//        function() {}
//      );
//    }
    res.append($(document.createElement('br'))).append('updated_at: '+ opt.updated_at).append(
      $(document.createElement('br'))
    ).append(
      $(document.createElement('a')).attr({href: permaUrl}).text('Permalink')
    );
    return res;
  }
  
  $('img.photo-tooltip').each(function(i, img) {
    var img = $(img);
    $('span.img_info', img.parent()).each(function(i,span) {
      span = $(span);
      var key = span.attr('class').replace(/(img_info|\s)/g, '');
//      var key = span.hasClass('img_path') ? 'img_path' : 
//        span.hasClass('mid_path') ? 'mid_path' : 
//        span.hasClass('content') ? 'content' : 
//        span.hasClass('good_score') ? 'good_score' : 
//        span.hasClass('img_width') ? 'img_width' : 
//        span.hasClass('img_height') ? 'img_height' : 
//        span.hasClass('mid_width') ? 'mid_width' : 
//        span.hasClass('mid_height') ? 'mid_height' : 
//        span.hasClass('updated_at') ? 'updated_at' : 
//        null;
      if (key) img.data(key, span.text());
      span.remove();
    });
    img.data('num', i);
    if (img.attr('id').match(/(\d+)$/)) {
      img.data('id', RegExp.$1);
    }
    if (img.attr('title').length > 0) img.removeAttr('title');
  });
  $.history.init(permaImgById);  
});
