var image_loading = base_url + topdir + '/images/nikurabe_loading.gif';
var image_loading_w = '280px';
var image_loading_h = '210px';

function initPage()
{
  // bind clicking the object to registering the click as a vote
  $("#obj1link > a").bind("click", function(){chooseOption($(this)); return false; });
  $("#obj2link > a").bind("click", function(){chooseOption($(this)); return false; });

  if($('.nik-single > a').size() >= 1) // okay to vote, so show hover effect
  {
    $('.nik-single').hover(
      function(){
        $(this).children('*:first-child').addClass('thisone');
        $(this).children('a:first-child').children().addClass('thisone');
      },
      function(){
        $(this).children('*:first-child').removeClass('thisone');
        $(this).children('a:first-child').children().removeClass('thisone');
      });
  }

  // initialize slider
  $('.nikslider').slideNews();

  // assign onclicks to slider item divs
  setSliderClicks();

  // hide comment submit button after clicked once ...
  $('#comment-button').click(function(){submitComment();});

  // replace video tags with correct <object> html
  $('.media').media( {width: 280, height: 210, type:'swf' });
}

function chooseOption(optionHref)
{
  // remove hovers; .unbind('hover') doesn't work correctly, apparently
  $(".nik-single").unbind('mouseover').unbind('mouseout');

  // if there's a child element of the href, we must be dealing with
  // an img tag; otherwise, must be a video type
  if($(optionHref).children().size() > 0)
  {
    $(optionHref).children().addClass('thisone');
    $(optionHref).addClass('thisone');
  }
  else
  {
    $(optionHref).siblings('div').addClass('thisone');
  }

  var pairId = $("#pairId").val();
  var oId = $(optionHref).attr("id");
  var oColumn = $(optionHref).attr("name");

  $("input[@id=objId]").attr("value", oId);
  $("input[@id=column]").attr("value", oColumn);
  
  $.post( topdir + "/nikurabe/aj_setChoice",
          {pairId: pairId, objId: oId, column: oColumn},
          function(data) {processOption(data);}
        );
  
  // remove onlick events so user can't choose stuff any more
  // have to unbind, then bind a different function; they don't overwrite
  $("#obj1link > a").unbind("click");
  $("#obj2link > a").unbind("click");
  $("#obj1link > a").bind("click", function(){return false; });
  $("#obj2link > a").bind("click", function(){return false; });
}

function processOption(jsondata)
{
  var data = eval('('+jsondata+')');
  
  if(data.result == 0) // must be logged in to comment
  { eval(data.error); }
  else
  {
    // nikurabe may have been ajax-loaded, and a comment may have
    // previously been submitted, in which case the submit button
    // was hidden ...
    $('#comment-loading').css('display', 'none');
    $('#comment-button').css('display', 'inline');

    // if revealComments == 1, it was previously hidden
    // so we must first hide the message
    if(data.revealcomments == 1)
    {
      $("#vdlater").slideUp("normal", 
        function(){
          $("#obj1voters").empty();
          $("#obj2voters").empty();
          $("#commentbox").slideDown("normal",
            function(){
              showVoteData(data);
            });
        });
    }
    else
    {
      // create html to insert
      var vdata = data.votedata;
      var html = '<a href="'+vdata.userlink+'" ><img src="'+vdata.avatar+'" class="avatar" alt="'+vdata.nickname+'" /></a>';
      
      // update vote data scale
      var obj = '#obj'+vdata.column;
      var otherdiv = $('#obj'+(3 - vdata.column)+'voters');
      var vdatadiv = $(obj+'voters');
      var vcount = parseInt($(obj+'votecount').text()) + 1;
      $(obj+'votecount').text(vcount.toString());
      
      var vdatarows = vdatadiv.children('.voteresult');
      var emptyrows = vdatadiv.children('.emptyrow');
      
      // if first div is not full, insert; if full, create a new div (row)
      if(vdatarows.size() > 0)
      {
        if(vdatarows.filter(':first').children('a').size() < 8)
        {
          vdatarows.filter(':first').prepend(html);
        }
        else
        {
          if(emptyrows.size() > 0)
          {
            emptyrows.filter(':last').prepend(html).removeClass('emptyrow').addClass('voteresult');
          }
          else
          {
            html = '<div class="voteresult">' + html + '</div>';
            vdatarows.filter(':first').before(html);
            // add new empty row to other side to align correctly
            otherdiv.children('p').after('<div class="emptyrow" style="height: 30px;"></div>');
          }
        }
      }
      else
      {
        if(emptyrows.size() > 0)
        {
          emptyrows.filter(':last').prepend(html).removeClass('emptyrow').addClass('voteresult');
        }
        else
        {
          html = '<div class="voteresult">' + html + '</div>';
          vdatadiv.children('p').after(html);
          // add new empty row to other side to align correctly
          otherdiv.children('p').after('<div class="emptyrow" style="height: 30px;"></div>');
        }
      }
      
      $("#commentbox").slideDown("normal");
    }
  }
}


