$(document).ready(function(){
	init();
	$(document).scroll(function(){
		if($(this).scrollTop() + $(window).height() > 1300)
		{
			initGraph();
		}
	});
});

///Infografico variables
var stage;
var stageUpdated = false;
var stage2;
var stageTetris;
var stageTetrisUpdated = false;

var xPos = [0,1,2,3,4];
var yPos = [0,1,2,3,4];
var initialPositions = [[93,1233],
						[182,1233],
						[225,1233],
						[270,1233],
						[313,1233],
						[357,1233],
						[378,1233],
						[400,1233],
						[443,1233],
						[487,1233],
						[508,1233],
						[531,1233],
						];
var positions =[ [[93,1212],[291,1212],[291,1166],[164,1166]],
				 [[182,1233],[182,1189],[595,1189]],
				 [[225,1233],[225,1148],[552,1148],[552,1028]],
				 [[270,1233],[270,1133] ],
				 [[313,1233],[313,1048],[180,1048] ],     
				 [[357,1129]],
				 [[378,1211], [334,1211], [334,1026],[316,1026] ],     
			 	 [[400,1167],[572,1167],[572,1118]],
				 [[443,1212],[606,1212]],
				 [[487,1063]],
				 [[508,988]],
				 [[531,960]]
			              ];
var nextPoint = [[0,0],[0,0]];

var boxPositions = [[39,1074],[591,1129],[546,974],[176,1065],[52,989],[351,1075],[198,956],[566,1039],[606,1206],[351,999],[328,933],[525,909]];

var shapes=[];


var colors=["FBB03B","CCCCCC","CCCCCC","CCCCCC","CAD400","CAD400","FF0000","29ABE2","29ABE2","CAD400","A859F7","FBB03B"];
var end = [false,false,false,false,false,false,false,false,false,false,false,false];

var currentID = 0;
var startedGraph = false;
var normalPath = true;
var loadedImg	= false;
///End Infografico variables

//Begin Tetris variables
var tetrisPos = [[209,475],[125,375],[89,283],[162,375],[149,475],[281,375],[89,475]];
var tetrisPieces = [];
	
function init() {
	$('<div id=infografico></div>').appendTo('body');
	$('#infografico').css({'top': '0px', 'left':'0px'});
	$('<div id=blackboard> </div>').css({'background-color': '#CCCCCC', 'position':'absolute', 'top': '0px', 'left':'0px'}).appendTo('#infografico');
	$('<canvas id="imgCanvas" width="800" height="1860" style="position:absolute; top:0; left:50%; margin-left:-400px "></canvas>').appendTo('#infografico');
	$('<canvas id="myCanvas" width="800" height="1300" style="position:absolute; top:0; left:50%; margin-left:-400px "></canvas>').appendTo('#infografico');
	$('<canvas id="tetrisCanvas" width="800" height="600" style="position:absolute; top:0; left:50%; margin-left:-400px "></canvas>').appendTo('#infografico');
	$('#blackboard').css('width',$('#infografico').css('width'));
	$('#blackboard').css('height',$('#imgCanvas').css('height'));
	$('siteJynx').css('height',$('#myCanvas').css('height'));
	
	$('<a href="http://www.jynx.com.br/wordpress"> <IMG SRC=info/exit.png style="position:absolute; left:50%; margin-left:350px ; margin-top:1820px; " > </a>').insertAfter('#tetrisCanvas');
	if(navigator.appName.indexOf("Explorer") != -1 )
	{
		$('<IMG SRC=info/image.png WIDTH=800 HEIGHT=1860 style="position:absolute; left:50%; margin-left:-400px " >').insertBefore('#myCanvas');		
		$('#myCanvas').remove();
		return;
	}
	
	

	// create a stage object to work with the canvas. This is the top level node in the display list:
	var canvas = document.getElementById("myCanvas");
	stage = new Stage( document.getElementById("myCanvas"));
	stage.autoClear = false;
	stage2 = new Stage( document.getElementById("imgCanvas"));
	stage2.autoClear = false;
	stageTetris = new Stage( document.getElementById("tetrisCanvas"));
	
	
					
	// Bitmap also supports construction with a URI to an image to load:
	
	
	//initGraph();
	var image = new Image();
	image.src = "info/Infografico011.png";
	image.onload = handleImageLoad;
	
	//Subscribe to the Tick class. This will call the tick
	//method at a set interval (similar to ENTER_FRAME with
	//the Flash Player)
	Ticker.setFPS(60);
	Ticker.addListener(this);
}
function onImageError(event)
{
	
}
function handleImageLoad(event)
{

	var image = event.target;
	var bmp = new Bitmap(image);	
	stage2.addChild(bmp);
	stage2.update();

	
	
	initTetris();
	//initClock();
	//stage.update();
	loadedImg = true;
}
function placeExitBtn()
{
	// enable touch interactions if supported on the current device:
	if (Touch.isSupported()) { 
		Touch.enable(stage); 
	}
	// enabled mouse over / out events
	stage.enableMouseOver(10);
	
	// Bitmap also supports construction with a URI to an image to load:
	var exit = new Bitmap("info/exit.png");	
	stage.addChild(exit);
	exit.x = 750;
	exit.y = 1825;
	//onPress,onClick,onMouseDown,onMouseUp,onMouseMove
	exit.onPress = function(mouseEvent) {		  
		window.location = "http://www.jynx.com.br/wordpress";
	}
}
function initClock()
{
	var data = {"images": ["info/clock.png"], "animations": {"all": [0, 40]}, "frames": {"regX": 0, "width": 53, "regY": 0, "height": 53, "count": 41}};
	var sprite = new SpriteSheet(data);
	var clockAnim = new BitmapAnimation(sprite);
	clockAnim.gotoAndPlay(1);
	clockAnim.x = 64;
	clockAnim.y = 1451;
	stage2.addChild(clockAnim);
}
function initTetris()
{
	var tetrisPiece;
	var imgTetris
	for(var i=1; i<=7 ; i++)
	{
		tetrisPiece = new Bitmap("info/tetris/tetris"+i+".png");
		imgTetris = new Image();
		imgTetris.onload = handleBoxImageLoad;
		imgTetris.src = "info/tetris/tetris"+i+".png"
		
			
		tetrisPiece.x = tetrisPos[i-1][0];
		if(navigator.platform.indexOf("iPad") == -1 )
		{
			tetrisPiece.y = Math.round(Math.random()*(-400));
		}
		else
		{
			tetrisPiece.y = tetrisPos[i-1][1];			
		}
		stageTetris.addChild(tetrisPiece);
		tetrisPieces.push(tetrisPiece);
	}
	stageTetris.update();
	//stage.update();
}
function updateTetris()
{
	var currentPiece;
	for(var i = 0; i <7;i++ )
	{
		currentPiece = tetrisPieces[i];
		if(currentPiece != undefined && currentPiece.y < tetrisPos[i][1])
		{
			currentPiece.y+=2;
			if(currentPiece.y > tetrisPos[i][1])
			{
				tetrisPieces[i] = undefined;
				currentPiece.y = tetrisPos[i][1];
				stageTetris.removeChild(currentPiece);
				stage2.addChild(currentPiece);
				stage2.update();
			}
			stageTetrisUpdated = true;
		}
		
	}
}

