var schema_type_vals = [];
var aspect_vals = [];
var reflex_vals = [];
var neg_vals = [];
var pred_vals = [];
var opinion_vals = [];
var filter_schema_type_val = '*';
var filter_aspect_val = '*';
var filter_reflex_val = '*';
var filter_neg_val = '*';
var filter_pred_val = '*';
var filter_opinion_val = '*';
var filter_position_val = '.*';
var filter_argument_val = '.*';
var prev_filter_schema_type_val = '*';
var prev_filter_aspect_val = '*';
var prev_filter_reflex_val = '*';
var prev_filter_neg_val = '*';
var prev_filter_pred_val = '*';
var prev_filter_opinion_val = '*';
var prev_filter_position_val = '.*';
var prev_filter_argument_val = '.*';

function cancel_schemata_filtering() {
	window.filter_position_val = '.*';
    window.filter_argument_val = '.*';
    window.filter_schema_type_val = '*'; 
    window.filter_aspect_val = '*';
    window.filter_reflex_val = '*';
    window.filter_neg_val = '*';
    window.filter_pred_val = '*';
    window.filter_opinion_val = '*';
    $('#frame_filter #argument_filter').val(window.filter_argument_val);
    $('#frame_filter #position_filter').val(window.filter_position_val);
    $('#frame_filter #schema_type_filter').val(window.filter_schema_type_val);
    $('#frame_filter #aspect_filter').val(window.filter_aspect_val);
    $('#frame_filter #reflex_filter').val(window.filter_reflex_val);
    $('#frame_filter #neg_filter').val(window.filter_neg_val);
    $('#frame_filter #pred_filter').val(window.filter_pred_val);
    $('#frame_filter #opinion_filter').val(window.filter_opinion_val);
    $('#frame_filter #argument_filter').trigger('change');
}

function cancel_prev_schemata_filtering() {
    window.prev_filter_position_val = '.*';
    window.prev_filter_argument_val = '.*';
    window.prev_filter_schema_type_val = '*';
    window.prev_filter_aspect_val = '*';
    window.prev_filter_reflex_val = '*';
    window.prev_filter_neg_val = '*';
    window.prev_filter_pred_val = '*'; 
    window.prev_filter_opinion_val = '*';
    $('#prev_frame_filter #argument_filter').val(window.prev_filter_argument_val);
    $('#prev_frame_filter #position_filter').val(window.prev_filter_position_val);
    $('#prev_frame_filter #schema_type_filter').val(window.prev_filter_schema_type_val);
    $('#prev_frame_filter #aspect_filter').val(window.prev_filter_aspect_val);
    $('#prev_frame_filter #reflex_filter').val(window.prev_filter_reflex_val);
    $('#prev_frame_filter #neg_filter').val(window.prev_filter_neg_val);
    $('#prev_frame_filter #pred_filter').val(window.prev_filter_pred_val);
    $('#prev_frame_filter #opinion_filter').val(window.prev_filter_opinion_val);
    $('#prev_frame_filter #argument_filter').trigger('change');
}

function initiateFrameFilters() {
   	  $.ajaxJSON({
         method: 'get',
         url: ajax_get_frame_filter_options,
         data: {
               //message_id: message_id, 
         },
         callback: function(result) {
           window.schema_type_vals = result['schema_type_options'];
           window.aspect_vals = result['aspect_options'];
           window.reflex_vals = result['reflex_options'];
           window.neg_vals = result['neg_options'];
           window.pred_vals = result['pred_options'];
           window.opinion_vals = result['opinion_options'];
         },
     
         error_callback: function(xhr, status, error) {
           error_alert(status + ': ' + error);
         },
       }); 	
}

