/**
 * profiles.js
 * @author Bram Van Damme <bramus@netlash.com>
 * @author Bert Pattyn <bert@netlash.com>
 */

/**
 * JS_NETLASH Object
 */
if (!JS_NETLASH) { var JS_NETLASH = new Object(); }

/**
 * JS_NETLASH - Profiles object
 */
JS_NETLASH.profiles = {

	/**
	 * Datamembers
	 */
	debug: false,

	/**
	 * init
	 * @return void
	 */
	init: function() {
		// init registerHandler
		JS_NETLASH.profiles.registerHandler.init();

		// init urlHandler
		JS_NETLASH.profiles.urlHandler.init();

		// init commentsHandler
		JS_NETLASH.profiles.commentsHandler.init();

		// init friendsHandler
		JS_NETLASH.profiles.friendsHandler.init();

		// init quickSearchHandler
		JS_NETLASH.profiles.quickFriendSearchHandler.init();
	}
}


/*
 * JS_NETLASH - Profiles object - registerHandler (handles the registration part)
 */
JS_NETLASH.profiles.registerHandler = {
		
	/**
	 * Datamembers (config)
	 */
	spinner			: '<img src="/modules/core/layout/images/spinner.gif" id="spinner_register" />',
	timeToWait		: 700,
	timer			: null,
	evt				: null,
	existsusername	: 0,
	existsurl		: 0,
	defaultUrl		: null,
	minChars		: 3,
	maxChars		: 30,


	/**
	 * init - hook ourselves to the register form
	 * 
	 * @return void
	 */
	init: function() {

		if ($('input:hidden[value=register]').length > 0) {
			
			// save url
			JS_NETLASH.profiles.registerHandler.defaultUrl = $('#yoururl').html();

			// inject span if needed
			if ($('#username_wrapper span').length == 0) {
				$('#username').after('<span style="display: none;"></span>');
			}
			// hook the keypress event of the username
			$('#username').attr('autocomplete','off').bind('keypress', JS_NETLASH.profiles.registerHandler._handleUsername);
			// hook the username event to the load of the document if there are errors!
			if($('span.form-error').length > 0 && $('#username').val().length > 0) $(document).ready(JS_NETLASH.profiles.registerHandler._handleUsername);

		}
	},
	
	
	/**
	 * _handleUsername - the function to check the username if it is valid
	 * 
	 * @return void
	 */
	_handleUsername: function (evt) {
		
		// don't let 'm type if we're already checking!
		if ($('#spinner_register').length > 0) {
			evt.preventDefault();

		// aah, we're not checking yet ...
		} else {

			// clear previous timer
			clearTimeout(JS_NETLASH.profiles.registerHandler.timer);

			// Store the event
			JS_NETLASH.profiles.registerHandler.evt = evt;
			
			// Che-che-che ... check.it.out!
			JS_NETLASH.profiles.registerHandler.timer = setTimeout(function() { 
					JS_NETLASH.profiles.registerHandler._initCheckUsername(); 
				}, 
				JS_NETLASH.profiles.registerHandler.timeToWait
			);
		}
	},		


	/**
	 * _initCheckUsername - Handle the flag comment link click event
	 * 
	 * @return void
	 */
	_initCheckUsername: function(evt) {

		// get the event
		evt = evt || JS_NETLASH.profiles.registerHandler.evt;

		// debug
		if (JS_NETLASH.profiles.debug)	console.log('_initCheckUsername');

		// hide previous message
		$('#username_wrapper span').hide();
		
		// inject spinner
		$('username').after(JS_NETLASH.profiles.registerHandler.spinner);

		// get username
		username = $('#username').val();
		
		// don't call if empty!
		if ($.trim(username) == '') {
			JS_NETLASH.profiles.registerHandler.existsusername = 1;
			JS_NETLASH.profiles.registerHandler.existsurl = 1;
			$('#yoururl').html(JS_NETLASH.profiles.registerHandler.defaultUrl);
			$('#spinner_register').remove();
			return;
		}
		// minimum 3 chars?
		else if($.trim(username).length < JS_NETLASH.profiles.registerHandler.minChars) {
			
			JS_NETLASH.profiles.registerHandler.existsusername = 1;
			JS_NETLASH.profiles.registerHandler.existsurl = 1;
			$('#yoururl').html(JS_NETLASH.profiles.registerHandler.defaultUrl);
			
			// error message
			$('#username_wrapper span').removeClass().addClass('form-error').html($('#formchecker_username_too_small').html()).css('display', 'block');
			
			$('#spinner_register').remove();
			return;
		}
		// maximum 30 chars?
		else if($.trim(username).length > JS_NETLASH.profiles.registerHandler.maxChars) {
			
			JS_NETLASH.profiles.registerHandler.existsusername = 1;
			JS_NETLASH.profiles.registerHandler.existsurl = 1;
			$('#yoururl').html(JS_NETLASH.profiles.registerHandler.defaultUrl);
			
			// error message
			$('#username_wrapper span').removeClass().addClass('form-error').html($('#formchecker_username_too_big').html()).css('display', 'block');
			
			$('#spinner_register').remove();
			return;
		}
		
		// define postData
		postData	= 'username=' + encodeURIComponent(username);

		// 	Now make the ajax call
		JS_NETLASH.profiles.registerHandler._doCheckUsername(postData);

	},


	/**
	 * _doCheckUsername - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doCheckUsername		: function(postData) {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=checkusername',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.registerHandler._doneCheckUsername(json);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

				// reload the page
				window.location.reload();

			}

		});
	},


	/**
	 * _doneCheckUsername - process the Ajax response
	 * 
	 * @return void
	 */
	_doneCheckUsername	: function(json) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneCheckUsername');
			
			console.log(json);
		}	

		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK - We haz got response
			case 200:

				// update existschecks
				JS_NETLASH.profiles.registerHandler.existsusername 	= parseInt(json.content.existsusername);
				JS_NETLASH.profiles.registerHandler.existsurl 		= parseInt(json.content.existsurl);
				
				// give notices
				if (JS_NETLASH.profiles.registerHandler.existsusername == 1) {
					$('#username_wrapper span').removeClass().addClass('form-error').html($('#formchecker_username_exists').html()).css('display', 'block');
				} else if (JS_NETLASH.profiles.registerHandler.existsurl == 1) {
					$('#username_wrapper span').removeClass().addClass('form-warning').html($('#formchecker_url').html()).css('display','block');
				} else {
					$('#username_wrapper span').hide().html('');
				}

				// update url
				$('#yoururl').html(json.content.suggestedurl);

				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}

		// remove spinner
			$('#spinner_register').remove();

	},


	/**
	 * end of object
	 */
	_eoo				: true
}







