﻿function jsVote(opt) {
	var q = 'dt=vote&po_id=' + $(opt).attr('opt_id');
	$.getJSON("/services/process.aspx", q, function (data) {
		var newCnt = parseInt($(opt).attr('votecnt')) + 1;
		$(opt).attr('votecnt', newCnt).next().attr('votecnt', newCnt);
		$('#poll > #question').attr('total_vote', parseInt($('#poll > #question').attr('total_vote')) + 1);
		jsSetVoteResultBar();

		jsSaveVoteHist($(opt).attr('q_id'), $(opt).attr('opt_id'));
		$(opt).addClass('voted');
		$('#poll > #options .handle').unbind('click').addClass('dim');
	});
}

function jsLoadPoll() {
	var q = "dt=poll";
	$.getJSON("/services/query.aspx", q, function (data) {
		if ($(data).length > 0) {
			var qu = data[0];
			$('#poll > #question').attr('q_id', qu.polling_id).append(qu["question_" + _711.language]);
			var vote_hist = jsGetVoteHist(qu.polling_id);

			q = "dt=pollopt&q_id=" + qu.polling_id;
			$.getJSON("/services/query.aspx", q, function (data) {

				var dl = $("<table width='100%' id='poll_list' cellspacing='0' cellpadding='0' border='0'></table>");
				var total_vote = 0;
				$.each(data, function (i, o) {
					$(dl).append("<tr id='choice_" + i + "' class='opt_r'>"
												+ "<td class='handle" + ((vote_hist == o.polling_option_id) ? " voted" : "") + "' q_id='" + qu.polling_id + "' opt_id='" + o.polling_option_id + "' votecnt='" + o.vote_cnt + "' title='" + o["option_" + _711.language] + "'>"
												+ o["option_" + _711.language]
												+ "</td>"
												+ "<td class='visual' opt_id='" + o.polling_option_id + "' votecnt='" + o.vote_cnt + "'>"
												+ "<div class='bar'>&nbsp;</div>"
												+ "<div class='bubble'></div>"
												+ "</td></tr>");
					total_vote += parseInt(o.vote_cnt);
				});
				$('#poll > #question').attr('total_vote', total_vote);
				$('#poll > #options').append(dl);
				jsSetVoteResultBar();
				$('#poll > #options .handle').css({ cursor: 'pointer' });
				if (!vote_hist) {
					$('#poll > #options .handle').click(function () {
						jsVote(this);
					});
				} else {
					$('#poll > #options .handle').addClass('dim');
				}
			});
		}
	});
}

function jsSaveVoteHist(q_id, opt_id) {
	$.cookie("__711_poll_" + q_id, opt_id);
}

function jsGetVoteHist(q_id) {
	return $.cookie("__711_poll_" + q_id);
}


function jsSetVoteResultBar() {
	var total_vote = parseInt($('#poll > #question').attr('total_vote'));
	//utils.log('total_vote=' + total_vote);

	$('#poll > #options .visual').each(function () {
		// set vote bar animation
		var votecnt = parseInt($(this).attr('votecnt'));
		var new_width = (votecnt * parseInt($(this).width()) / total_vote);
		//utils.log('new_width=' + new_width);

		$('div.bar', this).animate({ width: new_width + 'px' });
	});
}

$(function () {
	jsLoadPoll();
});
