var main_field = ax_main_field,

initialColModel = ax_initialColModel;
initialColNames = ax_initialColNames;

var sort_order = ax_sort_order;
var nkjp_opinion_tab = ax_nkjp_opinion_vals;
var nkjp_source_tab = ax_nkjp_source_vals;

// te wartosci maja zasieg na wszystkie hasla
 window.schemas = new Array();
 var lemma_id = -1;
 var prev_lemma_id = -1;

// te wartosci trzeba czyscic przy ladowaniu innego hasla
 var selected_id = -1;
 var prev_selected_id = -1;
 var edited_id = -1;
 var elem_in_bucket = '';
 var manipulated_id = -1;
 var new_elem_id = -2;
 var frames_modif = new Array();
 var frames_modif_idx = 0;
 var copy_elem_id = -1;
 var activeNewFramePanel = 'frames_modif';
 var selectedArgumentsIdNkjp = new Array();
 var selectedFrameIdNkjp = -1;
 var nkjp_examples = new Array();
 var curr_example_id = -1;
 var selected_example_id = -1;
 var nkjp_lemma_examples = new Array();
 var curr_lemma_example_id = -1;
 var selected_lemma_example_id = -1;
 var addedFrame = '';
 var emptyFrame = new frame(-1, '', ['_', '_'], new Array(), '');
 var emptyPosition = new position(-1, '', new Array(), new Array());
 var lemma_entry = '';
 var prev_lemma_entry = '';
 var selected_notes_row_id = -1;
 //var can_modify = false;
 
////////////////////////////////////////////////////////////////
 
function alertUserNotAuthenticated() {
	error_alert('Przed wykonaniem działania odśwież okno przeglądarki, a następnie zaloguj się ponownie do narzędzia.');
}

function resetLemmaVersions() {
	window.frames_modif = new Array();
	window.frames_modif_idx = 0;
	var lemma_version = new Lemma_Version(window.schemas, 
			  							   window.nkjp_examples, 
			  							   window.nkjp_lemma_examples); 
	frames_modif.push(lemma_version);
}

function argsToRemove(example, elementToRemoveId)
{
	argumentsToRemove = []
	for(var i=0; i<example.arguments_ids.length; i++)
	{
		if(example.arguments_ids[i].startsWith(elementToRemoveId))
			argumentsToRemove.push(example.arguments_ids[i]);
	}
	return argumentsToRemove
}

function moveExampleToLemmaEx(example)
{
	window.nkjp_examples.splice($.inArray(example, window.nkjp_examples), 1);
    example.frame_id = '';
    example.arguments_ids = '';
    example.example_id = curr_lemma_example_id;
    window.nkjp_lemma_examples.push(example);
    window.curr_lemma_example_id--;	
}

function addPinnedExamplesDialog() {
    $('#pinned-examples-dialog').dialog({ 
    	title: 'Dowiązane przykłady',
    	autoOpen: false, 
	    modal: true,
	    width: 'auto', 
	    height: 'auto',
	    closeOnEscape: false,
	    open: function(event, ui) { 
	    	$('.ui-dialog-titlebar-close', this.parentNode).hide(); 
	    	if(!parseId(window.selected_id)['pos_id'])
	    		$('.ui-button:contains(Zostaw)').hide();
	    	else
	    		$('.ui-button:contains(Zostaw)').show();
	    	if(user_has_perm('dictionary.add_syntactic_frames'))
	    		$('.ui-button:contains(Odepnij)').show();
	    	else
	    		$('.ui-button:contains(Odepnij)').hide();
	    },
	    buttons: {
	    	Odepnij: function()
	    	{
	    		$(this).dialog('close');
	    		assignedExamples = $(this).data('assignedExamples');
	    		for(var i=0; i<assignedExamples.length; i++)
	    		{
	    			example = assignedExamples[i];
	    			moveExampleToLemmaEx(example);
	    		}
	    		window.schemas = removeFrameElement(window.selected_id, window.schemas);
	    	    draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
	    	    $("tr.NkjpLemmaTableRow").click(function(){
	    	      selectLemmaNkjpTr(this.id)});
	    		new_frames_make_change();
	    	},
	    	Zostaw: function()
	    	{
	    		$(this).dialog('close');
	    		assignedExamples = $(this).data('assignedExamples');
	    		addSyntacticFramesPerm = user_has_perm('dictionary.add_syntactic_frames');
	    		
	    		for(var i=0; i<assignedExamples.length; i++)
	    		{
	    			example = assignedExamples[i];
	    			argumentsToRemove = argsToRemove(example, window.selected_id); 
	    			if(argumentsToRemove.length == example.arguments_ids.length)
	    			{
	    				if(addSyntacticFramesPerm) {
	    					moveExampleToLemmaEx(example);
	    				}
	    				else {
	    					window.nkjp_examples.splice($.inArray(example, window.nkjp_examples), 1);
	    				}
	    			}
	    			else
	    			{
	    				newArgumentsIds = $.grep(example.arguments_ids, function(n, i){
	    					                       return $.inArray(n, argumentsToRemove) == -1;
	    					              });
	    				window.nkjp_examples[$.inArray(example, window.nkjp_examples)].arguments_ids = newArgumentsIds;
	    			}
	    		}
	    		window.schemas = removeFrameElement(window.selected_id, window.schemas);
	    	    draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
	    	    $("tr.NkjpLemmaTableRow").click(function(){
	    	      selectLemmaNkjpTr(this.id)});
	    		new_frames_make_change();
	    	},
	    	Anuluj: function()
	    	{
	    		$(this).dialog('close');
	    	}
	    }
    });
}

///////////////////////////////////////////////////////////////

function load_content(id) {
  $('#add-table-elem-dialog').dialog('close');
  if(lemma_id != id)
    $('#ready-note-dialog').dialog('close');
  initiateFrameFilters();
  
  if(window.activeLemmaPanel == 'preview_lemma')
  {   
	ShowProgressAnimation();
    $('#preview_lemma').load(ajax_lemma_preview, 'id='+id+'&main_lemma_id='+window.lemma_id, function(){
       window.prev_lemma_id=id;
       loadPrevSchemataAndExamples(true);
       createSplitter('prevFramesSplit', 'prev-lemma-tables', 'prev_tabs');
       areNewPreviewEntriesRelated();
    });
  }
  else
  {
	ShowProgressAnimation();
    // czyszczenie wartosci
	window.elem_in_bucket = '';
    window.selected_notes_row_id = -1;
    window.selected_id = -1;
    window.prev_selected_id = -1;
    window.edited_id = -1;
    window.manipulated_id = -1;
    window.new_elem_id = -2;
    window.copy_elem_id = -1;
    window.activeNewFramePanel = 'frames_modif';
    window.selectedArgumentsIdNkjp = new Array();
    window.selectedFrameIdNkjp = -1;
    window.nkjp_examples = new Array();
    window.curr_example_id = -1;
    window.selected_example_id = -1;
    window.lemma_nkjp_examples = new Array();
    window.curr_lemma_example_id = -1;
    window.selected_lemma_example_id = -1;
    window.addedFrame = '';
  
    $('#new_frames').empty();
    $('#preview_lemma').empty();
    $('#status').empty();
    window.change = false;
    window.notesNotSaved = false;
    window.lemmaExNotSaved = false;
      
    $('#new_frames').load(ajax_new_frames, 'id='+id, function(data){
        window.lemma_id = id;
        
        loadSchemataAndExamples();
        
        createSplitter('framesSplit','new-frame-tables', 'tabs');
        /*if(window.can_modify)
        {
          addSyntacticFramesPerm = user_has_perm('dictionary.add_syntactic_frames');
          addPhraseologicFramesPerm = user_has_perm('dictionary.add_phraseologic_frames');
          
          if(addSyntacticFramesPerm || addPhraseologicFramesPerm) {
              $(document).unbind('keydown');
              $(document).bind('keydown', 'shift+s', saveHandle);
              $(document).bind('keydown', 'shift+z', function(evt){backOneModification(); return false; });
              $(document).bind('keydown', 'shift+y', function(evt){forwardOneModification(); return false; });
              $(document).bind('keydown', 'shift+a', function(evt){addElement(); return false; });
              $(document).bind('keydown', 'shift+r', function(evt){removeElement(); return false; });
              $(document).bind('keydown', 'shift+d', function(evt){duplicateElement(); return false; });
              $(document).bind('keydown', 'shift+c', function(evt){copyElement(); return false; });
              $(document).bind('keydown', 'shift+v', function(evt){pasteElement(); return false; });
              $(document).bind('keydown', 'shift+w', function(evt){validateSchemata(); return false; }); 
              if(addSyntacticFramesPerm) {
            	  $(document).bind('keydown', 'shift+x', function(evt){cutElement(); return false; });
                  $(document).bind('keydown', 'shift+m', function(evt){reserveLemma(); return false; });
              }
              if(addPhraseologicFramesPerm) {
            	  $(document).bind('keydown', 'shift+l', function(evt){addPhraseologicFrame(); return false; });
            	  $(document).bind('keydown', 'shift+b', function(evt){openAssignPhraseologicFrameDialog(); return false; });
              }
          }
        }
        else
        {
          $(document).unbind('keydown');
          $.get(ajax_user_has_perm, {perm: 'dictionary.own_lemmas'}, function(result) {
              if(result['has_perm']) {
            	  $(document).bind('keydown', 'shift+m', function(evt){reserveLemma(); return false; });
              }
          });
        }*/

  		if(document.getElementById("lemma_example_show"))
  		{
  		  draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_')
          $("tr.NkjpLemmaTableRow").click(function(){
            selectLemmaNkjpTr(this.id)});
        }  
  		addPinnedExamplesDialog();
  	    $('#lemma_desc').load(ajax_get_lemma_desc, 'id='+id);
  	    areNewPreviewEntriesRelated();
  		refresh_example_propositions();
      });
      $('#change_ctrl').load(ajax_change_ctrl, 'id='+id);
      $('#semantics').load(ajax_semantics, 'id='+id);
      $('#status').load(ajax_lemma_status, 'id='+id, function(){
    	  $("#lemma-status-change button").click(validate_and_change_status);
    	  $('#ready-note-dialog').dialog({ autoOpen: false, 
    		                               modal: true,
    		                               width: 'auto', 
    		                               height: 'auto',
    		                               closeOnEscape: true,
    		                               open: function(event, ui) { $('#ready-note-dialog #id_message_text').focus(); }
    	  });  
      });
      $('#notes').load(ajax_lemma_notes, 'id='+id);
      
      if(window.prev_lemma_id == -1)
        prevId = id;
      else 
        prevId = window.prev_lemma_id;
      
      $('#preview_lemma').load(ajax_lemma_preview, 'id='+prevId+'&main_lemma_id='+id, function(){
        window.prev_lemma_id=prevId;
        loadPrevSchemataAndExamples(false);
        createSplitter('prevFramesSplit', 'prev-lemma-tables', 'prev_tabs');
        areNewPreviewEntriesRelated();
      });  
  }
}

function validateSchemata() {
    if(window.change) {
        error_alert('Przed walidacją/zmianą statusu hasło musi zostać zapisane.');
        return false;
    }
    validate_new_frames(false, false);
}

function loadSchemataAndExamples() {
    $.ajaxJSON({
        method: 'get',
        url: ajax_get_schemata_and_examples,
        data: {
          lemma_id: window.lemma_id
        },

        callback: function(result) {
    	  window.schemas = serializedObjToObj(result['schemata']);
    	  window.nkjp_examples = serializedNkjpToObj(result['examples']);
    	  window.nkjp_lemma_examples = serializedNkjpToObj(result['lemma_examples']);
    	  resetLemmaVersions();
    	  var frame_class = 'InactiveFrameTable';
    	  if(result['can_modify']) {
    	      frame_class = 'ActiveFrameTable';
    	  }
    	  draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 
    			  			   'frame_filter', window.nkjp_examples, frame_class, 
    			  			   window.lemma_entry, window.lemma_entry);
          $('#examples').load(ajax_lemma_examples, 'id='+window.lemma_id, function(){
        	  draw_nkjp_table(document.getElementById("lemma_example_show"), '', 
        			          window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_')
              $("tr.NkjpLemmaTableRow").click(function(){selectLemmaNkjpTr(this.id)});
        	  HideProgressAnimation();
          });
          $("span#new-frames-count").empty();
          $("span#new-frames-count").append(window.schemas.length);
          $("span#lemma-examples-count").empty();
          $("span#lemma-examples-count").append(window.nkjp_lemma_examples.length);
        },
    });
}

function loadPrevSchemataAndExamples(hideWaitDialog) {
    $.ajaxJSON({
        method: 'get',
        url: ajax_get_schemata_and_examples,
        data: {
          lemma_id: window.prev_lemma_id
        },
        callback: function(result) {
          window.prev_frames = serializedObjToObj(result['schemata']);
          window.prev_nkjp_examples = serializedNkjpToObj(result['examples']);
    	  draw_filtered_frames(window.prev_frames, 'prev-lemma-tables', 'prev-lemma-table', 'prev_frame_filter', 
    			               window.prev_nkjp_examples, 'InactiveFrameTable', window.prev_lemma_entry);
    	  if(hideWaitDialog) {
    		  HideProgressAnimation();
    	  }
        },
    });
}

// klasa reprezentujaca wersje hasla, do cofania i dodawania
function Lemma_Version(schemas, nkjp_examples, nkjp_lemma_examples)
{
  	this.schemas = $.evalJSON($.toJSON(schemas));
  	this.nkjp_examples = $.evalJSON($.toJSON(nkjp_examples));
  	this.nkjp_lemma_examples = $.evalJSON($.toJSON(nkjp_lemma_examples));
}
  
 // position class
function position(id, text_rep, categories, arguments)
{
  	this.id = id;
  	this.text_rep = text_rep;
  	this.categories = categories;
  	this.arguments = arguments; 
  	this.error = false;
  	this.tooltip = '';
}
  
   // frame class
function frame(id, text_rep, characteristics, positions, opinion)
{
  	this.id = id
  	this.text_rep = text_rep;
    this.characteristics = characteristics;
    this.positions = positions;
    this.opinion = opinion;
    this.error = false;
    this.tooltip = '';
    this.is_phraseologic = false;
}  

function Nkjp_example(example_id, frame_id, arguments_ids, sentence, source, opinion, comment, semantic)
{
    this.example_id = example_id;
	this.frame_id = frame_id;
	this.arguments_ids = arguments_ids;
	this.sentence = sentence;
	this.source = source;
	this.opinion = opinion;
	this.comment = comment;
	this.semantic = semantic;
	this.lexical_unit = -1;
}

function Nkjp_example_ajax(frame, arg_selections, sentence, source, opinion, comment, semantic, lexical_unit)
{
	this.frame = frame;
	this.arg_selections = arg_selections;
	this.sentence = sentence;
	this.source = source;
	this.opinion = opinion;
	this.comment = comment;
	this.semantic = semantic;
	this.lexical_unit = lexical_unit;
}

function Nkjp_ArgSelection(position, arguments)
{
  this.position = position;
  this.arguments = arguments;
}

function frameToTableRows(frame)
{
    var rows = new Array();
    var max_arguments = 0;
    var number_of_positions = frame.positions.length;
    
    var positions_cat_row = new Array();
    for(var i=0; i < number_of_positions; i++)
    {
      positions_cat_row.push(frame.positions[i])
      if(max_arguments < frame.positions[i].arguments.length)
      	max_arguments = frame.positions[i].arguments.length;
    }
    
    rows.push(positions_cat_row);
  // appending table headers spans
    var span = new Array();
    span.push(number_of_positions);
    span.push(max_arguments);   
    rows.push(span);
 
    var arg_number = 0;
    
    for(var row_number=2; row_number<max_arguments+2; row_number++)
    {
      var arguments_row = new Array();
      for(var i=0; i < number_of_positions; i++)
      {
        if(frame.positions[i].arguments[arg_number])
          arguments_row.push(frame.positions[i].arguments[arg_number]);
        else
        {
          arguments_row.push(new argument(new_elem_id, '', '', []));
          new_elem_id--;
        }
      }  

      rows.push(arguments_row)
      arg_number++;
    }     
    return rows;
}


// puste frame_id oznacza rysowanie tabeli dla lemma
function draw_nkjp_table(parent, frame_id, nkjp_examples, row_class, td_id)
{
  $(parent).empty();
  var table = document.createElement('table');
  table.setAttribute('class', 'ExamplesTable');
  table.setAttribute('id', 'nkjp_table');
  	
  var tr = document.createElement('tr');
  var td = document.createElement('td');
  td.setAttribute('class', 'ColumnHeader');
  td.appendChild(document.createTextNode("Identyfikator:"));
  tr.appendChild(td);
  td = document.createElement('td');
  td.setAttribute('class', 'ColumnHeader');
  td.appendChild(document.createTextNode("Przykład:"));
  tr.appendChild(td);
  td = document.createElement('td');
  td.setAttribute('class', 'ColumnHeader');
  td.appendChild(document.createTextNode("Źródło:"));	
  tr.appendChild(td);
  td = document.createElement('td');
  td.setAttribute('class', 'ColumnHeader');
  td.appendChild(document.createTextNode("Ocena:"));	
  tr.appendChild(td);
  table.appendChild(tr);
  
  for(var k=0; k<nkjp_source_tab.length; k++)
  {
    for(var j=0; j<nkjp_opinion_tab.length; j++)
    {
      for(var i=0; i<nkjp_examples.length; i++)
      {  	
        if(nkjp_opinion_tab[j] == nkjp_examples[i].opinion && 
           nkjp_source_tab[k] == nkjp_examples[i].source &&
          (nkjp_examples[i].frame_id == frame_id || !frame_id)) // !frame_id oznacza, ze rysujemy wszystkie przyklady
        {
          var tdClass = '';
          if(nkjp_examples[i].semantic) {
        	  tdClass = 'Semantic';
          }
          tr = document.createElement('tr');
          tr.setAttribute('class', row_class);
          tr.setAttribute('id', td_id+nkjp_examples[i].example_id);
          td = document.createElement('td');
          td.setAttribute('class', tdClass);
          td.appendChild(document.createTextNode(nkjp_examples[i].example_id));
          tr.appendChild(td);
          td = document.createElement('td');
          td.setAttribute('class', tdClass);
          td.appendChild(document.createTextNode(nkjp_examples[i].sentence));
          tr.appendChild(td);
          td = document.createElement('td');
          td.setAttribute('class', tdClass);
          td.appendChild(document.createTextNode(nkjp_examples[i].source));
          tr.appendChild(td);
          td = document.createElement('td');
          td.setAttribute('class', tdClass);
          td.appendChild(document.createTextNode(nkjp_examples[i].opinion));
          tr.appendChild(td);
          table.appendChild(tr);
        }
      }
    }
  }
  parent.appendChild(table);
}

