﻿
$(document).ready(function(){
	
	$.featureList(
		$("#tabs li a"),
		$("#output li"), {
				start_item	:	1
			}
	);
	
	$("#voteForPoll").click(function(){
		voteForPoll();
	});
	
	var newsScrollTime = 5000;
	getNews();
	var newsInterval = setInterval(getNews, newsScrollTime);
	 
	$("#currentNews").hover(function(){
		clearInterval(newsInterval);
	}, function(){
		newsInterval = setInterval(getNews, newsScrollTime);
	});
});

var currNewsElement = 0;

function getNews()
{
	var newsElements = $("#newsList li");
	var newsDiv = $("#currentNews");
	newsDiv.fadeOut("slow", function() {
		newsDiv.html($(newsElements[currNewsElement]).html()).fadeIn("slow");
	});
	
	if(currNewsElement < newsElements.size() -1)
	{
		currNewsElement++;
	}
	else
	{
		currNewsElement = 0;
	}
}

function voteForPoll()
{
	var optionId = $("input[type=radio][name=option]:checked").val();
	if(typeof optionId == "undefined")
	{
		return;
	}
	var voteForPollURL = $("#voteForPollURL").val();
	
	$.postJSON(voteForPollURL, {'optionId': optionId}, function(data) {
		updatePollResults(optionId, data);  
	});

}

function updatePollResults(optionId, pollOptions)
{
	var totalWidth = 85;
	var totalVotesCount = getTotalVotesCount(pollOptions);
	
	$("#pollList li.option").each(function(){
		var listItem = $(this);
		var optionIdValue = listItem.children("input[type=radio][name=option]").val();
		var optionText = listItem.children("span").html();
		
		var votesCount = getOptionVotesCount(optionIdValue, pollOptions);
		
		var per = votesCount / totalVotesCount;
		
		var txtPer = 100*per;
		var percentage = per*totalWidth;
		if(txtPer != 0 && percentage != totalWidth)
		{
			txtPer = Math.round(txtPer);
		}
		
		var resultTemplate = $("#optionResultTemplate").html();
		resultTemplate = resultTemplate.replace("optionText", optionText);
		resultTemplate = resultTemplate.replace("optionPercentage", txtPer);
		
		listItem.empty();
		listItem.append(resultTemplate);
		var progressSpan = listItem.children("div").children("span.progress");
		
		if(optionIdValue == optionId)
		{
			progressSpan.css("background-color", "#0066cc");
		}
		
		progressSpan.css("width", "0%").animate({width: percentage}, 'slow');
	});
	$("#pollList li").last().attr("class", "totalVotes").html($("#totalVotesTemplate").html().replace("totalVotesCount", totalVotesCount));
}

function getOptionVotesCount(optionId, pollOptions)
{
	var votesCount = 0;
	$.each(pollOptions, function(index, option){
		if(option.id == optionId)
		{
			votesCount = parseInt(option.votesCount);
			return false;
		}
	});
	return votesCount;
}

function getTotalVotesCount(pollOptions)
{
	var totalVotes = 0;
	$.each(pollOptions, function(index, option){
		totalVotes += parseInt(option.votesCount);
	});
	return totalVotes;
}

