// Rating Points Chooser = rpc
var rpc_info = {};

function set_question_type(q, qt) /*  I think JS has an issue with using 'type' as a variable */
{
	if(!user.exists)
	{
		var error = '<b>Share what you know!</b><br />\
		To rate answers or questions, please '+ createReferrerLink('/register', '<b>sign up</b>') +'</a> for a free account or '+ createReferrerLink('/login', '<b>sign in</b>', 'return') +'.';
		$.popup.inline(error);
		return false;
	}
	else if(!user.confirmed)
	{
		$.popup.inline("You must confirm your account in order to rate something.<br/><br />  Please check your email for confirmation instructions or "+ createReferrerLink('/user/request_confirmation', '<b>request another confirmation</b>'));
		return false;
	}
	
	$.getJSON("/json/set_qtype.php", {question:q, qtype:qt},
		function (k)
		{			
			var qid = '#question_type' + k.questionid;
			$(qid).html("Conv: " + k.conv_votes + " Edu: " + k.edu_votes );
			
		}
	
	);
	return false;
}


$(document).ready( function()
{
	//$.popup.confirm('Are you sure you want to do this?', function() { alert('Yes, I do') }, function() { alert('No, I do not') });
	//$.popup.inline('test ksjdhfkhsdf khsdkjhf kdjgh ksdghksdh gkdhsgk sdhgkjh');
	// $.popup.inline('tools/dupefinder', {width: 600, height: 600});
	// $.popup.iframe('tools/dupefinder');
	//$.popup.iframe('tools/dupefinder?qid=141053&question=Excuse+me', {width: 600, height: 400});
	// $.popup.loader.start();
	// $.popup.loader.stop();
	$('.rating_box .pos, .rating_box .neg').each( function()
	{
		// If there's no id, the element should be disabled
		var id = $(this).parent().parent().attr('id');
		
		if($(this).parent().parent().attr('id'))
		{
			$(this).hover(
				
				function() 
				{ 
					var child = $(this).children('div');
	
					rpc_info['info'] = id.split('_'); // Question or answer
					rpc_info['box'] = $(this).parent().parent(); // The element
					rpc_info['button'] = child; // The button that is hovered
					rpc_info['rate'] = $(this).attr('class'); // Pos/neg
					if(user.confirmed) {
						var point_max = rpc_info['user'][rpc_info['info'][0]][rpc_info['rate']]; // Gets the max points
						if(Math.abs(point_max) > 1) {
							rpc_info['timer'] = window.setTimeout('show_rating_points_chooser()', rpc_info['user']['rating_box_delay']);
						}
					}

					child.addClass('hover');
				} ,
				function()
				{
					$(this).children('div').removeClass('hover');
					$('#rating_points_chooser').css('display', 'none');
					window.clearTimeout(rpc_info['timer']);
				}
			);
			$(this).click(
				function()
				{
					window.clearTimeout(rpc_info['timer']);
					rpc_info['info'] = id.split('_'); // Question or answer
					rate();
				} 
			);
		}
		
	});
});

function build_rating_points_chooser()
{
	var rps;
	var point_max = rpc_info['user'][rpc_info['info'][0]][rpc_info['rate']]; // Gets the max points
	var point_cur = rpc_info['button'].attr('dir') * 1;
	var str;
	var clas;
	var rate = point_max < 0 ? '-' : '';  // Save if it's negative
	var count = point_max + ''; // Make it a string 
	count = count.replace('-', '');

	// Only create the table once
	if(!$('#rating_points_chooser').size())
		$('body').append('<table id="rating_points_chooser"></table>');

	rps = $('#rating_points_chooser');
	rps.empty();

	clas = (point_max == count || point_max == 0-count) ? 'class="cur"' : '';
	str = '<tr><th rowspan="'+count+'">';
	str += point_cur ? 'Points given <b>' + point_cur +'</b>': 'Points to give';
	str += '</th><td '+clas+'>'+rate+count+'</td></tr>';
	
	for(var i=count-1; i >= 1; i--)
	{
		clas = (rate+i == point_max) ? 'class="cur"' : ''; 
		str += '<tr><td '+clas+'>'+rate+i+'</td></tr>';
	}
	rps.append(str);	
}

function show_rating_points_chooser()
{
	if(!user.exists) 
		return false;

	var loc = {};
	var chooser;
	
	build_rating_points_chooser();
	chooser = $('#rating_points_chooser');
	
	// Position the rating box based on it's calling button
	rpc_info['button'].offset({scroll: false}, loc);
	chooser.css('display', '');
	loc['top'] = loc['top'] - chooser.height();
	loc['left'] = loc['left'] - chooser.width() + 21+'px';
	chooser.css(loc);

	// Populate the TDs
	chooser.find('td').each( function()
	{
		var old = $(this).attr('class');
		$(this).unbind();
		$(this).hover(
			function() { $(this).addClass('hover'); },
			function() { this.className = old; }
		);
		$(this).click( function()
		{
			// Set current/previous points to what they clicked on	
			rate($(this).html());
		});
	});

	// Make sure it doesn't go away when hovering
	chooser.unbind();
	chooser.hover(
		function()
		{

			rpc_info['button'].addClass('hover');
			$(this).css('display', '');
		}
		,
		function()
		{
			rpc_info['button'].removeClass('hover');
			chooser.css('display', 'none');
		}
	);
}

