function pointercursor(){document.body.style.cursor = "move";}
function unpointercursor(){document.body.style.cursor="";}

// Startup variables
var imageTag = false;
var theSelection = false;
var textZoom = 0;
var currentUser = '';

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]','[s]','[/s]','[youtube]','[/youtube]');
imageTag = false;

// Shows the help messages in the helpline window
function helpline(help) {
	document.post.helpbox.value = eval(help + "_help");
}


// Replacement for arraygensmall.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arraygensmall.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arraygensmall.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}

function emoticon(text) {
    if (!document.getElementById('message')) return;
	var txtarea = document.post.message;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	var txtarea = document.post.message;

	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
        var caretPos = txtarea.caretPos;
            theSelection = bbopen + theSelection + bbclose;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? theSelection + ' ' : theSelection;
            caretPos.select();
        theSelection = '';
		txtarea.focus();
		return;
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbopen, bbclose);
		return;
	}
	else
	{
		txtarea.value += bbopen + bbclose;
		txtarea.focus();
	}
	storeCaret(txtarea);
}

function bbstyle(bbnumber) {
	var txtarea = document.post.message;

	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button gensmalls
        
        // if text was selected, do .select() to move cursor to the end, otherwise it will end up in the beginning
        if ((clientVer >= 4) && is_ie && is_win)
            theSelection = document.selection.createRange().text;
        
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.post.addbbcode' + butnumber + '.value');
			eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
        if ((clientVer >= 4) && is_ie && is_win)
        {
            var caretPos = document.selection.createRange();
                caretPos.collapse(false);
                if (theSelection)
                    caretPos.select();
        }
        txtarea.focus();
        storeCaret(txtarea);
        theSelection = '';
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
            var caretPos = txtarea.caretPos;
                theSelection = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
                caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? theSelection + ' ' : theSelection;
                caretPos.select();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}
	
	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button gensmalls
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
                insertAtCaret(bbtags[butnumber + 1], false);
				buttext = eval('document.post.addbbcode' + butnumber + '.value');
				eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags
	
		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
            insertAtCaret(bbtags[15], false);
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.post.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}
		
		// Open tag
        insertAtCaret(bbtags[bbnumber], false);
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.post.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

function isValidUrl(strUrl) {
    var RegexUrl = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return RegexUrl.test(strUrl);
}
function shortUrl(strUrl) { 
// turns http://www.yahoo.com into yahoo.com
    var RegexUrl = strUrl.replace(/^https?:\/\/(?:www\.)?/, ''); // remove http/https://www (if exist)
        RegexUrl = RegexUrl.replace(/\/.*/, '');                 // remove everything from the first / to the end
    return RegexUrl;
}
function getCBoardText() { 
    var savedtext = window.clipboardData.getData("Text"); 
    if (savedtext!='null') 
        return savedtext;
} 

function sourceUrl() {
	var txtarea = document.post.message;
	var theSelection = '';
    var theClipboard = '';

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
        theClipboard = getCBoardText();
		if (theSelection && isValidUrl(theSelection)) {
			// URL is selected -- truncate to domain + add URL tags around it
			insertAtCaret("[url=" + theSelection + "]" + shortUrl(theSelection) + "[/url]");
		}
        else if (theSelection && theClipboard && isValidUrl(theClipboard)) {
            // non-URL text selected, but there's URL in clipboard -- wrap selection with URL from clipboard
			insertAtCaret("[url=" + theClipboard + "]" + theSelection + "[/url]");
        }
        else if (!theSelection && theClipboard && isValidUrl(theClipboard)) {
            // nothing is selected, but there's URL in clipboard -- insert url truncated to domain + add URL tags around it
            insertAtCaret("[url=" + theClipboard + "]" + shortUrl(theClipboard) + "[/url]");
        }
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
        // URL is selected -- truncate to domain + add URL tags around it
    	var selLength = txtarea.textLength;
    	var selStart = txtarea.selectionStart;
    	var selEnd = txtarea.selectionEnd;
    	if (selEnd == 1 || selEnd == 2) 
    		selEnd = selLength;

    	var s1 = (txtarea.value).substring(0,selStart);
    	var s2 = (txtarea.value).substring(selStart, selEnd)
    	var s3 = (txtarea.value).substring(selEnd, selLength);
        if (isValidUrl(s2))
            txtarea.value = s1 + "[url=" + s2 + "]" + shortUrl(s2) + "[/url]" + s3;
	}
    txtarea.focus();
    return;
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2) 
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

function select_switch(status)
{
	for (i = 0; i < document.privmsg_list.length; i++)
	{
		document.privmsg_list.elements[i].checked = status;
	}
}

function maxWindow()
{
	window.moveTo(0,0);
	if (document.all)
	{
		top.window.resizeTo(screen.availWidth,screen.availHeight);
	}
	else if (document.layers||document.getElementById)
	{
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth)
		{
			top.window.outerHeight = screen.availHeight;
			top.window.outerWidth = screen.availWidth;
		}
	}
}

