// AutoPager
var AutoPager = function() {
    this.pageNum = 1;
    this.maxNum = 1000;
    this.state = "enable";
    this.loadedURLs = [];
    this.nextLinkTag = "a";
    this.nextLinkClass = "nextLink";
    this.insertBeforeTag = "div";
    this.insertBeforeClass = "autopagerize_insert_before";
    this.pageElementTag = "div";
    this.pageElementClass = "autopagerize_page_element";
    this.base_Remain_height = 400;
    this.remainHeight = 9999;

    var self = this;
    var url = getNextURL(this.nextLinkClass, this.nextLinkTag, document);
    this.requestURL = url;


    this.insertPoint = this.getInsertPoint();
    this.calcRemainHeight();
    this.scroll= function() { self.onScroll() }
    Event.observe(window, "scroll", this.scroll, false);
    
    this.onScroll()
}

// onScroll
AutoPager.prototype.onScroll = function() {
    var scrollHeight = this.getScrollHeight();
    var innerheight = window.innerHeight || document.documentElement.scrollHeight;
    var scrollY  = window.scrollY || document.body.scrollTop  || document.documentElement.scrollTop;
    
    var remain = scrollHeight - innerheight - scrollY
    
    if (this.state == 'enable' && remain < this.remainHeight && this.pageNum <= this.maxNum) {
          this.request()
    }
}

// request
AutoPager.prototype.request = function() {
    if (!this.requestURL || this.lastRequestURL == this.requestURL) {
        return
    }

    this.lastRequestURL = this.requestURL
    var self = this;
    new Ajax.Request(this.requestURL,
            { method:'get' ,
                onSuccess: function(res){
                             self.requestLoad.apply(self, [res])
                            }
           }
        );
}

// calcRemainHeight
AutoPager.prototype.getInsertPoint = function() {
    var insertList = getElementsByClassName(this.insertBeforeClass, this.insertBeforeTag, document)
    if(!insertList.length){
        return null;
    }
    return insertList[0];
}


// calcRemainHeight
AutoPager.prototype.calcRemainHeight = function() {
    var scrollHeight = this.getScrollHeight();
    var bottom = this.insertPoint.offsetTop
    this.remainHeight = scrollHeight - bottom + this.base_Remain_height
    
}

// getScrollHeight
AutoPager.prototype.getScrollHeight = function() {
    return Math.max(document.documentElement.scrollHeight,
                                document.body.scrollHeight)
}

// getNextURL
function getNextURL(nextLinkClass, nextLinkTag, elem) {
    var nextList = getElementsByClassName(nextLinkClass, nextLinkTag, elem);
    if(!nextList.length){
        return null;
    }
    var next = nextList[0];
    var url = next.href || next.action || next.value;
    return url;
}


// getElementsByClassName
function getElementsByClassName(className, tagName, elem) {
    var i, j, eltClass;
    var objAll = document.getElementsByTagName ? elem.getElementsByTagName(tagName) : elem.all;
    var objCN = new Array();
    for (i = 0; i < objAll.length; i++) {
        eltClass = objAll[i].className.split(/\s+/);
        for (j = 0; j < eltClass.length; j++) {
            if (eltClass[j] == className) {
                objCN.push(objAll[i]);
                break;
            }
        }
    }
    return objCN;
}

// requestLoad
AutoPager.prototype.requestLoad = function( res) {
    
    var str = res.responseText;
    var responseElement = getInsertElement(str, this.pageElementClass, this.pageElementTag);
    var url = getNextURL(this.nextLinkClass, this.nextLinkTag, responseElement);
    
    if (this.loadedURLs[this.requestURL]) {
        debug('page is already loaded.', this.requestURL, this.info.nextLink);
        this.terminate();
        return;
    }

    this.loadedURLs[this.requestURL] = true
    page = this.addPage(responseElement)
    this.requestURL = url
    //this.showLoading(false)
    this.onScroll()
    
}

// getInsertElement
function getInsertElement(responseText, pageElementClass, pageElementTag) {
    var dummy = document.createElement('div');
    dummy.innerHTML = responseText;
    var pageList = getElementsByClassName(pageElementClass, pageElementTag, dummy);
    if(!pageList.length){
        return null;
    }
    
    return pageList[0];
}

// addPage
AutoPager.prototype.addPage = function(responseElemnt) {
    this.insertPoint.parentNode.insertBefore(this.createNavigation(), this.insertPoint)
    this.insertPoint.parentNode.insertBefore(responseElemnt, this.insertPoint)

}

// createNavigation
AutoPager.prototype.createNavigation = function() {
    var div = document.createElement("div")
    div.setAttribute('id', 'autopagerize_controller')
    div.className = "apcontrollerblock";
    var p = document.createElement("p")
    p.innerHTML = 'page: ' + (++this.pageNum);
    div.appendChild(p)
    return div;
}

// stateToggle
AutoPager.prototype.stateToggle = function() {
    if (this.state == 'enable') {
        this.disable()
    }
    else {
        this.enable()
    }
}

// enable
AutoPager.prototype.enable = function() {
    this.state = 'enable'
    this.controller.style.background = AP_COLOR['on']
    this.controller.style.opacity = 1
}

// disable
AutoPager.prototype.disable = function() {
    this.state = 'disable'
    this.controller.style.background = AP_COLOR['off']
    this.controller.style.opacity = 0.5
}

window.onload = function(){
    var ap = new AutoPager();
}

