var nativeSplit = nativeSplit || String.prototype.split;

String.prototype.split = function (s /* separator */, limit) {
/*
Cross-Browser Split 0.2.1
By Steven Levithan <http://stevenlevithan.com>
MIT license
*/
	// If separator is not a regex, use the native split method
	if (!(s instanceof RegExp))
		return nativeSplit.apply(this, arguments);

	/* Behavior for limit: If it's...
	 - Undefined: No limit
	 - NaN or zero: Return an empty array
	 - A positive number: Use limit after dropping any decimal
	 - A negative number: No limit
	 - Other: Type-convert, then use the above rules */
	if (limit === undefined || +limit < 0) {
		limit = false;
	} else {
		limit = Math.floor(+limit);
		if (!limit)
			return [];
	}

	var	flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") + (s.multiline ? "m" : ""),
		s2 = new RegExp("^" + s.source + "$", flags),
		output = [],
		lastLastIndex = 0,
		i = 0,
		match;

	if (!s.global)
		s = new RegExp(s.source, "g" + flags);

	while ((!limit || i++ <= limit) && (match = s.exec(this))) {
		var zeroLengthMatch = !match[0].length;

		// Fix IE's infinite-loop-resistant but incorrect lastIndex
		if (zeroLengthMatch && s.lastIndex > match.index)
			s.lastIndex = match.index; // The same as s.lastIndex--

		if (s.lastIndex > lastLastIndex) {
			// Fix browsers whose exec methods don't consistently return undefined for non-participating capturing groups
			if (match.length > 1) {
				match[0].replace(s2, function () {
					for (var j = 1; j < arguments.length - 2; j++) {
						if (arguments[j] === undefined)
							match[j] = undefined;
					}
				});
			}

			output = output.concat(this.slice(lastLastIndex, match.index), (match.index === this.length ? [] : match.slice(1)));
			lastLastIndex = s.lastIndex;
		}

		if (zeroLengthMatch)
			s.lastIndex++;
	}

	return (lastLastIndex === this.length) ?
		(s.test("") ? output : output.concat("")) :
		(limit      ? output : output.concat(this.slice(lastLastIndex)));
};

//XMLData has been moved to /lib/js/default.js
var PeriodicalUpdater =  Class.create({
	initialize: function(c, f, getValue) { //args: callback, frequency, getvalue callback
		var lastValue = getValue();
		new PeriodicalExecuter(function() {
			if(lastValue != (lastValue=getValue())) {
				c();
			}
		},f);
	}
});
//RegExp escape function by Simon Willison, 20/01/06
RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}
function resize(img) {
	img = $(img);
	if(Prototype.Browser.IE) img.hide();
	var parent = img.up();
	var maxWidth = parent.getWidth() * 9 / 10;
	maxWidth = maxWidth < 480 ? maxWidth : 480;
	img.show();
	img.observe('mouseover', function () {
		if(img.resized)
			img.setStyle({cursor:'pointer'});
	});
	img.observe('click', function() {
		if(img.resized) {
			window.open(img.src);
		}
	});
	if(img.width > maxWidth) {
		img.resized = true;
		img.width = maxWidth;
		img.insert({before: '<div class="imgtitle" style="width:'+maxWidth+'px"><a href="'+img.src+'" target="_blank">ภาพนี้ถูกย่อขนาดอยู่ คลิ้กเพื่อขยายภาพ</a></div>'});
	}
	
}

String.prototype.strip2 = function () {
	return this.sub(/^(\s|<br\s*?\/?>)*([\s\S]*?)(\s|<br\s*?\/?>)*$/i,'#{2}');
};

