﻿
if (!window.aspNET)
	window.aspNET = {};

aspNET.Page = function() 
{
}

// Globals

// Handle to main canvas - set at startup
var mainCanvas;

// Plugin reference
var slPlugin;

// Needed whilst interacting with the downloader object
var thisRef;

// For drag & drop
var mouseIsDown  = false;
var miniMouseIsDown  = false;
var clearMouseIsDown = false;
var videoPlaying = false;

// Current mouse pos for drag & drop
var currentLeft = 0;
var currentTop = 0;
var miniCurrentLeft = 0;
var miniCurrentTop = 0;
var clearCurrentLeft = 0;
var clearCurrentTop = 0;
var clearCalculating = false;
var clearMiniCalculating = false;
var leftMoved = 0;
var topMoved = 0;

// Canvas boundaries for drag & drop
var MAX_TopPos = 120;

// Video cookie
var Video_Cookie = "StartupVideoPlayed";
var TopPos_Cookie = "TopPos";
var LeftPos_Cookie = "LeftPos";

// Video
var startupVideo = "TimelineCombined.wmv";
var Max_playCounter = 10;

var boundaryLeft = 0;
var boundaryTop = 0;
var boundaryRight = 0;
var boundaryBottom = 0;

// Mouse drag directions
var directionLeft = false;
var directionRight = false;
var directionUp = false;
var directionDown = false;

var miniBeginLeft = 0;
var miniBeginTop = 0;
var beginLeft = 0;
var beginTop = 0;
var clearBeginLeft = 0;
var clearBeginTop = 0;
var endLeft = 0;
var endTop = 0;

// End of Globals

