<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="Weewar" scrolling="true" height="260" width="280"
    author="Ben Petro"
    title_url="http://weewar.com"
    author_email="benpetro@gmail.com"
    author_location="Brisbane, QLD, Australia"
    author_link="http://benpetro.blogspot.com"
    description="A Weewar user profile gadget giving you up-to-date access to your current rating, your win/loss record, 
      your current games and your preferred players list.  You will see a live alert icon for games that 
      require your attention and be able to keep up to date with your friends' win/loss records."
    thumbnail="http://weewar.com/images/weewar_logo_tr.gif"
    screenshot="http://benpetro.googlepages.com/screenshot.png" >
    <Require feature="analytics" />
  </ModulePrefs>
  <UserPref name="username" display_name="Weewar Username" datatype="string" default_value="sebeda" required="true"/>
  <UserPref name="displayProfilePic" 
     display_name="Display Profile Pic"
     datatype="enum"
     default_value="1">
    <EnumValue value="1" display_value="Yes"/>
    <EnumValue value="0" display_value="No"/>
  </UserPref>
  <Content type="html">
  <![CDATA[ 
  <style>
    body{font-family:verdana;font-size:10pt;margin:10px;}
    #div_logo{text-align:center;margin-bottom:10px;}
    #h1_user{font-size:16pt;font-weight:normal;margin-top:0px;}
    h2{font-size:10pt;font-weight:bold;margin-top:20px;clear:all;font-weight:normal;}
    #img_profile{width:85px;height:85px;border:1px solid black;margin-right:5px;}
    #div_points{color:#DD4B00;}
    a{color:#3E93F0;text-decoration:none;}
    a:hover{text-decoration:underline;}
    a:visited{color:#3E93F0;}
    .off{display:none;}
    .on{display:block;}
    #div_last_updated{text-align:center;font-size:7pt;color:#999;margin-top:5px;display:none;}
    ul,li{margin:0px;padding:0px;}
    #div_loading{text-align:center;position:absolute;padding:20px;border:1px solid black;background:#FFF;z-index:100;font-size:8pt;}
    #div_loading img{margin-top:5px;}
    #div_loading_games{float:right;}
    .small{font-size:7pt;color:#999;}
  </style>
  <div id="weewarCorner" style="position:absolute; top:0px; right:0px; z-index:0;">
    <a href="http://weewar.com/headquarters/games" title="Have a little war at Weewar.com" target="_blank">
      <img style="border-width:0px;" src="http://benpetro.googlepages.com/weewar_corner_1.gif" width="75px" height="101px" alt="weewar.com corner"/>
    </a>
  </div>  
        
  <div id="div_loading">Updating data...<br />
    <img src="http://benpetro.googlepages.com/loading_animation_liferay.gif" />
  </div>
  <div id="div_content" class="off" style="z-index:99;">
    <h1 id="h1_user"></h1>
    <img id="img_profile" align="left"/>
    <div id="div_points"></div>
    <div id="div_victories"></div>
    <div id="div_losses"></div>
    <div id="div_draws"></div>
    <div id="div_win_loss"></div>
    <h2><a href="javascript:;" onclick="displayGames();" id="link_games" style="font-weight:bold;">Games</a> / 
    <a href="javascript:;" onclick="displayPlayers();" id="link_players">Preferred Players</a></h2>
    <div id="div_loading_games" class="off"><img id="img_loading_games" /></div>
    <ul id="ul_games"></ul>
    <ul id="ul_players"></ul>
    <div id="div_last_updated" class="off"></div>
  </div>
  <script type="text/javascript">
    var username = null;
    var timerGames = null;
    var timerProfile = null;
    var timerGamesLoading = null;
    var urlProfile = 'http://weewar.com/api1/user/';
    var gameList = null;
    var playerList = null;
    var profile_pause = 5;
    var games_pause = .5;
    var firstLoad = true;
    var ul_games = _gel('ul_games');
    var ul_players = _gel('ul_players');
    var gamesLoaded = false;
    var loadingImage = _IG_GetImage("http://benpetro.googlepages.com/indicator_arrows_circle.gif");
    
    function loadGadget()
    {
      var prefs = new _IG_Prefs(__MODULE_ID__);
      username = prefs.getString("username");
      displayProfilePic = prefs.getBool("displayProfilePic");
      _gel("h1_user").innerHTML = "<a href=\"http://weewar.com/user/" + username + "\" target=\"_blank\" rel=\"me\">" + username + "</a>";
      if (!displayProfilePic)
        _gel("img_profile").className = "off";
      loadProfile();
      _gel('img_loading_games').src = loadingImage.src;
    }
  
    function loadProfile()
    {
      //clear the past timeout
      window.clearTimeout(timerProfile);

      //display the loading div
      _gel("div_loading").className = "on";
      
      //set the last updated time:
      if (username.toLowerCase() == "sebeda")
      {
        _gel('div_last_updated').className = "on";
        var currentTime = new Date();
       _gel("div_last_updated").innerHTML = "Last updated: " + currentTime.getHours() + ":" + currentTime.getMinutes();
      }
      
      //get the url we're requesting:
      urlProfile += username;

      
      //send the request
     _IG_FetchXmlContent(urlProfile, callbackProfile,{refreshInterval:120} );
     
     //begin the timeout to reload the profile:
     timerProfile = window.setTimeout('loadProfile()',(profile_pause*60000));
  }
    
  //callback function for the profile
  function callbackProfile(response)
  {
    //set the content and loading divs
    _gel("div_content").className = "on";
    _gel("div_loading").className = "off";
         
    //check the response - if there's an error:
    if (response == null || typeof(response) != "object" || response.firstChild == null)
    {
      _gel("div_content").innerHTML = "<p><i>Error: That WeeWar user does not exist or the WeeWar server is not responding.</i></p>";

      //begin the timeout to reload the profile:
      timerProfile = window.setTimeout('loadProfile()',20000);
      return;
    }
    else
    {           
      //Get the rest of the data, which we want to do every time
      var victories = response.getElementsByTagName("victories")[0].firstChild.nodeValue;
      var losses = response.getElementsByTagName("losses")[0].firstChild.nodeValue;
      var draws = response.getElementsByTagName("draws")[0].firstChild.nodeValue;
      var points = response.getElementsByTagName("points")[0].firstChild.nodeValue;
           
      _gel("div_victories").innerHTML = "Victories: <strong>" + victories + "</strong>";
      _gel("div_losses").innerHTML = "Losses: <strong>" + losses + "</strong>";
      _gel("div_draws").innerHTML = "Draws: <strong>" + draws + "</strong>";
      _gel("div_points").innerHTML = "Points: <strong>" + points + "</strong>";
      _gel("div_win_loss").innerHTML = "Win/loss ratio: <strong>" + Math.round(parseFloat(victories/losses)*100)/100 + "</strong>";
      
      //get the game list every call
      gameList = response.getElementsByTagName("game");
      playerList = response.getElementsByTagName("preferredPlayers")[0].getElementsByTagName("player");
    
      //check if we're loading for the first time and if so, load the image
      if (firstLoad)
      {
        firstLoad = false;
        if (displayProfilePic)
        {
          var profileImage = response.getElementsByTagName("profileImage")[0].firstChild.nodeValue;
          //check if the user has not uploaded an image:
          if ( profileImage == "http://weewar.com/images/profile/" )
            _gel("img_profile").className = "off";
          else
          {
            //get the image using the igoogle cache:
            _gel("img_profile").src = _IG_GetImage(profileImage).src;
          }
        }
      
        //call the load game method on the first trip too:
        loadGames();
      }
   }
 }
  
  function loadGames()
  {
    //clear the past timeout
    window.clearTimeout(timerGames);
    window.clearTimeout(timerGamesLoading);
    gamesLoaded = false;
    _gel("div_loading_games").className = "on";
  
    //now get their games:
    for (var i=0; i<gameList.length; i++)
    {
      var gameId = gameList[i].firstChild.nodeValue;
      //get the game:
      var urlGame = "http://weewar.com/api1/game/" + gameId;

      _IG_FetchXmlContent(urlGame, callbackGames,{refreshInterval:0} );

    }//end the for loop
    //now set a timer to do it again
    timerGames = window.setTimeout('loadGames()', (games_pause*60000));
    checkGamesLoading();
  }
 
 //callback function for the games
  function callbackGames(response)
   {
        if (response == null || typeof(response) != "object" || response.firstChild == null)
	{
	}
	else
	{
          //get the xml
          var game_id = response.getElementsByTagName("game")[0].getAttribute('id');
    
          var gameName = response.getElementsByTagName("name")[0].firstChild.nodeValue;
	  var url = response.getElementsByTagName("url")[0].firstChild.nodeValue;
          var gameState = response.getElementsByTagName("state")[0].firstChild.nodeValue;
          var gameRound = response.getElementsByTagName("round")[0].firstChild.nodeValue;

          if ( gameState == "running" || gameState == "lobby" )
          {
	    //go through the playeres in the game and check if the active player is us:
            var players = response.getElementsByTagName("player");
	    var action = false;
	    for (var j = 0; j<players.length; j++)
	    {
	      if( players[j].getAttribute('current') )
	      {
                var currentPlayer = players[j].firstChild.nodeValue;
	        if (currentPlayer.toLowerCase() == username.toLowerCase())
	          action = true;
	      }
	    }
            //add or update the item in the lst
            var itemHtml = (action ? '<img src="http://weewar.com/images/message.gif" align="absmiddle" style="margin-right:5px;"/>' : '' ) +
	    '<a href="' + url + '" target="_blank">' + gameName + '</a> <span class="small">(Round ' + gameRound + ')</span>';
            addGameToList(game_id, itemHtml);
          }
          else //if the game is finished, remove it from the list
          {
            removeGameFromList(game_id);
          }
        }
  }
  function addGameToList( gameId, itemHtml )
  {
    //first check if the item already exists in the list
    var addItem = true;
    for (var i = 0; i < ul_games.childNodes.length; i++ )
    {
      if ( ul_games.childNodes[i].id.toString().indexOf(gameId) > -1)
      {
        ul_games.childNodes[i].innerHTML = itemHtml;
        addItem = false;
        break;
      }
    }
    //check if we're adding the item:
    if (addItem)
    {
      var item = document.createElement('li');
      item.id = "li_item_id_" + gameId;
      item.innerHTML = itemHtml;
      ul_games.appendChild(item);
    }
    gamesLoaded = true;
  }
  
  function removeGameFromList(gameId)
  {
    //go through the list and check if the game is in there:
    for (var i = 0; i < ul_games.childNodes.length; i++ )
    {
      //if this is the game id we're looking for:
      if ( ul_games.childNodes[i].id.toString().indexOf(gameId) > -1)
      {
        //remove the list item
        ul_games.removeChild(ul_games.childNodes[i]);
      }
    }
  }

  function displayGames()
  {
    ul_games.className = "on";
    ul_players.className = "off";
    _gel("link_games").style.fontWeight = "bold";
    _gel("link_players").style.fontWeight = "normal";
  }

  function displayPlayers()
  {
    ul_games.className = "off";
    ul_players.className = "on";
    _gel("link_games").style.fontWeight = "normal";
    _gel("link_players").style.fontWeight = "bold";
    
    //now check if we have preferred players and if the list is empty:
    if (playerList.length > 0 && ul_players.childNodes.length == 0)
    {
      for (var i=0; i < playerList.length; i++ )
      {
        //add the player to the list:
        var playerName = playerList[i].getAttribute("name");
        var item = document.createElement('li');
        item.id = 'player_id_' + playerList[i].getAttribute("id");
        item.innerHTML = '<a href="http://weewar.com/user/' + playerName + '" target="_blank" rel="friend">' + playerName + '</a>';
        ul_players.appendChild(item);
        //now load the profile for this player:
        loadPlayerProfile(playerName, item.id);
      }
    }
  }
    
    function loadPlayerProfile(playerName, item_id)
    {
      //get the url we're requesting:
      var url = 'http://weewar.com/api1/user/' + playerName;
      
      //create a loading icon:
      var loadingIcon = new Image();
      loadingIcon.style.margin = "0 5";
      loadingIcon.src = loadingImage.src;
      
      //add the icon to the list
      _gel(item_id).appendChild(loadingIcon);
     
      //send the request
     _IG_FetchXmlContent(url, function(response)
        {
          if (response == null || typeof(response) != "object" || response.firstChild == null)
	  {
	  }
	  else
	  {
            //get the player's profile:
            var points = response.getElementsByTagName("points")[0].firstChild.nodeValue;
            var wins = response.getElementsByTagName("victories")[0].firstChild.nodeValue;
            var losses = response.getElementsByTagName("losses")[0].firstChild.nodeValue;
            var draws = response.getElementsByTagName("draws")[0].firstChild.nodeValue;
            
            //remove the loading icon:
            _gel(item_id).removeChild(loadingIcon);
    
            //now update the list item html:      
            _gel(item_id).innerHTML += " <span class=\"small\">(W:" + 
              wins + ", L:" + 
              losses + ", D:" + 
              draws + " = " + points + " points)" + 
              "</span>";
          }
        },{refreshInterval:120}
       );
    }
  
    //function to check whether the game callbacks have finished
    function checkGamesLoading()
    {
      if ( gamesLoaded )
        _gel('div_loading_games').className = "off";
      else
        timerGamesLoading = window.setTimeout("checkGamesLoading()", 2000);
    }
  _IG_RegisterOnloadHandler(loadGadget);
  _IG_Analytics("UA-220874-14", "/weewar_profile");
  </script>
  ]]> 
  </Content>
</Module>
