var hasComments = false;
var currentIndex = null;
var refreshRequest = null;
var refreshMessage = null;
var refreshShowClose = false;
var commentsHidden = true;
var addRequest = null;
var sendRequest = null;
var containers = { 'commentsContainer': null, 'emailContainer': null };

function refreshComments ( startIndex, id )
{
	if ( typeof ( startIndex ) == "string" )
	{
		startIndex = ( new Number ( startIndex ) ).valueOf ( );
	}
	
	if ( startIndex == null || startIndex <= 0 )
	{
		startIndex = 1;
	}
	
	currentIndex = startIndex;
	
	refreshMessage = "Refreshing...";
	refreshShowClose = false;

	if ( ! commentsHidden )
	{
		showPopup ( refreshMessage, refreshShowClose );
	}
	
	var refreshRequest = new xmlRPCRequest ( cgiURL + '/Go.cgi?a_application=SlidebloxEditorXMLRPCApp', 'slideblox.getComments', onRefreshComments );
	
	refreshRequest.addParameter ( uid );
	refreshRequest.addParameter ( startIndex );
	refreshRequest.addParameter ( id );
	
	refreshRequest.send ( );
}

function onRefreshComments ( doNotShowPopup )
{
	if ( this.request.readyState != 4 )
	{
		return;
	}
	
	try
	{
		onRequestErrorCheck ( this );
		
		refreshMessage = null;

		hidePopup ( );
		
		var html = '';
		
		var comments = this.response [ 'comments' ];
		
		if ( comments != null )
		{
			for ( var index = 0; index < comments.length; index++ )
			{
				html += formatComment ( comments [ index ] );
			}
		}
		
		getChildElementById ( containers [ "commentsContainer" ], "comments" ).innerHTML = html;
		
		var totalPages = this.response [ 'totalComments' ];
		
		if ( totalPages == null )
		{
			totalPages = 1;
		}
		
		totalPages = totalPages / 10;
		
		if ( totalPages != Math.ceil ( totalPages ) )
		{
			totalPages = Math.ceil ( totalPages );
		}
		
		var pageSelector = getChildElementById ( containers [ "commentsContainer" ], "pageSelector" );
		
		while ( pageSelector.options.length > totalPages )
		{
			pageSelector.remove ( pageSelector.options.length - 1 );
		}
		
		while ( pageSelector.options.length < totalPages )
		{
			var newOption = document.createElement ( "OPTION" );
			pageSelector.options [ pageSelector.options.length ] = newOption;
			newOption.innerHTML = pageSelector.options.length;
			newOption.value = ( pageSelector.options.length - 1 ) * 10 + 1;
		}
		
		setCommentCount ( this.response [ 'totalComments' ] );
	}
	catch ( e )
	{
		refreshMessage = e;
		refreshShowClose = true;
	
		if ( ! commentsHidden )
		{
			showPopup ( refreshMessage, refreshShowClose );
		}
	}
	
	this.complete ( );
}

function addComment ( )
{
	var name  = getChildElementById ( containers [ "commentsContainer" ], 'name' ).value;
	var email = getChildElementById ( containers [ "commentsContainer" ], 'email' ).value;
	var url   = getChildElementById ( containers [ "commentsContainer" ], 'url' ).value;
	var text  = getChildElementById ( containers [ "commentsContainer" ], 'text' ).value;
	
	if ( name.length == 0 || email.length == 0 )
	{
		showPopup ( "Your name and email address are required.", true );
		
		return;
	}
	
	if ( text.length == 0 )
	{
		showPopup ( "Please enter a comment.", true );
		
		return;
	}
	
	showPopup ( "Adding comment...", false );
	
	addRequest = new xmlRPCRequest ( cgiURL + '/Go.cgi?a_application=SlidebloxEditorXMLRPCApp', 'slideblox.addComment', onAddComment );
	
	addRequest.addParameter ( uid );
	addRequest.addParameter ( name );
	addRequest.addParameter ( email );
	addRequest.addParameter ( url );
	addRequest.addParameter ( text );
	
	addRequest.send ( );
	
	setRememberMe ( getChildElementById ( containers [ "emailContainer" ], 'rememberMe2' ).checked, true, name, email, url );
}

function onAddComment ( )
{
	if ( this.request.readyState != 4 )
	{
		return;
	}
	
	try
	{
		onRequestErrorCheck ( this );
		
		hidePopup ( );
		
		var comments = getChildElementById ( containers [ "commentsContainer" ], "comments" );
		
		comments.innerHTML += formatComment ( this.response );
		
		var scrollTop = comments.scrollHeight - 200;
		
		comments.scrollTop = scrollTop < 0 ? 0 : scrollTop;
		
		getChildElementById ( containers [ "commentsContainer" ], 'text' ).value = '';
		
		setCommentCount ( commentCount + 1 );
	}
	catch ( e )
	{
		showPopup ( e, true );
	}
	
	this.complete ( );
}

