var lang = new Array();

lang['modify_post'] = "Modify";
lang['post_editor_title'] = "Post Title";
lang['post_editor_mandatory'] = "Mandatory Field";
lang['post_editor_optional'] = "Optional Field";
lang['post_editor_image_uploader'] = "Attach Images";
lang['post_edtor_image_uploader_tip'] = "You may attach as many images as you like, so long as they are under 300kb each and the entire post is smaller then 2mb";
lang['post_editor_post_size'] = "Your post contains <%A%>% of it's allowed filesize."
lang['post_editor_post_exact_size'] = "Your post is <%A%>kb";
lang['post_editor_post_content'] = "Post Content";
lang['post_editor_post_category'] = "Select a Category";
lang['post_editor_post_type'] = "Please Select a post type:";
lang['post_editor_post_save_post'] = "Save Post";
lang['post_editor_post_cancel_post'] = "Cancel";
lang['comment_editor_post_new_comment'] = "Post New Comment";
lang['post_editor_error'] = "Uh oh!";
lang['benchMarking'] = "benchMarking";
lang['error'] = "Oops! Looks like something went wrong...";
lang['delete'] = "Delete";
lang['delete_confirm'] = "Are you sure you want to delete this?";
lang['delete_yes'] = "Yes";
lang['delete_no'] = "No";

lang['admin_post_confirm_delete'] = "Are you sure you wish to remove this module?";
lang['admin_post_controls_new_module'] = "Add Module";
lang['admin_post_module_field_question'] = "Question";
lang['admin_post_module_field_answer'] = "Answer (please wrap each paragraph within &lt;p&gt; and &lt;/p&gt; tag)";
lang['admin_post_module_field_title'] = "Title";
lang['admin_post_module_field_subTitle'] = "Sub-Title";
lang['admin_post_module_field_poster'] = "Poster";
lang['admin_post_module_field_copy'] = "Copy";
lang['admin_post_module_field_link'] = "Link";
lang['admin_post_module_field_image'] = "Image Path";
lang['admin_post_module_field_tourListing'] = "Put each list item in an &lt;li&gt; tag";
lang['admin_post_module_field_code'] = "Code";
lang['admin_post_module_field_width'] = "Width (688 is the max width for the main content column)";
lang['admin_post_module_field_height'] = "Height";
lang['admin_post_module_field_rating'] = "05,10,15,20,25,30,35,40,45 or 50 (NOTE: There is not . between numbers)";
lang['admin_post_module_field_alt'] = "Short Image Description (Mandatory)";
lang['admin_post_module_field_align'] = "Alignment (center,left,right)";
lang['admin_post_module_field_path'] = "Path to the file";
lang['admin_post_module_field_date'] = "Date (example Mar 3, 2008)";
lang['admin_post_module_field_keywords'] = "Keywords (seperated by spaces)";
lang['admin_post_module_question'] = "Interview Question";
lang['admin_post_module_blockText'] = "Block of Code";
lang['admin_post_module_image'] = "Image";
lang['admin_post_module_sound'] = "Sound Player";
lang['admin_post_module_tourListing'] = "Tour Listing";
lang['admin_post_module_field_target'] = "The Target File";

lang['admin_post_module_field_lines'] = "Lines place each stanza in a &lt;ul&gt; and each line in a &lt;li&gt;";
lang['admin_post_module_field_author'] = "Author";
lang['admin_post_module_lyrics'] = "Lyrics or Poem";
lang['admin_post_module_rating'] = "Rating";
lang['admin_post_module_YouTube'] = "YouTube";
lang['admin_post_module_postFooter'] = "Post Footer";
lang['admin_post_module_tutorialStep'] = "Tutorial Step";
lang['admin_post_module_download'] = "External File Download";

lang['admin_post_module_video'] = "Video Player";
lang['admin_post_module_imageLink'] = "Image Link";
lang['admin_post_module_subHeader'] = "Subheader";
lang['admin_post_module_seperator'] = "Seperator";
lang['admin_post_module_audioCredit'] = "Audio Post Credit";
lang['admin_post_module_centeredIconBlock'] = "Centered Icon Block";
lang['admin_post_new_module'] = "Add a new module to the post";
lang['admin_post_module_editor_title'] = "Modules";
lang['admin_post_module_edit'] = "edit";

lang['ticket_manager_button'] = "Report a problem"
lang['ticket_manager_new_ticket'] = "New trouble ticket";
lang['ticket_manager_new_ticket_tip'] = "Report a bug, rules violation, or even ask for technical support. <br /> Be as detailed as possible.";
lang['ticket_manager_submit_new_ticket'] = "Submit Ticket";
lang['ticket_manager_submit_new_ticket_success'] = "Your ticket has been succesfully submitted.";
lang['ticket_manager_title'] = "ticketManager";
lang['ticket_manager_resolve'] = "Close Ticket";
lang['ticket_manager_empoty'] = "There are currently no unresolved tickets.";

lang['interview_index_labels'] = new Array("Prospects","Contacted","Responded","Confirmed","Pending","Live","Try Again","Declined","Unresponsive","Do Not Contact","No Contact Info","Trash");
lang['interview_index_columns_priority'] = "<img src='/templates/images/icons/flag.png' alt='#' style='border:none;' />";
lang['interview_index_columns_name'] = "Name";
lang['interview_index_columns_type'] = "Type";
lang['interview_index_columns_contact'] = "Contact";
lang['interview_index_columns_handler'] = "Handler";
lang['interview_index_columns_date'] = "Last Update";
lang['interview_index_columns_interview_post'] = "Interview Post";
lang['interview_index_columns_interview_podcast'] = "Podcast";
lang['interview_index_new_interviewee'] = "Create new interviewee";
lang['interview_index_contect_info_need'] = "need";
lang['interview_index_contect_info_uncomfirmed'] = "Uncomfirmed";
lang['interview_index_contect_info_comfirmed'] = "Comfirmed By";
lang['interview_index_notes'] = "notes";
lang['interview_index_add_note'] = "add note";
lang['interview_index_move'] = "move";
lang['interview_index_label_empty'] = "This label is empty.";
lang['interview_index_edit_interviewee_type'] = "Edit interviewee type.";
lang['interview_index_edit_interviewee_handler'] = "Edit interviewee hander.";
lang['interview_index_edit_interviewee_label_note'] = "Why? (mandatory)";
lang['interview_index_edit_interviewee_notes_reminder'] = "Notes do NOT save until the 'save' button below has been clicked. Notes cannot be edited once saved.";
lang['interview_index_edit_interviewee_label_note_move_to'] = "Moved to ";
lang['interview_index_edit_interviewee_name'] = "Edit interviewee name.";
lang['interview_index_edit_interviewee_priority'] = "Edit interviewee priority.";
lang['interview_index_edit_interviewee_priority_tip'] = "Red being the highest priority<br /><br />Black means this interviewee has a hold on it and that no further<br />contact or development should be made until the hold is resolved.<br />Details on the reason for the hold will be in the notes.";
lang['interview_index_edit_interviewee_label'] = "Move interviewee.";
lang['interview_index_edit_interviewee_contact'] = "Contact Info";
lang['interview_index_edit_interviewee_notes'] = "Notes for ";
lang['interivew_index_edit_interviewee_save_note_fail'] = "Unable to save while there is content in the field. Either click the add button to add it to the notes, remove the content or hit cancel."
lang['interview_index_new_interviewee'] = "New Interviewee";
lang['interview_index_save'] = "Save";
lang['interview_index_cancel'] = "Cancel";
lang['interview_index_create_interview_post'] = "Create Interview";
lang['interview_index_create_podcast'] = "Create Podcast";
lang['interview_index_published'] = "Published on ";
lang['interview_index_unpublished'] = "Unpublished";
lang['interview_index_interviewer'] = "Interviewer";
lang['interview_index_interview_controls'] = "Interview Control Panel";
lang['interview_index_interview_controls_visit'] = "View Interview";
lang['interview_index_interview_controls_publish'] = "Publish Interview";
lang['interview_index_interview_controls_unpublish'] = "Unpublish Interview";
lang['interview_index_interview_controls_delete'] = "Delete Interview";
lang['interview_index_podcast_published'] = "Published on ";
lang['interview_index_podcast_unpublished'] = "Unpublished";
lang['interview_index_create_podcast'] = "Create Podcast";
lang['interview_index_podcast_editor_title'] = "Podcast Title";
lang['interview_index_podcast_editor_subTitle'] = "Podcast Sub-Title";
lang['interview_index_podcast_editor_summary'] = "Description";
lang['interview_index_podcast_editor_keywords'] = "Keywords (up to 12, comma seperated)";
lang['interview_index_podcast_editor_mediaPath'] = "Sound File";
lang['interview_index_podcast_editor_mediaSize'] = "Sound File Size (bytes)";
lang['interview_index_podcast_editor_mediaLength'] = "Sound File Length (Hours:Minutes:Seconds) (Approximate Length is fine)";
lang['interview_index_view_podcast'] = "Edit Podcast";
lang['interview_index_title'] = "interviewManager";
lang['interview_index_loading'] = "Accessing Interview Database";

lang['podcast_manager_loading'] = "Accessing Podcast Database";
lang['podcast_manager_title'] = "podcastManager";
lang['podcast_manager_downloads'] = "Downloads";
lang['podcast_manager_podcast_title'] = "Podcast";
lang['podcast_manager_publish_date'] = "Publish Date";
lang['podcast_manager_publish'] = "Unpublished";
lang['podcast_manager_edit_podcast'] = "Podcast Editor";
lang['podcast_manager_publish'] = "Publish Podcast";
lang['podcast_manager_publish_confirm'] = "Are you sure you want to publish this podcast? <br /> Once a podcast has been published, it cannot be unpudblished:";
lang['podcast_manager_empty'] = "The podcastManager is empty";
lang['podcast_manager_cancel_publish'] = "Do not publish";
lang['podcast_manager_new_podcast'] = "New Podcast";

