// Variables to determine where the popup should appear
var x_dir 	= 'right';
var y_dir 	= 'top';
var orig_x 	= 0;
var orig_y 	= 0;

// Log to allow us to know which data parts to show and hide
var friend_total 	= new Array(2);
friend_total[1] 	= 0;
friend_total[2] 	= 0;
friend_total[3] 	= 0;
	
var orig_data_stored 	= false;
var orig_data 			= '';
var current_view 		= 'main';




/* DOM Ready *************************************************************************************/

window.addEvent('domready', function()
{
	$$('a.leftbar_link').each(
		function(link)
		{
			link.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					if(current_view != link.id)
					{
						var url = link.href;
						
						if(url.indexOf('?') > -1)
						{
							url += '&noreturn=1';
						}
						else
						{
							url += '?noreturn=1';
						}
						
						display_loading_spinner();
						
						var li = link.getParent();
						$$('ul.profile_editing_options li').each(
							function(acLi)
							{
								if(li == acLi)
								{
									acLi.className = 'active';
								}
								else
								{
									acLi.removeProperty('class');												
								}
							}
						);
						
						new Ajax(url, 
							{	
								method: 'get',
								onComplete: function(e)
								{										
									// Store the old data for a speedy return to the main view
									if(!orig_data_stored)
									{
										orig_data 			= $('main_slider').innerHTML;
										orig_data_stored 	= true;
									}
									var resp;
									if(link.id == 'media_edit' || link.id == 'picture_edit' || link.id == 'document_edit')
									{
										resp = this.response.text;
									}
									else
									{
										var myObject = Json.evaluate(this.response.text);
										resp = myObject['response'];
									}
									// Remember to add links back to the main data, and to edit the blog
									sweepInOut(resp);
									
									current_view = link.id;
								}
							}
						).request();
					}
				}
			);
		}
	);

	// Add an onclick event to the blog button if it is present
	if($('blog_expand'))
	{
		$('blog_expand').addEvent('click', 
			function(e) 
			{
				e = new Event(e).stop();
			 	
			 	if(current_view != 'blog_overview')
				{
					var url = $('blog_expand').href + '&noreturn=1';
	
					new Ajax(url, 
						{
							method: 'get',
							onComplete: function(e)
							{
								// Store the old data for a speedy return to the main view
								if(!orig_data_stored)
								{
									orig_data 			= $('main_slider').innerHTML;
									orig_data_stored 	= true;
								}
								
								// Remember to add links back to the main data, and to edit the blog
								sweepInOut(this.response.text);
								
								current_view = 'blog_overview';
							}
						}
					).request();
				}
			}
		);
	}
	
	
	// There could potentially be multiple blogs per user
	if($('blog_sidebar'))
	{
		$$('a.blogView').each(
			function(blogLink)
			{	
				blogLink.addEvent('click', 
					function(e) 
					{
						e = new Event(e).stop();
						
						if(current_view != 'blog_overview')
						{
							var url = this.href + '&noreturn=1';
			
							new Ajax(url, 
								{
									method: 'get',
									onComplete: function(e)
									{
										// Store the old data for a speedy return to the main view
										if(!orig_data_stored)
										{
											orig_data 			= $('main_slider').innerHTML;
											orig_data_stored 	= true;
										}
										
										// Remember to add links back to the main data, and to edit the blog
										sweepInOut(this.response.text);
										
										current_view = 'blog_overview';
									}
								}
							).request();
						}
					}
				);
			}
		);
	}
	
	
	// Add an onclick event to the wall button if it is present
	if($('wall_expand'))
	{
		$('wall_expand').addEvent('click', 
			function(e) 
			{
				e = new Event(e).stop();
			 	
			 	if(current_view != 'wall_overview')
				{
					var url = $('wall_expand').href + '&noreturn=1';
	
					new Ajax(url, 
						{
							method: 'get',
							onComplete: function(e)
							{
								// Store the old data for a speedy return to the main view
								if(!orig_data_stored)
								{
									orig_data 			= $('main_slider').innerHTML;
									orig_data_stored 	= true;
								}
								
								// Remember to add links back to the main data, and to edit the blog
								sweepInOut(this.response.text);
								
								current_view = 'wall_overview';
							}
						}
					).request();
				}
			}
		);
	}
	
	
	// Delete link for forum posts
	$$('a.delete_chain_link').each(
		function(link)
		{
			link.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					if(confirm($('del_wall_msg_txt').value))
					{					
						var url = link.href + '&noreturn=1&sure=1';
						
						new Ajax(url, 
							{
								method: 'get',
								onComplete: function(e)
								{
									var myObject = Json.evaluate(this.response.text);
									
									if(myObject['error'].length == 0)
									{
										fadeoutToHidden($('wall_post_' + myObject['chain_uid']));
									}
									else
									{
										alert(myObject['error']);
									}
								}
							}
						).request();
					}
				}
			);
		}
	);


	$('message_alert').style.display = 'block';
	var message_div = new Fx.Slide('message_alert');
	message_div.hide();
	
	// Add an onclick event to the friend request button if it is present
	if($('friendRequest'))
	{
		$('friendRequest').addEvent('click', 
			function(e) 
			{
				e = new Event(e).stop();
			 
				var url = $('friendRequest').href + '&noreturn=1';
			 
				new Ajax(url, 
					{
						method: 'get',
						onComplete: function(e)
							{
								if($('pity'))
								{
									var pity = new Fx.Style('pity', 'opacity', {duration: 400});
									pity.hide();
								}
								
								var myObject = Json.evaluate(this.response.text);
								
								if($('friend_status_wrapper'))
								{
									if(myObject['error'].length > 0)
									{
										$('friend_status_wrapper').innerHTML = myObject['error'];
									}
									else
									{
										$('friend_status_wrapper').innerHTML = myObject['message'];
									}
								}
							}
					}
				).request();
			}
		);
	}
	
	
	// Add an onclick event to the pity friend request button if it is present
	if($('pity'))
	{
		$('pity_link').addEvent('click', 
			function(e) 
			{
				e = new Event(e).stop();
			 
				var url = $('pity_link').href + '&noreturn=1';
			 
				new Ajax(url, 
					{
						method: 'get',
						onComplete: function(e)
							{
								var pity = new Fx.Style('pity', 'opacity', {duration: 400});
								pity.hide();
								
								var myObject = Json.evaluate(this.response.text);
								
								$('friend_status_wrapper').innerHTML = myObject['message'];
							}
					}
				).request();
			}
		);
	}
								
	
	// If there are records awaiting approval we need to handle them
	if($('awaitingApproval'))
	{
		var friend_total_waiting = 0;
		$$('a.friendApprove').each(
			function(approveLink)
			{	
				friend_total_waiting++;
			}
		);
		
		friend_total[1] = friend_total_waiting;
		
		// Add onclick to the confirm links if there are any
		$$('a.friendApprove').each(
			function(approveLink)
			{	
				approveLink.addEvent('click', 
					function(e) 
					{
						e = new Event(e).stop();
					 
						var url = approveLink.href + '&noreturn=1';
					 
						new Ajax(url, 
							{
								method: 'get',
								onComplete: function(e)
								{
									var myObject = Json.evaluate(this.response.text);
									
									if($('tot_friends_shown').innerHTML.toInt() < 8)
									{
										// Update the friends list
										$('friendsList').innerHTML += myObject['response'];
										
										$('friendsList').style.display = 'block';
										fadeinFromHidden($('friend_' + myObject['friend_uid']));
										
										// Remove the no-friends item
										if($('no_friends'))
										{
											var mySlider = new Fx.Slide('no_friends');
											mySlider.slideOut();
											
											$('no_friends').removeProperty('id');
										}
										
										// Make sure JavaScript is attached to the link
										addNewFriendHandler();
										
										$('tot_friends_shown').innerHTML = $('tot_friends_shown').innerHTML.toInt() + 1;
										
										friend_total[3]++;
									}
									
									$('tot_friends').innerHTML = $('tot_friends').innerHTML.toInt() + 1;
									$('friendsListTitle').style.display = 'block';
									
									// Either remove the whole approval list, or just the row depending on how many there are left
									colourFadeout(approveLink.getParent(), 1, '#377518', '#c6fcac');
									/*
									friend_total_waiting--;
									
									if(friend_total_waiting == 0)
									{
										fadeoutToHidden('waiting_approval_wrapper');
									}
									*/
								}
							}
						).request();
					}
				);
			}
		);
		
		
		// Add onclick to the rejection links if there are any		
		$$('a.friendReject').each(
			function(rejectLink)
			{	
				rejectLink.addEvent('click', 
					function(e) 
					{
						e = new Event(e).stop();
					 
						var url = rejectLink.href + '&noreturn=1';
					 
						new Ajax(url, 
							{
								method: 'get',
								onComplete: function(e)
								{
									colourFadeout(rejectLink.getParent(), 1, '#ff0000', '#ffb0b0');
								}
							}
						).request();
					}
				);
			}
		);
		
		
		// Add onclick to the block links if there are any
		$$('a.friendBlock').each(
			function(blockLink)
			{	
				blockLink.addEvent('click', 
					function(e) 
					{
						e = new Event(e).stop();
					 
						var url = blockLink.href + '&noreturn=1';
					 
						new Ajax(url, 
							{
								method: 'get',
								onComplete: function(e)
								{	
									colourFadeout(blockLink.getParent(), 1, '#ff0000', '#ffb0b0');
								}
							}
						).request();
					}
				);
			}
		);	
	}
	
	
	// Initialise all current friend requests with a handler
	friend_total[2] = $ES('a.friendWithdraw').length;
	addNewFriendWithdrawHandler();
	
	// Initialise all current friends with a handler
	friend_total[3] = $ES('a.currentFriend', 'friendsList').length;
	addNewFriendHandler();
	
	// Initialise all current friends with a handler
	addNewWallHandler();
	
	// Add Javascript to the inline wall posting (if it exists)
	if($('in_page_wall'))
	{
		$('in_page_wall').addEvent('submit', 
			function(e)
			{
				e = new Event(e).stop();
		 		
		 		$('in_page_wall').action += '&noreturn=1';
		 		
				$('in_page_wall').send(
					{
						onComplete: function()
						{
							// Remove any unnecessary holding messages
							if($('noWallPosts'))
							{
								var mySlider = new Fx.Slide('noWallPosts');
								mySlider.hide();
								
								$('noWallPosts').removeProperty('id');
							}
							
							if($('noWallPosts1'))
							{
								var mySlider = new Fx.Slide('noWallPosts1');
								mySlider.hide();
								
								$('noWallPosts1').removeProperty('id');
							}
							
							$('in_page_wall_content').setStyles(
								{
									'background': 'white'
								}
							);
							
							var myObject = Json.evaluate(this.response.text);
							
							if(myObject['error'].length == 0)
							{
								// Hide any errors
								$('WallMainFormError').innerHTML = '';
								fadeoutToHidden($('WallMainFormError'));
								
								// Side wall
								//--------------------------------------------------
								// Update the wall posts
								$('wallList').innerHTML = myObject['response'] + $('wallList').innerHTML;
								
								fadeinFromHidden($('newWallPost'));
								
								// Blank the textarea
								$('in_page_wall_content').value = '';
								
								$('newWallPost').removeProperty('id');
								
								
								// Main wall
								//--------------------------------------------------
								// Update the wall posts
								if($('wallList1'))
								{
									$('wallList1').innerHTML = myObject['response'] + $('wallList1').innerHTML;
									
									fadeinFromHidden($('newWallPost'));
									
									// Blank the textarea
									$('in_page_wall_content1').value = '';
									
									$('newWallPost').removeProperty('id');
									
									// Increment the main wall counter
									$('wallCount1').innerHTML = $('wallCount1').innerHTML.toInt() + 1;
								}
								
								
								// Make sure the new links are clickable
								addNewWallHandler();
							}
							else
							{
								// Show the error
								$('WallMainFormError').innerHTML = myObject['error'];
								fadeinFromHidden($('WallMainFormError'));
							}
						}
					}
				);
				
				$('in_page_wall_content').setStyles(
					{
						'background': 'white url(\'profile_information/spinner.gif\') no-repeat center center'
					}
				);
			}
		);
	}
	
	
	// Add Javascript to the inline search (if it exists)
	if($('in_page_search'))
	{
		var xCoord = 0;
		var yCoord = 0;
		var enter_pressed = false;
		
		$('in_page_search').action += '&noreturn=1';
		
		$('friend_search_submit').addEvent('click', 
			function(e)
			{
				if(!enter_pressed)
				{
					xCoord = 200;
					yCoord = e.clientY + window.getScrollTop();
					
					orig_x = xCoord;
					orig_y = yCoord;
					
					findExpandDirections(e.clientX, e.clientY);
					x_dir = 'left';
				}
				
				enter_pressed = false;
		 	}
		 );
		 
		 $('keyword_search').addEvent('keypress', 
		 	function(e)
		 	{ 
				// Catch the enter key
				if(e.keyCode == 13)
				{
					xCoord = 200;
					yCoord = 200 + window.getScrollTop();;
					
					orig_x = xCoord;
					orig_y = yCoord;
				
					x_dir = 'left';
					y_dir = 'bottom';
					
					enter_pressed = true;
				}
			}
		);
		 
		 $('in_page_search').addEvent('submit', 
			function(e)
			{
		 		e = new Event(e).stop();
		 		
		 		var initial_width = window.getWidth() - 530;
				
				initialiseHoverDiv('searchHoverDiv', initial_width, 250, true);
		
				$('searchHoverDivContent').innerHTML = '<center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /></center>';
		
				calculateDivPosition('searchHoverDiv', xCoord, yCoord);
		 		
				$('in_page_search').send(
					{
						onComplete: function()
						{
							var myObject = Json.evaluate(this.response.text);
							
							completeFriendSearch(myObject);
						}
					}
				);
			}
		);
	}
	
	
	// Add an onclick event to the search type buttons
	if($('friend_name'))
	{
		$('friend_name').addEvent('click', 
			function() 
			{
				// Ensure the text box is visible and the drop down is invisible / blank
				//$('friend_jobtype').options = '';
				
				$('jobtype_search').style.display = 'none';

				$('keyword_search').style.display = '';
			}
		);
	}
	
	if($('friend_location'))
	{
		$('friend_location').addEvent('click', 
			function() 
			{
				// Ensure the text box is visible and the drop down is invisible / blank
				//$('friend_jobtype').options = '';
				
				$('jobtype_search').style.display = 'none';

				$('keyword_search').style.display = '';
			}
		);
	}
	
	if($('friend_jobtype1'))
	{
		$('friend_jobtype1').addEvent('click', 
			function() 
			{
				// Ensure the text box is visible and the drop down is invisible / blank
				$('friend_search').value = '';
				
				$('keyword_search').style.display = 'none';

				$('jobtype_search').style.display = '';
			}
		);
	}
});