function selectNkjpTr(id)
{  	 
  if(window.selected_example_id != -1)
  {
  	var recent_row = document.getElementById(window.selected_example_id);
  	var recent_descendants = getDescendantsNodes(recent_row);
  	for(var i = 0; i<recent_descendants.length; i++)
  	  $(recent_descendants[i]).css("background-color", "");
  }
  	
  if(window.selected_example_id == id)
  {
  	  window.selected_example_id = -1;
  }
  else
  {
  	window.selected_example_id = id;
  	var row = document.getElementById(id);
  	var descendants = getDescendantsNodes(row);
  	for(var i = 0; i<descendants.length; i++)
  	  $(descendants[i]).css("background-color", "LightSteelBlue");  	  
  	nkjpInstance = getNkjpExampleInstance(window.nkjp_examples, id);
  	needConfirmation(nkjpInstance);
 
 // wyswietlanie komentarza jesli istnieje
    var last_shown_comm_elem = document.getElementById('example_comment');
  	$(last_shown_comm_elem).remove();
 
  	if(nkjpInstance.comment)
  	{
  	   var nkjp_table_container = document.getElementById("show_nkjp_table");
  	   
  	   var outer_div = document.createElement('div');
  	   outer_div.setAttribute('id', 'example_comment');
  	   var strong = document.createElement('strong');
  	   strong.appendChild(document.createTextNode("Komentarz do przykładu:"));
  	   outer_div.appendChild(strong);
  	   div = document.createElement('div');
  	   pre = document.createElement('pre');
  	   pre.appendChild(document.createTextNode(nkjpInstance.comment));
  	   div.appendChild(pre);
  	   outer_div.appendChild(div);
  	   nkjp_table_container.appendChild(outer_div);
  	}	 
  	
    var parent = document.getElementById("new-frame-tables");
    var matching_elements = getMatchingElements(parent, nkjpInstance.frame_id);
	for(var i=0; i<matching_elements.length; i++)
      $(matching_elements[i]).css("background-color", "LightSteelBlue");
      
    for(var i=0; i<nkjpInstance.arguments_ids.length; i++)
    {
      unselectTd(nkjpInstance.arguments_ids[i]);
    }
  }
}

function selectLemmaNkjpTr(id)
{  	 
  if(window.selected_lemma_example_id != -1)
  {
  	var recent_row = document.getElementById(window.selected_lemma_example_id);
  	var recent_descendants = getDescendantsNodes(recent_row);
  	for(var i = 0; i<recent_descendants.length; i++)
  	  $(recent_descendants[i]).css("background-color", "");
  }
  	
  if(window.selected_lemma_example_id == id)
  {
  	  window.selected_lemma_example_id = -1;
  	  resetForm($('.lemma-example-form'));
  }
  else
  {
  	window.selected_lemma_example_id = id;
  	var row = document.getElementById(id);
  	var descendants = getDescendantsNodes(row);
  	for(var i = 0; i<descendants.length; i++)
  	  $(descendants[i]).css("background-color", "LightSteelBlue");  
  		  
  	nkjpInstance = getNkjpLemmaExampleInstance(window.nkjp_lemma_examples, id);
  	fill_nkjp_example_form(nkjpInstance, '.lemma-example-form');
  }
}

function confirm_lemma_example(example_tabId)
{
  nkjpInstance = getNkjpLemmaExampleInstance(window.nkjp_lemma_examples, example_tabId);
  confirmNkjpExample(nkjpInstance);
}

function confirmNkjpExample(nkjpInstance)
{  	  
    ShowProgressAnimation();
    if(nkjpInstance.example_id < 0)
    {
      HideProgressAnimation();
      return false;
    }

    $.ajaxJSON({
      method: 'post',
      url: ajax_confirm_nkjp_example,
      data: {
        example_id: nkjpInstance.example_id,
        lemma_id: window.lemma_id
      },

    callback: function(result) {   
      if(nkjpInstance.frame_id) // przyklad dodany do schematu
        $("button#confirm_example").css("visibility","hidden"); 
      else // przyklad dodany do hasla
        $("button#confirm_lemma_example").css("visibility","hidden");
      HideProgressAnimation();	
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      HideProgressAnimation();
      return true;
    },
  });
  return false;
}

function needConfirmation(nkjpInstance) {
    $.ajaxJSON({
      method: 'get',
      url: ajax_can_confirm_example,
      data: {
        example_id: nkjpInstance.example_id,
        lemma_id: window.lemma_id
      },

    callback: function(result) {      
      if(result['can_confirm']) {
          $("button#confirm_example").css("visibility","visible");
      }
      else {
          $("button#confirm_example").css("visibility","hidden");
      }   	
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      return true;
    },
  });
  return false;
}

function unpin_nkjp_example(example_tabId)
{ 
  if(example_tabId != -1 &&
	 !checkIfSemChangedAndAlert())
  {
    example_id = example_tabId.replace('nkjp_', '');
    for(var i=0; i<window.nkjp_examples.length; i++)
    {
      if(window.nkjp_examples[i].example_id == example_id)
      {
        if(confirm("Czy jesteś pewien, że chcesz odpiąć od schematu wskazany przykład?")){
          window.selected_example_id = -1;
          example = nkjp_examples[i];
          nkjp_examples.splice(i, 1);
          example.frame_id = ''
          example.arguments_ids = ''
          example.example_id = curr_lemma_example_id;
          window.nkjp_lemma_examples.push(example);
          window.curr_lemma_example_id--;
      // rysowanie tabeli nkjp examples na nowo
          draw_nkjp_table(document.getElementById("show_nkjp_table"), window.selectedFrameIdNkjp, window.nkjp_examples, 'NkjpTableRow', 'nkjp_');
          $("tr.NkjpTableRow").click(function(){
            selectNkjpTr(this.id)});
      // rysowanie tabeli lemma nkjp examples na nowo
          draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
          $("tr.NkjpLemmaTableRow").click(function(){
            selectLemmaNkjpTr(this.id)});
      // rysowanie tabel ze schematami
          scrollPosition = $('#new-frame-tables').scrollTop();
          draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
          $('#new-frame-tables').scrollTop(scrollPosition);
      // zapisanie nowej wartosci w tabeli modyfikacji
          window.frames_modif = window.frames_modif.slice(0, frames_modif_idx+1);     
          var lemma_version = new Lemma_Version(window.schemas, window.nkjp_examples, window.nkjp_lemma_examples);
          window.frames_modif.push(lemma_version);
          window.frames_modif_idx++;
          change = true;
        }
        break;
      }
    }
  }
}

function gotAssignedExample(nkjp_examples, element_id, deleteAction)
{
  var id_map = parseId(element_id);
  var frame_id = 'frame_'+id_map['frame_id']+'_';
  var assignedExamples = [];
  
  if(id_map['arg_id'] && deleteAction)
  {
    var arg_id = 'frame_'+id_map['frame_id']+'_pos_'+id_map['pos_id']+'_arg_'+id_map['arg_id']+'_';
    confirmed = false;
    for(var i=0; i<nkjp_examples.length; i++)
    {
      if(nkjp_examples[i].frame_id == frame_id)
      {
        for(var j=0; j<nkjp_examples[i].arguments_ids.length; j++)
        {
          if(nkjp_examples[i].arguments_ids[j] == arg_id)
          {
        	  if($.inArray(nkjp_examples[i], assignedExamples) === -1) 
        		  assignedExamples.push(nkjp_examples[i]);
          }
        }
      }
    }
  }
  else if(deleteAction)
  {
    if(!id_map['pos_id'])
    {
      confirmed = false;
      for(var i=0; i<nkjp_examples.length; i++)
      {
        if(nkjp_examples[i].frame_id == frame_id)
        {
      	  if($.inArray(nkjp_examples[i], assignedExamples) === -1) 
    		  assignedExamples.push(nkjp_examples[i]);
        }
      }   
    }    
    else if(id_map['pos_id'])
    {
      confirmed = false;
      var pos_id = 'frame_'+id_map['frame_id']+'_pos_'+id_map['pos_id']+'_';
      
      for(var i=0; i<nkjp_examples.length; i++)
      {
        for(var j=0; j<nkjp_examples[i].arguments_ids.length; j++)
        {
          if(nkjp_examples[i].arguments_ids[j].startsWith(pos_id))
          {
        	  if($.inArray(nkjp_examples[i], assignedExamples) === -1) 
        		  assignedExamples.push(nkjp_examples[i]);
          }
        }
      }   
    }
  }
  return assignedExamples;
}

function gotAssignedExampleId(nkjp_examples, element_id)
{
  var frame_id = 'frame_'+element_id+'_';
  for(var i=0; i<nkjp_examples.length; i++)
  {
    if(nkjp_examples[i].frame_id == frame_id)
    {
      return true;
    }
  }
  return false;
}

function getNkjpExampleInstance(nkjp_examples, example_id)
{
  var example_id = example_id.replace('nkjp_', '');
  for(var i=0; i<nkjp_examples.length; i++)
  {
    if(nkjp_examples[i].example_id == example_id)
      return nkjp_examples[i];
  }
  return '';
}

function getNkjpLemmaExampleInstance(nkjp_examples, example_id)
{
  var example_id = example_id.replace('nkjpLemma_', '');
  for(var i=0; i<nkjp_examples.length; i++)
  {
    if(nkjp_examples[i].example_id == example_id)
      return nkjp_examples[i];
  }
  return '';
}

function remove_semantic_example(example_id) {
  if(example_id != -1 && !checkIfSemChangedAndAlert())
  {
    example_id = example_id.replace('nkjp_', '');
    for(var i=0; i<nkjp_examples.length; i++)
    {
      if(nkjp_examples[i].example_id == example_id)
      {
        if(nkjp_examples[i].semantic) {
        	remove_example_from_lemma(window.lemma_id, example_id, i);
        	break;
        }
      }  
    }
  }
}

function remove_example_from_lemma(lemma_id, example_id, examplesTabId) {
	  ShowProgressAnimation();
	  jQuery.ajax({
		type: 'post',
	    url: ajax_remove_example_from_lemma,
	    data: {
	    	lemma_id: lemma_id,
	    	example_id: example_id
	    },
	    success: function(result) {
	        nkjp_examples.splice(examplesTabId, 1);  
			   
		    window.selected_example_id = -1;
		    var parent = document.getElementById("show_nkjp_table");
		    draw_nkjp_table(parent, selectedFrameIdNkjp, window.nkjp_examples, 'NkjpTableRow', 'nkjp_');  
		    $("tr.NkjpTableRow").click(function(){
		      selectNkjpTr(this.id)});
		    
		    scrollPosition = $('#new-frame-tables').scrollTop();
		    draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
		    $('#new-frame-tables').scrollTop(scrollPosition);  	      
	    	HideProgressAnimation();
	    },
	    error_callback: function(xhr, status, error) {
	        HideProgressAnimation();
	        error_alert(status + ': ' + error);
	    },
	    bad_data_callback: function(result) {
	        if (result == 'old lemma') {
	            HideProgressAnimation();
	            error_alert('Odśwież hasło, widoczna wersja nie jest aktualna.');
	            return false;
	          } 
	        else {
	          HideProgressAnimation();
	          return true;
	        }
	    }
	  });
}

function addFrameClickEvents(tableClass, tableId) {
	selector = 'table.'+tableClass+'#'+tableId+' td';
	if(tableId === 'new-frame-table') {
		if(tableClass === 'ActiveFrameTable') {
			$(selector).dblclick(function(e){
		        e.stopPropagation();
		        openEditForm(this.id)});
		}
	    $(selector).click(function(e){
	        e.stopPropagation();
	        selectTd(this.id)});		
	}
	else if(tableId === 'prev-lemma-table') {
		$(selector).click(function(e){
	        e.stopPropagation();
	        selectPrevTd(this.id)});
	}
}

function draw_frames(schemas, parent, table_name, nkjp_examples, table_class, lemma_entry)
{
  $(parent).empty();
  window.selectedArgumentsIdNkjp = new Array();
  addSyntacticFramesPerm = user_has_perm('dictionary.add_syntactic_frames');
  addPhraseologicFramesPerm = user_has_perm('dictionary.add_phraseologic_frames');

  for(var i=0; i<window.reflex_vals.length; i++)
  {
	for(var l=0; l<window.neg_vals.length; l++)
	{
		for(var m=0; m<window.pred_vals.length; m++)
	    {
		    for(var k=0; k<window.aspect_vals.length; k++)
		    {
		      first = true;
		      for(var j=0; j<schemas.length; j++)
		      {
		        if(schemas[j].characteristics[3]==aspect_vals[k].value && schemas[j].characteristics[0]==reflex_vals[i].value && 
		           schemas[j].characteristics[1]==neg_vals[l].value && schemas[j].characteristics[2]==pred_vals[m].value)
		        {
		          if(first)
		          {
		            div = document.createElement('div');
		            strong = document.createElement('strong');
		            if(reflex_vals[i].value)
		  	          strong.appendChild(document.createTextNode(lemma_entry+" "+reflex_vals[i].name+" "+"("+neg_vals[l].name+","+pred_vals[m].name+","+aspect_vals[k].name+"):"));
		  	        else
		  	          strong.appendChild(document.createTextNode(lemma_entry+" "+"("+neg_vals[l].name+","+pred_vals[m].name+","+aspect_vals[k].name+"):"));
		  	        div.appendChild(strong);
		  	        parent.appendChild(div);
		            first = false;
		          }
		          var rows = frameToTableRows(schemas[j]);
		          frame_class = table_class;
		          if((schemas[j].is_phraseologic && !(addPhraseologicFramesPerm || addSyntacticFramesPerm)) ||
		        	 (!schemas[j].is_phraseologic && !addSyntacticFramesPerm))
		          {
		        	  frame_class = 'InactiveFrameTable';
		          }
		        	var table = document.createElement('table');
		          	parent.appendChild(table);
		          	var tr = document.createElement('tr');
		          	var td = document.createElement('td');
		          	
		          if(gotAssignedExampleId(nkjp_examples, schemas[j].id) && 
		            wholeCoordinationSpecified(schemas[j], nkjp_examples)) {
		        	  draw_table(td, schemas[j], rows, table_name, frame_class, 'CheckComp');
		          }
		          else if(gotAssignedExampleId(nkjp_examples, schemas[j].id)) {
		        	  draw_table(td, schemas[j], rows, table_name, frame_class, 'Check');
		          }
		          else {
		        	  draw_table(td, schemas[j], rows, table_name, frame_class, '');
		          }
		          tr.appendChild(td);
		          table.appendChild(tr);
		          
		        }
		      }
		    }
	    }
    }
  }
  addFrameClickEvents('InactiveFrameTable', table_name);
  addFrameClickEvents('ActiveFrameTable', table_name);
}

function goToFrame(tab_id, tables_div) {
	$(tables_div).scrollTo('#'+tab_id, {duration:'slow', offset:-10});
}

function draw_table(parent, frame, rows, table_id, table_class, coordinationClass)
{
  	var frame_table_container = parent;
  	frame_error = false;
  	var table = document.createElement('table');
  	table.setAttribute('class', table_class);
  	table.setAttribute('id', table_id);
  	if (frame.is_phraseologic) {
  		table.setAttribute('style', 'border:10px double gray;');
    }
  	
  	frame_table_container.appendChild(table);
  	
  	// wiersz opisujacy opinie na temat schematow
  	var tr = document.createElement('tr');
  	var td = document.createElement('td');
  	td.setAttribute('class', 'ColumnHeader');
  	td.appendChild(document.createTextNode("Schemat:"));
  	tr.appendChild(td);
  	 // pole z wartosciami cech schematu
  	td = document.createElement('td');
  	td.setAttribute('colspan', rows[1][0]);
  	td.setAttribute('id', 'frame_'+frame.id+'_');
  	td.setAttribute('class', 'ColumnCategory');
  	if(frame.error) {
  	  frame_error = true;
  	  td.setAttribute('style', 'background-color:red;'); 
  	  td.setAttribute('title', frame.tooltip);
  	}
  	
  	span_op = document.createElement('span');
  	span_op.setAttribute('class', 'Opinion');
  	span_op.appendChild(document.createTextNode(frame.opinion + ' ['+frame.id+']'));
  	td.appendChild(span_op);
  	span_img = document.createElement('span');
  	span_img.setAttribute('class', coordinationClass);
  	td.appendChild(span_img);
  	tr.appendChild(td);
  	table.appendChild(tr);// koniec pierwszego wiersza
  	
  	// wiersz opisujacy funkcje pozycji
  	tr = document.createElement('tr');
  	td = document.createElement('td');
  	td.setAttribute('class', 'ColumnHeader');
  	td.appendChild(document.createTextNode("Funkcja:"));
  	tr.appendChild(td);
  	
  	// pola z wartosciami funkcji pozycji
  	error_col = -1;
  	for(var i=0; i<frame.positions.length; i++)
  	{
  	  var position = frame.positions[i];
  	  td = document.createElement('td');
  	  td.setAttribute('id', 'frame_'+frame.id+'_pos_'+position.id+'_');
  	  td.setAttribute('class', 'position');
  	  if(position.error || frame_error)
  	  {
  	    error_col = i;
  	    td.setAttribute('style', 'background-color:red;');
  	  }
  	  if(position.error)
  	    td.setAttribute('title', position.tooltip);
  	  td.appendChild(document.createTextNode(position.categories.join(',')));
  	  tr.appendChild(td);
  	}
  	table.appendChild(tr); // koniec wiersza opisujacego funkcje pozycji
  	
  	// wiersze opisujace typy fraz w pozycjach
  	tr = document.createElement('tr'); 
  	td = document.createElement('td');
  	td.setAttribute('rowspan', rows[1][1]);
  	td.setAttribute('class', 'ColumnHeader');
  	td.appendChild(document.createTextNode("Typy fraz:"));
  	tr.appendChild(td);
  	
  	for(var row = 2; row<rows.length;row++)
  	{
  	  if(row > 2)
  	    tr = document.createElement('tr');
  	    
  	  for(var col=0; col<frame.positions.length; col++)
  	  {
  	    td = document.createElement('td');
  	    td.setAttribute('class', 'arg');
  	    td.setAttribute('id', 'frame_'+frame.id+'_pos_'+frame.positions[col].id+'_arg_'+rows[row][col].id+'_');
  	    if(rows[row][col].error || frame.positions[col].error || frame_error)
  	    {
  	      td.setAttribute('style', 'background-color:red;');
  	    }
  	    if(rows[row][col].error)
  	      td.setAttribute('title', rows[row][col].tooltip);
  	    
  	    td.appendChild(document.createTextNode(rows[row][col].text_rep)); 
  	    tr.appendChild(td);
  	  }
  	  table.appendChild(tr);
  	}	
}

