--Galcon Legends v0.11.3 by Evan Sparano
--(c) 2013 Phil Hassey, all rights reserved

require("gq_animation")
require("gq_gamemodes")
require("gq_bots")
require("gq_util")
require("gq_mapgen")
require("gq_data")
require("gq_leaderboards")

require("gq_about")
require("gq_title")
require("gq_tutorial")
require("gq_highs")
require("gq_engine")


-- first initialization of the entire mod
function gq_init()
    -- set up global constants
    GLOBAL = {
        version = "v0.12", -- not updated at the moment so people's data isn't erased
        player_color=0x00ff00,
        --sw=800,
        --sh=600,
        --scale_f = 800/2048, 
        sw=800,
        sh=600,
        scale_f = 800/2048,
        play_sw=720,
        play_sh=480,
        --map_sw=800,
        --map_sh=600,
        horizon=20, -- how many seconds into the future fair map generation is optimized for
        tolerance=1.1, -- 1 means maps are perfectly equal (not recommended), 1.1 means maps can differ by 0.1 "goodness"... lol
        min_map_value=10, -- higher values favor maps with larger, cheaper planets
        max_leaderboard_size = 1,   
	}

	-- load saved data
    load()
    
    -- uncomment to totally reset game
	--reset()
end

-- erase saved game data
function reset()
    g2.data = json.encode({})
    g2.state = "quit"
end


-- load game state
function load()
    local data = json.decode(g2.data)
    -- BY DEFAULT THIS WILL ERASE SAVED DATA IF VERSION IS NOT CORRECT. 
    -- Watch out if there is an update after production because players' data will be lost.
    local is_correct_version = false
    if data ~= nil then
        if data.version == GLOBAL.version then
            is_correct_version = true
        end
    end
    if data == nil or g2.data == "[]" or not is_correct_version then
        GLOBAL.highest_level = 1
        GLOBAL.current_difficulty = 1
        GLOBAL.highest_difficulty = 1
        GLOBAL.highest_ranks = {}
        for i=1,23 do
            GLOBAL.highest_ranks[i] = 0
        end
        GLOBAL.has_completed_tutorial = {}
        for i=1,3 do
            GLOBAL.has_completed_tutorial[i] = 0
        end
        GLOBAL.leaderboard = {}
        for i=1,23 do
            GLOBAL.leaderboard[i] = {}
        end
    else 
        GLOBAL.highest_level = data.highest_level
        GLOBAL.current_difficulty = data.current_difficulty
        GLOBAL.highest_difficulty = data.highest_difficulty
        GLOBAL.highest_ranks = data.highest_ranks
        GLOBAL.has_completed_tutorial = data.has_completed_tutorial
        GLOBAL.leaderboard = data.leaderboard
    end
    
    if GLOBAL.current_difficulty <= 1 then
        init_intro()
    else
        init_map()
    end
end

-- save game state
function save()
    g2.data = json.encode({
        highest_level = GLOBAL.highest_level,
        current_difficulty = GLOBAL.current_difficulty,
        highest_difficulty = GLOBAL.highest_difficulty,
        highest_ranks = GLOBAL.highest_ranks,
        has_completed_tutorial = GLOBAL.has_completed_tutorial,
        leaderboard = GLOBAL.leaderboard,
        version = GLOBAL.version
    })
end