/**
 * JS_NETLASH - Profiles object - urlHandler
 * -------------------------------------------------------------
 */

JS_NETLASH.profiles.urlHandler = {

	/**
	 * Datamembers (config)
	 */

	linkBlob: '<dd><input type="text" class="input-text" value="{link}" name="websites[]" id="websites{id}"/> <a href="#" title="{$lblDelete}" class="deleteWebsiteLink" rel="websites{id}">{$lblDelete}</a></dd>',


	/**
	 * init - hook ourselves to the url field!
	 * 
	 * @return void
	 */
	init: function() {

		if ($('#addWebsiteLink').length > 0) {

			// Add url to list (addWebsite link clicked)
			$('#addWebsiteLink').bind('click', JS_NETLASH.profiles.urlHandler._addUrl);

			// Add site to list (enter pressed in website field) + remove autocomplete!
			$('#website').attr("autocomplete", "off").bind('keypress', function(evt) {
				
				// if enter pressed, then add it
				if (evt.which == 13) {
					evt.preventDefault();
					evt.stopPropagation();
					JS_NETLASH.profiles.urlHandler._addUrl(evt);
				}
				
			}).bind('focus', function(evt) {
				
				if ($(this).val() == '') {
					$(this).val('http://');
				}
				
			}).bind('blur', function(evt) {
				
				if ($(this).val() == 'http://') {
					$(this).val('');
				}
				
			});

			// delete website links
			$('.deleteWebsiteLink').bind('click', JS_NETLASH.profiles.urlHandler._deleteUrl);

		}

	},


	/**
	 * _addUrl - Adds the url to the list
	 * 
	 * @return void
	 */
	_addUrl			: function(evt) {

		// don't jump/submit
		evt.preventDefault();

		// valid email!
		if (JS_NETLASH.utils.form.isUrl($('#website'))) {

			// Hide notice
			$('#invalidWebsite').hide();

			// define nextId
			var lastField = $('#addWebsiteWrapper').prev().find('input');
			if(lastField.length > 0) {
				nextId = parseInt(lastField.attr('id').substr(8)) + 1;
			}
			else {
				nextId = 1;
			}

			// add it (if not exists yet!)
			$('#addWebsiteWrapper').before(
				JS_NETLASH.utils.string.replaceAll(JS_NETLASH.utils.string.replaceAll(JS_NETLASH.profiles.urlHandler.linkBlob, '{link}', $('#website').val()), '{id}', nextId)
			);

			// rebind delete links
			$('.deleteWebsiteLink').unbind('click').bind('click', JS_NETLASH.profiles.urlHandler._deleteUrl);

			// clear val & focus
			$('#website').val('').focus();
		}

		// no valid email
		else {
			// give notice
			$('#invalidWebsite').show();
	
			// focus the field
			$('#website').focus();
		}

	},


	/**
	 * _deleteUrl - handles the click events on the itemz
	 * 
	 * @return void
	 */
	_deleteUrl: function(evt) {

		// don't jump!
		evt.preventDefault();

		// remove if sure
		if (confirm('{$msgAreYouSure}')) {
			$('#' + $(this).attr('rel')).parent().remove();
		}

	},

	/**
	 * end of object
	 */
	_eoo				: true

}


