var _tpDir;
var _nrOptions = 0;
var addpoll;
var el;
var msgbox;
var pic1, pic2, pic3, pic4, pic5;
var pix1, pix2, pix3, pix4, pix5, pix6, pix7;
var icon1, icon2, icon3, icon4;
var tab1, tab2, tab3, tab4, tab5;
var button1;
var tagOpen = new Array();
var _sel;
var _selStart;
var _selEnd;

function catchEnter(e) {

	if(navigator.userAgent.match("Gecko"))
		c=e.which;		
	else
		c=e.keyCode;
		
	if (c == 13){
		add_option();
		return false;
	}
	
	return true;

}

function del_option(id) {

	var box, option;
	
	box = document.getElementById("options");
	option = document.getElementById("option"+id);

	option.innerHTML = "";
	
	box.removeChild(option);
	
	document.getElementById("AddOption").focus();
	
	return true;
	
}

function add_option() {

	if (_nrOptions >= 12) {
		alert("Number of options have been limited to 12.");
		return false;
	}

	_nrOptions++;

	var box, input, val;
	var el, attr, id;
	var hel, hattr, hid;
	
	box = document.getElementById("options");
	input = document.getElementById("AddOption");
	val = trim(input.value);
	
	if (val.length<1) {
		alert("Please enter an option.");
		input.focus();
		return false;
	}
	
	el = document.createElement("div");			
	attr = document.createAttribute("id");
	
	el.setAttribute("id", "option"+_nrOptions);
	box.appendChild(el);
	el.innerHTML = "<img src='/Templates/"+_tpDir+"/Images/del.gif' alt='Del' style='float: right; cursor: pointer;' onclick='del_option(\""+_nrOptions+"\")' />";
	el.innerHTML+= input.value;
	
	
	hel = document.createElement("input");
	
	hattr = document.createAttribute("name");
	hel.setAttribute("name", "ForumPollOptions[]");
	
	hattr = document.createAttribute("type");
	hel.setAttribute("type", "hidden");
	
	el.appendChild(hel);
	
	hel.value = escape(val);
	
	input.value = "";
	input.focus();
	
	return true;

}	
	
function textRaffle(text, id, y) {

	var n = y-20;

	if (text.length>=n) {
	
		var chars = "abcdefghiklmnopqrstuvwxyz";
		var str = "";
		
		for (var i=0; i<text.length; i++) {
		
			var rnum = Math.floor(Math.random()*chars.length);
			
			if (i<n)
				str += text.substr(i, 1);
			else if (text.substr(i, 1) == " ")
				str += " ";
			else
				str += chars.substr(rnum, 1);
			
		}
		
		document.getElementById(id).innerHTML = str;
	
		y++;
		setTimeout('textRaffle("'+text+'", "'+id+'", "'+y+'")', 50);
		
	}
	else {
	
		setTimeout('document.getElementById("'+id+'").innerHTML = ""', 3000);
		setTimeout('textRaffle("'+text+'", "'+id+'", 1)', 3000);
	
	}

}
	
function xCountdown(time, el) {

	var days, hours, minutes, seconds;
	var string;
	
	days = Math.floor(time/(60*60*24));
	hours = Math.floor((time-days*60*60*24)/3600);
	minutes = Math.floor((time-days*60*60*24-hours*3600)/60);
	seconds = time%60;
	
	string = days+" days<br />"+hours+" hours<br />"+minutes+" minutes<br />"+seconds+" seconds";
	
	document.getElementById(el).innerHTML = string;
	time--;
	
	setTimeout('xCountdown("'+time+'", "'+el+'")', 1000);

}

function checkFields(arr) {

	for (var i=0; i<arr.length; i++) {
		
		if (document.getElementById(arr[i]).value.length<1 || document.getElementById(arr[i]).value == " ") {
		
			alert("Please fill in all the required fields.");
			return false;
			
		}
		
	}
	
}

