var anim_container, dom_overlay_container, fnStartAnimation, ctx,comp,lib, ss;
var errorcount = 0;
var lastW, lastH, lastS=1;	
var w,h,ha,iw,ih;
var partcharged = 0;

function resizeCanvas(isResp, respDim, isScale, scaleType) {			
			var w = lib.properties.width, h = lib.properties.height;			
			var iw = window.innerWidth, ih=window.innerHeight;			
			var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;			
			if(isResp) {                
				if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {                    
					sRatio = lastS;                
				}				
				else if(!isScale) {					
					if(iw<w || ih<h)						
						sRatio = Math.min(xRatio, yRatio);				
				}				
				else if(scaleType==1) {					
					sRatio = Math.min(xRatio, yRatio);				
				}				
				else if(scaleType==2) {					
					sRatio = Math.max(xRatio, yRatio);				
				}			
			}			
			canvas.width = w*pRatio*sRatio;			
			canvas.height = h*pRatio*sRatio;
			canvas.style.width = dom_overlay_container.style.width = anim_container.style.width =  w*sRatio+'px';				
			canvas.style.height = anim_container.style.height = dom_overlay_container.style.height = h*sRatio+'px';
			stage.scaleX = pRatio*sRatio;			
			stage.scaleY = pRatio*sRatio;			
			lastW = iw; lastH = ih; lastS = sRatio;		
			stage.tickOnUpdate = false;            
			stage.update();            
			stage.tickOnUpdate = true;	
		}




function init() {
	
	
	
	canvas = document.getElementById("canvas");
	anim_container = document.getElementById("animation_container");
	dom_overlay_container = document.getElementById("dom_overlay_container");
	loader = new createjs.LoadQueue(false);
	loader.addEventListener("fileload", function(evt){handleFileLoad(evt,comp)});
	loader.addEventListener("complete", function(evt){handleComplete(evt,comp)});
	loader.setMaxConnections(5); // Allow 10 concurrent loads
	
	stage = new createjs.Stage(canvas);
	
	preload.loadFile({id: "back" , src:"images/load.jpg"});
	preload.on("complete", imgloaded);
	
	//Texte de progression de chargement
	if(typechargement == 1)
	{
	loadProgressLabel = new createjs.Text("",tailletxtchargement+"px Verdana",couleurtxtchargement);
	loadProgressLabel.lineWidth = dimLturbo-10;
	loadProgressLabel.textAlign = "center";
	loadProgressLabel.x = posXchargement;
	loadProgressLabel.y = posYchargement
	loadProgressLabel.text =  " "
	}
	
	if(typechargement == 2)
	{
	//container that holds all the elements of the loading bar
	loadingBarContainer1 = new createjs.Container();

	//creating the loading bar   
    loadingBar1 = new createjs.Shape();
    loadingBar1.graphics.beginFill(LoadingBarColor1).drawRect(0, 0, 1, loadingBarHeight1).endFill();

    
    frame1 = new createjs.Shape();
	if (barrestype == 1){
	frame1.graphics.beginFill(LoadingBarColor2).drawRoundRect(-padding/2, -padding/2,loadingBarWidth1+padding, loadingBarHeight1+padding,10).endFill();
	}
	else{
    frame1.graphics.setStrokeStyle(epaisseurDbordure).beginStroke(LoadingBarColor2).drawRoundRect(-padding/2, -padding/2, loadingBarWidth1+padding, loadingBarHeight1+padding,8).endStroke();
	if (barrestype == 3){
		frame1.graphics.beginFill(LoadingBarColor2).drawRect(0, 0,loadingBarWidth1, loadingBarHeight1).endFill();
		}
	}

	loadLabel = new createjs.Text("Chargement ...",tailletxtchargement+"px Verdana",couleurtxtchargement);
	loadLabel.lineWidth = loadingBarWidth1;
	loadLabel.textAlign = "center";
	loadLabel.x = loadingBarWidth1/2;
	loadLabel.y = - loadingBarHeight1 - tailletxtchargement/2 // posYchargement;
	if( !isMobile.any() || window.innerWidth == window.innerHeight)
	{
	lib.properties.height = lib.properties.width;

	}
		
}
}

