function urlEncode( s )
{
  return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
}

function urlDecode( s )
{
  return decodeURIComponent( s.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) );
}

function showBlackBg(mode){
  if (mode == 'on'){
    $('#black_bg').fadeIn();
  }
  else{
    $('#black_bg').fadeOut();
  }
}

function showQuestion(mode){
  if (mode == 'on'){
    $('#question').fadeIn();
  }
  else{
    $('#question').fadeOut();
  }
}

function closeQuestion(){
  showQuestion('off');
  showBlackBg('off');
  
  $('#question_name').html('');
  $('#question_question').html('');
  $('#hdn_question').val('');
  
  $('#question_result').html('');
  $('#question_result').hide();
  
  $('#answer').val('');
}

function loadQuestion(id){
  $.ajax({
    url: '/eljuegodeana/api/question',
    data: 'id='+id,
    type: 'POST',
    dataType: 'json',
    success: function(data){
      if (data.status=='ok'){
        $('#question_name').html(urlDecode(data.name));
        $('#question_question').html(urlDecode(data.question));
        $('#hdn_question').val(id);
        showBlackBg('on');
        showQuestion('on');
        $('#answer').focus();
      }
      else{
        alert('Ocurrió un error :(');
      }
    }
  });
}

function answer(){
  var resp = $('#answer');
  if (resp.val() == ''){
    alert('¡No puedes dejar la respuesta en blanco!');
    resp.focus();
    return false;
  }
  
  var preg = $('#hdn_question');
  
  $.ajax({
    url: '/eljuegodeana/api/answer',
    data: 'id='+preg.val()+'&answer='+urlEncode(resp.val()),
    type: 'POST',
    dataType: 'json',
    success: function(data){
      if (data.status=='ok'){
        $('#question_result').html('Bien!');
        $('#question_result').show();
        
        var q = $('#q_'+data.id);
        q.removeClass('closed');
        q.addClass('open');
        q.html('Abierto');
        q.attr('onclick','');
        
        if (data.num == 0){
          setTimeout('allAnswered()',1200);
        }
        
        setTimeout('closeQuestion();',1000);
      }
      else{
        $('#question_result').html('Mal!');
        $('#question_result').show();
        
        $('#answer').select();
      }
    }
  });
}

function allAnswered(){
  showBlackBg('on');
  $('#all_answered').show();
}