-- start the actual game in a level
function init_game()
    local level = LEVELS[GLOBAL.current_level]
    g2.game_reset()
    g2.bkgr_src = level.background_image
    g2.play_music(level.music)
    math.randomseed(GLOBAL.seed)
    GAME.win_timer = GAME.WIN_TIMER_RESET

    GLOBAL.animations = {}
    GLOBAL.click_animations = {}
    GLOBAL.click_queue = {}
    GLOBAL.t = 0
    GLOBAL.state = "game"
    
    local user = g2.new_user("neutral",0x555555)
    user.user_neutral = 1
    user.ships_production_enabled = 0
    GAME.user_neutral = user   

    local use_team1 = false
    
    if level.teams ~= nil then
        for k,v in pairs(level.teams) do
            if v == 1 then
                use_team1 = true
            end
        end
        if use_team1 then
            GAME.team1 = g2.new_team("allies",0x0000ff)
            GAME.team1.has_player = true
        end
        GAME.team2 = g2.new_team("enemies",0xff0000)
    end
    
    user = g2.new_user("Buck", GLOBAL.player_color, GAME.team1)
    user.user_rank = string.format("%x",GLOBAL.current_difficulty)
    if RANKS[GLOBAL.current_difficulty].show_ships == 1 then user.ui_ships_show_mask = 0xf end
    g2.player = user
    GAME.player = user
    
    if use_team1 == false then
        GAME.team1 = user
    end

    GAME.bots = {} -- contains (bot)users, not bot_data arrays
    GAME.bot_ts = {}
    for i=1,#level.bots do
        local bot = get_bot_data(level.bots[i])
        local team = nil
        if level.teams ~= nil then team = _ENV["GAME"]["team"..level.teams[i]] end
        local user_bot = g2.new_user(bot.name, bot.color, team)
        user_bot.has_player = false
        if bot.name == "The Phantom" then user_bot.fleet_color = 0x000000 end
        if bot.name == "Banjo King" then user_bot.fleet_v_factor = 3 end
        GAME.bots[i] = user_bot
    end
    for i,_bot in ipairs(GAME.bots) do
        GAME.bot_ts[i] = 0
    end
    
    _ENV["init_"..level.game_mode]() 
    
    g2.planets_settle(0,0,GLOBAL.play_sw,GLOBAL.play_sh)
    --g2.view_set(0,0,GLOBAL.play_sw,GLOBAL.play_sh)
    
    do_tutorial(GLOBAL.current_level)
        
    g2.state = "pause"
    init_getready()
end

