/*****************************************************************************
SETS VARIABLE DEFAULTS
******************************************************************************/
newWindow = 0;
var iterator = 0;
var user = null;
var boOverlayOn = false;


/*****************************************************************************
CALLED UPON PAGE LOADING
******************************************************************************/
function pageLoad(passedUser)
{
    // inserts controls for latest comments
    $('#comment_stats_heading').after(getControls(boNoMoreComments));
    
    // sets the user (needed for database query)
    user = passedUser;
	    
	// create the overlay
	$("body").append('<div id="overlay" style="display:none;"></div>');
	
	// displays the overlay if an image is in the URL (like from an RSS link)
	anchor = parseUri(window.location.href).anchor;
	if(anchor)
	{
	    x = 0; 
	    while(arFiles[x] != anchor && x < arFiles.length)
	        x++;
	    //alert(arFiles[x]);
	    pictureWindow(x);
    }
}


/*****************************************************************************
RETURNS HTML TO DISPLAY LATEST COMMENT CONTROLS
******************************************************************************/
function getControls(endOfComments)
{
    var controls;
    
    controls = '<div id="arrowTable"><table cellpadding="0" cellspacing="0" border="0" width="95%" align="center"><tr>';	
		
	if (iterator > 0)
		controls += '<td align="left" width="50%"><a href="#" onClick="forward(); return false;"><img border="0" src="' + leftPng + '" /></a></td>';
	else
	    controls += '<td width="50%">&nbsp;</td>';
	
	if (! endOfComments)
    	controls += '<td align="right" width="50%"><a href="#" onClick="back(); return false;"><img border="0" src="' + rightPng + '" /></a></td>';
	else
	    controls += '<td width="50%">&nbsp;</td>';
	    
	controls += '</tr></table></div>';

	return controls;
}


/*****************************************************************************
DECREMENTS LATEST COMMENTS
******************************************************************************/
function back()
{
    showLoading();
    
    iterator++;
    updateComments(iterator);
}


/*****************************************************************************
INCREMENTS LATEST COMMENTS
******************************************************************************/
function forward()
{
    showLoading();
    
    if (iterator > 0)
    {
        --iterator;
        updateComments(iterator);
    }
}


/*****************************************************************************
REQUESTS THE APPROPRIATE SET OF COMMENTS FROM THE SERVER
[Called by back() and forward().  Response is handled by showResponse().]
******************************************************************************/
function updateComments(passedIterator)
{
    var pars = {ajax: 'latestComments', increment: passedIterator};
    
	$.get('index.php', pars, showResponse);
}


/*****************************************************************************
UPDATES LATEST COMMENTS SECTION WITH RESULTS FROM THE SERVER
******************************************************************************/
function showResponse(responseText)
{
	var heading;
	var end = false;
	var comments = responseText;
	
	if (responseText.indexOf("NO_MORE_COMMENTS") > 0)
	    end = true;
	
	if (iterator == 0)
	    heading = '<h3 id="comment_stats_heading"> last 10 comments </h3>';
	else
        heading = '<h3 id="comment_stats_heading">older comments X ' + iterator + '</h3>';
	
	$('#comment_stats').empty();
	$('#comment_stats').append(heading + getControls(end) + comments);
}


/*****************************************************************************
CHANGES LATEST COMMENT NAVIGATION WHILE COMMENTS ARE LOADING
******************************************************************************/
function showLoading()
{
    $('arrowTable').innerHTML = '<img src="' + pathToApp + '/themes/default/spacer.gif" height="20" />';
}


/*****************************************************************************
OPENS OVERLAY WHEN A LATEST COMMENT IS CLICKED
******************************************************************************/
function popUp($picture, $album) 
{
	$.get("index.php?ajax=nonCatPicture&picture=" + $picture + "&album=" + $album, 
			function(data){eval(data);});
}


/*****************************************************************************
OPENS OVERLAY WHEN A THUMBNAIL IS CLICKED
******************************************************************************/
function pictureWindow($i)
{
	$i = parseInt($i);
	$iNext = $i + 1;
	$iPrev = $i - 1;
	$prevLink = '';
	$nextLink = '';
	
	if($('#comments_' + arFiles[$i]).html() != null)
		$commentsHtml = $('#comments_'+arFiles[$i]).html();
	else
		$commentsHtml = '';
		
	if(arFiles[$iPrev])
	{	
		$prevLink = '<a href="#" onClick="pictureWindow(' + $iPrev + '); return false;">' +
						'<img src="' + leftPng + '" style="border:none; margin:0;">' + 
					'</a>';
	}
	if(arFiles[$iNext])
	{
		$nextLink = '<a href="#" onClick="pictureWindow(' + $iNext + '); return false;">' +
						'<img src="' + rightPng + '" style="border:none; margin:0;">' + 
					'</a>';
	}
		
	showOverlay($('#current_category/a').text(), $('#description_'+arFiles[$i]).text(), $commentsHtml, arFiles[$i], currentAlbum, $prevLink, $nextLink);
}


