var slideshow_interval = null;

var fb_color_default = '#cccccc';

var album_slideshow_interval = 4800;
var album_slideshow_max_counter = 4;
var index_slideshow_interval = 5000;
var index_slideshow_animation_time = 1200;

var photos_preload_count = 2; // количество предзагружаемых фотографий в каждом направлении 

var change_hash = true;

//var YaShareInstance;

$(document).ready(function(){
	
	$.positionAll();
	
	/*if ($("#ya_share1").length){
		ya_share();
	}*/
	
	if ($("#bg_multi").length){
		setInterval( "index_bg_slideshow()", index_slideshow_interval);	
	}
	
	
/*	$('div.bg_image img').load(function(){
		$(this).parent().addClass('complete');
		

		var main_images = $('div.bg_image');
		if (main_images.length == main_images.filter('.complete').length) {
			$('div.bg_image').each(function(index){
				$(this).animate({'left': '0'},2000-index*200);
			});
			//$('div.bg_image').animate({'left': '0'},2000);
		} 
		
	});*/
	var tmpstr='loaded: ';
	var tmpstr2='cached: ';
	$('div.bg_image img').each(function(index){
		var ttt = $(this).attr('src');
		$(this).attr('src','');
		$(this).attr('src',ttt);
		if (!this.complete /*|| this.readyState != "loaded"*/)  
		{
			$(this).load(function(){
				/*alert (index);*/
				tmpstr+=index + ', ';
				$(this).parent().addClass('complete');
				var main_images = $('div.bg_image');
				if (main_images.length == main_images.filter('.complete').length) {
					/*$('div.bg_image').each(function(index){
						$(this).animate({'left': '0'},2000-index*200);
					});*/
					main_images.css({'display':'none', 'left': '0'});
					main_images.fadeIn();
					
					//alert (tmpstr + "\n" + tmpstr2);
				} 
			});
        }
		else 
		{
			/*alert (index);*/
			tmpstr2+= index + ', ';
			$(this).parent().addClass('complete');
			var main_images = $('div.bg_image');
			if (main_images.length == main_images.filter('.complete').length) {
				/*$('div.bg_image').each(function(index){
					$(this).animate({'left': '0'},2000-index*200);
				});*/
				main_images.css({'display':'none', 'left': '0'});
				main_images.fadeIn();
				
				//alert (tmpstr + "\n" + tmpstr2);
			} 
        }
		
		if (index==11) {
			//alert (tmpstr + "\n" + tmpstr2);
		} 
		
		
		/*var flag = true;
		
		$('div.bg_image').each(function(index){
			if (!$(this).hasClass('complete'))
			{
				flag = false;
			}
			
			if (($('div.bg_image').size() - 1) == index && flag) // если все загрузились
			{
				$('div.bg_image').css('display', 'block');
			}
		});*/
		/*
		var main_images = $('div.bg_image');
		if (main_images.length == main_images.filter('.complete').length) {
			$('div.bg_image').each(function(index){
				$(this).animate({'left': '0'},2000-index*200);
			});
			//$('div.bg_image').animate({'left': '0'},2000);
		} 
		*/
	});
	
	$("#album_menu li.root").hover(
	  function () {
		$(this).children("div.root").addClass("current");
	  }, 
	  function () {
		$(this).children("div.root").removeClass("current");
	  }
	);


	
	/* Функция таймера информационных сообщений */
	setTimeout(function () {
		$(".alert_ok").fadeOut(function(){
			$(this).remove();
		});
	}, 5000);

	
	// заполнение форм по умолчанию
	if($('input[name="fb_name"]').val() == "") 
	{
		$('input[name="fb_name"]').val(fb_name_default).css("color", fb_color_default); ;
	}
	$('input[name="fb_name"]').focus(function()
	{
		if($(this).val() == fb_name_default) 
		{
			$(this).css("color", "").val("");
		}
	});
	$('input[name="fb_name"]').blur(function()
	{
		if ($(this).val() == "") 
		{
			$(this).css("color", fb_color_default).val(fb_name_default);
		}
	});
	
	if($('input[name="fb_contacts"]').val() == "") 
	{
		$('input[name="fb_contacts"]').val(fb_contacts_default).css("color", fb_color_default); ;
	}
	$('input[name="fb_contacts"]').focus(function()
	{
		if($(this).val() == fb_contacts_default) 
		{
			$(this).css("color", "").val("");
		}
	});
	$('input[name="fb_contacts"]').blur(function()
	{
		if ($(this).val() == "") 
		{
			$(this).css("color", fb_color_default).val(fb_contacts_default);
		}
	});
	
	$('input#feedback_submit_button').click(function(e){
		e.preventDefault();
		var is_error = false;
		if ($('input[name="fb_name"]').val() == '' || $('input[name="fb_name"]').val() == fb_name_default)
		{
			is_error = true;
			alert(no_name_error);
		}
		if ($('input[name="fb_contacts"]').val() == '' || $('input[name="fb_contacts"]').val() == fb_contacts_default)
		{
			is_error = true;
			alert(no_contacts_error);
		}
		
		if (!is_error)
		{
			$('#feedback_form').submit();
		}
	});
	
	if($('textarea[name="fb_message"]').val() == "") 
	{
		$('textarea[name="fb_message"]').val(fb_message_default).css("color", fb_color_default); ;
	}
	$('textarea[name="fb_message"]').focus(function()
	{
		if($(this).val() == fb_message_default) 
		{
			$(this).css("color", "").val("");
		}
	});
	$('textarea[name="fb_message"]').blur(function()
	{
		if ($(this).val() == "") 
		{
			$(this).css("color", fb_color_default).val(fb_message_default);
		}
	});
	
	function change_image(photo_id)
	{
		resize_photo(photo_id);
		$('#photo_container_hidden img[photo_id="'+photo_id+'"]')
			.clone()
			.attr('id', 'photo')
			.prependTo('#photo_content')
			.css('display', 'none')
			.fadeIn(1000)
			.next('img')
			.fadeOut(800, function() { 
				$(this).remove(); 
			});
		
		//$('#photo_content img#photo:last').fadeOut(500, function() { $(this).remove(); });
	}
	
	function show_photo(photo_id, photo_url)
	{
		// показываем просмотр фотографий
		$('#album_container').css('display', 'none');
		$('#photo_container').css('display', '');
		
		change_hash = false;
		window.location.hash = '#' + photo_id;
		
		// меняем yandex=share
		$('#ya_share1').replaceWith('<div style="float:right;" id="ya_share1" name="ya_share1"></div>');
		var YaShareInstance = new Ya.share({
			element: 'ya_share1',
			elementStyle: {
				'type': 'none',
				'border': false,
				'quickServices': ['vkontakte', 'facebook', 'twitter', 'odnoklassniki', 'lj']
			},
			link: window.location,
			onready: function(instance) {
                // После инициализации можно поменять ссылку или заголовок, которым требуется поделиться
				/*$("body").click(function(){
					instance.updateShareLink(
						window.location, document.title
					);	
				});*/
            }	
				
		});
		
		
		/*
		$(window).unbind('hashchange');
		
		window.location.hash = '#' + photo_id;
		
		$(window).bind('hashchange', function() {
			show_photo_hash();
		});
		*/
		

		if ($('#photo_container_hidden img[photo_id="'+photo_id+'"]').size() != 0) // если фотка уже была добавлена в список загруженных
		{
			if ($('#photo_container_hidden img[photo_id="'+photo_id+'"]').hasClass('complete')) // если уже загрузилась
			{
				change_image(photo_id);
			}
			else // если уже есть, но еще не загрузилась
			{
				show_loader();
				$('#photo_container_hidden img[photo_id="'+photo_id+'"]').load(function(){
					hide_loader();
					$(this).addClass('complete');
					var photo_id = $(this).attr('photo_id');
					change_image(photo_id);
				});
			}
		}
		else
		{
			show_loader();
			// если такой фотки нет в загруженных - загружаем
			$('<img src="'+photo_url+'" photo_id="'+photo_id+'" />').prependTo('#photo_container_hidden');
			
			// прикрепляем обработчик загрузки
			$('#photo_container_hidden img[photo_id="'+photo_id+'"]').load(function(){
				hide_loader();
				$(this).addClass('complete');
				var photo_id = $(this).attr('photo_id');
				change_image(photo_id);
			});
		}
		
		
		
		
		
		//$('#photo_container img#photo').attr('src', "").attr('src', photo_url);
		$('input#photo_current_id').val(photo_id);
		
		// определяем текущий номер фото
		$('div.photo_item').each(function(index) {
			if (photo_id == $(this).attr('photo_id'))
			{
				var photo_number = index + 1;
				var photos_count = $('input#photos_count').val();
				
				$('span.photo_name').html(photo_number + ' '+of_title+' ' + photos_count);
			}
		});
		//hide_loader();
		
		// загружаем в скрытый контейнер по две фотки в каждом направлении
		var photo_current_id = photo_id;
		
		// предыдущие
		var photo_temp_id = photo_current_id;
		for (i = 0; i < photos_preload_count; i++)
		{		
			photo_id = $('div.photo_item[photo_id="'+photo_temp_id+'"]').prev('div.photo_item').attr('photo_id');
			if (!photo_id)
			{
				photo_id = $('#album_container div.photo_item:last').attr('photo_id');
			}
			
			if ($('#photo_container_hidden img[photo_id="'+photo_id+'"]').size() == 0)
			{
				photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
				$('<img src="'+photo_url+'" photo_id="'+photo_id+'" />').prependTo('#photo_container_hidden');
			
				// прикрепляем обработчик загрузки
				$('#photo_container_hidden img[photo_id="'+photo_id+'"]').load(function(){
					$(this).addClass('complete');
				});
			}
			photo_temp_id = photo_id;
		}
		
		// сдежующие
		var photo_temp_id = photo_current_id;
		for (i = 0; i < photos_preload_count; i++)
		{		
			photo_id = $('div.photo_item[photo_id="'+photo_temp_id+'"]').next('div.photo_item').attr('photo_id');
			if (!photo_id)
			{
				photo_id = $('#album_container div.photo_item:first').attr('photo_id');
			}
			
			if ($('#photo_container_hidden img[photo_id="'+photo_id+'"]').size() == 0)
			{
				photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
				$('<img src="'+photo_url+'" photo_id="'+photo_id+'" />').prependTo('#photo_container_hidden');
			
				// прикрепляем обработчик загрузки
				$('#photo_container_hidden img[photo_id="'+photo_id+'"]').load(function(){
					$(this).addClass('complete');
				});
			}
			photo_temp_id = photo_id;
		}
		
		//YaShareInstance.updateShareLink(window.location, '');
		 
		//ya_share();
		
	}
	
	// нажатие на картинку превью
	$('div.photo_item').click(function(e){
		e.preventDefault();

		var photo_id = $(this).attr('photo_id');
		var photo_url = $(this).attr('photo_url');
		
		show_photo(photo_id, photo_url);
		
		$('ul#view_type_tab li').removeClass('current');
		$('ul#view_type_tab li#once').addClass('current');
	});
	

	// кнопки предыдущая и следующая
	$('.photo_arrow_left').click(function(e){
		e.preventDefault();
		
		var photo_current_id = $('input#photo_current_id').val();
		var photo_id = $('div.photo_item[photo_id="'+photo_current_id+'"]').prev('div.photo_item').attr('photo_id');
		if (!photo_id)
		{
			photo_id = $('#album_container div.photo_item:last').attr('photo_id');
		}
		var photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
		show_photo(photo_id, photo_url);
		
	});
	
	$('.photo_arrow_right').click(function(e){
		e.preventDefault();
		
		var photo_current_id = $('input#photo_current_id').val();
		var photo_id = $('div.photo_item[photo_id="'+photo_current_id+'"]').next('div.photo_item').attr('photo_id');
		if (!photo_id)
		{
			photo_id = $('#album_container div.photo_item:first').attr('photo_id');
		}
		var photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
		show_photo(photo_id, photo_url);
	});
	var next_photo_timer_interval;
	function start_slideshow_animation()
	{
		$("#slideshow_timer").html('<img src="'+BASEURL+'images/activity.gif" class="vmiddle" />');
	}
	function stop_slideshow_animation()
	{
		$("#slideshow_timer").html('');
	}

	function next_photo()
	{
		var photo_current_id = $('input#photo_current_id').val();
		var photo_id = $('div.photo_item[photo_id="'+photo_current_id+'"]').next('div.photo_item').attr('photo_id');
		if (!photo_id)
		{
			photo_id = $('div#album_container div.photo_item:first').attr('photo_id');
		}
		var photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
		
		show_photo(photo_id, photo_url);
	}
	
	$('div#photo_content img#photo').live('click', next_photo);
	
	// переключение по типу просмотра
	$('ul#view_type_tab li').click(function() {
		if (slideshow_interval != null)
		{
			clearInterval(slideshow_interval);
			stop_slideshow_animation();
		}

		$('ul#view_type_tab li').removeClass('current');
		$(this).addClass('current');
	});
	
	$('ul#view_type_tab li#all').click(function()
	{
		$('#album_container').css('display', '');
		$('#photo_container').css('display', 'none');
		window.location.hash = '';
	});
	
	$('#current_album').click(function()
	{
		$('#album_container').css('display', '');
		$('#photo_container').css('display', 'none');
		window.location.hash = '';
		if (slideshow_interval != null)
		{
			clearInterval(slideshow_interval);
			stop_slideshow_animation();
		}

		$('ul#view_type_tab li').removeClass('current');
		$('ul#view_type_tab li#all').addClass('current');
	});
	
	$('ul#view_type_tab li#slide').click(function() {
		slideshow_interval = setInterval(next_photo, album_slideshow_interval);
		start_slideshow_animation();
	});
	
	$('ul#view_type_tab li#once').click(function() {
		var photo_id = $('input#photo_current_id').val();
		if (photo_id == '0')
		{
			photo_id = $('#album_container div.photo_item:first').attr('photo_id');
		}

		var photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
		show_photo(photo_id, photo_url);
	});
	
	function show_photo_hash()
	{
		if (change_hash)
		{
			// загрузка сразу же фотки, если она была в адресной строке
			if (window.location.hash.length > 1)
			{
				var photo_id = window.location.hash.substr(1);
				var photo_url = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_url');
				
				if (photo_url != undefined)
				{
					show_photo(photo_id, photo_url);
					
					if ($('ul#view_type_tab li.current').attr('id') == 'all')
					{
						$('ul#view_type_tab li').removeClass('current');
						$('ul#view_type_tab li#once').addClass('current');
					}
				}
			}
			else
			{
				$('#album_container').css('display', '');
				$('#photo_container').css('display', 'none');
			}
		}
		change_hash = true;
	}
	
	/*
	$(window).bind('hashchange', function() {
		show_photo_hash();
	});
	show_photo_hash();
	*/
	
	$(window).resize(function(){
		$.positionAll();
	});
	
	$(window).hashchange( function(){
		show_photo_hash();
	});

	$(window).hashchange();
	
});


