$(document).ready(function() {
	pos();

	$('#deleteAvatar').change(function() {
		$('div#uploadAvatar').toggle(0);
	});

	$('#translation-expand').click(function() {
		$(this).parent().hide();
		$('#editortextEn').parent().show();
	});
	
	/*$('#translation-collapse').click(function() {
		$(this).parent().hide();
		$('#translation-expand').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);
			}
		});
	});

    $('.comment .ql').live('click', function() {
        $.dialog.ritoric('А вот и ссылка на коментарий<br /><input type="text" class="selt" value="' + $(this).attr('href') + '" />');
        return false;
    });
    
    /*$('.selt').live('click', function() {
        $(this).focus().select();
    });*/

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

	$('.sch a').click(function() {
		window.location = base + 'blog/search/' + $('.sch input').val();
	});
	
	$('.sch input').keypress(function(e) {
		if (e.keyCode == 13) {
			$('.sch a').click();
		}
	});
	
	$('.submenu .new').hover(function() {
		//$('.hsch').css('display', 'inline');
	});

	$('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',
			onSubmit: function(file, response) {
				this.setData({watermark: $('#watermark').attr('checked')});
				$('#ajax-upload').addClass('loading').html('<span>' + $('#ajax-upload').html() + '</span>');
			},
			onComplete: function(file, response) {
				$('#ajax-upload').removeClass('loading').html($('#ajax-upload span').html());
				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();
	});
	
	$('.smallp img').click(function() {
		$('.picture table img:first').attr('src', $(this).attr('rel'));
	});
	
	$('.bigpri a').click(function() {
		var id = $(this).attr('rel');
		$.dialog.tellme(['Как вас называть', 'Ваш email', 'Адрес', 'Телефон'], ['', '', '', ''], function(data) {
			if (!data) {
				return false;
			}
			$.post(base + 'shop/buy', {id: id, name: data[0], email: data[1], address: data[2], phone: data[3]}, function(data) {
				if (data) {
					$.dialog.ritoric('Все круто! С вами обязательно свяжутся.');
				}
			});
		});
		/*$.dialog.orly('Вам это точно надо?', function(callback) {
			if (!callback) {
				return false;
			}
			$.post(base + 'shop/buy', {id: id}, function(data) {
				if (!data) {
					$.dialog.ritoric('К сожалению без <a href="' + base + 'register/">регистрации</a> ничего не получится.');
				} else {
					$.dialog.ritoric('Все круто! С вами обязательно свяжутся.');
				}
			});
		});*/
		return false;
	});
	
	var slides = new Array(
		{src: base + 'themes/dropped/images/head-300-19.png'},
		{src: base + 'themes/dropped/images/head-300-21.jpg'},
		{src: base + 'themes/dropped/images/head-300-22.jpg'},
		{src: base + 'themes/dropped/images/head-300-23.jpg'},
		{src: base + 'themes/dropped/images/head-300-24.jpg'},
		{src: base + 'themes/dropped/images/head-300-25.jpg'}
	);
	slides.sort(function() {return 0.5 - Math.random();});
	/*
	$('#logo-slide .wrapper').html('<ul></ul>');
	$(slides).each(function(){
		$('#logo-slide .wrapper ul').html($('#logo-slide .wrapper ul').html() + '<li><img src="'+this.src+'" alt="" /></li>');
	});
	$('#logo-slide').anythingSlider({
		easing: 'easeInQuad',
        delay: 10000,
		animationTime: 2000,
        hashTags: false,
        buildNavigation: false,
        pauseOnHover: false
	});
	*/

	$('#logo-slide').crossSlide({
  		sleep: 10,
  		fade: 1
	}, slides);
	
    /*$('#hide-sidebar').click(function() {
        $('.sidebar').toggle('slide', {side: 'right'}, 300);
        return false;
    });*/
	
	$('.flash').click(function() {
		$(this).hide();
	});
	
	$('.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;
	});
});

function pos() {
	var ch = $('.content:first').height();
	var sh = $('.sidebar').height();
	if (sh > ch) {
		$('.content:first').css({height: sh + 50});
	}
}

