var keydown = function(e)
{
}

var keyup = function(e)
{
}

var hit = function(e, elem)
{
    if(elem)
    {
        elem.animdata.killTime = -pigRayTime;
    }
    initPigRay(e.clientX, e.clientY, elem);
    if(e.stopPropagation) e.stopPropagation();
    if(e.preventDefault) e.preventDefault();
    return false;
}

var titleDiv = document.getElementById('title');
var textDiv = document.getElementById('text');
var bbsDiv = document.getElementById('bbs');
var gameDiv = document.getElementById('game');
var gargajrin = document.getElementById('gargajrin');
var gargPosX = 0;
var gargPosY = 0;

var toggleText = function()
{
    time = 0;
    textDiv.style.display = 'block';
    gameDiv.style.display = titleDiv.style.display = 'none';
}
var toggleTitle = function()
{
    titleDiv.style.display = 'block';
    textDiv.style.display = gameDiv.style.display = 'none';
    music.startMenuMusic();
}
var startGame = function()
{
    time = 0;
    gameDiv.style.display = 'block';
    textDiv.style.display = titleDiv.style.display = 'none';
    music.startGameMusic();
}

var time = 0, 
    userTimeout = 4,
    userPostInterval = 5;

var gloeps = 0,
    gloepScore = document.getElementById('gloepScore');

var users = [], 
userTemplate = document.getElementById('usertemplate'),
userSpeed = 50;

var thumb = document.getElementById('thumb');
thumb.animTime = 99;

var pigRays = [],
    pigRayIdx = 0,
    pigRayTime = 0.5,
    pigTemplate = document.getElementById('pigtemplate');
for(var pigRayIdx = 0; pigRayIdx < 9; pigRayIdx++)
{
    var pigRay = [];
    pigRays.push(pigRay);
    for(var pigCnt = 0; pigCnt < 15; pigCnt++)
    {
        var pig = pigTemplate.cloneNode(true);
        pig.rayTime = 99;
        pig.style.zIndex = 100-pigCnt;
        pigRay.push(pig);
        pigTemplate.parentNode.insertBefore(pig, pigTemplate.nextSibling);
    }
}

var initPigRay = function(tx, ty, user)
{
    var ox = gargPosX+470/1.5+16;
    var oy = gargPosY+60/1.5+16;
    var ux = 0;
    var uy = 0;
    if(user)
    {
        ux = user.animdata.dir.x * pigRayTime*userSpeed;
        uy = user.animdata.dir.y * pigRayTime*userSpeed;
    }
    var pigRay = pigRays[pigRayIdx++ % pigRays.length];
    for(var pigIdx = 0; pigIdx < pigRay.length; pigIdx++)
    {
        var pig = pigRay[pigIdx];
        var p = pigIdx/(pigRay.length-1);
        pig.rayTime = -pigRayTime * (p-1);
        pig.rayBoom = user && (pigIdx == pigRay.length-1);
        var x = (ox-20*Math.log2(  pigIdx))*(1-p)+tx*p+(p*p*p)*ux;
        var y = (oy-20*Math.log2(3*pigIdx))*(1-p)+ty*p+(p*p*p)*uy;
        pos(pig, x, y, (2-1.5*p)*Math.min(1,p*7));
    }
}

var updatePigRays = function(deltaTime)
{
    for(var pigRayIdx = 0; pigRayIdx < pigRays.length; pigRayIdx++)
    {
        var pigRay = pigRays[pigRayIdx];
        for(var pigIdx = 0; pigIdx < pigRay.length; pigIdx++)
        {
            var pig = pigRay[pigIdx];
            pig.rayTime += deltaTime;
            var o = 1-Math.pow(pig.rayTime*2-1, 2);
            if(o > 0)
            {
                pig.style.opacity = pig.rayBoom ? o : Math.sqrt(o)*0.7;
                pig.style.visibility = 'visible';
                if(pig.rayBoom)
                {
                    pig.style.transform = 'scale('+(0.8+pig.rayTime*10)+')rotate('+(0.5-pig.rayTime)*0.5+'rad)';
                }
            }
            else
            {
                pig.style.visibility = 'hidden';
            }
        }
    }
}

var initThumb = function(suxx)
{
    thumb.animTime = 0;
    thumb.getElementsByTagName('img')[0].src = suxx ? 'geloet/sucks.gif' : 'geloet/rulez.gif';
    gloeps += suxx ? -1 : 1;
    gloepScore.innerText = ''+gloeps;
}


var updateThumb = function(deltaTime)
{
    var t = thumb.animTime = thumb.animTime + deltaTime;
    if(t < 1)
    {
        thumb.style.visibility = 'visible';
        thumb.style.transform = 'scale('+t*30+')rotate('+(t-0.5)*0.5+'rad)';
        thumb.style.opacity = Math.pow(1-t,2);
    }
    else
    {
        thumb.style.visibility = 'hidden';
    }
}

