"use strict";
var Premium = Premium || {};

Premium.creative = {
	init: function() {
		/* START OF CUSTOM JS */

		var useSpriteSheet = true;

		if (useSpriteSheet){
			var preload = [];
			var spriteSheet1 = new Image();
			spriteSheet1.src = "assets/sprite_0-70.png";
			spriteSheet1.addEventListener("load", imageLoadedHandler);
			preload.push(spriteSheet1);
			var spriteSheet2 = new Image();
			spriteSheet2.src = "assets/sprite_71-117.png";
			spriteSheet2.addEventListener("load", imageLoadedHandler);
			preload.push(spriteSheet2)
			var toLoad = preload.length;

			var spriteplayerEl = document.querySelector("#sprite-player");
			var hasPlayed = false;

			var pseudoCss = {width:1};
	
			var config = {
				targetElement:"#sprite-player", 
				classPrefix:[{ index: "0", classPrefix: "sprite-1 Frames_" }, { index: "71", classPrefix: "sprite-2 Frames_" }],
				numFrames:118, 
				startIndex:0, 
				suffixDigits:3
			}

			var spritePlayer = new JPSpritePlayer(config);
	
			// spritePlayer.setLoop(true);

			spritePlayer.setYoyo(true)
	
			function imageLoadedHandler() {
				toLoad--;
				if (toLoad === 0) {
					spritePlayer.preRender(function() {
						spritePlayer.showFrame(10);
					});
				}
			}

			var resizeHandler = function(){
				var scale = spriteplayerEl.offsetParent.clientWidth/spriteplayerEl.clientWidth;
				gsap.set(spriteplayerEl, {scale:scale * pseudoCss.width});
			}

			var scrollHandler = function(){
				if (!hasPlayed && Premium.jpxApi.getPercVis() > 50){
					hasPlayed = true;
					spritePlayer.play(1);
				}
			}

			window.addEventListener("resize", resizeHandler);
			window.addEventListener("load", resizeHandler);
			Premium.product.scopeWindow.addEventListener("scroll", scrollHandler)
		} else { // use frames --------------------------------------------------------

			var config = {
				targetElement:"#sprite-player", 
				path:"assets/frames/42083.00", 
				numFrames:36, 
				startIndex:1, 
				suffixDigits:2, 
				indexIncrem:2, 
				fileExt:"png"
			}
			var spritePlayer = new JPSpritePlayer(config);

			spritePlayer.on("framechange", function(index){
				// console.log(spritePlayer.currentIndex);
				
			})

			// spritePlayer.setLoop(true);

			spritePlayer.play();

			spritePlayer.setYoyo(true)
		}


		/* END OF CUSTOM JS */
	}
}