var startLanding = 0;
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this; 
    });
}


var $element = $('.eye-animation');
var imagePath = 'assets/images/sec/';
var totalFrames = 63;
var animationDuration = 2000;
var timePerFrame = animationDuration / totalFrames;
var timeWhenLastUpdate;
var timeFromLastUpdate;
var frameNumber = 1;
var direction = "up";

function step(startTime) {
  if (pClick == 2) {
      return;
  }
  // 'startTime' is provided by requestAnimationName function, and we can consider it as current time
  // first of all we calculate how much time has passed from the last time when frame was update
  if (!timeWhenLastUpdate) timeWhenLastUpdate = startTime;
  timeFromLastUpdate = startTime - timeWhenLastUpdate;
  
  // then we check if it is time to update the frame
  if (timeFromLastUpdate > timePerFrame) {
    // and update it accordingly
    var xf = "";
    if (frameNumber < 10) { xf = "00"+frameNumber; }
    else if (frameNumber < 100) { xf = "0"+frameNumber; }
    $element.attr('src', imagePath + `/Duendes_Alpha_v02_con_mb_${xf}.png`);
    // reset the last update time
    timeWhenLastUpdate = startTime;
    
    // then increase the frame number or reset it if it is the last frame
    if (frameNumber >= totalFrames && direction == "up") {
      frameNumber = totalFrames - 1;
      direction = "down";
    } 
    else if (frameNumber > 1 && direction == "down") {
        frameNumber = frameNumber - 1;
    }
    else if (frameNumber == 1 && direction == "down") {
      direction = "up";
    }
    else {
      frameNumber = frameNumber + 1;
    }        
  }
  requestAnimationFrame(step);
}

$(document).ready(function() {
	var loaded = 0;
	$(".comunicacion").css("z-index",1000000);
	$('img.postload').on('load', function() {
	   loaded++;
	   if(loaded == $('img.postload').length){
	      start();
	   }
	});
    for (var i = 1; i < totalFrames + 1; i++) {
        var xf = "";
        if (i < 10) { xf = "00"+i; }
        else if (i < 100) { xf = "0"+i; }
        $('body').append(`<div id="preload-image-${xf}" style="background-image: url('${imagePath}/Duendes_Alpha_v02_con_mb_${xf}.png');"></div>`);
    }
});


$(document).on("mouseover",".duende", function() {
	$(".duende").css("z-index", "");
	$(this).css("z-index", "100");
});
$(document).on("click",".btn-inicio", function(e) {
    e.preventDefault();
	$("#loading").addClass("no");
    $("#video").removeClass("fadeIn").addClass("fadeOut").removeClass("animated").addClass("animated");
    setTimeout(function() {
        $(".first_duende_left").addClass("bounceInLeft").addClass("animated").css("display","");
        $(".first_duende_right").addClass("bounceInRight").addClass("animated").css("display","");
        setTimeout(function() {
            $(".atrapalos").addClass("fadeInDown").addClass("animated").css("display","");
            setTimeout(function() {
                $(".dancing").css("display","");
                requestAnimationFrame(step);
            },1000);
            $("#video").remove();
        },1000);
    },1000);
});

setTimeout(function() {
 start();
},2000);
function start() { 
	if (startLanding == 0) {
		startLanding = 1;

		$(".container-fluid").addClass("show");
		setTimeout(function() {
			$("#loading>i").fadeOut();
			$("#loading").show(function() {
				//console.log('outload');
				$("#logos").addClass("fadeIn").addClass("animated").css("display","");
				$("#video").addClass("fadeIn").addClass("animated").css("display","");
				$("#pinos_fondo").addClass("fadeIn").addClass("animated").css("display","");
				$("#casa_fondo").addClass("fadeIn").addClass("animated").css("display","");
				$(".logoduende").addClass("fadeIn").addClass("animated").css("display","");
 
			});
		},500);
	}
}
 