lang['permission_manager_title'] = "permissions";
lang['permission_manager_index'] = "permissionIndex";
lang['permission_manager_groups'] = "memberGroups";
lang['permision_manager_index_modify'] = "Modify";
lang['permission_manager_permission_editor_name'] = "Name";
lang['permission_manager_permission_editor_description'] = "Description";
lang['permission_manager_permission_editor_rank'] = "Rank Name";
lang['permission_manager_permission_editor_color'] = "The color associated with this rank.<br />(don't forget the #)";
lang['permission_manager_edit_permission'] = "Edit Permission";
lang['permission_manager_permission_editor_save'] = "Save Permission";
lang['permission_manager_new_permission'] = "Create New Permission";
lang['permission_manager_new_member_group'] = "New Member Group";
lang['permision_manager_set_group_permissions'] = "Permissons";
lang['permission_manager_new_member_group'] = "New Member Group";

lang['admin_window_title'] = "adminPanel";
lang['admin_window_close'] = "close";
lang['admin_window_loading'] = "Verifying Admin Permissions";

lang['admin_window_header_published_media'] = "mediaPublishing";
lang['admin_window_header_admin_functions'] = "adminFunctions";

lang['cancel'] = "Cancel";
lang['save'] = "Save";
lang['modify'] = "Modify";
lang['ok'] = "Ok";
lang['loading'] = "Loading...";
lang['time_out'] = "Server failed to respond.";

lang['pages_manager_title'] = "pagesManager";
lang['pages_manager_up_one_level'] = "Back";
lang['pages_manager_move'] = "Move";
lang['pages_manager_edit'] = "Edit";
lang['pages_manager_launch'] = "Launch";
lang['pages_manager_edit_navigation'] = "Nav: ";
lang['pages_manager_delete'] = "Delete";
lang['pages_manager_open'] = "Edit"
lang['pages_manager_new_page'] = "New Page";
lang['pages_manager_new_folder'] = "New Folder";
lang['pages_manager_default_folder_name'] = "Untitled Folder";
lang['pages_manager_default_page_name'] = "Untitled Page";
lang['pages_manager_confirm_delete'] = "Are you sure you want to delete this?";
lang['pages_manager_navigation'] = "Navigation";
lang['pages_manager_new_navigation'] = "Create a new navigation";

lang['ie6'] = "<p>jitZul does not support Internet Explorer 6, sorry for the inconvenience. It is highly advised that you download a more modern browser such as <a href='http://www.getfirefox.com'>FireFox</a>, <a href='http://www.microsoft.com/windows/internet-explorer/default.aspx'>Internet Explorer 8</a>, or <a href='http://www.google.com/chrome/'>Google Chrome</a>. By upgrading, you will not only be able to browse faster with less crashes, you will also significantly increase your own personal security while online.</p><p>Feel free to browse jitZul in Internet Explorer 6 but be aware that several features will not work and that you will occasionally encounter display bugs.</p>";

lang['category_manager_title'] = "categoryManager";
lang['category_manager_edit_category_title'] = "Title";
lang['category_manager_edit_category_order'] = "Importance (A Number between 1 and 10, categories are ordered by importance)";
lang['category_manager_edit_category_description'] = "Description";
lang['category_manager_new_category'] = "Create New Category";

lang['blog_manager_title'] = "blogQueue";
lang['blog_manager_publish'] = "Publish Blog";
lang['blog_manager_publish_confirm']  = "Publishing: ";
lang['blog_manager_new_blog'] = "Create New Blog";


lang['resource_manager_title'] = "resourceQueue";
lang['resource_manager_publish'] = "Publish Resource";
lang['resource_manager_publish_confirm']  = "Publishing: ";
lang['resource_manager_new_resource'] = "Create New Resource";

lang['comment_manager_title'] = "moderateComments";
lang['comment_manager_reject'] = "Reject";
lang['comment_manager_approve'] = "Approve";var commentData = Array();// Array | When a comment is edited, the data is stored in this variable
var individual_comment_template = "";
var targetComment = "";
var commentAction = "";
var commentTemplateLoading = false;

/** EDIT COMMENT ACTIONS **/

/** Launches the editor in a commment
** @param commentId The id of the comment that was just saved
** @param userId The Id of the original poster of the comment
**/
function commentEditor(commentId){
	if(section_admin == 1){
		displayCommentEditorControls(commentId);
	}else{
		displayCommentEditorPrompt();
	};
};

/** Displays the editor field
** @param commentId The id of the comment that was just saved
**/
function editComment(commentId){
	targetComment = commentId;
	commentAction = "edit";	
	loadTemplate("sub_templates/individual_comment_template.html",commentTemplateLoaded);
};

function commentTemplateLoaded(data){
	individual_comment_template = data['template'];
	loadTemplate("sub_templates/emoticons.html",commentEmoticonsTemplateLoaded);
};

function commentEmoticonsTemplateLoaded(data){
	emoticons_template = data['template'];
	if(commentAction == "edit"){
		loadCommentEditor();
	}else{
		newCommentChange();
	};
};


/** Displays the modify and delete buttons
** @param commentId The id of the comment that was just saved
**/
function displayCommentEditorControls(commentId){
	var editor_controls = "<div class='comment_editor_controls'>";		
	editor_controls += createDelete("deleteComment("+commentId+");")+"</div>";	
	document.getElementById("commentEditor"+commentId).innerHTML = editor_controls;
};

function displayCommentEditorPrompt(){
	document.getElementById("commentEditor"+commentId).innerHTML = "<p>"+lang['comment_editor_login_prompt']+"</p>";
};




/** Displays the edits made to the comment **/
function editCommentComplete(data){
	document.getElementById("commentContent"+data['id']).innerHTML = commentData['edit'];
	displayCommentEditorControls(data['id']);
};

/** NEW COMMENT ACTIONS **/

/** Displays the new comment editor window
** @param postId The id of the post that is being replied to
**/
function newCommentEditor(postId){
	var comment_editor = "";	
	comment_editor = "<h3>Post a Comment</h3><div  class='new_comment'><div><label for='name'>Name</label><input name='name' id='newCommentName' type='text'  style='border-right:0px;' onkeyup='newCommentChange()' value='"+username+"' /></div><div><label for='email'>Email</label><input name='email' id='newCommentEmail' type='text'  style='border-right:0px;' onkeyup='newCommentChange()' value='"+email+"'/></div><div><label for='website'>Website (optional)</label><input name='website' id='newCommentWebsite' type='text' onkeyup='newCommentChange()'/></div><textarea id='newCommentEdit' onkeyup='newCommentChange()'></textarea><div class='comment_editor'><a href='javascript:newCommentSave("+postId+");' id='newCommentSaveButton' class='new_comment_save'><em>Please fill in the above fields to post a comment.</em></a></div></div>";
	document.getElementById("new_comment").innerHTML = comment_editor;
};

/** Sends the new comment's data to the server for saving 
** @param postId The id of the post that is being replied to
**/
function newCommentSave(postId){
	if(document.getElementById("newCommentEdit").value != "" && document.getElementById("newCommentName").value != "" && document.getElementById("newCommentEmail").value != ""){
		sendData(Array("action","comment","id","type","name","email","website"),Array("newComment",nl2br(secureText(document.getElementById("newCommentEdit").value)),postId,database_table,nl2br(secureText(document.getElementById("newCommentName").value)),nl2br(secureText(document.getElementById("newCommentEmail").value)),nl2br(secureText(document.getElementById("newCommentWebsite").value))),newCommentSaveSuccessful);
		commentData['new'] = nl2br(parseBB(document.getElementById("newCommentEdit").value));	
		document.getElementById("new_comment").innerHTML = loadingAnimation();
	}
};

/** When the server has returned success, display the new comment **/
function newCommentSaveSuccessful(data){
	document.getElementById("new_comment").innerHTML = "<h4>Thank-you, Your comment has been submitted and is awaiting moderation.</h4>";
};

/** When the field changes, scan it for change and update the preview accordingly **/
function newCommentChange(){	
	if(document.getElementById("newCommentEdit").value != "" && document.getElementById("newCommentName").value != "" && document.getElementById("newCommentEmail").value != ""){
		document.getElementById("newCommentSaveButton").innerHTML = lang['comment_editor_post_new_comment'];
	}else{
		document.getElementById("newCommentSaveButton").innerHTML = "<em>Please fill in the above fields to post a comment.</em>";
	};	
};

/** DELETE ACTIONS **/

/** Deletes the comment **/
function deleteComment(commentId){
	document.getElementById("comment"+commentId).innerHTML = loadingAnimation();
	sendData(Array("action","commentId"),Array("deleteComment",commentId),deleteCommentComplete);
};

/** Upon success it removes the post from the user's screen **/
function deleteCommentComplete(data){
	document.getElementById("comment"+data['id']).innerHTML = "";
	document.getElementById("comment"+data['id']).style.display = "none";	
};
var post_header_template = "";// String | Contains post headers
var flush;// Function | The function to be called when a flush is needed
var currentCategory = ""; // String | The current selected category of the post
var deletedData = "";
var emoticons_template = "";

/** Launches the editor in a commment
** @param postId The ID of the post that is to be edited
** @param poserId The ID of the poster who created the post
** @param postType The type of the post (text,image,tutorial,page etc)
**/
function postControls(postId,posterId,postType){
	if(user_id == posterId || section_admin == 1){
		displayEditorControls(postId,posterId,postType);
	};
};

