var metadata;
var last_chat_message_id = 0;
var new_messages = 0;
var show_tips   = 0;
var winWidth    = 620;//Largura da resolução da tela
var winHeight   = 480;//Altura da resolução da tela
var gameW       = 620;//Largura
var gameH       = 480;//Altura
var chat_active = false;
var game_zoom   = 0;



/*********************************************************************
 * Funções de controle globais
 *********************************************************************/


function load_metadata(file) {
  var temp_metadata;

  $.get(file,
    '',
    function (transport) {
      temp_metadata = eval(transport)
    }, "json");

  metada = temp_metadata;
}

function get_metadata(attribute) {
  return metadata[attribute];
}

function toggle_collection() {
  $('#toggle_collection').fade(10)
  $('#toggle_collection_loading').fadeIn(350)
}

function MakeItSo(gameId){
  if((detectOS() == 'Windows') && (detectBrowser() == 'IE')) {
    window.open(gameId+'/fullscreen','windowname','fullscreen=yes,width=100,height=100');
  } else {
    onload=FullScreen(gameId);
  }
}

/**
 * Troca o jogo da página de fundo por um link
 */
function updateGamePage(game_id){
    $('#game_cont').attr('innerHTML', '<a href="javascript:iframe_reload('+game_id+')" class="active" style="padding: 230px 0px 230px 152px; float: left;">Clique aqui para exibir o jogo novamente</a>');
}

function iframe_reload(game_id){
  $('#game_cont').attr('innerHTML', '<iframe frameborder="0" id="iframe_game" src="/games/iframe/'+game_id+'"/>');
}



/*********************************************************************
 * Funções para cálculo da resolução e tamanho dos games
 *********************************************************************/
function calcResolution(){
  var adjWidth;
  var adjHeight;

  if((detectOS() == 'Macintosh') && (detectBrowser() == 'Netscape')) {
    adjWidth = 20;
    adjHeight = 35;
  }
  if((detectOS() == 'Macintosh') && (detectBrowser() == 'IE')) {
    adjWidth = 20;
    adjHeight = 35;
    winOptions = 'fullscreen=yes';
  }
  if((detectOS() == 'Windows') && (detectBrowser() == 'Netscape')) {
    adjWidth = 30;
    adjHeight = 30;
  }
  winWidth = screen.availWidth - adjWidth;
  winHeight = screen.availHeight - adjHeight;
}

/**
 * Calcula a altura e largura do jogo para que se mantenham as proporções do game
 * levando-se em consideração a área livre no navegador e a resolução do usuário
 */
function calcGameResolution(widthGame, heightGame){

  var browser = detectBrowser();
  if(browser=='Netscape'){//Firefox e outros
    var freeWidth   = window.innerWidth;
    var freeHeight  = window.innerHeight;
    
    //alert('FIREFOX '+freeWidth+' - '+freeHeight);
  }
  else{//Internet Explorer
    var freeWidth   = document.documentElement.clientWidth;
    var freeHeight  = document.documentElement.clientHeight;
    //alert('IE w'+freeWidth+' - '+freeHeight);
  }
''

  var widthFactor  = freeWidth/widthGame;
  var heightFactor = freeHeight/heightGame;
  var factor;

  if(widthFactor<heightFactor){
    factor = widthFactor;
  }
  else{
    factor = heightFactor;
  }

  gameW = factor*widthGame;
  gameH = factor*heightGame;
}

function FullScreen(gameId){
  calcResolution();
  var winSize = 'width=' + winWidth + ',height=' + winHeight;
  var thewindow = window.open(gameId+'/fullscreen', 'WindowName', winSize);
  thewindow.moveTo(0,0);
}





/******************************************************************
 * FUNÇÕES DE REDIMENSIONAMENTO DE JOGOS                          *
 ******************************************************************/

/**
 * Redimensiona um elemento de acordo com o id ou classe no formato Jquery passado como parametro e os
 * parametros width e height
 */
function box_resize(width, height, id){
  $(id).width(width+'px');
  $(id).height(height+'px');
}

/**
 * Redimensiona qualquer elemento que esteja dentro do iframe de jogos, de acordo
 * com o id e parametros de altura e largura
 */
