
$(function() {

  if (false) {
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
  } else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
  }
  load_user_info();
});

function onBlur() {
  disable_all_func();
}

function onFocus() {}

function _init_start() {
  prepare_html();
}

function _init_events_render() {
  text_img_extremes();
  if (cache.first_loaded_xml === undefined) {
    prepare_menu_toggle();
    activate_dialogs();
    prepare_keyborad();
    activate_split_move();
    add_history_step('first');
    show_layer_tools(false);

    prepare_font_change_toolbar();
    generate_type_index_array();
    update_main_selects();
    cache.first_loaded_xml = true;
    setTimeout(switch_dictionary_env, 100);
  }
  set_events();
  set_key_bind_events();
  remove_content_chars();
  hide_meta_spans();
  disable_select_focus();
  activate_font_change_toolbar(true);
}

function render_main_selects() {
  render_record_type_select();
  render_dictionary_author_select();
  render_block_author_select();
  render_block_editor_select();
}

function disable_select_focus() {
  $('toptoolbar').find('select').each(function() {
    $(this).focus(function() {
      $(this).blur();
    });
  });
}

function switch_dictionary_env() {
  switch (get_url_params().dict) {
    case "SJS":

      break;
    case "MS":
      $('#dictionary_author_change_toolbar i').attr('title', 'Autor hesla');
      $('#author_change_toolbar').remove();
      break;
    case "RSI":
      $('#dictionary_author_change_toolbar i').attr('title', 'Autor hesla v ŘSI');
      $('#author_change_toolbar2').remove();
      $('#author_change_toolbar').remove();
      break;
    default:
      break;
  }
}

function meta_reorder() {
  var metadata = $(pageparts_div).last().find('metadata alto').clone();
  var page = $(pageparts_div).last().find('metadata pageinfo page').clone();
  if ($(pageparts_div).first().find('metadata pageinfo page').attr('id') !== $(pageparts_div).last().find('metadata pageinfo page').attr('id')) {
    $(pageparts_div).first().find('metadata').append(metadata);
    $(pageparts_div).first().find('metadata').find('pageinfo').append(page);
  }
  $(pageparts_div).last().find('metadata').remove();
  var html = $($(pageparts_div).last().html());
  $(pageparts_div).first().append(html)
  $(pageparts_div).last().remove();
  $(pageparts_div).append($(pageparts_div).find('metadata'));
}

function handle_lock_on_file(json) {
  clearInterval(check_interval);
  set_error_dialog(error_when_loading_record);
}

function get_xml_vers_from_json() {
  get_xml_vers_response(cache.full_record_json.gorazd_paths);
}

function get_xml_vers_response(json) {
  var select = render_xml_vers_select(json);
  var params = get_url_params();
  if (params.xmlVers == undefined) {
    select.find('option:last').prop('selected', true);
  }
  var div = $('<div/>');
  var text = select_xml_vers_text;
  div.append(text).append(select);
  set_confirm_dialog(div, xml_vers_load_accept, 500, 250, "Zrušit", "Načíst verzi", undefined, undefined, true);
}

function xml_vers_load_accept(dia) {
  var params = get_url_params();
  if (params.xmlVers != undefined) {
    location.href = location.href.replace('xmlVers=' + cache.loaded_version, 'xmlVers=' + dia.find('option:selected').val())
  } else {
    location.href = location.href + '&xmlVers=' + dia.find('option:selected').val();
  }


  start_full_loader(true);
}

function get_xml_vers_error(json) {
  set_error_dialog(error_loading_xml_vers, 500, 150, true);
}

function cancel_xml_edit_response(json) {
  switch (json.resultCode) {
    case 107:
      set_error_dialog(error_record_open_multiple, 500, 150, true);
      break;
    case 111:
      set_error_dialog(error_record_close_error, 500, 150, true);
      break;
    default:
      show_hint_msg("Hotovo zavírám", true);
      setTimeout(function() {
        window.close();
      }, 1000);
      break;
  }
}

