/*****************************************************************************
 *                                                                           *
 *      Aplikační rámec pro vícejazyčné webové aplikace TORNADO              *
 *                                                                           *
 *                            Javascript, AJAX                               *
 *                                                                           *
 *  file name:  app_glob.js                                                  *
 *  encoding:   UTF-8                                                        *
 *  created:    2007-11-01                                                   *
 * ------------------------------------------------------------------------- *
 * written by Karel KUČERA                                                   *
 * 2007                                                                      *
 *                                                                           *
 *****************************************************************************/    

 /*************************************
 * refactored by Sergei Kostyukevich  *
 * 2011                               *
 *************************************/
 
/* All next comments are written in czech and english */
                                                               
/*****************************************************************************/

// Global settings SK 20110126
var index_config;
var count = 20;
var qs_line_val;
var glob_temp = '';
var timestamp = {'time':0, 'elem':''};
var df = 0;

//define the 'indexOf' method for old browsers (like IE6)
if(!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex){
    for(var i = fromIndex||0, length = this.length; i<length; i++)
      if(this[i] === searchElement) return i;
      return -1
  };
}

$(function () {
  if ($('#asf').length) {
      // search form buttons
      $('#asf_srch').click(function() {
        hide_window('sf_indexArea');
        $('#searching_div').show(300);
        oldCity_init();
      });
      $('#asf_clr').click(function() {
        hide_window('sf_indexArea');
        clearForm();
        oldCity_init();
      });
      $('#asf_coll_2').delegate('.wtf_radios1', 'click', function(){
        exclude = ($(this).hasClass('wtf_groups')) ? '.wtf_groups' : '#'+this.id;
        $('.wtf_radios1:not('+exclude+'):checked').each(function() {
          $(this).removeAttr('checked');
        });
      });
      index_config = $.parseJSON($('#index_config').val());
      indexExtended_init();
      oldCity_init();
  } else if ($('#qsf').length) {
      //alert($.browser.mozilla); 
      index_config = $.parseJSON($('#index_config').val());  
      indexEasy_init();
  } 
})
function indexExtended_init() {
  $('#mainDlibArea').css('position', 'relative');
  $('#asf textarea.asf_txt').each(function(i, element) {
    $(this).height($('#id_fields_'+i).height())
  });
  if ($('#idx_mask_text').height() < 14) {
    ($.browser.mozilla) ? $('#idx_mask_text').height('23') : $('#idx_mask_text').height('25');
  }      
	$('table select.asf_sel').each(function (i, element) {
		if ($(this).attr('id').search(/id_fields_/) != -1) {
      id_num = this.id.match(/\d+/);
      $('#idxBtn_' + id_num).click(function() { //index buttons' "click" ivents
        open_index(this.id.substring(7));
      }); 
      $('#id_ed_' + id_num).click(function() { //query strings' "click" ivents
        edit_onClick(this.id.substring(6));
      });
      $('#id_ed_' + id_num).keyup(function(event) { //query strings' "keyup" ivents
        if ($('#sf_indexArea').css('left') != '-2000px')
          if (event.which==13 || event.which==38 || event.which==40 || 
              event.which==33 || event.which==34 || event.which==36 || event.which==35) 
            resolveSpecKeyUp(event.which, this.id.substring(6));
          else 
            resolveKeyUp(event.which, this.id.substring(6));
        else if (event.which==13) { $('#asf').submit(); return false;}
      });
      $('#id_ed_' + id_num).keydown(function(event) { //query strings' "keydown" ivents
        if ($('#sf_indexArea').css('left') != '-2000px')
          if (event.which==13 || event.which==38 || event.which==40 || 
              event.which==33 || event.which==34 || event.which==36 || event.which==35)
            return false;
          else 
            resolveKeyDown(event.which, this.id.substring(6));
        else if (event.which==13) return false;
      });
/*       $('#id_ed_' + id_num).keypress(function(event) {
        if (event.which==13 || event.which==38 || event.which==40 || 
            event.which==33 || event.which==34)
          return false;
      }); */
      $('#id_ed_' + id_num).change(function() { //select boxes' "change" ivents
        edit_onChange(this.id.substring(6));
      });
		}
	});

  //MASK
  var modalfield_val;
  var flag = true;
  var coord;
  $('#idx_mask_text').keydown(function(event) {
    if (event.which == 13) { return false; }
    modalfield_val = $('#idx_mask_text').val();
  });  
  $('#idx_mask_text').keyup(function(event) {
//    mask_edit_in_progress(event.which, resp_json.mask.edit_id);
    if (event.which == 13) {
      $('#idx_list_nums, #sf_indexArea_right, #mainDlibArea').unblock({
        onUnblock: function() {
          call_index(document.getElementById('idx_mask_text').selectionStart, 0, 
                     'index_mask_change', resp_json.mask.edit_id, $('#idx_mask_text').val());
        }
      });    
      $('#idx_mask_text').detach().appendTo('#sf_indexArea_mask ul li').offset(coord).focus(); 
      flag = true;
      return true;
    }
    if (flag == true && modalfield_val != $('#idx_mask_text').val()) {  
      coord = $('#idx_mask_text').offset();
      $('#idx_mask_text').detach().appendTo('body').offset(coord).focus();
      //alert(aaa);
      if ($.browser.msie) {
        var input = $('#idx_mask_text');
        input.blur().focus().val(input.val());
      }
      
      flag = false;
      $('#sf_indexArea_right, #mainDlibArea').block({
          theme: true,
          message: null
      }); 
      $('#idx_list_nums').block({
        theme: true,
        message: null
/*           message: 'press "Enter" to end' */
      });    
    }
  });

  // LST1, LST2
  for (i=0; i<count; i++) {
    $('#idxLeft_row'+i).click(function() {
      idxIvent_idxLeft_rows_click(this.id.substring(11));
    });
    $('#idxLeft_row'+i).dblclick(function() {
      idxIvent_idxLeftTable_rows_dblclick(this.id.substring(11));
    });
    $('#idxTable_row'+i).click(function() {
      idxIvent_idxTable_rows_click(this.id.substring(12));
    });
    $('#idxTable_row'+i).dblclick(function() { 
      idxIvent_idxLeftTable_rows_dblclick(this.id.substring(12));
    });
  }
  
  // CTRLS4
  $('#idx_trans2').click(function() {
    idxIvent_idx_trans2_click();   
  });  
  $('#idx_close').click(function() {
    idxIvent_idx_close_click();   
  });
  $('#idx_aster').click(function() { 
    if (!$(this).hasClass('disabled')) idxIvent_idx_aster_click();  
  });  
  $('#idx_copy_fast').click(function() {
    idxIvent_idx_copy_fast_click();  
  });
  $('#idx_del').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_del_click();    
  });
  $('#idx_copy').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_copy_click();   
  });

  // CTRLS2
  // glob-sel switch
  $('#globsel1').click(function() {
    idxIvent_idx_glob_click();  
  });   
  $('#globsel2').click(function() {
    idxIvent_idx_sel_click();
  });
  
  // left row  
  $('#idx_home').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_home_click();   
  });
  $('#idx_pgup').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_pgup_click(); 
  });
  $('#idx_up').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_up_click();  
  });
  $('#idx_fixrow').click(function() {
    idxIvent_idx_fixrow_click();   
  });
  $('#idx_dn').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_dn_click();    
  });
  $('#idx_pgdn').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_pgdn_click();   
  });  
  $('#idx_end').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_end_click();
  });
  
  // right row  
  $('#idx_spec_home').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_spec_home_click();
  });    
  $('#idx_trans2b').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_trans2b_click();    
  });    
  $('#idx_rus').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_rus_click();   
  });    
  $('#idx_spec_end').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_spec_end_click();   
  });    
  
  // CTRLS5 undoredo
  $('#idx_undo').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_undo_click();
  });
  $('#idx_redo').click(function() {
    if (!$(this).hasClass('disabled')) idxIvent_idx_redo_click();
  });

  // CTRLS3
  $('#rbtype1').click(function() {
    idxIvent_rbtype1_click();
  });
  $('#rbtype2').click(function() {
    idxIvent_rbtype2_click();
  });
  $('#rbtype3').click(function() {
    idxIvent_rbtype3_click();
  });
  $('#rbtype4').click(function() {
    idxIvent_rbtype4_click();
  });
  $('#additiona01').click(function() {
    idxIvent_additiona01_click();
  });

  $('#breadcrumb li a:contains('+index_config.catalogue+')').click(function() {
    href = $(this).attr('href');
    fdm = '';
    
// FDM-slovniki    
/*     $('#asf_fdm input:checked').each(function() {
      fdm += '&'+this.id+'=on';
    }); */
    
    $(this).attr('href', href+
                         '?sf_queryLine='+$('#id_ed_0').val()+
                         '&choice='+$('#id_fields_0 option:selected').val()+
                         '&fdm=1'+
                         fdm
                );
  });
  
