function ext_achievement_submit(name)
--     print(name)

    g2_ext_call("legends:achievement",json.encode({aid=name}))
end

function ext_leaderboard_submit(lid,ltitle,tm,rank,points)
    if GLOBAL.cheater == true then return end

    local data = {
        lid = lid,
        ltitle = ltitle,
        tm = tm,
        rank = rank,
        points = points
    }
--     for k,v in pairs(data) do print(k,v) end
    g2_ext_call("legends:scores",json.encode(data))
end

-- determine score based on time taken and rank
function get_score(time, rank)
--     return math.floor(1000*rank + 10000/time + 0.5)
    local t1 = math.min(300.0,time)
    local t2 = math.max(0,time-300.0)
    local score = 5000 + (500 * rank) + (-15 * t1) + (-1 * t2)
    return math.max(5,math.floor(score))
end

-- update leaderboards with current score
-- return true if new record
function add_leaderboard_score(score, time)
    ext_leaderboard_submit(GLOBAL.current_level,GLOBAL.current_level,
        time,GLOBAL.current_difficulty,get_score(time,GLOBAL.current_difficulty))

    local entry = GLOBAL.leaderboard[GLOBAL.current_level]
    local new_record = true
    if entry[1] ~= nil then
        if entry[1].score >= score then
            new_record = false
        end
    end
    entry[#entry+1] = {date=os.time(),time=time,rank=GLOBAL.current_difficulty,score=score}
    table.sort(entry, function(s1,s2) if s1 ~= nil and s2 ~= nil then if s1.score > s2.score then return true end end end)
    if #entry > GLOBAL.max_leaderboard_size then entry[#entry] = nil end
    return new_record
end