/** Displays the modify and delete buttons for the post
** @param postId The ID of the post that is to be edited
** @param poserId The ID of the poster who created the post
** @param postType The type of the post (text,image,tutorial,page etc)
**/
function displayEditorControls(postId,posterId,postType){
	var editor_controls = "<div class='post_controls'>";	
	editor_controls += "<a href='javascript:edit"+firstLetterToCap(postType)+"Post("+postId+");'>"+lang['modify_post']+"</a>";	
	if(database_table != "interviews"){editor_controls += createDelete("deletePost("+postId+",\""+database_table+"\");");};
	editor_controls += "</div>";
	document.getElementById("postControls").innerHTML = editor_controls;
};

/** Creates the title editor field
** @param title The title to be pre-filled
** @param flush The javascript function to be called to flush any edits to this field
**/
function titleEditor(title,refreshOnChange){
	if(refreshOnChange == undefined){refreshOnChange = true;};
	if(title == undefined){title = "";};
	var string = "";	
	string += "<h3>"+lang['post_editor_title']+"</h3><h4>"+lang['post_editor_mandatory']+"</h4><textarea "
	
	if(refreshOnChange){
		string += "onkeyup='flushDisplay();'";
	};
	
	string += " id='postTitle' class='title'>"+parseText(title)+"</textarea>";	
	return string;
};

var images = new Array();
var imageCount = 0;

/** Launches the imageBrowser **/
function imageBrowser(){
	imageManager = new Array();
	images = new Array();
	var string = "";	
	string += "<h3>"+lang['post_editor_image_uploader']+"</h3><h4>"+lang['post_edtor_image_uploader_tip']+"</h4><div id='imageBrowser' class='category_selector'><iframe id='uploadTarget' name='uploadTarget' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe><form action='/API/_uploadManager/UploadManager.php?action=uploadImage' method='post' enctype='multipart/form-data' target='uploadTarget'><input type='file' name='file'></input><input type='submit' value='Upload File' onmouseup='beginImageUpload();' id='fileUploadSubmit'></input></form><div id='imageManager' class='image_manager'></div></div>";	
	return string;
}

function addDefaultImages(data){
	var images = data.split("[,]");
	for(var i = 0;i<images.length;i++){
		addImageToImageManager(parseNameValuePairs(images[i]));
	};
};

/** Creates the uploadTracker interval **/
var uploadTracker;
function beginImageUpload(){
	uploadTracker = setInterval(trackImageUpload,500);
};

/** Tracks the image upload **/
function trackImageUpload(){		
	var returnData;	
	if(navigator.appName == "Microsoft Internet Explorer"){
		if(document.getElementById("uploadTarget").Document.getElementById("holder").innerHTML){
			clearInterval(uploadTracker);
			returnData = parseUploadReturn(document.getElementById("uploadTarget").Document.getElementById("holder").innerHTML);
			if(returnData['return'] != "true"){
				displayError(document.getElementById("uploadTarget").Document.getElementById("holder").innerHTML);
			};
			completeImageUpload(returnData);
			document.getElementById("uploadTarget").src = "/API/_uploadManager/UploadComplete.php";
		};
	}else{
		if(document.getElementById("uploadTarget").contentDocument.getElementById("holder").innerHTML){
			clearInterval(uploadTracker);
			returnData = parseUploadReturn(document.getElementById("uploadTarget").contentDocument.getElementById("holder").innerHTML);
			if(returnData['return'] != "true"){
				displayError(document.getElementById("uploadTarget").contentDocument.getElementById("holder").innerHTML);
			};
			completeImageUpload(returnData);
			document.getElementById("uploadTarget").src = "/API/_uploadManager/UploadComplete.php";
		};
	};
};

/** When the image upload is complete, handle the returned data 
** data The array of data returned from the server
**/
function completeImageUpload(data){
	if(data['error'] != undefined){
		openWindow("<h1>"+lang['post_editor_error']+"</h1><h2>"+data['error']+"</h2>",new Array("OK"),new Array(""),"alert");
	}else{	
		addImageToImageManager(data);
	};
};

var imageManager = new Array();
/** Adds a new image to the image manager
** @param data The image data for the new image
**/
function addImageToImageManager(data){
	imageManager.push(data);
	refreshImageManager();
	flushDisplay();
};


/** Refresh the contents of the image manager **/
function refreshImageManager(){
	var totalSize = 0;
	var string = "";
	for(var i = 0;i<imageManager.length;i++){
		string += "<span class='image'><div class='info'>"+imageManager[i]['name']+"</div><div class='thumb'><img src='/images/uploads/"+imageManager[i]['mid']+"/thumb_"+imageManager[i]['id']+"_"+imageManager[i]['name']+"' width='"+getUploaderThumbDimensions(imageManager[i])[0]+"' height='"+getUploaderThumbDimensions(imageManager[i])[1]+"' style='"+getUploaderThumbPadding(imageManager[i])+"' /></div><div class='info'>"+Math.round(imageManager[i]['size']/1024)+"Kb - "+createDelete("deleteImageFromManager("+i+");")+"</div></span>";		
		totalSize += imageManager[i]['size']/1024;
	};	
	if(largeUploads != 1){
		var percent = Math.round(totalSize/max_post_file_size_kb * 100);
		if(percent > 100){
			percent = 100;
			document.getElementById("fileUploadSubmit").disabled = true;
		}else{
			document.getElementById("fileUploadSubmit").disabled = false;	
		}
		string += "<br />"+replaceAll(lang['post_editor_post_size'],"<%A%>",percent);
	}else{
		string += "<br />"+replaceAll(lang['post_editor_post_exact_size'],"<%A%>",Math.round(totalSize));
		
	};
	document.getElementById("imageManager").innerHTML = string;
};

/** Calculates the padding of a thumb so it is centered 
** @param data Contains the image's data
**/
function getUploaderThumbPadding(data){
	var dimensions = getUploaderThumbDimensions(data);	
	var hPadding = (110 - dimensions[0])/2; 
	var vPadding = (110 - dimensions[1])/2; 	
	return "padding-top:"+vPadding+"px;padding-bottom:"+vPadding+"px;padding-left:"+hPadding+"px;padding-right:"+hPadding+"px;";
};

/** Calculates the shrunken thumb dimensions and returns them in an array
** @param data Contains the image's data
**/
function getUploaderThumbDimensions(data){
	var percent = 1;
	if(data['thumbWidth'] > 100){
		percent = 100/data['thumbWidth'];
		data['thumbWidth'] = percent * data['thumbWidth'];
		data['thumbHeight'] = percent * data['thumbHeight'];
	};		
	if(data['thumbHeight'] > 100){
		percent = 100/data['thumbHeight'];
		data['thumbWidth'] = percent * data['thumbWidth'];
		data['thumbHeight'] = percent * data['thumbHeight'];
	};		
	return new Array(data['thumbWidth'],data['thumbHeight']);
};

/** Removes an image from the manager
** @param target The target image 
**/
function deleteImageFromManager(target){
	imageManager.splice(target,1);
	refreshImageManager();
	flushDisplay();
};

/** Parses the contents of the upload iframe 
** @param string The string in iframe
**/
function parseUploadReturn(string){
	array = new Array();
	data = string.split("[?]")
	for(var i = 0;i<data.length;i++){
		if(data[i].split("[=]")[1] != undefined){
			array[data[i].split("[=]")[0]] = data[i].split("[=]")[1];	
		};
	}
	
	
	return array;
};


/** Creates the content editor field
** @param title The content to be pre-filled
** @param flush The javascript function to be called to flush any edits to this field
**/
function contentEditor(content){
	if(content == undefined){content = "";};
	var string = "";	
	string += "<h3>"+lang['post_editor_post_content']+"</h3><h4>"+lang['post_editor_optional']+"</h4><textarea onkeyup='flushDisplay();' type='text' id='postContent'>"+parseText(content)+"</textarea>";	
	return string;
};

/** displays the save/cancel controls
** @param submitString the javascript command to be ran when the save button is clicked
**/
function displayControls(submitString){
	return "<div class='controls'><a href='javascript:"+submitString+"' id='postSubmit'>"+lang['post_editor_post_save_post']+"</a><a href='javascript:cancelPostEdit();'>"+lang['post_editor_post_cancel_post']+"</a></div>";
};

/** Cancels the edit and displays the original post **/
function cancelPostEdit(){
	restoreContentArea();
};

/** Displays the category selector **/
function categorySelector(current){
	currentCategory = current;	
	return "<h3>"+lang['post_editor_post_category']+"</h3><h4>"+lang['post_editor_mandatory']+"</h4><div id='categorySelector' class='category_selector'>"+displayCategoryButton()+"</div>";
};

/** Begins the category selection process by loading in the category data **/
function changeCategory(){
	currentCategory = "";
	sendData(Array("action","section"),Array("gatherCategoryListing",database_table),categoriesGathered);
	document.getElementById("categorySelector").innerHTML = loadingAnimation();
	flushDisplay();
};

/** Once the category data is loaded, display the options
** @param data The data array populated by the dataHandler
**/
function categoriesGathered(data){
	var catListing = data['categories'].split(",");	
	var categories = "Choose Category: ";
	for(var i = 0;i<catListing.length;i++){
		categories += "<a href='javascript:selectCategory(\""+catListing[i]+"\");'>"+catListing[i]+"</a>";
	};	
	document.getElementById("categorySelector").innerHTML = categories;	
};

/** Sets the category to the newly selected one and displays it **/
function selectCategory(category){
	currentCategory = category;
	document.getElementById("categorySelector").innerHTML = displayCategoryButton();
	flushDisplay();
};

/** displays the category changer interface **/
function displayCategoryButton(){
	return "Category: <a href='javascript:changeCategory();'>"+currentCategory+"</a>";
};

/** sets the flush function 
** @param newFlush the function to be set as the flush function
**/
function setFlush(newFlush){
	flush = newFlush;
};

/** Flushes the display with updated data **/
function flushDisplay(){
	if(flush != undefined){flush();};
};