// FDM-slovniki  
/*   $('#asf').submit(function() {
    if (!$('#asf_fdm input:checked').length) {
      $('#asf_fdm span').css('border', '1px solid Red');
      $('#asf_fdm').append('<div style="color:red;">NOOOOOOOOoooooo!!!!!!</div>');
      return false;
    }
  }); */  
  
}


/**************************/
function jump(where) {
  document.location.href=where;
}

/**************************/
/* Zjistí abs. souřadnice objektu na HTML stránce
   pType=0 top, pType=1 left */
function findPosition(obj,pType) {
	cur = 0;
	if (obj!==null) {
		if(obj.offsetParent) {		
			while(obj.offsetParent) {
				cur+=pType?obj.offsetLeft:obj.offsetTop;
				obj = obj.offsetParent;
			}
		}
	} else {
		alert(obj.id);
	}
	return cur;
}

/**************************/

function setPosition(id,X,Y) {
	document.getElementById(id).style.top = Y+"px"; 
	document.getElementById(id).style.left = X+"px";
}        

/**************************/

function hide_window(id) {
	if (document.getElementById(id)) {
		document.getElementById(id).style.top = "-2000px";
		document.getElementById(id).style.left = "-2000px";
	}
}

/**************************/

function index_visible(id) {
	var t = document.getElementById(id).style.top;
	var l = document.getElementById(id).style.left;
	return ((parseInt(l) >= 0) && (parseInt(t) >= 0));
}

/**************************/
/*
id - identifikator okna indexu 
edit_id - identifikator radky, ke ktere index patri
*/
function show_index(edit_id) {
  id = index_config.index_id;
	var newY = $('#'+edit_id).offset().top + $('#'+edit_id).outerHeight() - 2 + (($.browser.msie) ? -1 : 0); 
	var newX = $('#'+edit_id).offset().left + (($.browser.msie) ? -1 : 0);
	$('#'+id).css('top', newY+"px"); 
	$('#'+id).css('left', newX+"px"); 
 // alert('idx_is_open = ' + idx_is_open);
	//zobrazení dalsich casti indexu
//  alert($(idx_tmp_line).val());
//	update_ql_marks(idx_tmp_line, edit_id);

	clb_show_index(edit_id);
}

