
var keys = [];  //main�gais kur glab�sies inform�cija par nospiestajiem klaviat�ras tausti�iem
var kameras_augstums = 0; //s�kum� kamera ir pa�� lej�

var old_player_pos = {}; //speletaja pozicija iepriekseja freima
var jump_sound;
var level_sound;
var coin_sound;
var goal_sound;
var enemy_death_sound;
var sword_draw;
var weapon_sound;
var player_speed = {x:0,y:0};
var animations = [];

var platformas = [];   //visas platformas
var player_speed = {x:0,y:0};
var game_over=0;
var have_weapon=0;
var weapon_used=0;
var jumped=0;
var jump_timer=0;
var switch_animation_frame=0;
var animation_timer=0;
var player_direction=1;
var is_running=0;
var goal_pos ={ x: 1000, y: -500 };
var score=0;
var level_score=0;
var at_ladder=0;
var on_ladder=0;
var startTime, endTime;
var stats ={time:'', score:'', deaths:''};

var server_url='http://127.0.0.1:6900/';

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var level_tmp = urlParams.get('level');
if(level_tmp)level = level_tmp;

function load_animation(name,count)
{
    var tmparr = [];
    for (let i = 0; i <= count; i++) {
        tmp = new Image();
        tmp.src= 'animations/'+name+'-'+i+'.png';
        tmparr.push(tmp);
    }
    animation = {current:0,max:count,list:tmparr};
    animations[name]=animation;
}

function initialize()
{
        startTime = new Date();

        score = localStorage.getItem("kmt_score");

        if(!level ) level=1;

        if(level==4) get_stats();

        if(level==1)level_data=level1_data;
        if(level==2)level_data=level2_data;
        if(level==3)level_data=level3_data;
        if(level==4)level_data=level4_data;
        if(level=='0')level_data=level0_data;

        //visa geometrija
        platformas=level_data.platformas;
        coins=level_data.coins;
        weapons=level_data.weapons;
        npcs=level_data.npcs;
        trepes=level_data.trepes;
        player_pos=level_data.player_pos;
        goal_pos=level_data.goal_pos;

        canvas.focus();
        bricks_image = new Image();
        fons_image = new Image();
        trepes_image = new Image();

        bricks_image.src = 'levels/bricks'+level+'.jpg';
        fons_image.src = 'levels/fons'+level+'.jpg';
        trepes_image.src = 'levels/trepes.png';


        //load_animation('standing',13);
        //load_animation('running',13);
        load_animation('standing',0);
        load_animation('running',2);
        load_animation('coin',64);
        load_animation('weapon',49);
        load_animation('enemy',0);
        load_animation('goal',0);

        coin_sound = document.getElementById("coin_sound");
        goal_sound = document.getElementById("goal_sound");
        enemy_death_sound = document.getElementById("enemy_death_sound");
        jump_sound = document.getElementById("jump_sound");
        weapon_sound = document.getElementById("weapon_sound");
        level_sound = document.getElementById("level_sound"+level);
        sword_draw = document.getElementById("sword_draw");
        jump_sound.volume = 0.2;
    //html5 media playeri
}

function main_loop()
{
        if(keys['Escape']==1)
        {
            localStorage.setItem("kmt_score", score-level_score);
            window.location.href = 'start.html';
        }

        if(level==4)
        {
            jump_speed = 0;
            max_speed = 0;
            jump_sound = level_sound;
            animation_timer=0;
        }

        animation_timer++;
        if(switch_animation_frame == 1)switch_animation_frame=0;
        if(animation_timer == 3)
            //ik pec 3 frames zimejam nakamo animacijas kadru visiem animetajiem objektiem
        {
            animation_timer=0;
            switch_animation_frame=1;
        }
        //visu notiram
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        //un zimejam nakoso kadru
        kontrolet_kameru();
        zimet_ieroci();
        zimet_pretiniekus();
        zimet_naudinas();
        zimet_goal();
        zimet_trepes();
        zimet_speletaju();
        zimet_platformas();
        //seciba ir svariga

        if(level==4)
        {
            zimet_final();

        }else
        {
            zimet_informaciju();
        }
        //visu atkartojam ik pec 10 milisekundem
        setTimeout(main_loop, 10);
}

