var control = "meanings";
var op = "none";
var arg = "";
window.units_operations = [];
window.frames_operations = [];
var highlighted_id = "";
var highlighted_class = "";
var semantics_selected_id = "";

var relations_creating = ["hiponimia", "synonimia", "nie umiem umieścić"];

//////////////////////////// Control ////////////////////////////

function prepareControl() {  
    $(".semantics-control-tabs").tabs().bind('tabsselect', function(event, ui) {
        if(ui.panel.id == 'select_meanings') {
        	control="meanings";
        	frameClick("");
        	$('#assign_role').attr('disabled', "True");
        	$('#add_preference').attr('disabled', "True");
            $('#delete').attr('disabled', "True");
        } 
        else if(ui.panel.id == 'select_creating') {
        	control="connect";
            frameClick("");
            $('#assign_role').attr('disabled', "True");
            $('#add_preference').attr('disabled', "True");
            $('#delete').attr('disabled', "True");
        }
   });
}

function alertSemantics() {
    alert("Nie można modyfikować semantyki. Zapisz zmiany w składni.");
}

function alertOldSchemas() {
	alert('Działanie niemożliwe, wyświetlona wersja składni jest nieaktualna.');
}

/////////////////////////// Meanings ////////////////////////////
function hide() {
    $("#synset_input").css('visibility', 'hidden');
}
        
function reveal() {
    $("#synset_input").css('visibility', '');
}

function changeSynsetInput() {
    if (parseInt($("#synset_input_relation").val()) == 2) {
        hide();
    } else {
        reveal();
    }
}

function openMeaningsMenu() {
	if(window.lemma_id != getActualLemmaId(window.lemma_id)){
    	alertOldSchemas();
    }
    else {
    	displayMeanings();
    }
}

