ypSlideOutMenu.Registry = []
ypSlideOutMenu.aniLen = 250
ypSlideOutMenu.hideDelay = 1000
ypSlideOutMenu.minCPUResolution = 10
// constructor
function ypSlideOutMenu(id, dir, left, top, width, height)
{
this.ie = document.all ? 1 : 0
this.ns4 = document.layers ? 1 : 0
this.dom = document.getElementById ? 1 : 0
if (this.ie || this.ns4 || this.dom) {
this.id = id
this.dir = dir
this.orientation = dir == "left" || dir == "right" ? "h" : "v"
this.dirType = dir == "right" || dir == "down" ? "-" : "+"
this.dim = this.orientation == "h" ? width : height
this.hideTimer = false
this.aniTimer = false
this.open = false
this.over = false
this.startTime = 0
this.gRef = "ypSlideOutMenu_"+id
eval(this.gRef+"=this")
ypSlideOutMenu.Registry[id] = this
var d = document
var strCSS = "";
strCSS += '#' + this.id + 'Container { visibility:hidden; '
strCSS += 'left:' + left + 'px; '
strCSS += 'top:' + top + 'px; '
strCSS += 'overflow:hidden; text-align:left; z-index:10000; }'
strCSS += '#' + this.id + 'Container, #' + this.id + 'Content { position:absolute; '
strCSS += 'width:' + width + 'px; '
strCSS += 'height:' + height + 'px; '
strCSS += 'clip:rect(0px,' + width + 'px,' + height + 'px,0px); '
strCSS += '}'
this.css = strCSS;
this.load()
}
}
ypSlideOutMenu.writeCSS = function() {
document.writeln('<style type="text/css">');
for (var id in ypSlideOutMenu.Registry) {
document.writeln(ypSlideOutMenu.Registry[id].css);
}
document.writeln('</style>');
}
ypSlideOutMenu.prototype.load = function() {
var d = document
var lyrId1 = this.id + "Container"
var lyrId2 = this.id + "Content"
var obj1 = this.dom ? d.getElementById(lyrId1) : this.ie ? d.all[lyrId1] : d.layers[lyrId1]
if (obj1) var obj2 = this.ns4 ? obj1.layers[lyrId2] : this.ie ? d.all[lyrId2] : d.getElementById(lyrId2)
var temp
if (!obj1 || !obj2) window.setTimeout(this.gRef + ".load()", 100)
else {
this.container = obj1
this.menu = obj2
this.style = this.ns4 ? this.menu : this.menu.style
this.homePos = eval("0" + this.dirType + this.dim)
this.outPos = 0
this.accelConst = (this.outPos - this.homePos) / ypSlideOutMenu.aniLen / ypSlideOutMenu.aniLen 
// set event handlers.
if (this.ns4) this.menu.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
this.menu.onmouseover = new Function("ypSlideOutMenu.showMenu('" + this.id + "')")
this.menu.onmouseout = new Function("ypSlideOutMenu.hideMenu('" + this.id + "')")
//set initial state
this.endSlide()
}
}
ypSlideOutMenu.showMenu = function(id)
{
var reg = ypSlideOutMenu.Registry
var obj = ypSlideOutMenu.Registry[id]
if (obj.container) {
obj.over = true
for (menu in reg) if (id != menu) ypSlideOutMenu.hide(menu)
if (obj.hideTimer) { reg[id].hideTimer = window.clearTimeout(reg[id].hideTimer) }
if (!obj.open && !obj.aniTimer) reg[id].startSlide(true)
}
}
ypSlideOutMenu.hideMenu = function(id)
{
var obj = ypSlideOutMenu.Registry[id]
if (obj.container) {
if (obj.hideTimer) window.clearTimeout(obj.hideTimer)
obj.hideTimer = window.setTimeout("ypSlideOutMenu.hide('" + id + "')", ypSlideOutMenu.hideDelay);
}
}
ypSlideOutMenu.hideAll = function()
{
var reg = ypSlideOutMenu.Registry
for (menu in reg) {
ypSlideOutMenu.hide(menu);
if (menu.hideTimer) window.clearTimeout(menu.hideTimer);
}
}
ypSlideOutMenu.hide = function(id)
{
var obj = ypSlideOutMenu.Registry[id]
obj.over = false
if (obj.hideTimer) window.clearTimeout(obj.hideTimer)
obj.hideTimer = 0
if (obj.open && !obj.aniTimer) obj.startSlide(false)
}
ypSlideOutMenu.prototype.startSlide = function(open) {
this[open ? "onactivate" : "ondeactivate"]()
this.open = open
if (open) this.setVisibility(true)
this.startTime = (new Date()).getTime() 
this.aniTimer = window.setInterval(this.gRef + ".slide()", ypSlideOutMenu.minCPUResolution)
}
ypSlideOutMenu.prototype.slide = function() {
var elapsed = (new Date()).getTime() - this.startTime
if (elapsed > ypSlideOutMenu.aniLen) this.endSlide()
else {
var d = Math.round(Math.pow(ypSlideOutMenu.aniLen-elapsed, 2) * this.accelConst)
if (this.open && this.dirType == "-") d = -d
else if (this.open && this.dirType == "+") d = -d
else if (!this.open && this.dirType == "-") d = -this.dim + d
else d = this.dim + d
this.moveTo(d)
}
}
ypSlideOutMenu.prototype.endSlide = function() {
this.aniTimer = window.clearTimeout(this.aniTimer)
this.moveTo(this.open ? this.outPos : this.homePos)
if (!this.open) this.setVisibility(false)
if ((this.open && !this.over) || (!this.open && this.over)) {
this.startSlide(this.over)
}
}
ypSlideOutMenu.prototype.setVisibility = function(bShow) { 
var s = this.ns4 ? this.container : this.container.style
s.visibility = bShow ? "visible" : "hidden"
}
ypSlideOutMenu.prototype.moveTo = function(p) { 
this.style[this.orientation == "h" ? "left" : "top"] = this.ns4 ? p : p + "px"
}
ypSlideOutMenu.prototype.getPos = function(c) {
return parseInt(this.style[c])
}
ypSlideOutMenu.prototype.onactivate = function() { }
ypSlideOutMenu.prototype.ondeactivate = function() { }// create dd menus
var myMenu1 = new ypSlideOutMenu("menu1", "down", -1000, 22, 116, 140);
var myMenu2 = new ypSlideOutMenu("menu2", "down", -1000, 22, 116, 100);
var myMenu3 = new ypSlideOutMenu("menu3", "down", -1000, 22, 116, 100);
var myMenu4 = new ypSlideOutMenu("menu4", "down", -1000, 22, 116, 360);
var myMenu5 = new ypSlideOutMenu("menu5", "down", -1000, 22, 116, 300);
var myMenu6 = new ypSlideOutMenu("menu6", "down", -1000, 22, 116, 215);
var myMenu7 = new ypSlideOutMenu("menu7", "down", -1000, 22, 116, 115);

