var modalHtml;
$(document).ready(function() { 
	$('tr .checkbox:checked').parent().parent().addClass('selected');
	$('tr .checkbox').click(function() {
		if ( $(this).attr('checked') ) {
			$(this).parent().parent().addClass('selected');
		} else {
			$(this).parent().parent().removeClass('selected');
		}
	});
})

/* FORUMVIEW AJAX ACTIONS */
function setTracking(action, threadId, confirm) {
	if (action == 'remove' && !confirm) {
		confirmDialog('Confirm Stop Tracking', 
					  'Are you sure you want to stop tracking this topic?<br /><br /><strong>Tip:</strong> &nbsp;If you only want to disable e-mail notifications, cancel this dialog box and click the envolope icon next to the topic title.', 
					  'Stop Tracking', 
			 		  function () { 
					  	setTracking(action, threadId, 1);
						modalHtml = $('.modalFoot').html();
						$('.modalFoot').html( $('#postLoadingBar').html() );
					  	return false;
					  } );
		return false;
	}
	$.ajax({
		type: 'POST',
		url: urlThreadTracking,
		data: {action: action, 'threadid': threadId},
		success: function(msg){
			switch (action) {
				case 'remove':
					closeDialog();
					$('.modalFoot').html(modalHtml);
					$('#row' + threadId).fadeOut('normal', function () {
						$('#row' + threadId).remove();
						resortRowBgs();
					} );
					break;

				case 'setemail':
					$('#row' + threadId + ' #emailTrackOff').fadeOut('fast', function () { 
						$('#row' + threadId + ' #emailTrackOn').show();
					} );
					break;

				case 'unsetemail':
					$('#row' + threadId + ' #emailTrackOn').hide();
					$('#row' + threadId + ' #emailTrackOff').show();
					break;
			}
		}
	});
	return false;
}
function massTrackingAction(action, confirm) {
	// ensure we have _something_ ticked first
	if ( $('.row .checkbox:checked').length > 0 ) {
		if (action == 'remove' && !confirm) {
			confirmDialog('Confirm Stop Tracking', 
						  'Are you sure you want to stop tracking the selected topics?', 
						  'Stop Tracking', 
				 		  function () { massTrackingAction(action, 1); closeDialog(); return false; } );
			return false;
		}
		$('#action').attr('value',action);
		$('#activeForm').submit();
	} else {
		alert('Please select at least one topic first.');
	}
	return false;
}
function resortRowBgs() {
	$('.forumContainer .row').removeClass('alt');
	$('.forumContainer .row:odd').addClass('alt');
}

