// JavaScript Document

var max_votes_per_category = 3;

function suggest_name(cid, suggestion)
{
	//First, check if data is valid for sumbit
	if(suggestion.indexOf('Write in your candidate') > -1){ return false; }
	if(suggestion.replace(/^\s+|\s+$/g,"") == ''){ return false; } //No empty submits

	//Second, submit
	$.post("process.php?a=suggest_name&cid=" + cid, { s: suggestion },
	  function(data){
		alert('Thank you for your contribution!');
		document.forms['suggestform'].input_suggestion.value = '';
	  });	  
	return false;
}

function send_suggestion(){ suggest_name(document.forms['suggestform'].input_cid.value, document.forms['suggestform'].input_suggestion.value); return false; }

function vote(action, cid, pid)
{
	$.getJSON("process.php?a=" + action + "&cid=" + cid + "&pid=" + pid,
        function(data){
          
			if(data.res == true){
				var votes_cast_in_category;
				
				
				if(action == 'vote'){
					
					if($(".hasvote").size() >= max_votes_per_category ){ alert( 'Sorry, you can only vote for ' + max_votes_per_category + ' people in every category.'); return true; }	
					$('#person_'+data.pid).addClass('hasvote');
					$('#person_'+data.pid).effect("pulsate", { times:-1 }, 1000);
					$('#navitem_'+cid).addClass('cathasvote');
					
					//Hide vote btns if max is reached
					if($(".hasvote").size() == max_votes_per_category ){ $('#people').addClass('maxvotesreached'); };
				}
				else if(action == 'removevote'){
					$('#person_'+data.pid).removeClass('hasvote');
					votes_cast_in_category = $(".hasvote").size();
					
					//Remove vited indicator from nav, if zero:
					if(votes_cast_in_category < 1){ $('#navitem_'+cid).removeClass('cathasvote'); };
					if(votes_cast_in_category < max_votes_per_category){ $('#people').removeClass('maxvotesreached'); };
				}
				
				update_vote_count();

			}
			else{
				alert('Sorry, your vote could not be processed at this time.');
			}

        });

}

function update_vote_count()
{
	var current_number_of_votes = $(".hasvote").size();

	$("#votecounter").html('<span class="highlight" id="voteconfirm">Thanks for voting!</span> Number of remaining votes: <span>' + (max_votes_per_category - current_number_of_votes) + '</span>');
	$('#voteconfirm').effect("pulsate", { times:-1 }, 1000);
}

$().ready(function() {
 $('#frontpage-features').cycle({ 
    fx:    'fade', 
    speed:  2500,
	timeout:  2000,
	pause: 5
 });
});
