var ourId;
var ourPassword;
var req;
var currentMessage;
var outgoing = new Array();
var to;
var is_ad=0;
var skip = 0;
var loggedIn = false;
var t; //setInterval handle
var em;  //is SSL?
var u=1; // # of users online
var usesecure=false; // offer https link?
// Get an XMLHttpRequest object in a portable way.
function newRequest()
{
	req = false;
	// For Safari, Firefox, and other non-MS browsers
	if (window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch (e) {
			req = false;
		} 
	} else if (window.ActiveXObject) {
		// For Internet Explorer on Windows
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				req = false;
			}
		}
	}
}

// TBB: play sound only if desired.
function playSound(sound, loopcount)
{
	if (get("soff").checked) {
		return;
	}
	soundManager.play(sound, loopcount);
}

function poll()
{
// Try every 5 seconds
	if (req) {
		skip += 1;
		if ((skip<15) && (ourId.substr(0,7) == 'support')) {
			get("drop").innerHTML += skip;
		}
		if (skip == 15) {
			if (ourId.substr(0,7) == 'support') {
				playSound('alarm',30);
				get("answer").style.display = "block";
			}
			alert("Possible lost Internet connection.");
			skip=0;
		}
		// Don't clobber a request in progress,
		return;
	}
	skip = 0;
	get("drop").innerHTML = "";
	newRequest();
	if (!req) {
		location.href = "apology.html";
		return;
	}
	// Asynchronous request
	// don't wait around for an answer, which would
	// block the user from entering more text, etc.
	req.onreadystatechange = pollStateChange;
	req.open("POST", "/battery-finder/server.php", true);
	// We'll send our text with normal form encoding. 
	req.setRequestHeader('Content-Type', 
		'application/x-www-form-urlencoded');
	var encoded = "";
	// TODO: deal with issue of recipient id when support speaks
	if (outgoing.length) {
		var message = outgoing.shift();
		text = message.text;	
		encoded = "message=" + escape(text) + 
			"&to=" + escape(message.to);
		// If the request fails, we can put the
		// message back on the queue and try again.
		currentMessage = message;
	}
	encoded += "&id=" + escape(ourId) + 
		"&password=" + escape(ourPassword);
	req.send(encoded);
}

function pollStateChange()
{
	// 0: unitialized
	// 1: loading
	// 2: loaded
	// 3: interactive
	// 4: complete
	if (req.readyState == 4) {
		// Check for OK HTTP response code
		try {
			if (req.status == 200) {
				// Use the server's response
				// alert(req.responseText);
				var data = req.responseXML;
				if (!data) {
					alert(req.responseText);
				}
				parseXML(data);
			} else {
				// Server error. If there was an
				// outgoing message, push it back
				// on the queue.
				if (currentMessage) {
					outgoing.push(message);
				}
			}
		} catch (e) {
		}
		req = null;
		currentMessage = null;
	}
}

function parseXML(xml)
{
	// What did the server say?
	var users = xml.getElementsByTagName("online");
	var i;
	// check for users list.  Only sent to support
	if (users.length) {
		var html = "";
		var isto = false;
		for (i = 0; (i < users.length); i++) {
			var user = users[i].attributes.getNamedItem("u").value;
			if (user ==  ourId) { continue; }
			if (user == to) { isto = true;}
			html += "<p><a href=\"javascript:speakTo('" + user + "')\">";
			html += user + "</a><p>";
		}
		if (!isto) {
			get('speakToLabel').innerHTML = "";
//			to = ourId;
			to = '';
		}
		if (html) {
			html = "<h2>Users online:</h2>" + html;
		}
		get("usersList").innerHTML = html;
		u = users.length;
	}
	var spoken = xml.getElementsByTagName("speak");
	for (i = 0; (i < spoken.length); i++) {
		var text;
		var id = spoken[i].attributes.getNamedItem("id").value;
		var html = "<p><strong>" + spoken[i].attributes.getNamedItem("t").value + " </strong>";
		em = spoken[i].attributes.getNamedItem("e").value;
		var d = spoken[i].attributes.getNamedItem("d").value;
		if (em) { html += '<img src="secure.gif" alt="(Secure)" />';}
		html += '<span class="name">';
		if ((ourId.substr(0,7) == 'support') && (id != ourId)) {
			html += "<a href=\"javascript:speakTo('" + id + "')\">" + id + "</a>";
		} else {
		html += id; }
		if ((ourId.substr(0,7) == 'support') && (u>2) && (d) && (d != ourId)) {
			html+= " to " + d;
		}
		html += '</span>: ';
		if (spoken[i].childNodes.length) {
			// The text will be in a CDATA (text) node inside
			// the speak node.
			text = spoken[i].firstChild.nodeValue;
			// Any HTML entities within the XML
			// were escaped *for XML* and now need escaping again
			// to be used *as HTML* without
			// being treated as elements.
			if ((!text.match(/[a-z]+:\/\/[^\s\w/]?[\w/]*/i)) && (!text.match(/[a-z0-9._%+-]+@[.-]?[a-z0-9]*/i))) {
			text = text.replace('&', '&amp;');
			text = text.replace('<', '&lt;');
			text = text.replace('>', '&gt;');
			}
		}
		if (id.substr(0,7) == "support") {
			html += '<span class="ad">' + text + '</span>';
		} else {
			html += text;
		}
	 	html += "</p>";
		var output = get("output");
		output.innerHTML += html;
		output.scrollTop = output.scrollHeight;
		if (ourId.substr(0,7) == 'support') {
			if (text == id + ' has just logged in.')
			{
				speakTo(id);
				if (id.substr(0,7) == 'support') {
					playSound('ring');
				} else if (get("roff").checked) {
					playSound('in');
				} else
				{
					get('answer').style.display = 'inline';
					get('setring').style.display = 'block';
					playSound('ring', 30);
				}
			} else if (text.match('has logged out.')) {
				playSound('out');
			}
			else { playSound('talk'); }
		}
		else { playSound('talk'); }
	}
}
function speakTo(id)
{
// only used by support
	if (id == ourId) {
		return;
	}
	to = id;
	var speakToLabel = get('speakToLabel');
	speakToLabel.innerHTML = "<p>Speaking to: " +
		"<span class=\"speakingToName\">" + id +
		"</p>";
	// Send text focus back to the input area
	var i = get("chatinput");
	i.focus();
}