/* THREADVIEW AJAX ACTIONS */
function replyToPost(postId, index, goAdvancedUrl, submitting) {
	if (submitting) {
		/* quickreply box has no index, replying to post does, use as condition
		   to determine if this is a reply to a specific post and not quickreply */
		if ( index === false ) {
			index = lastIndex;
			originalPostHTML =  $('#controls').html();
			var action = 'quickReply';
			var sourcePostId = '';
		} else {
			var action = 'add';
			var sourcePostId = postId;
		}
		
		message = $('#replyText' + sourcePostId).val();
		if ( message.length >= 2 ) {
			$('#replyText' + sourcePostId).attr('disabled','disabled');
			$('#controls' + sourcePostId).html( $('#postLoadingBar').html() );
			sendPostRequest(action, postId, {message: message, posting: 1});
		} else {
			alert('Please write a longer reply before submitting (there is a minimum of 2 characters).');
		}
	} else {
		var ppBoxId = '#postPopBox' + postId;
		if (!$(ppBoxId + ' textarea').length) {
			// hide any other reply pop boxes open
			if (popBoxOpenId && popBoxOpenId != postId) $('#postPopBox' + popBoxOpenId).hide();
			popBoxOpenId = postId;
			// create form from template
			$(ppBoxId).html( $('#postQuickReply').html() );
			$(ppBoxId + ' .submitReply').click( function () { replyToPost(postId, index, false, true); return false; } );
			$(ppBoxId + ' .goAdvanced').click( function () { goAdvanced('#replyText' + postId, false, goAdvancedUrl); return false; } );
			$(ppBoxId + ' .cancelReply').click( function () { expandCollapseElement(ppBoxId); return false; } );
			$(ppBoxId + ' textarea').attr('id','replyText' + postId);
			$(ppBoxId + ' .controls').attr('id','controls' + postId);
			$('#replyText' + postId).bind("keyup paste", function(e){ setCharLimit(e) });
			// if this is the last post, add padding to form for design
			if (arrPostsMap[index] == arrPosts.length-1) $(ppBoxId + ' .message').addClass('padTop');
		}
		expandCollapseElement('#postPopBox' + postId, 'replyText' + postId);
	}
	return false;
}
function inlineEdit(lastIndex, postId, submitting) {
	if (submitting) {
		message = $.trim( $('#editPostText'+postId).val() );
		title = $.trim( $('#threadTitle').val() );
		if ( message.length < 2 ) {
			alert('Please write a longer reply before submitting (there is a minimum of 2 characters).');
		} else if ( $('#threadTitle').length && title.length < 4) {
			alert('Please write a longer topic title before submitting (there is a minimum of 4 characters).');
		} else {
			$('#postControlsInline' + postId).html( $('#postLoadingBar').html() );
			sendPostRequest('edit', postId, {message: message, title: title, posting: 1});
		}
	} else {
		// if any other post is being edited inline, close
		if (editingPostId) cancelInlineEdit(editingPostId);
		editingPostId = postId;
		originalPostHTML = $('#postContainer' + postId).html();
		$('#postControls' + postId).html( $('#postLoadingBar').html() );
		sendPostRequest('edit', postId, {lastIndex: lastIndex});
	}
	return false;
}
function inlineEditTitle(titleElement, submitting, titleTextElement, threadId) {
	titleTextElement = (titleTextElement && titleTextElement != 'undefined') ? titleTextElement : undefined;
	if (submitting) {
		title = $.trim( htmlspecialchars($('#topicTitleInline').val()) );
		if ( title.length == 0 ) {
			$(titleElement).html(originalPostHTML).dblclick( function() { inlineEditTitle(titleElement, false, titleTextElement, threadId) } );			
		} else if ( title.length < 4) {
			$('#topicTitleInline').unbind('blur').unbind('keyup');
			alert('Please write a longer topic title before submitting (there is a minimum of 4 characters).');
			$('#topicTitleInline').bind('keyup', function(e){ if (e && e.keyCode == 13 && $('#topicTitleInline').val().length >= 4 ) { inlineEditTitle(titleElement, true, titleTextElement, threadId); } });
			$('#topicTitleInline').blur( function () { inlineEditTitle(titleElement, true, titleTextElement, threadId); } );
			//$('#topicTitleInline').focus();
		} else {
			if ( originalTitle != title ) {
				var postData = (threadId) ? {title: title, posting: 1, threadId: threadId} : {title: title, posting: 1};
				sendPostRequest('editTitleOnly', false, postData);
			}
			$(titleElement).html(originalPostHTML).dblclick( function() { inlineEditTitle(titleElement, false, titleTextElement, threadId) } );

			if (titleTextElement)  {
				$(titleTextElement).html(title);
			} else {
				$(titleElement).html(title);
			}
			
			$('#topicTitle').html(title);
		}
	} else {
		originalTitle = (titleTextElement) ? $(titleTextElement).html() : $(titleElement).html();
		originalPostHTML = $(titleElement).html();
		$(titleElement).html( $('#editTitle').html() ).unbind('dblclick');
		$(titleElement + ' input').bind('keyup', function(e){ if (e && e.keyCode == 13 ) { inlineEditTitle(titleElement, true, titleTextElement, threadId); } });
		$(titleElement + ' input').attr('id', 'topicTitleInline').val( html_entity_decode(originalTitle) ).focus();
		$(titleElement + ' input').blur( function () { inlineEditTitle(titleElement, true, titleTextElement, threadId); } );
		$('#topicTitleInline').focus();
	}
	return false;
}
function goAdvanced(postText, postTitle, submitScript) {
	var form = new hiddenForm(submitScript);
	form.createInput('message', $(postText).val());
	if(postTitle) form.createInput('title', $(postTitle).val());
	form.submitForm();
	return false;
}
function confirmDeletePost(index, postId, deleteUrl) {
	confirmDialog('Confirm Delete Post', 
				  'Are you sure you want to <strong>permanently delete</strong> this post? This cannot be undone!', 
				  'Delete Post', 
				  function () { deletePost(index, postId, deleteUrl); closeDialog(); return false; } );
	return false;
}
function deletePost(index, postId, deleteUrl) {
	$('#postControls' + postId).html( $('#postLoadingBar').html() );
	if (arrPosts.length > 1) {
		if (popBoxOpenId == postId) $('#postPopBox' + popBoxOpenId).hide();
		sendPostRequest('delete', index);
	} else {
		location.href = deleteUrl;
	}
	return false;
}
function cancelInlineEdit(postId) {
	editingPostId = false;
	$('#postContainer' + postId).html( originalPostHTML );
	return false;
}
/***** DEBUGGING FUNCT ************/
/*
function updateDebug() {
	var data = '';
	for( i=0;i<arrPosts.length;i++ ) {
		data = data + i + ' => ' + arrPosts[i] + ', ';
	}
	$('#arrPostsDebug').html(data);
	data = '';
	for(key in arrPostsMap) {
		data = data + key + ' => ' + arrPostsMap[key] + ', ';
	}
	$('#arrPostsMapDebug').html(data);
}
*/
/***** END DEBUGGING FUNCT ************/

