var ss;
//max count of popular photo thumbs
var ppCount = 11;

Object.extend(Array.prototype, {
    getRandom: function(count) {
        if (count > this.length) count = this.length;
        var copy = this.clone();
        var result = [];
        for (var i = 0; i < count; i++) {
            var rand = Math.floor(Math.random() * copy.length);
            result[result.length] = copy[rand];
            copy.splice(rand, 1);
        }
        return result.sort();
    }
});

function loadCategories() {
    new Ajax.Request(encodeURI('./galleries/categories/categories.json'), { method:'get',
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport) {
            drawCategories(transport.responseText.evalJSON().categories);
        }
    });
}

function loadGallery(category, index) {
    new Ajax.Request(encodeURI('./galleries/' + category.path + category.file), { method:'get',
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport) {
            var galleryCount = 1;
            var photoCount = 0;
            var lastUpdate;
            var lastModified = transport.getHeader('Last-Modified');
            if (lastModified) {
                lastModified = new Date(lastModified);
            }
            if (category.type == 'gallery') {
                var gallery = transport.responseText.evalJSON().gallery;
                gallery.album.each(function(album) {
                    photoCount += parseInt(album.itemCount);
                });
                galleryCount = gallery.album.length;
//                lastUpdate = getLastUpdate(gallery.album);
            } else {
                var album = transport.responseText.evalJSON().album;
                photoCount = album.itemCount;
//                lastUpdate = getDate(album.updated);
            }
//            var updated = (lastModified && lastModified.isAfter(lastUpdate)) ? lastModified : lastUpdate;
            var description = galleryCount + ((galleryCount > 4) ? ' galerií / ' : ' galerie / ') + photoCount + ' fotek';
            $('albumCount_' + index).update(description);
            $('lastUpdate_' + index).update('změněno: ' + formatDate(lastModified));
        }
    });
}

function getLastUpdate(albums) {
    var lastUpdate;
    albums.each(function(album, index) {
        var date = getDate(album.updated);
        if (date && (!lastUpdate || lastUpdate.isBefore(date))) {
            lastUpdate = date;
        }
    });
    return lastUpdate;
}

function formatDate(date) {
    return (date) ? date.format('dd.MM.yyyy HH:mm') : null
}

function getDate(string) {
    var date;
    if (Date.isValid(string, 'dd.MM.yyyy HH:mm')) {
        date = Date.parseString(string, 'dd.MM.yyyy HH:mm');
    }
    return date;
}

function drawCategories(categories) {
    categories.each(function(category, index) {
        //        console.log(category);
        if (category.visible) {
            if (category.type == 'gallery') {
                category.href = encodeURI('./html/' + 'gallery.html?galleryPath=' + category.path + category.file);
                loadGallery(category, index);
            } else {
                category.href = encodeURI('./html/album.html?album=' + category.name + '&path=' + category.path);
                loadGallery(category, index);
            }
            var miniBox = Builder.node('div', {className:'miniBox'}, [
                    Builder.node('div', {className:'thumb'},
                            Builder.node('a', {style:'background:url(./galleries/' + encodeURI(category.thumb) + ') no-repeat center;', href: category.href})
                            ),
                    Builder.node('div', {className: 'category'}, [
                            Builder.node('p', {className: 'categoryTitle'},
                                    Builder.node('a', {href: category.href}, category.name)),
                            Builder.node('p', {id: 'albumCount_' + index, className: 'description'}, ' galerie / fotek'),
                            Builder.node('p', {id: 'lastUpdate_' + index, className: 'updated'}, 'změněno: ')
                            ])
                    ]);
            $('categoriesBox').appendChild(miniBox);
        }
    });
    addCorners();
}

function addCorners() {
    new Effect.Corner($('mainBox'), '20px');
    $$('div.thumb').each(function(el) {
        new Effect.Corner(el, '5px');
    });
    $$('div.miniBox').each(function(el) {
        new Effect.Corner(el, '10px');
    });
}

function loadPopularPhotos() {
    new Ajax.Request(encodeURI('./galleries/popularPhotos/album.json'), { method:'get',
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport) {
            drawPopularPhotoThumbs(transport.responseText.evalJSON().album);
            //        },
            //        onException: function(request, error) {
            //            console.log('Can not load popular photos...' + error);
        }
    });
}
function drawPopularPhotoThumbs(album) {
    var photos;
    if (album.image.length < ppCount) {
        return;
    }
    photos = album.image.getRandom(ppCount);

    var path = './galleries/' + album.path + '/' + album.thumbPath;
    var uri = './html/album.html?album=' + album.name + '&path=' + album.path;

    var thumbnails = Builder.node('div', {id:'thumbnails'});
    photos.each(function(photo) {
        thumbnails.appendChild(getThumb(path + photo.filename, uri + '#photo=' + photo.filename));
    });

    $('popularPhotos').appendChild(thumbnails);
}

function getThumb(bgUrl, href) {
    return Builder.node('div', {className:'thumb'},
            Builder.node('a', {style:'background:url(' + encodeURI(bgUrl) + ') no-repeat center;', href: encodeURI(href)})
            );
}

function loadSlideshow() {
    new Ajax.Request(encodeURI('./galleries/slideshow/slideshow.json'), { method:'get',
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport) {
            var ssData = transport.responseText.evalJSON().slideshow;
            var path = './galleries/' + ssData.path + ssData.imagePath;
            var photos = ssData.image.clone();
            photos.each(function(photo, index) {
                photo.uri = encodeURI(path + ssData.image[index].filename);
            });
            ss = new Slideshow('slideshow', {duration: ssData.duration, interval: ssData.interval, crossfade: ssData.crossfade, photo : photos});
        }
    });
}

document.observe("dom:loaded", function() {
    loadSlideshow();
});

Event.observe(window, 'load', function() {
//    loadPopularPhotos();
    loadCategories();
});

