// XMLHTTPRequest
var xmlHTTP;

function createXMLHttpRequest() {
if (window.ActiveXObject) {
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
  }
}

function runAJAX(changeState, url) {
  createXMLHttpRequest();
  xmlHttp.onreadystatechange = changeState;
	var currentTime = new Date();
  xmlHttp.open("GET", url + "&timestamp=" + currentTime.getTime(), true)
  xmlHttp.send(null);
}

function runAJAXPost(changeState, url, data) {
  createXMLHttpRequest();
  xmlHttp.onreadystatechange = changeState;
  var currentTime = new Date();
  // Append a timestamp to ensure non-cached version
  xmlHttp.open("POST", url + "&timestamp=" + currentTime.getTime(), true);
  xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
  xmlHttp.send(data);
}

function handle() {
	// Dummy handle for when nothing is brought back
}

function saveDraftPost(topic_id) {
  var btn = document.getElementById('btnDraft');
  btn.value = "Saving...";
  btn.disabled = true;
//	runAJAXPost(handleSaveDraftPost,'actions.php?action=save_draft_post&t=' + topic_id , 'p=' + document.getElementById('message').value);
}

function handleSaveDraftPost() {
if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
		var doc = xmlHttp.responseXML;
		document.getElementById('msg_draft').innerText = doc.getElementsByTagName('response')[0].firstChild.data;
	}
  }
}

function updateTopicAnswered(topic_id) {
  runAJAX(handleUpdateTopicAnswered,'/forums/actions?action=request_answered&t=' + topic_id);
}

function handleUpdateTopicAnswered() {
if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
		document.getElementById('msg').innerHTML = xmlHttp.responseText;
		document.getElementById('msg').style.display = '';
	}
  }
}

var animTimer;
var ratingInProgress = false;
var ratingComplete = false;

function handleSubmitRating() {
	if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
			//alert(xmlHttp.responseText);
		  if (xmlHttp.responseXML.getElementsByTagName('response')[0].firstChild.data != 'success') {
				clearTimeout(animTimer);
				for (var i=0;i<=4;i++) {
						document.getElementById('mock' + i).src = images_dir + "misc/star.png";
				}
				document.getElementById('rating_caption').innerHTML = "Rate this design";
				alert("Unfortunately your rating could not be added");
			} else {
				ratingComplete = true;
				rating = xmlHttp.responseXML.getElementsByTagName('rating')[0].firstChild.data;
				description = xmlHttp.responseXML.getElementsByTagName('description')[0].firstChild.data;
				numVotes = xmlHttp.responseXML.getElementsByTagName('num_votes')[0].firstChild.data;
				affix = (numVotes > 1) ? "s" : "";
				clearTimeout(animTimer);

				stars = document.getElementById('rating_stars').getElementsByTagName('a');
				for (var i=stars.length-1;i>=0;i--) {
					//stars[i].parentNode.removeChild(stars[i]);
					stars[i].disabled = true;
				}

				for (var i=0;i<=4;i++) {
					if (i <= rating) {
						document.getElementById('mock' + i).src = images_dir + "misc/star-on.png";
					} else {
						document.getElementById('mock' + i).src = images_dir + "misc/star.png";
					}			
				}

				document.getElementById('rating_caption').innerHTML = description + " (" + numVotes + " vote" + affix + ")";
			}
		}
	}
	ratingInProgress = false;
}

function updateTopicStatus(topic_id) {
  runAJAX(handleUpdateTopicStatus,'modactions.php?action=update_topic_status&t=' + topic_id);
}

function handleUpdateTopicStatus() {
if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
		array_ret = xmlHttp.responseText.split(",");
		document.getElementById('img' + array_ret[0]).src = array_ret[1];
		alert(array_ret[2]);
	}
}
}

function hideTopic(topic_id) {
 runAJAX(handleHideTopic,'modactions.php?action=hide_topic&t=' + topic_id);
}

function handleHideTopic() {
if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
	  array_ret = xmlHttp.responseText.split(",");
	  var el = document.getElementById('row' + array_ret[0]);
	  el.parentNode.removeChild(el); 
	  alert(array_ret[1]);
	}
}
}


function saveTopicDesc() {

  var topic_id = document.formtopic.topic_id.value;
  // Ajax
  var tt = document.getElementById('topic_description');
  var ntt = tt.value;
  runAJAX(handleTopicDesc,'actions.php?action=edit_topic_description&t=' + topic_id + "&d=" + escape(ntt));

  // Return back to span tag
  var ett = document.createElement("span");
  tt.replaceNode(ett);
  ett.innerHTML = ntt;
  ett.id = 'topic_description';
  ett.title = "Click to edit the topic description";
  ett.style.cursor = "pointer";
  ett.onclick = new Function ("editTopicDesc()");
  document.getElementById('button_tt').style.display = "none";

}

function handleTopicDesc() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
		  if (xmlHttp.responseXML.getElementsByTagName('response')[0].firstChild.data != 'success') {
				alert("Unfortunately the topic description could not be changed");
			} else {
				document.getElementById('topic_description').innerHTML = xmlHttp.responseXML.getElementsByTagName('description')[0].firstChild.data;
			}
	  }
  }
}



