hasOverlay = false;

jQuery.cookie=function(key,value,options){if(arguments.length>1&&String(value)!=="[object Object]"){options=jQuery.extend({},options);if(value===null||value===undefined){options.expires=-1}if(typeof options.expires==='number'){var days=options.expires,t=options.expires=new Date();t.setDate(t.getDate()+days)}value=String(value);return(document.cookie=[encodeURIComponent(key),'=',options.raw?value:encodeURIComponent(value),options.expires?'; expires='+options.expires.toUTCString():'',options.path?'; path='+options.path:'',options.domain?'; domain='+options.domain:'',options.secure?'; secure':''].join(''))}options=value||{};var result,decode=options.raw?function(s){return s}:decodeURIComponent;return(result=new RegExp('(?:^|; )'+encodeURIComponent(key)+'=([^;]*)').exec(document.cookie))?decode(result[1]):null};

function nextImg() {
	var $active = $('.items img.active');
	
	if( $active.length == 0 ) $active = $('.items img:first');
	
	var $next = $active.next().length ? $active.next() : $('.items img:first');
	
	$active.addClass('last-active');
	$next.addClass('active');
	
	switchImg();
}

function switchImg() {
	$('.items img.last-active')
		.removeClass('active last-active')
		.fadeOut( 500, function() {
			$('.items img.active').fadeIn( 500 )
		})
}	

function prevImg() {
	var $active = $('.items img.active');
	
	if( $active.length == 0 ) $active = $('.items img:first');
	
	var $next = $active.prev().length ? $active.prev() : $('.items img:last');
	
	$active.addClass('last-active');
	$next.addClass('active');
	
	switchImg();
}

$(window).resize(function() {
	if( $('#overlay .items').length != 0 ) {
		$('#overlay .items').css({
			'width': window.innerWidth + 'px',
			'height': window.innerHeight + 'px'
		});
	}
});

$(document).keydown(function(e) {
	var $key = e.keyCode;

	if( $key == 27 ) $('#topnav .searchform').fadeOut( 100 ); 
	
	if( $('#overlay .items').length != 0 ) {
	
		switch( $key ) {
			case 37: prevImg(); break;	// Left arrow
			case 39: nextImg(); break;	// Right arrow
			case 27: closeOverlay(); break; // Escape
		}
	}
	

});

function closeOverlay() {
	$('#overlay').fadeOut(300, function() { $(this).html(''); $('#wrap').fadeIn( 300 ) });
}

function loadRandomPhotographer() {
	$('.cat-random-featured').load('/wp-content/themes/wpjeriko33.4/tp-fotografen-random.php', function() {
		$('.random-link').click( function() {
			loadRandomPhotographer();
		});
	});
}

// ACTUALLY CREATES THE LOUPE IF USER REQUESTS IT
function createLoupe( opacity ) {
	hasOverlay = true; 
	OverlayOpacity = opacity;

	if( jQuery('#loupeoverlay').length >= 1 ) {
		jQuery('#loupeoverlay')
			.animate({ 'opacity': opacity });
	} else {
		jQuery('<div></div>')
			.attr({ 'id' : 'loupeoverlay' })
			.css({ 'opacity': opacity })
			.prependTo('body')
			.fadeIn( 200 );
	}
	
	$('body').addClass('hasLoupe');
}

// RETURNS CURRENT POSITION IN DOCUMENT
function getScrollY() {
    scrOfY = 0;
    if( typeof( window.pageYOffset ) == "number" ) {
        scrOfY = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        scrOfY = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        scrOfY = document.documentElement.scrollTop;
    }
    return scrOfY;
}


jQuery(window).scroll(function() {
	if( jQuery('#loupeoverlay').length != 1 ) return;
	
	// SHOWS OR HIDES OVERLAY BASED ON CURRENT POSITION IN DOCUMENT (BELOW POST => HIDE)
	var offset = jQuery('.full .entry-content img:last').offset();
	var height = jQuery('.full .entry-content img:last').height();
	var scroll = getScrollY();
	
	if( scroll > (offset.top + height - 50 ) && jQuery('#loupeoverlay').length >= 1 ) {
		jQuery('#loupeoverlay').animate(
			{ 'opacity': 0 }, 
			200, 
			function() {
				jQuery('#loupeoverlay').remove()
			}
		);
	} else if( scroll < ( offset.top + height - 50 ) && hasOverlay == true && jQuery('#loupeoverlay').length < 1 ) {
		createLoupe( OverlayOpacity )
	}
});