function filter_update(id) {
	if(id == 'frame_filter')
	{
		window.filter_schema_type_val = $('#frame_filter #schema_type_filter').val();
	    window.filter_aspect_val = $('#frame_filter #aspect_filter').val();
	    window.filter_reflex_val = $('#frame_filter #reflex_filter').val();
	    window.filter_neg_val = $('#frame_filter #neg_filter').val();
	    window.filter_pred_val = $('#frame_filter #pred_filter').val();
	    window.filter_opinion_val = $('#frame_filter #opinion_filter').val();
	    window.filter_position_val = $('#frame_filter #position_filter').val();
	    window.filter_argument_val = $('#frame_filter #argument_filter').val();
	}
	else if(id == 'prev_frame_filter')
	{
		window.prev_filter_schema_type_val = $('#prev_frame_filter #schema_type_filter').val();
	    window.prev_filter_aspect_val = $('#prev_frame_filter #aspect_filter').val();
	    window.prev_filter_reflex_val = $('#prev_frame_filter #reflex_filter').val();
	    window.prev_filter_neg_val = $('#prev_frame_filter #neg_filter').val();
	    window.prev_filter_pred_val = $('#prev_frame_filter #pred_filter').val();
	    window.prev_filter_opinion_val = $('#prev_frame_filter #opinion_filter').val();
	    window.prev_filter_position_val = $('#prev_frame_filter #position_filter').val();
	    window.prev_filter_argument_val = $('#prev_frame_filter #argument_filter').val();
	}
}