function submitComment()
{
  // users must be logged in to comment; 
  // this validation should already have been done
  
  var comment = $.trim($("textarea[@name=commentarea]").val());

  if(comment.length > 0)
  {
    $('#comment-button').fadeOut('fast', function(){
      $('#comment-loading').fadeIn('normal'); });

    $.post( topdir + "/nikurabe/aj_comment",
            { objId: $("input[@id=objId]").val(),
              comment: comment,
              objColumn: $("input[@id=column]").val()
              }, 
            function(data) {showNewComment(data);}
          );
  }
  else
  {
    // XXX: what should we do?
  }
}


function showNewComment(jsondata)
{
  var data = eval('('+jsondata+')');  

  var link = '<li id="nc" style="display:none;"><a href="'+data.userlink+'">';
  var img = '<img src="'+data.avatar+'" class="avatar" /></a>';
  var comment = '<p>' + data.comment + '</p>';
  var nickname = '<p class="small"><a href="'+data.userlink+'">'+data.nickname+'</a></p></li>';

  var elem = "#obj"+data.column+"comments";
  
  // we also clear the comment box since if user loads a new nikurabe,
  // content otherwise remains... 
  $("#commentbox").slideUp("slow", 
    function(){ $(elem).prepend(link + img + comment + nickname);
                $("#nc").slideDown("normal");
                $("textarea[@name=commentarea]").val('');
                 });
}


/* AJAX call to get new nikurabe */
function getNewNikurabe()
{
  var loading_html = '<div class="nik-option"><img src="'+image_loading+'" width="'+image_loading_w+'" height="'+image_loading_h+'" /></div>';
  $('#curniktitle').empty().prepend('&nbsp;');
  $('#creatornickname').empty().prepend('&nbsp;');
  $('#obj1link').empty().prepend(loading_html);
  $('#obj2link').empty().prepend(loading_html);
  
  var pairId = $("#pairId").val();
  
  $.post( topdir + "/nikurabe/aj_getNikurabe",
          { pairId: pairId },
          function(data) {showNewNikurabe(data);}
        );

  if($('#commentbox').css('display') != 'none')
  {
    $('#commentbox').slideUp('normal');
  } 
}

