/*
*/

var post_url = "/ajax_video_discussion_thread/";
var current_display_child = GenerateUniqueId();
var display_style = 2;
var current_page = 0;
var page_count = 0;

function ParseXMLErrors( response )
{
	var retval = new Array();
	
	// Get the thread of the response
	var error_element = response.getElementsByTagName( 'thread' );
	var error_counter = 0;
	
	if ( error_element.length != 0 )
	{
		var errors = error_element[0].getElementsByTagName( 'error' );
		
		// Loop through all of the comments for the thread
		while ( errors[error_counter] )
		{
			data = new Array();
			
			// todo: check to see if the text value is going to be bigger than 1k, because if so then Firefox needs a workaround
			data['text'] = errors[error_counter].firstChild.nodeValue;
			
			retval.push( data );
			
			error_counter++;
		}
	}
	
	return retval;
}

function ParseXMLData( response )
{
	var retval = new Array();
	
	// Get the thread of the response
	// todo not dealing with the possibility of there not being a 'thread'
	var thread = response.getElementsByTagName( 'thread' );
	var post_counter = 0;
	
	// If we don't have any comments, then return with nothing
	if ( thread.length == 0 )
		return retval;
	
	// Update our counters for the current_page and page_count
	current_page = thread[0].getAttribute( "page" );
	page_count = thread[0].getAttribute( "page_count" );
	
	// All of the comments will be in the first thread
	var comments = thread[0].getElementsByTagName( 'comment' );
	
	// Loop through all of the comments for the thread
	while ( comments[post_counter] != null )
	{
		data = new Array();
		
		// todo: check to see if the text value is going to be bigger than 1k, because if so then Firefox needs a workaround
		data['postid'] = comments[post_counter].getAttribute( "postid" );
		data['username'] = comments[post_counter].getAttribute( "username" );
		data['avatar'] = comments[post_counter].getAttribute( "avatar" );
		data['display_name'] = comments[post_counter].getAttribute( "display_name" );
		data['post_date'] = comments[post_counter].getAttribute( "post_date" );
		data['text'] = comments[post_counter].firstChild.nodeValue;
		
		retval.push( data );
		
		post_counter++;
	}
	
	return retval;
}

// Update the page's display
function UpdateDisplay( response )
{
	if( response.responseXML == null )
	{
//		alert( "Error:\n" + response.responseText );
		return;
	}
	
	// Get a handle on the page object we are updating
	var container = document.getElementById( "video_discussion_thread" );
	
	// Create the new contents that we want to add to the page
	var contents = document.createElement( 'div' );
	var content_string = "";
	var new_id = GenerateUniqueId();
	contents.setAttribute( "id", new_id );
	
	// Check to see if there are 
	var errors = ParseXMLErrors( response.responseXML );
	
	// If we have any errors to display, format them and add them to the contents that we'll replace into the page
	content_string = content_string + FormatErrors( errors );
	
	// Parse the XML comments into something more readable
	var comments = ParseXMLData( response.responseXML );
	
	content_string = content_string + FormatComments( comments );
	
	// Get the new pagination block
	
	content_string = content_string + RenderPagination();
	
	// Get the comment box, or perhaps login box
	content_string = content_string + RenderCommentBox();
	
	// Now set all of the new HTML 
	contents.innerHTML = content_string;
	
	// Check to see if there is something already existing, and if so remove it
	var old_contents = document.getElementById( current_display_child );
	
	if ( old_contents )
	{
		container.removeChild( old_contents );
	}
	
	// Append the new stuff to the page
	container.appendChild( contents );
	
	// And update the current child id
	current_display_child = new_id;
}

