<!doctype html>
{% macro render_field(field, game) %}
  {%- if field.type == "Heading" -%}
      <tr><td colspan=4>{{-field(**kwargs)|safe-}}</td>
  {%- else -%}
      <tr data-expandedby="{{game.form_expanded_by[field.name]}}" class="{{'expanded' if game.form_expanded_by[field.name] else ''}}">
          <td class="not-i td-label">{%- if field.name != "submit" -%}{{- field.label -}}{%- endif -%}</td>
          <td>
            {% if field.description %}
              <span class="help help-popup" data-content="{{field.description}}">🛈</span>
            {% endif %}
          </td>
          <td class="not-i td-input">{{ field(**kwargs)|safe }}
          {% if field.errors %}
            <ul class=errors>
            {% for error in field.errors %}
              <li>{{ error }}</li>
            {% endfor %}
            </ul>
          {% endif %}
          </td>
      </tr>
  {%- endif -%}
{% endmacro %}
<html>
<head>
    <meta charset="utf-8">
    <title>Online Randomizer!</title>
    <meta name="viewport" content="width=device-width">
    <link href="static/css/semantic.min.css" rel="stylesheet" type="text/css" media="all">
    <style>

html {background: #ddd; color: #222; font-family: sans-serif;}
body {margin: auto; max-width: 800px;  padding: 12px;}
.main {background: white; padding: 12px; border-radius:8px; position:relative;}
.about {background: #f2f2f2; padding: 12px; border-radius:8px; position:relative; margin:16px;}
dt {/*font-weight:bold;*/ float:left; width:50%; clear:left;}
dt::after {content:'';}

.logo {text-align: center;}
h1 .randomized-games-logo {max-width: 100%;}

code {font-size:12px;}

#randomizer_options {margin-top: 8px;}
/*#options {border: 1px solid #aaa; padding:6px;}*/

/*footer {border-top: 1px solid #aaa; margin-top:12px; padding-top:6px;}*/

input {background: white;}

h4 {margin: 0;}

/*i.popup {cursor: default; margin-right:10px !important;}*/

table {border-collapse:collapse;}
td.not-i {width: 50%;}
td {vertical-align: top; border-bottom: 1px solid #eee;}
/*tr.expanded .td-label {padding-left:8px;}*/
tr.expanded .td-label {padding-left:12px;}

form table ul {margin:0; padding:0; list-style-type: none;}
form table ul li {margin:0; padding:0; display:inline;}

i.icon {opacity:0.5; cursor:default;}

p {text-indent:4%;}

.unstable {font-weight:bold !important; font-size:16px !important; cursor: default;}

.help-popup {cursor: default;  color: green;}

.big-presets .button-big-preset {color: #333; text-transform: none; font-weight: normal; 
    text-align: left; width: 100%;
    margin-bottom: 4px;}

.button-presets {margin-bottom: 8px !important;}

h4 {margin-bottom: 6px;}

button:disabled {cursor: default;}

    </style>
    
    <!--<script src="http://code.jquery.com/jquery-1.11.1.js"></script>-->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="static/javascript/semantic.js"></script>
    <script>

var games = {{games_json | safe}}
var curgame
var generating = false
var options_showed = false

function showgamelogo(gameid) {
    for (gameid_ in games) {
        if (gameid_ == gameid) {
            $("#game-logo-" + gameid_).show()
        } else {
            $("#game-logo-" + gameid_).hide()
        }
    }
}

function render_options(gameid, instant) {
    console.log(gameid)
    $("#btn-pickanother").show()
    $("#games").hide()
    $('#btn-generate').hide();
    showgamelogo(gameid)
    curgame = gameid
    for (gameid_ in games) {
        if (gameid_ != gameid ) {
            $("#options-"+gameid_).hide()
        }
    }
    //$("#options").show()
    //$("#options_controls").show()
    //$("#controls").show()
    $('#main-controls').show();
    $('#big-presets-'+gameid).show();
    if (instant) {
        $("#randomizer_options").show()
        $("#options-"+gameid).show()
        options_showed = true
    } else {
        if (!options_showed) {
            $("#randomizer_options").fadeIn(500)
            $("#options-"+gameid).show()
            options_showed = true
        }
        else {
            $("#options-"+gameid).fadeIn(500)
        }
    }
    window.location.hash = curgame
}

function pickanother() {
    $("#btn-pickanother").hide()
    $("#games").show()
    showgamelogo("")
    $("#randomizer_options").hide()
    options_showed = false;
}

function set_preset(presetid) {
    $('#options input').prop('checked', false)
    preset = games[curgame].presets[presetid]
    console.log(preset)
    for (option in preset) {
        if (preset[option] === true || preset[option] === false) {
            $("#"+option).prop('checked', preset[option])
        } else {
            $("#"+option).val(preset[option])
        }
    }
    update_all_expanded()
    // update_all_expanded has checked everyting newly expanded
    // even if it was unchecked above
    // Until this is fixed, we need to do two iterations
    for (option in preset) {
        if (preset[option] === false) {
            $("#"+option).prop('checked', false)
        }
    }
}

function generate() {
    if (!generating) {
        $("#btn-generate").addClass('loading')
        generating = true
        //$("#btn-generate").click(function(){})
        $("#generating").show()
        $("#generating").html('Generating...')
        $.post('generate', $("#form-"+curgame+", #filename").serialize(), generated, 'json').fail(oops)
    }
}

function generated(data) {
    generating = false
    if (data.error) {
        $("#btn-generate").removeClass('loading')
        $("#btn-generate").show()
        if (data.error == "cooldown") {
            $("#generating").html("Please wait " + Math.round(data.cooldown) + " more seconds before requesting a ROM.")
            $("#main-controls").show()
        } else if (data.error == "filename") {
            $("#generating").html("Filename too long, keep it to 64 characters please.")
            $("#main-controls").show()
        }
    } else {
        $("#btn-generate").removeClass('loading')
        $("#btn-generate").show()
        $("#btn-generate").text("Generate")
        $("#filename").val("")
        url = encodeURIComponent(data.filename).replace("%2F", "/").replace("%2F", "/")
        $("#generating").html("Randomized ROM generated in "+ (Math.round(data.time*100)/100) +"s! <a href='"+url+"' class='piwik_download'>Download</a><br>Link for sharing with friends:<br><code>https://sanqui.net/randomizer/"+url+"</code>")
    }
}
function oops(x) {
    generating = false
    $("#generating").html("Oops, something went wrong :(")
    $("#btn-generate").removeClass('loading')
    $("#btn-generate").show()
    $("#btn-generate").text("Try again")
}

function update_all_expanded(instant) {
    $('#options input').each(function(){
        if (!this.id) return
        var checked = this.checked
        
        console.log("thru update_all_expanded: input: "+this.id+", checked="+checked)
        
        if (checked) {
            $('*[data-expandedby="'+this.id+'"]').fadeIn(instant ? 0 : 500)
            $('*[data-expandedby="'+this.id+'"] input').prop('checked', true);
        }
        else { $('*[data-expandedby="'+this.id+'"]').fadeOut(instant ? 0 : 500) }
    })
}

clicked_big_preset = false

function makepresetbuttons() {
    for (gid in games) {
        $('#btn-'+gid).click(function() {render_options(this.getAttribute('data-game'), false) })
        for (presetid in games[gid].presets) {
            $('#btn-big-preset-'+gid+'-'+presetid).click(function() {
                if (clicked_big_preset) {
                    for (presetid in games[btn_gameid].presets) {
                        $('#btn-big-preset-'+btn_gameid+'-'+presetid).show();
                        $('#btn-big-preset-'+btn_gameid+'-custom').show();
                    }
                    $('#main-controls').show();
                    clicked_big_preset = false
                } else {
                    btn_presetid = this.getAttribute('data-preset');
                    btn_gameid = this.getAttribute('data-gameid');
                    set_preset(btn_presetid);
                    $('#btn-generate').click();
                    for (presetid in games[btn_gameid].presets) {
                        if (presetid != btn_presetid) {
                            $('#btn-big-preset-'+btn_gameid+'-'+presetid).hide();
                        }
                    }
                    $('#btn-big-preset-'+btn_gameid+'-custom').hide();
                    $('#main-controls').hide();
                    clicked_big_preset = true
                }
                
            })
            $('#btn-preset-'+presetid).click(function() {
                set_preset(this.getAttribute('data-preset'));
                return false;
            })
        }
        $('#btn-big-preset-'+gid+"-custom").click(function(){
            btn_gameid = this.getAttribute('data-gameid');
            $('#big-presets-'+btn_gameid).hide()
            $('#form-'+btn_gameid).fadeIn(500)
            $('#btn-generate').show();
        });
        $('#btn-presets-'+gid).click(function(){
            btn_gameid = this.getAttribute('data-gameid');
            $('#big-presets-'+btn_gameid).fadeIn(500)
            $('#form-'+btn_gameid).hide()            
            $('#btn-generate').hide();
            return false;
        });
    }
}

$(document).ready(function(){
    $('#btn-pickanother').click(pickanother)
    
    makepresetbuttons()
    
    $('#btn-select-all').click(function() { $('#options input').prop('checked', true); update_all_expanded()})
    $('#btn-select-none').click(function() { $('#options input').prop('checked', false); update_all_expanded()})
    $('#btn-generate').click(generate)
    
    $('#options input').change(function() {
        var checked = this.checked
        
        console.log("input changed: "+this.id+", checked="+checked)
        
        if (checked) { $('*[data-expandedby="'+this.id+'"]').fadeIn(500) }
        else { $('*[data-expandedby="'+this.id+'"]').fadeOut(500) }
    })
    
    if (window.location.hash) {
        render_options(window.location.hash.substr(1), true)
    }
    
    $('.help-popup').popup({
        position: 'top left',
        delay: 50,
    })
    $('.unstable').popup({position: 'bottom center'})
    
    update_all_expanded(true)
})
    </script>
</head>
<body>
<!--	<h1>the Online Randomizer will be back soon :(</h1>
</body>-->
    {% if debug %}
        <div class="ui label top left attached red unstable" style="font-size: 20px; font-weight:bold; position:fixed; z-index:50;"><u>DEBUG VERSION</u><br>NOT THE REAL THING!</div>
    {% endif %}
    
    <h1><a href="/"><img src="static/randomized_games_logo.png" class="randomized-games-logo"></a></h1>
    
    <div class="main">
        <div class="ui label top right attached red big unstable" data-content="New features are added often. The game may crash! Save your game often.">UNSTABLE</div>
        <!-- https://i.imgur.com/Z0k2D3y.png -->
        <!--<h1 class="logo"><img src="static/logos/{{'{:02}'.format(randlogo)}}.png" alt="Online Randomizer"></h1>-->
        <button class="ui button" data-game="pokered" id="btn-pickanother" style="display: none;">Pick a different game</button>
        <div id="games" style="text-align: center;">
            <h2 class="ui header">Pick a game</h2>
            <div class="ui buttons center">
                <button class="ui button" data-game="pokered" id="btn-pokered"><img src="static/games/pokered.png" alt="Pokémon Red" width="320" height="156"></button>
            </div>
            <div class="ui buttons center">
                {% for game in games[1:] %}
                    <button class="ui button" data-game="{{game.identifier}}" id="btn-{{game.identifier}}"><img src="static/games/{{game.identifier}}.png" alt="{{game.name}}" width="160" height="78"></button>
                {% endfor %}
            </div>
        </div>
        <div style="text-align: center;">
            {% for game in games %}
                <img id="game-logo-{{game.identifier}}" src="static/games/{{game.identifier}}.png" width="320" height="156" style="display: none;">
            {% endfor %}
        </div>
        <div id="randomizer_options" style="display:none;">
            <div id="options_controls" class="ui top attached header">
                <h3 class="ui header">How would you like to play?</h3>
            </div>
            <div id="options" class="ui segment attached">
                <!--
                    <div class="ui mini buttons">
                        <button id="btn-select-all"  class="ui button">Select all</button>
                        <button id='btn-select-none' class="ui button">Select none</button>
                    </div>
                -->
                {% for game in games %}
                    <div id="options-{{game.identifier}}" style="display:none;">
                        <div class="big-presets" id="big-presets-{{game.identifier}}">
                                {% for identifier, preset in game.presets.items() %}
                                    <button id="btn-big-preset-{{game.identifier}}-{{preset.identifier}}" data-preset="{{preset.identifier}}" data-gameid="{{game.identifier}}" class="ui button button-big-preset">
                                        <h4>{{preset.name}}</h4>
                                        {{preset.description}}
                                    </button>
                                {% endfor %}
                                <button id="btn-big-preset-{{game.identifier}}-custom" data-preset="custom" data-gameid="{{game.identifier}}" class="ui button button-big-preset">
                                    <h4>Custom</h4>
                                    Choose exactly how you'd like to play!
                                </button>
                        </div>
                        <form id="form-{{game.identifier}}" class="" style="display: none;">
                            <button id="btn-presets-{{game.identifier}}" data-gameid="{{game.identifier}}" class="ui button small button-presets">Choose a preset instead</button>
                            <div class="ui label top right attached">
                                Presets:
                                <div class="ui mini buttons">
                                    {% for preset in game.presets %}
                                        <button id="btn-preset-{{preset}}" data-preset="{{preset}}" class="ui button">{{preset}}</button>
                                    {% endfor %}
                                </div>
                            </div>
                            <input type="hidden" name="game" value="{{game.identifier}}">
                            <table>
                            {% for field in game.Form() %}
                                {{ render_field(field, game) }}
                            {% endfor %}
                            </table>
                        </form>
                    </div>
                {% endfor %}
            </div>
            <div id="controls" class="ui bottom attached header">
                <div id="main-controls">
                    <input type="text" id="filename" name="filename" class="ui input" placeholder="Custom filename" maxlength="64">.gbc
                    <button id="btn-generate" class="ui button">Generate</button>
                </div>
                <div id="generating" style="display:none;">Generating...</div>
            </div>
        </div>
</ul>
    </div>

    <div class="ui divider"></div>
    <div style="text-align: center;">
	The randomizer gets over 800 downloads a day.  If you enjoy using it and would like to support the server costs (or buy me a cup of tea), please feel free to donate.
	<br>
	<a href="https://www.paypal.me/sanquii/3usd" style="display: block; margin: auto; width: 128px;
	text-align: center; text-decoration: none;
	color: #0c2962; background: #fdd596; border: 2px solid #f9a656; border-radius: 24px;
	font-style: italic; font-weight: bold; margin-top: 8px; margin-bottom: 8px;
	padding: 4px 0px 4px 0px;">Donate</a>
	<small>Note that a large number of other people's work went into the randomizer.<br>By donating, you are only supporting the developer (me).</small>
    </div>
    <div class="ui divider"></div>
    <div class="about">
        <h3 class="ui header">What is this?</h3>
        <p>This is a randomizer - a program which changes up data inside the game in a random manner.  In a Pokémon game, for example, you can have three random starter Pokémon - and random wild Pokémon on each route or with other trainers, too.  In case you enjoy a game, but want to mix it up a little while playing it again, a randomizer is a wonderful tool.
        <p>Another popular use of Pokémon randomizers is to race the game.  With a group of other people, you make one randomized ROM for every player, and start playing together, seeing who beats a gym leader or the game first.  These games often happen on <a href="http://speedrunslive.com/">SpeedRunsLive</a>.
        <p>This randomizer a little experimental.  Among other things, it supports randomizing <i>any single Pokémon</i> into Pokémon Red.  Here's a screenshot:
        <p style="text-align:center;"><img src="static/screenshots/red00.png" style="width:160px; height:144px; margin: auto;">
        <p>Feel free to try it out!  That being said, the randomizer is still a work in progress, and sometimes I add shiny new features without testing them thoroughly first.  If you intend to do a long-term playthrough, like a Let's Play, <strong>maybe hold off a little bit</strong> until the randomizer becomes more stable.  Wouldn't want your game to crash near the end of the game!
        <p>Eventually, I intend on supporting a variety of different games.  I also have a lot of ideas coming for Pokémon Red, like random maps.  By the way, if you want to randomize Pokémon games other than Red, check out Dabomstew's <a href="http://pokehacks.dabomstew.com/randomizer/">Universal Randomizer</a>.
        <p><!--Got an idea of your own?  Or want to report a nasty bug?  Feel free to throw any feedback at me: <a href="mailto:gsanky@gmail.com">gsanky@gmail.com</a> - Thanks!-->
    </div>
    <footer class="ui two column  aligned relaxed grid basic segment">
        <div class="column">
            <h3 class="ui header">Credits</h3>
            <p>This randomizer was made possible with the help and gratuitous contributions by these great people and many others!
            <h4>Gen 1 style sprites</h4>
            <ul>
                <li><a href="http://project-rbydex.deviantart.com/">Project-RBYDex</a>
                <li><a href="http://azpainter.tumblr.com/">azpainter</a>
                <li><a href="https://twitter.com/Karmaverick">Karmaverick</a>
                <li><a href="http://ubasuteyama.deviantart.com/">ubasuteyama</a>
                <li><a href="http://tinyurl.com/4poyc6x">Behold3r</a>
                <li><a href="http://involuntary-twitch.deviantart.com/">Involuntary-Twitch</a>
                <li><a href="http://racieb.deviantart.com/">RacieB</a>
                <li><a href="http://mylittlekeldeo.deviantart.com/">mylittlekeldeo</a>
                <li><a href="https://www.furaffinity.net/user/kamikitty/">QueenKami</a>
                <li>Reimu
                <li><a href="http://sanqui.rustedlogic.net/">Sanqui</a>
                <li>Lunaria
                <li><a href="http://solo993.deviantart.com/">solo993</a>
                <li>Other Gen 2-5 sprites done mostly by anons of /vp/ some time ago.<br><small>See credits on <a href="http://www.tehowners.com/info/Non-Informative/Pokemon%20Sprites%20in%20Gen%201%20Style%20.png">this sheet</a>.  Please note that many of the sprites presented there are not actually in use.</small>
            </ul>
            <h4>Music</h4>
            <ul>
                <li><a href="http://froggestspirit.blogspot.com/">FroggestSpirit</a> - many remixes and demixes
                <li><a href="https://github.com/dannye/">Danny-E 33</a> - TCG ports
                <li><a href="https://www.youtube.com/user/levusbevus">LevusBevus</a> - Naljo Wild Batle
                <li><a href="https://www.youtube.com/user/GRonnoc">GRonnoc</a> - Naljo Gym Battle
            </ul>
            <h4>Other</h4>
            <ul>
                <li><a href="http://tinyurl.com/4poyc6x">Behold3r</a> - organization & motivation help
                <li><a href="http://darkdata.rustedlogic.net/">Darkdata</a> - extra overworld walking sprites
                <li><a href="http://www.rijon.com/">Koolboyman</a> - Prism assets (just music for now)
                <li><a href="http://pokehacks.dabomstew.com/randomizer/">Dabomstew</a> - creator of the Universal Pokémon Randomizer
                <li><a href="https://github.com/iimarckus/pokered">pokered</a> and <a href="https://github.com/kanzure/pokecrystal">pokecrystal</a> contributors, including iimarckus, yenatch, kanzure, dannye et al.
                <li><a href="https://github.com/veekun/pokedex/">veekun pokedex</a> contributors, including eevee, Zhorken, magical, En-Cu-Kou and others.
            </ul>
            <p>Huge thanks to everybody for their contributions!
            <p><small>Not credited?  <a href="mailto:gsanky@gmail.com">Please do let me know!</a></small>
        </div>
        <!--<div class="ui vertical divider"></div>-->
        <div class="column">
            <h3>Discuss</h3>
            <p>To discuss the randomizer you may <a href="https://discord.gg/FURyAXC">join the Discord server</a>.
            <h3>Source code</h3>
            <p>The source code is on Github:
            <ul>
                <li><a href="https://github.com/Sanqui/randomizer">randomizer</a> (central repo)
                <li><a href="https://github.com/Sanqui/pokered-randomizer">pokered-randomizer</a>
            </ul>
        </div>
    </footer>
    <p>Randomizer by Sanqui aka Sanky.
    <p><small>You <b>may not</b> publicly post links to ROMs generated by this randomizer online.</small>
</body>
</html>

