var loding_img = '<img src="/common/img/ajax_loading.gif" alt="now loading" class="loading"/>';

$(function(){

  $('a.applause img').load(function(){

    var id = $(this).parent().get(0).id.split("-").pop();
    if($.cookie('entry_'+id)){
        $($(this).parent().get(0)).html(desableBtn($(this)))
    }
  })

})

function getCookieLimit(){
var date=new Date();
date.setTime(date.getTime()+(30*60*1000));
return date;
}

/*
 * 拍手システム
 */

function desableBtn(elm){

  //var h = elm.height();
  //var w = elm.width();

  //elm.attr('src',"/common/img/btn_applause.gif");
  //elm.attr('width',w);
  //elm.attr('height',h);
  var file = elm.attr('src').split("/").pop();
  var img = '<img src="/common/img/'+ file +'" alt="投票済" class="btn"/>';
  return img;
}

function entryVote(n,cat){

if (!navigator.cookieEnabled){
alert("投票するにはクッキーを有効にして下さい。");
return;
}

$('#applause-'+n+' > img').each(function(){
  //desableBtn($(this));
  $($(this).parent().get(0)).html(desableBtn($(this)));
});

if($.cookie('entry_'+n)){
alert("すでに投票済みです。連続投票はできません。");
return;
}

$.cookie('entry_'+n,1,{ expires: getCookieLimit() });
$.ajax({
	type: "post",
	url: "http://sanka.pal-system.co.jp/cgi-bin/mt/mt-vote.cgi",
	data: "entry_id="+n+"&value=1&__mode=vote",
	success: function(msg){
		if(msg == "Vote posted"){ 
			updateEntryTotalVotes(n);
			updateCategoryTotalVotes(cat);
			updateVotesRankList(6);
		};
	}
});

$.each( $(".vote-total-"+n),function(){ $(this).html(loding_img) });

}

function updateEntryTotalVotes(n){

$.ajax({
	type: "get",
	url: "http://sanka.pal-system.co.jp/shouhin/vote.php",
	data: "id="+n,
	success: function(msg){
		$.each( $(".vote-total-"+n),function(){ $(this).html(Number(msg)) });
	}
});

}


function updateCategoryTotalVotes(cat){
$.ajax({
	type: "get",
	url: "http://sanka.pal-system.co.jp/shouhin/vote.php",
	data: "cat="+cat,
	success: function(msg){
		$(".vote-total-cat-"+cat).html(Number(msg));
	}
});
}

function updateVotesRankList(){
$.ajax({
	type: "get",
	url: "http://sanka.pal-system.co.jp/shouhin/vote.php",
	data: "rank="+6,
	success: function(msg){
		$(".ranking").html(setRankList(msg));
	}
});
}


function setRankList(json){

var html="";
var arr = eval(json);

arr.pop();
arr.sort(function(a, b) {return b.votes-a.votes});

var len = arr.length > 5 ? 5 : arr.length;

for(var i=0; i<len; i++){
  html += '<li class="rank'+(i+1)+'"><a href="'+ arr[i].url +'">'+ arr[i].name +'（'+ arr[i].votes +'拍手）</a></li>';
}


return html;
}
