// JavaScript Document

var Favorites =
{
	isInit: false,
	coloredImg: null,
	greyImg: null,
	
	init: function(coloredImg, greyImg)
	{
		if(this.isInit)
			return;
		
		this.isInit = true;
		
		this.coloredImg = coloredImg;
		this.greyImg = greyImg;
	},
	
	create: function(id, isFav)
	{
		if(!this.isInit)
			return;
		
		var id = parseInt(id);
		var isFav = !!isFav;
		
		document.writeln("<div alt=\"Add to favorites\" id=\"Favorites_" + id + "\"></div>");
		
		var Container = $("Favorites_" + id);
		Container.setStyle({
			marginTop: '1px',
			height: '23px',
			width: '24px',
			cursor: 'pointer',
			float: 'right',
			backgroundImage: 'url(' + this.greyImg + ')'
		});
		
		var FavImage = new Element('div');
		FavImage.setStyle({
			height: '23px',
			width: '24px',
			cursor: 'pointer',
			float: 'right',
			backgroundImage: 'url(' + this.coloredImg + ')'
		});
		Container.update(FavImage);
		
		if(isFav)
			FavImage.show();
		else
			FavImage.hide();
		
		Event.observe(Container, 'mouseenter', function()
		{
			FavImage.show();
			FavImage.setOpacity(.6);
		});
		
		Event.observe(Container, 'mouseleave', function()
		{
			FavImage.setOpacity(1);	
			
			if(!isFav)
				FavImage.hide();
		});
		
		Event.observe(Container, 'click', function()
		{
			if(isFav)
				FavImage.hide();
			else
				FavImage.show();
				
			isFav = !isFav;
			
			new Ajax.Request( $F('AjaxDir') + '/favorite.php',
			{
				method: 'post',
				
				parameters:
				{
					PostID: id
				},
				
				onComplete: function(val)
				{
			
					resp = val.responseText.evalJSON();
					
					if(!!resp.Error)
					{
						switch(resp.Error)
						{
							case "NOT_LOGGED_IN":
								alert("You must be logged in to add this to your favorites.");
								window.location.href = 	"login.php";
							break;
							
							case "INVALID_POST_ID": alert("This is an invalid post ID."); break;
						}
					}
					else
					{
						isFav = !!resp.IsFav;
						
						if(isFav)
							FavImage.show();
						else
							FavImage.hide();
					}
				}
			});
		});
	}
}