var Smallthing = Smallthing || {};

OS_WINDOWS_PHONE = 0;
OS_ANDROID = 1;
OS_APPLE = 2;
OS_UNKNOWN = -1;
OS_DEBUG = true;
OS_WORK_SCREEN_WIDTH = 400;
OS_WORK_SCREEN_HEIGHT = 400;
OS_LOAD_3D = true;

OS_GAME_SCALE = -1.0;
OS_GLOBAL_SCALE = 0.85;

OS_SCREEN_TYPE_PROTRAIT = 1;
OS_SCREEN_TYPE_LANDSCAPE = 2;
OS_SCREEN_TYPE = 1;

PARTICLESBUFFER = [];

AUTOUPDATE = PARTICLESBUFFER;

var title = '3d';

STAGE = new createjs.Stage("game"); //, {antialias:true, preserveBuffer:true});
game.style.backgroundColor = 'transparent';
GAME = createjs;

// create tween moion plugin

STAGE.canvas.width = window.innerWidth;
STAGE.canvas.height = window.innerHeight;
STAGE.enableDOMEvents(true);

// STAGE.updateViewport(window.innerWidth, window.innerHeight);

checkScreenType = function()
{
    if(window.innerWidth > window.innerHeight)
    {
        OS_SCREEN_TYPE = OS_SCREEN_TYPE_LANDSCAPE;
    }
    else
    {
        OS_SCREEN_TYPE = OS_SCREEN_TYPE_PROTRAIT;
    }
}

orientationchangeCallback = function()
{
    this.__orientationchangeCallbackObjects = [];
    
    this.add = function(c, cs)
    {
        var o = {c:c, cs:cs};
        this.__orientationchangeCallbackObjects.push(o);
    };

    this.invoke = function()
    {
        for(var i in this.__orientationchangeCallbackObjects) {

            var o = this.__orientationchangeCallbackObjects[i];
            GAME.Tween.get(o).call(o.c, null, o.cs);
        }
    }
};

window.orientationChangedCallback = new orientationchangeCallback();
window.resizeChangedCallback = new orientationchangeCallback();

resizeWindow = function()
{
    if(typeof MANAGER3D !== 'undefined' && MANAGER3D!=null) MANAGER3D.orientationchange();

    setTimeout(function(){
        checkScreenType();
        //console.log('CHANGE CANVAS: ' + window.innerWidth.toString() + ',' + window.innerHeight.toString());
        if(typeof STAGE !== 'undefined' && STAGE!=null) STAGE.canvas.width = window.innerWidth;
        if(typeof STAGE !== 'undefined' && STAGE!=null) STAGE.canvas.height = window.innerHeight;
        //STAGE.updateViewport(window.innerWidth, window.innerHeight);
        if(typeof OBJECTMANAGER !== 'undefined' && OBJECTMANAGER != null) OBJECTMANAGER.asDirty();
        if(typeof OBJECTMANAGER !== 'undefined' && OBJECTMANAGER != null) OBJECTMANAGER.onUpdate(0);
        if(typeof GAMESTATE !== 'undefined' && GAMESTATE != null) GAMESTATE.update(0);

        setTimeout(function(){
            checkScreenType();

            if(window.orientationChangedCallback != null)
                window.orientationChangedCallback.invoke();

            if(typeof OBJECTMANAGER !== 'undefined' && OBJECTMANAGER != null) OBJECTMANAGER.asDirty();
        },100);
    }, 300);
}

window.addEventListener("orientationchange", function () {

    resizeWindow();

    console.log('orientationchange: ', window.innerWidth, window.innerHeight);
});

window.addEventListener("resize", function () {

    resizeWindow();

    console.log('resize: ', window.innerWidth, window.innerHeight);
});

GAME.Ticker.interval = 25;
GAME.Ticker.framerate = 40;

createjs.MotionGuidePlugin.install();

isTABLET = deviceDetector.detect(navigator.userAgent) == 'tablet';

//createjs.Tween.get(target).to({guide:{ path:[0,0, 0,200,200,200, 200,0,0,0] }},7000);
// Visualizing the line
//graphics.moveTo(0,0).curveTo(0,200,200,200).curveTo(200,0,0,0);

Phaser = createjs;
Phaser.Easing = createjs.Ease;

Phaser.Easing.Bounce = {
    Out : createjs.Ease.bounceOut,
    In : createjs.Ease.bounceIn,
};

Phaser.Easing.Cubic = {
    Out : createjs.Ease.cubicOut,
    In : createjs.Ease.cubicIn,
    InOut : createjs.Ease.cubicInOut,
};

Phaser.Easing.Linear = {
    None : createjs.Ease.linear
};

createTween = function(target)
{
    return tween.get(target);
}

