/*
Copyright (c) 2012, Bartłomiej Nitoń
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var main_field = ax_main_field,

initialColModel = [
  { 
    name: 'id', 
    index: 'id', 
    width: 70, 
    search: false, 
    hidden: true, 
    sortable :true,
  },
  {
    name: 'entry', 
    index: 'entry', 
    width: 200,
    sortable :true,
  },
  {
    name: 'owner',
    index: 'owner',
    sortable :true,
    //stype: 'select'
  },
  {
    name: 'vocabulary',
    index: 'vocabulary',
    hidden: true,
    sortable :true,
    //sortable: false,
    //searchoptions: lip_searchoptions
  },
  {
    name: 'status',
    index: 'status',
    sortable :true,
    //hidden: true,
    //sortable: false,
    //searchoptions: lip_searchoptions
  }
],
initialColNames = ['Id', 'Hasło','Właściciel', 'Słownik', 'Status'];

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.frames = new Array();
 var lemma_id = -1;
 var elem_in_bucket = '';
 //var frame_char_order = new Array();
 var aspect_vals = new Array();
 var reflex_vals = new Array();
 var filter_aspect_val = '_';
 var filter_reflex_val = '_';
 var prev_lemma_id = -1;

// te wartosci trzeba czyscic przy ladowaniu innego hasla
 var selected_id = -1;
 var edited_id = -1;
 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 draw_frames_filter(id)
{     
    var frame_filter = document.getElementById(id);
    var select = document.createElement('select');
    select.setAttribute('id', 'aspect_filter');
    select.setAttribute('name', 'ASPEKT');
    frame_filter.appendChild(select);
    for(var i=0; i<aspect_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', aspect_vals[i]);
      option.appendChild(document.createTextNode(aspect_vals[i]));
      select.appendChild(option);
    }

    select = document.createElement('select');
    select.setAttribute('id', 'reflex_filter');
    select.setAttribute('name', 'ZWROTNOSC');
    frame_filter.appendChild(select);
    for(var i=0; i<reflex_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', reflex_vals[i]);
      option.appendChild(document.createTextNode(reflex_vals[i]));
      select.appendChild(option);
    }

	if(id == 'frame_filter')
	{
      $('#frame_filter #aspect_filter').val(window.filter_aspect_val);
      $('#frame_filter #reflex_filter').val(window.filter_reflex_val);
	}    
}


function load_content(id) {

  $('#add-table-elem-dialog').dialog('close');
  if(lemma_id != id)
    $('#ready-note-dialog').dialog('close');
    
  
  if(window.activeLemmaPanel == 'preview_lemma')
  {   
    $('#preview_lemma').load(ajax_lemma_preview, 'id='+id+'&main_lemma_id='+window.lemma_id, function(){
       window.prev_lemma_id=id;
       createSplitter('prevFramesSplit', 'prev-lemma-tables', 'prev_tabs');
       //    
    });
  }
  else
  {
    // czyszczenie wartosci
    //window.can_modify = false;
    window.selected_notes_row_id = -1;
    window.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();
    change = false;
  
    $.get(ajax_note_session_get, function(result) {
      if(result['lemma_from_note_id'])
      {
        id = result['lemma_from_note_id'];
      }
      
      $('#old_frames').load(ajax_old_frames, 'id='+id);//+'&variant=1');
      $('#new_frames').load(ajax_new_frames, 'id='+id, function(){
        window.lemma_id = id;
        createSplitter('framesSplit','new-frame-tables', 'tabs');
        if(window.can_modify)
        {
          $(document).unbind('keydown');
          $(document).bind('keydown', 'shift+s', saveHandle);
          $(document).bind('keydown', 'shift+a', function(evt){addElement(); return false; });
          $(document).bind('keydown', 'shift+c', function(evt){copyElement(); return false; });
          $(document).bind('keydown', 'shift+r', function(evt){removeElement(); return false; });
          $(document).bind('keydown', 'shift+v', function(evt){pasteElement(); return false; });
          $(document).bind('keydown', 'shift+x', function(evt){cutElement(); return false; });
          $(document).bind('keydown', 'shift+d', function(evt){duplicateElement(); return false; });
          $(document).bind('keydown', 'shift+z', function(evt){backOneModification(); return false; });
          $(document).bind('keydown', 'shift+y', function(evt){forwardOneModification(); return false; });
          $(document).bind('keydown', 'shift+m', function(evt){reserveLemma(); return false; });
          $(document).bind('keydown', 'shift+w', function(evt){validate_new_frames(''); return false; });
        }
        else
        {
          $(document).unbind('keydown')
          $(document).bind('keydown', 'shift+m', function(evt){reserveLemma(); return false; });
        }
        
        window.frames_modif = new Array(); // UWAGA, przestawic do lemma-view
        window.frames_modif_idx = 0;
  		var lemma_version = new Lemma_Version(window.frames, window.nkjp_examples, window.nkjp_lemma_examples); // TO
  		frames_modif.push(lemma_version);
  		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)});
        }        
      });
      $('#change_ctrl').load(ajax_change_ctrl, 'id='+id);
      $('#examples').load(ajax_lemma_examples, 'id='+id, function(){
        window.frames_modif = new Array(); // UWAGA, przestawic do lemma-view
        window.frames_modif_idx = 0;
  		var lemma_version = new Lemma_Version(window.frames, window.nkjp_examples, window.nkjp_lemma_examples); // TO
  		frames_modif.push(lemma_version);
  		draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_')
        $("tr.NkjpLemmaTableRow").click(function(){
          selectLemmaNkjpTr(this.id)});
      });
      $('#status').load(ajax_lemma_status, 'id='+id);
      $('#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;
        createSplitter('prevFramesSplit', 'prev-lemma-tables', 'prev_tabs');
       //    
      });
      
    });
    $.get(ajax_note_session_clear);
  }
}

// klasa reprezentujaca versje hasla, do cofania i dodawania
function Lemma_Version(frames, nkjp_examples, nkjp_lemma_examples)
{
  	this.frames = $.evalJSON($.toJSON(frames)) //eval ( frames.toSource() );
  	this.nkjp_examples = $.evalJSON($.toJSON(nkjp_examples)) //eval ( nkjp_examples.toSource() );
  	this.nkjp_lemma_examples = $.evalJSON($.toJSON(nkjp_lemma_examples)) //eval ( nkjp_lemma_examples.toSource() );
}

 // argument class
function argument(id, text_rep, type)
{
  	this.id = id
  	this.text_rep = text_rep;
    this.type = type;
    this.error = false;
    //this.atributes = atributes; // many to many
}
  
 // 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;	
}
  
   // 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;
}  

function Nkjp_example(example_id, frame_id, arguments_ids, sentence, source, opinion, comment)
{
    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;
}

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

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', 'ChangeControlTable');
  table.setAttribute('id', 'nkjp_table');
  	
  var tr = document.createElement('tr');
  var 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
        {
          tr = document.createElement('tr');
          tr.setAttribute('class', row_class);
          tr.setAttribute('id', td_id+nkjp_examples[i].example_id);
          td = document.createElement('td');
          td.appendChild(document.createTextNode(nkjp_examples[i].sentence));
          tr.appendChild(td);
          td = document.createElement('td');
          td.appendChild(document.createTextNode(nkjp_examples[i].source));
          tr.appendChild(td);
          td = document.createElement('td');
          td.appendChild(document.createTextNode(nkjp_examples[i].opinion));
          tr.appendChild(td);
        /*  td = document.createElement('td');
          if(nkjp_examples[i].confirmed) // czy przyklad potwierdzono (jesli trzeba)
            td.appendChild(document.createTextNode('TAK'));
          else
            td.appendChild(document.createTextNode('NIE'));
          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);
  	}	 
  	
    //selectTd(nkjpInstance.frame_id);
    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');
  	needConfirmation(nkjpInstance);
  }
}

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,
      },

    callback: function(result) {   
      if(nkjpInstance.frame_id) // przyklad dodany do ramki
        $("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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      HideProgressAnimation();
      return true;
    },
  });
  return false;
}

function needConfirmation(nkjpInstance) {
   // ShowProgressAnimation();

    $.ajaxJSON({
      method: 'post',
      url: ajax_can_confirm_example,
      data: {
        example_id: nkjpInstance.example_id,
      },

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

function unpin_nkjp_example(example_tabId)
{ 
  if(example_tabId != -1)
  {
    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 ramki 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 z ramkami
          draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
          $("#new-frame-tables td").click(function(e){
            e.stopPropagation();
            selectTd(this.id)});
          $("#new-frame-tables td").dblclick(function(e){
            e.stopPropagation();
            openEditForm(this.id)});
      // 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.frames, window.nkjp_examples, window.nkjp_lemma_examples);
          window.frames_modif.push(lemma_version);
          window.frames_modif_idx++;
          change = true;
        }
        break;
      }
    }
  }
}

// sprawdza czy ramka nie posiada dolaczonego przykladu
function gotAssignedExample(nkjp_examples, element_id, deleteAction)
{
  var id_map = parseId(element_id);
  var frame_id = 'frame_'+id_map['frame_id']+'_';
  var examplesRemoved = false;
  var exampleFound = false;
  
  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)
          {
            exampleFound = true;
            if(confirmed || confirm("Argument posiada dowiązane przykłady. Czy mają one zostać dodane do przykładów niedowiązanych?")){
              confirmed = true;
              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--;
              examplesRemoved = true;
              i--; // bo usunieto przyklad, a na jego miejsce wskoczyl nastepny w kolejnosci
              break;
            }
          //  return false;
          }
        }
      }
    }
    if(examplesRemoved || !exampleFound)
    {
      draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
      $("tr.NkjpLemmaTableRow").click(function(){
        selectLemmaNkjpTr(this.id)});
      return false;
    }   
    else
    {
      return true;
    } 
  }
  else if(id_map['arg_id'] && !deleteAction) // okazuje sie, ze jednak mozna modyfikowac argumenty do ktorych dodano przyklady
  {
    var arg_id = 'frame_'+id_map['frame_id']+'_pos_'+id_map['pos_id']+'_arg_'+id_map['arg_id']+'_';
    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)
          {
            alert('Działaj rozważnie, do modyfikowanego argumentu przyporządkowany jest przykład.')
            return false;
          }
        }
      }
    }
  }
  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)
        {
          //return true;
          exampleFound = true;
          if(confirmed || confirm("Ramka zawiera dowiązane przykłady. Czy mają one zostać dodane do przykładów niedowiązanych?")){
            confirmed = true;
            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--;
            examplesRemoved = true;
            i--;
          }
        }
      }
      if(examplesRemoved || !exampleFound)
      {
        draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
        $("tr.NkjpLemmaTableRow").click(function(){
          selectLemmaNkjpTr(this.id)});
        return false;
      }
      else
      {
        return true;
      }        
    }    
    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))
          {
            exampleFound = true;
            //return true;
            if(confirmed || confirm("Pozycja zawiera dowiązane przykłady. Czy mają one zostać dodane do przykładów niedowiązanych?")){
              confirmed = true;
              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--;
              examplesRemoved = true;
              i--;
              break;
            }
          }
        }
      }
      if(examplesRemoved || !exampleFound)
      {
        draw_nkjp_table(document.getElementById("lemma_example_show"), '', window.nkjp_lemma_examples, 'NkjpLemmaTableRow', 'nkjpLemma_');
        $("tr.NkjpLemmaTableRow").click(function(){
          selectLemmaNkjpTr(this.id)});
        return false;
      }
      else
      {
        return true;
	  }      
      
    }
  }
  
  return false;
}

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 draw_frames(frames, parent, table_name, nkjp_examples, table_class, lemma_entry)
{
  $(parent).empty();
  window.selectedArgumentsIdNkjp = new Array();
  //window.selectedFrameIdNkjp = -1; // TUTAJ

  for(var i=0; i<window.reflex_vals.length; i++)
  {
    for(var k=0; k<window.aspect_vals.length; k++)
    {
      first = true;
      for(var j=0; j<frames.length; j++)
      {
        if(frames[j].characteristics[0]==aspect_vals[k] && frames[j].characteristics[1]==reflex_vals[i])
        {
          if(first)
          {
            div = document.createElement('div');
            strong = document.createElement('strong');
            if(reflex_vals[i])
  	          strong.appendChild(document.createTextNode(lemma_entry+" "+reflex_vals[i]+" "+"("+aspect_vals[k]+"):"));
  	        else
  	          strong.appendChild(document.createTextNode(lemma_entry+" "+"("+aspect_vals[k]+"):"));
  	        div.appendChild(strong);
  	        parent.appendChild(div);
            first = false;
          }
          var rows = frameToTableRows(frames[j]);
          if(gotAssignedExampleId(nkjp_examples, frames[j].id) && 
            wholeCoordinationSpecified(frames[j], nkjp_examples))
            draw_table(parent, frames[j], rows, table_name, table_class+'ExComp');
          else if(gotAssignedExampleId(nkjp_examples, frames[j].id))
            draw_table(parent, frames[j], rows, table_name, table_class+'Ex');
          else
            draw_table(parent, frames[j], rows, table_name, table_class);
        }
      }
    }
  }
}


function draw_table(parent, frame, rows, table_id, table_class)
{
  	var frame_table_container = parent;
  	frame_error = false;
  	var table = document.createElement('table');
  	table.setAttribute('class', table_class);
  	table.setAttribute('id', table_id);
  	 
  	frame_table_container.appendChild(table);
  	
  	// wiersz opisujacy opinie na temat ram
  	var tr = document.createElement('tr'); // poczatek pierwszego wiersza
  	var td = document.createElement('td');
  	td.setAttribute('class', 'ColumnHeader');
  	td.appendChild(document.createTextNode("Ocena ramy:"));
  	tr.appendChild(td);
  	 // pole z wartosciami cech ramy
  	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;'); 
  	}
  	
  	span_op = document.createElement('span');
  	span_op.setAttribute('class', 'Opinion');
  	span_op.appendChild(document.createTextNode(frame.opinion));
  	td.appendChild(span_op);
  	span_img = document.createElement('span');
  	span_img.setAttribute('class', 'Check');
  	td.appendChild(span_img);
  	tr.appendChild(td);
  	table.appendChild(tr);// koniec pierwszego wiersza
  	
  	// wiersz opisujacy kategorie pozycji
  	tr = document.createElement('tr');
  	td = document.createElement('td');
  	td.setAttribute('class', 'ColumnHeader');
  	td.appendChild(document.createTextNode("Kategoria:"));
  	tr.appendChild(td);
  	
  	// pola z wartosciami kategorii ram
  	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;');
  	  }
  	  td.appendChild(document.createTextNode(position.categories.join(',')));
  	  tr.appendChild(td);
  	}
  	table.appendChild(tr); // koniec wiersza opisujacego kategorie pozycji
  	
  	// wiersze opisujace argumenty w pozycjach
  	tr = document.createElement('tr'); 
  	td = document.createElement('td');
  	td.setAttribute('rowspan', rows[1][1]);
  	td.setAttribute('class', 'ColumnHeader');
  	td.appendChild(document.createTextNode("Argumenty:"));
  	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 || error_col == col || frame_error)
  	    {
  	      td.setAttribute('style', 'background-color:red;');
  	    }
  	    
  	    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($(window).height() - $('#main_menu').height()- 80);

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

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


 String.prototype.startsWith = function(str)
 {return (this.match("^"+str)==str)}
 
 String.prototype.trim = function()
 {return (this.replace(/^\s+|\s+$/g, ''))}
 
 function argument_form_submit() {
    ShowProgressAnimation()
    this_form = $('.argument-add-form');
    form_data = this_form.serializeArray();
      
    type = ''
    values = [];
   // nested_values = [];
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'arg_model_name' && elem.name != 'atr_value')
      //  && elem.name != 'nested_value')
        return elem;
      else {
        if (elem.name == 'arg_model_name')
          type = elem.value.trim();
        else if (elem.name == 'atr_value')
          values.push(elem.value.trim());
      //  else if (elem.name == 'nested_value')
      //    nested_values.push(elem.value.trim());
      }
    });
  
    form_data.push({name: 'arg_model_name', value: type});
    form_data.push({name: 'atr_values', value: values});
    //form_data.push({name: 'nested_values', value: nested_values});

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

    callback: function(result) {      
      var arg = new argument(result["id"], result["text_rep"], result["type"]);
      
      // dodawanie argumentow
      if($('#add-table-elem-dialog').dialog( "option" , "title").startsWith("Dodawanie"))
      {
        selected_pos = getElementInstance(selected_id, frames);
        selected_pos['element'].arguments.push(arg);
        window.selected_id = -1;
      }
      else // edycja argumentow
      {
        edited_arg = getElementInstance(edited_id, frames);
        edited_arg['element'].id = arg.id;
        edited_arg['element'].text_rep = arg.text_rep;
        edited_arg['element'].type = arg.type;
          
        // przepisywanie przykladow ze starej instancji argumentu na nowa
        var ids = parseId(edited_id);
        var frame_tabId = 'frame_'+ids['frame_id']+'_';
        var arg_tabId = 'arg_'+ids['arg_id']+'_';
        var new_arg_tabId = 'arg_'+arg.id+'_';
        
        // podmienianie identyfikatorow argumentow na rzecz przypisywania do nich przykladow
        
        if(window.selectedFrameIdNkjp == frame_tabId && window.selectedArgumentsIdNkjp.indexOf(arg_tabId) != -1)
          window.selectedArgumentsIdNkjp = window.selectedArgumentsIdNkjp.replace(arg_tabId, new_arg_tabId)  
        
        for(var i=0; i<window.nkjp_examples.length; i++)
        {
          if(window.nkjp_examples[i].frame_id == frame_tabId)
          {
            for(var j=0; j<window.nkjp_examples[i].arguments_ids.length; j++)
            {
              if(window.nkjp_examples[i].arguments_ids[j] == edited_id)
              {
                window.nkjp_examples[i].arguments_ids[j] = window.nkjp_examples[i].arguments_ids[j].replace(arg_tabId, new_arg_tabId);
              }
            }
          }
        }
      }
      
      //$('table#new-frame-table').remove();     
      $('#add-table-elem-dialog').dialog('close'); 
      
     // var parent = document.getElementById("new-frame-tables");
     // draw_frames(frames, parent, 'new-frame-table');
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
  
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
       
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);     
      var lemma_version = new Lemma_Version(frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'empty fields error') {
        HideProgressAnimation();
        error_alert('Wypełnij wszystkie pola formularza.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function show_argument_realizations()
{
    ShowProgressAnimation();
    this_form = $('.argument-add-form');
    form_data = this_form.serializeArray();
      
    type = ''
    values = [];
    
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'arg_model_name' && elem.name != 'atr_value') 
        return elem;
      else {
        if (elem.name == 'arg_model_name')
          type = elem.value;
        else if (elem.name == 'atr_value')
          values.push(elem.value);
      }
    });
      
    form_data.push({name: 'arg_model_name', value: type});
    form_data.push({name: 'atr_values', value: values});
    form_data.push({name: 'manage', value: false});
    
    data = JSON.stringify(form_data)
    $('#realizations').load(ajax_show_realizations, "form_data="+data, function(){
      HideProgressAnimation();
    });
    
    return false;
}


function argument_model_change()
{
  arguments_form_change(true, '')
}

function atribute_value_change()
{
  //arguments_form_change(false, '')
}

function arguments_form_change(arg_model_change, arg_text_rep) {
    this_form = $('.argument-add-form');
    form_data = this_form.serializeArray();
      
    type = ''
    values = [];
    //nested_values = [];
  
  	if(!arg_text_rep)
  	{
      form_data = $.map(form_data, function(elem)
      {
        if (elem.name != 'arg_model_name' && elem.name != 'atr_value') 
       //   && elem.name != 'nested_value')
          return elem;
        else {
          if (elem.name == 'arg_model_name')
            type = elem.value;
          else if (elem.name == 'atr_value')
            values.push(elem.value);
       //   else if (elem.name == 'nested_value')
       //     nested_values.push(elem.value);
        }
      });
      
      form_data.push({name: 'arg_model_name', value: type});
      form_data.push({name: 'atr_values', value: values});
    //  form_data.push({name: 'nested_values', value: nested_values});
    
      if(arg_model_change)
        form_data.push({name: 'arg_model_change', value: 'arg_model_changed'});
      else
        form_data.push({name: 'arg_model_change', value: ''});
      
      form_data.push({name: 'arg_text_rep', value: ''});
    }
    else
      form_data.push({name: 'arg_text_rep', value: arg_text_rep});
    
    data = JSON.stringify(form_data)
    
    $('#add-table-elem-dialog').load(ajax_argument_form, "form_data="+data);
} 

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 = result["id"];
      //if(pos_id == -1)
      pos_id = new_elem_id;
      new_elem_id--;
      
      //var pos = new position(pos_id, result["text_rep"], cats, arguments);
      var pos = $.evalJSON($.toJSON(window.emptyPosition)) //eval ( window.emptyPosition.toSource() );
      pos.id = pos_id;
      pos.text_rep = result["text_rep"];
      pos.categories = cats;
      pos.arguments = arguments;
      
      frames = addFramePosition(selected_id, frames, pos);
      window.selected_id = -1;
      
      //var parent = document.getElementById("new-frame-tables");
      //$('table#new-frame-table').remove();
      
      $('#add-table-elem-dialog').dialog('close');
      //draw_frames(frames, parent, 'new-frame-table');
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
         
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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, frames)
{    
  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<frames.length; i++)
    {
      if(frames[i].id == frame_id && pos_id)
      {
        for(var j=0; j<frames[i].positions.length; j++)
        {
          if(frames[i].positions[j].id == pos_id && arg_id)
          {
          	return frames;
          }
          else if(frames[i].positions[j].id == pos_id)
          {
              // dodawanie argumentu do pozycji
            $('#add-table-elem-dialog').load(ajax_argument_form, "form_data=").dialog( "option", "title", "Dodawanie argumentu:" ).dialog('open');   
            new_elem_id--; 
            return window.frames;
          }
        }
      }
      else if(frames[i].id == frame_id) // dodawanie pozycji do ramki
      {
        // nowa pozycja
        $('#add-table-elem-dialog').load(ajax_position_form).dialog( "option", "title", "Dodawanie pozycji:" ).dialog('open');       
        new_elem_id--;    
        return window.frames;
      }
    }
  }
  //frame(id, text_rep, characteristics, positions, opinion)
  else // dodawanie nowej pustej ramki
  { 
    //window.addedFrame = new frame(new_elem_id, '', ['_', '_'], new Array(), '');
    window.addedFrame = $.evalJSON($.toJSON(window.emptyFrame)) //eval ( window.emptyFrame.toSource() );
    window.addedFrame.id = new_elem_id;
    form_data = new Array();
  	    //form_data.push({name: 'lemma_id', value: lemma_id});
  	form_data.push({name: 'opinion', value: window.addedFrame.opinion});
  	form_data.push({name: 'characteristics', value: window.addedFrame.characteristics});  
    data = JSON.stringify(form_data);   
    $('#add-table-elem-dialog').load(ajax_frame_form, "form_data="+data).dialog( "option", "title", "Dodawanie nowej ramki:" ).dialog('open');
    new_elem_id--;
    return window.frames;
  }
  return frames;
}
  
function openEditForm(id)
{   
    if(!gotAssignedExample(nkjp_examples, id, false))
    {
      elemInstance = getElementInstance(id, frames);
  	  window.edited_id = id;
  	  	  
  	  if(elemInstance['type'] == 'frame')
  	  {
  	    form_data = new Array();
  	    //form_data.push({name: 'lemma_id', value: lemma_id});
  	    form_data.push({name: 'opinion', value: elemInstance['element'].opinion});
  	    form_data.push({name: 'characteristics', value: elemInstance['element'].characteristics});  
        data = JSON.stringify(form_data)

  	    $('#add-table-elem-dialog').load(ajax_frame_form, "form_data="+data).dialog( "option", "title", "Edycja cech ramki:" ).dialog('open');
  	  //frame_form_change(false, elemInstance['element'].text_rep);
  	  }
  	  else if(elemInstance['type'] == 'position')
  	  {
  	    form_data = new Array();
  	    //form_data.push({name: 'lemma_id', value: lemma_id});
  	    form_data.push({name: 'categories', value: elemInstance['element'].categories});   
        data = JSON.stringify(form_data)
    
  	    $('#add-table-elem-dialog').load(ajax_pos_cat_form, "form_data="+data).dialog( "option", "title", "Edycja kategorii pozycji:" ).dialog('open'); 
  	  }
  	  else if(elemInstance['type'] == 'argument')
  	  {
  	    $('#add-table-elem-dialog').dialog( "option", "title", "Edycja argumentu:" ).dialog('open');
  	    arguments_form_change(false, elemInstance['element'].text_rep);
  	  }
    }  
}

// 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, frames);
      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], frames);
	      argument_selections[k].arguments.push(argInstance['element']);
	    }
	  }         
    }   
    frame = getElementInstance(nkjp_example.frame_id, frames);
         
    var convertedExample = new Nkjp_example_ajax(frame['element'], argument_selections, nkjp_example.sentence, nkjp_example.source, nkjp_example.opinion, nkjp_example.comment);
       
    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)
        {
         // rel_tmp_arguments = 
          
          
          for(var k=0; k<window.nkjp_examples[i].arguments_ids.length; k++)
          {
           // rel_tmp_arguments = findRelatedArguments(window.nkjp_examples[i].arguments_ids[k], frame_id, nkjp_examples)
            relatedArguments.push(window.nkjp_examples[i].arguments_ids[k])
           // relatedArguments.push(rel_tmp_arguments)
            
          }
          break;
        }
      }
    }
  } 
  return relatedArguments; 
}

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


function save_new_frames() {
  ShowProgressAnimation();
  $('#save').attr("disabled", true);

    data = JSON.stringify(frames);
    
	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_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 (ctrl)
      //  ctrl.remove();
      if (result == 'concurrent access') {
        HideProgressAnimation();
        error_alert('Hasło jest w tej chwili zapisywane przez kogoś innego.');
        $('#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);
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      //if (ctrl)
      //  ctrl.remove();
    },
  });
  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 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);
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'aspect' && elem.name != 'frame_opinion'
         && elem.name != 'reflex')
        return elem;
      else {
        if (elem.name == 'aspect')
          aspect = elem.value;
        else if (elem.name == 'reflex')
          reflex = elem.value;
        else if (elem.name == 'frame_opinion')
          frame_opinion = elem.value;
      }
    });
    
    if(window.addedFrame)
    {
      frame = JSON.stringify(window.addedFrame);
    }
    else 
    {
      elemInstance = getElementInstance(window.edited_id, frames);
      frame = JSON.stringify(elemInstance['element']);
    }

	form_data.push({name: 'aspect', value: aspect});
	form_data.push({name: 'reflex', value: reflex});
    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});

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

    callback: function(result) {    
      old_edited_frame_id =  ''; 
      if(window.addedFrame)
      {
        edited_frame = $.evalJSON($.toJSON(window.addedFrame)) //eval ( window.addedFrame.toSource() );
        
        edited_frame.id = window.addedFrame.id;
        edited_frame.text_rep = result['text_rep'];
        edited_frame.characteristics = result['characteristics'];
        edited_frame.opinion = result['opinion'];
        window.frames.push(edited_frame);
        window.addedFrame = '';
        changeFrameExamplesIds(window.nkjp_examples, old_edited_frame_id, result['id']);
      }
      else
      {
        edited_frame = getElementInstance(edited_id, frames);
        old_edited_frame_id = edited_frame['element'].id;
        //edited_frame['element'].id = result['id'];
        edited_frame['element'].id = new_elem_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);
      }      
      
      //var parent = document.getElementById("new-frame-tables");
      //$('table#new-frame-table').remove();
      
      $('#add-table-elem-dialog').dialog('close'); 
      
      //draw_frames(frames, parent, 'new-frame-table');
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);   

      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
       
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'empty fields error') {
        HideProgressAnimation();
        error_alert('Wypełnij wszystkie pola formularza.');
        return false;
      }  
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function pos_cat_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);
    form_data = this_form.serializeArray();
  
    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 = elem.value;
      }
    });
    
	elemInstance = getElementInstance(window.edited_id, frames);
    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, frames);
      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'];
   // TUTAJ
      changePosExamplesIds(window.nkjp_examples, frame_id, edited_old_pos_id, result['id']);
     // changePosExamplesIds(window.nkjp_examples, frame_id, result['id']);
      //var parent = document.getElementById("new-frame-tables");
     // $('table#new-frame-table').remove();
      
      
      $('#add-table-elem-dialog').dialog('close'); 
      //draw_frames(frames, parent, 'new-frame-table');   
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    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;
  
    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;

	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});

    $.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']);
        HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'required fields not selected') {
        HideProgressAnimation();
        error_alert('Należy wypełnić temat oraz treść wiadomości.');
        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) {
         // grid.trigger("reloadGrid");
          
          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);
      //if (ctrl)
      //  ctrl.remove();
        },
      }); 
  	  
  	  //fill_nkjp_example_form(nkjpInstance, '.lemma-example-form');
  	}
}

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

function nkjp_lemma_example_form_submit() {
    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']); 
      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.frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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_reset() {
          ShowProgressAnimation();
  	      $.ajaxJSON({
            method: 'post',
            url: ajax_similar_lemmas_reset,
            data: {
              //change_type: change_type, 
              //lemma_id: lemma_id    // obecnie ustawione haslo
            },

            callback: function(result) {
              grid.trigger("reloadGrid");
              HideProgressAnimation();	
            },
    
            error_callback: function(xhr, status, error) {
              HideProgressAnimation();
              error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
            },
          });
      return false;
}

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

function nkjp_example_form_submit() {
    ShowProgressAnimation();
	if(window.selectedArgumentsIdNkjp.length == 0)
	{
	  HideProgressAnimation();
	  error_alert('Wybierz przynajmniej jeden argument, 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;
      }
    });

	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']); 
        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']); 
        window.nkjp_examples.push(nkjp_example);
        window.curr_example_id--;
      }

      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      window.selectedArgumentsIdNkjp = new Array();
      window.selectedFrameIdNkjp = -1;
      
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);     
      var lemma_version = new Lemma_Version(frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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 serializedObjToObj(serialized_frames)
 {
    var serFrames = eval('(' + serialized_frames + ')');
    return serFrames;
 }
 
// function jsonEscape(str)  {
//    return str.replace(/\\n/g, "\\\\n").replace(/\\r/g, "\\\\r").replace(/\\t/g, "\\\\t");
//}
 
 
 function serializedNkjpToObj(serialized_nkjp_examples)
 {
   // alert(serialized_nkjp_examples)
   // serialized_nkjp_examples = serialized_nkjp_examples.replace(/\n/g, "\\\\n");
   // serialized_nkjp_examples = serialized_nkjp_examples.replace(/\\n/g, "\\\\n"); 
   // alert(serialized_nkjp_examples)
   //alert(serialized_nkjp_examples)
   //alert(jsonEscape(serialized_nkjp_examples))
   //var serNkjpExamples = eval('(' + jsonEscape(serialized_nkjp_examples) + ')');
    var serNkjpExamples = eval('(' + serialized_nkjp_examples + ')');
    
    //for(var i=0; i<serNkjpExamples.length; i++)
    //{
    //  serNkjpExamples[i].sentence = serNkjpExamples[i].sentence.replace(/-cudzyslow-/g, "\"")
    //  serNkjpExamples[i].comment = serNkjpExamples[i].comment.replace(/-cudzyslow-/g, "\"")
   // }
    
    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, frames)
{
    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<frames.length; i++)
      {
        if(frames[i].id == frame_id && pos_id)
        {
          for(var j=0; j<frames[i].positions.length; j++)
          {
            if(frames[i].positions[j].id == pos_id && arg_id)
            {
          	  for(var k=0; k<frames[i].positions[j].arguments.length; k++)
          	  {
          	    if(frames[i].positions[j].arguments[k].id == arg_id)
          	    {
          	      frames[i].positions[j].arguments.splice(k, 1);
          	      if(frames[i].positions[j].arguments.length == 0)
          	      {
          	        //frames[i].positions.splice(j, 1);
          	        break;
          	      }
          	    }
          	  }
            }
            else if(frames[i].positions[j].id == pos_id)
              frames[i].positions.splice(j, 1);
          }
        }
        else if(frames[i].id == frame_id)
        {
          frames.splice(i, 1); // takie usuwanie nie zostawia dziury w tabeli  
        }
      }
      selected_id=-1;
    }
    return frames;
}

function addFramePosition(id, frames, 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<frames.length; i++)
      {
        if(frames[i].id == frame_id && pos_id)
        {
		  return frames;
        }
        else if(frames[i].id == frame_id) // dodawanie pozycji do ramki
        {
        // nowa pozycja
          frames[i].positions.push(position); 
        }
      }
    }
    return frames;
}

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

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, frames);
  	  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, frames);
  	  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);
  	          //unselectTd(id);
  	          $(argElem).css("background-color", "");
  	          alreadySelected = true;
  	          break;
  	        }
  	      }
  	      if(!alreadySelected)
  	      {
  	        $(argElem).css("background-color", "LightSteelBlue");
  	        window.selectedArgumentsIdNkjp.push(id);
  	      }
  	    }
  	  }
  	}
}

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, frames)
{
    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<frames.length; i++)
      {
        if(frames[i].id == frame_id && pos_id)
        {
          for(var j=0; j<frames[i].positions.length; j++)
          {
            if(frames[i].positions[j].id == pos_id && arg_id)
            {
          	  for(var k=0; k<frames[i].positions[j].arguments.length; k++)
          	  {
          	    if(frames[i].positions[j].arguments[k].id == arg_id)
          	    {
          	      //frames[i].positions[j].arguments.splice(k, 1);
          	      return {'element': frames[i].positions[j].arguments[k],
          	              'type': 'argument'};
          	    }
          	  }
            }
            else if(frames[i].positions[j].id == pos_id)
            { // position
              return {'element': frames[i].positions[j],
          	          'type': 'position'};
            }
          }
        }
        else if(frames[i].id == frame_id)
        { // frame
          return {'element': frames[i],
          	      'type': 'frame'};
        }
      }
      selected_id=-1;
    }
    return {};
}

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

function filter_frames(frames, filter_id)
{
  var aspect_val = $('#'+filter_id+' #aspect_filter').val();
  var reflex_val = $('#'+filter_id+' #reflex_filter').val();
  var filtered_frames = new Array();
  
  for(var i=0; i<frames.length; i++)
  {
    if((frames[i].characteristics[0] == aspect_val || aspect_val == '_') 
      && (frames[i].characteristics[1] == reflex_val || reflex_val == '_'))
      filtered_frames.push(frames[i]);
  }
  
  return filtered_frames; 
}

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

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

function lemma_status_change(change_type) {
  ShowProgressAnimation();

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

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

    callback: function(result) {
      if(result['changed'])
      {
        if (change_type == 'ready')
        {
          topic = 'Hasło gotowe'; 
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic).dialog({width: 'auto', height: 'auto', modal: 'true', title: "Dodawanie uwag na temat gotowości hasła:"}).dialog('open');
        }
        else if (change_type == 'confirm')
        {
          topic = 'Hasło zatwierdzone'; 
          $('#ready-note-dialog').load(ajax_lemma_note_form, "topic="+topic).dialog({width: 'auto', height: 'auto', modal: 'true', 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('scrollAndSet', selectedRow, rowIndex, recordsCount);
              grid.jqGrid('scrollToRow', rowIndex, recordsCount);
            }
          });
        load_content(result['lemma_id']);
      }		
      HideProgressAnimation();
    },
    
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
  });
  return false;
}

/////////////////FUNKJE KLAWISZE/PRZYCISKOW MODYFIKACJI////////////////////////
  function pasteFrameElement(id, copy_elem, frames)
  {
    var target_elem = ''
    if(id != -1)
      target_elem = getElementInstance(id, frames);  
    var to_copy_elem = copy_elem;
    
        // kopiowanie ramki do hasla
    if(!target_elem && 
        to_copy_elem['type'] == 'frame')
    {
      var frame = $.evalJSON($.toJSON(to_copy_elem['element'])) //eval(to_copy_elem['element'].toSource());
      frame.id = new_elem_id;
      new_elem_id--;
      window.frames.push(frame);
    }
    else
    {
     // kopiowanie argumentu do pozycji
      if(target_elem['type'] == 'position' && 
          to_copy_elem['type'] == 'argument')
      {
        var argument = $.evalJSON($.toJSON(to_copy_elem['element'])) //eval(to_copy_elem['element'].toSource());
        argument.id = new_elem_id;
        new_elem_id--;
        target_elem['element'].arguments.push(argument);
      }
    // kopiowanie pozycji do ramki
      else if(target_elem['type'] == 'frame' && 
          to_copy_elem['type'] == 'position')
      {
        var position = $.evalJSON($.toJSON(to_copy_elem['element'])) //eval(to_copy_elem['element'].toSource());
        position.id = new_elem_id;
        new_elem_id--;
        target_elem['element'].positions.push(position);
      }
    }
    
    return frames;  
  }
  
  function removeElement()
  {
  	//var parent = document.getElementById("new-frame-tables");
    if(selected_id != -1 && !gotAssignedExample(nkjp_examples, selected_id, true)) 
    {
     // $('table#new-frame-table').remove();
      frames = removeFrameElement(selected_id, frames);	
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
         
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(frames, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
      change = true;
    }
  }
  
  function addElement()
  {  
    if(selected_id!=-1 && !gotAssignedExample(nkjp_examples, selected_id, false))
      frames = addFrameElementDialog(selected_id, frames);
    else if(selected_id==-1)
      frames = addFrameElementDialog(selected_id, frames);
  }
  
  function copyElement()
  {
     //window.copy_elem_id = window.selected_id;
     if(window.activeLemmaPanel == 'preview_lemma')
     {
       elem_in_bucket = getElementInstance(window.selected_id, prev_frames);
       unselectPrevTd(window.selected_id);
       unselectTd(window.selected_id);
     }
     else
     {
       elem_in_bucket = getElementInstance(window.selected_id, frames);
       unselectTd(window.selected_id);
       unselectPrevTd(window.selected_id);
     }   
     window.selected_id = -1;
  }

  function pasteElement()
  {
   if(selected_id != -1 && !gotAssignedExample(nkjp_examples, selected_id, false))
   {
     frames = pasteFrameElement(selected_id, elem_in_bucket, frames);
     draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
        
     $("#new-frame-tables td").click(function(e){
       e.stopPropagation();
       selectTd(this.id)});
     $("#new-frame-tables td").dblclick(function(e){
       e.stopPropagation();
       openEditForm(this.id)});
       
     frames_modif = frames_modif.slice(0, frames_modif_idx+1);
     var lemma_version = new Lemma_Version(frames, window.nkjp_examples, window.nkjp_lemma_examples);
     frames_modif.push(lemma_version);
     frames_modif_idx++;
     selected_id = -1;
     change = true;
   }
   else if(selected_id == -1)
   {
     frames = pasteFrameElement(selected_id, elem_in_bucket, frames);
     draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
        
     $("#new-frame-tables td").click(function(e){
       e.stopPropagation();
       selectTd(this.id)});
     $("#new-frame-tables td").dblclick(function(e){
       e.stopPropagation();
       openEditForm(this.id)});
       
     frames_modif = frames_modif.slice(0, frames_modif_idx+1);
     var lemma_version = new Lemma_Version(frames, window.nkjp_examples, window.nkjp_lemma_examples);
     frames_modif.push(lemma_version);
     frames_modif_idx++;
     selected_id = -1;
     change = true;
   }
  }
  
  function cutElement()
  {
    if(selected_id != -1 && !gotAssignedExample(nkjp_examples, selected_id, true)) 
    {
      elem_in_bucket = getElementInstance(selected_id, frames);
      var elem_to_remove = elem_in_bucket['element'];
      var elem_to_copy = $.evalJSON($.toJSON(elem_in_bucket['element'])); //eval(elem_in_bucket['element'].toSource());
      elem_in_bucket['element'] = elem_to_copy;
    
    // remove
      removeElement();
    }
  }
  
  function duplicateElement()
  {
    if(selected_id != -1 && !gotAssignedExample(nkjp_examples, selected_id, false)) 
    {
      elem_in_bucket = getElementInstance(selected_id, frames);
      var parent_elem = getParentInstance(selected_id, frames);
      var duplicate = $.evalJSON($.toJSON(elem_in_bucket['element'])); //eval(elem_in_bucket['element'].toSource());
      duplicate.id = new_elem_id;
      new_elem_id--;
      
      if(parent_elem['type']=='lemma')
        frames.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);

      draw_filtered_frames(frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
         
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
        
      frames_modif = frames_modif.slice(0, frames_modif_idx+1);
      var lemma_version = new Lemma_Version(frames, window.nkjp_examples, window.nkjp_lemma_examples);
      frames_modif.push(lemma_version);
      frames_modif_idx++;
       
      selected_id = -1;
      change = true;
    }
  }
  
  function backOneModification()
  {
    if(window.frames_modif_idx>0)
    {
      window.frames_modif_idx--;
       
      var lemma_version = window.frames_modif[window.frames_modif_idx]; 
      window.frames = lemma_version.frames;
      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)});
      
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      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.frames = lemma_version.frames;
      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)});
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      // 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)});
         
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      selected_id = -1;
    }	
  }

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

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

// WALIDACJA 1: Rama nie moĂ„Ä…Ă„Ëťe zawieraÄ‚â€žĂ˘â‚¬Ë‡ dwĂ„â€šÄąâ€šch argumentĂ„â€šÄąâ€šw tego samego typu, 
	        //  z takimi samymi wartoĂ„Ä…Ă˘â‚¬Ĺźciami atrybutĂ„â€šÄąâ€šw, w jednej pozycji.
function pass_walidate1(frames)
{
  for(var i=0; i<frames.length; i++)
  {
    for(var j=0; j<frames[i].positions.length; j++)
    {
      for(var k=0; k<frames[i].positions[j].arguments.length; k++)
      {
        for(var l=k+1; l<frames[i].positions[j].arguments.length; l++)
        {
          if(frames[i].positions[j].arguments[l].text_rep == frames[i].positions[j].arguments[k].text_rep)
          {
            frames[i].positions[j].arguments[k].error = true;
            return false;
          }
        }
      }
    }
  }
  return true;
}

// WALIDACJA 2: Rama nie moze zawierac dwoch identycznych pozycji. 
/*function pass_walidate2(frames)
{
  for(var i=0; i<frames.length; i++)
  {
    for(var j=0; j<frames[i].positions.length; j++)
    {
       var arg_str_array = new Array()
       for(var k=0; k<frames[i].positions[j].arguments.length; k++)
       {
         arg_str_array.push(frames[i].positions[j].arguments[k].text_rep)
       }
       arg_str_array.sort();
       argument_str = arg_str_array.join(',');
       pos_cat_str = frames[i].positions[j].categories.join(',');
       frames[i].positions[j].text_rep = pos_cat_str+'{'+argument_str+'}';
    }
    for(var k=0; k<frames[i].positions.length; k++)
    {
      for(var l=k+1; l<frames[i].positions.length; l++)
      {
        if(frames[i].positions[l].text_rep == frames[i].positions[k].text_rep)
        {
          frames[i].positions[k].error = true;
          for(var m=0; m<frames[i].positions[k].arguments.length; m++)
            frames[i].positions[k].arguments[m].error = true;
          return false;
        }
      }
    }
  }
  return true;
}*/

