var ilc;

$(document).ready(function()
{
	debug('Ready.');
	ilc = 1;

	if($('#gallery-photo').length > 0)
	{
		$('#loading').fadeIn(1000);
		var images = $('ul#gallery > li img');

		$('#loading #itot').html(images.length);
		$('#loading #ilc').html(1);

		$('div#hdr #m-mnu-sub').delay(1000).fadeIn(500);

		$.each(images, function(key, value) 
		{
			$(this).load(
				function() {
					if(key-1 > ilc) {
						ilc++;
						$('#loading #ilc').html(ilc);
					}
			});

			$('body').append('<img class="preloaded-img" src="'+this.src+'" style="display:none;" />');
			
			if(key == images.length-1)
			{
				$('.preloaded-img:last').load(
					function() {
						$('#loading').hide();
						$('#pg-cnt-l').fadeIn(500, function() 
						{
							galleryItem($('ul#gallery > li').first());	
							fadeItem($('ul#gallery > li').first());
						});

						$('ul#gallery > li').click(
						function() 
						{
							galleryItem($(this));
						});
				});
			}
		});
	}
	else
	{
		loadFancy();
		
		$('#pg-cnt-l').delay(1000).fadeIn(2000);
		$('#pg-cnt-r').hide().delay(1500).fadeIn(2500, function() {
			loadFancy();
		});
	}
});

function galleryItem(item)
{
	item.addClass('active').siblings().removeClass('active');

	if($('#gallery-content').html())
	{
		$('#gallery-content').fadeOut(750, 'easeInOutExpo');
		$('#gallery-photo').fadeOut(1200, 'easeInOutExpo', function() {
			galleryImage(item);
		});
	}
	else
	 galleryImage(item);
}

function galleryImage(item)
{
	var total = $('ul#gallery > li').length;

	$.ajax({
		url: '/index.php?id=7', 
		type: 'POST', 
		data: { docid: item.attr('data-id') }, 
		dataType: 'json', 
		success:
			function(data)
			{	
				debug('data:');
				debug(data);
				
				if(!data || !data.doc)
					return false;

				if(data.doc.content)
					$('#gallery-content').html(data.doc.content).fadeIn(1500, 'easeInOutExpo');

				if(data.doc.image)
				{
					$('#gallery-photo').html(data.doc.image);
					loadFancy();
					$('#gallery-photo').fadeIn(2500, 'easeInOutExpo');
				}
			}, 
		error:
			function(data) {
				if(data.responseText) debug(data.responseText);
			}
	});
}

function fadeItem(item)
{
	var total = $('ul#gallery > li').length;
	var minus = (total * 15);

	if(minus > 500) minus = 0;

	item.fadeIn(500 - minus, 'easeInExpo', function() 
	{
		var next	= item.next();
		var total	= $('ul#gallery > li').length;
		var visible = $('ul#gallery > li:visible').length;

		if(visible % 6 == 0 && total > visible)
		{
			$('#gallery').animate({
				height: "+=85" }, {
				duration: 500, 
				easing: 'easeOutExpo', 
				queue: false
			});
		}
		
		if(next) 
			fadeItem(next);
	});
}

function loadFancy()
{
	$('a.fancybox').fancybox({
		titlePosition: 'inside', 
		speedIn: 1200, 
		margin: 50
	});
}

function debug(str)
{
	if(window.console)
		window.console.log(str);
}