// assign events to dd menus
myMenu1.onactivate = function() { repositionMenu(myMenu1, 125); }
myMenu2.onactivate = function() { repositionMenu(myMenu2, 240); }
myMenu3.onactivate = function() { repositionMenu(myMenu3, 355); }
myMenu4.onactivate = function() { repositionMenu(myMenu4, 470); }
myMenu5.onactivate = function() { repositionMenu(myMenu5, 585); }
myMenu6.onactivate = function() { repositionMenu(myMenu6, 700); }
myMenu7.onactivate = function() { repositionMenu(myMenu7, 815); }

// functions for the calculation of menus
function repositionMenu(menu, offset) {
	// the new left position should be the center of the window + the offset
	var newLeft = /*getWindowWidth() / 2 +*/ offset;
	
	// setting the left position in netscape is a little different than IE
	menu.container.style ? menu.container.style.left = newLeft + "px" : menu.container.left = newLeft;
}

// this function calculates the window's width - different for IE and netscape
function getWindowWidth() {
	return window.innerWidth ? window.innerWidth : document.body.offsetWidth;
}

// write css for the menus
ypSlideOutMenu.writeCSS();/*
	Spands JS lib v. 0.1.0                      http://spand.org
	
	This file is copyrighted by Johannes U. Jensen aka Spand.
	
	Should you want to use it then you can, under the terms of
	the "Gnu General Public License", which can be found at:
	
	http://www.gnu.org/licenses/gpl.txt
*/

/*
 * Boolean function checking weather a string is a prefix of the other.
 * @param str The string to matched on.
 * @param prefix The possible prefix.
 */