function sendPostRequest(action, postId, postData) {
	switch (action) {
		case 'add':
		case 'quickReply':
			lastIndex++;
			$.ajax({
				type: 'POST',
				url: urlAddPosts + '&postid=' + postId + '&ajaxreply=' + allowAjaxReply + '&lastindex=' + lastIndex,
				data: postData,
				error: function(a,b,c) { alert('There was an error adding this post:\n' + b); lastIndex--; },
				success: function(msg) {
					if (allowAjaxReply == 1) {
						// hide any other reply pop boxes open & cleanup
						if ( action != 'quickReply' ) {
							$('#postPopBox' + postId).hide();
							popBoxOpenId = false;
							$('#postPopBox' + postId).html('');
						} else {
							$('#replyText').attr('disabled','').val('');
							$('#controls').html( originalPostHTML );
						}
						// append to table
						$('.postRows').append(msg);
						// append to stack
						var newPostId = $('.postId:last').attr('name');
						stackPosition = arrPosts.length;
						arrPosts.push( newPostId );
						arrPostsMap[lastIndex] = stackPosition;
						scrollToElement('[name=' + newPostId + ']');
					} else {
						// redirect
						location.href = msg;
					}
					//updateDebug();
				}
			});
			break;
			
		case 'edit':
			$.ajax({
				type: 'POST',
				url: urlEditPosts + '&postid=' + postId + '&lastindex=' + postData.lastIndex,
				data: postData,
				error: function(a,b,c) {
					alert('There was an error updating this post:\n' + b); 
					$('#postContainer' + postId).html( originalPostHTML );
				},
				success: function(msg) {
					if ( !postData.message ) {
						$('#postContainer' + postId).html( msg );
						scrollToElement('[name=' + postId + ']');
						$('#editPostText' + postId).focus();
					} else {
						$('#postContainer' + postId).html( originalPostHTML );
						$('#postText' + postId).html( msg );
						if ( postData.title ) {
							$('#pageHeader h1').html(postData.title);
							$('#topicTitle').html(postData.title);
						}
						editingPostId = false;
					}
					//updateDebug();
				}
			});
			break;
		
		case 'editTitleOnly':
			$.ajax({
				type: 'POST',
				url: urlEditPosts + '&titleonly=1' + ((postData.threadId) ? '&threadid=' + postData.threadId : '' ),
				data: postData,
				error: function(a,b,c) {
					alert('There was an error updating this thread title:\n' + b); 
				}
			});
			break;
		
		case 'delete':
			$.ajax({
				type: 'POST',
				url: urlEditPosts + '&postid=' + arrPosts[arrPostsMap[postId]] + '&action=delete',
				error: function(a,b,c) { alert('There was an error deleting this post:\n' + b); },
				success: function(msg){	
					// check if this is the last post
					if (arrPostsMap[postId] == arrPosts.length-1) {
						$('#postFoot' + arrPosts[arrPosts.length-2]).fadeOut(200);
						setTimeout( "handleLastPostDelete('#postFoot" + arrPosts[arrPosts.length-2] + "')", 250 );
					} else $('#postFoot' + arrPosts[arrPostsMap[postId]]).fadeOut(200);
					$('#postHead' + arrPosts[arrPostsMap[postId]]).fadeOut(200);
					$('#post' + arrPosts[arrPostsMap[postId]]).fadeOut(200);
					// remove from stack
					arrPosts[arrPostsMap[postId]] = null;
					arrPosts = reindexArray(arrPosts);
					arrPostsMap = reorderPostsMap(arrPostsMap, postId);
					
					//updateDebug();
				} });
			break;
	}
}
// handles AJAX deletion of the last post on the page
function handleLastPostDelete(lastPostFootId) {
	$(lastPostFootId+' td').addClass('lastSeperator');
	$(lastPostFootId).show();
}
// removes a key and reorders the posts map
function reorderPostsMap(object, keyToRemove) {
	var retObject = {};
	var count = 0;
	for (key in object) {
		if ( key != keyToRemove ) {
			retObject[key] = count;
			count++;
		}
	}
	return retObject;
}