function handleUpdateTopicStatus() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
		  array_ret = xmlHttp.responseText.split(",");
		  document.getElementById('img' + array_ret[0]).src = array_ret[1];
		  alert(array_ret[2]);
	  }
  }
}




function rtpSubmit() {
 var p = document.getElementById('rtp_post_id');
 var post = document.getElementById('rtp_text');
 var c = document.getElementById('category_id');
 var b = document.getElementById('btnRTP');
 if (post.value == "" && c.value == 0) {
	alert("Please provide a brief description of why you are reporting this post");
	post.focus();
 } else {
	 post.disabled = true;
	 b.disabled = true;
	 b.value = 'Sending...';
	 runAJAXPost(handleRtpSubmit,'/forums/actions.php?action=rtp&c=' + c.value + '&p=' + p.value, '&post=' + post.value);
 }
}

function handleRtpSubmit() {
	var p = document.getElementById('rtp_post_id');
	var post = document.getElementById('rtp_text');
//	var v = document.getElementById('rtp_vicinity');
	var b = document.getElementById('btnRTP');
	var msg = document.getElementById('msg');

  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {

	//alert(xmlHttp.responseText);

			if (xmlHttp.responseXML.getElementsByTagName('response')[0].firstChild.data != 'success') {
				alert("Unfortunately the RTP could not be submitted. Please try again or contact the moderators directly");
			} else {
				msg.innerHTML = "Thank you - the moderators will be notified about this post. In general you will not receive a personal reply but please be assured your message will be viewed and acted upon if necessary. Remember, few complaints are dealt with in the public eye.";
				msg.style.display = "block";
				msg.style.marginLeft = "5%";
				msg.style.marginRight = "5%";
			}

			hideOverlay();
			closeRTP();
			window.scrollTo(0,0);
			post.disabled = false;
			//v.disabled = false;
			b.disabled = false;
			b.value = 'Submit';
		}
  }
}

function popularity() {
	$.post("/forums/actions", { action: "popularity", topic_ids: $("#topics_ids").val() },
  function(xml){
    $(xml).find('topics').children().each(function(){
 			$("#pop" + $(this).attr('id')).html('<img src="' + images_dir + 'misc/popular-' + $(this).attr('pop') + '.gif" />');	
		});
  });
	
	$("*[class=popular]:hidden").show();
	return false;
}
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
    var i;
    for (i=0; i < this.length; i++) {
        if (this[i] == value) {
            return true;
        }
    }
    return false;
};

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function leadingZero(num) {
	return (num < 10 && num >= 0) ? "0" + num : num;
}images_dir = '/img/';

startList = function() {
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("nav");
		if (navRoot) {
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI") {
					node.onmouseover=function() {
						this.className+=" over";
					}
					node.onmouseout=function() {
						this.className=this.className.replace(" over", "");
					}
				}
			}
		}
	}
}
window.onload=startList;



function showRating(numb) {
	if (!ratingComplete) {
		for (var i=0;i<=4;i++) {
			if (numb < i) {
				document.getElementById('mock' + i).src = images_dir + "misc/star.png";
			} else {
				document.getElementById('mock' + i).src = images_dir + "misc/star-on.png";			
			}
		}
		switch (numb) {
			case 0:
				rating = 'Awful';
				break;
			case 1:
				rating = 'Poor';
				break;
			case 2:
				rating = 'Respectable';
				break;
			case 3:
				rating = 'Impressive';
				break;
			case 4:
				rating = 'Outstanding';
				break;
		}	
		document.getElementById('rating_caption').innerHTML = rating;
	}
}

function clearRating() {
	if (!ratingComplete) {
		for (var i=0;i<=4;i++) {
			document.getElementById('mock' + i).src = images_dir + "misc/star.png";
			document.getElementById('rating_caption').innerHTML = 'Rate this design';
		}
	}
}

/*
function rtp(elem, post_id) {
  var r = document.getElementById('rtp_post');
  document.getElementById('rtp_post_id').value = post_id;
  document.getElementById('rtp').style.display = "";
  r.value = "";
  elem.parentNode.parentNode.insertBefore(document.getElementById('rtp'), elem.parentNode);
  document.getElementById('rtp_successful').style.display = 'none';
  r.focus();
}
*/

function showHideForumBox(val) {
	if (val == "move_topics" || val == "move_topic") {
		disp = '';
	} else {
		disp = 'none';
	}
	document.getElementById('move_forum_id').style.display = disp;
}


function hideEmbedded() {
	hideOverlay();
	document.getElementById('divEmbeddedClip').style.display = "none";
}

