window.addEventListener('load', init, false);
var canvas = null, ctx = null;
var lastPress = null;
var pause = true, gameover = true;
var fullscreen=false;
var dir = 0, score = 0;
var body = new Array();
var food = new Rectangle(80, 80, 10, 10);
//var wall=new Array();
var iFood = new Image();
var aEat = new Audio(), aDie = new Audio();

//iBody.src = 'image/body.png';
iFood.src = 'image/fruit.png';
aEat.src = 'image/im2.ogg';
aDie.src = 'image/end.ogg';


//wall.push(new Rectangle(100,50,10,10));
//wall.push(new Rectangle(100,100,10,10));
//wall.push(new Rectangle(200,50,10,10));
//wall.push(new Rectangle(200,100,10,10));
//CHANGE ECENARION
//game.style.transform = "perspective(700px) rotateX(-30deg) rotateY(-30deg)";
var KEY_ENTER = 13;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_F=70;

var pointers;

function random(max) {
    return Math.floor(Math.random() * max);
}

function init() {
  
  
    toggleFullscreen();
    backs2 = document.getElementById('backs3');
    backs3 = document.getElementById('backs3');
    backs4 = document.getElementById('backs4');
    backs5 = document.getElementById('backs5');

    next = document.getElementById('next');
    next2 = document.getElementById('next2');
 //  spause = document.getElementById('spause');
    menu = document.getElementById('menu');
    control = document.getElementById('control');
    objArrastrableRStartbtn = document.getElementById("objArrastrableRStartbtn");
    msg = document.getElementById('msg');


//    level1 = document.getElementById("level1");
//    level2 = document.getElementById("level2");
//    level3 = document.getElementById("level3");

    //btn start

    mgameover = document.getElementById("mgameover");
    Bntgameover = document.getElementById("Bntgameover");
    btnreset = document.getElementById("btnreset");
    Btndown = document.getElementById("Btndown");
    Btnup = document.getElementById("Btnup");
    Btnleft = document.getElementById("Btnleft");
    Btnright = document.getElementById("Btnright");
    //btn end

    PLAY = document.getElementById('PLAY');
    canvas = document.getElementById('game');
    ctx = canvas.getContext('2d');
    /*
    canvas.width= 1800;
    canvas.height= 1800;*/
    run();
    repaint();
    Bntgameover.addEventListener('touchstart', btnClickBntgameover.bind(), false);
        Bntgameover.addEventListener('click', btnClickBntgameover.bind(), false);
    document.addEventListener('touchstart', onDocumentTouchStart2.bind(), false);

    PLAY.addEventListener('touchstart', btnClickMenuBtn.bind(), false);
  PLAY.addEventListener('click', btnClickMenuBtn.bind(), false);
    btnreset.addEventListener('touchstart', btnClickreset.bind(), false);

    btnhome.addEventListener('touchstart', btnClickhome.bind(), false);
     btnhome.addEventListener('click', btnClickhome.bind(), false);

    objArrastrableRStartbtn.addEventListener("touchstart", btnClick.bind(), true);
 objArrastrableRStartbtn.addEventListener("click", btnClick.bind(), true);
  //  control.addEventListener('touchstart', btnClickMenuBtn.bind(), false);

    
   
    //lleel
//    level1.addEventListener("touchstart", btnClicklevel1.bind(), true);
//    level2.addEventListener("touchstart", btnClicklevel2.bind(), true);
//    level3.addEventListener("touchstart", btnClicklevel3.bind(), true);


    //btn 


    Btnup.addEventListener("touchstart", btnClickBtnup.bind(), true);
    Btnright.addEventListener("touchstart", btnClickBtnright.bind(), true);

    Btndown.addEventListener("touchstart", btnClickBtndown.bind(), true);
 
    Btnleft.addEventListener("touchstart", btnClickBtnleft.bind(), true);


//    document.addEventListener('touchmove', onDocumentTouchMove, false);
}


//38 up

//40 down

//37 left

//right 39



//btn  con html nativo
function btnClickBtnup(e) {
    e.preventDefault();

    if (dir != 2) {

        var touch = e.changedTouches[0];
        dir = 0; // arriba
        
        collide.src="";
       collide.src="image/out.ogg";
       collide.play();
    }
    else {
        //alert("paso up");
    }

}