function zimet_final()
{
            ctx.font = '40px Sans-serif';
            ctx.strokeStyle = 'black';
            ctx.lineWidth = 2;
            text= "Score: "+score;
            x=400;
            y=150;
            ctx.strokeText(text, x, y);
            ctx.fillStyle = 'white';
            ctx.fillText(text, x, y);

            var time_today=localStorage.getItem("kmt_time");
            text= "Time played: "+time_today;
            x=400;
            y=190;
            ctx.strokeText(text, x, y);
            ctx.fillStyle = 'white';
            ctx.fillText(text, x, y);

            text= "Deaths: ";
            x=400;
            y=230;

            text= "Total time played: "+stats.time;
            x=400;
            y=270;
            ctx.strokeText(text, x, y);
            ctx.fillStyle = 'white';
            ctx.fillText(text, x, y);

            text= "Total points earned: "+stats.score;
            x=400;
            y=310;
            ctx.strokeText(text, x, y);
            ctx.fillStyle = 'white';
            ctx.fillText(text, x, y);

            text= "Total deaths: "+stats.deaths;
            x=400;
            y=350;
            ctx.strokeText(text, x, y);
            ctx.fillStyle = 'white';
            ctx.fillText(text, x, y);

}

function zimet_informaciju()
{
    ctx.font = '40px Sans-serif';
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 2;
    text= "Score: "+score;
    x=10;
    y=50;
    ctx.strokeText(text, x, y);
    ctx.fillStyle = 'white';
    ctx.fillText(text, x, y);
}

function kontrolet_kameru()
{
        if(player_pos.y<ekrana_augstums/2)
        {
                kameras_augstums=0;

        }else
        {
                kameras_augstums=player_pos.y-ekrana_augstums/2 ;
        }
        var attela_augstums=1500;

        y=ekrana_augstums-attela_augstums+kameras_augstums/4;
        //fons parvietojas 4x leenaak
        ctx.drawImage(fons_image, 0, y);
}

function zimet_platformas()
{
        platformas.forEach((platforma) =>
        {
            if(platforma.type==1 || platforma.type==2)
            {
                ctx.beginPath();
                var x=platforma.x;
                var y=platforma.y-kameras_augstums;
                var platums=platforma.w;
                var augstums=platforma.h;

                //t� k� y ass html canvas ir otr�di (y=0 aug��), tad apgrie�am y koordin�ti otr�di �emot v�r� ekr�na augstumu
                y=ekrana_augstums-y;
                augstums=-augstums;
                //z�m�jam taisnst�ri

                ctx.drawImage(bricks_image, 0, 0, platums, -augstums, x, y+augstums, platums, -augstums);
            }

        });
}

function zimet_ieroci()
{

    if(switch_animation_frame==1)animations['weapon'].current+=1;
    if(animations['weapon'].current > animations['weapon'].max) animations['weapon'].current=0;

        weapons.forEach((weapon)=>
        {
            if(weapon.y > 0)  //ja tas jau nav panemts
            {
                var weapon_width=16;
                var weapon_height=40;
                var platums=weapon_width;
                var augstums=-weapon_height;

                var x=weapon.x;
                var y=weapon.y;

                if(Math.abs(x-player_pos.x)<(player_width/2+weapon_width/2) )
                {
                    if(Math.abs((y+weapon_height/2)-(player_pos.y+player_height/2))<player_height/2)
                    {

                        //var tmp = coin_sound.cloneNode(true);
                        //tmp.volume = 0.2;
                        sword_draw.play();
                        have_weapon=1;
                        weapon.y=-1;   //noliekam arpus ekrana
                    }
                }


                x-=weapon_width/2;
                //y= ekrana_augstums-y;
                y=y-kameras_augstums;
                y=ekrana_augstums-y;
                ctx.fillStyle = "green";
                ctx.rect(x,y,platums, augstums);
                //ctx.fillRect(x, y, platums, augstums);

                //ctx.drawImage(myGif.image,x,y);

                var img = animations['weapon'].list[animations['weapon'].current];

                ctx.drawImage(img, x, y, platums, augstums);

            }
        })
}