function imgloaded(evt) {
	lib=comp.getLibrary();
	//Mise en place du fond d'écran de chargement + Texte de chargement
	back1 = preload.getResult("back");
	back1 = new createjs.Bitmap(back1);
	
	stage.addChild(back1);
	
	
	
	(function(isResp, respDim, isScale, scaleType) {			
		window.addEventListener('resize', resizeCanvas);		
		resizeCanvas(isResp, respDim, isScale, scaleType);		
	})(true,'both',true,1);	
	
	
	if(typechargement == 2)
	{
	stage.addChild(loadingBarContainer1);
	 //adding the loading bar and the frame to our container and placing it on the desired position on the canvas
    loadingBarContainer1.addChild(frame1, loadingBar1, loadLabel);
    loadingBarContainer1.x = posXchargement;
    loadingBarContainer1.y = posYchargement + 30;
	}	
	
	if(typechargement == 1)
	{
	stage.addChild(loadProgressLabel);
	}
	resized=1
	//resize();
	stage.update();

	loader.installPlugin(createjs.Sound);
loader.loadManifest(lib.properties.manifest);

}
function handleFileError(evt) {	
	console.log("Error!",evt.data.id );
	console.log("Error!",evt.data.src );
	console.log("Error!",evt.message);
	console.log("Error!",evt.title);
	loader.loadManifest([
     {id: evt.data.id, src:evt.data.src}]);
	/*console.log(evt.item.src);
	console.log(evt.item.id);
	console.log(errorcount);
	errorcount++
	loader.loadManifest([
     {id: evt.item.id, src:evt.item.src}
 ]);*/
}
function handleFileLoad(evt, comp) {	

	//console.log("Error!",evt.item );
	if (partcharged == 0){	var images=comp.getImages();} //pour partie 1
	if (partcharged == 1){	var images=comp2.getImages();} //pour partie 2
	
	if (evt && (evt.item.type == "image")) { images[evt.item.id] = evt.result; }	
		//Progression du Chargement du Turbomedia
	if(typechargement == 2)
	{
	loadingBar1.scaleX = evt.target.progress * loadingBarWidth1;	
	stage.update(loadingBar1);
	}
	if(typechargement == 1)
	{
	progresPrecentage = Math.round(evt.target.progress*100);
	loadProgressLabel.text = progresPrecentage + "%" ;
	stage.update(loadProgressLabel);
	}
if(Testbordure == 1){
	loadingBar1.scaleX = 0.5 * loadingBarWidth1;
	stage.update();
}
}