/* General Functions *************************************************************************************/



// Create the container if required, and make sure it is ready for use
function initialiseHoverDiv(divName, width, height, moveable)
{
	if(!$(divName))
	{
		var zindex = 5000;
		if(divName == 'friendHoverDiv')
		{
			zindex = 5001;
		}
		
		// Initialise the element
		var HoverDiv = new Element('div', 
			{
				id: divName, 
				styles: 
					{
						'position': 'absolute', 
						'width': width + 'px',
						'min-height': height + 'px', 
						'z-index': zindex 
					}
			}
		);
	
		// Add it to the page
		document.body.appendChild(HoverDiv);
		
		// Populate it with the required html parts
		$(divName).innerHTML = '<div id="' + divName + 'Title">&nbsp;</div><div id="' + divName + 'Content"></div><div id="' + divName + 'Close"><a href="#" title="' + $('close_link_txt').value + '" id="' + divName + 'CloseLink">x</a></div>';
		
		// Fade out the friend hover div
		if($(divName + 'CloseLink'))
		{
			$(divName + 'CloseLink').addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					fadeoutToHidden($(divName));
				}
			);
		}
		
		if(moveable)
		{
			new Drag.Move(divName, 
				{
					onComplete: function(e) 
					{
						//console.log(e);
						if($('wall_inline'))
						{
							$('wall_inline').focus();
						}
					}
				}	
			);
		}
	}
	
	changeSize($(divName), width, height);
	
	$(divName + 'Title').innerHTML 		= '&nbsp;';
	$(divName + 'Content').innerHTML 	= '<center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /></center>';
}


// Calculate what should happen to this container
function calculateDivPosition(divName, mouseX, mouseY)
{
	var width 	= $(divName).getStyle('width').toInt();
	var height 	= $(divName).getStyle('min-height').toInt();
	
	var adjX = -10;
	var adjY = -10;
	
	if(x_dir == 'left')
	{
		adjX = width + 10;
	}
	
	if(y_dir == 'bottom')
	{
		adjY = height + 10;
	}
	
	width 	= mouseX - width + adjX;
	height 	= mouseY - height + adjY;
	
	$(divName).setStyles(
		{
			'left': width,
			'top': height
		}
	);

	fadeinFromHidden($(divName));
}