var render = function(deltaTime)
{
    if(gameDiv.style.display == 'block')
    {
        for(var u = 0; u < users.length; u++) updateUser(u, deltaTime);
        if(userTimeout > userPostInterval)
        {
            userTimeout = 0;
            generateUser();
        }
        userTimeout += deltaTime;
        gargPosX = 800+300*Math.sin(time*0.3)+200*Math.sin(time*0.47);
        gargPosY = 830+50*Math.sin(time*1.1);
        pos(gargajrin,gargPosX,gargPosY);
        updateThumb(deltaTime);
        updatePigRays(deltaTime);
    }
    else if(textDiv.style.display == 'block')
    {
        writeText();
    }
}

var pos = function(element, x, y, s, r)
{
    element.style.top  = y;
    element.style.left = x;
    var trsf = 'scale(' + s + ')';
    if(r) trsf = 'rotate(' + r + 'deg)' + trsf;
    element.style['transform'] = trsf;
}

requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
     function(callback) {
       window.setTimeout(callback, 1000/60);
     };
})();

(function animloop(){
  requestAnimFrame(animloop);
  var deltaTime = 1/60;
  time += deltaTime;
  render(deltaTime);
})();

var generateUser = function()
{
    var r = Math.random(),
        i = Math.floor(r*userDB.length);
    var avatar = userDB[i].a,
        suxx = userDB[i].s;
    var d = Math.random()*Math.PI*2,
        speed = 0.5+Math.random();
    
    var newUser = userTemplate.cloneNode(true);
    newUser.id = generateUser.userCount = (generateUser.userCount || 0)+1;
    newUser.getElementsByTagName('img')[0].src = 'geloet/avatars/'+avatar;
    newUser.style.visibility = 'visible';
    var dir = { x:Math.sin(d)*speed, y:Math.cos(d)*speed };
    newUser.animdata = { dist:20, dir:dir, suxx:suxx };
    users.push(newUser);
    userTemplate.parentNode.insertBefore(newUser, userTemplate.nextSibling);
    
    userPostInterval = Math.max(0.5, userPostInterval*0.95);
}

var updateUser = function(userIndex, deltaTime)
{
    var user = users[userIndex];
    user.animdata.dist += deltaTime*userSpeed;
    var text = 'blahblah blab bluh blarb blob';
    var x = (bbsDiv.offsetWidth -user.offsetWidth )/2 + user.animdata.dir.x * user.animdata.dist;
    var y = (bbsDiv.offsetHeight-user.offsetHeight)/2 + user.animdata.dir.y * user.animdata.dist;
    var s = 0.1 + user.animdata.dist * 0.01;
    pos(user, x, y, 2*Math.min(1, s));
    if(s >= 0.7)
    {
        user.getElementsByTagName('span')[0].innerText = ' '+text.substr(0, Math.ceil(10*(s-0.7)));
    }

    var killed = false;
    if(user.animdata.killTime)
    {
        user.animdata.killTime += deltaTime;
        if(user.animdata.killTime >= 0)
        {
            killed = true;
            initThumb(user.animdata.suxx);
        }
    }

    if((x > bbsDiv.offsetWidth+user.offsetWidth*s*.5) ||
       (y > bbsDiv.offsetHeight+user.offsetHeight*s*.5) ||
       (x < -user.offsetWidth*s) || 
       (y < -user.offsetHeight*s) || killed)
    {
        user.parentNode.removeChild(user);
        users.splice(userIndex,1);
        if((!killed) && (user.animdata.suxx))
        {
            initThumb(true);
        }
    }
}

var writeText = function()
{
    var text = 'Once upon every 3 days pouët.net encountered infiltration attempts from CAPITALISTs. Central scene.org partycipants decided to engage their best man and send comrade Gargajrin as scenonautski into pouëtspace to defeat the trollistiky with his cochonista.';
    textDiv.innerText = text.substr(0, Math.floor(time*10));
    textDiv.style.opacity = 0.9+0.2*Math.sin(time*75)+0.1*Math.sin(time*197);
}


var userDB = [
{a:'4S_2.gif'},
{a:'aln_rzr.gif'},
{a:'amigafloppyanim.gif', s:true},
{a:'bass_.gif'},
{a:'BF02.gif'},
{a:'BITS-rolls5-20061117.gif', s:true},
{a:'brs.gif'},
{a:'Budda5.gif'},
{a:'cacobest.gif', s:true},
{a:'hardy2017.gif'},
{a:'hitchhikr.gif', s:true},
{a:'moondog-tscc_pouetlogo.gif', s:true},
{a:'mslug2.gif'},
{a:'onestanz.gif', s:true},
{a:'ps.gif'},
{a:'Scarab.gif', s:true},
{a:'sir.gif'},
{a:'small2.gif', s:true},
{a:'titancon2.gif'},
{a:'tomaes6.gif', s:true},
{a:'ulkugel.gif'},
{a:'up_icon_16x16.gif', s:true},
{a:'uristen_pofa.gif'},
{a:'zp01.gif'}
];