var pClick = 0;
var tClick = 0;
$(document).on("click",".dancing", function(e) {
    e.preventDefault();
    var x = e.clientX;
    //console.log('frameNumber: ', frameNumber, 'x-pos: ', x);
    var pass = false;
    var w = $(document).width();
    if (x < (w/3) && frameNumber < 24) { pass = true; }
    else if (x > (w/3) && x < ((w/3)*2) && frameNumber > 24 && frameNumber < 45) { pass = true; }
    else if (x > ((w/3)*2) && frameNumber > 45) { pass = true; }

    if (pass) {
        if (tClick == 1 && pClick == 0) {
            $(".dancing").fadeOut("fast");
            $(".atrapalos").removeClass("animated").removeClass("fadeInDown").addClass("fadeOutUp").addClass("animated");
            setTimeout(function() {
                $(".msg").addClass("fadeIn").addClass("animated").css("display","");
                setTimeout(function() {
                    $(".first_duende_left").removeClass("animated").removeClass("bounceInLeft").addClass("bounceOutLeft").addClass("animated").css("display","");
                    $(".first_duende_right").removeClass("animated").removeClass("bounceInRight").addClass("bounceOutRight").addClass("animated").css("display","");
                },2000);
                setTimeout(function() {
                    $(".msg").css("z-index",0);
                    $(".zoom_to_me").addClass("ok");
                },3400);
            },1000);
            pClick = 2;
        }
        else if (pClick == 0) {
            pClick = 1;
            tClick++;
            $(".atrapalos").removeClass("animated").removeClass("fadeInDown").addClass("fadeOutUp").addClass("animated");
            setTimeout(function() {
                $(".atrapalos").find("h1").html("¡Atrápalos 2 veces!");
                $(".atrapalos").removeClass("animated").removeClass("fadeOutUp").addClass("fadeInDown").addClass("animated");
            }, 1000);
            setTimeout(function() { pClick = 0; }, 2400);
        }
    }
});

const Snow = (canvas, count, options) => {
    const ctx = canvas.getContext('2d')
    const snowflakes = []
    const add = item => snowflakes.push(item(canvas))
    const update = () => _.forEach(snowflakes, el => el.update())
    const resize = () => {
    ctx.canvas.width = canvas.offsetWidth
    ctx.canvas.height = canvas.offsetHeight
    _.forEach(snowflakes, el => el.resized())
    }
    const draw = () => {
    ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight)
    _.forEach(snowflakes, el => el.draw())
    }
    const events = () => {
    window.addEventListener('resize', resize)
    }
    const loop = () => {
    draw()
    update()
    animFrame(loop)
    }
    const init = () => {
    _.times(count, () => add(canvas => SnowItem(canvas, null, options)))
    events()
    loop()
    }
    init(count)
    resize()
    return { add, resize }
}
const defaultOptions = {
    color: 'orange',
    radius: [0.5, 3.0],
    speed: [1, 3],
    wind: [-0.5, 3.0]
}
const SnowItem = (canvas, drawFn = null, opts) => {
    const options = { ...defaultOptions, ...opts }
    const { radius, speed, wind, color } = options
    const params = {
    color,
    x: _.random(0, canvas.offsetWidth),
    y: _.random(-canvas.offsetHeight, 0),
    radius: _.random(...radius),
    speed: _.random(...speed),
    wind: _.random(...wind),
    isResized: false
    }
    const ctx = canvas.getContext('2d')
    const updateData = () => {
    params.x = _.random(0, canvas.offsetWidth)
    params.y = _.random(-canvas.offsetHeight, 0)
    }
    const resized = () => params.isResized = true
    const drawDefault = () => {
    ctx.beginPath()
    ctx.arc(params.x, params.y, params.radius, 0, 2 * Math.PI)
    ctx.fillStyle = params.color
    ctx.fill()
    ctx.closePath()
    }

    const draw = drawFn
    ? () => drawFn(ctx, params)
    : drawDefault
    const translate = () => {
    params.y += params.speed
    params.x += params.wind
    }

    const onDown = () => {
    if (params.y < canvas.offsetHeight) return
    if (params.isResized) {
        updateData()
        params.isResized = false
    } else {
        params.y = 0
        params.x = _.random(0, canvas.offsetWidth)
    }
    }
    const update = () => {
    translate()
    onDown()
    }
    return {
    update,
    resized,
    draw
    }
}

const el = document.querySelector('.landing-duendes')
const wrapper = document.querySelector('body')
const canvas = document.getElementById('snow')
const animFrame = window.requestAnimationFrame ||
                    window.mozRequestAnimationFrame ||
                    window.webkitRequestAnimationFrame ||
                    window.msRequestAnimationFrame
Snow(canvas, 150, { color: 'white' })