function createSplitter(split_id, top_id, bottom_id) {
  $('#'+split_id).height($('#right').height() - 70);
  if ($.fn.splitter) {
	$(window).resize(function() {
		$('#'+split_id).height($('#right').height() - 70);
	});
    $('#'+top_id).bind('resize', function(e) {
      e.stopPropagation();
    });
    $('#'+bottom_id).bind('resize', function(e) {
      e.stopPropagation();
    });
    $('#'+split_id).splitter({
      type: "h",
      minTop: 200,
      minBottom: 50,
      sizeBottom: 170,
      resizeToWidth: true
    });
  }
}

///////////////////////////////////////////////////////////////////////////////////
 
 String.prototype.trim = function()
 {return (this.replace(/^\s+|\s+$/g, ''))}

function assignPhraseologicFrameFormSubmit() {
    ShowProgressAnimation();
    this_form = $(this);
    
    form_data = this_form.serializeArray();
    var entry = '';
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'entry' && elem.name != 'phraseologic_frame')
        return elem;
      else {
        if (elem.name == 'entry')
          entry = elem.value;
        else if (elem.name == 'phraseologic_frame')
        	phraseologic_frame = elem.value;
      }
    });

	form_data.push({name: 'entry', value: entry});
	form_data.push({name: 'phraseologic_frame', value: phraseologic_frame});

    $.ajaxJSON({
      method: 'post',
      url: ajax_assign_phraseologic_frame,
      data: {
        form_data: form_data,
        lemma_id: window.lemma_id,
      },

    callback: function(result) {
      HideProgressAnimation();	
      openAssignPhraseologicFrameDialog();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result) {
        HideProgressAnimation();
        error_alert(result);
        return false;
      } 
      else {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function add_pos_form_submit() {
    ShowProgressAnimation();
    this_form = $(this);
    
    form_data = this_form.serializeArray();
    categories = [];
    args = [];
    position_id = -1;
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'frequent_positions' && elem.name != 'filtered_positions')
        return elem;
      else {
        if (elem.name == 'frequent_positions')
          frequent_positions = elem.value;
        else if (elem.name == 'filtered_positions')
          filtered_positions = elem.value;
      }
    });

	form_data.push({name: 'frequent_positions', value: frequent_positions});
    form_data.push({name: 'filtered_positions', value: filtered_positions});

    $.ajaxJSON({
      method: 'post',
      url: ajax_add_position,
      data: {
        form_data: form_data
      },

    callback: function(result) {
      var catsObj = eval('(' + result["categories"] + ')');
      var argsObj = eval('(' + result["arguments"] + ')');
      
      var arguments = new Array();
      for(var i=0; i<argsObj.length; i++)
      {
        arguments.push(new argument(argsObj[i].pk, argsObj[i].fields.text_rep, argsObj[i].fields.type, []));
      }
      
      var cats = new Array();
      for(var i=0; i<catsObj.length; i++)
      {
        cats.push(catsObj[i].fields.category);
      }

      pos_id = new_elem_id;
      new_elem_id--;
      
      var pos = $.evalJSON($.toJSON(window.emptyPosition));
      pos.id = pos_id;
      pos.text_rep = result["text_rep"];
      pos.categories = cats;
      pos.arguments = arguments;
      
      schemas = addFramePosition(selected_id, schemas, pos);
      window.selected_id = -1;
      
      this_form.closest("$[id$='-dialog']").dialog('close');
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      change = true;
      HideProgressAnimation();	
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'not proper selection') {
        HideProgressAnimation();
        error_alert('Wybierz tylko jedną pozycję.');
        return false;
      }
      else if (result == 'wrong position representation')
      {
        HideProgressAnimation();
        error_alert('Niewłaściwie zapisana reprezentacja tekstowa pozycji.');
        return false;
      }   
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}
 
function addFrameElementDialog(id, schemas)
{    
  if(id!=-1 && id.startsWith('frame'))
  {
    var ids = parseId(id);
    var frame_id = ids['frame_id'];
    var pos_id = ids['pos_id'];
    var arg_id = ids['arg_id'];
      
    for(var i=0; i<schemas.length; i++)
    {
      if(schemas[i].id == frame_id && pos_id)
      {
        for(var j=0; j<schemas[i].positions.length; j++)
        {
          if(schemas[i].positions[j].id == pos_id && arg_id)
          {
          	return schemas;
          }
          else if(schemas[i].positions[j].id == pos_id)
          {
            // dodawanie argumentu do pozycji
        	positionArguments = schemas[i].positions[j].arguments; 
            $('#add-table-elem-dialog').data('positionArguments', positionArguments)
            						   .data('selectedFrame', schemas[i])
            						   .load(ajax_argument_form, {'form_data' : '',
            							   						  'lemma_id': window.lemma_id,
				                                                  'position_arguments': JSON.stringify(positionArguments),
				                                                  'phraseologic': false})
				                       .dialog( "option", "title", "Dodawanie typu frazy:" ).dialog('open');   
            new_elem_id--; 
            return window.schemas;
          }
        }
      }
      else if(schemas[i].id == frame_id) // dodawanie pozycji do schematu
      {
        // nowa pozycja
    	// TODO wyklucznie w czestych pozycjach, poprawic!!
    	$('#add-table-elem-dialog').load(ajax_position_form, {'lemma_id': window.lemma_id,
    														  'phraseologic': schemas[i].is_phraseologic}).dialog( "option", "title", "Dodawanie pozycji:" ).dialog('open');
        new_elem_id--;    
        return window.schemas;
      }
    }
  }
  else if(user_has_perm('dictionary.add_syntactic_frames')) // dodawanie nowego pustego schematu
  { 
    window.addedFrame = $.evalJSON($.toJSON(window.emptyFrame));
    window.addedFrame.id = new_elem_id;
    form_data = new Array();
  	form_data.push({name: 'opinion', value: window.addedFrame.opinion});
  	form_data.push({name: 'characteristics', value: window.addedFrame.characteristics}); 
  	form_data.push({name: 'edit', value: false});
  	form_data.push({name: 'lemma_id', value: window.lemma_id});
    data = JSON.stringify(form_data);   
    $('#add-table-elem-dialog').load(ajax_frame_form, {'form_data': data}, function(){
        $('#aspect-relations-frames').load(ajax_aspect_rel_missing_frames, {'lemma_id': window.lemma_id,
        	                                                                'frames': JSON.stringify(window.schemas),
        	                                                                'editable': true}, 
        function() {
    		$('#aspect-rel-missing-frames tr.MissFrame td.Frame').click(function(e) {
    			e.stopPropagation();
    		    selectTableTr(this.parentNode.id);
    		});
        });
    	$('#add-frame-tabs').tabs();
    }).dialog( 'option', 'title', 'Dodawanie nowych schematów:' ).dialog('option', 'width', 500)
    														 .dialog('open');
    new_elem_id--;
    return window.schemas;
  }
  return schemas;
}

function can_add_position_category(lemma_id) {
	  can_add_category = false;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_can_add_position_category,
	    data: {lemma_id: lemma_id},
	    success: function(result) {
	    	can_add_category = result['can_add_category'];
	    },
	    async:false
	  });
	  return can_add_category;
}

function openEditForm(id) {
  if(!checkIfSemChangedAndAlert()) {
	  editedFrameInstance = getFrameInstance(id, window.schemas);
	  elemInstance = getElementInstance(id, window.schemas);
	  addSyntacticFramesPerm = user_has_perm('dictionary.add_syntactic_frames');
	  addPhraseologicFramesPerm = user_has_perm('dictionary.add_phraseologic_frames') && editedFrameInstance['element'].is_phraseologic;
	  
	  window.edited_id = id;
	  	  
	  if(elemInstance['type'] == 'frame' && (addSyntacticFramesPerm || addPhraseologicFramesPerm))
	  {
		if(gotAssignedExample(nkjp_examples, id, true).length > 0) {
			alert('Działaj rozważnie, do modyfikowanego elementu przyporządkowany jest przykład.');
		}
	    form_data = new Array();
	    form_data.push({name: 'opinion', value: elemInstance['element'].opinion});
	    form_data.push({name: 'characteristics', value: elemInstance['element'].characteristics});  
	    form_data.push({name: 'edit', value: true});
	    form_data.push({name: 'lemma_id', value: window.lemma_id});
	    data = JSON.stringify(form_data);

	    $('#add-table-elem-dialog').load(ajax_frame_form, {'form_data': data,
	    												   'phraseologic': elemInstance['element'].is_phraseologic}, function(){
	    	$('#new-frames-tabs').hide();
	    }).data('selectedFrame', editedFrameInstance['element'])
	      .dialog( 'option', 'title', 'Edycja cech schematu:' )
	      .dialog('open');
	  }
	  else if(elemInstance['type'] == 'position' && (addSyntacticFramesPerm || addPhraseologicFramesPerm) && 
			  can_add_position_category(window.lemma_id))
	  {
		if(gotAssignedExample(nkjp_examples, id, true).length > 0) {
			alert('Działaj rozważnie, do modyfikowanego elementu przyporządkowany jest przykład.');
		}
	    form_data = new Array();
	    form_data.push({name: 'categories', value: elemInstance['element'].categories});
	    form_data.push({name: 'lemma_id', value: window.lemma_id});
	    data = JSON.stringify(form_data)
	    $('#add-table-elem-dialog').load(ajax_pos_cat_form, 'form_data='+data)
	    	.data('selectedFrame', editedFrameInstance['element'])
	    	.dialog( 'option', 'title', 'Edycja funkcji pozycji:' )
	        .dialog('open'); 
	  }
	  else if(elemInstance['type'] == 'argument' && 
			  (addSyntacticFramesPerm || addPhraseologicFramesPerm))
	  {
		edited_arg_id = getArgumentId(elemInstance['element'].text_rep);
		if(gotAssignedExample(nkjp_examples, id, true).length > 0) {
			alert('Działaj rozważnie, do modyfikowanego elementu przyporządkowany jest przykład.');
		}
	    if(addSyntacticFramesPerm || 
	    		(addPhraseologicFramesPerm && arg_can_be_lexicalized(edited_arg_id))) {
	    	$('#add-table-elem-dialog')
	    		.data('selectedArgId', edited_arg_id)
	    		.data('selectedFrame', editedFrameInstance['element'])
	    		.dialog( "option", "title", "Edycja typu frazy:" )
	    		.dialog('open');
	    	arguments_form_change(-1, edited_arg_id, $('#add-table-elem-dialog'), window.lemma_id);
	    }
	  }   
  }
}

function getArgumentId(text_rep) {
	  arg_id = null;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_get_arg_id,
	    data: {text_rep: text_rep},
	    success: function(result) {
	      arg_id = result['arg_id'];
	    },
	    async:false
	  });
	  return arg_id;
}

// konwertuje przyklady do latwiej definiowalnych na bazie danych
function convertExamples(nkjp_examples)
{
    var convertedExamples = new Array();
    for(var i=0; i<nkjp_examples.length; i++)
    {
       convertedExample = convertExample(nkjp_examples[i]);
       convertedExamples.push(convertedExample); 
    }
    return convertedExamples;
}

function convertExample(nkjp_example)
{
    var argument_selections = new Array();
       
    // zbieranie listy pozycji z ktorych wybrano argumenty
    for(var j=0; j<nkjp_example.arguments_ids.length; j++)
    {       
      var ids = parseId(nkjp_example.arguments_ids[j]);
      pos_id = nkjp_example.arguments_ids[j].replace('arg_'+ids['arg_id']+'_','');
      positionInstance = getElementInstance(pos_id, schemas);
      position = positionInstance['element'];  
      newPosition = true;
         
      for(var k=0; k<argument_selections.length; k++)
      {
        if(argument_selections[k].position == position)
        {
          newPosition = false;
          break;
        }
      }
      if(newPosition)
        argument_selections.push(new Nkjp_ArgSelection(position, new Array()));
    }
       
    // przyporzadkowanie argumentow pozycjom 
    for(var j=0; j<nkjp_example.arguments_ids.length; j++)
    {         
	  for(var k=0; k<argument_selections.length; k++)
	  {
	    if(nkjp_example.arguments_ids[j].startsWith(nkjp_example.frame_id+'pos_'+argument_selections[k].position.id+'_'))
	    {
	      var argInstance = getElementInstance(nkjp_example.arguments_ids[j], schemas);
	      argument_selections[k].arguments.push(argInstance['element']);
	    }
	  }         
    }   
    frame = getElementInstance(nkjp_example.frame_id, schemas);
         
    var convertedExample = new Nkjp_example_ajax(frame['element'], argument_selections, 
    		nkjp_example.sentence, nkjp_example.source, 
    		nkjp_example.opinion, nkjp_example.comment,
    		nkjp_example.semantic, nkjp_example.lexical_unit);
       
    return convertedExample;
}

// konwertuje przyklady do latwiej definiowalnych na bazie danych
function convertLemmaExamples(lemma_examples)
{
  lemma_examples_dict_list = []
  for(var i=0; i<lemma_examples.length; i++)
  {
    example_dict = convertLemmaExample(lemma_examples[i]); 
    lemma_examples_dict_list.push(example_dict);
  }
  return lemma_examples_dict_list;
}

function convertLemmaExample(lemma_example)
{
  example_dict = {'sentence': lemma_example.sentence,
                  'source'  : lemma_example.source,
                  'comment' : lemma_example.comment,
                  'opinion' : lemma_example.opinion};                  
  return example_dict;
}

function findRelatedArguments(arg_id, frame_id, nkjp_examples)
{
  var relatedArguments = new Array();
  for(var i=0; i<window.nkjp_examples.length; i++)
  {
    if(window.nkjp_examples[i].frame_id == frame_id)
    {
      for(var j=0; j<window.nkjp_examples[i].arguments_ids.length; j++)
      {
        if(window.nkjp_examples[i].arguments_ids[j] == arg_id)
        {
          for(var k=0; k<window.nkjp_examples[i].arguments_ids.length; k++)
          {
            relatedArguments.push(window.nkjp_examples[i].arguments_ids[k])
          }
          break;
        }
      }
    }
  } 
  return relatedArguments; 
}

function clear_errors(schemas)
{
  for(var i=0; i<schemas.length; i++)
  {
	schemas[i].error = false;
    for(var j=0; j<schemas[i].positions.length; j++)
    {
      schemas[i].positions[j].error = false;
      for(var k=0; k<schemas[i].positions[j].arguments.length; k++)
    	 schemas[i].positions[j].arguments[k].error = false;
    }
  }
}


function save_new_frames() {
  if(checkIfSemChangedAndAlert()) {
	  return false;
  }
  if(notesNotSaved && !confirm("Czy jesteś pewien, że chcesz zapisać hasło? Utracone zostaną dane wpisane w formularzu tworzenia notatek.")){
      return false;
  }
  if(lemmaExNotSaved && !confirm("Czy jesteś pewien, że chcesz zapisać hasło? Utracone zostaną dane zapisane w formularzu tworzenia przykładów niedowiązanych.")){
      return false;
  }
  ShowProgressAnimation();
  $('#save').attr("disabled", true);

    data = JSON.stringify(schemas);
	var convertedExamples = convertExamples(window.nkjp_examples);
	examples_data = JSON.stringify(convertedExamples);
	
	var convertedLemmaExamples = convertLemmaExamples(window.nkjp_lemma_examples);
	lemma_examples_data = JSON.stringify(convertedLemmaExamples)

    $.ajaxJSON({
      method: 'post',
      url: ajax_save_new_frames,
      data: {
        data: data,
        id: lemma_id,
        examples: examples_data,
        lemma_examples: lemma_examples_data,
      },

    callback: function(result) {  
      $('#save').attr("disabled", false);
      change = false;    
      window.lastSelectedId = result['id'];
      grid.trigger("reloadGrid");

      data = grid.jqGrid('getGridParam', 'postData');
      data['mask'] = '';
      data['id'] = result['id'];
      window.lemma_id = result['id'];

      $.get(ajax_location, data, function(resp) {
        var selectedRow = resp['selected_id'] + "";
        var rowIndex = resp['rowIndex'];
        var recordsCount = resp['records'];
        if (recordsCount > 0 && !resp['lemma_nfound']){
         grid.jqGrid('scrollToRow', rowIndex, recordsCount);
         load_content(window.lemma_id);
        }
        else if(resp['lemma_nfound'])
        {
          load_content(window.lemma_id);
        } 
      });
      HideProgressAnimation();
    },
    bad_data_callback: function(result) {
      if (result == 'concurrent access') {
        HideProgressAnimation();
        error_alert('Hasło jest w tej chwili zapisywane przez kogoś innego.');
        $('#save').attr("disabled", false);
        return false;
      }
      else if(result == 'old version') {
    	HideProgressAnimation();
        error_alert('Nie można zapisywać zmian na nieaktualnej wersji hasła.');
        $('#save').attr("disabled", false);
        return false;
      }
      else if(result == 'user logged out') {
      	HideProgressAnimation();
      	alertUserNotAuthenticated();
        $('#save').attr("disabled", false);
        return false;
      }
      else {
        $('#save').attr("disabled", false);
        HideProgressAnimation();
        return true;
      }        
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      $('#save').attr("disabled", false);
    },
  });
  return false;
}

function changeFrameExamplesIds(nkjp_examples, frame_id, new_frame_id)
{
  var frame_tabId = 'frame_'+frame_id+'_';
  var new_frame_tabId = 'frame_'+new_frame_id+'_';
  
  for(var i=0; i<nkjp_examples.length; i++)
  {
    if(nkjp_examples[i].frame_id == frame_tabId)
    {
      nkjp_examples[i].frame_id = new_frame_tabId;
      for(var j=0; j<nkjp_examples[i].arguments_ids.length; j++)
      {
        nkjp_examples[i].arguments_ids[j] = nkjp_examples[i].arguments_ids[j].replace(frame_tabId, new_frame_tabId);
      }
    }
  }   
}

