//////////////// START
window.onload = function()
{
    GET = Utils.parseGet();

    Utils.addMobileListeners(LANDSCAPE_MODE, true);
    Utils.mobileCorrectPixelRatio();
    Utils.addFitLayoutListeners();

    //isAndroid = true;

    if (window.navigator.userAgent.toLowerCase().indexOf("android") > -1 || window.navigator.userAgent.toLowerCase().indexOf("linux") > -1) {
        isAndroid = true;
        //alert('Android');
    }

	Level = getQueryParams(document.location.search);

    setTimeout(startLoad, 600);
};

function getScreenRatioCoef(resolution)
{
    var coef;

    /*
     * Определение коэфициента ширины для нестандартных экранов
     * [ 960x640, 978x640, 1024x640, 1062x640, 1088x640, 1140x640 ]
     */

    // width/height
    var ratioCoefs = [ 1.5, 1.528125, 1.6, 1.659375, 1.7, 1.78125 ];

    // width/960
    var ratioWidth = [ 1, 1.01875, 1.0666, 1.10625, 1.13333, 1.1875 ];

    // height/640
    var ratioHeight = [ 1, 1, 1, 1, 1, 1 ];

    var source = (Utils.touchScreen) ? screen: window;

    if (Utils.touchScreen)
    {
        coef = (source.width > source.height)
                ? source.width / source.height
                : source.height / source.width;
    }
    else
    {
        coef = (source.innerWidth > source.innerHeight)
                ? source.innerWidth / source.innerHeight
                : source.innerHeight / source.innerWidth;
    }

    var min = 100000, minPos = -1, diff;

    for (var i = 0; i < ratioCoefs.length; i++)
    {
        diff = Math.abs(coef - ratioCoefs[i]);

        if (diff < min)
        {
            min = diff;
            minPos = i;
        }
    }

    screenWidthCoef = ratioWidth[minPos];
    screenHeightCoef = ratioHeight[minPos];

    //screenWidthCoef = 1;
    //screenHeightCoef = 1;
}

