var User = {};
var Groups = new Data({ name: 'group' });
var Lists = new Data({ name: 'list' });
var Commitments = new Data({ name: 'commitment' });

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

function toggleTab(tab, pageLoad)
{
	var target = $(tab.target);
	
	if(pageLoad !== false) loadPage(target.attr('href').replace('#',''));
	
	$('nav a.selected').animate({
		opacity: 0.25
	}, 400, function() {
		$('nav a.selected').animate({ opacity: 1 });
		target.parents('nav:first').find(".selected").not(target).removeClass('selected');
	});

	target.addClass('selected');

}

function toggleCommitted(requestId)
{
	var request = $('#request-' + requestId);
	var committed = request.find('.committed');
	var countBox = request.find('.commitments');
	var count = parseInt(request.find('.count').html());
	
	if(committed.hasClass('committed_on'))
	{
		committed.removeClass('committed_on').addClass('committed_off');
		request.find('.count').html(--count);
	}
	else
	{
		committed.removeClass('committed_off').addClass('committed_on');
		request.find('.count').html(++count);
	}
	
	if(count == 0)
	{
		countBox.delay(1000).fadeOut(function() { countBox.removeClass('hidden'); });
	}
	else
	{
		countBox.hide().removeClass('hidden').fadeIn();
	}
}

function toggleFlagged(requestId)
{
	var request = $('#request-' + requestId);
	var flag = request.find('.flag');
	
	if(flag.hasClass('flag_on'))
	{
		flag.removeClass('flag_on').addClass('flag_off');
	}
	else
	{
		flag.removeClass('flag_off').addClass('flag_on');
	}
}

function userInit()
{
	var module = 'user';
	var action = 'init';
	var functionName = 'on' + module.toProperCase() + action.toProperCase();

	$.ajax({
		url: '/index.php?module=' + module + '&action=' + action,
		// data: params,
		dataType: 'json',
		type: 'POST',
		success: function(data, textStatus){
			if(data)
			{
				var fn = window[functionName];
				if(typeof fn === 'function') {
					fn.apply(this, arguments);
				}
			}
			
			init();
			
			var hash = window.location.hash;
			var matches = $('nav a[href="' + hash + '"]');
			
			if(matches.length > 0)
			{
				matches.click();
			}
			else
			{
				if(hash == '#' || hash == '')
				{
					// loadPage('requests');
				}
				else
				{
					loadPage(hash.replace('#',''));
				}
			}
		}
	});
}

function onUserInit(data, textStatus)
{
	Groups = new Data({ name: 'group' });
	Lists = new Data({ name: 'list' });
	Commitments = new Data({ name: 'commitment' });
	
	User = data.User;
	
	if(User)
	{
		if(!CookieJar.get('noTour') || CookieJar.get('noTour') == "false")
		{
			Tour.restart();
		}
	
		if(User.isAdmin)
		{
			var module = 'admin';
		
			$.ajax({
				url: '/index.php?module=' + module,
				dataType: 'html',
				type: 'POST',
				success: function(data, textStatus){
					if(data)
					{
						$('body > #admin').remove();
						$(data).prependTo('body');
					}
				}
			});
		}
		
		$('#welcomeNote').html('Welcome, ' + User.displayName + '.');
	}

	if(data.Groups && data.Groups.success && data.Groups.results.length > 0)
	{
		Groups.add(data.Groups.results);
	}

	if(data.Lists && data.Lists.success && data.Lists.results.length > 0)
	{
		Lists.add(data.Lists.results);
	}
	
	if(data.Commitments && data.Commitments.success && data.Commitments.results.length > 0)
	{
		Commitments.add(data.Commitments.results);
	}
	
	if(data.Messages)
	{
		$('.messageCount').html(data.Messages['messages'] + '/' + data.Messages['invites'] + '&nbsp; ');
	}
}

var validationTimer = null;