function displayMeanings() {

    var submitInitialState =
                function(e,v,m,f){ 
                    e.preventDefault();

                    if (v == 1) {
                        $.prompt.goToState('state1');
                    }
                    if (v == 2) {
                        if (f.meaning >= 0) {
                            if (isPlWNUnit(f.meaning)) {
                                $.prompt.goToState('state22');
                            } else {
                                $.prompt.goToState('state21');
                            }
                        } else {
                            if (f.meaning <= 0) {
                                $.prompt.goToState('state21');
                            } else {
                                // $.prompt.goToState('state20');
                                alert('Nie wybrano żadnego znaczenia!');
                            }
                        }
                    }
                    if (v == 3) {
                        if ((typeof f.meaning) == 'undefined') {
                            alert('Nie wybrano żadnego znaczenia!');
                        } else {
			    $.prompt.removeState('state3');
			    $.prompt.addState('state3', 
					      {
						title: 'Modyfikuj glossę', 
						html: 'Jednostka leksykalna: ' + getLexicalUnit(f.meaning) + '<br />' + 
						      '<label>Glossa <input type="text" name="glossa" value="' + getGlossa(f.meaning) + '"></label><br />', 
						buttons: glossa_buttons, 
						focus: 1, 
						submit: submitGlossa
					      }, 
					      'state22');
			    $.prompt.goToState('state3');
			}
                    }
                    if (v == 4) {
                        if ((typeof f.meaning) == 'undefined') {
                            alert('Nie wybrano żadnego znaczenia!');
                        } else {
			    var i = indexOfId(lexical_units, f.meaning);

			    $.prompt.removeState('state4');
			    $.prompt.addState('state4', 
					      {
						title: 'Podepnij przykłady do ' + getLexicalUnit(f.meaning), 
						html: getExamples(f.meaning), 
						buttons: examples_assignment_buttons, 
						focus:1, 
						submit: submitExamplesAssignment
					      }, 
					      'state22');
			    $.prompt.goToState('state4');
			}
                    }
                    if (v == 5) {
                        saveMeanings();
                        displayFrames();
		                $.prompt.close();  
		            }
		            
	            };
    var initial_state_buttons = { "Dodaj znaczenie": 1, "Usuń znaczenie": 2, "Modyfikuj glossę": 3, "Ustaw przykłady": 4, "Koniec": 5 };

    var submitGlossa = 
                function(e,v,m,f){ 
                    e.preventDefault();

                    if (v == -1) {
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        setGlossa(f.meaning, f.glossa[1]); // TODO: WHY f.glossa[1]?
                        $.prompt.removeState('state0');
                        $.prompt.addState('state0', {title: 'Znaczenia', html: getMeanings(), buttons: initial_state_buttons, focus: 4, submit: submitInitialState}, 'state1')
                        $.prompt.goToState('state0');
                    }
                    
	            };
    var glossa_buttons = { "Anuluj": -1, "Potwierdź": 1 };

    var submitExamplesAssignment = 
                function(e,v,m,f){ 
                    e.preventDefault();
                    
                    var connect = normalizeFormData(f.connect);

                    if (v == -1) {
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        setExamples(f.meaning, connect);
                        $.prompt.goToState('state0');
                    }
                    
	            };
    var examples_assignment_buttons = { "Anuluj": -1, "Potwierdź": 1 };

    var addLexicalUnitLocation =
        function(e,v,m,f){
            // arg = "frame_26_comp_36_"

            if (v == -1) {
                e.preventDefault();
                $.prompt.goToState('state1');
            }        
            if (v == 0) {
                e.preventDefault();
                $.prompt.goToState('state0');
            }
            if (v == 1) {
                e.preventDefault();
                if (parseInt(f.relation) != 2) {
                    $.prompt.removeState('state12');
                    $.prompt.addState('state12', {title: 'Znaczenia', html: getFormContent(f) + getRelation(f) + "w stosunku do:<br />" + getSynsets(f.context, "czasownik"), buttons: {Wstecz: -1, Anuluj: 0, Zatwierdź: 1}, focus: 1, submit: submitSynsetSelection}, 'state11');
                    $.prompt.goToState('state12');
                } else {
                    createLexicalUnit(f.refl, f.glossa, f.relation, -1);
                    $.prompt.removeState('state0');
                    $.prompt.addState('state0', 
                                      {
                                        title: 'Znaczenia', 
                                        html: getMeanings(), 
                                        buttons: initial_state_buttons, 
                                        focus: 4, 
                                        submit: submitInitialState
                                      }, 
                                      'state1');
                    $.prompt.goToState('state0');                
                }
            }
        };
    var add_lexical_unit_location_buttons = { Wstecz: -1, Anuluj: 0, Potwierdź: 1 };

    var getFormContent = 
        function(f) {
	        var result = '<label>Zwrotny <input type="checkbox" name="refl" value="true" disabled';
	        if (f.refl == 'true') {
	            result += ' checked';
            }
	        result += '></label><br /><label>Glossa <input type="text" name="glossa" value="' + f.glossa + '" disabled></label><br />';
	        return result;
        };

    var getRelation = 
        function(f) {
	        return '<label>Relacja <select name="relation" disabled><option value="' + f.relation + '">' + relations_creating[parseInt(f.relation)] + '</option></label></select><br />';
        };
        
    var getRelationsForm =
        function () {
            var result = '<label>Relacja ';
            result += '<select id="synset_input_relation" name="relation" onchange="changeSynsetInput()">';
            result += '<option value="0">' + relations_creating[0] + '</option>';
            result += '<option value="1">' + relations_creating[1] + '</option>';
            result += '<option value="2">' + relations_creating[2] + '</option>';
            result += '</select></label><br />';
            return result;
        };

    var submitSynsetSelection =
        function(e,v,m,f){
            if (v == -1) {
                e.preventDefault();
                $.prompt.goToState('state11');
            }
            if (v == 0) {
                e.preventDefault();
                $.prompt.goToState('state0');
            }
            if (v == 1) {
                e.preventDefault();
                if ((typeof f.synset) == 'undefined') {
                    alert('Nie wybrano żadnego synsetu!');
                } else {
                    createLexicalUnit(f.refl, f.glossa, f.relation, f.synset);
                    $.prompt.removeState('state0');
                    $.prompt.addState('state0', 
                                      {
                                        title: 'Znaczenia', 
                                        html: getMeanings(), 
                                        buttons: initial_state_buttons, 
                                        focus: 4, 
                                        submit: submitInitialState
                                      }, 
                                      'state1');
                    $.prompt.goToState('state0');
                }
            }
        };

    var display_meanings = {
            state0: {
	            title: 'Znaczenia',
	            html: getMeanings(),
	            buttons: initial_state_buttons,
	            focus: 4,
	            submit: submitInitialState,
            },
            state1: {
	            title: 'Dodawanie znaczenia',
	            html: '<label>Zwrotny <input type="checkbox" name="refl" value="true"></label><br />'+
			          '<label>Glossa <input type="text" name="glossa" value=""></label><br />',
	            buttons: { "Anuluj": -1, "Potwierdź": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
                    e.preventDefault();
                    if (v == -1) {
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        $.prompt.removeState('state11');
                        $.prompt.addState('state11', 
                                          {
                                            title: 'Miejsce w Słowosieci', 
                                            html: getFormContent(f) + getRelationsForm() + "<label id=\"synset_input\">w stosunku do <input id=\"plWN_context_selection\" type=\"text\" name=\"context\"></label>",
                                            buttons: add_lexical_unit_location_buttons,
                                            focus: 1, 
                                            submit: addLexicalUnitLocation
                                          }, 
                                          'state1');
                        $.prompt.goToState('state11');
                        attachPlWNContextAutocomplete();
                    }
	            }
            },
            state21: {
	            title: 'Usuwanie znaczenia',
	            html: 'Czy chcesz usunąć znaczenie?',
	            buttons: { "Nie": -1, "Tak": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
                    e.preventDefault();
                    if (v == -1) {
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        destroyLexicalUnit(f.meaning);
                        $.prompt.removeState('state0');
                        $.prompt.addState('state0', {title: 'Znaczenia', html: getMeanings(), buttons: initial_state_buttons, focus:4, submit: submitInitialState}, 'state1');
                        $.prompt.goToState('state0');
                    }
	            }
            },
            state22: {
	            title: 'Usuwanie znaczenia',
	            html: 'Nie można usunąć znaczenia ze Słowosieci',
	            buttons: { "Ok": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
                    e.preventDefault();
                    $.prompt.goToState('state0');
	            }
            },
            state20: {
	            // title: 'Usuwanie znaczenia',
	            html: 'Nie wybrano żadnego znaczenia',
	            buttons: { "Ok": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
                    e.preventDefault();
                    $.prompt.goToState('state0');
	            }
            },
        };
    if (change == true) {
        alertSemantics();
    } else {
        $.prompt(display_meanings);
    }
    
}
/////////////////////// Creating (Frames) ///////////////////////
function createFrame() {

    var create_frame = {
            state0: {
	            title: 'Tworzenie ramy',
	            html: getMeaningsSelection(),
	            buttons: { "Anuluj": -1, "Potwierdź": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
                    e.preventDefault();
                    if (v == -1) {
                        $.prompt.close();
                    }
                    if (v == 1) {
                    
                        var units;
                        if ((typeof f.meaning) == 'string') {
                            units = [f.meaning];
                        } else {
                            units = f.meaning;
                        }
			if ((typeof units) == 'undefined') {
			    units = [];
			}
                    
                        frameClick("");
                        newFrame(units);
                        displayFrames();
                        
                        $.prompt.close();
                    }
	            }
            },
        };
    if (change == true) {
        alertSemantics();
    } else {
        $.prompt(create_frame);
    }
    
}