function startsWith(str, prefix){
	if (!(typeof str == 'string' && typeof prefix == 'string'))
		return false;
		
	if (str.substring(0,prefix.length) == prefix)
		return true;
	else
		return false;
}

/*
 * Boolean function checking weather a string is a suffix of the other
 * @param str The string to matched on.
 * @param suffix The possible suffix.
 */
function endsWith(str, suffix){
	if (!(typeof str == 'string' && typeof suffix == 'string'))
		return false;
	
	var substr = str.substring(str.length-suffix.length, str.length);
	
	if (substr == suffix)
		return true;
	else
		return false;
}

/*
 * Put any element into partymode! It replaces the inner html of an element
 * with an auto updating cheerleader!
 * @param elm The element the text should be printed in or the id of the element.
 */
function setCheer(elm){
	if (typeof elm == 'string'){
		elm = $(elm);   
		
		if (elm == null)
			return;
	}
	var actions = new Array('.o.', '<o.', '<o>', '|o>', '|o|', '*\\o/*', '|o|', '|o>', '<o>', '<o.');
	var current = 0;
	var updateCheer = function (){
		if (current >= actions.length)
			current = 0;
        elm.innerHTML = actions[current++].replace('<','&lt;').replace('>','&gt;');
        setTimeout(updateCheer, 400);
	}
	updateCheer();
}



// Table of characters and their namecode
var _chars = new Array(
	new Array('&amp;', 		'&'),
	new Array('&quot;',		'"'),
	new Array('&apos;',		'\''),
	new Array('&lt;', 		'<'),
	new Array('&gt;',		'>'),
//	new Array('&nbsp;',		' '),
	new Array('&copy;',		'©'),
	new Array('&reg;',		'®'),
	new Array('&Aring;',	'Å'),
	new Array('&AElig;',	'Æ'),
	new Array('&Oslash;',	'Ø'),
	new Array('&aring;',	'å'),
	new Array('&aelig;', 	'æ'),
	new Array('&oslash;',	'ø')
);
// Table of regexs of above table with flag g
var _regexs = new Array(_chars.length);
for (var i = 0; i < _chars.length; i++){_regexs[i] = new Array(new RegExp(_chars[i][0], 'g'), new RegExp(_chars[i][1], 'g'));}

/*
 * Escape every special character in the supplied string with its corrosponding character namecode;
 * @param str the string to be escaped
 * @return the escaped string
 */
function htmlescape(str){
	if (typeof str != 'string')
		return '';
	for (var i = 0; i < _chars.length; i++){
		str = str.replace(_regexs[i][1], _chars[i][0]);
	}
	return str;
}
/*
 * Reverse the process of above function
 * @param str the string to be unescaped
 * @return the unescaped string
 */
function htmlunescape(str){
	// Cant remember the argument why this should be done backwards but Im certain it was a good argument :)
	//for (var i = _chars.length-1; i >= 0; i--){
	//	str = str.replace(_regexs[0], _chars[i][1]);
	//}
	for (var i = 0; i < _chars.length; i++){
		str = str.replace(_regexs[i][0], _chars[i][1]);
	}
	return str;
}


/////////////////////////////////////
// Misc
/////////////////////////////////////

/*
 * Wrapper function for document.getElementById.
 * @param id Id of the element to return;
 * @return The element with the specified id or null if no such element was found.
 */
 /*
function $(id){
	return document.getElementById(id);
}*/

/*
 * Padd a number with zeroes. ie. zeropad(7, 3) will return '003'; If the size is less then the
 * number of digits of the integer the full integer will be returned.
 * @param integer The integer to padd
 * @param size The max number of chars in the returned string if the number of digits
 *             in the integer does not exeed size
 * @return Returns the padded integer as a string of the specified size the number of digits
 *         in the integer does not exeed size
 */
function zeropad(integer, size){
	
	var padding = '';
	var numNeeded = size-(''+integer).length;
	
	if (numNeeded >= 0){
		for (var i = 0; i < numNeeded; i++){
			padding += '0';
		}
	}
	
	return padding+integer;
}

///////////////////////////////////////////////
// Set the eventhandler of an element.
// Handles previous assignments nicely :)
///////////////////////////////////////////////
/**
 * @param element The element to set the specific handle on.
 */
function setOnclick(element, func){
	_setAnEvent(element, func, 'onclick');
}