function cancel_xml_edit_error(json) {
  switch (json.resultCode) {
    case 107:
      set_error_dialog(error_record_open_multiple, 500, 150, true);
      break;
    case 111:
      set_error_dialog(error_record_close_error, 500, 150, true);
    default:
      set_error_dialog("Chyba na serveru", 500, 150, true);
      break;
  }
  console.log(json);
}

function generate_color_type() {
  var co = [];
  var result = {};
  for (var i in text_styling) {
    result[i] = text_styling[i][1];
  }
  aip_type_colors = result;
}

function toggle_top_menu() {
  $('.pageheader').slideToggle(1000);
  $('.menu_button').toggleClass('menu_button_active_menu');
}

function remove_content_chars() {
  $(pageparts_div).find(span).each(function() {
    for (var i in not_all_chars) {
      var text = String($(this).attr(content));
      var char_ = not_all_chars[i];
      $(this).attr(content, text.replace(char_.ch, char_.val));
    }
  });
}

function prepare_menu_toggle() {
  toggle_top_menu();
  var menu_button = $('<button class="menu_button" onclick="toggle_top_menu();"><i class="material-icons">menu</i></buttton>');
  $(body).append(menu_button);
}

function save_file(name, data, end = "txt") {
  var text = data;
  var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
  saveAs(blob, name + "." + end);
}

function check_url() {

  var params = get_url_params();
  cache.url_params = params;
  if (params.recid !== undefined) {
    cache.load_record_id = params.recid;

    check_mysql_backup(cache.load_record_id);
  } else {
    var rec = prompt(" Zadejte prosím ID pro načtení ", "");
    if (rec != null && isNaN(parseInt(rec)) == false) {

      cache.load_record_id = rec;

      check_mysql_backup(cache.load_record_id)
    } else {
      set_error_dialog(error_when_loading_record);
    }
  }
}

function save_user_info(json) {
  cache.user_json = JSON.parse(json);
}

function load_invenio_xml() {
  start_full_loader(true);
  load_record(cache.load_record_id, load_record_callback);
}

function start_check_interval() {
  check_interval = setInterval(function() {
    check_iter++;
    if (check_iter == 15) {
      set_error_dialog(error_loading_timeout, undefined, 230);
    }
  }, 1000);
}

function handle_check_mysql_backup(data) {
  var params = get_url_params();
  if (data == "null" || data === null) {
    load_record(cache.load_record_id, load_record_callback);
    start_check_interval();
  } else {

    var obj = JSON.parse(data);
    if (cache.user_json === undefined) {
      setTimeout(function() {
        check_mysql_backup(cache.load_record_id);
      }, 200);
    } else {
      if (obj.status == "save") {
        if (params.xmlVers == undefined) {
          if (cache.user_json.userInfo.uid != JSON.parse(obj.user_json).uid) {
            set_error_dialog(error_record_taken(JSON.parse(obj.user_json).name));
          } else {
            set_confirm_dialog(error_record_backup_found, load_invenio_xml, 500, 200, "Obnovit zálohu", "Načíst záznam z invenia", load_mysql_backup, true)
          }
        } else {
          load_invenio_xml();
        }
        start_full_loader(false);
      }
      if (obj.status == "error") {
        if (cache.user_json.userInfo.uid != JSON.parse(obj.user_json).uid) {
          set_error_dialog(error_record_taken(JSON.parse(obj.user_json).name));
        } else {
          set_confirm_dialog(error_record_save_error, load_invenio_xml, 500, 200, "Obnovit zálohu", "Načíst záznam z invenia", load_mysql_backup, true)
        }
        start_full_loader(false);
      }
      if (obj.status == "saving") {
        if (cache.user_json.userInfo.uid != JSON.parse(obj.user_json).uid) {
          set_error_dialog(error_record_taken(JSON.parse(obj.user_json).name));
        } else {
          start_ask_interval();
          set_error_dialog(error_record_saving);
        }
        start_full_loader(false);
      }
    }

  }
}

function start_ask_interval() {
  saved_interval = setInterval(function() {
    save_iter++;
    check_mysql_backup_interval()
    if (save_iter == 25) {
      set_error_dialog(error_record_long_saving);
    }
    if (save_iter == 150) {
      set_error_dialog(error_record_not_saving);
    }
  }, 1000);
}

