// Ajax functions
// Author: Erick Hamness

debugMode = true;    

String.prototype.trim = function() {
	return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");
}

// ####################
// Check file links
// ####################
function checkFilePostedIn(FileID)
{
	var elem = document.getElementById("DeletionPostedInConflict" + FileID);

	if(elem.innerHTML != "")
	{
		//We already have the data so just toggle the box
		toggleDiv("DeletionPostedInConflict" + FileID);
	}
	else
	{
		//We don't have the data so we have to make a call to the server to update the html
		blockLoadingBox = true;
		
		//Ajax call to lock / unlock the topic
		CubicSite.AjaxAction.checkFilePostedIn(FileID, checkFilePostedIn_CallBack);
	}
}

function checkFilePostedIn_CallBack(response)
{
	var resultsArray = response.value;

	//Update the attachments area
	var FileID = resultsArray[0];
	var WarningHTML = resultsArray[1];

	if(WarningHTML != null)
	{
		toggleDiv("DeletionPostedInConflict" + FileID);

		var elem = document.getElementById("DeletionPostedInConflict" + FileID);
		elem.innerHTML = WarningHTML;
	}

	blockLoadingBox = false;
}


// ####################
// Rate Posts
// ####################
var RatedPost;
var TypeOfRating;
var PostByUserName;

function ratePost(ForumPostID, RatingType, UsernameOfPoster)
{
	RatedPost = ForumPostID;
	TypeOfRating = RatingType;
	PostByUserName = UsernameOfPoster;

	blockLoadingBox = true;
	
	//Ajax call to lock / unlock the topic
	CubicSite.AjaxAction.ratePost(ForumPostID, RatingType, ratePost_CallBack);
}

function ratePost_CallBack(response)
{
	if(response.error)
	{
		alert(response.error.Message);
		alert("Error rating post!");
	} 
	else
	{
		var newRating = response.value;

		//Grab the HTML for the rating icons
		var rateButtons = document.getElementById("ratingButtons" + RatedPost);

		//Grab the HTML for the rating message area
		var ratingMessage = document.getElementById("RatingMessage" + RatedPost);

		//Grab the HTML for the current rating
	    var ratingForPost = document.getElementById("RatingForPost" + RatedPost);		

		if(newRating == "-")
		{
			alert("You are not allowed to rate posts.");
		}
		else
		{
			ratingForPost.innerHTML = newRating;

			if(TypeOfRating == 'good')
			{
				if(newRating > 0)
				{
					ratingForPost.innerHTML = "+" + ratingForPost.innerHTML;
				}
			} 
			else if(TypeOfRating == 'bad')
			{

				var ratingHTML = "You gave <a href=\"javascript:toggleDiv('PostRatingPost" + RatedPost + "');\">this post</a> a negative rating for a total rating of " + newRating + ". ";
				ratingHTML += "<a href=\"javascript:reportPost('" + RatedPost + "');\"> Was " + PostByUserName + " being offensive?</a>";

				ratingMessage.innerHTML = ratingHTML;
				//Toggle the rating message div
				toggleDiv("RatingMessage" + RatedPost);

				toggleDiv("PostRatingPost" + RatedPost);
			}

			//Toggle the thumbs up / down
			toggleDiv("ratingButtons" + RatedPost);
		}
	}
	blockLoadingBox = false;
}



// ####################
// Lock / Unlock Topics
// ####################

function lockUnlockTopic(ForumTopicID, dowhat, oldicon)
{
	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("TopicStatusIcon" + ForumTopicID);
	var newHTML = "";

	if(dowhat == 'locktopic')
	{
		//Modify the HTML for the new button
		newHTML = elem.innerHTML.replace("/" + oldicon, "/icon_locked.gif");
		newHTML = newHTML.replace("locktopic", "unlocktopic");
	} 
	else if(dowhat == 'unlocktopic')
	{
		//Modify the HTML for the new button
		newHTML = elem.innerHTML.replace("/icon_locked.gif", "/" + oldicon);
		newHTML = newHTML.replace("unlocktopic", "locktopic");
	}

	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
	
	blockLoadingBox = true;
	
	//Ajax call to lock / unlock the topic
	CubicSite.AjaxAction.lockUnlockTopic(ForumTopicID, dowhat, lockUnlockTopic_CallBack);
}

function lockUnlockTopic_CallBack(response)
{
	if(response.error || response.value == false)
	{
		alert("Error locking / unlocking post!");
	} 
	blockLoadingBox = false;
}


// ####################
// Email A User
// ####################
var MessageBeingReported;

function reportPost(ForumPostID)
{
	MessageBeingReported = ForumPostID;

	//Ajax call. Send the username to create the form
	CubicSite.AjaxAction.createReportPostForm(ForumPostID, reportPost_callback);
}

function reportPost_callback(Response) 
{ 
	//Get the file object that was returned from the server
	var previewHTML = Response.value;

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");
	elem.innerHTML = Response.value;

	openPageAnnounceBox(600, 450, true);
}

function sendReport()
{
	var Message = document.getElementById("ReportMessage");

	//Ajax call. Send the username to create the form
	CubicSite.AjaxAction.sendReport(Message.value, MessageBeingReported, sendReport_callback);
}

function sendReport_callback(Response) 
{ 
	if(Response.error != null)
	{
		alert(Response.error.Message);
	}

	//Get the file object that was returned from the server
	var previewHTML = Response.value;

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");
	elem.innerHTML = Response.value;
}



// ####################
// Email A User
// ####################

function emailUser(username)
{
	//Ajax call. Send the username to create the form
	CubicSite.AjaxAction.createEmailForm(username, emailUser_callback);
}

function emailUser_callback(Response) 
{ 
	if(Response.value == "blocked")
	{
		alert("This user has added you to their block list. You are unable to email them");
		return;
	}

	//Get the file object that was returned from the server
	var previewHTML = Response.value;

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");
	elem.innerHTML = Response.value;

	openPageAnnounceBox(600, 450, true);
}

function sendMessage()
{
	var sendToName = document.getElementById("SendToName");
	var emailMessage = document.getElementById("EmailMessage");

	//Ajax call. Send the username to create the form
	CubicSite.AjaxAction.sendEmail(sendToName.value, emailMessage.value, sendMessage_callback);
}

function sendMessage_callback(Response) 
{ 
	if(Response.error != null)
	{
		alert(Response.error.Message);
	}

	//Get the file object that was returned from the server
	var previewHTML = Response.value;

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");
	elem.innerHTML = Response.value;
}

// ####################
// Add a topic bookmark
// ####################

function addRemoveBookmark(ForumTopicID, SiteUserID, dowhat)
{
	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("Bookmark");
	var newHTML = null;

	if(dowhat == 'addbookmark')
	{
		addBookmark(ForumTopicID, SiteUserID);

		//Modify the HTML for the new button
		newHTML = elem.innerHTML.replace("icon_add_bookmark.gif", "icon_remove_bookmark.gif");
		newHTML = newHTML.replace("addbookmark", "removebookmark");
	} 
	else if(dowhat == 'removebookmark')
	{
		removeBookmark(ForumTopicID, SiteUserID);

		//Modify the HTML for the new button
		newHTML = elem.innerHTML.replace("icon_remove_bookmark.gif", "icon_add_bookmark.gif");
		newHTML = newHTML.replace("removebookmark", "addbookmark");
	}

	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

function addBookmark(ForumTopicID, SiteUserID)
{
    topic.addBookmark(ForumTopicID, SiteUserID, addBookmark_CallBack);
}

function addBookmark_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to add bookmark! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}  

function removeBookmark(ForumTopicID, SiteUserID)
{
    topic.removeBookmark(ForumTopicID, SiteUserID, removeBookmark_CallBack);
}

//Used in the user control panel
function removeBookmarkFromList(ForumTopicID, SiteUserID)
{
    members_Default.removeBookmark(ForumTopicID, SiteUserID, removeBookmark_CallBack);
	Effect.DropOut("BookmarkForTopic" + ForumTopicID);
}

function removeBookmark_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to remove bookmark! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}   

// ####################
// Add a subscription
// ####################

function addRemoveSubscription(ForumTopicID, SiteUserID, dowhat)
{
	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("Subscription");
	var newHTML = null;

	//alert(elem.innerHTML);

	if(dowhat == 'addsubscription')
	{
		addSubscription(ForumTopicID, SiteUserID);

		//Modify the HTML for the new button
		newHTML = elem.innerHTML.replace("icon_add_subscription.gif", "icon_remove_subscription.gif");
		newHTML = newHTML.replace("addsubscription", "removesubscription");
	} 
	else if(dowhat == 'removesubscription')
	{
		removeSubscription(ForumTopicID, SiteUserID);

		//Modify the HTML for the new button
		newHTML = elem.innerHTML.replace("icon_remove_subscription.gif", "icon_add_subscription.gif");
		newHTML = newHTML.replace("removesubscription", "addsubscription");
	}

	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

function addSubscription(ForumTopicID, SiteUserID)
{
    topic.addSubscription(ForumTopicID, SiteUserID, addSubscription_CallBack);
}

function addSubscription_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to add subscription! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}  

function removeSubscription(ForumTopicID, SiteUserID)
{
    topic.removeSubscription(ForumTopicID, SiteUserID, removeSubscription_CallBack);
}

//Used in the user control panel
function removeSubscriptionFromList(SubscriptionID)
{
    members_Default.removeSubscription(SubscriptionID, removeSubscription_CallBack);
	Effect.DropOut("Subscription" + SubscriptionID);
}

function removeSubscription_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to remove subscription! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}  

// ####################
// Create Poll Question
// ####################


function pollAddVote(ChoiceID, QuestionID)
{
	//Server Side AJAX Call to update the database and get back the poll stats
    var updatedHTML = topic.createPollVote(QuestionID, ChoiceID).value; 

	//Swap out the polling area for the updated poll stats
	swapText("question" + QuestionID + "choices", updatedHTML, 'green');

	new Effect.Highlight("question" + QuestionID + "choices", {startcolor:'#FFFFFF', endcolor:'#D3D3D3'});
}

//Ajax Function
function createPollVote(QuestionID, ChoiceID)
{

}

//Ajax Function
function createPollVote_CallBack(response)
{
    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
} 

function toggleLayerWithLabel(dividToToggle, LabelToChange, OpenIcon, OpenText, CloseIcon, CloseText, arrowPosition)
{
	toggleDiv(dividToToggle);
	
	//This is the label we are changing
	var Label = document.getElementById(LabelToChange);

	//This is the div we are toggling
	var Div = document.getElementById(dividToToggle);
	var arrow = "";

	if(Div.style.display != "none")
	{
		if(CloseIcon != "")
		{
			arrow = "<img src=\"" + CloseIcon + "\" />";
		}

		if(arrowPosition == 'left')
		{
			Label.innerHTML = arrow + "&nbsp;" + CloseText;
		}
		else if(arrowPosition == 'right')
		{
			Label.innerHTML = CloseText + "&nbsp;" + arrow;
		}
	}
	else
	{
		if(OpenIcon != "")
		{
			arrow = "<img src=\"" + OpenIcon + "\" />";
		}

		if(arrowPosition == 'left')
		{
			Label.innerHTML = arrow + "&nbsp;" + OpenText;
		}
		else if(arrowPosition == 'right')
		{
			Label.innerHTML = OpenText + "&nbsp;" + arrow;
		}
	}
}

function newPoll(polltitle)
{
	if(polltitle.value == "")
	{
		return;
	}

	//Use AJAX to create the poll
	createPoll(polltitle.value);

	var newQuestion = "";
	
	newQuestion += "<div id=\"PollQuestions\"></div>";
	newQuestion += "-- <input id=\"newquestion\" type=\"text\" name=\"newquestion\" />&nbsp;<input type=\"button\" name=\"createQuestion\" title=\"Create Question\" value=\"Create Question\" onclick=\"addNewPollQuestion(newquestion, 'add');\" />";

	var pollRemovalButton = "<img class=\"MousePoint\" src=\"http://images.snowmobilefanatics.com/siteicons/default/icon_remove.gif\" onclick=\"removePoll();\">";

	swapText("EntirePoll", "<strong>Poll Title: " + polltitle.value + "</strong> " + pollRemovalButton + "<br /><br />" + newQuestion, 'green');
}


//Ajax Function
function createPoll(title)
{
    topic.createPoll(title, updatePollArea_CallBack);
}

//Ajax Function
function createPoll_CallBack(response)
{
    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
} 

function removePoll()
{
	//Use AJAX to clear the session data
	deletePoll();
	//HTML for the new poll button so we can put it back
	var addPoll = "Poll Title: <input id=\"NewPollTitle\" type=\"text\" />&nbsp;<input type=\"button\" name=\"createQuestion\" title=\"Create Poll\" value=\"Create Poll\" onclick=\"newPoll(NewPollTitle);\" />";
	//Swap the old poll HTML out for the new Poll form and button
	swapText("EntirePoll", addPoll, 'red');
}

//Ajax Function
function deletePoll()
{
    topic.deletePoll(updatePollArea_CallBack);
}

//Ajax Function
function deletePoll_CallBack(response)
{
    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
} 


//Ajax Function
function updatePollArea()
{
    topic.getPollData(updatePollArea_CallBack);
}

//Ajax Function
function updatePollArea_CallBack(response)
{
	if(response.value != "")
	{
		swapText("PollTestArea", response.value, 'green');
	}
	else
	{
		swapText("PollTestArea","Current Poll Data", 'green');
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}  

function addNewPollQuestion(question, dowhat)
{
	if(question.value == "")
	{
		return;
	}
	//Create random number for the new label
	var randomnumber = Math.floor(Math.random() * 100000);

	//Collect all the old HTML
	var PollQuestionsData = document.getElementById("PollQuestions").innerHTML;

	var newRemovalButtonText = "<img class=\"MousePoint\" src=\"http://images.snowmobilefanatics.com/siteicons/default/icon_remove.gif\" onclick=\"removePollQuestion('" + randomnumber + "');\">";

	var newPollChoice = "---- <input type=\"text\" id=\"newchoice" + randomnumber + "\" />&nbsp;<input type=\"button\" value=\"Create Choice\" onclick=\"addPollChoice(newchoice" + randomnumber + ", 'question" + randomnumber + "');\">";

	//Use ajax to update the poll
	createPollQuestion(question.value, "question" + randomnumber);

	//use swaptext function to insert the old poll questions plus the new question
	swapText("PollQuestions", PollQuestionsData + "<span id=\"question" + randomnumber + "\">-- " + question.value + "  " + newRemovalButtonText + "<br /></span><span id=\"newchoicespan" + randomnumber + "\">" + newPollChoice + "<br /><br /></span>", 'green');

	//Set the question value back to nothing
	question.value = "";

}

//Ajax Function
function createPollQuestion(question, tempid)
{
    topic.createPollQuestion(question, tempid, createPollQuestion_CallBack);
}

//Ajax Function
function createPollQuestion_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to add the poll question! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}  

