var MAIN_NAV=[
				{ id: "facebookBtn", z:0, x:0, y:0 },
				{ id: "twitterBtn", z:0, x:0, y:0 },
				{ id: "youtubeBtn", z:0, x:0, y:0 },
				{ id: "newSongBtn", z:2000, x:0.09367141659682149, y:8.237667560321718 },
				{ id: "forumBtn", z:300, x:-0.23541492036881784, y:-0.891447721179625 },
				{ id: "storeBtn", z:-700, x:2.7609807208717543, y:6.117828418230584 },
				{ id: "newsBtn", z:7100, x:0.4336798342052725, y:-2.463884974483874},
				{ id: "creditsBtn", z:7100, x:0.4336798342052725, y:-2.463884974483874},
				{ id: "pastBtn", z:-8100, x:0.4336798342052725, y:-2.463884974483874},
				{ id: "discographyBtn", z:300, x:0.4336798342052725, y:-2.463884974483874},
				{ id: "gigographyBtn", z:900, x:0.1336798342052725, y:-2.463884974483874},
				{ id: "peopleBtn", z:9900, x:0.433121347456455, y:-2.46384564483874},
				{ id: "videosBtn", z:7780, x:0.43342052725, y:-2.463884974483874},
				{ id: "archiveBtn", z:7200, x:0.433456342052725, y:-2.463886544483874}
				
			];

var lineStart=modelLineStart;
var lineEnd=modelLineEnd;

var sprites=sphere_coords;
var spriteSize=sphere_rads;

var SUB_NAV_OPEN=false;

var SHOW_STATS=0;

var CONTENT_FADE_IN_DURATION=0.5;
var CONTENT_FADE_OUT_DURATION=0.5;
var MAIN_VANISHING_OFFX=-200;
var MAIN_VANISHING_OFFY=100;

var DIRECTION_UP="UP";
var DIRECTION_DOWN="DOWN";
var DIRECTION_LEFT="LEFT";
var DIRECTION_RIGHT="RIGHT";
var itemRolled=null;
var itemClicked=null;

var mousePressed=false;
var mousePos={x: 0, y: 0};
var mouseStartPos={x: 0, y: 0};
var mouseStartRot={x: 0, y: 0};

var scene;

var lines = [];
var circles = [];

var cam;
var camTween=null;
var camTweenPos=null;
		
var canvas;
var stats;

var introFinished = false;

var keyBoardDirection="";
var compassScene;
var compassCam;
var compassCamRotationOffset = new Quaternion(0.686074898128388, 0.7271461030878897, 0.023414709608057256, 0.0033956289871526907);
compassCamRotationOffset.invert();
var bjorkTextPoint;
var bjorkTextDiv;

var hotSpotDiv;

var forwardDirection=null;
var horizontalDirection=null;
var verticalDirection=null;

var fixedSize=false;

var prevTouchTime=-1;

var menuToRotation={};
var subNavContent={};
var subNavPath={};
var contentContainer=null;
var navShield=null;
var renderInterval=0;
var curRotationId=null;
var sceneScale=0;


var groupNameForAni={};

var currentAnimation = null;
var currentAnimationIndex = 0;
var sectionToGo = null;

var introOnceBool=null;

