var moveTime = 70; // milliseconds
var fluctuationTime = 400; // milliseconds

var speedText = new Array();
speedText[0] = '0'
speedText[4] = 'till 4 Mbit/s';
speedText[8] = '4-8 Mbit/s';
speedText[15] = '8-15 Mbit/s';
speedText[20] = '12-20 Mbit/s';

var fluctuation = new Array();
fluctuation[4] = 1;
fluctuation[8] = 5;
fluctuation[15] = 10;
fluctuation[20] = 14;

/* INITIALIZATION */

window.onload = function () {
	var supportCheck = document.createElement && document.getElementsByTagName && createXMLHTTPObject();
	if (!supportCheck) return;
	document.getElementById('submitImage').style.display = 'none';
	var formFields = document.getElementsByTagName('input');
	for (var i=0;i<formFields.length;i++) {
		if (formFields[i].type != 'text') continue;
		formFields[i].onkeyup = initSendData;
	}
	document.forms[0].onsubmit = initSendData;
}

var oldQueryString,sending;

function initSendData() {
	if (sending)
		clearTimeout(sending)
	sending = setTimeout('sendData()',500);
	return false;
}

function sendData() {
	var postCode = document.getElementById('postcode').value;
	var number = document.getElementById('huisnummer').value;
	if (postCode.length < 2) return;
	var queryString = '?postcode='+postCode+'&huisnummer='+number;
	if (queryString == oldQueryString) return;
	sendRequest('ajax_endpoint.php'+queryString, catchData);
	oldQueryString = queryString;
}

var currentSpeed = 0;

function catchData(req) {
	var returnXML = req.responseXML;
	if (!returnXML) return;
	var speed = parseInt(returnXML.getElementsByTagName('speed')[0].firstChild.nodeValue);
	if (speed != currentSpeed)
		moveToNewSpeed(speed);
	currentSpeed = speed;
	var error = returnXML.getElementsByTagName('message')[0].firstChild;
	if (error) {
		document.getElementById('errorMessage').innerHTML = error.nodeValue;
		document.getElementById('errorMessage').style.visibility = 'visible';
	}
	else
		document.getElementById('errorMessage').style.visibility = 'hidden';
}

/* ANIMATION */

function setWidth(width) {
	if (width < 0) width = 0;
	document.getElementById('meter').style.width = width + 'px';
}

var currentMbit = 0; // in Mbit; 1 Mbit = 14 pixels = 2 steps of 7 pixels
var animationSteps = new Array();

function moveToNewSpeed(Mbit) {
	for (var i=0;i<animationSteps.length;i++)
		clearTimeout(animationSteps[i]);
	animationSteps.length = 0;
	setWidth(currentMbit*14);
	var distance = Mbit - currentMbit;
	var direction = distance/Math.abs(distance);
	if (!direction) return;
	clearInterval(fluctuationInterval);
	document.getElementById('speed').innerHTML = speedText[Mbit];
	var timeoutCounter = 1;
	var pos = currentMbit*2;
	do {
		pos += direction;
		animationSteps[timeoutCounter] = setTimeout('setWidth(' + (pos*7) + ')',timeoutCounter*moveTime);
		timeoutCounter++;
	} while (pos != Mbit*2)
	currentMbit = parseInt(Mbit);
	setTimeout('initFluctuation()',timeoutCounter*moveTime);
}

var fluctuationBottom;
var currentFluctuation;
var fluctuationInterval;

function initFluctuation() {
	currentFluctuation = currentMbit*2;
	fluctuationBottom = fluctuation[currentSpeed];
	fluctuationInterval = setInterval('fluctuate()',fluctuationTime);	
}

function fluctuate() {
	var fluctuationDirection = (Math.random() < .5) ? 1 : -1;
	var newPos = currentFluctuation + fluctuationDirection;
	if (newPos > currentMbit*2 || newPos < fluctuationBottom*2)
		fluctuationDirection = -fluctuationDirection;
	currentFluctuation += fluctuationDirection;
	setWidth(currentFluctuation*7);
}

/* XMLHTTP */

function sendRequest(url,callback,postData) {
	var req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method,url,true);
	req.setRequestHeader('User-Agent','XMLHTTP/1.0');
	if (postData)
		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
			alert('HTTP error ' + req.status);
			return;
		}
		callback(req);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}

var XMLHttpFactories = [
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")},
];

function createXMLHTTPObject() {
	var xmlhttp = false;
	for (var i=0;i<XMLHttpFactories.length;i++)
	{
		try {
			xmlhttp = XMLHttpFactories[i]();
		}
		catch (e) {
			continue;
		}
		break;
	}
	return xmlhttp;
}