function _setAnEvent(element, func, event){
	if (element == null || func == null || event == null)
		return false;
	if (_getEvent(element, event) == null){
		_setEvent(element, func, event);
	} else {
		var oldfunc = _getEvent(element, event);
		_setEvent(element, function (){oldfunc(); func(); }, event);
	}
	return true;
}

function _getEvent(element, event){
	var result = null;
	switch(event){
		// as listed on http://www.w3schools.com/dhtml/dhtml_events.asp
		case 'onabort':
			if (element.onabort) result = element.onabort;
			break;
		case 'onblur':
			if (element.onblur) result = element.onblur;
			break;
		case 'onchange':
			if (element.onchange) result = element.onchange;
			break;
		case 'onclick':
			if (element.onclick) result = element.onclick;
			break;
		case 'ondblclick':
			if (element.ondblclick) result = element.ondblclick;
			break;
		case 'onfocus':
			if (element.onfocus) result = element.onfocus;
			break;
		case 'onkeydown':
			if (element.onkeydown) result = element.onkeydown;
			break;
		case 'onkeypress':
			if (element.onkeypress) result = element.onkeypress;
			break;
		case 'onkeyup':
			if (element.onkeyup) result = element.onkeyup;
			break;
		case 'onload':
			if (element.onload) result = element.onload;
			break;
		case 'onmousedown':
			if (element.onmousedown) result = element.onmousedown;
			break;
		case 'onmousemove':
			if (element.onmousemove) result = element.onmousemove;
			break;
		case 'onmouseover':
			if (element.onmouseover) result = element.onmouseover;
			break;
		case 'onmouseout':
			if (element.onmouseout) result = element.onmouseout;
			break;
		case 'onmouseup':
			if (element.onmouseup) result = element.onmouseup;
			break;
		case 'onreset':
			if (element.onreset) result = element.onreset;
			break;
		case 'onselect':
			if (element.onselect) result = element.onselect;
			break;
		case 'onsubmit':
			if (element.onsubmit) result = element.onsubmit;
			break;
		case 'onunload':
			if (element.onunload) result = element.onunload;
			break;
		// as found in ultraedit autocompletion list:
		case 'ondragdrop':
			if (element.ondragdrop) result = element.ondragdrop;
			break;
		case 'onerror':
			if (element.onerror) result = element.onerror;
			break;
		case 'onHelp':
			if (element.onHelp) result = element.onHelp;
			break;
		case 'onmove':
			if (element.onmove) result = element.onmove;
			break;
		case 'onresize':
			if (element.onresize) result = element.onresize;
			break;
		default:
			result = null;
	}
	return result;
}

function _setEvent(element, func, event){
	var result = false;
	switch(event){
		// as listed on http://www.w3schools.com/dhtml/dhtml_events.asp
		case 'onabort':
			element.onabort = func;
			result = true;
			break;
		case 'onblur':
			element.onblur = func;
			result = true;
			break;
		case 'onchange':
			element.onchange = func;
			result = true;
			break;
		case 'onclick':
			element.onclick = func;
			result = true;
			break;
		case 'ondblclick':
			element.ondblclick = func;
			result = true;
			break;
		case 'onfocus':
			element.onfocus = func;
			result = true;
			break;
		case 'onkeydown':
			element.onkeydown = func;
			result = true;
			break;
		case 'onkeypress':
			element.onkeypress = func;
			result = true;
			break;
		case 'onkeyup':
			element.onkeyup = func;
			result = true;
			break;
		case 'onload':
			element.onload = func;
			result = true;
			break;
		case 'onmousedown':
			element.onmousedown = func;
			result = true;
			break;
		case 'onmousemove':
			element.onmousemove = func;
			result = true;
			break;
		case 'onmouseover':
			element.onmouseover = func;
			result = true;
			break;
		case 'onmouseout':
			element.onmouseout = func;
			result = true;
			break;
		case 'onmouseup':
			element.onmouseup = func;
			result = true;
			break;
		case 'onreset':
			element.onreset = func;
			result = true;
			break;
		case 'onselect':
			element.onselect = func;
			result = true;
			break;
		case 'onsubmit':
			element.onsubmit = func;
			result = true;
			break;
		case 'onunload':
			element.onunload = func;
			result = true;
			break;
		// as found in ultraedit autocompletion list:
		case 'ondragdrop':
			element.ondragdrop = func;
			result = true;
			break;
		case 'onerror':
			element.onerror = func;
			result = true;
			break;
		case 'onHelp':
			element.onHelp = func;
			result = true;
			break;
		case 'onmove':
			element.onmove = func;
			result = true;
			break;
		case 'onresize':
			element.onresize = func;
			result = true;
			break;
		default:
			result = false;
	}
	return result;
}function overIcon(elm){
	elm.className += ' hover';
}

