//Supersize function
(function($){
    //Resize image on ready or resize
    $.fn.supersize = function() {  
        //Invoke the resizenow() function on document ready
        $(document).ready(function() {
            $('.supersize').resizenow();
        });
        //Invoke the resizenow() function on browser resize
        $(window).bind("resize", function() {
            $('.supersize').resizenow();
        });
    };
    //Adjust image size
    $.fn.resizenow = function() {
        //Define starting width and height values for the original image
        var startwidth = 665;  
        var startheight = 500;
        //Define image ratio
        var ratio = startheight/startwidth;
        //Gather browser dimensions
		var browserwidth;
        var browserheight;
		
		// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		if (typeof window.innerWidth != 'undefined')
		{
			browserwidth = window.innerWidth; //дndra till , pе fцrsta om det bцrjar brеka
			browserheight = window.innerHeight;
		}
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0)
		{
			browserwidth = document.documentElement.clientWidth;
			browserheight = document.documentElement.clientHeight;
		}
		// older versions of IE
		else
		{
			browserwidth = document.getElementsByTagName('body')[0].clientWidth;
			browserheight = document.getElementsByTagName('body')[0].clientHeight;
		}
		
		//Resize image to proper ratio
        if ((browserheight/browserwidth) > ratio) {
            $(this).height(browserheight);
            $(this).width(browserheight / ratio);
            $(this).children().height(browserheight);
            $(this).children().width(browserheight / ratio);
        } else {
            $(this).width(browserwidth);
            $(this).height(browserwidth * ratio);
            $(this).children().width(browserwidth);
            $(this).children().height(browserwidth * ratio);
        }
        //Make sure the image stays center in the window
        $(this).children().css('left', (browserwidth - $(this).width())/2);
        $(this).children().css('top', (browserheight - $(this).height())/2);
    };
})(jQuery);


// Set up the SimpleSlide function
jQuery.fn.simpleSlide = function(a){
	a				= a || {};
	a.duration		= a.duration || 5000;
	a.transition	= a.transition || 1500;
	var	c = $(this);
	$(this).css("position","relative");
	$(".slider",$(c));	
	$(this).find(".slide:first").addClass("slide-active").css({'z-index':'10'});
	
	runSlide = setInterval(function(){	
		var $active = $(".slide.slide-active");
		if ( $active.next('.slide').length != 0 ) {
			var $next = $active.next('.slide');
		} else {
			var $next = $(".slide:first")
		}
		$active.addClass("slide-last-active").css({'z-index':'9'});		
		if ( $.browser.msie ) {
			$next.addClass("slide-active").css({'z-index':'10'});
			$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
	   	} else {
			$next.css({opacity: 0.0}).addClass("slide-active").css({'z-index':'10'}).animate({opacity: 1.0}, a.transition, function(){
				$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
			});
		}
	}, a.duration);	
	
	$('.next').click(function(){			
		clearInterval(runSlide);		
		var $active = $(".slide.slide-active");				
		if ($active.next('.slide').length != 0) {
			var $next = $active.next('.slide');
		} else {
			var $next = $(".slide:first");
		}
		$active.addClass("slide-last-active").css({'z-index':'9'});
		if ( $.browser.msie ) {
			$next.addClass("slide-active").css({'z-index':'10'});
			$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
		} else { 
			$next.css({opacity: 0.0}).addClass("slide-active").css('z-index','10').animate({opacity: 1.0}, 300, function(){
				$active.removeClass('slide-active slide-last-active').css('z-index','8');
				runSlide = setInterval(function(){	
					var $active = $(".slide.slide-active");
					if ( $active.next('.slide').length != 0 ) {
						var $next = $active.next('.slide');
					} else {
						var $next = $(".slide:first")
					}
					$active.addClass("slide-last-active").css({'z-index':'9'});		
					if ( $.browser.msie ) {
						$next.addClass("slide-active").css({'z-index':'10'});
						$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
					} else {
						$next.css({opacity: 0.0}).addClass("slide-active").css({'z-index':'10'}).animate({opacity: 1.0}, a.transition, function(){
							$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
						});
					}
				}, a.duration);	
			});
		}
	});
	
	$('.prev').click(function(){			
		clearInterval(runSlide);		
		var $active = $(".slide.slide-active");			
		if ($active.prev('.slide').length != 0) {
			var $next = $active.prev('.slide');
		} else {
			var $next = $(".slide:last");
		}
		$active.addClass("slide-last-active").css({'z-index':'9'});
		if ( $.browser.msie ) {
			$next.addClass("slide-active").css({'z-index':'10'});
			$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
		} else { 
			$next.css({opacity: 0.0}).addClass("slide-active").css('z-index','10').animate({opacity: 1.0}, 300, function(){
				$active.removeClass('slide-active slide-last-active').css('z-index','8');
				runSlide = setInterval(function(){	
					var $active = $(".slide.slide-active");
					if ( $active.next('.slide').length != 0 ) {
						var $next = $active.next('.slide');
					} else {
						var $next = $(".slide:first")
					}
					$active.addClass("slide-last-active").css({'z-index':'9'});		
					if ( $.browser.msie ) {
						$next.addClass("slide-active").css({'z-index':'10'});
						$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
					} else {
						$next.css({opacity: 0.0}).addClass("slide-active").css({'z-index':'10'}).animate({opacity: 1.0}, a.transition, function(){
							$active.removeClass('slide-active slide-last-active').css({'z-index':'8'});
						});
					}
				}, a.duration);	
			});
		}
	});

};

/**
 * jQuery.Preload - Multifunctional preloader
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/25/2009
 * @author Ariel Flesler
 * @version 1.0.8
 */
