var frame_localization = [];    // list of localizations of all frames on page display
var frame_content = [];         // list of contents of all frames
var free_complement_id = -1;
var free_frame_id = -1;
var free_preference_id = -1;
var semantic_opinion_vals = [];

function selectedFrame() {
    return "frame_" + highlighted_id + "_";
}

function selectedFrameId() {
    return highlighted_id;
}

function getFrames(frames_display){
    var i, j;
    lexical_units_num = [];
    frame_content = [];
    for (i = 0; i < frames_display.length; i++) {
        lexical_units_num.push(frames_display[i].lexical_units);
        lexical_units_frames[i] = [];
        
        var frames = frames_display[i].frames;
	var visible = frames_display[i].visible;
	var local = frames_display[i].local;
	var locked = frames_display[i].locked;
        for (j = 0; j < frames.length; j++) {
            frame_content[frames[j].frame_id] = frames[j];
	    frame_content[frames[j].frame_id]['visible'] = visible;
	    frame_content[frames[j].frame_id]['local'] = local;
	    frame_content[frames[j].frame_id]['locked'] = locked;
            frame_localization[frames[j].frame_id] = {"units": i, "position": j};
            lexical_units_frames[i].push(frames[j].frame_id);
        }
    }
}

function memorizeOpinions(opinions_list){
    var i;

    for (i = 0; i < opinions_list.length; i++){
        semantic_opinion_vals[opinions_list[i].id] = opinions_list[i].name;
    }
}

function getStatusesForFrame(frame_id){
    // TODO: limit possible values
    var display = "";
    
    for (var id in semantic_opinion_vals){
        display += "<input type = \"radio\" name = \"opinion\" value = \"" + id + "\">" + semantic_opinion_vals[id] +  "<br>";
    }
    
    return display;
}

function getDisplay(visibility, checkboxes) {
    display = '';
    var i, j;
    for ( i = 0; i < lexical_units_num.length; i++) {
	if (lexical_units_frames[i].length > 0){
	var visible = frame_content[lexical_units_frames[i][0]].visible;
	if (visible == visibility) {
	    display += '<div id="lus_' + i + '_">';
	    display += '<div>';
	    if (checkboxes) {
		var frame_id = frame_content[lexical_units_frames[i][0]].frame_id;
		display += '<input type="checkbox" name= "frames" value="' + frame_id + '"';
		if (frame_content[lexical_units_frames[i][0]].locked) {
		    display += " disabled"
		}
		display += '>';
	    }
	    
	    var units = [];
	    for (j = 0; j < lexical_units_num[i].length; j++) {
		var id = parseInt(lexical_units_num[i][j].id);
		var lid = indexOfId(lexical_units, id);
		var u = '';
		if (lid == -1) {
		    u += '<em>';
		    u += lexical_units_num[i][j].base;
		    u += '-';
		    u += lexical_units_num[i][j].sense;
		    u += '</em>';
		} else {
		    u += '<strong title="';
		    u += lexical_units[lid].glossa;
		    if (lexical_units[lid].glossa != '') {
			u += '\n';
		    }
		    u += lexical_units[lid].definition;
		    if (lexical_units[lid].definition != '') {
			u += '\n';
		    }
		    u += lexical_units[lid].location;
		    u +='"> '; 
		    u += lexical_units[lid].base + '-' + lexical_units[lid].sense;
		    u += '</strong>';
		}
		units.push(u);
	    }
	    var frames = lexical_units_frames[i];
	    display += units.join()
	    for (j = 0; j < frames.length; j++) {
		display += '<div id="lus_' + i + '_pos_' + j +'_">';
		display += getFrameDisplay(frame_content[frames[j]]);
		display += '</div>';
	    }
	    display += '</div>';

	    display += '</div>';
	}
	}
    }
    return display;
}

function reloadFrames(lid){
    $.getJSON(ajax_frames, {lemma_id: lid}, function(data){
	lexical_units_frames = [];
        getFrames(data.frames_display);
        memorizeConnections(data.connections.connected,
	                    data.connections.connected_reverse);
        alternationCounts(data.alternations);
	displayFrames();
        $("#semantic-frames-count").empty();
      	$("#semantic-frames-count").append(data.frames_count);
    });
}

