/**
 * Main JS Tools
 */
var SK = {

    /**
     * Modules managment tools
     *
     */
    modules: {
        registred: {},
        register: function(name, module) {
            SK.modules.registred[name] = module;
        },
        get: function(name) {
            return SK.modules.registred[name];
        }
    },

    /**
     *    Utils
     *
     */
    utils: {

        /*
         * Target blanc, for external links
         */
        externalLink: function () {
            $('[rel="external"]').attr('target', '_blanc');
        }
    }

};


/**
 *
 * Animated photos show
 * 
 */
(function() {
    var m = function () {
        var distance = 290,
        
            animate = function (nr, count, photos, index) {
                setTimeout(function () {
                    photos.eq(nr).animate({
                        left: '+=' + distance,
                        top: '+=' + distance
                    }, 1000, '', function() {
                        $(this).css({
                            zIndex: --index
                        });
                        $(this).animate({
                            left: '-=' + distance,
                            top: '-=' + distance
                        }, 400, '', function () {
                            if (nr === 0) {
                                nr = count + 1;
                                index = count + 1;
                                photos.css({
                                    zIndex: index
                                });
                            }
                            animate(--nr, count, photos, index);
                        });
                    });
                }, 1000);
            },

            init = function (wrap) {
                var photos = wrap.children(),
                    count = photos.size();

                animate(count-1, count-1, photos, 10);
            };

        return {
            init: init
        };
    }();
    SK.modules.register('animPhotos', m);
})();



/**
 * Galery
 * 
 * @name galery
 */
