
var currTemplateId      = -1;
var gameOptionsPanel    = null;
var gameListPanel       = null;
var theChessBoard       = null;
var currBoards          = null;
var currBoardStart      = 0;
var currBoardCount      = -1;
var currSelectedBoard   = -1;
var numBoardsPerPage    = 10;

/**
 * Handler for when a particular cell in a board is clicked.
 */
function chessBoardCellClicked(board, x, y)
{
    if (board._curr_cell_x >= 0 && board._curr_cell_y >= 0)
    {
        board.boardCell(board._curr_cell_x, board._curr_cell_y).removeClass("selected_cell");
    }

    board._curr_cell_x = x;
    board._curr_cell_y = y;

    if (board.boardCell(x, y).hasClass("selected_cell"))
    {
        board.boardCell(x, y).removeClass("selected_cell");
    }
    else
    {
        board.boardCell(x, y).addClass("selected_cell");
    }
}

function refreshBoardList(start, count)
{
    var html = " ";
    if (count > 0)
    {
        function board_callback(json)
        {
            var code        = json.code;

            if (code < 0)
            {
                alert("Cannot load board list: " + json.value);
                return ;
            }

            var boards      = json['value'];
            var end         = start + boards.length;
            currBoards      = {};
            currBoards.records = null;

            if (boards.length > 0)
            {
                html = "<thead> " + 
                       "<td class='predef_header_cell'> Game </td> " +
                       "<td class='predef_header_cell'> Creator </td> " +
                       // "<td class='predef_header_cell'> Created </td>" +
                       "</thead>";

                currBoards.records = new Array();
                for (var i = 0;i < boards.length;i++)
                {
                    var board_data          = boards[i];
                    var tpl_data            = board_data['tpl_data'];
                    currBoards.records[i]   = board_data;
                    board_data.width        = tpl_data['width']
                    board_data.height       = tpl_data['height']
                    board_data.piece_info   = tpl_data['pieces']
                    board_data.tpl_data     = null;

                    html = html + 
                           "<tr id = board_tr_" + i + " > " +
                           "<td id = board_row_" + i + " class = board_list_cell > " + board_data.name + "</td>" +
                           // "<td id = board_row_" + i + " class = board_list_cell > " + board_data.creator.first_name + " " + board_data.creator.last_name + "</td>" +
                           "<td id = board_row_" + i + " class = board_list_cell > " + " " + "</td>" +
                           // "<td> " + rec.created + "</td>" +
                           "</tr>";
                }

                html = html + "<tr> <td colspan = 2><center>";
                if (json.hasprev)
                {
                    html = html + 
                           " <a href='javascript:void(0)' " + 
                               "onclick='refreshBoardList(0, " + count + ");'>First</a> ";
                    html = html + 
                           " <a href='javascript:void(0)' " + 
                               "onclick='refreshBoardList(" + (start - count) + ", " + count + ");'>Prev</a> ";
                }
                html = html + (start + 1) + " to " + end + " of " + json.total;
                if (json.hasnext)
                {
                    html = html + 
                           " <a href='javascript:void(0)' " + 
                               "onclick='refreshBoardList(" + end + ", " + count + ");'>Next</a> ";
                           // + " <a href='javascript:void(0)'>Last</a> ";
                }
                html = html + "</center></td></tr>";
                $("#predefined_game_list").html(html);

                $("#predefined_game_list").click(function (event){
                    var tid = event.target.id;
                    if (tid.indexOf("board_row_") == 0)
                    {
                        var row = parseInt(tid.substring(10, tid.length));
                        selectedBoardChanged(row);
                    }
                });
            }
            else
            {
                html = "<tr><td><center>No boards found.</center></td></tr>";
                $("#predefined_game_list").html(html);
            }

            $("#predefined_game_list").html(html);
        }

        // make an ajax request to the server now to 
        // refresh the maps in the game.
        $.ajax({
            url: "/templates/maps/?format=json",
            type: 'GET',
            dataType: 'json',
            data: 'from=' + start + "&to=" + (start + count),
            timeout: 120000,
            error: ajaxErrorHandler,
            success: board_callback });
    }
}