/*
function clearDropDown(postId) {
	threadPopBox('#threadPopBox' + postId);
	$('threadPopBox' + postId).html();
}
*/

/* DYNAMIC EFFECTS */
function threadPopBox(el) { // used for reply DELETE!??
	expandCollapseElement(el);
	return false;
}
function expandParentPost(el, parentPostEl) {
	$(el).toggleClass('collapse');
	expandCollapseElement(parentPostEl);
	return false;
}
function expandModTools(el, elFocus) {
	$('.dropDown').each( function() {
		if ($(el).attr('id') != $(this).attr('id') && $(this).css('display') == 'block') {
			$(this).hide();
			return false;
		}
	} );
	expandCollapseElement(el, elFocus);
	return false;
}

/* POST FORMATTING */
function toggleMoreSmileys() {
	if ( $('.smileyHidden').css('display') == 'none' ) {
		$('.smileyHidden').show();
		$('#smileyLabel').html('Show Less');
	} else {
		$('.smileyHidden').hide();
		$('#smileyLabel').html('Show More');
	}
	return false;
}
var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = (userAgent.indexOf('opera') != -1);
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv  = (userAgent.indexOf('webtv') != -1);
var isIE     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var txtAreaID = 'message';

/* BBCode button actions */
function applyTag(openTag, closeTag) {
	var txtArea = document.getElementById(txtAreaID);

	// windows / ie
	if (document.selection) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			alert('Please highlight the text you would like to format, and click this button again.');
			txtArea.focus();
			return false;
		} else {
			opentag = updateOpenTag( openTag );
		}

		document.selection.createRange().text = openTag + theSelection + closeTag;
		txtArea.focus();
		return;
	} else if (txtArea.selectionEnd && (txtArea.selectionEnd - txtArea.selectionStart > 0)) {
		openTag = updateOpenTag( openTag );
		
		mozWrap(txtArea, openTag, closeTag);
		txtArea.focus();
		return;
	} else {
		alert('Please highlight the text you would like to format, and click this button again.');
		txtArea.focus();
		return false;
	}
	storeCaret(txtArea);
}
function updateOpenTag( openTag ) {
	if ( openTag == '[URL]' ) {
		var linkUrl = prompt('Please enter the URL of your link', '');
		if ( linkUrl != '' && linkUrl != null ) {
			openTag = '[URL=' + trim(linkUrl) + ']';
		} else {
			return openTag;
		}
	}
	return openTag;
}
function storeCaret(txtArea) {
	if (txtArea.createTextRange) txtArea.caretPos = document.selection.createRange().duplicate();
}
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;
}
function trim(text) { 
	return text.replace(/^\s+|\s+$/, ''); 
}
/* Smiley button actions */
function getActiveText(){
	var txtArea = document.getElementById(txtAreaID);
	txtArea.focus();
	if ((isIE && !document.selection) || !document.selection) {
		return false;
	}

	var sel = document.selection;
	var rng = sel.createRange();

	if (rng != null && (sel.type == 'Text' || sel.type == 'None')) {
		text = rng.text;
	}
	if (rng != null && txtArea.createTextRange) {
		txtArea.caretPos = rng.duplicate();
	}
	return true;
}
function AddText(NewCode) {
	var txtArea = document.getElementById(txtAreaID);
	if (typeof(txtArea.createTextRange) != 'undefined' && txtArea.caretPos) {
		var caretPos = txtArea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? NewCode + ' ' : NewCode;
		caretPos.select();
	} else if (txtArea.selectionStart || txtArea.selectionStart == '0') {
		// its mozilla and we'll need to re-write entire text
		var start_selection = txtArea.selectionStart;
		var end_selection = txtArea.selectionEnd;

		// fetch everything from start of text area to selection start
		var start = (txtArea.value).substring(0, start_selection);
		// fetch everything from start of selection to end of selection
		var middle = NewCode;
		// fetch everything from end of selection to end of text area
		var end = (txtArea.value).substring(end_selection, txtArea.textLength);

		txtArea.value = start + middle + end;
		txtArea.focus();
		txtArea.selectionStart = end_selection + middle.length;
		txtArea.selectionEnd = start_selection + middle.length;
		getActiveText();
		AddTxt = '';
		return;
	} else {
		txtArea.value += NewCode;
	}
	txtArea.focus();
	getActiveText();
	AddTxt = '';
}
function addSmiley(smiley) {
	getActiveText();
	AddText(' ' + smiley + ' ');
	$('#'+txtAreaID).trigger('keyup');
	return false;
}