function showEmbedded(url,title,ws) {
	var objOverlay = document.getElementById('overlay');
	var objEmbedded = document.getElementById('divEmbeddedClip');
	var h1 = document.getElementById('divEmbeddedClipTitle');

	h1.style.display = (title == "") ? "none" : "block";
	h1.innerText = title;

	var arrayPageSize = getPageSize();
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	var width = 480;
	var height = (ws) ? 305 : 380;

	document.getElementById('divEmbeddedClipInner').innerHTML = '<embed src="http://www.tvforum.co.uk/player.swf" width="'+width+'" height="'+height+'" bgcolor="#FFFFFF" allowfullscreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" name="embeddedclip" flashvars="file='+url+'&showdigits=true&autostart=true&fullscreen=true&plugins=gapro-1&gapro.accountid=UA-241875-1&gapro.trackstarts=true&gapro.tracktime=true" />';

	objEmbedded.style.display = 'block';	
	objEmbedded.style.position = 'fixed';	
	objEmbedded.style.left = (((parseFloat(document.body.clientWidth) - 512)/2)/document.body.clientWidth)*100 + "%";
	objEmbedded.style.top = (((parseFloat(document.body.clientHeight) - 400)/2)/document.body.clientHeight)*100 + "%";
	return false;
}


function warnBan(type, post_id, username) {
	var objOverlay = document.getElementById('overlay');
	var objWarn = document.getElementById('warnban');

	var arrayPageSize = getPageSize();
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	objWarn.style.position = 'fixed';	
	objWarn.style.left = (((parseFloat(document.body.clientWidth) - 512)/2)/document.body.clientWidth)*100 + "%";
	objWarn.style.top = (((parseFloat(document.body.clientHeight) - 200)/2)/document.body.clientHeight)*100 + "%";
	$('#warnban').fadeIn("fast");

	document.getElementById('warn_post_id').value = post_id;
	document.getElementById('warn_type_id').value = type;
	if (type == 1) {
		document.getElementById('warn_title').innerHTML = "Warn " + username;
	} else {
		document.getElementById('warn_title').innerHTML = "Ban " + username + " from this forum";
	}

}

function siteBan(user_id, username) {
	var objOverlay = document.getElementById('overlay');
	var objBan = document.getElementById('siteban');

	var arrayPageSize = getPageSize();
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	objBan.style.position = 'fixed';	
	objBan.style.left = (((parseFloat(document.body.clientWidth) - 512)/2)/document.body.clientWidth)*100 + "%";
	objBan.style.top = (((parseFloat(document.body.clientHeight) - 200)/2)/document.body.clientHeight)*100 + "%";
	$('#siteban').fadeIn("fast");
	document.getElementById('siteban_user_id').value = user_id;
	document.getElementById('siteban_title').innerHTML = "Site ban " + username;
}

function closeWarnBan() {
	hideOverlay();
	document.getElementById('warnban').style.display = "none";
}

function closeSiteBan() {
	hideOverlay();
	document.getElementById('siteban').style.display = "none";
}


function rtp(elem, post_id) {
	var objOverlay = document.getElementById('overlay');
	var objRTP = document.getElementById('rtp');

var arrayPageSize = getPageSize();

	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
/*	objRTP.style.top = arrayPageSize[1] + "px";
//	objRTP.style.top = (((arrayPageSize[1]-arrayPageSize[3] -200) / 2) + 'px');
	objRTP.style.left = (((arrayPageSize[0] - 512) / 2) + 'px');
*/

	

//	centerDiv(objRTP);
//	objRTP.style.display = 'block';	
	objRTP.style.position = 'fixed';	
	objRTP.style.left = (((parseFloat(document.body.clientWidth) - 512)/2)/document.body.clientWidth)*100 + "%";
	objRTP.style.top = (((parseFloat(document.body.clientHeight) - 200)/2)/document.body.clientHeight)*100 + "%";

	$('#rtp').fadeIn("fast");

	document.getElementById('rtp_post_id').value = post_id;
	document.getElementById('rtp_text').focus();
	return false;
}

function closeRTP() {
	hideOverlay();
	document.getElementById('rtp').style.display = "none";
	document.getElementById('rtp_text').value = "";
}


function filterAVDownloads(type) {
	var rows = document.getElementById('downloadstable').getElementsByTagName('tr');
	var count = 0;
	for (var i=0;i<rows.length;i++) {
		row_type_id = rows[i].getAttribute("type_id");
		if (row_type_id) {
			if (i == 0 || type == "" ||
				(row_type_id == 2 && type == "v") ||
				(row_type_id == 3 && type == "a") ||
				(row_type_id >= 4 && row_type_id <= 5 && type == "ev") ||
				(row_type_id == 6 && type == "yt")) {
					rows[i].style.display = "";
					count++;
			} else {
				rows[i].style.display = "none";
			}
		}
	}
	document.getElementById('no_results').style.display = (count == 0) ? "" : "none";
}


function togglePoll() {

var poll_display = document.getElementById('table_poll').style.display;

if (poll_display == "none") {
  poll_display_new = "";
} else {
  poll_display_new = "none";
}

document.getElementById('table_poll').style.display = poll_display_new;

toggleBBCode('poll');

return true;

}

function updatePMTo(value) {
  document.getElementById('recipient').value = value;
  document.getElementById('recipient_dd').selectedIndex = 0;
  document.getElementById('subject').focus();
  return true;
}


