/**
 * maxon jQuery JavaScript
 *
 * @since 36
 * @require jQuery 1.3
 */

/**
 * Document ready
 *
 * @since 36
 * @require jQuery 1.3
 */
$(document).ready(function(){
	
	/**
	 * Closable filedsets
	 * @since 64
	 */
	$('fieldset.closable').each(function(){
		if ( 0 <= $( '.closable_content', this ).size() )
		{
			$( '> :not(legend, .closable_content)', this ).wrapAll(
				'<div class="closable_content"></div>'
			);
		}
		$('> legend', this ).click(function(){
			$( '.closable_content', $(this).parent() ).slideToggle();
		});
		if ( $(this).hasClass( 'closed' ) )
		{
			$( '.closable_content', this ).hide();
		}
	});

	var $img = $('body.gallery .center img');
	var $W = $img.parent();
	var $prev = $('body.gallery .center .galery-nav-prev');
	var $next = $('body.gallery .center .galery-nav-next');
	var $title = $('body.gallery .center .galery-image-title');
	var RegExp = Url.base.replace( /\//, '\/' );
	$('body.gallery .center .galery-nav').click(function(){
		$img.fadeOut();
		$('body.gallery .center .galery-image-title').fadeOut();
		$('body.gallery .center .galery-nav').fadeOut();
		var newHash = $('.galery-nav-next').attr('href').replace( document.location.pathname.replace( /\//, '\/' ), '' );
		$.getJSON(
			$(this).attr('href').replace( RegExp, Url.base + '/json' ),
			function( d ){
				var img = new Image();
				img.src = d.imagePath;
				img.alt = d.imageTitle;
				img.title = d.imageTitle;
				$prev.attr( 'href', d.prevPath );
				$next.attr( 'href', d.nextPath );
				$title.html( d.imageTitle );

				function pollLoadState()
				{
					if ( img.complete )
					{
						if ( $img.src != img.src )
						{
							$img.replaceWith( $(img).hide() );
							$img = $('body.gallery .center img');
							$img.fadeIn();
							$('body.gallery .center .galery-nav').fadeIn();
							$('body.gallery .center .galery-image-title').fadeIn();
							document.location.hash = newHash;
						}
					}
					else
					{
						window.setTimeout(pollLoadState, 2000);
					}
				}
				pollLoadState();
			}
		);
		return false;
	});

	if ( document.location.hash.match( /^#/ ) )
	{
		$.getJSON(
			document.location.href.replace( /#/, '' ),
			function( d )
			{
				if( d.imagePath && d.imageTitle )
				{
					$img.replaceWith( $img.clone().attr({
						src: d.imagePath,
						alt: d.imageTitle,
						title: d.imageTitle
					}));
					$img = $('body.gallery .center img');
					$prev.attr( 'href', d.prevPath );
					$next.attr( 'href', d.nextPath );
					$title.html( d.imageTitle );
				}
			}	
		);
	}
});

/* end */