function initGraph()
{
	if(!startedGraph)
	{
		startedGraph = true;
		for(var i=0;i <= 11;i++)
		{
			initID(i);
		}
	}	
	
}


//function called by the Tick instance at a set interval
function tick()
{
	if(!loadedImg)
	{
		return;
	}
		
	if(startedGraph)
	{
		for(var i=0;i <= 11;i++)
		{
			drawID(i);
		}
	}
//	if(Ticker.getTicks()%20 == 0)
//	{
		updateTetris();
//	}
	if(stageUpdated)
	{
		stageUpdated = false;
		stage.update();
	}
	if(stageTetrisUpdated && (Ticker.getTicks()%5 == 0))
	{
		stageTetrisUpdated = false;
		stageTetris.update();
	}
//	if(Ticker.getTicks() < 60)
//	{
//		return;
//	}
	/*
	var currentFPS = Ticker.getMeasuredFPS(30);
	
	
	 if ( currentFPS < 10 && currentFPS >0)
	 {
		//console.log(currentFPS); 
		normalPath = false;
	 }*/
	
}
function initID(id)
{
	positions[id].reverse();
	nextPoint[id] = positions[id].pop();
	xPos[id] = initialPositions[id][0];
	yPos[id] = initialPositions[id][1];			
	
}
function handleBoxImageLoad(event)
{
	stage2.update();
}
	
function drawID(id)
{
	if(end[id])
	{
		return;
	}
	var s;
	if(shapes[id] == undefined)
	{
		var g = new Graphics();
		g.setStrokeStyle(10).beginStroke("#"+colors[id]).beginFill(colors[id]);
		g.drawCircle(0,0,1);
		s = new Shape(g);
		s.x = xPos[id];
		s.y = yPos[id];
		stage.addChild(s);
		shapes[id] = s;
		stageUpdated = true;
	}
	else
	{
		s = shapes[id];
		s.x = xPos[id];
		s.y = yPos[id];
		stageUpdated = true;
	}
			
	if(xPos[id] == nextPoint[id][0] && yPos[id] == nextPoint[id][1])
	{
		if(positions[id].length > 0)
		{
		   nextPoint[id] = positions[id].pop();
		}	
		else
		{
			end[id] = true;
			
			// Bitmap also supports construction with a URI to an image to load:
			var bmp = new Bitmap("info/box"+id+".png");
			var image = new Image();
			image.onload = handleBoxImageLoad;
			image.src = "info/box"+id+".png";
			bmp.x = boxPositions[id][0];
			bmp.y = boxPositions[id][1];
			stage2.addChild(bmp);
			//stage2.update();
			
			return true;
		}
		
	}
	else
	{
		if(xPos[id] != nextPoint[id][0])
		{
			xPos[id] += ((nextPoint[id][0]-xPos[id])/(Math.abs(nextPoint[id][0]-xPos[id])))*2;
			if(Math.abs(xPos[id] - nextPoint[id][0]) < 2)
			{
				xPos[id] = nextPoint[id][0];
			}
		}
		if(yPos[id] != nextPoint[id][1])
		{
			yPos[id] += ((nextPoint[id][1]-yPos[id])/(Math.abs(nextPoint[id][1]-yPos[id])))*2;
			
			if(Math.abs(yPos[id] - nextPoint[id][1]) < 2)
			{
				yPos[id] = nextPoint[id][1];
			}
		}
		
	}
	return false;
}