function changeLexicalUnits() {

    var getRelation = 
        function(f) {
	        return '<label>Relacja <select name="relation" disabled><option value="' + f.relation + '">' + relations_creating[parseInt(f.relation)] + '</option></label></select><br />';
        };

    var getRelationsForm =
        function () {
            var result = '<label>Relacja ';
            result += '<select id="synset_input_relation" name="relation" onchange="changeSynsetInput()">';
            result += '<option value="0">' + relations_creating[0] + '</option>';
            result += '<option value="1">' + relations_creating[1] + '</option>';
            result += '<option value="2">' + relations_creating[2] + '</option>';
            result += '</select></label><br />';
            return result;
        };

    var units = [];
    var mwes = [];
    var new_mwes = [];
    var old_mwes = [];
    var a = "";
    var gloss = "";

    var addPhraseology =
                function(e,v,m,f){
                    e.preventDefault();
                    if (v == -1)
                        $.prompt.goToState('state0');
                    if (v == 0) {
                        $.prompt.close();
                    }
                    if (v == 1) {
                        if ((typeof f.synset) == 'undefined') {
                            alert('Nie wybrano żadnego synsetu!');
                        } else {
			    changeUnits(highlighted_id, units);

			    addPhraseologicalUnits(highlighted_id, units, old_mwes, new_mwes, f.glossa, f.relation, f.synset);

			    frameClick("");
			    displayFrames();
			    frameClick(a);
			    $.prompt.close();
                        }
                    }
                };

    var change_units = {
            state0: {
	            title: 'Zmiana jednostek leksykalnych',
	            html: getMeaningsSelectionForFrame(highlighted_id),
	            buttons: { "Anuluj": -1, "Potwierdź": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
			e.preventDefault();
			if (v == -1) {
			    $.prompt.close();
			}
			if (v == 1) {

                            new_mwes = [];
                            old_mwes = [];
			    units = normalizeFormData(f.meaning);
			    mwes = normalizeFormData(f.mwe);
			    a = semantics_selected_id;

                            if (mwes.length == 0) {
                                changeUnits(highlighted_id, units);
			    
                                frameClick("");
                                displayFrames();
                                frameClick(a);
                                $.prompt.close();
                            } else {
                                 
                                 var i;
                                 for (i = 0; i < mwes.length; i++) {
                                     var lu = mwes[i].split('_')[0];
                                     var id = mwes[i].split('_')[1];
                                     var luid = mwes[i].split('_')[2];
                                     var sid = mwes[i].split('_')[3];
                                     if (sid == '') {
                                         new_mwes.push(lu);
                                     } else {
                                         old_mwes.push({lu: lu, id: parseInt(id), luid: parseInt(luid), sid: parseInt(sid)});
                                     }
                                 }
                                 
                                 if (old_mwes.length > 0) {
                                     var sid = old_mwes[0].sid
                                     var ok = true;
                                     for (i = 0; i < old_mwes.length; i++) {
                                         if (old_mwes[i].sid != sid) {
                                             ok = false;
                                         }
                                     }
                                     if (ok) {
                                         changeUnits(highlighted_id, units);
                                         

                                         addPhraseologicalUnits(highlighted_id, units, old_mwes, new_mwes, old_mwes[0].lu, 1, sid);

                                         frameClick("");
                                         displayFrames();
                                         frameClick(a);
                                         $.prompt.close();
                                     } else {
                                         $.prompt.goToState('state1');
                                         attachPlWNContextAutocomplete();
                                     }
                                 } else {
                                     $.prompt.goToState('state1');
                                     attachPlWNContextAutocomplete();
                                 }
                            }

			}
	            }
            },
            state1: { /* nowa frazeologia */
	            title: 'Nowe jednostki frazeologiczne',
	            html: '<label>Glossa <input type="text" name="glossa" value=""></label><br />' + 
                          getRelationsForm() + "<label id=\"synset_input\">w stosunku do <input id=\"plWN_context_selection\" type=\"text\" name=\"context\"></label>",
	            buttons: { "Wstecz": -1, "Anuluj": 0, "Potwierdź": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
			e.preventDefault();
			if (v == -1) {
			    $.prompt.goToState('state0');
			}
                        if (v == 0) {
                            $.prompt.close();
                        }
			if (v == 1) {
                            if (parseInt(f.relation) != 2) { 
                                /* podana lokalizacja w Słowosieci */
                                $.prompt.removeState('state2');
                                $.prompt.addState('state2',
                                                  {
                                                      title: 'Znaczenia',
                                                      html: '<label>Glossa <input type="text" name="glossa" value="' + gloss + '" disabled></label><br />' + 
                                                            getRelation(f) + "w stosunku do:<br />" + getSynsets(f.context, "czasownik"), 
                                                      buttons: {Wstecz: -1, Anuluj: 0, Zatwierdź: 1}, 
                                                      focus: 1, 
                                                      submit: addPhraseology
                                                  })
                                $.prompt.goToState('state2');
                            } else {
                                /* zignorowane umiejscowienie w Słowosieci */
                                addPhraseologicalUnits(highlighted_id, units, old_mwes, new_mwes, f.glossa, f.relation, -1);
			        frameClick("");
			        displayFrames();
			        frameClick(a)
                                $.prompt.close();
                            }
			}
	            }       
            },
        };
    if (change == true) {
        alertSemantics();
    } else {
        $.prompt(change_units);
    }
    
}

function changeOpinion() {

    var change_opinion = {
            state0: {
	            title: 'Ustawianie statusu ramy',
	            html: getStatusesForFrame(highlighted_id),
	            buttons: { "Anuluj": -1, "Potwierdź": 1 },
	            focus: 1,
	            submit:function(e,v,m,f){ 
                    e.preventDefault();
                    if (v == -1) {
                        $.prompt.close();
                    }
                    if (v == 1) {
                    
                        var opinion = normalizeFormData(f.opinion);
                        if (opinion.length > 0) {
                    
                            var a = semantics_selected_id;
                            setOpinion(highlighted_id, opinion);
                            frameClick("");
                            displayFrames();
                            frameClick(a);
                            
                            $.prompt.close();
                            
                        } else {
                        
                            alert("Nie wybrano żadnego statusu");
                        
                        }
                    }
	            }
            },
        };
    if (change == true) {
        alertSemantics();
    } else {
        $.prompt(change_opinion);
    }
    
}