function init(obj)
{
	if(typeof obj == "undefined") obj = 'body';
	
	if(User)
	{
		if(User.loggedIn == true)
		{
			$("[data-auth='req']").show();
		}
		else
		{
			$("[data-auth='req']").hide();
		}
	}
	else
	{
		$("[data-auth='req']").hide();
	}
	
	$(obj).find('[title]').tooltip({ predelay: 150 });
	
	$(obj).find('nav a').bind('click', toggleTab);
	$(obj).find('button[data-modal]').bind('click', loadModal);
	
	$(obj).find('[data-empty_text]').each(function() {
		$(this).bind('focus', function() {
			if( $(this).val() == $(this).attr('data-empty_text') )
			{
				$(this).val('');
			}
		});
		
		$(this).bind('blur', function() {
			if(!$(this).val())
			{
				$(this).val( $(this).attr('data-empty_text') );
			}
		});
		
		$(this).blur();
	});
	
	$(obj).find('#requestEntry textarea').bind('focus', function() {
		$(this).height(140);
		$(this).parents('#requestEntry').animate({height: '200px'}, 500);
	});
	
	$(obj).find('#requestEntry .cancel').bind('click', function() {
		$('#requestEntry textarea').animate({ height: '16px' }, 500);
		$(this).parents('#requestEntry').animate({ height: '32px' }, 500);
	});
	
	// $(obj).find('.request, .message').bind('mouseenter', function() {
		// $(this).find('.options').fadeIn();
	// });
	
	// $(obj).find('.request, .message').bind('mouseleave', function() {
		// $(this).find('.options').fadeOut();
	// });
	
	$(obj).find('table#lists input[name="default"]').bind('change', function() {
		loadModule('user.updateDefaultList', 'default_list_id=' + this.value);
	});

	$(obj).find('table#memberOfGroups input[name="groupNotify"]').bind('change', function() {
		loadModule('group.updateNotify', 'group_id=' + this.value);
	});
	
	$(obj).find('button[data-action]').bind('click', function() {
		loadModule($(this).attr('data-action'), $(this).attr('data-data'));
	});
	
	$(obj).find('#noTour').bind('change', function() {
		if(this.checked)
		{
			CookieJar.set('noTour', true, 30);
		}
	});
	
	$(obj).find('.collapse').bind('click', function() {
		
		if($(this).hasClass('collapse_up'))
		{
			$(this).parent(':first').next('.collapsible').slideUp();
			$(this).removeClass('collapse_up')
					.addClass('collapse_down');
		}
		else
		{
			$(this).parent(':first').next('.collapsible').slideDown();
			$(this).removeClass('collapse_down')
					.addClass('collapse_up');
		}
	});
	
	$(obj).find('.userEnabled').bind('change', function() {
	
		var value = 0;
		var userId = $(this).parents('tr:first').attr('data-user_id');
	
		if(this.checked)
		{
			value = this.value;
		}
		
		loadModule('user.setEnabled', 'user_id=' + userId + '&enabled=' + value);
	});
		
	$(obj).find('.requestHidden').bind('change', function() {
	
		var value = 0;
		var requestId = $(this).parents('tr:first').attr('data-request_id');
	
		if(this.checked)
		{
			value = this.value;
		}
		
		loadModule('request.hide', 'request_id=' + requestId + '&hidden=' + value);
	});
			
	$(obj).find('.requestDeleted').bind('change', function() {
	
		var value = 0;
		var requestId = $(this).parents('tr:first').attr('data-request_id');
	
		if(this.checked)
		{
			value = this.value;
		}
		
		loadModule('request.delete', 'request_id=' + requestId + '&deleted=' + value);
	});
	
	$('<div class="loadingBox"></div>').insertAfter($(obj).find('input[data-validate="user"]'));
	
	$(obj).find('input[data-validate="user"]').bind('keydown', function() {
	
		var input = this;
		
		$('.loadingBox').removeClass('isValid').removeClass('isInvalid');
	
		if(validationTimer) clearTimeout(validationTimer);
	
		validationTimer = setTimeout(function() {
			if(!$('.loadingBox').hasClass('isLoading'))
			{
				$('.loadingBox').addClass('isLoading');
			}
			loadModule('user.exists','user=' + input.value);
		}, 600);
	});
	
	$(obj).find('form').bind('submit', function(event) {
	
		event.preventDefault();
		
		var form = $(this);
		var params = form.serialize();
		
		var module = form.attr('action').replace(/\..*/, '');
		var action = form.attr('action').replace(/.*\./, '');
		var functionName = 'on' + module.toProperCase() + action.toProperCase();

		$.ajax({
			url: '/index.php?module=' + module + '&action=' + action,
			data: params,
			dataType: 'json',
			type: 'POST',
			success: function(data, textStatus){
				if(data)
				{
					var fn = window[functionName];
					if(typeof fn === 'function') {
						fn.apply(this, arguments);
					}
				}
			}
		});

	});
}

