$( function()
{
	//TODO remove - only for IE7 bug at homepage and login page, please remove "overflow" also from home.xhtml 2x tag <style> #support...
	$("#support").css("overflow", "visible");
	
	editLink();
	cancelButton();
	showXmarkOnFeaturedPhotos();
	showXmarkOnAlbums();
	userBioScripts();
	categoryScripts();
	albumScripts();
	submitByEnter();
	sslightScripts();
	homeSectionMoveArrows();
	
});

function sslightScripts()
{
	$( "div[class^='homeSslight']" ).hover(
		function(){
			$( ".homeSslightChangeLook" ).fadeIn("fast");
	},
		function(){
			$( ".homeSslightChangeLook" ).fadeOut("fast");		
	});
	
	//re-register hover efects
	tabsHover();
}

function userBioScripts()
{
	showXmarkOnPortrait();

	$( "input[name=saveUserBio]" ).click( function( event )
	{
		var userBio = $( "#userBioTextArea" ).val();
	//	userBio = htmlCoding( userBio );			
		
		showMainLoading("Saving About Me...");
		
		var parameters = [{ "name": "method", "value": "bluemelon.users.update" }];
		parameters.push( { "name": "biotext", "value": userBio }) ;
		
		
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error
					hideMainLoading();
					alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
					return;
				}
				else
				{
					var newBioText = $(this).find( 'user > bio' ).text();
					// change text information in view
					$("span[id='userBioTextContent']")[0].innerHTML = formatForHTML( urldecode( newBioText ));
					hideMainLoading();
					
					//change [Add Description] to [Edit] or reversely
					if( $( "#userBioTextContent" ).text() == "" )
					{
						$( "#userBioTextContent" ).text( "Your visitors will see an empty space here." );
						$( "#userBioTextNoEdit a" )[0].innerHTML = "Add Description";
					}
					else
					{
						$( "#userBioTextNoEdit a" )[0].innerHTML = "Edit";
					}	
					
					// show normal mode
					$("#userBioTextEdit").hide();
					$("#userBioTextNoEdit").show();
				}
			});
		});
	});
}


function categoryScripts()
{
	// setting get request for category update - CATEGORY TITLE
	$( "input.editCat" ).click( function( event )
	{
		var formParamArray = $(this).parent().serializeArray();

		var categoryId = formParamArray[ 0 ].value; 
		var categoryName = formParamArray[ 1 ].value;
		//categoryName = htmlCoding( categoryName );

		showMainLoading("Saving Category title...");
		
		var parameters = [{ "name": "method", "value": "bluemelon.categories.update" }];
		parameters.push( { "name": "categoryid", "value": categoryId }) ;
		parameters.push( { "name": "name", "value": categoryName }) ;
	
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error
					hideMainLoading();
					alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
					return;
				}
				else
				{
					var newURL = $(this).find( 'category' ).attr( 'url' );
					var newTitle = $(this).find( 'category' ).attr( 'title' );

					//fix text in title link
					$( "#categoryTitleLink_" + categoryId ).text( urldecode( newTitle ));

					//fix address for title link					
					var ref = $( "#categoryTitleLink_" + categoryId ).attr( "href" );
					var pos = ref.lastIndexOf( '/' );
					
					$( "#categoryTitleLink_" + categoryId ).attr( "href", ref.substring( 0, pos + 1 ) + newURL );

					//fix address for category image link
					ref = $( "#categoryImageLink_" + categoryId ).attr( "href" );
					if(ref)//only if image exist
					{
						pos = ref.lastIndexOf( '/' );
						$( "#categoryImageLink_" + categoryId ).attr( "href", ref.substring( 0, pos + 1 ) + newURL );
					}
					
					hideMainLoading();
					
					// show normal mode
					$( "#categoryEdit_" + categoryId ).hide().prev().show();
				}
			});
		});
	});
	
	
}

function removeCoverPhoto( categoryId )
{
	showMainLoading( "Setting cover..." );
	
	var parameters = [{ "name": "method", "value": "bluemelon.categories.update" }];
	parameters.push( { "name": "categoryid", "value": categoryId });
	parameters.push( { "name": "coveritemid", "value": 0 });
	
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
				return;
			}
			else
			{	//status = OK
				showCategories( 1 );
			}
		});
	});
}

