var loop
var i = 0;
var ani = false;

jQuery(function($) {

    if ( $.browser.msie ) {
        $($('header div').get(0)).prepend('<!--[if IE 8 ]><div class="shadow"></div><![endif]-->');
        $($('footer').get(0)).prepend('<!--[if IE 8 ]><div class="shadow"></div><![endif]-->');
    }
    
    if(($('.slideshow').length && $('.slideshow div').length/2 && $('.start').length) || ($('.slideshowSmall').length && $('.slideshowSmall div').length/2-1)) {
		loop = setTimeout(nextImage,4000,1);
	} else {
	    $('.slideshow div div a.right, .slideshow div div a.left').remove();
	}
})

function nextImage(dir) {
	elem = $('.slideshow') ? $('.slideshow div:not(.slideshow div div)') : $('.slideshowSmall div:not(.slideshowSmall div div)');
	
	var hide = dir ? i == elem.length ? elem.length - 1 : i : i == 0 ? 0 : i;
	var show = dir ? i == elem.length - 1 ? 0 : ++i : i == 0 ? elem.length - 1 : --i;
	
	$(elem[show]).css('z-index','30');
	$(elem[show]).css('display','none');

	$(elem[show]).fadeIn(1000,function() {
		$(elem[hide]).css('z-index','20');
		$(elem[show]).css('z-index','25');
		ani = false;
	});
	
	if(show==0 && hide==elem.length-1) {
		i = 0;
	} else if(hide==0 && show==elem.length-1) {
		i = elem.length-1;
	}
	
	loop = setTimeout(nextImage,4000,1);
};


if($('.slideshow div div a').length != 0) {
    $('.slideshow div div a.left,.slideshowSmall div div a.left').click(function() {
    	if(!ani) {
    		clearTimeout(loop);
    		ani = true;
    		nextImage(0);
    	}
    });
    
    $('.slideshow div div a.right,.slideshowSmall div div a.right').click(function() {
    	if(!ani) {
    		clearTimeout(loop);
    		ani = true;
    		nextImage(1);
    	}
    });
}

$('.gallery div div').click(function() {
	
	var that = this;
	$(this).parent().children().each(function(id, elem) {
		if(elem == that) i = id-1;
	})
	
	var newImg = $(this).find('img').clone();
	$('.gallery').prepend(newImg);
	$($('.gallery img')[1]).fadeOut(500,function() {
		$(this).remove();
	});
})

$('.gallery div a').click(function() {
	var dir   = $(this).html() == "next" ? 1 : 0;
	var count = $('.gallery div div').length;
	
	i = dir ? i == (count - 1) ? 0 : ++i : i == 0 ? (count - 1) : --i;
	
	var newImg = $('.gallery div div')[i];
	$('.gallery').prepend($(newImg).find('img').clone());
	$($('.gallery img')[1]).fadeOut(500,function() {
		$(this).remove();
	});
})

