//------------------------------------------------------------------------------------------

var EndlessPage = {
    ep_getWindowSize : function(w) {
	var width, height;
        w = w ? w : window;
	var win = {
	    width  : (w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth)),
	    height : (w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight))
	};
        return win;
    },
    ep_loadMoreItems : function(opt) {
	// compute amount of page below the current scroll position
	var remaining = ($(opt.wrapper).viewportOffset()[1] + $(opt.wrapper).getHeight()) - document.ep_getWindowSize().height;

	// compute height of bottom element
	var last = $$('.' + opt.line).last().getHeight();

	if (remaining < last*2 && !$('ep_complete')) {
	    if (Ajax.activeRequestCount == 0) {
	        var url = opt.url;
		// Making this possible to config through opt.element_prefix
	        var last = $$('.' + opt.line).last().className.match(/el_[0-9]+/)[0];
                new Ajax.Request(url, {
                        method: 'get',
                        parameters: 'o=' + last + '&' + opt.param,
                        onLoading: function(){
                            $('loading_endlesspage').show();
                        },
                        onSuccess: function(xhr){
                            $('loading_endlesspage').hide();
                            $('loading_endlesspage').insert({before : xhr.responseText})
                        }
                    });
            }
	}
    },
    ep_init : function(opt) {
	//alert('init:' + opt.wrapper);
	// hide the pagination links
	if ($(opt.pagination)) {
	    $(opt.pagination).hide();
	    $(opt.pagination).insert({before : '<div id="loading_endlesspage" style="display: none;"><img src="/tools/ajax/img/loading_animation_liferay.gif" alt="loading..." /></div>'});
	}

	// find to events that could fire loading items at the bottom
	Event.observe(window, 'scroll', function(e) {
		document.ep_loadMoreItems(opt);
	    });

	Event.observe(window, 'resize', function(e) {
		document.ep_loadMoreItems(opt);
	    });
	
    }

};

// Extend document object with new functions.
Object.extend(document, EndlessPage);




//  //------------------------------------------------------------------------------------------
//  // Init functions we think you need after dom is loaded
//  document.observe("dom:loaded", function(){
//  	if ($('ep_artlist')) {
//  	    document.ep_init({
//  		    wrapper    : 'ep_artlist',
//  		    line       : 'ep_line',
//  		    pagination : 'pagination',
//  		    url        : '/tools/wip_v4/template/layout_3/wip4/inc/middle/article_list_1_endless.epl'
//  		});
//  	}
//  
//      });