function verifyReg() {

	var rf = document.regForm;

	if (!checkCaptcha(rf.VerificationCode.value)) {
		alert("Verification code was incorrect.");
		return false;
	}
	if (rf.MemberUsername.value.length < 1 || rf.MemberUsername.value == " " || rf.MemberUsername.value.match(/['"&{};$]/)) {
		alert("Invalid username.");
		return false;
	}
	if (rf.MemberEmail.value.length < 1 || rf.MemberEmail.value == " " || !rf.MemberEmail.value.match(/^[a-zA-Z0-9-._]+\@[a-zA-Z0-9-._]+\.[a-zA-Z0-9-._]+$/)) {
		alert("Invalid e-mail adress.");
		return false;
	}
	if (rf.MemberPassword.value.length < 1) {
		alert("Please enter a password.")
		return false;
	}
	if (rf.MemberPassword.value != rf.MemberPassword2.value) {
		alert("Passwords mismatch.");
		return false;
	}
	
	return true;

}

function verifyCon() {

	var cf = document.conForm;
	var check = null;

	if (!checkCaptcha(cf.VerificationCode.value)) {
		alert("Verification code was incorrect.");
		return false;
	}
	for (i = 0; i<cf.SubjectChoice.length; i++) {
		if (cf.SubjectChoice[i].checked)
			check = true;
	}
	if (!check) {
		alert("Please choose a subject.");
		return false;	
	}
	if (document.getElementById('other').checked && cf.SubjectValue.value.length<1) {
		alert("Please enter a subject.");
		return false;
	}
	if (cf.Email.value.length<1) {
		alert("Please enter an e-mail adress.");
		return false;	
	}
	if (cf.Email.value == " " || !cf.Email.value.match(/^[a-zA-Z0-9-._]+\@[a-zA-Z0-9-._]+\.[a-zA-Z0-9-._]+$/)) {
		alert("Invalid e-mail adress.");
		return false;
	}
	if (cf.Message.value.length<1) {
		alert("Please enter a message.");
		return false;
	}
	
	return true;
}

function imgLightbox(url, width, height, name, uploader, date, desc_id) {

	var screenHeight = screen.availHeight;
	var screenWidth = screen.availWidth;
	var maxHeight = parseInt(screenHeight - 100);
	var miscHeight;
	var totHeight;
	var ratio = parseInt(width/height);
	var dimensions = width+"x"+height;
	
	
	if (width > 960 && ratio>=(96/55)) {
		height = parseInt(height/width * 960);
		width = 960;
	}
	else if (height > 550) {
		width = parseInt(width/height * 550);
		height = 550;
	}
	
	var light = document.getElementById("light");
	var fade = document.getElementById("fade");
	var misc = document.getElementById("misc");
	var iHeight = 16 + parseInt(height);
	var description = document.getElementById(desc_id).innerHTML;
	if (description.length > 0)
		description = "<br /><br />"+description;

	fade.style.display = "block";
	document.getElementById("lightbox_img").innerHTML = "<a href='javascript:;' onclick='imgLightbox_off()'><img src='"+url+"' alt='' /></a>";
	misc.style.width = width+"px";
	misc.style.marginLeft = "-"+width/2+"px";
	misc.innerHTML+= "<div style='text-align: center; margin-bottom: 20px;'><b>"+name+"</b>"+description+"<br /><br />Uploaded by: <b>"+uploader+"</b><br />Date: <b>"+date+"</b><br />Dimensions: <b>"+dimensions+"</b><br /><a href='http://"+document.domain+url+"' target='_blank'>http://"+document.domain+url+"</a></div>";
	miscHeight = document.getElementById("misc").offsetHeight;
	totHeight = parseInt(miscHeight+iHeight);
	misc.style.marginTop = parseInt(totHeight/2 - miscHeight)+"px";
	light.style.display = "block";
	light.style.marginLeft = "-"+width/2+"px";
	light.style.marginTop = "-"+parseInt(totHeight/2)+"px";
	light.style.width = width+"px";
	light.style.height = iHeight+"px";
	
	if (width > screenWidth || totHeight > maxHeight) {
		light.style.position = "absolute";
		light.style.marginTop = "0px";
		light.style.top = "10px";
		misc.style.position = "absolute";
		misc.style.marginTop = "0px";
		misc.style.top = parseInt(iHeight+10)+"px";
	}
	else {
		light.style.position = "fixed";
		light.style.top = "50%";
		misc.style.position = "fixed";	
		misc.style.top = "50%";
	}
	
}
function imgLightbox_off () {
	document.getElementById("fade").style.display = "none";
	document.getElementById("light").style.display = "none";
	document.getElementById("misc").innerHTML = "";
}

function imgViewer(img_url) {
	window.open( "imgviewer.php?"+img_url, "", "scrollbars=0, resizable=1, height=200, width=200");
} 

function sync_value (ida, idb) {

	document.getElementById(idb).value = document.getElementById(ida).value;

	return;	
}

function pwlevel(sid, tid) {

	var pw = document.getElementById(sid).value;
	var score = 0;
	var a = new Array();   // Save combos
	var re;
	
	// Check password length
	if (pw.length<=4)					// 4+
		score = 3;
	if (pw.length>=5 && pw.length<=7)	// 5-7
		score = 6;
	if (pw.length>=8 && pw.length<=15)	// 8-15
		score = 12;
	if (pw.length>=16)					// 16+
		score = 18;
	
	if (pw.match(/[a-z]/)) {			// Atleast one lower case
		score+= 1;
		a[0] = 1;
	}
	if (pw.match(/[A-Z]/)) {			// Atleast one upper case
		score+= 5;
		a[1] = 1;
	}
		
	if (pw.match(/[0-9]/)) {			// One number
		score+=5;
		a[2] = 1;
	}
	if (pw.match(/(.*?)[0-9](.*?)[0-9]/))  // Two numbers
		score+=2;
	if (pw.match(/(.*?)[0-9](.*?)[0-9](.*?)[0-9]/))  // Three numbers
		score+=3;
		
	if (pw.match(/[-_.,:;!"'*~#¤%&=()@£§><\$\^\`\´\+\/\\\?{}\[\]\ ]/)) {   // One sign
		score+=5;
		a[3] = 1;
	}
	if (pw.match(/[-_.,:;!"'*~#¤%&=()@£§><\$\^\`\´\+\/\\\?{}\[\]\ ](.*?)[-_.,:;!"'*~#¤%&=()@£§><\$\^\`\´\+\/\\\?{}\[\]\ ]/))   // Two signs
		score+=5;
	
	// Combos
	if (a[0] && a[1])		// Lower + upper case
		score+=2;
	if ((a[0] || a[1]) && a[2])		// Letter + number
		score+=2;
	if ((a[0] || a[1]) && a[2] && a[3])		// Letter + number + sign
		score+=2;
		
	// Rate the score
	if (score<=15)
		re = "<span style='color: #ff0000'>Very weak</span>";
	if (score>=16 && score<=24)
		re = "<span style='color: #990000'>Weak</span>";
	if (score>=25 && score<=34)
		re = "<span style='color: #999900'>Moderate</span>";
	if (score>=35 && score<=44)
		re = "<span style='color: #009900'>Strong</span>";
	if (score>=45)
		re = "<span style='color: #00ff00'>Very strong</span>";
		
	document.getElementById(tid).innerHTML = re;

}

function matchpw(ida, idb, tid) {

	if (document.getElementById(ida).value == document.getElementById(idb).value && document.getElementById(ida).value.length>0)
		document.getElementById(tid).innerHTML = "<img src='/Templates/"+_tpDir+"/Images/sign_check.png' alt='Match' />";
	else
		document.getElementById(tid).innerHTML = "<img src='/Templates/"+_tpDir+"/Images/sign_cross.png' alt='Mismatch' />";

}

function clearText(field){

   if (field.defaultValue == field.value) field.value = '';
   else if (field.value == '') field.value = field.defaultValue;
   
}

function nl2br (str) {

	return (str + '').replace(/([^>]?)\n/g, '$1<br />\n');

}

function expand (id) {

	var elmt = document.getElementById(id);
	
	if (elmt.innerHTML == "[ + ]")
		elmt.innerHTML = "[ - ]";
	else
		elmt.innerHTML = "[ + ]";

}

function trim(str) {

	str = str.replace(/^[\s]+/g, "");
	str = str.replace(/[\s]+$/g, "");
	
	return str;

}

function overview (id) {

	document.getElementById('unread_posts').style.display = 'none';
	document.getElementById('my_threads').style.display = 'none';
	document.getElementById('watched_threads').style.display = 'none';
	document.getElementById('latest_posts').style.display = 'none';
	document.getElementById('latest_edits').style.display = 'none';
	
	document.getElementById('overview_unread').style.backgroundPosition = 'center top';
	document.getElementById('overview_my').style.backgroundPosition = 'center top';
	document.getElementById('overview_watched').style.backgroundPosition = 'center top';
	document.getElementById('overview_latest').style.backgroundPosition = 'center top';
	document.getElementById('overview_edits').style.backgroundPosition = 'center top';
	
	if (id == 'unread_posts')
		document.getElementById('overview_unread').style.backgroundPosition = 'center bottom';
	if (id == 'my_threads')
		document.getElementById('overview_my').style.backgroundPosition = 'center bottom';
	if (id == 'watched_threads')
		document.getElementById('overview_watched').style.backgroundPosition = 'center bottom';
	if (id == 'latest_posts')
		document.getElementById('overview_latest').style.backgroundPosition = 'center bottom';
	if (id == 'latest_edits')
		document.getElementById('overview_edits').style.backgroundPosition = 'center bottom';
	
	document.getElementById(id).style.display = '';

}

function show (id) { 

	el = document.getElementById(id).style;
	
	el.visibility = 'visible';
}

function hideslow (id) {

	el = document.getElementById(id).style;
	
	setTimeout("el.visibility = 'hidden'", 200);
}

function hideclass(theClass) {

	allPageTags=document.getElementsByTagName("div");

	for (i=0; i<allPageTags.length; i++) {

		if (allPageTags[i].className==theClass) {

			allPageTags[i].style.display='none';
			
		}
	}
} 

function showclass(theClass) {

	allPageTags=document.getElementsByTagName("div");

	for (i=0; i<allPageTags.length; i++) {

		if (allPageTags[i].className==theClass) {

			allPageTags[i].style.display='block';
			
		}
	}
}

function showhidecheck (sid, tid) {

	if (document.getElementById(sid).checked == true)
		document.getElementById(tid).style.display = 'none';
	else
		document.getElementById(tid).style.display = '';

}

function hideshowcheck (sid, tid) {

	if (document.getElementById(sid).checked == true)
		document.getElementById(tid).style.display = '';
	else
		document.getElementById(tid).style.display = 'none';

}

function showhide_any (id, sort) {

	var box = document.getElementById(id).style;

	box.display = (box.display==sort) ? 'none' : sort;
 }
 
function hideshow_any (id, sort) {

	var box = document.getElementById(id).style;

	box.display = (box.display=='none') ? sort : 'none';
}

function showhide (id) {

	var box = document.getElementById(id).style;

	box.display = (box.display=='block') ? 'none' : 'block';
 }
 
function hideshow (id) {

	var box = document.getElementById(id);

	if (box.style.display == "none")
		box.style.display = "";
	else
		box.style.display = "none";
}
 
function showhidetbl (id) {

	var box = document.getElementById(id).style;

	box.display = (box.display=='table') ? 'none' : 'table';
 }
 
function hideshowtbl (id) {

	var box = document.getElementById(id).style;

	box.display = (box.display=='none') ? 'table' : 'none';
 }
 
function switchbg (id, from, to) {

	var box = document.getElementById(id).style;

	box.backgroundImage = (stripQuote(box.backgroundImage) == from) ? to : from;
}

function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=600,left = 240,top = 112');");
}

function stripQuote(str) {

	str = str.replace(/\"/g, "");
	
	return str;

}

// Add smilies

function addsmiley(id, smil) {

	insertAtCursor(document.getElementById(id), smil);

}

function insertAtCursor(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
		myField.focus();
		myField.selectionStart = myField.selectionEnd = myField.value.substring(0, startPos).length + myValue.length;
	} else {
		myField.value += myValue;
	}

}

function saveSel(myField) {

	//IE support
	if (document.selection) {
		myField.focus();
		_sel = document.selection.createRange();
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		_selStart = myField.selectionStart;
		_selEnd = myField.selectionEnd;
	}
}

function setSel(myField) {

	//IE support
	if (_sel) {
		myField.focus();
		document.selection.createRange() = _sel;
	}
	//MOZILLA/NETSCAPE support
	else if (_selStart || _selEnd) {
		_selStart = myField.selectionStart;
		_selEnd = myField.selectionEnd;
	}
}

// Add list type
function addList(id) {

	var field = document.getElementById(id);
	var cake = 1;
	
	insertAtCursor(field, "[list]\r\n");
	
	while (cake) {
	
		cake = prompt("Add list paragraph\nPress cancel to stop", "");
	
		if (cake)
			insertAtCursor(field, "[*]"+cake+"\r\n");
	
	}
	
	insertAtCursor(field, "[/list]");

}

function getSelection(ta)
  { var bits = [ta.value,'','','']; 
    if(document.selection)
      { var vs = '#$%^%$#';
        var tr=document.selection.createRange()
        if(tr.parentElement()!=ta) return null;
        bits[2] = tr.text;
        tr.text = vs;
        fb = ta.value.split(vs);
        tr.moveStart('character',-vs.length);
        tr.text = bits[2];
        bits[1] = fb[0];
        bits[3] = fb[1];
      }
    else
      { if(ta.selectionStart == ta.selectionEnd) return null;
        bits=(new RegExp('([\x00-\xff]{'+ta.selectionStart+'})([\x00-\xff]{'+(ta.selectionEnd - ta.selectionStart)+'})([\x00-\xff]*)')).exec(ta.value);
      }
     return bits;
  }
  
// Add forum tags
function matchPTags(str)
  { str = ' ' + str + ' ';
    ot = str.split(/\[[B|U|I|img|quote|url|youtube].*?\]/i);
    ct = str.split(/\[\/[B|U|I|img|quote|url|youtube].*?\]/i);
    return ot.length==ct.length;
  }

function addcolor (color, tImg) {

	setSel("Message");
	showhide("quick_codes_colors");
	document.getElementById("colorclick").style.backgroundImage = 'url('+tImg+')';
	addPTag("Message","color" + color);

}
  
function addPTag(id,pTag) { 
	var ta = document.getElementById(id);
	var bits = getSelection(ta);
	var adds;
    if(bits) { 
		if(!matchPTags(bits[2])) { 
			alert('\t\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
        }
		var pattern=new RegExp(/^(color(.*?))$/);
		var pattern2=new RegExp(/^(size(.*?))$/);
		var color=pTag.replace(pattern,"$2");
		var size=pTag.replace(pattern2,"$2");
		if (pattern.test(pTag)) 
			adds = '[color=' + color + ']' + bits[2] + '[/color]';
		else if (pattern2.test(pTag))
			adds = '[size=' + size + ']' + bits[2] + '[/size]';
		else
			adds = '[' + pTag + ']' + bits[2] + '[/' + pTag + ']';
		
		if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent))
			ta.value = bits[1] + adds + bits[3];
		else
			insertAtCursor(ta, adds);
		
    }
	else {
		var pattern=new RegExp(/^(color(.*?))$/);
		var pattern2=new RegExp(/^(size(.*?))$/);
		var color=pTag.replace(pattern,"$2");
		var size=pTag.replace(pattern2,"$2");
		if (pattern.test(pTag)) {
			if (tagOpen[pTag]) {
				adds = '[/color]';
				tagOpen[pTag] = false;
			}
			else {
				tagOpen[pTag] = true;
				adds = '[color=' + color + ']';
			}
		}
		else if (pattern2.test(pTag))
			if (tagOpen[pTag]) {
				adds = '[/size]';
				tagOpen[pTag] = false;
			}
			else {
				tagOpen[pTag] = true;
				adds = '[size=' + size + ']';
			}
		else
			if (tagOpen[pTag]) {
				adds = '[/'+ pTag +']';
				tagOpen[pTag] = false;
			}
			else {
				tagOpen[pTag] = true;
				adds = '[' + pTag + ']';
			}
			
		insertAtCursor(ta, adds);
	}
}

  
// Add video tag 
function addVideoTag(id) 
{
	var ta = document.getElementById(id);
	var bits = getSelection(ta);
	var adds;
    if(bits) { 
		if (!matchPTags(bits[2])) { 
			alert('\t\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
        }
		adds = '[video]' + bits[2] + '[/video]';	
		if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) 
			ta.value = bits[1] + adds + bits[3];
		else
			insertAtCursor(ta, adds);
    }
	else {
		var addr = prompt("Enter youtube/liveleak adress", "");
		if (addr != null) 
			insertAtCursor(ta, '[video]'+addr+'[/video]');
	}
}

// Add url tag 
function addUrlTag(id) 
{
	var ta = document.getElementById(id);
	var bits = getSelection(ta);
	var adds;
    if(bits) { 
		if (!matchPTags(bits[2])) { 
			alert('\t\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
        }
		adds = '[url]' + bits[2] + '[/url]';		
		if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) 
			ta.value = bits[1] + adds + bits[3];
		else
			insertAtCursor(ta, adds);
    }
	else {
		var addr = prompt("Enter link adress", "");
		var descr = prompt("Enter link description", "");
		
		if (addr != null && descr != null)
			insertAtCursor(ta, "[url="+addr+"]"+descr+"[/url]");
		else if (addr != null)
			insertAtCursor(ta, "[url]"+addr+"[/url]");
	}
}

// Add img tag
function addImgTag(id) 
{
	var ta = document.getElementById(id);
	var bits = getSelection(ta);
	var adds;
    if(bits) { 
		if (!matchPTags(bits[2])) { 
			alert('\t\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
        }
		adds = '[img]' + bits[2] + '[/img]';	
		if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) 
			ta.value = bits[1] + adds + bits[3];
		else
			insertAtCursor(ta, adds);
    }
	else {
		var addr = prompt("Enter image adress", "");
		if (addr != null)
			insertAtCursor(ta, "[img]"+addr+"[/img]");
	}
}


var _countDowncontainer=0;
var _currentSeconds=0;

function ActivateCountDown(strContainerID, initialValue) {

    _countDowncontainer = document.getElementById(strContainerID);

    SetCountdownText(initialValue);

    window.setTimeout("CountDownTick()", 1000);

}

function CountDownTick() {

    if (_currentSeconds <= 1) {
        location.reload(true);
		return;
	}

    SetCountdownText(_currentSeconds-1);

    window.setTimeout("CountDownTick()", 1000);

}

function SetCountdownText(seconds) {

    _currentSeconds = seconds;

    var strText = seconds;

    _countDowncontainer.innerHTML = strText;

}