function refresh_username(selected_username)
{
	opener.document.forms['post'].username.value = selected_username;
	opener.focus();
	window.close();
}

function insertAtCaret(textV, pad) // pad = true/false, if =false, do not pad with spaces
{
    if (textV=='') return;
    var spacepad = (pad == null) ? true : pad; // set to true if pad wasn't passed

    var textObj;
    if (document.getElementById('message'))
    {
        textObj = document.getElementById('message');
    }
    else if (window.opener.document.post.message)
    {   // when called from child "smilies" windows
        textObj = window.opener.document.post.message;
    }
    else
        return;

    var multiline = true;
    
    textV = textV.replace(/\s\[\?\]/g,'');
    
    if ((textV.indexOf('\n') == -1) && spacepad)
    {   // smilies, username
        multiline = false;
        textV = ' ' + textV + ' ';
    }
    
    var ver = 8;
    
    if (document.all && !window.opera)
    {
        if (textObj.createTextRange && textObj.caretPos)
        {
            var caretPos  = textObj.caretPos;
            if (multiline)
                caretPos.text = textV;
            else {
                caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? textV + ' ' : textV;
                caretPos.select();
            }
        }
        else
            textObj.value+= textV;
    }
    else
    {
        var brows = navigator.userAgent.toString();
        var scrollTop, scrollLeft;
        
        if (textObj.type=='textarea' && textObj.scrollTop)
        {
            scrollTop  = textObj.scrollTop;
            scrollLeft = textObj.scrollLeft;
        }
        
        if (brows.search(/opera\/?(\d*.\d*)/i) != -1) 
            ver = RegExp.$1;
            
        if (textObj.selectionStart>=0 && ver>=8)
        {
            if (textObj.textLength != undefined) 
            {
                var selLength = textObj.textLength;
                var selStart  = textObj.selectionStart;
                var selEnd    = textObj.selectionEnd;
                
                if (selEnd==1 || selEnd==2)
                    selEnd = selLength;
                    
                var s1 = (textObj.value).substring(0,selStart);
                var s2 = (textObj.value).substring(selEnd,selLength);
                
                textObj.value = s1 + textV + s2;
                textObj.setSelectionRange(selStart + textV.length, selStart + textV.length);
            } 
            if (typeof scrollTop != 'undefined')
            {
                textObj.scrollTop  = scrollTop;
                textObj.scrollLeft = scrollLeft;
            }
        }
        else 
            textObj.value += textV;
    }
}

function insertAndFocus(inTxt) { insertAtCaret(inTxt); document.post.message.focus(); }

function change_curUser(u)
{
    if (typeof u=='string') // accept empty strings - clear user in non message areas
        currentUser = u;
    else
        currentUser = "";
}

function getFontSize(anObj) {
    if (anObj.currentStyle) // explorer + opera
        return parseInt(anObj.currentStyle.fontSize.replace("px",""));
    else if (window.getComputedStyle) // firefox
        return parseInt(document.defaultView.getComputedStyle(anObj,null).getPropertyValue('font-size').replace("px",""));
    else
        return 0;
}

function changeFontSize(fontInc, lineShift) {
    var posts = document.getElementsByTagName('td');
    var pattern = new RegExp('(txt_[0-9])'); // looking for IDs = "txt_#"
    
    var curFontSize = 0;
    for (i = 0; i < posts.length; i++) {
        if (pattern.test(posts[i].id)) {
            curFontSize = getFontSize(posts[i]);
            if (curFontSize == 0) // getFontSize() failed, no reason to continue
                break;
            posts[i].style.fontSize   = (curFontSize+fontInc).toString() + 'px';
            posts[i].style.lineHeight = (curFontSize+fontInc+lineShift).toString() + 'px';
            
            var elements = posts[i].getElementsByTagName("*");
            for (n = 0; n <= elements.length; n++) {
                if (elements[n] && elements[n].className && (elements[n].className == 'inside_quote' || elements[n].className == 'inside_code'))
                    continue; // skip "inside_..." divs -- they will inherit size from the parent, and if we don't skip, it will increase 2 times
                if (elements[n] && elements[n].style && ((elements[n].style.fontStyle == 'italic') || 
                                            (elements[n].style.fontWeight=='bold') || (elements[n].style.textDecoration=='underline')))
                    continue;
                if (elements[n] && elements[n].tagName && 
                  ((elements[n].tagName.toLowerCase() == 'span') || (elements[n].tagName.toLowerCase() == 'div'))) {
                    curFontSize = getFontSize(elements[n]);
                    elements[n].style.fontSize   = (curFontSize+fontInc).toString() + 'px';
                    elements[n].style.lineHeight = (curFontSize+fontInc+lineShift).toString() + 'px';
                }
            }
        }
    }
    return;
}
function toggleTextSize() {
    var zoomControl = document.getElementById('zoomDirection');
    if (textZoom == 0)
    {
        changeFontSize(3,3);
        zoomControl.innerHTML = '[-]';
        textZoom = 1;
    }
    else
    {
        changeFontSize(-3,3);
        zoomControl.innerHTML = '[+]';
        textZoom = 0;
    }
}