// WALIDACJA 3: HasĂ„Ä…Ă˘â‚¬Ĺˇo nie moze zawierac dwoch identycznych ram. 
function pass_walidate3(frames)
{
  for(var i=0; i<frames.length; i++)
  {
    positions_text_rep_tab = new Array();
    for(var j=0; j<frames[i].positions.length; j++)
    {
       var arg_str_array = new Array()
       for(var k=0; k<frames[i].positions[j].arguments.length; k++)
       {
         arg_str_array.push(frames[i].positions[j].arguments[k].text_rep)
       }
       arg_str_array.sort();
       argument_str = arg_str_array.join(',');
       pos_cat_str = frames[i].positions[j].categories.join(',');
       frames[i].positions[j].text_rep = pos_cat_str+'{'+argument_str+'}';
       positions_text_rep_tab.push(frames[i].positions[j].text_rep);
    }
    positions_text_rep_tab.sort();    
    frames[i].text_rep = frames[i].characteristics[1]+':'+frames[i].characteristics[0]+':'+positions_text_rep_tab.join('+');
  }
  
  for(var k=0; k<frames.length; k++)
  {
    for(var l=k+1; l<frames.length; l++)
    {
      if(frames[l].text_rep == frames[k].text_rep)
      {
        frames[k].error = true;
        for(var m=0; m<frames[k].positions.length;m++)
        {
          frames[k].positions[m].error = true;
          for(var n=0; n<frames[k].positions[m].arguments.length;n++)
            frames[k].positions[m].arguments[n].error = true;
        }
        return false;
      }
    }
  } 
  return true;
}

