Article = {

	locked : false,
	
	lock : function() { this.locked = true; },
	unlock: function() { this.locked = false; },

	getVote : function(id) {
		return Cookie.get("voted-for-" + id);
	},

	otherDirection : function(direction) {
		return (direction == "up" ? "down" : "up");
	},

	enableVote : function(id, direction) {
		var image = $("article_vote_"+direction+"_image");
		var src1 = (direction == "up" ? "/images/arrow_up.png" : "/images/arrow_down.png");
		var src2 = (direction == "up" ? "/images/arrow_up_green.png" : "/images/arrow_down_red.png");
		image.style.cursor = "pointer";
		image.onmouseover = function() {
			this.src = src2;
		};
		image.onmouseout = function() {
			this.src = src1;
		};
		image.onclick = function() {
			Article.vote(id, direction);
		};
		image.src = src1;
	},
	
	decrementCount : function(direction) {
		var text = $("article_vote_"+direction+"_count");
		text.innerHTML = parseInt(text.innerHTML, 10) - 1;
	},

	disableVote : function(direction) {
		var image = $("article_vote_"+direction+"_image");
		image.style.cursor = "default";
		image.onmouseover = null;
		image.onmouseout = null;
		image.onclick = null;
		image.src = (direction == "up" ? "/images/arrow_up_green.png" : "/images/arrow_down_red.png");
		var text = $("article_vote_"+direction+"_count");
		text.innerHTML = parseInt(text.innerHTML, 10) + 1;
	},

	vote : function(id, direction) {
		if (this.locked) return;
		if (Cookie.get("voted-for-" +id) == direction) return;
		this.lock();
		new Ajax.Request('/vote.php?article=' + id + '&direction=' + direction,
			{
				method:'get',
				onSuccess: function(transport) {
					var response = transport.responseText || "no response text";
					if (Cookie.get("voted-for-" +id) == Article.otherDirection(direction)) {
						Article.decrementCount(Article.otherDirection(direction));
						Article.enableVote(id, Article.otherDirection(direction));
					}
					Cookie.set("voted-for-" + id, direction, 365);
					//alert(Cookie.get("voted-for-" + id));
					Article.disableVote(direction);
					Article.unlock();
				},
				onFailure: function() {
					// do nothing.... whatevers, nobody cares
					Article.unlock();
				}
			}
		);
	},

	vote_up : function(id) {
		this.vote(id, "up");
	},

	vote_down : function(id) {
		this.vote(id, "down");
	}

};
