$(function() {
  window.selected_real_row_id = -1;
  
  $('#realization-type #realization-type-select').live('change', function (event) {
	  if($(this).val() == 'phrase_type') {
		  $('#create-realization').load(ajax_realization_arg_form, {'form_data': '',
              														'main_argument': false, 
              														'real_id': ''});
	  }
	  else if($(this).val() == 'positions') {
		  $('#create-realization').load(ajax_positions_extension_form);
	  }
  });
  
  $('#main-argument').load(ajax_realization_arg_form, {'form_data': '',
	                                                   'main_argument': true, 
	                                                   'real_id': ''});
  $('#create-realization').load(ajax_realization_arg_form, {'form_data': '',
                                                            'main_argument': false, 
                                                            'real_id': ''});
  
  $('#main-argument .argument-add-form #id_arg_type').live('change', function (event) {
	  realization_arguments_form_change(0, '', true, $(event.target).closest('.argument-add-form'));
  });
  
  $('#main-argument .argument-add-form #id_value_parameter_0').live('change', function (event) {
	  show_realizations();
  });
  
  $('#main-argument .argument-add-form #id_value_arguments_0').live('change', function (event) {
	  realization_arguments_form_change(-1, '', true, $(event.target).closest('.argument-add-form'));
  });
  
  $('#create-realization .argument-add-form #id_arg_type').live('change', function (event) {
	  realization_arguments_form_change(0, '', false, $(event.target).closest('.argument-add-form'));
  });
  
  $('#create-realization .argument-add-form #id_value_positions_0, #create-realization .argument-add-form #id_value_arguments_0, #create-realization .argument-add-form #id_value_parameter_0').live('change', function (event) {
	  realization_arguments_form_change(-1, '', false, $(event.target).closest('.argument-add-form'));
  });

  $('#create-realization .argument-add-form').live('submit', add_realization);
  $('#create-realization .positions-add-form').live('submit', add_realization);
  
  $('#modify-realization-dialog .argument-add-form #id_arg_type').live('change', function (event) {
	  realization_arguments_form_change(0, '', false, $(event.target).closest('.argument-add-form'));
  });
  
  $('#modify-realization-dialog .argument-add-form #id_value_positions_0, #modify-realization-dialog .argument-add-form #id_value_arguments_0, #modify-realization-dialog .argument-add-form #id_value_parameter_0').live('change', function (event) {
	  realization_arguments_form_change(-1, '', false, $(event.target).closest('.argument-add-form'));
  });
  
  $('#modify-realization-dialog .argument-add-form').live('submit', add_realization);
  $('#modify-realization-dialog .positions-add-form').live('submit', add_realization);
  
  $("#get-realizations").live('click', getRealizations);
  
  $("$[id$='-add_position_button']").live('click', function(event){openAddPositionDialog(event)});
  $("$[id$='-add_argument_button']").live('click', function(event){openAddArgumentDialog(event, null, 'Tworzenie typu frazy:')});
  $("$[id$='-add_realization_button']").live('click', function(event){openAddArgumentDialog(event, null, 'Tworzenie rozwinięcia typu frazy:')});
  $("$[id$='-select_argument_button']").live('click', function(event){openSelectArgumentDialog(event, null)});
  
  $("[id$='-argument-form-dialog'] .argument-add-form #id_arg_type'").live('change', function(event) {
	  arguments_form_change(0, null, $(event.target).closest(".argument-add-form"), null)
  });
  
  $("[id$='-argument-form-dialog'] .argument-add-form #id_value_positions_0, [id$='-argument-form-dialog'] .argument-add-form #id_value_arguments_0, [id$='-argument-form-dialog'] .argument-add-form #id_value_parameter_0").live('change', function(event) {
	  arguments_form_change(-1, null, $(event.target).closest(".argument-add-form"), null)
  });
  
  $('form.create-position-form').live('submit', create_position_form_submit);
  $('#position #remove-position').live('click', remove_position);
  $('#argument #remove-argument').live('click', remove_argument);
  $('#position #edit-position').live('click', edit_position);
  $('#argument #edit-argument').live('click', edit_argument);
  $('#argument #edit-realization').live('click', edit_realization);
  
  $("[id$='-argument-form-dialog'] .argument-add-form").live('submit', argument_form_submit);
  
  $('form.create-position-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
  });
  $('form.argument-add-form').live('reset', function(){
	  $(this).closest("$[id$='-dialog']").dialog('close');
  });
  $('form.argument-add-form #show-realizations').live('click', show_argument_realizations);

  addModifyRealizationDialog();
});