function albumScripts()
{
	//remove old event
	$( "input[name=saveAlbumTitle]" ).unbind("click");
	$( "input[name=saveAlbumDesc]" ).unbind("click");
	$( "input[name=saveAlbumKey]" ).unbind("click");
	
	// setting get request for album update - ALBUM TITLE
	$( "input[name=saveAlbumTitle]" ).click( function( event )
	{
		var thisObj = $(this);
		var formParamArray = $(this).parent().serializeArray();
		var nodeId = $(this)[0].parentNode.parentNode.id;
						
		var albumName = formParamArray[1].value;
		//albumName = htmlCoding( albumName );			
		
		showMainLoading("Saving Album title...");
		
		var parameters = [{ "name": "method", "value": "bluemelon.albums.update" }];
		parameters.push( { "name": "albumid", "value": formParamArray[ 0 ].value }) ;
		parameters.push( { "name": "name", "value": albumName }) ;
		
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error
					hideMainLoading();
					alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
					return;
				}
				else
				{
					//fix address for album link
					var newURL = $(this).find( 'album' ).attr( 'url' );
					var newTitle = $(this).find( 'album' ).attr( 'title' );
					nodeId = nodeId.substring( 0, nodeId.length - 4 );
					var ref = $( "#" + nodeId + " a" )[0].href;
					var pos = ref.lastIndexOf('/');
					
					$( "#" + nodeId + " a:first-child" ).each( function(){
						$(this)[0].href = ref.substring( 0, pos + 1 ) + newURL;
					});
					
					//fix title for album link
					$( "#" + nodeId + "  a:first-child" ).text( urldecode( newTitle ));
					
					//fix address for album image link
					ref = $( "#image_" + nodeId + " a" )[0].href;
					pos = ref.lastIndexOf('/');

					$( "#image_" + nodeId + " a" ).each( function(){
						$(this)[0].href = ref.substring( 0, pos + 1 ) +  newURL;
					});
					
					hideMainLoading();
					// show normal mode
					thisObj.parent().parent().hide().prev().show();
				}
			});
		});
	});
	
	
	// setting get request for album update - ALBUM DESC
	$( "input[name=saveAlbumDesc]" ).click( function( event )
	{
		var thisObj = $(this);
		var formParamArray = $(this).parent().serializeArray();
		var nodeId = $(this)[0].parentNode.parentNode.id;
						
		var albumDescription = formParamArray[1].value;
		//albumDescription = htmlCoding( albumDescription );			
		
		showMainLoading("Saving Album description...");
		
		var parameters = [{ "name": "method", "value": "bluemelon.albums.update" }];
		parameters.push( { "name": "albumid", "value": formParamArray[ 0 ].value }) ;
		parameters.push( { "name": "description", "value": albumDescription }) ;
		
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error
					hideMainLoading();
					alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
					return;
				}
				else
				{
					var newDescription = $(this).find( 'album > description' ).text();
					// change text information in view
					
					thisObj.parent().parent().prev().find("span[id*='albumDescContent']").html( formatForHTML( newDescription ));
					//change [Add Description] to [Edit] or reversely
					if( newDescription == "" )
					{
						thisObj.parent().parent().prev().find("a")[0].innerHTML = "Add Description";
					}
					else
					{
						thisObj.parent().parent().prev().find("a")[0].innerHTML = "Edit";
					}	
					
					
					hideMainLoading();
					
					// show normal mode
					thisObj.parent().parent().hide().prev().show();
				}
			});
		});
	});
	
	// setting get request for album update - ALBUM KEY
	$( "input[name=saveAlbumKey]" ).click( function( event )
	{
		var thisObj = $(this);
		var formParamArray = $(this).parent().serializeArray();
		var nodeId = $(this)[0].parentNode.parentNode.id;
						
		var albumKey = formParamArray[1].value;
		//albumKey = htmlCoding( albumKey );			
		
		showMainLoading("Saving Album keywords...");
		
		var parameters = [{ "name": "method", "value": "bluemelon.albums.update" }];
		parameters.push( { "name": "albumid", "value": formParamArray[ 0 ].value });
		parameters.push( { "name": "tags", "value": albumKey });
		
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error
					hideMainLoading();
					alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
					return;
				}
				else
				{
					var newTags = $(this).find( 'album > tags' ).text();
					// change text information in view
					thisObj.parent().parent().prev().find("span[id*='albumKeyContent']").html( formatForHTML( newTags ));
					//change [Add Description] to [Edit] or reversely
					if( newTags == "" )
					{
						thisObj.parent().parent().prev().find("a")[0].innerHTML = "Add Keywords";
					}
					else
					{
						thisObj.parent().parent().prev().find("a")[0].innerHTML = "Edit";
					}	
					
					hideMainLoading();
					// show normal mode
					thisObj.parent().parent().hide().prev().show();
				}
			});
		});
	});
	
	
	
	//show text OPENED on granted password protected albums
	$( "div.passProtectedOpened" ).each(function(){
		$(this).append("<div class='passwordMsgBox'>Opened</div>");
	});
	
	
	//show buttons on hover and password input
	$("td[class^='viewCatTd']").hover(
		function(){
			var passDiv = $(this).find( "div.passProtectedClosed" );
			if( passDiv.length > 0 )
			{
				var folderId = passDiv.attr("name");
				showPasswordDialog( folderId );	
			}
	},
		function(){
			var passDiv = $(this).find( "div.passProtectedClosed" );
			if( passDiv.length > 0 )
			{
				var folderId = passDiv.attr("name");
				hidePasswordDialog( folderId );	
			}
		}
	);
	
	thumbnailDropDown();
}

function submitByEnter()
{
	//unbind old listener
	$("#structure form input").unbind("keypress");
	
	//set Enter as submit
	$("#structure form input").keypress(function (e) 
	{  
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) 
		{  
			$(this).parent().find( "input[type='button']" ).click();
			return false;
		}
		else 
		{  
			return true;  
		}  
  }); 
}

function editLink()
{
	//remove old event
	$( "a.editObj" ).unbind("click");
	
	// add click event to edit link in edit category
	$( "a.editObj" ).click( function( event )
	{
		event.preventDefault();
		$(this).parent().hide().next().show();
		
		var nodeId = $(this)[0].parentNode.id; 
		$( "#" + nodeId + "Input" ).focus();
	});
}

function cancelButton()
{
	//remove old event
	$( "input.cancelEdit" ).unbind("click");
	
	// add click event to cancel edit mode
	$( "input.cancelEdit" ).click( function( event )
	{
		$(this).parent().find( "input[type=text]" ).attr( "value", $(this).parent().parent().prev().find( "a:first" ).text());
		$(this).parent().parent().hide().prev().show();
	});
}