function startLoad()
{
    var resolution = Utils.getMobileScreenResolution(LANDSCAPE_MODE);

	if(GET.debug) resolution = Utils.getScaleScreenResolution(1, LANDSCAPE_MODE);
	if(Utils.mobileCheckSlowDevice()) resolution = Utils.getScaleScreenResolution(1, LANDSCAPE_MODE);

	Utils.globalScale = resolution.scale;

    getScreenRatioCoef();

    resolution.width = Math.round(resolution.width * screenWidthCoef);

	Utils.createLayout(document.getElementById("main_container"), resolution);

	Utils.addEventListener("fitlayout", function()
	{
		if (stage)
		{
			stage.drawScene(stage.canvas);
			stage.drawScene(stage.backgroundCanvas, true);
		}

		if (GameWorld.world)
		{
			box2d.setDebugDrawScale(GameWorld.world);
		}
	});

	Utils.addEventListener("lockscreen", function()
    {
        if (stage && stage.started)
        {
            stage.stop();
        }
    });

    Utils.addEventListener("unlockscreen", function()
    {
        if (stage && !stage.started)
        {
            stage.start();
        }
    });

	Utils.mobileHideAddressBar();

	if(!GET.debug) Utils.checkOrientation(LANDSCAPE_MODE);

	//var path = Utils.imagesRoot + "/" + Utils.globalScale + "/";
    var path = Utils.imagesRoot + "/2/";

    var assets = [
        {"name": "aim_1", "src": "aim/aim_1.png", "width": 22, "height": 228},
        {"name": "aim_2", "src": "aim/aim_2.png", "width": 22, "height": 228},
        {"name": "aim_3", "src": "aim/aim_3.png", "width": 22, "height": 228},
        {"name": "aim_4", "src": "aim/aim_4.png", "width": 22, "height": 228},
        {"name": "back_1", "src": "backgrounds/back_1.jpg", "width": 570, "height": 320},
        {"name": "back_2", "src": "backgrounds/back_2.jpg", "width": 570, "height": 320},
        {"name": "back_3", "src": "backgrounds/back_3.jpg", "width": 570, "height": 320},
        {"name": "back_4", "src": "backgrounds/back_4.jpg", "width": 570, "height": 320},
        {"name": "back_comics", "src": "backgrounds/back_comics.jpg", "width": 570, "height": 320},
        {"name": "lvl_back", "src": "backgrounds/lvl_back.jpg", "width": 570, "height": 320},
        {"name": "preloader", "src": "backgrounds/preloader.jpg", "width": 570, "height": 320},
        {"name": "btn_credits", "src": "btn_credits.png", "width": 117, "height": 41},
        {"name": "btn_info", "src": "btn_info.png", "width": 50, "height": 50},
        {"name": "btn_left", "src": "btn_left.png", "width": 50, "height": 50},
        {"name": "btn_levels", "src": "btn_levels.png", "width": 50, "height": 50},
        {"name": "btn_menu", "src": "btn_menu.png", "width": 50, "height": 50},
        {"name": "btn_more_games", "src": "btn_more_games.png", "width": 117, "height": 41},
        {"name": "btn_next", "src": "btn_next.png", "width": 50, "height": 50},
        {"name": "btn_options", "src": "btn_options.png", "width": 50, "height": 50},
        {"name": "btn_pause", "src": "btn_pause.png", "width": 50, "height": 50},
        {"name": "btn_play", "src": "btn_play.png", "width": 50, "height": 50},
        {"name": "btn_play_big", "src": "btn_play_big.png", "width": 134, "height": 52, "frames": 2},
        {"name": "btn_records", "src": "btn_records.png", "width": 50, "height": 50},
        {"name": "btn_restart", "src": "btn_restart.png", "width": 50, "height": 50},
        {"name": "btn_right", "src": "btn_right.png", "width": 50, "height": 50},
        {"name": "btn_shop", "src": "btn_shop.png", "width": 50, "height": 50},
        {"name": "btn_sound", "src": "btn_sound.png", "width": 76, "height": 76, "frames": 2},
        {"name": "frame_01", "src": "comics/frame_01.png", "width": 480, "height": 320},
        {"name": "frame_02", "src": "comics/frame_02.png", "width": 480, "height": 320},
        {"name": "frame_03", "src": "comics/frame_03.png", "width": 480, "height": 320},
        {"name": "frame_04", "src": "comics/frame_04.png", "width": 480, "height": 320},
        {"name": "frame_05", "src": "comics/frame_05.png", "width": 480, "height": 320},
        {"name": "frame_06", "src": "comics/frame_06.png", "width": 480, "height": 320},
        {"name": "hint_1_1", "src": "hint/hint_1_1.png", "width": 274, "height": 152},
        {"name": "hint_1_2", "src": "hint/hint_1_2.png", "width": 278, "height": 97},
        {"name": "hint_2_1", "src": "hint/hint_2_1.png", "width": 333, "height": 93},
        {"name": "hint_2_2", "src": "hint/hint_2_2.png", "width": 347, "height": 107},
        {"name": "hint_3_1", "src": "hint/hint_3_1.png", "width": 268, "height": 148},
        {"name": "hint_4_1", "src": "hint/hint_4_1.png", "width": 268, "height": 132},
        {"name": "credits_popup", "src": "credits_popup.png", "width": 315, "height": 303},
        {"name": "explode", "src": "explode.png", "width": 60, "height": 56, "frames": 13},
        {"name": "game_field", "src": "game_field.png", "width": 570, "height": 320},
        {"name": "hourglass", "src": "hourglass.png", "width": 100, "height": 150},
        {"name": "light", "src": "light.png", "width": 62, "height": 84, "frames": 6, "layers": 2},
        {"name": "lose_popup", "src": "lose_popup.png", "width": 248, "height": 182},
        {"name": "lvl_star1", "src": "lvl_star1.png", "width": 15, "height": 15},
        {"name": "lvl_star2", "src": "lvl_star2.png", "width": 31, "height": 15},
        {"name": "lvl_star3", "src": "lvl_star3.png", "width": 39, "height": 15},
        {"name": "numbers_big", "src": "numbers_big.png", "width": 50, "height": 40, "frames": 10},
        {"name": "numbers_black", "src": "numbers_black.png", "width": 10, "height": 10, "frames": 12},
        {"name": "numbers_blue", "src": "numbers_blue.png", "width": 28, "height": 20, "frames": 10},
        {"name": "numbers_blue_mini", "src": "numbers_blue_mini.png", "width": 18, "height": 10, "frames": 12},
        {"name": "numbers_green", "src": "numbers_green.png", "width": 26, "height": 18, "frames": 10},
        {"name": "numbers_medium", "src": "numbers_medium.png", "width": 50, "height": 40, "frames": 12},
        {"name": "numbers_score", "src": "numbers_score.png", "width": 32, "height": 32, "frames": 11},
        {"name": "numbers_yellow", "src": "numbers_yellow.png", "width": 18, "height": 18, "frames": 10},
        {"name": "numbers_yellow_mini", "src": "numbers_yellow_mini.png", "width": 16, "height": 18, "frames": 12},
        {"name": "asteroids_a", "src": "objects/asteroids/asteroids_a.png", "width": 34, "height": 34, "frames": 2},
        {"name": "asteroids_a_explosion", "src": "objects/asteroids/asteroids_a_explosion.png", "width": 98, "height": 96, "frames": 8, "layers": 2},
        {"name": "asteroids_b", "src": "objects/asteroids/asteroids_b.png", "width": 34, "height": 34, "frames": 2},
        {"name": "asteroids_b_explosion", "src": "objects/asteroids/asteroids_b_explosion.png", "width": 98, "height": 96, "frames": 8, "layers": 2},
        {"name": "asteroids_c", "src": "objects/asteroids/asteroids_c.png", "width": 34, "height": 34, "frames": 2},
        {"name": "asteroids_c_explosion", "src": "objects/asteroids/asteroids_c_explosion.png", "width": 98, "height": 96, "frames": 8, "layers": 2},
        {"name": "ball_1", "src": "objects/balls/ball_1.png", "width": 15, "height": 15},
        {"name": "ball_2", "src": "objects/balls/ball_2.png", "width": 15, "height": 15},
        {"name": "ball_3", "src": "objects/balls/ball_3.png", "width": 15, "height": 15},
        {"name": "ball_4", "src": "objects/balls/ball_4.png", "width": 15, "height": 15},
        {"name": "ball_5", "src": "objects/balls/ball_5.png", "width": 15, "height": 15},
        {"name": "ball_6", "src": "objects/balls/ball_6.png", "width": 15, "height": 15},
        {"name": "ball_7", "src": "objects/balls/ball_7.png", "width": 15, "height": 15},
        {"name": "bottom", "src": "objects/bottom.png", "width": 115, "height": 61},
        {"name": "bottom_top", "src": "objects/bottom_top.png", "width": 42, "height": 52},
        {"name": "bullet_1", "src": "objects/bullets/bullet_1.png", "width": 20, "height": 20},
        {"name": "bullet_2", "src": "objects/bullets/bullet_2.png", "width": 20, "height": 20},
        {"name": "bullet_3", "src": "objects/bullets/bullet_3.png", "width": 20, "height": 20},
        {"name": "bullet_4", "src": "objects/bullets/bullet_4.png", "width": 20, "height": 20},
        {"name": "cannon", "src": "objects/cannon.png", "width": 112, "height": 112},
        {"name": "crystal_d", "src": "objects/crystals/crystal_d.png", "width": 40, "height": 40, "frames": 2},
        {"name": "crystal_d_explosion", "src": "objects/crystals/crystal_d_explosion.png", "width": 107, "height": 101, "frames": 7, "layers": 2},
        {"name": "crystal_e", "src": "objects/crystals/crystal_e.png", "width": 40, "height": 40, "frames": 2},
        {"name": "crystal_e_explosion", "src": "objects/crystals/crystal_e_explosion.png", "width": 107, "height": 101, "frames": 7, "layers": 2},
        {"name": "crystal_f", "src": "objects/crystals/crystal_f.png", "width": 40, "height": 40, "frames": 2},
        {"name": "crystal_f_explosion", "src": "objects/crystals/crystal_f_explosion.png", "width": 107, "height": 101, "frames": 7, "layers": 2},
        {"name": "crystal_i", "src": "objects/crystals/crystal_i.png", "width": 40, "height": 40, "frames": 2},
        {"name": "crystal_i_explosion", "src": "objects/crystals/crystal_i_explosion.png", "width": 107, "height": 101, "frames": 7, "layers": 2},
        {"name": "spaceships_large", "src": "objects/spaceships/spaceships_large.png", "width": 53, "height": 11},
        {"name": "spaceships_medium", "src": "objects/spaceships/spaceships_medium.png", "width": 39, "height": 9},
        {"name": "spaceships_small", "src": "objects/spaceships/spaceships_small.png", "width": 25, "height": 8},
        {"name": "stone_a", "src": "objects/stones/stone_a.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_a_explosion", "src": "objects/stones/stone_a_explosion.png", "width": 100, "height": 98, "frames": 10},
        {"name": "stone_b", "src": "objects/stones/stone_b.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_b_explosion", "src": "objects/stones/stone_b_explosion.png", "width": 100, "height": 98, "frames": 10},
        {"name": "stone_c", "src": "objects/stones/stone_c.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_c_explosion", "src": "objects/stones/stone_c_explosion.png", "width": 100, "height": 98, "frames": 10},
        {"name": "stone_d", "src": "objects/stones/stone_d.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_d_explosion", "src": "objects/stones/stone_d_explosion.png", "width": 107, "height": 101, "frames": 7, "layers": 2},
        {"name": "stone_e", "src": "objects/stones/stone_e.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_e_explosion", "src": "objects/stones/stone_e_explosion.png", "width": 107, "height": 101, "frames": 7, "layers": 2},
        {"name": "stone_f", "src": "objects/stones/stone_f.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_f_explosion", "src": "objects/stones/stone_f_explosion.png", "width": 104, "height": 98, "frames": 7, "layers": 2},
        {"name": "stone_i", "src": "objects/stones/stone_i.png", "width": 26, "height": 20, "frames": 2},
        {"name": "stone_i_explosion", "src": "objects/stones/stone_i_explosion.png", "width": 104, "height": 98, "frames": 7, "layers": 2},
        {"name": "pause_popup", "src": "pause_popup.png", "width": 265, "height": 181},
        {"name": "planet", "src": "planet.png", "width": 50, "height": 50, "frames": 2},
        {"name": "scale", "src": "scale.png", "width": 14, "height": 8, "frames": 3},
        {"name": "score_block", "src": "score_block.png", "width": 308, "height": 60},
        {"name": "star_anim_1", "src": "stars/star_anim_1.png", "width": 46, "height": 46, "frames": 9},
        {"name": "star_anim_2", "src": "stars/star_anim_2.png", "width": 40, "height": 40, "frames": 12},
        {"name": "star_anim_3", "src": "stars/star_anim_3.png", "width": 76, "height": 30, "frames": 10},
        {"name": "star_anim_4", "src": "stars/star_anim_4.png", "width": 110, "height": 88, "frames": 3},
        {"name": "fireball", "src": "txt/fireball.png", "width": 135, "height": 30},
        {"name": "megabonus", "src": "txt/megabonus.png", "width": 175, "height": 30},
        {"name": "multiball", "src": "txt/multiball.png", "width": 155, "height": 30},
        {"name": "plusball", "src": "txt/plusball.png", "width": 110, "height": 30},
        {"name": "rocketball", "src": "txt/rocketball.png", "width": 180, "height": 30},
        {"name": "x10", "src": "txt/x10.png", "width": 150, "height": 30},
        {"name": "x2", "src": "txt/x2.png", "width": 140, "height": 30},
        {"name": "x4", "src": "txt/x4.png", "width": 140, "height": 30},
        {"name": "x6", "src": "txt/x6.png", "width": 140, "height": 30},
        {"name": "x8", "src": "txt/x8.png", "width": 140, "height": 30},
        {"name": "win_popup", "src": "win_popup.png", "width": 260, "height": 298}
    ];

    TTLoader.create(loadImagesEnd, true, GET["debug"] == 1);

    library = new AssetsLibrary('images', Utils.globalScale, assets);
    library.load(TTLoader.loadComplete, TTLoader.showLoadProgress, null, 100);
}

