// ======================================================================
//
// JScript Source File -- copyright 2008 derStandard.at GmbH
// 
// NAME: ForumLiveBericht.js
//
// AUTHOR: Lukas Klaus, Mario Zoth, Wolfgang Goedel, derStandard.at GmbH
// DATE  : 24.04.2008 v1.0
// 
// COMMENT: Forum LiveBericht Tools Support 2008
// 
// sources are not to be used in other websites.
// if you want to use the navigation write to webmaster@derStandard.at
// =========================================================================

var LiveBericht = Class.create({
	initialize: function (element, params) {
		this.element = $(element);
		this.objectID = params.objectID;
		this.status = params.status;
		this.lkn = params.lkn;
		this.packetSize = params.packetSize;

		this.posts = new Array();
		this.lastID = 0;
		this.lastChange = 0;
		this.live = false;
		this.mode = params.mode;

		this.imgCanvas = this.element.down('.imgdiv');
		this.postingCanvas = this.element.down('.postingdiv');

		this.prepareTemplates();
	},

	prepareTemplates: function () {
		var syntax = /(^|.|\r|\n)(%=\s*(\w+)\s*%)/;
		LivePosting.prototype.template = new Template(this.element.down('.tmpl_posting').remove().innerHTML, syntax);
		LiveComment.prototype.template = new Template(this.element.down('.tmpl_comment').remove().innerHTML, syntax);
		LiveImage.prototype.template = new Template(this.element.down('.tmpl_image').remove().innerHTML, syntax);
	},

	start: function () {
		this.live = (this.status != 0);
		// hole daten immer auch wenn nicht live
		this.getForumData();
	},

	stop: function () {
		this.live = false;
		if (this.pe) this.pe.stop();
		this.pe = null;
	},

	bindStartStop: function (elmtID) {
		if (this.status != 0) {
			$(elmtID).observe('click', function (ev) {
				// starte oder stoppe den holmechanismus
				if (this.pe == null) {
					ev.target.value = "Stop";
					this.start();
				} else {
					ev.target.value = "Start";
					this.stop();
				}
			}.bind(this));
		}
	},

	getForumData: function () {
		new Ajax.Request('/live/forum/getForumDaten.aspx', {
			method: 'POST',
			parameters: { id: this.objectID, lastid: this.lastID, lastChange: this.lastChange },
			onSuccess: function (response) {
				var forumDaten = response.responseJSON;
				var newPosts = $A(forumDaten.New);
				var partial = newPosts.length < this.packetSize;

				newPosts.each(function (post) {
					try {
						this.lastID = (this.lastID < post.PostingID) ? post.PostingID : this.lastID;
						this.lastChange = (this.lastChange < post.Changedate) ? post.Changedate : this.lastChange;
						this.addItem(post, partial)
					} catch (e) { }
				} .bind(this));

				var changedPosts = $A(forumDaten.Changed);
				changedPosts.each(function (post) {
					try {
						this.lastChange = (this.lastChange < post.Changedate) ? post.Changedate : this.lastChange;
						this.changeItem(post);
					} catch (e) { }
				} .bind(this));

				if (!partial) {
					this.getForumData();
				} else {
					this.updating = false;
					if (this.live && !this.pe)
						this.pe = new PeriodicalExecuter(this.getForumDataUpdate.bind(this), 7);
				}

			}.bind(this)
		});
	},

	getForumDataUpdate: function()
	{
		//update only if first comment is in sight (with 50px tolerance)
		if (this.updating == false && this.postingCanvas.cumulativeOffset().top + 50 > document.viewport.getScrollOffsets().top) {
			this.updating = true;
			this.getForumData();
		}
	},

	addItem: function(post, fadeIn)
	{
		if (this.posts[post.PostingID.toString()] ||
		    (post.ParentID != -1 && !this.posts[post.ParentID.toString()])
		) return;

		var livePost;
		if (post.ParentID != -1) {
			livePost = new LivePosting(post, this);
		} else {
			if (post.Style != 'bild') {
				livePost = new LiveComment(post, this);
			} else {
				livePost = new LiveImage(post, this);
			}
		}

		this.posts[post.PostingID.toString()] = livePost;
		livePost.show(fadeIn);
	},

	changeItem: function (post) {
		var oldPost = this.posts[post.PostingID.toString()];

		if (post.Action == 'delete') {
			if (oldPost) oldPost.remove();
		} else if (post.Action == 'update') {
			if (oldPost) oldPost.replace(post);
		}
	}

});