function draw_frames_filter(id) {     
    var frame_filter = document.getElementById(id);
    
    p = document.createElement('p');
    text = document.createTextNode("Typ schematu: ");
    p.appendChild(text);
    var select = document.createElement('select');
    select.setAttribute('id', 'schema_type_filter');
    select.setAttribute('name', 'schema_type');
    p.appendChild(select);
    for(var i=0; i<schema_type_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', schema_type_vals[i].value);
      option.appendChild(document.createTextNode(schema_type_vals[i].name));
      select.appendChild(option);
    }
    frame_filter.appendChild(p);
    
    p = document.createElement('p');
    text = document.createTextNode("Aspekt: ");
    p.appendChild(text);
    var select = document.createElement('select');
    select.setAttribute('id', 'aspect_filter');
    select.setAttribute('name', 'ASPEKT');
    p.appendChild(select);
    for(var i=0; i<aspect_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', aspect_vals[i].value);
      option.appendChild(document.createTextNode(aspect_vals[i].name));
      select.appendChild(option);
    }
    frame_filter.appendChild(p);

    p = document.createElement('p');
    text = document.createTextNode("Zwrotność: ");
    p.appendChild(text);
    select = document.createElement('select');
    select.setAttribute('id', 'reflex_filter');
    select.setAttribute('name', 'ZWROTNOSC');
    p.appendChild(select);
    for(var i=0; i<reflex_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', reflex_vals[i].value);
      option.appendChild(document.createTextNode(reflex_vals[i].name));
      select.appendChild(option);
    }
    frame_filter.appendChild(p);
    
    p = document.createElement('p');
    text = document.createTextNode("Negatywność: ");
    p.appendChild(text);
    select = document.createElement('select');
    select.setAttribute('id', 'neg_filter');
    select.setAttribute('name', 'NEGATYWNOŚĆ');
    p.appendChild(select);
    for(var i=0; i<neg_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', neg_vals[i].value);
      option.appendChild(document.createTextNode(neg_vals[i].name));
      select.appendChild(option);
    }
    frame_filter.appendChild(p);
    
    p = document.createElement('p');
    text = document.createTextNode("Predykatywność: ");
    p.appendChild(text);
    select = document.createElement('select');
    select.setAttribute('id', 'pred_filter');
    select.setAttribute('name', 'PREDYKATYWNOŚĆ');
    p.appendChild(select);
    for(var i=0; i<pred_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', pred_vals[i].value);
      option.appendChild(document.createTextNode(pred_vals[i].name));
      select.appendChild(option);
    }
    frame_filter.appendChild(p);
    
    p = document.createElement('p');
    text = document.createTextNode("Opinia: ");
    p.appendChild(text);
    select = document.createElement('select');
    select.setAttribute('id', 'opinion_filter');
    select.setAttribute('name', 'OPINIA');
    p.appendChild(select);
    for(var i=0; i<opinion_vals.length; i++)
    {
      var option = document.createElement('option');
      option.setAttribute('value', opinion_vals[i].value);
      option.appendChild(document.createTextNode(opinion_vals[i].name));
      select.appendChild(option);
    }
    frame_filter.appendChild(p);
    
    p = document.createElement('p');
    text = document.createTextNode("Typ frazy: ");
    p.appendChild(text);
    select = document.createElement('input');
    select.setAttribute('id', 'argument_filter');
    select.setAttribute('name', 'ARGUMENT');       
    p.appendChild(select);
    frame_filter.appendChild(p);
    
    p = document.createElement('p');
    text = document.createTextNode("Pozycja: ");
    p.appendChild(text);
    select = document.createElement('input');
    select.setAttribute('id', 'position_filter');
    select.setAttribute('name', 'POZYCJA');   
    p.appendChild(select);
    frame_filter.appendChild(p);

	if(id == 'frame_filter')
	{
	  $('#frame_filter #schema_type_filter').val(window.filter_schema_type_val);
      $('#frame_filter #aspect_filter').val(window.filter_aspect_val);
      $('#frame_filter #reflex_filter').val(window.filter_reflex_val);
      $('#frame_filter #neg_filter').val(window.filter_neg_val);
      $('#frame_filter #pred_filter').val(window.filter_pred_val);
      $('#frame_filter #opinion_filter').val(window.filter_opinion_val);
      $('#frame_filter #position_filter').val(window.filter_position_val);
      $('#frame_filter #argument_filter').val(window.filter_argument_val);
	}
	else if(id == 'prev_frame_filter')
	{
	  $('#prev_frame_filter #schema_type_filter').val(window.prev_filter_schema_type_val);
      $('#prev_frame_filter #aspect_filter').val(window.prev_filter_aspect_val);
      $('#prev_frame_filter #reflex_filter').val(window.prev_filter_reflex_val);
      $('#prev_frame_filter #neg_filter').val(window.prev_filter_neg_val);
      $('#prev_frame_filter #pred_filter').val(window.prev_filter_pred_val);
      $('#prev_frame_filter #opinion_filter').val(window.prev_filter_opinion_val);
      $('#prev_frame_filter #position_filter').val(window.prev_filter_position_val);
      $('#prev_frame_filter #argument_filter').val(window.prev_filter_argument_val);
	}
	
    //attach autocomplete  
    $('#' + id + ' #argument_filter').autocomplete({  
    	   // triggers when selection performed
    	   select: function(event, ui){
    		   filter_update(id); 
    	   },
           //define callback to format results  
           source: function(req, add){  
                //pass request to server  
                $.getJSON(ajax_argument_lookup, req, function(data) {  
                    //create array for response objects  
                    var suggestions = [];  
                    $.each(data['result'], function(i, val){  
                      suggestions.push(val[0]);  
                });  
                //pass array to callback  
                add(suggestions);  
            });  
          },  
    });  
    $('#' + id + ' #position_filter').autocomplete({  
	 	   // triggers when selection performed
	 	   select: function(event, ui){
	 		   filter_update(id);
	 	   },
           //define callback to format results  
           source: function(req, add){  
                //pass request to server  
                $.getJSON(ajax_position_lookup, req, function(data) {  
                    //create array for response objects  
                    var suggestions = [];  
                    $.each(data['result'], function(i, val){  
                      suggestions.push(val[0]);  
                });  
                //pass array to callback  
                add(suggestions);  
            });  
          },  
    });
}