function loadImagesEnd()
{
    document.getElementById('progress_container').style.display = 'none';
    document.getElementById('screen_container').style.display = 'block';
    document.getElementById('screen_background_container').style.display = 'block';

    var channels = 2;

    if (!AudioMixer.isWebAudioSupport())
    {
        channels = 1;
    }

    mixer = new AudioMixer("music", channels);

    if (GET["debug"] != 1)
    {
        prepareGame();
    }
}

function getStageWidth()
{
    //console.log('getStageWidth = ' + Math.ceil(480 * screenWidthCoef));
    return Math.round(480 * screenWidthCoef);
}

function getStageHeight()
{
    //console.log('getStageHeight = ' + Math.ceil(320 * screenHeightCoef));
    return Math.floor(320 * screenHeightCoef);
}

function getStageWidthCenter()
{
    return Math.round(getStageWidth() / 2);
}

function getStageHeightCenter()
{
    return Math.round(getStageHeight() / 2);
}

function setCSSBack(img, color)
{
    backgroundElement = document.getElementById('screen_background_wrapper');

    backgroundElement.style.backgroundImage = "url(" + library.getSprite(img).bitmap.src + ")";
    backgroundElement.style.backgroundColor = color ? color : '#000000';
	backgroundElement.style.backgroundPosition = "center center";
	backgroundElement.style.backgroundRepeat = "no-repeat";
    backgroundElement.style.backgroundSize = "auto 100%";
}

function createStage()
{
    if (stage)
    {
        stage.destroy();
        stage.stop();
    }

    stage = new Stage('screen', getStageWidth(), getStageHeight());
    stage.setBackgroundCanvas('screen_background');

    stage.delay = 1000 / fps;
    stage.onpretick = preTick;
    stage.onposttick = postTick;
    stage.ceilSizes = true;
    stage.showFPS = false;

}

function createScene()
{
    console.log('=====createScene');
    createStage();

 	if (gameState == STATE_MENU)
	{
        showMenu();
	}

    if (gameState == STATE_CREDITS)
	{
        showCredits();
	}

    if (gameState == STATE_CHOOSE_LEVEL)
	{
        showChooseLevel();
    }

	if (gameState == STATE_GAME)
	{
        if (processState == PROCESS_START)
        {
            prepareLevel(curLevel);
        }
	}

    if (gameState == STATE_COMICS)
	{
        showComics();
    }

    if (gameState == STATE_COMICS_LAST_FRAME)
	{
        showComicsLastFrame();
    }

    if (gameState == STATE_LEVEL_CLEARED)
	{
        showLevelCleared();
    }

    if (gameState == STATE_LEVEL_FAILED)
	{
        showLevelFailed();
    }

    buildBackground();
    stage.start();
}

function showMenu()
{
    console.log('=====showMenu');

    setCSSBack('preloader');
    showRandomStar();
    playMusic('menu');

    var btn = library.getSprite('btn_play_big');
    btn.x = getStageWidthCenter();
    btn.y = getStageHeightCenter() + 240;
    btn.scaleX = 6;
    btn.scaleY = 6;
    btn.onclick = function()
    {
		gameState = STATE_CHOOSE_LEVEL;
        createScene();

        return false;
    };
    stage.addChild(btn);
    btn.gotoAndStop(1);

    var btn_snd = library.getSprite('btn_sound');
    btn_snd.x = getStageWidthCenter() + 210;
    btn_snd.y = getStageHeightCenter() - 130;
    btn_snd.scaleX = 0.01;
    btn_snd.scaleY = 0.01;
    btn_snd.music = 'menu';
    btn_snd.onclick = toggleSound;
    stage.addChild(btn_snd);
    btn_snd.gotoAndStop(1);

    var btn_cdt = library.getSprite('btn_credits');
    btn_cdt.x = getStageWidthCenter() + 410;
    btn_cdt.y = getStageHeightCenter() + 110;
    btn_cdt.onclick = function()
    {
        gameState = STATE_CREDITS;
        createScene();
        return false;
    };
    stage.addChild(btn_cdt);

    var btn_mgm = library.getSprite('btn_more_games');
    btn_mgm.x = getStageWidthCenter() - 410;
    btn_mgm.y = getStageHeightCenter() + 110;
    btn_mgm.onclick = function()
    {
        CocoonJS.App.openURL(MORE_GAMES_URL);
        return false;
    };
    stage.addChild(btn_mgm);

    if (!isSoundOn)
    {
        btn_snd.gotoAndStop(0);
    }

    btn.scaleTo(
            1,
            fps / 2,
            Easing.linear.easeInOut,
            function()
            {
                btn.scaleTo(
                        1.05,
                        fps / 10,
                        Easing.linear.easeInOut,
                        function()
                        {
                            btn.scaleTo(1, fps / 10);
                            btn_snd.scaleTo(0.74, fps / 2, Easing.back.easeOut);
                            btn_mgm.moveTo(getStageWidthCenter() - 150, btn_mgm.y, fps / 2, Easing.back.easeOut);
                            btn_cdt.moveTo(getStageWidthCenter() + 150, btn_cdt.y, fps / 2, Easing.back.easeOut);
                        });
            });
    btn.moveTo(
            btn.x,
            getStageHeightCenter() + 60,
            fps / 2,
            Easing.linear.easeInOut);

    buildBackground();
}