function outIcon(elm){
	elm.className = elm.className.replace(/hover/g, '');
}

function fixImages(width, height) {
	// IE
	if (document.all){
		var images = document.getElementsByTagName('img');
		for (var i = 0; i < images.length; i++){
			if (images[i].className.indexOf('fixTrans') >= 0){
				var imagesrc = images[i].src;
				images[i].src = 'http://static.hltv.org/images/1x1trans.gif';
				images[i].width = width;
				images[i].height = height;
			}
		}
	}
}

function setReplyto(id, number){
	var replytomsgElm = document.getElementById('replytomsg');
	if (id == 0){
		replytomsgElm.innerHTML = 'You are replying to the main post';
	} else {
		replytomsgElm.innerHTML = 'You are replying to post #'+number;
	}
	
	var replytoidElm = document.getElementById('replytoid');
	replytoidElm.value = id;

	$('replymsg').focus();
	
	$('replymsg').value = '';
	
	var action = $('action');
	if (action && action.value){
		action.value = 'reply';
	}
}

function setEdit(id, number){
	
	var replytomsgElm = $('replytomsg');
	replytomsgElm.innerHTML = 'You are editing your post #'+number;

	$('replymsg').focus();
	
	// Get the content that needs editing
	var forummessage = $('r'+id+'msg');
	
	//var findMessage = /^(.*?)(<span style.*)?<div class="timestamp">/
	
	//var resArray = findMessage.exec(forummessage.innerHTML);
	
	var end = forummessage.innerHTML.toLowerCase().indexOf('<span style=');
	
	if (end == -1){
		end = forummessage.innerHTML.toLowerCase().indexOf('<div class=');
	}
	
	var message = forummessage.innerHTML.substr(0, end);
	
	message = convertToHelperTags(message);
	
	// For moz
	message = message.replace(/<br>\n/g, "\n");
	// still moz. Shouldnt be necessary but just in case
	message = message.replace(/<br>/g, "");
	
	// For IE
	message = message.replace(/<BR>/g, "\n");
	
	// Trim newlines
	message = message.replace(/^(\n)*/gi, "");
	message = message.replace(/(\n)*$/gi, "");
	
	message = htmlunescape(message);
	
	$('replymsg').value = message;
	
	var action = $('action');
	if (action && action.value){
		action.value = 'edit';
	}
	
	var replytoid = $('replytoid');
	if (replytoid && replytoid.value){
		replytoid.value = id;
	}
   	
	$('replymsg').focus();
	
	var ko = "new"+replytoid.value;
}

function _loadXMLDoc(url, func) {
	var req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		req.onreadystatechange = function (){ processReqChange(req, func); }
		req.open("GET", url, true);		
		req.send('');
	}
}

