// wp-autopager.js
//  Released under the GPL license
//   http://www.gnu.org/copyleft/gpl.html

//  this script based on
//   GoogleAutoPager(http://la.ma.la/blog/diary_200506231749.htm)
//   thanks to ma.la.

function autopager(q,n,m){
  var query;
  var next_page = 0;
  var max_page = 0;
  var insertPoint;
  var Enable = 1;
  var loading = false;
  var last_page = false;

  // Array.prototype.contains()
  // Whether the value that exists in the array is included is examined.
  // Core code from - Reread (http://text.readalittle.net/article.php?id=135)
  if(!Array.prototype.contains){
    Array.prototype.contains = function(value){
      for(var i in this){if(this.hasOwnProperty(i) && this[i]===value){return true;}}
      return false;
    }
  }

  // getPageScroll()
  // Returns array with x,y page scroll values.
  // Core code from - quirksmode.org
  var getPageScroll = function(){
    var xScroll,yScroll;
    if (window.pageYOffset) {
      xScroll = window.pageXOffset;
      yScroll = window.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){
      // Explorer 6 Strict
      xScroll = document.documentElement.scrollLeft;
      yScroll = document.documentElement.scrollTop;
    } else if (document.body) {
      // all other Explorers
      xScroll = document.body.scrollLeft;
      yScroll = document.body.scrollTop;
    }
    arrayPageScroll = new Array(xScroll,yScroll);
    return arrayPageScroll;
  }

  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  var getPageSize = function(){
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
      xScroll = document.body.scrollWidth;
      yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){
      // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
    } else {
      // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (window.innerHeight) {
      // all except Explorer
      windowWidth = window.innerWidth;
      windowHeight = window.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) {
      // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }	
    // for small pages with total height less then height of the viewport
    pageHeight = (yScroll < windowHeight) ? windowHeight : yScroll;
    // for small pages with total width less then width of the viewport
    pageWidth = (xScroll < windowWidth) ? windowWidth : xScroll;

    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
    return arrayPageSize;
  }

  var watch_scroll = function(){
    if (last_page == true) {
      return;
    } else if (loading == false ) {
      var aryPageSize = getPageSize();
      var aryPageScroll = getPageScroll();
      var remain = aryPageSize[1] - aryPageSize[3] - aryPageScroll[1];
      if(remain < 500 && Enable){do_request();}
      var self = arguments.callee;
      setTimeout(self,100);
    } else {
      var self = arguments.callee;
      setTimeout(self,5000);
    }
  };

  var do_request = function(){
    var xmlhttp;

    // Get Next Page
    try{
      try{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }catch(e){
        xmlhttp = new XMLHttpRequest();
      }

      // XMLHttpRequest state change
      xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 1 && loading == false) {
          loading = true;

          // Display Now Loading...
          window.status = "loading ... " + (next_page - 1) +" - " + next_page;
          var p = document.createElement("p");
          var img = document.createElement("img");
          img.setAttribute("src","/wp-content/plugins/wp-autopager/ajax-loader.gif");
          img.setAttribute("alt","Now Loading...");
          img.setAttribute("style","float:left;margin-right:0.5em;");
          p.appendChild(img);
          p.appendChild(document.createTextNode("Now Loading..."));
          insertPoint.innerHTML="";
          insertPoint.appendChild(p);
        }
        if(xmlhttp.readyState == 4) {
          if(xmlhttp.status == 200) {
            var xmlString = xmlhttp.responseText.replace(/[\r\n]/g,"").replace(/.*<body.*?>(.*?)<\/body>.*$/, "$1");
            var newDoc = document.createElement("div");
            newDoc.innerHTML = xmlString;

            var div = newDoc.getElementsByTagName("div");
            var len = div.length;
            for(var i=0; i<len; i++){
              if(div[i].className.split(" ").contains("post")){
                insertPoint.parentNode.insertBefore(div[i],insertPoint);
                i--;len = div.length;
              }
              if(div[i].className.split(" ").contains("navigation")){
                insertPoint.innerHTML = div[i].innerHTML;
                break;
              }
            }

            window.status = "loading ... " + (next_page - 1) +" - " + next_page + " done.";
            next_page ++;
          } else {
            last_page = true;
            insertPoint.innerHTML = "";
          }
          if (max_page != 0 && next_page > max_page) {
           last_page = true;
           insertPoint.innerHTML = "";
          }
          loading = false;
        }
      };

      // XMLHttpRequest
      var href = query+next_page;
      if(href.indexOf("/page/")!=-1) {href = href + "/";}
      href = href.replace("&amp;","&");
      xmlhttp.open("GET", href, true);
      xmlhttp.send(null);

    }catch (e){

    }
  };

  var init_autopager = function(){
    next_page = 0;

    // find insertpoint
    var not_found = true;
    var content = document.getElementById("content");
    var div = content.getElementsByTagName("div");
    var len = div.length;
    for(var i=0;i<len;i++){
      if(div[i].className.split(" ").contains("navigation")){
        insertPoint = div[i];
        not_found = false;
        break;
      }
    }
    if (not_found) {
      insertPoint = document.createElement("div");
      insertPoint.setAttribute("class","navigation");
      content.appendChild(insertPoint);
    }

    // find next link
    if (q!="") {
      query = q;
      next_page = n;
      max_page = m;
      last_page = (max_page != 0 && next_page > max_page);
    } else {
      var a = insertPoint.getElementsByTagName("a");
      var len = a.length;
      for(var i=0;i<len;i++){
        var href = a[i].href;
        if(href.indexOf("/page/")!=-1) {
         var temp = href.match(/^(.+\/)(\d+)\/$/);
         query = temp[1];
         next_page = (temp[2]-0 > next_page) ? temp[2]-0 : next_page;
        }
        if(href.indexOf("paged=")!=-1) {
         var temp = href.match(/^(.+paged=)(\d+)$/);
         query = temp[1];
         next_page = (temp[2]-0 > next_page) ? temp[2]-0 : next_page;
        }
      }
    }

    if (next_page > 0 && last_page == false) {
      // attach Event (Double Click)
      if(document.body.attachEvent){
        document.body.attachEvent(
          "ondblclick",function(){
            Enable = Enable?false:true;
            window.status = (Enable)?"Enabled":"Disabled"
          }
        );
      }else{
        document.body.addEventListener(
          "dblclick",function(){
            Enable = Enable?false:true;
            window.status = (Enable)?"Enabled":"Disabled"
          },true
        );
      };

      // start watch scroll
      watch_scroll();
    }
  };

  // init 
  init_autopager();
};