(function() {
    var m = {
        bigPhoto: [],       // Duże zdjęcie (HTML)
        thumbs: [],         // Miniatruki (HTML)
        
        init: function () {
            var that = this,
                firstLoad = true,   // Czy galeria załadowana po raz pierwszy
                overlay,            // Div z warstwa (HTML)
                gallery,            // Div z galeria (HTML)
                thumbsWrap,         // Ul z miniaturkami (HTML)
                thumbW,
                visibledThumbs,     // Ile miniaturek mieście się w jednej stronie slidera
                thumbsLen,          // count miniatruek
                photo,              // Nr aktualnego, poprzedniego i nastepnego zdjecia, linki prev/next
                time;
            
            $('#miniGallery a').each(function(i, el) {
                $(el).data('eq', i).bind('click', function(e) {
                    e.preventDefault();
                    
                    if (firstLoad) {
                        overlay = $('#overlay');
                        gallery = $('#gallery');
                        thumbsWrap = gallery.find('ul');
                        photo = {
                            current: 0,                     // Nr aktualnie wyświetlanego zdjęcia
                            prev: 0,                        // Nr poprzedniego zdjęcia
                            next: 0,                        // Nr kolejnego zdjecia
                            nextLink: $('#gal-next'),       // Link Next (HTML)
                            prevLink: $('#gal-prev')        // Link Prev (HTML)
                        };
                        that.bigPhoto = $('#gal-photo');
                        that.thumbs = thumbsWrap.find('a');
                        thumbsLen = that.thumbs.size();
                        thumbW = that.thumbs.eq(0).parent().outerWidth();

                        // Ustawia layout galerii
                        visibledThumbs = that.setGalleryLayout(gallery, thumbsWrap, overlay, thumbsLen, thumbW, photo);

                        // Wyświetlenie pierwszego zdjęcia (zalezne od wybranego zdjęcia na stronie filmu)
                        photo = that.showBigPhoto($(this).data('eq'), photo, thumbsLen);
                        
                        // Inicjalizacja slidera
                        that.slider.init(visibledThumbs, thumbsLen, thumbW, that);

                        that.slider.checkPage(that, photo);
                        
                        // Podpięcie zdarzeń zamknięcia

                        // Klik w X oraz poza obszar galerii
                        $('#overlay, #gal-close').bind('click', function (e) {
                            e.preventDefault();
                            that.closeGallery(gallery, overlay);
                        });

                        that.thumbs.each(function (i, el) {
                            $(el).data('eq', i);

                            // Zmiana dowolnego zdjęcia
                            $(el).bind('click', function (e) {
                                e.preventDefault();
                                
                                if ($(this).data('eq') === photo.current) {
                                    return;
                                }
                                
                                photo = that.showBigPhoto($(this).data('eq'), photo, thumbsLen);
                            });
                            
                        });
                        
                        // Następne zdjęcie
                        $(photo.nextLink).bind('click', function (e) {
                            e.preventDefault();
                            photo = that.showBigPhoto(photo.next, photo, thumbsLen);
                            that.slider.checkPage(that, photo);
                        });

                        // Poprzednie zdjęcie
                        $(photo.prevLink).bind('click', function (e) {
                            e.preventDefault();
                            photo = that.showBigPhoto(photo.prev, photo, thumbsLen);
                            that.slider.checkPage(that, photo);
                        });
                        
                        that.bigPhoto.parent().bind('mouseenter mouseleave', function (e) {
                            if (e.type === 'mouseenter') {
                                clearTimeout(time);
                                that.showGalleryNav(photo);
                            } else {
                                time = setTimeout(function() {that.hideGalleryNav(photo);}, 1000);
                            }
                        });
                        
                        firstLoad = false;
                        
                    } else {
                        
                        // Ustawia layout galerii
                        visibledThumbs = that.setGalleryLayout(gallery, thumbsWrap, overlay, thumbsLen, thumbW, photo);
                        that.slider.setPagin(visibledThumbs, thumbsLen, thumbW);
                        // Wyświetlenie pierwszego zdjęcia (zależne od wybranego zdjęcia na stronie filmu)
                        photo = that.showBigPhoto($(this).data('eq'), photo, thumbsLen);
                        that.slider.checkPage(that, photo);
                        
                    }
                    
                    // Zdarzenia z klawiatury
                    $(document).bind('keydown', function (e) {
                        e.preventDefault();
                        
                        if (e.which === 27) { // ESC
                            that.closeGallery(gallery, overlay);
                        } else if (e.which === 39) {
                            if (photo.next < thumbsLen) {
                                photo = that.showBigPhoto(photo.next, photo, thumbsLen);
                                that.slider.checkPage(that, photo);
                            }
                        } else if (e.which === 37) {
                            if (photo.prev >= 0) {
                                photo = that.showBigPhoto(photo.prev, photo, thumbsLen);
                                that.slider.checkPage(that, photo);
                            }
                        }
                    });
                    
                    // Wyświetlenie galerii
                    that.showGallery(gallery, overlay);
                    time = setTimeout(function() {that.hideGalleryNav(photo);}, 2000);
                });
            });
        },
        
        
        
        
        /**
         * Oblicza wielkość i pozycję galerii oraz warstwy przykrywającej
         * Zwraca ileść widocznych elementów na liście slidera
         */
        setGalleryLayout: function (gallery, thumbsWrap, overlay, thumbsLen, thumbW, photo) {
            var that = this,
                winW = $(window).width(),
                winH = $(window).height(),
                bigPhotoWrap = that.bigPhoto.parent(),
                thumbsWrapW,
                visibled,
                galleryW,
                galleryH;
                
                
            // Zerowanie wymiarów
            thumbsWrap.css({
                left: 0
            }).parent().removeAttr('style');
            gallery.removeAttr('style');
            bigPhotoWrap.removeAttr('style');
            
            // Orginalny rozmiar galerii
            galleryW = gallery.outerWidth();
            galleryH = gallery.outerHeight();
            thumbsWrapW = thumbsWrap.parent().width();
            
            if (winW - 20 < galleryW) {
                var newGalleryW = winW - 20,
                    newThumbWrapW = thumbsWrapW - (galleryW - newGalleryW);
                
                thumbsWrapW = newThumbWrapW;
                galleryW = newGalleryW;
            }
            
            if (winH - 20 < galleryH) {
                var newGalleryH = winH - 20,
                    newBigPhotoH = bigPhotoWrap.outerHeight() - (galleryH - newGalleryH);
                
                bigPhotoWrap.css({
                    height: newBigPhotoH + 'px',
                    lineHeight: newBigPhotoH + 'px'
                });
                
                galleryH = newGalleryH;
            }
            
            // Pozycja galerii
            gallery.css({
                width: galleryW,
                height: galleryH,
                left: (winW - galleryW) / 2,
                top: (winH - galleryH) / 2
            });
            
            photo.nextLink.removeAttr('style');
            photo.prevLink.removeAttr('style');

            // Ile miniaturek sie mieści w na jednej stronie slidera
            visibled = Math.floor(thumbsWrapW / thumbW);
            visibled = (visibled > thumbsLen ) ? thumbsLen : visibled;
            
            // Korekta szerokości pojemnika na miniaturki
            thumbsWrapW = thumbW * visibled;
            
            // Wielkość pojemnika na miniaturki
            thumbsWrap.parent().css({
                width: thumbsWrapW
            });
            
            // Całkowita szerokość ul (dla slidera)
            thumbsWrap.css({
                width: thumbW * thumbsLen
            });

            // Overlay
            overlay.css({
                width: $(document).width(),
                height: $(document).height()
            });
            
            return visibled;
        },
         
         
         
         
        /**
         * Wyświetla duże zdjęcie,
         * zaznacza aktualną miniaturkę
         * zwraca informacje o kolejnym i następnym zdjęciu
         */
        showBigPhoto: function (toShow, photo, thumbsLen) {
            var that = this;

            that.thumbs.eq(photo.current).parent().removeClass('current');
            that.thumbs.eq(toShow).parent().addClass('current');
            
            if (that.bigPhoto.attr('src') !== that.thumbs.eq(toShow).attr('href')) {
                that.bigPhoto.fadeOut(200, function () {
                    that.bigPhoto.attr('src', that.thumbs.eq(toShow).attr('href'));
                    that.bigPhoto.load(function() {
                        $(this).fadeIn(200);
                    });
                });
                
                photo.current = toShow;
            
                if (toShow < thumbsLen - 1) {
                    photo.next = toShow + 1;
                    photo.nextLink.parent().removeClass('hide');
                } else {
                    photo.nextLink.parent().addClass('hide');
                    photo.next = toShow + 1;
                }

                if (toShow !== 0) {
                    photo.prev = toShow - 1;
                    photo.prevLink.parent().removeClass('hide');
                } else {
                    photo.prevLink.parent().addClass('hide');
                    photo.prev = -1;
                }

                $('#gal-current').text(toShow + 1);
            }
            
            return photo;
        },
        
        
        
        
        /**
         * Slider
         */
        slider: (function() {
            var prev = [],
                next = [],
                paginArr = [],
                current = 0,
                pages = 0,
                left = 0,
                
                setPagin = function (visibledThumbs, thumbsLen, thumbW) {
                    current = 0;
                    prev.addClass('unactive');
                    next.addClass('unactive');

                    if (thumbsLen > visibledThumbs) {
                        pages = Math.ceil(thumbsLen / visibledThumbs);
                        left = thumbW * visibledThumbs;
                        next.removeClass('unactive');
                    } else {
                        pages = 1;
                    }

                    for(var i = 0, j = 0; i < thumbsLen; i++) {
                        if (i > 0 && i % visibledThumbs === 0) {
                            j++;
                        }
                        paginArr[i] = j;
                    }
                },
                
                slideToPage = function (page, global) {
                    if (page === 'next' && current < pages) {
                        page = ++current;
                    } else if (page === 'prev' && current > 0) {
                        page = --current;
                    } else if (current === page) {
                        return;
                    } else {
                        current = page;
                    }

                    $(global.thumbs).parent().parent().animate({
                        left: page * -left
                    }, 300);

                    (current === 0) ? prev.addClass('unactive') : prev.removeClass('unactive');
                    (current === pages - 1) ? next.addClass('unactive') : next.removeClass('unactive');
                },
                
                checkPage = function (global, photo) {
                    if (current !== paginArr[photo.current]) {
                        slideToPage(paginArr[photo.current], global);
                        current = paginArr[photo.current];
                    }
                },
                
                init = function (visibledThumbs, thumbsLen, thumbW, global) {
                    next = $('#gal-slide-next');
                    prev = $('#gal-slide-prev');
                    current = 0;

                    setPagin(visibledThumbs, thumbsLen, thumbW);

                    next.bind('click', function (e) {
                        e.preventDefault();
                        if (current < pages - 1) {
                            slideToPage('next', global);
                        }
                    });

                    prev.bind('click', function (e) {
                        e.preventDefault();
                        if (current > 0) {
                            slideToPage('prev', global);
                        }
                    });
                };
                
                return {
                    init: init,
                    setPagin: setPagin,
                    slideToPage: slideToPage,
                    checkPage: checkPage
                };
            })(),
        
        
        /**
         * Show Gallery nav
         */
        showGalleryNav: function (photo) {
            $(photo.prevLink).stop().animate({
                left: 0 + 'px'
            }, 300);
            $(photo.nextLink).stop().animate({
                right: 0 + 'px'
            }, 400);
        },
        
        
        /**
         * Hide Gallery nav
         */
        hideGalleryNav: function (photo) {
            $(photo.prevLink).animate({
                left: -70 + 'px'
            }, 300);
            $(photo.nextLink).animate({
                right: -70 + 'px'
            }, 300);
        },
        
        
        /**
         * Wyświetlenie galerii
         */
        showGallery: function (gallery, overlay) {
            gallery.hide();
            overlay.fadeIn(600, function () {
                gallery.fadeIn(600);
            });
        },
        
        
        
        /**
         * Zamknięcie galerii
         */
        closeGallery: function (gallery, overlay) {
            overlay.fadeOut(300);
            gallery.fadeOut(300);
            
            $(document).unbind('keydown');
        }
    };
    SK.modules.register('gallery', m);
})();