function init()
{
	//Chrome white box fix
	/*$("body").prepend('<div id="sticker"></div>');
	$("#sticker").css({
		"backgroundColor" : "#000",
		"width" : "260px",
		"height": "1600px",
		"position" : "fixed",
		"top" : "0",
		"z-index" : "0"
	});*/
	
	
	
	
	
	
	prepareAnimationData();

	$(document).keydown(onKeyDown);
	$(document).keyup(onKeyUp);

	canvas=document.getElementById("mainCanvas");
	canvas.onmousedown=onMouseDown;
	document.onmousemove=onMouseMove;
	document.onmouseup=onMouseUp;
			
	scene=new Scene3D(canvas);
	scene.vanishingX+=MAIN_VANISHING_OFFX;
	scene.vanishingY+=MAIN_VANISHING_OFFY;
	
	cam=new Camera3D();

	/**/
	
	for(var i=0; i<MAIN_NAV.length; i++)
    {
    	var menuItem=$("#" + MAIN_NAV[i].id);
    	
    	menuItem.mouseover(onMenuRolled);
	 	menuItem.mouseout(onMenuRolledOut);
	 	
    	menuToRotation[MAIN_NAV[i].id]=MAIN_NAV[i];
    }
   
	for(var i=0;i<CONT_BTN.length;i++)
	{
		var menuItem=$("#"+	CONT_BTN[i].id).click(function(ev){ 
			ev.preventDefault();
			pauseAnyAudioPlayer();
			removeIntroPlayer();
			loadContent(subNavContent[$(this).attr("id")]); 
			SWFAddress.setValue(subNavPath[$(this).attr("id")]);
			onMenuPress(ev);
		});
		subNavContent[CONT_BTN[i].id]=CONT_BTN[i].content;
		subNavPath[CONT_BTN[i].id]=CONT_BTN[i].path;
	}
	
	var names = SWFAddress.getPathNames();
	$(".subNav").hide();	
	if (names[0]=="past") {
		$("#past_nav").show();			
	}
	
    navShield=$("#nav_shield");
	navShield.hide();
	contentContainer=$("#content");
    contentContainer.hide();	
	
	
	var names = SWFAddress.getPathNames();
	
	//if(names.length == 0)
	//{
		createItems(0);
		createCompass();
	//}
	
	SWFAddress.onExternalChange();
	
	
	if(SHOW_STATS)
	{
		stats=new Stats();
		document.getElementById("mainContainer").appendChild( stats.domElement );
	}

	$("#bjorkText").css("cursor","pointer");
	$("#hotspot").css("cursor","pointer");
	$("#secondhotspot").css("cursor","pointer");
	 
	bjorkTextDiv=$("#bjorkText");
	hotSpotDiv=$("#hotspot");
	hotSpotDivBjork=$("div#secondhotspot")
	bjorkTextDiv.bind("click", onResetScene);
	
	hotSpotDiv.bind("click", function(){
		onResetScene();
		onBackButtonHit();
	});
	hotSpotDivBjork.bind("click", function(){
		onResetScene();
		onBackButtonHit();
	});
	
	
	//canvas.onmousemove=onMouseMove;
	//canvas.onmousedown=onMouseDown;
	//canvas.onmouseup=onMouseUp;
	
	forwardDirection=new Vector3D();
	horizontalDirection=new Vector3D();
	verticalDirection=new Vector3D();
	calculateCamDirection();

	startRender();
    
    if (!fixedSize) {
		resizeCanvas();
		$(window).resize(resizeCanvas);
	}
}

SWFAddress.onExternalChange = function() {
	onExternalChange(); //comon.js
}
/*SWFAddress.onExternalChange = function() {
	//window.console.log("Xternal change");
	var names = SWFAddress.getPathNames();
	var item = null;
	
	switch (names[0]){
		case "news" :
			item = "newsBtn";
			loadContent(subNavContent[item]);
			break;
		
		case "signup" : 
			item = "newSongBtn";
			loadContent(subNavContent[item]);
			break;
		
		case "credits" : 
			item = "creditsBtn";
			loadContent(subNavContent[item]);
			break;
		
		default : initCompass();
	}
	
	if(item != null){
			_gaq.push(['_trackPageview','/'+item]);
			var e = {target : document.getElementById(item)};
			onMenuPress(e);
	}

}*/

function pauseAnyAudioPlayer(){
	$('.sc-player.playing a.sc-pause').click();
}

function removeIntroPlayer(){
	$("#playerContainer").fadeOut(200);
	
	/*if($("div.intro-player").hasClass("playing")){
		$("div.intro-player a.sc-pause").click();
	}*/
}



function onGalaxyReadyDeepLink(){
	//console.log("debug2");
	loadContent(sectionToGo);
}

function initMouseEvents()
{
	//canvas.onmousemove=onMouseMove;
	//canvas.onmousedown=onMouseDown;
	//canvas.onmouseup=onMouseUp;

	//document.onmousemove=onMouseMove;
	//canvas.onmousedown=onMouseDown;
	//document.onmouseup=onMouseUp;	
}

function startRender()
{
	//initMouseEvents();

	renderInterval=setInterval(onEnterFrame, 33);
	
	if(introOnceBool){
		animate('bjork');
	}else{
		animate('intro');	
	}
		
	introOnceBool = true;
	
}

function stopRender()
{
	clearInterval(renderInterval);
}

function onMenuRolled(ev)
{	
	setMenuItemRolled($(this));
}

function onMenuRolledOut(ev)
{
	setMenuItemRolledOut($(this));
}

function setMenuItemRolled(item)
{
	itemRolled = item.attr("id");
	
	//setGlowingItem(itemRolled);

	animate(itemRolled);
}

