var w1 = '';
var w2 = '';

var text = '';

function process(data){
  t = '';
  if (data) {
    if(data.length > 0){
      for (var i in data){
        t += '<li><a class="wrd" href="#">'+data[i]+'</a></li>';
      }
    } else {
      t += '<li>няма предложения за продължение</li>';
    }
  } else {
    t += '<li>няма предложения за продължение</li>';
  }
  $('#list').html(t);
}

function getWords(w1, w2) {
  $.post('/rpc/words', {'w1': w1, 'w2': w2}, process, "json");
  $('#new').focus();
}

$('#start').live('click', function(event) {
  event.preventDefault();
  w1 = $('#w1').val();
  w2 = $('#w2').val();
  if (w1 && w2){
    $('#command').hide();
    $('#composer').show();
    text += w1+' '+w2;
    getWords(w1, w2);
    renderText();
  } else {
    $('#error').addClass('error');
    $('#error').html('Моля, първо въведете думи в полетата.');
  }
});

$('#save').live('click', function(event){
  $('#composer').hide();
  $('#text').hide();
  $('#stih').val(text);
  $('#save_field').show();
});

$('#cancel').live('click', function(event){
  $('#composer').show();
  $('#text').show();
  $('#save_field').hide();
});

$('#add').live('click', function(event) {
  event.preventDefault();
  w3 = $('#new').val();
  $('#new').val('');
  if (w3){
    w1 = w2;
    w2 = w3;
    getWords(w1, w2);
    text += ' ' + w3;
    renderText();
  }
  $('#new').focus();
});

$('#new').live('keyup', function(e){
  if(e.keyCode == 13) {
    $('#add').click();
  }
});

$('#cr').live('click', function(event) {
  text += "\n";
  renderText();
});

$('.wrd').live('click', function(event) {
  event.preventDefault();
  w3 = $(this).html();
  if (w3){
    w1 = w2;
    w2 = w3;
    getWords(w1, w2);
    text += ' ' + w3;
  }
  renderText();
});

$('#save_final').live('click', function(event){
  event.preventDefault();
  $.post('/rpc/save', {'title': $('#title').val(), 'author': $('#author').val(), 'text': $('#stih').val()}, function(data){
    document.location = data;
  });
})

function renderText(){
  var nt = text.replace(/\n/g, '<br />')+' &larr;';
  $('#text').html(nt);
  $('#new').focus();
}
