// (c) Krzysztof Frankiewicz 2009

// THE MACHINE NEVER SLEEPS!
var theMachine = new Object();
theMachine.built = false;
theMachine.build = function (data) {
	theMachine.data = data;
	var fromtop = ($(window).height()-$('.container').height())/2;
	$('.container').css('opacity',0).show()
	.animate({'top':fromtop,'opacity':1},500, function () {
		theMachine.topmenu.build();
		theMachine.previewer.build();
		theMachine.submenu.build();
		theMachine.menu.build();
		theMachine.project.build();
		theMachine.info.build();
		theMachine.references.build();
		theMachine.firma.build();
		$('<div />').attr('class','maintext').hide().appendTo('.container').scroller();
		theMachine.mainPage();
		theMachine.built = true;
	});
}

theMachine.hideAll = function (fn)
{
	if (!$.isFunction(fn)) fn = function () {};
	theMachine.back.removeback();
	theMachine.previewer.hide();
	$('.container .maintext').fadeOut(200);
	if (!theMachine.menu.hidden || !theMachine.project.hidden)
		theMachine.project.hide(function () {
			theMachine.menu.hide(fn);
		});
	else if (!theMachine.references.hidden) theMachine.references.hide(fn);
	else if (!theMachine.firma.hidden) theMachine.firma.hide(fn);
	else fn();
}
theMachine.mainPage = function ()
{
	$('.container .topmenu a').removeAttr('class');

	theMachine.hideAll(function () {
		theMachine.previewer.loadMain();
		if ($('.container .maintext div').size() == 0)
			$.get('list.php',{'readfile':'contents/glowna.text'},function (b) {
				$('<div />').html(b).hide().appendTo('.container .maintext').fadeIn();
			},'html');
		$('.container .maintext').fadeIn();
	});
	theMachine.back.destroy();
}

// INFO
theMachine.info = {};
theMachine.info.build = function ()
{
	$('<div \>').attr('class','info').hide().text(theMachine.data.info).appendTo('.container');
}
theMachine.info.show = function ()
{
	$('.container .info').fadeIn(300);
}
theMachine.info.hide = function ()
{
	$('.container .info').fadeOut(300);
}

// TOP MENU
theMachine.topmenu = new Object();
theMachine.topmenu.build = function ()
{
	$('<div />').attr('class','topmenu').hide()
		.html('\
					<a href="#">firma</a>\
					<a href="#">realizacje</a>\
					<a href="#">konkursy</a>\
					<a href="#">nagrody</a>\
					<a href="#">referencje</a>\
					<a href="#">kontakt</a>')
		.appendTo('.container').fadeIn();
		
	$('.container .topmenu a').click(function () {
		if (selected(this))
		{
			$('.container .topmenu a').removeAttr('class');
			$(this).attr('class','selected');

			var text = $(this).text();
			var _data = theMachine.data[text];

			switch (text)
			{
					case 'realizacje': case 'konkursy': case 'nagrody':
						theMachine.back.destroy();
						theMachine.hideAll(function () {theMachine.menu.load(_data);});
						break;
					case 'kontakt':
						theMachine.back.destroy();
						theMachine.hideAll(function () {theMachine.project.view(_data);theMachine.back.build();});
						break;
					case 'referencje':
							theMachine.back.destroy();
							theMachine.hideAll(function () { theMachine.references.show(_data);theMachine.back.build(); });
//						alert('ni gotowe');
						break;
					case 'firma':
						theMachine.back.destroy();
						theMachine.hideAll(function () { theMachine.firma.show(_data); theMachine.back.build(); });
						break;
			}
		}
	});
}