function formatComment ( comment )
{
	var html;
	
	html = '<b>' + comment [ 'row' ] + '. ' + comment [ 'name' ] + ' says:</b><br />';
	html += comment [ 'text' ] + '<br />';
	
	var name = comment [ 'name' ];
	
	if ( comment [ 'url' ] != null )
	{
		var url = comment [ 'url' ];
		url.replace ( /"/g, '\\"' );
		name = '<a href="' + comment [ 'url' ] + '" target="_blank">' + name + '</a>';
	}
	
	html += '<span style="position: relative; left: 4px;">&raquo; by ' + name + ' on ' + comment [ 'time' ] + '</span><br /><br />';
	
	return html;
}

function sendEmail ( )
{
	var name       = getChildElementById ( containers [ "emailContainer" ], 'name2' ).value;
	var email      = getChildElementById ( containers [ "emailContainer" ], 'email2' ).value;
	var recipients = getChildElementById ( containers [ "emailContainer" ], 'recipients2' ).value;
	var text       = getChildElementById ( containers [ "emailContainer" ], 'text2' ).value;
	
	if ( name.length == 0 || email.length == 0 )
	{
		showPopup ( "Your name and email address are required.", true );
		
		return;
	}
	
	if ( recipients.length == 0 )
	{
		showPopup ( "Please enter a list of space-separated email addresses to receive your message.", true );
		
		return;
	}
	
	showPopup ( "Sending email...", false );
	
	sendRequest = new xmlRPCRequest ( cgiURL + '/Go.cgi?a_application=SlidebloxEditorXMLRPCApp', 'slideblox.sendEmail', onSendEmail );
	
	sendRequest.addParameter ( name );
	sendRequest.addParameter ( email );
	sendRequest.addParameter ( recipients );
	sendRequest.addParameter ( text );
	
	var slidebloxUrl = new String ( document.location );
	slidebloxUrl = slidebloxUrl.replace ( /#.*$/, '' );
	slidebloxUrl = slidebloxUrl.replace ( /^http:\/\/[^\/]+\//, '' );
	
	sendRequest.addParameter ( slidebloxUrl );
	
	sendRequest.send ( );
	
	setRememberMe ( getChildElementById ( containers [ "emailContainer" ], 'rememberMe2' ).checked, true, name, email, null );
}

function onSendEmail ( )
{
	if ( this.request.readyState != 4 )
	{
		return;
	}
	
	try
	{
		onRequestErrorCheck ( this );
		
		showPopup ( 'Your email has been sent.', true );
		
		getChildElementById ( containers [ "emailContainer" ], 'recipients2' ).value = '';
		getChildElementById ( containers [ "emailContainer" ], 'text2' ).value = '';
	}
	catch ( e )
	{
		showPopup ( e, true );
	}
	
	this.complete ( );
}

function showEmail ( )
{
	linkElement ( containers [ 'emailContainer' ] );
	
	setElementVisibility ( null, "showComments", false, null );
	setElementVisibility ( null, "closeEmail", true, null );
	
	jumpToAnchor ( 'pageBottom' );
}

function showComments ( )
{
	linkElement ( containers [ 'commentsContainer' ] );
	
	setElementVisibility ( null, "showComments", false, null );
	setElementVisibility ( null, "hideComments", true, null );
	
	jumpToAnchor ( 'pageBottom' );
	
	if ( refreshMessage != null )
	{
		showPopup ( refreshMessage, refreshShowClose );
	}
	
	commentsHidden = false;
}

// This hides everything.

function hideWorkArea ( )
{
	if ( hasComments )
	{
		setElementVisibility ( null, "hideComments", false, null );
	}
	
	setElementVisibility ( null, "showComments", true, null );
	setElementVisibility ( null, "closeEmail", false, null );
	
	unlinkElement ( containers [ 'commentsContainer' ] );
	unlinkElement ( containers [ 'emailContainer' ] );
	
	commentsHidden = true;
}

var commentCount = null;

function setCommentCount ( count )
{
	commentCount = new Number ( count ).valueOf ( );
	
	document.getElementById ( "commentsCount" ).innerHTML = ' (' + commentCount + ')';
}

function initialize ( setHasComments )
{
	hasComments = setHasComments;
	
	var containerAttacher = document.getElementById ( 'containerAttacher' );
	
	for ( var container in containers )
	{
		var element = document.getElementById ( container );
		containers [ container ] = element;
		element.parentNode.removeChild ( element );
		containerAttacher.appendChild ( element );
	}

	var rememberMe = false;
	
	var cookies = { 'commentatorName': 'name', 'commentatorEmail': 'email', 'commentatorURL': 'url' };
	var variants = { '': 'commentsContainer', '2': 'emailContainer' };
	
	for ( var cookie in cookies )
	{
		var value = readCookie ( cookie );
		
		if ( value )
		{
			for ( var variant in variants )
			{
				var element = getChildElementById ( containers [ variants [ variant ] ], cookies [ cookie ] + variant );
			
				if ( element != null )
				{
					element.value = value;
				}
			}
			
			rememberMe = true;
		}
	}
	
	setRememberMe ( rememberMe, false, null, null, null );
	
	hideWorkArea ( );
	
	if ( hasComments )
	{
		setTimeout ( 'refreshComments ( 1, 0, true )', 100 );
	}
}

function setRememberMe ( check, setCookies, name, email, url )
{
	var variants = { '': 'commentsContainer', '2': 'emailContainer' };
			
	for ( var variant in variants )
	{
		var element = getChildElementById ( containers [ variants [ variant ] ], 'rememberMe' + variant );
	
		if ( element != null )
		{
			element.checked = check;
		}
	}

	if ( setCookies )
	{
		if ( check )
		{
			createCookie ( 'commentatorName',  name,  3650 );
			createCookie ( 'commentatorEmail', email, 3650 );
			
			if ( url != null )
			{
				createCookie ( 'commentatorURL',  url,  3650 );
			}
		}
		else
		{
			eraseCookie ( 'commentatorName' );
			eraseCookie ( 'commentatorEmail' );
			eraseCookie ( 'commentatorURL' );
		}
	}
}