// WALIDACJA 4: Rama nie moĂ„Ä…Ă„Ëťe zawieraÄ‚â€žĂ˘â‚¬Ë‡ pustych pozycji (bez argumentĂ„â€šÄąâ€šw).
function pass_walidate4(frames)
{
  for(var i=0; i<frames.length; i++)
  {
    for(var j=0; j<frames[i].positions.length;j++)
    {
      if(frames[i].positions[j].arguments.length == 0)
      {
        frames[i].error = true;
        return false;
      }
    }
  }
  return true;
}

// WALIDACJA 5: Rama nie moĂ„Ä…Ă„Ëťe zawieraÄ‚â€žĂ˘â‚¬Ë‡ dwĂ„â€šÄąâ€šch pozycji oznaczonych w taki sam sposĂ„â€šÄąâ€šb 
//              (np. dwĂ„â€šÄąâ€šch podmiotĂ„â€šÄąâ€šw).
function pass_walidate5(frames)
{
  pos_cat_vals = ax_pos_cat_vals;
  
  
  for(var i=0; i<frames.length; i++)
  {
    for(var j=0; j<pos_cat_vals.length; j++)
    {
      catFound = false;
      for(var k=0; k<frames[i].positions.length;k++)
      {
        if(frames[i].positions[k].categories.indexOf(pos_cat_vals[j]) != -1 && !catFound)
          catFound = true;
        else if(frames[i].positions[k].categories.indexOf(pos_cat_vals[j]) != -1 && catFound)
        {
          HideProgressAnimation();
          error_alert('We wskazanej ramie występują dwie pozycje oznaczone jako: '+pos_cat_vals[j]+'(przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli rama nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).');
          ShowProgressAnimation();
          frames[i].error = true;
          return false;
        }
      }
    }
  }
  return true;
}