/* ADD & REMOVE LATEST GAMES TO TOPICS */
function addRelatedGame(gameRef,title) {
	if ( document.getElementById('item' + gameRef) != null ) {
		return false;
	}
	numSelected++;
	$('#someRelatedGames').css('display','block');
	$('#relatedGames').prepend('<li id="item' + gameRef + '"><input type="hidden" name="gamesSelected[]" value="' + gameRef + '"><strong>' + title + '</strong> &nbsp;(<a href="#" onclick="return removeRelatedGame(' + gameRef + ');" title="Remove ' + title + ' from this topic">remove</a>)</li>');
	return false;
}
function removeRelatedGame(gameRef) {
	$('#item' + gameRef).remove();
	numSelected--;
	var someRelatedGames = ( !numSelected ) ? 'none' : 'block';
	$('#someRelatedGames').css('display',someRelatedGames);
	return false;
}

/* OTHER */
var numSelected = 0;
var hlClass;
function highlightRow(checkbox,rowId) {
	if (checkbox.checked) {
		numSelected++;
		hlClass =  'postRowHl';
	} else {
		if (numSelected > 0) numSelected--;
		hlClass = 'postRow';
	}
	document.getElementById(rowId).className = hlClass;
	document.getElementById('deleteButtonTop').innerHTML = document.getElementById('deleteButtonBottom').innerHTML = 'Delete Selected Posts (' + numSelected + ')';
}
function setFocus(elFocus) {
	document.getElementById(elFocus).focus();
}
function goToCommentForm(sourceEl) {
	$(sourceEl).unbind();
	scrollToElement('[name=postcomment]', false, function() {
		$('#replyText').focus();
		return false;
	});
	return false;
}
function forumSearch() {
	document.searchForum.submit();
	return false;
}