function showChooseLevel()
{
	////////////////////
    ///для теста
    //openLevel = levels.length;
    ////////////////
    var spr;

    countLevels = levels.length;

	console.log('openLevel = ' + openLevel);

    setCSSBack('lvl_back');
    showRandomStar();

    var score_block = library.getSprite('score_block');
    score_block.x = getStageWidthCenter();
    score_block.y = -library.getSprite('score_block').height;
    stage.addChild(score_block);

    score_block.moveTo(
            score_block.x,
            library.getSprite('score_block').height / 2,
            fps / 2,
            Easing.linear.easeOut,
            function()
            {
                text = new SimpleText(library.getBitmap('numbers_green'), 26, 18);
                text.x = getStageWidthCenter();
                text.y = getStageHeightCenter() - 148.5;
                text.scale = 0.8;
                text.charMap = charMap;
                text.charWidth = charWidthGreen;
                text.charSpacing = -6;
                text.align = text.ALIGN_LEFT;
                text.write(gameScore);
            });

    var x1 = -151;
    var y1 = -63;
    var step_x = 75;
    var step_y = 73;

    var tmp;

    for (var n = 0; n < 15; n++)
    {
        tmp = n + page * 15;

        var i = n % 5;
        var j = Math.floor(n / 5);

        var pln = library.getSprite('planet');
        pln.x = getStageWidthCenter() + x1 + step_x * i;
        pln.y = getStageHeightCenter() + y1 + step_y * j;
        stage.addChild(pln);
        pln.gotoAndStop(1);
        //pln.setStatic(true);

        var srt = new Sprite(null, 50, 50);
        srt.n = tmp;
        srt.x = pln.x;
        srt.y = pln.y;
        srt.onmousedown = function() { return false; };
        srt.onmouseup = function(e)
        {
            if (e.target.n > openLevel || e.target.n > countLevels)
            {
                return false;
            }

            curLevel = e.target.n;

            if (curLevel > countLevels)
            {
                curLevel = countLevels;
            }

            gameState = (e.target.n > 0 ? STATE_GAME : STATE_COMICS);
            createScene();

			return false;
        };
        srt.setStatic(true);
        stage.addChild(srt);

		if (srt.n <= openLevel)
        {
            pln.gotoAndStop(0);

            var text = new SimpleText(library.getBitmap('numbers_big'), 50, 40);
            text.x = pln.x;
            text.y = pln.y;
            text.charMap = charMap;
            text.charWidth = charWidth;
            text.align = text.ALIGN_CENTER;
            text.charSpacing = 0;
            text.scale = 0.4;
            text.write((tmp <= countLevels ? tmp + 1 : ''));

            if (bestLevelStars[tmp])
            {
                var star_spr = library.getSprite('lvl_star' + bestLevelStars[tmp]);
                star_spr.x = pln.x;
                star_spr.y = pln.y + 15;
                stage.addChild(star_spr);
                //star_spr.setStatic(true);
            }
        }
    }

    var back = library.getSprite('btn_left');
    back.onclick = function()
    {
        if (page == 0)
        {
            gameState = STATE_MENU;
        }
        else
        {
            page--;
            gameState = STATE_CHOOSE_LEVEL;
        }

        createScene();
    };
    stage.addChild(back);
    back.setRelativePosition(-30, 0, 'left');
    back.moveTo(30, back.y, fps / 2, Easing.back.easeOut);

    if (page != 2) {
        var next = library.getSprite('btn_right');
        next.onclick = function()
        {
            page++;
            gameState = STATE_CHOOSE_LEVEL;
            createScene();
        };
        stage.addChild(next);
        next.setRelativePosition(-30, 0, 'right');
        next.moveTo(getStageWidth() - 30, back.y, fps / 2, Easing.back.easeOut);
    }

    var btn_snd = library.getSprite('btn_sound');
    btn_snd.x = getStageWidthCenter() + 210;
    btn_snd.y = getStageHeightCenter() - 130;
    btn_snd.scaleX = 0.01;
    btn_snd.scaleY = 0.01;
    btn_snd.music = 'menu';
    btn_snd.onclick = toggleSound;
    stage.addChild(btn_snd);
    btn_snd.gotoAndStop(1);

    if (!isSoundOn)
    {
        btn_snd.gotoAndStop(0);
    }

    btn_snd.scaleTo(0.74, fps / 2, Easing.back.easeOut);

    var btn_mgm = library.getSprite('btn_more_games');
    btn_mgm.x = getStageWidthCenter();
    btn_mgm.y = getStageHeightCenter() + 250;
    btn_mgm.onclick = function()
    {
        CocoonJS.App.openURL(MORE_GAMES_URL);
        return false;
    };
    stage.addChild(btn_mgm);

    btn_mgm.moveTo(getStageWidthCenter(), getStageHeightCenter() + 135, fps / 2, Easing.back.easeOut);

	return false;
}

function showComics()
{
    setCSSBack('back_comics');
    showRandomStar();

    GameComics.show();

    return false;
}

function showComicsLastFrame()
{
    setCSSBack('back_comics');
    showRandomStar();

    GameComics.showLastFrame();

    return false;
}

function showCredits()
{
    console.log('=====showCredits()');

    setCSSBack('lvl_back');
    showRandomStar();

    var credBG = library.getSprite('credits_popup');
    credBG.x = getStageWidthCenter() + popupWindowShift;
    credBG.y = getStageHeightCenter();
    stage.addChild(credBG);

	mc = library.getSprite('btn_menu');
    mc.x = credBG.x - 5;
    mc.y = credBG.y + 90;
    mc.onclick = function()
    {
        gameState = STATE_MENU;
        createScene();
        return false;
    };
    stage.addChild(mc);
}