function displayFrames(){
    $("#frames").html(getDisplay(true, false));
}

function getFrameDisplay(frame_description){
    var i, j;
    var display = '<table><tr><td>';
    display += '<table class="InactiveFrameTable">';
    display += '<tr><td class="ColumnHeader">Rama:</td><td id="frame_' + frame_description.frame_id + '_" class="frame_' + frame_description.frame_id + '_" colspan="' + frame_description.colspan + '" onclick="frameClick(\'frame_' + frame_description.frame_id + '_\', \'frame_' + frame_description.frame_id + '_\')">';
    display += '<span class="Opinion">' + frame_description.status + ' [' + frame_description.frame_id + ']</span>';
    // display += '</td>';
    if (frame_description.lemma.include) {
        display += '<table style="float: right"><td id="' + frame_description.lemma.csv_id + '" class="' + frame_description.lemma.csv_class + '" onclick="var e = arguments[0]; e.stopPropagation(); frameClick(\'' +frame_description.lemma.csv_id + '\', \'' + frame_description.lemma.csv_class + '\')">Lemma</td></table>';
    }
    display += '</td>';
    display += '</tr>';
    display += '<tr>';
    display += '<td class="ColumnHeader">Rola:</td>';
    for (i = 0; i < frame_description.display.roles.length; i++) {
        display += '<td id="' + frame_description.display.roles[i].csv_id + '" class="' + frame_description.display.roles[i].csv_class + '" onclick="frameClick(\'' +frame_description.display.roles[i].csv_id + '\', \'' + frame_description.display.roles[i].csv_class + '\')">';
        var roles = frame_description.display.roles[i].argument;
        var role_names = [];
        var j;
        for (j = 0; j < roles.length; j++) {
            role_names.push(role_name[parseInt(roles[j])]);
        }
        var displayed_role = "";
        if (role_names.length > 0)
        {
            displayed_role += role_names[0];
        
            for (j = 1; j < role_names.length; j++) {
                displayed_role += ", ";
                displayed_role += role_names[j];
            }
        }
        display += displayed_role;
        display += '</td>';
    }
    display += '</tr>';
    display += '<tr>';
    display += '<td class="ColumnHeader" rowspan="' + frame_description.rowspan + '">Preferencje <br/>selekcyjne:</td>';
    for (i = 0; i < frame_description.display.preferences.length; i++) {
        for (j = 0; j < frame_description.display.preferences[i].length; j++) {
            display += '<td id="' + frame_description.display.preferences[i][j].csv_id + '" class="' + frame_description.display.preferences[i][j].csv_class + '" onclick="frameClick(\'' + frame_description.display.preferences[i][j].csv_id + '\', \'' + frame_description.display.preferences[i][j].csv_class + '\')">';
            display += frame_description.display.preferences[i][j].preference;
            display += '</td>';
        }
        display += '</tr><tr>';
    }
    display += '</tr>';
    display += '</table>';
    display += '</td></tr></table>';
    return display;
}

// create new empty frame for selected lexical units
function newFrame(units) {
    var y = lexical_units_num.length;
    var x = free_frame_id;
    
    var newdiv = document.createElement('div');
    var divIdName = 'lus_' + y + '_';
    newdiv.setAttribute('id',divIdName);
    document.getElementById("frames").appendChild(newdiv);
    
    frame_localization[x] = {units: y, position: 0};
    
    lexical_units_frames.push(["" + x]);
    
    var units_list = [];
    var i;
    for (i = 0; i < units.length; i++) {
        lu = lexical_units[indexOfId(lexical_units, units[i])];
        units_list.push({base: lu.base, sense: lu.sense, id: lu.id});
    }
    lexical_units_num.push(units_list);
    
    frame_content[free_frame_id] = {colspan: "1", rowspan: "1", status: "brak", frame_id: "" + x, display: {preferences:[[]], roles:[]}, lemma: {include: false}, local:true, visible:true};
    frames_operations.push({operation: "create_frame", meanings: units_list, id: x});
    free_frame_id = free_frame_id - 1;
}