function btnClickBtndown(e) {
    e.preventDefault();

   
    if (dir != 0){
    var touch = e.changedTouches[0];

    dir = 2; // abajo
    //spause.play();
       
        collide.src="";
       collide.src="image/out.ogg";
       collide.play();

    }
    else {
        //alert("paso down");
    }

   
}

function btnClickBtnleft(e) {
    e.preventDefault();

    if (dir != 1) {

        var touch = e.changedTouches[0];
        dir = 3; // izquierda
           
        collide.src="";
       collide.src="image/out.ogg";
       collide.play();
       
    }
    else {
        //alert("paso down");
    }

}

function btnClickBtnright(e) {
    e.preventDefault();

    if (dir != 3){
    
    var touch = e.changedTouches[0];
    dir = 1; // derecha
    // menu.style.left = "-480px";
    //objArrastrableRStartbtn.style.display = "block";
   // gameover = false;
      
        collide.src="";
       collide.src="image/out.ogg";
       collide.play();
 
  }
    else {
        //alert("paso down");
    }
}



function btnClickreset(e) {
   
    e.preventDefault();

   

        var touch = e.changedTouches[0];
       // dir = 1; // derecha
       
        gameover = true;
        if (gameover) {
            reset();
           backs5.pause();
        }
        menu.style.left = "-100%";
        objArrastrableRStartbtn.style.display = "block";
        game.style.backgroundColor = "transparent";
        pause = false;


    }
    
    function btnClickhome(e) {
   
    e.preventDefault();

   
window.location="../../index.html";

    }
   
    
  
    
    function btnClickBntgameover(e) {

        e.preventDefault();



        var touch = e.changedTouches[0];
        // dir = 1; // derecha

        gameover = true;
        if (gameover) {
            reset();
        }
        mgameover.style.left = "-100%";
        objArrastrableRStartbtn.style.display = "block";
        game.style.backgroundColor = "transparent";
        pause = false;

        backs5.pause();
       
    }
    

/*level start*/
// dir = 0;
//dir = 0;// arriba
//dir = 2; // abajo
// dir = 1;// derecha
// dir = 3;// izquierda
//btn  con html nativo
/*

function btnClicklevel1(e) {
    e.preventDefault();

    var touch = e.changedTouches[0];
    dir = 0; // arriba

    menu.style.left = "-480px";
    objArrastrableRStartbtn.style.display = "block";
    pause = false;
}

//btn  con html nativo
function btnClicklevel2(e) {
    e.preventDefault();

    var touch = e.changedTouches[0];
    dir = 1; // derecha
    menu.style.left = "-480px";
    objArrastrableRStartbtn.style.display = "block";
    pause = false;
}

//btn  con html nativo
function btnClicklevel3(e) {
    e.preventDefault();

    var touch = e.changedTouches[0];

    menu.style.left = "-480px";
    objArrastrableRStartbtn.style.display = "block";
    pause = false;
    dir = 3; // izquierda
}
*/
function btnClick(e) {
   

    menu.style.left = "20px";
    menu.style.display = "block";
    objArrastrableRStartbtn.style.display = "none";
    pause = true;



}

//btn  con html nativo
function btnClickMenuBtn(e) {
   
   
    menu.style.left = "-100%";
    objArrastrableRStartbtn.style.display = "block";

   // reset();
    pause = false;

    

}




function onDocumentTouchStart2(event) {
//debugger
    isUserInteracting = true;

    event.preventDefault();

    pointers = [];
    control.style.left = "20px";

    /*
   // dir = 0;
    //dir = 0;// arriba
   // dir = 2;// abajo
   // dir = 1;// derecha
   // dir = 3;// izquierda
    for (var i = 0; i < event.touches.length; i++) {

       // pointers.push([event.touches[i].pageX / QUALITY, event.touches[i].pageY / QUALITY]);

//                for (var i = body.length - 1; i > 0; i--) {
//                    body[i].x = body[i - 1].x;
//                    body[i].y = body[i - 1].y;

//                }


       // debugger
                if (event.touches[i].pageY >= body[0].y+10) {
          //  alert("culebra y:" + body[0].y + "touch y:" + event.touches[i].pageY);

                    body[0].y += 10;
                //    alert("abajo");
                  //  dir = 2; // abajo
                  //  break;
        }

                if (event.touches[i].pageX >= body[0].x + 10) {
            //  alert("culebra y:" + body[0].y + "touch y:" + event.touches[i].pageY);
            body[0].x += 10;
         //   alert("arriba");
           // dir = 0; // abajo
          //  break;
        }

        if (event.touches[i].pageY <= body[0].y + 10) {
            //  alert("culebra
            
            
            body[0].y -= 10;
//            alert("derecha");
//             dir = 1; // derecha
//            break;
        }

        if (event.touches[i].pageX <= body[0].x + 10) {
            //  alert("culebra y:" + body[0].y + "touch y:" + event.touches[i].pageY);
            body[0].x -= 10;
//            alert("izquierda");
//            dir = 3; // izquierda
//            break;
        }


    }*/

}