/* edit DOM to show new Nikurabe */
function showNewNikurabe(jsondata)
{ 
  var data = eval('('+jsondata+')');
  
  if(data.result == 0) // nik was removed
  { eval(data.error); window.location.reload(true); }
  else
  { 
    $("#curniktitle").empty();
    $("#curniktitle").prepend(data.niktitle);
  
    $("#creatornickname").empty();
    $("#creatornickname").prepend(data.creatornickname);

    /*** for object 1 ***/
  
    if(data.obj1type == 'video')
    {
      var media_link1;
      var choose_link1;
      if(data.votedObjId != false)
      {
        if(data.votedObjId == data.obj1id)
        { media_link1 = '<a class="media nik-option thisone" href="'+data.obj1val+'"></a>'; }
        else
        { media_link1 = '<a class="media nik-option" href="'+data.obj1val+'"></a>'; }
      
        choose_link1 = '';
      }
      else
      {
        media_link1 = '<a class="media nik-option" href="'+data.obj1val+'"></a>';
        choose_link1 = '<a href="#" class="btn-video" name="1" id="'+data.obj1id+'"></a>';
      }
    
      $("#obj1link").empty().append(media_link1);
      $("#obj1link > .media").media({ width: 280, height: 210, type:'swf' });
      $("#obj1link").append(choose_link1);
      $("#obj1link > a").append('こっちがいい！');
    }
    else
    {
      var img_link1;
      var choose_link1;
      if(data.votedObjId != false)
      {
        if(data.votedObjId == data.obj1id)
        { img_link1 = '<div class="nik-option thisone"><img src="'+data.obj1val+'" width="'+data.obj1w+'" height="'+data.obj1h+'" class="thisone" /></div>';
        }
        else
        { img_link1 = '<div class="nik-option"><img src="'+data.obj1val+'" width="'+data.obj1w+'" height="'+data.obj1h+'" /></div>';
        }
      
        $("#obj1link").empty().append(img_link1);
      }
      else
      {
        img_link1 = '<img src="'+data.obj1val+'" width="'+data.obj1w+'" height="'+data.obj1h+'" />';
        choose_link1 = '<a href="#" name="1" id="'+data.obj1id+'"></a>';
        $("#obj1link").empty().append(choose_link1);
        $("#obj1link > a").append(img_link1);
      }
    }
  
    /*** now for object 2 ***/
  
    if(data.obj2type == 'video')
    {
      var media_link2;
      var choose_link2;
      if(data.votedObjId != false)
      {
        if(data.votedObjId == data.obj2id)
        { media_link2 = '<a class="media nik-option thisone" href="'+data.obj2val+'"></a>'; }
        else
        { media_link2 = '<a class="media nik-option" href="'+data.obj2val+'"></a>'; }

        choose_link2 = '';
      }
      else
      {
        media_link2 = '<a class="media nik-option" href="'+data.obj2val+'"></a>';
        choose_link2 = '<a href="#" class="btn-video" name="2" id="'+data.obj2id+'"></a>';
      }

      $("#obj2link").empty().append(media_link2);
      $("#obj2link > .media").media({ width: 280, height: 210, type:'swf' });
      $("#obj2link").append(choose_link2);
      $("#obj2link > a").append('こっちがいい');
    }
    else
    {
      var img_link2;
      var choose_link2;
      if(data.votedObjId != false)
      {
        if(data.votedObjId == data.obj2id)
        { img_link2 = '<div class="nik-option thisone"><img src="'+data.obj2val+'" width="'+data.obj2w+'" height="'+data.obj2h+'" class="thisone" /></div>';
        }
        else
        { img_link2 = '<div class="nik-option"><img src="'+data.obj2val+'" width="'+data.obj2w+'" height="'+data.obj2h+'" /></div>';
        }
        $("#obj2link").empty().append(img_link2);
      }
      else
      {
        img_link2 = '<img src="'+data.obj2val+'" width="'+data.obj2w+'" height="'+data.obj2h+'" />';
        choose_link2 = '<a href="#" name="2" id="'+data.obj2id+'"></a>';
        $("#obj2link").empty().append(choose_link2);
        $("#obj2link > a").append(img_link2);
      }
    }
  
    /** finished creating and inserting new links for objects **/
  
    // clear and load comments and vote count data (if allowed) 
    $("#obj1comments").slideUp("normal", function(){$("#obj1comments").empty();});
    $("#obj2comments").slideUp("normal", function(){$("#obj2comments").empty();});
    $("#obj1voters").slideUp("normal", function(){$("#obj1voters").empty();});

    // due to internal clock/timing, don't process showVoteData until
    // last of voterdata related elements has completed emptying
    $("#obj2voters").slideUp("normal",
      function(){
        $("#obj2voters").empty();
        if(data.revealComments == 1)
        {
          $("#vdlater").slideUp("fast");
          showVoteData(data.vdarray);
        }
        else
        {
          $("#vdlater").slideDown("fast");
        };
      });
  
    // re-assign onclicks; works b/c if alreadyVoted is true, there won't be an <a> tag
    $("#obj1link > a").bind("click", function(){chooseOption($(this)); return false; });
    $("#obj2link > a").bind("click", function(){chooseOption($(this)); return false; });
  
    // re-assign hovers if there are <a> tags; there will only be <a> tags if
    // user is allowed to vote for this pair
    if($('.nik-single > a').size() >= 1)
    {
      $('.nik-single').hover(
        function(){
          $(this).children('*:first-child').addClass('thisone');
          $(this).children('a:first-child').children().addClass('thisone');
        },
        function(){
          $(this).children('*:first-child').removeClass('thisone');
          $(this).children('a:first-child').children().removeClass('thisone');
        });
    }
    else
    {
      // need to otherwise unbind
      $('.nik-single').unbind('mouseover').unbind('mouseout');
    }

    // remember to update any and all links related to a nikurabe pair!!
    $('#widgeturl').attr('href', data.widgeturl); 
  
    // reset hidden objId and column
    $("input[@id=objId]").attr("value", '');
    $("input[@id=column]").attr("value", '');
    
    // let user reload current 2kurabe but with id in the URL
    $(".nikstrip > div:eq(2)").click( function(){
      window.location.href = topdir+'/display/'+$("#pairId").val();
    });
    
    // tell urchin tracker
    var url = '/display/' + $("#pairId").val();
    urchinTracker(url);
  }
}

function getVoteData()
{
  var pairId = parseInt($('a[@name=vdata]').attr('id'));
  $.post( topdir + "/nikurabe/aj_getVoteData",
          { pairId: pairId },
          function(data) {extractVoteData(data);}
        );
}

function extractVoteData(jsondata)
{
  var data = eval('('+jsondata+')');
  if(data.result == 0) // nik was removed
  { eval(data.error); window.location.reload(true); }
  else
  {
    showVoteData(data);
  }
}

