$(function() {
    var yosou = {};
    var yosou_url = "yosou/api/top";
    function getYosou()
    {
      $.ajax({
        url: yosou_url,
        type: "GET",
        dataType: "json",
        timeout: 5000,
        error: function() {},
        success: function(data) {
          if (data.result) {
            yosou = data.race;
            drawYosou();
          }
        }
      });
    }

    function drawYosou()
    {
        var tpl = $("#yosou-row").text();
        var tr = $("#yosou table tbody tr").each(function(i) {
          var val = yosou.rank[i+1];
          $("th span", this).attr("id", "rank" + val.rank).text(val.horse);
          $("td span.n", this).text(val.vote).after("<span>票</span");
          $("td.odds span", this).text(val.odds + "倍");
        });
        $("#yosou-race")
          .text("「" + yosou.race.name + "（" + yosou.race.grade + "）」")
          .show();
        $("#yosou table").show();

        effectYosou();
    }

    function effectYosou()
    {
      var maxBar = 160;

      $( '#yosou table tr:odd' ).addClass( 'oddline' );
      $( '#yosou table tr:even' ).addClass( 'evenline' );

      var voteArray = new Array();
      $( '#yosou table span.n' ).each( function( idx ) {
          voteArray.push( Number( $( this ).text() ) );
      });
      var maxVote = Math.max.apply( null, voteArray );
      var rateVote = maxBar / maxVote;
      $( '#yosou table span.n' ).each( function( idx ) {
          var vote = Number( $( this ).text() );
          var barWidth = Math.ceil( vote * rateVote );
          $( this ).text( '' ).css( {'width':barWidth + 'px', 'height':'18px', 'display':'block', 'background':'#fa4d51' }).attr( 'title', vote + '票' );
          $( '+ span', this ).hide();
      });
    }
    getYosou();
});
