///
/// Contains the GaugeManager and other classes which implement interactivity and callbacks.
//	
var DundasGauge = 
{
	//
	// A class containing all logic for the grid section panning.
	//
	GaugeManager: function()
	{
		//
		// Initialization method.
		//
		this.initialize = function()
		{
			this.isIE  = window.navigator.userAgent.indexOf("MSIE") > -1;
		
			// Save the references
			this.gaugeDiv = document.getElementById(this.gaugeContainerId);
			this.gaugeDiv.gridSectionManager = this;
			this.gaugeImage = document.getElementById(this.gaugeContainerId + "Image");
	        
			// Add the JavaScript API
			this.gaugeDiv.doCallback = function(commandName, commandArgument, async)
			{
				return this.gridSectionManager.doCallback(commandName, commandArgument, async);
			}      								
		}
		
		//
		// Handles the click event of the main div in order to perform a click callback.
		//
		this.onClick = function(e)
		{
			if (window.event)
			{
				e = window.event;
				e.layerX = e.offsetX;
				e.layerY = e.offsetY;
				e.target = e.srcElement;
			}
			
			var layerX = e.layerX;
			var layerY = e.layerY;
			var target = e.target;
				
			var url = this.getClickCallbackUrl(layerX, layerY);	
			
			var thisManager = this;
			setTimeout(function()
			{
				var request = thisManager.createRequest();
				if (request != null)
				{		
					thisManager.performCallback(request, url, true);
				}
			}, 0);	
		}
		
		//
		// Performs a user callback to the server.
		//
		this.doCallback = function(commandName, commandArgument, async)
		{
			this.updateEntireControl(commandName, commandArgument, async);
		}
		
		//
		// Initiates a callback to update the entire control.
		//
		this.updateEntireControl = function(commandName, commandArgument, async)
		{
			if (async == null)
			{
				async = true;
			}
			
			var url = this.getFullUpdateCallbackUrl(commandName, commandArgument);
			var thisManager = this;
			setTimeout(function()
			{
				var request = thisManager.createRequest();
				if (request != null)
				{						
					thisManager.performCallback(request, url, async);
				}	
			}, 0);		
		}
		
		//
		// Performs the a callback using the specified url.
		//
		this.performCallback = function(request, callbackUrl, async)
		{	
			var thisManager = this;				
			request.onreadystatechange = function()
			{			
				if (request.readyState == 4 && parseInt(request.status) > 300)
				{
					// Hit the callback url so the user can see the error.
					window.location = callbackUrl;
					return;
				}
				
				if (request.readyState == 4 && request.status == 200 && request.responseText != "")
				{
				
					var nodes = request.responseText.split("[!]");
					for (var i = 0; i < nodes.length; i++)
					{
						var subNodes = nodes[i].split("[!!]");
			
						// At this point subNodes[0] contains the command.		
						if (subNodes[0] == "CallbackReturnArguments")
						{
							if (thisManager.gaugeDiv.oncallbackcomplete != null)
							{
								thisManager.gaugeDiv.oncallbackcomplete(subNodes[1], subNodes[2]);
							}
						}						
						else if (subNodes[0] == "ClickReturnArguments")
						{
							if (thisManager.gaugeDiv.onclickcomplete != null)
							{
								thisManager.gaugeDiv.onclickcomplete(subNodes[1], subNodes[2]);
							}
						}				
						else if (subNodes[0] == "FullUpdateHtml")
						{
							var tempDiv = document.createElement("DIV");
							tempDiv.innerHTML = subNodes[1];
							
							var newGauge = tempDiv.firstChild;
							while (newGauge && newGauge.nodeType != 1)
							{
								newGauge = newGauge.nextSibling;
							}
							
							// Find the inner div
							var newInnerDiv = newGauge.firstChild;
							while (newInnerDiv && newInnerDiv.nodeType != 1)
							{
								newInnerDiv = newInnerDiv.nextSibling;
							}
							
							// Find the image
							var newGaugeImage = newInnerDiv.firstChild;
							while (newGaugeImage && newGaugeImage.nodeType != 1)
							{
								newGaugeImage = newGaugeImage.nextSibling;
							}							
							
							// Save the new image URL
							var newImageUrl = newGaugeImage.src;
							
							// Save the old gauge image
							var oldGaugeImage = thisManager.gaugeImage;
							
							
							// Replace the new image with the old image
							oldGaugeImage.setAttribute("width", newGaugeImage.getAttribute("width", 2));
							oldGaugeImage.setAttribute("height", newGaugeImage.getAttribute("height", 2));
							newInnerDiv.replaceChild(oldGaugeImage, newGaugeImage);////		
														
							// Save the attached events references
							var callbackCompleteRef = thisManager.gaugeDiv.oncallbackcomplete;
							var clickCompleteRef = thisManager.gaugeDiv.onclickcomplete;
							
							// Swap the two nodes											
							thisManager.gaugeDiv.parentNode.replaceChild(newGauge, thisManager.gaugeDiv);
							
							// Execute the initialization
							eval(subNodes[2]);

							// Set the new source
							thisManager.gaugeImage.src = newImageUrl;
							
							// Restore the attached event references
							thisManager.gaugeDiv.oncallbackcomplete = callbackCompleteRef;
							thisManager.gaugeDiv.onclickcomplete = clickCompleteRef;
						}
						else if (subNodes[0] == "ExecuteJavaScript")
						{
							eval(subNodes[1]);
						}
						else if (subNodes[0] == "UpdateClientControl")
						{			
							var clientControl = document.getElementById(subNodes[1]);
							if (clientControl != null)
							{
								var tempDiv = document.createElement("DIV");
								tempDiv.innerHTML = subNodes[2];
								var newControl = tempDiv.firstChild
								while (newControl && newControl.nodeType != 1)
								{
									newControl = newControl.nextSibling;
								}
								
								// Swap the two nodes			
								clientControl.parentNode.replaceChild(newControl, clientControl);
								clientControl = document.getElementById(subNodes[1]);
							}
						}					
					}
					
					if (thisManager.requests != null)
					{
						thisManager.requests.remove(request);
					}			
				}
			}
		
			request.open("GET", callbackUrl, async);
			request.send(null);	
		}
		
		//
		// Returns the url which will be used to perform a click callback.
		//	
		this.getClickCallbackUrl = function(x, y)
		{
			var requestParams = "____gaugeContainerId=" + this.gaugeContainerId +
				"&_controlPersistence=" + this.controlPersistence +
				"&_clickX=" + x + "&_clickY=" + y;
			
			var now = new Date();
			requestParams += "&_time=" + now.getTime() + now.getMilliseconds();						
			
			if (location.href.indexOf("?") == -1)
			{
				return location.href + "?" + requestParams;
			}
			else
			{
				return location.href + "&" + requestParams;
			}
		}	
		
		//
		// Returns the url which will be used to perform a full control update.
		//	
		this.getFullUpdateCallbackUrl = function(commandName, commandArgument)
		{
			var requestParams = "____gaugeContainerId=" + this.gaugeContainerId + "&_fullUpdate=1" +
				"&_controlPersistence=" + this.controlPersistence;
			
			if (commandName != null)
			{
				requestParams += "&_command=" + encodeURIComponent(commandName);
			}
			if (commandArgument != null)
			{
				requestParams += "&_arguments=" + encodeURIComponent(commandArgument);
			}	
		
			var now = new Date();
			requestParams += "&_time=" + now.getTime() + now.getMilliseconds();						
			
			if (location.href.indexOf("?") == -1)
			{
				return location.href + "?" + requestParams;
			}
			else
			{
				return location.href + "&" + requestParams;
			}
		}	
		
		//
		// Creates and returns the XMLHttpRequest object.
		//
		this.createRequest = function()
		{
			var request = null;
			
			if (window.XMLHttpRequest)
			{
				try
				{
					request = new XMLHttpRequest();
				}
				catch (e)
				{
					request = null;
				}
			}
			else if (window.ActiveXObject)
			{
				try
				{
					request = new ActiveXObject("Msxml2.XMLHTTP")
				}
				catch (e)
				{
					try
					{
						request = new ActiveX("Microsoft.XMLHTTP");
					}
					catch (e)
					{
						request = null;
					}
				}
			}
			
			return request;
		}

		//
		// Handler for the onDragStart event.
		//
		this.onDragStart = function(e)
		{
			e = e || window.event;
			e.returnValue = false;
		} 			
	}		
};

