var unsaved_changes = false;

function make_pick(gamecode, pick_team_id, unpick_team_id) {
    // For the full picks page where we submit via a form
    var form_field = $('game_picks['+gamecode+'][team_id]');
    if (form_field != null) {
        form_field.value = pick_team_id;
    }
    $('option_'+gamecode+'_'+pick_team_id).addClassName('selected');
    $('option_'+gamecode+'_'+unpick_team_id).addClassName('unselected');
    $('option_'+gamecode+'_'+pick_team_id).removeClassName('unselected');
    $('option_'+gamecode+'_'+unpick_team_id).removeClassName('selected');

    unsaved_changes = true;
}


function safe_to_leave() {
    if (unsaved_changes) {
        if (confirm('You have not saved your picks. Are you sure you wish to leave?')) {
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

function gate_links() {
    // Get all links
    var all_links = document.getElementsByTagName('a');
    if (all_links != null) {
        // Loop through all links
        var number_of_links = all_links.length;
        for (var i=0; i<number_of_links; i++) {
            // Only apply to links that aren't part of the game
            if (!(
                Element.hasClassName(all_links[i], 'pick_preview_open') ||
                Element.hasClassName(all_links[i], 'pick_preview_closed') ||
                Element.hasClassName(all_links[i], 'pick_toggle') ||
                Element.hasClassName(all_links[i], 'no_warn') ||
                Element.hasClassName(all_links[i], 'sign_out')
            )) {
                all_links[i].onclick = function() {
                    if (safe_to_leave()) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
    }
}

function save_picks() {
    var picks_form = $('pk_picks_form');
    if (picks_form == null) { return false; }
    
    // set unsaved changes flag to false
    unsaved_changes = false;
    //new Ajax.Request('/peter_king_challenge/save_picks', {asynchronous:true, evalScripts:true, onLoading:function(request){display_ajax_spinner('saving_picks_loading', 'Saving Picks');}, parameters:Form.serialize(picks_form) }); return false;
    picks_form.submit();
    return false;
};


function entries_locked() {
    alert('Sorry, entries have been locked. You may no longer create or change your picks.');
};


