var EFFECT_COUNT = 0;
var ARTICLE_HEIGHTS = [];

function ArticleEffect(id, type) {
	var self = this;
	
	this._container = $("#" + id);	// container of content
	this._type = type;				// type of article
	this._number = EFFECT_COUNT++;	// number of article effect
	this._last = 0;					// position of last article
	
	this.run = function() {
		// do json request
		$.getJSON('/ajax/json/article', {'count' : EFFECT_COUNT, 'number' : self._number, 'type' : self._type}, function(data) {
			// calculate id of data
			var count = Math.min(data.length, 10);
			if (count > 1) {
				// update last (generate next)
				self._last++;
				if (self._last >= count) {
					self._last = 0;
				}
				
				// create news container
				var next = self._createContainer(data[self._last]);
				
				// get old container and then append new container
				var old = self._container.find("div");
				self._container.append(next);
				
				// do the effect
				old.fadeOut(1000, function() {
					next.fadeIn(1000, function() {
						self._justify(next, true);
						old.empty();
						old.remove();
					});
				});
			}
		});
	}
	
	this._createContainer = function(article) {
		// div
		var div = $("<div></div>").hide();
		
		// image
		if (article.img) {
			var link = $("<a href='" + article.link + "'></a>");
			var img = $("<img></img>");
			img.attr("src", article.img);
			link.append(img);
			div.append(link);
		}
		
		// append headline and preview
		div.append("<h2><a href='" + article.link + "'>" + article.title + "</a></h2>");
		div.append("<p>" + article.preview + " <a href='" + article.link + "'>(mehr)</a></p>");
		
		return div;
	}
	
	this._justify = function(next) {
		var parent = next.parent();
		var nextHeight = next.outerHeight();
		
		ARTICLE_HEIGHTS[self._number] = 0;
		var justify = true;
		for (var i in ARTICLE_HEIGHTS) {
			var height = ARTICLE_HEIGHTS[i];
			if (height > nextHeight) {
				justify = false;
				break;
			}
		}
		
		ARTICLE_HEIGHTS[self._number] = nextHeight;
		if (justify) {
			parent.animate({
				"height": nextHeight
			}, 500);
		}
	}
	
	this.init = function() {
		var parent = self._container.parent();
		var height = parent.innerHeight();
		var nextHeight = self._container.outerHeight();
		ARTICLE_HEIGHTS[self._number] = nextHeight;
		if (nextHeight > height) {
			parent.css("height", nextHeight);
		}
	}
	this.init();
}