function initObject(obj, which)
{
	init(obj);

	var wizard = $(obj).find('form.wizard');
	var position = 0;
	
	wizard.find('fieldset.page').each(function(i) {
		if($(this).hasClass('first') == false) $(this).hide();
	});
	
	$(obj).find('.prevButton').bind('click', function() { wizardBack(obj); });
	$(obj).find('.nextButton').bind('click', function() { wizardNext(obj); });
	
	switch(which)
	{
		// Modal handlers go here
		case 'register':
			$(obj).find('#user_password, #user_password2').keyup(function() {
				if(this.value.length > 0)
				{
					if($('#user_password').val() == $('#user_password2').val())
					{
						$('#user_password, #user_password2').removeClass('invalid').addClass('valid');
					}
					else
					{
						$('#user_password, #user_password2').removeClass('valid').addClass('invalid');
					}
				}
			});
		default:
			$(obj).find('input[type=text], input[type=radio], input[type=password], textarea').change(function() {
			
				var target = $(obj).find('[data-source="' + this.name + '"]');
				var text = this.value;
				
				switch(target.attr('data-mask'))
				{
					case 'password': text = text.replace(/./g, '*'); break;
				}
			
				target.html(text);
			});
		break;
	}

	wizardRefresh(obj);

}

function pageInit(scope)
{
	addGroupData( Groups.records, scope );
	addListData( Lists.records, scope );
}

// ----- AJAX EVENTS -----

function onUserLogin(data)
{
	if(data.success === true)
	{
		userInit();
		$("nav a[href='#account']").parent('li').removeClass('hide');
		$("nav a[href='#login']").parent('li').addClass('hide');
		
		loadPage('requests');
	}
	else if(data.success === false)
	{
		if(data.isVerified === false)
		{
			if(confirm('You must verify your e-mail address to log in. Would you like to go to the verification page now?'))
			{
				loadPage('verify');
			}
		}
		else if(data.isEnabled === false)
		{
			alert('Your account has been disabled.');
		}
		else if(data.invalidLogin === true)
		{
			alert('You have submitted an incorrect username and/or password.');
		}
	}
	else
	{
		alert('We were unable to log in you at this time. Please try again.');
	}
}

function onUserLogout(data)
{
	if(data.success === true)
	{
		User = {};
		Groups = new Data({ name: 'group' });
		Lists = new Data({ name: 'list' });
		Commitments = new Data({ name: 'commitment' });
	
		$("[data-auth='req']").hide();
	
		userInit();
		$("nav a[href='#account']").parent('li').addClass('hide');
		$("nav a[href='#login']").parent('li').removeClass('hide');
		$('body > #admin').remove();
		loadPage('home');
	}
	else
	{
		alert('We were unable to log you out at this time.');
	}
}

function onUserVerify(data)
{
	if(data.success === true)
	{
		loadPage('login');
		alert('Verification complete. You may now log in.');
	}
	else
	{
		alert('Verification code did not match any user.');
	}
}

function onUserResendverify(data)
{
	if(data.success === true)
	{
		alert('Please check your e-mail for a new verification code.');
	}
	else
	{
		alert('Unable to send verification code at this time. Please try again later.');
	}
}

function onUserEdit(data)
{
	if(data.success === true)
	{
		alert('Your profile was successfully updated.');
	}
	else
	{
		alert('Failed to update your profile. Please try again later.');
	}
}

function onUserExists(data)
{
	$('.loadingBox').removeClass('isLoading');
	
	if(data.success === true)
	{
		$('.loadingBox').addClass('isValid').attr('title', 'Valid user!');
	}
	else
	{
		$('.loadingBox').addClass('isInvalid').attr('title', 'This user was not found. Please check your spelling and try again.');
	}
}

