// JavaScript Document
var output;
var clickCount = 0;
var visitorName;
var connector;
var ex;
var ey;
var debugOutput;
var cursors;
var movecount = 0;

function init()
{
	//alert("initializing...");
	cursors = new Object();
	output = document.getElementById("mouseCoordinates");
	document.onmousemove = onMouseMove;
	connector = getConnector();
	debugOutput = document.getElementById("debug");
}

function onMouseMove(e)
{
	//alert("test");
	movecount++;
	if(movecount >= 10)
	{
		var o = new Object();
		o.name = visitorName;
		if(isIE)
		{
			//output.innerHTML = event.clientX + ", " + event.clientY;
			o.x = event.clientX + document.body.scrollLeft;
			o.y = event.clientY + document.body.scrollTop;
		}
		else
		{
			//output.innerHTML = e.clientX + ", " + e.clientY;
			o.x = e.pageX;
			o.y = e.pageY;
		}
		//send(o);
		if(connector)
		{
			try
			{
				connector.publish(visitorName, o);	
			}
			catch(ex)
			{
				// ingore for now.	
			}
		}
		/*
		if(ex)
		{
			ex.innerHTML = o.x;	
		}
		if(ey)
		{
			ey.innerHTML = o.y;
		}
		*/
		movecount = 0;
	}
	else
	{
		return;
	}
	
	
}

// Called by the server when a visitor arrives 
function addVisitor(id, name, ip)
{
	if(name != visitorName)
	{
		createElement(name, name + " [" + ip + "] <img align=\"middle\" src=\"http://work.dallanporter.com/geolocate/getFlag.php?ip=" + ip  + "\" /> <img align=\"middle\" src=\"http://www.porterdigital.com/mini_cursor.png\" /> (<span id=\"" + name + "x\">-</span>,<span id=\"" + name + "y\">-</span>)", "visitorList");
		subscribeCursor(name); // let's try auto subscribing to remote cursors automatically.
	}
	
	else
	{
		// creating myself
		createElement(name, "me [" + ip + "] <img align=\"middle\" src=\"http://work.dallanporter.com/geolocate/getFlag.php?ip=" + ip  + "\" /> <img align=\"middle\" src=\"http://www.porterdigital.com/mini_cursor.png\" /> (<span id=\"" + name + "x\">-</span>,<span id=\"" + name + "y\">-</span>)", "visitorList");
		ex = document.getElementById(name + "x");
		ey = document.getElementById(name + "y");
	}
	//var con = getConnector();
	
}

function subscribeCursor(visitorName)
{
	if(connector)
	{
		connector.subscribe(visitorName, "onCursorData");
		createElement(visitorName + "_cursor", "<img src=\"http://www.porterdigital.com/ghost_cur.png\" />");
		updateCSS(visitorName + "_cursor", "position:absolute;width:18px;height:22px;left:20px;top:20px;");
		cursors[visitorName] = document.getElementById(visitorName + "_cursor");
		
	}
}

// Called by the server when a visitor leaves
function removeVisitor(visitorID, visitorName)
{
	removeElement(visitorName);
	removeElement(visitorName + "_cursor"); // remove the cursor if it's been created
	//var con = getConnector();
	if(connector)
	{
		try
		{
			connector.unsubscribe(visitorName); // unsubscribe to visitor events	
		}
		catch(ex)
		{
			// ignore for now	
		}
	}
	
}

function send(obj)
{
	/*
	var con = getConnector();
	try
	{
		con.sendMouse(obj);
	}
	catch(e)
	{
		//alert("Failed to get handle to Live Data Connector.");
	}
	*/
}

// Helper to get handle to Async proxy connector element
function getConnector() {
	 if (navigator.appName.indexOf("Microsoft") != -1) {
		 return window["PushManager"];
	 } else {
		 return document["PushManager"];
	 }
 }
 
// Called be either local JS or remote server to update an existing HTML element
function updateElement(id, content)
{
	var e = document.getElementById(id);
	if(e)
	{
		e.innerHTML = content;
	}
}

// Called be either local JS or remote server to update an existing HTML element
 function createElement(id, content)
 {

	var e = document.getElementById(id)
	if(e)
	{
		// already exists
	}
	else
	{
		// Let's create it now.
		var newe = document.createElement('div');
		newe.setAttribute('id', id);
		newe.innerHTML = content;
		document.body.appendChild(newe);

	}
 }