;(function($){var h=$.preload=function(c,d){if(c.split)c=$(c);d=$.extend({},h.defaults,d);var f=$.map(c,function(a){if(!a)return;if(a.split)return d.base+a+d.ext;var b=a.src||a.href;if(typeof d.placeholder=='string'&&a.src)a.src=d.placeholder;if(b&&d.find)b=b.replace(d.find,d.replace);return b||null}),data={loaded:0,failed:0,next:0,done:0,total:f.length};if(!data.total)return finish();var g=$(Array(d.threshold+1).join('<img/>')).load(handler).error(handler).bind('abort',handler).each(fetch);function handler(e){data.element=this;data.found=e.type=='load';data.image=this.src;data.index=this.index;var a=data.original=c[this.index];data[data.found?'loaded':'failed']++;data.done++;if(d.enforceCache)h.cache.push($('<img/>').attr('src',data.image)[0]);if(d.placeholder&&a.src)a.src=data.found?data.image:d.notFound||a.src;if(d.onComplete)d.onComplete(data);if(data.done<data.total)fetch(0,this);else{if(g&&g.unbind)g.unbind('load').unbind('error').unbind('abort');g=null;finish()}};function fetch(i,a,b){if(a.attachEvent&&data.next&&data.next%h.gap==0&&!b){setTimeout(function(){fetch(i,a,1)},0);return!1}if(data.next==data.total)return!1;a.index=data.next;a.src=f[data.next++];if(d.onRequest){data.index=a.index;data.element=a;data.image=a.src;data.original=c[data.next-1];d.onRequest(data)}};function finish(){if(d.onFinish)d.onFinish(data)}};h.gap=14;h.cache=[];h.defaults={threshold:2,base:'',ext:'',replace:''};$.fn.preload=function(a){h(this,a);return this}})(jQuery);

	
$('h4.share').live('click', function() {
	obj = $(this).parents('.postShare');
	obj.children('.shareLinks').slideToggle();
	if(!obj.hasClass('closed')){
		obj.addClass('closed');	
	} else {
		obj.removeClass('closed');	
	}
	return false;
});
				
//close
$('#fullscreen #close').live('click', function() {
	$('body').removeClass('fullscreen');
	var currSrc = $('#currentSlide img').attr('src');
	$('#fullscreen').remove();
	$('#wrapper').css({'display':'',margin:''});
	var imgPos = $('body').find('a[href="'+currSrc+'"]').offset();
	$('html, body').scrollTop(imgPos.top-120);
});


// Fullscreen Gallery Function
fsGallery = function() {	
	var currImg = $('#fullscreen #currentSlide img').attr('src');			
	var currImgLink = $('#inspiration').find('a[href="'+currImg+'"]');		
	var infoTxtCat = currImgLink.parents('.entry').siblings('.postHeading').find('h1 .cat').text();
	var infoTxtClient = currImgLink.parents('.entry').siblings('.postHeading').find('h1 .client').text();
	$('#fullscreen #fsInfo').empty().append('<strong>'+infoTxtCat+'</strong>'+infoTxtClient);	
	
	// Get next image link in same post
	if ( currImgLink.next('a').length != 0 ) {
		var nextImgURL = currImgLink.next('a').attr('href');
	// If there's no more images in current post get the first image from the next post
	} else if ( currImgLink.parents('.post').nextAll('.post:first').find('.postGallery').children('a').length != 0 ) {
		var nextImgURL = currImgLink.parents('.post').nextAll('.post:first').removeClass('thumbs').addClass('list').find('.postGallery').children('a').attr('href');	
		currImgLink.parents('.post').nextAll('.post:first').removeClass('thumbs').addClass('list').find('.postGallery').children('a img').css({width: '665px',height: '500px'});	
		var postInfoHeight = (500*(currImgLink.parents('.post').nextAll('.post:first').find('.postGallery').find('a img').length)-15);							
		currImgLink.parents('.post').nextAll('.post:first').find('.postInfo').removeClass('shortend').css({height:postInfoHeight,overflow:'',margin:''});
		if ( currImgLink.parents('.post').nextAll('.post:first').find('.postGallery a img').length != 1 ) {
			currImgLink.parents('.post').nextAll('.post:first').find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
		}
		
	// If no more posts in DOM, load more with Infitie Scroll then re-run get the next image
	} else if ( $('#navigation .alignleft a').length != 0 ) {
		$(document).trigger('retrieve.infscr');
		
		function delayedAlert() {
		  timeoutID = window.setTimeout(slowAlert, 2000);
		}
		
		function slowAlert() {
			if ( currImgLink.parents('.post').nextAll('.post:first').find('.postGallery').children('a').length != 0 ) {
				var nextImgURL = currImgLink.parents('.post').nextAll('.post:first').removeClass('thumbs').addClass('list').find('.postGallery').children('a').attr('href');
				if ( currImgLink.parents('.post').find('.postGallery a img').length != 1 ) {
					currImgLink.parents('.post').nextAll('.post:first').find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
				}
			} else {	
				var nextImgURL = "none";
			}
			clearAlert();
		}
		
		function clearAlert() {
		  window.clearTimeout(timeoutID);
		}
		
	} else {	
		var nextImgURL = "none";
	}
	
	if ( currImgLink.prev('a').length != 0 ) {
		var prevImgURL = currImgLink.prev('a').attr('href');
	} else if ( currImgLink.parents('.post').prevAll('.post:first').find('.postGallery').children('a').length != 0 ) {
		var prevImgURL = currImgLink.parents('.post').prevAll('.post:first').removeClass('thumbs').addClass('list').find('.postGallery').children('a:last').attr('href');
		if ( currImgLink.parents('.post').find('.postGallery a img').length != 1 ) {
			currImgLink.parents('.post').nextAll('.post:first').find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
		}
	} else {
		var prevImgURL = "none";			
	}						
	if ( prevImgURL != "none" ) {
		$('#fullscreen').prepend('<div id="leftArea">&nbsp;</div>');
		$('#leftArea').addClass('stop');
		$('#fullscreen #prevSlide').css({'background':''});
		$('#fullscreen #prevSlide img').css({opacity:0}).attr('src', prevImgURL);	
		$('#fullscreen #prevSlide img').preload({
			onFinish: function(){
				$('#fullscreen #prevSlide img').animate({opacity: 1.0});
				$('#fullscreen #prevSlide').css({'background':'none'});
				$('#leftArea').removeClass('stop');
			}
    	});
	} else {
		$('#fullscreen #leftArea').remove();		
	}
	
	if ( nextImgURL != "none" ) {
		$('#fullscreen').prepend('<div id="rightArea">&nbsp;</div>');
		$('#rightArea').addClass('stop');
		$('#fullscreen #nextSlide').css({'background':''});
		$('#fullscreen #nextSlide img').css({opacity:0}).attr('src', nextImgURL);
		$('#fullscreen #nextSlide img').preload({
			onFinish: function(){
				$('#fullscreen #nextSlide img').animate({opacity: 1.0});
				$('#fullscreen #nextSlide').css({'background':'none'});
				$('#rightArea').removeClass('stop');
			}
    	});
	} else {
		$('#fullscreen #rightArea').remove();		
	}				
	
	$(".supersize").supersize();
	
	var atm = ( ( $(window).height() - 28 ) / 2 );
	
	$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:0});	
	$('#fullscreen #prevSlide .supersize').css({marginLeft:-$(window).width(),opacity:0});
	
	$(window).bind("resize", function() {
		var atm = ( ( $(window).height() - 28 ) / 2 );
		$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:0});	
		$('#fullscreen #prevSlide .supersize').css({marginLeft:-$(window).width(),opacity:0});
	});				
}

