yardsUpdateRate                 =1000;
yardsCurrentGameRequest         ="";
yardsCurrentGameRequestModified =false;
yardsFlashIsReadyFlag           =false;
yardsHasLoadedGame              =false;
yardsDefaultGame                ="";

var updateCycleInterval;
var updateCycleCounter = 0;

function startUpdateCycle() {
    updateCycleCounter = 0;    
    updateCycleInterval = setInterval(updateCycle, yardsUpdateRate);
}

function updateGame(event) {
    // Tell flash to poll for new state. This is rate limited.
    if (yardsCurrentGameRequest != "" && thisMovie('Yards') != undefined) thisMovie('Yards').yardsPollGameInFlash();
}

function updateLists(event) {
    getGames("#current_games", false)
    getInvitations("#current_invitations", false);
    getRecentGames("#recent_games", false);
}

function updateAll(event){
    updateGame(event);
    updateLists(event);
}

function updateCycle(event) {
    updateCycleCounter += 1;
    if (updateCycleCounter % 30 == 0) updateLists(event);
    if (updateCycleCounter % 6  == 0) updateGame(event);
}

// Get profile names, scores (handle colors separately)
function getProfile() {
    $.ajax({        
        type: "GET",
        dataType: "json",
        url: "/event/profile",
        success: function(data){
            if (data.error) {
                yardsNotify(""+data.error, true)
            } else if (data.success) {
                yardsNotify(""+data.success)
            } 
            
            if (data.result) {
                result = data.result

                if (result.name) {
                    $("#user_name").html(result.name);
                } else {
                    $("#user_name").html("<label class='ui-state-disabled'>(No name)</label>");
                }


                if (result.teamname) {
                    $("#team_name").html(result.teamname);
                } else {
                    $("#team_name").html("<label class='ui-state-disabled'>(No team name)</label>");
                }

                if (result.initials) {
                    $("#initials").html(result.initials);    
                } else {
                    $("#initials").html("<label class='ui-state-disabled'>(No initials)</label>");
                }

                $("#notify").show(); // Make sure it's displayed
                if (result.notify) {
                    $("#notify").attr("checked", true);
                } else {
                    $("#notify").removeAttr("checked");
                }
                $("#wins").html(result.wins);
                $("#record_div").attr("title", "You have "+result.wins+" wins and "+result.losses+" losses.")
                $("#score").html(result.score);
                
                // update color... ?
            }            
        },
        cache: false            
    });    
}

function postProfile(attribute, value) {
    data = {}
    data[attribute] = value;
    $.ajax({        
        type: "POST",
        dataType: "json",
        data: data,
        url: "/event/profile",
        success: function(data){
            if (data.error) {
                yardsNotify(""+data.error, true)
            } else if (data.success) {
                //yardsNotify(""+data.success)
            }
            
            // refresh profile
            getProfile();

        },
        error: function(){
            yardsNotify("There was a problem updating profile info.", true)
        },
        cache: false            
    });       
}

function getGames(selector, animate) {
    $.ajax({        
        type: "GET",
        dataType: "json",
        url: "/event/games",
        success: function(data){
            if (data.error) {
                yardsNotify(""+data.error, true)
            } else if (data.success) {
                yardsNotify(""+data.success)
            } 
            
            if (data.result) {
                var result = data.result
                $(selector).html("");
                for (var j=0; j < result.length; j++) {
                    if (j==0) yardsDefaultGame = result[j].game_id;
                    var person = "";
                    if (result[j].game_id == yardsCurrentGameRequest) person = '<span title="Currently displayed game." class="icon1 ui-icon ui-icon-triangle-1-e">&nbsp;</span>';
                    if (result[j].has_turn) {
                        link = $("<div/>")
                                   .attr("game_id", result[j].game_id)
                                   .click(function(){ yardsLoadGame( $(this).attr("game_id") ); })
                                   .attr("title", "It's your turn to play.")
                                   .addClass("ui-state-default ui-corner-all yards-link")
                                   .html('<a href="javascript:void(0);" class="" id="yards-link-inside">v. '+ result[j].opponent +'</a> <a title="It\'s your turn to play." href="javascript:void(0);">'+person+'</a>');
                        $("<div/>").html(link).appendTo(selector);
                        
                        link.hover(
                    		function(e) { $(this).addClass('ui-state-hover'); }, 
                    		function(e) { $(this).removeClass('ui-state-hover'); }
                    	);

                    } else {

                        link = $("<div/>")
                                   .attr("game_id", result[j].game_id)
                                   .click(function(){ yardsLoadGame( $(this).attr("game_id") ); })
                                   .attr("title", "Waiting on "+ result[j].opponent+" to make a move.")
                                   .addClass("ui-state-default ui-state-disabled ui-corner-all yards-link")
                                   .html('<a href="javascript:void(0);" class="" id="yards-link-inside">v. '+ result[j].opponent + person +'</a>');
                        $("<div/>").html(link).appendTo(selector);
                        
                        link.hover(
                    		function(e) { $(this).addClass('ui-state-hover'); }, 
                    		function(e) { $(this).removeClass('ui-state-hover'); }
                    	);
                    }            
                }
            }
            if (animate) {$(selector).slideDown("fast")};
            if (yardsFlashIsReadyFlag && !yardsHasLoadedGame) yardsFlashIsReady(yardsCurrentGameRequest);
        },
        error: function(){
            
            //$(selector).html("<div>Could not update games list...</div>");
            //if (animate) {$(selector).slideDown("fast")};
            
        },
        cache: false            
    });    
}