/**************************/
function loadImg(imgName) {
  var img=new Image();
  img.src=imgName;
  return img;
}

/**************************/
function displayError(where,msg) {
	document.getElementById(where).innerHTML = msg;
}

/**************************/
function displayText(where,msg) {
	if (document.getElementById(where)) {
		document.getElementById(where).innerHTML = msg;
	} else {
		alert("chyba. element "+where+" neexistuje");
	}
} 

/*********************************/
/*                               */
/*           A J A X             */
/*                               */
/*********************************/


var xmlHttpEnabled = false;   // Proměnná určuje, zda je možno použít xmlHttpRequestObject
var index_element_id;         // id okna(div) indexu, do ktereho prijde AJAX odezva
var edit_element_id;          // id editacni radky, do ktere prijde AJAX odezva 
var qline_before_index;       // string radky pred otevrenim indexu 
var index_request;

// Inicializace XML HTTP Request objektu 
/** deprecated */
var xmlHttp = null;  // !!! pro IE7 a pravdepodobne jeste za urcitych jinych okolnosti musi vytvoreni objektu probehnout pri kazdem volani sendHttpRequest !!!
 
/**********************************************************/
/****	createXmlHttpRequestObject()                     ****/
/**********************************************************/  

/** deprecated */
function createXmlHttpRequestObject() {
  var xmlHttp1;
  try {                 
    xmlHttp1 = new XMLHttpRequest();
  }
  catch(E) {            
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp1; i++) {
      try { 
        xmlHttp1 = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }    
  }
  if (!xmlHttp1) xmlHttpEnabled = false;
  else {                                             
  	xmlHttpEnabled = true;
    return xmlHttp1;
  }
}  

/**********************************************************/
/****	sendHttpRequest(script,param,response)           ****/
/**********************************************************/  

/** deprecated */
function sendHttpRequest(script,param,response) {
	xmlHttp = createXmlHttpRequestObject();
	if (!xmlHttpEnabled) {                  
		showError("Your browser doesn't support the necessary functionality");
		return;		
	}	 
	try {   
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {      
			xmlHttp.onreadystatechange = response; // Funkce pro obsluhu odezvy     
			var params = param;
			xmlHttp.open("POST", script, true); // treti promenna == true => asynchronni pozadavek, pokud je false => synchronni pozadavek xmlHttp ceka na odezvu ze serveru !!!!
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");   
//			alert(params);
			xmlHttp.send(params);
		} else {   
   		setTimeout("sendHttpRequest('"+script+"','"+param+"','"+response+"');", 1000); 
		}
	}
	catch (e) {
		alert (e.toString()); // chybova hlaska
	}		
}

/**********************************************************/
/****	call_index()                                     ****/
/**********************************************************/  

function call_index(sessId, script, request, edit_id, edit_value, field_num, index_id, caret_pos, lang) {
  if (!(field_num)) { //5 params
    lang = index_config.lang;
    caret_pos = sessId;
    index_id = index_config.index_id;
    field_num_temp = $('#' + script).val();
    field_num = (field_num_temp !== undefined) ? field_num_temp : script;
    edit_id = edit_id;
    edit_value = edit_value;
    request = request;
    script = index_config.index_script;
    sessId = index_config.session_id;
  }
	index_element_id = index_id;  // globalni promenna s identifikatorem indexu	                   
	edit_element_id = edit_id;                     
	index_request = request;   
	var param = "sessionId=" + sessId + "&request=" + request + "&idx_field=" + field_num + "&edit_id=" + edit_id + "&value=" + edit_value + "&caret_pos=" + caret_pos + "&language=" + lang;	
// if (request=="index_open_with_caret") alert(param);
//	sendHttpRequest(script,param,write_index_tp);  
  var newY = Math.round(($($("#idx_list_items")).offset().top + $($("#idx_list_items")).height())/2) + 50; 
  var newX = Math.round(($($("#idx_list_items")).offset().left + $($("#idx_list_items")).width())/2);
  $("#idx_loading").css('left', newX+'px').css('top', newY+'px').show();
  $.post(script, param,
    function(data) { 
      write_index_tp(data, edit_id);
    }, 'json');
}


/**********************************************************/
/****	AJAX response                                    ****/
/**********************************************************/  

var idx_current_line=0; //ulozi current_line (tj. cislo radky v indexu!) pro dalsi pouziti
var startPos = 0; //poloha prvniho znaku vyrazu v radce dotazu, podle ktereho se nastavuje maska
var endPos = 0; //poloha posledniho znaku vyrazu v radce dotazu, podle ktereho se nastavuje maska
var alertStatus = 0;
var insertStatus = 0;
var resp_json;

