(function($){
    //cache needed for overagressive garbage collectors.
    var cache = [];
    //images can either be an array of paths to images or a  single image.
    $.loadImages = function(images, callback){

        if(images){
            //convert to array if needed so rest of script works
            if (!(images instanceof Array)) {
                images = [images];
            }
            var imagesLength = images.length;
            var loadedCounter = 0;
            for (var i = imagesLength; i--;) {
                var cacheImage = document.createElement('img');
                //set the onload method before the src is called otherwise will fail to be called in IE
                cacheImage.onload = function(){
                    loadedCounter++;
                    if (loadedCounter >= imagesLength) {
                        if ($.isFunction(callback)) {
                            callback();
                        }
                    }
                }
                cacheImage.src = images[i];
                cache.push(cacheImage);
            }
        }
    }
})(jQuery)

$(function(){
    var  photosSlideTime = 480;
    var  photosIntervalSlide = 8000;
    var  menuSlideTime = 295;
    var isProjectSliderActive = ($('div.dots.project.slide').size() > 0);
    var isPhotoSliderActive = ($('div.dots.photos.slide').size() > 0);
    
    var showLoading = function(){
        if ($('#mainContentBottom img#loader').size() == 0){
            $('#mainContentBottom').append('<img id="loader" src="/img/loading.gif" alt="Wczytanie danych"/>').show();
        }else{
            $('#mainContentBottom img#loader').show();
        }
    }

    var hideLoading = function(){
        $('#mainContentBottom img#loader').hide();
    }

    var loadPhoto = function($miniature){
        var indexT = $miniature.index()+1;
        if ($('div#indexphoto'+indexT).size() > 0){
            $('#imagesContainer div.bigPhoto:visible').fadeOut();
            $('div#indexphoto'+indexT).stop(true, true).fadeIn();
            if (isProjectSliderActive){
                $('#currentProjectIndex').text(indexT);
                scrollToProjectMiniature($miniature);
                $('#projectLink').attr('href',$miniature.attr('link'));
            }else{
                $('#currentPhotoIndex').text(indexT);
            }
        }else{
            showLoading();
            $.loadImages($miniature.attr('href'),function(){
                $('#imagesContainer div.bigPhoto:visible').stop(true, true).fadeOut();
                if (isProjectSliderActive){
                    $('#projectLink').attr('href',$miniature.attr('link'));
                    $('#currentProjectIndex').text(indexT);
                    $('<div id="indexphoto'+indexT+'" class="bigPhoto"><a title="Wyświetl projekt '+$miniature.attr('rel')+'" href="'+$miniature.attr('link')+'"><img src="'+$miniature.attr('href')+'"/></a></div>').appendTo('#imagesContainer').fadeIn();
                }else{
                    scrollToProjectMiniature($miniature);
                    $('#currentPhotoIndex').text(indexT);
                    $('<div id="indexphoto'+indexT+'" class="bigPhoto"><img  src="'+$miniature.attr('href')+'"/></div>').appendTo('#imagesContainer').stop(true, true).fadeIn();
                }
                hideLoading();
            });
        }
    }

    var scrollToProjectMiniature = function($el){
        var $container = $el.parents('.dotsMenu:first');
        //alert($container.html());
        $container.scrollTo($el,500);
    };

    var showDescription = function(){

        var $content = $('div#content');
        if ($content.is(':visible')){
            $content.stop(true, true).fadeOut('',function(){
                checkPrevNext($('div.dots.slide a.dot.active'));
                $('span.showDesc:first').attr('title','wyświetl opis').text('wyświetl opis');
            });
        }else{
            $('span.showDesc:first').attr('title','schowaj opis').text('schowaj opis');
            hidePhotosNav();
            $content.stop(true, true).fadeIn();
        }
        return false;
    }

    var hidePhotosNav = function(){
        $('#nextPhoto').hide();
        $('#prevPhoto').hide();
    };

    if (isPhotoSliderActive){
        $('a.closeBoxButton').click(showDescription);
        $('.titleWrapper a').click(showDescription);
    }

    $('#mainMenu li a').click(function(){
        if ($(this).hasClass('tak')){
            hidePhotosNav();
            $('#mainHeaderWrapper').addClass('down');
            $('#mainHeaderMenu').find('li').removeClass('active');
            $(this).parents('li:first').addClass('active');
            $('#mainHeaderMenuContent').find('li:visible').hide();
            $('#mainHeaderMenuContent').find('li.'+$(this).attr('id')+'_c:first').show();
            if ($('#mainContentWrapper').is(':visible')){
                $('#mainContentWrapper').fadeOut();
            }
            $('#mainHeaderWrapper').animate({
                "top": "0px"
            },menuSlideTime);
            checkPrevNext($('div.dots.slide a.dot.active'));
            return false;
        }else{

            var $this = $(this);
            if ($('#mainHeaderWrapper').hasClass('down')){
                $('#mainHeaderWrapper').animate({
                    "top": "-490px"
                },menuSlideTime,function(){
                    window.location.href=$this.attr('href');
                });
            }else{
                return true;
            }
        }
        return false;
    });

    $('a#closeTopMenu').click(function(){
        $('#mainHeaderWrapper').animate({
            "top": "-490px"
        },menuSlideTime,function(){
            $('#mainHeaderWrapper').removeClass('down');
            
            if (!$('#mainContentWrapper').is(':visible')){
                $('#mainContentWrapper').stop(true, true).fadeIn('',function(){
                    checkPrevNext($('div.dots.slide a.dot.active'));
                });
            }
        });
        return false;
    });

    $menuNavigation = $('.titleWrapper:first');
    $('div.dots.project.slide a').hover(
        function(){
            $menuNavigation.find('span.title').text($(this).attr('rel'));
        },
        function(){
            $menuNavigation.find('span.title').text($('div.dots.project.slide a.active').attr('rel'));
        });

    var $firstPhoto = $('div.dots.photos.slide a.dot:first').addClass('active');
    loadPhoto($firstPhoto);
        

    if ($('div.dots.project.slide').size() > 0){
        var $first = $('div.dots.project.slide a.dot:first').addClass('active');
        loadPhoto($first);
        $menuNavigation.find('span.title').text($first.attr('rel'));
    }

    $('div.dots.slide a.dot').click(function(){
        checkPrevNext($(this));
        $.doTimeout( 'slideAnimation' );
        loadPhoto($(this));

        
        $('div.dots.slide a.dot').removeClass('active');
        $(this).addClass('active');
        return false;
    });

    var checkPrevNext = function($el){

        var contentVisible = ($('#content:visible').size() == 0);
        if ($el.next('a').size()==0){
            
            $('#nextPhoto').hide();
            $('#nextProject').hide();
        }else{
            if (contentVisible)
                $('#nextPhoto').show();
            $('#nextProject').show();
        }

        if ($el.prev('a').size()==0){
            $('#prevPhoto').hide();
            $('#prevProject').hide();
        }else{
            if (contentVisible)
                $('#prevPhoto').show();
            $('#prevProject').show();
        }

        if (!contentVisible || $('#mainHeaderWrapper').hasClass('down')){
            $('#prevPhoto').hide();
            $('#nextPhoto').hide();
        }
    }

    var goNext = function(){
        if($('div.dots.slide a.dot').size()>1){
            if (!$('#mainHeaderWrapper').hasClass('down')){
                var $next  = $('div.dots.slide a.dot.active').next('a');
                if ($next.size() == 0)
                    $next = $('div.dots.slide a:first');
                
                checkPrevNext($next);
                $('div.dots.slide a.active').removeClass('active');
                $next.addClass('active');
                if (isProjectSliderActive){
                    $menuNavigation.find('span.title').text($next.attr('rel'));
                    scrollToProjectMiniature($next);
                }
                loadPhoto($next);
            }
            return true;
        }
        return false;
    }

    var goPrev = function(){
        if (!$('#mainHeaderWrapper').hasClass('down')){
            var $next  = $('div.dots.slide a.dot.active').prev('a');
            if ($next.size() == 0)
                $next = $('div.dots.slide a:last');

            checkPrevNext($next);
            $('div.dots.slide a.active').removeClass('active');
            $next.addClass('active');
            if (isProjectSliderActive){
                $menuNavigation.find('span.title').text($next.attr('rel'));
                scrollToProjectMiniature($next);
            }
            loadPhoto($next);
        }
        return true;
    }
    
    $.doTimeout( 'slideAnimation',photosIntervalSlide, goNext);

    if (isPhotoSliderActive){
        $('#totalPhotos').text($('div.dots.slide.photos a.dot').size());
        $('#currentProjectIndex').text($('div.dots.project a.dot.active').index()+1);
        checkPrevNext($('div.dots.slide a.dot.active'));
        scrollToProjectMiniature($('div.dots.project a.dot.active'));
    }

    if(isProjectSliderActive){
        checkPrevNext($('div.dots.slide a.dot.active'));
    }

    $('#totalProject').text($('div.dots.project a.dot').size());

    $('a#nextPhoto, a#nextProject').click(function(){
        $.doTimeout( 'slideAnimation');
        goNext();
        checkPrevNext($('div.dots.slide a.dot.active'));
        $.doTimeout( 'slideAnimation',photosIntervalSlide, goNext);
        return false;
    });

    $('a#prevPhoto, a#prevProject').click(function(){
        $.doTimeout( 'slideAnimation');
        goPrev();
        checkPrevNext($('div.dots.slide a.dot.active'));
        $.doTimeout( 'slideAnimation',photosIntervalSlide, goNext);
        return false;
    });

    $('.sideIconPopup').hover(function(){
        $(this).stop(true, true).css({"right": "0"});
    },function(){
        $(this).stop(true, true).css({"right": "-300px"});
    });
});