function iframe_box_resize(width, height, id){
    var game_box = window.frames[0].document.getElementById(id);
    game_box.style.width = width-20;//Retira 20 pixels para evitar a geração de scroll em determinados navegadores dentro do iframe
    game_box.style.height = height-20;
}

/**
 * Redimensiona tudo o que estiver dentro do iframe de jogos, incluindo ele
 */
function resize_game_internal(){

   var default_width = 600;
   var default_height = 450;

   var width = default_width+parseInt(default_width*game_zoom/100);
   var height = default_height+parseInt(default_height*game_zoom/100);

  iframe_box_resize(width, height, 'game_screen');
  iframe_box_resize(width, height, 'game_holder_internal');
  box_resize(width, height, '#iframe_game');
}

/**
 * Redimensiona tudo o que for externo ao iframe de jogo
 */
function resize_game_external(){
  var default_width = 914;
  var default_height = 505;
  var default_width_game = 600;
  var default_height_game = 450;

  var width = (default_width_game+parseInt(default_width_game*game_zoom/100)+10);//290
  var height = (default_height_game+parseInt(default_height_game*game_zoom/100)+20);

  if(width>=default_width){
    box_resize(width, height, '#gamebox');
  }
  else{
    if( height>=default_height){
       box_resize(default_width, height, '#gamebox');
    }
    else{
      box_resize(default_width, default_height, '#gamebox');
    }
  }
  
  box_resize(width, height, '#overloader');
  margin_update(default_width);

  default_width = 600;
  default_height = 450;
  width = default_width+parseInt(default_width*game_zoom/100);
  height = default_height+parseInt(default_height*game_zoom/100);
  box_resize(width, height, '#game_cont'); //Tem que ter o mesmo tamanho do jogo
}

/**
 * Atualiza a margem do container
 */
function margin_update(default_width){
    var margin = ($('#gamebox').width()-default_width)/2;
    $('#gamebox').css('margin-left', '-'+margin+'px');
}


/**
 * Redimensiona um jogo de acordo com a action passada como parametro.
 * action: amplify = Amplia 15% da dimensão do jogo
 *         reduce  = Reduz 15% o tamanho do jogo
 */
function resize_game(action){

  var game_flash = window.frames[0].document.getElementById('game_screen');
  
  if(game_flash){

    switch(action){
      case 'amplify':
          $('#game_restore_button').show();
          game_zoom += 10;
        break;
      case 'reduce':
          $('#game_restore_button').show();
          game_zoom -= 10;
        break;
      case 'restore':
          $('#game_restore_button').hide();
          game_zoom = 0;
        break;
      case 'restore_game':
          $('#game_restore_button').show();
        break;
    }
    resize_game_external();
    resize_game_internal();
  }
}


function fullScreen(gameId){
  resize_game('restore')
  MakeItSo(gameId);
  updateGamePage(gameId);
}

/**********************************************************************
 * FUNÇÕES PARA O CONTROLE DO CHAT                                    *
 **********************************************************************/

function chat_refresh(game_id){
  $.ajax({
    data: 'last_id=' + last_chat_message_id ,
    dataType:'script',
    type:'post',
    url:'/chat/update_chat/' + game_id
  }
  );
}

function view_chat_msg_window() {
  open_chat_tab();
  chat_active = true;
  $("#game_chat_users").attr('class', 'chat-wrap hide');
  $("#game_chat_messages_holder").attr('class', 'chat-wrap show');
  tab_unclass_active();
  $("#chat_messages").removeClass('hscore');
  $("#chat_messages").addClass('hscore-active');
  
  $("#chat_messages").scrollTo('max');
}

function view_chat_users_window() {
  chat_active = true;
  $("#game_chat_messages_holder").attr('class', 'chat-wrap hide');
  $("#game_chat_users").attr('class', 'chat-wrap show');
  tab_unclass_active();
  $("#chat_users").removeClass('hscore');
  $("#chat_users").addClass('hscore-active');
}

function game_chat_sending() {
  view_chat_msg_window();
	$('#message').hide();
  $('#game_chat_submit').hide();
  $('#game_chat_loading').show();
}

