var colModel = window.colModel;
var colNames = window.colNames;
var lastSelectedId = 0;
var lastPrevSelectedId = 0;
var alreadyLoaded = false;
var timeoutHnd;

$(function(){ 

  window.onload=createSearchDialog();
  if (!colModel) {
    colModel = initialColModel;
  };
  if (!colNames) {
    colNames = initialColNames;
  };

	grid = jQuery("#scroll")
	var data = grid.jqGrid('getGridParam', 'postData');
    grid.jqGrid({
    url: ajax_get_page,
    datatype: 'json',
    mtype: 'GET',
    colNames: colNames,
    colModel: colModel, 
    
    jsonReader:{
        root: "rows",
        repeatitems: false,
        id: "id"
    },
    cellEdit: true,
    rowNum:50,
    rowList:[20,30,50],
    scroll: 1,
    sortname: main_field,
    sortorder: sort_order,
    viewrecords: true,
 	autowidth: true,
 	rownumbers: false,
 	gridview: true,
    height: $('#left').height() - 25 - $('#search-panel').height(),
    
    onSearch: function() {
      $('#phrase_box').val('');
    },
    
    remapColumns: function (){ alert(window['remap']) 
     window['remap']? remap : undefined},
     
    gridComplete: function() {
     var lemma_id = window.lemma_id;
     var lastSelectedId = window.lastSelectedId;
     if(window.activeLemmaPanel == 'preview_lemma') {
       lemma_id = window.prev_lemma_id;
       lastSelectedId = window.lastPrevSelectedId;
     }
     
     if(lemma_id != -1 && grid.jqGrid('getGridParam','selrow')!=lemma_id && 
       lemma_id == lastSelectedId) {
       grid.jqGrid('setSelection', lastSelectedId);
     }   
     else if(lemma_id != -1 && lemma_id != lastSelectedId) {
       grid.jqGrid('setSelection', lastSelectedId);
     }
     else {
	  $.get(ajax_note_session_get, function(result) {
		    if(result['lemma_from_note_entry'])
		    {
		    	data = grid.jqGrid('getGridParam', 'postData');
		        $("#phrase_box").val(result['lemma_from_note_entry']);
		        data['mask'] = result['lemma_from_note_entry'];
		        data['id'] = result['lemma_from_note_id'];
    		    $.get(ajax_location, data, function(resp) {
      		      var selectedRow = resp['selected_id'];
      		      var rowIndex = resp['rowIndex'];
      		      var recordsCount = resp['records'];
      		      window.lastSelectedId = resp['selected_id'];
      		      grid.jqGrid('scrollToRow', rowIndex, recordsCount);
      		      grid.jqGrid('setSelection', resp['selected_id']);
      		    });
		    }
		   
	   });
     }
    },
    beforeSelectCell: function(id) {  
     var lemma_id = window.lemma_id;
     if(window.activeLemmaPanel == 'preview_lemma')
       lemma_id = window.prev_lemma_id;
    
     if(grid.jqGrid('getGridParam','selrow')!=lemma_id && 
       lemma_id == id) {
       alreadyLoaded = true;
     }   
     else if(grid.jqGrid('getGridParam','selrow')==lemma_id && 
       lemma_id == id) {
       alreadyLoaded = true;
     }
     else if(lemma_id != id) {
       alreadyLoaded = false;
     }
    
      if (change && window.activeLemmaPanel != 'preview_lemma' && !alreadyLoaded) {
        return confirm('Czy chcesz porzucić niezapisane zmiany? Utracone zostaną niezapisane działania na edytowanym haśle.');
      }
      if (semanticsChanged() && window.activeLemmaPanel != 'preview_lemma' && !alreadyLoaded) {
          return confirm('Czy chcesz porzucić niezapisane zmiany w semantyce? Utracone zostaną niezapisane działania na edytowanym haśle.');
      }
      if(notesNotSaved && window.activeLemmaPanel != 'preview_lemma' && !alreadyLoaded) {
        return confirm('Czy chcesz porzucić niezapisane zmiany? Utracone zostaną dane wpisane w formularzu tworzenia notatek.');
      }
      if(lemmaExNotSaved && window.activeLemmaPanel != 'preview_lemma' && !alreadyLoaded) {
          return confirm('Czy chcesz porzucić niezapisane zmiany? Utracone zostaną dane zapisane w formularzu tworzenia przykładów niedowiązanych.');
      }
      
      return true;
    },
    onSelectCell: function(id) {
      id = getActualLemmaId(id);
      if(window.activeLemmaPanel == 'preview_lemma')
        window.lastPrevSelectedId = id;
      else
        window.lastSelectedId = id;
      
      if(!alreadyLoaded) {
        load_content(id);
        alreadyLoaded = false;
      }
      $.get(ajax_note_session_clear);
    },
    onSortCol: sort_column
  }); 
  
  //zmiany w naglowkach kolumn
  refresh_column_headers();
  findAndScroll();
  $('#searchButton').click(findAndScroll);
  $('#phrase_box').keydown(doSearch);

  
  $("#open-sort-dialog").click(function(e){
    $('#search-panel-dialog').dialog( "option", "title", "Sortowanie haseł:" ).load(ajax_sort_form).dialog('open');
  });  
  $("#filter-button").click(function(e){
    $('#search-panel-dialog').empty().dialog( "option", "title", "Filtrowanie haseł:" ).load(ajax_filter_form).dialog('open');
  });
  
  $("#show-columns-button").click(function(){
    grid.jqGrid('columnChooser', {
      done: function(perm) {
        if(perm)
        {
          this.jqGrid("remapColumns", perm, true);
          var col_model = grid.jqGrid('getGridParam', 'colModel');
          var col_names = grid.jqGrid('getGridParam', 'colNames');
          var remap = grid.jqGrid('getGridParam', 'remapColumns');
          jQuery("#scroll").jqGrid('setGridWidth', $('#left').width() - 2, true);
          $.ajaxJSON({
            method: 'post',
            url: ajax_save_columns,
            data: {col_model: col_model, col_names: col_names, remap: remap},
          });
        }
      }
    });
  });
	
  $('form.sort-form').live('submit', sort_form_submit);
  $('form.filter-form').live('submit', filter_form_submit);
  $('button#filter-form-reset').live('click', function(){
    resetForm($('form.filter-form'));
    $('form.filter-form').submit();    
  });
  
  $('form.sort-form').live('reset', function(){
    $('#search-panel-dialog').dialog('close')});
  $('form.filter-form').live('reset', function(){
    $('#search-panel-dialog').dialog('close')});

}); 