/*
function goPM(section, data) {
 
 var url;
	if (section=='newest') {
		url = '/forums/privmsgs.php?action=newest';
  } else if (section=='message' && data) {
   url = '/forums/privmsgs.php?action=message&m=' + data;
  } else if (section=='new' && data) {
   url = '/forums/post.php?action=new_pm&u=' + data;
  } else {
   url = '/forums/privmsgs.php';
  }

	var win = window.open(url,"goPM",'width=750,height=500,resizable=1,scrollbars=yes,menubar=yes,status=yes,left=50,top=50');
}
*/


function goPM(url) {
	var win = window.open(url,'PMwin','width=751,height=500,resizable=1,scrollbars=yes,menubar=yes,status=yes,left=50,top=50');
	return false;
}

function goMSN(username) {
	alert("The user's MSN username is: " + username);
	return false;
}


function gotoPage(topic_id, max_pages) {
  var page = prompt('Which page in this topic?',1);
  if (page) {
    location.href = 'viewtopic.php?t='+topic_id+'&st='+page;
  }
}


function editTopicDesc() {

   var tt = document.getElementById('topic_description');
   var ttt = tt.innerHTML;
   var ett = document.createElement("input");
   ett.style.width = "200px";
   ett.id = 'topic_description';
   ett.value = ttt;
   tt.replaceNode(ett);
   document.getElementById('button_tt').style.display = "";
   ett.focus();
}

// profile
function changePassword() {
	document.getElementById('pwd-c').style.display = "";
	document.getElementById('pwd-c-no').style.display = "none";
	document.getElementById('current_password').focus();
}

function changeUsername() {
	var c = document.getElementById('usr-c');
    c.style.display = "";
	document.getElementById('new_username').focus();
	document.getElementById('btn_ch_user').style.display = "none";
}

// viewforum.php?f=4
function changeHiMock(mock, which) {
	var the_mock = document.getElementById(mock);
	if (which == 0) the_mock.className = 'mock-image'; else the_mock.className = 'mock-image-on';

}

// privmsgs
function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}

// preview post

function previewPost(formname) {

  var iframe = document.getElementById('preview_frame');
  var form = document.getElementById(formname);

  toggleShow('divPost');
  toggleShow('divPreviewPost');

  iframe.src = '/forums/templates/default/post_loading.html';
  form.target = 'preview_frame';
  document.getElementById('action').value = 'preview_post';
  form.submit();

}

function postDiv() {

  toggleShow('divPost');
  toggleShow('divPreviewPost');
 
}
  


function autofitIframe(frame,name){

	frame.style.height=(frames[name].document.body.scrollHeight)+"px";

}


function toggleShow(id) {

  var method = 'none';

  if (document.getElementById(id).style.display == 'none') {
    method = '';
  }

  document.getElementById(id).style.display = method;

  return true;

}



function addPollOption() {
  var element = document.getElementById('divOptions');
	if (element.getElementsByTagName("input").length <= 7) {	
		var wrapper = element.appendChild(document.createElement('div'));
		wrapper.className = "clear";

		var textbox = wrapper.appendChild(document.createElement('input'));
		textbox.type = "text";
		textbox.name = "poll_options[]";
		textbox.id = "poll_options[]";
		textbox.size = 48;
		textbox.className = "x";

		var btnD = wrapper.appendChild(document.createElement('a'));
		btnD.setAttribute("href","#");
		btnD.setAttribute("title",'Delete Poll Option');
		btnD.onclick = new Function ("deletePollOption(this); return false");
		img = btnD.appendChild(document.createElement('img'));
		img.setAttribute('src',images_dir + "icons/cross.png");
		img.style.marginLeft = "8px";
	}
}

function deletePollOption(option) {
  var element = document.getElementById('divOptions');
	if (element.getElementsByTagName("input").length > 1) {	
	  element.removeChild(option.parentNode);
	}
}

function durationDate(days) {

  var days = parseInt(days);

  var endDate=new Date();
  endDate.setDate(endDate.getDate()+days);


var months = new Array('January','February','March','April',
                           'May','June','July','August','September',
                           'October','November','December');

if (days > 0) {
document.getElementById('divEndDate').innerHTML = '(' + endDate.getDate() + ' ' + months[endDate.getMonth() + 1] + ' ' + endDate.getYear() + ')';
} else {
document.getElementById('divEndDate').innerHTML = '';
}

}


function mockHighlight(id, on) {
	if (on) {
		document.getElementById('mock-ttl-' + id).className = "mock-on";
	} else {
		document.getElementById('mock-ttl-' + id).className = "mock";
	}
}

function roll(img, dir) {

	var splits = img.src.split("/");
	var fileExt = splits[splits.length-1].replace("-on", "").split(".");
	splits.pop();
	if (dir == 1) {
		img.src = splits.join("/") + "/" + fileExt[0] + "-on." + fileExt[1];
	} else {
		img.src = splits.join("/") + "/" + fileExt[0] + "." + fileExt[1];
	}

}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


function hideOverlay() {
  var objOverlay = document.getElementById('overlay');
  objOverlay.style.display = "none";
}