function zimet_goal()
{
    if(switch_animation_frame==1)animations['goal'].current+=1;
    if(animations['goal'].current > animations['goal'].max) animations['goal'].current=0;

    var goal_width=140;
    var goal_height=140;
    var platums=goal_width;
    var augstums=-goal_height;

    var x=goal_pos.x;
    var y=goal_pos.y;

    if(Math.abs(x-player_pos.x)<(player_width/2) && game_over==0)
    {
        if(goal_pos.y < player_pos.y && goal_pos.y + goal_height > player_pos.y+player_height)
        {
            save_score();
            var tmp = goal_sound.cloneNode(true);
            tmp.play();
            level_sound.pause();
            level_sound='';

            endTime = new Date();
            var timeDiff = endTime - startTime; //in ms
            timeDiff /= 1000;
            var seconds = Math.round(timeDiff);
            save_time_played(seconds);
            level++;

            level_score = 0;
            localStorage.setItem("kmt_level", level);
            localStorage.setItem("kmt_score", score);

            var time_today=parseInt(localStorage.getItem("kmt_time"))+seconds;
            localStorage.setItem("kmt_time", time_today);
            player_speed = {x:0,y:0};
            //have_weapon=0;
            //ja velas atnemt weapon sakot lvl, atkomentet^^
            initialize();

        }
    }

    x-=goal_width/2;
    y=y-kameras_augstums;
    y=ekrana_augstums-y;
    var img = animations['goal'].list[animations['goal'].current];
    ctx.drawImage(img, x, y, platums, augstums);
}

function zimet_trepes()
{
    trepes.forEach((trepe)=>
    {
        var trepes_width=40;
        var x=trepe.x;
        var y=trepe.y;

        at_ladder=0;

        //lai pieliptu trepei speletajam nedrikst but liels atrums
        if(Math.abs(player_speed.y)<8 && Math.abs(player_speed.x)<2)
        {
            if(trepe.y<=player_pos.y && trepe.y+trepe.h>=player_pos.y+player_height/2)
            {
                if(Math.abs(trepe.x-player_pos.x)<20)
                {
                    at_ladder = trepe.x;
                }
            }
        }

        y=y-kameras_augstums;
        y=ekrana_augstums-y;

        var augstums=trepe.h;
        //ctx.fillRect(x-trepes_width/2, y, trepes_width, -augstums);
        var img = trepes_image;

        ctx.save();
        ctx.translate(x+20, y);

        const pattern = ctx.createPattern(img, "repeat");
        ctx.fillStyle = pattern;
        ctx.fillRect(x-trepes_width/2-x-20, 0, trepes_width, -augstums);
        ctx.restore();


    }
    );

    if(at_ladder==0) on_ladder=0;
}

function zimet_naudinas()
{

                if(switch_animation_frame==1)animations['coin'].current+=1;
                if(animations['coin'].current > animations['coin'].max) animations['coin'].current=0;

        coins.forEach((coin)=>
        {
            if(coin.y > 0)
            {
                var coin_width=40;
                var coin_height=40;
                var platums=coin_width;
                var augstums=-coin_height;

                var x=coin.x;
                var y=coin.y;

                if(Math.abs(x-player_pos.x)<(player_width/2+coin_width/2) )
                {
                    if(Math.abs((y+coin_height/2)-(player_pos.y+player_height/2))<player_height/2)
                    {
                        //alert('Game over!');

                        var tmp = coin_sound.cloneNode(true);
                        //tmp.volume = 0.2;
                        tmp.play();
                        score++;
                        level_score++;
                        coin.y=-100;
                    }
                }


                x-=coin_width/2;
                //y= ekrana_augstums-y;
                y=y-kameras_augstums;
                y=ekrana_augstums-y;
              

                var img = animations['coin'].list[animations['coin'].current];

                ctx.drawImage(img, x, y, platums, augstums);
                //ctx.drawImage(myGif.image,x,y);

            }
        })
}

function zimet_pretiniekus()
{
    if(switch_animation_frame==1)animations['enemy'].current+=1;
    if(animations['enemy'].current > animations['enemy'].max) animations['enemy'].current=0;
        npcs.forEach((npc) =>
        {
                var platums=enemy_width;
                var augstums=-enemy_height;

                var x=npc.x;
                var y=npc.y;

                if (typeof npc.alive === 'undefined') npc.alive=1;

                //virziens
                if(npc.alive)
                {
                    if(npc.direction==1)
                    {
                        npc.x+=enemy_speed;
                        if(npc.x > npc.max_x-enemy_width/2)npc.direction=2;
                    }
                    if(npc.direction==2)
                    {
                        npc.x-=enemy_speed;
                        if(npc.x < npc.min_x+enemy_width/2)npc.direction=1;
                    }
                }


                //ctx.rect(x,y,platums, augstums);
                //ctx.fillRect(x, y, platums, augstums);

                if(npc.alive)
                {
                    if(Math.abs(x-player_pos.x)<(player_width/2+enemy_width/2) && game_over==0)
                    {
                        if(npc.y < player_pos.y+player_height && npc.y + enemy_height > player_pos.y)
                        {
                            save_death();
                            player_dies();
                        }
                    }
                }

                x-=enemy_width/2;
                //y= ekrana_augstums-y;
                y=y-kameras_augstums;
                y=ekrana_augstums-y;

                ctx.rect(x,y,platums, augstums);
                ctx.fillStyle = "red";
                //ctx.fillRect(x, y, platums, augstums);

                var img = animations['enemy'].list[animations['enemy'].current];

                if(!npc.alive) img = animations['enemy'].list[0];

                //ctx.drawImage(img, x, y, platums, augstums);
                
                    ctx.drawImage(img, x, y+augstums, platums, -augstums);
                
                

                //ctx.fillStyle = "yellow";
                //ctx.rect(x,y,platums, augstums);
                //ctx.fillRect(x, y, platums, augstums);


        }
        );
}

