if (typeof Effect == 'undefined') 
	throw("thumbModule.js requires including script.aculo.us' effects.js library!");


var thumbModule = Class.create();
thumbModule.prototype = {

    url: '/data/interface.php', //API URL
    apiName: '', //The API call to make such as NetworkThumbnailRequest
    cache: null, //Cache each page after it's loaded
    divID: '', //ID for the div that holds the thumbnails
    userID: '', //Profile user id
    page: 0, //The current page
    type: 'friends', //The type of request
    pageLinks: [], //Save the 'click' event data so that I can unobserve them later.  Help prevents memory leaks, I think.
    numPerPage: 5,
    container : null,
    oldPage: 0,
    firstRun: true,
    
    initialize : function(id, apiName, user_id, func) {
        this.apiName = apiName;
        this.divID = id;
        this.userID = user_id;
        this.formLink = func;
        this.cache = new Object();
        this.pageLinks = new Array();
        this.firstRun = true;
    },
    
    getThumbs : function(start, num, type) {
        var postData = '';
        postData += '<InstantFame format="json"><'+this.apiName+'>';
        postData += '<user_id>'+this.userID+'</user_id>';
        postData += '<start>'+start+'</start>';
        postData += '<number>'+num+'</number>';
        postData += '<network>'+type+'</network>';
        postData += '</'+this.apiName+'></InstantFame>';

        this.oldPage = this.page;
        this.page = Math.ceil(start/5)+1;
        this.type = type;
        
        if(typeof this.cache[this.page] != 'undefined') {
            this.onSuccess(this.cache[this.page], null);
        } else {        
            new Ajax.Request(this.url, {
                method: 'post',
                postBody: postData,
                onSuccess : this.onSuccess.bind(this)
            });
        }
    },
    
    onSuccess : function(transport, jsonResponse) {
        var json = transport.responseJSON.items;
        if(json.length == 0) return;
        
        var mask = $(this.divID);
        mask.setStyle({height:'80px'});
        var container;
        
        if(this.firstRun) {
            mask.childElements().each(function(item) { item.remove() });
            container = new Element('div');
            container.setStyle({position:'absolute',width:'6000px'});
            mask.insert(container);
            this.container = container;
            var hasEmpty = mask.select('div.empty');
            this.firstRun = false;
        } else {
            container = this.container;
        }
        

        
        var pagination = mask.next();
        if(!pagination) {
            var pag = new Element('div');
            pag.addClassName('pagination');
            mask.ancestors()[0].insert(pag);
            pagination = mask.next();
        }
        var total = transport.responseJSON.total;
        var totalpages = Math.ceil(total / this.numPerPage);
		
        var items = container.childElements();

        for(var i = 0; i < items.length; i++) {
            var item = items[i];
          
            if(this.page >= this.oldPage) {
                new Effect.Parallel([
                    new Effect.Scale(item, 0, { scaleY:false, scaleContent:false, sync:true }),
                    new Effect.Opacity(item, { from:1.0,to:0.0, sync:true })
                ], {
                    duration:0.5,
                    afterFinish: function() { this.remove(); }.bind(item)
                });
            } else {
                item.remove();
            }
        }
        for(var i = 0; i < json.length; i++) {
            var div = new Element('div');
            var a = new Element('a');
            var img = new Element('img');
            var h5nam = new Element('h5');
            var h5loc = new Element('h5');
            
            div.addClassName('friend');
            a.writeAttribute('href', this.formLink(json[i]));
            img.addClassName('thumb');
            img.writeAttribute('src', json[i].thumbnail);
            img.writeAttribute('width',55);
            img.writeAttribute('height',55);
            a.insert(img);
            h5nam.insert(json[i].label);
            h5loc.insert(json[i].location);
            div.insert(a);
            div.insert(h5nam);
            container.insert(div);
        }
        
        this.cache[this.page] = transport;
                
        var paginationLinks = pagination.childElements();

        for(var i = 0; i < paginationLinks.length; i++) {
            var func = this.pageLinks.shift();
            paginationLinks[i].stopObserving('click', func);
            paginationLinks[i].remove();
        }
        pagination.innerHTML = '';

        var s = Math.min(this.page-2, totalpages-4);
        s = s<1?1:s;
        var end = Math.min(s+4, totalpages);
        
        if(totalpages > 1) {
            if(s > 1) {
                var a = new Element('a');
                a.insert('&laquo;');
                a.writeAttribute('href', '/profile/'+this.userID);
                a.onclick = function() { return false; };
                var func = function(start, num) {
                    this.getThumbs(start, num, this.type);
                }.bind(this,(this.page-2)*this.numPerPage,this.numPerPage);
                this.pageLinks.push(func);
                a.observe('click', func);           
                pagination.insert(a);
            }
            for(var i = s; i <= end; i++) {
                if(i == this.page) {
                    pagination.insert(i + '&nbsp;');
                } else {
                    var a = new Element('a');
                    a.insert(i);
                    a.writeAttribute('href', '/profile/'+this.userID);
                    a.onclick = function() { return false; };
                    var func = function(start, num) {
                        this.getThumbs(start, num, this.type);
                    }.bind(this,(i-1)*this.numPerPage,this.numPerPage);
                    this.pageLinks.push(func);
                    a.observe('click', func);           
                    pagination.insert(a);
                    pagination.insert('&nbsp;');
                }
            }
			
            if(end < totalpages) {
                var a = new Element('a');
                a.insert('&raquo;');
                a.writeAttribute('href', '/profile/'+this.userID);
                a.onclick = function() { return false; };
                var func = function(start, num) {
                    this.getThumbs(start, num, this.type);
                }.bind(this,(this.page)*this.numPerPage,this.numPerPage);
                this.pageLinks.push(func);
                a.observe('click', func);           
                pagination.insert(a);
            }
        }
    }
}