function setMenuItemRolledOut(item)
{
	itemRolled=null;

	//setGlowingItem(null);
}

/*function onMenuPress(ev)
{	
	itemClicked = $(ev.target).attr("id");
	setGlowingItem(itemClicked);
	
	if($(ev.target).parent().children().length>1)
	{
		
		if(ev.preventDefault != null)
			ev.preventDefault();
		if($(ev.target).parent().find("div").is(":hidden"))
			$(ev.target).parent().find("div").slideDown();
	} 
	else 
	{	
		if($("li div.subNav").is(":visible"))
			if(!( (itemClicked == "facebookBtn") || (itemClicked == "twitterBtn") || (itemClicked == "youtubeBtn"))){
				$("li div.subNav").slideUp();	
			}
	}
}*/


function resizeCanvas()
{
	canvasWidth = $(window).width();
	canvasHeight = $(window).height();
	
	$(canvas).attr("height", canvasHeight);
	$(canvas).attr("width", canvasWidth);
	
	contentContainer.css("width", canvasWidth-260); /* MARK - content width should be screen width MINUS the padding.. */
	contentContainer.css("height", canvasHeight);
	
	navShield.css("width", 260); /* MARK - content width should be screen width MINUS the padding.. */
	navShield.css("height", canvasHeight);
	
	if(scene!=null)
	{
		
		scene.vanishingX=canvasWidth*0.5;//+MAIN_VANISHING_OFFX;
		scene.vanishingY=canvasHeight*0.5;//+MAIN_VANISHING_OFFY;
		/**/
	}
	//ctx.globalCompositeOperation = "lighter";
	
	return true;
}


function createItems(iteration)
{
	//lines=[];
	//circles=[];
	
	var countLines=lineStart.length/3;
	var countCircles=sprites.length/3;
	
	var numLinesToRender=0;
	
	for(var i = 0; i <countLines; i++)
	{
		if(i % iteration == 0 || iteration == 0)
		{
			if(lines[i] == undefined)
			{
				lines[i]=new Line3D();
				lines[i].sX=lineStart[i3];
				lines[i].sY=lineStart[i3+1];
				lines[i].sZ=lineStart[i3+2];
				
				lines[i].eX=lineEnd[i3];
				lines[i].eY=lineEnd[i3+1];
				lines[i].eZ=lineEnd[i3+2];
				
				scene.addItem(lines[i]);
				
				var i3=i*3;
				numLinesToRender++;
			}
		}
	}
	
	for(var i = 0; i < countCircles; i++)
	{
		//if(i % iteration == 0  || iteration == 0)
		//{
			if(circles[i] == undefined)
			{
				var i3=i*3;
				
				circles[i]=new Circle3D();
				circles[i].x=sprites[i3];
				circles[i].y=sprites[i3+1];
				circles[i].z=sprites[i3+2];
				circles[i].radius=spriteSize[i];
				
				scene.addItem(circles[i]);
				
				//var i3=i*3;
			}
		//}
	}
}

function onMouseMove(ev)
{
	mousePos.x=ev.pageX;
	mousePos.y=ev.pageY;
		
	if(mousePressed)
	{
		var mouseDeltaX=mousePos.x-mouseStartPos.x;
		var mouseDeltaY=mousePos.y-mouseStartPos.y;
		
		mouseStartPos.x=mousePos.x;
		mouseStartPos.y=mousePos.y;
		
		rotateCamera(mouseDeltaX, mouseDeltaY);
	
		//updateControls();
	}
}

function onMouseDown(ev)
{
	mousePressed=true;
	
	mouseStartPos.x=mousePos.x;
	mouseStartPos.y=mousePos.y;
	
	
	//mouseStartRot.x=cam.rotationX;
	//mouseStartRot.y=cam.rotationY;
}

function onMouseUp(ev)
{
	mousePressed=false;
}


function onResetScene()
{
	animate("bjork");
}