function handleComplete(evt,comp) {
	switch(partcharged) {
		        case 0: 
	//partcharged++;
	//loader.loadManifest(lib2.properties.manifest);
	ss=comp.getSpriteSheet();
	var queue = evt.target;
	var ssMetadata = lib.ssMetadata;
	for(i=0; i<ssMetadata.length; i++) {
		ss[ssMetadata[i].name] = new createjs.SpriteSheet( {"images": [queue.getResult(ssMetadata[i].name)], "frames": ssMetadata[i].frames} )
	}	
	
	//Reduce quality upscaling / downscaling in mobile (better perf)
	if( isMobile.any() )
	{
	ctx = canvas.getContext("2d");
	ctx.mozImageSmoothingEnabled = false;
	ctx.webkitImageSmoothingEnabled = false;
	ctx.msImageSmoothingEnabled = false;
	ctx.imageSmoothingEnabled = false;
	}
	
	//focus for keyboard interaction
	window.focus();
	
	if(Testbordure == 0){
	
	//remove loading screen
	if(typechargement == 2)
	{
	stage.removeChild(loadingBarContainer1);
	}
	if(typechargement == 1)
	{
	stage.removeChild(loadProgressLabel);
	}
	
	//adding turbomedia
	exportRoot = new lib.turbo();
	//stage = new lib.Stage(canvas);
	stage.addChild(exportRoot);	

	//Registers the "tick" event listener.
	fnStartAnimation = function() {
		console.log(lib.properties.fps);
		createjs.Ticker.setFPS = lib.properties.fps;
		createjs.Ticker.addEventListener("tick", stage);
		stage.addEventListener("tick", handleTick)
	function getProjectionMatrix(totalDepth) {
			var focalLength = 528.25;
			var projectionCenter = { x : lib.properties.width/2, y : lib.properties.height/2 };
			var scale = (totalDepth + focalLength)/focalLength;
			var scaleMat = new createjs.Matrix2D;
			scaleMat.a = 1/scale;
			scaleMat.d = 1/scale;
			var projMat = new createjs.Matrix2D;
			projMat.tx = -projectionCenter.x;
			projMat.ty = -projectionCenter.y;
			projMat = projMat.prependMatrix(scaleMat);
			projMat.tx += projectionCenter.x;
			projMat.ty += projectionCenter.y;
			return projMat;
		}
		function handleTick(event) {
			var focalLength = 528.25;
			var cameraInstance = exportRoot.___camera___instance;
		if(cameraInstance !== undefined && cameraInstance.pinToObject !== undefined)
		{
			cameraInstance.x = cameraInstance.pinToObject.x + cameraInstance.pinToObject.pinOffsetX;
			cameraInstance.y = cameraInstance.pinToObject.y + cameraInstance.pinToObject.pinOffsetY;
			if(cameraInstance.pinToObject.parent !== undefined && cameraInstance.pinToObject.parent.depth !== undefined)
				cameraInstance.depth = cameraInstance.pinToObject.parent.depth + cameraInstance.pinToObject.pinOffsetZ;
		}
			for(child in exportRoot.children)
			{
				var layerObj = exportRoot.children[child];
				if(layerObj == cameraInstance)
					continue;
					if(layerObj.currentFrame != layerObj.parent.currentFrame)
					{
						layerObj.gotoAndPlay(layerObj.parent.currentFrame);
					}
				var matToApply = new createjs.Matrix2D;
				var cameraMat = new createjs.Matrix2D;
				var totalDepth = layerObj.layerDepth ? layerObj.layerDepth : 0;
				var cameraDepth = 0;
				if(cameraInstance && !layerObj.isAttachedToCamera)
				{
					var stageCenter = { 'x' : lib.properties.width/2, 'y' : lib.properties.height/2 };
					var mat = cameraInstance.getMatrix();
					mat.tx -= stageCenter.x;
					mat.ty -= stageCenter.y;
					cameraMat = mat.invert();
					cameraMat.prependTransform(stageCenter.x, stageCenter.y, 1, 1, 0, 0, 0, 0, 0);
					cameraMat.appendTransform(-stageCenter.x, -stageCenter.y, 1, 1, 0, 0, 0, 0, 0);
					if(cameraInstance.depth)
						cameraDepth = cameraInstance.depth;
				}
				if(layerObj.depth)
				{
					totalDepth = layerObj.depth;
				}
				//Offset by camera depth
				totalDepth -= cameraDepth;
				if(totalDepth < -focalLength)
				{
					matToApply.a = 0;
					matToApply.d = 0;
				}
				else
				{
					if(layerObj.layerDepth)
					{
						var sizeLockedMat = getProjectionMatrix(layerObj.layerDepth);
						if(sizeLockedMat)
						{
							sizeLockedMat.invert();
							matToApply.prependMatrix(sizeLockedMat);
						}
					}
					matToApply.prependMatrix(cameraMat);
					var projMat = getProjectionMatrix(totalDepth);
					if(projMat)
					{
						matToApply.prependMatrix(projMat);
					}
				}
				layerObj.transformMatrix = matToApply;
			}
		}
	
	
	
	
	}
	
	//touch event or Desktop mouse control
	if (createjs.Touch.isSupported()){
	document.addEventListener('touchmove', function(event) {
	event.preventDefault();
	createjs.Touch.enable(stage);
	}, false); 
	}
	else {
	if( !isMobile.any() )
	{
	stage.enableMouseOver();
	}
	}
	resizeCanvas(true,'both',true,1);	
	AdobeAn.compositionLoaded(lib.properties.id);
	fnStartAnimation();
	//comp=comp2;
	}
	break;
	case 1:
	console.log("charged");
	//exportRoot2 = new lib2.turbo2();
	lib2=comp2.getLibrary();
	initecran2();
	
	break
	default:
	console.log(partcharged);
	break
	}
	
}

function playSound(id, loop) {
	return createjs.Sound.play(id, createjs.Sound.INTERRUPT_EARLY, 0, 0, loop);
}