var uploadFileSelected = false;

$(document).ready(function(){
	$('div.closeButton').click(function() {
		$('div#upload-photo').hide();
	});
	
	//	Если пользователь авторизован
	$('span#upload-photo-item').click(function() {
		var offset = $(this).offset();
		showUploadPhoto( offset );
	});
	
	//	Если не авторизован
	$('span#upload-auth').click(function() {
		var offset = $(this).offset();
		showAuthBlock( offset );
	});
	
	$('div#download-forms input').change(function() {
		uploadFileSelected = true;
		$('div#download-forms input:image').attr('src', '/images/download-button.gif');
		$('div#download-forms input:image').removeClass('disabled');
	});
	$('div#download-forms form').submit(function() {
		return (uploadFileSelected);
	});

	$('div.photo-item img').click(function() {
		var offset = $(this).offset();
		var width = $(this).width();
		var height = $(this).height();
		var id = $(this).attr('id').replace("photo_new", "").replace("photo", "");
		
		if ($(this).hasClass('voted')) 
		{
			$('#photo-selected').addClass('voted');
		} else {
			$('#photo-selected').removeClass('voted');
		
			$.ajax({ 
				type: "GET",
				url: "/ajax/check_voted.php",
				data: {id: id},
				success: function(msg) {
					if (msg == 'true') { 
						$('#photo-selected').addClass("voted"); 
						$('#photo' + id).addClass('voted');
						$('#photo_new' + id).addClass('voted');
					}
				}
			});
		}
		$('#photo-selected').attr('s_id', id);
		$('#photo-selected-name').text($(this).attr('name') || "");
		$('#photo-title').text($(this).attr('title'));
		$('#photo-selected').attr('rating', parseInt($(this).attr('rating')));
		$('.rating-photo').attr("title", $(this).attr('rating'));
		$('#photo-selected textarea').text(code_template.replace("_ID_", id));
		$('#photo-selected-raiting-peoples').text($(this).attr('peoples'));
		$('#photo-selected-raiting').text($(this).attr('rating'));
		togglePhoto(offset, $(this).width(), $(this).height(), $(this).attr('furl'), $(this).attr('rating'), $(this).attr('fheight'));
		return false;
	});

	$('div.photo-item a').click(function() {
		var image = $(this).parent().prev();
		image.click();
		return false;
	});

	$('span#close-item, div#blackout').click(function() {
		hidePhoto();
	});

	$('li#list01').click(function() 
	{
		$(this).addClass('selected');
		$('li#list02').removeClass('selected');
		//$('div.rating-marks').show();
		$(this).parent().parent().parent().find('div.rating-marks').hide();
		$('div[type=1]').show();
		$('div[type=2]').hide();
	});

	$('li#list02').click(function() {
		$(this).addClass('selected');
		$(this).parent().parent().parent().find('div.rating-marks').show();
		$('div[type=1]').hide();
		$('div[type=2]').show();
		$('li#list01').removeClass('selected');
	});
	
	$('#photo-selected-comment span.open_code').click(function() {
		openCode();
	});
	$('#photo-selected-comment span.close_code').click(function() {
		closeCode();
	});
	
	if($.browser.safari){
		$('div#photo-selected .person-bubble').css('margin-top', '-17px');
	}
	
	$('#uploadForm').submit(function() {
		if($('#btnUpload').attr('src') == '/images/download-button.gif')
			uploadPhoto($('#btnUpload').attr('s_id'), $('#tbPhotoName').val());
		return false;
	});
	
	$('.rating-photo:not(.closed) li').hover(function() {
		if (!$('#photo-selected').hasClass("voted")) 
		{ 
			drawStars($(this).parent(), getRating(this));
		}
		
	}, function() {
		if (!$('#photo-selected').hasClass("voted"))
		{
			drawStars($(this).parent(), $('#photo-selected').attr('rating'));
		}
	});
	$('.rating-photo:not(.closed) li').click(function() {
		if (!$('#photo-selected').hasClass("voted")) 
		{ 
			var rating = getRating(this);
			drawStars($(this).parent(), rating);
			
			var id = $('#photo-selected').attr('s_id');
			submitRating(id, rating);
			$('#photo-selected').addClass('voted');
			$('#photo' + id).addClass('voted');
			$('#photo_new' + id).addClass('voted');
			
			var peoples = 1 + parseInt($('#photo-selected-raiting-peoples').text());
			var new_rating = Math.round((parseInt($('#photo-selected-raiting-peoples').text()) * parseInt($('#photo-selected-raiting').text()) + rating) / peoples * 100) / 100;
			
			$('#photo' + id).attr("peoples", peoples);
			$('#photo_new' + id).attr("peoples", peoples);
			$('#photo-selected-raiting-peoples').text(peoples);
			
			$('#photo' + id).attr("rating", new_rating);
			$('#photo_new' + id).attr("rating", new_rating);
			$('#photo-selected-raiting').text(new_rating);
			
//			if (peoples == 1) {
//				$('#photo' + id).attr("rating", rating);
//				$('#photo_new' + id).attr("rating", rating);
//			}
		}
	});
	
	var sDefaultPhotoName = $('#tbPhotoName').val();
	$('#tbPhotoName').focus(function() {
		if($(this).val() == sDefaultPhotoName)
		{
			$(this).val('');
			$(this).css('color', 'black');
		}
	});

	$('li#list01').click();
	
	openActivePhoto();
});