function getRealizations()
{
    ShowProgressAnimation();
    $.ajaxJSON({
      method: 'post',
      url: ajax_create_realizations,
      data: {
        form_data: ''
      },
    callback: function(result) {         
	  HideProgressAnimation();
      lemma_view_location = window.location.toString();
      var url = lemma_view_location.replace('/rozwiniecia_typow_fraz/', '/rozwiniecia_typow_fraz/'+result['file_name']);
      window.open(url,'Download');
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
  });
  return false;
}

function removeRealization(tabId)
{
  if(tabId != -1)
  {
	ShowProgressAnimation();
    realization_id = tabId.replace('realization_', ''); 
    
    main_arg_form = $('#main-argument .argument-add-form');
    main_arg_data = main_arg_form.serializeArray();
    main_arg_data = prepareArgFormData(main_arg_form, main_arg_data, -1);

    $.ajaxJSON({
      method: 'post',
      url: ajax_remove_realization,
      data: {
        realization_id: realization_id,
        main_arg_data: main_arg_data 
      },
      callback: function(result) { 
       window.selected_real_row_id = -1;
       show_realizations();	
       HideProgressAnimation();
      },
      error_callback: function(xhr, status, error) {
        HideProgressAnimation();
        error_alert(status + ': ' + error);
      },
      bad_data_callback: function(result) {
        if (result == 'empty main argument fields') {
          HideProgressAnimation();
          error_alert('Wypełnij wszystkie pola formularza wyboru głównego typu frazy.');
          return false;
        }
        else
        {
          HideProgressAnimation();
          return true;
        }
      },
    });
  }	
}

function realization_arguments_form_change(lastActualValueIdx, arg_id, main_argument, this_form) {
    form_data = this_form.serializeArray();
    this_dialog = this_form.closest("$[id$='-dialog']");
  
  	if(!arg_id) {
  	  form_data = prepareArgFormData(this_form, form_data, lastActualValueIdx);
      form_data.push({name: 'arg_id', value: ''});
    }
    else
        form_data.push({name: 'arg_id', value: arg_id});
    
    data = JSON.stringify(form_data);
    
    place_to_load_form = null
    if (this_dialog.length)
    	place_to_load_form = this_dialog;
    else if (main_argument)
    	place_to_load_form = $('#main-argument');
    else
    	place_to_load_form = $('#create-realization');
    place_to_load_form.empty();
    place_to_load_form.load(ajax_realization_arg_form, {'form_data': data,
    											        'main_argument': main_argument, 
    											        'real_id': ''}, 
    											        function() {
    											        	if(main_argument) {
    											        		show_realizations();
    											        	}
    											        });    
} 

function show_realizations() {
    window.selected_real_row_id = -1;
    this_form = $('#main-argument .argument-add-form');
    form_data = this_form.serializeArray();
    form_data = prepareArgFormData(this_form, form_data, -1);
    form_data.push({name: 'manage', value: true});
    
    data = JSON.stringify(form_data)
    $('#realizations').load(ajax_show_realizations, {'form_data' : data}, function() {
      $("tr.RealizationTableRow").click(function() {
        selectTr(this.id)});
      $("tr.RealizationTableRow").dblclick(function() {
    	  modifyRealization(this.id, $(this).attr('type'));
      });
        
      $("#delete-realization").click(function(e) {
        removeRealization(window.selected_real_row_id)});
    });
    return false;
}

function modifyRealization(html_id, type) {
	id = html_id.replace('realization_', '');
	$('#modify-realization-dialog').empty();
	$('#modify-realization-dialog').data('real_id', html_id);
	$('#modify-realization-dialog').data('extension_type', type);
	if(type == 'phrase_type') {
		$('#modify-realization-dialog').load(ajax_realization_arg_form, {'form_data': '',
	                                                                     'main_argument': false, 
	                                                                     'real_id': id}).dialog('open');
	}
	else if(type == 'positions') {
		$('#modify-realization-dialog').load(ajax_positions_extension_form, {'extension_id': id}).dialog('open');
	}
}

function addModifyRealizationDialog() {
    $('#modify-realization-dialog').dialog({ 
    	title: 'Zmiana rozwinięcia typu frazy',
    	autoOpen: false, 
	    modal: true,
	    width: 'auto', 
	    height: 'auto',
	    closeOnEscape: true,
    });
}

function add_realization() {
    var extension_form = $(this);
    var extension_type = extension_form.parent().data('extension_type');
    if(!extension_type) {
    	extension_type = $('#realization-type #realization-type-select').val();
    }
    if(extension_type == 'phrase_type') {
    	add_phrase_type_extension(extension_form);
    }
    else if(extension_type == 'positions') {
    	add_positions_extension(extension_form);
    }
    return false;
}

function add_phrase_type_extension(realization_form) {
	ShowProgressAnimation();
	var real_id = realization_form.parent().data('real_id');
	
	var realization_data = realization_form.serializeArray();
    realization_data = prepareArgFormData(realization_form, realization_data, -1);
    realization_data.push({name: 'lex_arg_choosing', value: false});
    
    var main_arg_form = $('#main-argument .argument-add-form');
    main_arg_data = main_arg_form.serializeArray();
    main_arg_data = prepareArgFormData(main_arg_form, main_arg_data, -1)
    main_arg_data.push({name: 'lex_arg_choosing', value: false});

   $.ajaxJSON({
      method: 'post',
      url: ajax_add_arg_realization,
      data: {
        main_arg_data: main_arg_data,
        realization_data: realization_data
      },

    callback: function(result) {
      if(result['added']) {
          if(real_id) {
        	  removeRealization(real_id);
          }
          else {
        	  show_realizations();
          } 
      }    
      $('#modify-realization-dialog').dialog('close');
      $('#modify-realization-dialog').data('real_id', '');
  	  $('#modify-realization-dialog').data('extension_type', '');
  	  $('#modify-realization-dialog').empty();
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'select opinion') {
          HideProgressAnimation();
          error_alert('Wybierz opinię.');
          return false;
      }
      else if (result) {
    	  HideProgressAnimation();
          error_alert(result);
          return false;
      }
      else {
        HideProgressAnimation();
        return true;
      }
    },
  });
}

