jQuery('.h-user-plate').ready(function($) {
	var link = $('.h-user-plate .profile-link').attr('title', 'Сменить портрет');

	link.click(function(e) {
		e.preventDefault();

		var dlg = $('<div style="text-align: center"><img src="/images/ajax/bigcircle-loader.gif" alt="Загрузка..." />').dialog( {
			title: '',
			width: 500,
			height: 300,
			buttons: {
				/*'Отмена': function() {
					$(this).dialog('close');
				},*/
				'Загрузить': function() {
					$('form', dlg).submit();
				}
			},
			close: function(){
				$(this).dialog('destroy').remove();
			},
			modal: true,
			resizable: false,

			open: function(){
				os.query('/ajax/users/', {
					cmd: 'portrait edit dialog'
				}, function(data, errors){
					if (!data.success)
					{
						os.alert('Произошла ошибка. Приносим извинения.');
						dlg.dialog('close');
						return;
					}

					dlg.html(data.dialog).dialog('option', {title: 'Портрет'}).css({'text-align': 'left'});
					/*.closest('.ui-dialog').animate({
						width: $('> *', dlg).width()+50,
						height: $('> *', dlg).height()+90,
						left: ($(window).width() - $('> *', dlg).width() - 50)/2,
						top: ($(window).height() - $('> *', dlg).height()- 90)/2,
					}, 500);*/
					
					var processing = false;
					$('form', dlg).submit(function(e)
					{
						e.preventDefault();
						if (processing) return;
						var file = $('input[type=file]', this);
						if (!file.val()) return;

						var submit = $('dutton[type=submit]', this);
						var processing = true;
						
						os.query('/ajax/users/', {
							cmd: 'upload portrait',
							portrait: file.get(0)
						}, function(data, errors){
							processing = false;
							if (!data.success)
							{
								os.alert('Произошла ошибка. Приносим извинения.');
								return;
							}

							$('img.avatar-x, img.avatar-50, img.avatar-100, img.avatar-150, a.profile-link > img').each(function(){
								var src = $(this).attr('src')+'';
								old = src.replace(/^.*?\/r\/[^\/]*?\/(.*)$/, '$1');
								if (old == data.old_image)
								{
									src = src.replace(/\/r\/([^\/]*?)\/.*$/, '/r/$1/'+data.portrait);
									$(this).attr('src', src);
								}
							});
							
							file.val('');
						}, true);
					});
				}, true);
			}
		});
	});
	
	// Анимируем выпадающее меню
	var m = $('.h-user-plate .profile-menu');
	var h = 0;
	$('.h-user-plate .uname').hover(function(){
		m.show();
		if (h == 0)
			h = m.height();
		m.height(0);
		m.stop().animate({height: h}, 250);
	}, function(){
		m.stop().animate({height: 0}, 250, function(){
			$(this).hide();
		});
	});
	
	$('.h-user-plate .profile-menu li').hover(
		function(){
			$(this).css('background','#5885aC');
		},
		function(){
			$(this).css('background','#28558C');
		}
	);	
});
