

this.Game = Class.create(Section,{
  service1:"http://www.brasilnetwork.tur.br/brnetwork/opencms/system/modules/br.com.brazilnetwork.twitcup/resources/",
  service2:"http://embratur-brasilnetwork-redesenho-des.agenciaclickdf.com.br/bn-site-des2/opencms/system/modules/br.com.brazilnetwork.twitcup/resources/",
  serviceCheck:"balancer.jsp?callback=?",
  serviceDo:"calculateTweets.jsp?callback=?",
  services:[],
  serviceIndex:-1,
  //servico:"/brnetwork/opencms/system/modules/br.com.brazilnetwork.twitcup/resources/calculateTweets.jsp",
  //servico:"http://embratur-brasilnetwork-redesenho-des.agenciaclickdf.com.br/bn-site-des2/opencms/system/modules/br.com.brazilnetwork.twitcup/resources/calculateTweets.jsp",
  //servico:"http://embratur-brasilnetwork-redesenho-des.agenciaclickdf.com.br/bn-site-des2/opencms/system/modules/br.com.brazilnetwork.twitcup/resources/calculateTweets.jsp",
  loadingUsuario: null,
  loadingAmigo: null,
  detailsUsuario: null,
  detailsAmigo: null,
  resultado: null,
  game: null,
  gameReady: false,
  goalElm:null,
  goals:null,
  totalTime:20000,
  gameTimer:null,
  letreiro:null,
  letreiroJS:null,
  
  initialize: function($super)
  {
    Game.ID = "game";
    $super( Game.ID );
    
    this.config();
  },
  
  config: function()
  {
    jQuery( "#usuario" ).append( this.getLoading() );
    this.loadingUsuario = jQuery( "#usuario .loading" );
    
     jQuery( "#amigo" ).append( this.getLoading() );
    this.loadingAmigo = jQuery( "#amigo .loading" );
    
    jQuery( this.loadingUsuario ).hide();
    jQuery( this.loadingAmigo ).hide();
    
    swfobject.embedSWF( "/brnetwork/export/system/modules/br.com.brazilnetwork.twitcup/resources/swf/game.swf", "fl_jogo", "600", "200", "9.0.0", "/brnetwork/export/system/modules/br.com.brazilnetwork.twitcup/resources/swf/expressInstall.swf", null, {wmode:"transparent"} );
    this.game = jQuery( "object#fl_jogo" )[0];
    
    swfobject.embedSWF( "/brnetwork/export/system/modules/br.com.brazilnetwork.twitcup/resources/swf/goal.swf", "fl_goal", "650", "450", "9.0.0", "/brnetwork/opencms/system/modules/br.com.brazilnetwork.twitcup/resources//expressInstall.swf", null, {wmode:"transparent"} );
    this.goalElm = jQuery( "object#fl_goal" )[0];
    
    swfobject.embedSWF( "/brnetwork/export/system/modules/br.com.brazilnetwork.twitcup/resources/swf/letreiro.swf", "fl_letreiro", "237", "83", "9.0.0", "/brnetwork/export/system/modules/br.com.brazilnetwork.twitcup/resources/swf/expressInstall.swf", {xml:"/brnetwork/opencms/system/modules/br.com.brazilnetwork.twitcup/resources/xml/letreiro.xml"}, {wmode:"transparent"} );
    this.letreiro = jQuery( "object#fl_letreiro" )[0];
    
    this.letreiroJS = new Letreiro;
  },
  
  getLoading: function()
  {
    return "<img src='/brnetwork/export/system/modules/br.com.brazilnetwork.twitcup/resources/img/loader.gif' class='loading' />";
  },
  
  doOpen: function($super)
  {
    $super();
    
    this.services = [],
    this.serviceIndex = -1,
    
    this.game = jQuery( "object#fl_jogo" )[0];
    this.goalElm = jQuery( "object#fl_goal" )[0];
    this.letreiro = jQuery( "object#fl_letreiro" )[0];
    
    jQuery( this.loadingUsuario ).fadeIn( 300 );
    jQuery( this.loadingAmigo ).fadeIn( 300 );
    //this.loadResultado();
    this.checkServices();
    
    this.onOpen();
  },
  
  doClose: function($super)
  {
    $super();
    
    this.letreiroJS.reset();
    if( gameReady ) this.letreiro.reset();
    jQuery( this.loadingUsuario ).hide();
    jQuery( this.loadingAmigo ).hide();
    
    jQuery( "#score_usuario" ).text( "0" );
    jQuery( "#score_amigo" ).text( "0" );
    
    jQuery( "#usuario .game" ).hide();
    jQuery( "#amigo .game" ).hide();
    
    this.onClose();
  },
  
  checkServices: function()
  {
    this.services = [ {path:this.service1,avaliable:"none"}, {path:this.service2,avaliable:"none"} ];
    for(var i = 0; i < this.services.length; i ++) this.checkService( i );
  },
  
  checkService: function( i )
  {
    var thisObj = this;
    jQuery.getJSON( this.services[i].path + this.serviceCheck, function(response){thisObj.onCheckService(response,i);} ); // delegate( thisObj, thisObj.onCheckService );
  },
  
  onCheckService: function(response, i)
  {
    this.services[i].avaliable = parseInt( response.totalRemaining ) > 0;
    if( this.services[i].avaliable ) this.serviceIndex = i;
    
    var remaining = false;
    for( var j = 0; j < this.services.length; j ++ ) remaining = this.services[j].avaliable == "none";
    
    if( !remaining )
    {
      this.serviceIndex == -1 ? this.showError() : this.loadResultado();
    } 
  },
  
  loadResultado: function()
  {
    jQuery.getJSON( this.services[this.serviceIndex].path + this.serviceDo, {user1:jQuery("#usuario input").val(), user2:jQuery("#amigo input").val()}, delegate( this, this.onLoadResultado ) );
  },
  
  onLoadResultado: function( request )
  {
    if( !request )
    {
      this.showError();
      return false;
    }
    
    this.resultado = request;
    if( this.resultado.erro )
    {
      this.showError();
      return false;
    }
    else
    {
      jQuery( this.loadingUsuario ).hide();
      jQuery( this.loadingAmigo ).hide();
      
      this.drawUsers();
      this.startGame();
    }
  },
  
  showError:function()
  {
    jQuery( "#erro" ).modal( {overlayClose:true} );
    SectionManager.openSection( Home.ID );
  },
  
  drawUsers: function()
  {
    var usuario = this.resultado.usuario;
    var amigo = this.resultado.amigo;
    this.displayUsuario = jQuery( "#usuario .game" );
    this.displayAmigo = jQuery( "#amigo .game" );
    
    this.drawUser( this.displayUsuario, usuario.nome, usuario.avatar, usuario.ataque, usuario.defesa );
    this.drawUser( this.displayAmigo, amigo.nome, amigo.avatar, amigo.ataque, amigo.defesa );
    
    jQuery( this.displayUsuario ).fadeIn( 300 );
    jQuery( this.displayAmigo ).fadeIn( 300 );
  },
  
  drawUser: function( container, name, avatar, attack, defense )
  {
    var strAvatar = '<div class="imgProfile"><img src="' + avatar + '" alt="avatar" /><div class="img"></div></div>';
    var strName = '<span class="name">@' + name + '</span>';
    var strInfo = ' <div class="info"><p>Attack: ' + attack + '%</p><p>Defense: ' + defense + '%</p></div>';
    
    jQuery( container ).html( strAvatar + strName + strInfo );
  },
  
  startGame: function()
  {
    if( gameReady )
    {
      this.game.reset();
      for(var i = 0; i < this.resultado.usuario.amigos.length; i ++) this.game.addPlayer( "left", this.resultado.usuario.amigos[i] );
      for(var i = 0; i < this.resultado.amigo.amigos.length; i ++) this.game.addPlayer( "right", this.resultado.amigo.amigos[i] );
      this.game.start();
    }
    else
    {
      this.startTimer();
    }
  },
  
  onGameLoaded: function()
  {
    this.game.begin();
    this.startTimer();
  },
  
  startTimer: function()
  {
    this.goals = [];
    var numGoals = this.resultado.usuario.gols + this.resultado.amigo.gols;
    var goalsUsuario = 0;
    var goalsAmigo = 0;
    var time = 0;
    var goalTeam;
    var t;
    for( i = 0; i < numGoals; i ++ )
    {
      t = this.totalTime / numGoals;
      t += ( Math.random() * 4000 ) - 2000;
      t = Math.max( Math.min( t, this.totalTime - t - 2000 ), time - t - 2500 );
      time += t;
      if( goalsUsuario >= this.resultado.usuario.gols ) goalTeam = "amigo";
      else if( goalsAmigo >= this.resultado.amigo.gols ) goalTeam = "usuario";
      else goalTeam = Math.floor(Math.random()*2) == 0 ? "usuario" : "amigo";
      goalTeam == "usuario" ? goalsUsuario ++ : goalsAmigo ++;
      this.goals.push( { time:time, done:false, team:goalTeam } );
    }
    
    this.letreiroJS.setTime( this.totalTime, 90 * 60000 );
    if( gameReady ) this.letreiro.setTime( this.totalTime, 90 * 60000 );
    this.gameTimer = new Timer( 100, delegate( this, this.tick ) );
    this.gameTimer.start();
    //this.letreiro.play();
    //this.endGame();
  },
  
  tick: function()
  {
    for( var i = 0; i < this.goals.length; i ++ )
    {
      if( this.gameTimer.time >= this.goals[i].time && this.goals[i].done == false )
      {
        this.goals[i].done = true;
        this.goal( this.goals[i] );
      }
    }
    
    this.letreiroJS.tick( this.gameTimer.time );
    if( gameReady ) this.letreiro.tick( this.gameTimer.time );
    if( this.gameTimer.time >= this.totalTime ) this.endGame();
  },
  
  goal: function( data )
  {
    this.drawGoal( data.team );
    jQuery("#goal").modal();
    //if(this.goalElm.play) this.goalElm.play();
    //this.game.reset();
    if( gameReady ) this.game.pause();
    this.gameTimer.pause();
    setTimeout( delegate( this, this.resume ), 2300 );
  },
  
  drawGoal: function(team)
  {
    var elm = team == "usuario" ? "#score_usuario" : "#score_amigo";
    var num = parseInt( jQuery( elm ).text() ) + 1;
    jQuery( elm ).text(num);
  },
  
  resume: function()
  {
    jQuery.modal.close();
    if( gameReady ) this.game.reset();
    if( gameReady ) this.game.begin();
    //if( gameReady ) this.letreiro.play();
    this.gameTimer.start();
  },
  
  endGame: function()
  {
    this.gameTimer.stop();
    if( gameReady ) this.game.clear();
    
    this.resultado.usuario.gols = parseInt( jQuery("#score_usuario").text() );
    this.resultado.amigo.gols = parseInt( jQuery("#score_amigo").text() );
    
    jQuery("#resultado").modal( {overlayClose:true, onClose:delegate(this, this.onPressNovamente)} );
    jQuery("#resultado #novamente").click( delegate( this, this.onPressNovamente ) );
    jQuery("#resultado #twittar").click( delegate( this, this.onPressTwittar ) );
    var winner = this.resultado.usuario.gols > this.resultado.amigo.gols ? this.resultado.usuario.nome : this.resultado.amigo.nome;
    if( this.resultado.usuario.gols == this.resultado.amigo.gols )
    {
      jQuery("#resultado p").text( "It's a tie!" );
    }
    else
    {
      jQuery("#resultado p").text( "@" + winner + " wins." );
    }
    
  },
  
  onPressTwittar: function()
  {
    pageTracker._trackEvent('world-cup','clique','twittar-resultado');
    var endereco = "http://migre.me/X49t";
    var tweet = "I challenged @" + this.resultado.amigo.nome + " and the score was " + this.resultado.usuario.gols + "x" + this.resultado.amigo.gols + ". Are you popular enough to beat me? " + endereco + " %23TwitCup";
    window.location.href = "http://twitter.com/home?status=" + tweet; //Utf8.encode(tweet);
  },
  
  onPressNovamente: function()
  {
    jQuery.modal.close();
    SectionManager.openSection( Home.ID );
  }
  
});