function documentLoaded()
{
    var tabView = new YAHOO.widget.TabView('game_options_panel'); 
    theChessBoard       = new ChessBoard('chess_board');
    theChessBoard.setShowMoves(false);
    theChessBoard.onCellClick(chessBoardCellClicked);

    refreshBoardList(0, numBoardsPerPage);

    $("#opponent_open").click(function () {
        $("#opponent_email_div").css("visibility", "hidden");
    });

    $("#opponent_me").click(function () {
        $("#opponent_email_div").css("visibility", "hidden");
    });

    $("#opponent_invite").click(function () {
        $("#opponent_email_div").css("visibility", "visible");
    });

    $("#first_mover_white").attr("checked", true);
    $("#player_color_white").attr("checked", true);
    $("#opponent_open").attr("checked", true);
    $("#opponent_email_div").css("visibility", "hidden");
}

$(document).ready(documentLoaded);

function get_player_data()
{
    var first_mover     = $("#first_mover_white").attr("checked") ? 0 : 1;
    var player_index    = $("#player_color_white").attr("checked") ? 0 : 1;
    var opponent        = null;

    if ($("#opponent_open").attr("checked"))
    {
        opponent = "open";
    }

    if ($("#opponent_me").attr("checked"))
    {
        opponent = "me";
    }

    if ($("#opponent_invite").attr("checked"))
    {
        opponent = $("#opponent_email").attr("value");
    }

    var player_data = {
        'starting_player': first_mover,
        'player_index': player_index,
        'players': []
    };

    player_data['players'][player_index] = "me";
    player_data['players'][(player_index + 1) % 2] = opponent;

    return player_data;
}

function get_game_data()
{
    return {'uri': $("#board_ref").attr("value")};
}

function load_board(board_data)
{
    var tpl_data = board_data['tpl_data'];
    $("#game_title").attr("value", board_data['name']);
    $("#board_ref").attr("value", board_data['uri'] == null ? "" : board_data['uri']);
    $("#game_desc").val(board_data['desc'] == null ? "" : board_data['desc']);
    theChessBoard.load(tpl_data);
}

function show_board_json()
{
    var board_data      = theChessBoard.getBoardData();
    board_data['title'] = $("#game_title").attr("value").trim();
    board_data['desc']  = $("#game_desc").attr("value").trim();
    board_data['ref']   = $("#board_ref").attr("value").trim();
    var board_string    = JSON.stringify(board_data);
    $("#json_text_area").html(board_string + ", ");
}

function save_board()
{
    var title       = $("#game_title").attr("value").trim();
    if (title == "") 
    {
        alert('Please enter a game title.');
        $("#game_title").focus();
        return ;
    }
    else
    {
        var title           = $("#game_title").attr("value").trim();
        var desc            = $("#game_desc").val().trim();
        var ref             = $("#board_ref").attr("value").trim();
        var board_data      = theChessBoard.getBoardData();
        var board_string    = JSON.stringify(board_data);

        function save_callback(json)
        {
            if (json.code < 0)
            {
                alert("Could not save board: " + json.value);
                return ;
            }
            else
            {
                currTemplateId = json.value['templateId'];
                alert("Board created successfully.");
            }
        }

        // make an ajax request to the server now to save the game.
        var save_url = '/templates/maps';

        if (currTemplateId >= 0)
            save_url += "/" + currTemplateId;
        save_url += "/save/?format=json";

        $.ajax({
            url: save_url,
            type: 'POST',
            dataType: 'json',
            data: "template_data=" + escape(board_string) +
                  "&creator=" + GFLoginManager.getActiveAlias() +
                  "&title=" + escape(title) +
                  "&description=" + escape(desc) +
                  "&uri=" + escape(ref),
            timeout: 120000,
            error: ajaxErrorHandler,
            success: save_callback });
    }
}

