hs.showCredits = false;
hs.graphicsDir = "http://static.lolkot.ru/js/highslide/graphics/";
hs.lang = {
   loadingText :     'Загружается...',
   loadingTitle :    'Нажмите для отмены',
   focusTitle :      'Нажмите чтобы поместить на передний план',
   fullExpandTitle : 'Развернуть до оригинального размера',
   fullExpandText :  'Оригинальный размер',
   creditsText :     'Использует <i>Highslide JS</i>',
   creditsTitle :    'Перейти на домашнюю страницу Highslide JS',
   previousText :    'Предыдущее',
   previousTitle :   'Предыдущее (стрелка влево)',
   nextText :        'Следующее',
   nextTitle :       'Следующее (стрелка вправо)',
   moveTitle :       'Переместить',
   moveText :        'Переместить',
   closeText :       'Закрыть',
   closeTitle :      'Закрыть (esc)',
   resizeTitle :     'Изменить размер',
   playText :        'Слайдшоу',
   playTitle :       'Начать слайдшоу (пробел)',
   pauseText :       'Пауза',
   pauseTitle :      'Приостановить слайдшоу (пробел)',   
   number :          'Изображение %1 из %2',
   restoreTitle :    'Нажмите чтобы закрыть изображение, нажмите и перетащите для изменения местоположения. Для просмотра изображений используйте стрелки.'
};
hs.align = 'center';
hs.transitions = ['expand', 'crossfade'];
hs.wrapperClassName = 'dark borderless floating-caption';
hs.fadeInOut = true;
hs.dimmingOpacity = .75;

function ajaxFileUpload(){
	if($('#album-upload').attr('disabled')){
		return;
	}
	$("#album-upload").addClass("loading").html("загрузка...").attr('disabled',true);
	$.ajaxFileUpload({
		url:'http://lolkot.ru/features/user-albums/upload.php', 
		secureuri:false,
		fileElementId:'userfile',
		dataType: 'plain',
		success: function (response, status){
			$("#album-upload").removeClass("loading").html("закачать").attr('disabled',false);
			if(response.length>2 && response.substring(0,2)=="ok"){
				var userid = response.substring(3,response.lastIndexOf(","));
				var imgid = response.substring(response.lastIndexOf(",")+1,response.length);
				ua_loadImage(imgid, userid, true);
			}else{
				alert(response);
			}
		},
		error: function (data, status, e){
			alert(e);
			$("#album-upload").removeClass("loading").html("закачать").attr('disabled',false);			
		}
	})
	return false;
}  

function ua_loadImage(image_id, user_id, doPrepend){
	var foto = 'http://static.lolkot.ru/images/user-albums/'+user_id+'/foto'+image_id+'.jpg',
		thumb = 'http://static.lolkot.ru/images/user-albums/'+user_id+'/thumbnails/foto'+image_id+'_140x140.jpg',
		img = new Image();
	img.onload = function(){
		var li = document.createElement('li');
		li.id = 'image_li' + image_id;
		li.style.display = 'none';
		li.innerHTML = '<a href="'+foto+'" class="image highslide" onclick="return hs.expand(this)" title="Увеличить"><img src="'+thumb+'" alt="" width="140" height="140" /></a><div class="highslide-caption"><a href="http://lolkot.ru/lolmixer/#'+foto+'">&rarr; отправить в лолМиксер</a></div><a class="removeAlbumPhoto photo'+image_id+'" title="удалить"></a>';
		if($("ul.thumb").length==0){
			var nofoto = document.getElementById('no-foto');
			var ul = document.createElement('ul');
			ul.className = 'thumb';
			nofoto.parentNode.insertBefore(ul, nofoto);
			$('#no-foto').remove();
		}
		
		if(doPrepend){
			$("ul.thumb").prepend(li);
			if($("ul.thumb li").length>9){
				$('ul.thumb>li:last').remove();
			}
			$(li).fadeIn('slow', function(){
				$(li).find('a.removeAlbumPhoto').click(removeAlbumPhoto);
			});
		}else{
			$("ul.thumb").append(li);
			$(li).fadeIn('slow', function(){
				$(li).find('a.removeAlbumPhoto').click(removeAlbumPhoto);
			});			
		}
	}
	img.src = thumb;
}