function run() {
    setTimeout(run, 50);
    act();
}

function repaint() {
    requestAnimationFrame(repaint);
    paint(ctx);
}

function toggleFullscreen(){
        fullscreen=!fullscreen;
        if(fullscreen){
            var w=window.innerWidth/canvas.width;
            var h=window.innerHeight/canvas.height;
            var scale=Math.min(h,w);
	    

            canvas.style.width=(canvas.width*scale)+'px';
            canvas.style.height=(canvas.height*scale)+'px';
            canvas.style.position='fixed';
            canvas.style.left='50%';
            canvas.style.top='50%';
            canvas.style.marginLeft=-(canvas.width*scale)/2+'px';
            canvas.style.marginTop=-(canvas.height*scale)/2+'px';
	    
	    
	  var game =  document.getElementById('game');
	   game.style.width=(canvas.width*scale)+'px';
            game.style.height=(canvas.height*scale)+'px';
            game.style.position='fixed';
            game.style.left='50%';
            game.style.top='50%';
            game.style.marginLeft=-(canvas.width*scale)/2+'px';
            game.style.marginTop=-(canvas.height*scale)/2+'px';
	    
	    
/*
            blackscreen.style.background='#000';
            blackscreen.style.position='fixed';
            blackscreen.style.left='0';
            blackscreen.style.top='0';
            blackscreen.style.width='100%';
            blackscreen.style.height='100%';*/
        }
        else{
            canvas.style.width='';
            canvas.style.height='';
            canvas.style.position='';
            canvas.style.marginTop='';
            canvas.style.marginLeft='';

    /*        blackscreen.style.position='';
            blackscreen.style.width='';
            blackscreen.style.height='';
  */
	  
	    
	}
    }

function reset() {
    score = 0;
    dir = 1;
    body.length = 0;
    body.push(new Rectangle(40, 40, 10, 10));
    body.push(new Rectangle(0, 0, 10, 10));
    body.push(new Rectangle(0, 0, 10, 10));
    food.x = random(canvas.width / 10 - 1) * 10;
    food.y = random(canvas.height / 10 - 1) * 10;
    gameover = false;
}