/**
 * JS_NETLASH - profiles object - commentsHandler
 */
JS_NETLASH.profiles.commentsHandler = {

	/**
	 * Datamembers (config)
	 */
	blob			: '<li><img id="comment-{commentid}" class="removeComment" src="/modules/core/layout/images/icons/delete.gif" width="16" height="16" alt="deletecomment" /><a href="{url}" title="{username}"><img src="/modulefiles/profiles/avatars/38x38/{avatar}" width="38" height="38" alt="{username}" /></a><h4><a href="{url}" title="{username}">{username}</a> has commented on <a href="{url2}" title="{username2}">{username2}</a>\'s profile. <span class="timeago">(1 Second Ago)</span></h4><p>{text}</p></li>',
	spinner			: '<img src="/modules/core/layout/images/spinner.gif" id="spinner_{id}" alt="" title="" />',


	/**
	 * init - hook ourselves to the form!
	 * 
	 * @return void
	 */
	init: function() {
		// hook submit button
		if ($('#btnAddComment').length > 0) {
			$('#btnAddComment').removeAttr('disabled').bind('click', JS_NETLASH.profiles.commentsHandler._initAddComment);
		}

		// show remove button
		$('#wall-and-comments > li').mouseover(function() { $(this).find('.removeComment').show(); });
		$('#wall-and-comments > li').mouseout(function() { $(this).find('.removeComment').hide(); });
		$('.removeComment').click(JS_NETLASH.profiles.commentsHandler._initRemoveComment);

		// hook flagLinks
		$('p.flagLink a').bind('click', JS_NETLASH.profiles.commentsHandler._initFlagComment);

		// hook 'more entries'
		$('a#moreEntries').click(JS_NETLASH.profiles.commentsHandler._initSeeMore);
	},


	/**
	 * _initAddComment - Handle the add comment button click event
	 * 
	 * @return void
	 */
	_initAddComment: function(evt) {

		if(JS_NETLASH.profiles.debug) console.log('_initAddComment');
		
		// don't submit!
		evt.preventDefault();

		// disable the button & show the spinner
		$('#btnAddComment').attr('disabled','disabled');
		$('#spinner').css('visibility','visible');

		// define postData
		postData	= $('#addCommentForm').serialize();

		// 	Now make the ajax call
		JS_NETLASH.profiles.commentsHandler._doAddComment(postData);

	},


	/**
	 * _doAddComment - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doAddComment: function(postData) {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=add_comment',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.commentsHandler._doneAddComment(json);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

			}

		});
	},



	/**
	 * _doneAddComment - process the Ajax response
	 * 
	 * @return void
	 */
	_doneAddComment: function(json) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneAddComment');
			
			console.log(json);
		}	

		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK and NOK (added // spammed)
			case 200:
			case 400:

				// define what to insert
				toInsert	= JS_NETLASH.utils.string.assignFromObject(JS_NETLASH.utils.string.assignFromObject(JS_NETLASH.profiles.commentsHandler.blob, json.content.user), json.content.comment);
				toInsert	= JS_NETLASH.utils.string.replaceAll(toInsert, '{lblFlagContent}', json.content.lblFlagContent);

				// debug
				if (JS_NETLASH.profiles.debug) console.log(toInsert);

				// insert comment into dom
				if ($('#wall-and-comments').length > 0) $('#wall-and-comments').prepend(toInsert);
				else $('#wallList').prepend('<ul id="wall-and-comments" class="clearfix">' + toInsert + '</ul>');

				// reset the form
				$('#addCommentForm').get(0).reset();

				// don't show "no messages"-message
				$('#wall-inactive').remove();

				// hook flagLinks
				$('p.flagLink a').bind('click', JS_NETLASH.profiles.commentsHandler._initFlagComment);

				// re-hook 'remove comment' button
				$('#wall-and-comments > li').unbind('mouseover');
				$('#wall-and-comments > li').unbind('mouseout');
				$('#wall-and-comments > li').mouseover(function() { $(this).find('.removeComment').show(); });
				$('#wall-and-comments > li').mouseout(function() { $(this).find('.removeComment').hide(); });
				$('.removeComment').unbind('click');
				$('.removeComment').click(JS_NETLASH.profiles.commentsHandler._initRemoveComment);

				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}

		// reactivate form
		$('#btnAddComment').removeAttr('disabled');
		$('#spinner').css('visibility','hidden');
	},


	/**
	 * _initRemoveComment - Handle the remove comment button click event
	 * 
	 * @return void
	 */
	_initRemoveComment: function(evt) {

		if(JS_NETLASH.profiles.debug) console.log('_initRemoveComment');
		
		// don't submit!
		evt.preventDefault();

		if (confirm("Are you sure you want to remove this comment?")) {
			// show the spinner
			$('#spinner').css('visibility','visible');
	
			// define url
			var id = $(this).attr('id').replace('comment-', '');
	
			// 	Now make the ajax call (after the action has been confirmed)
			JS_NETLASH.profiles.commentsHandler._doRemoveComment(id);
		}

	},


	/**
	 * _doRemoveComment - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doRemoveComment: function(id) {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=remove_comment',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		'id=' + id,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.commentsHandler._doneRemoveComment(json, id);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

			}
		});

	},


	/**
	 * _doneRemoveComment - process the Ajax response
	 * 
	 * @return void
	 */
	_doneRemoveComment: function(json, id) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneRemoveComment');
			
			console.log(json);
		}	

		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK and NOK (added // spammed)
			case 200:
			case 400:

				$('#comment-' + id).parent().remove();

				break;
			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}

		// reactivate
		$('#spinner').css('visibility','hidden');

	},


	/**
	 * _initSeeMore - Handle the 'see more entries' button click event
	 * 
	 * @return void
	 */
	_initSeeMore: function(evt) {

		if(JS_NETLASH.profiles.debug) console.log('_initSeeMore');
		
		// don't submit!
		evt.preventDefault();

		// show the spinner
		$('#spinner').css('visibility','visible');

		// 	Now make the ajax call
		JS_NETLASH.profiles.commentsHandler._doSeeMore();

	},


	/**
	 * _doSeeMore - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doSeeMore: function() {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=see_more',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		'entries=' + $('#wall-and-comments > li.wallEntry').length + '&profile=' + profileId,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.commentsHandler._doneSeeMore(json);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

			}
		});

	},


	/**
	 * _doneSeeMore - process the Ajax response
	 * 
	 * @return void
	 */
	_doneSeeMore: function(json) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneSeeMore');
			
			console.log(json);
		}	

		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK and NOK (added // spammed)
			case 200:
			case 400:

				// debug
				if (JS_NETLASH.profiles.debug) console.log(json.content.entries);

				// insert comment into dom
				$('#wall-and-comments').append(json.content.entries);

				// remove 'see more' button if there is no more to see
				if (json.content.seemore == '0') $('#moreEntries').remove();

				// re-hook 'delete comment'

				// re-hook 'remove comment' button
				$('#wall-and-comments > li').unbind('mouseover');
				$('#wall-and-comments > li').unbind('mouseout');
				$('#wall-and-comments > li').mouseover(function() { $(this).find('.removeComment').show(); });
				$('#wall-and-comments > li').mouseout(function() { $(this).find('.removeComment').hide(); });
				$('.removeComment').unbind('click');
				$('.removeComment').click(JS_NETLASH.profiles.commentsHandler._initRemoveComment);

				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}

		// reactivate
		$('#spinner').css('visibility','hidden');

	},


	/**
	 * _initFlagComment - Handle the flag comment link click event
	 * 
	 * @return void
	 */
	_initFlagComment: function(evt) {

		// don't jump to the top
		evt.preventDefault();

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_initFlagComment');
			
			console.log(evt);
		}	

		// define the id
		var id = evt.target.id.toString().substring(13);

		// inject spinner
		$(evt.target).parent().html(JS_NETLASH.utils.string.replaceAll(JS_NETLASH.profiles.commentsHandler.spinner, '{id}', id));

		// define postData
		postData = 'comment_id=' + id;

		// 	Now make the ajax call
		JS_NETLASH.profiles.commentsHandler._doFlagComment(postData, id);

	},


	/**
	 * _doFlagComment - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doFlagComment: function(postData, id) {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=flag_comment',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.commentsHandler._doneFlagComment(json, id);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');
			}

		});
	},



	/**
	 * _doneFlagComment - process the Ajax response
	 * 
	 * @return void
	 */
	_doneFlagComment		: function(json, id) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneFlagComment');
			
			console.log(json);
		}
		
		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK - Flagged & NOK - Already flagged
			case 200:
			case 400:
				$('#flagLink_'+id).parent().parent().parent().slideUp(null, function() {$(this).remove(); } );


				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				// reload the page
				if(!JS_NETLASH.profiles.debug) window.location.reload();


				break;

		}
	},


	/**
	 * end of object
	 */
	_eoo: true


}