function showXmarkOnPortrait()
{
	//show X mark on mouse over
	$("div#user_bio_container div.photoWrapT100" ).hover(
		function(){
			$( "#removePortrait" ).fadeIn("fast");
	},
		function(){
			$( "#removePortrait" ).fadeOut("fast");		
	});
}

function showXmarkOnFeaturedPhotos()
{
	//show Xmark on mouse over
	$("#featured_photos_container .rightTopCorner" ).parent().hover(
		function(){
			$(this).find( "div.rightTopCorner" ).fadeIn("fast");
	},
		function(){
			$(this).find( "div.rightTopCorner" ).fadeOut("fast");
		}
	);
}

function showXmarkOnAlbums()
{
	$("td[class^='viewCatTd']").hover(
		function(){
			$(this).find( "div.rightTopCorner" ).fadeIn("fast");
	},
		function(){
			$(this).find( "div.rightTopCorner" ).fadeOut("fast");
		}
	);
}

function showXmarkOnCategories()
{
	showXmarkOnAlbums(); //same funciton
}

function removePortrait()
{
	//save original border-color
	var origBorderColor = $("img#userPortrait").parent().css( "border-color" );
	//change to red
	$("img#userPortrait").parent().css( "border-color", "red" );
	
	if ( !confirm( "Do you really want to remove your portrait image?" ) ) 
	{//if no
		//restore border to original
			$("img#userPortrait").parent().css( "border-color", origBorderColor );
		return;
	}
	showMainLoading("Removing portrait...");
	
	var parameters = [{ "name": "method", "value": "bluemelon.users.unsetBioItem" }];
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error
				hideMainLoading();
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
				return;
			}
			else
			{
				var url_parameters = urldecode( $( "#url_parameters" ).text() );
				//load snippet
				//$( "#user_bio_container" ).hide();
				$( "#user_bio_container" ).load( "/homesections/user-bio.seam?" + url_parameters, function( data, status )
				{
					if( status != "success" )
					{
						//error
						hideMainLoading();
						alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
						return;
					}
					
					homeSectionMoveArrows();
					tabsHover();
					hideMainLoading();
					userBioScripts();
					editLink();
					cancelButton();
				});
			}
		});
	});

}

function removeFeaturedItem( albumId, itemId, title )
{
	var loadingMsg;
	var parameters;

	title = unescape( title );

	if( itemId >= 0 )
	{	//remove item
		//save original border-color
		var origBorderColor = $("img[id='featuredItem-"+itemId+"']").css( "border-color" );
		//change to red
		$("img[id='featuredItem-"+itemId+"']").css( "border-color", "red" );
		
		if ( !confirm( "Do you want to remove image '"+title+"' from featured photos?" ) ) 
		{//if no
			//restore border to original
			$("img[id='featuredItem-"+itemId+"']").css( "border-color", origBorderColor );
			return;
		}
		loadingMsg = "Removing from featured photos...";
		
		parameters = [{ "name": "method", "value": "bluemelon.featured.items.remove" }];
		parameters.push( { "name": "albumid", "value": albumId }) ;
		parameters.push( { "name": "itemid", "value": itemId }) ;
	}
	else	//only albumId -> remove album
	{
		//save original border-color
		var origBorderColor = $(".featuredAlbums div[id='image_album"+albumId+"']").parent().parent().css( "border-color" );
		//change to red
		$(".featuredAlbums div[id='image_album"+albumId+"']").parent().parent().css( "border-color", "red" );
		if ( !confirm( "Do you want to remove album '"+title+"' from featured albums?" ) )
		{//if no
			//restore border to original
			$(".featuredAlbums div[id='image_album"+albumId+"']").parent().parent().css( "border-color", origBorderColor );
			return;
		}
		loadingMsg = "Removing from featured albums...";
		
		parameters = [{ "name": "method", "value": "bluemelon.featured.albums.remove" }];
		parameters.push( { "name": "albumid", "value": albumId }) ;
	}

	showMainLoading(loadingMsg);
	
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				var newCount = $(this).find( 'collectionContext' ).attr( 'count' );
				
				if( itemId >= 0 )
				{
					if( newCount == 0 )
					{//if section is empty - hide
						$( "#featured_photos_container" ).slideUp( "slow" );
						
						//hide OK_mark in tools
						$("li[id='tools_featured_photos']").removeClass( "ok_mark" );
						//change function onClick
						$("li[id='tools_featured_photos']").find("a").attr( "href", "javascript:showFeaturedPhotos()" );
					}
					else
					{
						//graphical remove featured item
						$("img[id='featuredItem-"+itemId+"']").parents(".photoTableTdT100").eq(0).fadeOut("slow");
					}
				}
				else
				{
					if( newCount == 0 )
					{//if section is empty - hide
						$( "#featured_albums_container" ).slideUp( "slow" );
						
						//hide OK_mark in tools
						$("li[id='tools_featured_albums']").removeClass( "ok_mark" );
						//change function onClick
						$("li[id='tools_featured_albums']").find("a").attr( "href", "javascript:showFeaturedAlbums()" );
					}
					else
					{
						//graphical remove featured album
						$(".featuredAlbums div[id='image_album"+albumId+"']").parent().parent().fadeOut("slow");
					}
				}
			}
		});
	});
}

/************ SHOWING QUICK PANELS ***************/

function showSSLightPanel()
{
	showMainLoading("Loading Change Look panel...");
	
	$( ".quickPanel" ).load( "/snippets/category-display-sslight-quickpanel.inc.seam", function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			hideQuickPanel();
			return;
		}
		hideMainLoading();
		$( "div.quickPanel" ).css( "top", $("#user_sslight_container").offset().top);
		showQuickPanel( 520 );
	});
}


