var _visible = false;
var _redirect = false;

var showPage = null;
var showPicture = null;
var showCategory = null;

var showIndex = null;

var _hide = null;

var content = {};
var loadCounter = {};
var thumbCounter = {};

var _loadQueue = {};
var _activeLoadQueue = null;

var speed = 500;

var e_menu = null;
var e_backlink = null;

var e_controls = null;
var e_pictureIndex = null;
var e_next = null;
var e_prev = null;

var e_index = null;
var e_indexIndex = null;
var e_nextIndex = null;
var e_prevIndex = null;
var e_indexThumbs = null;

var e_picTitle = null;

var _scale = 0.75;
var _fontSize = [14, 18, 25];
var e_font = [];

$(document).ready(function()
{
	if (_redirect)
		return;
	
	$('body').disableTextSelect();
	
	$('#maininner').hide();
	$('noscript').remove();
	$('body script').remove();
	
	$('.works a, #menu a[target!=_blank], #logo a, #back a')
		.click(function() { return href(this); });
		
	for(var i = 0; i < _fontSize.length; i++)
		e_font[i] = $('.font' + (i + 1))
	e_picTitle = $('.picTitle');
	
	e_menu = $('#menu');
	e_backlink = $('#back');
	
	e_controls = $('#controls');
	e_pictureIndex = $('#e_pictureindex');
	e_next = $('#e_next').click( function() { href(this); return false; });
	e_prev = $('#e_prev').click( function() { href(this); return false; });
		
	e_index = $('#index');
	e_indexIndex = $('#e_indexindex');
	e_nextIndex = $('#e_nextindex').click( function() { href(this); return false; });
	e_prevIndex = $('#e_previndex').click( function() { href(this); return false; });

	$(jQuery.browser.mozilla ? window : "body").keydown(function(e) {
		switch(e.keyCode)
		{
			case 37: if (content[showPage]._type == 'gallery') e_prev.click(); break;
			case 39: if (content[showPage]._type == 'gallery') e_next.click(); break;
			case 33: case 36: if (content[showPage]._type == 'gallery') $.historyLoad(showPage + '/1'); break;
			case 34: case 35: if (content[showPage]._type == 'gallery') $.historyLoad(showPage + '/' + galleryData[showPage].length);  break;
		}
	});
	
	createPage('startpage');
		
	$.historyInit(show, "/");	

	$(window).resize(function(){
		resizeImages();
	});
	resizeImages();
});