function bbcode(str, preview) {
	//preview = true if use for preview mode
	var s = str.escapeHTML().nl2br();

	//code
	s = s.gsub(/\[code(=([a-z\+]*)?)?\]([\s\S]*?)\[\/code\]/im,
		function(match){
			var d_lang = supportLang[0];
			var code = match[3]
				.strip()
				.gsub('<br />','\n')
				.gsub('<','&lt;') //syntax highlighter required
				.gsub('\\[','&#91;')
				.gsub('\\]','&#93;')
				.gsub(':','&#58;');
			var lang = (match[2]==undefined||match[2]=='')?d_lang:match[2].capitalize();
			if(!supportLang.include(lang))
				lang=d_lang;
			return '<div class="codetitle">Code ('+lang+')</div>'
				+'<pre name="'+(preview?'pcode'+preview:'code')+'" class="'+lang.toLowerCase()+'">'+code+'</pre>';
		});
	//list
	var stack = [];
	var part = s.split(/(\[list.*?\]|\[\/list\])/im);
	s = '';
	part.each(function(x) {
		x = x.sub(/\[list(=([1ai])?)?\]/i, function(match) {
			if(match[2]) {
				var t = 'type'+match[2];
				stack.push('o');
				return '<ol class="'+t+'">';
			} else {
				stack.push('u');
				return '<ul>';
			}
		});
		if(stack.length > 0) {
			x = x.sub(/\[\/list\]/i, function(match) {
				var t = stack[stack.length-1];
				stack.length--;
				return '</'+t+'l>';
			});
			x = x.gsub(/\[\*\]([\s\S]*?)(?=\[\*\]|$)/i,function(match) { return '<li>'+match[1].strip2()+'</li>';});
		}
		s += x;
	});
	//quote
	s = s.gsub(/\[quote(=(.*?)(:\d+)?)?\]/im,function(match) {
		var header = match[2]?('<i>'+ (match[3]?'<a href="javascript:nav.goTo('+match[3].substring(1)+')"><img src="/pictures/link_grau.gif" alt="goto" /></a>':'')
			+match[2].gsub('\\[','&#91;')
			+' ว่าไว้ ...</i><br /><br />'):'';
		return '<blockquote class="quote">' + header;
	});
	//img
	s = s.gsub(/\[img\]([\s\S]*?)\[\/img\]/im,function(match) { 
		return '<img src="'+match[1].gsub(':','&#58;').gsub('\\[','&#91;')+'" onload="resize(this)" />';
	});
	//email
	s = s.gsub(/\[antispam\](\S*?)\[\/antispam\]/i,'<img src="/email.php?id=#{1}" />');
	//url
	s = s.gsub(/\[url=(.*?)\]([\s\S]*?)\[\/url\]/im,function(match) {
		return '<a href="'+match[1].gsub(':','&#58;').gsub('\\[','&#91;')+'">'+match[2].gsub(':','&#58;')+'</a>'});
	
	var subs = $H({/*'[b]' : '<b>', '[/b]' : '</b>', '[i]' : '<i>', '[/i]' : '</i>', '[u]' : '<span style="text-decoration:underline">', '[/u]' : '</span>',*/
		'[sub]' : '<sub>', '[/sub]' : '</sub>', '[sup]' : '<sup>', '[/sup]' : '</sup>', '[/font]' : '</span>',
		'[/color]' : '</span>','[/size]' : '</span>','[/quote]' : '</blockquote>'});
	subs.each(function(pair) {
		s = s.gsub(new RegExp(RegExp.escape(pair.key),'i'),pair.value);
	});
	s = s.gsub(/\[b\](.*?)\[\/b\]/i,'<b>#{1}</b>');
	s = s.gsub(/\[i\](.*?)\[\/i\]/i,'<i>#{1}</i>');
	s = s.gsub(/\[u\](.*?)\[\/u\]/i,'<span style="text-decoration:underline">#{1}</span>');
	s = s.gsub(/\[font=(.*?)\]/i,'<span style="font-family:\'#{1}\'">');
	s = s.gsub(/\[color=(.*?)\]/i,'<span style="color:#{1}">');
	s = s.gsub(/\[size=(.*?)\]/i,'<span style="font-size:#{1}">');

	//autourl
	//s = s.gsub(/(^.{0,8}|(?!<a href=").{9})((http|https|ftp):\/\/[a-z0-9\.]+(:\d+)?[^\s<]*)/im,'#{1}<a href="#{2}">#{2}</a>');
	s = s.gsub(/(http|https|ftp):\/\/[a-z0-9\.]+(:\d+)?[^\s<]*/im,'<a href="#{0}">#{0}</a>');
	return s;
}

function setHover(buttons) {
	buttons.invoke('observe','mouseover',function(event) {
		var e = event.element();
		e.addClassName('hover');
	});
	buttons.invoke('observe','mouseout',function(event) {
		var e = event.element();
		e.removeClassName('hover');
	});
}

//global var
var userLink = new Template('<a href="/profile.php?id=#{uid}">#{name}</a>');
var supportLang = ['C','C++','Pascal','Java','Html','Php'];