function clone_map_and_edit()
{
    currTemplateId = -1;
}

/**
 * Apply changes made to the board.
 */
function apply_changes()
{
    var boardwidth  = parseInt($("#board_width").attr("value"));
    var boardheight = parseInt($("#board_height").attr("value"));
    theChessBoard.createBoard(boardwidth, boardheight);
}

function selectedBoardChanged(rowIndex) //element, record)
{
    $("#predefined_game_list tr").removeClass("selected_board_row");
    if (rowIndex >= 0)
    {
        $("#board_tr_" + rowIndex).addClass("selected_board_row");
        // $("#predefined_game_list tr:eq(" + rowIndex + ")").addClass("selected_board_row");
    }

    var data = currBoards.records[rowIndex];

    function load_callback(json)
    {
        // alert("Load Completed: " + JSON.stringify(json));
        if (json.code < 0)
        {
            alert("Board loading failed: " + json.value);
        }
        else
        {
            currTemplateId = json.value.id
            load_board(json.value)
        }
    }

    // make an ajax request to the server now to save the game.
    $.ajax({
        url: "/templates/maps/" + data.id + "?format=json",
        type: 'GET',
        dataType: 'json',
        timeout: 120000,
        error: ajaxErrorHandler,
        success: load_callback });
}

function reset_board()
{
    $("#board_width").attr("value", 8);
    $("#board_height").attr("value", 8);
    theChessBoard.reset();
}

/*
 * Starts a game - now we are finished with creating a game.
 */
function start_game()
{
    var title       = $("#game_title").attr("value").trim();
    if (title == "") 
    {
        alert('Please enter a game title.');
        $("#game_title").focus();
        return ;
    }
    else
    {
        var game_data                   = get_game_data();
        game_data['board']              = theChessBoard.getBoardData();
        game_data['players']            = get_player_data();
        game_data['starting_player']    = game_data['players']['starting_player'];
        game_data['player_index']       = game_data['players']['player_index'];
        var game_string                 = JSON.stringify(game_data);
        var email                       = $("#opponent_email").attr("value").trim();

        if ($("#opponent_invite").attr("checked"))
        {
            if (email == "" || !email_valid(email))
            {
                alert("Please enter a valid email address.");
                $("#opponent_email").focus();
                return ;
            }
        }

        var start_button    = $("#start_button")[0];
        start_button.enabled = false;

        $("#mini_statusbar").html("Starting Game. Please wait...");

        function start_callback(json)
        {
            start_button.enabled = true;
            $("#mini_statusbar").html("");
            if (json['code'] == 0 || json['code'] == "0")
            {
                window.location = "/games/" + json['value']['gameid'];
            }
            else
            {
                alert("Could not start game: " + json['value']);
            }
        }

        function error_callback(json)
        {
            var here = true;
        }

        // make an ajax request to the server now to create the game.
        $.ajax({
            url: "/games/create/?format=json&__method__=put",
            type: 'POST',
            dataType: 'json',
            data: "title=" + $("#game_title").attr("value") +
                  "&desc=" + $("#game_desc").val() +
                  "&creator=" + GFLoginManager.getActiveAlias() +
                  "&num_players=2" +
                  "&game_data=" + escape(game_string),
            timeout: 120000,
            error: error_callback,
            success: start_callback });
    }
}


function email_valid(str)
{
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)

    if (str.indexOf(at)==-1){
       return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       return false;
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        return false;
    }

     if (str.indexOf(at,(lat+1))!=-1){
        return false;
     }

     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        return false;
     }

     if (str.indexOf(dot,(lat+2))==-1){
        return false;
     }
    
     if (str.indexOf(" ")!=-1){
        return false;
     }

     return true                    
}