function add_positions_extension(extension_form) {
	ShowProgressAnimation();
	var extension_id = extension_form.parent().data('real_id');
	
    var main_phrase_type_form = $('#main-argument .argument-add-form');
    var main_phrase_type_data = main_phrase_type_form.serializeArray();
    main_phrase_type_data = prepareArgFormData(main_phrase_type_form, main_phrase_type_data, -1)
    main_phrase_type_data.push({name: 'lex_arg_choosing', value: false});
	
	var opinion = '';
	var positions = [];
	var extension_data = extension_form.serializeArray();
	extension_data = $.map(extension_data, function(elem) {
      if (elem.name != 'value' && elem.name != 'opinion')
        return elem;
      else {
        if (elem.name == 'value')
            positions.push(elem.value);
        else if (elem.name == 'opinion')
        	opinion = elem.value;
      }
    });
	extension_data.push({name: 'positions', value: positions});
	extension_data.push({name: 'opinion', value: opinion});
    
   $.ajaxJSON({
      method: 'post',
      url: ajax_add_positions_extension,
      data: {
        main_phrase_type_data: main_phrase_type_data,
        extension_data: extension_data
      },

    callback: function(result) {
      if(result['added']) {
          if(extension_id) {
        	  removeRealization(extension_id);
          }
          else {
        	  show_realizations();
          } 
      }    
      $('#modify-realization-dialog').dialog('close');
      $('#modify-realization-dialog').data('real_id', '');
  	  $('#modify-realization-dialog').data('extension_type', '');
  	  $('#modify-realization-dialog').empty();
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'select opinion') {
          HideProgressAnimation();
          error_alert('Wybierz opinię.');
          return false;
      }
      else if (result) {
    	  HideProgressAnimation();
          error_alert(result);
          return false;
      }
      else {
        HideProgressAnimation();
        return true;
      }
    },
  });
}

function selectTr(id)
{  	  
  	if(selected_real_row_id != -1)
  	{
  	  var recent_row = document.getElementById(selected_real_row_id);
  	  var recent_descendants = getDescendantsNodes(recent_row);
  	  for(var i = 0; i<recent_descendants.length; i++)
  	    $(recent_descendants[i]).css("background-color", "");
  	}
  	if(selected_real_row_id == id)
  	  selected_real_row_id = -1;
  	else
  	{
  	  selected_real_row_id = id;
  	  var row = document.getElementById(id);
  	  var descendants = getDescendantsNodes(row);
  	  for(var i = 0; i<descendants.length; i++)
  	    $(descendants[i]).css("background-color", "LightSteelBlue");  
  	}
}