/**
 * JS_NETLASH - profiles object - friendsHandler
 */
JS_NETLASH.profiles.friendsHandler = {

	/**
	 * Datamembers (config)
	 */
	spinner				: '<img src="/modules/core/layout/images/spinner.gif" id="friend_spinner" style="visibility: visible;" />',
	btnNotFriend		: '<li class="addAsAFriend"><img id="friend_spinner" title="" alt="" src="/modules/core/layout/images/spinner.gif" /><a href="#" class="button button-fixed" id="btnAddFriendRequest">{msg}</a></li>',
	btnFriendRequested	: '<li class="headerMessage awaitingrequest secondarycontent clearfix">{msg} <a href="#" class="cancelButton modal-box-toggle" rel="removeFriendRequest">{cancel}</a></li>',
	lblIsFriend			: '<li class="headerMessage friend-status secondarycontent clearfix">{msg}</li>',
	

	/**
	 * init - hook ourselves to the form!
	 * 
	 * @return void
	 */
	init: function() {

		// hook buttons in profile view
		$('#btnAddFriendRequest').bind('click', JS_NETLASH.profiles.friendsHandler._initAddFriendRequest);
		$('#btnRemoveFriendRequest').bind('click', JS_NETLASH.profiles.friendsHandler._initRemoveFriendRequest);
		$('#btnRemoveFriend').bind('click', JS_NETLASH.profiles.friendsHandler._initRemoveFriend);

		// hook selectAll
		$('#addFriendAll').bind('change', JS_NETLASH.profiles.friendsHandler._selectAll);

		// hook addSelected
		$('#addSelected').bind('click', JS_NETLASH.profiles.friendsHandler._initAddFriends);

		// hook denySelected
		$('#denySelected').bind('click', JS_NETLASH.profiles.friendsHandler._initDenyFriendRequests);

	},


	/**
	 * Handle the add as friend button click event
	 * 
	 * @return void
	 */
	_initAddFriendRequest: function(evt) {
		
		// debug
		if(JS_NETLASH.profiles.debug) console.log('_initAddFriendRequest');

		// don't submit!
		evt.preventDefault();

		// disable the button & show the spinner
		$('#btnAddFriendRequest').addClass('button-disabled');
		$('#friend_spinner').css('visibility','visible');

		// define postData
		postData	= $('#friendRequestForm').serialize();

		// 	Now make the ajax call
		JS_NETLASH.profiles.friendsHandler._doAddFriendRequest(postData);

	},

	
	/**
	 * _initRemoveFriendRequest - Handle the cancel friend request button click event
	 * 
	 * @return void
	 */
	_initRemoveFriendRequest: function(evt) {
	
		// debug
		if(JS_NETLASH.profiles.debug) console.log('_initRemoveFriendRequest');		

		// don't submit!
		evt.preventDefault();
		
		$('.modal-box-close', this.parentNode.parentNode.parentNode).click();

		// show the spinner
		$('#friend_spinner').css('visibility','visible');

		// define postData (as object) (variables are in the template)
		postData	= {profile_id: profileId, username: profileUsername};
		
		// 	Now make the ajax call
		JS_NETLASH.profiles.friendsHandler._doRemoveFriendRequest(postData);

	},


	/**
	 * _doAddFriendRequest - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doAddFriendRequest: function(postData) {
		
		// debug
		if(JS_NETLASH.profiles.debug) console.log('_doAddFriendRequest');		

		// post it
		$.ajax({
			url:		'/ajax.php?module=profiles&action=add_friend_request',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.friendsHandler._doneAddFriendRequest(json);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

			}

		});
	},


	/**
	 * _doRemoveFriendRequest - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doRemoveFriendRequest: function(postData) {

		// debug
		if(JS_NETLASH.profiles.debug) console.log('_doRemoveFriendRequest');
		
		// post it
		$.ajax({
			url:		'/ajax.php?module=profiles&action=remove_friend_request',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.friendsHandler._doneRemoveFriendRequest(json);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

				// reload the page
				//if(!JS_NETLASH.profiles.debug) window.location.reload();

			}

		});
	},


	/**
	 * _doneAddFriendRequest - process the Ajax response
	 * 
	 * @return void
	 */
	_doneAddFriendRequest: function(json) {
		
		// debug
		if(JS_NETLASH.profiles.debug) {
			
			console.log('_doneAddFriendRequest');		
			
			console.log(json);
		}	
	
		// what what (in the butt)?
		switch (parseInt(json.status.code)) {
	
			// OK and NOK (added // exists)
			case 200:
			case 400:
	
				// reset the form
				// $('#friendRequestForm').get(0).reset();
	
				if(json.content.status == 'friends')
				{
					// set the new button
					$('#btnAddFriendRequest').parent().replaceWith(
						JS_NETLASH.utils.string.assignFromObject(
							JS_NETLASH.profiles.friendsHandler.lblIsFriend, json.content
						)
					);
	
				}
				else
				{
					// set the new button
					$('#btnAddFriendRequest').parent().replaceWith(
						JS_NETLASH.utils.string.assignFromObject(
							JS_NETLASH.profiles.friendsHandler.btnFriendRequested, json.content
						)
				);
	
				}
	
				JS_NETLASH.general._hookModalBoxes();
	
				this.init();
	
				break;
	
			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;
	
		}
	
		// reactivate form
		$('#friend_spinner').css('visibility','hidden');
	},


	/**
	 * _doneRemoveFriendRequest - process the Ajax response
	 * 
	 * @return void
	 */
	_doneRemoveFriendRequest: function(json) {
		
		// debug
		if(JS_NETLASH.profiles.debug) {
			
			console.log('_doneRemoveFriendRequest');		

			console.log(json);
		}	

		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK and NOK (added // exists)
			case 200:
			case 400:

				// set the new button
				$('.cancelButton').parent().replaceWith(
					JS_NETLASH.utils.string.assignFromObject(
						JS_NETLASH.profiles.friendsHandler.btnNotFriend,
						{'msg' : json.content.msg}
					)
				);

				this.init();
				
				// close modal

				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}

		// reactivate form
		$('#friend_spinner').css('visibility','hidden');
	},


	/**
	 * _initAddFriends - Handle adding the selected friends
	 * 
	 * @return void
	 */
	_initAddFriends		: function(evt) {
	
		// debug
		if(JS_NETLASH.profiles.debug) console.log('_initAddFriends');	

		// don't jump to the top
		evt.preventDefault();

		// get the friend_id's that have to be sent
		var friendId = JS_NETLASH.profiles.friendsHandler._getChecked().join(',');

		if(friendId == "") { return false; }

		// inject spinner
		$(this).parent().prepend(JS_NETLASH.profiles.friendsHandler.spinner);
		// disable buttons
		$('#addSelected, #denySelected').addClass('button-disabled');

		// get the friend_id's that have to be sent
		var friendId = JS_NETLASH.profiles.friendsHandler._getChecked().join(',');

		// define postData
		postData	= 'friend_id=' + friendId;

		// 	Now make the ajax call
		JS_NETLASH.profiles.friendsHandler._doAddFriend(postData, friendId);
	},


	/**
	 * _doAddFriend - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doAddFriend		: function(postData, id) {
	
		// debug
		if(JS_NETLASH.profiles.debug) console.log('_doAddFriend');		

		// post it
			$.ajax({
				url:		'/ajax.php?module=profiles&action=add_friend',
				type:		'post',
				dataType:	'json',
				cache:		false,
				data:		postData,

				// success making call
				success:	function(json) {

					// process the ajax response
					JS_NETLASH.profiles.friendsHandler._doneAddFriend(json, id);
				},

				// error making call - something went horribly wrong!
				error:		function(xhr,err,e) {
					
					// give notice
					alert(err + ' ' + e, 'Critical Error');
				}

			});
	},


	/**
	 * _doneAddFriend - process the Ajax response
	 * 
	 * @return void
	 */
	_doneAddFriend		: function(json, id) {

		// debug
		if (JS_NETLASH.profiles.debug) {
		
			console.log('_doneAddFriend');
			
			console.log(json);
		}	
			


		// what what (in the butt)?
			switch (parseInt(json.status.code)) {

				// OK - Flagged & NOK - Already flagged
					case 200:
					case 400:
						// remove the selected friends from the list and add them to the friend list
						jQuery.each(JS_NETLASH.profiles.friendsHandler._getChecked(), function() {

							// remove some classes and some stuff that is unique for the requests list
							var li = $('#addFriend_'+this).parent().parent();
							li.removeClass('request');
							$('.check', li).remove();

							if($('#my-friends').length == 0) $('#friend_holder').html('<ul id="my-friends" class="friends-list clearfix"></ul>');

							// add it to the friends list
							li.remove().prependTo('#my-friends');
						});

						// if there are no more requests, remove it
						// "== 1" because we will always have the select-all checkbox
						if($('#friend-requests input[type=checkbox]').length == 1)
						{
							$('#requests').slideUp(500, function() { $(this).remove(); });
						}
						$('#friend-status').html(json.content.msg);

						// reactivate form and hide spinner
						$('#addSelected, #denySelected').removeClass('button-disabled');
						$('#friend_spinner').css('visibility','hidden');
					break;

				// ERROR - Something went wrong (most likely insufficient params)
					case 500:
					default:

						// Give notice
						alert(json.status.text);

						// reload the page
						if(!JS_NETLASH.profiles.debug) window.location.reload();


					break;

			}
	},


	/**
	 * _initDenyFriendRequests - Deny a friend request
	 * 
	 * @return void
	 */
	_initDenyFriendRequests: function(evt) {
		
		// debug
		if (JS_NETLASH.profiles.debug)	console.log('_initDenyFriendRequests');
		
		// don't jump to the top
		evt.preventDefault();

		// get the friend_id's that have to be sent
		var friendId = JS_NETLASH.profiles.friendsHandler._getChecked().join(',');

		if(friendId == "") { return false; }

		// inject spinner
		$(this).parent().prepend(JS_NETLASH.profiles.friendsHandler.spinner);
		// disable buttons
		$('#addSelected, #denySelected').addClass('button-disabled');

		// get the friend_id's that have to be sent
		var friendId = JS_NETLASH.profiles.friendsHandler._getChecked().join(',');

		// define postData
		postData	= 'friend_id=' + friendId;

		// 	Now make the ajax call
		JS_NETLASH.profiles.friendsHandler._doDenyFriendRequests(postData, friendId);
	},


	/**
	 * _doDenyFriendRequests - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doDenyFriendRequests		: function(postData, id) {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=deny_friend_request',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.friendsHandler._doneDenyFriendRequests(json, id);
			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');

				// reload the page
				if(!JS_NETLASH.profiles.debug) window.location.reload();

			}

		});
	},



	/**
	 * _doneDenyFriendRequests - process the Ajax response
	 * 
	 * @return void
	 */
	_doneDenyFriendRequests: function(json, id) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneDenyFriendRequests');
			
			console.log(json);
		}	


		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK - Flagged & NOK - Already flagged
			case 200:
			case 400:
				// remove the selected friends from the list
				jQuery.each(JS_NETLASH.profiles.friendsHandler._getChecked(), function() {

					// remove the request
					var li = $('#addFriend_'+this).parent().parent().remove();
				});

				// if there are no more requests, remove it
				// "== 1" because we will always have the select-all checkbox
				if($('#friend-requests input[type=checkbox]').length == 1)
				{
					$('#requests').slideUp(500, function() { $(this).remove(); });
				}
				$('#friend-status').html(json.content.msg);

				// reactivate form and hide spinner
				$('#addSelected, #denySelected').removeClass('button-disabled');
				$('#friend_spinner').css('visibility','hidden');
				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}
	},


	/**
	 * _initRemoveFriend - Handle the remove friend click event
	 * 
	 * @return void
	 */
	_initRemoveFriend: function(evt) {

		// debug
		if(JS_NETLASH.profiles.debug) console.log('_initRemoveFriend');		
					
		// don't jump to the top
		evt.preventDefault();
		
		// hide the modal dialog
		$('.modal-box-close', this.parentNode.parentNode).click();

		// show the spinner
		$('#friend_spinner').css('visibility','visible');

		// define postData
		postData	= {profile_id: profileId};

		// 	Now make the ajax call
		JS_NETLASH.profiles.friendsHandler._doRemoveFriend(postData);

	},

	/**
	 * _doRemoveFriend - do the Ajax Dance
	 * 
	 * @return void
	 */
	_doRemoveFriend: function(postData) {

		$.ajax({
			url:		'/ajax.php?module=profiles&action=remove_friend',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		postData,

			// success making call
			success:	function(json) {

				// process the ajax response
				JS_NETLASH.profiles.friendsHandler._doneRemoveFriend(json);

			},

			// error making call - something went horribly wrong!
			error:		function(xhr,err,e) {

				// give notice
				alert(err + ' ' + e, 'Critical Error');
				
				// reload the page
				if(!JS_NETLASH.profiles.debug) window.location.reload();					

			}

		});
	},


	/**
	 * _doneRemoveFriend - process the Ajax response
	 * 
	 * @return void
	 */
	_doneRemoveFriend: function(json, id) {

		// debug
		if (JS_NETLASH.profiles.debug) {
			
			console.log('_doneRemoveFriend');
			
			console.log(json);
		}	


		// what what (in the butt)?
		switch (parseInt(json.status.code)) {

			// OK - Flagged & NOK - Already flagged
			case 200:
			case 400:

				// set the new button
				$('.friend-status').replaceWith(
					JS_NETLASH.utils.string.assignFromObject(
						JS_NETLASH.profiles.friendsHandler.btnNotFriend,
						{'msg' : json.content.msg}
					)
				);

				this.init();
				break;

			// ERROR - Something went wrong (most likely insufficient params)
			case 500:
			default:

				// Give notice
				alert(json.status.text);

				break;

		}
		
		// reactivate form
		$('#friend_spinner').css('visibility','hidden');
	},


	/**
	 * _selectAll - select all friend requests
	 * 
	 * @return void
	 */
	_selectAll: function(evt) {

		// get the new checkbox value
		var value = $(this).attr('checked');

		// get all checkboxes in this form
		$('#friend-requests input[type=checkbox]').each(function() { $(this).attr('checked', value); });
	},
	

	/**
	 * _getChecked - get the id's of the checked profiles
	 * 
	 * @return array
	 */
	_getChecked: function() {

		var options = new Array();

		// get all checkboxes in this form
		$('#friend-requests input[type=checkbox]').each(function() {
			if($(this).attr('checked') && $(this).attr('name')=="add_friend[]") options.push(parseInt($(this).val()));
		});

		return options;
	},


	/**
	 * end of object
	 */
	_eoo				: true


}