function removeAlbumPhoto(e){
	e.preventDefault();
	if(!confirm('Удалить фотографию?')){
		return;
	}
		
	var img_id = parseInt(this.className.replace('removeAlbumPhoto photo', '')),
		last_id = parseInt($('#user-album-photos>li:last').attr('id').replace('image_li',''));
		
	if(last_id == img_id){
		last_id = $('#image_li'+img_id).prev();
		if(last_id.length>0){
			last_id = last_id.attr('id').replace('image_li','');
		}else{
			last_id = 0;
		}
	}	
	$.ajax({
		url: '/features/user-albums/delete.php',
		data: 'id='+ img_id + '&last=' + last_id,
		dataType: 'json',
		success: function(data) {
			if(!data.error){
				$('#image_li'+img_id).fadeOut('slow', function(){
					$(this).remove();
					if(data.imageid>0){
						ua_loadImage(data.imageid, data.userid, false);
					}
				});
			}	
		},
		error: function(){}
	});
}

$(function(){
	if(document.getElementById('album-upload')!=null){
		$('#album-upload').click(ajaxFileUpload);
		$('a.removeAlbumPhoto').click(removeAlbumPhoto);
	}
	
	$('#show_name_changes').click(function(){
		$('#prev_names').toggle();
	});
	
	$('#uwall-msg').click(function(){
		var $this = $(this),
			p = $this.parent();
		if(!p.hasClass('on')){
			p.addClass('on');
			$this.val('');
		}
	}).autoGrow();
	
	$('#uwall-send').click(function(){
		var t = $('#uwall-msg');
		if(t.is(':disabled')){
			return;
		}
		t.attr('disabled', true);
		
		$.fancybox.showActivity();
		
		$.ajax('/features/profile/wall-post.php',{
			type: 'POST',
			data: 'message='+encodeURIComponent(t.val())+'&wall='+$('#page_owner').val(),
			success: function(data){
				t.attr('disabled', false).val('');
				if(data=='success'){
					location.href = 'http://lolkot.ru/user/'+$('#page_owner').val()+'/wall/';
				}
			}
		});
	});
	$('#uwall-msg').attr('disabled', false).val('Напишите здесь что-нибудь...');
	
	$('.uwall a.delete').click(function(e){
		e.preventDefault();
		if(!confirm("Удалить сообщение навсегда?")){
			return;
		}
		var link = $(this);
			id = /m(\d+)/.exec(link.attr('class'));
		id = id[1];
		
		$.ajax('/features/profile/wall-post-delete.php',{
			type: 'POST',
			data: 'id='+id,
			success: function(data){
				if(data=='success'){
					link.parent().parent().css('backgroundColor','#F2D8DE').fadeOut(500,function(){
						$(this).remove();
					});
				}
			}
		});		
	});
	
	// ++ SEND GIFT
	$('#sendgift').fancybox({autoDimensions:false,width:568,height:400,title:'выберите подарок',onComplete:function(){$('#gift-selection a').fancybox({onComplete:function(){$('#cancelgift').click(function(e){e.preventDefault();$('#sendgift').click();});$('#buygift').fancybox();}})}});
	// -- SEND GIFT
	
	$('#usermenu li').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});
		
	$('#lolCatSelector span').mouseenter(function(){
		$(this).addClass('hover');
		var div = $('#lolLinks'),
			p = $(this).position(),
			w = Math.max(div.outerWidth(),$(this).outerWidth());
		if(div.parent().parent().attr('id')!='lolCatSelector'){
			div.appendTo('#lolCatSelector span');
		}
		div.css({'left':(p.left)+'px','top':(p.top+18)+'px','display':'block','width':w+'px'});
		
	}).mouseleave(function(){
		$('#lolLinks').hide();
		$('#lolCatSelector span').removeClass('hover');
	});
});