aspNET.Page.prototype =
{
	handleLoad: function(control, userContext, rootElement) 
	{
		this.control = control;
		
		thisRef = this;
		
		// Set global var
		mainCanvas = rootElement;

		//Get a reference to the plugin
		slPlugin = rootElement.getHost();

		// Start the application
		this.startUp();
		
	},

	//
	//
	// Startup
	startUp: function()
	{
		// Show the app
		slPlugin.style.height = "100%";

		var timeDownloader = slPlugin.createObject("downloader");

		// Set preloader progress to zero
		this.control.content.findName("rectGreen")["Width"] = 0;

		thisRef.control.content.findName("cnv_preLoader")["Visibility"] = "Visible";

		timeDownloader.addEventListener("downloadProgressChanged", this.onTimeDownloadProgressChanged);
		timeDownloader.addEventListener("completed", this.onTimeDownloadCompleted);
		
		//timeDownloader.open("GET", "cnv_timeline.xaml");
		timeDownloader.open("GET", "zip/cnv_timeline.zip.deploy");
		timeDownloader.send();
	},
	
	onTimeDownloadProgressChanged: function(sender, eventArgs)
	{
		// Calculate the downloaded percentage.
		var percentage = Math.floor(sender.downloadProgress * 100);

	    // Update the Rectangle and TextBlock objects of the visual progress indicator.
		var maxWidth = thisRef.control.content.findName("rectGrey")["Width"];
		
		thisRef.control.content.findName("rectGreen")["Width"] = maxWidth * percentage / 100;
	},
	
	onTimeDownloadCompleted: function(sender, eventArgs)   
	{ 
		// Set the video content to the downloader content
		//var med = thisRef.control.content.findName("mediaStartup");
		//med.setSource(sender,"");
		
        // Retrieve downloaded XAML content.
        //var xamlFragment = sender.ResponseText;
		
		var xamlFragment = sender.getResponseText("cnv_timeline.xaml");
        
        // Create the objects from the XAML content.
        var plugin = sender.getHost();
        var canv = plugin.content.createFromXaml(xamlFragment);

        // Add downloaded XAML content to the root Canvas of the plug-in.
        var rootCanvas = sender.findName("CodeChronicles");

        rootCanvas.children.add(canv);

		thisRef.control.content.findName("cnv_preLoader")["Visibility"] = "Collapsed";
		
		thisRef.addEvents();

		var med = thisRef.control.content.findName("mediaStartup");
		med.setSource(sender, startupVideo);		

		thisRef.loadVideo(sender);
	},
	
	loadVideo: function(sender)
	{
		// Set startup canvas pos
        thisRef.setCanvasStartupPos();

        // Play the startup video
        thisRef.playMainVideo();
	},
	
	onVidDownloadProgressChanged: function(sender, eventArgs)
	{
		//var percentage = Math.floor(sender.downloadProgress * 100);   
		//thisRef.control.content.findName("txtLoadingPerc")["Text"] = percentage + "%"
	},

	onVidDownloadCompleted: function(sender, eventArgs)   
	{ 
		// Set the video content to the downloader content
		var med = thisRef.control.content.findName("mediaStartup");
		med.setSource(sender,"");

		// Set startup canvas pos
        thisRef.setCanvasStartupPos();

        // Play the startup video
        thisRef.playMainVideo();
	},

	addEvents: function()
	{
		// Set image boundaries
		this.setImageBoundaries();
		
        //
		// Picture Events
		var imgPic = this.control.content.findName("cnv_timeLine");
		
		// Mouse down
		imgPic.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.imgPicHandleMouseDown));
	
		// Mouse up
		imgPic.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.imgPicHandleMouseUp));

		// Mouse move
		imgPic.addEventListener("MouseMove", Silverlight.createDelegate(this, this.imgPicHandleMouseDrag));

		// Mouse enter
		imgPic.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.imgPicHandleMouseEnter));

		// Mouse leave
		imgPic.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.imgPicHandleMouseLeave));
    	//
		// End of picture events

        // Scroller	events
        //
		var miniMapBtn = this.control.content.findName("btn_scroller");
		
		// Mouse down
		miniMapBtn.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.miniMapHandleMouseDown));
	
		// Mouse up
		miniMapBtn.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.miniMapHandleMouseUp));

		// Mouse move
		miniMapBtn.addEventListener("MouseMove", Silverlight.createDelegate(this, this.miniMapHandleMouseDrag));

		var clearminiMapBtn = this.control.content.findName("clear_btn_scroller");
		
		// Mouse down
		clearminiMapBtn.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.clearminiMapHandleMouseDown));
	
		// Mouse up
		clearminiMapBtn.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.clearminiMapHandleMouseUp));

		// Mouse move
		clearminiMapBtn.addEventListener("MouseMove", Silverlight.createDelegate(this, this.clearminiMapHandleMouseDrag));

		// Mask at top of scroller
		this.control.content.findName("rectScrollMask").addEventListener("MouseMove", Silverlight.createDelegate(this, this.rectScrollMouseMove));
		this.control.content.findName("rectScrollMask").addEventListener("MouseEnter", Silverlight.createDelegate(this, this.rectScrollMouseEnter));
        //
        // End of scroller events
        
        //
        // Mouse down enhancement events
        this.control.content.findName("cnv_dateLine").addEventListener("MouseEnter", Silverlight.createDelegate(this, this.cnv_dateLineMouseEnter));
        this.control.content.findName("cnv_scroller").addEventListener("MouseEnter", Silverlight.createDelegate(this, this.cnv_scrollerMouseEnter));
        this.control.content.findName("cnv_scroller").addEventListener("MouseLeave", Silverlight.createDelegate(this, this.cnv_scrollerMouseLeave));
        //
        // End of mouse down enhancement events
        
        //
        // Button events
        this.addButtonEvents();
        //
        // End of button events
        
        //
        // Popup events
        this.control.content.findName("btnPopClose").addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.btnPopCloseClick));
        this.control.content.findName("btnPopCloseStart").addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.btnPopCloseStartClick));
        //
        // End of popup events
        
        //
        // Video events
        this.control.content.findName("mediaStartup").addEventListener("MediaEnded", Silverlight.createDelegate(this, this.startupVideoEnded));
        // End of video events
        //
        
        //
        // Storyboards
        this.control.content.findName("media_fadeOut").addEventListener("Completed", Silverlight.createDelegate(this, this.fadeOutCompleted));
        this.control.content.findName("miniInterval").addEventListener("Completed", Silverlight.createDelegate(this, this.miniIntervalCompleted));
        this.control.content.findName("canvasInterval").addEventListener("Completed", Silverlight.createDelegate(this, this.canvasIntervalCompleted));
		this.control.content.findName("sb_scrollerIntro").addEventListener("Completed", Silverlight.createDelegate(this, this.sb_scrollerIntroCompleted));
        // End of storyboards
        //

	},
	
    cnv_dateLineMouseEnter: function(sender, eventArgs) 
    {
        // If the mouse is over this then the drag & drop is over
        mouseIsDown = false;
        miniMouseIsDown = false;
		clearMouseIsDown = false;
    },
    
    cnv_scrollerMouseEnter: function(sender, eventArgs) 
    {
        // If the mouse is over this then the drag & drop is over
        mouseIsDown = false;
        miniMouseIsDown = false;
		clearMouseIsDown = false;
    },

    cnv_scrollerMouseLeave: function(sender, eventArgs) 
    {
        // If the mouse is over this then the drag & drop is over
        mouseIsDown = false;
        miniMouseIsDown = false;
		clearMouseIsDown = false;
    },
    
    rectScrollMouseMove: function(sender, eventArgs) 
    {
        // If the mouse is over this then the drag & drop is over
        mouseIsDown = false;
        miniMouseIsDown = false;
		clearMouseIsDown = false;
    },

    rectScrollMouseEnter: function(sender, eventArgs) 
    {
        // If the mouse is over this then the drag & drop is over
        mouseIsDown = false;
        miniMouseIsDown = false;
		clearMouseIsDown = false;
    },
    
    //
    // Picture events	
	imgPicHandleMouseDown: function(sender, eventArgs) 
	{
		if(videoPlaying == false)
		{
			mouseIsDown = true;
			miniMouseIsDown = false;
			clearMouseIsDown = false;
			clearCalculating = true;
		
			beginLeft = eventArgs.getPosition(null).x;
			beginTop = eventArgs.getPosition(null).y;
		}
	},
	
	imgPicHandleMouseUp: function(sender, eventArgs) 
	{
		mouseIsDown = false;
		miniMouseIsDown = false;
		clearMouseIsDown = false;
	
		// Allow all objects to receive mouse events.
        sender.releaseMouseCapture();

        // Set the top & left cookie pos
        setCookie(TopPos_Cookie,this.control.content.findName("cnv_timeLine")["Canvas.Top"],180);
        setCookie(LeftPos_Cookie,this.control.content.findName("cnv_timeLine")["Canvas.Left"],180);
    },
	
	imgPicHandleMouseEnter: function(sender, eventArgs) 
	{
		miniMouseIsDown = false;
		clearMouseIsDown = false;
		clearCalculating = false
		
	    if(!mouseIsDown)
	    {
            // Use the arrow on the toolbars
            sender["Cursor"] = "None";
        }

	},

	imgPicHandleMouseLeave: function(sender, eventArgs) 
	{
		mouseIsDown = false;
		miniMouseIsDown= false;
		clearMouseIsDown = false;
	},
	
	imgPicHandleMouseDrag: function(sender, eventArgs) 
	{
		miniMouseIsDown = false;
	 
		//this.control.content.findName("txtDebug")["Text"] = "x: " + sender["Canvas.Left"] + "\ny: " + sender["Canvas.Top"];
		
		if(videoPlaying == false)
		{
			// Ensure this object is the only one receiving mouse events.
			sender.captureMouse();
        
			//var mapcnv = this.control.content.findName("cnv_timeline");
			var wdth = parseInt(sender["Width"]);
			var hght = parseInt(sender["Height"]);
			var bot = parseInt(sender["Canvas.Top"]) + parseInt(sender["Height"]);

			var visWdth = mainCanvas["Width"];
			var visHght = mainCanvas["Height"];
        
			var dateLine = this.control.content.findName("cnv_dates");
        
			if (mouseIsDown == true)
			{
				// Retrieve the current position of the mouse.
				var currLeft = eventArgs.getPosition(null).x;
				var currTop = eventArgs.getPosition(null).y;

				// Apply boundaries
				if(currLeft - beginLeft > 0)
				{
					// Going right
					if(sender["Canvas.Left"] < 0)
					{
						sender["Canvas.Left"] += currLeft - beginLeft;
						dateLine["Canvas.Left"] = sender["Canvas.Left"];
					}
				}
				else if(currLeft - beginLeft < 0)
				{
					// Going left
					if(sender["Canvas.Left"] - visWdth + wdth > 0)
					{
						sender["Canvas.Left"] += currLeft - beginLeft;
						dateLine["Canvas.Left"] = sender["Canvas.Left"];
					}
				}
            
				if(currTop - beginTop > 0)
				{
					// Going down
					if(sender["Canvas.Top"] < MAX_TopPos)
					{
						sender["Canvas.Top"] += currTop - beginTop;
					}
				}
				else if(currTop - beginTop < 0)
				{
					// Going up
					if(sender["Canvas.Top"] -visHght + hght > 0)
					{
						sender["Canvas.Top"] += currTop - beginTop;
					}
                
				}
            
				// Update the beginning position of the mouse.
				beginLeft = currLeft;
				beginTop = currTop;
            
				// Update the minimap position
				this.calcMiniMapPos();
			}
			else
			{
			}
		}
	},
	// End of picture events
	//

	miniIntervalCompleted: function(sender, eventArgs)
	{
		this.control.content.findName("miniInterval").Stop();

		var clrctrl = this.control.content.findName("clear_btn_scroller");
		var btnctrl = this.control.content.findName("btn_scroller");
		
		if((clrctrl["Canvas.Left"] != btnctrl["Canvas.Left"]) || (clrctrl["Canvas.Top"] != btnctrl["Canvas.Top"]))
		{
			this.miniMapCatchUp(sender, eventArgs);
			
			this.control.content.findName("miniInterval").Begin();
			//this.control.content.findName("miniInterval").Begin();
		}
		else
		{
			clearMiniCalculating = false;
		}
		
		// Set the top & left cookie pos
		setCookie(TopPos_Cookie,this.control.content.findName("cnv_timeLine")["Canvas.Top"],180);
		setCookie(LeftPos_Cookie,this.control.content.findName("cnv_timeLine")["Canvas.Left"],180);

	},

	canvasIntervalCompleted: function(sender, eventArgs)
	{
		this.control.content.findName("canvasInterval").Stop();

		if(clearCalculating == true)
			{
			if((endLeft != beginLeft) || (endTop != beginTop))
			{
				this.mainCanvasCatchUp();
				this.control.content.findName("canvasInterval").Begin();
			}
			else
			{
				clearCalculating = false;
			}
		}

	},
	
	sb_scrollerIntroCompleted: function(sender, eventArgs)
	{
		this.control.content.findName("sb_scrollerIntro").Stop();
		
		// position the clear scroller to the same place
		this.control.content.findName("clear_btn_scroller")["Canvas.Left"] = 766;
		this.control.content.findName("clear_btn_scroller")["Canvas.Top"] = 9;
		this.control.content.findName("btn_scroller")["Canvas.Left"] = 766;
		this.control.content.findName("btn_scroller")["Canvas.Top"] = 9;
	},
	
	//
	// CLEAR minimap events
	//
	clearminiMapHandleMouseDown: function(sender, eventArgs) 
	{
		if(videoPlaying == false)
		{
			clearMouseIsDown = true;
			miniMouseIsDown = true;
			clearCalculating = false;
			clearMiniCalculating = true;
		
			miniBeginLeft = eventArgs.getPosition(null).x;
			miniBeginTop = eventArgs.getPosition(null).y;
			clearBeginLeft = eventArgs.getPosition(null).x;
			clearBeginTop = eventArgs.getPosition(null).y;

			sender.captureMouse();
		}
	},

	clearminiMapHandleMouseUp: function(sender, eventArgs) 
	{
		clearMouseIsDown = false;
		miniMouseIsDown = false;
		
		// Allow all objects to receive mouse events.
        sender.releaseMouseCapture();
	},
	
	clearminiMapHandleMouseDrag: function(sender, eventArgs) 
	{
	    var scrl = this.control.content.findName("clear_btn_scroller");
	    var mapcnv = this.control.content.findName("Lines");
	    var wdth = mapcnv["Width"] - scrl["Width"];
	    var bot = mapcnv["Height"] - scrl["Height"];

	    // Make sure that final position calculations take place
	    clearMiniCalculating = true;
	    
		if((clearMouseIsDown == true) && (videoPlaying == false))
		{
            var currLeft = eventArgs.getPosition(null).x;
            var currTop = eventArgs.getPosition(null).y;

            // Apply boundaries
            if(((sender["Canvas.Left"] + currLeft - clearBeginLeft) > 0) && ((sender["Canvas.Left"] + currLeft - clearBeginLeft) < wdth))
            {
                sender["Canvas.Left"] += currLeft - clearBeginLeft;
            }
            else if(sender["Canvas.Left"] == 0)
			{
				sender["Canvas.Left"] = 0;
			}
            
            if(((sender["Canvas.Top"] + currTop - clearBeginTop) > 0) && ((sender["Canvas.Top"] + currTop - clearBeginTop) < bot))
            {
                sender["Canvas.Top"] += currTop - clearBeginTop;
            }
            else if(sender["Canvas.Top"] <= 1)
			{
				sender["Canvas.Top"] = 0;
			}

            // Move the main canvas to reflect this position
            // this.calcMainCanvasPos()
            
            // Update the beginning position of the mouse.
            clearBeginLeft = currLeft;
            clearBeginTop = currTop;

    		// Set the new positions
	    	clearCurrentLeft = clearBeginLeft;
		    clearCurrentTop = clearBeginTop;
            
            this.miniMapCatchUp(sender, eventArgs);
		}

		//var tst = this.control.content.findName("miniInterval");
		//var tst2 = mainCanvas.resources.getItem(3);

		this.control.content.findName("miniInterval").Begin();
	},

	//
    // Minimap events	
	miniMapHandleMouseDown: function(sender, eventArgs) 
	{
		if(videoPlaying == false)
	    {
			miniMouseIsDown = true;
			clearMouseIsDown = true;
		
			miniBeginLeft = eventArgs.getPosition(null).x;
			miniBeginTop = eventArgs.getPosition(null).y;

			sender.captureMouse();
		}
	},
	
	miniMapHandleMouseUp: function(sender, eventArgs) 
	{
		miniMouseIsDown = false;
		clearMouseIsDown = false;
		
		// Allow all objects to receive mouse events.
        sender.releaseMouseCapture();

        // Set the top & left cookie pos
        setCookie(TopPos_Cookie,this.control.content.findName("cnv_timeLine")["Canvas.Top"],180);
        setCookie(LeftPos_Cookie,this.control.content.findName("cnv_timeLine")["Canvas.Left"],180);
	},

	getLDiff: function(ldifVar)
	{
		var leftVelocity = 0;
		
		switch(ldifVar)
		{
			case ldifVar > 100:
				leftVelocity = 1.5;
				break;
			case ldifVar > 80:
				leftVelocity = 1.25;
				break;
			case ldifVar > 60:
				leftVelocity = .8;
				break;
			case ldifVar > 40:
				leftVelocity = .7;
				break;
			case ldifVar > 30:
				leftVelocity = .6;
				break;
			default:
				leftVelocity = .5;
				break;
		}

		return leftVelocity;

	},

	getTDiff: function(tdifVar)
	{
		var topVelocity = 0;
		
		switch(tdifVar)
		{
			case tdifVar > 250:
				topVelocity = .75;
				break;
			case tdifVar > 180:
				topVelocity = .6;
				break;
			case tdifVar > 120:
				topVelocity = .5;
				break;
			case tdifVar > 75:
				topVelocity = .4;
				break;
			case tdifVar > 50:
				topVelocity = .3;
				break;

			default:
				topVelocity = .25;
				break;
		}
		
		return topVelocity;

	},
	
	miniGetLDiff: function(ldifVar)
	{
		var leftVelocity = 0;
		
		switch(ldifVar)
		{
			case ldifVar > 700:
				leftVelocity = 1;
				break;
			case ldifVar > 600:
				leftVelocity = .8;
				break;
			case ldifVar > 500:
				leftVelocity = .6;
				break;
			case ldifVar > 400:
				leftVelocity = .5;
				break;
			case ldifVar > 300:
				leftVelocity = .4;
				break;
			case ldifVar > 200:
				leftVelocity = .3;
				break;
			case ldifVar > 100:
				leftVelocity = .2;
				break;
			case ldifVar <= 100:
				leftVelocity = .15;
				break;
			default:
				leftVelocity = .15;
				break;
		}
		
		return leftVelocity;

	},

	miniGetTDiff: function(tdifVar)
	{
		var topVelocity = 0;
		
		switch(tdifVar)
		{
			case tdifVar > 40:
				topVelocity = 1;
				break;
			case tdifVar > 30:
				topVelocity = .75;
				break;
			case tdifVar > 20:
				topVelocity = .5;
				break;
			default:
				topVelocity = .25;
				break;
		}
		
		return topVelocity;

	},
	
	miniMapCatchUp: function(sender, eventArgs)
	{
		var btn_scroller = this.control.content.findName("btn_scroller");
		var clr_scroller = this.control.content.findName("clear_btn_scroller");
		var leftDiff = clr_scroller["Canvas.Left"] - btn_scroller["Canvas.Left"];
		var topDiff = clr_scroller["Canvas.Top"] - btn_scroller["Canvas.Top"];

		var leftVelocity = this.miniGetLDiff(Math.round(Math.abs(leftDiff)));
		var topVelocity = this.miniGetTDiff(Math.round(Math.abs(topDiff)));

		// Move based upon distance apart - simulates velocity
		btn_scroller["Canvas.Left"] = btn_scroller["Canvas.Left"] + (leftDiff * leftVelocity);
		btn_scroller["Canvas.Top"] = btn_scroller["Canvas.Top"] + (topDiff * topVelocity);

		// Move the main canvas to reflect this position
		this.calcMainCanvasPos()
	},

	miniMapHandleMouseDrag: function(sender, eventArgs) 
	{
	    var scrl = this.control.content.findName("btn_scroller");
	    var mapcnv = this.control.content.findName("Lines");
	    var wdth = mapcnv["Width"] - scrl["Width"];
	    var bot = mapcnv["Height"] - scrl["Height"];
	    
		if(miniMouseIsDown == true)
		{
            var currLeft = eventArgs.getPosition(null).x;
            var currTop = eventArgs.getPosition(null).y;

            // Apply boundaries
            if(((sender["Canvas.Left"] + currLeft - miniBeginLeft) > 0) && ((sender["Canvas.Left"] + currLeft - miniBeginLeft) < wdth))
            {
                sender["Canvas.Left"] += currLeft - miniBeginLeft;
            }
            else if(sender["Canvas.Left"] == 0)
			{
				sender["Canvas.Left"] = 0;
			}
            
            if(((sender["Canvas.Top"] + currTop - miniBeginTop) > 0) && ((sender["Canvas.Top"] + currTop - miniBeginTop) < bot))
            {
                sender["Canvas.Top"] += currTop - miniBeginTop;
            }
            else if(sender["Canvas.Top"] <= 1)
			{
				sender["Canvas.Top"] = 0;
			}

            // Move the main canvas to reflect this position
            this.calcMainCanvasPos()
            
            // Update the beginning position of the mouse.
            miniBeginLeft = currLeft;
            miniBeginTop = currTop;

    		// Set the new positions
	    	miniCurrentLeft = miniBeginLeft;
		    miniCurrentTop = miniBeginTop;
		}
	},
	// End of Minimap events
	//
	
	checkMove: function(left, top)
	{
	    var retVal = false;
	    
	    if((left != currentLeft) || (top != currentTop))
	    {
	        retVal = true;
	    }
	    
	    return retVal;
	},
	
	setImageBoundaries: function()
	{
	    // main image
		//var imgPic = thisRef.control.content.findName("cnv_timeline");
		
		var imgwidth = parseFloat(thisRef.control.content.findName("cnv_timeLine")["Width"]);
		var imgheight = parseFloat(this.control.content.findName("cnv_timeLine")["Height"]);
		var cnvwidth = parseFloat(mainCanvas["Width"]);
		var cnvheight = parseFloat(mainCanvas["Height"]);

		boundaryLeft = cnvwidth - imgwidth;
		boundaryTop = cnvheight - MAX_TopPos;	// Canvas top pos starts at MAX_TopPos (0,0 = fortran, some items are above)
		boundaryRight = 0;
		boundaryBottom = cnvheight + MAX_TopPos - imgheight;
		
	},
	
	moveCanvas: function(dragLeft,dragTop)
	{
	    // Get a reference to the image
	    var imgPic = this.control.content.findName("cnv_timeLine");

	    var newLeft = 0;
	    var newTop = 0;
	    var leftMove = dragLeft - currentLeft;
	    var upMove = dragTop - currentTop;
	    
	    //
	    // left-right
	    //
	    if(directionLeft == true)
	    {
            newLeft = Math.max(parseFloat(imgPic["Canvas.Left"]) + leftMove, boundaryLeft); // working
	    }
	    else if(directionRight == true)
	    {
	        newLeft = Math.min(parseFloat(imgPic["Canvas.Left"]) + leftMove, boundaryRight);
	    }
	    
	    //
	    // up-down
	    //
	    if(directionUp == true)
	    {
	        newTop = Math.max(parseFloat(imgPic["Canvas.Top"]) + upMove, boundaryTop);
	    }
	    else if(directionDown == true)
	    {
	        newTop = Math.min(parseFloat(imgPic["Canvas.Top"]) + upMove, boundaryBottom);
	    }
	    
	    //
	    // Set the new positions
	    //
	    if((directionLeft == true) || (directionRight == true))
	    {
            imgPic["Canvas.Left"] = newLeft;
        }
        
        if((directionUp == true) || (directionDown == true))
        {
            imgPic["Canvas.Top"] = newTop;
        }
	    	    
	},
	
	//
	// Button methods
	addButtonEvents: function()
	{
        var minBtns = 0;
        var maxBtns = 600;		// Time constraints - there's a better way of doing this
        var btnHandle;

        for (var i = minBtns; i <= maxBtns; i++)
        {
			btnHandle = this.control.content.findName("btn" + i);
			
			if(btnHandle != null)
			{
				// Click
				btnHandle.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.genBtnLeftUp));
				
				// Rollovers
				btnHandle.addEventlistener("MouseEnter", Silverlight.createDelegate(this, this.genBtnSwapColStart));
				btnHandle.addEventlistener("MouseLeave", Silverlight.createDelegate(this, this.genBtnSwapColRet));
		    }
        }

	},
	
	
	genBtnSwapColStart: function(sender, eventArgs)
	{
		var uNo = -1;

		// First child is btnLeftnn - where nn = unique number
		uNo = sender.children.getItem(0)["Name"].substr(7);
		
		this.control.content.findName("btnLeftBg" + uNo)["Fill"]["GradientStops"].getItem(0)["Color"] = "#1C9BF2";
		this.control.content.findName("btnLeftBg" + uNo)["Fill"]["GradientStops"].getItem(1)["Color"] = "#1C9BF2";

		this.control.content.findName("btnMidBg" + uNo)["Fill"]["GradientStops"].getItem(0)["Color"] = "#1C9BF2";
		this.control.content.findName("btnMidBg" + uNo)["Fill"]["GradientStops"].getItem(1)["Color"] = "#1C9BF2";

		this.control.content.findName("btnRightBg" + uNo)["Fill"]["GradientStops"].getItem(0)["Color"] = "#1C9BF2";
		this.control.content.findName("btnRightBg" + uNo)["Fill"]["GradientStops"].getItem(1)["Color"] = "#1C9BF2";
	},

	genBtnSwapColRet: function(sender, eventArgs)
	{
		var uNo = -1;

		// First child is btnLeftnn - where nn = unique number
		uNo = sender.children.getItem(0)["Name"].substr(7);
		
		this.control.content.findName("btnLeftBg" + uNo)["Fill"]["GradientStops"].getItem(0)["Color"] = "#FF4F4F4F";
		this.control.content.findName("btnLeftBg" + uNo)["Fill"]["GradientStops"].getItem(1)["Color"] = "#FF111111";

		this.control.content.findName("btnMidBg" + uNo)["Fill"]["GradientStops"].getItem(0)["Color"] = "#FF4F4F4F";
		this.control.content.findName("btnMidBg" + uNo)["Fill"]["GradientStops"].getItem(1)["Color"] = "#FF111111";

		this.control.content.findName("btnRightBg" + uNo)["Fill"]["GradientStops"].getItem(0)["Color"] = "#FF4F4F4F";
		this.control.content.findName("btnRightBg" + uNo)["Fill"]["GradientStops"].getItem(1)["Color"] = "#FF111111";
	},
	
	getBtnNo: function(btnName)
	{
	    return btnName.substring(3);
	},
	
	genBtnLeftUp: function(sender, eventArgs)
	{
	    // Not dragging
	    mouseIsDown = false;
	    
	    // popup reference
	    var popup = this.control.content.findName("cnv_pop");

        // Set the canvas positions        
        this.setPopupPos(sender, eventArgs);

        // Get the button number
        var dataId = this.getBtnNo(sender["Name"]);

        // Set the popup text
        this.getXMLPopData(dataId, sender["Name"]);

        // Show the popup - only if there's some data
		if(this.control.content.findName("popText")["Text"].length > 0)
		{
			popup["Visibility"] = "Visible";
			this.control.content.findName("sb_popExpand").Begin();
		}
	},
	//
	// End of button methods

    //
    // Popup methods
    setPopupPos: function(sender, eventArgs)
    {
        // Get popup handle
        var popup = this.control.content.findName("cnv_pop");
    
        // Button click positions
        var lPos = parseInt(sender["Canvas.Left"] + sender["Width"]/2);
        var tPos = parseInt((sender["Canvas.Top"]) + sender["Height"]/2);
        
        var xPos = eventArgs.getPosition(null).x;
        var yPos = eventArgs.getPosition(null).y;
        
        // Popup details
        var popHeight = popup["Height"];
        var popWidth = popup["Width"];
        
        // Canvas details
        var canvLeft = 0;
        var canvRight = mainCanvas["Width"];
        var canvTop = this.control.content.findName("cnv_dateLine")["Height"];
        var canvBottom = mainCanvas["Height"] - this.control.content.findName("cnv_scroller")["Height"];
        
        // If the left pos of the button + width of popup < canvas right pos then left pos = lPos
        // (calculated as button pos + half width)
        if(xPos + popWidth < canvRight)
        {
            popup["Canvas.Left"] = lPos;
        }
        else
        {
            // Left pos = current left pos minus popup width
            // This means that the popup will still appear halfway along the button
            popup["Canvas.Left"] = lPos - popWidth;
        }
        
        // If the top pos of the button + heigth of popup < canvas bottom pos then top pos = tPos
        // (calculated as button pos + half width)
        if(yPos + popHeight < canvBottom)
        {
            popup["Canvas.Top"] = tPos;
        }
        else
        {
            // Top pos = current top pos minus popup height
            // This means that the popup will still appear halfway between the button
            popup["Canvas.Top"] = tPos - popHeight;
        }
        
    },
    
    btnPopCloseClick: function(sender, eventArgs)
    {
        this.control.content.findName("cnv_pop")["Visibility"] = "Collapsed";
		this.control.content.findName("sb_popContract").Begin();
    },
    
    btnPopCloseStartClick: function(sender, eventArgs)
    {
        this.control.content.findName("cnv_popStart")["Visibility"] = "Collapsed";
    },

    //
    // End of popup methods
    
	calcMiniMapPos: function()
	{
		var btnScroll = this.control.content.findName("btn_scroller");
		var btnScrollWidth = btnScroll["Width"];
		var btnScrollHeight = btnScroll["Height"];
		
		//
		// Minimap boundaries
		var miniMap = this.control.content.findName("Lines");
		// Left & Top positions start at 0,0 not in the offset position
		var miniMapMinLeft = 0;
		var miniMapMinTop = 0;
		
		// Max Width position is left pos + minimap width - button width
		var miniMapMaxLeft = miniMapMinLeft + miniMap["Width"] - btnScrollWidth;

		// Max Height position is top pos + minimap height - button height
		var miniMapMaxTop = miniMapMinTop + miniMap["Height"] - btnScrollHeight;
		// End of minimap boundaries
		//

		//
		// Main map positions
        var mainMap = this.control.content.findName("cnv_timeLine");
        if(mainMap["Canvas.Top"] > MAX_TopPos)
        {
			// Cant go above max pos
			mainMap["Canvas.Top"] = MAX_TopPos
		}
		
        var mainLPos = Math.abs(mainMap["Canvas.Left"]);		// must be a +ve number
        var mainTPos = Math.abs(mainMap["Canvas.Top"]);			// must be a +ve number
        var mainWidth = mainMap["Width"] - mainCanvas["Width"];
        var mainHeight = this.control.content.findName("cnv_timeLine")["Height"] - mainCanvas["Height"];

		// Percentage position within canvas
		var lPosPerc = (Math.abs(mainLPos)) / mainWidth;
		var tPosPerc = (Math.abs(mainTPos)) / mainHeight;
		
		var minilPosPerc = miniMapMaxLeft * lPosPerc;
		var minitPosPerc = miniMapMaxTop * tPosPerc;
		
		// Debug only
		// var deb = this.control.content.findName("txtDebug");
		// deb["Text"] = "lPosPerc: " + lPosPerc + "\nmainLPos: " + mainLPos + "\ntPosPerc: " + tPosPerc + "\nmainTPos: " + mainTPos;
		
		// Adjust for max & min values
		if(minilPosPerc < miniMapMinLeft)
		{
			minilPosPerc = miniMapMinLeft
		}
		else if(minilPosPerc > miniMapMaxLeft)
		{
			minilPosPerc = miniMapMaxLeft
		}
		
		if(minitPosPerc < miniMapMinTop)
		{
			minitPosPerc = miniMapMinTop
		}
		else if(minitPosPerc > miniMapMaxTop)
		{
			minitPosPerc = miniMapMaxTop
		}
		
		// Finally - set the positions
		btnScroll["Canvas.Left"] = minilPosPerc;
		btnScroll["Canvas.Top"] = minitPosPerc;
		
		// Set the clear scroller as well
		var clearScroll = this.control.content.findName("clear_btn_scroller");
		clearScroll["Canvas.Left"] = minilPosPerc;
		clearScroll["Canvas.Top"] = minitPosPerc;
	},
	    
    calcMainCanvasPos: function()
    {
        // Minimap handles
        var miniMap = this.control.content.findName("Lines");
        var miniMapWidth = miniMap["Width"];
        var miniMapHeight = miniMap["Height"];
        
        // Minimap button handles
        var miniBtn = this.control.content.findName("btn_scroller");
        var miniBtnWidth = miniBtn["Width"];
        var miniBtnHeight = miniBtn["Height"];
        var miniBtnLeft = miniBtn["Canvas.Left"];

        // Adjust minimap width for width of button
        miniMapWidth = miniMapWidth - miniBtnWidth;
        
        // Same for height
        miniMapHeight = miniMapHeight;
        
        // Real left & top positions
        var miniLPos = miniBtn["Canvas.Left"] + miniMap["Canvas.Left"];
        var miniTPos = miniBtn["Canvas.Top"];

        // Main map handles
        var mainMap = this.control.content.findName("cnv_timeLine");
        var mainWidth = mainMap["Width"] - mainCanvas["Width"];
        var mainHeight = mainMap["Height"];
        
        // Dont forget the dateline
        var dateLine = this.control.content.findName("cnv_dates");
        
        // Percentages for ratio position
        var lPosPerc = Math.min(Math.abs(miniLPos /miniMapWidth),1);
        var tPosPerc = Math.min(Math.abs(miniTPos / (miniMapHeight-miniBtnHeight)),1);
        
        // Ensure default pos are handled
        if(miniBtn["Canvas.Left"] <= 1)
        {
			lPosPerc = 0;
		}

		if(miniBtn["Canvas.Top"] <= 0)
        {
			tPosPerc = 0;
		}
        // Set the main map left hand pos
        mainMap["Canvas.Left"] = (-mainWidth * lPosPerc);

        // Set the main map top pos
        mainMap["Canvas.Top"] = (-mainHeight * tPosPerc) + MAX_TopPos+180;	// Theres a glitch in the calc - 180 fixes it - dont know why!
        
        // Set the dateline pos as well
        dateLine["Canvas.Left"] = mainMap["Canvas.Left"];
        
        // DEBUG
        // var txt = this.control.content.findName("txtDebug");
        // txt["Text"] = "lPosPerc: " + lPosPerc + "\ntPosPerc: " + tPosPerc;
    },
    // End of calculated positions
    //

    //
    // XML methods
    getXMLPopData: function(dataId, senderName)
    {
		var xmlDoc;
		var xmlData;
        var langTitle = "";
	    var langText = "";
	    		
        try
        {
			xmlDoc = new JKL.ParseXML( "xml/langdata/lang" +dataId + ".xml" );
			xmlData = xmlDoc.parse();
			langTitle = xmlData["language"]["title"];
			langText = xmlData["language"]["text"];
		}
		catch(e)
		{
		}

		// Handle nulls
        if(langTitle != null)
        {
			this.control.content.findName("popTitle")["Text"] = langTitle;
			
			if(langText != null)
			{
				this.control.content.findName("popText")["Text"] = langText;
			}
			else
			{
				this.control.content.findName("popText")["Text"] = "";
			}
		}
        else
        {
			this.control.content.findName("popTitle")["Text"] = senderName;
			this.control.content.findName("popText")["Text"] = "";
		}
	},
    // End of XML methods
    //
    
    //
    // Video
    playMainVideo: function()
    {
		// Hide the preloaders
		this.control.content.findName("cnvMovie")["Visibility"] = "Visible";
		this.control.content.findName("mediaStartup")["Visibility"] = "Visible";

		var vid = this.control.content.findName("mediaStartup");
		vid["Width"] = mainCanvas["Width"];
		vid["Height"] = mainCanvas["Height"];
		
		var miniVidSB = this.control.content.findName("sb_scrollerIntro");
		
		// Only play if this is the first time
		if(checkCookie(Video_Cookie) == false)
		{
			// disable minimap dragging
			videoPlaying = true;
			
			// Play the video
			vid.Play();
			
			// move the scroller to the start
			this.control.content.findName("btn_scroller")["Canvas.Left"] = 1;
			this.control.content.findName("btn_scroller")["Canvas.Top"] = 1;
			
			// play the minimap storyboard at the same time - show the button as well
			this.control.content.findName("btn_scroller")["Visibility"] = "Visible";
			miniVidSB.Begin();
		}
		else
		{
			// Show the popup now so that it's visible straight away
			this.control.content.findName("cnv_popStart")["Visibility"] = "Visible";
			//this.control.content.findName("btn_scroller")["Visibility"] = "Visible";	
			
			this.control.content.findName("cnvMovie")["Visibility"] = "Collapsed";
		}
    },
    
    startupVideoEnded: function(sender, eventArgs)
    {
		// Media finished - set the cookie
		setCookie(Video_Cookie, true, 180);
		
		// Show the popup now so that it's visible on fade out
		this.control.content.findName("cnv_popStart")["Visibility"] = "Visible";
		//this.control.content.findName("btn_scroller")["Visibility"] = "Visible";
		
		// Fade it out
		var fadeOut = this.control.content.findName("media_fadeOut");
		fadeOut.Begin();
		
		// enable minimap dragging
		videoPlaying = false;
		
    },
    // End of video
    //
    
    // 
    // Storyboard
    fadeOutCompleted: function(sender, eventArgs)
    {
		this.control.content.findName("cnvMovie")["Opacity"] = this.control.content.findName("mediaStartup")["Opacity"] = 0;
		this.control.content.findName("cnvMovie")["Canvas.ZIndex"] = -5;
		this.control.content.findName("mediaStartup")["Canvas.ZIndex"] = -5;
    },    
    // End of storyboard
    //
    
    setCanvasStartupPos: function()
    {
		var canv = this.control.content.findName("cnv_timeLine");
		
		if(checkCookie(TopPos_Cookie) == false)
		{
			// No previous coordinates
			canv["Canvas.Left"] = -6572;
			canv["Canvas.Top"] = -360;
			this.control.content.findName("cnv_dates")["Canvas.Left"] = -6572;
		}
		else
		{
			canv["Canvas.Left"] = getCookie(LeftPos_Cookie);
			canv["Canvas.Top"] = getCookie(TopPos_Cookie);
			this.control.content.findName("cnv_dates")["Canvas.Left"] = getCookie(LeftPos_Cookie);
			this.control.content.findName("cnv_popStart")["Visibility"] = "Collapsed";
			
		// Adjust the minimap to match
		this.calcMiniMapPos();
		}
		
		// Adjust the minimap to match
		//this.calcMiniMapPos();
	}	
	// End of startup
	//
	//
}