function write_index_tp(resp, edit_id) {                                            
//			alert(resp);
  if (resp == "-513" || resp == "") {
    hide_idx_window();
    MW_reloadPageIdx();
    return false;       
  }
  
  // !!! JSON !!!
  resp_json = resp;
  if (edit_element_id) { //edit_element_id - глобальная переменная, номер строки ввода
    if (resp_json.idx_caret !== undefined) {
      if (resp_json.idx_query !== undefined) {
        $('#'+edit_element_id).val(resp_json.idx_query); //???? используется <!--QUERY-->?
      }
      
      // poloha caretu	  				
      var caret = parseInt(resp_json.idx_caret);

      //poloha prvniho znaku vyrazu v radce dotazu, podle ktereho se nastavuje maska
      startPos = parseInt(resp_json.idx_start_pos);

      //poloha posledniho znaku vyrazu v radce dotazu, podle ktereho se nastavuje maska
      endPos = parseInt(resp_json.idx_end_pos);

      //stav alertu
      //alertStatus = parseInt(resp_json.idx_alert);

      //stav pointeru vkladani
      insertStatus = parseInt(resp_json.idx_insert);

      //pozice highlighted radky v seznamu hodnot indexu
      idx_current_line = parseInt(resp_json.idx_line);

      //Tp: nastavit caret jen pokud se menila linka
      if (resp_json.idx_query !== undefined) {
        setCaretToPos($('#'+edit_element_id), caret);
      }
    } 
    else $('#'+edit_element_id).val(resp.substr(0,i));     
  }
   
// obsah okna indexu (včetně čudlíků)  			
  // MASK
  $('#idx_mask_text').addClass(resp_json.mask.input_addClass).val(resp_json.mask.input_value);

  //LST_1, LST_2
  for (i=0; i<count; i++) {
    $('#idxLeft_row'+i+'>span').html(resp_json.lst_1_2_elm[i].span_1_value);
    $('#idxTable_row'+i+'>span').html(resp_json.lst_1_2_elm[i].span_2_value);
    if (!($('#idxTable_row'+i).hasClass(resp_json.lst_1_2_elm[i].li_class))) {
      if (resp_json.lst_1_2_elm[i].li_class == 'idx_highlight') {
        $('#idxLeft_row'+i).removeClass('idx_row').addClass('idx_highlight');
        $('#idxTable_row'+i).removeClass('idx_row').addClass('idx_highlight');
      }
      else { 
        $('#idxLeft_row'+i).removeClass('idx_highlight').addClass('idx_row');
        $('#idxTable_row'+i).removeClass('idx_highlight').addClass('idx_row');
      }
    }
  }  

  $("#idx_list_items li:first, #idx_list_nums li:nth-child(n+2):first").addClass('first');
  $("#idx_list_items li>span, #idx_list_nums li>span").addClass(resp_json.lst_1_2.span_class);

  // MASKC
  $('#idx_mask_c').html(resp_json.maskc.maskc_val);

  // CTRLS4
  addPath = (index_config.lang == 'cs') ? '' : '../';
  if (resp_json.ctrls4.a_aster > 0) 
    $('#idx_aster').removeClass('disabled').attr('src', addPath + 'img/arr_right_aster_green.png');
  else 
    $('#idx_aster').addClass('disabled').attr('src', addPath + 'img/arr_right_aster_green_disabled.png');

  if (resp_json.ctrls4.a_left > 0) {
    $('#idx_del').removeClass('disabled').attr('src', addPath + 'img/arr_left_green.png');
  } else {
    $('#idx_del').addClass('disabled').attr('src', addPath + 'img/arr_left_disabled.png');
  }
  if (resp_json.ctrls4.a_right > 0) {
    $('#idx_copy').removeClass('disabled').attr('src', addPath + 'img/arr_right_green.png');
  } else {
    $('#idx_copy').addClass('disabled').attr('src', addPath + 'img/arr_right_disabled.png');
  }
   
  // CTRLS2
  // glob-sel switch
  $('#'+resp_json.ctrls2.checked).attr('checked', 'checked');

  // left row  
  if (resp_json.ctrls2.a_idx_home > 0) {
    $('#idx_home').removeClass('disabled').attr('src', addPath + 'img/idx_home.png');
  } else {
    $('#idx_home').addClass('disabled').attr('src', addPath + 'img/idxd_home.png'); 
  }
  if (resp_json.ctrls2.a_page_up > 0) {
    $('#idx_pgup').removeClass('disabled').attr('src', addPath + 'img/idx_pageup.png');
  } else {
    $('#idx_pgup').addClass('disabled').attr('src', addPath + 'img/idxd_pageup.png'); 
  }
  if (resp_json.ctrls2.a_line_up > 0) {
    $('#idx_up').removeClass('disabled').attr('src', addPath + 'img/idx_lineup.png');
  } else {
    $('#idx_up').addClass('disabled').attr('src', addPath + 'img/idxd_lineup.png'); 
  }
  if (resp_json.ctrls2.a_row_fixed > 0) {
    $('#idx_fixrow').attr('src', addPath + 'img/idx_fixrow5.png');
  } else {
    $('#idx_fixrow').attr('src', addPath + 'img/idx_fixrow4.png');
  }
  if (resp_json.ctrls2.a_line_down > 0) {
    $('#idx_dn').removeClass('disabled').attr('src', addPath + 'img/idx_linedn.png');
  } else {
    $('#idx_dn').addClass('disabled').attr('src', addPath + 'img/idxd_linedn.png'); 
  }
  if (resp_json.ctrls2.a_page_down > 0) {
    $('#idx_pgdn').removeClass('disabled').attr('src', addPath + 'img/idx_pagedn.png');
  } else {  
    $('#idx_pgdn').addClass('disabled').attr('src', addPath + 'img/idxd_pagedn.png'); 
  }
  if (resp_json.ctrls2.a_idx_end > 0) {
    $('#idx_end').removeClass('disabled').attr('src', addPath + 'img/idx_end.png');
  } else {   
    $('#idx_end').addClass('disabled').attr('src', addPath + 'img/idxd_end.png'); 
  }  

  // right row  
  if (resp_json.ctrls2.a_home_change > 0) {
    $('#idx_spec_home').removeClass('disabled').attr('src', addPath + 'img/arr_begin5.png');
  } else {
    $('#idx_spec_home').addClass('disabled').attr('src', addPath + 'img/arrd_begin5.png');
  }
  if (resp_json.ctrls2.a_go_transl > 0) {
    $('#idx_rus').removeClass('disabled').attr('src', addPath + 'img/arr_rus3.png');
  } else {  
    $('#idx_rus').addClass('disabled').attr('src', addPath + 'img/arr_rus3_disabled.png');
  }
  if (resp_json.ctrls2.a_end_change > 0) {
    $('#idx_spec_end').removeClass('disabled').attr('src', addPath + 'img/arr_end5.png');
  } else { 
    $('#idx_spec_end').addClass('disabled').attr('src', addPath + 'img/arrd_end5.png');
  }

  // CTRLS5 undoredo
  if (resp_json.ctrls5.a_undo > 0) {
    $('#idx_undo').removeClass('disabled').attr('src', addPath + 'img/jump_back.png');
  } else {  
    $('#idx_undo').addClass('disabled').attr('src', addPath + 'img/jump_back_disabled.png');
  }
  if (resp_json.ctrls5.a_redo > 0) {
    $('#idx_redo').removeClass('disabled').attr('src', addPath + 'img/jump_fwd.png');
  } else {  
    $('#idx_redo').addClass('disabled').attr('src', addPath + 'img/jump_fwd_disabled.png');
  }

  // CTRLS3 
  $('#'+resp_json.ctrls3.checked).attr('checked', 'checked');
  if (resp_json.ctrls3.enabled_word) {
    $('#rbtype1').removeAttr('disabled');
    $('#lbrbtype1').removeClass().addClass('enabled');
  } else {
    $('#rbtype1').attr('disabled', 'disabled');
    $('#lbrbtype1').removeClass().addClass('disabled');
  }
  if (resp_json.ctrls3.enabled_entry) {
    $('#rbtype2').removeAttr('disabled');
    $('#lbrbtype2').removeClass().addClass('enabled');
  } else {
    $('#rbtype2').attr('disabled', 'disabled');
    $('#lbrbtype2').removeClass().addClass('disabled');
  }
  if (resp_json.ctrls3.enabled_sequence) {
    $('#rbtype3').removeAttr('disabled');
    $('#lbrbtype3').removeClass().addClass('enabled');
  } else {
    $('#rbtype3').attr('disabled', 'disabled');
    $('#lbrbtype3').removeClass().addClass('disabled');
  }
  if (resp_json.ctrls3.enabled_num_dat) {
    $('#rbtype4').removeAttr('disabled');
    $('#lbrbtype4').removeClass().addClass('enabled');
  } else {
    $('#rbtype4').attr('disabled', 'disabled');
    $('#lbrbtype4').removeClass().addClass('disabled');
  } 

  alertStatus = resp_json.alert2;
  update_ql_marks(idx_tmp_line, edit_id);
  $("#idx_loading").hide();
}