// Display the top alert message
function displayMessage(text)
{
	// Currently testing one message
	var element = $('message_alert');
	
	element.innerHTML = text;

	// Run the slides
	message_div.slideIn().chain(
		function() 
		{
			message_div.slideOut.delay(2000, this);
		}
	);
}


// Turn a record part red and then fade it out (with it's parent container if required)
function colourFadeout(parent, total_key, text_colour, background_colour) 
{	
	var parent_links = $ES('a', parent);
	var parent_name = parent.id;
							
	var fx = parent.effects({duration: 1000, transition: Fx.Transitions.Quart.easeOut});
	
	parent_links.each(
		function(el)
		{
			new Fx.Style(el, 'color', {duration: 500}).start(text_colour);
		}
	);
	
	friend_total[total_key]--;
	
	// Either remove the whole approval list, or just the row depending on how many there are left
	fx.start(
		{
			'background-color': background_colour, 
			'color': text_colour
		}
	).chain(
		function()
		{
			fadeoutToHidden(parent);
			
			if(friend_total[total_key] == 0 && total_key == 1)
			{
				$('waiting_approval_wrapper').style.display = 'none';
				//fadeinFromHidden($(parent_name + 'None'));	
			}
			
			parent.removeProperty('id');
		}
	);
}


// Find what quadrant of the page we are in
function findExpandDirections(mX, mY)
{	
	// Are we nearest the left or right?
	x_dir = 'right';
	if(mX < window.getSize().size.x / 2)
	{
		x_dir = 'left';
	}
	
	y_dir = 'top';
	if(mY < window.getSize().size.y / 2)
	{
		y_dir = 'bottom';
	}
}


// Change the size of the popup container
function morphSize(element, width, height) 
{
	var orig_width 	= element.getStyle('width').toInt();
	var orig_height = element.getStyle('min-height').toInt();
	
	var orig_left 	= element.getStyle('left').toInt();
	var orig_top 	= element.getStyle('top').toInt();
	
	// We are morphing the width
	if(width != orig_width)
	{
		var width_diff 	= width - orig_width;

		if(x_dir == 'right')
		{
			var left = orig_left - width_diff;
		}
		else
		{
			var left = orig_left;
		}
	}
	else
	{
		var left = orig_left;
	}

	// We are morphing the height
	if(height != orig_height)
	{			
		var height_diff = height - orig_height;
		
		if(y_dir == 'bottom')
		{
			var top = orig_top;
		}
		else
		{
			var top = orig_top - height_diff;
		}
	}
	else
	{
		var top = orig_top;
	}
	
	var fx = element.effects(
						{
							duration: 1000, 
							transition: Fx.Transitions.Quart.easeOut
						}
					);
	
	// Alter the size
	fx.start(
		{
			'width': width + 'px', 
			'min-height': height + 'px', 
			'top': top + 'px', 
			'left': left + 'px'
		}
	);
}


// Change the size of the container instantly (without transition)
function changeSize(element, width, height) 
{
	element.setStyles(
					{
						'width': width,
						'min-height': height
					}
				);
}


// Fade in from hidden
function fadeinFromHidden(element) 
{
	var myFadeIn = new Fx.Style(element, 'opacity', {duration: 400});
	myFadeIn.hide();
	element.setStyles(
		{
			'display': 'block',
			'opacity': 0
		}
	);
	myFadeIn.start(0, 1);
}


// Appear from hidden
function fadeinNow(element) 
{
	element.setStyles(
		{
			'display': 'block',
			'opacity': 0
		}
	);
}

// Instantly become hidden
function fadeoutNow(element) 
{
	element.setStyles(
		{
			'display': 'none'
		}
	);
}


// Fade out to hidden
function fadeoutToHidden(element) 
{
	var myFadeOut = new Fx.Style(element, 'opacity', {duration: 400});
	
	myFadeOut.start(1, 0).chain(
		function()
		{
			fadeoutNow(element);
		}
	);
}


// Fade an element out and then slide it shut
function fadeoutShut(element) 
{
	new Fx.Style(element, 'opacity', {duration: 500, wait: true}).start(1, 0).chain(
		function() 
		{
			new Fx.Slide(element, {mode: 'vertical'}).slideOut();
		}
	);
}


// Function to restore the main page data
function restoreMain()
{
	if($('back_to_main_link'))
	{
		// Just in case
		$('back_to_main_link').removeEvents();
		
		$('back_to_main_link').addEvent('click', 
			function(e) 
			{
				e = new Event(e).stop();

				sweepInOut(orig_data);
				
				current_view = 'main';
			}
		);
	}
}

function display_loading_spinner()
{
	fadeinFromHidden($('general_spinner'));
}

function hide_loading_spinner()
{
	fadeoutToHidden($('general_spinner'));
}


function disableFormElements(form, fieldset)
{
	var elem = form.elements; 

	for(i = 0; i < elem.length; i++)
	{
		if(elem[i].nodeName == 'INPUT' || elem[i].nodeName == 'SELECT' || elem[i].nodeName == 'TEXTAREA')
		{
			elem[i].readOnly = true;
		}
	}
	if(fieldset)
	{
		fieldset.className = 'standard big disabled';
	}
}

function enableFormElements(form, fieldset)
{
	var elem = form.elements; 

	for(i = 0; i < elem.length; i++)
	{
		if(elem[i].nodeName == 'INPUT' || elem[i].nodeName == 'SELECT' || elem[i].nodeName == 'TEXTAREA')
		{
			elem[i].readOnly = false;
		}
	}
	if(fieldset)
	{
		fieldset.className = 'standard big';
	}
}

function fadeOutPopups()
{
	if($('editPortfolioDiv') && $('editPortfolioDiv').style.display == 'block')
	{
		fadeoutToHidden($('editPortfolioDiv'));
	}
	if($('friendHoverDiv') && $('friendHoverDiv').style.display == 'block')
	{
		fadeoutToHidden($('friendHoverDiv'));
	}
	if($('searchHoverDiv') && $('searchHoverDiv').style.display == 'block')
	{
		fadeoutToHidden($('searchHoverDiv'));
	}
}

// Transition effect for the main screen
function sweepInOut(page_content)
{
	// Close all opened popups
	fadeOutPopups();
	
	var myFadeOut = new Fx.Style($('main_slider'), 'opacity', {duration: 400});
	
	myFadeOut.start(1, 0).chain(
		function()
		{
			hide_loading_spinner();
			$('main_slider').innerHTML = page_content;
			
			myFadeOut.start(0, 1);
			
			if(current_view != 'main')
			{
				restoreMain();
			}
			
			refresh_uploader_links();
			
			addNewWallHandler();
			
			addNewMainWallHandler();
			
			init_privacy_page();
			
			init_profile_links();
			
			init_cv_profile_forms();

			init_profile_settings_forms();

			init_message_page();
		}
	);
}

/* Initialisers *************************************************************************************/

function init_message_page()
{
	init_message_tabs();
	init_message_read_links();
	init_message_delete_links();
}

function init_message_read_links()
{
	$$('a.read_message').each(
		function(reader)
		{
			reader.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();

					var url = reader.href + '&noreturn=1';

					initialiseHoverDiv('friendHoverDiv', 250, 115, true);

					var mouseX = e.client.x + window.getScrollLeft();
					var mouseY = e.client.y + window.getScrollTop();
					
					calculateDivPosition('friendHoverDiv', mouseX, mouseY);

					new Ajax(url, 
						{	
							method: 'get',
							onComplete: function(e)
							{	
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{
									morphSize($('friendHoverDiv'), myObject['width'], myObject['height']);
									
									$('friendHoverDivTitle').innerHTML 		= myObject['head_response'];
									$('friendHoverDivContent').innerHTML 	= myObject['response'];
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					).request();
				}
			);
		}
	);
}

function init_message_delete_links()
{
	$$('a.delete_message').each(
		function(reader)
		{
			reader.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();

					var url = reader.href + '&sure=1&noreturn=1';

					if(confirm($('del_priv_msg_txt').value))
					{
						new Ajax(url, 
							{	
								method: 'get',
								onComplete: function(e)
								{	
									var myObject = Json.evaluate(this.response.text);
									
									if(myObject['error'].length == 0)
									{
										if($('priv_msg_' + myObject['deleted']))
										{
											var count = 0;
											$$('div.priv_message_div').each(
												function(div)
												{
													if(div.style.display != 'none')
													{
														count++;
													}
												}
											);
											fadeoutToHidden($('priv_msg_' + myObject['deleted']));
											if(count <= 1)
											{
												$('no_priv_msg').style.display = 'block';
											}
										}
										alert(myObject['response']);
									}
									else
									{
										alert(myObject['error']);
									}
								}
							}
						).request();
					}
				}
			);
		}
	);
}