$(document).ready(function() {

	$('.showsearch').click(function() {
		$('#topnav .searchform').fadeToggle(100).find('#s').focus();
	});
	
	$('#topnav .searchform .search-close').click(function() {
		$('#topnav .searchform').hide();
	});

	$('#header .logo').hover( function() {
		$('#header .logobg').toggleClass('rotate');
	});

	if( $('body.category-337').not('.paged').length > 0 ) loadRandomPhotographer();
	
	if( $('.hentry.full .entry-content img').length >= 3 ) $('<li></li>').attr('id', 'link-overlay').html('<a>Slideshow (' + $('.hentry.full .entry-content img').length + ' Fotos)</a>').appendTo('#header-meta');


	$('.menulink').click(function() {
		$(this).toggleClass('active');
		$('.small ul').toggleClass('active');
	});
	
	if( $.cookie( 'newsfilter' ) != null ) {
		$('article.news').removeClass('news-compact news-full').addClass( $.cookie( 'newsfilter' ) );
		$('#news-filter input').attr( 'checked', false );
		$('#' + $.cookie( 'newsfilter' )).attr( 'checked', true );
	}
		
	$('#news-filter input').click(function() {
		$('article.news').removeClass('news-compact news-full').addClass( $(this).attr('id') );
		$.cookie( "newsfilter", $(this).attr('id') );
	});
	
	$('#link-overlay').click(function() {
		// Create Close Button
		$('<a>')
			.addClass('overlay-close')
			.attr('href','#')
			.html('x')
			.click(function() { closeOverlay() } )
			.prependTo('#overlay');
		
		// Create controls
		$('<a>')
			.addClass('overlay-next overlay-control')
			.attr('href','#')
			.html('&#9654;')
			.click( function() { nextImg() } )
			.appendTo('#overlay');
		$('<a>')
			.addClass('overlay-prev overlay-control')
			.attr('href','#')
			.html('&#9664')
			.click( function() { prevImg() } )
			.prependTo('#overlay');
			
		// Create title
		$('<h2>')
			.html( $('.hentry .entry-title').html() )
			.appendTo('#overlay');
			
		var items = $('<div>')
			.css({
				'width': window.innerWidth + 'px',
				'height': window.innerHeight + 'px'
			})
			.addClass('items');
			
		// Insert every image from post content
		$('.hentry.full .entry-content img').each(function() {
			img = $('<img>')
				.attr( 'src', $(this).attr('src') )
				.click( function() { nextImg() } )
				.appendTo( items );
		});
	
		$('#overlay').append( items );
			
		$('#wrap').fadeOut( 300, function() { $('#overlay').css('width', $(window).width()).fadeIn( 300 ) });
	});
	
	
	
	
	// SHOW LOUPE IF THERE IS AN IMAGE IN THE POST
	/*if( jQuery('.hentry.full .entry-content img').length >= 1  ) {
		jQuery('<div></div>').attr({
			'id' : 'loupe'
		})
		.append('<div class="light"></div><div class="grey"></div><div class="dark"></div>')
		.prependTo('body');
	}
	
	jQuery('#loupe .grey').click(function() { createLoupe( 0.8 ); });
	jQuery('#loupe .dark').click(function() { createLoupe( 1 ); });
	jQuery('#loupe .light').click(function() {
		hasOverlay = false;
		
		if( jQuery('#loupeoverlay').length >= 1 ) {
			jQuery('#loupeoverlay').animate(
				{ 'opacity': 0 }, 
				200, 
				function() {
					jQuery('#loupeoverlay').remove()
				}
			);
			
		}
		
		$('body').removeClass('hasLoupe');
	});*/
	
});