function validateRoles(roles) {
    
    if (roles.length > 2) {
        return false;
    };

    var ok = false;
    var i;
    for (i = 0; i < roles.length; i++) {
        if (role_color[roles[i]].color != 'None') {
            ok = !ok
        }
    }

    if (!ok) {
        return false;
    }
    
    return true;
}

// assign role(s) to given compelement
function setRole(frame_id, complement_id, roles) {

    if (validateRoles(roles)) {

        for (i = 0; i < frame_content[frame_id].display.roles.length; i++) {
            if (frame_content[frame_id].display.roles[i].csv_id == 'frame_' + frame_id + '_comp_' + complement_id + '_') {
                frame_content[frame_id].display.roles[i].argument = roles;
            }
        }
        
        frames_operations.push({operation: "assign_role", frame_id: frame_id, complement_id: complement_id, role: roles});
        return true;
    } else {
        return false;
    }
}


function removeFrame(frame_id) {
    var units = [];
    
    var i;
    for (i = 0; i < lexical_units_frames.length; i++) {
        if (lexical_units_frames[i].indexOf(frame_id) != -1) {
            var j = lexical_units_frames[i].indexOf(frame_id);

            lexical_units_frames[i].splice(j, 1);
            if (lexical_units_frames[i].length == 0) {
                var k;
                for (k = 0; k < lexical_units_num[i].length; k++) {
                    units.push(lexical_units_num[i][k].id);
                }
                lexical_units_num[i] = [];
            }
        }
    }
    
    var connections = getConnected(frame_id);
    removeFrameConnections(frame_id);
    frame_content[frame_id] = null;
    
    frames_operations.push({operation: "remove_frame", id: frame_id, units: units, connections: connections});
}

function roleFree(frame_id, field_ids) {
    var i;
    for (i = 0; i < field_ids.length; i++) {
        if (typeof(connected_reverse[field_ids[i]]) != 'undefined') {
            if (connected_reverse[field_ids[i]].indexOf('frame_' + frame_id + '_') >= 0) {
                return false;
            }
        }
    }
    return true;
}

function addArgument(frame_id, field_ids, roles) {

    if (validateRoles(roles)) {
        if (isLemma(roles)) {
            if (frame_content[frame_id].lemma.include) {
                alert("Ta rama ma już pole związane z lematem!");
                return;
            } else {
		frame_content[frame_id].lemma = {include: true, csv_class: 'frame_' + frame_id + '_comp_' + free_complement_id + '_lemma_', csv_id: 'frame_' + frame_id + '_comp_' + free_complement_id + '_lemma_'};
		connected['frame_' + frame_id + '_comp_' + free_complement_id + '_lemma_'] = field_ids;
                var complement_id_num = free_complement_id;
                free_complement_id = free_complement_id - 1;
                var complement_id = "frame_" + highlighted_id + "_comp_" + complement_id_num + "_lemma_";
                var conn_complement_id = "frame_" + highlighted_id + "_comp_" + complement_id_num + "_";
            }
        } else {
	    frame_content[frame_id].colspan = "" + (parseInt(frame_content[frame_id].colspan) + 1);
	    frame_content[frame_id].display.roles.push({csv_class: 'frame_' + frame_id + '_comp_' + free_complement_id + '_', csv_id: 'frame_' + frame_id + '_comp_' + free_complement_id + '_', argument: ''});
	    var i;
	    for (i = 0; i < frame_content[frame_id].rowspan; i++) {
		frame_content[frame_id].display.preferences[i].push({csv_class: 'frame_' + frame_id + '_comp_' + free_complement_id + '_', csv_id: 'frame_' + frame_id + '_comp_' + free_complement_id + '_pref_-' + i + '_', preference: ''});
	    }
	    connected['frame_' + frame_id + '_comp_' + free_complement_id + '_'] = field_ids;
            var complement_id_num = free_complement_id;
            free_complement_id = free_complement_id - 1;
            var complement_id = "frame_" + highlighted_id + "_comp_" + complement_id_num + "_";
            var conn_complement_id = complement_id;
        }
        
        for(i = 0; i < field_ids.length; i++) {
            if (typeof(connected_reverse[field_ids[i]]) == 'undefined') {
                connected_reverse[field_ids[i]] = [];
            }
            connected_reverse[field_ids[i]].push('frame_' + frame_id + '_');
        }

        for (i = 0; i < frame_content[frame_id].display.roles.length; i++) {
            if (frame_content[frame_id].display.roles[i].csv_id == complement_id) {
                frame_content[frame_id].display.roles[i].argument = roles;
            }
        }
        
        frames_operations.push({operation: 'add_argument', frame_id: frame_id, id: complement_id_num, role: roles});
        for (i = 0; i < field_ids.length; i++) {
            frames_operations.push({operation: 'connect', arg: conn_complement_id, connect: field_ids[i]});
        }

        return complement_id;
    } else {
        alert("Wybrano niepoprawny zestaw ról!");
        return false;
    }

}