// Открываем указанную фотку
function openActivePhoto(){
	$('#active_photo').each(function(index) {
		var image = $(this).find('img');
		image.click();
	});
}

//	Закрашываем нужное число звездочек
function drawStars(ul, rating){

	var i = 0;
	$(ul).find('li').each(function(index) {
		if(i < rating)
			$(this).addClass('selected');
		else
			$(this).removeClass('selected');
		i++;
	});
	
}

//	Определяем, над какой звездочкой находится курсор
function getRating( li ){
	var prevLi = $(li);
	var iStars = 1;
	while(prevLi = $(prevLi).prev()){
		if(prevLi.length == 0)
			break;
		iStars++;
		if(iStars >= 5)
			break;
	}
	return iStars;
}

//	Отправка рейтинга на сервер
function submitRating(id, iRating)
{
	jQuery.get('/ajax/do_photo_rate.php', {id: id, rating: iRating});
}

function openCode(){
	$('#photo-selected-comment .person-bubble').show();
} 

function closeCode()
{
	$('#photo-selected-comment .person-bubble').hide();
}

function lockRating()
{
	
}

function togglePhoto(offset, width, height, furl, rating, fheight)
{
	if ($('#photo-selected:visible').length > 0)
	{
		hidePhoto();
	}
	else{
		showPhoto(offset, width, height, furl, rating, fheight);
	}
}

function showPhoto(offset, width, height, furl, rating, fheight)
{
	var photoWidth = 416;
	var photoHeight = 368;
	var left = (offset.left - 58 - (290 - width) / 2);
	var top = 0;

	// Слишком слева
	if(left < 30) left = 30;
	
	//	Слишком справа
	var bodyWidth = $(document).width();
	var overflow_x = photoWidth + left - (bodyWidth - 40);
	if(overflow_x > 0){
		left -= overflow_x;
	}

	//	Вычисляем высоту
	if(height > 200){
		top = offset.top - 80;
	}else{
		top = offset.top - 170;
	}

	//	слишком высоко
	if(top < 30)
		top = 30;

	//	слишком низко
	var overflow_y = top + photoHeight + 150 - parseInt($(document).height());
	if(overflow_y > 0){
		top -= overflow_y;
	}
	
	//	поехали
	$('#photo-selected').css('left', left);
	$('#photo-selected').css('top', top);
	removeStars();
	for(var i = 1; i <= rating; ++i) 
	{
		$('#photo-selected li['+i+']').addClass('selected');
	}
	for(var i = rating+1; i <= 5; ++i)
	{
		$('#photo-selected li['+i+']').removeClass('selected');
	}
	drawStars('.rating-photo', rating);
	
	$('#photo-selected #cphoto').attr("src", furl);
	$('#photo-selected div.outer-img').css({height:"" + fheight + "px"});
	$('#photo-selected').show();
	$('#blackout').show();
	refixForIE();
}
function removeStars()
{
	$('#rating-photo li').removeClass('selected');
}
function hidePhoto()
{
	$('div#photo-selected').hide();
	$('div#blackout').hide();
	closeCode();
	removeStars();
	refixForIE();
	$('#photo-selected').attr('s_id', '');
	$('#photo-selected').removeClass('voted');
}
 
