String.prototype.sReplace = function(find, replace) {
	return this.split(find).join(replace);
};

String.prototype.repeat = function(times) {
	var rep = new Array(times + 1);
	return rep.join(this);
}

var YShout = function() {
	var self = this;
	var args = arguments;
	$(document).ready(function() {
		self.init.apply(self, args);
	});
} 

var yShout;

YShout.prototype = {
	animSpeed: 300,
	p: [],
		
	init: function(options) {
		yShout = this;
		var self = this;
		
		this.initializing = true;
		
		var dOptions = {
			yPath: './addons/yshout/',
			log: 1
		};

		this.options = jQuery.extend(dOptions, options);

		this.postNum = 0;
		this.floodAttempt = 0;	
		
		// Correct for missing trailing /
		if ((this.options.yPath.length > 0) && (this.options.yPath.charAt(this.options.yPath.length - 1) != '/'))
			this.options.yPath += '/';
		
		if (this.options.yLink) {
			if (this.options.yLink.charAt(0) != '#')
				this.options.yLink = '#' + this.options.yLink;
		
			$(this.options.yLink).click(function() {
				self.openYShout.apply(self);
				return false;
			});
		}
		
		// Load YShout from a link, in-page
		if (this.options.h_loadlink) {
			$(this.options.h_loadlink).click(function() {
				$('#yshout').css('display', 'block');
				$(this).unbind('click').click(function() { return false; });
				return false;
			});
			this.load(true);
		} else
			this.load();
		

	},
	
	load: function(hidden) {
		if ($('#yshout').length == 0) return;

		if (hidden) $('#yshout').css('display', 'none');
		
		this.ajax(this.initialLoad, { 
			reqType: 'init',
			yPath: this.options.yPath,
			log: this.options.log
		});
	},
	
	initialLoad: function(updates) {
		if (updates.yError) alert('There appears to be a problem: \n' + updates.yError + '\n\nIf you haven\'t already, try chmodding everything inside the YShout directory to 777.');
		this.d('In initialLoad');
		var self = this;
		
		this.prefs = jQuery.extend(updates.prefs, this.options.prefs);
		this.initForm();
		this.initRefresh();
		this.initLinks();
		if (this.prefs.flood) this.initFlood();

		if (updates.nickname)
			$('#ys-input-nickname')
				.removeClass('ys-before-focus')
				.addClass( 'ys-after-focus')
				.val(updates.nickname);

		if (updates)
			this.updates(updates);
	
		
		if (!this.prefs.doTruncate) {
			$('#ys-posts').css('height', $('#ys-posts').height + 'px');
		}

		if (!this.prefs.inverse) {
			var postsDiv = $('#ys-posts')[0];
			postsDiv.scrollTop = postsDiv.scrollHeight;
		}

		this.markEnds();
		
		this.initializing = false;
	},

	initForm: function() {
		this.d('In initForm');

		var yPath = this.options.yPath ? this.options.yPath : './addons/yshout/';
		var SmPath = this.options.yPath ? this.options.yPath : './addons/yshout/';
		var smileys = 
				'<div class="ys-smiley-bar">' +
					'<img src="' + SmPath + 'smilies/crying.png" onclick="javascript:smiley(\';(\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/nod.png" onclick="javascript:smiley(\'(nod)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/shake.png" onclick="javascript:smiley(\'(shake)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/happy.png" onclick="javascript:smiley(\'(happy)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/puke.png" onclick="javascript:smiley(\'(puke)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/handshake.png" onclick="javascript:smiley(\'(handshake)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/evilgrin.png" onclick="javascript:smiley(\'(grin)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/hi.png" onclick="javascript:smiley(\'(wave)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/bigsmile.png" onclick="javascript:smiley(\':D\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/cool.png" onclick="javascript:smiley(\'8)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/lipssealed.png" onclick="javascript:smiley(\':x\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/speechless.png" onclick="javascript:smiley(\':|\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/tongueout.png" onclick="javascript:smiley(\':P\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/sadsmile.png" onclick="javascript:smiley(\':(\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/smile.png" onclick="javascript:smiley(\':)\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/wink.png" onclick="javascript:smiley(\':o\');" style="cursor: pointer;" /> ' +
					'<img src="' + SmPath + 'smilies/heidy.png" onclick="javascript:smiley(\'(heidy)\');" style="cursor: pointer;" />' +
				'</div>';
		var inputUsername = this.options.inputUsername ? this.options.inputUsername : false;

		var postForm = 
			'<form id="ys-post-form"' + (this.prefs.inverse ? 'class="ys-inverse"' : '' ) + '><fieldset>' +
				(this.prefs.showSmileys && (inputUsername || this.prefs.allowGuests) ? smileys : '') +
				(!inputUsername && this.prefs.allowGuests ? '<input id="ys-input-nickname" value="' + this.prefs.defaultNickname + '" type="text" accesskey="N" maxlength="' + this.prefs.nicknameLength + '" class="ys-before-focus" />' : '<input id="ys-input-nickname" value="' + inputUsername + '" type="hidden" readonly="readonly" />') +
				'<input id="ys-input-userid" value="' + (this.options.inputUserID ? this.options.inputUserID : '1') + '" type="hidden" readonly="readonly" />' +
				'<input id="ys-input-color" value="' + (this.options.inputColor ? this.options.inputColor : '') + '" type="hidden" readonly="readonly" />' +
				(inputUsername || this.prefs.allowGuests ? '<input id="ys-input-message" value="' + (this.options.constMessage ? this.options.constMessage : this.prefs.defaultMessage) + '" type="text" accesskey="M" maxlength="' + this.prefs.messageLength + '" class="ys-before-focus" />' : '') +
				(this.prefs.showSubmit && (inputUsername || this.prefs.allowGuests) ? '<input id="ys-input-submit" value="' + (this.options.constSubmit ? this.options.constSubmit : this.prefs.defaultSubmit) + '" accesskey="S" type="submit" />' : '') +
				(this.prefs.postFormLink == 'cp' ? '<a title="' + (this.options.constControlPanel ? this.options.constControlPanel : 'View YShout Control Panel') + '" class="ys-post-form-link" id="ys-cp-link" href="' + yPath + 'cp/">' + (this.options.constAdminCP ? this.options.constAdminCP : 'Admin CP') + '</a>' : '') +
				(this.prefs.postFormLink == 'history' ? '<a title="' + (this.options.constHistoryViewer? this.options.constHistoryViewer : 'View YShout History') + '" class="ys-post-form-link" id="ys-history-link" href="' + yPath + 'history/?log=' + (this.options.log ? this.options.log : '1') + '&offset=' + (this.options.timeOffset ? this.options.timeOffset : '0') + '&language=' + (this.options.constLanguage ? this.options.constLanguage : 'english') + '">' + (this.options.constHistory ? this.options.constHistory : 'View History') + '</a>' : '') +
				(!inputUsername && !this.prefs.allowGuests ? '<br />' + (this.options.constLogin ? this.options.constLogin : 'You must be logged in to use the shoutbox!') : '') +
			'</fieldset></form>';

		var postsDiv = '<div id="ys-posts"></div>';

		if (this.prefs.inverse) $('#yshout').html(postForm + postsDiv);
		else $('#yshout').html(postsDiv + postForm);
		
		$('#ys-posts')
			.before('<div id="ys-before-posts"></div>')
			.after('<div id="ys-after-posts"></div>');
		
		$('#ys-post-form')
			.before('<div id="ys-before-post-form"></div>')
			.after('<div id="ys-after-post-form"></div>');
		
		var self = this;

		var defaults = { 
			'ys-input-nickname': self.prefs.defaultNickname, 
			'ys-input-message': self.options.constMessage ? self.options.constMessage : self.prefs.defaultMessage
		};

		var keypress = function(e) { 
			var key = window.event ? e.keyCode : e.which; 
			if (key == 13 || key == 3) {
				self.send.apply(self);
				return false;
			}
		};

		var focus = function() { 
			if (this.value == defaults[this.id])
				$(this).removeClass('ys-before-focus').addClass( 'ys-after-focus').val('');
		};

		var blur = function() { 
			if (this.value == '')
				$(this).removeClass('ys-after-focus').addClass('ys-before-focus').val(defaults[this.id]); 
		};

		$('#ys-input-message').keypress(keypress).focus(focus).blur(blur);
		$('#ys-input-nickname').keypress(keypress).focus(focus).blur(blur);

		$('#ys-input-submit').click(function(){ self.send.apply(self) });
		$('#ys-post-form').submit(function(){ return false });
	},

	initRefresh: function() {
		var self = this;
		if (this.refreshTimer) clearInterval(this.refreshTimer)
		this.refreshTimer = setInterval(function() {
			self.ajax(self.updates, { reqType: 'refresh' });
		}, this.prefs.refresh); // ! 3000..?
	},

	initFlood: function() {
		this.d('in initFlood');
		var self = this;
		this.floodCount = 0;
		this.floodControl = false;

		this.floodTimer = setInterval(function() {
			self.floodCount = 0;
		}, this.prefs.floodTimeout);
	},

	initLinks: function() {
		if ($.browser.msie) return;
		
		var self = this;

		$('#ys-cp-link').click(function() {
			self.openCP.apply(self);
			return false;
		});

		$('#ys-history-link').click(function() {
			self.openHistory.apply(self);
			return false;
		});

	},
	
	openCP: function() {
		var self = this;
		if (this.cpOpen) return;
		this.cpOpen = true;
		
		var url = this.options.yPath + 'cp/';

		$('body').append('<div id="ys-overlay"></div><div class="ys-window" id="ys-cp"><a title="Close Admin CP" href="#" id="ys-closeoverlay-link">Close</a><a title="View History" href="#" id="ys-switchoverlay-link">View History</a><object class="ys-browser" id="cp-browser" data="' + url +'" type="text/html">Something went horribly wrong.</object></div>');

		$('#ys-overlay, #ys-closeoverlay-link').click(function() { 
			self.reload.apply(self, [true]);
			self.closeCP.apply(self);
			return false; 
		}); 
		
		$('#ys-switchoverlay-link').click(function() { 
			self.closeCP.apply(self);
			self.openHistory.apply(self);
			return false;
		});

	},

	closeCP: function() {
		this.cpOpen = false;
		$('#ys-overlay, #ys-cp').remove();
	},

	openHistory: function() {
		var self = this;
		if (this.hOpen) return;
		this.hOpen = true;
		var url = this.options.yPath + 'history/?log=' + (this.options.log ? this.options.log : '1') + '&offset=' + (this.options.timeOffset ? this.options.timeOffset : '0') + '&language=' + (this.options.constLanguage ? this.options.constLanguage : 'english');
		$('body').append('<div id="ys-overlay"></div><div class="ys-window" id="ys-history"><a title="Close history" href="#" id="ys-closeoverlay-link">Close</a><a title="View Admin CP" href="#" id="ys-switchoverlay-link">View Admin CP</a><object class="ys-browser" id="history-browser" data="' + url +'" type="text/html">Something went horribly wrong.</object></div>');

		$('#ys-overlay, #ys-closeoverlay-link').click(function() { 
			self.reload.apply(self, [true]);
			self.closeHistory.apply(self);
			return false; 
		}); 

		$('#ys-switchoverlay-link').click(function() { 
			self.closeHistory.apply(self);
			self.openCP.apply(self);
			return false;
		});

	},

	closeHistory: function() {
		this.hOpen = false;
		$('#ys-overlay, #ys-history').remove();
	},
	
	openYShout: function() {
		var self = this;
		if (this.ysOpen) return;
		this.ysOpen = true;
		url = this.options.yPath + 'example/yshout.html';

		$('body').append('<div id="ys-overlay"></div><div class="ys-window" id="ys-yshout"><a title="Close YShout" href="#" id="ys-closeoverlay-link">Close</a><object class="ys-browser" id="yshout-browser" data="' + url +'" type="text/html">Something went horribly wrong.</object></div>');
	
		$('#ys-overlay, #ys-closeoverlay-link').click(function() { 
			self.reload.apply(self, [true]);
			self.closeYShout.apply(self);
			return false; 
		}); 
	},

	closeYShout: function() {
		this.ysOpen = false;
		$('#ys-overlay, #ys-yshout').remove();
	},
	
	send: function() {
		if (!this.validate()) return;
		if (this.prefs.flood && this.floodControl) return;

		var  postNickname = $('#ys-input-nickname').val(), postUserID = $('#ys-input-userid').val(), postColor = $('#ys-input-color').val(), postMessage = $('#ys-input-message').val();

		if (postMessage == '/cp')
			this.openCP();
		else if (postMessage == '/history')
			this.openHistory();
		else
			this.ajax(this.updates, {
				reqType: 'post',
				nickname: postNickname,
				userid: postUserID,
				color: postColor,
				message: postMessage
			});

		$('#ys-input-message').val('')

		if (this.prefs.flood) this.flood();
	},

	validate: function() {
		var nickname = $('#ys-input-nickname').val(),
			userid = $('#ys-input-userid').val(),
			color = $('#ys-input-color').val(),
			message = $('#ys-input-message').val(),
			error = false;

		if (this.options.inputUsername && nickname != this.options.inputUsername) {
			alert('You can\'t change your username.');
			error = true;
		}

		if (this.options.inputUserID && userid != this.options.inputUserID) {
			alert('You can\'t change your user ID.');
			error = true;
		}

		if (color != this.options.inputColor) {
			alert('You can\'t change user\'s group color.');
			error = true;
		}

		var showInvalid = function(input) {
			$(input).removeClass('ys-input-valid').addClass('ys-input-invalid')[0].focus();
			error = true;
		}

		var showValid = function(input) {
			$(input).removeClass('ys-input-invalid').addClass('ys-input-valid');
		}

		if (nickname == '' || nickname == this.prefs.defaultNickname)
			showInvalid('#ys-input-nickname');
		else
			showValid('#ys-input-nickname');

		var constMessage = this.options.constMessage ? this.options.constMessage : this.prefs.defaultMessage;
		if (message == '' || message == constMessage)
			showInvalid('#ys-input-message');
		else
			showValid('#ys-input-message');

		return !error;
	},

	flood: function() {
		var self = this;
		this.d('in flood');
		if (this.floodCount < this.prefs.floodMessages) {
			this.floodCount++;
			return;
		}

		this.floodAttempt++;
		this.disable();

		if (this.floodAttempt == this.prefs.autobanFlood)
			this.banSelf('You have been banned for flooding the shoutbox!');
			
		setTimeout(function() {
			self.floodCount = 0;
			self.enable.apply(self);
		}, this.prefs.floodDisable);
	},

	disable: function () {
		$('#ys-input-submit')[0].disabled = true;
		this.floodControl = true;
	},

	enable: function () {
		$('#ys-input-submit')[0].disabled = false;
		this.floodControl = false;
	},
	
	findBySame: function(ip) {
		if (!$.browser.safari) return;
		
		var same = [];
		for (var i = 0; i < this.p.length; i++)
			if (this.p[i].adminInfo.ip == ip) 
				same.push(this.p[i]);
		
		for (var i = 0; i < same.length; i++) {
			$('#' + same[i].id).fadeTo(this.animSpeed, .8).fadeTo(this.animSpeed, 1);
		}
	},
	
	updates: function(updates) {
		if (!updates) return;
		if (updates.prefs) this.prefs = updates.prefs;
		if (updates.posts) this.posts(updates.posts);
		if (updates.banned) this.banned();
	},

	banned: function() {
		var self = this;
		clearInterval(this.refreshTimer);
		clearInterval(this.floodTimer);
		if (this.initializing)
			$('#ys-post-form').css('display', 'none');
		else
			$('#ys-post-form').fadeOut(this.animSpeed);
		
		if ($('#ys-banned').length == 0) {
			$('#ys-input-message')[0].blur();
			$('#ys-posts').append('<div id="ys-banned"><span>You\'re banned. Click <a href="#" id="ys-unban-self">here</a> to unban yourself if you\'re an admin. If you\'re not, go <a href="' + this.options.yPath + 'cp/" id="ys-banned-cp-link">log in</a>!</span></div>');

			$('#ys-banned-cp-link').click(function() {
				self.openCP.apply(self);
				return false;
			});
			
			$('#ys-unban-self').click(function() {
				self.ajax(function(json) {
					if (!json.error)
						self.unbanned();
					 else if (json.error == 'admin')
						alert('You can only unban yourself if you\'re an admin.');
				}, { reqType: 'unbanself' });
				return false;
			});
		}		
	},

	unbanned: function() {
		var self = this;
		$('#ys-banned').fadeOut(function() { $(this).remove(); });
		this.initRefresh();
		$('#ys-post-form').css('display', 'block').fadeIn(this.animSpeed, function(){
			self.reload();
		});
	},
	
	posts: function(p) {
		for (var i = 0; i < p.length; i++) {
			this.post(p[i]);
		}
		
		this.truncate();
		
		if (!this.prefs.inverse) {
			var postsDiv = $('#ys-posts')[0];
			postsDiv.scrollTop = postsDiv.scrollHeight;
		}
	},

	post: function(post) {
		var self = this;

		var timeOffset = self.options.timeOffset ? self.options.timeOffset : '0';
		var pad = function(n) { return n > 9 ? n : '0' + n; };
		var date = function(ts) { return new Date((ts - timeOffset) * 1000); };
		var time = function(ts) { 
			var d = date(ts);
			var h = d.getHours(), m = d.getMinutes();

			if (self.prefs.timestamp == 12) {
				h = (h > 12 ? h - 12 : h);
				if (h == 0) h = 12;
			}

			return pad(h) + ':' + pad(m);
		};

		var dateStr = function(ts) {
			var t = date(ts);

		  var Y = t.getFullYear();
		  var M = t.getMonth();
		  var D = t.getDay();
		  var d = t.getDate();
		  var day = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][D];
		  var mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][M];

		  return day + ' ' + mon + '. ' + d + ', ' + Y;
		};

		var self = this;

		this.postNum++;
		var id = 'ys-post-' + this.postNum;
		post.id = id;
		
		post.message = this.links(post.message);
		post.message = this.smileys(post.message);