function createSearchDialog() {
  $('#search-panel-dialog').dialog({ autoOpen: false,
                                     height: 'auto',
                                     width: 'auto' });
}

function sort_form_submit() {
    this_form = $(this);
    form_data = this_form.serializeArray();
    
    var id_rules = { 'priority': '',
                 'sort_order': 'desc'}
    var entry_rules = { 'priority': '',
                    'sort_order': 'desc'}
    var owner_rules = { 'priority': '',
                    'sort_order': 'desc'}
    var phraseologist_rules = {'priority': '',
            				   'sort_order': 'desc'}
    var semanticist_rules = { 'priority': '',
            				  'sort_order': 'desc'}
    var vocabulary_rules = { 'priority': '',
                         'sort_order': 'desc'}
    var status_rules = { 'priority': '',
                     'sort_order': 'desc'}
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'id_priority' && elem.name != 'id_sort_order' &&
          elem.name != 'entry_priority' && elem.name != 'entry_sort_order' &&
          elem.name != 'owner_priority' && elem.name != 'owner_sort_order' &&
          elem.name != 'phraseologist_priority' && elem.name != 'phraseologist_sort_order' &&
          elem.name != 'semanticist_priority' && elem.name != 'semanticist_sort_order' &&
          elem.name != 'vocabulary_priority' && elem.name != 'vocabulary_sort_order' &&
          elem.name != 'status_priority' && elem.name != 'status_sort_order')
        return elem;
      else {
        if (elem.name == 'id_priority')
          id_rules['priority'] = elem.value;
        else if (elem.name == 'id_sort_order')
          id_rules['sort_order'] = elem.value;
        else if (elem.name == 'entry_priority')
          entry_rules['priority'] = elem.value;
        else if (elem.name == 'entry_sort_order')
          entry_rules['sort_order'] = elem.value;
        else if (elem.name == 'owner_priority')
          owner_rules['priority'] = elem.value;
        else if (elem.name == 'owner_sort_order')
          owner_rules['sort_order'] = elem.value;
        else if (elem.name == 'phraseologist_priority')
        	phraseologist_rules['priority'] = elem.value;
        else if (elem.name == 'phraseologist_sort_order')
        	phraseologist_rules['sort_order'] = elem.value;
        else if (elem.name == 'semanticist_priority')
        	semanticist_rules['priority'] = elem.value;
        else if (elem.name == 'semanticist_sort_order')
        	semanticist_rules['sort_order'] = elem.value;
        else if (elem.name == 'vocabulary_priority')
          vocabulary_rules['priority'] = elem.value;
        else if (elem.name == 'vocabulary_sort_order')
          vocabulary_rules['sort_order'] = elem.value;
        else if (elem.name == 'status_priority')
          status_rules['priority'] = elem.value;
        else if (elem.name == 'status_sort_order')
          status_rules['sort_order'] = elem.value;
      }
    });
    
	form_data.push({name: 'id', value: id_rules});
    form_data.push({name: 'entry', value: entry_rules});
    form_data.push({name: 'owner', value: owner_rules});
    form_data.push({name: 'phraseologist', value: phraseologist_rules});
    form_data.push({name: 'semanticist', value: semanticist_rules});
    form_data.push({name: 'vocabulary', value: vocabulary_rules});
    form_data.push({name: 'status', value: status_rules});

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

    callback: function(result) {
	  $('#search-panel-dialog').dialog('close');
	  refresh_column_headers();
	  grid.trigger("reloadGrid");
	      
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
    },
    bad_data_callback: function(result) {
      if (result == 'none priority selected') {
        error_alert('Określ priorytet chociaż jednego pola.');
        return false;
      }
      
      else
        return true;
    },
  });
  return false;
}