function refixForIE()
{
	if ($.browser.msie) {
		if($.browser.version < 7){
			$('body').css('position','relative');
			$('body').css('position','absolute');
		}
		// $('div#upload-photo').show();
		// $('div#upload-photo').hide();
	}
}

//	Код ниже отвечате за анимацию при клике по "сначала авторизуйся"
//	Анимация отличается от стандартной, поэтому делаем так
function showAuthBlock(offset)
{
	var uploadPhotoWidth = $('#login').width();
	var uploadPhotoHeight = $('#login').height();
	
	var x_start = offset.left + 81;
	var y_start = offset.top + 30;
	
	var body_width = $(document).width();
	var overflow_x = offset.left + uploadPhotoWidth - 120 - body_width;
	
	var y_end = offset.top - 90;
	var x_end = offset.left - 120;
	if($.browser.msie){x_end -= 20;}
	
	if(overflow_x > 0)
		x_end -= overflow_x;
	
	$('#login').css('top', y_end);
	$('#login').css('left', x_end);

	// var x_end = x_start - (width_end / 2);
	// var y_end = y_start - (height_end / 2);

	var width_end = uploadPhotoWidth - 60;
	var height_end = uploadPhotoHeight - 50;

	show_from_center('#tmp_for_show', $('#login'), x_start, x_end + 29, y_start, y_end + 24, width_end, height_end);
	
	window.login_function = function() {
		$("#upload-auth").toggle();
		$("#upload-photo-item").toggle();
		$("#header-link span").wrap("<a href='/cabinet/photos'></a>");
		setTimeout("$('#upload-photo-item').click()", 200);
	}
}

//	Код ниже отвечает за анимацию при клике по "загрузить фото"
function showUploadPhoto(offset)
{
	var uploadPhotoWidth = 407;
	var uploadPhotoHeight = 314;
	
	var x_start = offset.left + 81;
	var y_start = offset.top + 30;
	
	var body_width = $(document).width();
	var overflow_x = offset.left + uploadPhotoWidth - 120 - body_width;
	
	var y_end = offset.top - 90;
	var x_end = offset.left - 120;
	if(overflow_x > 0)
		x_end -= overflow_x;
	
	$('#upload-photo').css('top', y_end);
	$('#upload-photo').css('left', x_end);

	// var x_end = x_start - (width_end / 2);
	// var y_end = y_start - (height_end / 2);

	var width_end = uploadPhotoWidth - 60;
	var height_end = uploadPhotoHeight - 50;
	
	show_from_center('#tmp_for_show', $('#upload-photo'), x_start, x_end + 29, y_start, y_end + 24, width_end, height_end);
}
//	Загружаем аяксом фотку на сервер.
//	Выводим подтверждение загрузки
function uploadPhoto(id, name)
{
	$.ajaxFileUpload
	(
		{
			url:'/ajax/doajaxfileupload.php?id=' + encodeURIComponent(id) + '&name=' + encodeURIComponent(name),
			data: {
				id: id,
				name: name
			},
			secureuri:false,
			fileElementId: 'fileToUpload',
			dataType: 'text',
			success: function (data)
			{
				$('#uploadForm').hide();
				$('#uploadResult').show();
				$('#uploadResult').text(data);
			},
			error: function (data)
			{
				$('#uploadForm').hide();
				$('#uploadResult').show();
				$('#uploadResult').text(data);
			}
		}
	)
}