function processReqChange(req, func) {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            func(req);
        } else {
            alert("There was a problem retrieving the data:\n" +req.statusText);
        }
    }
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name,value,days){
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else 
		var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/* A note to anyone thinking they can mess up the site with this code. Think again.. */
function disablePost(img, replyid, threadid){
	
	var forummessage;
	var enableColor = '';
	
	if (0 == replyid){
		// Thread disable
		forummessage = img.parentNode.parentNode.nextSibling;
		enabledColor = '#FCFCFC';
    } else if (replyid > 0) {
		// Reply disable
		forummessage = document.getElementById('r'+replyid+'msg');
		enabledColor = '#F5F5F5';
	}
	
	var foo = (document.location+'').lastIndexOf('?');
	var loadingurl = '/?pageid=29&replyid='+replyid+'&threadid='+threadid;
	if (endsWith(img.src,'/images/forum_enablebutton.jpg')){
		img.src = 'http://static.hltv.org/images/forum_disablebutton.jpg';
		forummessage.style.backgroundColor = enabledColor;
		_loadXMLDoc(loadingurl+'&status=enable&PHPSESSID='+getCookie('PHPSESSID'), function(){ });
	} else if (endsWith(img.src,'/images/forum_disablebutton.jpg')){
		img.src = 'http://static.hltv.org/images/forum_enablebutton.jpg';
		forummessage.style.backgroundColor = '#FFCCCC';
		_loadXMLDoc(loadingurl+'&status=disable&PHPSESSID='+getCookie('PHPSESSID'), function(){ });
	}
}

function lockUser(img, replyid, threadid, userid){
	
	var forummessage;
	
	if (0 == replyid){
		// Thread disable
		forummessage = img.parentNode.parentNode.nextSibling;
    } else if (replyid > 0) {
		// Reply disable
		forummessage = document.getElementById('r'+replyid+'msg');
	}
	
	var foo = (document.location+'').lastIndexOf('?');
	var loadingurl = ((document.location+'').substring(0, foo))+'/?pageid=29&replyid='+replyid+'&threadid='+threadid+'&userid='+userid;
	if (endsWith(img.src,'/images/forum_unlockbutton.jpg')){
		img.src = 'http://static.hltv.org/images/forum_lockbutton.jpg';
		
		_loadXMLDoc(loadingurl+'&status=unlock&PHPSESSID='+getCookie('PHPSESSID'), function(){ });
	} else if (endsWith(img.src,'/images/forum_lockbutton.jpg')){
		img.src = 'http://static.hltv.org/images/forum_unlockbutton.jpg';
		_loadXMLDoc(loadingurl+'&status=lock&PHPSESSID='+getCookie('PHPSESSID'), function(){ });
	}
}

function updateColor(replyid) {
  var forummessage;
  forummessage = document.getElementById('r'+replyid+'msg');
  forummessage.style.backgroundColor = '#DDEEFF';
}

/* Functions for the reply form stuff */
function makeSelBold(){
	return insertFormat('BOLD');
}

function makeSelItalic(){
	return insertFormat('ITALIC');
}

function makeSelLink(){
	return insertFormat('LINK');
}

function makeSelImage(){
	return insertFormat('IMAGE');
}

function makeSelHeadline(){
	return insertFormat('HEADLINE');
}

function makeSelYoutube(){
	return insertFormat('YOUTUBE');
}

function makeSelIndent(){
	return insertFormat('INDENT');
}

function insertFormat(formatString){
	// Get the selected text
	var selectedText = '';
	if (window.getSelection){
		var ta = document.getElementById('replymsg');
		selectedText = ta.value.substring(ta.selectionStart, ta.selectionEnd);
		if (selectedText == '')
			return false;
		ta.value = // text before selection
					ta.value.substring(0, ta.selectionStart)
					// The formatted selection
					+'['+formatString+']'+selectedText+'[/'+formatString+']'
					// text after selection
					+ ta.value.substring(ta.selectionEnd, ta.value.length);

	// Not tested.. rumor has it that a browser uses this but.. lets hope it works :)
	} else if (document.getSelection){
		selectedText = document.getSelection();
		if (selectedText == '')
			return false;
		var ta = document.getElementById('replymsg');
		ta.value =  // text before selection
					ta.value.substring(0, ta.selectionStart)+
					// The formatted selection
					+'['+formatString+']'+selectedText+'[/'+formatString+']'
					ta.value.substring(ta.selectionEnd, ta.value.length);
	} else if (document.selection){
		selectedRange = document.selection.createRange();
		selectedText = selectedRange.text
		if (selectedText == '')
			return false;
		selectedRange.text = '['+formatString+']'+selectedText+'[/'+formatString+']';
	}
	
	return false;
}

function validateReply(){
	
	return true;
}                            

function convertHelperTags(str){
	var linkregex 		= /\[LINK\]http:\/\/(.+?)\[\/LINK\]/ig;
	var linkregexnohttp = /\[LINK\](.+?)\[\/LINK\]/ig;
	var italicregex 	= /\[ITALIC\](.+?)\[\/ITALIC\]/ig;
	var boldregex 		= /\[BOLD\](.+?)\[\/BOLD\]/ig;
	
	str = str.replace(linkregex, '<a href="http://$1" target="_blank">$1</a>')
			 .replace(linkregexnohttp, '<a href="http://$1" target="_blank">$1</a>')
			 .replace(italicregex, '<i>$1</i>')
			 .replace(boldregex, '<b>$1</b>');
	
	// Remove empty tags
	str = str.replace(/\[LINK\]\[\/LINK\]/ig, '')
			 .replace(/\[ITALIC\]\[\/ITALIC\]/ig, '')
			 .replace(/\[BOLD\]\[\/BOLD\]/ig, '');
			 
	return str;
}

function convertToHelperTags(str){
	var linkregex = /<a href=".+?" target="_blank">(.+?)<\/a>/g;
	var italicregex = /<i>(.+?)<\/i>/g;
	var boldregex = /<b>(.+?)<\/b>/g;
	
	str = str.replace(linkregex, '[LINK]$1[/LINK]')
			 .replace(italicregex, '[ITALIC]$1[/ITALIC]')
			 .replace(boldregex, '[BOLD]$1[/BOLD]');
			 
	return str;
}

var timestampStuff = null
function updatePreview(){
	// Make it visible if its not
	var previewCon = $('replypreviewCon');
	previewCon.style.visibility = 'visible';
	
	// Insert content
	var forummessage = $('tamtamNewTam');

	// First escape all the html tags and special chars
	var replymsg = $('replymsg').value;
	
	// Trim newlines
	replymsg = replymsg.replace(/^(\n)*/gi, "");
	replymsg = replymsg.replace(/(\n)*$/gi, "");
	
	replymsg = htmlescape(replymsg).replace(/\n/g, '<br />');
	//replymsg = replymsg.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g, '<br/>');
	
	// Then convert helper tags to html. Allow both capital and non-capital(?) letters tags
	replymsg = convertHelperTags(replymsg);
	
	if (timestampStuff == null){
		timestampStuff = forummessage.innerHTML;
	}
	
	var ts = timestampStuff+'';
	
    
    var now = new Date();
    
    var timestamp = now.getFullYear()+'-'+zeropad(now.getMonth()+1, 2)+'-'+zeropad(now.getDate(), 2)+' '+zeropad(now.getHours(), 2)+':'+zeropad(now.getMinutes(), 2)+':'+zeropad(now.getSeconds(), 2);
    
  ts = ts.replace('PUT TS HERE', timestamp);
	
	forummessage.innerHTML = replymsg + ts;
	
	return false;
}

function updateThreadPreview(){
	// Make it visible if its not
	var previewCon = $('startPost');
	previewCon.style.visibility = 'visible';

	$('headertext').innerHTML = $('forum_subject').value;

	// First escape all the html tags and special chars
	var replymsg = $('replymsg').value;
	replymsg = htmlescape(replymsg).replace(/\n/g, '<br />');
	//replymsg = replymsg.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g, '<br/>');
	
	// Then convert helper tags to html. Allow both capital and non-capital(?) letters tags
	replymsg = convertHelperTags(replymsg);
	
	// insert it
	var forummessage = $('tamtam');
	forummessage.innerHTML = replymsg;
    
    var signatureElm = $('signature');
	var inlen = signatureElm.innerHTML.length;
	var first = (signatureElm.innerHTML+'').toLowerCase().indexOf('<a');
	var therest = (signatureElm.innerHTML).substring(first,inlen);
    
    var now = new Date();
    var timestamp = now.getFullYear()+'-'+zeropad(now.getMonth()+1, 2)+'-'+zeropad(now.getDate(), 2)+' '+zeropad(now.getHours(), 2)+':'+zeropad(now.getMinutes(), 2);
    signatureElm.innerHTML = '<div id="numreplies">(0 replies so far)</div>Created '+timestamp+' by '+therest;
	
	return false;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function removeGalleryPicture(galleryid, notRealId){
	
	var wantToRemove = window.confirm("Are you sure want to remove this picture from the gallery?");

	if (wantToRemove){
		var id = 'thumbFrame_'+notRealId;
		var pictureFrame = $(id);
		
		var id = 'thumb_'+notRealId+'_realid';
		var pictureid = $(id).innerHTML;
		
		new Ajax.Request('/?pageid=86&galleryid='+galleryid+'&action=pictureRemoval&pictureid='+pictureid, {asynchronous:true});
		
		_shrinkPictureFrame(pictureFrame);
		
	}
}

function _shrinkPictureFrame(elem){
	var clone = elem.cloneNode(true);
	
	elem.style.visibility = 'hidden';
	clone.style.visibility = 'hidden';
	
	document.getElementsByTagName("BODY")[0].appendChild(clone);
	clone.style.position = 'absolute';
	clone.style.top = (findPosY(elem))+'px';
	clone.style.left = (findPosX(elem))+'px';
	clone.style.zIndex = 5000;
	clone.style.visibility = 'visible';
	
	Effect.Shrink(clone);
}

var _picturepopup = null;
function openGalleryPopup(galleryid, pictureid){
	_picturepopup=window.open('/?pageid=90&galleryid='+galleryid+'&pictureid='+pictureid, null,'height=665,width=850,location=0,menubar=0,resizable=1', _picturepopup);
	_picturepopup.focus();
}

function rotateGalleryPicture(galleryid, notRealId){
	var id = 'thumb_'+notRealId+'_realid';
	var pictureid = $(id).innerHTML;
	
	var img = $('picture_'+pictureid);
	var oldSrc = img.src+'';
	
	var pictureChanger = function () {
		img.src = oldSrc.replace('galleries', 'galleries/hack');
	}
	var options =	{asynchronous:true, onSuccess: pictureChanger};
	new Ajax.Request('/?pageid=86&galleryid='+galleryid+'&action=pictureRotate&pictureid='+pictureid, options );
}

var formData = new Array();
function updateSelection(newSelection, odds){
	var checked = newSelection.checked;
	var betid = ''+newSelection.name.substring(1);
	
	// Uncheck all;
	document.getElementsByName("1"+betid)[0].checked = false;
	document.getElementsByName("X"+betid)[0].checked = false;
	document.getElementsByName("2"+betid)[0].checked = false;
	
	// Set it back if it was checked
	newSelection.checked = checked;
	
	if (checked){
		formData[betid] = odds;
	} else {
		formData[betid] = '-1';
	}
	
	updateForm();
	return true;
}

function updateForm(){
	var data = getBettingData();
	updateTotalOdds(data[0], data[1]);
	updateWinnings(data[0], data[1]);
}

function getBettingData(){
	var totalOdds = 1;
	var checkedBoxes = 0;
	for (x in formData){
		if (x.charAt(0) == '-' && formData[x] != -1){
			totalOdds *= formData[x];
			checkedBoxes++;
		}
	}
	
	return new Array(totalOdds, checkedBoxes);
}

function updateTotalOdds(totalOdds, numCheckedBoxes){
	if (numCheckedBoxes > 0){
		document.bettingForm.totalOdds.value = stripDecimals(totalOdds, 2);
	} else {
		document.bettingForm.totalOdds.value = '';
	}
}

function updateWinnings(totalOdds, numCheckedBoxes){
	var normalBet = (0 == document.bettingForm.system.value ? true : false);
	var stakePerSlip = parseInt(document.bettingForm.stakePerSlip.value, 10);
	if (normalBet && !isNaN(stakePerSlip) && numCheckedBoxes > 0){
		var winnings = totalOdds * stakePerSlip;
		document.bettingForm.winnings.value = stripDecimals(winnings, 2);
	} else {
		document.bettingForm.winnings.value = '';
	}
}
// Amount to leave
function stripDecimals(numb, amount){
	numb = ''+numb;
	var index = numb.indexOf('.');
	if (index != -1){
		var decimals = ''+numb.substring(index+1);
		if (decimals.length > amount){
			decimals = decimals.substring(0, amount);
			numb = numb.substring(0, index+1)+decimals;
		}
	}
	return numb;
}

function winner_updateWinnings(){
	var odds = $('totalOdds').value;
	var stake = $('stakePerSlip').value;
	
	if (odds != '' && stake != '' && stake > 0){
		$('winnings').value = stripDecimals(odds*stake,2);
	} else {
		$('winnings').value = '';
	}
}

var currentlySelectedCheckbox = null;
function winner_updateOdds(newCheckbox){
	// Deselect selected checkbox
	if (currentlySelectedCheckbox != null && currentlySelectedCheckbox != newCheckbox)
		currentlySelectedCheckbox.checked = false;
	
	// If the clicked checkbox is checked then set it to be the selected one.
	if (newCheckbox.checked == true){
		currentlySelectedCheckbox = newCheckbox;
		
		var id = newCheckbox.name.substring(7);
		var oddsElem = $('odds_'+id);
		$('totalOdds').value = oddsElem.value;
	} else {
		$('totalOdds').value = '';
	}
	
	winner_updateWinnings();
}