function showLevelCleared()
{
    console.log('=====showLevelCleared()');

	GameBase.setPlayerScore();

    setCSSBack('lvl_back');
    showRandomStar();

    playSound('win1');

    var bg = library.getSprite(null, {width: getStageWidth(), height: getStageHeight()});
    bg.x = getStageWidthCenter();
    bg.y = getStageHeightCenter();
    bg.onclick = function()
    {
        for (var i = 0; i < stage.tweens.length; i++)
        {
            stage.tweens[i].forward();
        }

        mixer.stop(1);

        return false;
    };
    stage.addChild(bg);

    var lvlBG = library.getSprite('win_popup');
    lvlBG.x = getStageWidthCenter() + popupWindowShift;
    lvlBG.y = getStageHeightCenter();
    stage.addChild(lvlBG);

    mc = library.getSprite('btn_restart');
    mc.x = lvlBG.x - 73;
    mc.y = lvlBG.y + 88;
    mc.onmousedown = function() { return false; };
    mc.onmouseup = function()
    {
        mixer.stop(1);
        gameState = STATE_GAME;
        createScene();
		return false;
    };
    stage.addChild(mc);

	mc = library.getSprite('btn_menu');
    mc.x = lvlBG.x - 10;
    mc.y = lvlBG.y + 100;
    mc.onmousedown = function() { return false; };
    mc.onmouseup = function()
    {
        if (curLevel >= levels.length - 1 && levelStars[curLevel] >= 1)
        {
            gameState = STATE_COMICS_LAST_FRAME;
        }
        else
        {
            gameState = STATE_CHOOSE_LEVEL;
        }

        mixer.stop(1);

        createScene();
        return false;
    };
    stage.addChild(mc);

    if (curLevel < levels.length - 1 && levelStars[curLevel] >= 1)
    {
        mc = library.getSprite('btn_play');
        mc.x = lvlBG.x + 49;
        mc.y = lvlBG.y + 88;
        mc.onmousedown = function() { return false; };
        mc.onmouseup = function()
        {
            mixer.stop(1);
            curLevel++;
            gameState = STATE_GAME;
            createScene();
            return false;
        };
        stage.addChild(mc);
    }

	text = new SimpleText(library.getBitmap('numbers_black'), 10, 10);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y - 51;
    text.scale = 1;
	text.charMap = charMap;
	text.charWidth = charWidthBlack;
	text.charSpacing = -4;
	text.align = text.ALIGN_LEFT;
	text.write(Shots.maxCount);

	text = new SimpleText(library.getBitmap('numbers_black'), 10, 10);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y - 37;
    text.scale = 1;
	text.charMap = charMap;
	text.charWidth = charWidthBlack;
	text.charSpacing = -4;
	text.align = text.ALIGN_LEFT;
	text.write(Shots.count);

    text = new SimpleText(library.getBitmap('numbers_black'), 10, 10);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y - 22;
    text.scale = 1;
	text.charMap = charMap;
	text.charWidth = charWidthBlack;
	text.charSpacing = -4;
	text.align = text.ALIGN_LEFT;
	text.write(Shots.count * freeBulletPrize);

    showCounter(text, 0, Shots.count * freeBulletPrize);

    text = new SimpleText(library.getBitmap('numbers_black'), 10, 10);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y - 5;
    text.scale = 1;
	text.charMap = charMap;
	text.charWidth = charWidthBlack;
	text.charSpacing = -4;
	text.align = text.ALIGN_LEFT;
	text.write(GameBase.elementScore.ASTEROID ? GameBase.elementScore.ASTEROID : 0);

    showCounter(text, 0, GameBase.elementScore.ASTEROID ? GameBase.elementScore.ASTEROID : 0);

    text = new SimpleText(library.getBitmap('numbers_black'), 10, 10);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y + 12;
    text.scale = 1;
	text.charMap = charMap;
	text.charWidth = charWidthBlack;
	text.charSpacing = -4;
	text.align = text.ALIGN_LEFT;
	text.write(GameBase.elementScore.CRYSTAL ? GameBase.elementScore.CRYSTAL : 0);

    showCounter(text, 0, GameBase.elementScore.CRYSTAL ? GameBase.elementScore.CRYSTAL : 0);

    ////
    text = new SimpleText(library.getBitmap('numbers_yellow'), 18, 18);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y + 31;
    text.scale = 0.6;
	text.charMap = charMap;
	text.charWidth = charWidthYellow;
	text.charSpacing = -5;
	text.align = text.ALIGN_LEFT;
	text.write(curLevelScore);

    showCounter(text, 0, curLevelScore);

    text = new SimpleText(library.getBitmap('numbers_yellow'), 18, 18);
	text.x = lvlBG.x + 20;
	text.y = lvlBG.y + 48;
    text.scale = 0.6;
	text.charMap = charMap;
	text.charWidth = charWidthYellow;
	text.charSpacing = -5;
	text.align = text.ALIGN_LEFT;
	text.write(gameScore);

    showCounter(text, gameScore - curLevelScore, gameScore);

    //playSound('score');

    GameBase.resetGameParameters();
}

function showLevelFailed()
{
    console.log('=====showLevelFailed');
    setCSSBack('lvl_back');
    showRandomStar();

    playSound('lose1');

    var pauseBG = library.getSprite('lose_popup');
    pauseBG.x = getStageWidthCenter() + popupWindowShift;
    pauseBG.y = getStageHeightCenter();
    pauseBG.static = false;
    pauseBG.onclick = function() { return false; };
    stage.addChild(pauseBG);

    var menuButton = library.getSprite('btn_menu');
    menuButton.x = pauseBG.x - 50;
    menuButton.y = pauseBG.y + 50;
    menuButton.static = false;
    menuButton.onmousedown = function() { return false; };
    menuButton.onmouseup = function()
    {
        GameBase.resetGameParameters();
        gameState = STATE_MENU;
        createScene();
        return false;
    };
    stage.addChild(menuButton);

    var playButton = library.getSprite('btn_restart');
    playButton.x = pauseBG.x + 12;
    playButton.y = pauseBG.y + 50;
    playButton.static = false;
    playButton.onmousedown = function() { return false; };
    playButton.onmouseup = function()
    {
        GameBase.resetGameParameters();
        gameState = STATE_GAME;
        createScene();
        return false;
    };
    stage.addChild(playButton);

    buildBackground();

    return false;
}

function showPause()
{
    console.log('=====showPause');
    pause_flag = true;

    var shadowSprite = new Sprite(null, getStageWidth(), getStageHeight(), 1);
    shadowSprite.x = getStageWidthCenter();
    shadowSprite.y = getStageHeightCenter();
    shadowSprite.fillColor = '#000000';
    shadowSprite.opacity = 0.5;
    shadowSprite.onclick = function() { return false; };
    shadowSprite.onmousemove = function() { return false; };
    stage.addChild(shadowSprite);

    var pauseBG = library.getSprite('pause_popup');
    pauseBG.x = getStageWidthCenter() + popupWindowShift;
    pauseBG.y = getStageHeightCenter();
    pauseBG.static = false;
    stage.addChild(pauseBG);
    pauseBG.setZIndex(stage.objects[stage.getMaxZIndexInStack(stage.objects)].zIndex + 1);

    var menuButton = library.getSprite('btn_menu');
    menuButton.x = pauseBG.x - 75;
    menuButton.y = pauseBG.y + 50;
    menuButton.static = false;
    menuButton.onmousedown = function() { return false; };
    menuButton.onmouseup = function()
    {
        GameBase.resetGameParameters();
        gameState = STATE_CHOOSE_LEVEL;
        createScene();
        return false;
    };
    stage.addChild(menuButton);

    var menuRestart = library.getSprite('btn_restart');
    menuRestart.x = pauseBG.x - 18;
    menuRestart.y = pauseBG.y + 50;
    menuRestart.onmousedown = function() { return false; };
    menuRestart.onmouseup = function()
    {
        gameState = STATE_GAME;
        createScene();
		return false;
    };
    stage.addChild(menuRestart);

    var playButton = library.getSprite('btn_next');
    playButton.x = pauseBG.x + 42;
    playButton.y = pauseBG.y + 50;
    playButton.static = false;
    playButton.onmousedown = function() { return false; };
    playButton.onmouseup = function()
    {
        pause_flag = false;
        shadowSprite.destroy = true;
        pauseBG.destroy = true;
        playButton.destroy = true;
        menuButton.destroy = true;
        menuRestart.destroy = true;
        return false;
    };
    stage.addChild(playButton);

    buildBackground();

    return false;
}