function onGroupCreate(data)
{
	if(data.success === true)
	{
		Groups.add({
			name: data.results.name,
			description: data.results.description,
			group_id: data.results.group_id
		});
		
		if(currentPage == 'groups') loadPage('groups');
		
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onGroupEdit(data)
{
	if(data.success === true)
	{
		loadPage('groups');
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onGroupDelete(data)
{
	if(data.success === true)
	{
		loadPage('groups');
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onListEdit(data)
{
	if(data.success === true)
	{
		loadPage('lists');
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onUserCreate(data)
{
	if(data.success === true)
	{
		alert("Account created successfully!\nPlease check your e-mail to get your account verification code.");
		loadPage('verify');
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onListCreate(data)
{
	if(data.success === true)
	{
		Lists.add({
			name: data.results.name,
			description: data.results.description,
			list_id: data.results.list_id
		});
		
		if(currentPage == 'lists') loadPage('lists');
		
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onRequestCreate(data)
{
	if(data.success === true)
	{
		addRequest(data, true);
		$('#requestEntry textarea').val('').blur();
		$('#requestEntry .cancel').click();
	}
	else
	{
		alert(data.error);
	}
}

function onMessageCreateinvite(data) { onMessageCreate(data); }
function onMessageCreate(data)
{
	if(data.success === true)
	{
		alert('Your message has been sent!');
		$('.close-reveal-modal').click();
	}
	else
	{
		alert(data.error);
	}
}

function onRequestAddcomment(data)
{
	if(data.success === true)
	{
		var row = data.results[0];
		var div = buildCommentListItem(row);
		
		$(div).hide();
		
		var commentCount = $('#request-' + row.request_id).find('.commentCount');
		var count = parseInt(commentCount.html());
		commentCount.html(++count);
		
		$('#commentsFor-' + row.request_id + ' input[name=comment_body]').val('');
		$('#commentsFor-' + row.request_id + ' .commentsList').prepend(div);
		
		$(div).slideDown();
	}
	else
	{
		alert(data.error);
	}
}

function buildCommentListItem(data)
{
	var div = document.createElement('div');
	var user = document.createElement('div');
	
	$(user).addClass('user').html(data.username);
	$(div).html(data.body).append(user);
	
	return div;
}

function onRequestGetcomments(data)
{
	if(data.success === true)
	{
		for(var i in data.results)
		{
			var row = data.results[i];
			var div = buildCommentListItem(row);

			$('#commentsFor-' + row.request_id + ' .commentsList').append(div);
		}
	}
	else
	{
		alert(data.error);
	}
}

function onToggleComment(requestId)
{
	var parent = $('#request-' + requestId);
	var commentBox = parent.find('.options .comment');
	
	if(commentBox.hasClass('comment_on'))
	{
		commentBox.removeClass('comment_on').addClass('comment_off');
	}
	else
	{
		commentBox.removeClass('comment_off').addClass('comment_on');
	}

	if($('#commentsFor-' + requestId).children('.commentsInner').length === 0)
	{
		var container = document.createElement('form');
		var textarea = document.createElement('input');
		var button = document.createElement('button');
		var buttonGroup = document.createElement('div');
		var hiddenInput = document.createElement('input');
		
		var commentsList = document.createElement('div');
		$(commentsList).addClass('commentsList');
		
		loadModule('request.getComments', 'request_id=' + requestId);
		
		$(hiddenInput).attr('name', 'request_id').attr('type', 'hidden').val(requestId);
		$(button).attr('type', 'submit').addClass('default').html('Submit Encouragement').attr('disabled','disabled');
		$(textarea).attr('name','comment_body').bind('change', function() {
			if($(textarea).val().length > 0)
			{
				$(button).removeAttr('disabled');
			}
			else
			{
				$(button).attr('disabled','disabled');
			}
		});
		$(container).addClass('commentsInner').attr('action','request.addComment').hide()
			.append(hiddenInput)
			.append(textarea)
			.append(button)
			.append(buttonGroup)
			.append(commentsList);
		$('#commentsFor-' + requestId).append(container);
		$(container).slideDown(function() {
			init('#commentsFor-' + requestId);
		});
	}
	else
	{
		var comments = $('#commentsFor-' + requestId + ' .commentsInner');
		
		if(comments.is(':visible'))
		{
			comments.slideUp();
		}
		else
		{
			comments.slideDown();
		}
	}
}

function onListEmaillastviewed(data)
{
	if(data.success === true)
	{
		alert('Message sent successfully');
	}
	else
	{
		alert('The message could not be sent!');
	}	
}

function onRequestSearch(data) { addRequest(data); }
function onRequestGetrecent(data) { addRequest(data); }
function onRequestGetbygroupid(data) { $('#list-toolbar').slideUp();  addRequest(data); }
function onRequestGetbylistid(data) { $('#list-toolbar').slideDown(); addRequest(data); }

function addRequest(data, stopClear)
{
	if(data.success === true)
	{
		if(!stopClear)
		{
			$('#requests').fadeOut(function() { addRequestInner(data, stopClear) });
		}
		else
		{
			addRequestInner(data, stopClear);
		}
	}
	else
	{
		alert(data.error);
	}
}

function onListDelete(data)
{
	if(data.success === true)
	{
		$("[data-type='list'] + [data-id='" + data.results.list_id + "']").remove();
	}
}

function onGroupJoin(data)
{
	if(data.success === true)
	{
		var pending = data.results.pending;
		if(pending)
		{
			alert('You have been added to a waiting list for the group.');
		}
		else
		{
			alert('You have joined the group!');
		}
		
		$('.close-reveal-modal').click();
	}
}

function onGroupLeave(data)
{
	if(data.success === true)
	{
		alert('You have left the group.');
		
		if(currentPage == 'groups') loadPage('groups');
		
		$('.close-reveal-modal').click();
	}
}

function onMessageUs(data)
{
	if(data.success === true)
	{
		alert('Thank you for your feedback! Your message was sent to us successfully.');
		$('form#contact').find('input, textarea').val('');
	}
}

function onGroupAcceptmember(data)
{
	if(data.success === true)
	{
		var obj = $('[data-user_id=' + data._post.user_id + ']');
		var text = obj.text().trim();
		
		obj.fadeOut(function() {
		
			var ml = $("#membersList[data-is-empty]");
			
			if(ml.length) {
				ml.removeAttr('data-is-empty').html(text);
			} else {
				ml = $("#membersList");
				ml.html( ml.html() + ', ' + text );
			}
			
			$('.tooltip').hide();
			$(this).remove();
		
		});
	}
}

function onGroupDeclinemember(data)
{
	if(data.success === true)
	{
		$('[data-user_id=' + data._post.user_id + ']').fadeOut(function() { $(this).remove(); });
	}
}

function addRequestInner(data, stopClear)
{
	if(!stopClear)
	{
		$('#requests').html('');
	}
	
	$('#requests').show();

	for(var i=data.results.length - 1; i != -1; i--)
	{
		var hidden = '';
		var record = data.results[i];
		var group_name = record.group_name ? "<a href=\"javascript:void(0);\" onclick=\"loadModal('group_details','group_id=" + record.group_id + "');\">" + record.group_name + "</a>" : 'Public Request';
		
		var request = $('<div id="request-' + record.request_id + '">');
		var requestHTML = "<div class=\"avatar\"><img src=\"" + record.avatarUrl + "\" alt=\"Avatar\" /></div>"
			+ "<div class=\"title\">" + group_name + "<div class=\"time\">" + record.displayTime + "</div></div>"
			+ "<div class=\"body\">" + record.content + "<div class=\"user\">" + record.username + "</div></div>";
			
		if(!record.commitments || record.commitments == 0) { hidden = ' hidden' }
		
		requestHTML += "<div class=\"commitments" + hidden + "\"><span class=\"count\" title=\"" + record.commitmentMessage + "\">" + record.commitments + "</span></div>";
		
		requestHTML += "<div class=\"options\">"
			+ "<a href=\"javascript:void(0);\" onclick=\"onCommit(" + record.request_id + ");\" class=\"icon committed committed_" + (record.committed > 0 ? 'on' : 'off') + "\" title=\"Commit to praying\">&nbsp;</a>"
			+ "<a href=\"javascript:void(0);\" class=\"icon comment comment_off\" title=\"Comments\" onclick=\"onToggleComment(" + record.request_id + ");\">" + (record.comments || '0') + "&nbsp;</a>"
			+ "<a href=\"javascript:void(0);\" class=\"icon send_message send_message_off\" onclick=\"loadModal('new_message', { request_id: " + record.request_id + "});\" title=\"Send this person a private message.\">&nbsp;</a>"
			+ "<a href=\"javascript:void(0);\" onclick=\"onSave(" + record.request_id + ");\" class=\"icon save save_off\" title=\"Save to a list. If you have not selected a list, it will be saved to Uncategorized.\">&nbsp;</a>"
			+ "<a href=\"javascript:void(0);\" onclick=\"onFlag(" + record.request_id + ");\" class=\"icon flag flag_off\" title=\"Mark as inappropriate\">&nbsp;</a>"
			+ "</div>";

		$(request).addClass('request').html(requestHTML).hide();
		$(request).prependTo('#requests').fadeIn();
		
		commentHTML = $('<div class="comments" id="commentsFor-' + record.request_id + '">');
		
		$(commentHTML).insertAfter(request);
	}
	
	if(data.results.length == 0)
	{
		var request = $('<div id="request-0">');
		var requestHTML = "We're sorry, but no requests were found.";

		$(request).addClass('request').html(requestHTML).hide();
		$(request).prependTo('#requests').fadeIn();
	}
	
	init('#requests');
}

// ----- END AJAX EVENTS -----

function wizardBack(obj)
{
	wizardRefresh(obj, -1);
}

function wizardNext(obj)
{
	wizardRefresh(obj, 1);
}

function wizardRefresh(obj, amount)
{
	var wizard = $(obj).find('form.wizard');
	var pages = wizard.find('fieldset.page');

	var i = 1;
	
	if(amount)
	{
		for(i = 0; i < pages.length; i++)
		{
			if($(pages[i]).is(':visible'))
			{
				$(pages[i]).hide();
				$(pages[i + amount]).show();
				break;
			}
		}
	}
	
	if(pages.length == 1)
	{
		$(obj).find('.nextButton').hide();
		$(obj).find('.doneButton').show();
	}
	else if(i + 2 == pages.length)
	{
		$(obj).find('.nextButton').hide();
		$(obj).find('.doneButton').show();
	}
	else
	{
		$(obj).find('.nextButton').show();
		$(obj).find('.doneButton').hide();
	}
	
	if(i == 1) { $(obj).find('.prevButton').hide(); } else { $(obj).find('.prevButton').show(); }
	
	onWizardRefreshed(obj);
}

function onWizardRefreshed(obj)
{

}

function listDelete(listId)
{
	if(confirm('Are you sure you want to delete this list?'))
	{
		loadModule('list.delete', 'list_id=' + listId);
	}
}

function loadModal(which, data)
{
	var element = null;
	
	if(typeof which == "object")
	{
		element = $(which.target);
		element.attr('disabled', 'disabled');
		which = $(which.target).attr('data-modal');
	}
	
	data = data || {};

	var content = $(document.createElement('div'));
	content.appendTo("body");
	content.load('/?module=' + which, data, function(responseText, textStatus, XMLHttpRequest) {
	
		switch(XMLHttpRequest.status)
		{
			case 404:
				alert('We were unable to load the data you requested right now. Please try again soon.');
			break;
			default:
				$(content).find('.reveal-modal').reveal();
				initObject(content, which);
			break;
		}
		
		if(element) element.removeAttr('disabled');
	});
}

var currentPage = "";

function loadPage(target, checkBeforeLoad)
{
	if(checkBeforeLoad)
	{
		if(currentPage == target) return;
	}

	var matches = $('nav a[href="#' + target + '"]');
	var query = '&' + window.location.search.replace('?','');
	
	currentPage = target;
	
	if(matches.length > 0)
	{
		toggleTab({ target: matches[0] }, false);
	}

	$('#main').load('/?module=' + target + query, function() { init('#main'); pageInit('#main'); });
	
	window.location.hash = target;
}


function loadModule(target, params)
{
	var module = target.replace(/\..*/, '');
	var action = target.replace(/.*\./, '');
	var functionName = 'on' + module.toProperCase() + action.toProperCase();

	$.ajax({
		url: '/index.php?module=' + module + '&action=' + action,
		dataType: 'json',
		type: 'POST',
		data: params || {},
		success: function(data, textStatus){
			if(data)
			{
				var fn = window[functionName];
				if(typeof fn === 'function') {
					fn.apply(this, arguments);
				}
			}
		}
	});
}

$(function() {
	
	userInit();

});


var Paginator = function(config)
{
	// Private methods
	

	// Public methods
	return {
		resultsPerPage: 20
	}
};