function RenderPagination()
{
	var retval = "";
	
	// If we have no pages to display, or only one page, don't show a paginator
	if ( page_count == 0 || page_count == 1 )
		return retval;
	
	if ( display_style == 1 )
	{
		retval = retval + "<div class=\"altrows_row1 video_discussion_thread_pager\">";
		
		display_style = 2;
	}
	else
	{
		retval = retval + "<div class=\"altrows_row2 video_discussion_thread_pager\">";
		
		display_style = 1;
	}
	
	var display_current_page = current_page * 1 + 1;
	
	// New paginator for the upgraded pagination module
	retval = retval + "<div class=\"pagination_wrapper\">";
	
	// Show a link to the first page?
	if ( current_page >= 5 && page_count >= 10 )
	{
		retval = retval + "<a href=\"#\" onClick=\"RequestPageOfComments( 0 ); return false;\">";
		retval = retval + "<span class=\"pagination_button_left\">&nbsp;</span><span class=\"pagination_button_middle\">1</span>";
		retval = retval + "<span class=\"pagination_button_right\">&nbsp;</span></a>";
		retval = retval + "<span class=\"pagination_elipses\">...</span>";
	}
	
	// Figure out how many page links we're going to show, and then display them in a big loop
	var starting_page = 1;
	var display_count = 1;
	
	// First, start off with the case of <10 pages
	if ( page_count > 1 && page_count < 10 )
	{
		// This is the easiest case
		starting_page = 1;
		display_count = parseInt( page_count );
	}
	
	// Do we have lots of pages and are at the beginning?
	if ( page_count >= 10 && current_page <= 4 )
	{
		// This will probably be the common case for things that start getting popular
		starting_page = 1;
		display_count = 6;
	}
	
	// Are we in the middle of everything?
	if ( page_count >= 10 && current_page >= 5 && current_page < page_count - 4 )
	{
		starting_page = current_page - 2;
		display_count = 6;
	}
	
	// Are we getting rid of the ending elipses? We show one more page link with this case
	if ( page_count >= 10 && current_page == page_count - 4 )
	{
		starting_page = current_page - 2;
		display_count = 7;
	}
	
	// Farther along than that, we go back to only 6 patge links
	if ( page_count >= 10 && current_page >= page_count - 3 )
	{
		starting_page = page_count - 5;
		display_count = 6;
	}
	
	// Run through the correct number of pages, setting the template variables needed to show all of the pages
	var this_page = starting_page;
	var end_page = starting_page + display_count - 1;
	
	for ( this_page = starting_page; this_page <= end_page; this_page++ )
	{
		if ( this_page == display_current_page ) {
			retval = retval + "<span class=\"pagination_current_page\"><span class=\"pagination_button_left\">&nbsp;</span>";
			retval = retval + "<span class=\"pagination_button_middle\">" + this_page + "</span>";
			retval = retval + "<span class=\"pagination_button_right\">&nbsp;</span></span>";
		} else {
			retval = retval + "<a href=\"#\" onClick=\"RequestPageOfComments( " + ( this_page - 1 ) + " ); return false;\"><span class=\"pagination_button_left\">&nbsp;</span>";
			retval = retval + "<span class=\"pagination_button_middle\">" + this_page + "</span>";
			retval = retval + "<span class=\"pagination_button_right\">&nbsp;</span></a>";
		}
	}
	
	// Show a link to the last page?
	if ( ( display_current_page <= page_count - 4 ) && page_count >= 10 )
	{
		retval = retval + "<span class=\"pagination_elipses\">...</span>";
		retval = retval + "<a href=\"#\" onClick=\"RequestPageOfComments( " + page_count  + " ); return false;\"><span class=\"pagination_button_left\">&nbsp;</span>";
		retval = retval + "<span class=\"pagination_button_middle\">" + page_count  + "</span>";
		retval = retval + "<span class=\"pagination_button_right\">&nbsp;</span></a>";
	}
	
	// Show a spacer button if we show either the previous or next links
	if ( ( display_current_page > 1 || display_current_page < page_count ) && page_count >= 10 )
	{
		retval = retval + "<span class=\"pagination_link_spacer\"></span>";
	}
		
	// Show a 'previous' link?
	if ( display_current_page > 1 && page_count >= 10 )
	{
		retval = retval + "<a href=\"#\" onClick=\"RequestPageOfComments( " + ( current_page * 1 - 1 ) + " ); return false;\"><span class=\"pagination_button_left\">&nbsp;</span>";
		retval = retval + "<span class=\"pagination_button_middle\">" + prev_string + "</span>";
		retval = retval + "<span class=\"pagination_button_right\">&nbsp;</span></a>";
	}
	
	// Show a 'next' link?
	if ( display_current_page < page_count && page_count >= 10 )
	{
		retval = retval + "&nbsp;<a href=\"#\" onClick=\"RequestPageOfComments( " + ( current_page * 1 + 1 ) + " ); return false;\"><span class=\"pagination_button_left\">&nbsp;</span>";
		retval = retval + "<span class=\"pagination_button_middle\">" + next_string + "</span>";
		retval = retval + "<span class=\"pagination_button_right\">&nbsp;</span></a>";
	}
	
	// End of the pagination
	retval = retval + "</div>";
	
	return retval;
}

// Update the comment box row
function RenderCommentBox()
{
	var retval = "";
	
	// If we have a username, display the comment box. Otherwise display a link to login
	if ( username != "" )
	{
		if ( allowed_to_post )
		{
			if ( display_style == 1 )
			{
				retval = retval + "<div class=\"altrows_row1 video_discussion_thread_comment_box\">";
			}
			else
			{
				retval = retval + "<div class=\"altrows_row2 video_discussion_thread_comment_box\">";
			}
		
			retval = retval + "<textarea id=\"comment_text\"></textarea><br />";
			retval = retval + "<p>" + bbcode_allowed_string + "</p>";
			retval = retval + "<input type=\"submit\" onClick=\"PostComment(); return false;\" value=\"" + submit_string + "\" />";
			retval = retval + "</div>";
		
			if ( display_style == 1 )
				display_style = 2;
			else
				display_style = 1;
		}
	}
	else
	{
		if ( display_style == 1 )
		{
			retval = retval + "<div class=\"altrows_row1 video_discussion_thread_login\">";
		}
		else
		{
			retval = retval + "<div class=\"altrows_row2 video_discussion_thread_login\">";
		}
		
		retval = retval + "<a href='/login/?redirect=/video/" + video_hexid  + "/'>" + login_string + "</a></div>";
		
		if ( display_style == 1 )
			display_style = 2;
		else
			display_style = 1;
	}
	
	// Return the rendered text
	return retval;
}