function href(e)
{
	var hash = e.href;
	if (hash.indexOf('#') == -1)
		hash = hash.replace(root, root + '#');
	hash = hash.replace(/^.*#/, '');
	$.historyLoad(hash);
	return false;
}

//----------------------------------------------------------------------------------------------------


function createPage(page)
{
	if (pageData[page] === undefined)
		return false;
		
	content[page] = $('<div id="' + page + '" class="page" style="display:none;">' + pageData[page][1] + '</div>');
	content[page].appendTo('#content');

	content[page]._page = page;
	content[page]._visible = false;
	content[page]._type = 'page';
	content[page]._title = parseInt(pageData[page][2]) ? '' : '| ' + pageData[page][0];
	content[page]._backlink = false;
	content[page]._category = 'categories';
	
	return true;
}


function createCategory(page)
{
	if (categoryData[page] === undefined || !categoryData[page][1].length)
		return false;
		
	content[page] = $('#startpage');
	content[page]._page = 'startpage';
	content[page]._visible = false;
	content[page]._type = 'category';
	content[page]._title = '| ' + categoryData[page][0];
	content[page]._backlink = root;
	content[page]._category = 'category_' + page;
}


function createGallery(page)
{
	if (galleryData[page] === undefined)
		return;
		
	loadCounter[page] = galleryData[page][1].length;
	thumbCounter[page] = {};
	
	content[page] = $('<div id="' + page + '" class="series" style="display:none;"></div>');
	content[page]._page = page;
	content[page]._title = '| ' + galleryData[page][0];
	content[page]._pic = [];
	content[page]._thumb = [];
	content[page]._category = galleryData[page][3] ? 'category_' + galleryData[page][3] : 'categories';
	content[page]._backlink = root;
	
	var line = null;
	content[page]._index = [];
	
	_loadQueue[page] = [];
	
	for (var index = 0; index < galleryData[page][2].length; index++)
	{
		content[page]._index[index] = $('<div class="indexTable"></div>');
		var table = $('<table id="index_' + page + '_' + (index + 1) + '" cellspacing="0" cellpadding="0" border="0"></table>').
			appendTo(content[page]._index[index]);
			
		if (!$.browser.opera)
		{
			table.hide();
			content[page]._index[index].addClass('loading');
		}
			
		thumbCounter[page][index] = 0;

		for(var pos = 0; pos < galleryData[page][2][index].length; pos++)
		{
			if (!(pos % INDEXCOUNT))
				line = $('<tr></tr>').appendTo(table);

			var cell = null;				
			if (galleryData[page][2][index][pos][1] == 'q')
				cell = $('<td></td>');
			else if (galleryData[page][2][index][pos][1] == 'ho')
				cell = $('<td rowspan="2"></td>');
			else if (galleryData[page][2][index][pos][1] == null || galleryData[page][2][index][pos][1] == -1)
				cell = $('<td>&nbsp;</td>');
			
			 if (galleryData[page][2][index][pos][1] == 'q' || galleryData[page][2][index][pos][1] == 'ho')
			 {
			 	thumbCounter[page][index]++;
			 	
			 	content[page]._thumb[galleryData[page][2][index][pos][0]] = $('<img>')
			 		.attr('id', 'thumb_' + page + '_' + (1 + galleryData[page][2][index][pos][0]))
			 		.attr(($.browser.opera ? 'src' : '_src'), root + 'files/gallery/tn_' + galleryData[page][1][galleryData[page][2][index][pos][0]][0] + '.jpg')
			 		.attr('class', 'indexThumb')
			 		.appendTo(cell)
			 		.click(function(){ 
			 			
			 			var parts = this.id.substring(6).split("_");
						if (parts.length > 1)
						    parts[parts.length - 2] += '/' + parts.pop();

						$.historyLoad(parts.join('_'));
						return false;
					 });

				if (!$.browser.opera)
					_loadQueue[page].push([0, content[page]._thumb[galleryData[page][2][index][pos][0]]]);
			}
				
			if (cell)
				cell.appendTo(line);
		}
		content[page]._index[index]
			.appendTo(content[page]);
			
		_loadQueue[page].push([1, table]);
	}
	
	for(var index = 0; index < galleryData[page][1].length; index++)
	{
		content[page]._pic[index] = {};
		
		content[page]._pic[index].div = $('<div id="' + page + '_' + (index+1) + '" class="picdiv">')
			.hide()
			.width(Math.round(1000 * _scale))
			.height(Math.round(700 * _scale))
			.appendTo(content[page])
			.click(function(){ 
				var pos = this.id.lastIndexOf('_');
				var k = this.id.substring(0, pos);
				var i = this.id.substring(pos + 1);
				$.historyLoad(k + "/" + (i < galleryData[k][1].length ? parseInt(i) + 1 : i));
				return false;
			 });
			 
		content[page]._pic[index].img = $(new Image());
					 
		if (!$.browser.opera)
		{
			content[page]._pic[index].img
				.hide()
				.load(function() { loadPicture(this) });
				
			content[page]._pic[index].div.addClass('loading');
		}
		
		content[page]._pic[index].img
			.prependTo(content[page]._pic[index].div)
			.width(Math.round(galleryData[page][1][index][1] * _scale))
			.height(Math.round(galleryData[page][1][index][2] * _scale))
			.attr(($.browser.opera ? 'src' : '_src'), root + 'files/gallery/pic_' + galleryData[page][1][index][0] + '.jpg');
			
		if (!$.browser.opera)
			content[page]._pic[index].img.hide();
			
		if (index == galleryData[page][1].length - 1)
			content[page]._pic[index].img.css('cursor', 'default');
		
		if (galleryData[page][1][index][3])
			$('<div class="picTitle">' + galleryData[page][1][index][3] + '</div>')
				.appendTo(content[page]._pic[index].div);
	}
	
	content[page].appendTo('#content');
	content[page]._visible = false;
	content[page]._type = 'gallery';
	
	e_indexThumbs = $('.indexThumb');
	e_picTitle = $('.picTitle');
	resizeImages();
	
	startLoadQueue(page);
}


function startLoadQueue(page)
{
	if (_loadQueue[page] == undefined || !_loadQueue[page].length)
	{
		$('#' + page + ' [_src]').each(function() {
			$(this).attr('src', $(this).attr('_src')).removeAttr('_src');
		});
		return;
	}
		
	var next = _loadQueue[page].shift();
	if (next[0] == 0)
	{
		next[1]
			.load(function() { startLoadQueue(page); })
			.attr('src', next[1].attr('_src'))
			.removeAttr('_src');
	}
	else
	{
		next[1].fadeIn(speed, function() {
			startLoadQueue(page);
		});
		next[1].parent().removeClass('loading');
	}
}


function loadPicture(img)
{
	var id = $(img).parent().attr('id');
	var pos = id.lastIndexOf('_');
	var page = id.substring(0, pos);
	var picture = id.substring(pos + 1);
	loadCounter[page]--;

	content[page]._pic[picture - 1].div.removeClass('loading');
	content[page]._pic[picture - 1].img.fadeIn(speed);
}


function loadThumb(img)
{
	var id = $(img).parents('table').attr('id');
	
	var pos = id.lastIndexOf('_');
	var page = id.substring(0, pos).substring(6);
	var index = id.substring(pos + 1);

	thumbCounter[page][index - 1]--;

	if (!thumbCounter[page][index - 1])
		$(img).parents('table').fadeIn(speed);
}


//----------------------------------------------------------------------------------------------------


function show(key)
{
	if (!key)
		key = initPage ? initPage : initAlbum;
		
	var k = key.split('/');
	if (k.length < 2)
		k[1] = null;
		
	if (k[0] == showPage && (k[1] == showPicture || (k[1] !== null && k[1][0] == 'i' && parseInt(k[1].substring(1)) == showIndex)))
		return;
		
	if (content[k[0]] === undefined)
		if (!createPage(k[0]))
			if (!createCategory(k[0]))
				createGallery(k[0]);
	
	changePage(k[0], k[1]);
}


function swapView(show, hide, condition)
{
	if (condition === undefined)
		condition = true;
	
	if (!condition)
	{
		var s = show;
		show = hide;
		hide = s;
	}
	
	if (show !== null && show.css('display') == 'none')
		show.fadeIn(speed);
		
	if (hide !== undefined && hide !== null && hide.css('display') != 'none')
		hide.fadeOut(speed);
}


function changePage(page, picture)
{
	if (!_visible)
	{
		e_menu.hide();
		e_backlink.hide();
		
		e_controls.hide();
		$('.works').hide();
		showPage = null;
		var s = speed;
		speed = 0;
	}
	
	var index = null;
	
	if (content[page]._type == 'gallery')
	{
		if (!picture || isNaN(picture))
		{
			index = page;
			if (!picture)
				index = 1;
			else
				index = parseInt(picture.substr(1));
			picture = null;
		}
	}
	
	if (showPage && content[showPage]._type == 'gallery')
	{
		if (showPage == page)
			picHide(showPage, showPicture, showIndex);
		else
			_hide = [showPage, showPicture, showIndex];
	}
	else
		_hide = null;
		
	if (content[page]._type == 'gallery')
		picShow(page, picture, index);
	else
	{
		swapView(null, e_controls);
		swapView(null, e_index);
	}

	if (page != showPage)
	{
		if (content[page]._category != showCategory)
		{
			if (showCategory)
				$('#' + showCategory).fadeOut(speed);

			$('#' + content[page]._category).fadeIn(speed);
			showCategory = content[page]._category;
		}
		
		swapView(e_backlink, e_menu, Boolean(content[page]._backlink));
		
		if (!showPage || content[page]._page != content[showPage]._page)
		{
			if (showPage)
				content[showPage].fadeOut(speed, function() { picHide(); $(this).hide()});
			
			content[page].fadeIn(speed);
		}
	}
	
	if (content[page]._backlink)
		if (picture)
			$('a', e_backlink).attr('href', root + page);
		else
			$('a', e_backlink).attr('href', content[page]._backlink);
			
	$('#l_' + showPage).removeClass('selected');
	$('#l_' + page).addClass('selected');
	
	showPage = page;
	showPicture = picture;
	showIndex = index;

	document.title = 'Bernd Schuler | Photography ' + content[page]._title;

	if (!_visible)
	{
		speed = s;
		$('#maininner').fadeIn(speed);	
		_visible = true;
	}
}


//----------------------------------------------------------------------------------------------------


function picShow(page, picture, index)
{
	if (picture === null)
	{
		openIndex(page, index);
		return;
	}
			
	if (!content[page]._pic.length)
		return;

	picture = parseInt(picture);

	if ($.browser.msie)
		content[page]._pic[picture - 1].div.children('div').hide();
		
	if (showPage != page)
	{
		content[page]._pic[picture - 1].div.show();
		if ($.browser.msie)
			content[page]._pic[picture - 1].div.children('div').show();
	}
	else
		content[page]._pic[picture - 1].div.fadeIn(speed, function() {
			if ($.browser.msie)
				content[page]._pic[picture - 1].div.children('div').show();
		});
	
	swapView(e_controls, e_index);
	e_pictureIndex.html((picture < 10 ? '0' : '') + picture);
			
	if (picture <= 1)
		e_prev.addClass('disable').attr('href', root + page + '/1');
	else
		e_prev.removeClass('disable').attr('href', root + page + '/' + (picture - 1));
			
	if (picture >= galleryData[page][1].length)
		e_next.addClass('disable').attr('href', root + page + '/' + galleryData[page][1].length);
	else
		e_next.removeClass('disable').attr('href', root + page + '/' + (1 + picture));
}


function picHide(page, picture, index)
{
	if (page == undefined)
	{
		if (!_hide)
			return;
			
		page = _hide[0];
		picture = _hide[1];
		index = _hide[2];
	}
	
	if (picture === null) 
	{
		closeIndex(page, index);
		return;
	}
	
	if (picture <= content[page]._pic.length)
	{
		if ($.browser.msie)
			content[page]._pic[picture - 1].div.children('div').hide();
		
		if (_hide)
			content[page]._pic[picture - 1].div.hide();
		else
			content[page]._pic[picture - 1].div.fadeOut(speed);
	}
	_hide = null;
}

//----------------------------------------------------------------------------------------------------



function openIndex(page, index)
{
	content[page]._index[index - 1].fadeIn(speed);
	
	if (showPicture === null)
		e_index.attr('href', root + page + '/1');
	else if (showPicture != 'index')
		e_index.attr('href', root + page + '/' + showPicture);

	if (content[page]._index.length > 1)
	{
		e_indexIndex.html((index < 10 ? '0' : '') + index);
		
		if (index >= content[page]._index.length)
			e_nextIndex
				.addClass('disable')
				.attr('href', root + page + '/i' + content[page]._index.length)
				.show();
		else
			e_nextIndex
				.removeClass('disable')
				.attr('href', root + page + '/i' + (1 + index))
				.show();
			
		if (index > 1)
			e_prevIndex
				.removeClass('disable')
				.attr('href', root + page + '/i' + (index - 1))
				.show();
		else
			e_prevIndex
				.addClass('disable')
				.attr('href', root + page)
				.show();
				
		swapView(e_index);
	}
	
	swapView(null, e_controls);
}

function closeIndex(page, index)
{
	content[page]._index[index - 1].fadeOut(speed);
}


//----------------------------------------------------------------------------------------------------


function resizeImages()
{
	_scale = Math.min(Math.min(($(window).width() - 50) / 1000, ($(window).height() - 50) / 800), 1);
	_scale = Math.max(_scale, 0.4);

	$('#maincontainer').height(Math.round(800 * _scale));
	$('#maininner')
		.width(Math.round(1000 * _scale))
		.height(Math.round(800 * _scale));
		
	$('#startpic')
		.width(Math.round(1000 * _scale))
		.height(Math.round(700 * _scale));
		
	var _scalef = Math.pow(_scale, 0.6);

	for(var i = 0; i < _fontSize.length; i++)
		e_font[i].css('font-size', Math.round(_fontSize[i] * _scalef) + 'px');
	
	e_picTitle
		.css('top', Math.round(-49 * _scale) + 'px')
		.css('right', Math.round($('#back').width() + 20 * _scale) + 'px');

	var thumbWidth = Math.round(1000 / INDEXCOUNT * _scale - 0.5);
	var thumbHeight = Math.round(700 / INDEXCOUNT * _scale - 0.5);

	for(var page in content)
		if (content[page]._type == 'gallery')
		{
			for (var picture = 0; picture < galleryData[page][1].length; picture++)
			{
				content[page]._pic[picture].div
					.width(Math.round(1000 * _scale))
					.height(Math.round(700 * _scale));
				
				content[page]._pic[picture].img
					.width(Math.round(galleryData[page][1][picture][1] * _scale))
					.height(Math.round(galleryData[page][1][picture][2] * _scale));
					
				var hscale = galleryData[page][1][picture][1] > galleryData[page][1][picture][2] ? 1 :  2;
				content[page]._thumb[picture]
					.width(thumbWidth)
					.height(thumbHeight * hscale);
			}
		}
}


//----------------------------------------------------------------------------------------------------


function UnCryptMailto( s )
{
	var n = 0;
	var r = "";
	for( var i = 0; i < s.length; i++)
	{
	    n = s.charCodeAt( i );
	    if( n >= 8364 )
	    {
	        n = 128;
	    }
	    r += String.fromCharCode( n - 1 );
	}
	return r;
}

function linkTo_UnCryptMailto( s )
{
	location.href=UnCryptMailto( s );
}