function tab_unclass_active() {
  $("#chat_messages").removeClass('hscore-active');
  $("#chat_messages").addClass('hscore');
  $("#chat_users").attr('class', 'hscore');
  $("#scores_general").attr('class', 'hscore');
  $("#friends_scores").attr('class', 'hscore');
}

function toggle_tips() {
  if (show_tips == 1) {
    $("#baloon_holder").hide();
    $("#baloon_close_holder").hide();
    $("#baloon_btn").attr('class', 'bt-open');
    show_tips = 0;
  }
  else {
    $("#baloon_holder").show();
    $("#baloon_close_holder").show();
    $("#baloon_btn").attr('class', 'bt-close');
    show_tips = 1;
  }
}

function set_new_message() {
  if ( (! $("#chat_messages").hasClass('talk-active')) && (! $("#chat_messages").hasClass('active')))
  {
    new_messages = 1;
    check_new_messages();
  }
}

function check_new_messages() {
  if (new_messages == 1) {
    $("#chat_messages").addClass('talk-active');
  } else {
    $("#chat_messages").removeClass('talk-active');
  }
}




/**********************************************************************
 * FUNÇÕES PARA O CONTROLE DE ABAS                                    *
 **********************************************************************/

/**
 * Fecha todas as abas abertas
 */
function close_all_tabs(){
  $('#hscores').hide();
  $('#chat').hide();
  $('#commands').hide();
  $('#hscores_button').removeClass('active');
  $('#chat_button').removeClass('active');
  $('#commands_button').removeClass('active');
}

function open_commands(){
  close_all_tabs();
  $('#commands').show();
  $('#commands_button').addClass('active');
  $('#sep_one').hide();
  $('#sep_two').show();
}



/**
 * Funções de gerenciamento da aba de highscores
 */
function open_hscores(){
  close_all_tabs();
  $('#hscores-global').show();
  $('#hscores_button').addClass('active');
  $('#sep_two').hide();
  $('#sep_one').hide();
}
function open_global_hscores(){
  $('#hscorelist-friend').hide();
  $('#hscorelist-global').show();
  $('#hscores_friends_button').removeClass('active').addClass('inactive');
  $('#hscores_global_button').addClass('active').removeClass('inactive');
}
function open_friends_hscores(){
  $('#hscorelist-friend').show();
  $('#hscorelist-global').hide();
  $('#hscores_friends_button').addClass('active').removeClass('inactive');
  $('#hscores_global_button').removeClass('active').addClass('inactive');
}


/**
 * Funções de gerenciamento da aba do chat
 */
function open_chat(){
  close_all_tabs();
  $('#chat').show();
  $('#chat_button').addClass('active');
  $('#sep_one').show();
  $('#sep_two').hide();
}
function open_otzees(){
  $('#chat_otzees_button').addClass('active');
  $('#chat_messages').removeClass('active');
  $('#game_chat_messages_holder').hide();
  $('#game_chat_users').show();
}
function open_chat_tab(){
  $('#chat_otzees_button').removeClass('active');
  $('#chat_messages').addClass('active');
  $('#game_chat_messages_holder').show();
  $('#game_chat_users').hide();
	new_messages = 0;
  if ($("#chat_messages").hasClass('talk-active')) {
    $("#chat_messages").removeClass('talk-active');
  }
}





/**
 * Controla a troca de abas posicionadas ao lado do jogo
 */
function tabs_game_controller(){
  $('#commands_button').click(open_commands);

  $('#chat_button').click(open_chat);
  $('#chat_messages').click(open_chat_tab);
  $('#chat_otzees_button').click(open_otzees);


  $('#hscores_button').click(open_hscores);
  $('#hscores_friends_button').click(open_friends_hscores);
  $('#hscores_global_button').click(open_global_hscores);
  
  $('#sep_one').hide();
}

/**
 * game_concept - Conceito do jogo
 * user_concept - Conceito do jogo para o usuário
 */
function ratio_update(game_concept, user_concept){
  $('#stars').width(user_concept);
  $('#my_concept').attr('innerHTML', user_concept);
  $('#game_concept').width(game_concept).attr('innerHTML', 'Conceito desse jogo: '+game_concept);
}