// PREVIEWER
theMachine.previewer = new Object ();
theMachine.previewer.build = function ()
{
	$('<div />').attr('class','previewer')
		.appendTo('.container');
	theMachine.previewer.loadMain();
}
theMachine.previewer.loadMain = function ()
{
	if ($('.container .previewer img').size() > 0)
	{
		$('.container .previewer img').fadeOut(100,function () { $(this).removeImage(); theMachine.previewer.loadMain(); });
		return;
	}
	$('.container .previewer').fadeIn();
	$.getImage('image.php?W=533&H=264&quality=90&path=contents/glowna.image&mode=crop').appendTo('.container .previewer');
//	$('<img />').attr('src','image.php?W=533&H=264&path=/contents/glowna.image&mode=crop').appendTo('.container .previewer').hide().load(function () { $(this).fadeIn(100); });
}
theMachine.previewer.loadImage = function (img)
{
//	if (img.search('Acontents') != -1) img = '/'+img.substr(1);
	$('.container .previewer').fadeIn();
	if ($('.container .previewer img').attr('src') != img && img)
		$('.container .previewer img').fadeOut(100,function () {
			$('.container .previewer img').removeImage();
			$.getImage('image.php?W=532&H=264&quality=90&mode=crop&path='+img).appendTo('.container .previewer');
//			$('.container .previewer').empty();
//			$('<img />').attr('src','image.php?W=532&H=264&quality=25&mode=crop&path='+img).appendTo('.container .previewer').hide().load(function () { $(this).fadeIn(100); });
		});
}
theMachine.previewer.hide = function (fn)
{
	if (!$.isFunction(fn)) fn = function () {};
	$('.container .previewer').fadeOut(300,fn);
}



// MENU
theMachine.menu = new Object();
theMachine.menu.right = '-80px';
theMachine.menu.hidden = true;
theMachine.menu.build = function ()
{
	$('<div />').attr('class','menu').css({'right': theMachine.menu.right}).appendTo('.container').scroller();
	$('<div />').attr('class','menu_cover').appendTo('.container');
}
theMachine.menu.show = function (fn)
{
	$('.container .menu').animate({'right': '70px'}, function () { theMachine.menu.hidden = false; if ($.isFunction(fn)) fn(); });
	theMachine.back.build();
}
theMachine.menu.hide = function (fn)
{
	theMachine.submenu.hide(function () {
		if (!theMachine.menu.hidden) 
			$('.container .menu').animate({'right': theMachine.menu.right}, function () { theMachine.menu.hidden = true; if ($.isFunction(fn)) fn(); });
		else if ($.isFunction(fn)) fn();
	});
}

theMachine.menu.load = function (data)
{
	theMachine.previewer.loadImage(data.image);
	$('.container .submenu a').unbind();
	theMachine.menu.hide(function () {
		$('.container .menu a').unbind();
		$('.container .menu').empty();
		$.each(data,function (i,el) {
			if (el.name)
				$('<a />').attr('href','#').text(el.name).appendTo('.container .menu')
					.click(function () {
						if (selected(this))
						{
							$('.container .menu a').removeAttr('class');
							$(this).attr('class','selected');
							theMachine.submenu.load(el.subdirs);
						}
					})
					.mouseover(function () { theMachine.previewer.loadImage(el.image); });
		});
		$('.container .menu').get(0).scrollTop = 0;
		theMachine.menu.show();
	});
}



// SUBMENU
theMachine.submenu = new Object();
theMachine.submenu.right = '-20px';
theMachine.submenu.hidden = true;
theMachine.submenu.build = function ()
{
	$('<div />').attr('class','submenu').css({'right':theMachine.submenu.right}).appendTo('.container').scroller();	
	$('<div />').attr('class','submenu_cover').appendTo('.container');
}
theMachine.submenu.show = function ()
{
	$('.container .submenu').animate({'right': '231px'}, function () { theMachine.submenu.hidden = false; });
}
theMachine.submenu.hide = function (fn)
{
	if (!theMachine.submenu.hidden)
		$('.container .submenu').animate({'right': theMachine.submenu.right }, function () { theMachine.submenu.hidden = true; if ($.isFunction(fn)) fn(); });
	else  if ($.isFunction(fn)) fn();
}

theMachine.submenu.load = function (data)
{
	theMachine.submenu.hide(function () {
		$('.container .submenu').empty();
		$.each(data, function (i,el) {
			$('<a />').attr('href','#').text(el.name).appendTo('.container .submenu')
				.mouseover(function () { if (el.image != '') theMachine.previewer.loadImage(el.image); })
				.click(function () { theMachine.project.view(el); });
			
		});
		$('.container .submenu').get(0).scrollTop = 0;
		theMachine.submenu.show();
	});
}