function getRecentGames(selector, animate) {
    $.ajax({        
        type: "GET",
        dataType: "json",
        data: {"action":"recent"},
        url: "/event/games",
        success: function(data){
            if (data.error) {
                yardsNotify(""+data.error, true)
            } else if (data.success) {
                yardsNotify(""+data.success)
            } 
            
            if (data.result) {
                result = data.result
                $(selector).html("");
                for (var j=0; j < result.length; j++) {
                    var person = "";
                    if (result[j].outcome == "won") {
                        if (result[j].game_id == yardsCurrentGameRequest) person = '<span title="Currently displayed game." class="icon2 ui-icon ui-icon-triangle-1-e">&nbsp;</span>';
                        
                        link = $("<div/>")
                                   .attr("game_id", result[j].game_id)
                                   .click(function(){ yardsLoadGame( $(this).attr("game_id") ); })
                                   .attr("title", "You won!")                        
                                   .addClass("ui-state-default ui-state-disabled ui-corner-all yards-link")
                                   .html('<a href="javascript:void(0);" class="" id="yards-link-inside">v. '+ result[j].opponent +'</a> <a title="Yay! You won. This flag is yours to keep." href="javascript:void(0);"><span class="icon1 ui-icon ui-icon-flag">&nbsp;</span>'+person+'</a> ');
                        $("<div/>").html(link).appendTo(selector);
                        
                        link.hover(
                    		function(e) { $(this).addClass('ui-state-hover'); }, 
                    		function(e) { $(this).removeClass('ui-state-hover'); }
                    	);

                    } else {
                        if (result[j].game_id == yardsCurrentGameRequest) person = '<span title="Currently displayed game." class="icon1 ui-icon ui-icon-triangle-1-e">&nbsp;</span>';

                        link = $("<div/>")
                                   .attr("game_id", result[j].game_id)
                                   .click(function(){ yardsLoadGame( $(this).attr("game_id") ); })                        
                                   .attr("title", "Oof. Didn't win this one.")
                                   .addClass("ui-state-default ui-state-disabled ui-corner-all yards-link")
                                   .html('<a href="javascript:void(0);" class="" id="yards-link-inside">v. '+ result[j].opponent + person +'</a>');
                        $("<div/>").html(link).appendTo(selector);
                        
                        link.hover(
                    		function(e) { $(this).addClass('ui-state-hover'); }, 
                    		function(e) { $(this).removeClass('ui-state-hover'); }
                    	);
                    }            
                }
            }
            if (animate) {$(selector).slideDown("fast")};
            
        },
        error: function(){
            //$(selector).html("<div>Could not update games list...</div>");
            //if (animate) {$(selector).slideDown("fast")};
            
        },
        cache: false            
    });    
}


function getInvitations(selector, animate) {
    $.ajax({        
        type: "GET",
        dataType: "json",
        url: "/event/invitations",
        success: function(data){
            if (data.error) {
                yardsNotify(""+data.error, true)
            } else if (data.success) {
                yardsNotify(""+data.success)
            }
            
            if (data.result) {
                result = data.result
                $(selector).html("");
                for (var j=0; j < result.length; j++) {
                    //$("<div/>").html(""+result[j].name).appendTo(selector);
                                    
                    if (result[j].type == "received") {

                        link = $("<div/>")
                                   .attr("title", "New game invitation! Click the check to start a game with "+ result[j].name +".")
                                   .addClass("ui-state-default ui-corner-all yards-link")
                                   .html('<b>From:</b> '+ result[j].name +' <a title="Accept invitation." href="javascript:void(0);" onClick=\'postInvitation("'+ result[j].invitation_id +'", "accept");\'> <span class="icon2 ui-icon ui-icon-circle-check">&nbsp;</span></a> <a title="Decline invitation." href="javascript:void(0);" onClick=\'postInvitation("'+ result[j].invitation_id +'", "decline");\'> <span class="icon1 ui-icon ui-icon-circle-close ui-priority-secondary">&nbsp;</span>');
                        $("<div/>").html(link).appendTo(selector);
                        
                        link.hover(
                    		function(e) { $(this).addClass('ui-state-hover'); }, 
                    		function(e) { $(this).removeClass('ui-state-hover'); }
                    	);
                    	
                    } else {
                        

                        link = $("<div/>")
                                   .attr("title", "Invitation sent. Waiting for "+ result[j].name +" to accept it.")
                                   .addClass("ui-state-default ui-state-disabled ui-corner-all yards-link")
                                   .html('<b>Sent To:</b> '+ result[j].name +' <a title="Cancel invitation." href="javascript:void(0);" onClick=\'postInvitation("'+ result[j].invitation_id +'", "cancel");\'><span class="icon1 ui-icon ui-icon-circle-close ui-priority-secondary">&nbsp;</span>');
                        $("<div/>").html(link).appendTo(selector);
                        
                        // add hover behavior
                        link.hover(
                    		function(e) { $(this).addClass('ui-state-hover'); }, 
                    		function(e) { $(this).removeClass('ui-state-hover'); }
                    	);
                    }
            

                }                
            }
            if (animate) {$(selector).slideDown("fast")};
            
        },
        error: function(){
            //$(selector).html("<div>Could not update invitations list...</div>");
            //if (animate) {$(selector).slideDown("fast")};
            
        },
        cache: false            
    });    
}

