jQuery(document).ready(function($) {
  $(document).keypress(function(e) {
    if (((e.keyCode == 13 && e.ctrlKey) || (e.keyCode == 10)) && $('#user-spell-block').css('display') == 'none') {
      var text = user_spell_get_selected_text();
      if (text.length == 0)
        return;

      $('#user-spell-form-text').text(text);
      user_spell_center_div();
      $('#user-spell-block').show();
      $('#user-spell-form-comment').focus();
    }
    else if (e.keyCode == 27 && $('#user-spell-block').css('display') != 'none') {
      user_spell_hide_block();
    }
  });
  
  $('#user-spell-form-cancel').click(function() {
    user_spell_hide_block();
  });
  
  $('#user-spell-form-send').click(user_spell_send);
  $('#user-spell-form').submit(function() {
    user_spell_send();
    return false;
  });
  
  $(window).resize(user_spell_center_div);
  $(document).scroll(user_spell_center_div);
  
  function user_spell_center_div() {
    var obj = $('#user-spell-block');
    var height = window.innerHeight || $(window).height();
    var top = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
      
    obj.css('top', top + height / 2 - obj.height() / 2);
    obj.css('left', $(window).width() / 2 - obj.width() / 2); 
  }
  
  function user_spell_hide_block() {
    $('#user-spell-form-comment').val('');
    $('#user-spell-block').hide();
  }
  
  function user_spell_send() {
    var data = {
      'url' : location.href,
      'text' : $('#user-spell-form-text').text(),
      'comment' : $('#user-spell-form-comment').val()
    };
    
    $.ajax({
      url : user_spell_ajax_url,
      type: "POST",
      data : data,
      success : function() { alert('Ваше сообщение отправлено. Спасибо за помощь!'); },
      error : function() { alert('Произошла ошибка :(' ); }
    });
    
    $('#user-spell-block').hide();
    $('#user-spell-form-comment').val('');
  }
});

function user_spell_get_selected_text() {
  if (window.getSelection)
    return window.getSelection().toString();
  else if (document.getSelection)
    return document.getSelection();
  else if (document.selection)
    return document.selection.createRange().text;
}

