var request = null;
var begTime = 0;
var endTime = 0;

function createRequestObject() {
	var tmpXmlHttpObject;
    
    // depending on what the browser supports, 
    // use the right way to create the XMLHttpRequest object
    if (window.XMLHttpRequest) { 
        // Mozilla, Safari, etc
        tmpXmlHttpObject = new XMLHttpRequest();
    } else if (window.ActiveXObject) { 
        // Internet Explorer
        tmpXmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
    }
    
    return tmpXmlHttpObject;
}

function startBandwidthTest() {
	var curDate = new Date();
	begTime = curDate.getTime();
	
	request = createRequestObject();
	request.open('post', 'detectbandwidth.256'); 
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.onreadystatechange = processResponse;
	
	request.send('?no-cache=' + begTime);
}

function processResponse() {
	if (request.readyState == 4) {
		var curDate = new Date();
		endTime = curDate.getTime();
		
		request = null; // is there a better way to free up memory
		
		var duration = endTime - begTime;
	    var kbps = (256 / (duration / 1000));
	    
	    if (kbps.toFixed(1) <= 57) {
	        var supportValue = kbps.toFixed(1) + ' kbps (Dialup)';
	        document.getElementById('btmysys').innerHTML = kbps.toFixed(1) + ' kbps Dialup';
	    } else if (kbps.toFixed(1) < 100) {
	        var supportValue = kbps.toFixed(1) + ' kbps (Broadband)';
	        document.getElementById('btmysys').innerHTML = kbps.toFixed(1) + ' kbps Broadband';
	    } else {
	        var supportValue = kbps.toFixed(1) + ' kbps (High Speed Network)';
	        document.getElementById('btmysys').innerHTML = 'High Speed Network';
	    }
	    
	    if (isFaq) { return; }
	    
	    var ismin = (parseFloat(kbps.toFixed(1)) >= 56) ? 1 : 0;
        var isrec = (parseFloat(kbps.toFixed(1)) >= 100) ? 1 : 0;
        
        if (isrec) {
            document.getElementById('bandwidthicon').innerHTML = '<img src="icon-ok.png" />';
        } else if (ismin) {
            document.getElementById('bandwidthicon').innerHTML = '<img src="icon-warning.png" />';
        } else {
            errors++; // count our errors
            document.getElementById('bandwidthicon').innerHTML = '<img src="icon-error.png" />';
        }
        
        showhowto(ismin, isrec, 'bt');
        
        // disable the ticket button when their bandwidth is too low
        // if (errors > 0) {
        //    document.getElementById('sticket').disabled = true;
        // }
        
        // create a hidden input that will be used to send data to support
        hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'bt');
        hiddenInput.setAttribute('value', supportValue);
        
        inputs[inputs.length] = hiddenInput;
        
        document.getElementById('support').appendChild(inputs[inputs.length - 1]);  
	}
}