postsLoaded = function() {
	
	if ( !$('#inspiration').hasClass('single') ) {
		$('.post.last').removeClass('last');
		$(".post:odd").addClass('odd');						   
		$('.post:last').addClass('last');
		$('.shareLinks').hide();
		$('.postGallery').each(function(i) {
			if ( $(this).parents('.post').find('.postGallery a img').length < 5) {
				$(this).siblings('.postInfo').addClass('shortend').css({height:'120px',overflow:'hidden'});
			}
		});
	} else {
		var postInfoHeight = (509*($('.postGallery').find('a img').length)-15);							
		$('.postInfo').removeClass('shortend').css({height:postInfoHeight,overflow:'',margin:''});		
	}
	
	$('.count').each(function(i){
		if ( (i+1)==9 ) {
			$(this).empty().append('Ex 00'+(i+1)+'.');
		} else if ( (i+1)>9 ) {
			$(this).empty().append('Ex 0'+(i+1)+'.');
		} else if ((i+1)<9) {
			$(this).empty().append('Ex 00'+(i+1)+'.');
		} else {
			$(this).empty().append('Ex '+(i+1)+'.');			
		}
	});
	
	if (!$.browser.msie) {
		$(".thumbs .postGallery a img").lazyload({
			placeholder : "",
			effect : "fadeIn"		 
		});
	}
}