function removePollQuestion(QuestionIDNumber)
{
	//TODO: Use fancy transition here



	var questionidtext = "question" + QuestionIDNumber;

	//Use AJAX to remove the question from the session
	deletePollQuestion(questionidtext);

	//remove the new choice button
	theQuestionNewChoice = document.getElementById("newchoicespan" + QuestionIDNumber);
    theQuestionNewChoice.innerHTML = "";

	//remove the question
	theQuestionData = document.getElementById("question" + QuestionIDNumber);
    theQuestionData.innerHTML = "";


}

//Ajax Function
function deletePollQuestion(questionID)
{
    topic.deletePollQuestion(questionID, deletePollQuestion_CallBack);
}

//Ajax Function
function deletePollQuestion_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to remove the poll question! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
} 

function addPollChoice(choice, questionID)
{
	if(choice.value == "")
	{
		return;
	}

	//alert("add " + choice.value + " for " + questionID);

	//Create random number for the new label
	var randomnumber = Math.floor(Math.random() * 100000);

	//Collect all the old HTML
	var QuestionData = document.getElementById(questionID).innerHTML;
	var newRemovalButtonText = "<img class=\"MousePoint\" src=\"http://images.snowmobilefanatics.com/siteicons/default/icon_remove.gif\" onclick=\"removePollChoice('choice" + randomnumber + "', '" + questionID + "');\">";

	//Use AJAX to add question to session
	createPollChoice(questionID, choice.value, "choice" + randomnumber);

	//use swaptext function to insert the old poll questions plus the new question
	swapText(questionID, QuestionData + "<span id=\"choice" + randomnumber + "\">---- " + choice.value + "  " + newRemovalButtonText + "<br /></span>", 'green');

	//Set the new poll choice back to nothing
	choice.value = "";
}

//Ajax Function
function createPollChoice(questiontempid, choicetext, choicetempid)
{
    topic.createPollChoice(questiontempid, choicetext, choicetempid, createPollChoice_CallBack);
}

//Ajax Function
function createPollChoice_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to add the poll choice! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
} 


function removePollChoice(choiceID, questionID)
{
	//alert("questionID: " + questionID + " choiceID: " + choiceID);

	//remove the choice
	theChoice = document.getElementById(choiceID);
    theChoice.innerHTML = "";

	//Use AJAX to delete the choice from the question in the session
	deletePollChoice(questionID, choiceID);
}


//Ajax Function
function deletePollChoice(questionID, choiceID)
{
    topic.deletePollChoice(questionID, choiceID, createPollChoice_CallBack);
}

//Ajax Function
function deletePollChoice_CallBack(response)
{
	if(response.value == "false")
	{
		alert("Unable to remove the poll choice! Please notify an administrator.");
	}

    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
} 

// ####################
// Private Messages
// ####################

function removePM(MessageID)
{
	//Delete the PM from the database
	if(members_messages.deleteMessage(MessageID).value == false)
	{
		alert("There was a problem deleting the message! Please try again.");
	}
	else
	{
		//Disable use of preview pane
		var usePreviewPane = false;

		//If this message was selected and we are using the previewPane, clear the preview pane
		if(usePreviewPane)
		{
			var SelectedMessage = Get_Cookie("SelectedMessage")
			
			if(SelectedMessage != "" && SelectedMessage != null && SelectedMessage == MessageID)
			{
				var PreviewPane = document.getElementById("PMPreviewPane");
				PreviewPane.innerHTML = "<div style=\"text-align:center; width:100%;\">No messages are currently selected</div>";
			}
		}

		//Remove the PM from the select list if it is selected.
		removeModPM(MessageID);

		//Remove the message from the display list
		Effect.DropOut("Message" + MessageID);
	}

}

function movePMDrag(MessageIDString, DirectoryIDString)
{
	//Trim off the Message and Directory in the strings
	MessageID = MessageIDString.replace("Message", "");
	DirectoryID = DirectoryIDString.replace("Directory", "");

	//Ajax call to move message on server side
	if(members_messages.moveMessage(MessageID, DirectoryID).value == false)
	{
		alert("Unable to move the selected message!");
	}
	else
	{
		//Hide the message
		Element.hide(MessageIDString);
	}
}

function moveSelectedPrivateMessages(DirectoryToMoveTo)
{
	var modPMList = members_messages.moveSelectedMessages(DirectoryToMoveTo).value;

	//Split the returned messageID string into an array
	var MessageIDNumbers = modPMList.split(",");

	//Loop through the array and hide moved messages
	for(i=0; i < MessageIDNumbers.length; i++)
	{
		Element.hide("Message" + MessageIDNumbers[i]);
	}

	//Update selected message count
    var selectedItems = document.getElementById("TotalItemsSelected");
	selectedItems.innerHTML = 0;
}

function addPMDirectory(newDirectoryName)
{
	if(newDirectoryName != "")
	{
		//Ajax call to add directory and get the new directory listing HTML
		var directoryListingHTML = members_messages.createDirectory(newDirectoryName).value;


		//alert(directoryListingHTML);

		//For some reason the following will not work so we much refresh the page instead!
		swapText("AllDirectoriesListing", directoryListingHTML, "green");
		
		//window.location.reload( true );
	}
}

function removePMDirectory(DirectoryIDString)
{
	//Make sure the user really wants to delete this directory
	var confirmdelete= confirm("Are you sure you want to delete this directory? All messages will be moved to the inbox.");

	if (confirmdelete == true)
	{
		//Trim off the Directory in the string
		DirectoryID = DirectoryIDString.replace("Directory", "");

		//Ajax call to add directory and get the new directory listing HTML
		
		var directoryListingHTML = members_messages.deleteDirectory(DirectoryID).value;

		
		//For some reason the following will not work so we much refresh the page instead!
		swapText("AllDirectoriesListing", directoryListingHTML, "green");
		//window.location.reload( true );
	}
}

//Ajax Function
function general_CallBack(response)
{
    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }

	if(blockLoadingBox == true)
	{
		blockLoadingBox = false;
	}
} 

function toggleMakeNewPMDirectory(divid)
{
	toggleDiv(divid)
	var PMNewDirectoryLabel = document.getElementById("OpenCloseNewPMDirectory");
    elem = document.getElementById("OpenCloseNewPMDirectory");

	if(PMNewDirectoryLabel.innerHTML == "Add Directory")
	{
		elem.innerHTML = "Close";
	}
	else
	{
		elem.innerHTML = "Add Directory";
	}
}