/*****************************************************************************
BUILDS CONTENT FOR OVERLAY
[called by pictureWindow() and popUp() remote script]
******************************************************************************/
function showOverlay(stCategoryTitle, stImageDescription, stCommentsHtml, iFileId, iAlbumId, stPrevLink, stNextLink)
{
	$image = 'photos/' + iFileId + '.jpg';

	$stHtml = '\n\n<table border="0" width="100%" height="100%" cellspacing="0" cellpadding="0">' +
			'	<tr>\n' +
			'		<td valign="top" align="left">\n' +
			'			<div style="height: 490px; overflow: auto;">\n' +
			'				<div style="margin-bottom: 10px"><b>\n' +
							stImageDescription +
			'				</b></div>\n' +
			'				<div class="comment" id="overlayComments"> \n' +
								stCommentsHtml +	
			'				</div>\n' +
			'				<a onClick="comment(' + iFileId + ', ' + iAlbumId + ', true); return false;" class="comment_link" href="#">\n' +
								'add comment</a>\n' +
			'				<div id="commentForm" style="display:none"></div>\n' +
			'		</td>\n' +
			'		<td valign="middle" align="center" width="502" style="background-image: url(' + loadingGif + '); background-position:center center; background-repeat:no-repeat;">\n' +
			'			<a href="#" onClick="TB_remove(); return false;" title="Close"><img style="border:1px solid black; margin:0;" src="' + $image + '" /></a>\n' +
			'		</td>\n' +
			'	</tr>\n' +
			'	<tr>\n' +
			'		<td>&nbsp;</td>\n' +
			'			<td>\n' +
			'			<table border="0" cellpadding="0" cellspacing="0" width="100%">\n' +
			'				<tr>\n' +
			'					<td align="left" width="33%">\n' +
									stPrevLink +
			'					</td>\n' +
			'					<td align="middle" width="34%">\n' +
			'					</td>\n' +
			'					<td align="right" width="33%">\n' +
									stNextLink +
			'					</td>\n' +
			'				</tr>\n' +
			'			</table>\n' +
			'		</td>\n' +
			'	</tr>\n' +
			'</table>\n\n';
			
	if( !boOverlayOn )
		TB_show(stCategoryTitle, "#TB_inline?height=560&width=680&stringId=$stHtml", false);
	else
		$("#TB_ajaxContent").html($stHtml);
			
	boOverlayOn = true;
}


/*****************************************************************************
OPENS COMMENTING WINDOW
******************************************************************************/
function comment(picture, album, boOverlay) 
{
	if(boOverlay)
	{
		oThisDiv = $("#TB_ajaxContent//div#commentForm");
		width = '150px';
	}
	else
	{
		oThisDiv = $('#addComment_' + picture);
		width = '200px';
	}
	
	if( oThisDiv.css('display') == 'none' )
	{
		stHtml =    '<p>' +
						'<b>Name</b><br/>' +
						'<input type="text" id="nameEntry_' + picture + '" style="width:' + width + '">' +
					'</p>' +
					'<p>' +
						'<b>Comments</b><br/>' +
						'<TEXTAREA id="commentEntry_' + picture + '" style="width:' + width + '; height:100px;"></TEXTAREA>' +
					'</p>' +
					'<div align="center" style="margin-top:5px">' +
						'<p><input type="submit" id="submit_' + picture + '" value="Submit" onClick="saveComment(' + picture + ', ' + album + ', ' + boOverlay + '); return false;"></p>' +
					'</div>';
		
		oThisDiv.html(stHtml);
		oThisDiv.slideDown('fast');
	}
	else
	{
		oThisDiv.slideUp('fast');
	}
}
/*****************************************************************************
SAVES COMMENT TO THE DATABASE, RETURNS ARRAY OF COMMENTS FOR THE PICTURE
******************************************************************************/
function saveComment(picture, album, boOverlay)
{
	$('#submit_' + picture).disabled = 'true';
	ac_name = $('#nameEntry_'+picture).val();
	ac_comment = $('#commentEntry_'+picture).val();

	if(boOverlay)
		oCommentDiv = $("#TB_ajaxContent//div#overlayComments");
	else
		oCommentDiv = $('#comments_' + picture);

	oCommentDiv.load(
			'index.php?ajax=postComment', 
			{name: ac_name, comment: ac_comment, picture: picture, album: album}); 
			
	$('#commentEntry_'+picture).parent().parent().hide('fast');
	$('#submit_' + picture).disabled = 'false';
	
	return false;
}
/*****************************************************************************
DISPLAYS COMMENTS FOR ONE THUMBNAIL
******************************************************************************/
function display(file){
	div_id = "comments_"+file;
	
	if (document.getElementById(div_id).style.display == 'none'){
		document.getElementById(div_id).style.display='block'	;
	}else{
		document.getElementById(div_id).style.display='none'	;
	}
}


/*****************************************************************************
SHOWS OR HIDES COMMENTS FOR ALL THUMBNAILS
******************************************************************************/
function commentToggle()
{
	$(".comment").toggle("fast");
	
	if($("#show_hide/a").html() == 'hide all comments')
		$("#show_hide/a").html('show all comments');
	else
		$("#show_hide/a").html('hide all comments');
}


/*****************************************************************************
/* parseUri JS v0.1, by Steven Levithan (http://badassery.blogspot.com)
Splits any well-formed URI into the following parts (all are optional):
----------------------
• source (since the exec() method returns backreference 0 [i.e., the entire match] as key 0, we might as well use it)
• protocol (scheme)
• authority (includes both the domain and port)
    • domain (part of the authority; can be an IP address)
    • port (part of the authority)
• path (includes both the directory path and filename)
    • directoryPath (part of the path; supports directories with periods, and without a trailing backslash)
    • fileName (part of the path)
• query (does not include the leading question mark)
• anchor (fragment)
*/
function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};
    
    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    
    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }
    
    return uri;
}