// ==UserScript==
// @name         Google Auto Pager 2008
// @namespace	   http://ma.la/
// @author	  	 ma.la <timpo@ma.la>
// @include	  	 http://www.google.*/search*
// @description	 Auto-loads next page of Google search results.
// @source	  	 http://userscripts.org/scripts/show/8430
// @date	  	   25-10-2008
// @version	  	 1.06.1 modified by Protector one, originally Pawel Kubisz
// ==/UserScript==


(function(){

	var base = "http://"+location.host+"/search";
	var startNr;
	var itemsQuantity;
	var storageContainer;
	var resultsCount;
	var query;
	var loadingElemID = 'nav';
	var Enable = -1;
	var currVer = '1.05';
	var tmpnodes;

	function remain() {
    var scroll = document.documentElement.scrollTop;
    var total = document.documentElement.scrollHeight;
    return total - scroll;
  }
	
  function endScroll() {
    if (remain() < 1100 && Enable == 1) {
      Enable = -1;
      document.body.style.cursor = 'wait';
      do_request();
      waitInterval = setTimeout(function(){
        document.body.style.cursor = 'auto';
      },300);
    }
	}

	function existNodeNN() {
    var ob = document.getElementById('ssb'); // Results x of x
    var res = ob.innerHTML.split('\n')[1].match(/[\d|,]+/g);
    return res[1]!=res[2];
	}
  
  function getResultNodes() {
    var node = document.getElementById('googleResult');
    if(!node){return false;}
    tmpnodes = node.getElementsByTagName('li');
    var res = [];
    for(var i in tmpnodes){
      if(tmpnodes[i].className == 'g'){
        res.push(tmpnodes[i]);
      }
    }
    return res;
	}

	function appendSearchResult(){
    var startTime = new Date().getTime();
    var list = getResultNodes();
    for (var i = 0, j = list.length; i < j; i++){
      resultsCount++;
      storageContainer.appendChild(list[i]);
    }
    startNr += itemsQuantity;
    var ob = document.getElementById('ssb');
    var res = ob.innerHTML.split('\n')[1].match(/[\d|,]+/g);
    var front = res[0]+'</B> - <B>';
    var nuw = Math.min(parseInt(res[2].replace(/,/g,'')),startNr)
    ob.innerHTML = ob.innerHTML.replace(front+res[1],front+nuw);
    if (existNodeNN()){
      Enable = 1;
    }else{
      insertEndText();
    }
    document.body.removeChild(document.getElementById('googleResult'));
	}

	function addCounter(it, rc){
    var nr = rc + ". ";
    it.insertBefore(document.createTextNode(nr), it.firstChild);
	}

	function insertEndText() {
    var elem = document.createElement("div");
    elem.innerHTML = "End of the search results";
    with (elem.style){
      padding = "0.3em";
      marginBottom = "5em";
      background = "#EBEFF9";
      color = "#000000";
      fontWeight = "bold";
      textDecoration = "blink";
    }
    var sumdiv = document.getElementById('bsf');
    sumdiv.parentNode.insertBefore(elem,sumdiv);
	}
  
	function insertLoadingText() {
    var wait = document.getElementById(loadingElemID);
    if(wait){
      var par = wait.parentNode;
      var nu = document.createElement('div');
      nu.id = loadingElemID;
      par.insertBefore(nu,wait);
      par.removeChild(wait);
      nu.innerHTML = '<tbody><div style="margin: 0 auto; width: 176px; height: 63px;"><p style="margin: 0; padding: 20px 0 0 15px; font-weight: bold; font-size: 130%; color: rgb(34, 34, 34);">Loading</p></div></tbody>';
    }
	}

	function do_request(){
    document.getElementById(loadingElemID).style.display = 'block';
    var xmlhttp = PRO_xmlhttpRequest();
    if (query.search('start=') < 0){
      var url = base + query + '&start=' + startNr;
    }else{
      var url = base + query.replace(/start=\d+/,'start=' + startNr);
    }
    xmlhttp.open("GET", url, true); 
    xmlhttp.onreadystatechange = function(){
      if(xmlhttp.readyState == 4){
        document.getElementById(loadingElemID).style.display = 'none';
        var googleResult = document.body.appendChild(document.createElement('div'));
        googleResult.innerHTML = xmlhttp.responseText;
        googleResult.style.display = 'none';
        googleResult.id = 'googleResult';
        appendSearchResult();
      }
    }
    xmlhttp.send(null);
	}

	function getStorageContainer() {
    return document.getElementById('res').getElementsByTagName('ol')[0];
	}

	function getResultsCount() {
    var elms = document.getElementsByTagName('div');
    var count = 0;
    for(var i=0; i<elms.length; i++){
      if(elms[i].className == 'g'){ count++; }
    }
    return count;
	}

	function init_autopager(){
      query = location.search;
      if (query.search(/start=(\d+)/) > -1){
        startNr = parseInt(query.match(/start=(\d+)/)[1]);
        var tmp = query.match(/num=(\d+)/);
      }else{
        startNr = 10
      }
  	storageContainer = getStorageContainer();
  	resultsCount = getResultsCount();
  	itemsQuantity = tmp ? (tmp[1] - 0) : 10;
	}

	function dblClickEvents(){
    if (window.location.href.indexOf(base) != -1 && existNodeNN()){
      Enable *= -1;
        onscroll = endScroll;
      init_autopager();
      insertLoadingText();
    }
	}

	function getInitNodes(){
    var res = [];
    var elms = document.getElementsByTagName('div');
    for(var i=0; i<elms.length; i++){
      if(elms[i].className == 'g'){ res.push(elms[i]) };
    }
    return res;
	}
  
  function addStupidNumbers(){
	  var res = getInitNodes();
	  for (var i = 0; i < res.length; i++){
      addCounter(res[i], i+1);
    }
  }
  
  
  // To enable double click activation, comment-switcheroo next 2 lines
  
  //document.body.attachEvent('ondblclick', dblClickEvents);
  dblClickEvents();


})();