//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function animateRating(numb) {
	if (numb == 5) numb = 0;
	for (var i=0;i<=4;i++) {
		if (i == numb) {
			document.getElementById('mock' + i).src = images_dir + "misc/star-on.png";
		//	alert("on");
		} else {
			document.getElementById('mock' + i).src = images_dir + "misc/star.png";
		}			
	}
	animTimer = setTimeout("animateRating(" + (numb+1) + ");",150);
}

function submitRating(rating, topic_id) {
	if (!ratingInProgress && !ratingComplete) {
		ratingInProgress = true;
		document.getElementById('rating_caption').innerHTML = "Submitting...";
		animateRating(0);
		runAJAX(handleSubmitRating,'actions.php?action=mock_rating&t=' + topic_id + "&r=" + rating);
	}
}



// Add an eventListener to browsers that can do it somehow.
function addEvent(obj, evType, fn){
        if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
        } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
        } else {
                return false;
        }
}

function trackInit() {
	var links = document.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		var link = links[i];
		if (link.className && link.className == "extlink") {
			link.onclick = function() { track(this); return true; };
		}
	}
}

function track(link, area) {
	var url = escape(link.href);
	var trImg = new Image();
	var now = new Date();
	trImg.src = "/extlinks.php?u="+url+"&a="+area+"&"+now.getTime();
}

	function showCalendar(obj, type) {
		
		var pos = findPos(obj);
		if (pos[0]+200 > document.body.clientWidth) pos[0] = document.body.clientWidth - 220;

		var popup = document.getElementById('cal_popup');
		popup.style.top = (pos[1]+10) + "px";
		popup.style.left = (pos[0]+10) + "px";
		popup.style.display = "";
	//	popup.firstChild.style.height = popup.offsetHeight + "px";
	//	popup.firstChild.style.width = popup.offsetWidth + "px";
		getCalendar(0, type);
		fadeObj('cal_popup',0,1);
		
	}
	
	function getCalendar(dir, type) {
		var month = document.getElementById('cal_month').value;
		var year = document.getElementById('cal_year').value;
	//	alert("year: " + year);
		if (dir == 1) {
			month = leadingZero(parseFloat(month)-1);
			if (month == 0) {
				month = 12;
				year = leadingZero(parseFloat(year) - 1);
			}
		} else if (dir == 2) {
			month = leadingZero(parseFloat(month) + 1);
			if (month == 13) {
				month = "01";
				year = leadingZero(parseFloat(year) + 1);
			}
		} 
		
//		alert(month);
//		alert(year);
		
		
		document.getElementById('cal_month').value = month;
		document.getElementById('cal_year').value = year;
		
		//alert('actions.php?action=topic_calendar&t=' + topic_id + '&mmyy=' + month + year);
//		fadeObj('cal_popup_inner');
		for (i=0;i<calendars.length;i++) {
			if (calendars[i].month == month && calendars[i].year == year) {
				buildCal(month, year, type);
				return true;
			}
		} 	

//		alert("calling");
			$.get("/forums/actions.php", { action: "page_calendar", type: type, t: page_id, mmyy: month + year },
				function(xml){
					if ($(xml).find("response").text() == "success") {
						month = $(xml).find("month").text();
						year = $(xml).find("year").text();
						calendars[calendars.length] = new calendar(month, year, $(xml).find("first_day").text(), $(xml).find("days_in_month").text(), $(xml).find("days").text().split(","));
						buildCal(month, year, $(xml).find("type").text());
					} else {
						alert("Unfortunately the calendar could not be shown");
					}	    
				});
			



	  //runAJAX(handleGetCalendar,'/forums/actions.php?action=page_calendar&type=' + type + '&t=' + page_id + '&mmyy=' + month + year);
	  return true;
	}
	
	function calendar(month, year, firstDay, daysInMonth, days) {
		this.month = month;
		this.year = year;
		this.firstDay = firstDay;
		this.daysInMonth = daysInMonth;
		this.days = days;
	}
	
	
	calendars = new Array();
	
	function handleGetCalendar() {
		if (xmlHttp.readyState == 4) {
	if (xmlHttp.status == 200) {
	//			alert(xmlHttp.responseText);
				response = singleXMLNode(xmlHttp, 'response');
				if (response == 'success') {
					month = singleXMLNode(xmlHttp, 'month');
					year = singleXMLNode(xmlHttp, 'year');
					firstDay = singleXMLNode(xmlHttp, 'first_day');
					daysInMonth = singleXMLNode(xmlHttp, 'days_in_month');
					days = singleXMLNode(xmlHttp, 'days');
					type = singleXMLNode(xmlHttp, 'type');
					calendars[calendars.length] = new calendar(month, year, firstDay, daysInMonth, days.split(","));
					buildCal(month, year, type);
		//			fadeObj('cal_popup_inner');
				}
			}
		}
}			