function removeArgument(frame_id, complement_id, argument) {
    var pos = -1;
    var arg = argument;
    
    if (argument.split('_').length == 5) { // zwykły argument
	var i;
	for (i = 0; i < frame_content[frame_id].display.roles.length; i++) {
	    if (frame_content[frame_id].display.roles[i].csv_id == arg) {
		pos = i;
	    }
	}

	frame_content[frame_id].display.roles.splice(pos, 1);

	var j;
	for (j = 0; j < frame_content[frame_id].display.preferences.length; j++) {
	    frame_content[frame_id].display.preferences[j].splice(pos, 1);
	}
    } else { // argument leksykalny
        frame_content[frame_id].lemma.include = false;
    }

    removeArgumentConnections(frame_id, complement_id);
    
    frames_operations.push({operation: 'remove_argument', frame_id: frame_id, complement_id: complement_id});
}

function changeUnits(frame_id, units) {
    var id = "" + frame_id;

    var j;
    for (j = 0; j < lexical_units_num.length; j++) {
        if (lexical_units_frames[j].indexOf(id) != -1) {
	    var temp = [];
	    var l;
	    for (l = 0; l < lexical_units_num[j].length; l++) {
		var lu = lexical_units_num[j][l]
		if (indexOfId(lexical_units, lu.id) == -1) {
		    temp.push(lu);
		}
	    }
            lexical_units_num[j] = temp;
            var i;
            for (i = 0; i < units.length; i++) {
                var k;
                
                for (k=0; k < lexical_units.length; k++) {
                    if (lexical_units[k].id == parseInt(units[i])) {
                        lexical_units_num[j].push(lexical_units[k]);
                        break;
                    }
                }
                
            }
            break;
        }
    }

    frames_operations.push({operation: "change_units", frame_id: frame_id, units: units});
}

function setOpinion(frame_id, opinion) {
    var id = "" + frame_id;

    frame_content[frame_id].status = semantic_opinion_vals[opinion];

    frames_operations.push({operation: "set_opinion", frame_id: frame_id, opinion: opinion[0]});
}
 
function isNewPreference(frame_id, complement_id, preference) {

    var i, j, k;
    
    j = -1;
    for (k = 0; k < frame_content[frame_id].display.roles.length; k++) {
        if (frame_content[frame_id].display.roles[k].csv_class == 'frame_' + frame_id + '_comp_' + complement_id + '_') {
            j = k;
        }
    }
    if (j < 0) {
        return false;
    }
    
    i = -1;
    for (k = 0; k < frame_content[frame_id].display.preferences.length; k++) {
        if (frame_content[frame_id].display.preferences[k][j].preference == preference.text.split(':')[0]) {
            return false;
        }
    }
    return true;

}

