// XHTML live visitor counter
// author: codewolf
// version: 1.0
// http://www.codewolf.com
// XHTML live user count (including this script) is published under a creative commons license
// license: http://creativecommons.org/licenses/by-nc-sa/2.0/

var GetUserCounturl = "getusercount.php";
var number_of_users = 0; //initial value will be replaced by the latest number of users
window.onload = initJavaScript;

function initJavaScript() {
	receiveUserCount(); //initiates the first data query
	handlehHttpReceiveUserCount();
}

//initiates the first data query
function receiveUserCount() {
	if (httpReceiveUserCount.readyState == 4 || httpReceiveUserCount.readyState == 0) {
  	httpReceiveUserCount.open("GET",GetUserCounturl + '?number_of_users=' + number_of_users + '&rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveUserCount.onreadystatechange = handlehHttpReceiveUserCount;
  	httpReceiveUserCount.send(null);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveUserCount() {
  if (httpReceiveUserCount.readyState == 4) {
    results = httpReceiveUserCount.responseText
    insertNewContent(results); //inserts the new content into the page
    setTimeout('receiveUserCount();',20000); //executes the next data query in 4 seconds
  }
}

//inserts the new content into the page
function insertNewContent(linumusers) {
	insertO = document.getElementById("usercount");
	oLi = document.createElement('li');
	oSpan = document.createElement('span');
	oSpan.setAttribute('className','numusers'); //for IE's sake
	oSpan.setAttribute('class','numusers');
	onumusers = document.createTextNode(linumusers);
	oSpan.appendChild(onumusers);
	oLi.appendChild(oSpan);
	insertO.replaceChild(oLi, insertO.firstChild);
}

//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}


// initiates the two objects for sending and receiving data
var httpReceiveUserCount = getHTTPObject();
