var gamecall = function() 
{
    var request;
    var timeout;

    function response()
    {
        var obj;
        var answer;

        if(request.readyState == 4 && request.status == 200)
        {
            obj = eval("("+request.responseText+")");

            if(!obj) 
            {
                timeout = setTimeout(checkForCall, 30000);
                return;
            }

            answer = window.confirm("User "+obj.fromUser+" has issued a general challenge for "+obj.gameName+". Would you like to answer the challenge? Pressing 'Yes' will take you to a page to launch the game.");

            if(answer) window.location = "/gameDetail.aspx?gameID="+obj.gameID;
        }
    }

    function checkForCall()
    {
        request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        
        request.open("GET", "http://www.wiicade.com/games/requestChallenger.jsp", true);
        request.onreadystatechange = response;
        request.send(null);
    }

    timeout = setTimeout(checkForCall, 5000);


    function confirm()
    {
        var obj;

        if(request.readyState == 4 && request.status == 200)
        {
            try { obj = eval("("+request.responseText+")"); } 
            catch(e) { alert("Unable to issue challenge. An unknown error has occurred. Please try back later."); return; }

            window.alert(obj.message);
        }
    }

    window.requestChallenger = function(gameID, gameName)
    {
        var answer = window.confirm("Can't find anyone to play "+gameName+" with? This feature will allow you to send a general call for opponents. Opponents will be able to see your username and will be asked if they wish to respond to your challenge. Do you wish to issue a general challenge?");

        if(answer)
        {
            clearTimeout(timeout);

            request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        
            request.open("GET", "http://www.wiicade.com/games/requestChallenger.jsp?gameID="+gameID+"&gameName="+escape(gameName), true);
            request.onreadystatechange = confirm;
            request.send(null);
        }
    };
};

gamecall();
delete gamecall;