// Prebarvení aktivní rádky tabulky indexu - kvůli potížím s dblclick v MSIE a Opere
function set_current_line(index_element_id, current_line) {
	var i = 0;
	while (i<25) {  // jádro může teď mít max. 25 rádek indexu  
		if (document.getElementById('row'+i)) {
			if (i == current_line)                                                      
				document.getElementById('row'+i).className = 'idx_highlight';
			else                                                                 
				document.getElementById('row'+i).className = 'idx_text';
		}		
		i++;
	}		
}


/**********************************************************/
/****	                 events                          ****/
/**********************************************************/  
  // LST1
function idxIvent_idxLeft_rows_click(id) {
  highlightNum = $('#idx_list_items li.idx_highlight').attr('id').match(/\d+/);
  call_index(id - highlightNum, id, 'index_scroll', resp_json.lst_1_2.edit_id, '');
  $('#'+resp_json.lst_1_2.edit_id).focus();
}

  // LST2
function idxIvent_idxTable_rows_click(id) {
  call_index(document.getElementById(resp_json.lst_1_2.edit_id).selectionStart, id, 'index_click', resp_json.lst_1_2.edit_id, '');
  $('#'+resp_json.lst_1_2.edit_id).focus();
}

  // LST1, LST2
function idxIvent_idxLeftTable_rows_dblclick(id) {
  call_index(document.getElementById(resp_json.lst_1_2.edit_id).selectionStart, id, 'index_dblClick', resp_json.lst_1_2.edit_id, '');
  $('#'+resp_json.lst_1_2.edit_id).focus();
}
  
  // CTRLS4