function singleXMLNode(xmlHttp, name) {
	try {
			return xmlHttp.responseXML.getElementsByTagName(name)[0].firstChild.data;
		} catch (err) {
			return "";
		}
}

	function buildCal(month, year, type) {
		
		var found = false;			
		for (i=0;i<calendars.length;i++) {
			if (calendars[i].month == month && calendars[i].year == year) {
				firstDay = calendars[i].firstDay;
				daysInMonth = calendars[i].daysInMonth;
				days = calendars[i].days;
				found = true;
				break;
			}
		}
		if (!found) return false;
		
		var daysHeader = new Array('Mo','Tu','We','Th','Fr','Sa','Su');
		
		var tbl = document.createElement("table");
		tbl.width = "100%";
		tbl.cellpadding = 0;
		tbl.cellspacing = 0;
		//tbl.border = 1;
		var tblh = tbl.insertRow(0);
	  tblh.className = "rowhead";
	  for (var i=0;i<7;i++) {
		var cell = tblh.insertCell(i);
		cell.innerHTML = daysHeader[i];
	  }
	  
	  rowCount = 1;
	 //var tblr = tbl.insertRow(1);
	  for (var i=0;i<42;i++) {
		if (i == 0 || i == 7 || i == 14 || i == 21 || i == 28 || i == 35) {
				tblr = tbl.insertRow(rowCount);
				rowCount++;
			}
			var cell = tblr.insertCell(i%7);
		var day = i-firstDay+2;
			if (i > firstDay-2 && day <= daysInMonth) {
				cell.innerHTML = day;
				if (days.inArray(day)) {
					cell.className = "cal_posted";
					if (type == 'topic') {
						cell.onclick = new Function("window.location.href='/forums/topic" + page_id + "/" + leadingZero(day) + "-" + month + "-" + year + "';");
					} else {
						cell.onclick = new Function("window.location.href='/forums/topic" + page_id + "/" + leadingZero(day) + "-" + month + "-" + year + "';");
					}
				} else {
					cell.className = "cal_date";
				}
			} else {
			//	cell.className = "cal_invalid";
			}
	  }
		
		var cpi = document.getElementById('cal_popup_inner');	
		cpi.innerHTML = '';	
		cpi.appendChild(tbl);
		
	}

var fadeTimer;

function fadeObj(name) {
	var obj = document.getElementById(name);
	if (obj.style.opacity == 0 || obj.style.opacity == undefined) {
		fadeAnim(name,0,1);
	} else {
		fadeAnim(name,100,0);
	}
}

function fadeAnim(name,newOpacity,dir) {		
	var obj = document.getElementById(name);
	obj.style.filter = 'alpha(opacity = ' + newOpacity + ')';
	obj.style.opacity = (newOpacity/100);
	//alert(obj.style.filter);
	if (newOpacity < 100 && dir == 1) { 
		fadeTimer = window.setTimeout("fadeAnim('"+name+"',"+(newOpacity+20)+","+dir+");",20);
	} else if (newOpacity > 0 && dir == 0) {
		fadeTimer = window.setTimeout("fadeAnim('"+name+"',"+(newOpacity-20)+","+dir+");",20);			
	}
	
}
	
function hideCal(evt) {
	var srcElement = evt.srcElement ? evt.srcElement : evt.target;
	if (!findElement(srcElement, 'cal_popup')) {
		var obj = document.getElementById('cal_popup');
		if (obj.style.opacity == 1) fadeObj('cal_popup');
	}
}
		
function findElement(obj, name) {
	if (obj.id && obj.id == name) {
		return true;
	} else if (obj.parentNode && obj.parentNode.nodeType == 1) {
	//	alert(obj.innerHTML);
		if (obj.parentNode.id && obj.parentNode.id == name) {
			return true;
		} else {
			return findElement(obj.parentNode, name);
		}
	}
	return false;
}


// Index
function loadCal() {			
	for (var i=0;i<dt.length;i++) {
		var caltd = document.getElementById('cal_' + dt[i].day + dt[i].month + dt[i].year);
		if (caltd) {
			caltd.className = "cal_avail";		
			caltd.style.cursor = "pointer";
			caltd.onmouseover = new Function('showPostit(' + dt[i].year + ',' + dt[i].month + ',' + dt[i].day + ', this);');
			caltd.onmouseout = new Function("hidePostit()");
		}
	}
}


var globDay = 0;

var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function daySuffix(day) {
	day = day + "";
	var day2 = day.substring(day.length-1,day.length);
	if (day2 == 1) return day + "st";
	else if (day2 == 2) return day + "nd";
	else if (day2 == 3) return day + "rd";
	else return day + "th";
}


function showPostit(year, month, day, obj) {
 
	var postit = document.getElementById('postit');
	
	if (day != globDay || true) {
		var pos = findPos(obj);
		
		postit.style.top = (pos[1]+15)+"px";
		postit.style.left = pos[0]-100-document.getElementById('cal_container').scrollLeft;//-document.getElementById('calendar').clientWidth+35)+"px";
		globDay = day;
	}

	document.getElementById('postit_text').innerHTML = "";
	var shown = 0;
	for (var i=0;i<dt.length;i++) {
		if (dt[i].year == year && dt[i].month == month && dt[i].day == day) {
			document.getElementById('postit_date').innerHTML = daySuffix(day) + " " + months[month-1] + " " + year;
			line = (shown > 0) ? '<hr />' : '';
			document.getElementById('postit_text').innerHTML += line + "<b>" + dt[i].time + " - " + dt[i].channel + "</b><br/>" + dt[i].description + "<br/><small>Posted by " + dt[i].username + "</small><br/>";
			shown++;
		}
	}				
	postit.style.display = "";

}

