<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs
    title="Pick Up Sticks"
    height="500px"
    description="Wave implementation of pick-up sticks"
    author="Bryan Bibat"
    author_email="bryan.bibat@gmail.com">
   <Require feature="wave"/>
   <Require feature="dynamic-height"/>
   <Require feature="locked-domain"/>
  </ModulePrefs>
  <Content type="html">
  <![CDATA[
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

  <script type="text/javascript">
  var NUMBER_OF_STICKS = 60;

  function waveParticipantUpdated() {
  
    var participants = wave.getParticipants();
    
    if (participants && participants.length > 0) {
    
      var str = "";
      var participantCount = 0;
      for (var i = 0; i < participants.length; i++) {
        var participant = participants[i];
        var pid = participant.getId();
        if(/@.*appspot\.com$/.exec(pid) != null ? true : false)
          continue;
        if(/@a\.gwave\.com$/.exec(pid) != null ? true : false)
          continue;
        str += "<div id='participant" + participantCount + "' style='padding:1px;border:1px solid #dddddd;margin:1px;'>";
        str += "<img height='30px' width='30px' src='" + participant.getThumbnailUrl() + "'>";            
        if (pid == wave.getViewer().getId())
          str += "me";
        else
          str += participant.getDisplayName();
        str += " <span id='score_" + participant.getId() +"'>0</span> points</div>";
        participantCount++;
      }
      document.getElementById("participants").innerHTML = str;
      gadgets.window.adjustHeight();
    }
        
  }
 
  function isVisible(clicked) {
    return wave.getState().get(clicked).split('|')[4] == "table"; 
  }
  
  function isLegalMove(clicked) {
    var state = wave.getState();
    
    var pos = state.get(clicked).split('|');
    var class = pos[0];
    var x = parseInt(pos[1]);
    var y = parseInt(pos[2]);
    var x2 = x + (pos[0] == "horizontal" ? 200 : 5);
    var y2 = y + (pos[0] == "horizontal" ? 5: 200);
    
    var start = parseInt(clicked.split("_")[1]);
    
    for (var i = start + 1; i < NUMBER_OF_STICKS; ++i) {
      pos = state.get('stick_' + i).split('|');
      
      if (pos[4] == "none") {
        continue;
      }
      var targetClass = pos[0];
      var targetX = parseInt(pos[1]);
      var targetY = parseInt(pos[2]);
      var targetX2 = targetX + (pos[0] == "horizontal" ? 200 : 5);
      var targetY2 = targetY + (pos[0] == "horizontal" ? 5: 200);

      if (x < targetX2 && x2 > targetX && y < targetY2 && y2 > targetY) {
        return false;
      }
    }
    
    return true;
  }

  function stateUpdated() {

    var state = wave.getState();
    var delta = {};
    var dirty = false;
    
    if (!state.get("time")) {
      delta["time"] = wave.getTime();
      //alert("time cleared");
      waveParticipantUpdated();
      dirty = true;
    }
     
    var participants = wave.getParticipants(); 
    
    for (var i = 0; i < participants.length; ++i) {
      var partId = participants[i].getId();
      
      if(/@.*appspot\.com$/.exec(partId) != null ? true : false) 
        continue;
      if(/@a\.gwave\.com$/.exec(partId) != null ? true : false)
        continue;
        
      //alert(partId + "_move");
      //alert(state.get(partId + "_move"));
       
      if (state.get(partId + "_move")) {
        var clicked = state.get(partId + "_move");
        
        if (isVisible(clicked)) {
          if (isLegalMove(clicked)) {
		        var pos = state.get(clicked).split('|');
		        class = pos[0];
		        x = parseInt(pos[1]);
		        y = parseInt(pos[2]);
		        color = pos[3];
		        delta[clicked] = class + '|' + x + '|' + y + '|' + color + '|none';
		        
		        if (!state.get(partId)) {
		          delta[partId] = "1";
		        } else {
		          delta[partId] = parseInt(state.get(partId)) + 1 ;
		        }
		        
          } else {
            if (!state.get(partId)) {
              delta[partId] = "-10";
            } else {
              delta[partId] = parseInt(state.get(partId)) - 10 ;
            }   
          }
        }
        delta[partId + "_move"] =  null;
        dirty = true;
        //process one move at a time 
        break;
      }
    }
    
    for (var i = 0; i < participants.length; ++i) {
      var partId = participants[i].getId();
      if(/@.*appspot\.com$/.exec(partId) != null ? true : false) 
        continue;
      if(/@a\.gwave\.com$/.exec(partId) != null ? true : false)
        continue;
      if (state.get(partId)) {
        document.getElementById("score_" + partId).innerHTML = state.get(partId);
      } else {
        document.getElementById("score_" + partId).innerHTML = "0";
      }
    }
    
    for (var i = 0; i < NUMBER_OF_STICKS; ++i) {
      var x = 0;
      var y = 0;
      var display = "none";
      var class = "horizontal";
      var color = "#FFFFFF";
      var pos = state.get('stick_' + i);
      if (!pos) {

        class = (Math.round(Math.random()) == 0) ? "horizontal" : "vertical";
        if (class == "horizontal") {
          x = Math.round(200 * Math.random());
          y = Math.round(295 * Math.random());
        } else {
          x = Math.round(395 * Math.random());
          y = Math.round(100 * Math.random());
        }
        
        display = "table";
        color = "rgb(" + (50 + Math.floor(206 * Math.random())) + ", " + (50 + Math.floor(206 * Math.random())) + ", " + (50 + Math.floor(206 * Math.random())) + ")";
        delta['stick_' + i] = class + '|' + x + '|' + y + '|' + color + '|' + display;
        
        dirty = true;
      } else {
        var pos = pos.split('|');
        class = pos[0];
        x = parseInt(pos[1]);
        y = parseInt(pos[2]);
        color = pos[3];
        display = pos[4];        
      }
      if (class == "horizontal") {
        if ($('#stick_' + i).hasClass("vertical")) {
          $('#stick_' + i).removeClass("vertical"); 
        }
        $('#stick_' + i).addClass("horizontal");
      } else {
        if ($('#stick_' + i).hasClass("horizontal")) {
          $('#stick_' + i).removeClass("horizontal"); 
        }        
        $('#stick_' + i).addClass("vertical");
      }
      $('#stick_' + i).css({left: x + 'px', top: y + 'px', position: 'absolute', display: display, background: color});
      
    }
    
    
    if (dirty) {
      delta["last_move"] = wave.getTime();
      state.submitDelta(delta);
    } else {
      checkWin();
    }
    gadgets.window.adjustHeight();
  }
  
  function checkWin() {
    var state = wave.getState();
    for (var i = 0; i < NUMBER_OF_STICKS; ++i) {
      var pos = state.get('stick_' + i).split('|');
      if (pos[4] == "table") {
        return false;
      } 
    }
    if ($("#winner").length == 1) {
      return false;
    }
    //game ended
    var participants = wave.getParticipants();
    var max = null;
    var maxId = new Array();
    for (var i = 0; i < participants.length; ++i) {
      var partId = participants[i].getId();
      
      if(/@.*appspot\.com$/.exec(partId) != null ? true : false) 
        continue;
      if(/@a\.gwave\.com$/.exec(partId) != null ? true : false)
        continue;
      
      if (!max) {
        max = state.get(partId) ? parseInt(state.get(partId)) : 0;
        maxId.push(partId);
      } else {
        curVal = state.get(partId) ? parseInt(state.get(partId)) : 0;
        if (curVal > max) {
          maxId = new Array();
          maxId.push(partId);
        } else if (curVal == max) {
          maxId.push(partId);
        }
      } 
    }
    
    var winners = "";
    if (maxId.length == 1) {
      winners = '<div id="winner">';
      winners += "<img height='30px' width='30px' src='" + wave.getParticipantById(maxId[0]).getThumbnailUrl() + "'>"; 
      if (maxId[0] == wave.getViewer().getId()) {
        winners += "You won with ";
      } else {           
        winners += wave.getParticipantById(maxId[0]).getDisplayName() + " won with ";
      }
      winners += max + " point" + (max == 1 ? "" : "s");
    } else {
      winners = "<div>It's a tie between ";
      for (var j = 0; j < maxId.length; j++) {
        if (j > 0) {
          winners += " and ";
        }
        winners += "<img height='30px' width='30px' src='" + wave.getParticipantById(maxId[j]).getThumbnailUrl() + "'>"; 
        if (maxId[j] == wave.getViewer().getId()) {
	        winners += "you";
	      } else {           
	        winners += wave.getParticipantById(maxId[j]).getDisplayName();
	      }
      }
      
    }
    winners += "! (" + Math.floor((state.get("last_move") - state.get("time")) /1000) + " seconds)</div>";
    $("#participants").append($(winners)); 
    gadgets.window.adjustHeight();
  }
  
  function reset() {
    wave.getState().reset();
  }
 
  function main() {

    if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(stateUpdated);
      wave.setParticipantCallback(waveParticipantUpdated);

      for (var i = 0; i < NUMBER_OF_STICKS; ++i) {
        var html = '<div id="stick_' + i + '" >&nbsp;</div>'
        div = $(html);
        
        div.click(function () { 
          var delta = {};
          //alert($(this).attr("id"));
			    delta[wave.getViewer().getId() + "_move"] = $(this).attr("id");
			    wave.getState().submitDelta(delta);
        });
        
	      $("#innercontainer").append(div);
	    }
    }
  };
  
  gadgets.util.registerOnLoadHandler(main);
  </script>

  <style>
  .horizontal {
    border-left: 1px solid #101010;
    border-top: 1px solid #101010;
    border-right: 1px solid #101010;
    border-bottom: 1px solid #101010;
    height:5px;
    width:200px;
    display: table;
    cursor: pointer;
    position: absolute;
    font-size:1px;
  }

  .vertical {
    border-left: 1px solid #101010;
    border-top: 1px solid #101010;
    border-right: 1px solid #101010;
    border-bottom: 1px solid #101010;
		height:200px;
		width:5px;
    display: table;
    cursor: pointer;
    position: absolute;
    font-size:1px;
  }


  </style>
  
  <div id="container">
    <h1>Pick Up Sticks</h1> <input type="button" value="reset" onclick="reset()" />
    <div id="innercontainer" style="width:400px; height:300px; border: 0px; position:relative">&nbsp;</div>
    <div id="participants"></div>
  </div>
]]></Content>
</Module>