function idxIvent_idx_trans2_click() {
  call_index(0, 0, 'index_mask_dblclick', resp_json.mask.edit_id, $('#idx_mask_text').val());
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_close_click() {
  hide_idx_window(); // ЗАЧЕМ???
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_aster_click() {
  if (resp_json.ctrls4.a_aster > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_asterix', resp_json.mask.edit_id, '');
  }   
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_copy_fast_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_row_to_mask', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_del_click() {
  if (resp_json.ctrls4.a_left > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_delChar', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_copy_click() {
  if (resp_json.ctrls4.a_right > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_copyChar', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}

  // CTRLS2
  // glob-sel switch
function idxIvent_idx_glob_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_global', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
} 
function idxIvent_idx_sel_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_select', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();
} 
  
  // left row  
function idxIvent_idx_home_click() {
  if (resp_json.ctrls2.a_idx_home > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_home', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();
}
function idxIvent_idx_pgup_click() {
  if (resp_json.ctrls2.a_page_up > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_prev', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_up_click() {  
  if (resp_json.ctrls2.a_line_up > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_lineUp', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_fixrow_click() {  
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_fix_row', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_dn_click() {  
  if (resp_json.ctrls2.a_line_down > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_lineDn', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_pgdn_click() {  
  if (resp_json.ctrls2.a_page_down > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_next', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_end_click() {
  if (resp_json.ctrls2.a_idx_end > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_end', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}

  // right row  
function idxIvent_idx_spec_home_click() {
  if (resp_json.ctrls2.a_home_change > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_home_change', resp_json.mask.edit_id, '');
    $('#'+resp_json.mask.edit_id).focus();      
  }
}  
function idxIvent_idx_trans2b_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_dblClick', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();      
}
function idxIvent_idx_rus_click() {
  if (resp_json.ctrls2.a_go_transl > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_transl', resp_json.mask.edit_id, '');
    $('#'+resp_json.mask.edit_id).focus();      
  }
}
function idxIvent_idx_spec_end_click() {
  if (resp_json.ctrls2.a_end_change > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_end_change', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();      
}

  // CTRLS5 undoredo
function idxIvent_idx_undo_click() {
  if (resp_json.ctrls5.a_undo > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_undo', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_idx_redo_click() {
  if (resp_json.ctrls5.a_redo > 0) {
    call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_redo', resp_json.mask.edit_id, '');
  }
  $('#'+resp_json.mask.edit_id).focus();    
}

  // CTRLS3
function idxIvent_rbtype1_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_word', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_rbtype2_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_entry', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_rbtype3_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_sequence', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_rbtype4_click() {
  call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_num_dat', resp_json.mask.edit_id, '');
  $('#'+resp_json.mask.edit_id).focus();    
}
function idxIvent_additiona01_click() {
  get_help('index', index_config.lang);
}

  
/*********************************/
/*                               */
/*           I N D E X           */
/*                               */
/*********************************/
                                                        
function edit_onChange(id_num) {
  edit_id = 'id_ed_' + id_num;
  index_id = index_config.index_id;
	if (index_visible(index_id)) {
		show_index(edit_id);  
		var caret_pos = getCaretPosition(document.getElementById(edit_id));   
		call_index(caret_pos, $('#id_fields_' + id_num).val(), 'index_edit_change', edit_id, $('#'+edit_id).val());         
	}
}

function edit_onClick(id_num) {
  edit_id = 'id_ed_' + id_num;
  index_id = index_config.index_id;
	if (index_visible(index_id)) {
		show_index(edit_id);  
		var caret_pos = getCaretPosition(document.getElementById(edit_id));
		call_index(caret_pos, $('#id_fields_' + id_num).val(), 'index_edit_click', edit_id, $('#'+edit_id).val());
  }
}

function open_index(id_num) {
/*   if (console.log) {
    console.log('#sf_indexArea_right = ' + $('#sf_indexArea_right').width());
    console.log('# = ' + $('#sf_indexArea_right .idx_qlitems:first').height());
  } */

  if ($('#sf_indexArea_right').width() != 60) {
    $('#sf_indexArea_right').width(60);
  }
  if ($('#sf_indexArea_right .idx_qlitems:first').height() != 30) {
    $('#sf_indexArea_right img.asf_rbtns.last').css('margin-left', '-5px');
  }
//  if (console.log) console.log('++NEW++ #sf_indexArea_right = ' + $('#sf_indexArea_right').width());  
  $('#asf_srch').attr('disabled', 'disabled');
  edit_id = 'id_ed_' + id_num;
	show_index(edit_id);  
	var caret_pos = getCaretPosition(document.getElementById(edit_id));
  call_index(caret_pos, $('#id_fields_' + id_num).val(), 'index_open_with_caret', edit_id, $('#'+edit_id).val());
  document.getElementById(edit_id).focus();
}


/***************************************************************/
/****				osetreni keydown eventu a souvisejiciho         ****/
/***************************************************************/  
/****				prevzato z metoolu         ****/
/***************************************************************/  

var cPressed=new Array();
cPressed["shift"]=false;
cPressed["ctrl"]=false;
cPressed["alpha"]="";

var currSC="";
var currFocusId="";

var helpDiv,helpText;

function resolveKeyDown(cc, id_num) {
  sessId = index_config.session_id;
  script = index_config.index_script;
  field_num = $('#id_fields_' + id_num).val();
  edit_id = 'id_ed_' + id_num;
  index_id = index_config.index_id;
  lang = index_config.lang;

	var currInput;
	var returnCC=true;
	if (currFocusId!="") {
		currInput=document.getElementById(currFocusId);
	}
	//nastavit kombinaci zmacknutych tlacitek
	switch (cc) {
		case 16:
			cPressed["shift"]=true;
			break;
		case 17:
			cPressed["ctrl"]=true;
			break;
		//zavri index
		case 27:
			hide_idx_window();
		default:
			cPressed["alpha"]=cc;
//			document.getElementById("tetsStuff").innerHTML=cc;
	}
	
	if (cPressed["shift"] && cPressed["ctrl"] && cPressed["alpha"]!="") {
//					document.getElementById("charCode").value="CTRL + SHIFT + " +cPressed["alpha"];
		switch (cPressed["alpha"]) {
			//zobrazeni/skryti okna nahledu
			//"i" jako "index"
			case 73:
				resolveKeyUp(16);
				resolveKeyUp(17);
				resolveKeyUp(73);
        alert('oi_1');
				open_index(id_num);
				break;
		}
//				} else {
//					document.getElementById("charCode").value=document.getElementById("charCode").value=cc;
	}
	return returnCC;
}

function resolveKeyUp(cc, id_num) {
  sessId = index_config.session_id;
  script = index_config.index_script;
  field_num = $('#id_fields_' + id_num).val();
  edit_id = 'id_ed_' + id_num;
  index_id = index_config.index_id;
  lang = index_config.lang;
  
	switch (cc) {
		case 16:
			cPressed["shift"]=false;
			break;
		case 17:
			cPressed["ctrl"]=false;
			break;
		default:
			cPressed["alpha"]="";
	}
	if (idx_is_open) edit_onChange(id_num);
//				document.getElementById("charCode").value=document.getElementById("charCode").value+" dropped";
//				document.getElementById("charCode").value=document.getElementById("charCode").value="";
}

function resolveSpecKeyUp(cc, id_num) {
  sessId = index_config.session_id;
  script = index_config.index_script;
  field_num = $('#id_fields_' + id_num).val();
  edit_id = 'id_ed_' + id_num;
  index_id = index_config.index_id;
  lang = index_config.lang;
  
	var edit_value = document.getElementById(edit_id).value;
	var caret_pos = getCaretPosition(document.getElementById(edit_id));
	switch (cc) {
		case 36:
				if (idx_is_open) {
          call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_home', resp_json.mask.edit_id, '');      
				}
			break;
		case 38:
				if (idx_is_open) {
					call_index(sessId,script,'index_lineUp',edit_id,"",field_num,index_id,caret_pos,lang);         
				}
			break;
		case 33:
				if (idx_is_open) {
					call_index(sessId,script,'index_prev',edit_id,"",field_num,index_id,caret_pos,lang);         
				}
			break;
		case 34:
				if (idx_is_open) {
					call_index(sessId,script,'index_next',edit_id,"",field_num,index_id,caret_pos,lang);         
				} else {
          alert('oi_2');
					open_index(id_num);
				}
			break;
		case 40:
				if (idx_is_open) {
					call_index(sessId,script,'index_lineDn',edit_id,"",field_num,index_id,caret_pos,lang);         
				} else {
          alert('oi_3');          
					open_index(id_num);
				}
			break;
		case 35:
				if (idx_is_open) {
          call_index(document.getElementById(resp_json.mask.edit_id).selectionStart, resp_json.ctrls4.field_num, 'index_end', resp_json.mask.edit_id, '');     
				}
			break;
		case 13:
				if (idx_is_open) {
					call_index(sessId,script,'index_dblClick',edit_id,"",idx_current_line,index_id,caret_pos,lang);
        }
			return false;
			break;
	} 
}

function getCaretPosition(el) { 
	var caretPos = 0;
  if (el.selectionStart) { 
    caretPos=el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      caretPos=0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

   caretPos=rc.text.length; 
  }  
  return caretPos; 
}

function setSelectionRange(elm, selectionStart, selectionEnd) {
  if (elm.setSelectionRange) {
    elm.focus();
    elm.setSelectionRange(selectionStart, selectionEnd);
  } else {
  	if (elm.createTextRange) {
	    var range = elm.createTextRange();
	    range.collapse(true);
	    range.moveEnd('character', selectionEnd);
	    range.moveStart('character', selectionStart);
	    range.select();
	  }
	}
}

function setCaretToPos(elm, pos) {
  setSelectionRange(elm, pos, pos);
}

window.onresize = function () {
	if (index_element_id !== undefined) {
		if (index_visible(index_element_id)) {
			show_index(index_element_id, edit_element_id); 
		}
	}
}

function clearForm() {
  $('#asf input.asf_txt').val('');
}

var idx_tmp_line;
var idx_tmp_line1;
var idx_is_open=false;
function clb_show_index(line_id) {
	idx_tmp_line = document.getElementById(line_id); 
	idx_tmp_line1 = $('#'+line_id); 
//  alert($(idx_tmp_line1).offset().left+", "+$(idx_tmp_line1).position().left);
  var newY = $(idx_tmp_line1).position().top + $(idx_tmp_line1).outerHeight();
  var newX = $(idx_tmp_line1).position().left;

  $('#sf_indexArea_left').css('top', (newY + 1) + 'px'); //cislo spojeno s css
	$('#sf_indexArea_left').css('left', (newX - 61) + 'px'); //cislo spojeno s css
  $('#sf_indexArea').css('left', newX + 'px'); //cislo spojeno s css
  $('#sf_indexArea').css('top', (newY - 2) + 'px'); //cislo spojeno s css
	$('#sf_indexArea_right').css('top', (newY - 25) + 'px'); //cislo spojeno s css
	$('#sf_indexArea_right').css('left', (newX + $(idx_tmp_line1).outerWidth()) + 'px'); //cislo spojeno s css
	selId="id_fields_"+line_id.substring(6);
	$('#sf_indexArea_table').css('width', $(idx_tmp_line1).outerWidth() + "px"); //cislo spojeno s css prave casti a sirkou obrazku:)
	idx_is_open=true;
} 

function update_ql_marks(ql, edit_id) {
	var noOfCharsVisible=51;
	var charWidth=8;
	var paddingLeft = $('#'+edit_id).position().left + 2;
	insertMarkHalfWidth=4;
	var mark = document.getElementById("sf_indexArea_indicators");
	var mark2 = document.getElementById("idx_alert_button");
	var insertMark = document.getElementById("sf_indexArea_insert_mark");
    addPath = (index_config.lang == 'cs') ? '' : '../';

	if (idx_is_open) {
		startCoord=paddingLeft+charWidth*startPos-ql.scrollLeft;
		endCoord=charWidth*endPos-ql.scrollLeft;
		if (startCoord<paddingLeft) startCoord=paddingLeft;
		if (endCoord>ql.offsetWidth) endCoord=ql.offsetWidth;
//document.getElementById("tetsStuff").innerHTML="startPos: "+startPos+" endPos: "+endPos+" alertStatus: "+alertStatus+" insertStatus: "+insertStatus+" idx_current_line "+idx_current_line;
//document.getElementById("tetsStuff").innerHTML+="<br/>startCoord: "+startCoord+", paddingLeft: "+paddingLeft;
//document.getElementById("tetsStuff").innerHTML+="<br/>endCoord: "+endCoord+", ql.offsetWidth: "+ql.offsetWidth;
		switch (alertStatus) {
			case "G": //zelena
				mark.className="ok";
        $(mark2).attr('src', addPath + 'img/idx_alert_ok.png');
				break;
			case "R": //cervena
				mark.className="ko";
        $(mark2).attr('src', addPath + 'img/idx_alert_ko.png');
				break;
			default: //zluta
				mark.className="x";
        $(mark2).attr('src', addPath + 'img/idx_alert_x.png');
		}
		if (startCoord<ql.offsetWidth) {
			mark.style.display="block";
			insertMark.style.display="block";
			mark.style.top = $('#'+edit_id).position().top + $('#'+edit_id).outerHeight()+"px";
			mark.style.left=startCoord+"px";
			mark.style.width=endCoord-startCoord+paddingLeft+"px";
			insertMark.style.top=mark.style.top;
			switch (insertStatus) {
				case 2: //vlevo
					insertMark.style.left=startCoord-insertMarkHalfWidth+"px";
					break;
				case 1: //vpravo
					insertMark.style.left=startCoord+endCoord-startCoord+paddingLeft-insertMarkHalfWidth+"px";
					break;
				default: //vprostred
					insertMark.style.left=startCoord+Math.round((endCoord-startCoord+paddingLeft)/2)-insertMarkHalfWidth+"px";
			}
		} else {
			mark.style.display="none";
			insertMark.style.display="none";
		}

//		alert(mark.style.left+" x "+mark.style.top);
//		startCoord=8*startPos-ql.scrollLeft+"px";
//		endCoord=8*endPos-ql.scrollLeft+"px";
//		mark.style.left=startCoord;
//		mark.style.width=endCoord-startCoord;
//		if (elm.selectionStart<51) {
//			elm.style.backgroundPosition=8*elm.selectionStart+"px";
//		} else {
//			elm.style.backgroundPosition=8*(elm.selectionStart-noOfCharsVisible)+"px";
//		}
	} else {
		mark.style.width="0px";
	}
}

function hide_idx_window() {
	hide_window("sf_indexArea_left");
	hide_window("sf_indexArea");
	hide_window("sf_indexArea_right");
	hide_window("sf_indexArea_indicators");
	hide_window("sf_indexArea_insert_mark");
	idx_is_open=false;
	idx_tmp_line.style.backgroundImage="none";
  $('#asf_srch').removeAttr('disabled');
}

function get_help(forwhat, mylang) {
	var path="";
	switch (mylang) {
		case "cs":
			path="docs/mns_guide_index_cs.pdf"; 
			break;
		default:
			path="../docs/mns_guide_index_en.pdf";
	}
	var helpWin=window.open(path,'mns20help');
}


/**
*  ]:->  Block of useless and needless functions
*/

function mask_edit_in_progress(cc, edit_id) { //not used, to remove
	if (cc != '13') {
//		call_index(document.getElementById('idx_mask_text').selectionStart, 0, 'index_mask_change', edit_id, $('#idx_mask_text').val());  
		$('#idx_list_items').addClass('disabled');
		$('#idx_list_nums').addClass('disabled');
	} 
   else {
    $('#idx_list_items').removeClass('disabled');
    $('#idx_list_nums').removeClass('disabled');
		call_index(document.getElementById('idx_mask_text').selectionStart, 0, 'index_mask_change', edit_id, $('#idx_mask_text').val());
	}
}

/* function wtf_radios(cid,ccn) {
	var inputs=document.getElementsByTagName("input");
	for (i=0;i<inputs.length;i++) {
		if (inputs[i].className==ccn) {
			if (inputs[i].id!=cid) inputs[i].checked=false;
		}
	}
} */

function is_MSIE() {
	if (navigator.userAgent.indexOf("MSIE")!= -1) 
	return(1); else return(0); 
}

/**
*  ]:-> 
*/