function showHint()
{
    console.log('==========showHint()');

    if (hint_flag)
    {
        return false;
    }

    hint_flag = true;
    hintSprite1 = null;
    hintSprite2 = null;

    switch (curLevel)
    {
        case 0: {
                hintSprite1 = library.getSprite('hint_1_1');
                hintSprite1.x = getStageWidthCenter() + 10;
                hintSprite1.y = getStageHeightCenter();
                stage.addChild(hintSprite1);

                setTimeout(function()
                {
                    hintSprite1.fadeTo(
                            0.01,
                            fps / 2,
                            Easing.linear.easeOut,
                            function()
                            {
                                hintSprite2 = library.getSprite('hint_1_2');
                                hintSprite2.x = getStageWidthCenter() - 33;
                                hintSprite2.y = getStageHeightCenter();
                                hintSprite2.opacity = 0.01;
                                stage.addChild(hintSprite2);

                                hintSprite2.fadeTo(
                                        1,
                                        fps / 2,
                                        Easing.linear.easeOut,
                                        function()
                                        {
                                            setTimeout(function()
                                            {
                                                hintSprite2.fadeTo(
                                                        0,
                                                        fps / 2,
                                                        Easing.linear.easeOut,
                                                        function()
                                                        {
                                                            hintSprite1.destroy = true;
                                                            hintSprite2.destroy = true;
                                                            hint_flag = false;
                                                        });
                                            },
                                            3000);
                                        });
                            });
                },
                3000);

                break;
        }
        case 1: {
                hintSprite1 = library.getSprite('hint_2_1');
                hintSprite1.x = getStageWidthCenter() - 40;
                hintSprite1.y = getStageHeightCenter() - 75;
                stage.addChild(hintSprite1);

                var t1 = setTimeout(function()
                {
                    clearTimeout(t1);
                    hintSprite1.fadeTo(
                            0.01,
                            fps / 2,
                            Easing.linear.easeOut,
                            function()
                            {
                                hintSprite2 = library.getSprite('hint_2_2');
                                hintSprite2.x = getStageWidthCenter() + 40;
                                hintSprite2.y = getStageHeightCenter() - 67;
                                hintSprite2.opacity = 0.01;
                                stage.addChild(hintSprite2);

                                hintSprite2.fadeTo(
                                        1,
                                        fps / 2,
                                        Easing.linear.easeOut,
                                        function()
                                        {
                                            var t2 = setTimeout(function()
                                            {
                                                clearTimeout(t2);
                                                hintSprite2.fadeTo(
                                                        0,
                                                        fps / 2,
                                                        Easing.linear.easeOut,
                                                        function()
                                                        {
                                                            hintSprite1.destroy = true;
                                                            hintSprite2.destroy = true;
                                                            hint_flag = false;
                                                        });
                                            },
                                            3000);
                                        });
                            });
                },
                3000);

                break;
        }
        case 2: {
                hintSprite1 = library.getSprite('hint_3_1');
                hintSprite1.x = getStageWidthCenter() + 7;
                hintSprite1.y = getStageHeightCenter() + 58;
                stage.addChild(hintSprite1);

                var t1 = setTimeout(function()
                {
                    hintSprite1.fadeTo(
                            0.01,
                            fps / 2,
                            Easing.linear.easeOut,
                            function(e)
                            {
                                e.target.obj.destroy = true;
                                hint_flag = false;
                            });
                },
                3000);

                break;
        }
        case 3: {
                hintSprite1 = library.getSprite('hint_4_1');
                hintSprite1.x = getStageWidthCenter() + 7;
                hintSprite1.y = getStageHeightCenter() - 48;
                stage.addChild(hintSprite1);

                var t1 = setTimeout(function()
                {
                    hintSprite1.fadeTo(
                            0.01,
                            fps / 2,
                            Easing.linear.easeOut,
                            function(e)
                            {
                                e.target.obj.destroy = true;
                                hint_flag = false;
                            });
                },
                3000);

                break;
        }
        default: {
                hint_flag = false;
                break;
        }
    }
}

function showRandomStar()
{
    var star1 = library.getSprite('star_anim_1');
    star1.x = getRandomInt(20, getStageWidth() - 20);
    star1.y = getRandomInt(20, getStageHeightCenter());
    star1.animation = true;
    star1.animDelay = 3;
    star1.static = false;
    star1.onrender = function(e)
	{
        if ((e.target.currentFrame == e.target.totalFrames - 1) && (e.target.animStep == e.target.animDelay - 1))
        {
            if (e.target.currentLayer !== e.target.totalLayers - 1)
            {
                e.target.currentLayer++;
            }
            else
            {
                e.target.gotoAndStop(0);
                setTimeout(function()
                {
                    e.target.gotoAndPlay(0);
                },
                2000);
            }
        }
    };
    stage.addChild(star1);

    var star2 = library.getSprite('star_anim_2');
    star2.x = getRandomInt(20, getStageWidth() - 20);
    star2.y = getRandomInt(getStageHeightCenter(), getStageHeight() - 20);
    star2.animation = true;
    star2.animDelay = 3;
    star2.static = false;
    star2.onrender = function(e)
	{
        if ((e.target.currentFrame == e.target.totalFrames - 1) && (e.target.animStep == e.target.animDelay - 1))
        {
            if (e.target.currentLayer !== e.target.totalLayers - 1)
            {
                e.target.currentLayer++;
            }
            else
            {
                e.target.gotoAndStop(0);
                setTimeout(function()
                {
                    e.target.gotoAndPlay(0);
                },
                5000);
            }
        }
    };
    stage.addChild(star2);

    var star3 = library.getSprite('star_anim_3');
    star3.x = getRandomInt(20, getStageWidth() - 20);
    star3.y = getRandomInt(20, getStageHeightCenter());
    star3.animation = true;
    star3.animDelay = 3;
    star3.static = false;
    star3.onrender = function(e)
	{
        if ((e.target.currentFrame == e.target.totalFrames - 1) && (e.target.animStep == e.target.animDelay - 1))
        {
            if (e.target.currentLayer !== e.target.totalLayers - 1)
            {
                e.target.currentLayer++;
            }
            else
            {
                e.target.gotoAndStop(0);
                setTimeout(function()
                {
                    e.target.gotoAndPlay(0);
                },
                7000);
            }
        }
    };
    stage.addChild(star3);
}

function showCounter(textSprite, start_value, end_value)
{
    var score = {"val": 0};
    var tween = stage.createTween(score, "val", start_value, end_value, fps * 2, Easing.sine.easeInOut);

    tween.onchange = function(e)
    {
        textSprite.write(Math.round(e.target.obj.val));
    };
    tween.onfinish = function(e)
    {
        textSprite.write(Math.round(e.target.obj.val));
    };

    tween.play();
}

