if(!jsProfiles) { var jsProfiles = new Object(); }

jsProfiles = {
	// datamembers
	debug: jsFrontend.debug,
	// init, something like a constructor
	init: function() {
		jsProfiles.calendar.init();
		jsProfiles.relations.init();
		jsProfiles.messages.init();
		jsProfiles.newsletters.init();
		jsProfiles.privatemessage.init();
		jsProfiles.register.init();
		jsProfiles.stream.init();
		jsProfiles.urls.init();
	},
	// end
	_eoo: true
}	

jsProfiles.calendar = {
	// init, something like a constructor
	init: function() {
		jsProfiles.calendar.toggleAllSites();
	},
	// if the checkbox is checked all items with .otherSite are shown
	toggleAllSites: function() {
		if($('#all_sites').length > 0) {
			$('#all_sites').bind('change', function(evt) {
				if($('#all_sites').is(':checked')) { $('.otherSite:hidden').show(); }
				else $('.otherSite:visible').hide();
				jsProfiles.calendar.toggleMessage();
			});
		}		
	},
	// show or hide the message for filtered items
	toggleMessage: function() {
		// do some layout stuff
		if($('.events tr:hidden').length > 0) $('#someEventsAreHidden').slideDown(500);
		else $('#someEventsAreHidden').slideUp(500);
	},
	// end
	_eoo: true
}

jsProfiles.messages = {
	// datamembers
	receiverHTML:	'<li id="receiver-{id}" style="display: none;">' +
					'	<span class="closeButton"><a href="#{id}" class="icon closeButton"><span>verwijder</span></a></span>' +
					'	<div class="avatar av48">' +
					'		<div class="avOverlay">&nbsp;</div>' +
					'		<img src="http://api.musichall.be/modulefiles/profiles/avatars/48x48/{avatar}"/>' +
					'		<p>{nick}</p>' +
					'	</div>' +
					'</li>',
	// init, something like a constructor
	init: function() {
		if(!jQuery.browser.msie) $('#sendMessage #message').autogrow();
		$('#addReceiver').bind('click', jsProfiles.messages.addReceiver);
		$('.closeButton').live('click', jsProfiles.messages.closeButton);
	},
	// add a friend
	addReceiver: function(evt) {
		evt.preventDefault();
		
		if($('#friends').val() === null) return false;
		
		// split val into chunks
		var chunks = $('#friends').val().split(':::');
		var val = $('#friends').val();

		// create object
		friend = new Object();
		friend.id = chunks[0];
		friend.avatar = chunks[1];
		friend.nick = chunks[2];
		
		// already in list
		if($('#receiver-'+ friend.id).length > 0) $('#receiver-'+ friend.id).effect('highlight');

		// else
		else {
			// build html
			var toInsert = JS_NETLASH.utils.string.assignFromObject(jsProfiles.messages.receiverHTML, friend); 
			
			$('#receivers').append(toInsert);
			$('#receiver-'+ friend.id).fadeIn();
	
			// get current receivers
			var receiverIdsValue = $('#receiver_ids').val();
			var receiverIds = new Array();
			
			// split exisiting receivers
			if(receiverIdsValue != '') receiverIds = receiverIdsValue.split(',');
			
			// add
			receiverIds.push(friend.id);
			
			// set val
			$('#receiver_ids').val(receiverIds.join(','));
			
			// disable element
			$('#friends option[value='+ val +']').attr('disabled', 'disabled');
			$('#friends').val('-1');
		}
	},
	// delete a receiver
	closeButton: function(evt) {
		evt.preventDefault();

		// get id
		var id = $(this).attr('href').split('#')[1];

		// loop all options
		$('#friends option').each(function() { 
			if($(this).val().split(':::')[0] == id) $(this).attr('disabled', '');
		});
		
		
		// get current receivers
		var receiverIdsValue = $('#receiver_ids').val();
		var receiverIds = new Array();
		var newReceiverIds = new Array();
		
		// split exisiting receivers
		if(receiverIdsValue != '') receiverIds = receiverIdsValue.split(',');
		
		// loop receivers
		for(var i in receiverIds) {
			if(receiverIds[i] != id) newReceiverIds.push(receiverIds[i]);
		}
		
		$('#receiver_ids').val(newReceiverIds.join(','));
		$('#receiver-'+ id).fadeOut(500, function() { $(this).remove(); });
	},
	// end
	_eoo: true		
}

jsProfiles.newsletters = {
	// init, something like a constructor
	init: function() {
		if($('#newsletter').length > 0) {
			jsProfiles.newsletters.toggle();
			$('#newsletter').bind('change', jsProfiles.newsletters.toggle);
		}
	},
	// if the checkbox is checked all items with .otherSite are shown
	toggle: function() {
		if($('#newsletter').is(':checked')) {
			$('#newsletterList input').attr('disabled', '')
			  						  .removeClass('disabled');
			$('#newsletterList').removeClass('disabled');
		} else {
			$('#newsletterList input').attr('disabled', 'disabled')
									  .addClass('disabled');
			$('#newsletterList').addClass('disabled');
		}
	},
	// end
	_eoo: true
}