// BACK
theMachine.back = new Object();
theMachine.back.hidden = true;
theMachine.back.build = function ()
{
	$('<div />').attr('class','back')
	.html('\
				<a href="#">?</a>\
				<a href="#">strona glowna</a>\
				')
	.appendTo('.container').fadeIn();
	$('.container .back a:last').unbind().click(theMachine.mainPage);
	$('.container .back a:first').unbind().mouseover(theMachine.info.show).mouseout(theMachine.info.hide);
	$(document).bind('keydown','space', theMachine.mainPage );
}
theMachine.back.destroy = function (fn)
{
	if (!$.isFunction(fn)) fn = function () {};
	$('.container .back a').unbind();
	$(document).unbind();
	$('.container .back').fadeOut(500,function() { $(this).remove(); theMachine.back.hidden = true; fn(); });
}
theMachine.back.addback = function (fn)
{
//	if ($('.container .back a').size() >1) return;
	if (!$.isFunction(fn)) fn = function () {};
	$('<a />').attr('href','#').text('powrot').hide().appendTo('.container .back')
		.click(function () {fn(); theMachine.back.removeback(); })
		.fadeIn();
	$(document).bind('keydown','left', function () { fn(); theMachine.back.removeback(); });

}
theMachine.back.removeback = function (fn)
{
	if (!$.isFunction(fn)) fn = function () {};
//	$(document).unbind();
	$('.container .back a').each(function () {
		if ($(this).text() == 'powrot')
			$(this).unbind().fadeOut(function () {$(this).remove(); fn(); });
	});
}

// PROJECT
theMachine.project = {}
theMachine.project.hidden = true;
theMachine.project.left = '1100px';
theMachine.project.build = function ()
{
	$('<div />').attr('class','project').css('left',theMachine.project.left)
		.insertBefore('.container .menu_cover');
}
theMachine.project.view = function (data)
{
	if (!theMachine.project.hidden) return;
	theMachine.project.hidden = false;
	$('.container .project').empty().animate({'left':'70px'},500);
	$.get('list.php',{'readfile':data.text},function (b) {
		if ($.trim(b) == "") b = "Brak opisu.";
		$('<div />').attr('class','right').html(b).appendTo('.container .project');
	},'html');
	theMachine.back.addback(theMachine.project.hide);
	theMachine.gallery.build(data.images);
}
theMachine.project.hide = function (fn)
{
	if (!$.isFunction(fn)) fn = function () {}; 
	if (theMachine.project.hidden) fn();
	else $('.container .project').stop().animate({'left':theMachine.project.left},function () { theMachine.project.hidden = true; theMachine.gallery.destroy(); fn(); });
}

// REFERENCES
theMachine.references = {};
theMachine.references.hidden = true,
theMachine.references.left = '1100px';
theMachine.references.build = function ()
{
	$('<div />').attr('class','references').css('left',theMachine.references.left)
		.insertBefore('.container .menu_cover');
}
theMachine.references.show = function (data)
{
	theMachine.references.hidden = false;
	$('.container .references img').removeImage();
	$('.container .references').empty().animate({'left':'70px'},500).append('<div class="inner" />');
//	alert(data.images.length+' '+Math.floor(data.images.length / 4))
	for (var i=0;i<Math.floor(data.images.length / 4);i++)
	{
		$('.container .references .inner').append('<div />');
	}
	$.each(data.images,function (i,el) {
		$.getImage('image.php?W=200&H=264&quality=90&mode=crop&path=contents/referencje/'+el)
		.click(function () { theMachine.enlarger.show('contents/referencje/'+el); })
		.appendTo('.container .references .inner div:nth-child('+Math.floor(1 + i / 4)+')');//.wrap('<div />');
	});
	$('.container .references .inner').gallery({mouseover : false, mousewheel : true});
}
theMachine.references.hide = function (fn)
{
	$('.container .references img').unbind();
	if (!$.isFunction(fn)) fn = function () {}; 
	$('.container .references').animate({'left': theMachine.references.left},500,fn);
}