function addModPM(PMID)
{
	//Un-highlight any message that the user is currently viewing
	var SelectedMessage = Get_Cookie("SelectedMessage")
	
	//Ajax call to add a PostID to the list
	var PMsToModCount = CubicSite.AjaxAction.addModPM(PMID).value;

	//Grab the HTML from the TotalItemsSelected label
    var selectedItems = document.getElementById("TotalItemsSelected");
	selectedItems.innerHTML = PMsToModCount;

	//Grab the HTML from the postMod label
    var elem = document.getElementById("ModPM" + PMID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_item_unselected.gif", "icon_item_selected.gif");
	newHTML = newHTML.replace("addModPM", "removeModPM");
	
	//Change the style of the PM Message to reflect it being selected if it currently NOT being displayed in the preview pane.
	if (PMID != SelectedMessage)
	{
		var MessageDiv = document.getElementById("Message" + PMID);
		MessageDiv.className = "PMMessageSelectedForMod";
	}
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

function removeModPM(PMID)
{
	//Ajax call to remove PostID from the list
	var PMsToModCount = CubicSite.AjaxAction.removeModPM(PMID).value;

	//Grab the HTML from the TotalItemsSelected label
    var selectedItems = document.getElementById("TotalItemsSelected");
	selectedItems.innerHTML = PMsToModCount;

	//Grab the HTML from the postMod label
    var elem = document.getElementById("ModPM" + PMID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_item_selected.gif", "icon_item_unselected.gif");
	newHTML = newHTML.replace("removeModPM", "addModPM");
	

	//Un-highlight any message that the user is currently viewing
	var SelectedMessage = Get_Cookie("SelectedMessage")
	
	//alert(SelectedMessage + "-->" + PMID);
	if(SelectedMessage != PMID)
	{
		//Change the style of the PM Message to reflect it being unselected
		var MessageDiv = document.getElementById("Message" + PMID);
		
		var MessageRead = document.getElementById("MessageRead" + PMID).value;

		//Depending on if the message was read or unread will determine which style it gets changed back to.
		if(MessageRead == "True")
		{
			//The message had been read
			MessageDiv.className = "PMMessage";
		}
		else 
		{
			//The message has not been read
			MessageDiv.className = "PMMessageUnread";
		}
	}

	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

// ####################
// PM Message Preview
// ####################

function loadPMPreview(MessageID)
{
	//Check to see if there was a previously selected message
	var SelectedMessage = Get_Cookie("SelectedMessage")

	//alert("Value in cookie: " + SelectedMessage);

	if(SelectedMessage != "" && SelectedMessage != MessageID && SelectedMessage != null)
	{
		//alert("Loaded for mod?" + CubicSite.AjaxAction.modPMExists(SelectedMessage).value);
		var OldMessageDiv = document.getElementById("Message" + SelectedMessage);

		if(OldMessageDiv != "" && OldMessageDiv != null)
		{
			if(CubicSite.AjaxAction.modPMExists(SelectedMessage).value == false)
			{
				OldMessageDiv.className = "PMMessage";
			}
			else
			{
				OldMessageDiv.className = "PMMessageSelectedForMod";
			}
		}
	}

	//Set the message we just loaded and highlighted so we can use it to un-highlight it in the future
	document.cookie = "SelectedMessage=" + MessageID;

	var MessageDiv = document.getElementById("Message" + MessageID);
	MessageDiv.className = "PMMessageSelected";

	//Ajax call to get the private message contents
	 //var pmPreviewText = CubicSite.AjaxAction.loadPMPreview(MessageID).value;

	//Ajax Call
	pmPreview(MessageID);
}

function pmPreview(MessageID)
{
	CubicSite.AjaxAction.loadPMPreview(MessageID, pmPreview_callback);
}

function pmPreview_callback(Response) {
	//Swap out the text in the preview pane
	var PreviewPane = document.getElementById("PMPreviewPane");

	PreviewPane.innerHTML = Response.value;
}

function pmLoadingMessage()
{
	var PreviewPane = document.getElementById("PMPreviewPane");
	PreviewPane.innerHTML = "Loading...";

	return true;
}

function setPMPreviewHeight()
{
	var PreviewPane = document.getElementById("PMPreviewPane");
	var MessageList = document.getElementById("PMMessageList");
	var FolderList  = document.getElementById("PMFolderList");
	
	var height = parseInt(document.documentElement.clientHeight) - 400;

	PreviewPane.style.height = height + 'px';
	MessageList.style.height = height + 'px';
	FolderList.style.height = height + 'px';
}

function setH()
{
  if (document.documentElement && document.documentElement.clientHeight)
	 H=document.documentElement.clientHeight;
  else
	 H=document.body.clientHeight;
  obj=document.getElementById('thetable')
  tabH=Math.max(obj.offsetHeight,H)-obj.offsetTop-15;
  document.getElementById('thecell').style.height=tabH+'px';
}



// ####################
// Add / Remove Friends
// ####################

function addFriend(FriendID)
{
	//Ajax call to add a new friend
	CubicSite.AjaxAction.createFriend(FriendID, general_CallBack);

	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("AddRemoveFriend");

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_add_friend.gif", "icon_remove_friend.gif");
	newHTML = newHTML.replace("addFriend", "removeFriend");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;


	//Grab the HTML from the AddRemove Enemy label so that we can change it incase they already had this person as an enemy
    var elem2 = document.getElementById("AddRemoveEnemy");

	//Modify the HTML for the new button
	newHTML = elem2.innerHTML.replace("icon_remove_enemy.gif", "icon_add_enemy.gif");
	newHTML = newHTML.replace("removeEnemy", "addEnemy");
	
	//Replace the button HTML with the modified HTML
	elem2.innerHTML = newHTML;
}

function removeFriend(FriendID)
{
	//Ajax call to remove a friend
	CubicSite.AjaxAction.deleteFriend(FriendID, general_CallBack);

	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("AddRemoveFriend");

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_remove_friend.gif", "icon_add_friend.gif");
	newHTML = newHTML.replace("removeFriend", "addFriend");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}


function removeFriendFromList(FriendID)
{
    //Ajax call to remove a friend
	CubicSite.AjaxAction.deleteFriend(FriendID, general_CallBack);
	
	Effect.DropOut("Friend" + FriendID);
}

// ####################
// Add / Remove Enemies
// ####################

function addEnemy(EnemyID)
{
	//Ajax call to add a new enemy
	CubicSite.AjaxAction.createEnemy(EnemyID, general_CallBack);

	//Grab the HTML from the AddRemove enemy label
    var elem = document.getElementById("AddRemoveEnemy");

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_add_enemy.gif", "icon_remove_enemy.gif");
	newHTML = newHTML.replace("addEnemy", "removeEnemy");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;


	//Grab the HTML from the AddRemove Friend label so that we can change it incase they already had this person as a friend
    var elem2 = document.getElementById("AddRemoveFriend");

	//Modify the HTML for the new button
	newHTML = elem2.innerHTML.replace("icon_remove_friend.gif", "icon_add_friend.gif");
	newHTML = newHTML.replace("removeFriend", "addFriend");

	//Replace the button HTML with the modified HTML
	elem2.innerHTML = newHTML;

}

function removeEnemy(EnemyID)
{
	//Ajax call to remove an enemy
	CubicSite.AjaxAction.deleteEnemy(EnemyID, general_CallBack);

	//Grab the HTML from the AddRemove enemy label
    var elem = document.getElementById("AddRemoveEnemy");

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_remove_enemy.gif", "icon_add_enemy.gif");
	newHTML = newHTML.replace("removeEnemy", "addEnemy");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

function removeEnemyFromList(EnemyID)
{
    //Ajax call to remove an enemy
	CubicSite.AjaxAction.deleteEnemy(EnemyID, general_CallBack);
	
	Effect.DropOut("Enemy" + EnemyID);
}



// ####################
// Add / Remove Quote
// ####################

function addQuote(PostID)
{
	//Ajax call to add a PostID to the list
	CubicSite.AjaxAction.addQuote(PostID, general_CallBack);

	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("MultiQuote" + PostID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_add_quote.gif", "icon_remove_quote.gif");
	newHTML = newHTML.replace("addQuote", "removeQuote");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

function removeQuote(PostID)
{
	//Ajax call to remove PostID from the list
	CubicSite.AjaxAction.removeQuote(PostID, general_CallBack);

	//Grab the HTML from the AddRemove Friend label
    var elem = document.getElementById("MultiQuote" + PostID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_remove_quote.gif", "icon_add_quote.gif");
	newHTML = newHTML.replace("removeQuote", "addQuote");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;
}

// #################################
// Add / Remove Posts For Moderation
// #################################

function addModPost(PostID)
{
	//Grab the HTML from the postMod label
    var elem = document.getElementById("ModPost" + PostID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_item_unselected.gif", "icon_item_selected.gif");
	newHTML = newHTML.replace("addModPost", "removeModPost");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;

	blockLoadingBox = true;

	//Ajax call to add a PostID to the list
	CubicSite.AjaxAction.addModPost(PostID, addModPost_CallBack);
}

function addModPost_CallBack(response)
{
	if(response.error)
	{
		alert("Error selecting post!");
	} 
	else
	{
		var PostsToModCount = response.value;

		//Grab the HTML from the TotalItemsSelected label
		var selectedItems = document.getElementById("TotalItemsSelected");
		selectedItems.innerHTML = PostsToModCount;
	}

	blockLoadingBox = false;
}

function removeModPost(PostID)
{
	//Grab the HTML from the postMod label
    var elem = document.getElementById("ModPost" + PostID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_item_selected.gif", "icon_item_unselected.gif");
	newHTML = newHTML.replace("removeModPost", "addModPost");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;

	blockLoadingBox = true;

	//Ajax call to remove PostID from the list
	CubicSite.AjaxAction.removeModPost(PostID, removeModPost_CallBack);
}

function removeModPost_CallBack(response)
{
	if(response.error)
	{
		alert("Error unselecting post!");
	} 
	else
	{
		var PostsToModCount = response.value;

		//Grab the HTML from the TotalItemsSelected label
		var selectedItems = document.getElementById("TotalItemsSelected");
		selectedItems.innerHTML = PostsToModCount;
	}

	blockLoadingBox = false;
}

// ##################################
// Add / Remove Topics For Moderation
// ##################################

function addModTopic(TopicID)
{
	//Grab the HTML from the postMod label
    var elem = document.getElementById("ModTopic" + TopicID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_item_unselected.gif", "icon_item_selected.gif");
	newHTML = newHTML.replace("addModTopic", "removeModTopic");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;

	blockLoadingBox = true;

	//Ajax call to add a PostID to the list
	CubicSite.AjaxAction.addModTopic(TopicID, addModTopic_CallBack);
}

function addModTopic_CallBack(response)
{
	if(response.error)
	{
		alert("Error selecting topic!");
	} 
	else
	{
		var TopicsToModCount = response.value;

		//Grab the HTML from the TotalItemsSelected label
		var selectedItems = document.getElementById("TotalItemsSelected");
		selectedItems.innerHTML = TopicsToModCount;
	}

	blockLoadingBox = false;
}

function removeModTopic(TopicID)
{
	//Grab the HTML from the postMod label
    var elem = document.getElementById("ModTopic" + TopicID);

	//Modify the HTML for the new button
	newHTML = elem.innerHTML.replace("icon_item_selected.gif", "icon_item_unselected.gif");
	newHTML = newHTML.replace("removeModTopic", "addModTopic");
	
	//Replace the button HTML with the modified HTML
	elem.innerHTML = newHTML;

	blockLoadingBox = true;

	//Ajax call to remove PostID from the list
	CubicSite.AjaxAction.removeModTopic(TopicID, removeModTopic_CallBack);
}

function removeModTopic_CallBack(response)
{
	if(response.error)
	{
		alert("Error unselecting topic!");
	} 
	else
	{
		var TopicsToModCount = response.value;

		//Grab the HTML from the TotalItemsSelected label
		var selectedItems = document.getElementById("TotalItemsSelected");
		selectedItems.innerHTML = TopicsToModCount;
	}

	blockLoadingBox = false;
}

// #####################
// Change Avatar Preview
// #####################

function changeAvatarPreview(AvatarID)
{
	currentlyAdjustingAvatarID = AvatarID;
	var avatarObject = new Object();

	avatarObject = CubicSite.AjaxAction.getAvatarDetails(AvatarID).value;
	
	//Grab the HTML from the editAvatarDisplay label
    var elem = document.getElementById("editAvatarDisplay");

	var AvatarURL = "";

	if(AvatarID == 0)
	{
		AvatarURL = avatarObject.UnknownURL;
	}
	else
	{
		AvatarURL = avatarObject.FullURL;
	}

	//Modify the HTML for the new image
	var newHTML = "<img src=\"" + AvatarURL + "\">";
	
	//Replace the old HTML with the modified HTML
	elem.innerHTML = newHTML;

	//Toggle and/or change the thumbnail display
	if(AvatarID == 0)
	{
		document.getElementById("AvatarThumbnailArea").style.display = "none";
	}
	else
	{
		document.getElementById("editAvatarThumbnailDisplay").innerHTML = "<img border=\"0\" src=\"" + avatarObject.ResizedProportionateURL + "\">";
		document.getElementById("AvatarThumbnailArea").style.display = "block";
	}
}

// ####################
// Scan For Attachments
// ####################

var currentAttachments = "";
var timeCounter = 0;
var allowAttachmentCheck = true;
var blockLoadingBox = false;

function blockChecking()
{
	allowAttachmentCheck = false;
	//Reset the counter to 0!
	timeCounter = 0;
}

function startCheckTimer()
{
	if(timeCounter == 10)
	{
		//Allow the form to be checked for attachments after 10 seconds of no typing
		allowAttachmentCheck = true;
	}
	timeCounter++;
	
	//document.getElementById("attachments").innerHTML = timeCounter;
	setTimeout("startCheckTimer()",1000)
}

function startScanTimer(EditorID)
{
	scanForAttachments(EditorID, true);
	setTimeout("startScanTimer('" + EditorID + "')",5000)
}


function scanForAttachmentsAfterInsert(EditorID)
{
	allowAttachmentCheck = true;
	scanForAttachments(EditorID, false);
	blockChecking();
}

function startForumDraftSaver(ForumForumID, ForumTopicID, TitleFormID, DesriptionFormID, PostFormID)
{
	//Check and save the topic/post if we need to
	saveDraft(ForumForumID, ForumTopicID, TitleFormID, DesriptionFormID, PostFormID, true);

	//Run every 2 minutes
	setTimeout("startForumDraftSaver('" + ForumForumID + "','" + ForumTopicID + "','" + TitleFormID + "','" + DesriptionFormID + "','" + PostFormID + "')",120000)
}

function preScanForAttachmentTags(EditorID)
{
	var elem = document.getElementById(EditorID);

	if(elem.value == "")
	{
		return true;
	}

	attachRegEx = /\[attach=\d*\]/;
	attachmentRegEx = /\[attachment=\d*\]/;
	galleryattachRegEx = /\[galleryattach=\d*\]/;
	
	if(elem.value.match(attachRegEx))
	{
		//There is a tag here
		return true;
	}

	if(elem.value.match(attachmentRegEx))
	{
		//There is a tag here
		return true;
	}

	if(elem.value.match(galleryattachRegEx))
	{
		//There is a tag here
		return true;
	}

	return false;
}

function scanForAttachments(EditorID, Auto)
{
	//See if the text contains any attachments at all, if not, don't bother continuing
	if(!preScanForAttachmentTags(EditorID))
	{
		return;
	}

	//Grab the current editor
    var elem = document.getElementById(EditorID);
	var previousMessage = document.getElementById("previousMessageText");

	if(allowAttachmentCheck == true)
	{
		if(previousMessage.value.trim() != elem.value.trim())
		{
			//Save the value of the current attachments so we don't lose what was changed in title and description
			updateAttachmentDetails();

			//Set the value of the previous message for future checking
			previousMessage.value = elem.value;
			
			if(Auto == true)
			{
				blockLoadingBox = true;
			}

			//Ajax call to find the attachments in the text
			CubicSite.AjaxAction.scanForAttachments(elem.value, scanForAttachments_callback);
			//document.getElementById("attachments").innerHTML = CubicSite.AjaxAction.scanForAttachments(elem.value).value;
		}
	}
}

function scanForAttachments_callback(Response)
{ 
	blockLoadingBox = false;

	var resultsArray = Response.value;

	//Update the attachments area
	var attachmentsHTML = resultsArray[0];
	currentAttachments = resultsArray[1];

	if(attachmentsHTML.length == 0)
	{
		//If no HTML was returned and attachmentcount > 0 that means there are attachments but they are not new ones
		//so the HTML doesn't need updating since last time
		if(currentAttachments.length == 0)
		{
			//There are no attachments in this post, clear the HTML
			document.getElementById("attachments").innerHTML = "There are currently no attachments.";
		}
	}
	else
	{
		document.getElementById("attachments").innerHTML = attachmentsHTML;
	}
}

function updateAttachmentDetails()
{
	if(currentAttachments.length > 1)
	{
		var currentAttachmentsArray = currentAttachments.split(",");

		var ds = new Ajax.Web.DataSet();
		var dt = new Ajax.Web.DataTable();
		dt.addColumn("FileID", "System.Int32");
		dt.addColumn("Title", "System.String");
		dt.addColumn("Description", "System.String");

		var allowDatabaseUpdate = false;

		//Loop through the array to create an array of arrays
		for(i=0; i < currentAttachmentsArray.length; i++)
		{
			if(document.getElementById("attachedFileTitle" + currentAttachmentsArray[i]) != null)
			{
				var fileID = currentAttachmentsArray[i];
				var title = document.getElementById("attachedFileTitle" + currentAttachmentsArray[i]).value;
				var description = document.getElementById("attachedFileDescription"+currentAttachmentsArray[i]).value;

				var row = new Object();
				row.FileID = fileID;
				row.Title = title;
				row.Description = description;

				dt.addRow(row);

				//There is at least one item we can update in the database
				allowDatabaseUpdate = true;
			}
		}

		if(allowDatabaseUpdate)
		{
			//Add the datatable to the dataset
			ds.addTable(dt);
				
			//Ajax call to update the files in the dataset
			CubicSite.AjaxAction.updateAttachmentDetails(ds, updateAttachmentDetails_CallBack);
		}
	}
}

function updateAttachmentDetails_CallBack(response)
{
    if (response.error != null)
    {
        alert(response.error.Message);
        return;
    }
}

//function trim(s)
//{
//	return s.replace(/^\s+|\s+$/g,"");
//}

function toggleTitleText(textfield)
{
	if(textfield.value == "Title")
	{
		textfield.value = "";
	} 
	else if(textfield.value == "")
	{
		textfield.value = "Title";
	}
}

function toggleDescriptionText(textfield)
{
	if(textfield.value == "Description")
	{
		textfield.value = "";
	} 
	else if(textfield.value == "")
	{
		textfield.value = "Description";
	}
}

// ####################
// Quick Post Edit
// ####################
var currentlyEditingPost;

function openQuickEdit(PostID)
{
	currentlyEditingPost = PostID;
	
	//Ajax call to get the forum code for the post, send only the PostID
	CubicSite.AjaxAction.getQuickEditPostData(PostID, openQuickEdit_callback);

	return false;
}

function openQuickEdit_callback(Response) 
{ 
	//First close the edit links box
	togglePostEditLinks('editLinks' + currentlyEditingPost);

	//Grab the current div contents
    var elem = document.getElementById("Post" + currentlyEditingPost);
	
	elem.innerHTML = Response.value;	
	document.getElementById("AjaxStorage").value = "";

	//Reposition the page so we are at the start of the post
	var postDivTop = getObjTop(elem);
	scroll(0, postDivTop-50);

	currentlyEditingPost = "";
}

function saveAndCloseQuickEdit(PostID)
{
	currentlyEditingPost = PostID;

	//Grab the user modified post containing the new raw forumcode
    var textfield = document.getElementById("quickEditTextBox" + PostID);
	
	//Ajax call. Send the PostID and the user modified raw forum code and get back the user modified formatted HTML
	CubicSite.AjaxAction.updateQuickEditPost(PostID, textfield.value, closeQuickEdit_callback);
}

function cancelAndCloseQuickEdit(PostID)
{
	currentlyEditingPost = PostID;

	//Grab the user modified post containing the new raw forumcode
    var textfield = document.getElementById("quickEditTextBox" + PostID);
	
	//Ajax call. Send the PostID and the user modified raw forum code and get back the user modified formatted HTML
	CubicSite.AjaxAction.cancelQuickEditPost(PostID, closeQuickEdit_callback);
}

function closeQuickEdit_callback(Response) 
{ 
	//Grab the current div contents
    var elem = document.getElementById("Post" + currentlyEditingPost);
	
	elem.innerHTML = Response.value;	

	//Reposition the page so we are at the start of the post
	var postDivTop = getObjTop(elem);
	scroll(0, postDivTop-50);

	currentlyEditingPost = "";
}

function getObjTop(obj)
{
	var top=obj.offsetTop;
	while((obj=obj.offsetParent)!=null)
	{
		top+=obj.offsetTop;
	}
	return top;
}

function breadCrumbDropDown (breadcrumb, Type, CrumbIDNumber)
{
	//The first thing we do is set the onclick of the page click cover
	//Once that is done, we display the cover so that the next time it
	//is clicked the menu will close and everything will be reset again
	document.getElementById("PageClickCover").onclick = function(){ 
		closeCrumbDropdown(breadcrumb);
		document.getElementById("PageClickCover").style.display = "none";
	};
	document.getElementById("PageClickCover").style.display = "block";


	if(CrumbIDNumber == "")
	{
		CrumbIDNumber = 0;
	}

	//The dropdown object
	var DropDown = document.getElementById("crumbDropDownBox");

	//If the dropdown is open somewhere, close it for repeat onclicks!
	if(DropDown.style.display == "block")
	{
		//DropDown.style.display = "none";
		closeCrumbDropdown(breadcrumb);
		return;
	}

	//The crumb object
	var obj = document.getElementById(breadcrumb);

	var menuLinks = "";

	switch (Type)
	{
		case "forum":
				//Ajax call
			//alert('here with ' + Type + ' and ' + CrumbIDNumber);	
				menuLinks = CubicSite.AjaxAction.getBreadcrumbLinks(Type, CrumbIDNumber).value;
			break;
	
		case "default":
				//Ajax call
				menuLinks = CubicSite.AjaxAction.getBreadcrumbLinks(Type, CrumbIDNumber).value;
			break;

		default:
			menuLinks = "Nothing";
	}


	//The crumb was clicked. Change the class of it to the "clicked state".
	obj.className = "BreadCrumbActiveState MousePoint";

	//Find the position on the page of the current crumb we want a dropdown for so we know where to position the div
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	//Put the link HTML into the dropdown div
	DropDown.innerHTML = menuLinks;

	//Position the dropdown div on the page under the requesting crumb
	var DropDownWidth = DropDown.style.width.replace("px", "");
	var TotalLeftPosition = parseInt(curleft) - parseInt(20);
	var TotalTopPosition = parseInt(curtop) + 18;

	DropDown.style.left = TotalLeftPosition + "px";
	DropDown.style.top = TotalTopPosition + "px";
	DropDown.style.display = "block";
}

function closeCrumbDropdown(breadcrumb)
{
	//The crumb object
	var obj = document.getElementById(breadcrumb);	
	obj.className = "BreadCrumb MousePoint";

	//Close the dropdown
	document.getElementById("crumbDropDownBox").style.display = "none";
}


//May not need this one!!
function breadCrumbHover (breadcrumb)
{
	// this is the way the standards work
	var style2 = document.getElementById(breadcrumb + "Arrow").style;

	var crumbStyle = document.getElementById(breadcrumb).style;

	if(style2.display != "" && style2.display != "none")
	{
		style2.display = "none";
		crumbStyle.border = "0px";

		//Close the dropdown if it is open
		document.getElementById("crumbDropDownBox").style.display = "none";
	}
	else
	{
		style2.display = "inline";
		crumbStyle.border = "1px solid black";
	}	
}

function togglePostEditLinks(DivToToggle)
{
	toggleDiv(DivToToggle);

	//If the div is not already displayed, set the click cover to close it
	if(document.getElementById(DivToToggle).style.display == "block")
	{
		//The first thing we do is set the onclick of the page click cover
		//Once that is done, we display the cover so that the next time it
		//is clicked the menu will close and everything will be reset again
		document.getElementById("PageClickCover").onclick = function(){ 
			toggleDiv(DivToToggle);
			document.getElementById("PageClickCover").style.display = "none";
		};
		document.getElementById("PageClickCover").style.display = "block";
	} 
	else
	{
		//Hide the click cover since we want to close the status update div
		document.getElementById("PageClickCover").style.display = "none";
	}
}

function toggleUserStatus()
{
	toggleDiv("UpdateStatusBox");

	//If the div is not already displayed, set the click cover to close it
	if(document.getElementById("UpdateStatusBox").style.display == "block")
	{
		//The first thing we do is set the onclick of the page click cover
		//Once that is done, we display the cover so that the next time it
		//is clicked the menu will close and everything will be reset again
		document.getElementById("PageClickCover").onclick = function(){ 
			toggleDiv("UpdateStatusBox");
			document.getElementById("PageClickCover").style.display = "none";
		};
		document.getElementById("PageClickCover").style.display = "block";

		//Focus and select all the text in the status form
		var StatusArea = document.getElementById("NewStatus");
		StatusArea.focus();
		StatusArea.select();
	} 
	else
	{
		//Hide the click cover since we want to close the status update div
		document.getElementById("PageClickCover").style.display = "none";
	}
}

function updateUserStatus ()
{
	var newStatusMessage = document.getElementById("NewStatus").value;

	//Toggle the update box so it is hidden
	toggleUserStatus();

	//Block the loading box from showing
	blockLoadingBox = true;
	
	if(newStatusMessage != "")
	{
		CubicSite.AjaxAction.updateUserStatus(newStatusMessage, updateUserStatus_CallBack);
	}

	//Stop the page from submitting the form because we may have hit enter
	return false;
}

function updateUserStatus_CallBack(result)
{
	var formattedStatusMessage = result.value;
	//Update the html on the site with the new status message
	document.getElementById("CurrentStatusText").innerHTML = formattedStatusMessage;

	//Unblock the loading box from showing
	blockLoadingBox = false;
}

function clearUserStatus ()
{
	//Toggle the update box so it is hidden
	toggleUserStatus();

	//Update the html on the site with the new status message
	var StatusText = "Your status has been cleared.";
	StatusText += "<div class=\"UserStatusEdit\"><a href=\"#\" onclick=\"toggleDiv('UpdateStatusBox');\">Edit</a></div>";

	document.getElementById("CurrentStatusText").innerHTML = StatusText;

	//Block the loading box from showing
	blockLoadingBox = true;

	CubicSite.AjaxAction.clearUserStatus(clearUserStatus_CallBack);
}

function clearUserStatus_CallBack(response)
{
    if (response.error != null)
    {
		alert(response.error.Message);
        return;
    }

	//Unblock the loading box from showing
	blockLoadingBox = false;
}

// ####################
// General Functions
// ####################

function pause(milliseconds)
{
	var now = new Date();
	var exitTime = now.getTime() + milliseconds;

	while(true)
	{
		now = new Date();
		if (now.getTime() > exitTime) return;
	}
}

function toggleDiv(divid)
{

	//new Effect.SlideDown(divid);

	//new Effect.toggle(divid, 'blind', {duration:0.2});

	toggleLayer(divid);
}

function toggleLayer(whichLayer)
{
	// this is the way the standards work
	var style2 = document.getElementById(whichLayer).style;

	if(style2.display != "" && style2.display != "none")
	{
		style2.display = "none";
	}
	else
	{
		style2.display = "block";
	}	
}


//This function swaps the text in a label field (maybe others) and adds an effect as well
function swapText(fieldName, newText, effectColor)
{
    elem = document.getElementById(fieldName);
	if(elem != null)
	{
		elem.innerHTML = newText; 
	}

	
	//NOTE: Disable colors for now...
	/*
	if(effectColor == 'red')
	{
		elementRedEffect(elem);
	}
	else if (effectColor == 'green')
	{
		elementGreenEffect(elem);
	}
	*/
}

function elementRedEffect(element)
{
	new Effect.Highlight(element, {startcolor:'#ffc0cb', endcolor:'#FFFFFF'});
}

function elementGreenEffect(element)
{
	new Effect.Highlight(element, {startcolor:'#90EE90', endcolor:'#FFFFFF'});
}

function updateProfilePicture(FileID, SiteUserID)
{
	//Ajax call to update the settings
	CubicSite.AjaxAction.updateProfilePicture(FileID, SiteUserID, updateProfilePicture_callback);
}


function updateProfilePicture_callback(Response) 
{ 
	//Close the attachment top page fade
	var AttachPageFade = document.getElementById("AttachPageFade");
	AttachPageFade.style.display = "none";

	//Close the attachment selector
	var AttachmentSelector = document.getElementById("AttachmentSelector");
	AttachmentSelector.style.display = "none";

	//Get the html that was returned from the server
	var GalleryFile = Response.value;

	//Get the div that the picture is supposed to go into
	var profilePictureContainer = document.getElementById("profilePictureContainer");

	var displayHTML = "";
	displayHTML += "<a href=\"javascript:previewGalleryImage('" + GalleryFile.fileID + "');\">";
	//displayHTML += "<div style=\"display:table\" class=\"GalleryFileThumbMediumWrapper\">";
	displayHTML += "<img class=\"GalleryFileThumbMediumWrapper\" border=\"0\" src=\"" + GalleryFile.thumbnailMediumURL + "\">";
	//displayHTML += "</div>";
	displayHTML += "</a>";

	//Modify the HTML for the display area
	profilePictureContainer.innerHTML = displayHTML;
}


function getSmilies(EditorID)
{
	//Ajax call to get the other smilies
	CubicSite.AjaxAction.getSmilies(EditorID, getSmilies_CallBack);
}

function getSmilies_CallBack(Response)
{
	//Open the attachment top page fade
	var AttachPageFade = document.getElementById("AttachPageFade");
	AttachPageFade.style.display = "block";

	//Open the attachment selector
	var AttachmentSelector = document.getElementById("AttachmentSelector");
	AttachmentSelector.style.display = "block";

	//Get the html that was returned from the server
	var smiliesHTML = Response.value;

	var AttachmentSelectorContent = document.getElementById("AttachmentSelectorContent");

	//Modify the HTML for the display area
	AttachmentSelectorContent.innerHTML = smiliesHTML

}

function getGalleryFiles(SiteUserID, EditorID, VirDirID, mode, Page)
{
	//Ajax call. Get the contents of the galleryFiles Directory requested for this user
	CubicSite.AjaxAction.getGalleryFiles(SiteUserID, EditorID, VirDirID, mode, Page, getGalleryFiles_callback);
}

function getGalleryFiles_callback(Response) 
{ 
	//Open the attachment top page fade
	var AttachPageFade = document.getElementById("AttachPageFade");
	AttachPageFade.style.display = "block";
	
	//toggleDiv("AttachPageFade");
	//toggleDiv("AttachmentSelector");

	//Open the attachment selector
	var AttachmentSelector = document.getElementById("AttachmentSelector");
	AttachmentSelector.style.display = "block";

	//Get the html that was returned from the server
	var attachmentsHTML = Response.value;

	var AttachmentSelectorContent = document.getElementById("AttachmentSelectorContent");

	//Modify the HTML for the display area
	AttachmentSelectorContent.innerHTML = attachmentsHTML
}

function uploadHotOrNot(mode)
{
	openPageAnnounceBox(600, 450, true);

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");

	var textarea = "";

	pickVirtualDirectory = CubicSite.AjaxAction.setUploadDirectory(0, mode, textarea).value;

	//Modify the HTML for the display area
	elem.innerHTML = pickVirtualDirectory
}

function uploadFiles(mode, textarea)
{
	openPageAnnounceBox(600, 450, true);

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");

	pickFileUploadType = CubicSite.AjaxAction.getFileTypesHTML(mode, textarea).value;

	//Modify the HTML for the display area
	elem.innerHTML = pickFileUploadType
}

function setUploadFileType(UploadType, mode, textarea)
{
	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");

	var uploadTypeHTML = CubicSite.AjaxAction.setUploadFileType(UploadType, mode, textarea).value;

	//Modify the HTML for the display area
	elem.innerHTML = uploadTypeHTML;
}

function setUploadDirectory(UploadDirectoryID, mode, textarea)
{
	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");

	var uploadDirectoryHTML = CubicSite.AjaxAction.setUploadDirectory(UploadDirectoryID, mode, textarea).value;

	//Modify the HTML for the display area
	elem.innerHTML = uploadDirectoryHTML;
}

function setUploadVirtualDirectory(UploadVirtualDirectoryID, mode, textarea)
{
	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");

	var uploadVirtualDirectoryHTML = CubicSite.AjaxAction.setUploadVirtualDirectory(UploadVirtualDirectoryID, mode, textarea).value;

	//Modify the HTML for the display area
	elem.innerHTML = uploadVirtualDirectoryHTML;
}

var MinutesSinceDraft = 0;
var SecondsSinceDraft = 0;
var MinuteTimerID;
var SecondTimerID;

function copyTextAreaData(PostFormID)
{
	var Post = document.getElementById(PostFormID);
	var previousMessageDraft = document.getElementById("previousMessageDraftText");

	//Copy the contents of the textarea to the hidden field
	//This is used when someone replies with a quote or multi-quote 
	//or if the contents of the textarea is retrieved as a saved draft
	previousMessageDraft.value = Post.value;
}

function saveDraft(ForumForumID, ForumTopicID, TitleFormID, DesriptionFormID, PostFormID, AutoSaved)
{
	//Get the post contents
	var Post = document.getElementById(PostFormID);
	var previousMessageDraft = document.getElementById("previousMessageDraftText");

	if(previousMessageDraft.value.trim() == Post.value.trim())
	{
		//Do not go any further, no changes were made to the post since the last time
		return;
	}
	//else
	//{
	//	alert("we are saving!");
	//	alert(Post.value.length + "-->" + previousMessageDraft.value.length);
	//	alert(">>>" + Post.value + "<<<-->>>" + previousMessageDraft.value + "<<<");
	//	return;
	//}

	//Set the value of the previous message for future checking
	previousMessageDraft.value = Post.value;

	if(AutoSaved)
	{
		blockLoadingBox = true;
	} 

	if(ForumTopicID.trim() != "")
	{
		//Insert post draft into database
		CubicSite.AjaxAction.savePostDraft(ForumTopicID, Post.value, AutoSaved, saveDraft_callback);
	}
	else
	{
		var Title = document.getElementById(TitleFormID);
		var Description = document.getElementById(DesriptionFormID); 

		//Insert topic draft into database
		CubicSite.AjaxAction.saveTopicDraft(ForumForumID, Title.value, Description.value, Post.value, AutoSaved, saveDraft_callback);
	}
}

function saveDraft_callback(Response)
{ 
	var DraftNotice = "";

	if(blockLoadingBox == true)
	{
		DraftNotice = "Draft autosaved ";
		blockLoadingBox = false;
	} 
	else
	{
		DraftNotice = "Draft saved ";
	}

	//Get the file object that was returned from the server
	var SaveDateFormatted = Response.value;
	
	var DraftSaveNotice = document.getElementById("DraftSaveNotice");
	if(SaveDateFormatted == "0")
	{
		clearTimeout(MinuteTimerID);
		MinutesSinceDraft = 0;
		SecondsSinceDraft = 0;
		document.getElementById("DraftMinuteCounter").innerHTML = "";
		DraftSaveNotice.innerHTML = "Your draft has been removed";
	} 
	else
	{
		clearTimeout(MinuteTimerID);
		MinutesSinceDraft = 0;
		SecondsSinceDraft = 0;
		draftMinuteCounter();
		DraftSaveNotice.innerHTML = DraftNotice + SaveDateFormatted;
	}
}

function draftMinuteCounter()
{
	var minuteMinutes;

	var MinutesSinceDraft = Math.floor(SecondsSinceDraft / 60)

	if(SecondsSinceDraft < 60)
	{
		MinuteHourText = SecondsSinceDraft;
		if(SecondsSinceDraft == 1)
		{
			minuteMinutes = "second";
		}
		else
		{
			minuteMinutes = "seconds";
		}
	}
	else
	{
		if(MinutesSinceDraft == 1 || (MinutesSinceDraft > 59 && MinutesSinceDraft < 120))
		{
			if(MinutesSinceDraft > 1)
			{
				minuteMinutes = "hour";
			}
			else
			{
				minuteMinutes = "minute";
			}
		}
		else
		{
			if(MinutesSinceDraft >= 120)
			{
				minuteMinutes = "hours";
			}
			else
			{
				minuteMinutes = "minutes";
			}
		}
		var MinuteHourText;
		if(MinutesSinceDraft < 60)
		{
			MinuteHourText = MinutesSinceDraft;
		} 
		else 
		{
			MinuteHourText =  Math.floor(MinutesSinceDraft / 60);
		}
	}
	if(SecondsSinceDraft > 0)
	{
		document.getElementById("DraftMinuteCounter").innerHTML = "&nbsp;(" + MinuteHourText + " " + minuteMinutes + " ago)";
	}
	SecondsSinceDraft++;
	MinuteTimerID = setTimeout("draftMinuteCounter()",1000)
}

function previewMessage(MessageBoxID)
{
	//Get the text in the MessageBox that the user wants to preview
	var MessageBox = document.getElementById(MessageBoxID);
	
	//Ajax call. Send the raw text and get back the formatted HTML
	CubicSite.AjaxAction.previewMessage(MessageBox.value, previewMessage_callback);
}

function previewMessage_callback(Response) 
{ 
	//Get the file object that was returned from the server
	var previewHTML = Response.value;

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");
	
	//Set the windo width for the preview window based as a percentage of
	//the users current browser windo width
	var currentWindowWidth = getCurrentWindowWidth();


	//Set the preview window to 75% of the current browser window width
	var previewWindowWidth = Math.round(currentWindowWidth * .75 / 1);


	var currentWindowHeight = getCurrentWindowHeight();
	var previewWindowHeight = currentWindowHeight - 55;
	//Open the site announcement box to display the preview window with waiting symbol
	openPageAnnounceBox(previewWindowWidth, previewWindowHeight, false);

	elem.innerHTML = previewHTML
}

function openImage(imageURL)
{
	if(IsGoodBrowser())
	{
		var previewHTML = "<div style=\"font-size:10pt; width:100%; padding-top:5px; display:none;\" id=\"previewImage\"><img class=\"GalleryFileWrapper\" src=\"" + imageURL + "\"></div>";

		//Grab the display area content box
		var elem = document.getElementById("PageAnnounceBoxContent");
		//Modify the HTML for the display area to make sure the waiting image is there...
		elem.innerHTML = "<div class=\"Loading\">Downloading Image...</div>";

		//Open the site announcement box to display the preview window with waiting symbol
		openPageAnnounceBox(200,200, true);

		//Start preloading the image while the waiting icon rotates
		imgPreloader = new Image();
		
		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
			//Get rid of the loading icon
			elem.innerHTML = "";
			resizeImageContainer (imgPreloader.width, imgPreloader.height, previewHTML);
		}
		imgPreloader.src = imageURL;
	}
	else
	{
		var previewHTML = "<div style=\"text-align:center;\"><img src=\"" + imageURL + "\"></div>";
		imagePreviewWindow = window.open("", "imagePreview", "menubar=no,width=680, height=550, scrollbars=yes,toolbar=no");
		imagePreviewWindow.document.writeln(previewHTML);
	}
}

function previewGalleryImage(FileID)
{
	//Ajax call. Send the FileID and get back the image object which is used in the callback
	//The waiting notice message is shown until the information is received from the server
	CubicSite.AjaxAction.previewGalleryImage(FileID, previewGalleryImage_callback);
}

function previewGalleryImage_callback(Response) 
{ 
	//Get the file object that was returned from the server
	var file = Response.value;

	var tagBoxStart = "";
	var tagBoxEnd = "";

	tagBoxStart += "<div id=\"ImageContent\" style=\"text-align:center;width:650px;margin:auto auto auto auto; text-align:left;\">";
	tagBoxStart += "<div id=\"TagBox\" style=\"display:none; position:relative; height:100px; width:100px; margin-bottom:-100px;\">";
	tagBoxStart += "<div style=\"width:100%; height:100%; border:5px solid Red;\">";
	tagBoxStart += "</div></div>";

	tagBoxEnd = "</div>";

	if(IsGoodBrowser())
	{
		if(file.fileType != null && file.fileType == "video")
		{ 
			var previewHTML = "<div style=\"font-size:10pt; width:100%; padding-top:5px;>";
			previewHTML += file.videoPlayer;
			previewHTML += "<br />" + file.title ;
			if(file.description != "")
			{
				previewHTML += "<br />" + file.description ;
			}
			previewHTML += "<br /><a href=\"/gallery/file/"+ file.fileID +"/display.aspx\">View this video in the Media Gallery.</a>";
			previewHTML += "</div>";

			openPageAnnounceBox(640,480, true);

			//Grab the display area content box
			var elem = document.getElementById("PageAnnounceBoxContent");

			//Modify the HTML for the display area
			elem.innerHTML = previewHTML

			openPageAnnounceBox(640,480, true);

			//Grab the display area content box
			var elem = document.getElementById("PageAnnounceBoxContent");

			//Modify the HTML for the display area
			elem.innerHTML = previewHTML

		}
		else
		{
			var imageURL = file.resizedURL;
			var previewHTML = tagBoxStart + "<div style=\"font-size:10pt; padding-top:5px; display:none;\" id=\"previewImage\"><img class=\"GalleryFileWrapper\" src=\"" + imageURL + "\">";

			previewHTML += "<div style=\"float:left; width:80%; font-size:9pt;\">";
			if(file.fileTagHTML != "")
			{
				previewHTML += file.fileTagHTML ;
			}
			previewHTML += "<br />" + file.title ;
			if(file.description != "")
			{
				previewHTML += " - " + file.description ;
			}
			previewHTML += "</div>";
			previewHTML += "<div style=\"float:right; width:20%;text-align:right;\">";
			previewHTML += "<a href=\"/gallery/file/"+ file.fileID +"/display.aspx\">View In Gallery</a><br />";
			previewHTML += "<a href=\"/gallery/image/"+ file.fileID +"-original." + file.extension + "\">Full Size</a>";
			previewHTML += "</div>";
			previewHTML += "</div>" + tagBoxEnd;

			//Grab the display area content box
			var elem = document.getElementById("PageAnnounceBoxContent");
			//Modify the HTML for the display area to make sure the waiting image is there...
			elem.innerHTML = "<div class=\"Loading\">Downloading Image...</div>";

			//Open the site announcement box to display the preview window with waiting symbol
			openPageAnnounceBox(200,200, true);

			//Start preloading the image while the waiting icon rotates
			imgPreloader = new Image();
			
			// once image is preloaded, resize image container
			imgPreloader.onload=function(){
				//Get rid of the loading icon
				elem.innerHTML = "";
				resizeImageContainer (imgPreloader.width, imgPreloader.height, previewHTML);
			}
			imgPreloader.src = imageURL;
		}
	}
	else
	{
		if(file.fileType != null && file.fileType == "video")
		{ 
			var imageURL = file.resizedURL;
			var previewHTML = "<div style=\"text-align:center;\">";
			previewHTML += file.videoPlayer;
			previewHTML += "<br />" + file.title ;
			if(file.description != "")
			{
				previewHTML += "<br />" + file.description ;
			}
			previewHTML += "<br /><a href=\"javascript:opener.document.location('/gallery/file/"+ file.fileID +"/display.aspx');window.close();\">View this video in the Media Gallery.</a>";
			previewHTML += "</div>";

			imagePreviewWindow = window.open("", "imagePreview", "menubar=no,width=640, height=480, scrollbars=yes,toolbar=no");
			imagePreviewWindow.document.body.innerHTML = "";
			imagePreviewWindow.document.writeln(previewHTML);
		}
		else
		{
			var imageURL = file.resizedURL;
			var previewHTML = "<div style=\"text-align:center;\"><img src=\"" + imageURL + "\">";
			previewHTML += "<br />" + file.title ;
			if(file.description != "")
			{
				previewHTML += "<br />" + file.description ;
			}
			previewHTML += "<br /><a href=\"javascript:opener.document.location('/gallery/file/"+ file.fileID +"/display.aspx');window.close();\">View this image in the Media Gallery.</a>";
			previewHTML += "</div>";

			imagePreviewWindow = window.open("", "imagePreview", "menubar=no,width=680, height=550, scrollbars=yes,toolbar=no");
			imagePreviewWindow.document.body.innerHTML = "";
			imagePreviewWindow.document.writeln(previewHTML);
		}
	}
}

function resizeImageContainer (imgWidth, imgHeight, previewHTML)
{
    var wrapper = document.getElementById("PageAnnounceBox");

	// get current width and height of the preview box (We set these values in the previous function)
	//this.widthCurrent = wrapper.style.width.replace('px', '');
	//this.heightCurrent = wrapper.style.height.replace('px', '');

	this.widthCurrent = 200;
	this.heightCurrent = 200;

	// get new width and height - account for the border
	var widthNew = (imgWidth + 15);
	var heightNew = (imgHeight  + 70);
	
	var originalHeight = heightNew;

	var currentWindowHeight = getCurrentWindowHeight();

	if(currentWindowHeight < heightNew)
	{
		heightNew = currentWindowHeight - 100;
	}

	// scalars based on change from old to new
	this.xScale = ( widthNew / this.widthCurrent) * 100;
	this.yScale = ( heightNew / this.heightCurrent) * 100;

	// calculate size difference between new and old image, and resize if necessary
	wDiff = this.widthCurrent - widthNew;
	hDiff = this.heightCurrent - heightNew;

	//alert("heightCurrent:" + this.heightCurrent + " Make New Window:" + heightNew + " hDiff: " + hDiff + " xscale: " + xScale);

	var resizeDuration = 0.5;

	//Resize the container. Once that is done, load the new HTML for the image into the container and display the image
	if(!( hDiff == 0)){ new Effect.Scale('PageAnnounceBox', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
	if(!( wDiff == 0)){ new Effect.Scale('PageAnnounceBox', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration, afterFinish: function(){	previewGalleryImageLoaded(previewHTML, currentWindowHeight, originalHeight); }}); }

	// if new and old image are same size and no scaling transition is necessary, 
	// do a quick pause to prevent image flicker.
	if((hDiff == 0) && (wDiff == 0)){
		if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
	}
}

function previewGalleryImage_CallBack(response)
{
	alert(response.value);
}

function previewGalleryImageLoaded(previewHTML, currentWindowHeight, originalPreviewBoxHeight)
{	

	if(currentWindowHeight < originalPreviewBoxHeight)
	{
		var PageAnnounceBox = document.getElementById("PageAnnounceBox");
		PageAnnounceBox.style.overflow = 'auto';
	}

	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");

	//Modify the HTML for the display area
	elem.innerHTML = previewHTML

	Effect.Appear('previewImage', {duration: 0.75});
}

function registerCheckUsername(UsernameToCheck)
{
	blockLoadingBox = true;
	CubicSite.AjaxAction.registerCheckUsername(UsernameToCheck, registerCheckUsername_CallBack);
}

function registerCheckUsername_CallBack(response)
{
	blockLoadingBox = false;
	var userNameCheckArray = response.value;

	//Update the warning image
	document.getElementById("UserNameStatusBoxImage").innerHTML = userNameCheckArray[0];

	//Set the message for the warning box
	document.getElementById("UserNameStatusBoxMessage").innerHTML = userNameCheckArray[1];

	//Enable or disable the warning box
	if(userNameCheckArray[2] == "true")
	{
		//The username is taken
		document.getElementById("UserNameStatusBoxMessage").style.display = "block";
		document.getElementById("usernameConfirmed").value = "false";
	} 
	else
	{
		document.getElementById("UserNameStatusBoxMessage").style.display = "none";
		document.getElementById("usernameConfirmed").value = "true";
	}
}

function registerCheckEmail(EmailToCheck1, EmailToCheck2)
{
	if(EmailToCheck1.length > 0 && EmailToCheck2.length > 0)
	{
		blockLoadingBox = true;
		CubicSite.AjaxAction.registerCheckEmail(EmailToCheck1, EmailToCheck2, registerCheckEmail_CallBack);
	}
}

function registerCheckEmail_CallBack(response)
{
	blockLoadingBox = false;
	var emailCheckArray = response.value;

	//Update the warning image
	document.getElementById("EmailStatusBoxImage").innerHTML = emailCheckArray[0];

	//Set the message for the warning box
	document.getElementById("EmailStatusBoxMessage").innerHTML = emailCheckArray[1];

	//Enable or disable the warning box
	if(emailCheckArray[2] == "true")
	{
		//The username is taken
		document.getElementById("EmailStatusBoxMessage").style.display = "block";
		document.getElementById("emailConfirmed").value = "false";
	} 
	else
	{
		document.getElementById("EmailStatusBoxMessage").style.display = "none";
		document.getElementById("emailConfirmed").value = "true";
	}
}

function registerCheckPassword(PasswordToCheck1, PasswordToCheck2)
{
	if(PasswordToCheck1.length > 0 && PasswordToCheck2.length > 0)
	{
		blockLoadingBox = true;
		CubicSite.AjaxAction.registerCheckPassword(PasswordToCheck1, PasswordToCheck2, registerCheckPassword_CallBack);
	}
}

function registerCheckPassword_CallBack(response)
{
	blockLoadingBox = false;
	var passwordCheckArray = response.value;

	//Update the warning image
	document.getElementById("PasswordStatusBoxImage").innerHTML = passwordCheckArray[0];

	//Set the message for the warning box
	document.getElementById("PasswordStatusBoxMessage").innerHTML = passwordCheckArray[1];

	//Enable or disable the warning box
	if(passwordCheckArray[2] == "true")
	{
		//The username is taken
		document.getElementById("PasswordStatusBoxMessage").style.display = "block";
		document.getElementById("passwordConfirmed").value = "false";
	} 
	else
	{
		document.getElementById("PasswordStatusBoxMessage").style.display = "none";
		document.getElementById("passwordConfirmed").value = "true";
	}
}

function registerCheckBirthdate(BirthdateToCheck)
{
	if(BirthdateToCheck.trim().length > 0)
	{
		blockLoadingBox = true;
		CubicSite.AjaxAction.registerCheckBirthdate(BirthdateToCheck, registerCheckBirthdate_CallBack);
	}
}


function registerCheckBirthdate_CallBack(response)
{
	blockLoadingBox = false;
	var birthdateCheckArray = response.value;

	//Update the warning image
	document.getElementById("BirthdateStatusBoxImage").innerHTML = birthdateCheckArray[0];

	//Set the message for the warning box
	document.getElementById("BirthdateStatusBoxMessage").innerHTML = birthdateCheckArray[1];

	//Enable or disable the warning box
	if(birthdateCheckArray[2] == "true")
	{
		//The username is taken
		document.getElementById("BirthdateStatusBoxMessage").style.display = "block";
		document.getElementById("birthdateConfirmed").value = "false";
	} 
	else
	{
		document.getElementById("BirthdateStatusBoxMessage").style.display = "none";
		document.getElementById("birthdateConfirmed").value = "true";
	}
}

function registerConfirmFields()
{
	var usernameConfirmed = document.getElementById("usernameConfirmed").value;
	var emailConfirmed = document.getElementById("emailConfirmed").value;
	var passwordConfirmed = document.getElementById("passwordConfirmed").value;
	var birthdateConfirmed = document.getElementById("birthdateConfirmed").value;	

	var validForms = true;

	if(usernameConfirmed == "false")
	{
		var StatusBox = document.getElementById("UserNameStatusBoxMessage");
		if(StatusBox.style.display != "block")
		{
			StatusBox.innerHTML = "You must provide a username!";
			StatusBox.style.display = "block";
		}

		validForms = false;
	}

	if(emailConfirmed == "false")
	{
		var StatusBox = document.getElementById("EmailStatusBoxMessage");
		if(StatusBox.style.display != "block")
		{
			StatusBox.innerHTML = "You must provide an email address!";
			StatusBox.style.display = "block";
		}

		validForms = false;
	}

	if(passwordConfirmed == "false")
	{
		var StatusBox = document.getElementById("PasswordStatusBoxMessage");
		if(StatusBox.style.display != "block")
		{
			StatusBox.innerHTML = "You must provide a password!";
			StatusBox.style.display = "block";
		}

		validForms = false;
	}

	if(birthdateConfirmed == "false")
	{
		var StatusBox = document.getElementById("BirthdateStatusBoxMessage");
		if(StatusBox.style.display != "block")
		{
			StatusBox.innerHTML = "You must provide a valid birthdate!";
			StatusBox.style.display = "block";
		}

		validForms = false;
	}

	if(!validForms)
	{
		alert('There were errors with your registration details! Please review and try again.');
	}

	return validForms;
}


function createGuestbookEntry(SiteUserID)
{
	//Grab the textbox
    var elem = document.getElementById("newGuestbookEntry");

	if (elem.value != "")
	{	
		//Ajax call to post new entry and get new HTML for display area
		CubicSite.AjaxAction.createGuestbookEntry(SiteUserID, elem.value, createGuestbookEntry_CallBack);
	}
}

function createGuestbookEntry_CallBack(response)
{
    if (response.error != null)
    {
		alert(response.error.Message);
        return;
    }


	//Grab the textbox
	var elem = document.getElementById("newGuestbookEntry");

	if(response.value == "blocked")
	{
		alert("This user has added you to their block list. You are unable to post in their guestbook");
	}
	else
	{
		//Update the HTML for the current guestbook entries
		var guestbookEntries = document.getElementById("guestbookEntries");
		guestbookEntries.innerHTML = response.value;
	}

	//Clear the textarea
	elem.value = "";
}

function deleteGuestbookEntry(SiteUserID, EntryID)
{
	//Make sure the user really wants to delete this entry
	var confirmdelete= confirm("Are you sure you want to delete this guestbook entry?");

	if (confirmdelete == true)
	{
		//Ajax call to delete entry and get new HTML for display area
		CubicSite.AjaxAction.deleteGuestbookEntry(SiteUserID, EntryID, deleteGuestbookEntry_CallBack);
	}
}

function deleteGuestbookEntry_CallBack(response)
{
    if (response.error != null)
    {
        alert("There was an error deleting your message. Please try again.");
        return;
    }

	//Update the HTML for the current guestbook entries
	var guestbookEntries = document.getElementById("guestbookEntries");
	guestbookEntries.innerHTML = response.value;
}   

function getBlogReplies(EntryID)
{
	var blogEntryReplies = document.getElementById("blogEntryReplies" + EntryID);
	if(blogEntryReplies.innerHTML != "")
	{
		toggleDiv("blogEntryReplies" + EntryID);
	}
	else
	{
		document.getElementById("AjaxStorage").value = EntryID;
		//Ajax call to to get reply HTML for entry
		CubicSite.AjaxAction.getBlogReplies(EntryID, getBlogReplies_CallBack);
	}
}

function getBlogReplies_CallBack(response)
{
    if (response.error != null)
    {
        alert("There was an error getting the replies to this entry. Please try again.");
        return;
    }

	//Update the HTML for the current entries
	var blogEntryReplies = document.getElementById("blogEntryReplies" + document.getElementById("AjaxStorage").value);
	blogEntryReplies.innerHTML = response.value;
	toggleDiv("blogEntryReplies" + document.getElementById("AjaxStorage").value);
}   

function getHomepageTopicPost(TopicID)
{
	var postDiv = document.getElementById("PostForTopic" + TopicID);
	if(postDiv.innerHTML != "")
	{
		toggleDiv("PostForTopic" + TopicID);

	}
	else
	{
		document.getElementById("AjaxStorage").value = TopicID;
		//Ajax call to to get reply HTML for entry
		CubicSite.AjaxAction.getTopicPost(TopicID, getHomepageTopicPost_CallBack);
	}
}

function getHomepageTopicPost_CallBack(response)
{
    if (response.error != null)
    {
        alert("There was an error getting this entry. Please try again.");
        return;
    }

	//Update the HTML for the current entries
	var postDiv = document.getElementById("PostForTopic" + document.getElementById("AjaxStorage").value);
	postDiv.innerHTML = response.value;
	toggleDiv("PostForTopic" + document.getElementById("AjaxStorage").value);
}   

function openPageFold()
{

	toggleDiv('PageFold');
	//new Effect.Scale('PageFold', {scaleMode:{originalHeight: 400, originalWidth: 400}});
}

function closePageAnnounceBox()
{
	//new Effect.Fade('PageFade');
	var PageFadeDiv = document.getElementById("PageFade");
	PageFadeDiv.style.display = "none";

	var PageAnnounceBoxOuterDiv = document.getElementById("PageAnnounceBoxOuter");
	PageAnnounceBoxOuterDiv.style.display = "none";

	//Bring back the scrollbar
	//var PageBody =  document.getElementById("MainBody");
	//PageBody.style.overflow = "auto";
}

function closePageAnnounceBoxAfterMultiUpload(mode, textarea, UserID)
{
	if(mode == "forum")
	{
		alert('Upload Complete! Your files will now be inserted into your post');

		//NOTE: This function is called from within the iframe so we need to run these following
		//functions with relation to the parent or it will not work!
		var attachHTML = parent.CubicSite.AjaxAction.getRecentUploadsAttachCode().value;
		parent.insertEmoticon(attachHTML, textarea);
		parent.closePageAnnounceBox();
		parent.scanForAttachmentsAfterInsert(textarea);
	} 
	else if(mode == "quickselectorprofile")
	{
		alert('Upload Complete!');

		//NOTE: This function is called from within the iframe so we need to run these following
		//functions with relation to the parent or it will not work!
		parent.closePageAnnounceBox();
		parent.CubicSite.AjaxAction.getGalleryFiles(UserID, '', 0, 'profilephoto', '1');
		//getGalleryFiles(SiteUserID, EditorID, VirDirID, mode, Page)

	}
}

function openPageAnnounceBox(initialWidth, initialHeight, noOverflow)
{
	var PageFadeDiv = document.getElementById("PageFade");
	PageFadeDiv.style.display = "block";
	
	var PageAnnounceBoxOuterDiv = document.getElementById("PageAnnounceBoxOuter");
	PageAnnounceBoxOuterDiv.style.display = "block";

	var PageAnnounceBox = document.getElementById("PageAnnounceBox");
	PageAnnounceBox.style.display = "block";

	if(noOverflow)
	{
		PageAnnounceBox.className = "PageAnnounceBoxImagePreview";
	}
	else
	{
		PageAnnounceBox.className = "PageAnnounceBox";
	}

	if(initialWidth > 0)
	{
		PageAnnounceBox.style.width = initialWidth + "px";
	}

	if(initialHeight > 0)
	{
		PageAnnounceBox.style.height = initialHeight + "px";
	}

	//Get rid of the scrollbar
	//var PageBody =  document.getElementById("MainBody");
	//PageBody.style.overflow = "hidden";
}


// ####################
// Cookie Manipulation
// ####################

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this function gets the cookie, if it exists
function Get_Cookie( name ) 
{	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) 
{
	if ( Get_Cookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getCurrentWindowWidth()
{
	var width = 0;

	//Try various ways to get the window width
	width = document.documentElement.clientWidth;

	if(width <= 0)
	{
		width = document.body.clientWidth;
	}

	if (width  <= 0)
	{
		width = window.innerWidth;
	}

	return width;
}

function getCurrentWindowHeight()
{
	var height = 0;

	//Try various ways to get the window width
	height = document.documentElement.clientHeight;

	if(height <= 0)
	{
		height = document.body.clientHeight;
	}

	if (height  <= 0)
	{
		height = window.innerHeight;
	}

	return height;
}

function getSpellingSuggestions(word, wordContainerName)
{

}

function stopEnterSubmit() 
{
	//This will stop a form from being submitted when the enter key is hit
	if (event.keyCode == 13) event.returnValue = false;
}

function changeTextAreaHeight(TextAreaID, dowhat)
{
	var TextArea = document.getElementById(TextAreaID);
	var currentHeight = parseInt(TextArea.style.height.replace("px", ""));
	var amountToChange = 0;

	if(dowhat == "increase")
	{
		amountToChange = 100;
	}
	else if(dowhat == "decrease")
	{
		if((currentHeight - 100) > 100)
		{
			amountToChange = -100;
		}
		else
		{
			amountToChange = (currentHeight - 100) * -1;
		}
	}
	
	var newHeight = (currentHeight + amountToChange);
	TextArea.style.height = newHeight + "px";
}

function keyShortcut(event)
{
	//Check to see if the escape key has been pressed
	if (event.keyCode == 27)
	{
		//Close the preview box if it is open
		closePageAnnounceBox();
	}
}

// ####################
// Browser Detection
// ####################

function IsGoodBrowser()
{
	if((BrowserDetect.browser == "Explorer" && BrowserDetect.version == "7") || BrowserDetect.browser == "Firefox" || BrowserDetect.browser == "Opera" || BrowserDetect.browser == "Safari" || BrowserDetect.browser == "Chrome")
	{
		return true;
	}
	else
	{
		return false;
	}
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function goToPage(PageNumber, PageCount)
{
	var currentLocation = "";

	try
	{
		currentLocation = window.document.location.toString();
	}
	catch(e)
	{
		alert("Error on goToPage");
	}
	
	var goToURL = "";
	var goToPage = PageNumber;

	if(!isNaN(goToPage))
	{
		if(goToPage <= 0)
		{
			goToPage = 1;
		}

		if(goToPage > PageCount)
		{
			goToPage = PageCount;
		}

		if(currentLocation.indexOf('page=') == "-1")
		{
			goToURL = currentLocation;

			if(currentLocation.indexOf('?') == "-1")
			{
				goToURL += "?";
			} 
			else
			{
				goToURL += "&";
			}

			goToURL += "page=" + goToPage;
		}
		else
		{
			//goToURL = currentLocation.substring(0, currentLocation.indexOf('?page='));
			goToURL = currentLocation.replace(/page=\d*/g, 'page=' + goToPage);
		}

		location.href = goToURL;
	}
	else
	{
		alert("Please enter a number between 1 and " + PageCount);
	}

	//Cancel form submitting enter action
	event.returnValue = false;
	event.cancel = true;

	//Stop the page from submitting the form because we may have hit enter
	return false;
}

var currentTagX;
var currentTagY;
var currentTaggingFile;

function showTag(posHorizontal, posVertical, showForTagging)
{
	var tagSelector = document.getElementById("TagSelector");
	if(!showForTagging && tagSelector != null)
	{
		tagSelector.style.display = "none";
	}

	var theTagBox = document.getElementById("TagBox");
	theTagBox.style.left = (posHorizontal-50) + "px";
	theTagBox.style.top = (posVertical-50) + "px";
	theTagBox.style.display = "block";
}

function hideTag()
{
	var TagSelectorList = document.getElementById("TagSelectorList");
	var TagSearchBox = document.getElementById("TagSearchBox");
	var TagSelector = document.getElementById("TagSelector");
	
	if(TagSelectorList != null)
	{
		TagSelectorList.innerHTML = "";
		TagSearchBox.value = "";
		TagSelector.style.display = "none";
	}
	document.getElementById("TagBox").style.display = "none";
}

function getXY (evt)
{
	if(taggingEnabled)
	{
		var img_x;
		var img_y;
		if (document.all) 
		{ // MSIE
			img_x = evt.offsetX;
			img_y = evt.offsetY;
		} 
		else 
		{ // Netscape, etc.
			img_x = evt.clientX;
			img_y = evt.clientY;
			for (var offMark = evt.target; offMark; offMark = offMark.offsetParent) 
			{
				img_x -= offMark.offsetLeft;
			}

			var counter = 0;
			var total = 0;


			for (var offMark = evt.target; offMark;offMark = offMark.offsetParent) 
			{
				img_y -= offMark.offsetTop;
				counter++;
				total += offMark.offsetTop;
			}

			//Need to subtract the scroll offset if there is any
			img_y = window.pageYOffset + img_y;
		}
		var coordinates = 'x: ' + img_x + ', y: ' + img_y;

		currentTagX = img_x;
		currentTagY = img_y;

		updateTagSelectorList("");


		showTag(img_x, img_y, true);
		document.getElementById("TagSelector").style.display = "block";
		document.getElementById("TagSearchBox").focus();
	}
}

function imageWidth(imageURL)
{
	var theImage = new Image();

	theImage.onload=function(){
		//Get rid of the loading icon
		//updateImageContentArea (theImage.width);
	}

	theImage.src = imageURL;
	return theImage.width;
}

function setGalleryImage(imageURL)
{
	var theImage = new Image();

	theImage.onload=function(){
		//Get rid of the loading icon
		updateImageContentArea (theImage.width, imageURL);
	}

	theImage.src = imageURL;
}

function updateImageContentArea(width, imageURL)
{
	document.getElementById("ImageContent").style.width = (width + 14) + "px";
	var ImageArea = document.getElementById("ImageArea");
	ImageArea.className = "";
	ImageArea.innerHTML = "<img src=\"" + imageURL + "\" class=\"GalleryFileWrapper MainImage\">";
}

var taggingEnabled = false;

function startTagging(currentFile)
{
	currentTaggingFile = currentFile;
	taggingEnabled = true;
	toggleLayer("ImageTaggingInfo");
	updateTagSelectorList("");
}

function finishTagging()
{
	taggingEnabled = false;
	toggleLayer("ImageTaggingInfo");
	hideTag();
}

function removeTag(TagID)
{
	blockLoadingBox = true;
	CubicSite.AjaxAction.removeFileTag(TagID, removeTag_CallBack);
}

function removeTag_CallBack(response)
{
	if(response.error != null)
	{
		alert(response.error.Message);
	}

	document.getElementById("CurrentFileTags").innerHTML = response.value;
	blockLoadingBox = false;
}

function addTagForUser(SiteUserID)
{
	blockLoadingBox = true;
	CubicSite.AjaxAction.addFileTag(currentTaggingFile, SiteUserID, null, currentTagX, currentTagY, addTag_CallBack);
}

function addTagForKeyword()
{
	blockLoadingBox = true;
	var keyword = document.getElementById("TagSearchBox").value;
	if(keyword != "")
	{
		CubicSite.AjaxAction.addFileTag(currentTaggingFile, 0, keyword, currentTagX, currentTagY, addTag_CallBack);
	}
}

function addTag_CallBack(response)
{
	if(response.error != null)
	{
		alert(response.error.Message);
	}
	else
	{
		if(response.value != "")
		{
			document.getElementById("CurrentFileTags").innerHTML = response.value;
		}
		hideTag();
	}
	blockLoadingBox = false;
}


var searchInProgress = false;
var lastSearchTerm = "";

function updateTagSelectorList(keyword)
{
	if(searchInProgress)
	{
		lastSearchTerm = keyword;
	}
	else
	{
		searchInProgress = true;
		blockLoadingBox = true;
		lastSearchTerm = "";
		CubicSite.AjaxAction.fileTagSearch(keyword, currentTaggingFile, updateTagSelectorList_CallBack);
	}
}

function updateTagSelectorList_CallBack(response)
{
	searchInProgress = false;
	blockLoadingBox = false;

	if(lastSearchTerm != "")
	{
		//perform the search again because the user has modified the 
		//contents of the box since the last search was performed
		updateTagSelectorList(lastSearchTerm);
	}
	else
	{
		if(response.error != null)
		{
			alert(response.error.Message);
		}
		else
		{
			document.getElementById("TagSelectorList").innerHTML = response.value;
		}
	}	
}

function hideEventInProfile(eventType, eventObjectID)
{
	CubicSite.AjaxAction.hideSiteEventInProfile(eventType, eventObjectID, hideEventInProfile_CallBack);
}

function hideEventInProfile_CallBack(response)
{
		if(response.error != null)
		{
			alert(response.error.Message);
		}
		else
		{
			document.getElementById("UserLowdown").innerHTML = response.value;
		}
}

function loadAds(headerAdURL, sidebarAdURL, footerAdURL, displayAds)
{
	if(displayAds == 'True')
	{
		if(document.getElementById("HeaderAdFrame") != null)
		{
			document.getElementById("HeaderAdFrame").src = headerAdURL;
		}
		if(document.getElementById("SidebarAdFrame") != null)
		{
			document.getElementById("SidebarAdFrame").src = sidebarAdURL;
		}
		if(document.getElementById("FooterAdFrame") != null)
		{
			document.getElementById("FooterAdFrame").src = footerAdURL;
		}
	}
}

function loadAd(adLocation)
{
	//alert('loading ad');
	var returnvalue = "No Ad";
	if(adLocation == "header")
	{
		var adSize = 1;
		var adLocation = 1;
		var adGroup = 0;
		//returnvalue = CubicSite.AjaxAction.loadAd(adSize, adLocation, adGroup).value;
		CubicSite.AjaxAction.loadAd(adSize, adLocation, adGroup, loadAd_CallBack);
	}
	
	//return returnvalue;
}

function loadAd_CallBack(response)
{
	alert(response.value);
	document.getElementById("HeaderAdDiv").innerHTML = response.value;
	//eval(document.getElementById("HeaderAdDiv").innerHTML);
}


var currentlyLoadingPostsForTopic;

function loadTopicPosts(TopicID)
{
	if(document.getElementById("Topic" + TopicID + "Posts").style.display == "none")
	{
		document.getElementById("PageClickCover").onclick = function(){ 
			toggleLayer("Topic" + currentlyLoadingPostsForTopic + "Posts");
			document.getElementById("PageClickCover").style.display = "none";
		};
		document.getElementById("PageClickCover").style.display = "block";
	}
	else
	{
		document.getElementById("PageClickCover").style.display = "none";
	}

	currentlyLoadingPostsForTopic = TopicID;
	if(document.getElementById("Topic" + currentlyLoadingPostsForTopic + "Posts").innerHTML == "")
	{
		CubicSite.AjaxAction.loadTopicPostsPreview(TopicID, loadTopicPosts_CallBack);
	}
	else
	{
		toggleLayer("Topic" + TopicID + "Posts");
	}
}

function loadTopicPosts_CallBack(response)
{
	document.getElementById("Topic" + currentlyLoadingPostsForTopic + "Posts").innerHTML = response.value;
	toggleLayer("Topic" + currentlyLoadingPostsForTopic + "Posts");
}

//USERNAME SUGGESTION DROPDOWN

var currentSuggestionListID = "";
var currentSuggestionFormID = "";
var currentEvent = "";
var currentSearchTerm = "";







/*


function updateTagSelectorList(keyword)
{
	if(searchInProgress)
	{
		lastSearchTerm = keyword;
	}
	else
	{
		searchInProgress = true;
		blockLoadingBox = true;
		lastSearchTerm = "";
		CubicSite.AjaxAction.fileTagSearch(keyword, currentTaggingFile, updateTagSelectorList_CallBack);
	}
}

function updateTagSelectorList_CallBack(response)
{
	searchInProgress = false;
	blockLoadingBox = false;

	if(lastSearchTerm != "")
	{
		//perform the search again because the user has modified the 
		//contents of the box since the last search was performed
		updateTagSelectorList(lastSearchTerm);
	}
	else
	{
		if(response.error != null)
		{
			alert(response.error.Message);
		}
		else
		{
			document.getElementById("TagSelectorList").innerHTML = response.value;
		}
	}	
}


*/










function getUsernameSuggestions(event, suggestionListID, suggestionFormID, performSearch)
{
	currentSuggestionListID = suggestionListID;
	currentSuggestionFormID = suggestionFormID;
	currentEvent = event;

	if(event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 40 || event.keyCode == 38)
	{
		if(!performSearch)
		{
			return suggestBoxEvents(event, suggestionFormID, suggestionListID);
		}
		else
		{
			return false;
		}
	}
	else
	{
		if(performSearch)
		{
			var keywordform = document.getElementById(suggestionFormID);
			//keywordform.Attributes.Add("autocomplete", "off");
			var keyword = keywordform.value;

			if(searchInProgress)
			{
				lastSearchTerm = keyword;
			}
			else
			{
				searchInProgress = true;
				blockLoadingBox = true;
				currentSearchTerm = keyword;
				lastSearchTerm = "";
				nextSuggestionID = 0;
				CubicSite.AjaxAction.usernameSuggestionSearch(keyword, getUsernameSuggestions_CallBack);
			}
		}
	}
}

function getUsernameSuggestions_CallBack(response)
{
	searchInProgress = false;
	blockLoadingBox = false;

	if(lastSearchTerm != "")
	{
		//perform the search again because the user has modified the 
		//contents of the box since the last search was performed
		getUsernameSuggestions(currentEvent, currentSuggestionListID, currentSuggestionFormID);
	}
	else
	{
		if(response.error != null)
		{
			alert(response.error.Message);
		}
		else
		{
			var displayArea = document.getElementById(currentSuggestionListID);

			if(response.value == "")
			{
				displayArea.innerHTML = "";
				displayArea.style.display = "none";
			}
			else
			{
				//Split the returned messageID string into an array
				var usernameResults = response.value.split(",");
				var htmlToDisplay = "";
				var usernameText = "";
				//Loop through the array and hide moved messages
				for(i=0; i < usernameResults.length; i++)
				{
					//Highlight the matching text
					var pattern = new RegExp(currentSearchTerm,"gi");
					usernameText = usernameResults[i].replace(pattern, "<span class=\"ush\">" + currentSearchTerm + "</span>");
					htmlToDisplay += "<div class=\"us\" id=\"sug" + (i + 1) + "\">" + usernameText + "</div>";
				}

				displayArea.innerHTML = htmlToDisplay;
				displayArea.style.display = "block";
				currentSearchTerm = "";
			}
		}
	}	
}

var nextSuggestionID = 0;

function suggestBoxEvents(event, suggestionFormID, suggestionListID)
{
	var nextSuggestionDiv = null;
	var previousSuggestionDiv = null;

	var suggestForm = document.getElementById(suggestionFormID);
	var suggestList = document.getElementById(suggestionListID);

	//Check to see if the escape key has been pressed
	if (event.keyCode == 27)
	{
		//Escape key
		//Reset everything
		var currentlySelectedSuggestion = document.getElementById("sug" + nextSuggestionID);

		if(currentlySelectedSuggestion != null)
		{
			currentlySelectedSuggestion.style.background = "white";
		}
		nextSuggestionID = 0;
		suggestForm.value = "";
		suggestList.innerHTML = "";
		suggestList.style.display = "none";
		suggestForm.focus();
	}
	else if(event.keyCode == 9)
	{
		//Tab
		//Fill the suggestion form with the selected suggestion
		var currentlySelectedSuggestion = document.getElementById("sug" + nextSuggestionID);

		//Get rid of any highlighting html that may be present
		var formFillText = currentlySelectedSuggestion.innerHTML.replace(/<span class=ush>/gi, "");
		formFillText = formFillText.replace(/<\/span>/gi, "");
		suggestForm.value = formFillText;
		suggestList.innerHTML = "";
		suggestList.style.display = "none";
		//Set focus on the form field again and return false so the browser doesn't go to the 
		//next element on the page when tabbing
		suggestForm.focus();
		return false;
	}
	else if(event.keyCode == 40)
	{
		//Keying Down
		//Only allow them to continue keying down if there is another suggestion available in the list
		if(document.getElementById("sug" + (nextSuggestionID + 1)) != null)
		{
			nextSuggestionID = nextSuggestionID + 1;			
		}

		nextSuggestionDiv = document.getElementById("sug" + nextSuggestionID);
		previousSuggestionDiv = document.getElementById("sug" + (nextSuggestionID - 1));
		
	}
	else if(event.keyCode == 38)
	{
		//Keying Up
		//Allow the to continue keying up unless they try go past 1
		if((nextSuggestionID - 1) > 0)
		{
			nextSuggestionID = nextSuggestionID - 1;
		}
 		nextSuggestionDiv = document.getElementById("sug" + nextSuggestionID);
		previousSuggestionDiv = document.getElementById("sug" + (nextSuggestionID + 1));
	}

	//Highlight the appropriate div
	if(nextSuggestionDiv != null)
	{
		nextSuggestionDiv.style.background = "pink";
	}
	
	if(previousSuggestionDiv != null)
	{
		previousSuggestionDiv.style.background = "white";
	}
}

var currentIconURL = "";

function updateSiteEventSettings(FriendsOnly, BlockEnemies, ShowNewForumTopics, ShowNewGalleryComments, ShowNewGalleryFiles, ShowNewSiteUsers, ShowNewSiteUserStatuses, ShowNewGuestbookEntries, ShowSiteUserUpdates, iconURL)
{
	currentIconURL = iconURL;
	CubicSite.AjaxAction.updateSiteEventSettings(FriendsOnly, BlockEnemies, ShowNewForumTopics, ShowNewGalleryComments, ShowNewGalleryFiles, ShowNewSiteUsers, ShowNewSiteUserStatuses, ShowNewGuestbookEntries, ShowSiteUserUpdates, updateSiteEventSettings_CallBack);	
}

function updateSiteEventSettings_CallBack(response)
{
	toggleLayerWithLabel('CustomizeHomepage', 
						  'customizeLabel', 
						  currentIconURL + '/arrow_down.gif',
						  'Customize Lowdown',
						  currentIconURL + '/arrow_up.gif',
						  'Close',
						  'left');

	//document.getElementById("CustomizeHomepage").style.display = "none";
	document.getElementById("SiteEventsArea").innerHTML = response.value;
	setFilterButtonHilights("AllEvents");
}
function updateSiteEventSettingsCancel(iconURL)
{
	toggleLayerWithLabel('CustomizeHomepage', 
						  'customizeLabel', 
						  iconURL + '/arrow_down.gif',
						  'Customize Lowdown',
						  iconURL + '/arrow_up.gif',
						  'Close',
						  'left');
}

var moreEventsStartDate = ""
var currentFilter = "AllEvents";

function moreSiteEvents(StartDate)
{
	moreEventsStartDate = StartDate;
	CubicSite.AjaxAction.instantSiteEvents(currentFilter, StartDate, moreSiteEvents_CallBack);
}

function moreSiteEvents_CallBack(response)
{
	var moreEventsOldLabel = document.getElementById("MoreEvents" + moreEventsStartDate);
	moreEventsOldLabel.style.display = "none";

	document.getElementById("SiteEventsArea").innerHTML += response.value;
	
	//Reposition the page so we are at the start of the new content
	//var moreEventsTop = getObjTop(moreEventsOldLabel);
	//alert(moreEventsTop);
	//scroll(0, moreEventsTop-25);
}

function filterSiteEvents(EventType)
{
	currentFilter = EventType;
	CubicSite.AjaxAction.instantSiteEvents(EventType, null, filterSiteEvents_CallBack);
}

function filterSiteEvents_CallBack(response)
{
	if(response.error != null)
	{
		alert(response.error.Message);
	}

	document.getElementById("SiteEventsArea").innerHTML = response.value;
	setFilterButtonHilights(currentFilter);
}

function setFilterButtonHilights(currentFilterSet)
{
	document.getElementById("FilterAllEvents").className = "info";
	document.getElementById("FilterNewForumTopic").className = "info";
	document.getElementById("FilterNewGalleryFile").className = "info";
	document.getElementById("FilterNewGalleryComment").className = "info";
	document.getElementById("FilterNewSiteUserStatus").className = "info";
	document.getElementById("FilterNewSiteUser").className = "info";
	document.getElementById("FilterNewGuestbookEntry").className = "info";
	document.getElementById("FilterSiteUserUpdate").className = "info";

	document.getElementById("Filter" + currentFilterSet).className = "info infoselected";
}

var currentEventIDFieldID;

function addEventAttachment(GalleryFileID, EventID)
{
	CubicSite.AjaxAction.addEventAttachment(GalleryFileID, EventID, addEventAttachment_callback);
}

function addEventAttachment_callback(Response) 
{
	var resultsArray = Response.value;

	//Update the attachments area and total filecount
	var TotalFileCount = resultsArray[0];
	var htmlCode = resultsArray[1];

	document.getElementById("EventAttachments").innerHTML = htmlCode;
	document.getElementById("EventAttachmentsCount").innerHTML = TotalFileCount;
}

function chooseEventPicture(EventIDFieldID, SiteUserID)
{
	currentEventIDFieldID = EventIDFieldID;
	//Open the file selector
	getGalleryFiles(SiteUserID, '', 0, 'eventphoto', '1');
}

function removeEventPicture(EventIDFieldID)
{
	document.getElementById(EventIDFieldID).value = "";
	document.getElementById("PickEventPhotoArea").innerHTML = "";
	document.getElementById("RemoveEventPhotoLink").style.display = "none";
}

function updateEventPicture(FileID, SiteUserID)
{
	//Ajax call to update the settings
	CubicSite.AjaxAction.updateEventPicture(FileID, SiteUserID, updateEventPicture_callback);
}

function updateEventPicture_callback(Response) 
{ 
	//Close the attachment top page fade
	var AttachPageFade = document.getElementById("AttachPageFade");
	AttachPageFade.style.display = "none";

	//Close the attachment selector
	var AttachmentSelector = document.getElementById("AttachmentSelector");
	AttachmentSelector.style.display = "none";

	//Get the html that was returned from the server
	var GalleryFile = Response.value;

	//Get the div that the picture is supposed to go into
	var profilePictureContainer = document.getElementById("PickEventPhotoArea");

	var displayHTML = "";
	displayHTML += "<a href=\"javascript:previewGalleryImage('" + GalleryFile.fileID + "');\">";
	//displayHTML += "<div style=\"display:table\" class=\"GalleryFileThumbMediumWrapper\">";
	displayHTML += "<img class=\"GalleryFileThumbMediumWrapper\" border=\"0\" src=\"" + GalleryFile.thumbnailMediumURL + "\">";
	//displayHTML += "</div>";
	displayHTML += "</a>";

	//Set the hidden field value
	document.getElementById(currentEventIDFieldID).value = GalleryFile.fileID;

	//Modify the HTML for the display area
	profilePictureContainer.innerHTML = displayHTML;

	//Display removal link
	document.getElementById("RemoveEventPhotoLink").style.display = "inline";
}

var currentlyInvitingToEvent;

function updateInviteSelectorList(keyword)
{
	if(searchInProgress)
	{
		lastSearchTerm = keyword;
	}
	else
	{
		searchInProgress = true;
		blockLoadingBox = true;
		lastSearchTerm = "";
		CubicSite.AjaxAction.eventInviteSearch(keyword, currentlyInvitingToEvent, updateInviteSelectorList_CallBack);
	}
}

function updateInviteSelectorList_CallBack(response)
{
	searchInProgress = false;
	
	if(lastSearchTerm != "")
	{
		//perform the search again because the user has modified the 
		//contents of the box since the last search was performed
		updateInviteSelectorList(lastSearchTerm);
	}
	else
	{
		blockLoadingBox = false;
		if(response.error != null)
		{
			alert(response.error.Message);
		}
		else
		{
			document.getElementById("InviteSelectorList").innerHTML = response.value;
		}
	}	
}

function updateInviteList(EventID)
{
	if(searchInProgress)
	{
		setTimeout("updateInviteList(" + EventID + ")",1000);
	}
	else
	{
		var InviteFilterList = document.getElementById("InviteFilterList")
		var InviteFilter = InviteFilterList[InviteFilterList.selectedIndex].value;

		blockLoadingBox = true;
		CubicSite.AjaxAction.updateEventInviteList(EventID, InviteFilter, updateInviteList_CallBack);
	}
}

function updateInviteList_CallBack(response)
{
	blockLoadingBox = false;
	document.getElementById("EventInviteList").innerHTML = response.value;
}

function inviteUserToEvent(SiteUserID, EventID)
{
	CubicSite.AjaxAction.inviteUserToEvent(SiteUserID, EventID, inviteUserToEvent_CallBack);
}

function inviteUserToEvent_CallBack(response)
{
	var PendingInvitesHTML = response.value;

	//Place HTML on the page
	document.getElementById("PendingInviteList").innerHTML = PendingInvitesHTML;
	document.getElementById("PendingInviteListArea").style.display = "block";

	//Update search list
	var UsernameSearchString = document.getElementById("UsernameSearchBox").value;
	updateInviteSelectorList(UsernameSearchString);
}

function removePendingEventInvite(SiteUserID, EventID)
{
	CubicSite.AjaxAction.removePendingUserFromEvent(SiteUserID, EventID, removePendingEventInvite_CallBack);
}

function removePendingEventInvite_CallBack(response)
{
	var PendingInvitesHTML = response.value;

	//Place HTML on the page or hide the box
	var PendingInviteList = document.getElementById("PendingInviteList");
	if(PendingInvitesHTML == "")
	{
		document.getElementById("PendingInviteList").innerHTML = "";
		document.getElementById("PendingInviteListArea").style.display = "none";
	}
	else
	{
		document.getElementById("PendingInviteList").innerHTML = PendingInvitesHTML;
		document.getElementById("PendingInviteListArea").style.display = "block";
	}

	//Update search list
	var UsernameSearchString = document.getElementById("UsernameSearchBox").value;
	updateInviteSelectorList(UsernameSearchString);
}

function removeEventInvite(SiteUserID, EventID)
{
	CubicSite.AjaxAction.removeUserFromEvent(SiteUserID, EventID, removeEventInvite_CallBack);
}

function removeEventInvite_CallBack(response)
{
	var EventID = response.value;

	if(EventID > 0)
	{
		//Update both the lists
		var UsernameSearchString = document.getElementById("UsernameSearchBox").value;
		updateInviteSelectorList(UsernameSearchString);
		updateInviteList(EventID);
	}
}

function addEventAdmin(SiteUserID, EventID)
{
	var confirmadd= confirm("Making this person an event admin will give them the same powers as you have. Are you sure you want to do this?");

	if (confirmadd == true)
	{
		CubicSite.AjaxAction.addRemoveEventAdmin(SiteUserID, EventID, "add", addEventAdmin_CallBack);
	}
}

function addEventAdmin_CallBack(response)
{
	var EventID = response.value;

	if(EventID > 0)
	{
		updateInviteList(EventID);
	}
}

function removeEventAdmin(SiteUserID, EventID)
{
	CubicSite.AjaxAction.addRemoveEventAdmin(SiteUserID, EventID, "remove", removeEventAdmin_CallBack);
}

function removeEventAdmin_CallBack(response)
{
	var EventID = response.value;

	if(EventID > 0)
	{
		updateInviteList(EventID);
	}
}

function createEventComment(EventID)
{
	//Grab the textbox
    var elem = document.getElementById("newCommentEntry");

	if (elem.value != "")
	{	
		//Ajax call to post new entry and get new HTML for display area
		CubicSite.AjaxAction.createEventComment(EventID, elem.value, createEventComment_CallBack);
	}
}

function createEventComment_CallBack(response)
{
    if (response.error != null)
    {
		alert(response.error.Message);
        return;
    }
	//Grab the textbox
	var elem = document.getElementById("newCommentEntry");
	
	//Update the HTML for the comments
	var eventComments = document.getElementById("eventComments");
	eventComments.innerHTML = response.value;

	//Clear the textarea
	elem.value = "";
}

function deleteEventComment(EventCommentID)
{
	//Make sure the user really wants to delete this entry
	var confirmdelete= confirm("Are you sure you want to delete this comment?");

	if (confirmdelete == true)
	{
		//Ajax call to delete entry and get new HTML for display area
		CubicSite.AjaxAction.deleteEventComment(EventCommentID, deleteEventComment_CallBack);
	}
}

function deleteEventComment_CallBack(response)
{
    if (response.error != null)
    {
        alert("There was an error deleting your comment. Please try again.");
        return;
    }

	//Update the HTML for the comments
	var eventComments = document.getElementById("eventComments");
	eventComments.innerHTML = response.value;
}   

function deleteWebpage(WebpageID)
{
	//Make sure the user really wants to delete this entry
	var confirmdelete= confirm("Are you sure you want to delete this webpage?");

	if (confirmdelete == true)
	{
		//Ajax call to delete entry and get new HTML for display area
		CubicSite.AjaxAction.deleteWebpage(WebpageID, deleteWebpage_CallBack);
	}
}

function deleteWebpage_CallBack(response)
{
	var WebpageDeleted = 0;

    if (response.error == null)
    {
		WebpageDeleted = response.value;
	}

	if(response.error != null || WebpageDeleted <= 0)
	{
        alert("There was an error deleting your webpage. Please try again.");
        return;
	}
	
	document.getElementById("Webpage" + WebpageDeleted).style.display = "none";
}   

//New Poll Management
function createNewPoll()
{
	var title = document.getElementById("polltitle");
	if(title.value != "")
	{
		CubicSite.AjaxAction.createPoll(title.value, pollManagement_CallBack);
	}
}

function updatePollTitle()
{
	var title = document.getElementById("polltitle");
	blockLoadingBox = true;
	CubicSite.AjaxAction.updatePollTitle(title.value, general_CallBack);
}

function removeCurrentPoll()
{
	var confirmdelete= confirm("Remove this poll and all its data?");
	if(confirmdelete)
	{
		CubicSite.AjaxAction.removePoll(pollManagement_CallBack);
	}
}

function createPollQuestion()
{
	var title = document.getElementById("polltitle");
    var elem = document.getElementById("newPollQuestion");
	if(elem.value != "")
	{
		CubicSite.AjaxAction.createPollQuestion(title.value, elem.value, pollManagement_CallBack);
	}
}

function createPollChoice(tempQuestionID)
{
	var title = document.getElementById("polltitle");
    var elem = document.getElementById("newchoice" + tempQuestionID);
	if(elem.value != "")
	{
		CubicSite.AjaxAction.createPollChoice(title.value, tempQuestionID, elem.value, pollManagement_CallBack);
	}
}

function removePollChoice(tempQuestionID, tempChoiceID)
{
	var title = document.getElementById("polltitle");
	CubicSite.AjaxAction.removePollChoice(title.value, tempQuestionID, tempChoiceID, pollManagement_CallBack);
}

function removeTempPollQuestion(tempQuestionID)
{
	var title = document.getElementById("polltitle");
	var confirmdelete= confirm("Remove this question and all its choices?");
	if(confirmdelete)
	{
		CubicSite.AjaxAction.removeTempPollQuestion(title.value, tempQuestionID, pollManagement_CallBack);
	}
}

function removePollQuestion(QuestionID)
{
	var title = document.getElementById("polltitle");
	var confirmdelete= confirm("Remove this question? All choices and votes for the question will be lost.");
	if(confirmdelete)
	{
		CubicSite.AjaxAction.removePollQuestion(title.value, QuestionID, pollManagement_CallBack);
	}
}

function pollManagement_CallBack(response)
{
    if (response.error != null)
    {
		alert(response.error.Message);
        return;
    }
	
	//Update the HTML for the comments
	var poll = document.getElementById("PollManagementArea");
	poll.innerHTML = response.value;
}

function toggleStatusComments(SiteUserStatusID)
{
	toggleDiv("status" + SiteUserStatusID + "commentsarea");

	var currentComments = document.getElementById("status" + SiteUserStatusID + "comments");

	if(currentComments.innerHTML == "")
	{
		statusCommentBoxFocus(SiteUserStatusID);
	}
}

function statusCommentBoxBlur(SiteUserStatusID)
{
	var currentCommentBox = document.getElementById("status" + SiteUserStatusID + "textbox");
	var currentCommentButton = document.getElementById("status" + SiteUserStatusID + "button");
	
	if(currentCommentBox.value.trim().length == 0)
	{
		var currentComments = document.getElementById("status" + SiteUserStatusID + "comments");
		var currentCommentArea = document.getElementById("status" + SiteUserStatusID + "commentsarea");

		if(currentComments.innerHTML == "")
		{
			currentCommentArea.style.display = "none";
		}

		//Hide the button and collapse the box
		currentCommentButton.style.display = "none";
		currentCommentBox.style.height = "17px";
		currentCommentBox.style.overflow = "hidden";
		currentCommentBox.style.color = "gray";
		currentCommentBox.value = "Write a comment...";
	}
}

function statusCommentBoxFocus(SiteUserStatusID)
{
	var currentCommentBox = document.getElementById("status" + SiteUserStatusID + "textbox");
	var currentCommentButton = document.getElementById("status" + SiteUserStatusID + "button");
	
	if(currentCommentBox.value.trim() == "Write a comment...")
	{
		//Show the button and expand the box
		currentCommentBox.style.height = "75px";
		currentCommentBox.style.overflow = "auto";
		currentCommentBox.style.color = "black";
		currentCommentBox.value = "";
		currentCommentBox.focus();
		currentCommentButton.style.display = "block";
	}
}

var currentSiteUserStatusID;

function addSiteUserStatusComment(SiteUserStatusID)
{
	currentSiteUserStatusID = SiteUserStatusID;

	var currentCommentBox = document.getElementById("status" + currentSiteUserStatusID + "textbox");
	CubicSite.AjaxAction.addSiteUserStatusComment(SiteUserStatusID, currentCommentBox.value, addRemoveSiteUserStatusComment_CallBack);
}

function removeSiteUserStatusComment(SiteUserStatusCommentID, SiteUserStatusID)
{
	currentSiteUserStatusID = SiteUserStatusID;
	CubicSite.AjaxAction.removeSiteUserStatusComment(SiteUserStatusCommentID, addRemoveSiteUserStatusComment_CallBack);
}

function addRemoveSiteUserStatusComment_CallBack(response)
{
    if (response.error != null)
    {
		alert(response.error.Message);
        return;
    }
	
	//Update the HTML for the comments
	var commentslist = document.getElementById("status" + currentSiteUserStatusID + "comments");
	commentslist.innerHTML = response.value;

	document.getElementById("status" + currentSiteUserStatusID + "textbox").value = "";
	statusCommentBoxBlur(currentSiteUserStatusID);
}

var currentlyAdjustingAvatarID;

function adjustAvatarThumbnail()
{
	//Grab the display area content box
    var elem = document.getElementById("PageAnnounceBoxContent");
	elem.innerHTML = "";

	//alert("Modifying Avatar #" + currentlyAdjustingAvatarID);
	openPageAnnounceBox(350, 200, true);

	var adjusthtml = CubicSite.AjaxAction.adjustAvatarThumbnailForm(currentlyAdjustingAvatarID).value;

	//Modify the HTML for the display area
	elem.innerHTML = adjusthtml;
}

function adjustAvatarThumbnailCrop(avatarID, xOffset, yOffset)
{
	if(xOffset == "")
	{
		xOffset = 1;
	}
	if(yOffset == "")
	{
		yOffset = 1;
	}

	CubicSite.AjaxAction.adjustAvatarThumbnailCrop(avatarID, xOffset, yOffset, adjustAvatarThumbnailCrop_CallBack);
}

function adjustAvatarThumbnailCrop_CallBack(Response)
{
	if(Response.error)
	{
		alert(Response.error.Message);
		alert("Error adjusting avatar!");
	}
	else
	{
		var avatarObject = new Object();
		avatarObject = Response.value;

		//NOTE: This function is called from within the iframe so we need to run these following
		//functions with relation to the parent or it will not work!
		//Note that we also tack on a random number to the new image so the browser will load it instead of getting it from cache
		parent.document.getElementById("editAvatarThumbnailDisplay").innerHTML = "";
		parent.document.getElementById("editAvatarThumbnailDisplay").innerHTML = "<img border=\"0\" src=\"" + avatarObject.ResizedProportionateURL + "?" + (Math.floor(Math.random()*1000000)) + "\">";
		parent.document.getElementById("AvatarThumbnailArea").style.display = "block";
		parent.closePageAnnounceBox();
	}
}