time = function() {

    this._events = function() {

        this.add = function(time, func, funcThis)
        {
            return GAME.Tween.get(this).wait(time).call(func, null, funcThis);
        }
    }

    this.events = new this._events();
}

GAME.time = new time();

createTimeEvent = function(time, func, funcThis, o)
{
    if(o != null)
    {
        return GAME.Tween.get(o).wait(time).call(func, null, funcThis);
    }

    GAME.Tween.get(this).wait(time).call(func, null, funcThis);
    return this;
}

var State = {

    kIdle : 0,
    kPreload : 1,
    kInit : 2,
    kUpdate : 3
};

var currentState = State.kIdle;

// enable touch stage
GAME.Touch.enable(STAGE);


//
// create Sprite Sheet
SPRITESHEETBUILDER = new createjs.SpriteSheetBuilder();

buildFrame = function(frame)
{
    var index = -1;
    index = SPRITESHEETBUILDER.addFrame(new createjs.Bitmap(PRELOAD.get(frame)));
    SPRITESHEETBUILDER.addAnimation(frame, index);
}

isInit = false;

loadedGfx = function()
{
    if(isInit)
        return;

    isInit = true;

    fileSpriteSheet = [

    ];

    SPRITESHEET = null;

    if(fileSpriteSheet.length > 0) {
        for(var j = 0; j < fileSpriteSheet.length; j++)
        {
            var file = fileSpriteSheet[j];
            buildFrame(file);
        }

        SPRITESHEET = SPRITESHEETBUILDER.build();        
    }

    var sfx = PRELOAD.get('SoundFX');
    if(sfx != null) {

        SFX_SPRITES = new Howl({
            src: sfx.src,
            sprite: {
            }
      });          
    }
    else {
        SFX_SPRITES = null;
    }

    if(OS_LOAD_3D)
    {
        Create3D();
    }
}

playSfx = function(id) {

    if(SFX_SPRITES != null)
    {
        return SFX_SPRITES.play(id);
    }

    var ret = PRELOAD.get(id);
    if(ret.play != null)
    {
        ret.play();
        return ret;
    }

    return null;
}

playMusic = function(id)
{
    if(id == null)
        id = 'Music';

    if(typeof CURRENTMUSIC === 'undefined' || CURRENTMUSIC == null) {

        CURRENTMUSIC = PRELOAD.get(id);
        if(CURRENTMUSIC != null) {
            CURRENTMUSIC.loop = true;
            CURRENTMUSIC.play();
        }
        else {
            CURRENTMUSIC = null;
        }
    }
}

stopMusic = function()
{
    if(typeof CURRENTMUSIC !== 'undefined' && CURRENTMUSIC != null) {
        CURRENTMUSIC.stop();
        CURRENTMUSIC = null;
    }
}

GAME.Ticker.addEventListener("tick", function(event){

    var dtime = event.delta / 1000.0;
    if(dtime > 1.0/15.0)
        dtime = 1.0/15.0;

    if(AUTOUPDATE != null)
    {
        for(var i = AUTOUPDATE.length-1; i >= 0; i--)
        {
            var p = AUTOUPDATE[i];
            p.onUpdate(dtime);
            if(p.done)
            {
                p.destroy();
                AUTOUPDATE.splice(i, 1);
            }
        }
    }

    checkScreenType();

//    console.log("Paused:", event.paused, event.delta);

    switch(currentState)
    {
        case State.kIdle:

            currentState = State.kPreload;

            this.preload = new Smallthing.Preload();

            break;

        case State.kPreload:

            this.preload.onUpdate();

            if(this.preload.done) {

                // CREATE GOOGLE ANALYTICS
                // Smallthing.Tracking_Init('UA-112633217-1');

                currentState = State.kInit;
            }

            break;

        case State.kInit:

            Smallthing.GameState.init();

            currentState = State.kUpdate;

            OBJECTMANAGER = new Smallthing.ObjectManager();

            STAGE.on("stagemousedown", function(event) {

                OBJECTMANAGER.onMouseDown(event);
            });

            STAGE.on("stagemouseup", function(event) {

                OBJECTMANAGER.onMouseUp(event);
            });

            STAGE.on("stagemousemove",function(event) {

                INPUT_MOUSE_X = event.stageX;
                INPUT_MOUSE_Y = event.stageY;

                OBJECTMANAGER.onMouseMove(event);
            });

            if(Smallthing.GameManager != null)
                GAMESTATE.SetNextScene(new Smallthing.GameManager());
            else
                console.error('ERROR! Missing SceneStart.');

            break;

        case State.kUpdate:

            GAMESTATE.update(dtime);

            OBJECTMANAGER.onUpdate(dtime);

            break;
    }

    STAGE.update(event);
});

checkScreenType();