// GALLERY
theMachine.gallery = {};
theMachine.gallery.build = function (images)
{
	var left = $('<div />').attr('class','left').prependTo('.container .project');
	if (!images.length) left.css({'background':'none','font-size':'12px'}).text('Brak obrazów.');
	$.each(images,function (i,el) {
//		$('<img />').attr('src','image.php?W=532&H=264&quality=35&mode=crop&path='+el)
		$.getImage('image.php?W=532&H=264&quality=45&mode=crop&path='+el).appendTo('.container .project .left').click(function () { theMachine.enlarger.show(el); });
	});
	$('.container .project .left').gallery();
	
}
theMachine.gallery.destroy = function ()
{
	$('.container .project .left img').removeImage();
	$('.container .project .left').remove();
}

// ENLARGER
theMachine.enlarger = {};
theMachine.enlarger.show = function (src)
{
//	alert(src);
	var w = $(window).width();
	var h = $(window).height();
	$('<div />').addClass('enlarger').css('opacity',0.93).appendTo('body').click(theMachine.enlarger.hide).fadeIn();
	$.getImage('image.php?W='+w+'&H='+h+'&mode=resize&path='+src).load(function () { $(this).css('margin-top', (h-$(this).height())/2); }).appendTo('.enlarger').wrap('<center />').click(theMachine.enlarger.hide);
}
theMachine.enlarger.hide = function ()
{
	$('.enlarger').fadeOut(function () {
		$('.enlarger img').removeImage();
		$('.enlarger').remove();
	});
}

// FIRMA
theMachine.firma = {
	hidden : true,
	object : null,
	left : 70,
	build : function ()
	{
		this.object = $('<div />').addClass('firma').hide().insertBefore('.container .menu_cover');
		var right = $('<div />').addClass('right').appendTo(theMachine.firma.object);
		$('<a />').text('Zespół projektowy').appendTo(right).click(function () { $(this).addClass('selected'); lessright.fadeIn(); });
		$.each(theMachine.data.firma.wycieczki,function (i,el) {
			$('<a />')
				.text(el.name)
				.appendTo(right)
				.click(function () { theMachine.project.view(el); })
			;
		});
		var lessright = $('<div />').addClass('lessright').appendTo(theMachine.firma.object).hide();
		$('<a />')
			.text('mgr inż. arch. Lesław Rubik')
			.appendTo(lessright)
//			.click(function () { if (el.realname != '') theMachine.previewer.loadImage('/contents/firma/'+el.realname); else theMachine.previewer.loadImage(theMachine.data.firma.primage);})
			;
		
		$.each(theMachine.data.firma.pracownicy,function (i,el) {
			$('<a />')
				.text(el.name)
				.appendTo(lessright)
				.click(function () { $('.container .lessright a').removeClass('selected'); $(this).addClass('selected'); if (el.realname != '') theMachine.previewer.loadImage('contents/firma/'+el.realname); else theMachine.previewer.loadImage(theMachine.data.firma.primage);})
			;
		});
	},
	show : function (data) {
		this.hidden = false;
		this.object.show().css('left',$('.container').width()).animate({'left' : theMachine.firma.left});
		theMachine.previewer.loadImage(theMachine.data.firma.primage);
	},
	hide : function (fn) {
		if (!$.isFunction(fn)) fn = function () {};
		this.hideLessright();
		this.object.animate({'left' : $('.container').width()},function () { theMachine.firma.hidden = true; theMachine.firma.object.hide(); fn(); });
	},
	hideLessright : function () {
		this.object.find('.lessright').find('a').removeClass('selected').fadeOut();
		this.object.find('.right a').removeClass('selected');
	}

}

// TOOLS
function selected(el)
{
	return $(el).attr('class') != 'selected';
}

// JQUERY SCROLLER
$.fn.scroller = function ()
{
	var params = {};
	$(this).mousemove(function (e) {
		params.sh = this.scrollHeight;
		params.h = $(this).height() - 20;
		params.d = params.sh - params.h;
		if (params.d > 0)
		{
			var of = $(this).offset();
			params.o = e.pageY - of.top-10;
			params.p = params.o / (params.h);
			params.st = Math.floor(params.p * (params.d));
			params.time = (Math.abs(params.st - this.scrollTop) > params.h*2/3) ? 150 : 0;
			$(this).scrollTo({top: params.st, left: 0},params.time);
//			$('body').prepend(params.st+'; ');
		}
		
	});
	return;
}

