var galleries = null;
var images;
var page = 1;
var pageSize = 6;

var photoGallery =
{
    initialize: function(galleryDataPath, galleryProfilePath) {
        var div = $(document.createElement('div')).addClass('galleryColumn');

        $.ajax({
            type: "GET",
            url: galleryDataPath,
            cache: true,
            dataType: "xml",
            success: function(xml) {
                galleries = xml;

                // Set Hidden Div Width
                $('#gallery').width($('#gallery').width() * Math.ceil($('#gallery .profileImage').length / 6));

                photoGallery.togglePagers();
            }
        });


    },

    openModal: function(folder) {
        pause();
        $('#imageContainer').height(0);
        Modal.show('modalWrapper', null, function() { $('#innerContainer').empty(); $('#imageContainer').empty().hide(); photoGallery.clear(); resume(); });
        $('#overlay').width($('#outerContainer').width());
        $('#overlay').height($('#outerContainer').height());
        $('#overlay').show();
        this.loadImages(folder);
    },

    loadImages: function(folder) {
        images = new Array();

        // Get Photos For Gallery
        $('Galleries > Gallery[@folder=' + folder + '] > Photo[@active=True]', galleries).each(function(i) {
            var path = $(this).attr('image');
            images.push(path);
        });

        // Get Path To Images
        var path = 'Assets/Events/Photos/' + folder + '/Thumbnails/';

        // Preload Gallery
        $(function($) {

            $.preload(images, {
                base: path,
                ext: '',
                onComplete: function(data) {

                    // Create New Image
                    var img = new Image();
                    img.src = data.image;

                    // Append Click Event
                    var imageName = data.original;
                    var path = data.image;
                    $(img).click(function() {
                        photoGallery.showImage(imageName, path);
                    });

                    // Append To Display
                    $('#innerContainer').append(img);
                },
                onFinish: function() {
                    photoGallery.justifyImages();

                }
            });
        });
    },

    // Enlarges An Image
    showImage: function(imageName, path) {
        $("#imageContainer").addClass('loading').find(' > img').remove();

        var img = new Image();

        $(img).load(function() {
            $(this).hide();

            $("#outerContainer").animate({
                height: $(this).attr('height')
            });

            $("#imageContainer").removeClass('loading').append(this);
            $(this).fadeIn();
        }).error(function(e) {
            $('#imageName').text('Image Not Found');
        }).attr('src', path.replace('Thumbnails', 'Images'));

        $('#imageName').text(imageName);

        $('.imagePager').unbind('click');

        var index = $.inArray(imageName, images);

        if (index == 0) {
            $('.imagePager:first').hide();
        }
        else {
            var previousImage = images[index - 1];

            $('.imagePager:first').show().find(' > .pagerInfo > span').text(previousImage);

            $('.imagePager:first').one('click', function() {
                photoGallery.showImage(previousImage, path.replace(imageName, previousImage));
            }).find(' .photoPager').attr('src', path.replace(imageName, previousImage));
        }

        if (index == (images.length - 1)) {
            $('.imagePager:last').hide();
        }
        else {
            var nextImage = images[index + 1];

            $('.imagePager:last').show().find(' > .pagerInfo > span').text(nextImage);

            $('.imagePager:last').one('click', function() {
                photoGallery.showImage(nextImage, path.replace(imageName, nextImage));
            }).find(' .photoPager').attr('src', path.replace(imageName, nextImage));
        }

        $('#closeGallery').show();
        $('#modalHeader .nextprev').show();
        $("#imageContainer").height($("#outerContainer").height()).width($("#outerContainer").width()).fadeIn('slow');
        $('#innerContainer').fadeOut();
    },

    justifyImages: function() {
        $('#innerContainer').show();

        var containerHeight = $("#outerContainer").height();
        var imageHeight = $('#innerContainer img:first').height();
        var imageContainerHeight = $("#innerContainer").height();

        // Resize Images If Overflow Occurs
        if (containerHeight <= imageContainerHeight) {
            this.scaleDown(containerHeight, imageContainerHeight);
        }

        // Find Needed Padding and Row Count
        var padding = $("#outerContainer").width() - $('#innerContainer').width();
        var count = Math.floor($("#outerContainer").width() / $('#innerContainer img:first').width());

        // Is Count More Then Images Per Row Then Center Image Container
        if ($('#innerContainer img').length > count) {
            // Calculate Padding
            padding = Math.floor(padding / count)
            $('#innerContainer img').css('margin-right', padding);

            var center = $("#outerContainer").width() - $('#innerContainer').width() - padding / 2 - 5;
            if (center > 1) {
                $('#innerContainer').css('left', center);
            }
            else {
                $('#innerContainer').css('left', padding);
            }
        }

        $('#overlay').hide();
    },

    scaleDown: function(containerHeight, imageContainerHeight) {
        for (var i = imageContainerHeight; 0 < i; i--) {
            $('#innerContainer img').width($('#innerContainer img:first').width() - 1);
            $('#innerContainer img').height($('#innerContainer img:first').height() - 1);
            if (containerHeight >= $("#innerContainer").height()) {
                break;
            }
        }
    },

    backToGallery: function() {
        $('#innerContainer').fadeIn();
        $('#imageContainer').fadeOut().find(' > img').remove();
        this.clear();
    },

    closeModal: function(modal) {
        resume();
        $('#innerContainer').empty();
        $('#imageContainer').find(' > img').remove().hide();
        this.clear();
        Modal.close(modal);
    },

    clear: function() {
        $("#outerContainer").animate({
            height: 555
        });

        $('#imageName').empty();
        $('#modalHeader .nextprev').hide();
        $('#closeGallery').hide();
    },

    previous: function() {
        $('#gallery').animate({
            left: 440 + parseInt($('#gallery').css('left'))
        });
        page = page - 1;
        this.togglePagers();
    },

    next: function() {
        $('#gallery').animate({
            left: -440 + parseInt($('#gallery').css('left'))
        });
        page = page + 1;
        this.togglePagers();
    },

    togglePagers: function() {
        $('#nextThumbnails').empty();
        $('#previousThumbnails').empty();

        if (page == Math.ceil($('#gallery .profileImage').length / pageSize)) {
            $('#nextGalleryPager').hide();
        }
        else {
            $('#nextGalleryPager').show();

            var profiles = $('Galleries > Gallery[@active=true]', galleries);
            var thumbnails = $.grep(profiles, function(n, i) {
                if (i >= ((page * pageSize)) && ((page * pageSize) + pageSize) >= i) {
                    var img = new Image();
                    img.src = 'Assets/Events/Photos/Profiles/Pager/' + $(n).attr('profile');
                    $('#nextThumbnails').append(img);
                }
            })
        }

        if (page == 1) {
            $('#previousGalleryPager').hide();
        }
        else {
            $('#previousGalleryPager').show();

            var profiles = $('Galleries > Gallery[@active=true]', galleries);
            var thumbnails = $.grep(profiles, function(n, i) {
                if (i >= (((page - 1) * pageSize) - pageSize) && ((page - 1) * pageSize) > i) {
                    var img = new Image();
                    img.src = 'Assets/Events/Photos/Profiles/Pager/' + $(n).attr('profile');
                    $('#previousThumbnails').append(img);
                }
            })
        }
    }


}