function addPreference(frame_id, complement_id, preference) {
    if (isNewPreference(frame_id, complement_id, preference)) {

        var i, j, k;
        
        j = -1;
        for (k = 0; k < frame_content[frame_id].display.roles.length; k++) {
            if (frame_content[frame_id].display.roles[k].csv_class == 'frame_' + frame_id + '_comp_' + complement_id + '_') {
                j = k;
            }
        }
        if (j < 0) {
            return false;
        }
        
        i = -1;
        for (k = 0; k < frame_content[frame_id].display.preferences.length; k++) {
            if (frame_content[frame_id].display.preferences[k][j].preference == "" && i < 0) {
                i = k;
            }
        }
        if (i < 0) { 
            i = parseInt(frame_content[frame_id].rowspan);
        
            frame_content[frame_id].rowspan = "" + (i + 1);
            
            var new_row = [];
            for (k = 0; k < frame_content[frame_id].display.roles.length; k++) {
                new_row.push({csv_class: frame_content[frame_id].display.roles[k].csv_class, csv_id: frame_content[frame_id].display.roles[k].csv_class + "pref_-" + frame_content[frame_id].rowspan + "_", preference: ""});
            }
            frame_content[frame_id].display.preferences.push(new_row);
        }

        var preference_id = preference.type + free_preference_id;
        frame_content[frame_id].display.preferences[i][j].csv_id = frame_content[frame_id].display.preferences[i][j].csv_class + "pref_" + preference_id + "_";
        frame_content[frame_id].display.preferences[i][j].preference = preference.text.split(':')[0];
        free_preference_id = free_preference_id - 1;

        frames_operations.push({operation: 'add_preference', frame_id: frame_id, complement_id: complement_id, preference_id: preference_id, preference: preference});
        return preference_id;
    }
    
}

function removePreference(frame_id, complement_id, preference_id) {
    var i, j, k;
    
    j = -1;
    for (k = 0; k < frame_content[frame_id].display.roles.length; k++) {
        if (frame_content[frame_id].display.roles[k].csv_class == 'frame_' + frame_id + '_comp_' + complement_id + '_') {
            j = k;
        }
    }
    if (j < 0) {
        return false;
    }
    
    i = -1;
    for (k = 0; k < frame_content[frame_id].display.preferences.length; k++) {
        if (frame_content[frame_id].display.preferences[k][j].csv_id == 'frame_' + frame_id + '_comp_' + complement_id + '_pref_' + preference_id + '_') {
            i = k;
        }
    }
    if (i < 0) { 
        return false;
    } 

    frame_content[frame_id].display.preferences[i][j].csv_id = 'frame_' + frame_id + '_comp_' + complement_id + '_pref_' + (- i) + '_';
    frame_content[frame_id].display.preferences[i][j].preference = "";
    
    for (k = i; k < frame_content[frame_id].display.preferences.length - 1; k++) {
        var tmp = frame_content[frame_id].display.preferences[k][j];
        frame_content[frame_id].display.preferences[k][j] = frame_content[frame_id].display.preferences[k + 1][j];
        frame_content[frame_id].display.preferences[k + 1][j] = tmp;
    }
    
    var remove = true;
    for (k = 0; k < frame_content[frame_id].display.preferences[frame_content[frame_id].display.preferences.length - 1].length; k++) {
        if (frame_content[frame_id].display.preferences[frame_content[frame_id].display.preferences.length - 1][k].preference != "") {
            remove = false;
        }
    }
    if (remove) {
        k = parseInt(frame_content[frame_id].rowspan);
        if (k > 1) {
            frame_content[frame_id].display.preferences.splice(frame_content[frame_id].display.preferences.length - 1, 1);
            frame_content[frame_id].rowspan = "" + (k - 1);
        }
    }
    
    frames_operations.push({operation: 'remove_preference', frame_id: frame_id, complement_id: complement_id, preference_id: preference_id});
    return true;
}

function saveFrames() {
    if (change == true) {
        alertSemantics();
    } 
    else if(window.lemma_id != getActualLemmaId(window.lemma_id)){
    	alertOldSchemas();
    }
    else if (!userIsAuthenticated()) {
    	alertUserNotAuthenticated();
    }
    else {
        frameClick("");
        $.post(ajax_modify_frames, {"operations": JSON.stringify(frames_operations), "lemma_id": lemma_id}, function(data){
            $.getJSON(ajax_units, {"lemma_id": window.lemma_id}, function(units) {
                memorizeLexicalUnits(units.lexical_units);
                basicLexicalUnitsData(units.informations);
		getFrames(data.frames_display);
		displayFrames();
		memorizeConnections(data.connections.connected, data.connections.connected_reverse);
		$("#semantic-frames-count").empty();
                $("#semantic-frames-count").append(data.frames_count);
                updateSchemataConnections();
            });
        }, 'json');
        frames_operations = [];
    }
}