function onKeyDown(ev)
{	
	var ev2 = window.event ? window.event : ev;
	
	if (ev.which == 37 || ev.which == 38 || ev.which == 39 || ev.which == 40)
	{
		
		if (ev.which == 38 || ev.which == 40) { // Forward movement
			if (ev2.shiftKey) {
				var directionMultiplier; 
				var directionVector;
				directionVector = verticalDirection;
				directionMultiplier = (ev.which == 40) ? 1 : -1;
				targetCameraX += directionMultiplier * directionVector.x;
				targetCameraY += directionMultiplier * directionVector.y;
				targetCameraZ += directionMultiplier * directionVector.z;
			} else {
				var directionMultiplier; 
				var directionVector;
				directionVector = forwardDirection;
				directionMultiplier = (ev.which == 38) ? 1 : -1;
				targetCameraX += directionMultiplier * directionVector.x;
				targetCameraY += directionMultiplier * directionVector.y;
				targetCameraZ += directionMultiplier * directionVector.z;
			} 
		}
		if (ev.which == 37 || ev.which == 39) { // Horizontal movement
			if (ev2.shiftKey) {
				var directionMultiplier = (ev.which == 37) ? 1 : -1;
				
				// This will rotate the camera around the camera's vertical axis, i.e. "turning your head left and right" 
				cam.rotation.multiply( Quaternion.getFromAxisAngle(directionMultiplier * 0.01, verticalDirection.x, verticalDirection.y, verticalDirection.z) );
				calculateCamDirection();
			} else {
				var directionMultiplier; 
				var directionVector;
				directionVector = horizontalDirection;
				directionMultiplier = (ev.which == 39) ? 1 : -1;
				targetCameraX += directionMultiplier * directionVector.x;
				targetCameraY += directionMultiplier * directionVector.y;
				targetCameraZ += directionMultiplier * directionVector.z;
			} 
		}
		
	}
		
		
}

function rotateCamera(deltaX, deltaY)
{
	var deltaRotX=deltaY/200;
	var deltaRotY=-deltaX/200;
	
	cam.rotation.multiply( Quaternion.getFromEuler(deltaRotX, deltaRotY, 0) );
	
	calculateCamDirection();
}

function onKeyUp(ev)
{
	keyBoardDirection="";
}

var lastTickTime=(new Date()).getTime();
//function onRenderEnter()
function onEnterFrame()
{	
	var newTickTime=(new Date()).getTime();
	
	if(!mousePressed) {
	}
	
	if(camTween)
	{
		camTween.tick(newTickTime-lastTickTime);
		
		targetCameraX= cam.x=camTweenProp.x;
		targetCameraY= cam.y=camTweenProp.y;
		targetCameraZ= cam.z=camTweenProp.z;
		
		//console.log(camTweenProp.s, curWaypointIndex);
		cam.rotation=Quaternion.slerp(curQuat, nextQuat, camTweenProp.s);
		calculateCamDirection();

	}
	else
	{
		// Find where the mouse is relative to the center of the screen.
		var dx = mousePos.x - scene.vanishingX;
		var dy = mousePos.y - scene.vanishingY;
		
		
		// The camera should always be heading towards targetCameraXYZ, the dx and dy stuff
		// is the offset added in the camera's horizontal and vertical direction to simulate
		// the 'sliding' effect.
		
		var adjustedCameraTargetX = targetCameraX + 0.001 * dx * horizontalDirection.x + 0.001 * dy * verticalDirection.x; 
		var adjustedCameraTargetY = targetCameraY + 0.001 * dx * horizontalDirection.y + 0.001 * dy * verticalDirection.y; 
		var adjustedCameraTargetZ = targetCameraZ + 0.001 * dx * horizontalDirection.z + 0.001 * dy * verticalDirection.z; 
		
		cam.x += 0.1 * (adjustedCameraTargetX - cam.x);
		cam.y += 0.1 * (adjustedCameraTargetY - cam.y);
		cam.z += 0.1 * (adjustedCameraTargetZ - cam.z);
	}
	
	bjorkTextDiv.css("left", bjorkTextPoint.x2D+"px");
	bjorkTextDiv.css("top", bjorkTextPoint.y2D+"px");
	scene.render(cam);
	lastTickTime=newTickTime;

	
	// The second line puts an overall 'offset' on the compass' rotation so that
	// the bjork screen and the vertical position of the compass line up. 
	compassCam.rotation=cam.rotation.clone();
	compassCam.rotation.multiply(compassCamRotationOffset);
	//console.log(compassCam);
	compassScene.render(compassCam);
}

function animate(animationName)
{
	currentAnimation = animationName;
	currentAnimationIndex = animationNameToIndex[animationName];
	
	
	curWaypoints = animationData[currentAnimationIndex].waypoints;
	curWaypointIndex = -1;
	
	camTweenProp={x: cam.x, y: cam.y, z: cam.z, s: 0};
	camTween=Tween.get(camTweenProp);
	camTween.to({x: curWaypoints[0].px, y: curWaypoints[0].py, z: curWaypoints[0].pz, s: 1}, curWaypoints[0].duration, curWaypoints[0].easeFunction);
	camTween.call(incrementPosIdx);
	
	curQuat=cam.rotation.clone();
	nextQuat=curWaypoints[0].rotation.clone();
}