function getActualLemmaId(chosenId) {
  var actualId = chosenId;
  jQuery.ajax({
	type: 'get',
    url: ajax_get_actual_lemma_id,
    data: {chosen_id: chosenId},
    success: function(result) {
    	actualId = result['actual_id'];
    },
    async: false
  });
  return actualId;
}

function userIsAuthenticated() {
	  var authenticated = false;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_user_is_authenticated,
	    success: function(result) {
	    	authenticated = result['authenticated'];
	    },
	    async: false
	  });
	  return authenticated;
	}

function changePosExamplesIds(nkjp_examples, frame_id, old_pos_id, new_pos_id)
{
  var frame_tabId = 'frame_'+frame_id+'_';
  var new_pos_tabId = 'pos_'+new_pos_id+'_';
  var old_pos_tabId = 'pos_'+old_pos_id+'_';
  
  for(var i=0; i<nkjp_examples.length; i++)
  {
    if(nkjp_examples[i].frame_id == frame_tabId)
    {
      for(var j=0; j<nkjp_examples[i].arguments_ids.length; j++)
      {
        nkjp_examples[i].arguments_ids[j] = nkjp_examples[i].arguments_ids[j].replace(old_pos_tabId, new_pos_tabId);
      }
    }
  }   
}

function frame_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);
	base_frame = null;
    form_data = this_form.serializeArray();
    var selected_examples = [];
    var propose_phraseology = null;
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'aspect' && elem.name != 'frame_opinion' && 
         elem.name != 'reflex' && elem.name != 'predicativity' &&
         elem.name != 'propose_skladnica' && elem.name != 'propose_B' &&
         elem.name != 'negativity' && elem.name != 'base_frame' && 
         elem.name != 'propose_phraseology')
        return elem;
      else {
        if (elem.name == 'aspect')
          aspect = elem.value;
        else if (elem.name == 'reflex')
          reflex = elem.value;
        else if (elem.name == 'negativity')
        	negativity = elem.value;
        else if (elem.name == 'predicativity')
        	predicativity = elem.value;
        else if (elem.name == 'frame_opinion')
          frame_opinion = elem.value;
        else if (elem.name == 'base_frame')
        	base_frame = elem.value; 
        else if (elem.name == 'propose_skladnica')
            propose_skladnica = elem.value;
        else if (elem.name == 'propose_B')
            propose_B = elem.value;
        else if (elem.name == 'propose_phraseology')
        	propose_phraseology = elem.value;
      }
    });
    
    if(window.addedFrame) {
      frame = JSON.stringify(window.addedFrame);
    }
    else if(propose_phraseology) {
    	frame = '';
    }
    else {
    	  elemInstance = getElementInstance(window.edited_id, schemas);
    	  frame = JSON.stringify(elemInstance['element']);	  
    }
    if (typeof(frame) == "undefined") {
    	frame = '';
    }

	form_data.push({name: 'aspect', value: aspect});
	form_data.push({name: 'reflex', value: reflex});
	form_data.push({name: 'negativity', value: negativity});
	form_data.push({name: 'predicativity', value: predicativity});
    form_data.push({name: 'opinion', value: frame_opinion});
    form_data.push({name: 'frame_str', value: frame});
    form_data.push({name: 'lemma_id', value: lemma_id});
    form_data.push({name: 'base_frame', value: base_frame});
    form_data.push({name: 'propose_skladnica', value: propose_skladnica});
    form_data.push({name: 'propose_B', value: propose_B});
    if(propose_phraseology != null)
    	form_data.push({name: 'propose_phraseology', value: propose_phraseology});
    
    $('#example-propositions tr').filter(function(){
        var color = $(this).css("background-color").toLowerCase();
        if(color === window.selectedColor)
        	selected_examples.push($(this).attr('id'));
    });

    selected_realization = $('#realization-select').val();
    if(!selected_realization)
    	selected_realization = '';
    form_data.push({name: 'frame_realization', value: selected_realization});
    form_data.push({name: 'selected_examples', value: selected_examples});
    
    $.ajaxJSON({
      method: 'post',
      url: ajax_frame_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {  
      edited_frame_id = null;
      old_edited_frame_id =  '';
      if(window.addedFrame) {
        edited_frame = $.evalJSON($.toJSON(window.addedFrame));
        edited_frame = serializedObjToObj(result['frame']);
        edited_frame.id = window.addedFrame.id;
        edited_frame.text_rep = result['text_rep'];
        edited_frame.characteristics = result['characteristics'];
        edited_frame.opinion = result['opinion'];
        edited_frame.is_phraseologic = result['phraseologic'];
        edited_frame_id = window.addedFrame.id;
        
        examples = serializedNkjpToObj(result['examples']);
        if(examples.length > 0)
        {
            for(var i = 0; i<examples.length; i++)
            {
            	examples[i].example_id = window.curr_example_id;
            	window.curr_example_id--;
            	window.nkjp_examples.push(examples[i]);
            }
        }
        window.schemas.push(edited_frame);
        changeFrameExamplesIds(window.nkjp_examples, result['id'], window.addedFrame.id);
      }
      else if(result['phraseologic']) {
          edited_frame = serializedObjToObj(result['frame']);
          edited_frame.id = new_elem_id;
          new_elem_id--;
          edited_frame.text_rep = result['text_rep'];
          edited_frame.characteristics = result['characteristics'];
          edited_frame.opinion = result['opinion'];
          edited_frame.is_phraseologic = result['phraseologic'];
          edited_frame_id = edited_frame.id;
          window.schemas.push(edited_frame);
      }
      else {
        edited_frame = getElementInstance(edited_id, schemas);
        var old_edited_frame_id = edited_frame['element'].id;
        edited_frame['element'].id = new_elem_id; //tutaj zmienilem
        //edited_frame['element'].id = result['id'];
        edited_frame_id = edited_frame['element'].id;
        new_elem_id--;
        edited_frame['element'].text_rep = result['text_rep'];
        edited_frame['element'].characteristics = result['characteristics'];
        edited_frame['element'].opinion = result['opinion'];
        changeFrameExamplesIds(window.nkjp_examples, old_edited_frame_id, edited_frame['element'].id);
      }      
      
      $('#add-table-elem-dialog').dialog('close');
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);   
      goToFrame('frame_'+edited_frame_id+'_', document.getElementById('new-frame-tables'));
       
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      change = true;	
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'empty fields error') {
        HideProgressAnimation();
        error_alert('Wypełnij wszystkie niezbędne pola formularza.');
        return false;
      }
      else if (result == 'data error') {
          HideProgressAnimation();
          error_alert('Brakuje danych do stworzenia schematu.');
          return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function add_aspect_rel_frames() {
    ShowProgressAnimation();
    var selected_frames = [];
    
    $('#aspect-rel-missing-frames tr').filter(function(){
        var color = $(this).css("background-color").toLowerCase();
        if(color === window.selectedColor)
        	selected_frames.push({'frame'  : $(this).attr('id'),
        		                  'aspect' : $(this).find('#id_aspect').val(),
        		                  'opinion': $(this).find('#id_opinion').val()});
    });
    form_data.push({name: 'lemma_id', value: window.lemma_id});
    form_data.push({name: 'selected_frames', value: selected_frames});
    
    $.ajaxJSON({
      method: 'post',
      url: ajax_add_new_frames,
      data: {
        form_data: form_data
      },

    callback: function(result) {   
    	if(result['new_frames'].length > 0)
    	{
    		new_frames = serializedObjToObj(result['new_frames']);
    		for(var i = 0; i<result['new_frames'].length; i++)
    	    {
    			new_frame = serializedObjToObj(result['new_frames'][i]);
    			new_frame.id = window.new_elem_id;
    			window.schemas.push(new_frame);
    	        window.new_elem_id--;
    	    }
          
    		$('#add-table-elem-dialog').dialog('close'); 
    		draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);   
    		   
    		frames_modif = frames_modif.slice(0, frames_modif_idx+1);
    		var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
    		frames_modif.push(lemma_version);
    		frames_modif_idx++;
    		change = true;	
    	}
		HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
  });
  return false;
}

function pos_cat_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);
    form_data = this_form.serializeArray();
    var control = new Array(); 
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'category' && elem.name != 'control')
        return elem;
      else {
        if (elem.name == 'category')
          category = elem.value;
        else if (elem.name == 'control')
          control.push(elem.value);
      }
    });
    
	elemInstance = getElementInstance(window.edited_id, schemas);
    position = JSON.stringify(elemInstance['element']);

	form_data.push({name: 'category', value: category});
    form_data.push({name: 'control', value: control});
    form_data.push({name: 'position_str', value: position});

    $.ajaxJSON({
      method: 'post',
      url: ajax_pos_cat_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {      
      edited_pos = getElementInstance(edited_id, schemas);
      var edited_old_pos_id = edited_pos['element'].id    
      var frame_id = parseId(edited_id)['frame_id'];    

      edited_pos['element'].id = result['id'];
      edited_pos['element'].text_rep = result['text_rep'];
      edited_pos['element'].categories = result['categories'];
      changePosExamplesIds(window.nkjp_examples, frame_id, edited_old_pos_id, result['id']);    
      
      $('#add-table-elem-dialog').dialog('close'); 
      
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      change = true;	
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      HideProgressAnimation();
      return true;
    },
  });
  return false;
}
//////////////////////////////// lemma notes //////////////////////////////

function lemma_notes_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);	
    form_data = this_form.serializeArray();
    private_flag = false;
    var is_ready_note = false; 
  
    form_data = $.map(form_data, function(elem)
    { 
      if (elem.name != 'topic' && elem.name != 'message_text' &&
         elem.name != 'private')
        return elem;
      else {
        if (elem.name == 'topic')
          topic = elem.value;
        else if (elem.name == 'message_text')
          message_text = elem.value;
        else if (elem.name == 'private')
          private_flag = true;
      }
    });
    
    if(this.id == "ready-note-form") {
      private_flag = false;
      is_ready_note = true;
    }
    
	form_data.push({name: 'topic', value: topic});
    form_data.push({name: 'message_text', value: message_text});
    form_data.push({name: 'private', value: private_flag});
    form_data.push({name: 'lemma_id', value: window.lemma_id});
    form_data.push({name: 'is_ready_note', value: is_ready_note});

    $.ajaxJSON({
      method: 'post',
      url: ajax_lemma_notes_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {      
    	$('#ready-note-dialog').dialog('close');
        $('#notes').load(ajax_lemma_notes, 'id='+result['id']);
        window.notesNotSaved = false;
        HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Należy wypełnić temat oraz treść wiadomości.');
        return false;
      } 
      else if (result == 'initial status') {
          HideProgressAnimation();
          error_alert('Nie rozpoczęto jeszcze obróbki wybranego hasła.');
          return false;
        } 
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function selectNotesTr(id)
{  	  
  	if(selected_notes_row_id != -1)
  	{
  	  var recent_row = document.getElementById(selected_notes_row_id);
  	  var recent_descendants = getDescendantsNodes(recent_row);
  	  for(var i = 0; i<recent_descendants.length; i++)
  	    $(recent_descendants[i]).css("background-color", "");
  	}
  	
  	if(selected_notes_row_id == id)
  	{
  	  selected_notes_row_id = -1;
  	  resetForm($('.lemma-notes-form'));
    }  	
  	else
  	{
  	  ShowProgressAnimation();
  	  selected_notes_row_id = id;
  	  var row = document.getElementById(id);
  	  var descendants = getDescendantsNodes(row);
  	  for(var i = 0; i<descendants.length; i++)
  	    $(descendants[i]).css("background-color", "LightSteelBlue");
  	  message_id = id.replace('note_', '');
  	  
  	  $.ajaxJSON({
        method: 'post',
        url: ajax_get_lemma_note,
        data: {
              message_id: message_id, 
        },
        callback: function(result) {
          if(result['private'])
		    $('.lemma-notes-form #id_private').attr('checked', true);
		  else
		    $('.lemma-notes-form #id_private').attr('checked', false);
		  $('.lemma-notes-form #id_message_text').val(result['message_text']);
          $('.lemma-notes-form #id_topic').val(result['topic']);
          $('.lemma-notes-form #id_message_text').width($('#notes').width())
          
          HideProgressAnimation();	
        },
    
        error_callback: function(xhr, status, error) {
          HideProgressAnimation();
          error_alert(status + ': ' + error);
        },
        
        bad_data_callback: function(result) {
            if (result == 'already removed') {
                HideProgressAnimation();
                error_alert('Notatka została usunięta, odśwież widok.');
                return false;
            }
            else {
              HideProgressAnimation();
              return true;
            }
        },
      }); 
  	}
}

////////////////////////////////// lemma notes end /////////////////////////

function nkjp_lemma_example_form_submit() {
	if(checkIfSemChangedAndAlert()) {
		return false;
	}
	
    ShowProgressAnimation();
	this_form = $(this);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'sentence' && elem.name != 'source' && elem.name != 'opinion'
       && elem.name != 'comment')
        return elem;
      else {
        if (elem.name == 'sentence')
          sentence = elem.value;
        else if (elem.name == 'source')
          source = elem.value;
        else if (elem.name == 'opinion')
          opinion = elem.value;
        else if (elem.name == 'comment')
          comment = elem.value;
      }
    });

	form_data.push({name: 'sentence', value: sentence});
    form_data.push({name: 'source', value: source});
    form_data.push({name: 'opinion', value: opinion});
    form_data.push({name: 'comment', value: comment});

    $.ajaxJSON({
      method: 'post',
      url: ajax_nkjp_example_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {     
      var nkjp_example = new Nkjp_example(window.curr_lemma_example_id, '', '',
                            result['sentence'], result['source'], result['opinion'], result['comment'],
                            false);
      window.nkjp_lemma_examples.push(nkjp_example);
      window.curr_lemma_example_id--;
      
      window.frames_modif = window.frames_modif.slice(0, frames_modif_idx+1);     
      var lemma_version = new Lemma_Version(window.schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++; 
      
      draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
      $("tr.NkjpLemmaTableRow").click(function(){
        selectLemmaNkjpTr(this.id)});
      resetForm(this_form);
      change = true;	
      window.lemmaExNotSaved = false;
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Wszystkie pola poza komentarzem są wymagane.');
        return false;
      }
      else if (result == 'comment required') {
        HideProgressAnimation();
        error_alert('Wybrane źródło wymaga dodatkowych informacji.');
        return false;
      }   
      else
      {
        HideProgressAnimation();
        return true;
      }      
    },
  });
  return false;
}

/////////////////////// CZASOWNIKI PODOBNE ////////////////////////