function act() {
    if (!pause) {
        themestart.pause();
        //spause.play();
        backs5.play();

        // GameOver Reset
        if (gameover) {
            reset();
            backs5.pause();
            
        }
        // Move Body
        for (var i = body.length - 1; i > 0; i--) {
            body[i].x = body[i - 1].x;
            body[i].y = body[i - 1].y;

        }
        // Change Direction
//        if (btnClickBtnup(e) == true && dir != 2) {
//            dir = 0;
//        }
//        if (btnClickBtnright(e) == true && dir != 3)
//            dir = 1;
//        if (btnClickBtndown(e) == true && dir != 0)
//            dir = 2;
//        if (btnClickBtnleft(e) == true && dir != 1)
//            dir = 3;

        msg.style.left = food.x + "px";
        msg.style.top = food.y + "px";


//        control.style.left = food.x + "px";
//        control.style.top = food.y + "px";

        if (score == 1) {
            next.play();

            lbmsg.innerHTML = "here!";


        }

        if (score == 9) {
            next.play();
          
            lbmsg.innerHTML = "1 more!";
      

        }

        if (score >=10) {
           // backs.pause();
            backs5.pause();
            backs4.play();
            lbmsg.innerHTML = "here!";
            game.style.backgroundColor = "rgba(20, 83, 33, 0.33)";
          
            
        }
        if (score == 10) {
            next.play();
        }
        if (score == 11) {
            next.play();
            //            msg.style.left = food.x+"px";
            //            msg.style.top = food.y + "px";
            lbmsg.innerHTML = "good!";
            //            next.seekable.start(1);  // Returns the starting time (in seconds)
            //            next.seekable.end();    // Returns the ending time (in seconds)
            //            next.currentTime = 5; // Seek to 122 seconds
            //            next.played.end();      // Returns the number of seconds the browser has played

        }

       

       
        if (score >= 20) {
            // backs.pause();
            backs4.pause();
            backs3.play();
            lbmsg.innerHTML = "here!";
            game.style.backgroundColor = "rgba(50, 206, 245, 0.329412)";

        }
        if (score == 21) {
            next.play();

            lbmsg.innerHTML = "great!";
           

        }

        if (score >= 30) {
            // backs.pause();
            backs4.pause();
            backs3.play();
            lbmsg.innerHTML = "here!";

            game.style.backgroundColor = "rgba(50, 245, 50, 0.329412)";

        }

        if (score == 30) {
            next.play();

        }
        if (score == 31) {
            next.play();

            lbmsg.innerHTML = "very good!";


        }
        if (score == 35) {
           

            lbmsg.innerHTML = "WOw!";


        }

        if (score >= 50 ) {
            // backs.pause();
            backs3.pause();
            backs2.play();
            lbmsg.innerHTML = "here!";
            game.style.backgroundColor = "transparent";
        }
        if (score == 50) {
            next2.play();

        }
        if (score == 51) {
            next.play();

            lbmsg.innerHTML = "awesome!";


        }
        
        if (score == 52) {
            // backs.pause();
            backs2.pause();
            backs3.play();
            lbmsg.innerHTML = "owo!";
        }

        if (score == 54) {
            next.play();

            lbmsg.innerHTML = "Danger!";


        }
        if (score >= 100) {
            // backs.pause();
            backs3.pause();
            backs2.play();
            lbmsg.innerHTML = "here!";
        }
        if (score == 101) {
            next.play();

            lbmsg.innerHTML = "fantastic!";


        }

        // Change Direction
        if (lastPress == KEY_UP && dir != 2) {
            dir = 0;
        }
        if (lastPress == KEY_RIGHT && dir != 3)
            dir = 1;
        if (lastPress == KEY_DOWN && dir != 0) {
            dir = 2;
        }
        if (lastPress == KEY_LEFT && dir != 1)
            dir = 3;

        // Move Head
        if (dir == 0)
            body[0].y -= 10;
        if (dir == 1)
            body[0].x += 10;
        if (dir == 2)
            body[0].y += 10;
        if (dir == 3)
            body[0].x -= 10;

        // Out Screen
        if (body[0].x > canvas.width - body[0].width)
            body[0].x = 0;
        if (body[0].y > canvas.height - body[0].height)
            body[0].y = 0;
        if (body[0].x < 0)
            body[0].x = canvas.width - body[0].width;
        if (body[0].y < 0)
            body[0].y = canvas.height - body[0].height;

        // Wall Intersects
//        for(var i=0,l=wall.length;i<l;i++){
//            if(food.intersects(wall[i])){
//                food.x=random(canvas.width/10-1)*10;
//                food.y=random(canvas.height/10-1)*10;
//            }
//          
//            if(body[0].intersects(wall[i])){
//                gameover=true;
//                pause=true;
//            }
//        }

        // Body Intersects
        for (var i = 2, l = body.length; i < l; i++) {
            if (body[0].intersects(body[i])) {
                gameover = true;
                pause = true;
                aDie.play();

                mgameover.style.left = "5px";
                mgameover.style.display = "block";
                objArrastrableRStartbtn.style.display = "none";

               // gameover.style.left = "10px";
                control.style.left = "-210px";

                lbmsg.innerHTML = "upss!";
              
                game.style.backgroundColor = "rgba(83, 20, 20, 0.329412)";

            }
        }

        // Food Intersects
        if (body[0].intersects(food)) {
            body.push(new Rectangle(food.x, food.y, 10, 10));
            score++;
            food.x = random(canvas.width / 10 - 1) * 10;
            food.y = random(canvas.height / 10 - 1) * 10;
            aEat.play();
        }
    }
    // Pause/Unpause
    if (lastPress == KEY_ENTER) {
        pause = !pause;
        lastPress = null;
    }
     // Toggle Fullscreen
        if(lastPress==KEY_F){ //F
            toggleFullscreen();
            lastPress=null;
        }
}

