$(document).ready(function()
{
	bindTranslate();
	
	// Hide any menus if the main body is clicked
	$('#mainContainer').bind('click', function(event)
	{
		$('.active').removeClass('active');
		$('#popup').hide();
		$('#popupMenu').hide();
	});
	
	// "Add to my zhongwen" button 
	$('#btnAddToMyZhongwen').click( function(event) 
	{
		addToMyZhongwen(currentWord.substr(7));
				 
		$('.active').removeClass('active');
		$('#popup').hide();
		$('#popupMenu').hide();
		
		return false;
	});
	
	// View full entry button
	$('#btnViewFullEntry').click( function(event) 
	{
		window.location = currentWord;
		return false;
	});

});

currentWord = false;

function bindTranslate() {

	$(".translate").bind('mouseenter', function(event)
	{
		// Do nothing if popup menu is visible
		if ($('#popupMenu').is(':visible')) return;
		
		$('#popup').hide().html($(this).html()).css({ top: event.pageY + 2, left: event.pageX + 20}).show();
		$('#popupMenu').hide();
		//currentWord = $(this).parent().attr('href');
		currentWord = $(this).attr('href');
		return false;
	});
	
	// Hide popup when mouse leaves the element
	$(".translate").bind('mouseleave', function(event)
	{
		$('#popup').hide();
		return false;
	});
	
	// Show the popup menu if the hanzi is clicked
	$(".translate").bind('click', function(event)
	{
		$(this).addClass('active');
		$('#popup').hide();
		$('#popupMenu').hide().css({ top: event.pageY + 2, left: event.pageX + 20}).show();
		return false;
	});
	
	
}

function addToMyZhongwen(wordId)
{
	$.ajax({
	   type: "POST",
	   url: "/ajax/addtomyzhongwen/" ,
	   data: "wordId=" + wordId,
	   dataType: 'text',
	   success: function(msg){
		 
		 // Check for error
		 if (msg == 'not logged in') {
		 	if (confirm('Sorry, you must be registered and logged in to use MyZhongwen. Would you like to register now?')) window.location = '/register/';
		 }
		 
		 if ((msg == 'ok') || (msg == 'already added')) {
		 	// Show "word added" graphic
		 	// Make sure it shows at top of viewport
		 	offset = $('#btnMainMyZhongwen').offset();
		 	top = offset.top + 30;
		 	windowTop = $(document).scrollTop();
		 	if (windowTop > top) top = windowTop;
		 	$('#wordAdded').css({ left: offset.left - 40, top: top}).
		 			fadeIn().animate({opacity: 1.0}, 1000).fadeOut();
		 }

	   }
	 });

}




function resetErrors()
{
	$('.error').hide();
}