function refresh_column_headers() {
    $.ajaxJSON({
        method: 'get',
        url: ajax_get_sort_order,
        data: {
        },

      callback: function(result) {
    	  //grid.setGridParam({sortname: result['main_field'], sortorder: result['order']});
    	  //grid.jqGrid('setGridParam', { sortname: result['main_field'], sortorder: result['order']});
  	  var thd= $("thead:first", $('#scroll')[0].grid.hDiv).get(0);  
        $("tr th span.s-ico",thd).hide(); // tym sie chowa ikony
        $("tr th span.ui-icon",thd).addClass('ui-state-disabled');
        $("tr th[id='scroll_"+result['main_field']+"'] span.s-ico",thd).show();
        $("tr th[id='scroll_"+result['main_field']+"'] span.ui-icon-"+result['order'], thd).removeClass('ui-state-disabled');
  	      
      },
      error_callback: function(xhr, status, error) {
        error_alert(status + ': ' + error);
      },
      bad_data_callback: function(result) {
          return true;
      },
    });
}

function findAndScroll() {
  $.get(ajax_note_session_get, function(result) {
    data = grid.jqGrid('getGridParam', 'postData');
    data['mask'] = $("#phrase_box").val();
    data['id'] = '';
    
    if(result['lemma_from_note_entry'])
    {
        $("#phrase_box").val(result['lemma_from_note_entry']);
        data['mask'] = result['lemma_from_note_entry'];
        data['id'] = result['lemma_from_note_id'];
    }

    $.get(ajax_location, data, function(resp) {
      var selectedRow = resp['selected_id'];
      var rowIndex = resp['rowIndex'];
      var recordsCount = resp['records'];
      window.lastSelectedId = resp['selected_id'];
      grid.jqGrid('scrollToRow', rowIndex, recordsCount);
      grid.jqGrid('setSelection', resp['selected_id']);
    });
  });
}


function sort_column(colName, index, order) 
{
	grid.jqGrid('setGridParam', { datatype: 'local'});
  $.ajaxJSON({
    method: 'get',
    url: ajax_sort_column,
    data: {colName: colName, 
    	   sortOrder: order
    },
     
    callback: function(result) {
       refresh_column_headers()
       grid.jqGrid('setGridParam', { datatype: 'json'});
       grid.trigger("reloadGrid");
    },
    
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
    },
    
    bad_data_callback: function(result) {
        return true;
    },  
  });  
}


function doSearch(ev){
  if(ev.which == 13) // wcisnieto Enter
  {
    findAndScroll();
  }

  if(!ax_auto_search)
    return;
  if(timeoutHnd)
    clearTimeout(timeoutHnd);
  timeoutHnd = setTimeout(findAndScroll, 500);
}
