
// @param host the element to which this button should be attached.
// @param x the x position for this button
// @param y the y position for this button
function Button(host, x, y) {
	// Save this stuff for use for when the download completes
	this.host = host;
	this.x = x;
	this.y = y;
	
	// Create a new 'downloader' object that will allow us to fetch the XAML from the server
	this.downloader = host.getHost().createObject("downloader");
	
	// Hook up a notification for when the download has completed.
	this.downloader.addEventListener("completed", Sys.Silverlight.createDelegate(this, this.handleDownloadCompleted));
	// For this example, we'll make the download synchronous to block the UI until the buttons can appear.
	this.downloader.open("GET", "Button.xaml", true);
	
	this.downloader.send();
}

Button.prototype = 
{
	// Property for outside elements to hook up a handler for the click event on this.
	clickHandler: null,
	
	// Handler for when the download has completed.
	handleDownloadCompleted: function() {
		// Check that the download is a success
		if (this.downloader.status == 200) {
			// If the XAML was in a Zip file, then we'd use the filename here. Otherwise we just use the default object.
			var xaml = this.downloader.getResponseText("");
			
			// The second argument is whether or not to use a new namespace.
			// Since we want to allow multiple elements in the scene at once, then we do want each one to be a namespace.
			this.buttonElement = this.host.getHost().content.createFromXaml(xaml, true);
			this.buttonElement["Canvas.Left"] = this.x;
			this.buttonElement["Canvas.Top"] = this.y;
			this.host.children.add(this.buttonElement);
			
			// Hook up some event handlers to the button so we can play the animations and such.
			this.buttonElement.addEventListener("MouseEnter", Sys.Silverlight.createDelegate(this, this.handleMouseEnter));
			this.buttonElement.addEventListener("MouseLeave", Sys.Silverlight.createDelegate(this, this.handleMouseLeave));
			this.buttonElement.addEventListener("MouseLeftButtonDown", Sys.Silverlight.createDelegate(this, this.handleMouseDown));
		}
	},
	
	handleMouseEnter: function() {
		// Find the mouse over animation and play it.
		// Need to use the buttonElement to find the name since it's in it's own namespace.
		var mouseEnterAnim = this.buttonElement.findName("MouseOver");
		mouseEnterAnim.begin();
	},
	
	handleMouseLeave: function(sender, eventArgs) {
		var mouseLeaveAnim = this.buttonElement.findName("MouseOut");
		mouseLeaveAnim.begin();
	},
	
	handleMouseDown: function(sender, eventArgs) {
		if (this.clickHandler != null)
			this.clickHandler();
	}
}