// assign role to selected complement
function assignRole() {

    var result = false;

    var assign_role = {
            state0: {
                title: 'Wybierz rolę',
                html: roles_display_table,
                buttons: { Anuluj: -1, Zatwierdź: 1 },
                focus: 1,
                close: function(){return result;},
                submit: function(e,v,m,f){ 
                    // arg = "frame_26_comp_36_"
                
                    if (v == -1) {
                        e.preventDefault();
                        $.prompt.close();
                    }
                    if (v == 1) {
                        e.preventDefault();
                        
                        var roles = normalizeFormData(f.roles);

                        var frame_id = parseInt(arg.split('_')[1]);
                        var complement_id = parseInt(arg.split('_')[3]);
                        
                        if (setRole(frame_id, complement_id, roles)) {
                        
                            var h = "frame_" + highlighted_id + "_";
                            var a = arg;
                            
                            // re-draw and re-color frame
                            frameClick(h);
                            displayFrames();
                            frameClick(a);
                            
                            result = true;
                            $.prompt.close();
                            
                        } else {
                            
                            alert("Wybrano niepoprawne role!");
                            
                        }
                    }
                    
                }
            },
        };
    if (change == true) {
        alertSemantics();
    } else {
        $.prompt(assign_role);
    }
    
}

function addSelectivePreference() {

    var submitSynsetSelection = function(e,v,m,f){ 
                    if (v == -1) {
                        e.preventDefault();
                        $.prompt.goToState('state2');                    
                    }
                    if (v == 1) {
                        e.preventDefault();
                        var frame_id = parseInt(arg.split('_')[1]);
                        var complement_id = parseInt(arg.split('_')[3]);
                        var synset = normalizeFormData(f.synset);
                        
                        var i;
                        for (i = 0; i < synset.length; i++) {
                            addPreference(frame_id, complement_id, { type: 's', content: synset[i], text: synsets[indexOfId(synsets, synset[i])].content[0].base + "-" + synsets[indexOfId(synsets, synset[i])].content[0].sense });
                        }
                        $.prompt.goToState('state0');                       
                    }
                }

    var select_preference = {
            state0: {
                title: 'Typ preferencji selekcyjnej',
                html: 'Wybierz typ preferencji selekcyjnej',
                buttons: { Predefiniowana: 1, Słowosieć: 2, Relacja: 3, Koniec: -1 },
                focus: -1,
                submit: function(e,v,m,f){ 
                    if (v == -1) {
                        e.preventDefault();

                        var h = "frame_" + highlighted_id + "_";
                        var a = arg;
                        
                        // re-draw and re-color frame
                        frameClick(h);
                        displayFrames();
                        frameClick(a);

                        $.prompt.close();
                    }
                    if (v == 1) {
                        e.preventDefault();
                        $.prompt.goToState('state1');
                            
                    } 
                    if (v == 2) {
                        e.preventDefault();
                        $.prompt.goToState('state2');
                            
                    } 
                    if (v == 3) {
                        e.preventDefault();
                        $.prompt.goToState('state3');
                            
                    } 
                }
            },
            state1: {
                title: 'Wybierz preferencję selekcyjną',
                html: predefinedSelect(),
                buttons: { Anuluj: -1, Zatwierdź: 1 },
                focus: 1,
                submit: function(e,v,m,f){
                    // arg = "frame_26_comp_36_"
                
                    if (v == -1) {
                        e.preventDefault();
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        e.preventDefault();
                        var frame_id = parseInt(arg.split('_')[1]);
                        var complement_id = parseInt(arg.split('_')[3]);
                        var predef = normalizeFormData(f.predef);
                        
                        var i;
                        for (i = 0; i < predef.length; i++) {
                            addPreference(frame_id, complement_id, { type: 'g', content: predef[i], text: predefined[indexOfId(predefined, predef[i])].content });
                        }
                        $.prompt.goToState('state0');
                    }
                }
            },
            state2: {
                title: 'Wybierz preferencję selekcyjną',
                html: "<input id=\"plWN_context_selection\" type=\"text\" name=\"context\">",
                buttons: { Anuluj: -1, Wyszukaj: 1 },
                focus: 1,
                submit: function(e,v,m,f){
                    // arg = "frame_26_comp_36_"
                
                    if (v == -1) {
                        e.preventDefault();
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        e.preventDefault();
                        $.prompt.removeState('state21');
                        $.prompt.addState('state21', {title: 'Znaczenia', html: getSynsets(f.context), buttons: {Anuluj: -1, Zatwierdź: 1}, focus: 1, submit: submitSynsetSelection}, 'state2');
                        $.prompt.goToState('state21');
                    }
                }
            },
            state3: {
                title: 'Wybierz relację i argument',
                html: relationArgument(arg),
                buttons: { Anuluj: -1, Zatwierdź: 1 },
                focus: 1,
                submit: function(e,v,m,f){
                    // arg = "frame_26_comp_36_"
                
                    if (v == -1) {
                        e.preventDefault();
                        $.prompt.goToState('state0');
                    }
                    if (v == 1) {
                        e.preventDefault();
                        
                        var frame_id = parseInt(arg.split('_')[1]);
                        var complement_id = parseInt(arg.split('_')[3]);
                        var rel = normalizeFormData(f.rel);
                        var args = normalizeFormData(f.arg);
                        
                        var i, j;
                        for (i = 0; i < rel.length; i++) {
                            var text = [];
                            for (j = 0; j < args.length; j++) {
                                var list = args[j].split(',');
                                var k;
                                for (k = 0; k < list.length; k++) {
                                    text.push(role_name[list[k]]);
                                }
                                addPreference(frame_id, complement_id, {type: 'r', content: { relation: rel[i], to: args[j] }, text: relations[indexOfId(relations, rel[i])].content + "<br>-> [" + text + "]" });
                            }
                        }
                        
                        $.prompt.goToState('state0');
                    }
                }
            },
        };
    if (change == true) {
        alertSemantics();
    } else {
        $.prompt(select_preference);
        attachPlWNContextAutocomplete();
    }

}