function incrementPosIdx()
{
	curWaypointIndex++;
	
	
	//console.log(curWaypointIndex);
	
	if(curWaypointIndex<curWaypoints.length-1)
	{
		camTweenProp.s=0;
		
		curQuat=curWaypoints[curWaypointIndex].rotation.clone();
		nextQuat=curWaypoints[curWaypointIndex+1].rotation.clone();
		
		camTween=Tween.get(camTweenProp);
		// alert(curWaypointIndex+1 +": " +curWaypoints[curWaypointIndex+1].duration);
		
		camTween.to({x: curWaypoints[curWaypointIndex+1].px, y: curWaypoints[curWaypointIndex+1].py, z: curWaypoints[curWaypointIndex+1].pz, s: 1}, curWaypoints[curWaypointIndex+1].duration, curWaypoints[curWaypointIndex+1].easeFunction);
		camTween.call(incrementPosIdx);
	}
	else
	{
		//console.log("ANI FINISHED:"+ curWaypointIndex);
		camTween=null;

		// Intro finished here
		if(currentAnimation == "intro"){
			$(document).trigger("galaxyReady");	//Mathieu..
			//console.log("galaxy ready");
		}
	}
}

var curQuat;
var nextQuat;
var curWaypointIndex=0;
var curWaypoints;
var camTweenProp=null;


function calculateCamDirection()
{
	forwardDirection	= new Vector3D(0,0,100);
	horizontalDirection	= new Vector3D(100,0,0);
	verticalDirection	= new Vector3D(0,100,0);
	
	var rotMat=cam.rotation.getMatrix();
	rotMat.transformPoint(forwardDirection);
	rotMat.transformPoint(horizontalDirection);
	rotMat.transformPoint(verticalDirection);
}



function setGlowingItem(newRotId)
{
	
	if(curRotationId != newRotId)
	{	
		removeGlow($("#"+curRotationId));
		addGlow($("#"+newRotId));
		curRotationId = newRotId;
	}
/*	if(newRotId!=null && newRotId!=curRotationId) //Mathieu
	{
		if(curRotationId!=null)
			removeGlow($("#"+curRotationId));
		
		addGlow($("#"+newRotId));
		curRotationId=newRotId;
	}
	else if(newRotId==null && curRotationId!=newRotId)
	{
		removeGlow($("#"+curRotationId));
		curRotationId=null;
	}*/
} 

function createCompass()
{
	compassScene=new Scene3D(canvas);
	compassCam=new Camera3D();

	// Unfortunately, I removed scaleX, scaleY, scaleZ and combined them into 'scale'
	// before I realized that the compass was actually being flipped, so this is a 
	// small hack to allow flipping in the x-direction.
	
	compassCam.flipHack=-1;

	
	
	compassScene.doClear=false;
	compassScene.vanishingX=114; /* MARK */
	compassScene.vanishingY=112; /* MARK */
	compassCam.scale=0.7;/* MARK */
	initCompass();
	
	bjorkTextPoint = new Vector3D(-100, -12, 0);
	compassScene.addItem(bjorkTextPoint);
}

function loadContent(content)
{
	contentContainer.load(content, onContentLoaded);
}

function onContentLoaded(ev)
{
	stopRender();
	
	contentContainer.find("#backButton").click(function(){ 
		$("li div.subNav").slideUp();
		sectionToGo = null;
		location.hash = "";
		onResetScene();
		onBackButtonHit(); 
	});
	
	contentContainer.fadeIn(CONTENT_FADE_IN_DURATION*1000);
	navShield.fadeIn(CONTENT_FADE_IN_DURATION*1000);
	if (typeof activateSearch==='function') activateSearch();
}

function onBackButtonHit(){
	console.log("back button");
	location.hash = "";
	navShield.fadeOut(CONTENT_FADE_OUT_DURATION*1000); 
	contentContainer.fadeOut(CONTENT_FADE_OUT_DURATION*1000, onContentOut);
}

function onContentOut(ev)
{
	startRender(); 
	contentContainer.html("");
}

/*function addGlow(target)
{
	target.addClass('glow');
}

function removeGlow(target)
{
	target.removeClass('glow');
}*/

