/**(2009-4-22)
 * @requires jQuery v1.2+
 *
 * 
 */
(function($){
	var requestUrl = "service/s_Vote_post.php";
	var options = {
		max: 18,
		file: "fashionlove_090602",
		ctime: 0
	};
	var total = [];
	
	function getArray(data, type){
		var result = [], count = 0;
		if (!data) 
			return 0;
		
		data = data.split(",");
		count = type == 0 ? 0 : (type == 1 ? 6 : 12);
		total[type] = 0;
		for (var i = 0 + count; i < 6 + count; i++) {
			result[i - count] = data[i];
			total[type] = total[type] + parseFloat(data[i]);
		}
		return result;
	}
	function getRatio(data, type, i){
		return total[type] == 0 ? 0 : Math.round((parseFloat(data[i]) / total[type]) * 100);
	}
	function setVote(btn, div, type){
		var span = $("span", div), em = $("em", div);
		var index = $(".btn", div).index(btn);
		var texts = [];
		em.each(function(i){
			texts[i] = $(this).text();
		});
		index = type == 0 ? index : (type == 1 ? index + 6 : index + 12);
		$(span).addClass("loading").find("em").text("");
		
		$("#c3 .btn").attr("disabled", "disabled");
		options.o = index;
		$.post(requestUrl, options, function(data){
			if (data == "voted") {
				$(span).removeClass("loading").find("em").each(function(i){
					$(this).text(texts[i]);
				});
				alert("您已经投过票了！");
				$("#c3 .btn").removeAttr("disabled");
				return;
			}
			var votes = getArray(data, type);
			setTimeout(function(){
				showVote(span, votes, type);
				$("#c3 .btn").removeAttr("disabled");
			}, 5000);
		});
	}
	function showVote(span, votes, type){
		$(span).each(function(i){
			var num = votes == 0 ? 0 : getRatio(votes, type, i);
			$(this).removeClass("loading").find("em").text(num + "%");
		});
	}
	
	//load
	$(function(){
		$("#c1-2 span:odd").css({
			background: "#8A535C",
			color: "#FAB"
		});
		$(".poll span").addClass("loading");
		
		$("#c3 .btn").attr("disabled", "disabled");
		$.post(requestUrl, options, function(data){
			var votes = [];
			setTimeout(function(){
				$("#c3 .list").each(function(i){
					votes[i] = getArray(data, i);
					showVote($(this).find("span"), votes[i], i);
				});
				$("#c3 .btn").removeAttr("disabled");
			}, 500);
		});
		
		$("#c3-1 .btn").bind("click", function(){
			setVote($(this), $("#c3-1"), 0);
		});
		$("#c3-2 .btn").bind("click", function(){
			setVote($(this), $("#c3-2"), 1);
		});
		$("#c3-3 .btn").bind("click", function(){
			setVote($(this), $("#c3-3"), 2);
		});
	});
})(jQuery);