function makeInvitationSender(buttonSelector, emailSelector, invitationSelector) {
    $(buttonSelector).click(function(event){
       event.preventDefault();


       $.ajax({        
           type: "POST",
           dataType: "json",
           data: {"action":"create", "email": $(emailSelector).val() },
           url: "/event/invitations",
           success: function(data){
               if (data.error) {
                   yardsNotify(""+data.error, true)
               } else if (data.success) {
                   yardsNotify(""+data.success)
               }
               
               // refresh invitation list
               getInvitations(invitationSelector, false);

           },
           error: function(){
           },
           cache: false            
       });    
   });
}

function postInvitation(invitation_id, action) {
    data = {}
    data["action"] = action;
    data["invitation_id"] = invitation_id;
    $.ajax({        
        type: "POST",
        dataType: "json",
        data: data,
        url: "/event/invitations",
        success: function(data){
            if (data.error) {
                yardsNotify(""+data.error, true)
            } else if (data.success) {
                yardsNotify(""+data.success)
            }
            
            // refresh lists
            updateLists();

        },
        error: function(){
            yardsNotify("There was a problem "+action+"ing invitation.", true)
        },
        cache: false            
    });       
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}


var yardsNotifyTimeout;
function yardsNotify(msg, error) {
    hideNotify(null, false);
    var msgtype = "notification"
    if (error) msgtype = "error"
    if (msgtype == undefined) msgtype = "notification";
    $("#yards-"+msgtype+"-text").html(msg + "<a title='Close notification.' href='javascript:void(0);' onclick='hideNotify();'> <span class='icon2 ui-icon ui-icon-close'>&nbsp;</span> </a>");
    $("#yards-"+msgtype).fadeIn(500);    
    yardsNotifyTimeout = setTimeout(hideNotify, 8000);
}

function hideNotify(event, animate) {
    clearTimeout(yardsNotifyTimeout);
    if (animate == undefined || animate == true)
    {
        $(".notification").slideUp(250);
    } else {
        $(".notification").hide();
    }
}

function yardsFlashIsReady(current_game_id) {
    yardsFlashIsReadyFlag   = true;

    // This is called by Flash upon init.
    if (current_game_id != undefined && current_game_id != "") {
        yardsCurrentGameRequest = current_game_id;
    }
    
    // If a game has been manually selected before Flash loaded, load game.
    // (Or if no game was manually selected, but a current game exists,
    // load it.)
    if (yardsCurrentGameRequestModified) {
        yardsLoadGame(yardsCurrentGameRequest);
    } else if ((current_game_id == undefined || current_game_id == "") && (yardsDefaultGame != undefined && yardsDefaultGame != "")){
        yardsCurrentGameRequest = yardsDefaultGame;
        yardsLoadGame(yardsCurrentGameRequest);
    }
}

function yardsFlashUpdate() {
    // This is called by Flash when, e.g., an action is accepted and committed.
    // refresh lists
    updateAll();
    getProfile();    
}

function yardsLoadGame(game_request) {
    yardsCurrentGameRequest         = game_request;
    yardsCurrentGameRequestModified = true;
    if (yardsFlashIsReadyFlag && yardsCurrentGameRequest != undefined && yardsCurrentGameRequest != "") {
        // Attempt to load requested game.
        if (thisMovie('Yards') != undefined) {
            yardsHasLoadedGame = true;
            thisMovie('Yards').yardsLoadGameInFlash(yardsCurrentGameRequest);
        }
    }
    
    // refresh lists
    updateAll();
}

startUpdateCycle();