function handle_check_mysql_backup_interval(json) {
  if (json.status == "error") {
    clearInterval(saved_interval);
    reaload_page();
  }
  if (json == "null" || json === null) {
    clearInterval(saved_interval);
    reaload_page();
  }

}

function reaload_page() {
  location.reload();
}

function change_el_index(el, index) {
  switch (index) {
    case "":
      el.attr('aip-index', '');
      el.css({'text-decoration': 'none'});
      break;
    case "dolni":
      el.attr('aip-index', index);
      el.css({'text-decoration': 'overline'});
      break;
    case "horni":
      el.attr('aip-index', index);
      el.css({'text-decoration': 'underline'});
      break;
  }
  refresh_all_info()
}

function handle_load_errors(json, wat = false) {
  if (json.resultCode == 105) {
    set_error_dialog(error_record_saving);
  }
  if (json.resultCode == 104) {
    set_error_dialog(error_record_locked);
  }
  if (json.resultCode == 102) {
    set_error_dialog(error_record_not_exists);
  }
  if (json.resultCode == 111) {
    set_error_dialog(error_record_corrupted);
  }
  if (json.resultCode != 3 && wat) {
    setTimeout(function() {
      dialog_uni.dialog('close');
      start_full_loader(false);
    }, 5000);
  }
}

function merge_load_record_callback(json) {
  handle_load_errors(json, true);
  if (json.resultCode == 3) {
    var temp = json;
    switch (get_url_params().dict) {
      case "SJS":
        break;
      case "MS":
        cache.merge_load_temp_record = json;

        displayResult(cache.load_xml, in_xsl);
        break;
      case "RSI":
        cache.merge_load_temp_record = json;

        displayResult(cache.load_xml, in_xsl);
        break;
      default:

        cache.merge_load_temp_record = json;


        cache.load_img = temp.record['956'];
        cache.pages_num = temp.record['956'].length / 2;
        cache.pages = temp.record['956'].length / 2;
        var time = 0;
        var imgs = temp.record['956'];
        var img_sort = [];
        var ex_arr = {};
        var uc_arr = {};
        for (var i in imgs) {
          if (imgs[i][0][0][1].indexOf('EX') == -1) {
            img_sort.push(get_base_editor_url() + "/datastorage/" + find_img_walkaround(imgs[i]));
            uc_arr[get_base_editor_url() + "/datastorage/" + find_img_walkaround(imgs[i])] = imgs[i];
          } else {
            ex_arr[get_base_editor_url() + "/datastorage/" + find_img_walkaround(imgs[i])] = imgs[i];
          }
        }
        var error = 0;
        img_sort.sort();
        for (var i in img_sort) {
          var url = img_sort[i];
          $('canvas').each(function() {
            if ($(this).css('background-image').replace('url("', '').replace('")', '') == url) {
              error++;
              cache.pages--;
            }
          });
          if (error == 0) {
            cache.full_record_json.record['956'].push(uc_arr[url]);
            cache.full_record_json.record['956'].push(ex_arr[url.replace('UC', 'MC').replace('N1', 'EX').replace('N1', 'EX')]);
            set_page_image(url.replace('N3', 'N1').replace('N3', 'N1'), time);
            time++;
          }
        }
        if (error != 0) {
          displayResult(cache.load_xml, in_xsl);
        }
        break;
    }
  }
}

function find_img_walkaround(imgs) {
  for (var i in imgs) {
    var sub = imgs[i];
    if (typeof sub == 'object') {
      for (var j in imgs) {
        if (sub[j] && sub[j][0] == 'u') {
          return sub[j][1];
        }
      }
    }
  }
}

