$(document).ready(function() {
	$('#deleteAvatar').change(function() {
		$('div#uploadAvatar').toggle('fast');
	});

	$('#translationExpand').click(function() {
		$(this).hide();
		$('#editortextEn').parent().show();
	});

	$('a.orly').click(function() {
		var a = $(this);
		var link = $(a).attr('href');
		$(a).removeAttr('href');
		var text = $(a).attr('rel');
		$.dialog.orly(text, function(data) {
			if (data) {
				window.location = link;
			} else {
				$(a).attr('href', link);
			}
		});
	});

	$('.lolwhat').qtip({
		position: {
			my: 'bottom center',
			at: 'top center'
		},
		style: {
			tip: true,
			classes: 'ui-tooltip-dppd'
		}
	});

	$('img#yt0').click(function() {
		var rnd = Math.floor(10000001 * Math.random());
		var src = $(this).attr('src').replace(/#[0-9]+$/, '');
		$(this).attr('src', src + '#' + rnd);
	});

	$('a.submit').click(function() {
		$(this).removeClass('submit').addClass('loading').html('<span>' + $(this).html() + '</span>');
		$('form[name=' + $(this).attr('rel') + ']').submit();
	});

	$('form').keypress(function(e) {
		if (e.keyCode == 13 && !$(e.target).is('textarea') && !$(e.target).is('#Entry_savedTags')) {
			var submitButton = $('form[name=' + $(this).attr('name') + '] a.submit');
			$(submitButton).removeClass('submit').addClass('loading').html('<span>' + $(submitButton).html() + '</span>');
			$(this).submit();
		}
	});
	
    if ($('input#Entry_savedTags').length) {
		$('input#Entry_savedTags').tag_add({
			maxitem: 0,
			minlength: 2,
			maxlength: 10,
			loadinfo: base + 'blog/getTags'
		});
	}

	$('#comment_form form').submit(function() {
		var text = $('textarea[name*=text]').val();
		var entryID =  $('input[name*=entryID]').val();
		var parentID =  $('input[name*=parentID]').val();
		if (!text) {
			$('div#comment_form a.button').removeClass('loading').addClass('submit');
			$('#editor-error').show();
			$('#editor').addClass('error');
			return false;
		}
		$.dialog.loading();
		$.post(base + 'comment/add', {text: text, entryID: entryID, parentID:parentID}, function(data) {
			$('#i-wanna-comment').show();
			if (!data) {
				$('div#comment_form a.button').removeClass('loading').addClass('submit');
				$.dialog.loading(true);
				return false;
			}
			$('#editor-error').hide();
			$('#editor').removeClass('error');
			$('div#comment_form').appendTo('div.comments');
			$('textarea#editor').val('');
			$('div#comment_form').hide();
			$('div.comment a.reply-to').show();
			$('div.comments a.big').show();
			$('div#comments').html(data);
			$('div#comment_form a.button').removeClass('loading').addClass('submit');
			$.dialog.loading(true);
		});
		return false;
	});

	$('.entry .text img, .comment .text img').each(function() {
		if ($(this).attr('src').indexOf('/m_') == -1) {
			$(this).wrap('<a href="' + $(this).attr('src') + '" rel="expand"></a>');
		}
	});
	
	var fancyOptions = {
		'speedIn': 200,
		'speedOut': 200,
		'overlayShow': true,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'padding': 0,
		'hideOnContentClick': true
	}
	
	$('*[rel*=expand]').fancybox(fancyOptions);
	
	if ($('#ajax_upload').length) {
		new AjaxUpload('ajax_upload', {
			action: base + 'blog/uploadImage',
			name: 'image',
			onComplete: function(file, response) {
				if (response == 'errorSmallSize') {
					$.dialog.ritoric('Картинка слишком мала.');
					return;
				}
				if (response == 'errorBigFile') {
					$.dialog.ritoric('Размер картинки слишком велик.');
					return;
				}
				if (response == 'errorExtension') {
					$.dialog.ritoric('Не пытайтесь загрузить хуйню.');
					return;
				}
				$(response).appendTo('#uploads');
				$('.expand-uploaded-image').fancybox(fancyOptions);
			}
		});
	}
	
	if ($('#pictures').length) {
		$('#pictures').MultiFile({
			accept: 'gif|jpg|png|jpeg',
			STRING: {
				remove: 'Удолить!'
			}
		});
	}

	$('.gallery-picture').hover(function() {
		$(this).find('img').fadeTo(0, 0.9);
		$(this).find('.gallery-picture-info').show();
	}, function() {
		$(this).find('img').fadeTo(0, 1);
		$(this).find('.gallery-picture-info').hide();
	});
	
	var slides = new Array(
		{src: base + 'themes/dropped/images/head-300-1.jpg'},
		{src: base + 'themes/dropped/images/head-300-2.jpg'},
		{src: base + 'themes/dropped/images/head-300-3.jpg'},
		{src: base + 'themes/dropped/images/head-300-4.jpg'},
		{src: base + 'themes/dropped/images/head-300-5.jpg'},
		{src: base + 'themes/dropped/images/head-300-6.jpg'},
		{src: base + 'themes/dropped/images/head-300-7.jpg'},
		{src: base + 'themes/dropped/images/head-300-8.jpg'},
		{src: base + 'themes/dropped/images/head-300-9.jpg'}
	);
	
	$('#logo-slide').crossSlide({
  		sleep: 10,
  		fade: 1
	}, slides.sort(function() {return 0.5 - Math.random()}));

    /*$('#hide-sidebar').click(function() {
        $('.sidebar').toggle('slide', {side: 'right'}, 300);
        return false;
    });*/
	
	$('.flash').click(function() {
		$(this).slideUp(200);
	});
	
	$('.reply-to').live('click', function() {
		var commentId = $(this).attr('rel');
		$('.reply-to').show();
		$('#i-wanna-comment').show();
		var appendTo = 'div#comment' + commentId;
		if (commentId == 0) {
			$('#i-wanna-comment').hide();
			appendTo = 'div.comments';
		}
		$('div#comment_form').appendTo(appendTo).show();
		//window.location = '#comment-form';
		$('div#comment' + commentId + ' .reply-to').hide();
		$('input#Comment_parentID').attr('value', commentId);
		return false;
	});
	
	$('.delete-comment').live('click', function() {
		var commentId = $(this).attr('rel');
		$.dialog.orly('Вы уверены, что хотите удалить этот комментарий? Все ответы на него тоже пойдут пиздой.', function(data) {
			if (!data) {
				return false;
			}
			$.dialog.loading();
			$.post(base + 'comment/delete', {commentID: commentId}, function(data) {
				$('div#comment_form').appendTo('div.comments');
				$('textarea#Comment_text').val('');
				$('div#comment_form').hide();
				$('div.comment a.dashed').show();
				$('div.comments a.big').show();
				$('div#comments').html(data);
				$.dialog.loading(true);
			});
		});
		return false;
	});
	
	$('.rate').click(function() {
		var entryId = $(this).parents('.entry').attr('id').match(/entry_(\d+)/)[1];
		var rating = $(this).attr('rel');
		$.post(base + 'blog/rate', {entryID: entryId, rating: rating}, function(data) {
			if (!data) {
				return false;
			}
			$('div#entry_' + entryId + ' span.rating').replaceWith(data);
			$('div#entry_' + entryId + ' a.rate').remove();
		});
		return false;
	});
	
	$('.fav-add').click(function() {
		var entryId = $(this).parents('.entry').attr('id').match(/entry_(\d+)/)[1];
		$.post(base + 'blog/favouriteAdd', {entryId: entryId}, function(data) {
			if (!data) {
				return false;
			}
			$('div#entry_' + entryId + ' .fav-add').hide();
			$('div#entry_' + entryId + ' .fav-del').show();	
		});
		return false;
	});
	
	$('.fav-del').click(function() {
		var entryId = $(this).parents('.entry').attr('id').match(/entry_(\d+)/)[1];
		$.post(base + 'blog/favouriteRemove', {entryId: entryId}, function(data) {
			if (!data) {
				return false;
			}
			$('div#entry_' + entryId + ' .fav-del').hide();
			$('div#entry_' + entryId + ' .fav-add').show();	
		});
		return false;
	});
	
	$('#community_join').click(function() {
		$.dialog.loading();
		$.post(base + 'community/join', {communityID: $(this).attr('rel')}, function(data) {
			if (data) {
				$('a#community_join').addClass('hidden');
				$('a#community_leave').removeClass('hidden');
				$('#button_create').removeClass('hidden');
				$.dialog.loading(true);
			}
		}, 'json');
		return false;
	});
	
	$('#community_leave').click(function() {
		var communityId = $(this).attr('rel');
		$.dialog.orly('Вы уверены, что хотите покинуть это сообщество?', function(data) {
			if (!data) {
				return false;
			}
			$.dialog.loading();
			$.post(base + 'community/leave', {communityID: communityId}, function(data) {
				if (data) {
					$('a#community_join').removeClass('hidden');
					$('a#community_leave').addClass('hidden');
					$('#button_create').addClass('hidden');
				}
				$.dialog.loading(true);
			});
		});
		return false;
	});
	
	$('.friend-add').click(function() {
		var userId = $(this).attr('rel');
		$.dialog.orly('Вы уверены, что хотите добавить этого пользователя в друзья?', function(data) {
			if (!data) {
				return false;
			}
			$.dialog.loading();
			$.post(base + 'user/friendAdd', {userID: userId}, function(data) {
				if (data) {
					$('.friend-add').remove();
					$.dialog.loading(true);
					$.dialog.ritoric('Ждем пока пользователь подтвердит это...');
				}
			});
			$.dialog.loading(true);
		});
		return false;
	});
	
	$('.friend-confirm').click(function() {
		var userId = $(this).attr('rel');
		$.dialog.loading();
		$.post(base + 'user/friendConfirm', {userID: userId}, function(data) {
			if (data) {
				$('#friend_' + userId).removeClass('new');
				$('#friend_' + userId + ' .titsorgtfo').remove();
			}
		});
		$.dialog.loading(true);
		return false;
	});
	
	$('.friend-reject').click(function() {
		var userId = $(this).attr('rel');
		$.dialog.loading();
		$.post(base + 'user/friendReject',{userID: userId}, function(data) {
			if (data) {
				$('#friend_' + userId).remove();
			}
		});
		$.dialog.loading(true);
		return false;
	});
	
	$('.friend-delete').click(function() {
		var userId = $(this).attr('rel');
		$.dialog.orly('Вы уверены, что хотите удалить этого пользователя из списка друзей?', function(data) {
			if (!data) {
				return false;
			}
			$.dialog.loading();
			$.post(base + 'user/friendDelete', {userID: userId}, function(data) {
				if (data) {
					$('#friend_' + userId).remove();
				}
			});
			$.dialog.loading(true);
		});
		return false;
	});
	
	$('.delete-uploaded-image').live('click', function() {
		var that = this;
		var file = $(that).parent().find('a:first').text();
		$.post(base + 'blog/uploadImageDelete', {file: file}, function(data) {
			if (!data) {
				return false;
			}
			$(that).parent().remove();
			$.dialog.ritoric('Не забудьте удалить ссылки из текста.');
		});
		return false;
	});
	
	$('.insert-uploaded-image').live('click', function() {
		var file = $(this).attr('rel');
		if (file.indexOf('/b_') > 0) {
			$('#editor').insertTags('<img src="' + file + '" alt="" />', '').focus();
		} else if (file.indexOf('/m_') > 0) {
			var bigFile = file.replace('/m_', '/b_');
			$('#editor').insertTags('<a href="' + bigFile + '" rel="expand"><img src="' + file + '" alt="" /></a>', '').focus();
		}
		return false;
	});
});