function $XML(Obj) {
	Obj.getChildren = function() {
		var Ar = [];
		$A(this.childNodes).each(function(e) {
			if(e.nodeType > 2) return;
			Ar[Ar.length] = $XML(e);
		});
		return $A(Ar);
	}
	
	Obj.getAttribute = function(key) {
		for(var i = 0; i < this.attributes.length; i++) {
			var attr = this.attributes[i];
			if(attr.nodeName == key) return attr.nodeValue;
		}
	}
	return Obj;
}

function ucfirst(str) {
	return str.charAt(0).toUpperCase() + str.substr(1, str.length - 1);
}

LD = new Class({
	Page: '',
	PageNum: '',
	Id: '',
	Link: '',
	Translate: [],
	Cookie: '',
	Timer: 0,
	Updater: {},
	Root: '',
	CommentColour: {},
	Comments: [],
	CommentCount: 0,
	Theme: '',
	
	initialize: function() {
		this.Cookie = Cookie.get('LDState');
		if(!this.Cookie) {
			this.SetCookie(0);
			this.Cookie = '0';
		}
		this.Cookie = this.Cookie.toInt();
	},
	
	AttachLink: function() { 
		var items = $$('div#Panel ul');
		items.each(function(item) {
			var h2 = item.getElement('li h2');
			if(h2 && h2.innerHTML == this.Translate[0]) {
				var Filter = 'li ul li a';
				switch(this.Theme) {
					case 'organic': Filter = 'li a'; break;
				}
				item.getElement(Filter).setProperty('id', 'LDLink');
			}
		}.bind(this));
		
		this.Link = $('LDLink');
		this.Link.innerHTML = (this.Cookie) ? this.Translate[1] : this.Translate[2];
		this.Link.addEvent('click', this.CheckState.bind(this));
		
		if(this.Cookie) this.Start();
	},
	
	CheckState: function() {
		if(this.Cookie) this.Stop();
		else this.Start();
		this.SetCookie(this.Cookie);
	},
	
	SetCookie: function(state) {
		Cookie.set('LDState', state.toString(), {
				path: '/',
				duration: 365
			});
		},
		
	Start: function() {
		this.Updater = this.Live.periodical(this.Timer, this);
		this.Link.innerHTML = this.Translate[1];
		this.Cookie = 1;
	},
	
	Stop: function() {
		$clear(this.Updater);
		this.Link.innerHTML = this.Translate[2];
		this.Cookie = 0;
	},
	
	Live: function() {
		var Jax = new Ajax(this.Root + 'extensions/LiveDiscussions/ajax.php', {
			autoCancel: true,
			data: 'page=' + this.Page + '&pgnum=' + this.PageNum + '&id=' + this.Id,
			onComplete: this.Update.bind(this)
		});
		Jax.request();
	},
	
	Update: function(response) {
		var XML = this.CreateXML(response);
		XML = $XML(XML);
		var Action = XML.documentElement.attributes[0].nodeValue;
		if(Action == 'kill') {
			this.Stop();
			return;
		}
		
		var Updates = XML.getChildren()[0].getChildren();
		
		if(this.Page == 'index') {
			Updates.each(function(updt) {
				var New = false;
				var Prepend = '';
				updt.getChildren().each(function(e) {
					if(e.tagName == 'new') New = true;
					else {
						if(!Prepend) Prepend += '[';
						else Prepend += ', ';
						Prepend += ucfirst(e.tagName);
					}
				});
				if((updt.getChildren().length > 0 && !New) || (New && updt.getChildren().length > 1)) {
					Prepend += ']';
				}
				if(!New) var El = $('Discussion_' + updt.getAttribute('id'));
				else var El = this.CreateNewDiscussion(updt);
				El = this.UpdateDiscussion(El, updt, Prepend);
				
				if(New) El.injectBefore($('Discussions').getFirst());
				
				new Fx.Style(El.getFirst(), 'background-color').start('#FFFEEC', '#FEFECC');
			}.bind(this));
		} else if(this.Page == 'comments') {
			Updates.each(function(updt) {
				var El = this.CreateNewComment(updt);
				this.UpdateComment(El, updt);
				El.injectInside($('Comments'));
				this.Comments[this.Comments.length] = El;
			}.bind(this));
			this.SetColours();
		}
	},
	
	SetColours: function() {
		if(this.CommentCount >= this.Comments.length) return;
		var Colour = this.CommentColour;
		for(var i = this.Comments.length - 1; i > -1; i--) {
			var el = this.Comments[i];
			if(i == this.Comments.length) {
				new Fx.Style(el, 'background-color').start('#fff', Colour);
				continue;
			}
			Colour = Colour.mix('#fff', 20);
			el.setStyle('background-color', Colour);
		}
		this.CommentCount = this.Comments.length;
	},
	
	CreateXML: function(str) {
		if(Window.ie) return new ActiveXObject('Microsoft.XMLDOM').loadXML(str);
		else return new DOMParser().parseFromString(str, 'application/xml');
	},
	
	CreateNewDiscussion: function(updt) {
		return new Element('li', {
			id: 'Discussion_' + updt.getAttribute('id'),
			class: 'Discussion NewComments'
		}).adopt(
			new Element('ul').adopt([
				new Element('li', { class: 'DiscussionType' }),
				new Element('li', { class: 'DiscussionTopic' }).adopt(
					new Element('a', { href: updt.getAttribute('LinkTarget') })
				),
				new Element('li', { class: 'DiscussionCategory' }).adopt([
					new Element('span'),
					new Element('a', { href: updt.getAttribute('CatTarget') })
				]),
				new Element('li', { class: 'DiscussionStarted' }).adopt(
					new Element('span')
				),
				new Element('li', { class: 'DiscussionComments' }).adopt(
					new Element('span')
				),
				new Element('li', { class: 'DiscussionLastComment' }).adopt(
					new Element('span')
				),
				new Element('li', { class: 'DiscussionActive' }).adopt(
					new Element('span')
				),
				new Element('li', { class: 'DiscussionNew' }).adopt(
					new Element('span')
				)
			])
		);
	},
	
	CreateNewComment: function(updt) {
		return new Element('li', {
			id: 'Comment_' + updt.getAttribute('id')
		}).adopt([
			new Element('div', { class: 'CommentHeader' }).adopt([
				new Element('ul').adopt([
					new Element('li').adopt([
						new Element('div', {
							class: 'CommentIcon',
							styles: { 'background-image': "url('" + updt.getAttribute('icon') + "');" }
						}),
						new Element('a', { href: updt.getAttribute('LinkTarget') })
					]),
					new Element('li', { styles: { color: '#CC0000' } })
				]),
				new Element('span')
			]),
			new Element('div', {
				id: 'CommentBody_' + updt.getAttribute('id'),
				class: 'CommentBody'
			})
		]);
	},
	
	UpdateComment: function(el, updt) {
		el.getElement('div.CommentHeader span').innerHTML = '&nbsp;';
		el.getElement('div.CommentHeader ul li a').innerHTML = updt.getAttribute('user');
		el.getElements('div.CommentHeader ul li')[1].innerHTML = ' ' + this.Translate[8];
		el.getElement('div.CommentBody').innerHTML = updt.getAttribute('content');
	},
	
	UpdateDiscussion: function(el, updt, Prepend) {
		var rows = el.getElements('ul li');
		
		rows[0].innerHTML = Prepend;
		rows[1].getChildren()[0].innerHTML = updt.getAttribute('name');
		
		rows[2].getChildren()[0].innerHTML = this.Translate[5] + ' ';
		rows[2].getChildren()[1].innerHTML = updt.getAttribute('category');
		
		rows[3].getChildren()[0].innerHTML = this.Translate[3] + ' ';
		rows[3].getElements('a').each(function(e) { e.remove(); });
		if(rows[3].childNodes.length < 2) {
			rows[3].appendChild(document.createTextNode(updt.getAttribute('started')));
		} else {
			$A(rows[3].childNodes).getLast().nodeValue = updt.getAttribute('started');
		}
		
		rows[4].getChildren()[0].innerHTML = this.Translate[6] + ' ';
		if(rows[4].childNodes.length < 2) {
			rows[4].appendChild(document.createTextNode(updt.getAttribute('comments')));
		} else {
			$A(rows[4].childNodes).getLast().nodeValue = updt.getAttribute('comments');
		}
		
		rows[5].getChildren()[0].innerHTML = this.Translate[4] + ' ';
		rows[5].getElements('a').each(function(e) { e.remove(); })
		if(rows[5].childNodes.length < 2) {
			rows[5].appendChild(document.createTextNode(updt.getAttribute('last')));
		} else {
			$A(rows[5].childNodes).getLast().nodeValue = updt.getAttribute('last');
		}
		
		rows[6].getChildren()[0].innerHTML = this.Translate[7] + ' ';
		if(rows[6].childNodes.length < 2) {
			rows[6].appendChild(document.createTextNode(updt.getAttribute('active')));
		} else {
			$A(rows[6].childNodes).getLast().nodeValue = updt.getAttribute('active');
		}
		
		rows[7].getChildren()[0].innerHTML = this.Translate[8] + ' ';
		if(rows[7].childNodes.length < 2) {
			rows[7].appendChild(document.createTextNode(updt.getAttribute('new')));
		} else {
			$A(rows[7].childNodes).getLast().nodeValue = updt.getAttribute('new');
		}
		
		return el;
	}
});

var LiveDiscussion = new LD();

Window.addEvent('domready', function() {
	LiveDiscussion.AttachLink();
});