jsProfiles.privatemessage = {
	// init, something like a constructor
	init: function() {
		if($('#sendPrivateMessage').length > 0) {
			$('#sendPrivateMessage').dialog({ autoOpen: false, modal: true, resizable: false, draggable: false, width: 400,
				buttons: {
					'Verstuur': function() { jsProfiles.privatemessage.send(); },
					'Annuleer': function() { $(this).dialog('close'); }
			} });			
			$('#sendMessageSent').dialog({ autoOpen: false, modal: true, resizable: false, draggable: false });			
			
			$('.toggleMessage').bind('click', function(evt) { 
				evt.preventDefault();
				$('#sendPrivateMessage').dialog('open');
			});
		}
	},
	send: function() {
		// init var
		var error = false;

		// validate
		if($('#subject').val() == '') {
			$('#subject').after('<span class="form-error">Gelieve een onderwerp in te geven.</span>');
			error = true;
		}

		if($('#message').val() == '') {
			$('#message').after('<span class="form-error">Gelieve een boodschap in te geven.</span>');
			error = true;
		}
		
		if(!error)
		{
			$.ajax({ type: 'post', dataType: 'json', cache: false,
				url: '/ajax.php?module=profiles&action=send_message', 
				data: 'receiver_id='+ $('#profile_id').val() + '&subject=' + $('#subject').val() + '&message='+ $('#message').val(),
				success: function(json) {
					switch (parseInt(json.status.code)) {
						case 200:
						case 400:
							$('#sendPrivateMessage').dialog('close');
							$('#sendMessageSent').dialog('open');
						break;
						case 500:
						default:
							if(jsFrontend.debug) { alert(json.status.text); }
						break;
					}
				},
				error: function(xhr,err,e) { if(jsFrontend.debug) { alert(err + ' ' + e, 'Critical Error'); } }
			});
		}
	},
	// end
	_eoo: true
}

jsProfiles.relations = {
	// datamembers
	followerHTML: 	'<li id="follower-{id}">' +
					'	<div class="avatar av48">' +
					'		<a href="{url}">' +
					'			<div class="avOverlay">&nbsp;</div>' +
					'			<img src="http://api.musichall.be/modulefiles/profiles/avatars/48x48/{avatar}"/>' +
					'		</a>' +
					'	</div>' +
					'	<p><a href="{url}">{nick}</a></p>' +
					'</li>',
	// init, something like a constructor
	init: function() {
		if($('.toggleFollow').length > 0) {
			$('#modalLoginScreen').dialog({ autoOpen: false, modal: true, resizable: false, draggable: false, width: 400 });
			$('.toggleFollow').bind('click', function(evt) { jsProfiles.relations.toggle(evt, $(this)); });
		}
	},
	toggle: function(evt, el) {
		evt.preventDefault();
		var method = el.attr('rel');
		var id = el.attr('href').split('#')[1];
		
		// show spinner
		$('#followSpinner').fadeIn();
		
		$.ajax({ type: 'post', dataType: 'json', cache: false,
			url: '/ajax.php?module=profiles&action=toggle_follow', 
			data: 'method='+ method +'&other_id='+ id,
			success: function(json) {
				switch (parseInt(json.status.code)) {
					case 200:
					case 400:
						if(method == 'follow') {
							var toInsert = JS_NETLASH.utils.string.assignFromObject(jsProfiles.relations.followerHTML, json.content.user);
							$('#followers').prepend(toInsert);
							$('#follower-'+ json.content.user.id).effect('highlight', null, 2500);
							$('#noFollowers').hide();
							el.attr('rel', 'unfollow');
							$('.toggleFollow span').html('Niet meer volgen');
							$('.followersCount').each(function() { $(this).html(parseInt($(this).html()) + 1); });
							$('#notFollowingMessage').hide();
							$('#followingMessage').show();
						} else {
							$('#follower-'+ json.content.user.id).effect('highlight', null, 400, function() {
								$(this).fadeOut(400, function() {
									if($('#followers li:visible').length == 0) {
										$('#noFollowers').show();
										$('#followers').hide();
									}
									$(this).remove();
								});
								el.attr('rel', 'follow');
								$('.toggleFollow span').html('Volg');
								$('.followersCount').each(function() { $(this).html(parseInt($(this).html()) - 1); });
								$('#notFollowingMessage').show();
								$('#followingMessage').hide();
							});
						}
						$('#followers li').removeClass('newRow');
					break;

					case 500:
						$('#modalLoginScreen').dialog('open');
					break;
					default:
						if(jsFrontend.debug) { alert(json.status.text); }
					break;
				}
			},
			error: function(xhr,err,e) { if(jsFrontend.debug) { alert(err + ' ' + e, 'Critical Error'); } }
		});
		
		// hide spinner
		$('#followSpinner').fadeOut();
		
	},
	// end
	_eoo: true
}

