// mog
/*jslint devel: true, browser: true */
var Greetings = (function () {
    "use strict";
    var _duration = 0,
        _holder,
        _ctx,
        _sctx,
        _picBundle,
        _toBeGreeted = ['#modarchive', '#modulez', 'alcatraz', 'brainstorm', 'dacapo', 'dem las sein blob,und las', 'des!re', 'extrait', 'guideline', 'haujobb',
            'inque', 'kakiarts', 'limp ninja', 'moodsplateau', 'nuance', 'outbreak', '0utracks', 'peisik', 'rbbs',
            'ske', 'titan', 'team 3v0ke', 'trbl kids that stayed at home', 'anybody not in this array', 'hi mum!', ''],
        _scrollStartText = "                         oh hey! music by alpha-c,code and gfx by mog. Let\'s greet,some of the 74088,3ln fellas. ",
        LETTER_WIDTH = 64,
        LETTER_HEIGHT = 64,
        _mayRender = false,
        _images,
        _3lnPPL;

    function build(message) {

        var charcode, i, x, y,
            msg = (message.toUpperCase()).split(''),
            res = [];

        for (i = 0; i < msg.length; i++) {

            charcode = msg[i].charCodeAt(0);

            if (charcode >= 65) {
                x = charcode - 65;
            }
            else {

                if (charcode >= 48 && charcode <= 57) {
                    x = charcode - 48 - 1;
                }

                switch (charcode) {

                    case 48: //0
                        x = 9;
                        break;

                    case 39:
                        x = 10;
                        break;

                    case 34:
                        x = 11;
                        break;

                    case 33:
                        x = 12;
                        break;

                    case 63:
                        x = 13;
                        break;

                    case 46:
                        x = 14;
                        break;

                    case 44:
                        x = 15;
                        break;

                    case 45:
                        x = 16;
                        break;

                    case 35:
                        x = 17;
                        break;

                    case 32:
                        x = 18;
                        break;
                }
            }

            //numbers and special chars on second line
            y = (charcode >= 65) ? 0 : 1;

            res.push({"x":x, "y":y});
        }

        return res;
    }

    function renderText(text, startX, startY) {

        var msg = build(text);

        for (var i = 0; i <= msg.length; i++) {

            if(msg[i] != undefined){
                _ctx.drawImage(_images['font'], msg[i].x * LETTER_WIDTH, msg[i].y *
                    LETTER_HEIGHT, LETTER_WIDTH, LETTER_HEIGHT, startX, startY, LETTER_WIDTH, LETTER_HEIGHT);
            }

            var kerning = LETTER_WIDTH;

            if (isSpace(msg[i])) {
                kerning /= 2;
            }

            startX += kerning - 4;
        }
    }

    function isSpace(letter) {

        if(letter)
            return (letter.x == 18 && letter.y == 1);
        else
            return false;
    }

    function init(duration) {

        _duration = duration;

        _toBeGreeted.reverse();

        _3lnPPL = get3lnPPL();
        //console.log(_3lnPPL.length);
        _3lnPPL = (_3lnPPL).splice(0, 30);
        _3lnPPL = build(_scrollStartText + (_3lnPPL.join(',')) +'.');


        _holder = document.createElement('div');
        document.getElementById('root').appendChild(_holder);

        _picBundle = document.createElement('div');
        _picBundle.setAttribute('id', "picBundle");
        _picBundle.innerHTML = '<div id="picBundle"><div class="zoomPic" id="pic1"></div><div class="zoomPic" id="pic2"></div></div>​';
        _holder.appendChild(_picBundle);

        var canvas = document.createElement('canvas');
        _ctx = canvas.getContext('2d');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        canvas.style.cssText = 'position:absolute;left:0;top:0;';
        _holder.appendChild(canvas);

        var canvasScroller = document.createElement('canvas');
        _sctx = canvasScroller.getContext('2d');
        canvasScroller.width = window.innerWidth;
        canvasScroller.height = window.innerHeight;
        canvasScroller.style.cssText = 'position:absolute;left:0;top:0;z-index:1;';
        _holder.appendChild(canvasScroller);

        var schreiman = document.createElement('div');
        schreiman.setAttribute('id', "schreimann");
        var schreimanWange = document.createElement('div');
        schreimanWange.setAttribute('id', "schreimannWange");

        _holder.appendChild(schreiman);
        _holder.appendChild(schreimanWange);

        document.body.style.backgroundColor = '#ffffff';

        loadResources();
    }

    function loadResources() {

        var _imgLoader,
            resourceURL = [
                {"vignette":'data/05_space_vignette.png'},
                {"schreiman":'data/schreiman_full.gif'},
                {"font":'data/font.gif'}
            ];

        _imgLoader = ImgLoader();
        _imgLoader.load(resourceURL, resourcesLoaded);
    }

    function resourcesLoaded(images) {

        _images = images;

        _mayRender = true;
    }

    function render(msT, beat, frameDeltaMs) {

        if (!_mayRender) {
            return;
        }

        //endcap
        if(msT >= (_duration - 2600)){
            document.body.style.backgroundImage = 'url(data/chimera_3ln.jpg)';

            _holder.style.opacity = 1 / 2600 * (_duration - msT);
            return;
        }

        _sctx.clearRect(0, 0, _sctx.canvas.width, _sctx.canvas.height);

        _sctx.save();
        _sctx.drawImage(_images['vignette'], 0, 0);
        _sctx.globalCompositeOperation = 'destination-out';
        _sctx.drawImage(_images['schreiman'], _sctx.canvas.width - _images['schreiman'].width + 10, _sctx.canvas.height- _images['schreiman'].height);
        _sctx.restore();

        scroller();


        var floatBeat = parseFloat('0.' +((beat +'').split('.')[1]));

        //mwaha
        _picBundle.style.opacity = 1 - (floatBeat / 2);

        _sctx.drawImage(_images['vignette'], 0, 0, 200, _sctx.canvas.height, 0, 0, 200, _sctx.canvas.height);
    }

    function onBeat(beat) {

        if (!_mayRender) {
            return;
        }

        if (beat % 5 === 0) {
            if(_toBeGreeted.length > 0) {
                _ctx.clearRect(0, 0, _ctx.canvas.width, _ctx.canvas.height);
                var text = _toBeGreeted.pop(),
                    centerX = (_ctx.canvas.width - (text.length * LETTER_WIDTH)) / 2;

                if(_toBeGreeted.length == 3)
                    centerX += (5 * LETTER_WIDTH) / 2;
                else if(_toBeGreeted.length == 2)
                    centerX += (4 * LETTER_WIDTH) / 2;
                else if(_toBeGreeted.length == 20)
                    centerX += (4 * LETTER_WIDTH) / 2;

                renderText(text, Math.round(centerX), Math.round(_ctx.canvas.height / 2) - 50);
            }
        }
    }

    var SCROLL_SPEED = 12,
        startAtLetter = 0,
        scrollX = 1;

    function scroller() {

        var carretX = 0,
            i,
            endAtLetter;

        if(Math.floor(scrollX / LETTER_WIDTH) >= 1) {
            startAtLetter += 1;
            scrollX = 1;
        }

        endAtLetter = startAtLetter + 31;

        if(endAtLetter > _3lnPPL.length) {
           endAtLetter = _3lnPPL.length;
        }

        for (i = startAtLetter; i < endAtLetter; i++) {
             _sctx.drawImage(_images['font'], _3lnPPL[i].x * LETTER_WIDTH, _3lnPPL[i].y * LETTER_HEIGHT, LETTER_WIDTH, LETTER_HEIGHT, (carretX - scrollX), _sctx.canvas.height - LETTER_HEIGHT - 110, LETTER_WIDTH, LETTER_HEIGHT);
            carretX += LETTER_WIDTH;
        }

        scrollX += SCROLL_SPEED;
    }

    function fisherYates ( myArray ) {
      var i = myArray.length;
      if ( i == 0 ) return false;
      while ( --i ) {
         var j = Math.floor( Random.float() * ( i + 1 ) );
         var tempi = myArray[i];
         var tempj = myArray[j];
         myArray[i] = tempj;
         myArray[j] = tempi;
       }

        return myArray;
    }

    function get3lnPPL() {
        var LETTER = ('abcdefghijklmnopqrstuvwxyz0123456789-').split(''),
            LEN = LETTER.length,
            brigade = [];

        for(var i = 0; i < LEN; i++) {

            for(var c = 0; c < LEN; c++) {

                for(var u = 0; u < LEN; u++) {

                    var abridge = LETTER[i] + LETTER[c] + LETTER[u];
                    brigade.push(abridge);
                }
            }
        }

        return fisherYates(brigade);
    }

    function clear() {
        document.getElementById('root').removeChild(_holder);
    }

    function resize(w, h) {

    }

    return {
        init:init,
        render:render,
        onBeat:onBeat,
        clear:clear,
        resize:resize
    };
}());