function init_message_tabs()
{
	$$('a.message_tab_link').each(
		function(tabLink)
		{
			tabLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					var url = tabLink.href + '&noreturn=1&justcontent=1';
					
					new Ajax(url, 
						{	
							method: 'get',
							onComplete: function(e)
							{	
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{
									$('content').innerHTML = myObject['response'];
									
									$$('a.message_tab_link').each(
										function(link)
										{
											if(link.id == tabLink.id)
											{
												link.getParent().className = 'active';
											}
											else
											{
												link.getParent().removeProperty('class');
											}
										}
									);
									

									init_message_msg_form();
									init_message_read_links();
									init_message_delete_links();
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					).request();
				}
			);
		}
	);
}

function init_message_msg_form()
{
	if($('private_msg_form'))
	{
		$('private_msg_form').addEvent('submit', 
			function(e)
			{
				e = new Event(e).stop();
				
				display_loading_spinner();
				
				$('private_msg_form').action += '?noreturn=1';
				$('private_msg_form').send(
					{
						onComplete: function()
						{		
							hide_loading_spinner();

							var myObject = Json.evaluate(this.response.text);
							
							if(myObject['error'].length == 0)
							{
								$('private_msg_input').value = '';

								alert(myObject['response']);
							}
							else
							{
								alert(myObject['error']);
							}
						}
					}
				);
			}
		);
	}
}




/* Friend functionsÊ*************************************************************************************/

function completeFriendSearch(myObject)
{
	if(myObject['error'].length == 0)
	{
		$('searchHoverDivTitle').innerHTML 		= myObject['head_response'];
		$('searchHoverDivContent').innerHTML 	= myObject['response'];
		
		addNewSearchHandler();
	}
	else
	{
		$('searchHoverDivTitle').innerHTML 		= myObject['head_response'];
		$('searchHoverDivContent').innerHTML 	= myObject['error'];
	}
	
	$$('a.friend_search_pagin_link').each(
		function(pagingLink)
		{
			pagingLink.addEvent('click',
				function(e)
				{
					e = new Event(e).stop();
					
					var url = pagingLink.href + '&noreturn=1';
					
					$('searchHoverDivContent').innerHTML = '<center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /></center>';
	
					new Ajax(url, 
						{
							method: 'get',
							onComplete: function(e)
							{	
								var myObject = Json.evaluate(this.response.text);
								
								completeFriendSearch(myObject);
							}
						}
					).request();
					
					
				}
			);
		}
	);
}


// Pop up the box giving the user their specific friend options
function showFriendDefaultOptions(friend_uid, profile_uid, url, mouseX, mouseY, message)
{
	if(profile_uid == 0)
	{
		profile_uid = $('profile_uid').value;
	}
	if(url.length == 0)
	{
		url = $('siteurl').value + '/profile_information/friend_request.php?friend_uid=' + friend_uid + '&details=1&profile_uid=' + profile_uid;
	}
	url += '&noreturn=1&message=' + message;
	
	initialiseHoverDiv('friendHoverDiv', 250, 115, true);
	
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
				
				if(myObject['error'].length == 0)
				{
					morphSize($('friendHoverDiv'), myObject['width'], myObject['height']);
					
					$('friendHoverDivTitle').innerHTML 		= myObject['head_response'];
					$('friendHoverDivContent').innerHTML 	= myObject['response'];
					
					// If the user clicks the private message button
					if($('privateMessage'))
					{
						$('privateMessage').addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								showFriendMessageForm(myObject['friend_uid'], '');
							}
						);
					}
					
					// If the user clicks the wall button
					if($('wallMessage'))
					{
						$('wallMessage').addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								showFriendMessageForm(myObject['friend_uid'], '');
							}
						);
					}
					
					// If the user clicks remove friend button
					if($('friendRemove'))
					{
						$('friendRemove').addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								friendRemove();
							}
						);
					}
					
					// If the user clicks the add friend button (they are on someone elses profile)
					if($('friendAdd'))
					{
						$('friendAdd').addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								friendAdd(myObject['friend_uid'], '');
							}
						);
					}
					
					// If the user clicks the withdraw friend request button (they are on someone elses profile)
					if($('friendWithdraw'))
					{
						$('friendWithdraw').addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								friendWithdraw(myObject['friend_uid'], '', 0);
							}
						);
					}
					
					// If the user clicks the friend reject button (they are on someone elses profile)
					if($('friendReject'))
					{
						$('friendReject').addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								friendReject(myObject['friend_uid'], '');
							}
						);
					}
				}
				else
				{
					//$('friendHoverDivTitle').innerHTML 	= 'Error';
					$('friendHoverDivContent').innerHTML 	= myObject['error'];
				}
			}
		}
	).request();
	
	calculateDivPosition('friendHoverDiv', mouseX, mouseY);
}

// Removes a current friend from the list
function friendRemove()
{
	var url = $('friendRemove').href + '&noreturn=1';
								
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
										
				if(myObject['error'].length == 0)
				{
					fadeoutToHidden($('friendHoverDiv'));
				
					if($('friend_' + myObject['friend_uid']))
					{
						var friend_link = $('friend_' + myObject['friend_uid']);
					}
					else if($('friend_' + myObject['my_uid']))
					{
						var friend_link = $('friend_' + myObject['my_uid']);
					}

					colourFadeout(friend_link.getParent(), 3, '#ff0000', '#ffb0b0');
					
					if(friend_total[3] == 0)
					{
						fadeoutToHidden($('friendsList'));
						fadeinFromHidden($('friendsListNone'));
					}
					
					$('tot_friends_shown').innerHTML = $('tot_friends_shown').innerHTML.toInt() - 1;
					
					$('tot_friends').innerHTML = $('tot_friends').innerHTML.toInt() - 1;
					
					if($('tot_friends_shown').innerHTML == '0')
					{
						$('tot_friends_shown').style.display == 'none';
						$('friendsListNone').style.display == 'block';
					}
				}
				else
				{
					showFriendMessageForm(myObject['friend_uid'], myObject['error']);
				}
			}
		}
	).request();
}


// Adds a person to the awaiting approval list
function friendAdd(uid, errorMessage)
{
	var url = $('siteurl').value + '/profile_information/friend_request.php?friend_uid=' + uid + '&addfriend=1&noreturn=1&errorMessage=' + errorMessage + '&special=1';
								
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
										
				if(myObject['error'].length == 0)
				{
					friend_total[2]++;
					if(friend_total[2] == 1)
					{
					  //fadeoutToHidden($('awaitingDecisionNone'));
					  fadeinFromHidden($('waiting_decision_wrapper'));
					}
					// Update the friends list
					$('awaitingDecision').innerHTML = myObject['response'] + $('awaitingDecision').innerHTML;
					
					// Make sure JavaScript is attached to the link
					addNewFriendHandler();
					addNewFriendWithdrawHandler();
					fadeinFromHidden($('friendWithdraw_' + myObject['friend_uid']));
						
					showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, myObject['message']);
				}
				else
				{
					showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, myObject['error']);
				}
			}
		}
	).request();
}


// Withdraws a friend request to a user
function friendWithdraw(uid, url, showOptions)
{
	if(url.length == 0)
	{
		url = $('siteurl').value + '/profile_information/friend_request.php?friend_uid=' + uid + '&withdrawfriend=1';
	}
	url += '&noreturn=1';
	
	
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
										
				if(myObject['error'].length == 0)
				{
					if($('friendWithdraw_' + myObject['friend_uid']))
					{
						colourFadeout($('friendWithdraw_' + myObject['friend_uid']), 2, '#ff0000', '#ffb0b0');
						
						if(friend_total[2] == 0)
						{
							fadeoutToHidden($('waiting_decision_wrapper'));
						}
						
						$('friendWithdraw_' + myObject['friend_uid']).removeProperty('id');
					}
					else
					{
						//alert('Could not remove: friendWithdraw_' + myObject['friend_uid']);
					}
					
					if(showOptions != 1)
					{
						showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, myObject['message']);
					}
				}
				else
				{
					if(showOptions != 1)
					{
						showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, myObject['error']);
					}
				}
			}
		}
	).request();
}