function categoryShowAlbumPanel()
{
	showMainLoading("Loading Change Look panel...");
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	
	$( ".quickPanel" ).load( "/snippets/category-display-album-quickpanel.inc.seam", url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			hideQuickPanel();
			return;
		}
		hideMainLoading();
		$( "div.quickPanel" ).css( "top", $("#albums_container").offset().top);
		showQuickPanel( 500 );
	});
}

function showCategoryPanel()
{
	showMainLoading("Loading Change Look panel...");

	$( ".quickPanel" ).load( "/snippets/category-display-category-quickpanel.inc.seam", function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			hideQuickPanel();
			return;
		}
		$( "div.quickPanel" ).css( "top", $("#subcategories_container").offset().top);
		hideMainLoading();
		showQuickPanel( 500 );
	});
}

function showCollectionsPanel()
{
	showMainLoading("Loading Change Look panel...");

	$( ".quickPanel" ).load( "/snippets/category-display-collections-quickpanel.inc.seam", function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			hideQuickPanel();
			return;
		}
		$( "div.quickPanel" ).css( "top", $("#collections_container").offset().top);
		hideMainLoading();
		showQuickPanel( 500 );
	});
}
/************ END of SHOWING QUICK PANELS ***************/

function showFeaturedSslight( saveUserVar )
{
	if( saveUserVar == null )
	{
		saveUserVar = true;
	}
	
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading Featured Slideshow" );
	
	if( saveUserVar )
	{ 
		//set userVariable
		var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
		parameters.push( { "name": "name", "value": "SHOW_FEATURED_SSLIGHT" });
		parameters.push( { "name": "value", "value": "TRUE" });
			
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error	
					hideMainLoading();	
					alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
					return;
				}
				else
				{	
					//status = OK
				}
			});
		});
		
		$( "#user_sslight_container" ).hide();
	}
	
	//load snippet
	$( "#user_sslight_container" ).load( "/homesections/sslight.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}
		homeSectionMoveArrows();
		$( "#user_sslight_container" ).slideDown("slow");
		sslightScripts();
		hideMainLoading();
		
		//hide OK_mark
		$("li[id='tools_featured_sslight']").addClass( "ok_mark" );
		//change function onClick
		$("li[id='tools_featured_sslight']").find("a").attr( "href", "javascript:hideFeaturedSslight()" );
	});
}

function hideFeaturedSslight()
{
	showMainLoading( "Hiding Featured Slideshow" );
	
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "SHOW_FEATURED_SSLIGHT" });
	parameters.push( { "name": "value", "value": "FALSE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
			
				$( "#user_sslight_container" ).slideUp( "slow", function(){
					$(this).html("");
					homeSectionMoveArrows();
				});
				
				//hide OK_mark
				$("li[id='tools_featured_sslight']").removeClass( "ok_mark" );
				//change function onClick
				$("li[id='tools_featured_sslight']").find("a").attr( "href", "javascript:showFeaturedSslight()" );
			}
		});
	});
}

function showUserBio()
{
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading About Me" );
	
	//set userVariable
	
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "DISPLAY_MY_BIO" });
	parameters.push( { "name": "value", "value": "TRUE" });
		
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();	
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
			}
		});
	});
	
	//load snippet
	$( "#user_bio_container" ).hide();
	$( "#user_bio_container" ).load( "/homesections/user-bio.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}
		
		$( "#user_bio_container" ).slideDown("slow");
		hideMainLoading();
		homeSectionMoveArrows();
		//hide OK_mark
		$("li[id='tools_user_bio']").addClass( "ok_mark" );
		//change function onClick
		$("li[id='tools_user_bio']").find("a").attr( "href", "javascript:hideUserBio()" );
		userBioScripts();
		//re-register hover efects
		tabsHover();
		editLink();
		cancelButton();
	});
}

function hideUserBio()
{
	showMainLoading( "Hiding About Me" );
	
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "DISPLAY_MY_BIO" });
	parameters.push( { "name": "value", "value": "FALSE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				//because this Xmark has position:absolute
				$( "#removePortrait" ).hide();
				
				$( "#user_bio_container" ).slideUp( "slow", function(){
					$(this).html("");
					homeSectionMoveArrows();
				});
				
				//hide OK_mark
				$("li[id='tools_user_bio']").removeClass( "ok_mark" );
				//change function onClick
				$("li[id='tools_user_bio']").find("a").attr( "href", "javascript:showUserBio()" );
			}
		});
	});
}

function showFeaturedPhotos()
{
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading Featured Photos" );
	
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "SHOW_FEATURED_PHOTOS" });
	parameters.push( { "name": "value", "value": "TRUE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();	
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
			}
		});
	});
	
	//load snippet
	$( "#featured_photos_container" ).hide();
	$( "#featured_photos_container" ).load( "/homesections/featured-photos.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}
		showXmarkOnFeaturedPhotos();
		$( "#featured_photos_container" ).slideDown("slow");
		hideMainLoading();
		homeSectionMoveArrows();
		//re-register hover efects
		tabsHover();
		//hide OK_mark
		$("li[id='tools_featured_photos']").addClass( "ok_mark" );
		//change function onClick
		$("li[id='tools_featured_photos']").find("a").attr( "href", "javascript:hideFeaturedPhotos()" );
	});
}