function removeFromFrame() {
    if (change == true) {
        alertSemantics();
        return;
    }
    if (op == "none") {
    }
    if (op == "add_argument") {
        // highlighted_id = "26"

        removeFrame(highlighted_id);
        
        frameClick("frame_" + highlighted_id + "_");
        displayFrames();
        
    }
    if (op == "add_realization") {
        // arg = "frame_26_comp_36_(lemma_)"
        
        var frame_id = parseInt(arg.split('_')[1]);
        var complement_id = parseInt(arg.split('_')[3]);
        var pos = -1;
        var h = "frame_" + highlighted_id + "_";
        
        frameClick(h);
  
        removeArgument(frame_id, complement_id, arg);
        
        op = "add_argument";
        arg = "";
        
        displayFrames();
        frameClick(h);
        
    }
    if (op == "remove_preference") {
        // arg = "frame_26_comp_36_pref_s1_"
        
        var frame_id = parseInt(arg.split('_')[1]);
        var complement_id = parseInt(arg.split('_')[3]);
        var preference_id = arg.split('_')[5];
        var pos = -1;
        var h = "frame_" + highlighted_id + "_";
        
        frameClick(h);

        removePreference(frame_id, complement_id, preference_id);
        
        op = "add_argument";
        arg = "";
        
        displayFrames();
        frameClick(h);
        
    }
}

///////////////////////// Frame Sharing /////////////////////////

function sharableFrames() {
    return getDisplay(false, true);
}

function shareFrame() {

    var share_frame = {
	state0: {
	    title: 'Współdzielona rama',
	    html: sharableFrames(),
	    buttons: { Anuluj: -1, Zatwierdź: 1 },
	    focus: 1,
	    submit: function(e,v,m,f) {
		if (v == -1) {
		    e.preventDefault();
		    $.prompt.close();
		}
		if (v == 1) {
		    var frames = normalizeFormData(f.frames);
		    var i;
		    for (i = 0; i < frames.length; i++) {
			frame_content[frames[i]].visible = true;
		    }
		    displayFrames();
		    e.preventDefault();
		    $.prompt.close();
		}
	    }
	},
    };
    
    $.prompt(share_frame);
    
}

//////////////////////////// Display ////////////////////////////

function frameClick(clicked_id) {

    if (clicked_id == "") {
        deselect();
        highlighted_id = "";
        semantics_selected_id = "";
	$('#assign_role').attr('disabled', "True");
	$('#add_preference').attr('disabled', "True");
	$('#delete').attr('disabled', "True");
	$('#multi_lus').attr('disabled', "True");
	$('#change_lus').attr('disabled', "True");
	$('#change_opinion').attr('disabled', "True");
        return;
    }
    
    if (control != "connect") {
        var frame_id = clicked_id.split('_')[1]

        if (highlighted_id != "") {
            deselect();
        }
        
        if (semantics_selected_id == frame_id) {
            highlighted_id = "";
            semantics_selected_id = ""
        } else {
            select(frame_id, clicked_id.split('comp')[0]);
            highlighted_id = frame_id;
            semantics_selected_id = frame_id;
        }
    } else {
        if (clicked_id.split('_').length == 3) {    // frame click
            var frame_id = clicked_id.split('_')[1];
	    var local = frame_content[frame_id].local;
            
            if (highlighted_id != "") {
                deselect();
            }
            if (semantics_selected_id == clicked_id) {
                highlighted_id = "";
                semantics_selected_id = "";
                op = "none";
                
                $('#assign_role').attr('disabled', "True");
                $('#add_preference').attr('disabled', "True");
                $('#delete').attr('disabled', "True");
		$('#multi_lus').attr('disabled', "True");
                $('#change_lus').attr('disabled', "True");
		$('#change_opinion').attr('disabled', "True");
            } else {
                select(frame_id, clicked_id);
                highlighted_id = frame_id;
                semantics_selected_id = clicked_id;
                op = "add_argument";

                $('#assign_role').attr('disabled', "True");
                $('#add_preference').attr('disabled', "True");
		$('#multi_lus').removeAttr('disabled');
                $('#change_lus').removeAttr('disabled');
		if (!local) {
                    $('#delete').attr('disabled', "True");
		    $('#change_opinion').attr('disabled', "True");
		} else {
                    $('#delete').removeAttr('disabled');
		    $('#change_opinion').removeAttr('disabled');
		}
            }
        } else if (clicked_id.split('_')[4] == 'lemma') { // part of lemma click
            frame_id = clicked_id.split('_')[1]
	    var local = frame_content[frame_id].local;
            
            if (highlighted_id != "") {
                deselect();
            }
            if (semantics_selected_id == clicked_id) {
                highlighted_id = "";
                semantics_selected_id = "";
                op = "none";
                
                $('#assign_role').attr('disabled', "True");
                $('#add_preference').attr('disabled', "True");
                $('#delete').attr('disabled', "True");
		$('#multi_lus').attr('disabled', "True");
                $('#change_lus').attr('disabled', "True");
		$('#change_opinion').attr('disabled', "True");
            } else {
                select(frame_id, clicked_id);

                highlighted_id = frame_id;
                semantics_selected_id = clicked_id;
                op = "add_realization";
                arg = clicked_id //.split('pref')[0]
                
                $('#assign_role').attr('disabled', "True");
                $('#add_preference').attr('disabled', "True");
		$('#multi_lus').removeAttr('disabled');
                $('#change_lus').removeAttr('disabled');
		if (!local) {
                    $('#delete').attr('disabled', "True");
		    $('#change_opinion').attr('disabled', "True");
		} else {
                    $('#delete').removeAttr('disabled');
		    $('#change_opinion').removeAttr('disabled');
		}
            }
        } else { // argument click
            frame_id = clicked_id.split('_')[1]
	    var local = frame_content[frame_id].local;
            
            if (highlighted_id != "") {
                deselect();
            }
            if (semantics_selected_id == clicked_id) {
                highlighted_id = "";
                semantics_selected_id = "";
                op = "none";
                
                $('#assign_role').attr('disabled', "True");
                $('#add_preference').attr('disabled', "True");
                $('#delete').attr('disabled', "True");
		$('#multi_lus').attr('disabled', "True");
                $('#change_lus').attr('disabled', "True");
		$('#change_opinion').attr('disabled', "True");
            } else {
                select(frame_id, clicked_id);

                highlighted_id = frame_id;
                semantics_selected_id = clicked_id;
                if(clicked_id.split('_').length == 5) {        
                    op = "add_realization";
                } else {
                    op = "remove_preference";
                }
                arg = clicked_id //.split('pref')[0]

		if (!local) {
                    $('#assign_role').attr('disabled', "True");
                    $('#add_preference').attr('disabled', "True");
                    $('#delete').attr('disabled', "True");
		    $('#change_opinion').attr('disabled', "True");
		} else {
                    $('#assign_role').removeAttr('disabled');
                    $('#add_preference').removeAttr('disabled');
                    $('#delete').removeAttr('disabled');
		    $('#change_opinion').removeAttr('disabled');
		}
		$('#multi_lus').removeAttr('disabled');
                $('#change_lus').removeAttr('disabled');
            }
        }
    }
}

