var flickr = {
    container: null,
    proxy: '/proxy.php?url=http://api.flickr.com/services/rest/&mode=native',
    userId: null,
    sets: null,
    renderedSet: null,
    nextButton: null,
    setsPerPage: 30,
    expandedSets: 4,
    pageLoaded: 0,
    
    init: function(userId, container, nextButton) 
    {
        this.container = container;
        this.userId = userId;
        this.sets = this.getSets();
        this.nextButton = nextButton;
    },
    
    getSets: function()
    {
        var data = {
            method: 'flickr.photosets.getList',
            user_id: this.userId,
            format: 'json',
            nojsoncallback: '1'
        };
        var self = this;
        $.ajax({
            url: this.proxy,
            dataType: 'json',
            data: data,
            type: 'POST',
            success: function(response){
                self.sets = response.photosets.photoset;
                self.onSetsLoad();
            }
        });
    },
    
    onSetsLoad: function()
    {
        var self = this;
        this.nextButton.click(function(){
            var lastSet = self.renderNextPage();
            if (lastSet) {
                self.nextButton.remove();
            }
            return false;
        });
        this.nextButton.click();
    },
    
    renderSet: function(index, expanded)
    {
        var self = this;
        var setContainer = $('<div class="set" id="flickr-set-' + this.sets[index].id + '"></div>');
        var date = Date.parseExact("01/01/1970", "M/d/yyyy");
        date.addSeconds(this.sets[index].date_create);
        setContainer.append('<h3><strong>' + this.sets[index].title._content + '</strong> - ' + date.toString('MMMM d, yyyy') + ' <span class="render-content-link">(<a href="#">Show</a>)</span> <span class="photos-num">' + this.sets[index].photos + ' Photos</span></h3>');
        self.container.append(setContainer);
        setContainer.find('a').click(function(){
            $(this).unbind();
            self.renderSetContents(index, setContainer);
            $(this).text('Hide');
            $(this).toggle(function(){
                $(this).text('Show');
                $(this).closest('div.set').find('div.column').hide();
            }, function(){
                $(this).text('Hide');
                $(this).closest('div.set').find('div.column').show();
            });
            return false;
        });
        
        if (expanded) {
            setContainer.find('a').click();
        }
        
        return;
    },
    
    renderSetContents: function(index, setContainer)
    {
        setContainer.append('<div class="loading"><img src="/public/assets/lightbox-ico-loading.gif"/></div>')
        var data = {
            method: 'flickr.photosets.getPhotos',
            photoset_id: this.sets[index].id,
            format: 'json',
            nojsoncallback: '1'
        };
        $.ajax({
            url: this.proxy,
            dataType: 'json',
            data: data,
            type: 'POST',
            success: function(response){
                var columns = new Array();
                columns[0] = $('<div class="column"></div>');
                columns[1] = $('<div class="column"></div>');
                columns[2] = $('<div class="column"></div>');
                columns[3] = $('<div class="column last"></div>');
                $(response.photoset.photo).each(function(index, img){
                    columns[index % 4].append(
                        '<a href="http://farm' + img.farm + '.static.flickr.com/' + img.server + '/' + img.id + '_' + img.secret + '_z.jpg">'+
                        '    <img src="http://farm' + img.farm + '.static.flickr.com/' + img.server + '/' + img.id + '_' + img.secret + '_m.jpg"/>'+
                        '</a>'
                    );
                });
                setContainer.append(columns[0]);
                setContainer.append(columns[1]);
                setContainer.append(columns[2]);
                setContainer.append(columns[3]);
                setContainer.find('.loading').remove();
                setContainer.find('div.column a').lightBox({
                    imageLoading:			'/public/assets/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
                    imageBtnPrev:			'/public/assets/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
                    imageBtnNext:			'/public/assets/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
                    imageBtnClose:			'/public/assets/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
                    imageBlank:			    '/public/assets/lightbox-blank.gif'
                });
            }
        });
    },
    
    /**
     * Returns true if rendered set is the last one.
     */
    renderNextSet: function()
    {
        if (!this.renderedSet) {
            this.renderedSet = 0;
        }
        this.renderSet(this.renderedSet);
        this.renderedSet++;
        if (this.renderedSet == this.sets.length) {
            return true;
        } else {
            return false;
        }
    },
    
    renderSetsList: function(page)
    {
        var self = this;
        $.each(this.sets, function(index){
            if (index >= self.setsPerPage * page || index < self.setsPerPage * (page - 1)) {
                //return false;
            } else {
                if (index < self.expandedSets) {
                    self.renderSet(index, true);
                } else {
                    self.renderSet(index, false);
                }
            }
        });  
    },
    
    renderNextPage: function()
    {
        this.pageLoaded = this.pageLoaded + 1;
        this.renderSetsList(this.pageLoaded);
        console.log([this.setsPerPage, this.pageLoaded, this.sets.length, this.setsPerPage * this.pageLoaded >= this.sets.length]);
        if (this.setsPerPage * this.pageLoaded >= this.sets.length) {
            return true;
        } else {
            return false;
        }
    }
}