// JQUERY GALLERY
$.fn.gallery = function (_setup)
{
	var setup = 	{
									mouseover: true
								}
	for (i in _setup)
		setup[i] = _setup[i];
	
	var of = $(this).offset();
	var parent = this;
	var params = {};
	
	params.size = $(this).children().size();
	if (params.size <= 1) return $(this);
	params.stripeheight = $(this).height() / params.size;
	params.current = 0;
	params.dots = $('<div />').css({
		'position':'absolute',
		'left': $(this).width() + 4,
		'bottom' : 0,
		'height' : params.size*12,
		'width' : 10,
		'top' : 'auto'
	}).insertAfter(this);
	// dodawanie elementu zawierajacego kropki
	params.slider = $('<div />').attr('class','slider').css({
		'width': 10,
		'height': 10,
		'position': 'absolute',
		'top':0,
		'background': '#E21424'
	}).appendTo(params.dots);
	// dodawanie kropek wraz z nawigacja myszowa nad kropkami
	$(this).children().each(function (i,el) {
		$('<div />').attr('class','dot').css({
			'margin': '3px 3px 8px',
			'width': 4,
			'height': 4,
			'background': '#FFF',
			'position': 'absolute',
			'top': 12*i
		}).appendTo(params.dots).mouseover(function () {
			params.current = i;
			$(parent).stop().scrollTo($(parent).children().eq(params.current),250);
			params.slider.stop().animate({'top': 12*i});
		});
	});
	// nawigacja klawiszami
	$(document)
	.bind('keydown','up',function () {
			params.current = (params.current-1+params.size)%params.size;
			$(parent).stop().scrollTo($(parent).children().eq(params.current),250);
			params.slider.stop().animate({'top': 12*params.current});
	})
	.bind('keydown','down',function () {
			params.current = (params.current+1)%params.size;
			$(parent).stop().scrollTo($(parent).children().eq(params.current),250);
			params.slider.stop().animate({'top': 12*params.current});
	});
	if (setup.mousewheel)
	$(parent).mousewheel(function (e,d) {
		if (d<0) {
			params.current = (params.current+1)%params.size;
			$(parent).stop().scrollTo($(parent).children().eq(params.current),250);
			params.slider.stop().animate({'top': 12*params.current});
		}
		else {
			params.current = (params.current-1+params.size)%params.size;
			$(parent).stop().scrollTo($(parent).children().eq(params.current),250);
			params.slider.stop().animate({'top': 12*params.current});
		}
	});
// nawigacja myszka nad zdjeciami
	if (setup.mouseover)
		$(this).mousemove(function (e) {
			if (params.size > 1)
			{
				var of = $(this).offset();
				params.o = e.pageY - of.top;
				params.goto = Math.floor(params.o / params.stripeheight);
	//			$('body').prepend(params.goto);
				if (params.current != params.goto)
				{
					params.slider.stop().animate({'top': 12*params.goto});
					params.current = params.goto;
					$(parent).stop().scrollTo($(parent).children().eq(params.current),250);
				}
	//			$('body').prepend(params.st+'; ');
			}
		
	});
	return $(this);
}


$.fn.removeImage = function ()
{
	if ($('.imagecontainer').size() == 0) $('body').append('<div class="imagecontainer" />').find('.imagecontainer').hide();
	$(this).hide().appendTo('body .imagecontainer');
}
$.getImage = function (src)
{
	var img = null;
	$('.imagecontainer img').each(function () {
		if ($(this).attr('src') == src ) img = ($(this).attr('loaded') == 1) ? $(this).fadeIn(200) : $(this);
	});
	
	if (!img) img = $('<img />').attr('src',src).hide().load(function () { $(this).attr('loaded',1).fadeIn(200); });
	return img;
}


$(document).ready(function () {
	$.get('list.php',{'new': 1},function (data) {theMachine.build(data);},'json');
});

$(window).resize(function () {
	if (theMachine.built)
	{
		var fromtop = ($(window).height()-$('.container').height())/2;
		$('.container').stop().animate({'opacity':1,'top':fromtop},500);
	}
});