function hidePostit() {
document.getElementById('postit').style.display = "none";
}

			




function addPostit(year, month, day, obj) {

	var objOverlay = document.getElementById('overlay');
	var objAdd = document.getElementById('add_postit');
	var arrayPageSize = getPageSize();

	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
	
	//document.getElementById('flash_images').style.visibility = "hidden";
	document.getElementById('add_postit_date').innerHTML = day + "/" + month + "/" + year;

	document.getElementById('add_date').value = day + "/" + month + "/" + year;	
	document.getElementById('add_postit').style.display = "";

	document.getElementById('channel').value = "";
	document.getElementById('description').value = "";	
	document.getElementById('hour').value = 12;
	document.getElementById('minute').value = 0;
	document.getElementById('postit_ajax_loader').style.visibility = 'hidden';
//  document.getElementById('btnPositSubmit').disabled = false;
	document.getElementById('channel').focus();	

	objAdd.style.top = (((arrayPageSize[3] - objAdd.clientHeight) / 2) + 'px');
	objAdd.style.left = (((arrayPageSize[0] - objAdd.clientWidth) / 2) + 'px');
	objAdd.style.display = 'block';	

}

function closeAddPostit() {
  document.getElementById('add_postit').style.display = "none";
  hideOverlay();
}
var theSelection = false;

var clientPC = navigator.userAgent.toLowerCase();
var clientVer = parseInt(navigator.appVersion);

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_win   = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac    = (clientPC.indexOf("mac")!=-1);

/*
b_help = "Bold text: [B]text[/B]";
i_help = "Italic text: [I]text[/I]";
u_help = "Underline text: [U]text[/U]";
q_help = "Quote text: [QUOTE]text[/QUOTE]";
c_help = "Code display: [CODE]code[/CODE]";
p_help = "Insert image: [IMG]http://image_url[/IMG]";
w_help = "Insert URL: [URL]http://url[/URL] or [URL=http://url]URL text[/URL]";
s_help = "Font color: [COLOR=red]text[/COLOR] Tip: can also use HTML color=#FF0000";
f_help = "Font size: [SIZE=9]small text[/SIZE]";
*/

var Quote = 0;
var Bold  = 0;
var Italic = 0;
var Underline = 0;
var Code = 0;
var Spoiler = 0;
var Video = 0;

function toggleBBCode(name) {
	var image_src = document.getElementById('icon-' + name).src;
	var image_new_src;

	if (image_src.indexOf('-on.png') != -1) {
		image_new_src = '/forums/img/icons/' + name + '.png';
	} else {
		image_new_src = '/forums/img/icons/' + name + '-on.png';
	}

	document.getElementById('icon-' + name).src = image_new_src;
	return true;
}

/*
function helpline(help) {
	document.form_post.helpbox.value = eval(help + "_help");
	document.form_post.helpbox.readOnly = "true";
}
*/

function checkForm() {
	formErrors = false;    
	if (document.form_post.message.value.length < 2) {
		formErrors = "You must enter a message when posting";
	}
	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	text = ' ' + text + ' ';
	PostWrite(text);
}

function bbfontstyle(bbopen, bbclose) {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			document.form_post.message.value += bbopen + bbclose;
			document.form_post.message.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		document.form_post.message.focus();
		return;
	} else {
		document.form_post.message.value += bbopen + bbclose;
		document.form_post.message.focus();
		return;
	}
	storeCaret(document.form_post.message);
}

function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

function PostWrite(text) {
	if (document.form_post.message.createTextRange && document.form_post.message.caretPos) {
		var caretPos = document.form_post.message.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?	text + ' ' : text;
	}
	else document.form_post.message.value += text;
	document.form_post.message.focus(caretPos)
}

function BBCcode() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[CODE]" + theSelection + "[/CODE]";
		document.form_post.message.focus();
		return;
		}
	}
	if (Code == 0) {
		ToAdd = "[CODE]";
		document.form_post.code.value = "Code*";
		Code = 1;
	} else {
		ToAdd = "[/CODE]";
		document.form_post.code.value = "Code";
		Code = 0;
	}
	PostWrite(ToAdd);
}

function BBCquote() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[QUOTE]" + theSelection + "[/QUOTE]";
		document.form_post.message.focus();
		return;
		}
	}
	if (Quote == 0) {
		ToAdd = "[QUOTE]";
		Quote = 1;
	} else {
		ToAdd = "[/QUOTE]";
		Quote = 0;
	}
	toggleBBCode('quote');
	PostWrite(ToAdd);
}

function BBCbold() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[B]" + theSelection + "[/B]";
		document.form_post.message.focus();
		return false;
		}
	}
	if (Bold == 0) {
		ToAdd = "[B]";
		Bold = 1;
	} else {
		ToAdd = "[/B]";
		Bold = 0;
	}
	toggleBBCode('bold');
	PostWrite(ToAdd);
	return false;
}