function ya_share(){
	var YaShareInstance = new Ya.share({
			element: 'ya_share1',
			elementStyle: {
				'type': 'none',
				'border': false,
				'quickServices': ['vkontakte', 'facebook', 'twitter', 'odnoklassniki', 'lj']
			},
			link: window.location,
			onready: function(instance) {
                // После инициализации можно поменять ссылку или заголовок, которым требуется поделиться
           
				instance.updateShareLink(
					window.location,
					'',
					{
					   twitter: {link: 'http://ya.ru', title: 'ya.ru'}
					}
				);
                   
            }	
				
	});
}



function index_bg_slideshow(){
	if ($("div.bg_image:last").hasClass('complete'))
	{
		$("div.bg_image:last").fadeOut(index_slideshow_animation_time,function(){
			 $(this).remove().insertBefore("div.bg_image:first").css('display','block');
		});
	}
	//$("div.bg_image:first").fadeOut(index_slideshow_animation_time).remove().prependTo("div.bg_image:last");
}
function show_loader()
{
	$('#photo_loader').css('display', 'block');
}

function hide_loader()
{
	$('#photo_loader').css('display', 'none');
}

function resize_photo(photo_id)
{
	/*
	//top_menu_height=37; above_top_menu_space=22; bread_crumb_margin + bread_crumb_height = 45; footer = 40; arrows_height = 30
	var w_height=$(window).height()-37-22-45-40-50; 
	var w_width=$(window).width();
	
	var photo_width = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_width');
	var photo_height = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_height');
	
	
	var w_proportion = w_width/w_height;
	var image_proportion = photo_width/photo_height;
	
	if (w_proportion>=image_proportion)
	{
		new_photo_width = photo_width * w_height / photo_height;
		new_photo_height = w_height;
	}
	else
	{
		new_photo_width = w_width;
		new_photo_height = photo_height * w_width / photo_width;
	}
	$('#photo_container_hidden img[photo_id="'+photo_id+'"]').css({width: new_photo_width + 'px', height: new_photo_height + 'px'});
	*/
	var photo_width = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_width');
	var photo_height = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_height');
	
	var new_photo_height = photo_height;
	var new_photo_width = photo_width;
	
	if (photo_height > photo_width && photo_height > 450)
	{
		new_photo_height = 600;
		new_photo_width = photo_width * new_photo_height / photo_height;
	}
	$('#photo_container_hidden img[photo_id="'+photo_id+'"]').css({width: new_photo_width + 'px', height: new_photo_height + 'px', left: (450 - new_photo_width/2) + 'px'});
	 
	$("#photo_content").css('height',new_photo_height + 'px');
}

