var ReactContext = {
	
	init: function()
	{
		if (! this.element)
			this.element = $('article-context');
	}
	
	,isLoggedIn: function()
	{
		return this.element.getAttribute('logged-in') == '1';
	}
	
	,getAccountId: function()
	{
		return this.element.getAttribute('account-id');
	}
	
	,getInstanceId: function()
	{
		return this.element.getAttribute('instance-id');
	}
};

function toggleReactOptionsPanel()
{
	$('reactOptions').toggle();
}

function getRatingLevel()
{
	var value = $('ratingLevelSelect').getValue();
	return (value == '')
		? 'all' : parseInt(value);
}

function changeRatingLevel()
{
	var rating = getRatingLevel();
	
	Cookie.setData('rating', rating);
	
	$$('.comment-entry').each(function(comment) {
		setCommentVisibilityByRating(comment, rating);
	});
}

function setCommentVisibilityByRating(comment, rating)
{
	if (rating == 'all')
	{
		showComment(comment);
	}
	else
	{
		var r = parseInt(comment.getAttribute('rating'));
		
		if (r < rating)
			hideComment(comment);
		else
			showComment(comment);
	}
}

function hideComment(comment)
{
	if (comment.hasClassName('hidden'))
		return;
		
	comment.down('.body').hide();
	comment.addClassName('hidden');
	
	
	with ($E)
	{
		var showLink = a({href: '#'}, "Tonen");
		
		showLink.observe('click', function(e) {
			Event.stop(e);
			showComment(comment);
		});
		
		var pane = div(
			p(
				small(
					'(Reactie verborgen, zie opties) '
					,showLink
				)
			).addClassName('hidden-message')
		);
		
		comment.appendChild(pane);
	}
}

function showComment(comment)
{
	if (comment.hasClassName('hidden'))
	{
		comment.down('.hidden-message').remove();
		comment.removeClassName('hidden');
		comment.down('.body').show();	
	}
}

function updateCommentRating(comment, score)
{
	var scoreEl = comment.down('.score');
	var oldScore = parseInt(scoreEl.innerHTML);
	var score = oldScore + parseInt(score);
	
	scoreEl.update(score);
	comment.setAttribute('rating', score);
	setCommentVisibilityByRating(comment, getRatingLevel());
	updateRatingColor(comment);
}

function disableVoteButtons(comment)
{
	comment.select('BUTTON').invoke('addClassName', 'disabled');
}

function enableVoteButtons(comment)
{
	var buttons = comment.select('BUTTON');
	
	buttons.each(function(button) {
		button.observe('mouseover', function() {
			if (button.hasClassName('disabled'))
				return;
				
			button.addClassName('hover');
		});
		
		button.observe('mouseout', function() {
			button.removeClassName('hover');
		});
		
		button.observe('click', function() {
			
			if (this.hasClassName('disabled'))
				return false;
			
			if (! ReactContext.isLoggedIn())
			{
				new ReactieScoreLoginDialog().show();	
			}
			else
			{
				var score = (this.hasClassName('thumbs-up') ? 1 : -1);
				
				showLoader(comment);
				
				new Ajax.Request('/static/reacties.ajax.php', {
					parameters: {
						action: 'vote'
						,s: score
						,r: comment.getAttribute('rel')
						,a: ReactContext.getInstanceId()
					}
					,onSuccess: function(transport)
					{
						hideLoader(comment);
						
						var json = transport.responseJSON;
						
						if (json.status == 'error')
						{
							alert(json.message);
						}
						else
						{
							VoteAccess.markVoted(comment.getAttribute('rel'));
							updateCommentRating(comment, score);
							disableVoteButtons(comment);
						}
					}
					,onComplete: function(transport)
					{
						
					}
				});
			}
		});
	});
}

var VoteAccess = {
	
	list: null
	
	,initialize: function()
	{
		var self = this;
		
		if (! ReactContext.isLoggedIn())
		{
			this.list = [];
			this.initializeVoteButtons();
			return;
		}
			
		var voted = Cookie.getData('voted');
		
		if (voted == undefined)
		{
			// we have to load the votes
			new Ajax.Request('/static/reacties.ajax.php', {
				parameters: {
					action: 'get_vote_ids'
				}
				
				,onSuccess: function(transport)
				{
					var json = transport.responseJSON;
					
					if (json.status == 'success')
					{
						self.list = json.message;
					}
					else
					{
						// we are not logged in
						self.list = [];
					}

					// set the cookie
					Cookie.setData('voted', self.list);
					self.initializeVoteButtons();
				}
			});
		}
		else
		{
			this.list = voted;
			this.initializeVoteButtons();
		}
	}
	
	,initializeVoteButtons: function()
	{
		$$('.comment-entry').each(function(comment) {
			
			updateRatingColor(comment);
			
			if (! VoteAccess.mayVote(comment))
			{
				disableVoteButtons(comment);
			}
			else
			{
				enableVoteButtons(comment);
			}
		});
	}
	,mayVote: function(comment)
	{
		return (this.list.indexOf(comment.getAttribute('rel')) == -1 && comment.getAttribute('author') != ReactContext.getAccountId())
	}
	
	,markVoted: function(commentId)
	{
		this.list.push(commentId);
		Cookie.setData('voted', self.list);
	}
	
}

function showLoader(comment)
{
	var loader = new Element('img', { src: '/media/gfx/react/loader.gif' });
	loader.addClassName('loader');
	loader.setStyle({'float': 'right', 'marginRight': '10px', 'marginTop': '2px'});
	var header = comment.down();
	var scorebar = header.down();
	
	scorebar.hide();
	scorebar.insert({ before: loader});
}

function hideLoader(comment)
{
	comment.down('.loader').remove();
	comment.down('.score-bar').show();
}

function updateRatingColor(comment)
{
	var rating = comment.getAttribute('rating');
	var score = comment.down('.score');

	// remove old class names
	score.removeClassName('score-positive');
	score.removeClassName('score-negative');
	
	if (rating > 0)
		score.addClassName('score-positive');
	else if (rating < 0)
		score.addClassName('score-negative');
}

Event.observe(window, 'load', function() 
{	
	// initialize the context
	ReactContext.init();
	
	// initialize rating level
	Cookie.init({name: 'texelsecourant', expires: 90}, { 'rating': 0 });
				
	var rating = Cookie.getData('rating');
	
	$('ratingLevelSelect').select('option').each(function(option) {
		if (option.value == rating)
			option.selected = true;
	});
	
	changeRatingLevel();
	
	// initialize vote access
	VoteAccess.initialize();
});

var ReactieScoreLoginDialog = Class.create(IpDialogWidget, {
	initialize: function($super)
	{
		with ($E)
		{
			var linkClose = a({href:''}, "Sluiten");
			linkClose.observe('click', this.closeHandler.bindAsEventListener(this));
			
			var linkLogin = button("Nu inloggen");
			
			linkLogin.observe('click', function() {
				document.location = $('loginUrl').value;
			});
			
			var pane = div(
				p("U moet ingelogd zijn om op een reactie te kunnen stemmen.")
				,p(linkLogin).addClassName('alignCenter')
				,p(linkClose).addClassName('alignRight')
			);
		}

		options = {
			title: 'Inloggen'
			,pane: pane
			,width: 300	
		};
		
		$super(options);
	}
});