// Blog module javascript file.

$j(document).ready(function() {	
	$j('a[rel*=voting]').click(function(e) {
		e.preventDefault();
		if(check_login()){
			// Let them vote....
			preVote();
		} else {
			loginDoneTxt = 'Your vote has been submitted.';
			loginDoneExe = 'preVote()';
			//var html = 'You need to <a href="#login" onClick="login()">log in</a> to vote for a post.';
			//$j.facebox(html);
			login();
		}
	});
	
	// Preload the filled heart graphic.
	preload_image = new Image(25,25); 
	preload_image.src = "http://toastedrav.com/modules/blog/extra/images/v1/icon_favorited.gif"; 	
	// Display the voting box
	$j('#votes').css('display', 'block');	
	
	// Set click event for Voted tab
	$j('#voted_tab').click(function(e){
		// Check to see if there is any HTML in the voted div: If yes, call the ajax...if no, do nothing.
		if($j('#voted').html() == ''){
			var votedDiv = $j('#voted');
			votedDiv.html('Please wait, while we load the voter list...');
			
			$j.ajax({
				type: 'GET',
				url: base_url+'/blogPost/get_voters',
				dataType: 'html',
				data: 'blogPost_id='+blogPost_id,
				timeout: 2000,
				success: function(msg){
					votedDiv.html(msg);
				},
				error: function(){
					votedDiv.html("We're sorry, but the voter list isn't available at this time.");
				}
			});
		}
	});
}); 

function preVote(){
	var currentVotes = $j('#num_votes').html();
	var post_id = $j('#this_post_id').val();
	//alert('Vote counted: '+currentVotes+' / '+post_id);
	vote(currentVotes, post_id);
}


function vote(current, id, value){
	if(value == ''){
		value = 1;
	}
	
	$j.ajax({
		type: "GET",
		url: base_url+"/blogPost/vote?ajax=true",
		dataType: "json",
		data: 'blogPost_id='+id+'&value='+value,
		timeout: 2000,
		error: function(){
			$j.facebox("Sorry, but we are having a few issues right now and your vote didn't get received.  Please try again later.");
		},
		success: function(msg){
			if(msg['data']['return'] == 'success'){
				//$j('#voteLink').attr('rel', '');
				//$j('#voteLink').text('Thanks for voting!');
				//var newVotes = parseInt(current) + parseInt(1);
				//$j('#num_votes').text(newVotes);
				var voteLink = $j('#voteLink');
				voteLink.fadeOut('slow', function(){
					voteLink.attr('rel', '');
					voteLink.attr('href', '#');
					$j('#voteLink img').attr('src', '/modules/blog/extra/images/v1/icon_favorited.gif');
					voteLink.fadeIn('slow');
					voteLink.unbind('click');
					$j('#vote h3').html('You favorited this!');
				});
			} else {
				$j.facebox(msg['data']['return']);
			}
		}
	});
}