// Create Character Element
$(document).ready(function()
{
	// Check For Flash Availanility
	var Object_FlashVersion = swfobject.getFlashPlayerVersion();
	if(Object_FlashVersion.major > 8)
	{
		// Append Container
		$(".page").before('<div class="snail animation"><div id="snailswf"></div></div>');
   
		// Initialise Animation
		var Array_FlashVariables = {
			variable1: "hello",
			variable2: "world"
		};
		var Array_FlashParameters = {
			wmode: "transparent",
			allowscriptaccess: "always"
		};
		var Array_FlashAttributes = {
			id: "snailswfid",
			name: "snailswfname"
		};

		swfobject.embedSWF("animations/snail.swf", "snailswf", "300", "300", "9.0.0", "install.swf", Array_FlashVariables, Array_FlashParameters, Array_FlashAttributes);

		// Define Movement
		function stopSnail()
		{
			// Stop All Animation
			$('#snailswfid').get(0).snailStop();
		}
		
		function animateSnail()
		{
			// Calculate Movement
			Integer_InitialX = parseInt($(".snail").css('left').replace('px',''));
			Integer_InitialY = parseInt($(".snail").css('top').replace('px',''));
			Integer_TargetX = parseInt($(window).width() * 0.5);
			Integer_TargetY = parseInt($(window).height());
			
			Integer_TravelX = parseInt(Math.abs(Integer_TargetX - Integer_InitialX));
			Integer_TravelY = parseInt(Math.abs(Integer_TargetY - Integer_InitialY));
			
			Integer_Duration = parseInt((Integer_TravelY + Integer_TravelX) * 300);
			
			Integer_Radians = Math.atan2(Integer_TargetY - Integer_InitialY, Integer_TargetX - Integer_InitialX);
			Integer_Angle = parseInt(Integer_Radians * 180 / Math.PI);

			// Apply Rotation
			function tempFunc(Integer_NewAngle)
			{
				function pointSnail()
				{
					if(typeof(document.getElementById('snailswfid').snailRotate) == "function")
					{
						document.getElementById('snailswfid').snailRotate(Integer_NewAngle + 100);
					}
					else
					{
						setTimeout(pointSnail, 100);
					}
				}

				setTimeout(pointSnail, 100);
			}
   
			tempFunc(Integer_Angle);

			
			//$('#snailswfid').get(0).snailRotate(120);
				
			// Start Animation
			$(".snail").animate({ 'left': Integer_TargetX + 'px', 'top': Integer_TargetY + 'px' }, Integer_Duration, function()
			{
				// Move To Initial Position
				$(".snail").css('left', '-300px');
				$(".snail").css('top', '450px');

				// Loop Animation
				animateSnail();
			});
		}
		
		// Begin Movement
		animateSnail(true);
   
		// Make Draggable
		$(".snail").draggable({ scroll: false, start: function()
			{
				// Play Flinch Animation
				$('#snailswfid').get(0).snailFlinch();
   
				// Halt Movement
				$(".snail").stop(true, false);
   
			}, drag: function() {
   
			}, stop: function() {
   
				// Play Relax Animation
				$('#snailswfid').get(0).snailRelax();

				// Restart Movement
				animateSnail();
			}
		});
	
	}

});