function load_record_callback(json) {
  handle_load_errors(json);
  cache.loaded_dict = json.record['035'][0][0][0][1].split('_')[0].toUpperCase();
  assign_xml_();
  assing_styles_();
  generate_color_type();
  render_main_selects();

  switch (get_url_params().dict) {
    case "SJS":
      break;
    case "MS":
      clearInterval(check_interval);
      if (json.resultCode == 3) {
        var temp = json;
        cache.full_record_json = temp;

        displayResult(cache.load_xml, in_xsl);
        clearInterval(check_interval);
      }
      break;
    case "RSI":
      clearInterval(check_interval);
      if (json.resultCode == 3) {
        var temp = json;
        cache.full_record_json = temp;

        displayResult(cache.load_xml, in_xsl);
        clearInterval(check_interval);
      }
      break;
    default:
      clearInterval(check_interval);
      if (json.resultCode == 3) {
        var temp = json;
        if (temp.record['956'] == undefined || temp.record['856'] == undefined) {

          setTimeout(function() {
            start_full_loader(false);
          }, 500);
          set_confirm_dialog(error_record_corrupted, reaload_page, 500, 200, "Zkusit znovu", undefined, undefined, true)
        }
        cache.full_record_json = temp;

        if (temp.record['956']) {
          cache.load_img = temp.record['956'];
          cache.pages_num = temp.record['956'].length / 2;
          cache.pages = temp.record['956'].length / 2;
        }
        var time = 0;
        var imgs = temp.record['956'];
        var img_sort = [];
        for (var i in imgs) {
          if (imgs[i][0][0][1].indexOf('EX') == -1) {
            img_sort.push(get_base_editor_url() + "/datastorage/" + find_img_walkaround(imgs[i]));
          }
        }
        img_sort.sort();
        for (var i in img_sort) {
          set_page_image(img_sort[i].replace('N3', 'N1').replace('N3', 'N1'), time);
          time++;
        }
      }
      break;
  }
}

function set_page_image(url, i) {

  var img = $('<img onload="store_img_temp_($(this),' + i + ');" src="' + url + '">');
  $(body).append(img);

}

function get_base_editor_url() {
  pathArray = location.href.split('/');
  protocol = pathArray[0];
  host = pathArray[2];

  return url;
}