/** Deletes a post
** @param id The id value of the post to be deleted
** @param section The section that the post is in
**/
function deletePost(id,section){
	snapShotContentArea();
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();
	sendData(Array("action","id","section"),Array("deletePost",id,database_table),postDeleted);
};

/** Once a post has been deleted, show the option to reverse the delete
** @param data Returned data from the server
**/
function postDeleted(data){
	deletedData = data;
	if(data['error'] == undefined){
		loadTemplate("sub_templates/posts/deleted_post.html",deletedTemplateLoaded);		
	}else{
		restoreContentArea();
	};
};

function deletedTemplateLoaded(data){
	var string = data['template'];
	string = string.replace(/<%post_id%>/g,deletedData['id']);
	string = string.replace(/<%user_id%>/g,deletedData['mid']);
	document.getElementById("primaryContentArea").innerHTML = string;
	restoreDeletedPostControls(data['id'],deletedData['mid'])
	document.getElementById("secondaryContentArea").innerHTML = "";
	//document.getElementById("tertiaryNavButton"+deletedData['id']).innerHTML = "";
	checkForEmptySections();
};

/** Shows the option to restore a post if the user is the owner or admin
** @param id The id of the post to be restored
** @param mid The mid of the original owner
**/
function restoreDeletedPostControls(id,mid){
	if(user_id == mid || section_admin == 1){
		var editor_controls = "";	
		editor_controls += "<a href='javascript:restoreDeletedPost("+id+");'>Restore Post</a>";	
		document.getElementById("postControls").innerHTML = editor_controls;
	};
};

/** Restores a deleted post
** @param id The id of the post to be restored
**/
function restoreDeletedPost(id){
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();
	sendData(Array("action","id","section"),Array("restoreDeletedPost",id,database_table),postRestored);
};

/** Once the post has been restored redirect the user to it
** @param data The data returned from the server (should be empty)
**/
function postRestored(data){
	window.location = window.location;
};

/** Creates a new post (if available the user can choose a post type **/
function newPost(){
	snapShotContentArea();	
	
	if(post_types.length > 1){		
		var postTypes = new Array();
		var postFunctions = new Array();
		
		for(var i = 0;i<post_types.length;i++){			
			postTypes.push(post_types[i]);
			postFunctions.push("new"+post_types[i]+"Post();");
		};
		
		postTypes.push("Cancel");		
		postFunctions.push("");
		
		openWindow("<h1>"+lang['post_editor_post_type']+"</h1>",postTypes,postFunctions,"alert");
	}else{
		eval("new"+post_types[0]+"Post();");
	};	
};var textPostData;// Array | The data brought it from the server when the edit is initialised
var text_post_template = "";
var textPostTarget = "";
var textPostAction = "";

/** Initiates a text post edit, if the templates do not exist load them
** @param postId The id of the post to be edited
**/
function editTextPost(postId){
	textPostTarget = postId;
	textPostAction = "edit";
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();
		loadTemplate("sub_templates/posts/text_post.html",textPostTemplateLoaded);
};

/** When the template has been loaded, load the header template **/
function textPostTemplateLoaded(data){
	text_post_template  = data['template'];
	loadTemplate("sub_templates/emoticons.html",textPostEmoticonTemplatLoaded);
};
	
	
	
function textPostEmoticonTemplatLoaded(data){
	emoticons_template = data['template'];
	if(post_header_template == ""){
		loadTemplate("sub_templates/post_header.html",textPostHeaderTemplateLoaded);
	}else{
		if(textPostTarget == "edit"){
			textPostEditor();
		}else{
			newTextPostEditor();
		};
	};
};

/** Once the header template has been loaded, display the editor **/
function textPostHeaderTemplateLoaded(data){
	post_header_template  = data['template'];
	if(textPostAction == "edit"){
		textPostEditor();
	}else{
		newTextPostEditor();
	};
};

/** Display the editor **/
function textPostEditor(){
	snapShotContentArea();	
	sendData(Array("action","postId","section"),Array("gatherTextPost",textPostTarget,database_table),textPostDataGathered);	
};

/** Displays the editor once the data has been loaded
** @param data Data array passed by the dataHandler
**/
function textPostDataGathered(data){
	textPostData = data;
	var editor_string = "<div class='post_editor'>";	
	
	editor_string += titleEditor(textPostData['title']);
	editor_string += categorySelector(textPostData['category']);	
	editor_string += contentEditor(br2nl(textPostData['content']));
	editor_string += displayControls("saveTextPost("+textPostData['id']+");");	
	editor_string += textPostPreviewPane();	
	editor_string += "</div>";	
	document.getElementById("primaryContentArea").innerHTML = editor_string;
	setFlush(flushTextPostPreview);
	flushDisplay();
};

/** Creates the text post preview page **/
function textPostPreviewPane(){
	return "<div id='postPreview'></div>";	
};

/** Everytime something is typed, refresh the preview and do any data validation **/
function flushTextPostPreview(){
	var textPost = text_post_template;
	var header = post_header_template;	
	textPost = replaceAll(textPost,"<%copy%>",nl2br(parseBB(document.getElementById("postContent").value)));
	header = replaceAll(header,"<%post_title%>",nl2br(parseBB(document.getElementById("postTitle").value)));
	header = replaceAll(header,"<%poster%>",username);
	header = replaceAll(header,"<%date%>",textPostData['date']);
	header = replaceAll(header,"<%category%>",currentCategory);
	header = replaceAll(header,"<%poster_id%>",textPostData['mid']);	
	if(document.getElementById("postTitle").value != "" && document.getElementById("postContent").value != "" && currentCategory != ""){
		document.getElementById("postSubmit").style.visibility = "visible";
	}else{
		document.getElementById("postSubmit").style.visibility = "hidden";
	};	
	document.getElementById("postPreview").innerHTML = "<div class='post_preview'>"+header + textPost+"</div>";
	checkForEmptySections();
};

/** Saves the edited text post
** @param id The id of the post to be saved
**/
function saveTextPost(id){	
	sendData(Array("action","id","section","title","category","content"),Array("saveTextPost",id,database_table,secureText(document.getElementById("postTitle").value),currentCategory,secureText(document.getElementById("postContent").value)),textPostSaved);
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();
};

/** Once the new text post has been saved, display it
** @param data The data array passed by the dataHandler
**/
function textPostSaved(data){
	var textPost = text_post_template;
	var header = post_header_template;
	textPost = replaceAll(textPost,"<%copy%>",nl2br(parseBB(data['content'])));
	header = replaceAll(header,"<%post_title%>",nl2br(parseBB(data['title'])));
	header = replaceAll(header,"<%poster%>",data['poster']);
	header = replaceAll(header,"<%date%>",data['date']);
	header = replaceAll(header,"<%category%>",data['category']);
	header = replaceAll(header,"<%poster_id%>",data['mid']);	
	document.getElementById("primaryContentArea").innerHTML = header + textPost;
	//document.getElementById("tertiaryNavButtonAnchor"+data['id']).innerHTML = nl2br(parseBB(data['title']));
	postControls(data['id'],user_id,"text");
};

/** Launches the new text post editor **/
function newTextPost(){
	textPostAction = "new";
	if(text_post_template == ""){
		loadTemplate("sub_templates/posts/text_post.html",textPostTemplateLoaded);
	}else{
		newTextPostEditor();
	};
};
	
function newTextPostEditor(){
	clearContent();
	textPostData = new Array();
	textPostData['date'] = current_date;
	var editor_string = "<div class='post_editor'>";	
	currentCategory = "";	
	editor_string += titleEditor();
	editor_string += categorySelector();	
	editor_string += contentEditor();
	editor_string += displayControls("saveNewTextPost();");	
	editor_string += textPostPreviewPane();
	editor_string += "</div>";
	document.getElementById("primaryContentArea").innerHTML = editor_string;
	changeCategory();
	setFlush(flushTextPostPreview);
	flushDisplay();
};

/** Saves a new text post **/
function saveNewTextPost(){
	sendData(Array("action","section","title","category","content"),Array("saveNewTextPost",database_table,secureText(document.getElementById("postTitle").value),currentCategory,secureText(document.getElementById("postContent").value)),newTextPostSaved);
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();	
};

/** Once the new text post has been saved, redirect the user to the new post
** @param data The data returned from the server
**/
function newTextPostSaved(data){
	window.location = "index.php?target="+data['id'];
};
function newImagePost(){
	clearContent();
	textPostData = new Array();
	textPostData['date'] = current_date;
	var editor_string = "<div class='post_editor'>";	
	currentCategory = "";	
	editor_string += titleEditor();
	editor_string += categorySelector();
	editor_string += contentEditor();
	editor_string += displayControls("saveNewImagePost();");	
	editor_string += textPostPreviewPane();
	editor_string += "</div>";
	document.getElementById("primaryContentArea").innerHTML = editor_string;
	changeCategory();
	setFlush(flushTextPostPreview);
	flushDisplay();
};var hybrid_post_template = "";
var hybrid_post_image_template = "";
var hybridPostTarget = "";
var hybridPostAction = "";

/** Begins Editing a hybrid post by loading the templates
** @param postId The Id of the post to be edited
**/
function editHybridPost(postId){
	hybridPostTarget = postId;
	hybridPostAction = "edit";
	snapShotContentArea();
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();
	loadTemplate("sub_templates/posts/hybrid_post.html",hybridPostTemplateLoaded);
};

/** Once the main template is loaded, load the image template **/
function hybridPostTemplateLoaded(data){
	hybrid_post_template  = data['template'];
	loadTemplate("sub_templates/posts/hybrid_post_image.html",hybridPostImageTemplateLoaded);
};

/** Once the image tempalte is loeaded, load the header **/
function hybridPostImageTemplateLoaded(data){
	hybrid_post_image_template  = data['template'];
	loadTemplate("sub_templates/emoticons.html",hybridPostEmoticonTemplatLoaded);
};