// WALIDACJA 6: Pozycje obj i controller nie mogÄ‚â€žĂ˘â‚¬Â¦ byÄ‚â€žĂ˘â‚¬Ë‡ jednoczeĂ„Ä…Ă˘â‚¬Ĺźnie oznaczone jako controlee. 
             // Pozycja nie moĂ„Ä…Ă„Ëťe byÄ‚â€žĂ˘â‚¬Ë‡ jednoczeĂ„Ä…Ă˘â‚¬Ĺźnie oznaczona jako subj i obj.
             // z hardcodami niestety, do poprawy na bazie, kiedy tempo zmaleje :(
             
function pass_walidate6(frames)
{  
  for(var i=0; i<frames.length; i++)
  {
    for(var j=0; j<frames[i].positions.length; j++)
    {
      if(frames[i].positions[j].categories.indexOf('subj') != -1)
      {
       /* if(frames[i].positions[j].categories.indexOf('controlee') != -1)
        {
          HideProgressAnimation();
          error_alert('Wskazana pozycja jest jednoczeÄąâ€şnie oznaczona jako subj i controlee (przejdÄąĹź do zakÄąâ€šadki z nowymi ramkami aby jĂ„â€¦ zobaczyĂ„â€ˇ, jeÄąâ€şli pozycja nie jest widoczna sprawdÄąĹź ustawienia filtrÄ‚Ĺ‚w i powtÄ‚Ĺ‚rz walidacjĂ„â„˘).')
          ShowProgressAnimation();
          frames[i].positions[j].error = true;
          return false;
        }
        else*/ 
        if(frames[i].positions[j].categories.indexOf('obj') != -1)
        {
          HideProgressAnimation();
          error_alert('Wskazana pozycja jest jednocześnie oznaczona jako subj i obj (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli pozycja nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
          ShowProgressAnimation();
          frames[i].positions[j].error = true;
          return false;
        }
      }
      /*if(frames[i].positions[j].categories.indexOf('obj') != -1) UPDATE
      {
        if(frames[i].positions[j].categories.indexOf('controlee') != -1)
        {
          HideProgressAnimation();
          error_alert('Wskazana pozycja jest jednoczeÄąâ€şnie oznaczona jako obj i controlee (przejdÄąĹź do zakÄąâ€šadki z nowymi ramkami aby jĂ„â€¦ zobaczyĂ„â€ˇ, jeÄąâ€şli pozycja nie jest widoczna sprawdÄąĹź ustawienia filtrÄ‚Ĺ‚w i powtÄ‚Ĺ‚rz walidacjĂ„â„˘).')
          ShowProgressAnimation();
          frames[i].positions[j].error = true;
          return false;
        }
      }*/
      if(frames[i].positions[j].categories.indexOf('controller') != -1)
      {
        if(frames[i].positions[j].categories.indexOf('controlee') != -1)
        {
          HideProgressAnimation();
          error_alert('Wskazana pozycja jest jednocześnie oznaczona jako controller i controlee (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli pozycja nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
          ShowProgressAnimation();
          frames[i].positions[j].error = true;
          return false;
        }
      }
    }
  }
  return true;
}

// WALIDACJA 7: Rama zawierajÄ‚â€žĂ˘â‚¬Â¦ca pozycjÄ‚â€žĂ˘â€žË� oznaczonÄ‚â€žĂ˘â‚¬Â¦ jako controlee musi jednoczeĂ„Ä…Ă˘â‚¬Ĺźnie 
             // zawieraÄ‚â€žĂ˘â‚¬Ë‡ innÄ‚â€žĂ˘â‚¬Â¦ pozycjÄ‚â€žĂ˘â€žË� oznaczonÄ‚â€žĂ˘â‚¬Â¦ jako controller.
             // z hardcodami niestety, do poprawy na bazie, kiedy tempo zmaleje :(
function pass_walidate7(frames)
{  
  for(var i=0; i<frames.length; i++)
  {
    for(var j=0; j<frames[i].positions.length; j++)
    {
      if(frames[i].positions[j].categories.indexOf('controlee') != -1)
      {
        foundControl = false;
        for(var k=0;k<frames[i].positions.length;k++)
        {
          if(frames[i].positions[k].categories.indexOf('controller') != -1)
            foundControl = true;
        }
        if(!foundControl)
        {
          HideProgressAnimation();
          error_alert('Wskazana ramka posiada pozycję oznaczoną jako controlee, ale nie posiada pozycji oznaczonej jako controller (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli pozycja nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
          ShowProgressAnimation();
          frames[i].error = true;
          return false;
        }
      }    
    }
  }
  return true;
}

// WALIDACJA 13: Kazda ramka musi posiadac wyznaczona ocene
function pass_walidate13(frames)
{   
  for(var i=0; i<frames.length; i++)
  {
    if(!frames[i].opinion)
    {
      HideProgressAnimation();
      error_alert('Wskazana ramka nie posiada opinii (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli rama nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
      ShowProgressAnimation();
      frames[i].error = true;
      return false;
    }
  }    
  return true;
}

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). 
// Nie ma wymogu dotyczĂ„â€¦cego dodania przykladu do ramek z jednym argumentem w pozycji.
function pass_walidate14(frames)
{   
  for(var i=0; i<frames.length; i++)
  {
    var frame_id = 'frame_'+frames[i].id+'_';
    
    for(var j=0; j<frames[i]['positions'].length; j++)
    {
      if(frames[i]['positions'][j]['arguments'].length > 1)
      {
     //   onlySingleArgPoss = false;
        foundRelation = checkPosCoordination(frames[i]['positions'][j], frame_id, nkjp_examples)   

        if(!foundRelation)
        {
            HideProgressAnimation();
            error_alert('Wskazana pozycja nie posiada koordynacji dla wszystkich argumentów (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli pozycja nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
            ShowProgressAnimation();
            frames[i]['positions'][j].error = true;
            return false;
        }  
      }
    }
  }    
  return true;
}

// PREWALIDACJA NASTEPUJE JUZ TUTAJ
function validate_new_frames(status) {
  ShowProgressAnimation();
  var framesToValid = new Array();
  validate_selected = false;
  
  if(window.selectedId != -1)
  {
    selected_elem = getElementInstance(window.selected_id, window.frames);
    if(selected_elem['type'] == 'frame')
    {
      framesToValid.push(selected_elem['element']);
      validate_selected = true;
    }   
    else 
      framesToValid = window.frames;
  }
  else
    framesToValid = window.frames;
  
/// PREWALIDACJA //
	// WALIDACJA 1: Rama nie moĂ„Ä…Ă„Ëťe zawieraÄ‚â€žĂ˘â‚¬Ë‡ dwĂ„â€šÄąâ€šch argumentĂ„â€šÄąâ€šw tego samego typu, 
	            //  z takimi samymi wartoĂ„Ä…Ă˘â‚¬Ĺźciami atrybutĂ„â€šÄąâ€šw, w jednej pozycji.
	if(!pass_walidate1(framesToValid))
	{
	  draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
     // $(document).bind('keydown', 'ctrl+s', saveHandle);
      $('#save').attr("disabled", false);
      HideProgressAnimation();
      error_alert('Wskazany argument występuje dwa razy w jednej pozycji (przejdź do zakładki z nowymi ramkami aby go zobaczyć, jeśli argument nie jest widoczny sprawdź ustawienia filtrów i powtórz walidację).')
      return false;
	}
	
	// DO PRZYWROCENIA
	// WALIDACJA 2: Rama nie moze zawierac dwoch identycznych pozycji. 
	/*if(!pass_walidate2(framesToValid))
	{
	  draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
   //   $(document).bind('keydown', 'ctrl+s', saveHandle);
      HideProgressAnimation();
      error_alert('Wskazana pozycja wystĂ„â„˘puje dwa razy w tej samej ramie (przejdÄąĹź do zakÄąâ€šadki z nowymi ramkami aby jĂ„â€¦ zobaczyĂ„â€ˇ, jeÄąâ€şli pozycja nie jest widoczna sprawdÄąĹź ustawienia filtrÄ‚Ĺ‚w i powtÄ‚Ĺ‚rz walidacjĂ„â„˘).')
      return false;
	}*/
	
	// WALIDACJA 3: HasĂ„Ä…Ă˘â‚¬Ĺˇo nie moze zawierac dwoch identycznych ram. 
    if(!pass_walidate3(framesToValid) && !validate_selected)
    {
	  draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      HideProgressAnimation();
      error_alert('Wskazana rama występuje dwa razy w obrębie hasła (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli rama nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
      return false;
    }

	// WALIDACJA 4: Rama nie moĂ„Ä…Ă„Ëťe zawieraÄ‚â€žĂ˘â‚¬Ë‡ pustych pozycji (bez argumentĂ„â€šÄąâ€šw). 
    if(!pass_walidate4(framesToValid))
    {
	  draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      HideProgressAnimation();
      error_alert('Wskazana ramka posiada puste pozycje (przejdź do zakładki z nowymi ramkami aby ją zobaczyć, jeśli rama nie jest widoczna sprawdź ustawienia filtrów i powtórz walidację).')
      return false;
    }

	// WALIDACJA 5: Rama nie moĂ„Ä…Ă„Ëťe zawieraÄ‚â€žĂ˘â‚¬Ë‡ dwĂ„â€šÄąâ€šch pozycji oznaczonych w taki sam sposĂ„â€šÄąâ€šb 
    //              (np. dwĂ„â€šÄąâ€šch podmiotĂ„â€šÄąâ€šw).
    if(!pass_walidate5(framesToValid))
    {
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      HideProgressAnimation();
      return false;
    }
    
    // WALIDACJA 6: Pozycje subj, obj i controller nie mogÄ‚â€žĂ˘â‚¬Â¦ byÄ‚â€žĂ˘â‚¬Ë‡ jednoczeĂ„Ä…Ă˘â‚¬Ĺźnie oznaczone jako controlee. 
                 // Pozycja nie moĂ„Ä…Ă„Ëťe byÄ‚â€žĂ˘â‚¬Ë‡ jednoczeĂ„Ä…Ă˘â‚¬Ĺźnie oznaczona jako subj i obj.
    if(!pass_walidate6(framesToValid))
    {
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
   //   $(document).bind('keydown', 'ctrl+s', saveHandle);
      HideProgressAnimation();
      return false;
    }
    
    // WALIDACJA 7: Rama zawierajÄ‚â€žĂ˘â‚¬Â¦ca pozycjÄ‚â€žĂ˘â€žË� oznaczonÄ‚â€žĂ˘â‚¬Â¦ jako controlee musi jednoczeĂ„Ä…Ă˘â‚¬Ĺźnie 
                 // zawieraÄ‚â€žĂ˘â‚¬Ë‡ innÄ‚â€žĂ˘â‚¬Â¦ pozycjÄ‚â€žĂ˘â€žË� oznaczonÄ‚â€žĂ˘â‚¬Â¦ jako controller.
    if(!pass_walidate7(framesToValid))
    {
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      HideProgressAnimation();
      return false;
    }
    
    // DO PRZYWROCENIA
    // WALIDACJA 13: Kazda ramka musi posiadac wyznaczona ocene
    if(!pass_walidate13(framesToValid))
    {
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#save').attr("disabled", false);
      HideProgressAnimation();
      return false;
    } 

// DO PRZYWROCENIA
// 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). 
// Nie ma wymogu dotyczĂ„â€¦cego dodania przykladu do ramek z jednym argumentem w pozycji.
    if(!pass_walidate14(framesToValid))
    {
      draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
      $("#new-frame-tables td").click(function(e){
        e.stopPropagation();
        selectTd(this.id)});
      $("#new-frame-tables td").dblclick(function(e){
        e.stopPropagation();
        openEditForm(this.id)});
      clear_errors(window.frames);
      $('#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
      },

    callback: function(result) {
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      $('#save').attr("disabled", false);
      if(result['error_message'])
      {
        HideProgressAnimation();
        error_alert(result['error_message']);
        ShowProgressAnimation();
        if(validate_selected)
        {
          framesToValid[0] = result['frames'][0];
        }
        else
          window.frames = result['frames'];
        draw_filtered_frames(window.frames, 'new-frame-tables', 'new-frame-table', 'frame_filter', window.nkjp_examples, 'InflectionTable', window.lemma_entry);
        $("#new-frame-tables td").click(function(e){
          e.stopPropagation();
          selectTd(this.id)});
        $("#new-frame-tables td").dblclick(function(e){
          e.stopPropagation();
          openEditForm(this.id)});
        clear_errors(window.frames);
        //return false;
      }
      else
      {
        if(status)
          lemma_status_change(status);
        HideProgressAnimation();
        alert('Walidacja ukończona pomyślnie.');
        return true;
      }
      HideProgressAnimation();
    },
    
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    //  $('#save').attr("disabled", false);
    //  $(document).bind('keydown', 'ctrl+s', saveHandle);
      //if (ctrl)
      //  ctrl.remove();
    },
  });

  return false;
}
///////////////////////////////////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.frames, 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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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)
   {
     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.frames, 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)
  {
    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)
  {
    nkjp_lemma_modify(window.nkjp_lemma_examples, example_id, '.lemma-example-form')
  }
}

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


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

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

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

      callback: function(result) { 
       // grid.trigger("reloadGrid");
       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);
      //if (ctrl)
      //  ctrl.remove();
      },
      bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
        if (result == 'can not remove') {
          HideProgressAnimation();
          error_alert('Usuwać można jedynie notatki prywatne.');
          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);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      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;
  }	
}