$(document).ready(function() {
	
	if ( $('#catMenu').length != 0 ) {
		$(window).scroll(function() {
			if($(this).scrollTop() < 250) {
				$('#nav').css({marginBottom:''});
				$('#catMenu').css({'position':'','top':'','left':'',marginLeft:'','z-index':'','border-bottom':''});
			} else {
				$('#nav').css({marginBottom:''});
				$('#catMenu').css({'position':'fixed','top':'-30px','left':'',marginLeft:'','z-index':100000,'border-bottom':''});
			}
		});
	}
	
	if ( ($('#catMenu').length != 0) && ( !$('#inspiration').hasClass('single') ) ) {
		
		if (/\/en\//.test(window.location)) {
    		$('#catMenu').append('');;
		} else {		
			$('#catMenu').append('');
		}
		
	} else {
		var post = $('#inspiration').find('.post');
		if ( post.find('.postGallery a img').length != 1 ) {
			post.find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
		}
	}
	
	$(".kontakt h3:first").addClass("first");
	$(".kontakt .column2 h3:first").addClass("first");
	$(".kontakt ul li:nth-child(4)").addClass("fourth");
	$(".column1 ul:first-child").addClass("first");
	$("li:first-child").addClass("first");								
	$("li:last-child, p:last-child").addClass("last");		
	$(".col h3").next('ul').addClass("first");
		
	if ( $(".slider").length != 0 ) {	
		$(".slider").each(function(i) {			
			$(this).addClass("slider"+i);    
			$(".slider"+i).css({opacity:0});			
			$(".slider"+i+ " .slide img").preload({
				onFinish: function(){
					$(".slider"+i).animate({opacity: 1.0});
					if ( $('.slider'+i+' .slide').length > 1 ) {
						// Run the SimpleSlide
						$(".slider"+i).simpleSlide();
						$(".slider"+i).bind("mouseenter",function(){		
							$(this).children(".next").css({'display' : 'block'});		
							$(this).children(".prev").css({'display' : 'block'});		
						}).bind("mouseleave",function(){		
							$(this).children(".next").css({'display' : 'none'});		
							$(this).children(".prev").css({'display' : 'none'});	
						});
					}
				}
			}); 	
		});		
	}
	
	$(".column1 ul").bind("mouseenter",function(){
		if ( $(this).find('a').attr('href') ) {
			href = $(this).find('a').attr('href');
			name = href.replace('mailto:', "").replace('@gbgt.se', "").replace('.', "").replace('.', "");
		} else {
			var text = $(this).find('strong').text();
			name = text.replace("е", "a").replace("д", "a").replace("ц", "o").replace("Е", "A").replace("Д", "A").replace("Ц", "O").toLowerCase();
			name = name.replace(/[^a-zA-Z0-9]+/g, "");
		}
		
		if ( $('#portratt img.'+name).length != 0 ) {
			ulOffset = $(this).offset();
			column2Offset = $(this).parents('.column1').siblings('.column2').offset();
			if ( $('#portratt img.'+name).length > 0 ) {
				if ($.browser.msie) {
					$('.column2').css({opacity:0});
				} else {
					$('.column2').css({opacity:0.3});				
				}
				$('#portratt').css({'display':'block',opacity:1,marginTop:ulOffset.top,marginLeft:column2Offset.left});
				$('#portratt img').css({'display':'none'});
				$('#portratt img.'+name).css({'display':'block'});
			}
		}
	}).bind("mouseleave",function(){
		$('.column2').css({opacity:1});
		if($.browser.msie){
			$('.column2').get(0).style.removeAttribute('filter');
		}	
		$('#portratt img').css({'display':'none'});		
		$('#portratt').css({'display':'none'});	
	});
	
	if ( $('a.click-here').length != 0 ) {
		$('a.click-here').live('click', function() {
			$(this).hide();
			$(this).siblings('a').show();
			return false;
		});
	}
	
	if ( $('#teasers').length != 0 ) {
	
		$("#teasers .col").bind("mouseenter",function(){
			$(this).css({opacity:1});
			if(!$(this).hasClass('active')){
				$(this).addClass('active');	
			}
			$(".archive .heading, .archive #teasers .col:not(.active)").css({opacity:0.3});
			$(".avdelningar, .bp-kontakt, .bd-kontakt").css({opacity:0.3});
			$(this).parents('.section.top').children('.heading');
		}).bind("mouseleave",function(){
			$(".archive .heading, .archive #teasers .col").css({opacity:''});
			$(".avdelningar, .bp-kontakt, .bd-kontakt").css({opacity:''});
			$(this).parents('.section.top').children('.heading');
			$(this).removeClass('active');		
		});
	
	}
	
	postsLoaded();
	
	
	// Gallery functions
	// & clicks et c
	
	if ( $('#inspiration').length ) {
		
		$('#gallery').bind('click', function() {
			$('#list, #fs').removeClass('active');
			$('.enlarge, .shareImg, .shareImgCover, .shareImgLinks, .closeShare').remove();
			$(this).addClass('active');
			var post = $('.post');
			$('.list .postGallery a').css({'clear':''});		
			$('.list .postGallery a img').css({'clear':''});
			$('.list .postGallery a img').each(function(i) {
				if ( (i+1) == $('.list .postGallery a img').length ) {
					$(this).animate({
						opacity:0,
						width: '205px',
						height: '150px'
					}, 600, function() {
						$(this).animate({opacity:1}, 400, function() {});
						var navPos = $('#nav').offset();
						$('html, body').scrollTop((navPos.top+($('#nav').height())));
						post.removeClass('list');
						post.addClass('thumbs');
						post.each(function(i) {
							if ( $(this).find('.list .postGallery a img').length < 5 ) {
								$(this).find('.postInfo').addClass('shortend').css({height:'120px',overflow:'hidden'});					
							}
						});
					});
				} else {
					$(this).animate({
						opacity:0,
						width: '205px',
						height: '150px'
					}, 600, function() {
						$(this).animate({opacity:1}, 400, function() {});
					});
				}
			});
		});
		
		$('#list').bind('click', function() {
			$('#gallery, #fs').removeClass('active');
			$(this).addClass('active');
			var post = $('.post');			
			$('.thumbs .postGallery a img').each(function(i) {
				if ( (i+1) == $('.thumbs .postGallery a img').length ) {	
					$(this).animate({
						opacity:0
					}, 400, function() {
						$(this).parent('a').css({'clear':'both'});
						var navPos = $('#nav').offset();
						$('html, body').scrollTop((navPos.top+($('#nav').height())));
						$(this).css({'clear':'both'}).animate({
							opacity:1,
							width: '665px',
							height: '500px'
						}, 600, function() {
							$(this).css({'clear':''});
							post.removeClass('thumbs');
							post.addClass('list');
							$('.post').each(function(i) {
								var postInfoHeight = (509*($(this).find('.postGallery').find('a img').length)-15);							
								$(this).find('.postInfo').removeClass('shortend').css({height:postInfoHeight,overflow:'',margin:''});
								if ( $(this).find('.postGallery a img').length != 1 ) {
									$(this).find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
								}
							});
						});	
					});					
				} else {
					$(this).animate({
						opacity:0
					}, 400, function() {
						$(this).parent('a').css({'clear':'both'});
						$(this).css({'clear':'both'}).animate({
							opacity:1,
							width: '665px',
							height: '500px'
						}, 600, function() {
							$(this).css({'clear':''});
						});	
					});			
				}
			});
		});
		
		$('#fs').bind('click', function() {
		// Load Fullscreen			
			if (!$('body').hasClass('fullscreen')) {				
				$('html, body').scrollTop(0);
				var imgURL = $('#inspiration .postGallery:first a:first').attr('href');
				$('body').addClass('fullscreen').prepend('<div id="fullscreen"><div id="fsInfo"></div><div id="symbol"></div><div id="close">Выход из полноэкранного режима [ esc ]</div><div id="prevBtn"></div><div id="nextBtn"></div><div id="currentSlide"><span class="supersize"><img src="" width="665" height="500"></span></div><div id="prevSlide"><span class="supersize"><img src="" width="665" height="500"></span></div><div id="nextSlide"><span class="supersize"><img src="" width="665" height="500"></span></div></div>');
				if ( $.cookie("fullscreen-first") != "no" ) {
					$('#fullscreen').prepend('<div id="keyboardInfo"><p>Tangentbords- / Keyboard Navigation</p><ul><li class="prevTxt">Prev.</li><li class="nextTxt">Next</li><li class="closeTxt">Close</li></ul></div>');
					$.cookie("fullscreen-first", "no");
					$('#keyboardInfo').css({'display':'block',opacity:0}).animate({opacity:1},500).delay(4000).animate({opacity:0},500, function() {
						$('#keyboardInfo').remove();
					});
				}
				$('#wrapper').css({'display':'none',margin:0});
				$('#inspiration .post:first').removeClass('thumbs').addClass('list');
				$('#fullscreen #currentSlide img').css({opacity:0});
				$('#fullscreen #currentSlide img').attr('src', imgURL);
				$('#fullscreen #currentSlide img').preload({
					onFinish: function(){
						$('#fullscreen #currentSlide img').animate({opacity: 1.0});
					}
				});
				// Run Fullscreen Gallery function to decide image sources
				fsGallery();
				//fullscreenButtonFunctions();			
			}					
		});
		
		$('.post .postHeading .arrow').live('click', function() {
			var post = $(this).parents('.post');
			var postPos = post.offset();
			if(post.hasClass('thumbs')){			
				post.find('.postGallery a img').each(function(i) {
					if ( (i+1) == post.find('.postGallery a img').length ) {
						$(this).animate({
						opacity:0
						}, 400, function() {
							$(this).parents('.postGallery').find('a').css({'clear':'both'});
							$(this).animate({
								opacity:1,
								width: '665px',
								height: '500px'
							}, 500, function() {
								post.find('.postGallery a').css({'clear':''});
								$('html, body').scrollTop((postPos.top-112));
								var postInfoHeight = (509*($(this).parents('.postGallery').find('a img').length)-15);							
								post.find('.postInfo').removeClass('shortend').css({height:postInfoHeight,overflow:'',margin:''});
								if ( post.find('.postGallery a img').length != 1 ) {
									post.find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
								}
								post.removeClass('thumbs');
								post.addClass('list');
							});
						});
					} else {
						$(this).animate({
						opacity:0
						}, 400, function() {
							$(this).parents('.postGallery').find('a').css({'clear':'both'});
							$(this).animate({
								opacity:1,
								width: '665px',
								height: '500px'
							}, 500, function() {
								$(this).css({'clear':''});
							});
						});	
					}
				});
			} else {			
				post.find('.postGallery a img').each(function(i) {
					if ( (i+1) == post.find('.postGallery a img').length ) {
						$(this).animate({
							opacity:0,
							width: '205px',
							height: '150px'
						}, 600, function() {
							$(this).animate({opacity:1}, 400, function() {});
							$(this).css({'clear':''});
							$(this).parents('a').css({'clear':''});
						});
					} else {
						$(this).animate({
							opacity:0,
							width: '205px',
							height: '150px'
						}, 600, function() {
							$(this).animate({opacity:1}, 400, function() {});
							$(this).css({'clear':''});
							$(this).parents('a').css({'clear':''});						
							post.removeClass('list');
							post.addClass('thumbs');
							$('#inspiration').css({'height':'auto'});
							post.find('.postInfo').css({'height':''});
							if ( post.find('.postGallery a img').length < 5 ) {
								post.find('.postInfo').addClass('shortend').css({height:'120px',overflow:'hidden'});
							}
						});	
					}
				});			
			}
		});
		
		/* Thumbnail or list view click function */ 
		$('.postGallery a img').live('click', function() {
			// List view function
			$('#thumbHover').css({opacity:0});	
			var post = $(this).parents('.post');
			if (post.hasClass('thumbs')) {
				var url = $(this).parent('a').attr('href');		
				$(this).parents('.postGallery').find('a img').each(function(i) {
					if ( (i+1) == $(this).parents('.postGallery').find('a img').length ) {
						$(this).animate({
						opacity:0
						}, 400, function() {
							$(this).parents('.postGallery').find('a').css({'clear':'both'});
							$(this).animate({
								opacity:1,
								width: '665px',
								height: '500px'
							}, 500, function() {
								$(this).css({'clear':''});
								imgPos = $(this).parents('.postGallery').find('a[href="'+url+'"]').offset();
								post.removeClass('thumbs');
								post.addClass('list');
								$('html, body').scrollTop((imgPos.top-120));
								var postInfoHeight = (509*($(this).parents('.postGallery').find('a img').length)-15);							
								post.find('.postInfo').removeClass('shortend').css({height:postInfoHeight,overflow:'',margin:''});							
								if ( post.find('.postGallery a img').length != 1 ) {
									post.find('.postShare').css({'bottom':262,'height':232,'position':'absolute','float':'','clear':'','margin':''});
								}
							});
						});
					} else {
						$(this).animate({
						opacity:0
						}, 400, function() {
							$(this).parents('.postGallery').find('a').css({'clear':'both'});
							$(this).animate({
								opacity:1,
								width: '665px',
								height: '500px'
							}, 500, function() {
								$(this).css({'clear':''});
							});
						});	
					}
				});
			} else {
				// Load Fullscreen	
				$('#listHover').css({opacity:0});			
				if (!$('body').hasClass('fullscreen')) {				
					$('html, body').scrollTop(0);				
					var imgURL = $(this).parent('a').attr('href');			
					$('body').addClass('fullscreen').prepend('<div id="fullscreen"><div id="fsInfo"></div><div id="symbol"></div><div id="close">Выход из полноэкранного режима [ esc ]</div><div id="prevBtn"></div><div id="nextBtn"></div><div id="currentSlide"><span class="supersize"><img src="" width="665" height="500"></span></div><div id="prevSlide"><span class="supersize"><img src="" width="665" height="500"></span></div><div id="nextSlide"><span class="supersize"><img src="" width="665" height="500"></span></div></div>');
					$('#wrapper').css({'display':'none',margin:0});					
					$('#fullscreen #currentSlide img').css({opacity:0});
					$('#fullscreen #currentSlide img').attr('src', imgURL);
					$('#fullscreen #currentSlide img').preload({
						onFinish: function(){
							$('#fullscreen #currentSlide img').animate({opacity: 1.0}, 400, function(){
								if ( $.cookie("fullscreen-first") != "no" ) {
									$('#fullscreen').prepend('<div id="keyboardInfo"><p>Tangentbords- / Keyboard Navigation</p><ul><li class="prevTxt">Prev.</li><li class="nextTxt">Next</li><li class="closeTxt">Close</li></ul></div>');
									$.cookie("fullscreen-first", "no");
									$('#keyboardInfo').css({'display':'block',opacity:0}).animate({opacity:1},500).delay(3000).animate({opacity:0},500, function() {
										$('#keyboardInfo').remove();
									});
								}
							});
							$('#listHover').remove();
						}
					});
					// Run Fullscreen Gallery function to decide image sources
					fsGallery();
				}
			}
			return false;
		});
	
		$('.section .heading .arrow, .section .heading h2').live('click', function() {
			var obj = $(this).parents('.section');
			if(!obj.hasClass('closed')){
				obj.addClass('closed');	
			} else {
				obj.removeClass('closed');	
			}
			obj.children('.content').slideToggle();
			return false;
		});
		
		$(".postHeading").live("mouseenter",function(){		
			$(this).siblings(".postCount").find('.count').css({'color' : '#14E8DE'});	
		}).bind("mouseleave",function(){		
			$(this).siblings(".postCount").find('.count').css({'color' : ''});	
		});
		
		$(".entry").live("mouseenter",function(){		
			$(this).siblings(".postCount").find('.count').css({'color' : '#14E8DE'});	
		}).bind("mouseleave",function(){		
			$(this).siblings(".postCount").find('.count').css({'color' : ''});	
		});
			
		$('.postGallery a').live({
			click: function() {
				$(this).children('img').click();						   
				return false;
			},
			mouseenter: function() {
				if ( $(this).parents('.post').hasClass('thumbs') && $(this).children('img').width() == 205 ) {
					$(this).prepend('<div id="thumbHover">&nbsp;</div>');
				} else  if ( $(this).parents('.post').hasClass('list') && $(this).children('img').width() == 665 ){
					$(this).prepend('<div id="listHover">&nbsp;</div>');			
				}
			},
			mousemove: function() {
				if ( $(this).parents('.post').hasClass('thumbs') && $(this).children('img').width() == 205 && !$(this).children('#thumbHover').length ) {
					$(this).prepend('<div id="thumbHover">&nbsp;</div>');
				} else  if ( $(this).parents('.post').hasClass('list') && $(this).children('img').width() == 665 && !$(this).children('#listHover').length ){
					$(this).prepend('<div id="listHover">&nbsp;</div>');			
				}
			},
			mouseleave: function() {
				$('#thumbHover, #listHover').remove();
			}
		});
		
		$('#inspiration').infinitescroll({ 
			navSelector  : "div.navigation",            
			nextSelector : "div.navigation a:first",    
			itemSelector : "#inspiration div.post:not(.campaign)",          
			loadingImg   : "http://egf.ru/data/uploads/deco/fsloader.gif",
			loadingText  : "",
			donetext     : '<img src="http://egf.ru/data/uploads/deco/fsloader.gif" width="30" height="30">'
		},function(arrayOfNewElems){
			postsLoaded();
		});
		
		
		// Fullscreen
		$("#fullscreen #leftArea").live({			
			mouseenter: function() {
				var loaderMarginHorisontal = $('#fullscreen #prevSlide .supersize').outerWidth() - 25 - ($("#fullscreen #leftArea").width() / 2);
				var loaderMarginVertical = ($(window).height() / 2) - 25;		
				$('#fullscreen #prevSlide .supersize').css({'background-position':loaderMarginHorisontal+'px '+loaderMarginVertical+'px'});		
				$('#fullscreen #prevSlide .supersize').css({marginLeft:-$('#fullscreen #prevSlide .supersize').outerWidth(),opacity:1});
				$('#fullscreen #prevSlide .supersize img').css({left:'',right:0});
				$('#fullscreen #prevSlide .supersize').animate({
					marginLeft:-($('#fullscreen #prevSlide .supersize').outerWidth()-$("#fullscreen #leftArea").outerWidth())
				});		
			},
			mouseleave: function() {
				$('#fullscreen #prevSlide .supersize').animate({
					marginLeft:-$('#fullscreen #prevSlide .supersize').outerWidth()
				}, 500, function() {	
					$('#fullscreen #prevSlide .supersize').css({marginLeft:-$('#fullscreen #prevSlide .supersize').outerWidth(),opacity:0});
				});
			},
			click: function() {
				if ( !$(this).hasClass('stop') ) {
					if ( $('#fullscreen #currentSlide .supersize').length > 1 ) {
						$('#fullscreen #currentSlide .supersize:last-child').remove();
					}
					$('#fullscreen #leftArea, #fullscreen #rightArea').remove();
					$('#fullscreen #prevSlide .supersize').animate({
						marginLeft:0
					}, 500, function() {
						//prev slide done
						$('#fullscreen #prevSlide .supersize').css({marginLeft:0,opacity:1});
						var newCurrImg = $('#fullscreen #prevSlide img').attr('src');
						$('#fullscreen #currentSlide .supersize').clone().appendTo('#fullscreen #currentSlide');
						$('#fullscreen #currentSlide .supersize:first-child img').attr('src', newCurrImg);						
						$('#fullscreen #currentSlide .supersize:first-child img').clone().appendTo('#fullscreen #currentSlide .supersize:last-child');
						fsGallery();
					});
				}
			}
		});
		
		$("#fullscreen #rightArea").live({
			mouseenter: function() {		
				var loaderMarginHorisontal = ($("#fullscreen #rightArea").width() / 2) - 25;
				var loaderMarginVertical = ($(window).height() / 2) - 25;		
				$('#fullscreen #nextSlide .supersize').css({'background-position':loaderMarginHorisontal+'px '+loaderMarginVertical+'px'});		
				if ( !$(this).hasClass('slidingIn') || !$(this).hasClass('slidingOut') ) {
					$(this).addClass('sliding');
					$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:1}).animate({marginLeft:( $(window).width() - $("#fullscreen #rightArea").width())});
				}	
			},
			mouseleave: function() {			
				if ( !$(this).hasClass('slidingOut') ) {
					$(this).removeClass('slidingIn').addClass('slidingOut');
					$('#fullscreen #nextSlide .supersize').animate({
						marginLeft:$(window).width()
					}, 500, function() {	
						$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:0});
						$("#fullscreen #rightArea").removeClass('sliding').removeClass('slidingOut');
					});
				}
			},
			click: function() {
				if ( !$(this).hasClass('stop') ) {
					if ( $('#fullscreen #currentSlide .supersize').length > 1 ) {
						$('#fullscreen #currentSlide .supersize:last-child').remove();
					}
					$('#fullscreen #leftArea, #fullscreen #rightArea').remove();
					$('#fullscreen #nextSlide .supersize').animate({
						marginLeft:0
					}, 500, function() {
						$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:0});
						var newCurrImg = $('#fullscreen #nextSlide img').attr('src');
						$('#fullscreen #currentSlide .supersize').clone().appendTo('#fullscreen #currentSlide');
						$('#fullscreen #currentSlide .supersize:first-child img').attr('src', newCurrImg);						
						$('#fullscreen #currentSlide .supersize:first-child img').clone().appendTo('#fullscreen #currentSlide .supersize:last-child');
						fsGallery();
					});
				}
			}
		});
		
		$('#fullscreen #nextBtn').live({
			click: function() {
				console.log('#fullscreen #nextBtn');
				$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:1});
				$('#fullscreen #rightArea').click();
			}
		});
		
		$('#fullscreen #prevBtn').live({
			click: function() {
				console.log('#fullscreen #prevBtn');
				$('#fullscreen #prevSlide .supersize').css({marginLeft:-$(window).width(),opacity:1});
				$('#fullscreen #leftArea').click();
			}
		});
	
		// set key use
		$(document).keydown(function(e){
			if ($('#fullscreen').length) {
				if (e.keyCode == 37) {
					$('#fullscreen #prevSlide .supersize').css({marginLeft:-$(window).width(),opacity:1});
					$('#fullscreen #leftArea').click();
				}
			}
		});
		
		$(document).keydown(function(e){
			if ($('#fullscreen').length) {
				if (e.keyCode == 39) {
					$('#fullscreen #nextSlide .supersize').css({marginLeft:$(window).width(),opacity:1});
					$('#fullscreen #rightArea').click();
				}
			}
		});
		
		$(document).keydown(function(e){
			if ($('#fullscreen').length) {
				if (e.keyCode == 27) { 
				   $('#fullscreen #close').click();
				   return false;
				}
			}
		});
	}
	
	if ( $('.campaign .slider').length != 0 ) {
		
		$('.campaign .slider').live("mouseenter",function(){
			$('.sliderHover').stop(true,true).css({'background':'none'});			
			$(this).children(".sliderHover").css({'display' : 'block'});		
			$(this).children('.slide').children("img.colour").css({'display' : 'block'});
			$(this).children('.slide').children("img.pic").css({'display' : 'none'});	
		}).live("mouseleave",function(){	
			$(this).children(".sliderHover").css({'display' : 'none'});		
			$(this).children('.slide').children("img.colour").css({'display' : ''});
			$(this).children('.slide').children("img.pic").css({'display' : ''});		
		});
		
		$('.sliderHover').delay(10000).fadeOut(1500);
	
	}
	
	if ( $('.section.campaignForm').length != 0 ) {
	
		$('.autoclear').autoclear();
	
		$.backstretch("", {centeredX: true, centeredY: false, speed: 150});
	
		$('#formail').attr('action', '');
		$("#sendmail").click(function(){
			
			var valid = true;
			
			var fornamn = $("#fornamn").val();
			var efternamn = $("#efternamn").val();
			var titel = $("#titel").val();
			var foretag = $("#foretag").val();
			var epost = $("#epost").val();
			var postadress = $("#postadress").val();
			var zip = $("#zip").val();
			var city = $("#city").val();
			var county = $("#county").val();
			var country = $("#country").val();
			
			if ( $('input.default:not(#county)').length ) {
				valid = false;
				$('input.other').css({'background':'','color':''});	
				$('input.default').css({'background':'#ffddcc','color':'#cc0000'});
			}
			
			if (!epost.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
				valid = false;
				$('input#epost').css({'background':'#ffddcc','color':'#cc0000'});
			} else {
				$('input#email').css({'background':'','color':''});			
			}
			
			if ( valid ) {
				var datastr = 'fornamn=' + fornamn + '&efternamn=' + efternamn + '&titel=' + titel + '&foretag=' + foretag + '&epost=' + epost + '&postadress=' + postadress + '&zip=' + zip + '&city=' + city + '&county=' + county + '&country=' + country;
				$("#response").css({"display":"block"});
				if ( $("#response").hasClass('en') ) {
					$("#response").html("Sending...");				
				} else {
					$("#response").html("Skickar formul&auml;r...");
				}
				$("#response").fadeIn("slow");
				$.ajax({
					type: "POST",
					url: "",
					data: datastr,
					cache: false,
					success: function(html){
						$("#response").fadeIn("slow");
						if ( $("#response").hasClass('en') ) {							
							$("#response").html('Thank you for your order. We hope you will enjoy our sample book.');			
						} else {
							$("#response").html('Tack f&ouml;r din best&auml;llning! Vi hoppas att du kommer uppskatta v&aring;r provbok.');
						}
					}
				});
			}		
			return false;
		});
		
	}
	
	if ( $('.section.offert').length != 0 ) {
	
		$('#formail').attr('action', '');
		$("#sendmail").click(function(){
			
			var valid = '';
			
			var arbetsnamn = $("#arbetsnamn").val();
			var produkttyp = $("#produkttyp").val();
			var upplaga = $("#upplaga").val();
			var formatBredd = $("#formatBredd").val();
			var formatHojd = $("#formatHojd").val();
			var antalSidorInlaga = $("#antalSidorInlaga").val();
			var antalSidorOmslag = $("#antalSidorOmslag").val();
			var fargerInlaga = $("#fargerInlaga").val();
			var fargerOmslag = $("#fargerOmslag").val();
			var fargerOverdrag = $("#fargerOverdrag").val();
			var fargerSkyddsomslag = $("#fargerSkyddsomslag").val();
			var pappersval1 = $("#pappersval1").val();
			var pappersval1vikt = $("#pappersval1vikt").val();
			var pappersval2 = $("#pappersval2").val();
			var pappersval2vikt = $("#pappersval2vikt").val();
			var pappersval3 = $("#pappersval3").val();
			var pappersval3vikt = $("#pappersval3vikt").val();
			var pappersval4 = $("#pappersval4").val();
			var pappersval4vikt = $("#pappersval4vikt").val();
			var ytbehandling = $("#ytbehandling").val();
			var original = $("#original").val();
			var provtryck = $("#provtryck").val();
			var haftning = $("#haftning").val();
			var overdrag = $("#overdrag").val();
			var foreEfter = $("#foreEfter").val();
			var parmpapp = $("#parmpapp").val();
			if ( $("#skyddsomslag").is(':checked') ) {
				var skyddsomslag = $("#skyddsomslag").val();
			} else {
				var skyddsomslag = '';
			}
			if ( $("#kapital").is(':checked') ) {
				var kapital = $("#kapital").val();
			} else {
				var kapital = '';
			}
			if ( $("#flikomslag").is(':checked') ) {
				var flikomslag = $("#flikomslag").val();
			} else {
				var flikomslag = '';
			}
			if ( $("#markband").is(':checked') ) {
				var markband = $("#markband").val();
			} else {
				var markband = '';
			}		
			var paketering = $("#paketering").val();
			var levDatum = $("#levDatum").val();
			var foretag = $("#foretag").val();
			var namn = $("#namn").val();
			var adress = $("#adress").val();
			var postnummer = $("#postnummer").val();
			var ort = $("#ort").val();
			var telefon = $("#telefon").val();
			var fax = $("#fax").val();
			var email = $("#email").val();
			var meddelande = $("#meddelande").val();
				
			if (arbetsnamn == 'Arbetsnamn') {
				valid += '<p>V&auml;nligen fyll i ett arbetsnamn</p>';
				$('input#arbetsnamn').css({'background':'#ffddcc','color':'#cc0000'});
			} else {
				$('input#arbetsnamn').css({'background':'','color':''});			
			}
			if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
				valid += '<p>V&auml;nligen fyll i en godk&auml;nd email kr&auml;vs.</p>';
				$('input#email').css({'background':'#ffddcc','color':'#cc0000'});
			} else {
				$('input#email').css({'background':'','color':''});			
			}
			if (namn == 'Namn') {
				valid += '<p>V&auml;nligen fyll i ditt namn</p>';
				$('input#namn').css({'background':'#ffddcc','color':'#cc0000'});
			} else {
				$('input#namn').css({'background':'','color':''});			
			}
			
			if ( valid != '' ) {
				$("#response").css({'color':'#cc0000'}).fadeIn("slow").html(valid).delay(4000).fadeOut("slow");
			} else {
				var datastr = 'arbetsnamn=' + arbetsnamn + '&produkttyp=' + produkttyp + '&upplaga=' + upplaga + '&formatBredd=' + formatBredd + '&formatHojd=' + formatHojd + '&antalSidorInlaga=' + antalSidorInlaga + '&antalSidorOmslag=' + antalSidorOmslag + '&fargerInlaga=' + fargerInlaga + '&fargerOmslag=' + fargerOmslag + '&fargerOverdrag=' + fargerOverdrag + '&fargerSkyddsomslag=' + fargerSkyddsomslag + '&pappersval1=' + pappersval1 + '&pappersval1vikt=' + pappersval1vikt + '&pappersval2=' + pappersval2 + '&pappersval2vikt=' + pappersval2vikt + '&pappersval3=' + pappersval3 + '&pappersval3vikt=' + pappersval3vikt + '&pappersval4=' + pappersval4 + '&pappersval4vikt=' + pappersval4vikt + '&ytbehandling=' + ytbehandling + '&original=' + original + '&provtryck=' + provtryck + '&haftning=' + haftning + '&overdrag=' + overdrag + '&foreEfter=' + foreEfter + '&parmpapp=' + parmpapp + '&skyddsomslag=' + skyddsomslag + '&kapital=' + kapital + '&flikomslag=' + flikomslag + '&markband=' + markband + '&paketering=' + paketering + '&levDatum=' + levDatum + '&foretag=' + foretag + '&namn=' + namn + '&adress=' + adress + '&postnummer=' + postnummer + '&ort=' + ort + '&telefon=' + telefon + '&fax=' + fax + '&email=' + email + '&meddelande=' + meddelande;
				$("#response").css({"display":"block",'color':'#cc0000'});
				$("#response").html("Skickar formul&auml;r...");
				$("#response").fadeIn("slow");
				$.ajax({
					type: "POST",
					url: "",
					data: datastr,
					cache: false,
					success: function(html){
						$("#response").fadeIn("slow");
						$("#response").html(html);
					}
				});
			}		
			return false;
		});
		
	}
	
});