function player_dies()
{
    game_over=1;
    level_sound.pause();
    death_sound.play();
    player_speed.y=4;

    score = score - level_score;
    level_score = 0;

    endTime = new Date();
    var timeDiff = endTime - startTime; //in ms
    timeDiff /= 1000;
    var seconds = Math.round(timeDiff);
    save_time_played(seconds);

    var time_today=parseInt(localStorage.getItem("kmt_time"))+seconds;
    localStorage.setItem("kmt_time", time_today);


    setTimeout( function() {window.location.href = 'start.html';}  , 3000);
}

function zimet_speletaju()
{
        //horizontalais atrums un pozicija
        if(player_speed.y==0 || difficulty_level==1)  //hard mode will not allow this
        {
                if(keys['ArrowLeft']==1)
                {
                    player_speed.x -= acceleration;
                    player_direction=1;
                    is_running=1;
                }
                if(keys['ArrowRight']==1)
                {
                    player_speed.x += acceleration;
                    player_direction=2;
                    is_running=1
                }
                if(keys['ArrowLeft']!=1 && keys['ArrowRight']!=1)
                {   //bremzejam
                    is_running=0;
                    if(player_speed.x > 0) player_speed.x -= deceleration;
                    //pie neliela �truma apst�jamies pavisam
                    if(Math.abs(player_speed.x)<(deceleration/2)) player_speed.x=0;
                    if(player_speed.x < 0) player_speed.x += deceleration;
                    //pie neliela �truma apst�jamies pavisam
                    if(Math.abs(player_speed.x)<(deceleration/2)) player_speed.x=0;
                }
                //ierobezojam max speed
                if(player_speed.x >  max_speed) player_speed.x =  max_speed;
                if(player_speed.x < -max_speed) player_speed.x = -max_speed;
        }
        if(player_speed.y !=0) is_running=0;
        old_player_pos.x=player_pos.x;
        player_pos.x += player_speed.x;

        if(keys[' ']==1 && weapon_used==0 && have_weapon==1 && game_over==0)
        {
            var tmp = weapon_sound.cloneNode(true);
            tmp.play();
            weapon_used=1;
            var weapon_position= player_pos.y;

            y=ekrana_augstums-weapon_position+kameras_augstums;
            if(player_direction==2)
            {
                //ctx.rect(player_pos.x,y,1000, 1);
                ctx.fillStyle = "white";
                ctx.fillRect(player_pos.x,y,weapon_hit_distance, -player_height);
            }
            if(player_direction==1)
            {
                //ctx.rect(0,y,player_pos.x, 1);
                //ctx.fillStyle = "white";
                //ctx.fillRect(0,y,player_pos.x, 1);
                ctx.fillStyle = "white";
                ctx.fillRect(player_pos.x-weapon_hit_distance,y,weapon_hit_distance, -player_height);
            }
            npcs.forEach((npc) =>
            {
                var augstums=-enemy_height;
                //if(weapon_position > y && weapon_position< y+enemy_height)
                if((npc.y + enemy_height >= player_pos.y) && (npc.y <= player_pos.y + player_height))
                {
                    if(Math.abs(player_pos.x - npc.x)< weapon_hit_distance + enemy_width/2) //tuvums
                    {
                        //virziens
                        if((player_direction==1 && npc.x < player_pos.x) ||(player_direction==2 && npc.x > player_pos.x))
                        {
                            npc.alive=0;
                            var new_coin= { x: npc.x, y: npc.y };
                            coins.push(new_coin);
                            npc.y = -100;  //aizvacam prom beigto

                            var tmp = enemy_death_sound.cloneNode(true);
                            //tmp.volume = 0.2;
                            tmp.play();

                        }
                    }
                }
            }
            );

        }
        if(weapon_used==1 && keys[' ']==0)
        {
            weapon_used=0;
        }

        if(jumped==1 && keys['ArrowUp']==1)
        {
            jump_timer++;
        }
        //vertikalais atrums un pozicija
        if(keys['ArrowUp']==1 && player_speed.y==0 && jumped==0 && at_ladder==0)
        {   //l�ciens
            //jump_sound.play();
            jumped=1;
            jump_timer++;
            var tmp = jump_sound.cloneNode(true);
            tmp.volume = 0.2;
            tmp.play();
            player_speed.y = jump_speed;
        }
        if(jumped==1 && keys['ArrowUp']==0)
        {
            //ja tas ir mazais l�ciens (poga bija nospiesta maz�k k� 8 kadrus), tad samazinam vertik�lo �trumu uz pusi
            if(jump_timer < 8) player_speed.y = player_speed.y/2;
            jump_timer=0;
            jumped=0;
        }

        if(on_ladder == 1 ) player_speed.y=0;
        if(keys['ArrowUp']==1 && at_ladder!=0)
        {
            on_ladder=1;
            player_speed.y=1;
            player_speed.x=0;
            player_pos.x=at_ladder;
        }
        if(keys['ArrowDown']==1 && at_ladder!=0)
        {
            on_ladder=1;
            player_speed.y=-1;
            player_speed.x=0;
            player_pos.x=at_ladder;
        }

        if(on_ladder ==0 )
        {
            player_speed.y -= gravity;
        }
        if(player_speed.y < -max_vspeed) player_speed.y = -max_vspeed;
        old_player_pos.y=player_pos.y;
        player_pos.y += player_speed.y;

        if(player_pos.y < -200 && game_over!=1)
        {
            player_dies();
        }

        find_colisions();

        //player drawing box
        var x=player_pos.x-player_width/2;
        var y=player_pos.y-kameras_augstums;
        var platums = player_width;
        var augstums = player_height;

        //t� k� y ass html canvas ir otr�di (y=0 aug��), tad apgrie�am y koordin�ti otr�di �emot v�r� ekr�na augstumu
        y=ekrana_augstums-y;
        augstums=-augstums;
        //ctx.fillRect(x, y, platums, augstums);

        if(is_running)
        {
            if(switch_animation_frame==1)animations['running'].current+=1;
            if(animations['running'].current > animations['running'].max) animations['running'].current=0;
            var img = animations['running'].list[animations['running'].current];
        }else
        {
            if(switch_animation_frame==1)animations['standing'].current+=1;
            if(animations['standing'].current > animations['standing'].max) animations['standing'].current=0;
            var img = animations['standing'].list[animations['standing'].current];
        }
        //ctx.drawImage(img, 0, 0, 1127, 1175, x-0.85*platums, y+augstums+0.51*augstums, platums*2.5, -augstums*1.65);

        ctx.save();
        if(player_direction==1)
        {
            ctx.scale(-1, 1);
            ctx.drawImage(img, (x+platums)*(-1), y+augstums, platums, -augstums);
        }else
        {
            ctx.scale(1, 1);
            ctx.drawImage(img, x, y+augstums, platums, -augstums);
        }
        ctx.restore();
        // lai sprite apgrieztos spogulattela
}