/* edit DOM to show comment / voter data */
function showVoteData(data)
{
  var obj1Comments = data.comments.obj1Comments;
  var obj2Comments = data.comments.obj2Comments;

  var voters = data.votedata;
  
  for(i = 0; i < obj1Comments.length; i++)
  {
    comment = obj1Comments[i];
    url = '<li><a href="'+data.user_url+comment.userId+'">';
    url += '<img src="'+comment.userAvatarMini+'" class="avatar" /></a>';
    url += '<p>'+comment.comment+'</p>';
    url += '<p class="small"><a href="'+data.user_url+comment.userId+'">';
    url += comment.userNickname+'</a></p></li>';
    $("#obj1comments").append(url);
  }
  
  for(i = 0; i < obj2Comments.length; i++)
  {
    comment = obj2Comments[i];
    url = '<li><a href="'+data.user_url+comment.userId+'">';
    url += '<img src="'+comment.userAvatarMini+'" class="avatar" /></a>';
    url += '<p>'+comment.comment+'</p>';
    url += '<p class="small"><a href="'+data.user_url+comment.userId+'">';
    url += comment.userNickname+'</a></p></li>';
    $("#obj2comments").append(url);
  } 

  $('#obj1voters').append(voters.obj1voters);
  $('#obj2voters').append(voters.obj2voters);
    
  $("#obj1voters").prepend('<p id="obj1votecount">'+voters.obj1vc+'</p>');
  $("#obj2voters").prepend('<p id="obj2votecount">'+voters.obj2vc+'</p>');
  
  $("#obj1comments").slideDown("normal");
  $("#obj2comments").slideDown("normal");
  $("#obj1voters").slideDown("normal");
  $("#obj2voters").slideDown("normal");
  
  setAnalyticsClicks('#obj1comments');
  setAnalyticsClicks('#obj2comments');
}




/****** AJAX / DOM functions for scroll strip ******/

// WARN: if you change newsWidth in slider.js, change these values too
var nikItemWidth = 190;

/* preload nikurabes on edges of scrolling strip
 *
 * this function is called by the accessible-slider script.
 */
function prefillNikurabe(jsondata)
{
  var data = eval('('+jsondata+')');
  var newItem = '';
  
  if(data.nikid != 'blank')
  {
    newItem = '<div class="nikstripitem" id="'+data.nikid+'"><h3 class="nikstriptitle">'+data.niktitle+'</h3>';
    newItem += '<div class="nikstrippair">';
  }
  else
  {
    newItem = '<div class="nikstripitem-blank"><h3 class="nikstriptitle-blank"></h3>';
    newItem += '<div class="nikstrippair-blank">';
  }

  newItem += '<img src="'+data.obj1val+'" width="'+data.obj1w+'" height="'+data.obj1h+'"/>';
  newItem += '<img src="'+data.obj2val+'" width="'+data.obj2w+'" height="'+data.obj2h+'"/>';
  newItem += '</div></div>';    
  
  if(data.direction == 'next')
  {
    $(".nikstrip > div:first").remove();

    // move left pos back to original pos
    newLeft = 0 - nikItemWidth;
    $(".nikstrip").css("left", newLeft + "px");
    $(".nikstrip").append(newItem);
  }
  else if(data.direction == 'prev')
  {
    $(".nikstrip > div:last").remove();
    
    // move left pos back to original pos
    newLeft = 0 - nikItemWidth;
    $(".nikstrip").css("left", newLeft + "px");
    $(".nikstrip").prepend(newItem);
  }
  else
  {
    alert('エラー発生。開発者へのご連絡をお願いします。');
  }
  
  // used by jquery.accessible-slider.js
  g_animating = false;
  
  setSliderClicks();
}

function setSliderClicks()
{
  $('.nikstripitem').css('cursor', 'pointer');

  // assign clicks to nik-slider items
  $('.nikstripitem').click(function(){
    var prev = $('.nikstrip > div:eq(1)');
    var next = $('.nikstrip > div:eq(3)');
    if($(this).attr('id') == prev.attr('id')){ $('.prev').click(); }
    else if ($(this).attr('id') == next.attr('id')){ $('.next').click(); }
    else { /* do nothing */ }
  });
  
  // remove prev / next if need be
  if($('.nikstrip > div:eq(1)').attr('class') == 'nikstripitem-blank')
  { $('.prev').hide(); }
  else
  { $('.prev').show(); }
  
  if($('.nikstrip > div:eq(3)').attr('class') == 'nikstripitem-blank')
  { $('.next').hide(); }
  else
  { $('.next').show(); }

}

$(function(){ initPage(); });