function hideFeaturedPhotos()
{
	showMainLoading( "Hiding Featured Photos" );
	
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "SHOW_FEATURED_PHOTOS" });
	parameters.push( { "name": "value", "value": "FALSE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				$( "#featured_photos_container" ).slideUp( "slow", function(){
					$(this).html("");
					homeSectionMoveArrows();
				});
				
				//hide OK_mark
				$("li[id='tools_featured_photos']").removeClass( "ok_mark" );
				//change function onClick
				$("li[id='tools_featured_photos']").find("a").attr( "href", "javascript:showFeaturedPhotos()" );
			}
		});
	});
}

function showFeaturedAlbums()
{
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading Featured Albums" );
	
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "SHOW_FEATURED_ALBUMS" });
	parameters.push( { "name": "value", "value": "TRUE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();	
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
			}
		});
	});
	
	//load snippet
	$( "#featured_albums_container" ).hide();
	$( "#featured_albums_container" ).load( "/homesections/featured-albums.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}
		//re-register hover efects
		tabsHover();
		showXmarkOnAlbums();
		$( "#featured_albums_container" ).slideDown("slow");
		dropdown();
		hideMainLoading();
		homeSectionMoveArrows();
		//hide OK_mark
		$("li[id='tools_featured_albums']").addClass( "ok_mark" );
		//change function onClick
		$("li[id='tools_featured_albums']").find("a").attr( "href", "javascript:hideFeaturedAlbums()" );
	});
}

function hideFeaturedAlbums()
{
	showMainLoading( "Hiding Featured Albums" );
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "SHOW_FEATURED_ALBUMS" });
	parameters.push( { "name": "value", "value": "FALSE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				$( "#featured_albums_container" ).slideUp( "slow", function(){
					$(this).html("");
					homeSectionMoveArrows();
				});
				
				//hide OK_mark
				$("li[id='tools_featured_albums']").removeClass( "ok_mark" );
				//change function onClick
				$("li[id='tools_featured_albums']").find("a").attr( "href", "javascript:showFeaturedAlbums()" );
			}
		});
	});
}

function showCategories( mode )
{	//mode 0 = setUserVar and load category snippet (slide efect)
	//mode 1 = reload category snippet (fade effect)
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading Categories" );
	
	if( mode == 0 )
	{
		//set userVariable
		var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
		parameters.push( { "name": "name", "value": "DISPLAY_SUBCATEGORIES" });
		parameters.push( { "name": "value", "value": "SHOW" });
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error	
					hideMainLoading();	
					alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
					return;
				}
				else
				{	
					//status = OK
				}
			});
		});
	}
	
	
	if( mode == 0 )
	{
		$( "#subcategories_container" ).hide();
	}
	
	//load snippet
	$( "#subcategories_container" ).load( "/homesections/categories-container.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}

		if( mode == 0 )
		{
			$( "#subcategories_container" ).slideDown("slow");
			hideMainLoading();
			//hide OK_mark
			$("li[id='tools_categories']").addClass( "ok_mark" );
			//change function onClick
			$("li[id='tools_categories']").find("a").attr( "href", "javascript:hideCategories()" );
		}
		else
		{
			$( "#subcategories_container" ).fadeTo( "fast", 1.0 );
			hideMainLoading();
		}
	
		//re-register events
		showXmarkOnCategories();
		thumbnailDropDown();
		categoryScripts();
		submitByEnter();
		editLink();
		cancelButton();
		
		//re-register hover efects
		tabsHover();
		homeSectionMoveArrows();
	});
}

function hideCategories()
{
	showMainLoading( "Hiding Categories" );
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "DISPLAY_SUBCATEGORIES" });
	parameters.push( { "name": "value", "value": "HIDE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				$( "#subcategories_container" ).slideUp( "slow", function(){
					$(this).html("");
					homeSectionMoveArrows();
				});
				
				//hide OK_mark
				$("li[id='tools_categories']").removeClass( "ok_mark" );
				//change function onClick
				$("li[id='tools_categories']").find("a").attr( "href", "javascript:showCategories(0)" );
			}
		});
	});
}

function showCollections( mode )
{	//mode 0 = setUserVar and load collection snippet (slide efect)
	//mode 1 = reload collection snippet (fade effect)
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading Collections" );

	if( mode == 0 )
	{
		//set userVariable
		var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
		parameters.push( { "name": "name", "value": "SHOW_COLLECTIONS" });
		parameters.push( { "name": "value", "value": "TRUE" });
		$.post( "/api/ajax/", parameters, function( xml ){
			$( xml ).find( 'rsp' ).each( function(){
				if( $(this).attr( 'status' ) != 'ok' )
				{
					//error
					hideMainLoading();
					alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
					return;
				}
				else
				{
					//status = OK
				}
			});
		});
	}

	if( mode == 0 )
	{
		$( "#collections_container" ).hide();
	}
	//load snippet
	$( "#collections_container" ).load( "/homesections/collections-container.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}

		if( mode == 0 )
		{
			$( "#collections_container" ).slideDown("slow");
			hideMainLoading();
			//hide OK_mark
			$("li[id='tools_collections']").addClass( "ok_mark" );
			//change function onClick
			$("li[id='tools_collections']").find("a").attr( "href", "javascript:hideCollections()" );
		}
		else
		{
			$( "#collections_container" ).fadeTo( "fast", 1.0 );
			hideMainLoading();
		}

		//re-register hover efects
		tabsHover();
		dropdown();
		homeSectionMoveArrows();
	});
}