function gq_event(e)
    if e.type == 'quit' then
        if GLOBAL.state == "map" then
            ENGINE.engine:next(ENGINE.modules.title)
        else
            init_map()
        end
        g2.quit = false
        return
    end
    
    if (e.type == 'ui:down' or e.type == 'ui:motion') and g2.state == 'scene' and GLOBAL.state == "map" then 
        if GLOBAL.map_label ~= nil then
            GLOBAL.map_label:destroy()
            GLOBAL.map_label = nil
        end
        local level = get_planet_at({x=e.x,y=e.y})
        local next_n = GLOBAL.highest_level
        if level ~= nil and next_n ~= level then
            local label = nil 
            local sf = GLOBAL.scale_f
            local pad = 12
            local title = level .. ". "..LEVELS[level].title
            if GLOBAL.map == "A" and level >= 1 and level <= 18 then
                if level < 12 then
                    label = g2.new_label(title,PLANETS[level].x*sf + pad,PLANETS[level].y*sf, 0xffffff)
                    label.label_align = 1
                else
                    label = g2.new_label(title,PLANETS[level].x*sf - pad,PLANETS[level].y*sf, 0xffffff)
                    label.label_align = -1
                end
            end
            if GLOBAL.map == "B" and level >= 19 and level <= 23 then
                if level < 23 then
                    label = g2.new_label(title,PLANETS[level].x*sf + pad,PLANETS[level].y*sf, 0xffffff)
                    label.label_align = 1
                else
                    label = g2.new_label(title,PLANETS[level].x*sf - pad,PLANETS[level].y*sf, 0xffffff)
                    label.label_align = -1
                end
            end
            
            if label then 
                label.label_size = 30
                GLOBAL.map_label = label 
            end
        end
    end
                

    if e.type == "ui:up" and g2.state == "scene" then
        -- click_animations have to run out before advancing to the game/level/map
        if #GLOBAL.click_animations == 0 or GLOBAL.state == "map" then
            -- also make sure animations aren't cut off prematurely
            if GLOBAL.state == "intro" then
                init_map()
            elseif GLOBAL.state == "ending" and #GLOBAL.animations == 0 then
                init_map()
            elseif GLOBAL.state == "map" then       
                -- user wants to change difficulty
                if e.x >= 49 - 10 and e.x <= 49 + 39 + 10 and e.y >= 60 - 10 and e.y <= 60 + 39 + 10 then
                    g2.state = "dialog"
                    init_change_difficulty()
                else
                    local level = get_planet_at({x=e.x,y=e.y})
                    -- user has clicked on a planet and can start a level
                    if level ~= nil then
                        init_level(level)
                    else
                        local sf = GLOBAL.scale_f
                        local w 
                        if GLOBAL.map == "A" then w = WORMHOLES[1] else w = WORMHOLES[2] end
                        -- user has clicked on the wormhole
                        if dist(e.x, e.y, w.x*sf, w.y*sf) < (w.r+10)*sf then
                            if GLOBAL.map == "A" and GLOBAL.highest_level > 18 then
                                init_map("B")
                            elseif GLOBAL.map == "B" then
                                init_map("A")
                            end
                        end
                    end
                end
            elseif GLOBAL.state == "pre_game" then
                init_game()
            elseif GLOBAL.state == "post_game" and #GLOBAL.animations == 0 then
                if GAME.won then
                    -- update leaderboards/achievements/etc.
                    local time = math.floor(100*GLOBAL.finish_t + 0.5)/100 -- round to nearest hundredth of a second
                    local score = get_score(time, GLOBAL.current_difficulty)
                    local new_record = add_leaderboard_score(score, time)
                    update_achievements() 
                    local level = LEVELS[GLOBAL.current_level]
                    if level.ach ~= nil then
                        ext_achievement_submit(level.ach)
                    end
                    save()
                    g2.state = "dialog"
                    init_win_prompt(score, time, new_record)
                else
                    g2.state = "dialog"
                    init_lose_prompt()
                end
            end
        else
            if #GLOBAL.animations == 0 then
                -- activate click animations
                while #GLOBAL.click_animations > 0 do
                    local ca = table.remove(GLOBAL.click_animations,1)
                    table.insert(GLOBAL.animations, {object=ca.object,start_t=GLOBAL.t+ca.start_t,end_t=GLOBAL.t+ca.end_t,actions=ca.actions})
                    if ca.stop then break end
                end
            else -- if the user is spam-clicking, don't cut the animations off but remember they clicked
                GLOBAL.click_queue[#GLOBAL.click_queue + 1] = e
            end
        end
    end
    
    if (e["type"] == "onclick" and e["value"] == "newmap") then
        GLOBAL.seed = os.time();
        init_game();
        init_getready();
        g2.state = "pause"
    end
    if (e["type"] == "onclick" and e["value"] == "leaderboard") then
        g2_ext_call("legends:leaderboard",json.encode({lid=GLOBAL.current_level}))
    end
    if (e["type"] == "onclick" and e["value"]:find("leaderboard:") == 1) then
        local q = e.value:sub(e.value:find(":")+1,-1)
        g2_ext_call("legends:leaderboard",json.encode({lid=GLOBAL.current_level,q=q}))
    end
    if (e["type"] == "onclick" and e["value"] == "leaderboard_back") then
        -- update leaderboards/achievements/etc.
        local time = math.floor(100*GLOBAL.finish_t + 0.5)/100 -- round to nearest hundredth of a second
        local score = get_score(time, GLOBAL.current_difficulty)
        g2.state = "dialog"
        init_win_prompt(score, time, false)
    end

    if (e["type"] == "api:leaderboard") then
        g2.state = "dialog"
        g2.html = "<table>"..
            "<tr><td><input type='button' class='button2' value='Back' onclick='leaderboard_back' />"..
            "<tr><td><h3>&nbsp;</h3>"..
            "<tr><td>"..e.value..
            "<tr><td><h3>&nbsp;</h3>"..
            "<tr><td><input type='button' class='button2' value='Back' onclick='leaderboard_back' />"..
            "</table>"
    end
    if (e["type"] == "onclick" and e["value"] == "restart") then
        init_game();
        init_getready();
        g2.state = "pause"
    end
    if (e["type"] == "onclick" and e["value"] == "resume_game") then
        g2.state = "play"
    end
    if (e["type"] == "onclick" and e["value"] == "resume_scene") then
        g2.state = "scene"
    end
    if (e["type"] == "onclick" and e["value"] == "back_to_map") then
        init_map()
    end
    if e["type"] == "onclick" and e["value"] == "back_to_title" then
        ENGINE.engine:next(ENGINE.modules.title)
    end
    if (e["type"] == "onclick" and e["value"] == "raise_difficulty") then
        GLOBAL.current_difficulty = GLOBAL.current_difficulty + 1
        if GLOBAL.current_difficulty > GLOBAL.highest_difficulty then GLOBAL.highest_difficulty = GLOBAL.current_difficulty end
        save()
        if GAME.won and GLOBAL.highest_level == 19 and GLOBAL.current_level == 18 then
            init_map("B")
        else
            init_map()
        end
    end
    if (e["type"] == "onclick" and e["value"] == "lower_difficulty") then
        GLOBAL.current_difficulty = GLOBAL.current_difficulty - 1
        save()
        init_map()
    end
    if (e["type"] == "onclick" and e["value"] == "init_change_difficulty") then
        init_change_difficulty()
    end
    if (e["type"] == "onclick" and e["value"] == "init_lose_prompt") then
        init_lose_prompt()
    end
    if (e["type"] == "onclick" and string.find(e["value"],"change_difficulty:") ~= nil) then
        GLOBAL.current_difficulty = tonumber(string.sub(e["value"],19))
        save()
        if GAME ~= nil then 
            init_game()
        else
            init_map()
        end
    end
    if (e["type"] == "onclick" and e["value"] == "continue") then
        -- change map if user beat level 18
        if GAME.won and GLOBAL.highest_level == 19 and GLOBAL.current_level == 18 then
            GLOBAL.map = "B"
        end
        -- if they beat the 23rd level, play the ending animation
        if GLOBAL.current_level == 23 and GAME.won then 
            init_ending() 
        -- otherwise, go back to the map
        elseif GAME.won and GLOBAL.current_difficulty < 10 then
            init_raise_difficulty()
            g2.state = "dialog"
        elseif not GAME.won and GLOBAL.current_difficulty > 1 then
            init_lower_difficulty()
            g2.state = "dialog"
        else
            init_map()
        end
    end
    if (e["type"] == "pause") then
        init_pause();
    end
end

-- return planet index closest to user click
function get_planet_at(point)
--     local PLANET_SELECTION_FORGIVENESS = 37 -- radius in pixels from planet that will still pick up the click
    local PLANET_SELECTION_FORGIVENESS = 60 -- radius in pixels from planet that will still pick up the click
    local closest_dist = 1000000000000000
    local closest_i
    local sf = GLOBAL.scale_f
    for i,planet in ipairs(PLANETS) do
        if (GLOBAL.map == "A" and i < 19) or (GLOBAL.map == "B" and i > 18) then
            local dist = dist(point.x, point.y, planet.x*sf, planet.y*sf)
            if dist < (planet.r + PLANET_SELECTION_FORGIVENESS)*sf and dist < closest_dist and i <= GLOBAL.highest_level then 
                closest_dist = dist
                closest_i = i
            end
        end
    end
    return closest_i
end

function cheat()
    local planets = g2.search("planet -neutral")
    GLOBAL.cheater = true
    for k,o in pairs(planets) do
        o:planet_chown(GAME.player)
    end
end

-- GAME UTILITY FUNCTIONS ------------------------------------------------------

function _winner_planets()
    local win = nil;
    local planets = g2.search("planet -neutral")
    for _i,p in ipairs(planets) do
        local team = p:owner():team()
        if (win == nil) then win = team end
        if (win ~= team) then return nil end
    end
    return win
end

function _winner_ships(team)
    local items = g2.search("planet OR fleet -neutral")
    local us = 0
    local them = 0
    for _i,p in ipairs(items) do
        if p:owner():team() == team then us = us + p.ships_value + p.fleet_ships 
        else them = them + p.ships_value + p.fleet_ships end
    end
    return (us >= (them * 2))
end

function get_winner()
    local win = _winner_planets()
    if win == nil then return nil end
    if not _winner_ships(win) then return nil end
    return win
end

---------------------------------------------------------------------------------

function gq_loop(t)
    GLOBAL.t = GLOBAL.t + t
    
    -- process any pending clicks
    if #GLOBAL.click_queue > 0 and #GLOBAL.animations == 0 then
        click = GLOBAL.click_queue[#GLOBAL.click_queue]
        GLOBAL.click_queue[#GLOBAL.click_queue] = nil
        event(click)
    end
    
    -- play any queued animations
    for i,animation in ipairs(GLOBAL.animations) do
        if GLOBAL.t > animation.end_t then
            do_animation(animation,t)
            table.remove(GLOBAL.animations, i)
            GLOBAL.click_queue = {GLOBAL.click_queue[1]}
        elseif GLOBAL.t >= animation.start_t then
            do_animation(animation,t)
        end
    end
    
    if GLOBAL.state == "map" then
        -- wormhole animation
        if GLOBAL.wormholes ~= nil then
            local w
            if GLOBAL.map == "A" then w = WORMHOLES[1] else w = WORMHOLES[2] end
            for i=1,3 do
                GLOBAL.wormholes[i].image.image_a = GLOBAL.wormholes[i].image.image_a + GLOBAL.wormholes[i].rot_speed
            end
        end
        -- glowing star
        if GLOBAL.star ~= nil then
            if GLOBAL.star.render_alpha == 255 then
                GLOBAL.star_coeff = -1
            elseif GLOBAL.star.render_alpha < 100 then
                GLOBAL.star_coeff = 1
            end
            GLOBAL.star.render_alpha = GLOBAL.star.render_alpha + 3*GLOBAL.star_coeff
        end
    end
    
    if g2.state ~= "play" then return end
    
    -- bot AI
    local level = LEVELS[GLOBAL.current_level]
    -- update GLOBAL.finish
    if level.teams ~= nil then
        if count_ships(GAME.team2) > count_ships(GAME.team1)*2 then 
            GLOBAL.finish = true 
        else
            GLOBAL.finish = false
        end
    else
        -- account for 3+ teams in FFA games too
        local total_ships = count_ships(GAME.player:team())
        for i,user in ipairs(GAME.bots) do
            total_ships = total_ships + count_ships(user:team())
        end
        for i,user in ipairs(GAME.bots) do
            if count_ships(user:team()) > total_ships*2/3 then 
                GLOBAL.finish = true 
                break
            else
                GLOBAL.finish = false
            end
        end
    end
    -- bot loops
    for i,name in ipairs(level.bots) do
        local data = get_bot_data(name)
        GAME.bot_ts[i] = GAME.bot_ts[i] + t
        if (GAME.bot_ts[i] >= data.wait[GLOBAL.current_difficulty]) then
            GAME.bot_ts[i] = GAME.bot_ts[i] - data.wait[GLOBAL.current_difficulty]
            if _ENV[data.loop] ~= nil then
                _ENV[data.loop](GAME.bots[i])
            end
        end
    end
    
    -- game-mode-specific loops
    local m = level.game_mode
    if m == "vacuum" then loop_vacuum(t) return end
    if m == "grinder" or m == "seduction" then loop_grinder(t) end
    if m == "wormhole" or m == "invasion" or m == "armistice" or m == "orbit" then _ENV["loop_"..m](t) end

    -- test whether any one team controls all planets
--     local win = nil
--     local planets = g2.search("planet -neutral")
--     for _i,p in ipairs(planets) do
--         local team = p:owner():team()
--         if (win == nil) then win = team end
--         if (GLOBAL.current_level == 5) then
--             if (win ~= team and (win == g2.item(g2.player):team() or team == g2.item(g2.player):team())) then
--                 GAME.win_timer = GAME.WIN_TIMER_RESET
--                 return 
--             end
--         elseif (win ~= team) then 
--             GAME.win_timer = GAME.WIN_TIMER_RESET
--             return 
--         end
--     end
    
    local win = get_winner()
    if (GLOBAL.current_level == 5 or GLOBAL.current_level == 14) then
        local items = g2.search("planet team:"..g2.item(g2.player):team())
        if #items == 0 then win = GAME.bots[1]:team() end
    end
    if win == nil then
        GAME.win_timer = GAME.WIN_TIMER_RESET
        return
    end
    
    
    GAME.win_timer = GAME.win_timer - t
    if GAME.win_timer > 0 then return end
    if (win ~= nil) then
        if (win.has_player == true) then
            -- make sure not to end wormhole games prematurely
            if level.game_mode == "wormhole" then 
                if (GAME.wave_num < 3) or (GAME.wave_num == 3 and GAME.time_left > 20) then return end
            end
            GAME.won = true
            -- update important data since game was won
            if GLOBAL.current_level == GLOBAL.highest_level and GLOBAL.highest_level < 24 then 
                GLOBAL.highest_level = GLOBAL.highest_level + 1 
            end
            if GLOBAL.current_difficulty > GLOBAL.highest_ranks[GLOBAL.current_level] then
                GLOBAL.highest_ranks[GLOBAL.current_level] = GLOBAL.current_difficulty
            end
            if GLOBAL.has_completed_tutorial[GLOBAL.current_level] ~= 1 and GLOBAL.current_level < 4 then 
                GLOBAL.has_completed_tutorial[GLOBAL.current_level] = 1
            end
            if GLOBAL.current_difficulty == GLOBAL.highest_difficulty and GLOBAL.highest_difficulty < 10 then
                GLOBAL.highest_difficulty = GLOBAL.highest_difficulty + 1
            end
            save()
        else
            -- if the player still has any fleets, the game should not end
            local fleets = g2.search("fleet owner:"..GAME.player.n)
            if #fleets > 0 then return end
            -- make sure not to end invasion games prematurely
            if level.game_mode == "invasion" then 
                if (GAME.wave_num < 3) or (GAME.wave_num == 3 and GAME.time_left > 20) then return end
            end
            GAME.won = false
        end
        init_post_game()
    end
end

-- every time the player completes a level, 
function update_achievements()
    local highest_difficulty = 10
    for level=1,23 do
        if GLOBAL.highest_ranks[level] < highest_difficulty then 
            highest_difficulty = GLOBAL.highest_ranks[level]
        end            
    end
    for rank=1,highest_difficulty do
        ext_achievement_submit("rank"..tostring(rank))
--         ext_achievement_submit(RANKS[rank].full_name.." Complete")   
    end  
end

function init_getready()
    g2.html = "<table>"..
    "<tr><td><h3 align=center width=320>"..MESSAGES[GLOBAL.current_level].."\n</h3>"..
    "<tr><td><input type='button' value='Tap to Begin' onclick='resume_game' />"
end

function init_win_prompt(score, time, new_record)
    g2.html = "<table>"..
--     "<tr><td><h1>Good Job!</h1>"..
--     "<tr><td><h3>&nbsp;</h3>"..
    "<tr><td><h3>Time: "..math.floor(time/60)..":"..zero_pad(math.floor(time%60)).."."..zero_pad(math.floor((time%1)*100))..
    "<tr><td><h3>Score: "..score.." points</h3>"
    local entry = GLOBAL.leaderboard[GLOBAL.current_level][1]
    if new_record then 
        g2.html = g2.html .. "<tr><td><h3>New record!</h3>"
    else
        g2.html = g2.html .. "<tr><td><h3>Your best time: "..math.floor(entry.time/60)..":"..zero_pad(math.floor(entry.time%60)).."."..zero_pad(math.floor((entry.time%1)*100))
        g2.html = g2.html .. "<tr><td><h3>Your best score: "..entry.score.." points</h3>"
    end
    g2.html = g2.html ..
    "<tr><td><h3>&nbsp;</h3>"..
    "<tr><td><input type='button' class='button2' value='Continue' onclick='continue' />"..
    "<tr><td><input type='button' value='Leaderboard' onclick='leaderboard' />"..
    "<tr><td><input type='button' value='Replay' onclick='restart' />"..
    "<tr><td><input type='button' value='New Map' onclick='newmap' />"..
    ""
end

function init_lose_prompt()
    g2.html = "<table>"..
    "<tr><td><input type='button' class='button2' value='Try Again' onclick='restart' />"..
    "<tr><td><input type='button' value='New Map' onclick='newmap' />"..
    "<tr><td><input type='button' value='Change Rank' onclick='init_change_difficulty' />"..
    "<tr><td><input type='button' value='Back to Galaxy' onclick='continue' />"
end

function init_pause() 
    g2.html = "<table>"
    -- user has clicked pause during a game
    if g2.state == "play" then
        g2.html = g2.html .. 
        "<tr><td><input type='button' value='Resume' onclick='resume_game' />"..
        "<tr><td><input type='button' value='Restart' onclick='restart' />"..
        "<tr><td><input type='button' value='New Map' onclick='newmap' />"..
        "<tr><td><input type='button' value='Back to Galaxy' onclick='back_to_map' />"
    elseif g2.state == "scene" then
        -- user has clicked during map or pre/post-game scene
        g2.html = g2.html .. "<tr><td><input type='button' value='Resume' onclick='resume_scene' />"
        if GLOBAL.state ~= "intro" then
            if GLOBAL.state ~= "map" then
                g2.html = g2.html .. "<tr><td><input type='button' value='Back to Galaxy' onclick='back_to_map' />"
            end
            if GLOBAL.state == "map" then
                g2.html = g2.html .. "<tr><td><input type='button' value='Back to Menu' onclick='back_to_title' />"
            end
        end
    end
end

function xinit_raise_difficulty()
g2.html = "<table>"..
"<tr><td><h2>Current Rank</h2></td></tr>"..
"<tr><td colspan=30><input type='image' src='rank"..GLOBAL.current_difficulty..".png' width=75 height=75 onclick='' /></td>"..
"<tr><td><p>&nbsp;</p></tr>"..
"<tr><td><h2 align=center>Feeling awesome?\nRaise the challenge.</h2>"..
"<tr><td><input type='button' value='Yes' onclick='raise_difficulty' />"..
"<tr><td><input type='button' value='No' onclick='back_to_map' />"
end

function xinit_lower_difficulty()
g2.html = "<table>"..
"<tr><td><h2>Current Rank</h2></td></tr>"..
"<tr><td colspan=30><input type='image' src='rank"..GLOBAL.current_difficulty..".png' width=75 height=75 onclick='' /></td>"..
"<tr><td><p>&nbsp;</p></tr>"..
"<tr><td><h2 align=center>Feeling defeated?\nLower the challenge.</h2>"..
"<tr><td><input type='button' value='Yes' onclick='lower_difficulty' />"..
"<tr><td><input type='button' value='No' onclick='back_to_map' />"
end

function init_raise_difficulty()
    local html = "<table>"..
    "<tr><td><h2>Not bad for a $RANKNAME.</h2></td></tr>"..
    "<tr><td colspan=30><input type='image' src='rank"..GLOBAL.current_difficulty..".png' width=75 height=75 onclick='' /></td>"..
    "<tr><td><h2 align=center>Time to turn up the heat!\nIncrease your rank?</h2>"..
    "<tr><td><p>&nbsp;</p></tr>"..
    "<tr><td><input type='button' value='Yes' onclick='raise_difficulty' />"..
    "<tr><td><input type='button' value='No' onclick='back_to_map' />"
    html = html:gsub("$RANKNAME",RANKS[GLOBAL.current_difficulty].full_name)
    g2.html = html

end

function init_lower_difficulty()
    local html = "<table>"..
    "<tr><td><h2>$RANKNAME a bit too tough?</h2></td></tr>"..
    "<tr><td colspan=30><input type='image' src='rank"..GLOBAL.current_difficulty..".png' width=75 height=75 onclick='' /></td>"..
    "<tr><td><h2 align=center>Cool things down a bit.\nLower your rank?</h2>"..
    "<tr><td><p>&nbsp;</p></tr>"..
    "<tr><td><input type='button' value='Yes' onclick='lower_difficulty' />"..
    "<tr><td><input type='button' value='No' onclick='back_to_map' />"
    html = html:gsub("$RANKNAME",RANKS[GLOBAL.current_difficulty].full_name)
    g2.html = html
end

function init_change_difficulty()
    g2.html = "<table>"..
    "<tr><td><h2>Change Rank</h2></td></tr>"..
--     "<tr><td><p>&nbsp;</tr>"..
--     "<tr><td colspan=30><h2>Current Rank</h2></td></tr>"..
    "<tr><td colspan=30><input type='image' src='rank"..GLOBAL.current_difficulty..".png' width=75 height=75 onclick='' /></td>"..
    "<tr><td><p>&nbsp;</tr>"..
    "<tr><td><h2>Choose a Rank</h2></td></tr>"..
--     "<tr><td><p>&nbsp;</tr>"..
    "<tr><td><table><tr>"
    for i=1,GLOBAL.highest_difficulty do
        if i == 6 then 
            g2.html = g2.html.."</tr><tr>" 
        end
        g2.html = g2.html.."<td colspan=30><input type='image' src='rank"..i..".png' width=25 height=25 onclick='change_difficulty:"..i.."' /></td>"
    end
    g2.html = g2.html .. "<tr><td><p>&nbsp;</tr>"
    if GAME ~= nil then
        g2.html = g2.html .. "</tr></table><tr><td><input type='button' value='Back' onclick='init_lose_prompt' />"
    else 
        g2.html = g2.html .. "</tr></table><tr><td><input type='button' value='Back' onclick='back_to_map' />"
    end
end