function hybridPostEmoticonTemplatLoaded(data){
	emoticons_template = data['template'];
	loadTemplate("sub_templates/post_header.html",hybridPostHeaderTemplateLoaded);
};

/** Once the header is loaded, display the editor **/
function hybridPostHeaderTemplateLoaded(data){
	post_header_template  = data['template'];
	if(hybridPostAction == "edit"){
		hybridPostEditor();
	}else{
		newHybridPostEditor();
	};
};

/** The hybrid post editor **/
function hybridPostEditor(){	
	sendData(Array("action","postId","section"),Array("gatherPost",hybridPostTarget,database_table),hybridPostDataGathered);	
};

/** Once the post's data has been gathered, launch the editor
** @param data The data returned from the server
**/
function hybridPostDataGathered(data){
	clearContent();
	textPostData = new Array();
	textPostData['date'] = current_date;
	var editor_string = "<div class='post_editor'>";	
	currentCategory = "";	
	editor_string += titleEditor(data['title']);
	editor_string += categorySelector(data['category']);	
	var contentData = data['content'].split("[~]");	
	editor_string += imageBrowser();	
	editor_string += contentEditor(contentData[1]);
	editor_string += displayControls("saveHybridPost("+data['id']+");");	
	editor_string += textPostPreviewPane();
	editor_string += "</div>";
	document.getElementById("primaryContentArea").innerHTML = editor_string;
	addDefaultImages(contentData[0]);
	setFlush(flushHybridPostPreview);
	flushDisplay();
};

/** Creates a new Hybrid post **/
function newHybridPost(){
	hybridPostAction = "new";
	snapShotContentArea();
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();
	loadTemplate("sub_templates/posts/hybrid_post.html",hybridPostTemplateLoaded);
};

function newHybridPostEditor(){
	clearContent();
	textPostData = new Array();
	textPostData['date'] = current_date;
	var editor_string = "<div class='post_editor'>";	
	currentCategory = "";	
	editor_string += titleEditor();
	editor_string += categorySelector();
	editor_string += imageBrowser();	
	editor_string += contentEditor();
	editor_string += displayControls("saveNewHybridPost();");	
	editor_string += textPostPreviewPane();
	editor_string += "</div>";
	document.getElementById("primaryContentArea").innerHTML = editor_string;
	changeCategory();
	setFlush(flushHybridPostPreview);
	flushDisplay();
};

/** Everytime something is typed, refresh the preview and do any data validation **/
function flushHybridPostPreview(){
	var hybridPost = hybrid_post_template;
	var header = post_header_template;	
	var images = flushHybridPostImages();	
	hybridPost = replaceAll(hybridPost,"<%image%>",images);
	hybridPost = replaceAll(hybridPost,"<%copy%>",nl2br(parseBB(document.getElementById("postContent").value)));
	header = replaceAll(header,"<%post_title%>",nl2br(parseBB(document.getElementById("postTitle").value)));
	header = replaceAll(header,"<%poster%>",username);
	header = replaceAll(header,"<%date%>",textPostData['date']);
	header = replaceAll(header,"<%category%>",currentCategory);
	header = replaceAll(header,"<%poster_id%>",textPostData['mid']);	
	if(document.getElementById("postTitle").value != ""  && currentCategory != ""){
		document.getElementById("postSubmit").style.visibility = "visible";
	}else{
		document.getElementById("postSubmit").style.visibility = "hidden";
	};	
	var post = prepareStringForDisplay(header + hybridPost);
	document.getElementById("postPreview").innerHTML = "<div class='post_preview'>"+post+"</div>";
	checkForEmptySections();
	checkForScripts(post);
	
	
};

/** Loop through and flush the image preview **/
function flushHybridPostImages(){
	var string = "";	
	for(var i = 0;i<imageManager.length;i++){
		var image = hybrid_post_image_template;		
		image = replaceAll(image,"<%id%>",imageManager[i]['id']);
		image = replaceAll(image,"<%mid%>",imageManager[i]['mid']);
		image = replaceAll(image,"<%name%>",imageManager[i]['name']);
		image = replaceAll(image,"<%size%>",imageManager[i]['size']);
		image = replaceAll(image,"<%thumbWidth%>",imageManager[i]['thumbWidth']);
		image = replaceAll(image,"<%thumbHeight%>",imageManager[i]['thumbHeight']);
		string += image;
	};	
	return string;
};

/** Saves the new post **/
function saveNewHybridPost(){
	var images = "";
	for(var i = 0;i<imageManager.length;i++){
		if(i != 0){images += "[,]";};
		images += "[&]id[=]"+imageManager[i]['id']+"[&]mid[=]"+imageManager[i]['mid']+"[&]name[=]"+imageManager[i]['name']+"[&]thumbWidth[=]"+imageManager[i]['thumbWidth']+"[&]thumbHeight[=]"+imageManager[i]['thumbHeight']+"[&]size[=]"+imageManager[i]['size'];
	};
	sendData(Array("action","section","title","category","content","images"),Array("saveNewHybridPost",database_table,secureText(document.getElementById("postTitle").value),currentCategory,secureText(document.getElementById("postContent").value),secureText(images)),newHybridPostSaved);
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();	
};

/** Once the new post has been saved, redirect to it 
** @param data The data from the server
**/
function newHybridPostSaved(data){
	window.location = "index.php?target="+data['id'];
};

/** Begins saving the post
8* @param id The id of post to be saved
**/
function saveHybridPost(id){	
	var images = "";
	for(var i = 0;i<imageManager.length;i++){
		if(i != 0){images += "[,]";};
		images += "[&]id[=]"+imageManager[i]['id']+"[&]mid[=]"+imageManager[i]['mid']+"[&]name[=]"+imageManager[i]['name']+"[&]thumbWidth[=]"+imageManager[i]['thumbWidth']+"[&]thumbHeight[=]"+imageManager[i]['thumbHeight']+"[&]size[=]"+imageManager[i]['size'];
	};
	sendData(Array("action","section","title","category","content","images","id"),Array("saveHybridPost",database_table,secureText(document.getElementById("postTitle").value),currentCategory,secureText(document.getElementById("postContent").value),secureText(images),id),hybridPostSaved);
	document.getElementById("primaryContentArea").innerHTML = loadingAnimation();	
};

/** Once the post has beeen saved, hide the editor and display the post
** @param data The data from the server
**/
function hybridPostSaved(data){
	var textPost = hybrid_post_template;
	var header = post_header_template;
	
	var contentData = data['content'].split("[~]");
	var imagesData = contentData[0].split("[,]");
	
	var img = "";	
	for(var i = 0;i<imagesData.length;i++){
		var image = hybrid_post_image_template;	
		var imageData = parseNameValuePairs(imagesData[i]);
		image = replaceAll(image,"<%id%>",imageData['id']);
		image = replaceAll(image,"<%mid%>",imageData['mid']);
		image = replaceAll(image,"<%name%>",imageData['name']);
		image = replaceAll(image,"<%size%>",imageData['size']);
		image = replaceAll(image,"<%thumbWidth%>",imageData['thumbWidth']);
		image = replaceAll(image,"<%thumbHeight%>",imageData['thumbHeight']);
		img += image;
	};

	textPost = replaceAll(textPost,"<%image%>",img);
	textPost = replaceAll(textPost,"<%copy%>",nl2br(parseBB(contentData[1])));
	header = replaceAll(header,"<%post_title%>",nl2br(parseBB(data['title'])));
	header = replaceAll(header,"<%poster%>",data['poster']);
	header = replaceAll(header,"<%date%>",data['date']);
	header = replaceAll(header,"<%category%>",data['category']);
	header = replaceAll(header,"<%poster_id%>",data['mid']);	
	var post = prepareStringForDisplay(header + textPost);
	document.getElementById("primaryContentArea").innerHTML = post;
	document.getElementById("tertiaryNavButtonAnchor"+data['id']).innerHTML = nl2br(parseBB(data['title']));
	postControls(data['id'],user_id,"hybrid");
	
	checkForScripts(post);
};var ajax; // HTTP Object | Used to communicate with the server
var ajaxTracker; // SetInterval to track load;
var ajaxCount; // How long the current load has been going
var currentDepth = 50000; // Number | A unique number reflecting the current depth of the object ids (started as some stupidly high number to avoid conflic with the backend)

 createConnection();// Called to instantiate the ajax connection upon page load
 
/** Sends data to the server and and starts watching the frame for return 
** @param queryNames An array containing the variables to be added to the query
** @param queryValues An array containing the respective values
** @param cb The callback to be used once the return has been discovered
**/
function sendData(queryNames,queryValues,cb){	
	var query = "send=ajax";	
	for(var i = 0;i<queryNames.length;i++){
		query += "&"+queryNames[i]+"="+queryValues[i];
	};	

 	ajax.open("POST","/API/_javascript_api/ajax_connect.php",true); 
	ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajax.setRequestHeader("Content-length", query.length);
	ajax.setRequestHeader("Connection", "close"); 
 	ajax.send(query);
	ajax.onreadystatechange=function(){	 
		if(ajax.readyState==4){		
			cb(parseReturn(ajax.responseText));
			document.getElementById("topMessage").className = "dead";
			document.getElementById("topMessage").innerHTML = "";	
			document.getElementById("topMessage").style.display = "none";	
		};
	};
	
	count = 0;
	if(ajaxTracker == undefined){ajaxTracker = setInterval(trackLoad,1);};
	
};

/** Tracks the AJAX load **/
function trackLoad(){
	count ++	
	if(count == 1){
		document.getElementById("topMessage").style.top = getScrollPositionY() +"px";
		document.getElementById("topMessage").className = "top_message";
		document.getElementById("topMessage").innerHTML = lang['loading'];
		document.getElementById("topMessage").style.display = "block";	
	};
	if (count == 3000){
		document.getElementById("topMessage").innerHTML = lang['time_out'];
	};
};