function hideCollections()
{
	showMainLoading( "Hiding Collections" );
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "SHOW_COLLECTIONS" });
	parameters.push( { "name": "value", "value": "FALSE" });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				$( "#collections_container" ).slideUp( "slow", function(){
					$(this).html("");
					homeSectionMoveArrows();
				});
				
				//hide OK_mark
				$("li[id='tools_collections']").removeClass( "ok_mark" );
				//change function onClick
				$("li[id='tools_collections']").find("a").attr( "href", "javascript:showCollections(0)" );
			}
		});
	});
}

function showThemePanel()
{
	disableAlbumSettingsPanelThemePreview = false;
	var url_parameters = urldecode( $( "#url_parameters" ).text() );
	
	//load snippet
	$( ".quickPanel" ).load( "/snippets/category-display-theme-quickpanel.inc.seam?" + url_parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "Error loading Theme Panel: " + $(this).attr( 'errormsg' ));
			return;
		}
		$( "li#tools_themes" ).parent().hide();
		showQuickPanel( 500 );
	});
}
	
function switchTheme( themeCode, themeName )
{
	if( $("link[id='themeLink']").length == 0 )
	{
		$("head").append("<link id='themeLink' href='"+themeName+"' rel='stylesheet' type='text/css' />");
	}
	else
	{
		$("link[id='themeLink']").attr({href : themeName});
	}
	showMainLoading( "Saving Theme" );
	//set userVariable
	var parameters = [{ "name": "method", "value": "bluemelon.users.setuservar" }];
	parameters.push( { "name": "name", "value": "GLOBAL_CATEGORY_THEME" });
	parameters.push( { "name": "value", "value": themeCode });
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();
				alert( "The changes are not saved: " + $( this ).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				hideMainLoading();
				
				//hide all OK_marks
				$("li[id*='tools_themes']").removeClass( "ok_mark" );
				
				//set OK_Mark
				$("li[id='tools_themes_"+themeCode+"']").addClass( "ok_mark" );
			}
		});
	});
	
}

function APIcreateNewCategory( parentId )
{
	showMainLoading("Creating category...");
	
	var parameters = [{ "name": "method", "value": "bluemelon.categories.create" }];
	parameters.push( { "name": "categoryname", "value": "New Category" });
	
	if( parentId > 0 )
		parameters.push( { "name": "categoryid", "value": parentId });
		
	$( "#subcategories_container" ).fadeTo( "fast", 0.5 );
	
	//create new category through api
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();				
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
				$( "#subcategories_container" ).fadeTo( "fast", 1.0 );
				return;
			}
			else
			{	
				//status = OK
				
				showCategories(1);
			}
		});
	});
} 

function APIremoveCategory( categoryId )
{
	var catTitle = $( "#categoryTitleLink_"+categoryId ).text();
	if ( !confirm( "Do you really want to delete the category "+catTitle+" and all its sub-categories?" ) ) 
	{//if no
		return;
	}	
	
	//removing category and subcategories
	showMainLoading("Removing category...");

	var parameters = [{ "name": "method", "value": "bluemelon.categories.delete" }];
	parameters.push( { "name": "categoryid", "value": categoryId });
	
	$( "#subcategories_container" ).fadeTo( "fast", 0.5 );
	
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();			
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ) + ". Please reload page");
				return;
			}
			else
			{	//status = OK
				showCategories(1);
				if( $("#isRootCategory").text() == 'true' )
				{
					$( "#albums_container" ).fadeTo( "fast", 0.5 );
					showAlbums();
				}
			}
		});
	});
}

function APIcreateNewAlbum( parentId )
{
	var newAlbumId;
	showMainLoading("Creating album...");
	
	var parameters = [{ "name": "method", "value": "bluemelon.albums.create" }];
	parameters.push( { "name": "albumname", "value": "New Album" });

	if( parentId > 0 )
		parameters.push( { "name": "categoryid", "value": parentId });
	
	$( "#albums_container" ).fadeTo( "fast", 0.5 );
	
	//create new album through api
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error	
				hideMainLoading();			
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
				return;
			}
			else
			{	
				//status = OK
				showAlbums();
			}
		});
	});
}

function showAlbums( )
{
	var parameters = urldecode( $( "#url_parameters" ).text() );
	showMainLoading( "Loading albums" );
	
	//load snippet
	$( "#albums_container" ).load( "/homesections/albums-container.seam?" + parameters, function( data, status )
	{
		if( status != "success" )
		{
			//error
			hideMainLoading();
			alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
			return;
		}

		$( "#albums_container" ).fadeTo( "fast", 1.0 );
		hideMainLoading();
	
		//re-register events
		albumScripts();
		showXmarkOnAlbums();
		submitByEnter();
		editLink();
		cancelButton();
		
		//re-register hover efects
		dropdown();
		tabsHover();
		homeSectionMoveArrows();
	});
}