function paint(ctx) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = 'transparent';

    //ctx.fillStyle='#0f0';
    for (var i = 0, l = body.length; i < l; i++) {
        body[i].fill(ctx);
       //ctx.drawImage(iBody, body[i].x, body[i].y);
    }
    //ctx.fillStyle='#999';
    //for(var i=0,l=wall.length;i<l;i++){
    //    wall[i].fill(ctx);
    //}
    //ctx.fillStyle='#f00';
    //food.fill(ctx);
   ctx.drawImage(iFood, food.x, food.y);

    //ctx.fillStyle = '#fff';
    //ctx.fillText('Last Press: '+lastPress,0,20);
   ctx.fillText('Score: ' + score, 0, 10);
   txtscore.value = score;
    if (pause) {
        themestart.play();
        if (gameover) {
           
   ctx.textAlign = 'center';
            ctx.fillText('GAME OVER', 150, 75);

            backs5.pause();


        } else {
            ctx.fillText('PAUSE', 150, 75);
            menu.style.left = "10px";
            ctx.textAlign = 'left';

            //ctx.fillStyle = "cyan";

            ctx.save();
            ctx.fillStyle = "cyan";
            //ctx.translate(90, -60);
            ctx.rotate(Math.PI / 2);
            ctx.font = "bold 40px Arial";
            ctx.fillText("Good Player!", 250, 150); //
            ctx.restore();
          backs5.pause();
        }



    }
    else {
        menu.style.left = "-100%";
    }

    
    
    /*
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    /// ctx.fillStyle = 'rgba(255, 0, 0, 0.12)';
   
    //ctx.fillStyle='#0f0';
    for (var i = 0, l = body.length; i < l; i++) {
        //body[i].fill(ctx);
        ctx.drawImage(iBody, body[i].x, body[i].y);
    }
    //ctx.fillStyle='#999';
    //for(var i=0,l=wall.length;i<l;i++){
    //    wall[i].fill(ctx);
    //}
    //ctx.fillStyle='#f00';
    //food.fill(ctx);
    ctx.drawImage(iFood, food.x, food.y);

    //ctx.fillStyle = '#fff';
    //ctx.fillText('Last Press: '+lastPress,0,20);
    ctx.fillText('Score: ' + score, 0, 10);
    if (pause) {
        ctx.textAlign = 'center';
        if (gameover)
            ctx.fillText('GAME OVER', 150, 75);
        else
            ctx.fillText('PAUSE', 150, 75);
        ctx.textAlign = 'left';
    }
    */
}

document.addEventListener('keydown', function (evt) {
    lastPress = evt.keyCode;
}, false);

function Rectangle(x, y, width, height) {
    this.x = (x == null) ? 0 : x;
    this.y = (y == null) ? 0 : y;
    this.width = (width == null) ? 0 : width;
    this.height = (height == null) ? this.width : height;

    this.intersects = function (rect) {
        if (rect != null) {
            return (this.x < rect.x + rect.width &&
                this.x + this.width > rect.x &&
                this.y < rect.y + rect.height &&
                this.y + this.height > rect.y);
        }
    }

    this.fill = function (ctx) {
        if (ctx != null) {
          // ctx.fillRect(this.x, this.y, this.width, this.height);

            ctx.beginPath();
            ctx.strokeStyle = "cyan";
            ctx.lineWidth = 0.5;
            ctx.arc(this.x, this.y+25, 20, 0, 3, true);
            ctx.stroke();
            ctx.beginPath();
            ctx.strokeStyle = "cyan";
            ctx.lineWidth = 0.8;
            ctx.arc(this.x, this.y + 5, 5, 0, Math.PI * 2, true);
            ctx.stroke();
            ctx.beginPath();
            ctx.strokeStyle = "cyan";
            ctx.arc(this.x, this.y + 5, 5, 0, Math.PI * 2, true);
            ctx.stroke();
        }
    }
}

window.requestAnimationFrame = (function () {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function (callback) { window.setTimeout(callback, 17); };
})();

///display  touch





