// View the given page's worth of comments
// 0 - first page
// -1 - last page
// anything else, view that page
function RequestPageOfComments( page )
{
	//todo: check boundaries
	
	//
	var params = {
		'videoid':videoid,
		'action':'view_comments',
		'page':page
	}
	
	ResetGlobals();
	
	AjaxRequest.post(
		{
			'url':post_url,
			'parameters':params,
			'onSuccess':UpdateDisplay,
			'generateUniqueUrl': true
		}
	);
}

// Get a dump of the pagination module
function RequestPagination( page )
{

}

function PostComment()
{
	// Get the textarea to find out what it has for text
	var comment_box = document.getElementById( 'comment_text' );
	var post_text = comment_box.value;
	post_text = post_text.substring( 0, 2048 );
	
	// Set up the parameters to post
	var params = {
		'videoid':videoid,
		'action':'post_comment',
		'post_text':post_text
	}
	
	ResetGlobals();
	
	AjaxRequest.post(
		{
			'url':post_url,
			'parameters':params,
			'onSuccess':UpdateDisplay,
			'generateUniqueUrl': true
		}
	);
}

function DeleteComment( postid )
{
	// Set up the parameters to post
	var params = {
		'videoid':videoid,
		'action':'delete_comment',
		'postid':postid,
		'page':current_page
	}
	
	ResetGlobals();
	
	AjaxRequest.post(
		{
			'url':post_url,
			'parameters':params,
			'onSuccess':UpdateDisplay,
			'generateUniqueUrl': true
		}
	);
}

function FormatErrors( errors )
{
	var retval = "";
	
	for ( var item in errors )
	{
		retval = retval + FormatError( errors[item] );
		
		if ( display_style == 1 )
			display_style = 2;
		else
			display_style = 1;
	}
	
	return retval;
}

function FormatError( error )
{
	var retval = "";
	
	if ( display_style == 1 )
	{
		retval = retval + "<div class='altrows_row1'><div class='video_discussion_thread_error'>";
	}
	else
	{
		retval = retval + "<div class='altrows_row2'><div class='video_discussion_thread_error'>";
	}
	
	retval = retval + error['text'] + "</div></div>";
	
	return retval;
}

function FormatComments( comments )
{
	var content = "";
	
	for ( var item in comments )
	{
		content = content + FormatComment( comments[item] );
		
		if ( display_style == 1 )
			display_style = 2;
		else
			display_style = 1;
	}
	
	return content;
}

function FormatComment( comment )
{
	var retval = "";
	
	if ( display_style == 1 )
	{
		retval = retval + "<div class='altrows_row1'><div class='video_discussion_thread_comment'>";
	}
	else
	{
		retval = retval + "<div class='altrows_row2'><div class='video_discussion_thread_comment'>";
	}
	
	// Draw up the avatar
	retval = retval + "<div class='video_discussion_thread_comment_avatar'>";
	retval = retval + comment['avatar'];
	retval = retval + "</div>";
	
	// Enclose the nickname and actual post
	retval = retval + "<div class='video_discussion_thread_comment_block'>";
	retval = retval + "<div class='video_discussion_thread_comment_poster'><a href='/profile/" + comment['username'] + "/'>" + comment['display_name'] + "</a></div>";
	retval = retval + "<div class='video_discussion_thread_comment_text'>" + comment['text'] + "</div>";
	retval = retval + "</div>";
	
	// Add the timestamp and a possible post-delete link
	retval = retval + "<div class='video_discussion_thread_comment_time'><div>" + comment['post_date'] + "</div>";
	
	if ( username == comment['username'] )
	{
		retval = retval + "<a href=\"#\" onClick=\"DeleteComment( " + comment['postid'] + " ); return false;\">Delete</a>";
	}
	
	retval = retval + "</div>";
	
	// Finish off the entire div, placing a clearfloat beneath the entire comment but not the altrow
	retval = retval + "</div><div class='clearfloat'></div></div>";
	
	return retval;
}

function GenerateUniqueId()
{
	var retval = "vdt";
	
	var d = new Date();
	var t = d.getTime();
	var r = Math.floor( Math.random() * 10001 );
	
	retval = retval + t + r;
	
	return retval;
}

// Remove whitespace and newlines from the beginning or end of the string
function StripSpaces( text_string )
{
	return text_string;
}

function ResetGlobals()
{
	display_style = 2;
	current_page = 0;
	page_count = 0;
}
