/**
 * 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 = {

	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();
	}
}


/*
 * 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		: 100,


	/**
	 * init - hook ourselves to the register form
	 * 
	 * @return void
	 */
	init: function() {
		 
		// only on step 2
		if ($('input:hidden[value=step_two]').length > 0) {
			
			// save url
			JS_NETLASH.profiles.registerHandler.defaultUrl = $('#yoururl').html();
			
			// inject span if needed
			if ($('#sp_username_wrapper span').length == 0) {
				$('#sp_username').after('<span style="display: none;"></span>');
			}
			
			// call the username check on load
			JS_NETLASH.profiles.registerHandler._initCheckUsername();
			
			// hook the keypress event of the username
			$('#sp_username').attr('autocomplete','off').bind('keypress', JS_NETLASH.profiles.registerHandler._handleUsername);
			// hook the username event if there are errors!
			if($('span.form-error').length > 0 && $('#sp_username').val().length > 0) 
			{
				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 - check the username
	 * 
	 * @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
		$('#sp_username_wrapper span').hide();
		
		// inject spinner
		$('#sp_username').after(JS_NETLASH.profiles.registerHandler.spinner);

		// get username
		username = $('#sp_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
			$('#sp_username_wrapper span').removeClass().addClass('form-error').html($('#formchecker_username_too_small').html()).css('display', 'block');
			
			$('#spinner_register').remove();
			return;
		}
		// maximum 100 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
			$('#sp_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) {
					$('#sp_username_wrapper span').removeClass().addClass('form-error').html($('#formchecker_username_exists').html()).css('display', 'block');
				} else if (JS_NETLASH.profiles.registerHandler.existsurl == 1) {
					$('#sp_username_wrapper span').removeClass().addClass('form-warning').html($('#formchecker_url').html()).css('display','block');
				} else {
					$('#sp_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 = {

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


	/**
	 * 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 = $('.online-profiles ul li:last').find('input');
			if(lastField.length > 0) {
				nextId = parseInt(lastField.attr('id').substr(8)) + 1;
			}
			else {
				nextId = 1;
			}
			
			// add it (if not exists yet!)
			$('.online-profiles ul').append(
				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('Ben je zeker dat je deze website wil verwijderen uit je profiel?')) {
			$('#' + $(this).attr('rel')).parent().remove();
		}

	},

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

}


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

	spinner			: '<img class="spinner" alt="even geduld..." src="/modules/core/layout/images/spinner.gif" />',


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

		// show remove button
		$('#prikbordItems > li')
			.mouseover(function() { $(this).find('.verwijderPrikbordItem').show(); })
			.mouseout(function() { $(this).find('.verwijderPrikbordItem').hide(); });
		
		$('.verwijderPrikbordItem').click(JS_NETLASH.profiles.commentsHandler._initRemoveComment);

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


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

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

		// disable the button & show the spinner
		$('#addReaction :submit').attr('disabled','disabled');
		$('#addReaction .spinner').css('visibility','visible');
		
		// define postData
		postData	= $('#addReaction form').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) {

		switch (parseInt(json.status.code)) {

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

				// insert comment into dom
				if ($('#prikbordItems').length > 0) $('#prikbordItems').prepend(json.content.comment);
				else $('#prikbord > h3').after('<ul id="prikbordItems">' + json.content.comment + '</ul>');
				
				// show this new comment
				$('#prikbordItems #prikbordItem_'+json.content.comment_id).slideDown();

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

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

				// re-hook 'remove comment' button
				$('#prikbordItems > li')
					.unbind('mouseover')
					.unbind('mouseout')
					.mouseover(function() { $(this).find('.verwijderPrikbordItem').show(); })
					.mouseout(function() { $(this).find('.verwijderPrikbordItem').hide(); });
				
				$('#prikbordItems .verwijderPrikbordItem').unbind('click').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
		$('#addReaction :submit').removeAttr('disabled');
		$('#addReaction .spinner').css('visibility','hidden');
	},


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

		// don't submit!
		evt.preventDefault();
		
		// remove mouseover & mouseout event on the 'li' element
		$(this).parent().unbind('mouseover mouseout');

		if (confirm("Ben je zeker dat je dit bericht wil verwijderen?")) {
			// show the spinner
			$(this).html(JS_NETLASH.profiles.commentsHandler.spinner);
			
			// define url
			var id = $(this).parent().attr('id').replace('prikbordItem_', '');
			
			// 	Now make the ajax call (after the action has been confirmed)
			JS_NETLASH.profiles.commentsHandler._doRemoveComment(id);
		}
		else
		{
			// hide removeWall icon
			$(this).parent().find('.verwijderPrikbordItem').hide();
			
			// rebind the mouseout & mouseover events
			$(this).parent()
				.mouseover(function() { $(this).find('.verwijderPrikbordItem').show(); })
				.mouseout(function() { $(this).find('.verwijderPrikbordItem').hide(); });
		}

	},


	/**
	 * _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) {

		switch (parseInt(json.status.code)) {

			// OK
			case 200:

				$('#prikbordItem_' + id).slideUp('normal', function() {
					$(this).remove();
				});

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

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

				break;

		}

	},


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

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

		// show the spinner
		$('#prikbordMeerItems .spinner').css('visibility','visible');
		
		// get last item in de list
		var id = $('#prikbordItems li:last').attr('id').replace('prikbordItem_', '');
		
		// 	Now make the ajax call
		JS_NETLASH.profiles.commentsHandler._doSeeMore(id);

	},


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

		$.ajax({
			url:		'/ajax.php?module=profiles&action=see_more',
			type:		'post',
			dataType:	'json',
			cache:		false,
			data:		'last_entry_id=' + id + '&profile_id=' + 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) {

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

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

				// insert comment into dom
				$('#prikbordItems').append(json.content.entries);

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

				// re-hook events
				$('#prikbordItems > li')
					.unbind('mouseover')
					.unbind('mouseout')
					.mouseover(function() { $(this).find('.verwijderPrikbordItem').show(); })
					.mouseout(function() { $(this).find('.verwijderPrikbordItem').hide(); });
				
				$('#prikbordItems .verwijderPrikbordItem').unbind('click').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
		$('#prikbordMeerItems .spinner').css('visibility','hidden');

	},

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


}

/**
 * Main Run : Init objects when document is loaded
 */
$(document).ready(function() {
	JS_NETLASH.profiles.init();
	
	// add confirm message to submit button when delete profile is selected
	$('#delete_profile').change(function()
	{
		// checkbox is checked
	    if($('#delete_profile').is(':checked'))
	    {
	    	// adds a confirm message to the mainSubmit button
			$('#mainSubmit').attr('onclick', "javascript: return confirm('Ben je zeker dat je jouw profiel wilt verwijderen?\\n\\nOpgelet: dit verwijdert al jouw ingegeven data permanent!');");
			
			// exit here
			return;
	    }
	    
	    // checkbox is not checked
	    else $('#mainSubmit').attr('onclick', '');
	});
});