//		post.message = this.bbcode(post.message);
		post.message = this.bbcodes(post.message);
		post.message = this.censor(post.message);
		var html = 
			'<div id="' + id + '" class="ys-post' + (post.admin ? ' ys-admin-post' : '') + (post.banned ? ' ys-banned-post' : '') + '">' +
				(this.prefs.timestamp > 0 ? '<span class="ys-post-timestamp">' + time(post.timestamp) + '</span> ' : '') +
				(post.userid != 1 ? '<span class="ys-post-nickname"><a href="./userdetails.php?id=' + post.userid + '" target="_blank"' + (post.color ? ' style="color: ' + post.color + ';"' : '') + '>' + post.nickname + '</a></span>' + this.prefs.nicknameSeparator + ' ' : '<span class="ys-post-nickname"' + (post.color ? ' style="color: ' + post.color + ';"' : '') + '>' + post.nickname + '</span>' + this.prefs.nicknameSeparator + ' ') +
				'<span class="ys-post-message">' + post.message + '</span> ' +
				'<span class="ys-post-info' + (this.prefs.info == 'overlay' ? ' ys-info-overlay' : ' ys-info-inline') + '">' + (post.adminInfo ? '<em>IP:</em> ' + post.adminInfo.ip + ', ' : '') + '<em>Posted:</em> ' + dateStr(post.timestamp) + ' at ' + time(post.timestamp)  + '.</span>' +
				'<span class="ys-post-actions"><a title="Show post information" class="ys-info-link" href="#">Info</a>'  + (post.adminInfo ? ' | <a title="Delete post" class="ys-delete-link" href="#">Delete</a> | ' + (post.banned ? '<a title="Unban user" class="ys-ban-link" href="#">Unban</a>' : '<a title="Ban user" class="ys-ban-link" href="#">Ban</a>') : '') + '</span>' +
			'</div>';
		if (this.prefs.inverse) $('#ys-posts').prepend(html);
		else $('#ys-posts').append(html);
		
		this.p.push(post);

		$('#' + id)
			.find('.ys-post-nickname').click(function() {
				if (post.adminInfo)
					self.findBySame(post.adminInfo.ip);
			}).end()
			.find('.ys-info-link').toggle(
				function() { self.showInfo.apply(self, [id, this]); return false; },
				function() { self.hideInfo.apply(self, [id, this]); return false; })
			.end()
			.find('.ys-ban-link').click(
				function() { self.ban.apply(self, [post, id]); return false; })
			.end()
			.find('.ys-delete-link').click(
				function() { self.del.apply(self, [post, id]); return false; });
			
	},
	
	showInfo: function(id, el) {
		var jEl = $('#' + id + ' .ys-post-info');
		if (this.prefs.info == 'overlay')
			jEl.css('display', 'block').fadeIn(this.animSpeed);
		else
			jEl.slideDown(this.animSpeed);
		
		el.innerHTML ='Close Info'
		return false;
	},
	
	hideInfo: function(id, el) {
		var jEl = $('#' + id + ' .ys-post-info');
		if (this.prefs.info == 'overlay')
			jEl.fadeOut(this.animSpeed);
		else
			jEl.slideUp(this.animSpeed);
			
		el.innerHTML = 'Info';
		return false;
	}, 
	
	ban: function(post, id) {
		var self = this;

		var link = $('#' + id).find('.ys-ban-link')[0];

		switch(link.innerHTML) {
			case 'Ban':
				var pars = {
					reqType: 'ban',
					ip: post.adminInfo.ip,
					nickname: post.nickname
				};

				this.ajax(function(json) {
					if (json.error) {
						switch (json.error) {
							case 'admin':
								self.error('You\'re not an admin. Log in through the Admin CP to ban people.');
								break;
						}
						return;
					}
					//alert('p: ' + this.p + ' / ' + this.p.length);
					if (json.bannedSelf)
						self.banned(); // ?
						
					else 						
						$.each(self.p, function(i) {
							if (this.adminInfo && this.adminInfo.ip == post.adminInfo.ip) 
									$('#' + this.id)
										.addClass('ys-banned-post')
										.find('.ys-ban-link').html('Unban');
						});
						
				}, pars);
				
				link.innerHTML = 'Banning...';
				return false;
				break;
			
			case 'Banning...':
				return false;
				break;
			
			case 'Unban':
				var pars = {
					reqType: 'unban',
					ip: post.adminInfo.ip
				};
	
				this.ajax(function(json) {
					if (json.error) {
						switch(json.error) {
							case 'admin':
								self.error('You\'re not an admin. Log in through the Admin CP to unban people.');
								return;
								break;
						}
					}
					
					$.each(self.p, function(i) {
						if (this.adminInfo && this.adminInfo.ip == post.adminInfo.ip) 
							$('#' + this.id)
								.removeClass('ys-banned-post')
								.find('.ys-ban-link').html('Ban');
					});
					
				}, pars);
	
				link.innerHTML = 'Unbanning...';
				return false;
				break;
				
			case 'Unbanning...':
				return false;
				break;
		}
	},
	
	del: function(post, id) {
		var self = this;
		var link = $('#' + id).find('.ys-delete-link')[0];

		if (link.innerHTML == 'Deleting...') return;
	
		var pars = {
			reqType: 'delete',
			uid: post.uid
		};

		self.ajax(function(json) {
			if (json.error) {
				switch(json.error) {
					case 'admin':
						self.error('You\'re not an admin. Log in through the Admin CP to ban people.');
						return;
						break;
				}
			}
			self.reload();
		}, pars);

		link.innerHTML = 'Deleting...';
		return false;

	},
	
	banSelf: function(reason) {
		var self = this;

		this.ajax(function(json) {
			if (json.error == false)
				self.banned();
		}, {
			reqType: 'banself',
			nickname: $('#ys-input-nickname').val() 
		});
	},

	censor: function(s) {
		var arrayBadwords = this.options.arrayBadwords ? this.options.arrayBadwords : new Array();
		for (var i = 0; i < arrayBadwords.length; ++i)
			s = s.replace(arrayBadwords[i], '<img src="addons/yshout/smilies/swear.gif" /> ');
		return s;
	},