function showPasswordDialog( folderID )
{
	var findResult = $("div[id='enterPassword"+folderID+"']");
	if( findResult.size() == 0 )
	{
		var imgOffset = $( "div[id='image_album"+ folderID +"']" ).find( "img.passwordIMG" ).offset();
 		leftOffset = imgOffset.left - $("#structure").offset().left;
		$( "div[id='image_album"+ folderID +"']" ).append(
		"<div class='passwordBox' id='enterPassword"+folderID+"' style='top:"+(imgOffset.top+54)+"px; left:"+(leftOffset+27)+"px;' >"+
				"<input type='password' value='' name='"+folderID+"' size='15' style='margin-left:0px; margin-rigth:0px;'/>"+
				"<br/><input type='button' class='saveButton3' value='OK' onClick='javascript:checkPassword("+folderID+");' />" +
			"</div>"
		);
		
		//register enter event
		$( "div[id='image_album"+ folderID +"'] input[type='password']" ).keypress(function (e) 
		{  
			if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) 
			{  
				var folderId = $(this).attr('name');
				checkPassword( folderID );
				return false;
			}
			else 
			{  
				return true;  
			}  
	  }); 
	  
	  $( "div[id='enterPassword"+ folderID +"']" ).css( "opacity", 0.01 );
		$( "div[id='enterPassword"+ folderID +"']" ).show();
	  $( "div[id='enterPassword"+ folderID +"']" ).fadeTo("fast", 1.0, function(){
		//set focus to input
		$( "div[id='enterPassword"+ folderID +"'] input[type='password']" ).focus();
		});
		
	}
	else
	{
		$( "div[id='enterPassword"+ folderID +"']" ).stop();
		$( "div[id='enterPassword"+ folderID +"']" ).css( "opacity", 1.0 );
		$( "div[id='enterPassword"+ folderID +"']" ).show();
		$( "div[id='enterPassword"+ folderID +"'] input[type='password']" ).focus();
	}
	
	
	
}

function hidePasswordDialog( folderID )
{
	$("div [id='enterPassword"+folderID+"']").fadeOut("slow", function(){
		$("div [id='enterPassword"+folderID+"']").remove();
	});
	
}


function checkPassword(folderID)
{
	var enteredPasswd = $( "div[id='enterPassword"+ folderID +"'] input[type='password']" ).val();
	
	if( enteredPasswd == "" )
	{
		wrongPassMsg( folderID );
		return;
	}
	
	showMainLoading("Checking password...");
	
	var parameters = [{ "name": "method", "value": "bluemelon.albums.checkpassword" }];
	parameters.push( { "name": "folderid", "value": folderID });
	parameters.push( { "name": "password", "value": enteredPasswd });

	//create new album through api
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//if wrong
				hideMainLoading();			

				//show custom error message
				wrongPassMsg( folderID );
				
				$( "div[id='image_album"+ folderID +"'] input[type='password']" ).val("");
				$( "div[id='image_album"+ folderID +"'] input[type='password']" ).focus();
				return;
			}
			else
			{	
				//status = OK
				var folderUrl = $(this).find("string").text();
				showMainLoading("Loading album...");
				//hidePasswordDialog(folderID);
				$( "div[id='enterPassword"+ folderID +"']" ).css( "opacity", 0.01 );
				window.location = folderUrl;

			}
		});
	});
}

function enterPassMsg( folderID )
{
	if( $( "div[id='enterPassword"+ folderID +"']").prev().find( "div.passwordMsgBox" ).length == 0 )
	{
		$( "div[id='enterPassword"+ folderID +"']" ).prev().append("<div class='passwordMsgBox' id='enterPass"+ folderID +"' style='display:none;'>Enter password</div>");
	}
	else
	{
		var msgBox = $( "div[id='enterPassword"+ folderID +"']").prev().find( "div.passwordMsgBox" );
		msgBox.attr( "id", "enterPass"+ folderID );
		msgBox.text( "Enter password" );
		
	}
	
	blinkEffect( "div#enterPass"+ folderID, 6 ); //count must be even number
}



function wrongPassMsg( folderID )
{
	if( $( "div[id='enterPassword"+ folderID +"']").prev().find( "div.passwordMsgBox" ).length == 0 )
	{
		$( "div[id='enterPassword"+ folderID +"']" ).prev().append("<div class='passwordMsgBox' id='wrongPassword"+ folderID +"' style='display:none;'>Wrong password</div>");
	}
	else
	{
		var msgBox = $( "div[id='enterPassword"+ folderID +"']").prev().find( "div.passwordMsgBox" );
		msgBox.attr( "id", "wrongPassword"+ folderID );
		msgBox.text( "Wrong password" );
	}
	blinkEffect( "div#wrongPassword"+ folderID , 6 );	//count must be even number
}


function blinkEffect( jSelector, count )
{
	if( count > 1 )
	{
		$(jSelector).stop()
		$(jSelector).css( "opacity", 1.0 );
	
		//$(jSelector).toggle();
		if( count % 2 )
		{
			$(jSelector).hide();
		}
		else
		{
			$(jSelector).show();
		}
		count--;
		setTimeout( "blinkEffect( '"+jSelector+"', "+count+" )", 200 );	//speed of blinking
	}
	else
	{
		$(jSelector).fadeOut(3000);
	}
}
/*
function blinkEffect( jObject )
{
	jObject.stop()
	jObject.css( "opacity", 1.0 );
	
	jObject.fadeIn("fast", function () 
		{	//run after fadeIn finish
			$(this).fadeOut("fast", function () 
			{	//run after fadeOut finish
				$(this).fadeIn("fast", function () 
				{	//run after fadeIn finish
					$(this).fadeOut("fast", function () 
					{	//run after fadeOut finish
						$(this).fadeIn("fast", function () 
						{	//run after fadeIn finish
							$(this).fadeOut(3000, function () 
							{	//run after fadeOut finish
								$(this).remove();
				      });
			      });
			    });
	      });
	    });
	  });
}
*/


function htmlCoding( inTxt )
{
	return encodeURIComponent(inTxt);
	/*inTxt = inTxt.replace( /%/g, "%25" );
	inTxt = inTxt.replace( /&/g, "%26" );
	inTxt = inTxt.replace( /#/g, "%23" );
	inTxt = inTxt.replace( /\\/g, "%5C" );	
	inTxt = inTxt.replace( /\+/g, "%2B" );
	return inTxt;
	*/
}