function addNewFriendWithdrawHandler()
{
	if($$('a.friendWithdraw'))
	{
		// Add onclick to the withdraw links if there are any
		$$('a.friendWithdraw').each(
			function(withdrawLink)
			{	
				withdrawLink.addEvent('click', 
					function(e) 
					{
						e = new Event(e).stop();
					 	
					 	friendWithdraw('', withdrawLink.href, 1);
					}
				);
			}
		);	
	}
}


// Rejects a friend request
function friendReject(uid, errorMessage)
{
	var url = $('siteurl').value + '/profile_information/friend_request.php?friend_uid=' + uid + '&rejectfriend=1&noreturn=1&errorMessage=' + errorMessage;
								
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
										
				if(myObject['error'].length == 0)
				{
					showFriendDefaultOptions(uid, 0, '', orig_x, orig_y, myObject['message']);
				}
				else
				{
					showFriendDefaultOptions(uid, 0, '', orig_x, orig_y, myObject['error']);
				}
			}
		}
	).request();
}


// Changes to the popup with the private message details in it
function showFriendMessageForm(uid, errorMessage)
{
	url = $('siteurl').value + '/profile_information/wall_message.php?friend_uid=' + uid + '&compose=1&noreturn=1&existing=' + $('friendHoverDivTitle').innerHTML + '&errorMessage=' + errorMessage;
			
	$('friendHoverDivContent').innerHTML = '<center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /></center>';
	
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
				
				morphSize($('friendHoverDiv'), myObject['width'], myObject['height']);
				
				$('friendHoverDivTitle').innerHTML 		= myObject['head_response'];
				$('friendHoverDivContent').innerHTML 	= myObject['response'];
				
				// If the user clicks the back button
				$('friendHoverDivResetLink').addEvent('click', 
					function(e) 
					{
						e = new Event(e).stop();
						
						showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, '');
					}
				);
				
				// Submit the wall form
				if($('wallForm'))
				{
					$('wall_inline').focus();
					$('wallForm').addEvent('submit', 
						function(e)
						{
							e = new Event(e).stop();
					 
							$('wallForm').send(
								{
									onComplete: function()
									{	
										var myObject = Json.evaluate(this.response.text);
										
										if(myObject['error'].length == 0)
										{											
											// If the post is on someone elses wall, make it appear
											if(myObject['special'] == 1)
											{
												// Update the wall posts
												$('wallList').innerHTML = myObject['response'] + $('wallList').innerHTML;
												
												fadeinFromHidden($('newWallPost'));
												
												$('newWallPost').removeProperty('id');
												
												// Make sure the new links are clickable
												addNewWallHandler();
											}
										
											// Show the default again
											showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, myObject['message']);
										}
										else
										{
											showFriendMessageForm(myObject['friend_uid'], myObject['error']);	
										}
									}
								}
							);
							
							$('friendHoverDivContent').innerHTML = '<center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /><br />' + $('posting_msg_txt').value + '</center>';
						}
					);
				}
				
				// Submit the wall form
				if($('pmForm'))
				{
					$('pmForm').addEvent('submit', 
						function(e)
						{
							e = new Event(e).stop();
					 
							$('pmForm').send(
								{
									onComplete: function()
									{											
										var myObject = Json.evaluate(this.response.text);
										
										if(myObject['error'].length == 0)
										{												
											// Show the default again
											showFriendDefaultOptions(myObject['friend_uid'], 0, '', orig_x, orig_y, myObject['message']);
										}
										else
										{
											showFriendMessageForm(myObject['friend_uid'], myObject['error']);
										}
									}
								}
							);
							
							$('friendHoverDivContent').innerHTML = '<center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /><br />' + $('sending_msg_txt').value + '</center>';
						}
					);
				}
				
			}
		}
	).request();
}

// Called when a new friend is added and upon initialisation to make sure they all have events
function addNewFriendHandler()
{	
	// Add onclick to the current friend links if there are any		
	$$('a.currentFriend').each(
		function(currentFriendLink)
		{
			// make sure we are not loading the same events many times
			currentFriendLink.removeEvents();
			
			currentFriendLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					var xCoord = e.client.x + window.getScrollLeft();
					var yCoord = e.client.y + window.getScrollTop();
					
					orig_x = xCoord;
					orig_y = yCoord;
					
					findExpandDirections(e.client.x, e.client.y);
					
					showFriendDefaultOptions('', 0, currentFriendLink.href, xCoord, yCoord, '');
				}
			);
		}
	);
}


// Called when a new friend is added and upon initialisation to make sure they all have events
function addNewWallHandler()
{	
	// Add onclick to the current friend links if there are any		
	$$('a.wallFriend').each(
		function(wallFriendLink)
		{
			// Make sure we are not loading the same events many times
			wallFriendLink.removeEvents();
			
			wallFriendLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					var xCoord = e.client.x + window.getScrollLeft();
					var yCoord = e.client.y + window.getScrollTop();
					
					orig_x = xCoord;
					orig_y = yCoord;
					
					findExpandDirections(e.client.x, e.client.y);
					
					showFriendDefaultOptions('', 0, wallFriendLink.href, xCoord, yCoord, '');
				}
			);
		}
	);
}


// Called when a new search is conducted
function addNewSearchHandler()
{	
	// Add onclick to the current friend links if there are any		
	$$('a.searchFriend').each(
		function(searchFriendLink)
		{
			// Make sure we are not loading the same events many times
			searchFriendLink.removeEvents();
			
			searchFriendLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					var xCoord = e.client.x + window.getScrollLeft();
					var yCoord = e.client.y + window.getScrollTop();
					
					orig_x = xCoord;
					orig_y = yCoord;
					
					findExpandDirections(e.client.x, e.client.y);
					
					showFriendDefaultOptions('', 0, searchFriendLink.href, xCoord, yCoord, '');
				}
			);
		}
	);
}



// Add Javascript to the inline main wall posting (if it exists)
function addNewMainWallHandler()
{
	if($('in_page_wall1'))
	{
		$('in_page_wall1').addEvent('submit', 
			function(e)
			{
				e = new Event(e).stop();
				
				$('in_page_wall1').action += '&noreturn=1';
				
				$('in_page_wall1').send(
					{
						onComplete: function()
						{
							// Remove any unnecessary holding messages
							if($('noWallPosts'))
							{
								var mySlider = new Fx.Slide('noWallPosts');
								mySlider.hide();
								
								$('noWallPosts').removeProperty('id');
							}
							
							if($('noWallPosts1'))
							{
								var mySlider = new Fx.Slide('noWallPosts1');
								mySlider.hide();
								
								$('noWallPosts1').removeProperty('id');
							}
							
							$('in_page_wall_content1').setStyles(
								{
									'background': 'white'
								}
							);
							
							var myObject = Json.evaluate(this.response.text);
							
							if(myObject['error'].length == 0)
							{
								// Hide any errors
								$('WallMainFormError1').innerHTML = '';
								fadeoutToHidden($('WallMainFormError1'));
								
								// Main wall
								//--------------------------------------------------
								// Update the wall posts
								$('wallList1').innerHTML = myObject['response'] + $('wallList1').innerHTML;
								
								fadeinFromHidden($('newWallPost'));
								
								// Blank the textarea
								$('in_page_wall_content1').value = '';
								
								$('newWallPost').removeProperty('id');
								
								// Increment the main wall counter
								$('wallCount1').innerHTML = $('wallCount1').innerHTML.toInt() + 1;
								
								
								// Side wall
								//--------------------------------------------------
								// Update the wall posts
								$('wallList').innerHTML = myObject['response'] + $('wallList').innerHTML;
								
								fadeinFromHidden($('newWallPost'));
								
								// Blank the textarea
								$('in_page_wall_content').value = '';
								
								$('newWallPost').removeProperty('id');
								
								
								// Make sure the new links are clickable
								addNewWallHandler();
							}
							else
							{
								// Show the error
								$('WallMainFormError1').innerHTML = myObject['error'];
								fadeinFromHidden($('WallMainFormError1'));
							}
						}
					}
				);
				
				$('in_page_wall_content1').setStyles(
					{
						'background': 'white url(\'profile_information/spinner.gif\') no-repeat center center'
					}
				);
			}
		);
	}
}




/* Media functions *************************************************************************************/