function similar_lemmas_old_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'compatibility')
        return elem;
      else {
        if (elem.name == 'compatibility')
          compatibility = elem.value;
      }
    });

	form_data.push({name: 'compatibility', value: compatibility});
	form_data.push({name: 'lemma_id', value: window.lemma_id});

    $.ajaxJSON({
      method: 'post',
      url: ajax_similar_lemmas_old_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {      
      grid.trigger("reloadGrid");
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'main lemma not selected') {
        HideProgressAnimation();
        error_alert('Zaznacz hasło w zakładce "Schematy".');
        return false;
      }
      else if (result == 'compatibility not selected') {
        HideProgressAnimation();
        error_alert('Nie określono skali zgodności.');
        return false;
      }
      else if (result == 'compatibility not digit') {
        HideProgressAnimation();
        error_alert('Podobieństwo należy określić jako liczbę od 1 do 100.');
        return false;
      }
      else if (result == 'wrong compatibility range') {
        HideProgressAnimation();
        error_alert('Podobieństwo może przyjąć wartości od 1% do 100%.');
        return false;
      }
      else if (result == 'similar lemmas not found') {
        HideProgressAnimation();
        error_alert('Nie odnaleziono haseł spełniających podane kryteria.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function similar_lemmas_new_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'compatibility' && elem.name != 'status')
        return elem;
      else {
        if (elem.name == 'compatibility')
          compatibility = elem.value;
        else if (elem.name == 'status')
          status = elem.value;
      }
    });

	form_data.push({name: 'compatibility', value: compatibility});
	form_data.push({name: 'status', value: status});
	form_data.push({name: 'lemma_id', value: window.lemma_id});

    $.ajaxJSON({
      method: 'post',
      url: ajax_similar_lemmas_new_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {      
      grid.trigger("reloadGrid");
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'main lemma not selected') {
        HideProgressAnimation();
        error_alert('Zaznacz hasło w zakładce "Schematy".');
        return false;
      }
      else if (result == 'compatibility not selected') {
        HideProgressAnimation();
        error_alert('Nie określono skali zgodności.');
        return false;
      }
      else if (result == 'status not selected') {
        HideProgressAnimation();
        error_alert('Nie określono minimalnego statusu haseł.');
        return false;
      }
      else if (result == 'wrong compatibility range') {
        HideProgressAnimation();
        error_alert('Kompatybilność może przyjąć wartości od 1% do 100%.');
        return false;
      }
      else if (result == 'compatibility not digit') {
        HideProgressAnimation();
        error_alert('Kompatybilność należy określić jako liczbę od 1 do 100.');
        return false;
      }
      else if (result == 'similar lemmas not found') {
        HideProgressAnimation();
        error_alert('Nie odnaleziono haseł spełniających podane kryteria.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function similar_lemmas_show_synonyms() {
    ShowProgressAnimation();

    $.ajaxJSON({
      method: 'post',
      url: ajax_similar_lemmas_show_synonyms,
      data: {
        lemma_id: window.lemma_id
      },

    callback: function(result) {      
      grid.trigger("reloadGrid");
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'main lemma not selected') {
        HideProgressAnimation();
        error_alert('Zaznacz hasło w zakładce "Schematy".');
        return false;
      }
      else if (result == 'similar lemmas not found') {
        HideProgressAnimation();
        error_alert('Nie odnaleziono haseł podobnych znaczeniowo.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function related_lemmas_show() {
    ShowProgressAnimation();

    $.ajaxJSON({
      method: 'post',
      url: ajax_related_lemmas_show,
      data: {
        lemma_id: window.lemma_id
      },

    callback: function(result) {      
      grid.trigger("reloadGrid");
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'main lemma not selected') {
        HideProgressAnimation();
        error_alert('Zaznacz hasło w zakładce "Schematy".');
        return false;
      }
      else if (result == 'related lemmas not found') {
        HideProgressAnimation();
        error_alert('Nie odnaleziono powiązanych haseł.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function similar_lemmas_reset() {
          ShowProgressAnimation();
  	      $.ajaxJSON({
            method: 'post',
            url: ajax_similar_lemmas_reset,
            data: {
            },
            callback: function(result) {
              grid.trigger("reloadGrid");
              HideProgressAnimation();	
            },
            error_callback: function(xhr, status, error) {
              HideProgressAnimation();
              error_alert(status + ': ' + error);
            },
          });
      return false;
}

/////////////////////////////////////////////////////

function nkjp_example_form_submit() {
	if(checkIfSemChangedAndAlert()) {
		return false;
	}
    ShowProgressAnimation();
	if(window.selectedArgumentsIdNkjp.length == 0)
	{
	  HideProgressAnimation();
	  error_alert('Wybierz przynajmniej jeden typ frazy, aby dodać przykład.');
	  return  false;
	}
	if(!canModifyFrame(window.selectedFrameIdNkjp, window.schemas)) {
		HideProgressAnimation();
		error_alert('Nie można dodawać przykładów do wybranego schematu.');
		return  false;
	}
	this_form = $(this);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'sentence' && elem.name != 'source' && elem.name != 'opinion'
       && elem.name != 'comment')
        return elem;
      else {
        if (elem.name == 'sentence')
          sentence = elem.value;
        else if (elem.name == 'source')
          source = elem.value;
        else if (elem.name == 'opinion')
          opinion = elem.value;
        else if (elem.name == 'comment')
          comment = elem.value;
      }
    });

	form_data.push({name: 'sentence', value: sentence});
    form_data.push({name: 'source', value: source});
    form_data.push({name: 'opinion', value: opinion});
    form_data.push({name: 'comment', value: comment});

    $.ajaxJSON({
      method: 'post',
      url: ajax_nkjp_example_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) { 
      if(window.selected_example_id != -1)
      {
        for(var i=0; i<window.nkjp_examples.length; i++)
        {
          example_tabId = 'nkjp_'+window.nkjp_examples[i].example_id
          if(example_tabId==window.selected_example_id)
          {
            window.nkjp_examples[i].frame_id = window.selectedFrameIdNkjp;
            window.nkjp_examples[i].arguments_ids = window.selectedArgumentsIdNkjp;
            window.nkjp_examples[i].sentence = result['sentence'];
            window.nkjp_examples[i].source = result['source'];
            window.nkjp_examples[i].opinion = result['opinion'];
            window.nkjp_examples[i].comment = result['comment'];
            window.nkjp_examples[i].example_id = window.curr_example_id;
            window.curr_example_id--;
            $('.new_frame_tabs').tabs('select', 2);
            break;
          }
        }
      }
      else if(window.selected_lemma_example_id != -1)
      {
        for(var i=0; i<window.nkjp_lemma_examples.length; i++)
        {
          example_tabId = 'nkjpLemma_'+window.nkjp_lemma_examples[i].example_id
          if(example_tabId==window.selected_lemma_example_id)
          {
            window.nkjp_lemma_examples.splice(i, 1);
            window.selected_lemma_example_id = -1;
            draw_nkjp_table(document.getElementById("lemma_example_show"), '', nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_')
            $("tr.NkjpLemmaTableRow").click(function(){
              selectLemmaNkjpTr(this.id)});
            break;
          }
        }
        var nkjp_example = new Nkjp_example(window.curr_example_id, window.selectedFrameIdNkjp, window.selectedArgumentsIdNkjp,
                            result['sentence'], result['source'], result['opinion'], result['comment'], false); 
        window.nkjp_examples.push(nkjp_example);
        window.curr_example_id--;
      }
      else
      {       
        var nkjp_example = new Nkjp_example(window.curr_example_id, window.selectedFrameIdNkjp, window.selectedArgumentsIdNkjp,
                            result['sentence'], result['source'], result['opinion'], result['comment'], false); 
        window.nkjp_examples.push(nkjp_example);
        window.curr_example_id--;
      }
      
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
      window.selectedArgumentsIdNkjp = new Array();
      window.selectedFrameIdNkjp = -1;
      
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);     
      var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      
      resetForm(this_form);
      change = true;
      HideProgressAnimation();	
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Wszystkie pola poza komentarzem są wymagane.');
        return false;
      }
      else if (result == 'comment required') {
        HideProgressAnimation();
        error_alert('Wybrane źródło wymaga dodatkowych informacji.');
        return false;
      }  
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function semantic_example_form_submit() {
    ShowProgressAnimation();
	if(window.selectedArgumentsIdNkjp.length == 0)
	{
	  HideProgressAnimation();
	  error_alert('Wybierz przynajmniej jeden typ frazy, aby dodać przykład.');
	  return false;
	}
	this_form = $(this);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'sentence' && elem.name != 'source' && elem.name != 'opinion'
       && elem.name != 'comment')
        return elem;
      else {
        if (elem.name == 'sentence')
          sentence = elem.value;
        else if (elem.name == 'source')
          source = elem.value;
        else if (elem.name == 'opinion')
          opinion = elem.value;
        else if (elem.name == 'comment')
          comment = elem.value;
      }
    });
    
    var convertedArgSelections = convertArgumentSelections(window.selectedFrameIdNkjp, 
    		window.selectedArgumentsIdNkjp)
	form_data.push({name: 'sentence', value: sentence});
    form_data.push({name: 'source', value: source});
    form_data.push({name: 'opinion', value: opinion});
    form_data.push({name: 'comment', value: comment});
    form_data.push({name: 'lemma', value: window.lemma_id});
    form_data.push({name: 'frame', value: parseId(window.selectedFrameIdNkjp)['frame_id']});
    form_data.push({name: 'arg_selections', value: JSON.stringify(convertedArgSelections)});

    $.ajaxJSON({
      method: 'post',
      url: ajax_semantic_example_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(example) {       
      var nkjp_example = new Nkjp_example(example['id'], window.selectedFrameIdNkjp, window.selectedArgumentsIdNkjp,
    		  example['sentence'], example['source'], example['opinion'], example['comment'], true); 
      window.nkjp_examples.push(nkjp_example);
      
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
      window.selectedArgumentsIdNkjp = new Array();
      window.selectedFrameIdNkjp = -1;
      
      resetForm(this_form);
      HideProgressAnimation();	
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Wszystkie pola poza komentarzem są wymagane.');
        return false;
      }
      else if (result == 'comment required') {
        HideProgressAnimation();
        error_alert('Wybrane źródło wymaga dodatkowych informacji.');
        return false;
      }  
      else if (result == 'old lemma') {
          HideProgressAnimation();
          error_alert('Odśwież hasło, widoczna wersja nie jest aktualna.');
          return false;
        } 
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function convertArgumentSelections(frameTabId, argumentSelections) {
    var argument_selections = new Array();
    
    // zbieranie listy pozycji z ktorych wybrano argumenty
    for(var j=0; j<argumentSelections.length; j++)
    {       
      var ids = parseId(argumentSelections[j]);
      pos_id = argumentSelections[j].replace('arg_'+ids['arg_id']+'_','');
      positionInstance = getElementInstance(pos_id, schemas);
      position = positionInstance['element'];  
      newPosition = true;
         
      for(var k=0; k<argument_selections.length; k++)
      {
        if(argument_selections[k].position == position)
        {
          newPosition = false;
          break;
        }
      }
      if(newPosition)
        argument_selections.push(new Nkjp_ArgSelection(position, new Array()));
    }
       
    // przyporzadkowanie argumentow pozycjom 
    for(var j=0; j<argumentSelections.length; j++)
    {         
	  for(var k=0; k<argument_selections.length; k++)
	  {
	    if(argumentSelections[j].startsWith(frameTabId+'pos_'+argument_selections[k].position.id+'_'))
	    {
	      var argInstance = getElementInstance(argumentSelections[j], schemas);
	      argument_selections[k].arguments.push(argInstance['element']);
	    }
	  }         
    }
    return argument_selections;
}

 function serializedObjToObj(serialized_frames)
 {
    var serFrames = eval('(' + serialized_frames + ')');
    return serFrames;
 }
 
 function serializedNkjpToObj(serialized_nkjp_examples)
 {
    var serNkjpExamples = eval('(' + serialized_nkjp_examples + ')'); 
    return serNkjpExamples;
 }
 
///////////////////////////////////////////////////////////////////////////////////////////////
  function getMatchingElements(parent, id)
  {
    var elements = getDescendantsNodes(parent);
    var matching_elements = new Array();
    
  // declare our regex
    var re = new RegExp("^("+id+").*");
  // loop through the form elements
    for(i = 0; i < elements.length; i++)
    {
  // execute our regular expression against each element id
      var m = re.test(elements[i].id);
      if (m && id) 
        matching_elements.push(elements[i]);
    }
    return matching_elements;
  }
  
function removeFrameElement(id, schemas)
{
    if(id != -1 && id.startsWith('frame'))
    { 
      var ids = parseId(id);
      var frame_id = ids['frame_id'];
      var pos_id = ids['pos_id'];
      var arg_id = ids['arg_id'];
    
      for(var i=0; i<schemas.length; i++)
      {
        if(schemas[i].id == frame_id && pos_id)
        {
          for(var j=0; j<schemas[i].positions.length; j++)
          {
            if(schemas[i].positions[j].id == pos_id && arg_id)
            {
          	  for(var k=0; k<schemas[i].positions[j].arguments.length; k++)
          	  {
          	    if(schemas[i].positions[j].arguments[k].id == arg_id)
          	    {
          	      schemas[i].positions[j].arguments.splice(k, 1);
          	      if(schemas[i].positions[j].arguments.length == 0)
          	      {
          	        break;
          	      }
          	    }
          	  }
            }
            else if(schemas[i].positions[j].id == pos_id)
              schemas[i].positions.splice(j, 1);
          }
        }
        else if(schemas[i].id == frame_id)
        {
        	schemas.splice(i, 1); // takie usuwanie nie zostawia dziury w tabeli  
        }
      }
      selected_id = -1;
    }
    return schemas;
}

function addFramePosition(id, schemas, position)
{    
    if(id!=-1 && id.startsWith('frame'))
    {
      var ids = parseId(id);
      var frame_id = ids['frame_id'];
      var pos_id = ids['pos_id'];
      var arg_id = ids['arg_id'];
      
      for(var i=0; i<schemas.length; i++)
      {
        if(schemas[i].id == frame_id && pos_id)
        {
		  return schemas;
        }
        else if(schemas[i].id == frame_id) // dodawanie pozycji do schematu
        {
        // nowa pozycja
        	schemas[i].positions.push(position); 
        }
      }
    }
    return schemas;
}

function removeDescElements(parent)
{
  if(parent.hasChildNodes())
  {
    while (parent.childNodes.length >= 1)
      parent.removeChild(parent.firstChild);       
  }
}

function refresh_example_propositions()
{
	frame_json = '';
	argument_ids = '';
	if (window.selectedFrameIdNkjp != -1) {
		frame_id = window.selectedFrameIdNkjp.split('_')[1];
		frame = ''
		for(var i=0; i<window.schemas.length; i++)
		{
			if(window.schemas[i].id == frame_id)
			{
				frame = window.schemas[i];
				break;
			}
		}
		frame_json = encodeURIComponent(JSON.stringify(frame));
		argument_ids = JSON.stringify(window.selectedArgumentsIdNkjp);
	}
	$('#skladnica-example-propositions-select').empty();
	$('#skladnica-example-propositions-select').load(ajax_skladnica_example_propositions, 
			'frame='+frame_json+'&argument_ids='+argument_ids+'&lemma_id='+window.lemma_id);
	$('#xcp-example-propositions-select').empty();
	$('#xcp-example-propositions-select').load(ajax_xcp_example_propositions, 
			'frame='+frame_json+'&argument_ids='+argument_ids+'&lemma_id='+window.lemma_id);
}

function selectTd(id)
{     
  	var parent = document.getElementById("new-frame-tables");
  	var recent_sel_elements = new Array();

  	if(window.copy_elem_id != -1)
  	{
  	   var copied_elements = getMatchingElements(parent, window.copy_elem_id);
	   for(var i=0; i<copied_elements.length; i++)
         $(copied_elements[i]).css("background-color", "");
       window.copy_elem_id = -1;
  	}
  	
   if(window.activeNewFramePanel == 'frames_modif')
   {
  	  if(selected_id != -1)
  	  {
  	    recent_sel_elements = getMatchingElements(parent, selected_id);
  	    for(var i=0; i<recent_sel_elements.length; i++)
		  $(recent_sel_elements[i]).css("background-color", "");
  	  }
  	
  	  if(selected_id == id)
  	    selected_id = -1;
  	  else
  	  {
  	    selected_id = id;
  	    var matching_elements = getMatchingElements(parent, id);
	    for(var i=0; i<matching_elements.length; i++)
          $(matching_elements[i]).css("background-color", "LightSteelBlue");
  	  }
  	}
  	else if(window.activeNewFramePanel == 'show_nkjp_example')
  	{
  	  elementInstance = getElementInstance(id, schemas);
  	  if(elementInstance['type'] == 'frame')
  	  {
  	    window.selected_example_id = -1;
  	    if(id != window.selectedFrameIdNkjp)
  	    {
  	      unselectTd(window.selectedFrameIdNkjp);
  	      $("button#confirm_example").css("visibility","hidden"); 
  	    }
  	      
  	    window.selectedFrameIdNkjp = id;
  	    var parent = document.getElementById("new-frame-tables");
  	    var matching_elements = getMatchingElements(parent, id);
	    for(var i=0; i<matching_elements.length; i++)
          $(matching_elements[i]).css("background-color", "LightSteelBlue");
          
        var table_container = document.getElementById("show_nkjp_table");
        draw_nkjp_table(table_container, id, nkjp_examples, 'NkjpTableRow', 'nkjp_');
        $("tr.NkjpTableRow").click(function(){
          selectNkjpTr(this.id)});
  	  }
  	}  	
  	else if(window.activeNewFramePanel == 'add_nkjp_example')
  	{
  	  elementInstance = getElementInstance(id, schemas);
  	  if(elementInstance['type'] == 'argument')
  	  {
  	    if(selectedFrameIdNkjp == -1)
  	    {
  	      selectedFrameIdNkjp = 'frame_'+parseId(id)['frame_id']+'_';
  	    }
  	    else
  	    {
  	    // jesli chcemy zaznaczyc argument w innej ramce
  	      if(!id.startsWith(selectedFrameIdNkjp))
  	      {
  	        unselectTd(selectedFrameIdNkjp)
  	        window.selectedArgumentsIdNkjp = new Array();
  	        selectedFrameIdNkjp = 'frame_'+parseId(id)['frame_id']+'_';
  	      }
  	      argElem = document.getElementById(id);
  	      
  	      alreadySelected = false;
  	      for(var i=0; i<window.selectedArgumentsIdNkjp.length; i++)
  	      {
  	        if(window.selectedArgumentsIdNkjp[i]==id)
  	        {
  	          window.selectedArgumentsIdNkjp.splice(i, 1);
  	          $(argElem).css("background-color", "");
  	          alreadySelected = true;
  	          break;
  	        }
  	      }
  	      if(!alreadySelected)
  	      {
  	        $(argElem).css("background-color", "LightSteelBlue");
  	        window.selectedArgumentsIdNkjp.push(id);
  	      }
  	    }
  	    refresh_example_propositions();
  	  }
  	}
}

function unselectTd(id)
{ 
  	var parent = document.getElementById("new-frame-tables");
  	var recent_sel_elements = getMatchingElements(parent, id);
  	for(var i=0; i<recent_sel_elements.length; i++)
	  $(recent_sel_elements[i]).css("background-color", "");
}

function parseId(id)
{
    var pattern = /(frame_)(-?\d+)_(pos_)?(-?\d*)_?(arg_)?(-?\d*)_?/
    var match = id.match(pattern);
    return {'frame_id': match[2],
            'pos_id': match[4],
            'arg_id': match[6]}
}
  
function getElementInstance(id, schemas)
{
    if(id != -1 && id.startsWith('frame'))
    {
      var ids = parseId(id);
      var frame_id = ids['frame_id'];
      var pos_id = ids['pos_id'];
      var arg_id = ids['arg_id'];
    
      for(var i=0; i<schemas.length; i++)
      {
        if(schemas[i].id == frame_id && pos_id)
        {
          for(var j=0; j<schemas[i].positions.length; j++)
          {
            if(schemas[i].positions[j].id == pos_id && arg_id)
            {
          	  for(var k=0; k<schemas[i].positions[j].arguments.length; k++)
          	  {
          	    if(schemas[i].positions[j].arguments[k].id == arg_id)
          	    {
          	      return {'element': schemas[i].positions[j].arguments[k],
          	               'type': 'argument'};
          	    }
          	  }
            }
            else if(schemas[i].positions[j].id == pos_id)
            { // position
              return {'element': schemas[i].positions[j],
          	           'type': 'position'};
            }
          }
        }
        else if(schemas[i].id == frame_id)
        { // frame
          return {'element': schemas[i],
          	       'type': 'frame'};
        }
      }
      selected_id=-1;
    }
    return {};
}

/////////////////////// filtering frames /////////////////////

function escape_regex(str)
{
	return str.split('(').join('\\(').
			split(')').join('\\)').
			split('[').join('\\[').
			split(']').join('\\]').
			split('{').join('\\{').
			split('}').join('\\}')
}

function draw_filtered_frames(schemas, parent_id, table_id, filter_id, nkjp_examples, table_class, lemma_entry)
{
  var parent = document.getElementById(parent_id);
  filtered_frames = schemas;
  if(filter_id)
    filtered_frames = filter_frames(schemas, filter_id);
  draw_frames(filtered_frames, parent, table_id, nkjp_examples, table_class, lemma_entry);
}

////////////////////////////////////////////////////

function validate_and_change_status()
{
  if(window.change || semanticsChanged()) {
	  error_alert('Przed zmianą statusu hasło musi zostać zapisane.');
	  return false;
  }

  status_id = this.id;
  $.ajaxJSON({
    method: 'post',
    url: ajax_status_need_validation,
    data: {
      status_id: status_id,
      lemma_id: lemma_id
    },
    callback: function(result) {
      if(result['need_validation']) {
    	  if(semanticsValid(status_id)) {
    		  validate_new_frames(status_id, true);
    	  }
      }
      else {
    	  lemma_status_change(status_id);
      }
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
    },
  });
  return false;
}


function lemma_status_change(status_id) {
  if(window.change || semanticsChanged()) {
	error_alert('Przed zmianą statusu hasło musi zostać zapisane.');
	return false;
  }
  if(!confirm("Czy jesteś pewien, że chcesz zmienić status hasła?")){
	return false;
  }
  if(notesNotSaved && !confirm("Czy jesteś pewien, że chcesz zmienić status hasła? Utracone zostaną dane wpisane w formularzu tworzenia notatek.")){
    return false;
  }
  if(lemmaExNotSaved && !confirm("Czy jesteś pewien, że chcesz zmienić status hasła? Utracone zostaną dane zapisane w formularzu tworzenia przykładów niedowiązanych.")){
	return false;
  }
  ShowProgressAnimation();

  $.ajaxJSON({
    method: 'post',
    url: ajax_lemma_status_change,
    data: {
      status_id: status_id, 
      lemma_id: lemma_id    // obecnie ustawione haslo
    },

    callback: function(result) {
      if(result['changed'])
      {
        if (result['new_status_type'] == 'ready' && result['next_status'])
        {
          topic = 'Hasło gotowe';
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic, function() {
        	  $('#ready-note-dialog').dialog({title: "Dodawanie uwag na temat gotowości hasła:"}).dialog('open');
          })
        }
        else if(result['new_status_type'] == 'checked' && result['next_status'])
        {
          topic = 'Hasło zatwierdzone';
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic, function() {
        	  $('#ready-note-dialog').dialog({title: "Dodawanie uwag na temat zatwierdzenia hasła:"}).dialog('open');
          })
        }
        else if (result['new_status_type'] == 'ready_f' && result['next_status'])
        {
          topic = 'Hasło gotowe frazeologicznie';
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic, function() {
        	  $('#ready-note-dialog').dialog({title: "Dodawanie uwag na temat gotowości hasła:"}).dialog('open');
          })
        }
        else if(result['new_status_type'] == 'checked_f' && result['next_status'])
        {
          topic = 'Hasło zatwierdzone frazeologicznie';
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic, function() {
        	  $('#ready-note-dialog').dialog({title: "Dodawanie uwag na temat zatwierdzenia hasła:"}).dialog('open');
          })
        }
        else if (result['new_status_type'] == 'ready_s' && result['next_status'])
        {
          topic = 'Hasło gotowe semantycznie';
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic, function() {
        	  $('#ready-note-dialog').dialog({title: "Dodawanie uwag na temat gotowości hasła:"}).dialog('open');
          })
        }
        else if(result['new_status_type'] == 'checked_s' && result['next_status'])
        {
          topic = 'Hasło zatwierdzone semantycznie';
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic, function() {
        	  $('#ready-note-dialog').dialog({title: "Dodawanie uwag na temat zatwierdzenia hasła:"}).dialog('open');
          })
        }
        
          window.lastSelectedId = result['lemma_id'];
          grid.trigger("reloadGrid");

          data = grid.jqGrid('getGridParam', 'postData');
          data['mask'] = '';
          data['id'] = result['lemma_id'];

          $.get(ajax_location, data, function(resp) {
            var selectedRow = resp['selected_id'] + "";
            var rowIndex = resp['rowIndex'];
            var recordsCount = resp['records'];
            if (recordsCount > 0){
              grid.jqGrid('scrollToRow', rowIndex, recordsCount);
            }
          });
        load_content(result['lemma_id']);
        HideProgressAnimation();
      }
      else 
      {
    	HideProgressAnimation();
    	if(result['message'])
    	    alert(result['message']);
      }
    },
    bad_data_callback: function(result) {
        if(result == 'old version') {
      	  HideProgressAnimation();
          error_alert('Nie można zmienić statusu nieaktualnej wersji hasła.');
          return false;
        }
        else if(result == 'user logged out') {
          HideProgressAnimation();
          alertUserNotAuthenticated();
          return false;
        }
        else if(result == 'already changed') {
            HideProgressAnimation();
            error_alert('Status już został zmieniony.');
            return false;
        }
        else if(result == 'wrong change') {
            HideProgressAnimation();
            error_alert('Nie można dokonać zmiany statusu, najpewniej został on już zmieniony.');
            return false;
        }
        else {
          HideProgressAnimation();
          return true;
        }        
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
  });
  return false;
}

function restore_lemma() {
    ShowProgressAnimation();
    change = false;
  
    if(selected_ctrl_row_id != -1)
	  {
	      change_id = selected_ctrl_row_id.replace('change_', '');
	      $.ajaxJSON({
          method: 'post',
          url: ajax_restore_lemma,
          data: {
            change_id: change_id, // haslo przechowywane w systemie kontroli zmian
            lemma_id: lemma_id    // obecnie ustawione haslo
          },
          callback: function(result) {
            window.lastSelectedId = result['id'];
            grid.trigger("reloadGrid");

            data = grid.jqGrid('getGridParam', 'postData');
            data['mask'] = '';
            data['id'] = result['id'];
            window.lemma_id = result['id'];

            $.get(ajax_location, data, function(resp) {
              var selectedRow = resp['selected_id'] + "";
              var rowIndex = resp['rowIndex'];
              var recordsCount = resp['records'];
              if (recordsCount > 0 && !resp['lemma_nfound']){
                grid.jqGrid('scrollToRow', rowIndex, recordsCount);
                load_content(window.lemma_id);
              }
              else if(resp['lemma_nfound'])
              {
                load_content(window.lemma_id);
              }
            });
            HideProgressAnimation();	
            alert('Przywracanie hasła zakończono pomyślnie.');	
          },
          bad_data_callback: function(result) {
              if(result == 'old version') {
            	HideProgressAnimation();
                error_alert('Nie można przywrócić hasła, wyświetlana w interfejsie wersja nie jest aktualna.');
                return false;
              }
              else {
                HideProgressAnimation();
                return true;
              }        
          },
          error_callback: function(xhr, status, error) {
            HideProgressAnimation();
            error_alert(status + ': ' + error);
          },
        });
	  }
    return false;
}

/////////////////////////////////////////

  function elements_need_conversion(from_lemma_id, to_lemma_id) {
	  need_conversion = false;
	  can_be_converted = false;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_need_conversion,
	    data: {from_lemma_id: from_lemma_id,
	    	   to_lemma_id: to_lemma_id},
	    success: function(result) {
	    	need_conversion = result['need_conversion'];
	    	can_be_converted = result['can_be_converted'];
	    },
	    async:false
	  });
	  return [can_be_converted, need_conversion];
  }

  function openConvertFrameForm(from_lemma_id, to_lemma_id, frame_id) {
	  $('#add-table-elem-dialog').load(ajax_frame_conversion_form, {
		  'from_lemma_id': from_lemma_id,
		  'to_lemma_id': to_lemma_id,
		  'frame_id': frame_id})
		  .dialog( 'option', 'title', 'Konwersja schematu:' )
		  .dialog('open');
  }
  
  function convertFrameFormSubmit() {
    ShowProgressAnimation();
	this_form = $(this);	
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    { 
      if (elem.name != 'frame_versions')
        return elem;
      else {
        if (elem.name == 'frame_versions')
          frame_version = elem.value;
      }
    });
    
    form_data.push({name: 'frame_version', value: frame_version});
    form_data.push({name: 'lemma_id', value: window.lemma_id});

    $.ajaxJSON({
      method: 'post',
      url: ajax_frame_conversion_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) { 
	    new_frame = serializedObjToObj(result['frame']);
	    new_frame.id = new_elem_id;
        new_elem_id--;
	    window.schemas.push(new_frame);   
	    new_frames_make_change();
	    goToFrame('frame_'+new_frame.id+'_', document.getElementById('new-frame-tables'));
	    $('#add-table-elem-dialog').dialog('close');
        HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'select frame version') {
        HideProgressAnimation();
        error_alert('Wybierz wersję schematu.');
        return false;
      } 
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
  }

  function pasteFrameElement(id, copy_elem, schemas)
  {
    var target_elem = ''
    if(id != -1)
      target_elem = getElementInstance(id, schemas);  
    var to_copy_elem = copy_elem; 
    elements_conversion = elements_need_conversion(elem_in_bucket['lemma_id'], window.lemma_id);
    can_be_converted = elements_conversion[0]
    need_conversion = elements_conversion[1]
    
    // kopiowanie schematu do hasla
    if(!target_elem && 
        to_copy_elem['type'] == 'frame')
    {
      var frame = $.evalJSON($.toJSON(to_copy_elem['element']));
      clearSemanticConnections(to_copy_elem['type'], frame);
      // kopiowanie schematu z podgladu (moze wymagac konwersji)
      if(elem_in_bucket['lemma_id'] && 
         need_conversion && can_be_converted &&
    	 elem_in_bucket['lemma_id'] != window.lemma_id) {
    	  openConvertFrameForm(elem_in_bucket['lemma_id'], window.lemma_id, frame.id)
      }
      else if(!need_conversion) {
    	  if(frame.id > 0) {
    		  var frame_chars = get_compatible_schema_chars(window.lemma_id, frame.id);
        	  frame.characteristics = frame_chars;
    	  }
		  frame.id = new_elem_id;
          new_elem_id--;
          window.schemas.push(frame);
          new_frames_make_change();
      }
    }
    else
    {
     // kopiowanie argumentu do pozycji
      if(target_elem['type'] == 'position' && 
         to_copy_elem['type'] == 'argument' && !need_conversion)
      {
        var argument = $.evalJSON($.toJSON(to_copy_elem['element']));
        clearSemanticConnections(to_copy_elem['type'], argument);
        argument.id = new_elem_id;
        new_elem_id--;
        target_elem['element'].arguments.push(argument);
        new_frames_make_change();
      }
    // kopiowanie pozycji do schematu
      else if(target_elem['type'] == 'frame' && 
          to_copy_elem['type'] == 'position' && !need_conversion)
      {
        var position = $.evalJSON($.toJSON(to_copy_elem['element']));
        clearSemanticConnections(to_copy_elem['type'], position);
        position.id = new_elem_id;
        new_elem_id--;
        target_elem['element'].positions.push(position);
        new_frames_make_change();
      }
    } 
  }
  
  function get_compatible_schema_chars(lemma_id, schema_id) {
	  var schema_chars = [];
	  jQuery.ajax({
		type: 'get',
	    url: ajax_get_compatible_schema_chars,
	    data: {lemma_id: lemma_id,
	    	   schema_id: schema_id},
	    success: function(result) {
	    	schema_chars = result['schema_chars'];
	    },
	    async: false
	  });
	  return schema_chars;
  }
  
  function new_frames_make_change()
  {
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      change = true;
  }
  
  function getFrameInstance(id, schemas) {
    if(id != -1 && id.startsWith('frame')) {
      var ids = parseId(id);
      var frame_id = ids['frame_id'];
      for(var i=0; i<schemas.length; i++) {
        if(schemas[i].id == frame_id) { // frame
          return {'element': schemas[i],
          	       'type': 'frame'};
        }
      }
    }
    return {};
  }
  
  function arg_can_be_lexicalized(argument_id) {
	  can_be_lexicalized = false;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_arg_can_be_lexicalized,
	    data: {argument_id: argument_id},
	    success: function(result) {
	    	can_be_lexicalized = result['can_be_lexicalized'];
	    },
	    async:false
	  });
	  return can_be_lexicalized;
  }
  
  function user_has_perm(perm) {
	  has_perm = false;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_user_has_perm,
	    data: {perm: perm},
	    success: function(result) {
	      has_perm = result['has_perm'];
	    },
	    async:false
	  });
	  return has_perm;
  }
  
  function canModifyFrame(id, schemas) {
	  canModify = false;
	  frameInstance = getFrameInstance(id, schemas);
	  if((user_has_perm('dictionary.add_syntactic_frames')) ||
		 (user_has_perm('dictionary.add_phraseologic_frames') && frameInstance['element'].is_phraseologic)) {
		  canModify = true;
	  }
	  return canModify;  
  }
  
  function removeElement() {
	if(window.selected_id != -1) {
		var assignedExamples = [];
		if(canModifyFrame(window.selected_id, window.schemas) &&
		   !checkIfSemChangedAndAlert()) {
			assignedExamples = gotAssignedExample(nkjp_examples, selected_id, true);
			if(assignedExamples.length == 0) {
				schemas = removeFrameElement(selected_id, schemas);	
			    new_frames_make_change();
			}
			else {
				$('#pinned-examples-dialog').data('assignedExamples', assignedExamples).dialog('open');
			}
		}
	} 
  }
  
  function addElement() {
	  if(!checkIfSemChangedAndAlert() && 
		 (window.selected_id == -1 || canModifyFrame(window.selected_id, window.schemas))) {
		  window.schemas = addFrameElementDialog(window.selected_id, window.schemas);
	  }
  }
  
  function copyElement()
  {
     if(window.activeLemmaPanel == 'preview_lemma' && 
    	window.prev_selected_id != -1 &&
    	canModifyFrame(window.prev_selected_id, prev_frames))
    	//user_has_perm('dictionary.add_syntactic_frames'))
     {
       elem_in_bucket = getElementInstance(window.prev_selected_id, prev_frames);
       elem_in_bucket['lemma_id'] = window.prev_lemma_id; 
       unselectPrevTd(window.prev_selected_id);
       window.prev_selected_id = -1;
     }
     else if(window.activeLemmaPanel == 'new_frames' &&
    		  window.selected_id != -1 &&
    		  canModifyFrame(window.selected_id, window.schemas))
     {
       elem_in_bucket = getElementInstance(window.selected_id, schemas);
       elem_in_bucket['lemma_id'] = window.lemma_id;
       unselectTd(window.selected_id);
       window.selected_id = -1;
     }   
  }

//////////////////////////////////////////////////////
  function areNewPreviewEntriesRelated() {
	    $.ajaxJSON({
	      method: 'get',
	      url: ajax_are_new_preview_entries_related,
	      data: {
	    	  lemma_id: window.lemma_id,
		      preview_lemma_id: window.prev_lemma_id
	      },

	    callback: function(result) {      
	      if(result['related']) {
	          $("button#prev_disrelate_entries").css("visibility","visible");
	      }  	
	      else {
	    	  $("button#prev_disrelate_entries").css("visibility","hidden");
	      }
	    },
	    error_callback: function(xhr, status, error) {
	      error_alert(status + ': ' + error);
	    },
	    bad_data_callback: function(result) {
	      return true;
	    },
	  });
	  return false;
  }
  
  function relateEntries()
  {
    if (confirm('Czy jesteś pewien, że chcesz powiazać hasło z zakładki "Schematy" z hasłem wybranym w zakładce "Podgląd hasła"?')) {
	    ShowProgressAnimation();
	    $.ajaxJSON({
	      method: 'post',
	      url: ajax_relate_entries,
	      data: {
	        lemma_id: window.lemma_id,
	        preview_lemma_id: window.prev_lemma_id
	      },

	    callback: function(result) {    
	      $("button#prev_disrelate_entries").css("visibility", "visible");
	      HideProgressAnimation();	   
	    },
	    error_callback: function(xhr, status, error) {
	      HideProgressAnimation();
	      error_alert(status + ': ' + error);
	    },
	    bad_data_callback: function(result) {
	      if (result == 'lemma not selected') {
	        HideProgressAnimation();
	        error_alert('Nie zaznaczono hasła w zakładce "Schematy" lub "Podglądzie hasła".');
	        return false;
	      }
	      else if (result == 'same lemma id') {
	        HideProgressAnimation();
	        error_alert('Nie można powiązać hasła z samym sobą.');
	        return false;
	      }
	      else if (result == 'same part of speech') {
		        HideProgressAnimation();
		        error_alert('Nie można powiązywać haseł reprezentujących tę samą część mowy.');
		        return false;
		      }
	      else
	      {
	        HideProgressAnimation();
	        return true;
	      }      
	    },
	  });
	  return false;
	}
  }

  function disrelateEntries()
  {
    if (confirm('Czy jesteś pewien, że chcesz anulować relację hasła wybranego w zakładce "Schematy" z hasłem wybranym w zakładce "Podgląd hasła"?')) {
	    ShowProgressAnimation();
	    $.ajaxJSON({
	      method: 'post',
	      url: ajax_disrelate_entries,
	      data: {
	        lemma_id: window.lemma_id,
	        preview_lemma_id: window.prev_lemma_id
	      },
	    callback: function(result) {   
	      $("button#prev_disrelate_entries").css("visibility", "hidden");
	      HideProgressAnimation();	
	    },
	    error_callback: function(xhr, status, error) {
	      HideProgressAnimation();
	      error_alert(status + ': ' + error);
	    },
	    bad_data_callback: function(result) {
	      HideProgressAnimation();
	      return true;     
	    },
	  });
	  return false;
	}
  }
  
///////////////////////////////////////////////////////
    
  function pasteElement()
  {
	 if(window.elem_in_bucket && !checkIfSemChangedAndAlert() &&
		(window.selected_id == -1 || 
		 canModifyFrame(window.selected_id, window.schemas))) {
		 pasteFrameElement(selected_id, elem_in_bucket, schemas);
	 }
  }
  
  function cutElement()
  {
    if(selected_id != -1) 
    {
      elem_in_bucket = getElementInstance(selected_id, schemas);
      if(window.activeLemmaPanel == 'preview_lemma') {
    	  elem_in_bucket['lemma_id'] = window.prev_lemma_id;
      }
      else {
    	  elem_in_bucket['lemma_id'] = window.lemma_id;
      }
      var elem_to_remove = elem_in_bucket['element'];
      var elem_to_copy = $.evalJSON($.toJSON(elem_in_bucket['element']));
      elem_in_bucket['element'] = elem_to_copy;
    
    // remove
      removeElement();
    }
  }
  
  function duplicateElement()
  {
    if(window.selected_id != -1 && 
       canModifyFrame(window.selected_id, window.schemas) &&
       !checkIfSemChangedAndAlert()) 
    {
      elem_in_bucket = getElementInstance(selected_id, schemas);
      
      var parent_elem = getParentInstance(selected_id, schemas);
      var duplicate = $.evalJSON($.toJSON(elem_in_bucket['element']));
      clearSemanticConnections(elem_in_bucket['type'], duplicate);
      duplicate.id = new_elem_id;
      new_elem_id--;
      
      if(parent_elem['type']=='lemma')
    	  schemas.push(duplicate);
      else if(parent_elem['type']=='frame')
        parent_elem['element'].positions.push(duplicate);
      else if(parent_elem['type']=='position')
        parent_elem['element'].arguments.push(duplicate);
      
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      if (elem_in_bucket['type'] == 'frame') {
    	goToFrame('frame_'+duplicate.id+'_', document.getElementById('new-frame-tables'));  
      }
      else {
    	$('#new-frame-tables').scrollTop(scrollPosition);
      }  
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      selected_id = -1;
      window.elem_in_bucket = '';
      change = true;
    }
  }
  
  function addPhraseologicFrame()
  {
    if(selected_id != -1) {
      var schema = getElementInstance(selected_id, schemas);
      var parent_elem = getParentInstance(selected_id, schemas);
      
      if(parent_elem['type']=='lemma' 
    	  && !schema['element'].is_phraseologic
    	  && user_has_perm('dictionary.add_phraseologic_frames')) {
        var duplicate = $.evalJSON($.toJSON(schema['element']));
        clearSemanticConnections(schema['type'], duplicate);
        duplicate.id = new_elem_id;
        new_elem_id--;
      	duplicate.is_phraseologic = true;
      	schemas.push(duplicate);

        draw_filtered_frames(schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
        goToFrame('frame_'+duplicate.id+'_', document.getElementById('new-frame-tables'));
        
        frames_modif = frames_modif.slice(0, frames_modif_idx+1);
        var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
        frames_modif.push(lemma_version);
        frames_modif_idx++;
        selected_id = -1;
        change = true;
      }
    }
    else if(phraseologicPropositionsExists(window.lemma_id)) {
        form_data = new Array();
      	form_data.push({name: 'opinion', value: ''});
      	form_data.push({name: 'characteristics', value: ['_', '_']}); 
      	form_data.push({name: 'edit', value: false});
      	form_data.push({name: 'lemma_id', value: window.lemma_id});
        data = JSON.stringify(form_data);
        $('#add-table-elem-dialog').load(ajax_frame_form, {'form_data': data,
        												   'phraseologic': true}, function(){
	    														$('#new-frames-tabs').hide();
	    													 })
        												     .dialog( 'option', 'title', 'Dodawanie schematów frazeologicznych:' )
        													 .dialog('option', 'width', 500)
        												     .dialog('open');
    }
  }
  
  function openAssignPhraseologicFrameDialog() {
    if(selected_id != -1) {
        var frame = getElementInstance(selected_id, schemas);
        var parent_elem = getParentInstance(selected_id, schemas);
        
        if(parent_elem['type']=='lemma' 
      	  && frame['element'].is_phraseologic
      	  && user_has_perm('dictionary.add_phraseologic_frames')) {
        	
          $('#add-table-elem-dialog').load(ajax_assign_phraseologic_frame_form, 
        		  {'lemma_id': window.lemma_id,
        		   'phraseologic_frame': JSON.stringify(frame['element'])})
				     .dialog( 'option', 'title', 'Przypisywanie frazeologizmu do haseł:' )
					 .dialog('option', 'width', 300)
				     .dialog('open');
        }
      }
  }
  
  function phraseologicPropositionsExists(lemma_id) {
	  propositionsExists = false;
	  jQuery.ajax({
		type: 'get',
	    url: ajax_phraseologic_propositions_exists,
	    data: {lemma_id: lemma_id},
	    success: function(result) {
	    	propositionsExists = result['propositions_exists'];
	    },
	    async:false
	  });
	  return propositionsExists;
  }
  
  function delete_nkjp_example(example_id)
  {
    if(example_id != -1 && !checkIfSemChangedAndAlert())
    {
      example_id = selected_example_id.replace('nkjp_', '');
      for(var i=0; i<nkjp_examples.length; i++)
      {
        if(nkjp_examples[i].example_id == example_id)
        {
          if(canModifyFrame(nkjp_examples[i].frame_id, window.schemas)) {
  	        nkjp_examples.splice(i, 1);
  	        change = true;
  	        
  		    window.frames_modif = window.frames_modif.slice(0, frames_modif_idx+1);     
  		    var lemma_version = new Lemma_Version(schemas, window.nkjp_examples, window.nkjp_lemma_examples);
  		    frames_modif.push(lemma_version);
  		    frames_modif_idx++;   
  		   
  		    window.selected_example_id = -1;
  		    var parent = document.getElementById("show_nkjp_table");
  		    draw_nkjp_table(parent, selectedFrameIdNkjp, window.nkjp_examples, 'NkjpTableRow', 'nkjp_');  
  		    $("tr.NkjpTableRow").click(function(){
  		      selectNkjpTr(this.id)});
  		    
  		    scrollPosition = $('#new-frame-tables').scrollTop();
  		    draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
  		    $('#new-frame-tables').scrollTop(scrollPosition);  	      
  	        break;
          }
        }  
      }
    }
  }
    
  function delete_all_nkjp_examples(frame_id)
  {
  	if(canModifyFrame(frame_id, window.schemas) && 
  	   !checkIfSemChangedAndAlert())
  	{
  		var new_example_tab = new Array();
  	    for(var i=0; i<nkjp_examples.length; i++)
  	    {
  	      if(nkjp_examples[i].frame_id != frame_id)
  	      {
  	        new_example_tab.push(nkjp_examples[i]);
  	      }  
  	      else
  	        change = true;
  	    }
  	    window.nkjp_examples = new_example_tab;
  	    
  	    frames_modif = frames_modif.slice(0, frames_modif_idx+1);     
  	    var lemma_version = new Lemma_Version(window.schemas, window.nkjp_examples, window.nkjp_lemma_examples);
  	    frames_modif.push(lemma_version);
  	    frames_modif_idx++;
  	    
  	    window.selected_example_id = -1;
  	    var parent = document.getElementById("show_nkjp_table");
  	    draw_nkjp_table(parent, frame_id, window.nkjp_examples, 'NkjpTableRow', 'nkjp_');
  	    $("tr.NkjpTableRow").click(function(){
  	      selectNkjpTr(this.id)});     
  	    
  	    scrollPosition = $('#new-frame-tables').scrollTop();
  	    draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
  	    $('#new-frame-tables').scrollTop(scrollPosition);  
  	}
  }

  function fill_nkjp_example_form(example, form_selector) {	
  	
      $.ajaxJSON({
        method: 'get',
        url: ajax_get_nkjp_dict_ids,
        data: {
          source_str: example.source,
          opinion_str: example.opinion
        },

      callback: function(result) {      
  		$(form_selector+' #id_source').val(result['source_id']);
  		$(form_selector+' #id_opinion').val(result['opinion_id']);
  		$(form_selector+' #id_sentence').val(example.sentence);
          $(form_selector+' #id_comment').val(example.comment);
      },
      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
      bad_data_callback: function(result) {
        return true;
      },
    });
    return false;
  }

  function modify_nkjp_example(example_id)
  {
    if(example_id != -1 && !checkIfSemChangedAndAlert())
    {
      var example = '';
      for(var i=0; i<window.nkjp_examples.length; i++)
      {
        example_tabId = 'nkjp_'+window.nkjp_examples[i].example_id;
        if(example_tabId == example_id)
        {
          example = window.nkjp_examples[i];
          break;
        }
      }
    
      if(canModifyFrame(example.frame_id, window.schemas) || user_has_perm('dictionary.modify_all_examples')) {
  	    $('.new_frame_tabs').tabs('select', 1);
      	window.selected_example_id = example_id;
      	fill_nkjp_example_form(example, '.nkjp-example-form');
      	window.selectedFrameIdNkjp = example.frame_id;
      	for(var i=0; i<example.arguments_ids.length; i++)
        		selectTd(example.arguments_ids[i]);
      }
    }
  }

  function confirm_nkjp_example(example_tabId)
  {
    if(example_tabId != -1)
    {
      nkjpInstance = getNkjpExampleInstance(window.nkjp_examples, example_tabId);
      confirmNkjpExample(nkjpInstance);
    }
  }
  
  function backOneModification()
  {
    if(window.frames_modif_idx>0)
    {
      window.frames_modif_idx--;
       
      var lemma_version = window.frames_modif[window.frames_modif_idx]; 
      window.schemas = lemma_version.schemas;
      window.nkjp_examples = lemma_version.nkjp_examples;
      window.nkjp_lemma_examples = lemma_version.nkjp_lemma_examples;
      draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');     
      $("tr.NkjpLemmaTableRow").click(function(){
        selectLemmaNkjpTr(this.id)});
      // rysowanie tabeli nkjp examples na nowo
      draw_nkjp_table(document.getElementById("show_nkjp_table"), window.selectedFrameIdNkjp, window.nkjp_examples, 'NkjpTableRow', 'nkjp_');
      $("tr.NkjpTableRow").click(function(){
        selectNkjpTr(this.id)});
      
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
      selected_id = -1;
    }
  }
  
  function forwardOneModification()
  {
    if(window.frames_modif_idx+1<window.frames_modif.length)
    {
      window.frames_modif_idx++;
      
      var lemma_version = window.frames_modif[window.frames_modif_idx]; 
      window.schemas = lemma_version.schemas;
      window.nkjp_examples = lemma_version.nkjp_examples;
      window.nkjp_lemma_examples = lemma_version.nkjp_lemma_examples;
      draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');     
      
      $("tr.NkjpLemmaTableRow").click(function(){
        selectLemmaNkjpTr(this.id)});
      
      scrollPosition = $('#new-frame-tables').scrollTop();
      draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
      $('#new-frame-tables').scrollTop(scrollPosition);
      
      // rysowanie tabeli nkjp examples na nowo
      draw_nkjp_table(document.getElementById("show_nkjp_table"), window.selectedFrameIdNkjp, window.nkjp_examples, 'NkjpTableRow', 'nkjp_');
      $("tr.NkjpTableRow").click(function(){
        selectNkjpTr(this.id)});
      selected_id = -1;
    }	
  }

////////////////////////////////////////////////////////////////

////////////////////// WALIDACJA /////////////////////////////// 

function relPosArgumentsGet(arguments_ids, position_arg_ids)
{
  relArguments = new Array();
  for(var i=0; i<arguments_ids.length; i++)
  {
    for(var j=0; j<position_arg_ids.length; j++)
    {
      if(arguments_ids[i] == position_arg_ids[j])
      {
        relArguments.push(position_arg_ids[j]);
        break;
      }
    }
  }  
  return relArguments;
}

function eliminateDuplicates(arr) {
    var i,
	len=arr.length,
	      out=[],
	      obj={};
	 
	  for (i=0;i<len;i++) {
	    obj[arr[i]]=0;
	  }
	  for (i in obj) {
	    out.push(i.split(','));
	  }
	  return out;
}

function checkPosCoordination(position, frame_id, nkjp_examples)
{
  pos_args_id = new Array();
  for(var i=0; i<position.arguments.length; i++)
    pos_args_id.push(frame_id + 'pos_'+position.id+'_'+'arg_'+position.arguments[i].id+'_');
    
  pos_args_groups = new Array();
    
  for(var a=0; a<pos_args_id.length; a++)
  {
    for(var i=0; i<nkjp_examples.length; i++)
    {
      pos_rel_arguments = relPosArgumentsGet(nkjp_examples[i].arguments_ids, pos_args_id);
      if(nkjp_examples[i].frame_id == frame_id && pos_rel_arguments.length!=1)
      {
        for(var j=0; j<pos_rel_arguments.length; j++)
        {
          if(pos_rel_arguments[j] == pos_args_id[a])
          {
            args_group = pos_rel_arguments;
            pos_args_groups.push(args_group);
          }
        }        
      }
    }    
  }
  
  cl_pos_args_groups = new Array();
  // removing duplicates from pos_args_groups
  cl_pos_args_groups = eliminateDuplicates(pos_args_groups);
  // laczenie grup posiadajacych chociaz jeden jednakowy argument    
  pos_args_groups = joinArgGroups(cl_pos_args_groups);
  
  if(pos_args_groups.length == 1)
  {
    for(var j=0; j<pos_args_id.length; j++)
    {
      if(pos_args_groups[0].indexOf(pos_args_id[j])==-1)
      {
        return false;
      }
    }
  } 
  else
    return false;
    
  return true;
}

function joinArgGroups(pos_args_groups)
{
  if(pos_args_groups.length == 1)
    return pos_args_groups;
    
  var joined_arrays = new Array();
  match_index = -1;
  for(var i=1; i<pos_args_groups.length; i++)
  {
    for(var j=0; j<pos_args_groups[0].length; j++)
    {
      if(pos_args_groups[i].indexOf(pos_args_groups[0][j])!=-1)
      {
        match_index = i;
        joined_arrays = pos_args_groups[i].concat(pos_args_groups[0]);
        break;
      }
    }
    if(match_index!=-1)
      break;
  }
  if(match_index==-1)
    return pos_args_groups
  
  pos_args_groups.splice(match_index, 1);
  pos_args_groups.splice(0, 1);
  pos_args_groups.push(joined_arrays);
  pos_args_groups = eliminateDuplicates(pos_args_groups)
  
  return joinArgGroups(pos_args_groups)  
}

function wholeCoordinationSpecified(frame, nkjp_examples)
{
    var frame_id = 'frame_'+frame.id+'_';
    var onlySingleArgPoss = true;
    var hasExamples = false;
    for(var j=0; j<frame['positions'].length; j++)
    {
      if(frame['positions'][j]['arguments'].length > 1)
      {
        onlySingleArgPoss = false;
        foundRelation = checkPosCoordination(frame['positions'][j], frame_id, nkjp_examples)   

        if(!foundRelation)
          return false; 
      }
      else if(frame['positions'][j]['arguments'].length == 1)
        hasExamples=true;
    }    
    if(!onlySingleArgPoss)
      return true;
    else if(onlySingleArgPoss && hasExamples)
      return true;
    else 
      return false;
}

// WALIDACJA 14: Zapisanie hasla dopuszczalne jest jedynie wtedy, 
// kiedy kazda rama zawierajaca wiecej niz jeden argument w tej samej pozycji 
// posiada przyklad potwierdzajacy mozliwosc ich koordynacji 
// (przyklady koordynacji, ktorych zbior obejmuje mozliwosc koordynacji wszystkich argumentow). 
function pass_validate14(schemas)
{   
  valid = true;
  for(var i=0; i<schemas.length; i++)
  {
    var frame_id = 'frame_'+schemas[i].id+'_';
    
    for(var j=0; j<schemas[i]['positions'].length; j++)
    {
      if(schemas[i]['positions'][j]['arguments'].length > 1)
      {
        foundRelation = checkPosCoordination(schemas[i]['positions'][j], frame_id, nkjp_examples)   

        if(!foundRelation)
        {
            if(valid) {
            	HideProgressAnimation();
            	error_alert('Wskazane pozycje nie posiadają przykładów potwierdzających koordynację dla wszystkich typów fraz (przejdź do zakładki ze schematami aby je zobaczyć, jeśli pozycje nie są widoczne sprawdź ustawienia filtrów i powtórz walidację).')
                ShowProgressAnimation();
            }
            schemas[i]['positions'][j].error = true;
            valid = false;
        }  
      }
    }
  }    
  return valid;
}

function send_miss_frames_msg(lemma_id, status_id)
{
  $.ajaxJSON({
      method: 'post',
      url: ajax_send_miss_frames_msg,
      data: {
        lemma_id: lemma_id,
        status_id: status_id,
      },
      callback: function(result) {    
      },
      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
  });
  return false;
}

// PREWALIDACJA NASTEPUJE JUZ TUTAJ
function validate_new_frames(status_id, status_change) {
  ShowProgressAnimation();
  var framesToValid = new Array();
  selected_frame_id = null;
  
  if(window.selected_id != -1 && !status_change)
  {
    selected_elem = getElementInstance(window.selected_id, window.schemas);
    if(selected_elem['type'] == 'frame')
    {
      framesToValid.push(selected_elem['element']);
      selected_frame_id = selected_elem['element'].id;
    }   
    else 
      framesToValid = window.schemas;
  }
  else
    framesToValid = window.schemas;
  
/// PREWALIDACJA //	
	if(!pass_validate14(framesToValid))
	{  
	    scrollPosition = $('#new-frame-tables').scrollTop();
		draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
		$('#new-frame-tables').scrollTop(scrollPosition);
		clear_errors(window.schemas);
		$('#save').attr("disabled", false);
		HideProgressAnimation();
		return false;
	}

///////////////////

    data = JSON.stringify(framesToValid);
	var convertedExamples = convertExamples(nkjp_examples);
	examples_data = JSON.stringify(convertedExamples)
	var convertedLemmaExamples = convertLemmaExamples(nkjp_lemma_examples);
	lemma_examples_data = JSON.stringify(convertedLemmaExamples);

    $.ajaxJSON({
      method: 'post',
      url: ajax_validate_new_frames,
      data: {
        data: data,
        id: lemma_id,
        examples: examples_data,
        lemma_examples: lemma_examples_data,
        status_id: status_id,
        selected_frame_id: selected_frame_id
      },

    callback: function(result) {
      $('#save').attr("disabled", false);
      if(result['error_message'] && !result['confirm_message'])
      {
        HideProgressAnimation();
        error_alert(result['error_message']);
        ShowProgressAnimation();
        window.schemas = result['frames'];
	      
	    scrollPosition = $('#new-frame-tables').scrollTop();
        draw_filtered_frames(window.schemas, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'ActiveFrameTable', window.lemma_entry);
        $('#new-frame-tables').scrollTop(scrollPosition);
        clear_errors(window.schemas);
      }
      else if(result['error_message'] && confirm(result['error_message']))
      {
        if(status_id)
        {
            lemma_status_change(status_id);
            send_miss_frames_msg(lemma_id, status_id);
        }
        HideProgressAnimation();
        if(!status_id)
        	alert('Walidacja ukończona pomyślnie.');
      }
      else if(!result['error_message'])
      {
        if(status_id)
        {
            lemma_status_change(status_id);
            send_miss_frames_msg(lemma_id, status_id);
        }
        HideProgressAnimation();
        if(!status_id)
        	alert('Walidacja ukończona pomyślnie.');
      }
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
  });

  return false;
}

/////////////////////////// Semantic validation /////////////////////////// 
function semanticsValid(status_id) {
	ShowProgressAnimation();
	semantics_valid = false;
	jQuery.ajax({
		async: false,
	    type: 'get',
	    url: ajax_validate_semantics,
	    data: {
	        lemma_id: window.lemma_id,
	        new_status_id: status_id
	    },
	    success: function(result) {
	    	HideProgressAnimation();
	        if(result['error_message'].length > 0) {
		        alert(result['error_message']);
	        }
	        else {
	        	semantics_valid = true;
	        }
	    },
	});
	return semantics_valid;
}

///////////////////////////////////lemma_examples/////////////////////////////
function nkjp_lemma_modify(nkjp_lemma_examples, example_tabId, form_selector) {
    ShowProgressAnimation();
	this_form = $(form_selector);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'sentence' && elem.name != 'source' && elem.name != 'opinion'
       && elem.name != 'comment')
        return elem;
      else {
        if (elem.name == 'sentence')
          sentence = elem.value;
        else if (elem.name == 'source')
          source = elem.value;
        else if (elem.name == 'opinion')
          opinion = elem.value;
        else if (elem.name == 'comment')
          comment = elem.value;
      }
    });

	form_data.push({name: 'sentence', value: sentence});
    form_data.push({name: 'source', value: source});
    form_data.push({name: 'opinion', value: opinion});
    form_data.push({name: 'comment', value: comment});

    $.ajaxJSON({
      method: 'post',
      url: ajax_nkjp_example_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {    
      nkjpInstance = getNkjpLemmaExampleInstance(nkjp_lemma_examples, example_tabId); 
      nkjpInstance.sentence =  result['sentence'];
      nkjpInstance.source =  result['source'];
      nkjpInstance.opinion =  result['opinion'];
      nkjpInstance.comment =  result['comment'];
      nkjpInstance.example_id = curr_lemma_example_id;
      curr_lemma_example_id--;
      window.selected_lemma_example_id = -1;
      
      window.frames_modif = window.frames_modif.slice(0, frames_modif_idx+1);     
      var lemma_version = new Lemma_Version(window.schemas, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;  
     
      draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
      $("tr.NkjpLemmaTableRow").click(function(){
        selectLemmaNkjpTr(this.id)});
      resetForm(this_form);
      change = true;
      HideProgressAnimation();	   
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Wszystkie pola poza komentarzem są wymagane.');
        return false;
      }
      else if (result == 'comment required') {
        HideProgressAnimation();
        error_alert('Wybrane źródlo wymaga dodatkowych informacji.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }      
    },
  });
  return false;
}

function delete_lemma_example(example_id)
{
   if(example_id != -1 && !checkIfSemChangedAndAlert())
   {
     example_id = example_id.replace('nkjpLemma_', '');
     for(var i=0; i<nkjp_lemma_examples.length; i++)
     {
       if(nkjp_lemma_examples[i].example_id == example_id)
       {
         nkjp_lemma_examples.splice(i, 1);
         change = true;
         break;
       }  
     }
     window.selected_lemma_example_id = -1;
     var parent = document.getElementById("lemma_example_show");
     draw_nkjp_table(parent, '', nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');     
     $("tr.NkjpLemmaTableRow").click(function(){
       selectLemmaNkjpTr(this.id)});
     
     window.frames_modif = window.frames_modif.slice(0, frames_modif_idx+1);     
     var lemma_version = new Lemma_Version(window.schemas, window.nkjp_examples, window.nkjp_lemma_examples);
     frames_modif.push(lemma_version);
     frames_modif_idx++; 
   } 
}

function assign_lemma_example(example_id)
{
  if(window.selected_lemma_example_id != -1 && !checkIfSemChangedAndAlert())
  {
    window.activeLemmaPanel = 'new_frames';
    $('.tabs').tabs('select', 0);
    $('.new_frame_tabs').tabs('select', 1);
    window.selected_lemma_example_id = example_id;
    var example = '';
    
    for(var i=0; i<window.nkjp_lemma_examples.length; i++)
    {
      example_tabId = 'nkjpLemma_'+window.nkjp_lemma_examples[i].example_id;
      if(example_tabId == example_id)
      {
        example = window.nkjp_lemma_examples[i];
        break;
      }
    }
    fill_nkjp_example_form(example, '.nkjp-example-form');
    resetForm($('.lemma-example-form'));
  }
}

function modify_lemma_example(example_id)
{ 
  if(example_id != -1 && !checkIfSemChangedAndAlert())
  {
    nkjp_lemma_modify(window.nkjp_lemma_examples, example_id, '.lemma-example-form')
  }
}
////////////////////////////////////////////////////////////////


function reserveLemma()
{
  lemma_status_change('');
}

function saveHandle(event)
{
  save_new_frames();
  return false;
}

////////// lemma notes ///////////////
function removeLemmaNote(id) {
  if(id != -1)
  {
	ShowProgressAnimation();
    message_id = id.replace('note_', ''); 
     
    $.ajaxJSON({
      method: 'post',
      url: ajax_remove_lemma_note,
      data: {
              message_id: message_id, 
      },

      callback: function(result) { 
       window.selected_notes_row_id = -1;
       $('#notes').load(ajax_lemma_notes, 'id='+window.lemma_id);	
       HideProgressAnimation();
      },
    
      error_callback: function(xhr, status, error) {
        HideProgressAnimation();
        error_alert(status + ': ' + error);
      },
      bad_data_callback: function(result) {
        if (result == 'can not remove') {
          HideProgressAnimation();
          error_alert('Usuwać można jedynie notatki prywatne.');
          return false;
        }
        else if (result == 'already removed') {
            HideProgressAnimation();
            error_alert('Notatka została już usunięta, odśwież widok.');
            return false;
        }
        else {
          HideProgressAnimation();
          return true;
        }
      },
    });
  }	
}

////////////////////////////////////

//////////////////////////////////////

function modifyLemmaNote(id, form_selector)
{
  ShowProgressAnimation();
  if(id != -1)
  {
    message_id = id.replace('note_', ''); 

	this_form = $(form_selector);	
    form_data = this_form.serializeArray();
    private_flag = false;
  
    form_data = $.map(form_data, function(elem)
    { 
      if (elem.name != 'topic' && elem.name != 'message_text' &&
         elem.name != 'private')
        return elem;
      else {
        if (elem.name == 'topic')
          topic = elem.value;
        else if (elem.name == 'message_text')
          message_text = elem.value;
        else if (elem.name == 'private')
          private_flag = true;
      }
    });

	form_data.push({name: 'topic', value: topic});
    form_data.push({name: 'message_text', value: message_text});
    form_data.push({name: 'private', value: private_flag});
    form_data.push({name: 'lemma_id', value: window.lemma_id});
    form_data.push({name: 'message_id', value: message_id});

    $.ajaxJSON({
      method: 'post',
      url: ajax_lemma_notes_modify,
      data: {
        form_data: form_data
      },

    callback: function(result) {      
        $('#notes').load(ajax_lemma_notes, 'id='+result['id']);
        HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Należy wypełnić temat oraz treść wiadomości.');
        return false;
      } 
      else if (result == 'not private') {
        HideProgressAnimation();
        error_alert('Można modyfikować jedynie notatki prywatne.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
  }	
}

// zaznacz przyklad skladnicowy
function selectTableTr(id)
{  	  
	if($('#'+id).css("background-color") != window.selectedColor) 
	{
		$('#'+id).css("background-color", window.selectedColor);
		$('#'+id).children().css('background-color', window.selectedColor);
	}
	else
	{
		$('#'+id).css("background-color", '');
		$('#'+id).children().css('background-color', '');
	}
}

function show_skl_propositions()
{
	$('#id_propose_B').val('');
	$('#skladnica-examples').empty();
	$('#frame-realizations').empty();
	$('#skladnica-examples').load(ajax_show_skladnica_examples, 'id='+$('#id_propose_skladnica').val(), function() {
		$("#example-propositions tr").click(function(){
		    selectTableTr(this.id)
		});
	    $("#example-propositions tr").dblclick(function(){
	    	$('#example-opinion-dialog').empty();
	        $('#example-opinion-dialog').load(ajax_example_opinion_form, "example_id="+this.id).dialog('open'); 
	    });
	});
	$('#frame-realizations').load(ajax_show_frame_realizations, {'id': $('#id_propose_skladnica').val(),
																 'propose_type': 'skladnica'});
}

function show_B_propositions()
{
	$('#id_propose_skladnica').val('');
	$('#skladnica-examples').empty();
	$('#frame-realizations').empty();
	$('#frame-realizations').load(ajax_show_frame_realizations, {'id': $('#id_propose_B').val(),
		 														 'propose_type': 'B'});
}

function get_skladnica_example_and_fill_form() {
	skl_frame_id = $(this).val();
    $.ajaxJSON({
      method: 'post',
      url: ajax_get_skladnica_example,
      data: {
    	  skl_frame_id: skl_frame_id
      },
      callback: function(result) {  
    	example = serializedNkjpToObj(result['example']);
  		$('.nkjp-example-form #id_source').val(example.source);
		$('.nkjp-example-form #id_opinion').val(example.opinion);
		$('.nkjp-example-form #id_sentence').val(example.sentence);
        $('.nkjp-example-form #id_comment').val(example.comment);
      },
      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
    });
}

function get_xcp_example_and_fill_form() {
	exampleId = $(this).val();
    $.ajaxJSON({
      method: 'post',
      url: ajax_get_xcp_example,
      data: {
    	  example_id: exampleId
      },
      callback: function(result) {  
    	example = serializedNkjpToObj(result['example']);
  		$('.nkjp-example-form #id_source').val(example.source);
		$('.nkjp-example-form #id_opinion').val(example.opinion);
		$('.nkjp-example-form #id_sentence').val(example.sentence);
        $('.nkjp-example-form #id_comment').val(example.comment);
      },
      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
    });
}

function fill_frame_chars()
{
	frame_id = $(this).val();
    $.ajaxJSON({
      method: 'post',
      url: ajax_get_frame_chars,
      data: {
    	  frame_id: frame_id
      },
      callback: function(result) {  
  		$('#id_reflex').val(result['reflex_id']);
  		$('#id_negativity').val(result['negativity_id']);
  		$('#id_predicativity').val(result['predicativity_id']);
  		$('#id_aspect').val(result['aspect_id']);
      },
      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
    });
}

function create_example_opinion_dialog()
{
  $('#example-opinion-dialog').dialog({ autoOpen: false, 
	  								    modal: 'true',
	  								    closeOnEscape: 'true',
	  								    title: 'Oznaczanie poprawności przykładu'});
}

function example_opinion_form_submit() {
    ShowProgressAnimation();
    is_wrong = false;
	this_form = $(this);
    form_data = this_form.serializeArray(); 
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'is_wrong')
        return elem;
      else {
        if (elem.name == 'is_wrong')
          is_wrong = elem.value;
      }
    });

	form_data.push({name: 'is_wrong', value: is_wrong});
	form_data.push({name: 'example', value: $('.selected-example').attr('id')})

    $.ajaxJSON({
      method: 'post',
      url: ajax_example_opinion_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {   
      $('#example-opinion-dialog').dialog('close');
      $('#id_propose_skladnica').trigger('change');  
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      HideProgressAnimation();
      return true;
    },
  });
  return false;
}

function gridPreviewContent(isPreview) {
      $.ajaxJSON({
      method: 'get',
      url: ajax_preview_select,
      async: false,
      data: {
        isPreview: isPreview, 
      },

      callback: function(result) {
        
        if(result['reload'])
        {
          if(isPreview)
          {
            window.lastPrevSelectedId = window.prev_lemma_id;
            grid.trigger("reloadGrid");

            data = grid.jqGrid('getGridParam', 'postData');
            data['mask'] = '';
            data['id'] = window.prev_lemma_id;

            $.get(ajax_location, data, function(resp) {
              var selectedRow = resp['selected_id'] + "";
              var rowIndex = resp['rowIndex'];
              var recordsCount = resp['records'];
              if (recordsCount > 0){
                grid.jqGrid('scrollToRow', rowIndex, recordsCount);
              }
            });        
          }
          else
          {
            window.lastSelectedId = window.lemma_id;
            grid.trigger("reloadGrid");

            data = grid.jqGrid('getGridParam', 'postData');
            data['mask'] = '';
            data['id'] = window.lemma_id;

            $.get(ajax_location, data, function(resp) {
              var selectedRow = resp['selected_id'] + "";
              var rowIndex = resp['rowIndex'];
              var recordsCount = resp['records'];
              if (recordsCount > 0){
                grid.jqGrid('scrollToRow', rowIndex, recordsCount);
              }
            });
          }
          refresh_column_headers();
        }
      },

      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
    });
return false;
}

/////////////////////////////////////

$(function(){
  $.get(ajax_deselect_preview_tab);
	
  $('form.argument-add-form #show-realizations').live('click', show_argument_realizations);
  $('form.frame-conversion-form').live('submit', convertFrameFormSubmit);
  
  $('form.frame-form').live('submit', frame_form_submit);
  $('form.pos-cat-form').live('submit', pos_cat_form_submit);
  
// lemma notes
  $('form.lemma-notes-form').live('submit', lemma_notes_form_submit);
  $('#add_lemma_note form.lemma-notes-form').live('change', function(){
	  window.notesNotSaved = true;
  });
  $('form.lemma-notes-form').live('reset', function(){
	  window.notesNotSaved = false;
  });
  
// czasowniki podobne
  $('form.similar-lemmas-new-form').live('submit', similar_lemmas_new_form_submit);
  $('form.similar-lemmas-old-form').live('submit', similar_lemmas_old_form_submit);
  $('#similar-lemmas-show-synonyms').live('click', similar_lemmas_show_synonyms);
  $('#related-lemmas-show').live('click', related_lemmas_show);
  $('#reset-similar-button').live('click', similar_lemmas_reset);

  $('form.position-add-form').live('reset', function(){
	$(this).closest("$[id$='-dialog']").dialog('close');
    }); 
  $('form.argument-add-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
    });
  $('form.frame-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
    });
  $('form.pos-cat-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
    });
  $('form.frame-conversion-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
	});
  $('form.create-position-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
  });
  
  $('#add-table-elem-dialog').live('dialogclose', function(event) {
	  window.addedFrame = '';
	  $('#add-table-elem-dialog').data('selectedArgId', '');
	  $('#add-table-elem-dialog').data('selectedFrame', '');
  });
  
  $('form.nkjp-example-form').live('submit', nkjp_example_form_submit);
  $('button#nkjp-example-form-cancel').live('click', function(){
	    if(confirm("Czy jesteś pewien, że chcesz wyczyścić formularz dodawania przykładów?")){
	    	resetForm($('form.nkjp-example-form'));
	    }
  });
  
  $('form.semantic-example-form').live('submit', semantic_example_form_submit);
  $('button#semantic-example-form-cancel').live('click', function(){
	    if(confirm("Czy jesteś pewien, że chcesz wyczyścić formularz dodawania przykładów?")){
	    	resetForm($('form.semantic-example-form'));
	    }
  });
  
  $('form.lemma-example-form').live('submit', nkjp_lemma_example_form_submit);
  $('form.lemma-example-form').live('change', function(){
	  window.lemmaExNotSaved = true;
  });
  $('button#lemma-example-form-cancel').live('click', function(){
	    if(confirm("Czy jesteś pewien, że chcesz wyczyścić formularz dodawania przykładów?")){
	    	resetForm($('form.lemma-example-form'));
	    	window.lemmaExNotSaved = false;
	    }
  });

  $('form.position-add-form').live('submit', add_pos_form_submit);
  $('form.argument-add-form').live('submit', argument_form_submit);
  $('form.assign-phraseologic-frame-form').live('submit', assignPhraseologicFrameFormSubmit);
  $('form.assign-phraseologic-frame-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
  });
  
  $('form.create-position-form').live('submit', create_position_form_submit);
  
  $("[id^=id_value_positions_0], [id^=id_value_arguments_0], [id^=id_value_parameter_0]").live('change', function(event) {
	  arguments_form_change(-1, null, $(event.target).closest(".argument-add-form"), window.lemma_id)
  });
  $("[id^=id_arg_type]").live('change', function(event) {
	  arguments_form_change(0, null, $(event.target).closest(".argument-add-form"), window.lemma_id)
  });
  
  $("$[id$='-add_position_button']").live('click', function(event){openAddPositionDialog(event)});
  $("$[id$='-add_argument_button']").live('click', function(event){openAddArgumentDialog(event, window.lemma_id, 'Tworzenie typu frazy:')});
  $("$[id$='-add_realization_button']").live('click', function(event){openAddArgumentDialog(event, window.lemma_id, 'Tworzenie rozwinięcia typu frazy:')});
  $("$[id$='-select_argument_button']").live('click', function(event){openSelectArgumentDialog(event, window.lemma_id)});
  
  $('#id_propose_skladnica').live('change', show_skl_propositions);
  $('#id_propose_B').live('change', show_B_propositions);
  $('#skladnica-example-propositions-select').live('change', get_skladnica_example_and_fill_form);
  $('#xcp-example-propositions-select').live('change', get_xcp_example_and_fill_form);
  $('#realization-select').live('change', fill_frame_chars);
  
  $('form.example-opinion-form').live('submit', example_opinion_form_submit); 
  $('#add-aspect-rel-frames').live('click', add_aspect_rel_frames);
  
  $('#position #remove-position').live('click', remove_position);
  $('#argument #remove-argument').live('click', remove_argument);
  $('#position #edit-position').live('click', edit_position);
  $('#argument #edit-argument').live('click', edit_argument);
  $('#argument #edit-realization').live('click', edit_realization);
  
  $('#new-frame-tables').live('click', function(e) {
      e.stopPropagation();
      unselectTd(window.selected_id);
      window.selected_id = -1;
      unselectTd(selectedFrameIdNkjp);
      window.selectedArgumentsIdNkjp = new Array();
      $('#show_nkjp_table').empty();
      selectedFrameIdNkjp = -1;
      window.selected_example_id = -1;

      if (window.activeNewFramePanel == 'add_nkjp_example') {
    	  refresh_example_propositions();
      }
    });
  
  gridPreviewContent(false);
  
  $('.tabs').tabs().bind('tabsselect', function(event, ui) {
      if(ui.panel.id == 'preview_lemma')
      {
        setTimeout(function () {
          $(window).trigger('resize');
        }, 30);
        window.activeLemmaPanel = ui.panel.id;
        gridPreviewContent(true);
      }
      else if(ui.panel.id == 'new_frames')
      {
        setTimeout(function () {
          $(window).trigger('resize');
        }, 30);
        window.activeLemmaPanel = ui.panel.id;
        gridPreviewContent(false);
      }
      else if(ui.panel.id == 'semantics')
      {
        setTimeout(function () {
          $(window).trigger('resize');
        }, 30);
        window.activeLemmaPanel = ui.panel.id;
        gridPreviewContent(false);
      }
      else if( ui.panel.id == 'old_frames' || ui.panel.id == 'notes' || ui.panel.id == 'examples' || 
             ui.panel.id == 'change_ctrl' || ui.panel.id == 'status')
      {
        window.activeLemmaPanel = ui.panel.id;
        gridPreviewContent(false);
      }  
  });
  
  refresh_column_headers();
});