function urldecode( inputText ) 
{
  var histogram = {} ;
  var ret = inputText.toString();
  
  var replacer = function(search, replace, inputText) {
      var tmp_arr = [];
      tmp_arr = inputText.split(search);
      return tmp_arr.join(replace);
  };
  
  // The histogram is identical to the one in urlencode.
  histogram['!']   = '%21';
  histogram['%20'] = '+';
  
  for (replace in histogram) {
      search = histogram[replace]; // Switch order when decoding
      ret = replacer(search, replace, ret) // Custom replace. No regexing   
  }
  // End with decodeURIComponent, which most resembles PHP's encoding functions
  ret = decodeURIComponent(ret);
  return ret;
}

function formatForHTML( inputText )
{
	if( inputText == null )
	{
		return null;
	}
	return inputText.replace( /\n/g, "<br />" );
}

function homeSectionMoveArrows()
{
	var firstSection;
	var lastSection;
	
	$( "div.homeSection" ).each( function(){
		if( jQuery.trim( $(this).text() ) != "" )
		{
			if( !firstSection )
			{
				firstSection = $(this);
			}
			lastSection = $(this);
		}
		
	});
	
	if(!firstSection)
	{
		return;
	}
	
	if( firstSection.attr("name") == lastSection.attr("name") )
	{
		//if only one section is shown (albums)
		firstSection.find( "td[name='homeSectionMoveUp']" ).hide();
		firstSection.find( "td[name='homeSectionMoveDown']" ).hide();
		return;
	}
	
	$( "div.homeSection td[name*='homeSectionMove']" ).show();

	firstSection.find( "td[name='homeSectionMoveUp']" ).hide();
	firstSection.find( "td[name='homeSectionMoveDown']" ).show();
	lastSection.find( "td[name='homeSectionMoveUp']" ).show();
	lastSection.find( "td[name='homeSectionMoveDown']" ).hide();
}

var homeSectionMoveInProgress = false;

function changeHomeSectionPosition( homeSection, direction )
{	
	if( homeSectionMoveInProgress )
	{
		return;
	}
	
	var newPosition;
	var refHomeSection;
	
	if( direction == "UP" )
	{
		refHomeSection = $( "div.homeSection[name='"+homeSection+"']" );
		while( true )
		{
			var prevHomeSection = refHomeSection.prev();
			if( prevHomeSection.length == 0)
			{
				return;
			}
			
			if( !prevHomeSection.hasClass( "homeSection" ) )
			{
				refHomeSection = prevHomeSection;
				continue;
			}
			if( jQuery.trim( prevHomeSection.text()) !=	"" )
			{
				refHomeSection = prevHomeSection;
				break;
			}
			refHomeSection = prevHomeSection;
		}
		newPosition = $( "div.homeSection" ).index( refHomeSection );
	}	
	else
	{//DOWN
		refHomeSection = $( "div.homeSection[name='"+homeSection+"']" );
		while( true )
		{
			var nextHomeSection = refHomeSection.next();
			if( nextHomeSection.length == 0)
			{
				return;
			}
			
			if( !nextHomeSection.hasClass( "homeSection" ) )
			{
				refHomeSection = nextHomeSection;
				continue;
			}
			if( jQuery.trim( nextHomeSection.text()) !=	"" )
			{
				refHomeSection = nextHomeSection;
				break;
			}
			refHomeSection = nextHomeSection;
		}
		newPosition = $( "div.homeSection" ).index( refHomeSection );
	}		
	
	homeSectionMoveInProgress = true;
	showMainLoading("Saving position...");
	
	var parameters = [{ "name": "method", "value": "bluemelon.homesections.changeposition" }];
	parameters.push( { "name": "homesectionid", "value": homeSection });
	parameters.push( { "name": "newposition", "value": newPosition });
	
	$.post( "/api/ajax/", parameters, function( xml ){
		$( xml ).find( 'rsp' ).each( function(){
			if( $(this).attr( 'status' ) != 'ok' )
			{
				//error
				hideMainLoading();
				alert( "The changes are not saved: " + $(this).attr( 'errormsg' ));
				homeSectionMoveInProgress = false;
				return;
			}
			else
			{
				hideMainLoading();
				//change position 
				if( direction == "UP" )
				{
					var homeSec = $( "div.homeSection[name='"+homeSection+"']" );
					//remove 	<div class="cleaner"></div>
					homeSec.next().remove();
					
					homeSec.slideUp("slow", function(){
						//change position
						$(this).insertBefore( refHomeSection );
						//show/hide move arrow if first or last
						homeSectionMoveArrows();
						//add new <div class="cleaner"></div>
						$(this).after("<div class='cleaner'></div>");	
						$(this).slideDown("slow", function(){
							homeSectionMoveInProgress = false;
						});
					});
					
				}
				else
				{//DOWN
					var homeSec = $( "div.homeSection[name='"+homeSection+"']" );
					//remove 	<div class="cleaner"></div>
					homeSec.next().remove();
					
					homeSec.slideUp("slow", function(){
						//change position
						$(this).insertAfter( refHomeSection );
						
						//show/hide move arrow if first or last
						homeSectionMoveArrows();
						
						//add new <div class="cleaner"></div>
						$(this).before("<div class='cleaner'></div>");
						$(this).slideDown("slow", function(){
							homeSectionMoveInProgress = false;
						});
					});
				}
			}
		});
	});
}