function call(operation, dataType, parameters, callback) {
	$.ajax({
		type : 'POST',
		url : 'inc/ajax_ops/' + operation + '.php',
		data : parameters,
		dataType : dataType,
		success : function(data) {
			if (callback != undefined) {
				callback(data);
			}
		}
	});
}

function resizeImages(container)
{
	offset = container.offset();
	ctop = offset.top;
	cleft = offset.left;

	totalHeight = $(window).height();
	totalWidth = $(window).width();

	availableHeight = totalHeight - ctop;
	availableWidth = totalWidth - cleft;

	$('img', $(container)).each(function(index, element) {
		$(element).css('max-width',availableWidth);
		$(element).css('max-height',availableHeight);
	});
}

function resizeImage(image, marginBottom, marginRight)
{
	if (image.is(':visible'))
	{
		var mb = marginBottom != undefined ? marginBottom : 0;
		var mr = marginRight != undefined ? marginRight : 0;

		var _offset = image.offset();
		var ctop = _offset.top;
		var cleft = _offset.left;

		var totalHeight = $(window).height();
		var totalWidth = $(window).width();

		var availableHeight = totalHeight - ctop - mb;
		var availableWidth = totalWidth - cleft - mr;

		$(image).css('max-width',availableWidth);
		$(image).css('max-height',availableHeight);
	}
}

function startSlideshow() {
	$('#language_dependent_container').hide();
	$('#info_container').hide();
	$('#gallery_container').hide();
	$('#slideshow_container').hide();

	call('get_slideshow_images', 'html', {}, function(html) {
		slideshow = $('#slideshow_container');
		slideshow.html(html);
		slideshow.children('img').fadeTo('0').end;
		slideshow.show();
		resizeImages(slideshow);
		slideSwitch();
		slideshowTimer = setInterval( "slideSwitch()", 4000 );
		$('img').mousedown(function(e) { e.preventDefault(); });
		$(window).resize(function() {
			resizeImages(slideshow);
		});
	});
}

function stopSlideshow(callback) {
	if (typeof (slideshowTimer) != undefined) {
		clearInterval(slideshowTimer);
		$('#slideshow_container').fadeOut('fast', function() {
			$('#slideshow_container').children().remove();
			callback();
		});
	} else {
		callback();
	}
}

var slideshowTimer;

function slideSwitch() {

    var $active = $('#slideshow_container IMG.active');

    var fadeOutLast = true;

    if ( $active.length == 0 )
	{
	    $active = $('#slideshow_container IMG:last');
	    fadeOutLast = false;
	}

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow_container IMG:first');

    if ($('#slideshow_container IMG:first').is(':last') && $next.css('opacity') > 0)
	{
    	return;
	}

    if (fadeOutLast)
	{
	    $active.addClass('last-active');
	    $active.css({opacity: 1.0})
		.animate({opacity: 0.0}, 2000);
	}

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 2000 , function() {
            $active.removeClass('active last-active');
        });
}

//function slideSwitch() {
//	call('get_random_image', 'html', {}, function(html) {
//		slideshow = $('#slideshow_container');
//		slideshow.append(html);
//
//	    var $active = $('#slideshow_container IMG.active');
//
//	    if ( $active.length == 0 ) $active = $('#slideshow_container IMG:last');
//
//	    var $next =  $active.next().length ? $active.next()
//	        : $('#slideshow_container IMG:first');
//
//	    $active.addClass('last-active');
//
//	    $next.css({opacity: 0.0})
//	        .addClass('active')
//	        .animate({opacity: 1.0}, 1000, function() {
//	    		slideshow.children().not('.active').remove();
//	            $active.removeClass('active last-active');
//	        });
//	});
//}

function setLanguage(langElement) {
	call('set_language', 'json', {
		lang : langElement.id
	}, function(json) {
		$('.lang_selected').removeClass('lang_selected');
		$(langElement).addClass('lang_selected');
		$('#language_dependent_container').fadeOut('fast', function() {
			$('.selected').removeClass('selected');
			loadCategories();

			if (langElement.id == 'english') {
				$('#bio').html('bio');
				$('#contact').html('contact');
				$('#portfolio_link').html('Download portfolio PDF');
			} else {
				$('#bio').html('bio');
				$('#contact').html('kontakt');
				$('#portfolio_link').html('Portfolio als PDF');
			}
		}).fadeIn();
	});
}

/**
 * get all categories and create the accordion
 *
 * @param container
 *            (category container)
 * @param callback
 *            (arbitrary callback function)
 */
function loadCategories() {
	call('get_categories', 'html', {}, function(html) {
		stopSlideshow(function() {
			$('#slideshow_container').hide();
			$('#info_container').hide();
			$('#gallery_container').fadeOut('fast', function() {
				container = $("#categories");
				container.html(html);
				container.accordion('destroy');
				container.accordion({
					header : 'div.menu_item',
					active : false,
					fillSpace : false,
					autoHeight : false,
					collapsible: true,
					changestart : function(event, ui) {

						if (ui.newContent.length == 0)
						{
							return; // is collapsing
						}

						if (ui.newContent.children().size() == 0) {
							selectAlbum(ui.newHeader);
							return;
						}

						$('.selected').removeClass('selected');
						$(ui.newHeader).addClass('selected');

						var albums = $(ui.newContent).find('.sub_menu_item');

						albums.click(function(event) {
							selectAlbum(event.target);
						});

						albums.first().trigger('click');
					}
				});
				container.children('div.menu_item').each( function(index, element) {
					if ($(element).next().children().size() == 0)
					{
						index = container.children('div.menu_item').index($(element));
						$(element).click(function(event) {
							$("#categories").accordion('activate', index);
						});
					}
				});

				$("#categories").accordion("option", "active", 0);
			});
		});
	});
}