/** Parses the data returned from the server
** @param string The string to be parsed
** @returns String
**/
function parseReturn(string){
	var data = Array();
	
	var rawData = string.split("[&]");
	
	for(var i = 0;i<rawData.length;i++){
		var singleData = rawData[i].split("[=]");
		
		if(singleData[1] != undefined){
			singleData[1] = checkForNonStringDataTypes(parseText(singleData[1]));
		};
		
		data[singleData[0]] = singleData[1];
	};
	
	if(data['error'] != undefined){
		displayError(data['error']);
	};
	
	if(data['success'] != "true"){
		displayError(string);
	};	
	
	return data;
};

/** Checks to see if the data is another data type and converts it if needed
** string The string to be analyzed
**/
function checkForNonStringDataTypes(string){
	if(string.substr(0,7) == "[Array]"){
		return string.substr(7).split("[,]");	
	}else{
		return string;
	};
};

/** Removes the current data from the data frame **/
function flushDataFrame(){	
	document.getElementById('data_frame').src = "/API/_javascript_api/mysql_return.php"
};

/** Checks for data inside the frame **/
function checkDataFrame(){	
	if(parseUrlString(frames["data_frame"].location.href)['return'] == "success"){		
		
		if(queryCallbacks[0] != undefined){queryCallbacks[0]();};			
		
		queries.shift();
		queryCallbacks.shift()
		
		flushDataFrame();		
		
		if(queries.length == 0){
			clearInterval(queryInterval);	
		}else{
			runQuery(queries[0]);		
		};		
	};
};

/** Sends the data up to the server
** @param query The compiled query string using name value pairs ( &one=1&two=2 )
**/
function runQuery(query){
	document.getElementById('data_frame').src = "/API/_javascript_api/mysql_query.php?query="+query;
};

/** Removes data protection from a string that is added by the URL bar
** @param returnString The string to be parsed
** @returns String
**/
function parseUrlString(returnedString){	
	var splitUrl = returnedString.split("?");	
	var string = splitUrl[1];
	var varsArray = Array();	
	if(string != null){
		varsArray = string.split("&");	
	};	
	var returnData = Array();	
	var tempArray = Array();	
	for(var i = 0;i < varsArray.length;i++){		
		tempArray = varsArray[i].split("=");
		returnData[tempArray[0]] = decodeUrl(tempArray[1]);
	};
	return returnData	
};

/** Converts all line breaks to <br /> tags 
** str The string to be converted
** @returns String
**/
function nl2br(str) {  
    return (str + '').replace(/([^>]?)\n/g, '$1'+ '<br />');
};

/** Converts all <br/> tags to new lines 
** str The string to be converted
** @returns String
**/
function br2nl(str) { 
    return str.replace(/<br \/>/g,'\n');
};