function createGameArea()
{
	console.log('=====createGameArea');

    setCSSBack('back_' + getRandomInt(1, 3));
    showRandomStar();

    var ga = library.getSprite(null, {width: getStageWidth(), height: getStageHeight(), opacity: 0});

    ga.static = true;
    ga.setPosition(getStageWidthCenter(), getStageHeightCenter());
    ga.onmousedown = function(e)
    {
		//console.log('===================ga.onmousedown()');
		if (!Bullet.onFieldFlag && (Math.abs(e.x) < GameWorld.sideShiftWall) && !hint_flag)
		{
			Cannon.startRotation = true;
		}

        return false;
    };
    ga.onmouseup = function(e)
    {
        //console.log('===================ga.onmouseup()');
		if (!Bullet.onFieldFlag && (Math.abs(e.x) < GameWorld.sideShiftWall) && !hint_flag)
		{
			Cannon.startRotation = false;
			Bullet.createBody();
			Bullet.move();
		}

		return false;
    };
    ga.onmousemove = function(e)
    {
        //console.log('===================ga.onmousemove()');
		if (!Bullet.onFieldFlag && !hint_flag)
		{
            Cannon.startRotation = true;
			Cannon.rotate(e);
			Bullet.takeAim();
		}
    };
    stage.addChild(ga);

    gameAreaSprite = ga;

    mc = library.getSprite('btn_pause');
    mc.x = getStageWidthCenter() - 221;
    mc.y = getStageHeight() - 22;
    mc.onclick = function()
    {
        if (!pause_flag && !explosion_flag && !hint_flag)
        {
            showPause();
        }

        return false;
    };
    stage.addChild(mc);

    var btn_snd = library.getSprite('btn_sound');
    btn_snd.x = getStageWidthCenter() + 221;
    btn_snd.y = getStageHeight() - 22;
    btn_snd.scaleX = 0.74;
    btn_snd.scaleY = 0.74;
    btn_snd.music = 'game';
    btn_snd.onclick = toggleSound;
    stage.addChild(btn_snd);
    btn_snd.gotoAndStop(1);

    if (!isSoundOn)
    {
        btn_snd.gotoAndStop(0);
    }

    mc = library.getSprite('game_field');
    mc.x = getStageWidthCenter();
    mc.y = getStageHeightCenter();
    stage.addChild(mc);
    //mc.setStatic(true);

	levelText = new SimpleText(library.getBitmap('numbers_green'), 26, 18);
    levelText.x = getStageWidthCenter() - 110;
    levelText.y = getStageHeightCenter() - 147;
	levelText.scale = 0.6;
    levelText.charMap = charMap;
	levelText.charWidth = charWidthGreen;
    levelText.align = levelText.ALIGN_LEFT;
    levelText.charSpacing = -5;
    levelText.write(curLevel + 1);

    shotsText = new SimpleText(library.getBitmap('numbers_blue_mini'), 18, 10);
    shotsText.x = getStageWidthCenter() - 207;
    shotsText.y = getStageHeightCenter() - 126;
	shotsText.scale = 0.9;
    shotsText.charMap = charMap;
	shotsText.charWidth = charWidthBlueMini;
    shotsText.align = shotsText.ALIGN_CENTER;
    shotsText.charSpacing = -5;
    shotsText.write(startCountShots[curLevel]);

    multipliText = new SimpleText(library.getBitmap('numbers_blue_mini'), 18, 10);
    multipliText.x = getStageWidthCenter() + 204;
    multipliText.y = getStageHeightCenter() - 126;
	multipliText.scale = 0.9;
    multipliText.charMap = charMap;
	multipliText.charWidth = charWidthBlueMini;
    multipliText.align = multipliText.ALIGN_CENTER;
    multipliText.charSpacing = -5;
    multipliText.write('x' + scoreMultiplier);

	scoreText = new SimpleText(library.getBitmap('numbers_green'), 26, 18);
    scoreText.x = getStageWidthCenter() + 135;
    scoreText.y = getStageHeightCenter() - 147;
	scoreText.scale = 0.6;
    scoreText.charMap = charMap;
	scoreText.charWidth = charWidthGreen;
    scoreText.align = scoreText.ALIGN_CENTER;
    scoreText.charSpacing = -5;
    scoreText.write(curLevelScore.insertComma());

    buildBackground();
	GameWorld.createWorld();
}

function spritesSync(e, x, y)
{
    var p = new Vector(-e.target.syncX, -e.target.syncY);
    p.rotate(-e.target.rotation);
    e.target.x += p.x;
    e.target.y += p.y;
}

function prepareGame()
{
    console.log('=====prepareGame');

    //console.log('library = ', library.getSprite('aim').bitmap.src);

//    if ((parseInt(Utils.getCookie("sound")) == 2) || (parseInt(Utils.getCookie("sound")) == 1)) {
//    }
//    else {
//        Utils.setCookie("sound", 1);
//    }
//
//    if (parseInt(Utils.getCookie("sound")) == 1) {
//        sound = true;
//    }
//    else if (parseInt(Utils.getCookie("sound")) == 2) {
//        sound = false;
//    }

    GameBase.getPlayerScore();

    gameState = STATE_MENU;
    createScene();
}

function prepareLevel(id)
{
    if (stage)
    {
        mc = library.getSprite("hourglass");
        mc.x = getStageWidthCenter();
        mc.y = getStageHeightCenter();
        stage.addChild(mc);
    }

    //setTimeout("startLevel(" + id + ")", 20);
    startLevel(id);
}

function startLevel(id, data)
{
    console.log('=====startLevel');

    mixer.stop(0);

	if (Level.level)
    {
		id = Level.level;
	}

	console.log('level = ' + id);

    inGameMusic = true;

	GameBase.resetGameParameters();

    createStage();
    createGameArea(data ? false : true);

    var levelObjs;
    var levelJoints;

    if (data) {
        id = 0;
        levels = [data];
        gameState = STATE_GAME;
    }

    levelObjs = levels[id].objects;
    levelJoints = levels[id].joints;

    if (!levels[id])
    {
        return;
    }

    curLevel = id;
    starCouter = -1;

    if (id > openLevel)
    {
        openLevel = id;
    }

	console.log('openLevel = ' + openLevel);

    var lo, ob;
    for (var i = 0; i < levelObjs.length; i++)
    {
        lo = levelObjs[i];
        ob = GameWorld.findObject(lo.type);
        mc = GameWorld.createObject(lo, ob);
    }

   if (levelJoints)
    {
        var j, joint, stack, body1, body2;
        for (var i = 0; i < levelJoints.length; i++)
        {
            joint = levelJoints[i];
            body1 = Game.getBodyByPoint(joint.point1);
            body2 = Game.getBodyByPoint((joint.point2 ? joint.point2 : joint.point1), body1);

            if (joint.type == 0)
            {
                var options = {
                    body1: body1,
                    body2: body2,
                    point: joint.point1,
                };

                if (typeof joint.custom != "undefined")
                {
                    options.enableMotor = true;
                    options.motorSpeed = joint.custom;
                    options.maxMotorTorque = Math.PI * 2;
                }

                j = box2d.createRevoluteJoint(Game.world, options);
            }

            if (joint.type == 1)
            {
                j = box2d.createDistanceJoint(Game.world, {
                    body1: body1,
                    body2: body2,
                    point1: joint.point1,
                    point2: joint.point2
                });
            }
        }
    }

	Shots.init();
    Cannon.init();
	Crab.init();
    Bullet.init();
    Shots.show();
	countPosibleLevelScore();
    showHint();

    playMusic('game');

    stage.start();
}