function select(frame_id, clicked_id) { 
    
    redrawSchemas(frame_id);
    getDisplayedExamples(frame_id);
    displayExamples();
    fadeSchemas();
    highlighted_id = frame_id;
    brightenSchemasForDisplayedExamples();
    selectFrame(frame_id, clicked_id);
    
}   

function deselect() {

    redrawSchemas();
    displayed_examples = [];
    clearExampleArgumentsSelection();
    displayExamples();
    deselectFrame();
    deselectSchema();
    brightenSchemas();

} 

function selectFrame(frame_id, clicked_id) {

    $("#frame_" + frame_id + "_").css('background-color', 'LightSteelBlue');
    
    var i;
    var roles = frame_content[frame_id].display.roles;
    for (i = 0; i < roles.length; i++) {
        var style = getStyle(frame_id, i)
        $('#' + roles[i].csv_id).css(style.type, style.value);
        var j;
        for (j = 0; j < connected[roles[i].csv_class].length; j++) {
            $('#' + connected[roles[i].csv_class][j]).css(style.type, style.value);
            $('#' + connected[roles[i].csv_class][j]).css('color', '');
            $('#' + functionCsvId(connected[roles[i].csv_class][j])).css(style.type, style.value);
            $('#' + functionCsvId(connected[roles[i].csv_class][j])).css('color', '');
        }
    }

    var lemma = frame_content[frame_id].lemma;
    if (lemma.include) {
        var style = {type: 'background-color', value: 'white'};
        $('#' + lemma.csv_id).css(style.type, style.value);
        var j;
        for (j = 0; j < connected[lemma.csv_class].length; j++) {
            $('#' + connected[lemma.csv_class][j]).css(style.type, style.value);
            $('#' + connected[lemma.csv_class][j]).css('color', '');
            $('#' + functionCsvId(connected[lemma.csv_class][j])).css(style.type, style.value);
            $('#' + functionCsvId(connected[lemma.csv_class][j])).css('color', '');
        }
    }
    
    $("#" + clicked_id).css('border-width', '5px');

}

function deselectFrame() {

	$('[class^=frame_]').each(function(){
		$(this).css('background-color', "");
		$(this).css('background', "");
		$(this).css('border-width', '');
	});
}

function fadeSchemas() {

	$('[class^=schema_]').each(function(){
		$(this).css('color', "#aaaaaa");
		$(this).css('background-color', "#e8e8e8");
	});
	
}


function brightenSchemas() {

	$('[class^=schema_]').each(function(){
		$(this).css('color', "");
		$(this).css('background-color', "");
		$(this).css('background', "");
	});

}

function brightenSchemasForDisplayedExamples() {

    var i;
    for (i = 0; i < displayed_examples.length; i++){
        brightenSchemaArguments(displayed_examples[i].arguments);
    }

}

function brightenSchemaArguments(arguments_list) {

    if (arguments_list.length > 0) {
        brightenSchemaHeader(schemaId(arguments_list[0].id))
        
        var alts = alternations(selectedFrameId(), schemaId(arguments_list[0].id));
        var i, j;   
        for (i = 0; i < arguments_list.length; i++) {
            for (j = 0; j < alts; j++) {
                $('#schema_' + arguments_list[i].id.split('_')[1] + '_pos_' + arguments_list[i].id.split('_')[3] + '_alt_' + (j + 1) + '_').css('color', "");
                $('#schema_' + arguments_list[i].id.split('_')[1] + '_pos_' + arguments_list[i].id.split('_')[3] + '_alt_' + (j + 1) + '_').css('background-color', "");
                $('#' + arguments_list[i].id + 'alt_' + (j + 1) + '_').css('color', "");
		        $('#' + arguments_list[i].id + 'alt_' + (j + 1) + '_').css('background-color', "");
            }
        }
    }

}

function brightenSchemaHeader(schema_id) {

    $("#schema_" + schema_id + '_').css('color', "");
    $("#schema_" + schema_id + '_').css('background-color', "");   
    
}

function getDisplayedExamples(frame_id) {

    var lexical_units = getFrameLexicalUnits(frame_id);
    
    displayed_examples = [];
    
    var i;
    var to_display = false;
    for (i = 0; i < examples.length; i++) {
        to_display = false;
        var j;
        for (j = 0; j < lexical_units.length; j++) {
            if(examples[i].meanings.indexOf(parseInt(lexical_units[j].id)) != -1) {
                to_display = true;
            }
        }
        if (to_display) {
            displayed_examples.push(examples[i]);
        }
    }

}

function displayExamples() {
    
    $("#semantics-examples").html(getDisplayedExamplesTable());
    
}

function getFrameLexicalUnits(frame_id) {

    var selected_lexical_units = [];

    var i;
    for (i = 0; i < lexical_units_frames.length; i++) {
        if (lexical_units_frames[i].indexOf(frame_id) != -1) {
            selected_lexical_units = selected_lexical_units.concat(lexical_units_num[i]);
        }
    }

    return selected_lexical_units;

}