var LiveComment = Class.create({
	initialize: function (post, lb) {
		post.pcount = post.Pos + post.Med + post.Neg;
		this.lb = lb;
		this.content = post;
		this.posts = new Array();
		this.postsShown = false;
		this.postCount = 0;
	},

	show: function (fadeIn) {
		var html = this.template.evaluate(this.content);
		this.element = new Element('div', { "style": "display:none", "class": "comment" });
		this.element.update(html.replace('redon', 'Redaktion'));
		this.postings = this.element.down('.posting');
		this.toggler = this.element.down('.toggler');
		this.toggler.observe('click', this.showHidePosts.bind(this));
		
		if (this.lb.mode == 0)
		{
			this.lb.postingCanvas.insert(this.element);
		} else {
			this.lb.postingCanvas.insert({ top: this.element });
		}

		if (this.content.pcount > 0) {
			var ratingElmt = '#b_' + this.content.PostingID;
			this.element.down(ratingElmt).insert(t_create(this.content.Pos, this.content.Med, this.content.Neg));
			//this.element.down('div.pcount').insert('[' + this.content.pcount + ']');
		}

		if (this.content.Ebene > 1) {
			addLink(this.content.PostigID, 0, this.lb.lkn);
		}

		addLink(this.content.PostingID, 1, this.lb.lkn);

		//FIX NG
			//Effect Blinddown führt zu inkorrekter Daretsllung der Umlaute für neu hinzugefügte Postings
			//		if (fadeIn) {
			//			Effect.BlindDown(this.element, { duration: 0.5 });
			//		} else {
		this.element.show();
			//}
		//END FIX NG
	},

	replace: function (post) {
		post.pcount = post.Pos + post.Med + post.Neg;
		this.content = post;

		this.toggler = this.toggler.remove();
		this.postings = this.postings.remove();

		var html = this.template.evaluate(this.content);
		this.element.update(html.replace('redon', 'Redaktion'));

		this.element.down('.posting').replace(this.postings);
		this.element.down('.toggler').replace(this.toggler);

		if (this.content.pcount > 0) {
			var ratingElmt = '#b_' + this.content.PostingID;
			this.element.down(ratingElmt).insert(t_create(this.content.Pos, this.content.Med, this.content.Neg));
		}
		if (this.content.Ebene > 1)
			addLink(this.content.PostingID, 0, this.lb.lkn);

		addLink(this.content.PostingID, 1, this.lb.lkn);
	},

	remove: function () {
		this.posts.each(function(post) { post.detach(); });
		this.element.fade({ duration: 0.25, afterFinish: this.element.remove.bind(this.element) });
		this.detach();
	},

	detach: function () {
		this.lb.posts[this.content.PostingID.toString()] = null;
		this.posts.clear();
		this.element = null;
		this.lb = null;
	},

	addPost: function (post) {
		post.comment = this;
		post.parent = this;
		this.posts[this.posts.length] = post;
		this.incPostCount();
	},

	incPostCount: function () {
		this.postCount++;
		this.toggler.show();
		this.toggler.down('.upcount').update(this.postCount.toString());
	},

	decPostCount: function () {
		this.postCount--;
		this.toggler.down('.upcount').update(this.postCount.toString());
		if (this.postCount == 0) this.toggler.hide();
	},

	showHidePosts: function () {
		if (this.postsShown) {
			this.postsShown = false;
			try {
				this.postings.fade({ duration: 0.5 });
			} catch (e) {
				this.postings.setStyle({ display: 'none' });
			}
			this.toggler.down(1).update('anzeigen');
		} else {
			this.postsShown = true;
			if (!this.postsCreated) this.createPosts();
			try {
				this.postings.appear({ duration: 0.5 });
			} catch (e) {
				this.postings.setStyle({ display: 'block' });
			}
			this.toggler.down(1).update('ausblenden');
		}
	},

	createPosts: function () {
		this.postsCreated = true;
		this.posts.each(function (post) {
			post.show(false);
		});
	}
});

var LiveImage = Class.create({
	initialize: function(post, lb)
	{
		this.content = post;
		this.lb = lb;
	},

	show: function(fadeIn)
	{
		var html = this.template.evaluate(this.content);
		this.element = new Element('div', { 'style': 'display:none' });
		this.element.update(html.replace('redon', 'Redaktion'));

		if (this.lb.mode == 0) {
			this.lb.imgCanvas.insert(this.element);
		} else {
			this.lb.imgCanvas.insert({ top: this.element });
		}
		//FIX NG
			//Effect Blinddown führt zu inkorrekter Daretsllung der Umlaute für neu hinzugefügte Postings
			//		if (fadeIn) {
			//			Effect.BlindDown(this.element, { duration: 0.5 });
			//		} else {
		this.element.show();
			//}
		//END FIX NG
	},

	replace: function(post)
	{
		this.content = post;

		var html = this.template.evaluate(this.content);
		this.element.update(html.replace('redon', 'Redaktion'));
	},

	remove: function()
	{
		this.element.fade({ duration: 0.25, afterFinish: this.element.remove.bind(this.element) });
		this.detach();
	},

	detach: function()
	{
		this.lb.posts[this.content.PostingID.toString()] = null;
		this.posts.clear();
		this.element = null;
		this.lb = null;
	},

	addPost: function() { }
});