function resize_main_photo()
{
	/*var w_height=$(window).height()-37-22-45-40-50; 
	var w_width=$(window).width();
	
	var photo_id = $('input#photo_current_id').val();
	
	var photo_width = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_width');
	var photo_height = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_height');
	
	var w_proportion = w_width/w_height;
	var image_proportion = photo_width/photo_height;
	
	if (w_proportion>=image_proportion)
	{
		new_photo_width = photo_width * w_height / photo_height;
		new_photo_height = w_height;
	}
	else
	{
		new_photo_width = w_width;
		new_photo_height = photo_height * w_width / photo_width;
	}
	$('#photo_container img#photo:first').css({width: new_photo_width + 'px', height: new_photo_height + 'px'});
	*/
	
	var photo_width = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_width');
	var photo_height = $('div.photo_item[photo_id="'+photo_id+'"]').attr('photo_height');
	var photo_id = $('input#photo_current_id').val();
	var new_photo_height = photo_height;
	var new_photo_width = photo_width;
	
	if (photo_height > photo_width && photo_height > 450)
	{
		new_photo_height = 600;
		new_photo_width = photo_width * new_photo_height / photo_height;
	}
	$('#photo_container img#photo:first').css({width: new_photo_width + 'px', height: new_photo_height + 'px'});
	$("#photo_content").css('height',new_photo_height + 'px');
}

$.positionAll=function()
{
	var w_height=$(window).height()-37-22;
	var w_width=$(window).width();
	
	if($("#album_container"))
	{
		resize_main_photo();
	}
};