/** Secures a string for use in query
** @param returnData The string to be secured
** @returns String
**/
function secureText(returnData){		
	returnData = returnData.replace(/&/g,"~amp~");
	returnData = returnData.replace(/"/g,'~quot~');
	returnData = returnData.replace(/'/g,"~rsquo~");
	returnData = returnData.replace(/=/g,"~equal~");
	returnData = returnData.replace(/\\/g,"~bslash~");
	return returnData;
};

/** parses text that was previously secured
** @param returnData The string to be parsed
** @returns String
**/
function parseText(returnData){		
	returnData = returnData.replace(/~amp~/g,"&");
	returnData = returnData.replace(/~quot~/g,'"');
	returnData = returnData.replace(/~rsquo~/g,"'");
	returnData = returnData.replace(/~equal~/g,"=");
	returnData = returnData.replace(/~bslash~/g,"\\");
	return returnData;
};

/** Parses BB code
** @param target The string to be parsed
** @returns String
**/
function parseBB(target){
	target = target.replace(/\[1\]/g,"'");
	target = target.replace(/\[2\]/g,"%");
	target = target.replace(/\[3\]/g,"&");
	target = target.replace(/\[4\]/g,"\"");
	
	if (html_enabled != 1){		
		target = target.replace(/<(.*?)\>/ig, "&lt;$1&gt;");
	};
	
	target = target.replace(/\[b\](.*?)\[\/b\]/ig, "<b>$1</b>");
	target = target.replace(/\[i\](.*?)\[\/i\]/ig, "<i>$1</i>");
	target = target.replace(/\[u\](.*?)\[\/u\]/ig, "<u>$1</u>");
	target = target.replace(/\[center\](.*?)\[\/center\]/ig, "<center>$1</center>");
	target = target.replace(/\[size=(.*?)\](.*?)\[\/size\]/ig, "<span style='font-size:$1px'>$2</span>");
	target = target.replace(/\[color=(.*?)\](.*?)\[\/color\]/ig, "<span style='color:$1'>$2</span>");
	target = target.replace(/\[url=(.*?)\](.*?)\[\/url\]/ig, "<a href='$1' target='_blank'>$2</a>");
	target = target.replace(/\[url\]www\.(.*?)\[\/url\]/ig, "<a href='http://www.$1\">www.$1</a>', target");
	target = target.replace(/\[url\](.*?)\[\/url\]/ig, "<a href='$1\">$1</a>', target");
	
	target = parseEmoticons(target);
	
	return target;
};

/** Loops through a string and swaps in emoticons
** @param string The string to be parsed
** @returns String
**/
function parseEmoticons(string){
	var smiley = "";
	for(var i = 0;i<emoticons_code.length;i++){
		smiley = replaceAll(emoticons_template,"<%emoticon%>",emoticons_emoticons[i]);
		string = replaceAll(string,emoticons_code[i],smiley);
	};
	return string;
};

/** Decodes a string with special characters instead of %hex values
** @param string The string to be decoded
** @returns String
**/
function decodeUrl (string) {
	var output = string;
	  var binVal, thisString;
	  var myregexp = /(%[^%]{2})/;
	  while ((match = myregexp.exec(output)) != null
				 && match.length > 1
				 && match[1] != '') {
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	  }
	  return output;
}

/** Encodes a string with %hex values instead of special characters
** @param string The string to be encoded
** @returns String
**/
function encodeUrl (string) {
  var output = '';
  var x = 0;
  string = string.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < string.length) {
    var match = regex.exec(string.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (string[x] == ' ')
        output += '+';
      else {
        var charCode = string.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      };
      x++;
    };
  };
  return output;
};


//Instantiates the ajax connection to the server
function createConnection(){		
	try  {
	  ajax=new XMLHttpRequest();
	}catch (e){
		try{
			ajax=new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e){
			try {
				ajax=new ActiveXObject("Microsoft.XMLHTTP");
			}catch (e){
				displayError("You're browser does not support AJAX, please update to the latest version of Firefox, Chrome, Safari, Internet Explorer, or Opera to use jitZul.");
				return false;
			};
		};
	};
 };
 
 /** checks a string to see if it has any <script> tags and calls the code inside
 ** @param string The desired string
 **/
 function checkForScripts(string){
	 var scripts = string.match(/\<script type="text\/javascript"\>(.*?)\<\/script\>/gi);	
	string = "";
	if(scripts != null){
		for(var i=0;i<scripts.length;i++){
			var cmd = scripts[i].substr(31,scripts[i].length-40);
			eval(cmd);			
		};	
	};	
 };
 
/** Prepares a string for post to the brower
** @param string The string to prepare
** @returns String
**/
 function prepareStringForDisplay(string){		
		string = swapInDepths(string);		
		return string;
 };

/** Swaps in depths variables for a true depth, all <%n#%>  and all subsequent <%#%> (until a new <%n#%> is found) with a unique depth id
** @param string The string to swap ids into
** @returns String
**/
function swapInDepths(string){
	var strings = string.split("<%n#%>");		
	var newStr = "";
	for(var i = 1;i<strings.length;i++){
		currentDepth ++;
		newStr += "IID"+currentDepth + strings[i].replace(/\<%#%>/g,"IID"+currentDepth);
	};
	return strings[0]+newStr;
};



 var windowsOpen = 0; // Number | How many windows are currently open
var alertCommands; // Array | The current set of alert commands
var keyCodes = new Array(); // Array | A list of key code for the keyboard event manager
var keyCommands = new Array(); // Array | A list of key commands for the keyboard event manager
var cellSheetManagerCol; // Number | The column ID that is currently selected
var cellSheetManagerRow; // Number | The row ID that is currently selected
var cellSheetManagerTarget; // String | The id of the table to be used
var cellSheetManagerScrollField; // Object | The Field that handles the scrolling for the page
var deleteBoxId = 0; // Number | The id of the currently created delete box
var deleteCommand = new Array(); // Array | An array of delete commands
var imagesToPreload = new Array("/templates/images/main_nav_roll_over.jpg","/templates/images/buttons/yellow_button_right_over.jpg","/templates/images/buttons/yellow_button_left_over.jpg");


function addLeftColumnFiller(){
	if(document.getElementById('leftColumnFillerHolder') != undefined){
		var rightCol = document.getElementById('standardSectionRightColumn').offsetHeight;
		var leftCol = document.getElementById('standardSectionLeftColumn').offsetHeight;
		
		if(leftCol < rightCol){
			document.getElementById('leftColumnFillerHolder').className = "visible";
			document.getElementById('leftColumnFiller').style.height = (rightCol-leftCol-document.getElementById('leftColumnFillerHolder').offsetHeight-1)+"px";
		};
	};
};


function bustFrames(){
	if (top.location != self.location) top.location.replace(self.location+"&google_images=true");
};


function checkBrowser(){
	if (document.all && !window.opera && !window.XMLHttpRequest) {
		document.getElementById('alertMessage').innerHTML = lang['ie6'];
		document.getElementById('alertMessage').className = "alert_message";
		document.body.scrollTop = 0;
	};
};

function bodyLoad(){
	checkBrowser();
	addLeftColumnFiller();
	if(GoogleImages != undefined){		
		bustFrames();
		if(google_images){
			GoogleImages();
		};
	};
};

function preloadImages(){
	for(var i = 0;i<imagesToPreload.length;i++){
		var temp = new Image();
		temp.src = imagesToPreload[i];
	};
};


/** Returns the user to the homepage **/
function returnHome(){
	goToURL("/");
};

function goToURL(target){
	window.location = target;
};

/** Creates a delete button with confirmation
** @param command What is to be places in the href of the confirmation 
**/
function createDelete(command){
	deleteBoxId ++;
	string = "<a href='javascript:confirmDelete("+deleteBoxId+")'>"+lang['delete']+"</a>";
	deleteCommand["del"+deleteBoxId] = command
	return string;
};


/** Displays the delete confirmation
** @param deleteBoxId The id number of the delete box to have it's confirmation shown
**/	
function confirmDelete(deleteBoxId){
	openWindow("<h1>"+lang['delete_confirm']+"</h1>",new Array(lang['delete_yes'],lang['delete_no']),new Array(deleteCommand["del"+deleteBoxId],""),"alert");
};

/** Displays a preset loading animation 
** @param loader Which loading animation to use
**/
function loadingAnimation(loader){
	if(loader == undefined){loader = 1;};
	return "<div class='loading_holder'><img src='/templates/images/loading/animation_"+loader+".gif' /></div>";
};

/** Displays a window with the loading animation **/
function loadingWindow(message){
	openWindow("<h1>"+message+"</h1><img src='/templates/images/loading/animation_1.gif' class='loading_window_img' />",new Array(),new Array(),"alert");
};

/** Closes the current loading window **/
function closeLoadingWindow(){
	closeWindow("alert");
};

/** Removes all visisble CSS properties from a div, essentialy making it non existant
** @param divId The id of the div to be killed
**/
function killDiv(divId){
	document.getElementById(divId).className  = "dead";
};

/** Searches through a string and replaces all instances of one sting, with another sting (replaces the normal replace method in that it does not require regexp to replace all version, thus allowing you to store the findString in a variable
** @param string The string to be searched through
** @param findString The string that will be swapped out
** @param newString The string that will be swapped in
** @returns String
**/
function replaceAll(string,findString,newString){
	while (string.indexOf(findString) > -1){
		string = string.replace(findString,newString);
	};
		
	return string;
};

/** Converts the first letter of the string to caps
** @param string The string to be converted
** @returns String
**/
function firstLetterToCap(string){
	string = string.substring(0,1).toUpperCase() + string.substring(1,string.length);	
	return string;
};

/** Takes a snapshop of the current content area in case in needs to be later restored **/
var contentsOfContentArea = "";
var contentsOfSecondaryContentArea = "";
function snapShotContentArea(){
	contentsOfContentArea = document.getElementById("primaryContentArea").innerHTML;
	contentsOfSecondaryContentArea = document.getElementById("secondaryContentArea").innerHTML;
};

/** Restores a prevously taken snapshop of the content area **/
function restoreContentArea(){
	document.getElementById("primaryContentArea").innerHTML = contentsOfContentArea;
	document.getElementById("secondaryContentArea").innerHTML = contentsOfSecondaryContentArea;
};

/** Clears all the content in the main content areas **/
function clearContent(){
	document.getElementById("primaryContentArea").innerHTML = "";
	document.getElementById("secondaryContentArea").innerHTML = "";
};

/** Displays an error in an alert window
** @param error The desired error message
**/
function displayError(error){
	openWindow("<h1>"+lang['error']+"</h1><h2>"+error+"</h2>",new Array("Ok"),new Array(""),"error");
	if(contentsOfContentArea != ""){restoreContentArea();};
};

/** Creates and opens a new window
** @param contents The desired contents of the window
** @param buttons An array of strings to be used as button copy
** @param buttonCommands An array of strngs containing javascript functions to be called when the buttons are clicked
** @param type The type of window to be displayed, for example, alert or admin
**/
function openWindow(contents,buttons,buttonCommands,type){	
	document.getElementById(type+"WindowBg").className = type+"_window_bg";
	document.getElementById(type+"Window").className = type+"_window";
	
	
	var string = contents;
	
	string += "<div class='window_controls'>";
	for(var i = 0;i<buttons.length;i++){
		string += "<a href='javascript:"+buttonCommands[i]+"closeWindow(\""+type+"\");'>"+buttons[i]+"</a>";	
	}
	string += "</div>";
	
	document.getElementById(type+"Window").innerHTML = string;
	
	document.getElementById(type+"WindowBg").style.top = getScrollPositionY() +"px";
	document.getElementById(type+"Window").style.top = (getScrollPositionY() + document.getElementById(type+"WindowBg").offsetHeight/2 - document.getElementById(type+"Window").offsetHeight/2) + "px";
	document.getElementById(type+"Window").style.left = (getScrollPositionX() + document.getElementById(type+"WindowBg").offsetWidth/2 - document.getElementById(type+"Window").offsetWidth/2) + "px";
	windowsOpen ++;	
	if(windowsOpen == 1){
		document.body.style.overflow = "hidden";
	};
	
	if(type == "alert"){
		//addKeyEvent(13,buttonCommands[0]+"closeWindow('alert');");
		addKeyEvent(27,buttonCommands[buttonCommands.length-1]+"closeWindow('alert');");
		cellSheetManagerDisable();
		alertCommands = buttonCommands;
	};
};

/** Closes an open window
** @param Type The window's type
**/
function closeWindow(type){
	document.getElementById(type+"WindowBg").className = "";
	document.getElementById(type+"Window").className = "";
	//document.body.style.overflow = "auto";
	document.getElementById(type+"Window").innerHTML = "";
	
	windowsOpen --;
	if(windowsOpen == 0){
		document.body.style.overflow = "auto";
	};
	
	if(type == "alert"){
	//	removeKeyEvent(13,alertCommands[0]+"closeWindow('alert');");
	removeKeyEvent(27,alertCommands[alertCommands.length-1]+"closeWindow('alert');");
		cellSheetManagerEnable();
	};
	
};

/** Gets the current Y scroll position on the page
** @returns Number
**/
function getScrollPositionY() {
	return window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
};

/** Gets the current X scroll position on the page
** @returns Number
**/
function getScrollPositionX() {
	return window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
};

/** Converts a number date string (ex 091231) to a more readable one (ex 12/31/2009)
** @param string The string to convert
** @returns String
**/
function convertNumberDate(string){
	return string.substr(2,2)+"/"+string.substr(4,2)+"/20"+string.substr(0,2);
};


/** Checks to see if a string is empty, and if it is, place a space in the string
** @param target The string to be checked
**/
function replaceEmptyStringWithSpace(target){
	if(target == ""){
		return "&nbsp";
	}else{
		return target;
	};
};

/** Opens the benchMarking tool window **/
function openBenchMark(){
	var list = bench_mark_data.split(",");
	var string = "<h1>"+lang['benchMarking']+"</h1><table class='benchMark_table'>";	
	var total = list[list.length-2].split(":")[1];	
	for(var i=0;i<list.length-1;i++){
		var data = list[i].split(":");
		string += "<tr><th>"+data[0]+"</th><td>"+data[1]+"</td><td>"+Math.round(data[1]/total*100);
		string += "%</td></tr>";
	};	
	string += "</table>";	
	openWindow(string,new Array("Close"),new Array(""),"alert");
};

/** Parses a set of name value pairs
** @param $string Contains the name value pairs seperated by [&] and [=]
** @retruns Array
**/
function parseNameValuePairs(string){
	array = new Array();
	
	if(string != undefined){	
		var data = string.split("[&]");
		for(var i = 0;i<data.length;i++){
			var singleData = data[i].split("[=]");
			array[singleData[0]] = singleData[1];	
		};	
	};
	return array;
};

/** checks to see if any sections are emppty and hide's their containers **/
function checkForEmptySections(){
	var sectionsToCheck = new Array("primaryContentArea","secondaryContentArea");
	for(var i = 0;i<sectionsToCheck.length;i++){		
		if(trim(document.getElementById(sectionsToCheck[i]).innerHTML) == ""){
			document.getElementById(sectionsToCheck[i]+"Container").style.display = "none";	
		}else{
			document.getElementById(sectionsToCheck[i]+"Container").style.display = "block";	
		};
	};
};

/** Trims from the front and back of a string
** @param str The desired string
** @param chars Any characters to ignore
**/
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
};
 
/** Trims from the front of a string
** @param str The desired string
** @param chars Any characters to ignore
**/
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
};
 
 /** Trims from the back of a string
** @param str The desired string
** @param chars Any characters to ignore
**/
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
};

/** If the user hand unread mail, display the icon
** @param count How many unread msgs the user has
**/
function userInbox(count){
	if(count > 0){
		document.getElementById("mainTemplateHeader").innerHTML += "<div class='mail_icon'><a href='http://www.jitzul.com/fanCentral/index.php?action=pm'><img src='/templates/images/icons/mail_icon.png' /></a></div>";
	};
};

function loadTemplate(target,callback){
	sendData(Array("action","target"),Array("gatherTemplate","/templates/"+target),callback);
};