function getDisplayedExamplesTable() {
    var table = '<table id="examples_table" class="ChangeControlTable">';
    
    table += '<tr>';
    table += '<td class="ColumnHeader">Identyfikator:</td>';
    table += '<td class="ColumnHeader">Przykład:</td>';
    table += '<td class="ColumnHeader">Źródło:</td>';
    table += '<td class="ColumnHeader">Ocena:</td>';
    table += '</tr>';
    
    var i;
    for (i = 0; i < displayed_examples.length; i++){
    	var exampleDomId = 'example_' + displayed_examples[i].id;
        table += '<tr id="' + exampleDomId + '" class="ExampleRow">';
        table += '<td ' + 'onclick=showExampleArguments("' + exampleDomId + '")' + '>' + displayed_examples[i].id + '</td>';
        table += '<td ' + 'onclick=showExampleArguments("' + exampleDomId + '")' + '>' + displayed_examples[i].sentence + '</td>';
        table += '<td ' + 'onclick=showExampleArguments("' + exampleDomId + '")' + '>' + displayed_examples[i].source + '</td>';
        table += '<td ' + 'onclick=showExampleArguments("' + exampleDomId + '")' + '>' + displayed_examples[i].opinion + '</td>';
        table += '</tr>';
    }
    
    table += '</table>';
    
    return table;
}

function color(what, how, disconnected_background, disconnected_text) {

    for (i = 0; i < connected[what].length; i++) {
        $('.' + connected[what][i]).css('background-color', how);
        $('.' + what).css('background-color', how);
    }

    capo = frame_id(what)
    for (i = 0; i < disconnected[capo].length; i++) {
        $('.' + disconnected[capo][i]).css('background-color', disconnected_background);
        $('.' + disconnected[capo][i]).css('color', disconnected_text);
    }

}

function schemaClick(class_id, lex) {
    
    var table = roles_display_table;
    if (lex.length != 0){
	table = roles_display_table_full;
    }

    var field_ids;
    if (class_id.split('arg').length == 1) {
        field_ids = position_arguments[class_id].slice();
    } else {
        if (class_id.split('_').length > 7) {
            if (parseInt(class_id.split('_')[5]) < 0) {
                return;
            }
        }
        field_ids = [class_id];
    }

    if (control == "connect") {
        if (op == "none") {
            return;
        }
        if (op == "add_argument") {
            // highlighted_id = "26"
	    var local = frame_content[highlighted_id].local;
	    if (!local) {
		return;
	    }
            var frame_id = parseInt(highlighted_id);

            if (roleFree(frame_id, field_ids)) {

                var choose_role = {
                        state0: {
                            title: 'Wybierz rolę',
                            html: table,
                            buttons: { Anuluj: -1, Zatwierdź: 1 },
                            focus: 1,
                            close: function(){return result;},
                            submit: function(e,v,m,f){ 
                            
                                if (v == -1) {
                                    e.preventDefault();
                                    $.prompt.close();
                                }
                                if (v == 1) {
                                    e.preventDefault();
                                    
                                    var roles = normalizeFormData(f.roles);

                                    // var frame_id = parseInt(highlighted_id);
                                    var complement_id = addArgument(frame_id, field_ids, roles);
                                    
                                    if (complement_id) {
                                        var h = "frame_" + highlighted_id + "_";
                                        var a = complement_id;  //"frame_" + highlighted_id + "_comp_" + complement_id + "_";
                                        
                                        // re-draw and re-color frame
                                        frameClick(h);
                                        displayFrames();
                                        frameClick(a);
                                        
                                        result = true;
                                        $.prompt.close();
                                    } /*else {
                                        alert("Wybrano niepoprawne role!");
                                    } */ 
                                }
                                
                            }
                        },
                    };
                if (change == true) {
                    alertSemantics();
                } else {
                    $.prompt(choose_role);
                }
            } else {
                alert("Nie można ponownie podłączyć tej samej pozycji składniowej");
            }
            
        }
        if (op == "add_realization") {
            if (change == true) {
                alertSemantics();
                return;
            }
            if (arg == "") {
                return;
            } else {
                // arg = "frame_26_comp_36_(lemma_)"
                if (arg.split('_')[4] == 'lemma' && lex.length == 0) {
                    alert("Nie można podłączyć do lematu!");
                    return;
                }
                var frame_id = parseInt(parseInt(arg.split('_')[1]));
                var i, j;
                var can_connect = false;
                if (roleFree(frame_id, field_ids)) {
                    can_connect = true;
                }
                var connect = true;
                for (i = 0; i < field_ids.length; i++) {
                    if (connected[arg].indexOf(field_ids[i]) != -1) {
                    connect = false;
                    break;
                    }
                }
                if (connect && !can_connect) {
                    alert("Nie można ponownie podłączyć tej samej pozycji składniowej");
                } else {
                    for (i = 0; i < field_ids.length; i++) {
                        if (!connect) {
                            // disconnect
                            j = connected[arg].indexOf(field_ids[i])
                            if (j != -1) {
                                connected[arg].splice(j, 1);
                                j = connected_reverse[field_ids[i]].indexOf('frame_' + frame_id + '_')
                                connected_reverse[field_ids[i]].splice(j, 1);
                                frames_operations.push({operation: 'disconnect', arg: arg, connect: field_ids[i]});
                                var a = arg;
                                frameClick("");
                                frameClick(a);
                            }
                        } else {
                            //connect
                            j = connected[arg].indexOf(field_ids[i])
                            if (j == -1) { // redundant
                                connected[arg].push(field_ids[i]);
                                if (typeof(connected_reverse[field_ids[i]]) == 'undefined') {
                                    connected_reverse[field_ids[i]] = []
                                }
                                connected_reverse[field_ids[i]].push('frame_' + frame_id + '_');
                                frames_operations.push({operation: 'connect', arg: arg, connect: field_ids[i]});
                                var a = arg;
                                frameClick("");
                                frameClick(a);
                            }
                        }
                    }
                } 
            } 
        }
    } else {
        return;
    }
}

function selectSchema(schema_id) {
	deselect();
    $("#schema_" + schema_id + "_").css('background-color', 'LightSteelBlue');
    $("#schema_" + schema_id + "_").css('border-width', '5px');
    getSchemaExamples(schema_id);
    displayExamples();
}

function deselectSchema() {
	$('[class^=schema_]').each(function(){
		$(this).css('background-color', "");
		$(this).css('background', "");
		$(this).css('border-width', '');
	});
}