/*
 * JS_NETLASH - Profiles object - quickSearchHandler
 */
JS_NETLASH.profiles.quickFriendSearchHandler = {

	/**
	 * init - hook ourselves to the search field!
	 * 
	 * @return void
	 */
	init: function() {
		// bind events
		JS_NETLASH.profiles.quickFriendSearchHandler._initDeleteFriend();

		// autocomplete friends
		$('#friends').autocomplete('/ajax.php?module=profiles&action=autocomplete_friends', {
			width: 175,
			max: 5,
			selectFirst: false
		});

		var donotsubmit = false;

		// prevent enter from submitting form. Add friend instead
		$('#friends').keydown(function(evt) {
			if (evt.keyCode == 13) {
				// do nut submit the form
				donotsubmit = true;

				// add friend
				$('#add_friend_button').click();
			}
		});
		$('#friends').keyup(function(evt) {
			donotsubmit = false;
		});

		// catch form submit (to stop it when it is not required)
		$('#sendAMessage').submit(function(evt) {
			if (donotsubmit == true)
			{
				// prevent default
				evt.preventDefault();
				evt.stopPropagation();
			}
		});

		$('#add_friend_button').bind('click', function(evt) {
			// get friend info through ajax, then go to next function
			var friendname = $('#friends').val();

			// prevent default
			evt.preventDefault();
			evt.stopPropagation();

			$.ajax({
				url:		'/ajax.php?module=profiles&action=get_friend_info',
				type:		'post',
				dataType:	'json',
				cache:		false,
				data:		'user=' + friendname,

				// success making call
				success:	function(json) {
					if (json.status.code == 200)
					{
						// process the ajax response
						JS_NETLASH.profiles.quickFriendSearchHandler._addFriend(evt, json);
					}
					// else, do nothing, the username just didn't exist (finish your damn username, loser!)
				},

				// error making call - something went horribly wrong!
				error:		function(xhr,err,e) {
					// give notice
					alert(err + ' ' + e, 'Critical Error');

					// reload the page
					window.location.reload();
				}

			});

			
		});
	},


	/**
	 * _addFriend - add friend to send a message to
	 * 
	 * @return void
	 */
	_addFriend: function(evt, friends) {

		//debug
		if(JS_NETLASH.profiles.debug) console.log('_addFriend');

		// cleanup
		if($('#friends_list li').length == 0) $('#buddies').val('');

		var id = friends.content.id;
		var avatar = friends.content.avatar;
		var nick = friends.content.username;

		if(id == '-1') return false;

		if($('#buddy_' + id).length == 0)
		{
			$('#buddies').val($('#buddies').val() + ':::' + id);

			// add to list
			JS_NETLASH.profiles.quickFriendSearchHandler._doneAddFriend(id, avatar, nick);
		}
		else $('#buddy_' + id).fadeTo('normal', 0.33).fadeTo('normal', 1);

	},

	
	/**
	 * _doneAddFriend - handles the result of _addFriend
	 * 
	 * @return void
	 */
	_doneAddFriend: function(id, avatar, nick) {
		
		//debug
		if(JS_NETLASH.profiles.debug) console.log('_doneAddFriend');		
		
		// build html
		html = '<li id="buddy_'+ id +'"><img src="/modulefiles/profiles/avatars/21x21/'+ avatar +'" width="21" height="21" /><p>'+ nick +' <a class="deleteTag noborder" href="#" rel="'+ id +'" title="{$lblDelete}">{$lblDelete}</a></p></li>';

		// append html
		$('#friends_list').append(html);

		// show
		$('#recipients').fadeIn('fast');

		// bind events
		JS_NETLASH.profiles.quickFriendSearchHandler._initDeleteFriend();
	},

	
	/**
	 * _initDeleteFriend - deletes a friend from the senderslist
	 * 
	 * @return void
	 */
	_initDeleteFriend: function(evt) {
		
		$('.deleteTag').bind('click', function(evt) {
			// prevent default
			evt.preventDefault();
			evt.stopPropagation();

			// get id
			id = $(this).attr('rel');

			// remove id
			$('#buddies').val($('#buddies').val().replace(':::' + id, ''));

			// cleanup
			if($('#friends_list li').length == 0) $('#buddies').val('');

			// remove visual
			$('#buddy_'+ id).remove();
		});
	},

	/**
	 * end of object
	 */
	_eoo: true
}



/**
 * Main Run : Init objects when document is loaded
 */
$(document).ready(function() {
	JS_NETLASH.profiles.init();
});