function checkLevelScore()
{
	var percent = (curLevelScore * 100) / posibleLevelScore;
	var id		= -1;

	if (percent >= starPrize[0] && percent < starPrize[1])
	{
		id = 0;
	}

	if (percent >= starPrize[1] && percent < starPrize[2])
	{
		id = 1;
	}

	if (percent >= starPrize[2] && percent <= 100)
	{
		id = 2;
	}

	if (id > -1 && (starCouter < id || starCouter < 0))
	{
        console.log('percent = ' + percent);
        starCouter = id;
	}
}

function countPosibleLevelScore()
{
    var multiplier = 1;
    var count_points = 0;

    numberTouches = Elements.allCount * numberTouches;

    for (var i = 0; i < scaleScoreMultiplier.length; i++)
    {
        if (count_points + scaleScoreMultiplier[i] >= numberTouches)
        {
            multiplier = multiplierValue[i + 1];
            break;
        }

        count_points += scaleScoreMultiplier[i];
    }

    for (var i = 0; i < Elements.allCount; i++)
    {
        for (j = 0; j < prize[Elements.body[i].typeName].length; j++)
        {
            posibleLevelScore += prize[Elements.body[i].typeName][j] * multiplier;
        }
    }

	console.log('posibleLevelScore = ' + posibleLevelScore);
}

function calculateGameScore()
{
    curLevelScore = Shots.count * freeBulletPrize;

    for (var key in GameBase.elementScore)
    {
        if (!GameBase.elementScore.hasOwnProperty(key))
        {
            continue;
        }

        curLevelScore += GameBase.elementScore[key];
    }

    gameScore += curLevelScore;
}

function showExplosion(x, y, name)
{
    explosion_flag++;

    var ex = library.getSprite(name + '_explosion');

    if (!ex.bitmap)
    {
        ex = library.getSprite('explode');
        ex.bullet = true;
    }

    ex.x = x;
    ex.y = y;
    ex.animation = true;
    ex.animDelay = 3;
    ex.static = false;
    ex.onrender = function(e)
	{
        if ((e.target.currentFrame == e.target.totalFrames - 1) && (e.target.animStep == e.target.animDelay - 1))
        {
            if (e.target.currentLayer !== e.target.totalLayers - 1)
            {
                e.target.currentLayer++;
            }
            else
            {
                e.target.destroy = true;
                e.target.stop();
                explosion_flag--;
            }
        }
    };
    stage.addChild(ex);

    ex.setZIndex(0);

    playSound(ex.bullet ? 'explode_2' : 'explode_1');

    buildBackground();
}

function moveTextHitScore(text, x_start, y_start, y_end, scale)
{
    if (!text)
    {
        return;
    }

	text = '+' + text;

    t = new SimpleText(library.getBitmap('numbers_score'), 32, 32);
    t.x = x_start;
    t.y = y_start;
    t.scale = !scale ? 1 : scale;
    t.charMap = charMapScore;
	t.charWidth = charWidthScore;
    t.align = t.ALIGN_CENTER;
	t.charSpacing = -10;
    t.write(text);

    t.moveTo(
            t.x,
            y_end,
            fps / 2,
            Easing.sine.easeInOut,
            function(e)
            {
                e.target.obj.fadeTo(
                        0,
                        fps / 2,
                        Easing.sine.easeInOut,
                        function(e)
                        {
                            e.target.obj.write('');
                            delete e.target.obj;
                        });
            });

}

function moveInfoText(sprite, x_start, y_start, y_end)
{
	var inf = library.getSprite(sprite);
    inf.x = x_start;
    inf.y = y_start;
    inf.static = false;
	stage.addChild(inf);

    inf.moveTo(
            inf.x,
            y_end,
            fps / 2,
            Easing.sine.easeInOut,
            function(e)
            {
                e.target.obj.fadeTo(
                        0,
                        fps / 2,
                        Easing.sine.easeInOut,
                        function(e)
                        {
                            e.target.obj.destroy = true;
                        });
            });

}

function tremors(body)
{
    var x = body.START_POINT.x + getRandom(-0.5, 0.5);
    var y = body.START_POINT.y + getRandom(-0.5, 0.5);

    body.SetPosition(new b2Vec2(GameWorld.convertMetersToBox2d(x), GameWorld.convertMetersToBox2d(y)));
    buildBackground();
}


function toggleSound(e)
{
	if (isSoundOn)
	{
		isSoundOn = false;

		mixer.stop(0);

        e.target.gotoAndStop(0);
	}
	else
	{
		isSoundOn = true;

        playMusic(e.target.music);

        e.target.gotoAndStop(1);
	}

	return false;
}

function playSound(name)
{
    if (isSoundOn)
    {
        if (AudioMixer.isWebAudioSupport())
        {
            mixer.play(name, false, true, 1);
        }
    }
}

function playMusic(name)
{
    if (isSoundOn)
    {
        mixer.stop(0);
        mixer.play(name, true, false, 0);
    }
}


function buildBackground()
{
    if (GameWorld.world)
    {
        box2d.syncStage(GameWorld.world);
    }

    stage.refreshBackground();
}

function preTick()
{
    if (gameState == STATE_GAME && GameWorld.world && !pause_flag && !shop_flag && !hint_flag)
    {
		GameWorld.actionBeforeCalcWorld();
        Bullet.setBulletVectorForRocket();

        GameWorld.world.Step(1/fps, 10, 10);
        box2d.syncStage(GameWorld.world);

		Crab.move();

        for (var e = 0; e < Elements.body.length; e++)
        {
            if (Elements.sprite[e] && Elements.sprite[e].touchesInOneShot > 0 && (Elements.body[e].type == ASTEROID || Elements.body[e].type == CRYSTAL))
            {
                tremors(Elements.body[e]);
            }
        }

		checkLevelScore();

		shotsText.write(Shots.count);
		scoreText.write(curLevelScore.insertComma());
        multipliText.write('x' + scoreMultiplier);

        for (var p = 0; p < Bullet.sprite.length; p++)
		{
            Bullet.checkCoor(p);
		}

		if (!Elements.count)
		{
			if (!timeInterval)
			{
				timeInterval = setInterval(function()
				{
					if (!explosion_flag && !animation_star_flag)
					{
						clearInterval(timeInterval);
						timeInterval = null;
						levelStars[curLevel] = starCouter + 1;

                        calculateGameScore();

                        gameState = STATE_LEVEL_CLEARED;
						createScene();

						return;
					}
				}, 20);
			}

			return;
		}

		if (Elements.count && !Shots.count && !Bullet.onFieldFlag)
		{
			if (!timeInterval)
			{
				timeInterval = setInterval(function()
				{
					if (!explosion_flag && !animation_star_flag)
					{
						clearInterval(timeInterval);
						timeInterval = null;

                        gameState = STATE_LEVEL_FAILED;
						createScene();

						return;
					}
				}, 20);
			}

			return;
		}
    }
}

function postTick()
{
    if (gameState == STATE_GAME && GameWorld.world && !pause_flag)
    {
//		if (fish_array && showDebugDraw)
//		{
//			for (var i = 0; i < fish_array.length; i++)
//			{
//				stage.drawCircle(fish_array[i].x, fish_array[i].y, 10, 2, '#F0F');
//			}
//		}
	}
/*
    if (!showDebugDraw) {
        return;
    }
*/
    if (GameWorld.world && showDebugDraw)
    {
        GameWorld.world.DrawDebugData();
    }
}