function store_img_temp_(img, i) {
  cache.pages--;
  cache.img_temp_store[i] = img;
  if (cache.pages == 0) {
    var temp = cache.img_temp_store;
    for (var j in temp) {
      continue_img_size(temp[j], j);
    }
  }

function continue_img_size(img, order) {
  cache.pages_num--;
  img.hide();
  var obj_i = {};
  if (cache.img_prev_max_width < img.width() || cache.img_prev_max_width == undefined) {
    cache.img_prev_max_width = img.width();
  }
  obj_i.id = img.attr("src").split('N1/')[1].split('.')[0];
  obj_i.source_id = img.attr("src").split('N1/')[1].split('.')[0].replace('N1', 'EX');
  obj_i.img = img.attr("src").split('N1/')[1];
  obj_i.width = img.width();
  obj_i.height = img.height();
  cache.imgs.push(obj_i);
  var canvas_ = $('<canvas id="canvas_preview" class="' + img.attr("src").split('N1/')[1].split('.')[0] + '"></canvas>');
  $(canvas_).width(img.width()).height(img.height()).css({
    'background-image': 'url(' + img.attr("src") + ')'
  });
  $("#arround_page").append(canvas_);
  img.remove();
  if (cache.pages_num == 0) {
    if (cache.load_mysql_backup == undefined) {
      displayResult(cache.load_xml, in_xsl);
    } else {
      insert_html_start($(cache.load_mysql_backup.xml));
    }
  }
}

function recognize_xml_response(json) {
  console.log(json);
}

function clone_record_response(json) {
  cache.clone_resp_json = json;
  setTimeout(function() {
    start_full_loader(false);
    set_confirm_dialog("Záznam naklonován s id " + json.newRecID + "<i class='material-icons'>content_copy</i><br> Tlačítkem \"Zavřít\" se otevře záložka s klonem", open_new_clone_tab, 500, 250, "Zavřít", undefined, undefined, true);
  }, 500);
}

function clone_record_response_error(json) {
  set_error_dialog(error_record_clone, 500, 150, true);
}

function open_new_clone_tab() {
  window.open(get_base_editor_url() + "/record/gorazd_edit/?ln=cs&recid=" + cache.clone_resp_json.newRecID, '_blank');
}

function save_and_go() {
  var o = nodeToString($('pageparts div')[0]).replace(/\r?\n|\r/g, '');
  save_backup(o);
  setTimeout(function() {
    go_to_record(cache.clone_json.newRecID);
  }, 200);
}

function save_not_and_go() {
  go_to_record(cache.clone_json.newRecID);
}

function go_to_record(id) {
  location.href = get_base_editor_url() + "/record/gorazd_edit/?ln=cs&recid=" + id;
}

function save_record_status(val) {
  if ($(metadata).find('status').length == 0) {
    $(metadata).prepend('<status>' + val + '</status>')
  } else {
    $(metadata).find('status').html(val);
  }
  start_transform_from_html();
}

function save_block_status() {
  var text = "";
  if ($('.new_create').length > 0) {
    text += "\n Needitovaný blok v hesle";
  }
  if ($(pageparts_div).find('input').length > 0) {
    text += "\n Otevřená editace v hesle";
  }
  if ($(pageparts_div).attr('aip-type') == "") {
    text += "\n Typ záznamu prázdný";
  }
  if ($('span[aip-type="zahlavi"]').length == 0) {
    text += "\n Prázdné záhlaví <br>";
  }
  if ($(pageparts_div).attr('aip-type') == "odkazove") {
    if ($('span[aip-type="odkaz"]').length == 0) {
      text += "\n Není odkaz <br>";
    }
  }
  if ($(pageparts_div).attr('status') == "") {
    text += "\n Stav bloku prázdný <br>";
  }
  if (text == "") {
    return true;
  } else {
    set_confirm_dialog(text, prepare_select_block_status_dialog(false), 700, 200, "Zrušit", undefined);
    return false;
  }
}

function getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

function gtc() {
  var r = function() {
    return Math.floor(Math.random() * 256);
  };
  return "rgba(" + r() + "," + r() + "," + r() + ",'.4')";
}

function fullscreen() {
  var docElm = document.documentElement;
  if (docElm.requestFullscreen) {
    docElm.requestFullscreen();
  } else if (docElm.mozRequestFullScreen) {
    docElm.mozRequestFullScreen();
  } else if (docElm.webkitRequestFullScreen) {
    docElm.webkitRequestFullScreen();
  }
}


function update_main_selects() {
  $('#type_change_toolbar select').val($(pageparts_div).attr('aip-type'));
  if ($('metadata autor_slovniku').text() != "") {
    $('#dictionary_author_change_toolbar select').val($('metadata autor_slovniku').text());
  } else {
    $('metadata autor_slovniku').text(dictionary_author[0]);
  }
  if ($('metadata autor_hesla').text() != "") {
    $('#dictionary_author_change_toolbar select').val($('metadata autor_hesla').text());
  } else {
    $('metadata autor_hesla').text(dictionary_author[0]);
  }
  $('#author_change_toolbar select').val($('metadata autor_dodatku').text());
  $('#author_change_toolbar2 select').val($('metadata redaktor_hesla').text());
}

function update_font_change_select(span) {
  if (span.attr('aip-size') != undefined) {
    $('#font_change_toolbar select[wat="aip-size"]').val(translate_font_(span.attr('fontsize')));
  } else {
    $('#font_change_toolbar select[wat="aip-size"]').val(translate_font_(span.attr('fontsize')));
  }
  $('#font_change_toolbar select[wat="aip-style"]').val(span.attr('aip-style'));
  $('#font_change_toolbar select[wat="lang"]').val(trasnlate_attr_(span.attr('aip-font')));
  $('#font_change_toolbar select[wat="aip-index"]').val(span.attr('aip-index'));
}

function trasnlate_attr_(attr, el = "", re = false) {
  switch (attr) {
    case "italics":
      el.css('font-weight', '');
      el.css('font-style', 'italic');
      if (re) {
        return 'italics';
      }
      break;
    case "Tučně":
    case "tucne":
    case "bold":
      el.css('font-weight', 'bold');
      el.css('font-style', 'normal');
      if (re) {
        return 'bold';
      }
      break;
    case "Normálně":
    case "normalni":
    case "normal":
      el.css('font-weight', '');
      el.css('font-style', 'normal');
      if (re) {
        return 'normal';
      }
      break;
    case "Kurzíva":
    case "kurziva":
      el.css('font-style', 'italic');
      el.css('font-weight', '');
      if (re) {
        return 'italics';
      }
      break;
    case "FreeSerif":
      return 'ru';
      break;
    case "CyrillicaBulgarian10U":
      return 'ocs';
      break;
    case "ArialNarrow":
      return 'arial';
      break;
  }
  $(el).each(function() {
    update_el_info($(this));
  });
}

function translate_font_(string) {
  switch (string) {
    case "normal":
      return 24;
      break;
    case "small":
      return 16;
      break;
    case "big":
      return 32;
      break;
    case "24":
      return "normal";
      break;
    case "32":
      return "big";
      break;
    case "16":
      return "small";
      break;
    case "10":
      return "24";
      break;
    case "16":
      return "32";
      break;
    case "8":
      return "16";
      break;
    case "24_":
      return "10";
      break;
    case "32_":
      return "16";
      break;
    case "16_":
      return "8";
      break;
  }
}

function user_json() {
  var obj = {};
  var user = cache.user_json.userInfo;
  obj.uid = user.uid;
  obj.email = user.email;
  obj.name = user.nickname;
  return JSON.stringify(obj);
}

function font_update_keybind(type) {
  font_select_change_update_span(type, 'lang');
}

function font_select_change_update_span(change, wat) {
  add_history_step(wat + ' change');
  switch (wat) {
    case "aip-size":
      $(selected_span).attr(wat, change);
      $(selected_span).css({
        'font-size': (parseInt(change) + page_zoom_edit) + "px"
      });
      $(selected_span).attr('fontsize', translate_font_(change));
      break;
    case "aip-style":
      if (change == "tucne") {
        $(selected_span).attr(wat, 'bold');
        trasnlate_attr_(change, $(selected_span));
      } else {
        $(selected_span).attr(wat, change);
        trasnlate_attr_(change, $(selected_span));
      }
      break;
    case "aip-font":
      $(selected_span).attr(wat, change);
      $(selected_span).css({'font-family': change});
      break;
    case "aip-index":
      change_el_index($(selected_span), change);
      break;
    case "lang":
      switch (change) {
        case "ru":
          $(selected_span).attr('alphabet', change);
          $(selected_span).attr('lang', change);
          $(selected_span).attr("aip-font", 'FreeSerif');
          $(selected_span).css({'font-family': 'FreeSerif'});
          break;
        case "ocs":
          $(selected_span).attr('alphabet', change);
          $(selected_span).attr('lang', change);
          $(selected_span).attr("aip-font", 'CyrillicaBulgarian10U');
          $(selected_span).css({'font-family': 'CyrillicaBulgarian10U'});
          break;
        case "arial":
          $(selected_span).attr("aip-font", 'ArialNarrow');
          $(selected_span).css({'font-family': 'ArialNarrow'});
          break;
      }

      break;
  }
  $(selected_span).each(function() {
    update_el_info($(this));
  });
  update_font_change_select($(selected_span).first());
}

function set_el_to_freeserif(el) {
  $(el).attr('alphabet', 'ru');
  $(el).attr('lang', 'ru');
  $(el).attr("aip-font", 'FreeSerif');
  $(el).css({'font-family': 'FreeSerif'});
}

function set_input_width_by_lenght(input, result) {
  var css_size = parseInt(input.css('font-size'));
  var add = (
    css_size > 0
    ? css_size / 1.9
    : cache.input_length_const);
  $(input).width(String(result).length * add);
}

function point_div(shape, point, x, y) {
  var div = $('<div shape="' + shape + '" point="' + point + '" class="point_div" style="top:' + y + 'px; left:' + x + 'px;"></div>');
  var new_x = x;
  var new_y = y;
  div.draggable({
    drag: function(e, ui) {},
    stop: function(e, ui) {
      var x = (e.clientX - rect.left) / (rect.right - rect.left) * canvas.width;
      var y = ((e.clientY + scrolled) - rect.top) / (rect.bottom - rect.top) * canvas.height
      update_shape_point($(this).attr('shape'), $(this).attr('point'), x, y);
    }
  })
  div.click(function() {
    if (active_func.remove) {
      remove_shape_point($(this).attr('shape'), $(this).attr('point'));
      disable_remove_shape_point();
    }
  })
  return div;
}


function show_hint_msg(msg, long_ = false) {
  $('#hint_msg_box').stop();
  $('#hint_msg_box').find('p').text(msg);
  if (long_) {
    $('#hint_msg_box').stop().fadeIn(1000).fadeOut(1000);
  } else {
    $('#hint_msg_box').stop().fadeIn(400).fadeOut(400);
  }
}

function resize(a) {
  resized = a;
}

function button_highlight(button) {
  button.stop();
  button.stop().animate({
    'background-color': 'rgba(250,0,0,.5)'
  }, 400);
  button.animate({
    'background-color': 'transparent'
  }, 200);
}

function select_menu_button(button) {
  button.css({'background-color': 'rgba(250,0,0,.5)'});
}

function hide_meta_spans() {
  $('span[aip-type="autor_dodatku"]').hide();
  $('span[aip-type="autor_slovniku"]').hide();
  $('span[aip-type="typ_zaznamu"]').hide();
}

function check_if_not_hidden(el) {
  if (!el.is('span[aip-type="autor_dodatku"]') && !el.is('span[aip-type="autor_slovniku"]') && !el.is('span[aip-type="typ_zaznamu"]')) {
    return false;
  } else {
    return true;
  }
}

function save_xml_response(json) {
  submit_xml("");
}

function submit_xml_response(json) {
  if (cache.reaload_page_submit) {
    setTimeout(function() {
      go_to_record(cache.load_record_id);
    }, 500);
  }
  if (json.status == "OK") {
    show_hint_msg("Uloženo", true);
  } else {
    show_hint_msg("Ukládání se nezdařilo", true);
  }
}

function check_end_start_gulas() {
  html = $(pageparts_div);
  var error = "";
  var error_num = 0;
  var level = 0;
  var max_level = 0;
  var border_arr = {};
  var level_arr = {};
  var prev_start = -1;
  var prev_end = -1;
  var border_levels_arr = {};
  html.children().each(function() {
    var el = $(this);
    if (el.is('start')) {
      var temp_level = get_el_level(el);
      if (max_level < level) {
        max_level = temp_level;
      }
      if (prev_start != temp_level) {
        prev_start = temp_level;
      } else {
        error += "\n Opakující se start tag " + temp_level;
        error_num++;
      }
      border_levels_arr[el.attr('block')] = temp_level;
      if (level_arr[temp_level] == undefined) {
        level_arr[temp_level] = true;
      }

      level = temp_level;
      border_arr[el.attr('block')] = true;
    }
    if (el.is('end')) {
      var temp_level = get_el_level(el);
      if (prev_start == temp_level) {
        prev_start = "";
      }
      if (level > temp_level) {
        for (var i = level; i < max_level; i++) {
          if (level_arr[i] == true) {
            error += "\n Stupeň " + i + " není uzavřen";
            error_num++;
          }
        }
      }
      level_arr[temp_level] = false;
      border_arr[el.attr('block')] = false;
    }
  });
  for (var i in border_arr) {
    if (border_arr[i] == true) {
      error += '\n  Špatné umístění  ' + $('start[block="' + i + '"]').attr('aip-block-name');
      error_num++;
    }
  }
  error += "\n \n počet nalezených chyb : " + error_num;
  if (error_num == 0) {
    return true;
  } else {
    alert(error);
    return false;
  }
  console.log(border_arr)
  console.log(level_arr)
  console.log(border_levels_arr)
}

function get_el_level(ol) {
  var _level = 0;
  html = $(pageparts_div);
  var first = html.children().first('start');
  $(ol).prevUntil(first.prev(':not(span)')).each(function() {
    var el = $(this);
    if (el.is('start')) {
      _level++;
    }
    if (el.is('end')) {
      _level--;
    }
  });
  if (ol.is('end')) {
    _level--;
  }
  return _level;
}