//	bbcode: function(s) {
//		s = s.sReplace('[i]', '<i>');
//		s = s.sReplace('[/i]', '</i>');
//		s = s.sReplace('[I]', '<i>');
//		s = s.sReplace('[/I]', '</i>');
//
//		s = s.sReplace('[b]', '<b>');
//		s = s.sReplace('[/b]', '</b>');
//		s = s.sReplace('[B]', '<b>');
//		s = s.sReplace('[/B]', '</b>');
//
//		s = s.sReplace('[u]', '<u>');
//		s = s.sReplace('[/u]', '</u>');
//		s = s.sReplace('[U]', '<u>');
//		s = s.sReplace('[/U]', '</u>');
//
//		return s;
//	},

	bbcodes: function(s) {
		s = s.replace(/\[b\]((\s|.)+?)\[\/b\]/, '<b>$1</b>');
		s = s.replace(/\[i\]((\s|.)+?)\[\/i\]/, '<i>$1</i>');
		s = s.replace(/\[u\]((\s|.)+?)\[\/u\]/, '<u>$1</u>');
		s = s.replace(/\[color=([a-zA-Z]+)\]((\s|.)+?)\[\/color\]/i, '<font color="$1">$2</font>');
		s = s.replace(/\[color=(#[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9])\]((\s|.)+?)\[\/color\]/i, '<font color="$1">$2</font>');
		s = s.replace(/\[size=([1-7])\]((\s|.)+?)\[\/size\]/i, '<font size="$1">$2</font>');
		s = s.replace(/\[font=([a-zA-Z ,]+)\]((\s|.)+?)\[\/font\]/i, '<font face="$1">$2</font>');
		return s;
	},

	smileys: function(s) {
		var yp = this.options.yPath;

		var smile = function(str, smiley, image) {
			return str.sReplace(smiley, '<img src="' + yp + 'smilies/' + image + '" />');
		};
		s = smile(s, '(angel)',  'angel.gif');
		s = smile(s, '(hug)',  'bear.gif');
		s = smile(s, '(happy)',  'happy.gif');
		s = smile(s, '(beer)',  'beer.gif');
		s = smile(s, ':D',  'bigsmile.gif');
		s = smile(s, 'xD',  'bigsmile.gif');
		s = smile(s, ';D',  'bigsmile.gif');
		s = smile(s, '(blush)',  'blush.gif');
		s = smile(s, '(bow)',  'bow.gif');
		s = smile(s, '(u)',  'brokenheart.gif');
		s = smile(s, '(call)',  'call.gif');
		s = smile(s, '(clap)',  'clapping.gif');
		s = smile(s, '(empe3)',  'empe3.gif');
		s = smile(s, '(coffee)',  'coffee.gif');
		s = smile(s, '8)',  'cool.gif');
		s = smile(s, ';(',  'cry.gif');
		s = smile(s, '(dance)',  'dance.gif');
		s = smile(s, '(devil)',  'devil.gif');
		s = smile(s, '(doh)',  'doh.gif');
		s = smile(s, '(d)',  'drink.gif');
		s = smile(s, '|(',  'dull.gif');
		s = smile(s, '|-(',  'dull.gif');
		s = smile(s, '(emo)',  'emo.gif');
		s = smile(s, ':O',  'eek.gif');
		s = smile(s, '(envy)',  'envy.gif');
		s = smile(s, '(chuckle)',  'giggle.gif');
		s = smile(s, '(handshake)',  'handshake.gif');
		s = smile(s, '(h)',  'heart.gif');
		s = smile(s, '(hi)',  'hi.gif');
		s = smile(s, '(wave)',  'hi.gif');
		s = smile(s, '(grin)',  'evilgrin.gif');
		s = smile(s, '(inlove)',  'inlove.gif');
		s = smile(s, '(wasntme)',  'itwasntme.gif');
		s = smile(s, ':*',  'kiss.gif');
		s = smile(s, ':x',  'lipssealed.gif');
		s = smile(s, '(m)',  'mail.gif');
		s = smile(s, '(makeup)',  'makeup.gif');
		s = smile(s, '(mm)',  'mmm.gif');
		s = smile(s, '(movie)',  'movie.gif');
		s = smile(s, '(muscle)',  'muscle.gif');
		s = smile(s, '(music)',  'music.gif');
		s = smile(s, '8-|',  'nerd.gif');
		s = smile(s, '(ninja)',  'ninja.gif');
		s = smile(s, '(n)',  'no.gif');
		s = smile(s, '(nod)',  'nod.gif');
		s = smile(s, '(party)',  'party.gif');
		s = smile(s, '(mp)',  'phone.gif');
		s = smile(s, '(pizza)',  'pizza.gif');
		s = smile(s, '(pi)',  'pizza.gif');
		s = smile(s, '(punch)',  'punch.gif');
		s = smile(s, '(rain)',  'rain.gif');
		s = smile(s, '(rofl)',  'rofl.gif');
		s = smile(s, ':(',  'sad.gif');
		s = smile(s, '(shake)',  'shake.gif');
		s = smile(s, '(skype)',  'skype.gif');
		s = smile(s, ':)',  'smile.gif');
		s = smile(s, '(smirk)',  'smirk.gif');
		s = smile(s, ':|',  'speechless.gif');
		s = smile(s, '(*)',  'star.gif');
		s = smile(s, '(sun)',  'sun.gif');
		s = smile(s, '(sweat)',  'sweating.gif');
		s = smile(s, '(talk)',  'talking.gif');
		s = smile(s, '(thing)',  'thinking.gif');
		s = smile(s, ':P',  'tongueout.gif');
		s = smile(s, '(wait)',  'wait.gif');
		s = smile(s, '(dull)',  'dull.gif');
		s = smile(s, '|-(',  'dull.gif');
		s = smile(s, '(cat)',  'cat.gif');
		s = smile(s, ';)',  'wink.gif');
		s = smile(s, ':o',  'wink.gif');
		s = smile(s, ':^)',  'wondering.gif');
		s = smile(s, ':s',  'worried.gif');
		s = smile(s, ':S',  'worried.gif');
		s = smile(s, '(yawn)',  'yawn.gif');
		s = smile(s, '(y)',  'yes.gif');
		s = smile(s, '(whew)',  'whew.gif');
		s = smile(s, '(bandit)',  'bandit.gif');
		s = smile(s, '(bug)',  'bug.gif');
		s = smile(s, '(drunk)',  'drunk.gif');
		s = smile(s, '(fubar)',  'fubar.gif');
		s = smile(s, '(headbang)',  'headbang.gif');
		s = smile(s, '(heidy)',  'heidy.gif');
		s = smile(s, '(finger)',  'middlefinger.gif');
		s = smile(s, '(mooning)',  'mooning.gif');
		s = smile(s, '(poolparty)',  'poolparty.gif');
		s = smile(s, '(rock)',  'rock.gif');
		s = smile(s, '(smoke)',  'smoke.gif');
		s = smile(s, '(swear)',  'swear.gif');
		s = smile(s, '(tmi)',  'tmi.gif');
		s = smile(s, '(toivo)',  'toivo.gif');
		s = smile(s, '(f)',  'flower.gif');
		s = smile(s, '(F)',  'flower.gif');
		s = smile(s, '(puke)',  'puke.gif');
		s = smile(s, '|-)',  'sleepy.gif');
		s = smile(s, ':@',  'angry.gif');
		s = smile(s, '(MySpace)',  'myspace.gif');
		s = smile(s, '(myspace)',  'myspace.gif');
		s = smile(s, '(cash)',  'cash.gif');

		s = smile(s, '(flag:lt)',  'lt.png');
		s = smile(s, '(flag:ru)',  'ru.png');
		s = smile(s, '(flag:gb)',  'gb.png');
		s = smile(s, '(flag:de)',  'de.png');
		s = smile(s, '(flag:be)',  'be.png');
		s = smile(s, '(flag:by)',  'by.png');
		s = smile(s, '(flag:eg)',  'eg.png');
		s = smile(s, '(flag:es)',  'es.png');
		s = smile(s, '(flag:gr)',  'gr.png');
		s = smile(s, '(flag:hk)',  'hk.png');
		s = smile(s, '(flag:hn)',  'hn.png');
		s = smile(s, '(flag:hu)',  'hu.png');
		s = smile(s, '(flag:il)',  'il.png');
		s = smile(s, '(flag:in)',  'in.png');
		s = smile(s, '(flag:iq)',  'iq.png');
		s = smile(s, '(flag:ir)',  'ir.png');
		s = smile(s, '(flag:jp)',  'jp.png');
		s = smile(s, '(flag:kg)',  'kg.png');
		s = smile(s, '(flag:lv)',  'lv.png');
		s = smile(s, '(flag:ne)',  'ne.png');
		s = smile(s, '(flag:tr)',  'tr.png');
		s = smile(s, '(flag:ua)',  'ua.png');
		s = smile(s, '(flag:us)',  'us.png');
		s = smile(s, '(flag:zw)',  'zw.png');
		s = smile(s, '(flag:at)',  'at.png');
		s = smile(s, '(flag:ca)',  'ca.png');
		s = smile(s, '(flag:ch)',  'ch.png');
		s = smile(s, '(flag:cu)',  'cu.png');
		s = smile(s, '(flag:dk)',  'dk.png');
		s = smile(s, '(flag:gr)',  'gr.png');
		s = smile(s, '(flag:no)',  'no.png');
		s = smile(s, '(flag:pl)',  'pl.png');
		s = smile(s, '(flag:py)',  'py.png');
		s = smile(s, '(flag:ro)',  'ro.png');
		s = smile(s, '(flag:si)',  'si.png');
		s = smile(s, '(flag:sn)',  'sn.png');

		s = smile(s, '(banana)',  'banana.gif');
		s = smile(s, '(bzzz)',  'bzzz.gif');
		s = smile(s, '(ciucia)',  'ciucia.gif');
		s = smile(s, '(sn)',  'sn.gif');
		s = smile(s, '(dbanana)',  'dbanana.gif');
		s = smile(s, '(faki)',  'faki.gif');
		s = smile(s, '(fbanana)',  'fbanana.gif');
		s = smile(s, '(ffanas)',  'ffanas.gif');
		s = smile(s, '(inv)',  'inv.gif');
		s = smile(s, '(jebanana)',  'jebanana.gif');
		s = smile(s, '(jfilmas)',  'jfilmas.gif');
		s = smile(s, '(joda)',  'joda.gif');
		s = smile(s, '(lis)',  'lis.gif');
		s = smile(s, '(melzkim)',  'melzkim.gif');
		s = smile(s, '(musicman)',  'musicman.gif');
		s = smile(s, '(nereikia)',  'nereikia.gif');
		s = smile(s, '(rruletka)',  'rruletka.gif');
		s = smile(s, '(sfilmas)',  'sfilmas.gif');
		s = smile(s, '(skaito)',  'skaito.gif');
		s = smile(s, '(sveiki)',  'sveiki.gif');
		s = smile(s, '(tfu)',  'tfu.gif');
		s = smile(s, '(ufanas)',  'ufanas.gif');
		s = smile(s, '(dfemale)',  'dfemale.gif');
		s = smile(s, '(think)',  'thinking.gif');
		s = smile(s, '(parama)',  'parama.gif');
		s = smile(s, '(^)',  'cake.gif');
		s = smile(s, '(time)',  'time.gif');
		s = smile(s, '(aku)',  'aku.gif');
		s = smile(s, '(clapu)',  'clapu.gif');
		s = smile(s, '(axaxa)',  'axaxa.gif');
		s = smile(s, '(labanakt)',  'labanakt.gif');
		s = smile(s, '(pirst)',  'pirst.gif');
		s = smile(s, '(pak)',  'pak.gif');
		s = smile(s, '(av)',  'av.gif');
		s = smile(s, '(muse)',  'muse.gif');
		s = smile(s, '(mda)',  'mda.gif');
		s = smile(s, '(karsta)',  'karsta.gif');

		s = smile(s, '(btt)',  'btt.gif');
		s = smile(s, '(btt-team)',  'btteam.gif');
		s = smile(s, '(lnk)',  'lnk.gif');
		s = smile(s, '(mbtt)',  'mbtt.gif');
		s = smile(s, '(tv3)',  'tv3.gif');
		s = smile(s, '(btv)',  'btv.gif');
		s = smile(s, '(tv6)',  'tv6.gif');
		s = smile(s, '(ltv)',  'ltv.gif');
		s = smile(s, '(youtube)',  'youtube.gif');
		s = smile(s, '(lietuva)',  'lietuva.gif');

		return s;
	},

	links: function(s) {
		return s.replace(/((https|http|ftps|ftp|ed2k|irc):\/\/[\S]+)/gi, '<a href="$1" target="_blank">$1</a>');
	},

	truncate: function(clearAll) {
		var truncateTo = clearAll ? 0 : this.prefs.truncate;
		var posts = $('#ys-posts .ys-post').length;
		if (posts <= truncateTo) return;
		//alert(this.initializing);
		if (this.prefs.doTruncate || this.initializing) {
			var diff = posts - truncateTo;
			for (var i = 0; i < diff; i++)
				this.p.shift();
			
			//	$('#ys-posts .ys-post:gt(' + truncateTo + ')').remove();

			if (this.prefs.inverse) 
				$('#ys-posts .ys-post:gt(' + (truncateTo - 1) + ')').remove();
				else 
				$('#ys-posts .ys-post:lt(' + (posts - truncateTo) + ')').remove();
		}
		
		this.markEnds();		
	},
	
	markEnds: function() {
		$('#ys-posts')
			.find('.ys-first').removeClass('ys-first').end()
			.find('.ys-last').removeClass('ys-last');
			
		$('#ys-posts .ys-post:first-child').addClass('ys-first');
		$('#ys-posts .ys-post:last-child').addClass('ys-last');
	},
	
	reload: function(everything) {
		var self = this;
		this.initializing = true;
		
		if (everything) {
			this.ajax(function(json) { 
				$('#yshout').html(''); 
				clearInterval(this.refreshTimer);
				clearInterval(this.floodTimer);
				this.initialLoad(json); 
			}, { 
				reqType: 'init',
				yPath: this.options.yPath,
				log: this.options.log
			});
		} else {
			this.ajax(function(json) { this.truncate(true); this.updates(json); this.initializing = false; }, {
				reqType: 'reload'
			});
		}
	},

	error: function(str) {
		alert(str);
	},

	json: function(parse) {
		this.d('In json: ' + parse);
		var json = eval('(' + parse + ')');
		if (!this.checkError(json)) return json;
	},

	checkError: function(json) {
		if (!json.yError) return false;

		this.d('Error: ' + json.yError);
		return true;
	},

	ajax: function(callback, pars, html) {
		pars = jQuery.extend({
			reqFor: 'shout'
		}, pars);

		var self = this;

		$.post(this.options.yPath + 'index.php', pars, function(parse) {
			if (parse)
				if (html)
					callback.apply(self, [parse]);
				else
					callback.apply(self, [self.json(parse)]);
			else
				callback.apply(self);
		});
	},

	d: function(message) {
		$('#debug').css('display', 'block').prepend('<p>' + message + '</p>');
		return message;
	}
};