var xmlhttp = null;
var shorts = null;
var semaphore = false;

function sliceItem(list, start){
    var copy = [], i;
    
    for (i = start; i < list.length; i++) {
        copy.push(list[i]);
    }
    return copy;
}

function writeShort() {
    var short, values;
    if (xmlhttp != null && xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            values = getElementsByClassName('values', document, 'div')[0];
	    response = xmlhttp.responseText;
            node = document.createElement("DIV");
            node.innerHTML = response;
            values.appendChild(node);
            values.appendChild(getElementsByClassName('jslink',values,'div')[0]);
	    values.appendChild(getElementsByClassName('rightvalues',values,'div')[0]);
	    shorts = sliceItem(shorts, 1);
	    semaphore = false;
            xmlhttp = null;
	    uploadshortviews();
	
        }
    }
}

function uploadShort () {

    if (shorts[0] != null) { 
       xmlhttp = createRequestObject();
       xmlhttp.open('GET', shorts[0].firstChild.nodeValue+'/@@shortpage', true);
       xmlhttp.onreadystatechange = writeShort;
       xmlhttp.send(null);
    }
}

function uploadShortUrls() {
    var response;

    if (xmlhttp != null && xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
                response = xmlhttp.responseXML;
	        shorts = response.getElementsByTagName('span');

  	        shorts = sliceItem(shorts, 3);
	        uploadShort();
	    }
    }
}

function getShortUrls(url) {

  semaphore = true;
  xmlhttp = createRequestObject();
  xmlhttp.open('GET', url,  true); 
  xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  xmlhttp.onreadystatechange = uploadShortUrls;
  xmlhttp.send(null);
}

function uploadshortviews() {
    var wh, bh, sh,
    elem, url, jslink;

    // window height
    wh = parseInt(window.innerHeight || document.documentElement.clientHeight);

    // body height
    bh = parseInt(document.body.offsetHeight);
    // scrollbar height
    sh = (bh / (bh / wh)).toFixed(0);
    // document.body.scrollTop is the same that
    // window.pageYOffset and the sale that
    // document.documentElement.scrollTop
    if (document.documentElement.scrollTop > (bh - sh * 2)) {
        if (semaphore == false) {
	    semaphore = true;

            if (shorts != null) {
                  uploadShort();
            } else {
                  jslink = getElementsByClassName('jslink', document, 'div')[0];

                  elem = jslink.getElementsByTagName('a')[0];

                  url = elem.href;

                  getShortUrls(url);
            }
        }
    }
}