//////////////////////////////// frame filters ////////////////////////
function aspect_filter_change()
{
  window.filter_aspect_val = $('#frame_filter #aspect_filter').val();
}

function reflex_filter_change()
{
  window.filter_reflex_val = $('#frame_filter #reflex_filter').val();
}

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


$(function(){
  
  /*$(document).bind('keydown', 'shift+s', saveHandle);
  $(document).bind('keydown', 'shift+a', function(evt){addElement(); return false; });
  $(document).bind('keydown', 'shift+c', function(evt){copyElement(); return false; });
  $(document).bind('keydown', 'shift+r', function(evt){removeElement(); return false; });
  $(document).bind('keydown', 'shift+v', function(evt){pasteElement(); return false; });
  $(document).bind('keydown', 'shift+x', function(evt){cutElement(); return false; });
  $(document).bind('keydown', 'shift+d', function(evt){duplicateElement(); return false; });
  $(document).bind('keydown', 'shift+z', function(evt){backOneModification(); return false; });
  $(document).bind('keydown', 'shift+y', function(evt){forwardOneModification(); return false; });
  $(document).bind('keydown', 'shift+m', function(evt){reserveLemma(); return false; });
  $(document).bind('keydown', 'shift+w', function(evt){validate_new_frames(false); return false; });*/
  
  $('form.position-add-form').live('submit', add_pos_form_submit);
  $('form.argument-add-form').live('submit', argument_form_submit);
  $('form.argument-add-form #show-realizations').live('click', show_argument_realizations);
  
  $('form.frame-form').live('submit', frame_form_submit);
  $('form.pos-cat-form').live('submit', pos_cat_form_submit);
  $('form.nkjp-example-form').live('submit', nkjp_example_form_submit);
  $('form.lemma-example-form').live('submit', nkjp_lemma_example_form_submit);
  
// lemma notes
  $('form.lemma-notes-form').live('submit', lemma_notes_form_submit);
  
// 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);
  $('#reset-similar-button').live('click', similar_lemmas_reset);
 // $('#reset-similar-button').live('click', similar_lemmas_reset);

  $('form.position-add-form').live('reset', function(){
    $('#add-table-elem-dialog').dialog('close')}); 
  $('form.argument-add-form').live('reset', function(){
    $('#add-table-elem-dialog').dialog('close')});
  $('form.frame-form').live('reset', function(){
    $('#add-table-elem-dialog').dialog('close')});
  $('form.pos-cat-form').live('reset', function(){
    $('#add-table-elem-dialog').dialog('close')});
  $('form.nkjp-example-form').live('reset', function(){
    $('#add-table-elem-dialog').dialog('close')});
 
  $('#id_arg_model_name').live('change', argument_model_change);
  $('#id_atr_value').live('change', atribute_value_change);
  
  $('#frame_filter #aspect_filter').live('change', aspect_filter_change)
  $('#frame_filter #reflex_filter').live('change', reflex_filter_change)

 /* $('#menu_option a').click(function(e) {
    if (change) {
      if(confirm('Czy chcesz porzuciĂ„â€ˇ niezapisane zmiany?'))
      {
        e.enableDefault();
        change = false;
      }
      else
        e.preventDefault();
    }
  });*/
  
  refresh_column_headers();
});