function rate(points)
{

	/*
	rpc_info['info'][0] - question or answer
	rpc_info['info'][1] - the id of above
	rpc_info['info'][2] - Hash
	*/
	if(!user.exists)
	{
		var error = '<b>Share what you know!</b><br />\
		To rate answers or questions, please '+ createReferrerLink('/register', '<b>sign up</b>') +'</a> for a free account or '+ createReferrerLink('/login', '<b>sign in</b>', 'return') +'.';
		$.popup.inline(error);
		return false;
	}
	else if(!user.confirmed)
	{
		$.popup.inline("You must confirm your account in order to rate something.<br/><br />  Please check your email for confirmation instructions or "+ createReferrerLink('/user/request_confirmation', '<b>request another confirmation</b>'));
		return false;
	}

	// They are clicking directly on the button, get the max points
	if(!points)
		points = rpc_info['user'][rpc_info['info'][0]][rpc_info['rate']];

	// Get the points box and save it
	rpc_info.points_box = rpc_info['box'].find('.points');

	// default points are stored in that element.
	rpc_info['info'].points_next = (points * 1) + (rpc_info.points_box.attr('points') * 1);

	// Now update the points
	rpc_info.points_box.html(rpc_info['info'].points_next + "");

	var params =
	{
		type: rpc_info['info'][0],
		id: rpc_info['info'][1],
		rate: rpc_info['rate'],
		rating: points,
		hash: rpc_info['info'][2]
	}
	var url = '/json/rate.php';
	$('#rating_points_chooser').css('display', 'none');
	$.getJSON(url, params, rate_handler);
}
function rate_handler(obj)
{
	if(obj.error)
	{
		$.popup.inline(obj.error);
		return;
	}
	
	rpc_info['box'].find('.pressed').removeAttr('dir');
	rpc_info['box'].find('.pressed').attr('dir', ' '); // IE's not removing it & setting it to '' doesn't work.  We'll trim in the build function
	rpc_info['box'].find('.pressed').removeClass();

	/*  
	points_box.fadeOut("normal", function() 
	{
		points_box.html(obj.rating);  
		points_box.fadeIn("normal");  
   });
   */
	rpc_info['button'].attr('dir', obj.last_rating);
	rpc_info['button'].attr('class', 'pressed');
}

/*
	Flag Handlers
******************************************/
var moderate = 
{
	id: null,
	hash: null,
	value: null,
	o: null,
	
	// Used by both
	user_okay: function()
	{
		if(!user.exists) 
		{
			var error = '<b>Help us keep Answerbag clean!</b><br />\
			To moderate answers or questions, please '+createReferrerLink('/register', '<b>sign up</b>')+'</a> for a free account or '+createReferrerLink('/login', '<b>sign in</b>', 'return') +'.';
			$.popup.inline(error);				
			return false;
		}
		else if(!user.confirmed)
		{
			$.popup.inline("You must confirm your account in order to moderate a question.<br/><br />  Please check your email for confirmation instructions.");
			return false;
		}	
		return true;
	},
	set: function(id, hash, value, o)
	{
		this.id = id;
		this.hash = hash;
		this.value = value;
		this.o = o;
	},
	close: function()
	{
   	$.popup.close();
   	this.o.selectedIndex = 0; // Set it back to the normal position
	},

	// Question Stuff
	question: function(id, hash, value, o)
	{
		if(!this.user_okay())
			return false;

		this.set(id, hash, value, o);
		
	   if(value == -100) { return; } // They are changing it back to it's "flag this question"
		if(value == 3) // duplicate
		{
			// show the fake popup
			var settings =  { height: 400, width: 600 };
			var url = '/tools/dupefinder?qid='+question_info.id+'&question='+question_info.text;
			$.popup.iframe(url, settings)
			return;
		}
		else if(value == 13) // Wrong Category
		{
			// show the fake popup
			var settings =  { height: 400, width: 400 };
			var url = '/tools/catchooser?qid='+question_info.id;
			$.popup.iframe(url, settings)
			return;
		}
		if (value == 12) // Nonsense
		{
			var str = "Thank you for helping keep Answerbag clean (while earning 5 points.)\n  Are you sure you want to mark this question as nonsense?";
			$.popup.confirm(str, 
				function(){	moderate.question_flag(); },
				function(){	moderate.close() }
			);
		}
		if (value == 11) // Spam
		{
			var str = "Thank you for helping keep Answerbag clean (while earning 5 points.)\n  Are you sure you want to mark this question as spam?";
			$.popup.confirm(str, 
				function(){	moderate.question_flag(); },
				function(){	moderate.close() }
			);
		}
	},
	question_flag: function()
	{
   	$.popup.close();
		var url = '/json/question_flag.php?question=' + this.id + "&flag=" +this.value+ '&hash=' +this.hash;
		$.getJSON(url, moderate.question_flag_handler);
		this.o.disabled = 'true';
	},
	question_flag_handler: function()
	{
		this.o.disabled = 'true';
	},
	// Answer 
	answer: function(id, value, hash, o)
	{
		if(!this.user_okay())
			return false;
		this.set(id, hash, value, o);
		if (value == 12) // Nonsense
		{
			var str = "Thank you for helping keep Answerbag clean (while earning 5 points.)\n  Are you sure you want to mark this answer as nonsense?";
			$.popup.confirm(str, 
				function(){	moderate.answer_flag(); },
				function(){	moderate.close() }
			);
		}
		if (value == 11) // Spam
		{
			var str = "Thank you for helping keep Answerbag clean (while earning 5 points.)\n  Are you sure you want to mark this answer as spam?";
			$.popup.confirm(str, 
				function(){	moderate.answer_flag(); },
				function(){	moderate.close() }
			);
		}
	},
	answer_flag: function()
	{
   	$.popup.close();
		var url = '/json/answer_flag.php?answer=' +this.id + "&flag=" + this.value  + '&hash='+this.hash;
		$.getJSON(url, moderate.answer_flag_handler);
	},
	answer_flag_handler: function(obj)
	{
		var adiv = "#answer_moderation_" + obj.answerid;
		$(adiv).html('Answer flagged. Thank you.');
	}
}