function find_colisions()
{
        //ekrana laba un kreisa mala
        if(player_pos.x < player_width/2) //kreis� mala
        {
                player_pos.x = player_width/2;
                player_speed.x=0;
        }
        if(player_pos.x > ekrana_platums-player_width/2) //lab� mala
        {
                player_pos.x = ekrana_platums-player_width/2;
                player_speed.x=0;
        }

        //platformas
        if(game_over==0)
        platformas.forEach((platforma) =>
        {
                if(platforma.type==1 || platforma.type==3)
                {
                        //no augsas
                        var x1=platforma.x-player_width/2;
                        var x2=platforma.x + platforma.w + player_width/2;
                        var y= platforma.y + platforma.h;
                        if(player_pos.y<y && (old_player_pos.y)>=y)
                        {
                                if(player_pos.x>x1 && player_pos.x<x2 )
                                {
                                        player_pos.y=y;
                                        player_speed.y=0;
                                }
                        }
                        //no lejas
                        var x1=platforma.x-player_width/2;
                        var x2=platforma.x + platforma.w + player_width/2;
                        var y= platforma.y-player_height;
                        if(player_pos.y>y && old_player_pos.y<=y)
                        {
                                if(player_pos.x>x1 && player_pos.x<x2 )
                                {
                                        player_pos.y=y;
                                        player_speed.y=0-gravity;
                                }
                        }
                        //no kreisas
                        var x=platforma.x-player_width/2;
                        var y1=platforma.y-player_height;
                        var y2= platforma.y + platforma.h;
                        if(player_pos.x>x && old_player_pos.x<=x)
                        {
                                if((player_pos.y>y1 && player_pos.y<y2) )
                                {
                                        player_pos.x=x;
                                        player_speed.x=0;
                                }
                        }
                        //no labas
                        var x=platforma.x + platforma.w + player_width/2;
                        var y1=platforma.y-player_height;
                        var y2= platforma.y + platforma.h;
                        if(player_pos.x<x && old_player_pos.x>=x)
                        {
                                if((player_pos.y>y1 && player_pos.y<y2) )
                                {
                                        player_pos.x=x;
                                        player_speed.x=0;
                                }
                        }
                }
        });

}