function getKey(event)
{
	var key;
	// Different browsers hide the
	// keycode in different places
	if (window.event) {
		key = window.event.keyCode;
	} else if (event) {
		key = event.which;
	}
	return key;
}
function checkEnter(i, event)
{
	if (!loggedIn) {
		return;
	}
	var key = getKey(event);
	if (!key) {
		return;
	}
	// 13 is the ASCII code for
	// the enter key
	if (key == 13) {
		enqueueSpeech();
		return false;
	}	
	return true;
}
function messageMaker(text, to)
{
	this.text = text;	
	this.to = to;
}

function enqueueSpeech()
{
	// Append to the queue of things
	// to be said
	var i = get("chatinput");
	var message = new messageMaker(i.value, to);
	if (!to) {
		alert("Click on the name of a customer first.");
		return;
	}
	outgoing[outgoing.length] = message;
	i.value = "";	
	// Force a poll for perceived snappiness
	poll();
}
function checkPasswordVisible(event)
{
	var i = get("id");
	var pf = get("passwordFields");
	if (i.value.substr(0,7) == "support") {
		pf.style.display = 'block';	
	} else {		
		pf.style.display = 'none';	
	}
}

function logInNow(event)
{
	var i = get("id");
	var p = get("password");
	newRequest();
	req.open("POST", "/battery-finder/server.php", false);
	req.setRequestHeader('Content-Type', 
		'application/x-www-form-urlencoded');
	var encoded = "";
	encoded = "id=" + escape(i.value) + 
		"&password=" + escape(p.value) +
		"&login=1";
	req.send(encoded);
	var message = "Communications Error";
	if (req.status == 200) {
		// Use the server's response
		// alert(req.responseText);
		var xml = req.responseXML;
		if (xml) {
			var login = xml.getElementsByTagName("login");
			if (login.length) {
				login = login[0];
				var success = 
					login.attributes.getNamedItem("success").value;
				if (success == 1) {
					loggedIn = true;
					em = login.attributes.getNamedItem("e").value;
				} else {
					message = login.attributes.getNamedItem("message").value;
				}
			}
		} else {
			alert(req.responseText);
		}
		req = null;
	} else {
		alert(req.responseText);
	}
	if (loggedIn) {
		get("login").style.display = 'none';
		get("intro").style.display = 'none';
		get("loggedin").style.display = 'block';
		get("interface").style.display = 'block';
		var chatinput = get("chatinput");
		chatinput.focus();
		ourId = i.value;
		if (ourId.substr(0,7) != 'support') {
			get('setring').style.display = 'none';
		} else {
			to ='';
		}	
		ourPassword = p.value;
		get("ourId").innerHTML = ourId;
		if (em) {
			get("ourId").innerHTML += '<img src="secure.gif" alt="(Secure)" />';
		}
		poll();
		t = setInterval('poll()',5000);
	} else {
		alert("Logon failed: " + message);
	}
}
function get(name)
{
	return document.getElementById(name);
}

function init()
{
	ourId = "";
	to = 'support';
	ourPassword = "";
	get("login").style.display = 'block';
	get("interface").style.display = 'none';
	get("loggedin").style.display = 'none';
	get("usersList").innerHTML = "";
	get("output").innerHTML = "";
	get("speakToLabel").innerHTML = "";
	checkPasswordVisible();
	var i = get("id");
	if (i.value != "") {
		if (i.value.substr(0,7) == "support") {
			var p = get("password");
			p.focus();
		} else {
			var b = get("loginButton");
			b.focus();
		}
	} else {
		i.focus();
	}
}

function idEnter(i, event)
{
	var key = getKey(event);
	if (!key) {
		return;
	}
	if (key == 13) {
		if (i.value.substr(0,7) == 'support') {
			get('password').focus();
		} else {	
			logInNow();
		}
	} else {
		// Let the keystroke be added BEFORE
		// we check whether the id is now
		// 'support' and show the password
		// if needed.	
		setTimeout('checkPasswordVisible()', 10);
	}
}

function passwordEnter(i, event)
{
	var key = getKey(event);
	if (!key) {
		return;
	}
	if (key == 13) {
		logInNow();
	}	
}

function logOut()
{
	if (!loggedIn) {
		return;
	}
	if (req) {
		req.abort();
	}
	newRequest();
	req.open("POST", "/battery-finder/server.php", false);
	req.setRequestHeader('Content-Type', 
		'application/x-www-form-urlencoded');
	var encoded = "";
	encoded = "id=" + escape(ourId) + 
		"&password=" + escape(ourPassword) +
		"&logout=1";
	req.send(encoded);
	loggedIn = false;	
	clearInterval(t);
	init();
}