/** Adds the clone method to an array **/
Object.prototype.clone = function () {var o = new Object(); for (var property in this) {o[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return o}

Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}

keyEventManager();

/** Manages Keyboard events **/
function keyEventManager(){
	document.onkeydown = keyEvent;
};

/** Adds a key event to the keyboard event manager 
* @param code The numeric value of the key to be listened for
* @param command A string containing the code to be resolved once the event has been triggered
**/
function addKeyEvent(code,command){
	var exists = false;
	for(var i = 0;i<keyCodes.length;i++){
		if(code == keyCodes[i] && command == keyCommands[i]){
			exists = true;
		};
	};
	if(exists != true){
		keyCodes.push(code);
		keyCommands.push(command);
	};
};

/** Removes a key event to the keyboard event manager 
* @param code The numeric value of the key to be listened for
* @param command A string containing the code to be resolved once the event has been triggered
**/
function removeKeyEvent(code,command){
	var newCodes = Array();
	var newCommands = Array();
	
	for(var i = 0;i<keyCodes.length;i++){
		if(code == keyCodes[i] && command == keyCommands[i]){
			//keyCodes.splice(i,1);
		//	keyCommands.splice(i,1);
		}else{
			newCodes.push(keyCodes[i]);
			newCommands.push(keyCommands[i]);
		}
	};
	keyCodes = newCodes;
	keyCommands = newCommands;
};

/** When a key event is registered, check to see if it matches any of the listeners 
* @param evt Contains the event data
**/
function keyEvent(evt){
	for(var i = 0;i<keyCodes.length;i++){
		if(evt.keyCode == keyCodes[i]){
			eval(keyCommands[i]);
		};
	};
};

/** Launches the cellsheet manager
** @param target The desired table to be managed
** @param scrollField The desired scroll field that contains the table
** @param column The default column to be selected
** @param row The default row to be selected
**/
function cellSheetManager(target,scrollField,column,row){
	cellSheetManagerTarget = target;
	cellSheetManagerScrollField = scrollField;
	if(column == undefined){
		cellSheetManagerCol = 0;
	}else{
		cellSheetManagerCol = column;
	};
	if(row == undefined){
		cellSheetManagerRow = 1;
	}else{
		cellSheetManagerRow = row;
	};
	cellSheetManagerSelectCell(cellSheetManagerCol,cellSheetManagerRow);	
	cellSheetManagerEnable();
};

/** Disables the cellsheet manager **/
function cellSheetManagerDisable(){
	removeKeyEvent(39,"cellSheetManagerSlideCell(1,0);");
	removeKeyEvent(37,"cellSheetManagerSlideCell(-1,0);");
	removeKeyEvent(40,"cellSheetManagerSlideCell(0,1);");
	removeKeyEvent(38,"cellSheetManagerSlideCell(0,-1);");
	removeKeyEvent(16,"cellSheetManagerActivateCell();");
};

/** Enables the cellsheet manager **/
function cellSheetManagerEnable(){
	addKeyEvent(39,"cellSheetManagerSlideCell(1,0);");
	addKeyEvent(37,"cellSheetManagerSlideCell(-1,0);");
	addKeyEvent(40,"cellSheetManagerSlideCell(0,1);");
	addKeyEvent(38,"cellSheetManagerSlideCell(0,-1);");
	addKeyEvent(16,"cellSheetManagerActivateCell();");
};

/** Selects a specific cell on the table
** @param column The column of the cell
** @param row The row of the cell
**/
function cellSheetManagerSelectCell(column,row){
	if(cellSheetManagerCol != undefined){
		document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[cellSheetManagerRow].getElementsByTagName("td")[cellSheetManagerCol].className = "";
	};	
	if(row > document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr").length-1){
		row = 1;
	};
	if(row < 1){
		row = document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr").length-1;
	};	
	if(column > document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td").length-1){
		column = 0;
	};
	if(column < 0){
		column = document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td").length-1;
	};	
	document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].className = "selected";	
	cellSheetManagerRow = row;
	cellSheetManagerCol = column;
	cellSheetManagerScrollToCell(column,row);	
	document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].focus();
};

/** Slides the current selected cell
** @param column How many columns to slide it by
** @param row How many rows to slide it by
**/
function cellSheetManagerSlideCell(column,row){
	cellSheetManagerSelectCell(cellSheetManagerCol+column,cellSheetManagerRow+row);
};

/** Activates the contents of the current cell **/
function cellSheetManagerActivateCell(){	
	//eval(document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[cellSheetManagerRow].getElementsByTagName("td")[cellSheetManagerCol].getElementsByTagName("a")[0].href.substr(11));
};

/** Scrolls the page to a cell 
** @param column The column of the cell
** @param row The row of the cell
**/
function cellSheetManagerScrollToCell(column,row){
	var cellPos = cellSheetManagerGetCellPosition(document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column]);	
	if(cellPos>(cellSheetManagerScrollField.scrollTop + cellSheetManagerScrollField.offsetHeight - document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].offsetHeight)){
		cellSheetManagerScrollField.scrollTop = cellPos - cellSheetManagerScrollField.offsetHeight + document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].offsetHeight;	};
	
	if(cellPos<cellSheetManagerScrollField.scrollTop){
		cellSheetManagerScrollField.scrollTop = cellPos;
	};
}

/** returns the Y position of a cell
** @param cell The desired cell
** @returns Number
**/
function cellSheetManagerGetCellPosition (cell) {
    var cellPos = 0;
    while (cell) {
      cellPos += cell.offsetTop;
      cell = cell.offsetParent;
    };	
	var field = cellSheetManagerScrollField;
	var fieldPos = 0;
	while (field) {
      fieldPos += field.offsetTop;
      field = field.offsetParent;
    };
    return cellPos-fieldPos;
}

/** Capitalized the first letter of a string
** @param string The desired string
**/
function cap(string) {		
		return string.substring(0,1).toUpperCase() + string.substring(1)		
};

/** Loops through the imagesToPreload array and loads those images **/
preLoadImages();
function preLoadImages(){
	for(var i=0;i<imagesToPreload.length;i++){
		var pic = new Image();
		pic.src = imagesToPreload[i]; 
	};
};

/** Preloads an image and resizes it if needed
** @param target The id of the image to be loaded
** @optionalParam class A class associated with the image
** @optionalParam maxWidth The maximum width the image can be
** @optionalParam maxHeight The maximum height the image can be
** @optionalParam linkToOriginal If the image has been resized, link to the original one
**/
var jitSitesDomain = 0;
function displayImage(target,cssClass,maxWidth,maxHeight,linkToOriginal){	
	var imagePath = document.getElementById(target).src;
	var originalImage = document.getElementById(target).src;
	
	if(imagePath.substr(0,25) == "http://media.jitsites.com"){
		
		jitSitesDomain = (jitSitesDomain-1)*-1;
		imagePath = "http://media"+jitSitesDomain+".jitsites.com/imageLoader.php?target="+imagePath.substr(26)+"&width="+maxWidth+"&height="+maxHeight;
	}else if(imagePath.substr(0,35) == "http://"+locale+".jitzul.com/images"){
		imagePath = "http://"+locale+".jitzul.com/images/imageLoader.php?target="+imagePath.substr(36)+"&width="+maxWidth+"&height="+maxHeight;
	}else if(imagePath.substr(0,28) == "http://"+locale+".jitzul.com/images"){
		imagePath = "http://"+locale+".jitzul.com/images/imageLoader.php?target="+imagePath.substr(29)+"&width="+maxWidth+"&height="+maxHeight;
	};
	
	document.getElementById(target).src = "/templates/images/empty.gif";
	document.getElementById(target).className = "dead";
	var image = new Image();
	image.onload = function (){		
		
		var width = image.width;
		var height = image.height;		
		if(maxWidth != undefined && maxHeight != undefined){
			var percent;
			if(width > maxWidth){
				percent = maxWidth/width;
				width = width*percent;
				height = height*percent;	
			};
			if(height > maxHeight){
				percent = maxHeight/height;
				width = width*percent;
				height = height*percent;
			};
		};		
		document.getElementById(target).src = imagePath;
		document.getElementById(target).width = width;
		document.getElementById(target).height = height
		if(cssClass != undefined){document.getElementById(target).className = cssClass};		
		if(linkToOriginal){
			document.getElementById(target).onclick = function(){
				openPopUp(originalImage);
			};				
			document.getElementById(target).onmouseover = function(){
				document.getElementById(target).style.cursor="pointer";
			};
		};
	};	
	image.src = imagePath;
};


/** Opens a popup window
** @param url The desired URL of the item in the popup
**/
function openPopUp(url){
	window.open(url,"_blank", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0');
};



/** If the user is logged in, display the report button **/
function ticketButton(){
	if(username != "" && username != undefined){
		document.getElementById("ticketButton").innerHTML = "<a href='javascript:newTicket();'>"+lang['ticket_manager_button']+"</a>";
	};		
};

/** Begins the new ticket process by opening the prompt **/
function newTicket(){
	openWindow("<h1>"+lang['ticket_manager_new_ticket']+"</h1><h2>"+lang['ticket_manager_new_ticket_tip']+"</h2><textarea id='newTicketInput' class='new_ticket_text_area'></textarea>",new Array(lang['ticket_manager_submit_new_ticket'],lang['cancel']),new Array("saveNewTicket();",""),"alert");
	document.getElementById("newTicketInput").focus();
};

/** Gathers the browser info and saves the ticket **/
function saveNewTicket(){
	var browserInfo = navigator.appName + ", "+ navigator.appCodeName + " " + navigator.appVersion + "<br /><b>Cookies: </b>" + navigator.cookieEnabled + " <b>OS: </b>" + navigator.platform + " <b>userAgent:</b>" + navigator.userAgent + " <b>js: </b>" + navigator.javaEnabled();
	if(document.getElementById("newTicketInput").value != ""){
		sendData(Array("action","contents","browser","url"),Array("saveNewTicket",secureText(document.getElementById("newTicketInput").value),secureText(browserInfo),secureText(location.href)),newTicketSaved);
	};
};

/** Once the ticket has been saved, provide the user with confirmation **/
function newTicketSaved(data){
	openWindow("<h1>"+lang['ticket_manager_submit_new_ticket_success']+"</h1>",new Array(lang['ok']),new Array(""),"alert");
};/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;