// Called be either local JS or remote server to create a new HTML element
 function createElement(id, content, parentId)
 {
	var parent = null;
	if(parentId != null || parentId != "")
	{
		parent = document.getElementById(parentId);
	}
	var e = document.getElementById(id)
	if(e)
	{
		// already exists
	}
	else
	{
		// Let's create it now.
		var newe = document.createElement("div");
		newe.setAttribute("id", id);
		newe.innerHTML = content;
		if(parent == null)
		{
			document.body.appendChild(newe);
		}
		else
		{
			parent.appendChild(newe);	
		}
	}
 }
 
 // Called be either local JS or remote server to remove an existing HTML element
 function removeElement(id)
 {
	var e = document.getElementById(id);
	//alert("inside removeElement(" + id + ")");
	if(e)
	{
		e.parentNode.removeChild(e);
	}	
 }
 
 // Called be either local JS or remote server to update an existing HTML elements CSS
 function updateCSS(id, newCSS)
 {
	var e = document.getElementById(id);
	var array;
	if(e)
	{
		array = newCSS.split(";");
		for(var i=0; i<array.length; i++)
		{
			var array2 = array[i].split(":");
			//alert("element[" + id + "] => " + array2[0] + " -> " + array2[1] + "!");
			if(isIE)
			{
				//alert("result -> " + toCamelCase(array2[0]));
				e.style[toCamelCase(array2[0])] = array2[1];
			}
			else
			{
				e.style.setProperty(array2[0], array2[1], '');
			}
		}
	}
 }
 
 // Helper function to change a dashed-css name to camelCase (IE requires this)
 function toCamelCase(value)
 {
	if(value.indexOf('-') > -1)
	{
		var test = /(-[a-z])/i.exec(value);
		return value.replace(RegExp.$1, RegExp.$1.substr(1).toUpperCase());
	}
	else 
	{
		return value;
	}
 }
 
 // Called by the server when a remote visitor clicks somewhere on the page
 function remoteClick(url, visitor, x, y, ip)
 {
	//alert(url + " " + visitor + " " + x + " " + y);
	var id = "click" + (clickCount++).toString();
	createElement(id, "x");
	var newcss = "position:absolute;width:50px;height:50px;top:" +
				(parseInt(y)-25).toString() + "px;left:" + (parseInt(x)-25).toString() + "px;";
	updateElement(id, "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0\" width=\"50\" height=\"50\">" +
					"<param name=\"movie\" value=\"http://www.porterdigital.com/click.swf\" />" +
					"<param name=\"quality\" value=\"high\" />" +
					"<param name=\"wmode\" value=\"transparent\" />" +
					"<param name=flashvars VALUE=\"visitorName=" + visitor + "\">" +
					"<embed src=\"http://www.porterdigital.com/click.swf\" wmode=\"transparent\" flashvars=\"visitorName=" + visitor + "\" quality=\"high\" pluginspage=\"http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=\"50\" height=\"50\"></embed>" +
					"</object>");
	updateCSS(id, newcss);
	updateCSS(visitor, "color:red");
	//setTimeout("removeElement('" + id + "')", 1000);
	setTimeout("onTimeout('" + id + "', '" + visitor + "')", 1000);
 }
 
 function onTimeout(visitorID, visitor)
 {
	 removeElement(visitorID);
	 updateCSS(visitor, "color:");
 }
 
 // Called by JS when local visitor clicks 
 function onClick(e)
 {
	//var con = getConnector();
	if(connector)
	{
		if(isIE)
		{
			//alert("inside onClick(" + event +  ")");
			connector.sendClick(location.href, event.clientX + document.body.scrollLeft, event.clientY + document.body.scrollTop);
		}
		else
		{
			//alert("inside onClick(" + e + ")");
			connector.sendClick(location.href, e.pageX, e.pageY);
			//con.click("testpage", 100, 100);
		}
	}
	else
	{
		//alert("Error getting handle to connector.");
	}
 }
 
 // Called by the server when the connection is established
 function onConfirm(vname)
 {
	 // clear the visitor list since it's out of date at the moment
	var vl = document.getElementById("visitorList");
	if(vl)
	{
		vl.innerHTML = "";	
	}
	visitorName = vname;
	return;
 }
 
 // called by server to init the page after connection is complete
 function remoteInit()
 {
	//var con = document.getElementById("PushManager");
	//alert("inside remoteInit() -> " + document.getElementById("PushManager"));
	if(connector)
	{
		//alert("Setting page...");
		connector.setPage(visitorName, location.href);
		//con.subscribe("arduino", "onArduinoData"); // subscribe to Shared Object named "arduino"
	}
	else
	{
		connector = getConnector();
		if(connector)
		{
			connector.setPage(visitorName, location.href);	
		}
	}
 }
 
 function onCursorData(cursorData)
 {
	/*
	if(debugOutput)
	 {
		debugOutput.innerHTML = cursorData.name + " => " + cursorData.x + ", " + cursorData.y; 
	 }
	 var x = document.getElementById(cursorData.name + "x");
	 var y = document.getElementById(cursorData.name + "y");
	 if(x)
	 {
		x.innerHTML = cursorData.x;
	 }
	 if(y)
	 {
		y.innerHTML = cursorData.y; 
	 }
	*/
	var css = "top:" + cursorData.y + "px;left:" + cursorData.x + "px;";
	updateCSS(cursorData.name + "_cursor", css);
 }
 
 function onArduinoData(newval)
 {
	var el = document.getElementById("arduino0");
	if(el)
	{
		el.innerHTML = newval;	
	}
 }