var LivePosting = Class.create({
	initialize: function(post, lb)
	{
		post.pcount = post.Pos + post.Med + post.Neg;
		this.lb = lb;
		this.content = post;
		this.posts = new Array();
		this.element = null;
		lb.posts[post.ParentID.toString()].addPost(this);
	},

	show: function(fadeIn)
	{
		if (this.comment.postsCreated) {
			var html = this.template.evaluate(this.content);
			this.element = new Element('div');
			this.element.update(html);
			this.addHickePic();

			var str_icon = '';
			for (var i = 0; i < (this.content.Ebene - 1); i++)
				str_icon += '<img width="7" height="17" border="0" src="/img/comm/forum/triangleneu.gif" alt=""/>';
			this.element.down('td.icons').update(str_icon);
			this.parent.element.down('div.posting').insert({ top: this.element });

			if (this.content.pcount > 0) {
				var ratingElmt = '#b_' + this.content.PostingID;
				this.element.down(ratingElmt).insert(t_create(this.content.Pos, this.content.Med, this.content.Neg));
			}

			if (this.content.Ebene > 1)
				addLink(this.content.PostingID, 0, this.lb.lkn);

			addLink(this.content.PostingID, 1, this.lb.lkn);
			addLink(this.content.PostingID, 2, this.lb.lkn);

			//FIX NG
				//Effect Blinddown führt zu inkorrekter Daretsllung der Umlaute für neu hinzugefügte Postings
				//		if (fadeIn) {
				//			Effect.BlindDown(this.element, { duration: 0.5 });
				//		} else {
			//this.element.show();
				//}
			//END FIX NG

			this.posts.each(function(post)
			{
				post.show(fadeIn);
			});
		} else if (fadeIn && this.comment.posts.length == 1)
		// neue postings sollen angezeigt werden, wenn es die ersten sind
			this.comment.showHidePosts();
	},

	replace: function(post)
	{
	},

	remove: function()
	{
		this.posts.each(function(post) { post.detach(); });
		if (this.element) {
			this.element.fade({ duration: 0.25, afterFinish: this.element.remove.bind(this.element) });
			this.element.remove();
		}
		this.detach();
	},

	detach: function()
	{
		this.lb.posts[this.content.PostingID.toString()] = null;
		this.posts.clear();
		this.element = null;
		this.parent = null;
		this.comment.decPostCount();
		this.comment = null;
		this.lb = null;
	},

	addPost: function(post)
	{
		this.posts[this.posts.length] = post;
		post.comment = this.comment;
		post.parent = this;
		this.comment.incPostCount();
	},

	addHickePic: function()
	{
		if (this.content.Pic != '') {
			//!! this.element.down('td.hicke').update('<a href="?page=showpic&_hicke=true&_u=http://hicke.derStandard.at/'+this.content.Pic.replace('Hicke','img').replace('.jpg','_big.jpg')+'" target="_blank" alt="Hickersberg Foto" title="Wir machen Sie zum Teamchef derStandard.at/HickersbergYourself"><img src="http://images.derstandard.at/t/18/forumpics/'+this.content.Pic+'" style="margin: 0 0 0 2px; padding: 0; border: 0; width: 72px; height: 72px" /></a>');
		}
	}
});

function addLink(id, type, lnk)
{
	switch (type) {
		// link "antworten" 
		case (0):
			document.getElementById("p" + id + "0").innerHTML = "<a href=\"javascript:void window.open('/?page=post&amp;re=" + id + "','','toolbar=no,menubar=no,scrollbars=no,resizable=no,width=515,height=515');\" title=\"Klicken Sie hier, wenn Sie auf dieses Posting antworten m&ouml;chten.\" onmouseover=\"window.status='Auf dieses Posting antworten';return true;\" onMouseOut=\"window.status='';return true;\"><img border='0' width='9' height='11' alt='' src='http://derstandard.at/img/cont/lnk/artikel_093875.gif'>antworten&nbsp;</a>";
			break;
		// link "bewerten" 
		case (1):
			document.getElementById("p" + id + "1").innerHTML = "<a href=\"javascript:void window.open('/?page=postbewerten&amp;postID=" + id + "','','toolbar=no,menubar=no,scrollbars=no,resizable=no,width=515,height=505');\" title=\"Geben Sie Ihre Bewertung &uuml;ber die Qualit&auml;t dieses Postings ab.\" onmouseover=\"window.status='Dieses Posting bewerten';return true;\" onMouseOut=\"window.status='';return true;\"><img border='0' width='9' height='11' alt='' src='http://derstandard.at/img/cont/lnk/artikel_093875.gif'>bewerten&nbsp;</a>";
			break;
		// link "melden" 
		case (2):
			document.getElementById("p" + id + "2").innerHTML = "<a href=\"javascript:void window.open('/?page=postmelden&amp;re=" + id + "','','toolbar=no,menubar=no,scrollbars=no,resizable=no,width=515,height=505');\" title=\"Melden Sie Postings an die Redaktion, wenn diese den Community Richtlinien widersprechen.\" onmouseover=\"window.status='Dieses Posting der Redaktion melden';return true;\" onMouseOut=\"window.status='';return true;\"><img border='0' width='9' height='11' alt='' src='http://derstandard.at/img/cont/lnk/artikel_990000.gif'>melden&nbsp;</a>";
			break;
		default:
			// void
			break;
	}
}

