var IS_BANDWIDTH_DETECTED = false;
var IS_BANDWIDTH_DETECTION_CANCELLED = false;
var DETECTED_KBPS = "";

function setBandwidth(setBandwidthUrl, kbps) {
	$.ajax({
		async: false,
		type: "POST",
		url: setBandwidthUrl,
		data: {bandwidth: kbps},
		dataType: "json",
		success: function(response) {
			setBandwidthDetected(true);
            setDetectedKbps(response.kbps);
            reportDetectedBandwidth(kbps);
            if (typeof updateMyConnectionSpeed == "function") updateMyConnectionSpeed(response.bandwidth);
		}
	});
}

function reportDetectedBandwidth(kbps) {
    var bwReportString = createbandwidthReportString(kbps);
    cmCreatePageElementTag(bwReportString, "UserBandwidth Auto-Detected");
    // cmPageTag for "Unknown" is located in bandwidthPreferencesPopup.js
}

function createbandwidthReportString(kbps) {
    var rounded = (Math.round(kbps / 100)) * 100;
    if (rounded > 100) {
        return (zeroPad((rounded - 100),6)) + "-" + zeroPad(rounded, 6);
    } else {
        return "000000-000100";
    }
}

function zeroPad(num, count) {
    var numZeropad = num + '';
    while(numZeropad.length < count) {
        numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}

function setBandwidthDetected(value) {
	IS_BANDWIDTH_DETECTED = value && true;
}

function isBandwidthDetected() {
	
	return IS_BANDWIDTH_DETECTED;
}

function setDetectedKbps(value) {
	DETECTED_KBPS = value;
}

function getDetectedKbps() {
	return DETECTED_KBPS;
}

function cancelBandwidthDetection() {
	if(!isBandwidthDetected()) {
		IS_BANDWIDTH_DETECTION_CANCELLED = true;
	}
}

function isBandwidthDetectionCancelled () {
	return IS_BANDWIDTH_DETECTION_CANCELLED;
}

function isFlashInstalled() {
 return DetectFlashVer(9, 0, 0);
}

function getBandwidthClientEmbedCode() {
	var code = "";
	code = AC_FL_GetContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
			'width', '1',
			'height', '1',
			'src', '/staticFlash/BandwidthClient',
			'quality', 'high',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'align', 'middle',
			'play', 'true',
			'loop', 'true',
			'scale', 'showall',
			'wmode', 'window',
			'devicefont', 'false',
			'id', 'BandwidthClient',
			'bgcolor', '#777777',
			'name', 'BandwidthClient',
			'menu', 'true',
			'allowFullScreen', 'false',
			'allowScriptAccess','sameDomain',
			'movie', '/staticFlash/BandwidthClient',
			'salign', ''
		); //end AC code
	return code;
}