var column_left_height = 0;
var column_right_height = 0;
var current_page = 0;
var count_pages = 0;

jQuery(document).ready(
		function()
		{
			column_left_height = parseInt(jQuery('.book-container .column-left').height());
			column_right_height = parseInt(jQuery('.book-container .column-right').height());
						
			//--- назначем принадлежность к странице
			resetPageLink();
		
			//--- показываем первую страницу
			initNavigation();
			
			//--- показываем первую страницу
			jQuery('.book-container .page-container.page-0').click();
			
			initEdit();
		}
);

function resetPageLink()
{
	//--- назначем принадлежность к странице и колонке
	var page = 0;
	var column = 0;
	var columns = Array(column_left_height, column_right_height);
	var current_heights = Array(0, 0);
	jQuery('.book-container .block').each(
			function(i)
			{
				var block = jQuery(this);
				var height = block.parent().height() + 20;
				
				//--- если в текущей колонеке пусто а высота блока больше самой колонки
				if (current_heights[column] == 0 && height > columns[column])
				{
					//--- добавляем скрол и фиксируем высоту
					height = columns[column] - 20;
					block.css({
						height : height + 'px',
						'overflow-y' : 'scroll'
					});
				}

				//--- если колонка заполнена
				if (current_heights[column] + height > columns[column])
					column++;
				
				//--- если заполнена последняя колонка
				if (column > 1)
				{
					page++;
					column = 0;
					current_heights = Array(0, 0);
				}
				
				//--- если в текущей колонеке пусто а высота блока больше самой колонки
				if (current_heights[column] == 0 && height > columns[column])
				{
					//--- добавляем скрол и фиксируем высоту
					height = columns[column] - 20;
					block.css({
						height : height + 'px',
						'overflow-y' : 'scroll'
					});
				}
				
				//--- метки
				block.addClass('page-'+page)
						 .addClass('column-'+column)
						 .data({
							 page : page,
							 column : column
						 });
				
				//--- сразу помещаем в нужную колонку
				block.insertBefore(jQuery('.book-container .column-'+ (column == 0 ? 'left' : 'right') +' .clear.end'));
				block.hide();
				
				current_heights[column] += height;
				count_pages = page + 1;
				//jQuery('.date', jQuery(this)).text(height);
			}
	);
}

function showPage(index)
{
	jQuery('.book-container .block').hide();
	jQuery('.book-container .block');
	jQuery('.book-container .block.page-' + index).show();
	
	jQuery('.page-container.index').removeClass('active');
	jQuery('.page-container.index.page-'+current_page).addClass('active');
	
	//--- подсвечиваем текущий li класом active
	jQuery('.book-container .bottom li').removeClass('active');
	jQuery('.page-container.active').parent().addClass('active');
}

function initNavigation()
{
	//--- добавление "назад"
	var li = jQuery('<li class="prev"><span class="page-container prev"><span class="bg-left"><span class="bg-right"><span class="bg-center"></span></span></span></span></li>');
	jQuery('.bg-center', li).text('назад');
	li.appendTo(jQuery('.book-container .column-left-bottom ul'));
	
	//--- добавление страниц в левую часть 
	for (i = 0; i < Math.round(count_pages / 2); i++)
	{
		var li = jQuery('<li class="index"><span class="page-container index"><span class="bg-left"><span class="bg-right"><span class="bg-center"></span></span></span></span></li>');
		
		jQuery('.bg-center', li).text(i + 1);
		jQuery('.page-container', li).addClass('page-'+i)
		
		li.appendTo(jQuery('.book-container .column-left-bottom ul'));
	}
	
	//--- добавление страниц в правую часть 
	for (i = Math.round(count_pages / 2); i < count_pages; i++)
	{
		var li = jQuery('<li class="index"><span class="page-container index"><span class="bg-left"><span class="bg-right"><span class="bg-center"></span></span></span></span></li>');
		
		jQuery('.bg-center', li).text(i + 1);
		jQuery('.page-container', li).addClass('page-'+i)
		
		li.appendTo(jQuery('.book-container .column-right-bottom ul'));
	}
	
	//--- добавление "вперед"
	var li = jQuery('<li class="next"><span class="page-container next"><span class="bg-left"><span class="bg-right"><span class="bg-center"></span></span></span></span></li>');
	jQuery('.bg-center', li).text('вперед');
	li.appendTo(jQuery('.book-container .column-right-bottom ul'));
	
	//--- переключение
	jQuery('.page-container').click(
			function()
			{
				if (jQuery(this).is('.index'))				
					current_page = parseInt(jQuery('.bg-center', jQuery(this)).text()) - 1;
				
				if (jQuery(this).is('.prev'))				
					current_page -= 1;
				
				if (jQuery(this).is('.next'))				
					current_page += 1;
				
				if (current_page >= count_pages - 1)
					jQuery('.page-container.next').hide();
				else jQuery('.page-container.next').show();
				
				if (current_page <= 0)
					jQuery('.page-container.prev').hide();
				else jQuery('.page-container.prev').show();
				
				showPage(current_page);
			}
	);
}

function initEdit()
{
	jQuery('.edit-link').click(
			function()
			{
				var block = jQuery(this).parents('.block:first');
				
				if (jQuery('.inp_textarea', block).length > 0)
					return false;
				
				var textarea = jQuery('<textarea class="inp inp_textarea" name="text['+parseInt(jQuery('.id', block).val())+']"></textarea>');
				textarea.val(jQuery('.text', block).text());
				
				jQuery('.text', block).html(textarea);
				
				jQuery(this).text('сохранить').click(
						function()
						{
							jQuery(this).parents('form:first').submit();
							return false;				
						}
				);
				
				return false;				
			}
	);
}