function BBCitalic() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[I]" + theSelection + "[/I]";
		document.form_post.message.focus();
		return false;
		}
	}
	if (Italic == 0) {
		ToAdd = "[I]";
		Italic = 1;
	} else {
		ToAdd = "[/I]";
		Italic = 0;
	}
	toggleBBCode('italic');
	PostWrite(ToAdd);
	return false;
}

function BBCunder() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[U]" + theSelection + "[/U]";
		document.form_post.message.focus();
		return false;
		}
	}
	if (Underline == 0) {
		ToAdd = "[U]";
		Underline = 1;
	} else {
		ToAdd = "[/U]";
		Underline = 0;
	}
	toggleBBCode('underline');
	PostWrite(ToAdd);
	return false;
}

function BBCspoiler() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[SPOILER]" + theSelection + "[/SPOILER]";
		document.form_post.message.focus();
		return false;
		}
	}
	if (Spoiler == 0) {
		ToAdd = "[SPOILER]";
		Spoiler = 1;
	} else {
		ToAdd = "[/SPOILER]";
		Spoiler = 0;
	}
	toggleBBCode('spoiler');
	PostWrite(ToAdd);
	return false;
}

function BBCurl2(enterURL) {
	var FoundErrors = '';
	var enterTITLE = prompt("Enter the webpage title", "Webpage Title");
	if (!enterURL)    {
		FoundErrors += " You have not entered the URL yet!";
	}
	if (!enterTITLE)  {
		FoundErrors += " You have not entered the title yet!";
	}
	if (FoundErrors)  {
		alert("Error!"+FoundErrors);
		return;
	}
	var ToAdd = "[url="+enterURL+"]"+enterTITLE+"[/url]";
	document.form_post.message.value+=ToAdd;
	document.form_post.message.focus();
	return false;
}

function BBCurl() {
var enterURL2   = prompt("Enter your URL", "");
BBCurl2(enterURL2);
}

function BBCimg() {
var enterURL2   = prompt("Enter your image URL","");
BBCimg2(enterURL2);
}

function BBCimg2(enterURL) {
	var FoundErrors = '';
		if (!enterURL) {
		return false;
	}
	var ToAdd = "[img]"+enterURL+"[/img]";
	document.form_post.message.value+=ToAdd;
	document.form_post.message.focus();
	return false;
}


function BBCvideo() {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (theSelection != '') {
		document.selection.createRange().text = "[wsvideo]" + theSelection + "[/wsvideo]";
		document.form_post.message.focus();
		return false;
		}
	}

	var url = prompt('Enter your Flash video URL','http://');
	if (url != "" && url != null && url != "http://") {
		ToAdd = "[wsvideo]" + url + "[/wsvideo]";
		PostWrite(ToAdd);
	}

	return false;
}

function BBCupload() {
 var t = window.open('http://rp-network.com/tvforum/','',' width=300,height=600,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=1,left=50,top=50');
 return false;
}// Global
var emotCount = 0;

function validatePost(post) {

	var valid = true;
	var message = "";
	var str = "";
	emotCount = 0;	// reset

	// Test length
	str = post.replace(/\s/g,"");
	if (str.length < 3) {
		message += "\nIt must include at least 3 characters";
		valid = false;
	}

	// Test quotes contain a response
	if (post.match(/\[quote(\=\"(.*?)\")?\](.*?)\[\/quote\]/g)) {
		str = post.replace(/(\[quote(\=\"(.*?)\")?\](.*?)\[\/quote\])|\s/g, "");
		if (trim(str.length) == 0) {
			message += "\nIt contains quote(s) with no response";
			valid = false;
		}
	}


	// Check number of emoticons
	var emot = new Array(":D",":)",":(",":o",":shock:",":?","8)",":lol:",":x",":P",":oops:"
	,":cry:",":evil:",":twisted:",":roll:",":wink:",":!:",":?:",":idea:");

	for (i=0;i<emot.length;i++) {
		// Ignoring emoticons from quoted posts
		checkEmoticon(str, emot[i], 0);
	}

	if (emotCount > 5) {
		message += "\nIt contains more than five emoticons. Please remove some of them!";
		valid = false;
	}


  if (valid == false)  {
	  alert("There are errors with your post:" + message);
  }

	return valid;

}


function checkEmoticon(str, emoticon, start) {
	res = str.indexOf(emoticon, start);

	if (res > -1 && str.length > res) {
	 	emotCount++;
		res++;
		checkEmoticon(str, emoticon, res);
	}

}

function validateEmail(email) {

  var pattern = /^.+@.+\\.[a-z]+$/;
  var valid = pattern.test(email);
  return valid;
}

function submitForgottenPassword() {

  var email = document.getElementById('email_address');

  if (email.value.length == 0)  { 
    alert("You must specify an email address.");
    return false;
  }
  
  if (validateEmail(email.value) == false) {
    alert("Invalid email address specified.");
    return false;
  }

  return true;

}