function logout()
{
    window.location.href = 'index.html';
    localStorage.removeItem("kmt_user_id");
}

function register(username,password)
{
    const xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
                console.log(this.responseText);
                atbilde = JSON.parse(this.responseText);
                console.log(atbilde);
                if(atbilde.insertId)
                {
                    localStorage.setItem("kmt_user_id", atbilde.insertId);
                    localStorage.setItem("kmt_level", 1);
                    window.location.href = 'start.html';
                }

        }

    xhttp.open("GET", server_url+"register?username="+username+"&password="+password, true);
    xhttp.send();
}

//saglab�sim datub�z� nomir�anas notikumu
function save_death()
{
    const xhttp = new XMLHttpRequest();
    xhttp.open("GET", server_url+"update_deaths?user="+user_id+"&level="+level+'&deaths=1', true);
    xhttp.send();
}

//saglab�sim datub�z� nomir�anas notikumu
function save_score()
{
    const xhttp = new XMLHttpRequest();
    xhttp.open("GET", server_url+"update_score?user="+user_id+"&level="+level+'&score='+level_score, true);
    xhttp.send();
}

//saglab�sim datub�z� sp�l��anas ilgumu
function save_time_played(time)
{
    const xhttp = new XMLHttpRequest();
    xhttp.open("GET", server_url+"update_time_played?user="+user_id+"&level="+level+'&time='+time, true);
    xhttp.send();
}

function get_stats()
{
    const xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
                console.log(this.responseText);
                atbilde = JSON.parse(this.responseText);
                //console.log(atbilde);
                stats= atbilde;
        }

    xhttp.open("GET", server_url+"get_data?user="+user_id, true);
    xhttp.send();
}

function save_game()
{
    var save = {};
    save.level=localStorage.getItem("kmt_level");
    save.score = localStorage.getItem("kmt_score");  ;
    var save_string = JSON.stringify(save);
    localStorage.setItem("kmt_save", save_string);
}

function load_game()
{
    save_string = localStorage.getItem("kmt_save");
    save = JSON.parse(save_string);
    level = save.level;
    score = save.score;
    localStorage.setItem("kmt_score", score);
    localStorage.setItem("kmt_level", level);
    window.location.href = 'play.html';
}

function login()
{
    var username = document.getElementById('username').value
    var password = document.getElementById('password').value
    const xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
                atbilde = JSON.parse(this.responseText);

                if(atbilde[0])
                {
                    localStorage.setItem("kmt_user_id", atbilde[0].id);
                    localStorage.setItem("kmt_level", 1);
                    score = 0;
                    localStorage.setItem("kmt_score", score);
                    localStorage.setItem("kmt_time", 0);
                    window.location.href = 'start.html';
                } else
                {
                    var answer = confirm("Do you want to register with this username?");
                    if(answer)
                    {
                        register(username,password);
                    }
                }

        }

    xhttp.onerror = function() {
        alert ('xmlHTTP Error'+'. maybe server offline.', xhttp.responseText);
    }

    xhttp.open("GET", server_url+"login?username="+username+"&password="+password, true);
    xhttp.send();
}

function start_game()
{
    window.location.href = 'play.html';
}