/**
 * selects sub-category, i.e. marks it with 'selected' and populates the gallery
 *
 * @param category
 */
function selectAlbum(category) {
	stopSlideshow(function() {
		$('#slideshow_container').hide();
		$('#info_container').hide();
		$('.selected').removeClass('selected');
		$(category).addClass('selected');
		$(category).parent('.category_sub_menu').prev().addClass('selected');
		$('#gallery_container').hide();

		id = $(category).attr('id');

		call('get_gallery', 'html', {
			album_id : id
		}, function(html) {
//			$('#gallery_container').fadeOut('fast', function() {

				$('#gallery_container').html(html);

				$('a',$('ul.thumbs')).each(function (index, element) {
					$(element).bind('click', function(event) {
						if (event.preventDefault)
						{
							event.preventDefault();
						}
						else
						{
							event.returnValue = false;
						}
					});
				});

				images = $('img',$('ul.thumbs'));
				toLoad = images.size();

				images.load(function () {
					toLoad--;
					if (toLoad == 0)
					{
						if ($('#gallery_overview').children('ul').children().size() > 0) {

							var onMouseOutOpacity = 0.67;

							$('#gallery_overview ul.thumbs li').opacityrollover({
								mouseOutOpacity:   onMouseOutOpacity,
								mouseOverOpacity:  1.0,
								fadeSpeed:         'fast',
								exemptionSelector: '.selected'
							});

							$('#gallery_container').show();

							$('#gallery_overview').galleriffic({
						        delay:                     1000, // in milliseconds
						        numThumbs:                 200, // The number of thumbnails to show page
						        preloadAhead:              -1, // Set to -1 to preload all images
						        enableTopPager:            false,
						        enableBottomPager:         false,
						        maxPagesToShow:            0,  // The maximum number of pages to display in either the top or bottom pager
						        imageContainerSel:         '#viewport', // The CSS selector for the element within which the main slideshow image should be rendered
						        controlsContainerSel:      '', // The CSS selector for the element within which the slideshow controls should be rendered
						        captionContainerSel:       '#comment', // The CSS selector for the element within which the captions should be rendered
						        loadingContainerSel:       '', // The CSS selector for the element within which should be shown when an image is loading
						        renderSSControls:          true, // Specifies whether the slideshow's Play and Pause links should be rendered
						        renderNavControls:         true, // Specifies whether the slideshow's Next and Previous links should be rendered
						        playLinkText:              'Play',
						        pauseLinkText:             'Pause',
						        prevLinkText:              'Previous',
						        nextLinkText:              'Next',
						        nextPageLinkText:          'Next &rsaquo;',
						        prevPageLinkText:          '&lsaquo; Prev',
						        enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
						        enableKeyboardNavigation:  true, // Specifies whether keyboard navigation is enabled
						        autoStart:                 false, // Specifies whether the slideshow should be playing or paused when the page first loads
						        syncTransitions:           true, // Specifies whether the out and in transitions occur simultaneously or distinctly
						        defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
								onSlideChange:             function(prevIndex, nextIndex) {
									// 'this' refers to the gallery, which is an extension of $('#thumbs')
									prev = this.find('ul.thumbs').children().eq(prevIndex);
									prev.fadeTo('fast', onMouseOutOpacity).end();
									prev.children('a').children('span').remove();

									next = this.find('ul.thumbs').children().eq(nextIndex);
									next.fadeTo('fast', 1.0).end();

									current = this.find('ul.thumbs').children().eq(nextIndex);
									nextImg = $('img', $(current));
									var w = nextImg.width() - 4;
						            var h = nextImg.height() - 4;
						            border = $('<span id="thumbnail_border" style="border: 2px solid red; position: absolute; top: 0px; left: 0px; width: '+w+'px; height: '+h+'px;"></span>');
									border.fadeTo('fast', 0.0).end();
									current.children('a').append(border);
									border.offset(nextImg.offset());
									border.fadeTo('fast', 0.8);

//									$('#viewport_container').width(current.attr('width'));
//									alert(current.attr('width')+", "+current.attr('height'));
								},
								onTransitionIn: function(slide, caption, isSync, callback) {
									slide.fadeTo(1000, 1.0);
									if (caption)
										caption.fadeTo(1000, 1.0);

									image = $('img',$(slide));

									resizeImage(image, 30);
									$('#viewport_container').height(image.attr('offsetHeight'));
								}
						    });

						}
					}
				});

				if ($.browser.msie)
				{
					//TODO ?
				}
				else
				{
					$(window).resize(function() {
						image = $('img',$('#viewport_container'));
						resizeImage(image, 30);
						$('#viewport_container').height(image.attr('offsetHeight'));
					});
				}
//			});
		});
	});
}

/**
 * loads the selected text into #gallery_container
 *
 * @param type
 */
function loadText(type) {

	id = $(type).attr('id');

	call('get_text', 'html', {
		id : id
	}, function(html) {
		$('#categories').accordion("activate", false);
		$('.selected').removeClass('selected');
		$(type).addClass('selected');
		$('#slideshow_container').hide();
		$('#gallery_container').hide();
		$('#info_container').hide().html(html).fadeIn('slow');
	});
}