jsProfiles.register = {
	// init, something like a constructor
	init: function() {
		if($('#nickname').length > 0) {
			$('#nickname').bind('keyup', function(evt) { 
				if($('#nickname').val() == '') $('#yoururl').html('je-nickname');
				else $('#yoururl').html(JS_NETLASH.utils.string.urlise($('#nickname').val()));
			});
		}
	},
	// end
	_eoo: true
}

jsProfiles.stream = {
	// datamembers
	interval: null,
	intervalInSeconds: 20,
	// init, something like a constructor
	init: function() {
		if($('#activities').length > 0) {
			jsProfiles.stream.interval = setInterval(jsProfiles.stream.get, parseInt(jsProfiles.stream.intervalInSeconds * 1000));
		}
	},
	// load the data
	get: function() {
		$.ajax({ type: 'post', dataType: 'json', cache: false,
			url: '/ajax.php?module=profiles&action=get_stream',
			data: 'last_date='+ $('#streamFull ul li:first').attr('id').split('-')[2],
			success: function(json) {
				switch (parseInt(json.status.code)) {
					case 200:
					case 400:
						// loop actions
						for(var i in json.content.actions) {
							// already in log?
							if($('#' + json.content.actions[i].id).length == 0) {
								// get class
								var newClass = ($('#streamFull ul li:first').attr('class') == 'odd') ? 'even' : 'odd';
								
								// build html
								var html = 	'<li class="'+ newClass +'" id="'+ json.content.actions[i].id +'">' +
											'	<div class="avatar av24"><img width="24" height="24" alt="'+ json.content.actions[i].profile_nick +'" src="http://api.musichall.be/modulefiles/profiles/avatars/24x24/'+ json.content.actions[i].profile_avatar +'"/></div>' +
											'		<div class="item">'+ json.content.actions[i].message +'</a>' +
											'	</div>' +
											'	<div class="time"><p>'+ json.content.actions[i].date +'</p></div>' +
											'	<div class="guillotineFix">&nbsp;</div>' +
											'</li>';
								
								// insert html
								$('#streamFull ul').prepend(html);
								$('#'+ json.content.actions[i].id).effect('highlight');
							}
						}
					break;
					case 500:
						if(jsFrontend.debug) { alert(json.status.text); }
					break;
					default:
						if(jsFrontend.debug) { alert(json.status.text); }
					break;
				}
			},
			error: function(xhr,err,e) { if(jsFrontend.debug) { alert(err + ' ' + e, 'Critical Error'); } }
		});
	},
	// end
	_eoo: true	
}

jsProfiles.urls = {
	// datamembers
	urlHTML: '<li>' +
			 '	<input class="inputCheckbox" type="checkbox" />' +
			 '	<input class="inputText" type="text" value="{link}" name="websites[]" id="websites{id}" />' +
			 '</li>',
	// init, something like a constructor
	init: function() {
		if($('#addWebsiteLink').length > 0) {
			if($('#urlManager input:checkbox').length == 0) { $('#urlManager').hide(); }
			$('#addWebsiteLink').bind('click', jsProfiles.urls.add);
			$('#website').attr('autocomplete', 'off')
						 .bind('keypress', function(evt) {
							if (evt.which == 13) {
								evt.preventDefault();
								evt.stopPropagation();
								jsProfiles.urls.add(evt);
							} })
						.bind('focus', function(evt) { if ($(this).val() == '') { $(this).val('http://'); } })
						.bind('blur', function(evt) { if ($(this).val() == 'http://') { $(this).val(''); } });
			$('#deleteWebsitesLink').bind('click', jsProfiles.urls.deleteUrls);
		}
	},
	// add an url
	add: function(evt) {
		evt.preventDefault();
		$('#invalidWebsite').hide();
		$('#addWebsiteWrapper .form-error').hide();
		if(!JS_NETLASH.utils.form.isUrl($('#website'))) {
			$('#invalidWebsite').show();
			$('#website').focus();			
		} else {
			$('#urlManager').fadeIn(500);
			$('#invalidWebsite').hide();

			var nextId = parseInt($('#urlManager li:last p input').length) + 1;
			
			$('#urlManager ul.inputList').append(JS_NETLASH.utils.string.replaceAll(JS_NETLASH.utils.string.replaceAll(jsProfiles.urls.urlHTML, '{link}', $('#website').val()), '{id}', nextId));
			$('#website').val('').focus();
		}
	},
	deleteUrls: function(evt) {
		evt.preventDefault();
		$('#urlManager input:checkbox:checked').parent().remove();
		if($('#urlManager input:checkbox').length == 0) { $('#urlManager').hide(); }
	},
	// end
	_eoo: true
}

$(document).ready(function() { jsProfiles.init(); });