function getSchemaExamples(schema_id) {
	
    displayed_examples = [];
    for(var i=0; i<window.examples.length; i++) {
      var exampleSchemaId = schemaId(window.examples[i].arguments[0].id);
      if(exampleSchemaId == schema_id) {
    	  displayed_examples.push(window.examples[i]);
      }
    }

}

var exampleSelectionColor = "rgb(176,196,222)";

function showExampleArguments(id) {
	clearExamplesSelection();
	selectExample(id);
	selectExampleArguments(id);
}

function clearExamplesSelection() {
	$('[id^=example_][selected=selected]').children().css('background-color', "");
	$('[id^=example_][selected=selected]').removeAttr('selected');
}

function selectExample(example_dom_id)
{  	 
	$('#' + example_dom_id).attr('selected', "selected");
	$('#' + example_dom_id).children().css('background-color', exampleSelectionColor);
}

function selectExampleArguments(example_dom_id) {
	var selected_example = null;
	var selected_example_id = example_dom_id.replace('example_', '');
	clearExampleArgumentsSelection();
	
	for(i = 0; i < window.nkjp_examples.length; i++) {
		if(window.nkjp_examples[i].example_id == selected_example_id) {
			selected_example = window.nkjp_examples[i];
			break;
		}
	}
	
	if(selected_example) {
		var selected_schema_id = parseId(selected_example.arguments_ids[0])['frame_id'];
		goToFrame('schema_'+selected_schema_id+'_', document.getElementById('schemas'));
		for(i = 0; i < selected_example.arguments_ids.length; i++) {
			var arg_dom_id = selected_example.arguments_ids[i].replace('frame', 'schema');
			$('[id^=' + arg_dom_id + ']').each(function(){
				$(this).attr('selected', "selected");
			});
		}
	}
}

function clearExampleArgumentsSelection() {
	$('[id^=schema_][id*=_arg_][selected=selected]').each(function() {
		$(this).removeAttr('selected');
	});
}

function frame_id(class_id) {
    parts = class_id.split('_');
    if (parts.length < 3) {
        console.log("Błąd wywołania");
        return "";
    }
    var result = "";
    for (i = 0; i < 2; i++) {
        result += parts[i] + '_';
    }
    return result;
}

function value_compare(a, b) {
    return b.value - a.value;
}

/////////////////////////// Splitters ///////////////////////////

var hSplitterId = 'semantics-hsplit';
var topSplitId = 'semantics-hsplit-top';
var bottomSplitId = 'semantics-hsplit-bottom';
var topVSplitterId = 'semantics-vsplit-top';
var bottomVSplitterId = 'semantics-vsplit-bottom';
var topLeftSplitId = 'frames';
var topRightSplitId = 'schemas';
var bottomLeftSplitId = 'control';
var bottomRightSplitId = 'semantics-examples';

function createHSplitter() {
  $('#'+hSplitterId).height($('#right').height() - 70);
  
  if ($.fn.splitter) {
	  
	$(window).resize(function() {
		$('#'+hSplitterId).height($('#right').height() - 70);
	});
	  
    $('#'+hSplitterId).bind('resize', function(e) {
		  var resizeEvt;
	      clearTimeout(resizeEvt);
	      resizeEvt = setTimeout(function() {
	        	$('#'+topVSplitterId).trigger('resize', $('#'+topLeftSplitId).width());
	            $('#'+bottomVSplitterId).trigger('resize', $('#'+bottomLeftSplitId).width()+7);
	        }, 50);
		  e.stopPropagation();
	});
	  
    $('#'+topSplitId).bind('resize', function(e) {
    	$('#'+topVSplitterId).height($('#'+topSplitId).height());
    	$('#'+topVSplitterId).children().each(function () {
    		$(this).height($('#'+topSplitId).height() - 7);
    	});
    	
    	$('#'+bottomVSplitterId).height($('#'+bottomSplitId).height());
    	$('#'+bottomVSplitterId).children().each(function () {
    		$(this).height($('#'+bottomSplitId).height() - 7);
    	});
        e.stopPropagation();
    });
    $('#'+bottomSplitId).bind('resize', function(e) {
      e.stopPropagation();
    });
    $('#'+hSplitterId).splitter({
      type: "h",
      minTop: 200,
      minBottom: 100,
      sizeBottom: 170,
      resizeToWidth: true,
      outline: true
    });
  }
}

function createVTopSplitter() {
  var w=$('#'+topVSplitterId).width();
  
  $('#'+topVSplitterId).height(2*$('#right').height()/3);
  
  if ($.fn.splitter) {
    $('#'+topLeftSplitId).bind('resize', function(e) {
    	$('#'+topVSplitterId).height($('#'+topSplitId).height());
    	$('#'+topVSplitterId).children().each(function () {
    		$(this).height($('#'+topSplitId).height() - 7);
    	});
    	$('#'+topRightSplitId).width($('#'+topRightSplitId).width() - 20);
        e.stopPropagation();
    });
    $('#'+topRightSplitId).bind('resize', function(e) {
      e.stopPropagation();
    });
    $('#'+topVSplitterId).splitter({
      type: "v",
      minLeft: 50,
      sizeLeft: w/2,
      resizeToWidth: true,
      outline: true
    });
  }
}

function createVBottomSplitter() {
  var w=$('#'+bottomVSplitterId).width();
  $('#'+bottomVSplitterId).height($('#right').height()/3);
  if ($.fn.splitter) {
    $('#'+bottomLeftSplitId).bind('resize', function(e) {
    	$('#'+bottomVSplitterId).height($('#'+bottomSplitId).height());
    	$('#'+bottomVSplitterId).children().each(function () {
    		$(this).height($('#'+bottomSplitId).height()-7);
    	});

    	$('#'+bottomLeftSplitId).width($('#'+bottomLeftSplitId).width() - 7);
    	$('#'+bottomRightSplitId).width($('#'+bottomRightSplitId).width() - 20);
        e.stopPropagation();
    });
    $('#'+bottomRightSplitId).bind('resize', function(e) {
      e.stopPropagation();
    });
    $('#'+bottomVSplitterId).splitter({
      type: "v",
      sizeLeft: w/3,
      minLeft: 200,
      resizeToWidth: true,
      outline: true
    });
  }
}