function init_privacy_page()
{
	$$('a.cv_profile_link').each(
		function(tabLink)
		{
			tabLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					$$('div.profile_set').each(
						function(profDiv)
						{
							if(profDiv.id == tabLink.id + '_div')
							{
								profDiv.style.display = 'block';
							}
							else
							{
								profDiv.style.display = 'none';
							}
						}
					);
					$$('a.cv_profile_link').each(
						function(proLink)
						{
							if(proLink.id == tabLink.id)
							{
								proLink.getParent().className = 'active';
							}
							else
							{
								proLink.getParent().removeProperty('class');
							}
						}
					);
				}
			);
		}
	);
}


function init_cv_profile_forms()
{
	$$('form.ed_profile_form').each(
		function(pForm)
		{
			pForm.addEvent('submit', 
				function(e)
				{
					e = new Event(e).stop();
					
					display_loading_spinner();
					disableFormElements(pForm, $(pForm.id + '_fs'));
					
					pForm.action += '?noreturn=1';
					pForm.send(
						{
							onComplete: function()
							{		
								hide_loading_spinner();
								enableFormElements(pForm, $(pForm.id + '_fs'));
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{
									var profile_uid = $(pForm.id + '_hid').value;
									$('profile_set_' + profile_uid).innerHTML = $('ed_title[' + profile_uid + ']').value;
									
									alert(myObject['response']);
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					);
				}
			);
		}
	);
}

function init_profile_settings_forms()
{
	$$('form.profile_settings_form').each(
		function(pForm)
		{
			pForm.addEvent('submit', 
				function(e)
				{
					e = new Event(e).stop();
					
					display_loading_spinner();
					
					pForm.action += '?noreturn=1';
					pForm.send(
						{
							onComplete: function()
							{		
								hide_loading_spinner();
								
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{									
									alert(myObject['response']);
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					);
				}
			);
		}
	);
}

function init_profile_links()
{
	if($('add_profile_link'))
	{
		$('add_profile_link').addEvent('click', 
			function(e) 
			{
				e = new Event(e).stop();
				
				var name = prompt($('newprof_prompt_txt').value);
				
				if(name)
				{
					name = name.replace(/\&/g, '&amp;');

					var url = $('add_profile_link').href + '&noreturn=1&name=' + name;
	
					display_loading_spinner();
					
					new Ajax(url, 
						{	
							method: 'get',
							onComplete: function(e)
							{	
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{
									location.reload(true);
									/*
									// Store the old data for a speedy return to the main view
									if(!orig_data_stored)
									{
										orig_data 			= $('main_slider').innerHTML;
										orig_data_stored 	= true;
									}
									sweepInOut(myObject['response']);
									
									// Remember to add links back to the main data, and to edit the blog
									current_view = 'privacy_settings';
									*/
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					).request();
				}
			}
		);
	}
	
	$$('a.remove_profile_link').each(
		function(link)
		{
			link.addEvent('click', 
				function(e)
				{
					e = new Event(e).stop();
					
					if(confirm($('txt_confirm_profile_delete').value))
					{
						display_loading_spinner();
						
						var url = link.href + '&noreturn=1&sure=1';
						new Ajax(url, 
							{	
								method: 'get',
								onComplete: function(e)
								{	
									var myObject = Json.evaluate(this.response.text);
									
									if(myObject['error'].length == 0)
									{
										location.reload(true);
										/*
										// Store the old data for a speedy return to the main view
										if(!orig_data_stored)
										{
											orig_data 			= $('main_slider').innerHTML;
											orig_data_stored 	= true;
										}
										sweepInOut(myObject['response']);
										
										// Remember to add links back to the main data, and to edit the blog
										current_view = 'privacy_settings';
										*/
									}
									else
									{
										alert(myObject['error']);
									}
								}
							}
						).request();
					}
				}
			);
		}
	);
	
	$$('a.set_profile_default_link').each(
		function(link)
		{
			link.addEvent('click', 
				function(e)
				{
					e = new Event(e).stop();
					

					display_loading_spinner();
					
					var url = link.href + '&noreturn=1';
					new Ajax(url, 
						{	
							method: 'get',
							onComplete: function(e)
							{	
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{
									// Store the old data for a speedy return to the main view
									if(!orig_data_stored)
									{
										orig_data 			= $('main_slider').innerHTML;
										orig_data_stored 	= true;
									}
									sweepInOut(myObject['response']);
									
									// Remember to add links back to the main data, and to edit the blog
									current_view = 'privacy_settings';
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					).request();
				}
			);
		}
	);
	
}


function remove_portfolio_item(portfolio_id)
{
	var itemsLeft = false;
	
	if($('portfolio_item[' + portfolio_id + ']'))
	{
		var element = $('portfolio_item[' + portfolio_id + ']');
		
		element.style.backgroundColor = '#ff3300';
		
		new Fx.Style(element, 'opacity', {duration: 500, wait: true}).start(1, 0).chain(
			function() 
			{
				element.style.display = 'none';
				
				$$('li.profile_media_item').each(
					function(portfolioItem)
					{
						if(portfolioItem.id != element.id && portfolioItem.style.visibility != 'hidden' && portfolioItem.style.display != 'none')
						{
							itemsLeft = true;
						}
					}
				);
				
				if(!itemsLeft)
				{
					$('no_mediaitems_text').style.display = 'inline';
				}
			}
		);
	}
	remove_leftbar_item(portfolio_id)
}

function remove_leftbar_item(portfolio_id)
{
	if($('left_media_item[' + portfolio_id + ']'))
	{
		var elementx 	= $('left_media_item[' + portfolio_id + ']');
				
		var par	= elementx.parentNode;
		if(par.id == 'profile_mainpicture_link')
		{
			// move next image into mainpic if left else show 'none left'
			var nextPic = get_next_visible_image();
			if(nextPic != null)
			{
				// Move next image into mainwrapper
				elementx.src 		= nextPic.src;
				var nextPicWrapper	= nextPic.parentNode.parentNode;
				
				new Fx.Style(nextPicWrapper, 'opacity', {duration: 500, wait: true}).start(1, 0).chain(
					function() 
					{
						nextPicWrapper.style.display = 'none';
						var oldWrapper 	= nextPicWrapper.parentNode.removeChild(nextPicWrapper);
						elementx.id		= oldWrapper.id;
						check_remove_media_headline($('profile_images'), elementx);
					}
				);
			}
			else
			{
				// Display 'no item uploaded yet'
				fade_out_media_item(elementx);

				$('profile_mainpicture').innerHTML = $('no_mainpic_text').value;
			}
		}
		else
		{
			fade_out_media_item(elementx);
			// Delete headline if no item left
			check_remove_media_headline(par, elementx);
		}
	}
}
			
function check_remove_media_headline(par, elementx)
{
	var children	= par.childNodes;
	var count		= count_visible_media_items(par, elementx);

	if(count < 1)
	{
		var headline = $(par.id + '_headline');
		new Fx.Style(headline, 'opacity', {duration: 500, wait: true}).start(1, 0).chain(
			function() 
			{
				headline.style.display = 'none';
			}
		);
	}
}
function fade_out_media_item(elementx)
{
	elementx.style.backgroundColor = '#ff3300';
	
	new Fx.Style(elementx, 'opacity', {duration: 500, wait: true}).start(1, 0).chain(
		function() 
		{
			elementx.style.display = 'none';
		}
	);
}

function count_visible_media_items(wrapper, elementx)
{
	var children	= wrapper.childNodes;
	var count		= 0;
	for(var i = 0; i < children.length; i++)
	{
		if(children[i].visibility != 'hidden' && children[i].style.display != 'none' && children[i].id != elementx.id && children[i].className != 'clearline')
		{
			count++;
		}
	}
	return count;
}

function get_next_visible_image()
{
	var children	= $('profile_images').childNodes;
	var result		= null;
	var i = 0;
	while(i < children.length && result == null)
	{
		if(children[i].visibility != 'hidden' && children[i].style.display != 'none' && children[i].className != 'clearline')
		{
			if(children[i].childNodes.length > 0 && children[i].childNodes[0].childNodes.length > 0)
			{
				result = children[i].childNodes[0].childNodes[0];
			}
		}
		i++;
	}
	return result;
}

function check_for_new_media_items(url)
{
	// Build an array of the existing media files to check out new ones
	var i 		= 0;
	var param 	= '?check_new_portfolio=1';
	
	$$('li.profile_media_item').each(
		function(portfolioItem)
		{
			param += '&item[' + i + ']=' + portfolioItem.id;
			i++;
		}
	);
	
	new Ajax(url + param, 
		{
			method: 'get',
			onComplete: function(e)
			{	
				var myObject = Json.evaluate(this.response.text);
				
				if(myObject['error'].length > 0)
				{
					alert(myObject['error']);
				}
				else
				{
					if(myObject['portfolio_uid'].length > 0)
					{
						add_leftbar_media(	myObject['portfolio_uid'], 
											myObject['metatype'], 
											myObject['site_uid'], 
											myObject['image_text'], 
											myObject['video_text'], 
											myObject['audio_text'],
											myObject['login_uid'],
											myObject['site_url'],
											myObject['description']);
											
						$('existing_items').innerHTML += myObject['item'];
						$('no_mediaitems_text').style.display = 'none';
						add_delete_portfolio_links();
						
						if(myObject['mediatype'] == '1' && $('media_files_uploaded'))
						{
							$('media_files_uploaded').innerHTML = $('media_files_uploaded').innerHTML.toInt() + 1;
							
							handle_media_files_limit();
						}
					}
				}
			}
		}
	).request();
}

function add_leftbar_media(item_uid, item_type, site_uid, img_text, vid_text, aud_text, login_uid, site_url, description)
{
	var location = Math.floor(item_uid / 5000);
	if(item_type == 'picture')
	{
		if($('profile_mainpicture_link'))
		{
			show_media_headline(item_type);
			var newCont  = '';
			newCont 	+= '<div class="profile_item" style="min-height: 110px; width: 150px; visibility: hidden" id="left_media_item[' + item_uid + ']">';
			newCont 	+= '<a href="javascript:;" title="' + img_text + '" onclick="javascript:window.open(\'portfolioview.php?viewee_uid=' + login_uid + '&amp;portfolio_uid=' + item_uid + '\', \'img\', \'width=400, height=400, directories=no, location=no, menubar=no, scrollbars=yes, status=yes, toolbar=no, resizable=yes\');"><img src="http://' + site_url + '/uploads/site_' + site_uid + '/thumb200/' + location + '/' + item_uid + '.jpg" style="width: 150px; border: 0;" class="pointerhand" alt="IMG" onload="fade_new_leftbaritem(' + item_uid + ', false);" /></a>';
			
			
			newCont 	+= '</div><div class="clearline"></div>';
			$('profile_images').innerHTML = $('profile_images').innerHTML.replace(/<div class="clearline"><\/div>/, '') + newCont;
		}
		else
		{
			// image gets profile picture
			var newCont 	 = '';
			newCont			+= '<a style="visibility: hidden" href="javascript:;" id="profile_mainpicture_link" title="' + img_text + '" onclick="javascript:window.open(\'portfolioview.php?viewee_uid=' + login_uid +'&amp;portfolio_uid=' + item_uid + '\', \'img\', \'width=400, height=400, directories=no, location=no, menubar=no, scrollbars=yes, status=yes, toolbar=no, resizable=yes\');">';
				newCont			+= '<img src="uploads/site_' + site_uid + '/thumb200/' + location +'/' + item_uid + '.jpg" class="pointerhand" id="left_media_item[' + item_uid + ']" alt="PIC" onload="fade_new_leftbaritem(' + item_uid + ', true);" />';
			newCont			+= '</a>';
			$('profile_mainpicture').innerHTML = newCont;
		}
	}
	if(item_type == 'video')
	{
		show_media_headline(item_type);
		var newCont  = '';
		
		newCont 	+= '<li style="min-height: 29px; visibility: hidden" id="left_media_item[' + item_uid + ']">';
		newCont 	+= '<a href="javascript:;" title="' + vid_text + '" onclick="javascript:window.open(\'portfolioview.php?viewee_uid=' + login_uid + '&amp;portfolio_uid=' + item_uid + '\', \'' + description + '\', \'width=400, height=400, directories=no, location=no, menubar=no, scrollbars=yes, status=yes, toolbar=no, resizable=yes\');"><img src="http://' + site_url + '/images/videoicon_tiny.gif" style="float: left; border: 0; width: 23px; height: 30px; margin-right: 6px;"  onload="fade_new_leftbaritem(' + item_uid + ', false);" class="pointerhand" alt="VID" />';
		newCont 	+= description + '</a></li>';
		$('profile_video').innerHTML += newCont;	
	}
	if(item_type == 'audio')
	{
		show_media_headline(item_type);
		var newCont  = '';
		
		newCont 	+= '<li style="min-height: 29px; visibility: hidden" id="left_media_item[' + item_uid + ']">';
		newCont 	+= '<a href="javascript:;" title="' + aud_text + '" onclick="javascript:window.open(\'portfolioview.php?viewee_uid=' + login_uid + '&amp;portfolio_uid=' + item_uid + '\', \'' + description + '\', \'width=400, height=200, directories=no, location=no, menubar=no, scrollbars=yes, status=yes, toolbar=no, resizable=yes\');"><img src="http://' + site_url + '/images/mp3icon_tiny.gif" style="float: left; border: 0; width: 23px; height: 30px; margin-right: 6px;" onload="fade_new_leftbaritem(' + item_uid + ', false);" class="pointerhand" alt="MP3" />';
		newCont 	+= description + '</a></li>';
		$('profile_audio').innerHTML += newCont;	
	}
}

function show_media_headline(metaType)
{
	if(metaType == 'picture')
	{
		var wrapper = $('profile_images');
	}
	if(metaType == 'video' || metaType == 'flash')
	{
		var wrapper = $('profile_video');
	}
	if(metaType == 'audio')
	{
		var wrapper = $('profile_audio');
	}
	if(wrapper)
	{
		var headline = $(wrapper.id + '_headline');
		if(headline.style.display == 'none')
		{
			headline.style.visibility 	= 'hidden'; 
			headline.style.display 		= 'block';
			new Fx.Style(headline, 'opacity', {duration: 500, wait: true}).start(0, 1);
			wrapper.style.visibility 	= 'hidden'; 
			wrapper.style.display 		= 'block';
			new Fx.Style(wrapper, 'opacity', {duration: 500, wait: true}).start(0, 1);
		}
	}	
}
	
function fade_new_leftbaritem(portfolio_id, fadeParent)
{
	var element = $('left_media_item[' + portfolio_id + ']');
	if(fadeParent)
	{
		element = element.parentNode;
	}
	if(element.style.visibility == 'hidden')
	{
		new Fx.Style(element, 'opacity', {duration: 500, wait: true}).start(0, 1);
	}
}

function fade_new_mediaitem(portfolio_id)
{
	var element = $('portfolio_item[' + portfolio_id + ']');

	if(element.style.visibility == 'hidden')
	{
		new Fx.Style(element, 'opacity', {duration: 500, wait: true}).start(0, 1);
	}
}

function add_delete_portfolio_links()
{
	$$('a.delete_portfolio_link').each(
		function(deleteLink)
		{
			deleteLink.removeEvents();
			
			deleteLink.addEvent('click', 
				function(e)
				{
					e = new Event(e).stop();
					
					final_delete_item(this);
				}
			);
		}
	);
	
	$$('a.edit_portfolio_link').each(
		function(editLink)
		{
			editLink.removeEvents();
			
			editLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					var xCoord = e.client.x + window.getScrollLeft();
					var yCoord = e.client.y + window.getScrollTop();
					
					orig_x = xCoord;
					orig_y = yCoord;
						
					findExpandDirections(e.client.x, e.client.y);
					
					showPortfolioEdit(editLink, xCoord, yCoord, true);
				}
			);
		}
	);
	
	$$('a.activate_portfolio_link').each(
		function(actiLink)
		{
			actiLink.removeEvents();
			
			actiLink.addEvent('click', 
				function(e) 
				{
					e = new Event(e).stop();
					
					var url = actiLink.href + '&noreturn=1';
					new Ajax(url, 
						{	
							method: 'get',
							onComplete: function(e)
							{	
								var myObject = Json.evaluate(this.response.text);
								
								if(myObject['error'].length == 0)
								{
									var portfolio_uid	= myObject['portfolio_uid'];
									$('portfolio_item[' + portfolio_uid + ']').style.backgroundColor = 'white';
									$('activate_portfolio[' + portfolio_uid + ']').style.display = 'none';
									
									add_leftbar_media(	myObject['portfolio_uid'], 
														myObject['metatype'], 
														myObject['site_uid'], 
														myObject['image_text'], 
														myObject['video_text'], 
														myObject['audio_text'],
														myObject['login_uid'],
														myObject['site_url'],
														myObject['description']);
								}
								else
								{
									alert(myObject['error']);
								}
							}
						}
					).request();
				}
			);
		}
	);
}

function handle_media_files_limit()
{
	if($('media_files_uploaded') && $('media_items_limit_reached') && $('media_items_existing'))
	{
		var num_files = $('media_files_uploaded').innerHTML.toInt();
		
		$('media_items_limit_reached').style.display 	= 'none';
		$('media_items_existing').style.display 		= 'none';
		if(num_files >= 5)
		{
			$('media_items_limit_reached').style.display 	= 'block';
			if($('FlashFilesUpload'))
			{
				$('FlashFilesUpload').style.display				= 'none';
			}
		}
		else if(num_files > 0)
		{
			$('media_items_existing').style.display 		= 'block';
		}
	}
}


function final_delete_item(deleteLink)
{
	var url = deleteLink.href + '&noreturn=1';
	new Ajax(url, 
		{
			method: 'get',
				onComplete: function(e)
				{
					var result = this.response.text;
					
					if(result.length > 0)
					{
						var myObject = Json.evaluate(this.response.text);
						
						if(myObject['error'].length > 0)
						{
							alert(myObject['error']);
						}
						else
						{
							if(myObject['remove_portfolio'].length > 0)
							{
								remove_portfolio_item(myObject['remove_portfolio']);
								if(myObject['mediatype'] == '1' && $('media_files_uploaded'))
								{
									$('media_files_uploaded').innerHTML = $('media_files_uploaded').innerHTML.toInt() - 1;
									
									if($('media_files_uploaded').innerHTML.toInt() == 4)
									{
										load_uploader('http://' + myObject['site_url'] + '/profile_information/media.php?uploader=2');
									}
									else
									{
										handle_media_files_limit();
									}
								}
							}
						}
					}
				}
		}
	).request();
}


function handlePortfolioForm()
{
	if($('edMediaForm'))
	{
		$('edMediaForm').addEvent('submit', 
			function(e)
			{
				e = new Event(e).stop();
				
				 $('edMediaForm').action += '&noreturn=1';
				$('edMediaForm').send(
					{
						onComplete: function()
						{											
							var myObject = Json.evaluate(this.response.text);
							
							if(myObject['error'].length == 0)
							{
								// Show the default again
								$('editPortfolioDivContent').innerHTML 	= '<center><p>' + myObject['message'] + '</p><p><a href="javascript:close_portfolio_window();">[' + $('close_link_txt').value + ']</a></p></center>';
								if(myObject['vis_added'] == 1)
								{
									var portfolio_uid	= myObject['portfolio_uid'];
									$('portfolio_item[' + portfolio_uid + ']').style.backgroundColor = 'white';
									$('activate_portfolio[' + portfolio_uid + ']').style.display = 'none';
									
									add_leftbar_media(	myObject['portfolio_uid'], 
														myObject['metatype'], 
														myObject['site_uid'], 
														myObject['image_text'], 
														myObject['video_text'], 
														myObject['audio_text'],
														myObject['login_uid'],
														myObject['site_url'],
														myObject['description']);
								}
								else if(myObject['vis_removed'] == 1)
								{
									var portfolio_uid	= myObject['portfolio_uid'];
									$('portfolio_item[' + portfolio_uid + ']').style.backgroundColor = 'red';
									$('activate_portfolio[' + portfolio_uid + ']').style.display = 'inline';
									remove_leftbar_item(portfolio_uid);
								}
							}
							else
							{
								$('editPortfolioDivContent').innerHTML 	= '<p><center>' + myObject['message'] + '</center></p>';
							}
							if($('ed_portf_desc_' + myObject['portfolio_uid']))
							{
								$('ed_portf_desc_' + myObject['portfolio_uid']).innerHTML = myObject['description'];
							}
						}
					}
				);
				
				$('editPortfolioDivContent').innerHTML = '<p><center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /><br />' + $('sending_msg_txt').value + '</center></p>';
				morphSize($('editPortfolioDiv'), 250, 125);
			}
		);
	}
}

function close_portfolio_window()
{
	fadeoutToHidden($('editPortfolioDiv'));
}

// Pop up the box giving the portfolio-edit options
function showPortfolioEdit(editLink, mouseX, mouseY, initDiv)
{
	var url = editLink.href + '&noreturn=1';
	
	if(initDiv )
	{
		initialiseHoverDiv('editPortfolioDiv', 250, 300, false);
	}
 
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
					
				morphSize($('editPortfolioDiv'), myObject['width'], myObject['height']);
				
				$('editPortfolioDivTitle').innerHTML 	= myObject['head_response'];
				$('editPortfolioDivContent').innerHTML 	= myObject['response'];
				
				if(myObject['new_thumb'].length > 0)
				{
					var ThmbImg = $('ed_portf_thumb_img_' + myObject['portfolio_uid']);
					if(ThmbImg)
					{
						ThmbImg.src = myObject['new_thumb'];
						ThmbImg.style.width = myObject['thumb_width'] + 'px';
						ThmbImg.style.height = myObject['thumb_height'] + 'px';
						
						if(myObject['thumb_deleted'])
						{
							$('ed_portf_thumb_img_' + myObject['portfolio_uid'] + '_wrap').setStyles(
								{
									'vertical-align': 'middle',
									'line-height': '172px'
								}
							);
						}
						else
						{
							$('ed_portf_thumb_img_' + myObject['portfolio_uid'] + '_wrap').setStyles(
								{
									'vertical-align': 'top',
									'line-height': 'auto'
								}
							);
						}
					}
				}
				
				handlePortfolioForm();
			}
		}
	).request();
	if(initDiv)
	{
		calculateDivPosition('editPortfolioDiv', mouseX, mouseY);
	}
}
	
	
function load_uploader(url)
{
	new Ajax(url + '&noreturn=1&justuploader=1', 
		{
			method: 'get',
			evalScripts: true,
			onComplete: function(e)
			{
				$('uploader_wrapper').innerHTML = this.response.text;
				
				refresh_uploader_links();
			}
		}
	).request();
}

function refresh_uploader_links()
{
	add_delete_portfolio_links();
	
	if($('upload_explain'))
	{
		$$('a.uploader_choose_link').each(
			function(chooseLink)
			{
				chooseLink.addEvent('click', 
					function(e)
					{
						e = new Event(e).stop();
						
						load_uploader(this.href);
					}
				);
			}
		);
	}
	
	if($('reset_uploader_link'))
	{
		$('reset_uploader_link').addEvent('click', 
			function(e)
			{
				e = new Event(e).stop();
				
				var url = this.href + '&noreturn=1&justuploader=1';
				
				new Ajax(url, 
					{
						method: 'get',
						evalScripts: true,
						onComplete: function(e)
						{
							$('uploader_wrapper').innerHTML = this.response.text;
							
							refresh_uploader_links();
						}
					}
				).request();
			}
		);
	}
}

function change_portfolio_thumb(uid)
{
	var url = 'profile_information/media.php?thumbs=' + uid + '&noreturn=1';
	$('editPortfolioDivContent').innerHTML = '<p><center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /></center></p>';
	new Ajax(url, 
		{
			method: 'get', 
			onComplete: function(e)
			{
				var myObject = Json.evaluate(this.response.text);
					
				morphSize($('editPortfolioDiv'), myObject['width'], myObject['height']);
				
				$('editPortfolioDivTitle').innerHTML 	= myObject['head_response'];
				$('editPortfolioDivContent').innerHTML 	= myObject['response'];
				if($('thumb_div'))
				{
					fadeinFromHidden($('thumb_div'));
				}
				
				$$('a.thumb_back_link').each(
					function(back_link)
					{
						back_link.removeEvents();
						
						back_link.addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								$('editPortfolioDivContent').innerHTML = '<p><center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /></center></p>';
		
								showPortfolioEdit(back_link, 0, 0, false);
							}
						);
					}
				);
				$$('a.thumb_sel_link').each(
					function(sel_link)
					{
						sel_link.removeEvents();
						
						sel_link.addEvent('click', 
							function(e) 
							{
								e = new Event(e).stop();
								
								$('editPortfolioDivContent').innerHTML = '<p><center><img src="profile_information/spinner.gif" style="margin: 10px 0;" /><br />' + $('sending_msg_txt').value + '</center></p>';
		
								showPortfolioEdit(back_link, 0, 0, false);
							}
						);
					}
				);
			}
		}
	).request();
}