function filter_frames(schemas, filter_id) {
  var schema_type_val = $('#'+filter_id+' #schema_type_filter').val();
  var aspect_val = $('#'+filter_id+' #aspect_filter').val();
  var reflex_val = $('#'+filter_id+' #reflex_filter').val();
  var neg_val = $('#'+filter_id+' #neg_filter').val();
  var pred_val = $('#'+filter_id+' #pred_filter').val();
  var opinion_val = $('#'+filter_id+' #opinion_filter').val();
  var position_val = $('#'+filter_id+' #position_filter').val().trim();
  var argument_val = $('#'+filter_id+' #argument_filter').val().trim();
  var filtered_frames = new Array();
  
  if(position_val == '.*')
	  position_val = ''
  if(argument_val == '.*')
	  argument_val = ''
  
  for(var i=0; i<schemas.length; i++)
  {
    if((schemas[i].characteristics[3] == aspect_val || aspect_val == '*') 
      && (schemas[i].characteristics[0] == reflex_val || reflex_val == '*')
      && (schemas[i].characteristics[1] == neg_val || neg_val == '*')
      && (schemas[i].characteristics[2] == pred_val || pred_val == '*')
      && (schemas[i].opinion == opinion_val || opinion_val == '*')
      && schema_type_valid(schemas[i], schema_type_val))
    {
      frameMatch = false;
      if(position_val)
    	  frameMatch = has_positions(schemas[i], position_val)
      if(argument_val && (frameMatch || !position_val))
    	  {
    	  
    	  frameMatch = has_arguments(schemas[i], argument_val)
    	  }
      if(frameMatch || (!argument_val && !position_val))
    	  filtered_frames.push(schemas[i]);
    }
  }
  return filtered_frames; 
}

function has_positions(frame, pos_term) {
	var alternatives = pos_term.split('|');
	for(var h=0; h<alternatives.length; h++) {
		var allConjsMatch = true;
		var conjs = alternatives[h].split('&');
		
		for(var i=0; i<conjs.length; i++) {
			try {
				var matched_poss = [];
				var conj = conjs[i].trim();
				var regEx = conj;
				if (regEx.substring(0, 1) == '!') {
					regEx = regEx.substring(1);
				}
				var posRe = new RegExp('^'+escape_regex(regEx)+'$');
				matched_poss = $.grep(frame.positions, 
						  function(pos){
					return pos.text_rep.match(posRe);
				});
				if((matched_poss.length > 0 && conj.startsWith('!')) || 
				   (matched_poss.length == 0 && !conj.startsWith('!'))) {
					allConjsMatch = false;
					break;
				}
			}
			catch(e) {
				allConjsMatch = false;
				break;
			}
		}
		if(allConjsMatch) {
			return true;
		}
	}
	
	return false;
}

function has_arguments(frame, arg_term) {
	var alternatives = arg_term.split('|');
	for(var h=0; h<alternatives.length; h++) {
		var allConjsMatch = true;
		var conjs = alternatives[h].split('&');
		for(var i=0; i<conjs.length; i++) {
			try {
				var matched_args = [];
				var conj = conjs[i].trim();
				var regEx = conj;
				if (regEx.substring(0, 1) == '!') {
					regEx = regEx.substring(1);
				}
				var argRe = new RegExp('^'+escape_regex(regEx)+'$');
				
		    	for(var j=0; j<frame.positions.length; j++) {
		    		matched_args = $.grep(frame.positions[j].arguments, function(arg) {
						return arg.text_rep.match(argRe);
					});
					if(matched_args.length > 0) {
						break;
					}
		    	}
		    	if((matched_args.length > 0 && conj.startsWith('!')) || 
				   (matched_args.length == 0 && !conj.startsWith('!'))) {
					allConjsMatch = false;
					break;
				}
			}
			catch(e) {
				allConjsMatch = false;
				break;
			}
		}
		if(allConjsMatch){
			return true;
		}
	}
	return false;
}

function schema_type_valid(schema, filter_option) {
	if(filter_option == '*') return true;
	else if(filter_option == 'normal' && !schema.is_phraseologic) return true;
	else if(filter_option == 'phraseologic' && schema.is_phraseologic) return true;
	else return false;
}
