/*
Copyright (c) 2012, Bartłomiej Nitoń
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

﻿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(grid.jqGrid('getGridParam','selrow')!=lemma_id && 
       lemma_id == lastSelectedId)
     {
       grid.jqGrid('setSelection', lastSelectedId);
     }   
     else if(lemma_id != lastSelectedId)
     {
       grid.jqGrid('setSelection', lastSelectedId);
     }
     
     /* if (grid.jqGrid('getGridParam', 'setOnComplete') == true)
      {
        grid.jqGrid('scrollToLastSelection');
        grid.jqGrid('setGridParam', {'setOnComplete' : false});
      }*/
    },
    beforeSelectCell: function(id) { // event rÄ‚â€žĂ˘â‚¬ĹˇÄ‚Ë�Ă˘â€šÂ¬ÄąÄľĂ„â€šĂ‹ďż˝Ä‚Ë�Ă˘â€šÂ¬ÄąÄľÄ‚â€ąÄŹĹĽËťcznie doimplementowany w jqgrid-patch.js
    // window.lastSelectedId = grid.jqGrid('getGridParam','selrow')
     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?');
      }
      return true;
    },
    onSelectCell: function(id) {
      //alert(alreadyLoaded)
      if(window.activeLemmaPanel == 'preview_lemma')
        window.lastPrevSelectedId = id;
      else
        window.lastSelectedId = id;
      
      if(!alreadyLoaded)
      {
        load_content(id);
        alreadyLoaded = false;
      }
    },
    onSortCol: sort_column
     
  }); 
  
  //zmiany w nagĂ„Ä…Ă˘â‚¬ĹˇĂ„â€šÄąâ€šwkach kolumn
  refresh_column_headers();
  findAndScroll();
  $('#searchButton').click(findAndScroll);
 // $('#phrase_box').keydown(doSearch);
  $('#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').dialog( "option", "title", "Filtrowanie haseł:" ).load(ajax_filter_form).dialog('open');
  });
  
  $("#show-columns-button").click(function(){
    //$('#search-panel-dialog').dialog( "option", "title", "PokaĹĽ/ukryj kolumnÄ™:" ).load(ajax_show_hide_form).dialog('open');
    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},
          });
        }
      }
    });
    //if ($.isFunction(window.afterShowColumnChooser))
    //  afterShowColumnChooser();
  });
	
  $('form.sort-form').live('submit', sort_form_submit);
  $('form.filter-form').live('submit', 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 filter_form_submit() {
    this_form = $(this);
    form_data = this_form.serializeArray();
  
    var owner = '';
    var vocabulary = '';
    var status = '';
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'owner' && elem.name != 'vocabulary' &&
          elem.name != 'status' && elem.name != 'has_old_frames_property' && 
          elem.name != 'has_argument' && elem.name != 'has_position' &&
          elem.name != 'approver' && elem.name != 'has_message_from')
        return elem;
      else {
        if (elem.name == 'owner')
          owner = elem.value;
        else if (elem.name == 'vocabulary')
          vocabulary = elem.value;
        else if (elem.name == 'status')
          status = elem.value;
        else if (elem.name == 'has_old_frames_property')
          has_old_frames_property = elem.value;
        else if (elem.name == 'has_argument')
          has_argument = elem.value;
        else if (elem.name == 'has_message_from')
          has_message_from = elem.value;
        else if (elem.name == 'has_position')
          has_position = elem.value;
        else if (elem.name == 'approver')
          approver = elem.value;
      }
    });
    
    form_data.push({name: 'owner', value: owner});
    form_data.push({name: 'vocabulary', value: vocabulary});
    form_data.push({name: 'status', value: status});
    form_data.push({name: 'has_old_frames_property', value: has_old_frames_property});
    form_data.push({name: 'has_argument', value: has_argument});
    form_data.push({name: 'has_message_from', value: has_message_from});
    form_data.push({name: 'has_position', value: has_position});
    form_data.push({name: 'approver', value: approver});
    
    act_lemma_id = window.prev_lemma_id;
    if(window.activeLemmaPanel != 'preview_lemma')
      act_lemma_id = window.lemma_id;
    
    form_data.push({name: 'lemma_id', value: act_lemma_id})

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

    callback: function(result) {
	  $('#search-panel-dialog').dialog('close');
	  grid.trigger("reloadGrid");
	      
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
        return true;
    },
  });
  return false;
}


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 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 != '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 == '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: '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');
	  window.main_field = result['column'];
	  window.sort_order = result['sort_order'];
	  refresh_column_headers();
	  grid.trigger("reloadGrid");
	      
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'none priority selected') {
        error_alert('Określ priorytet chociaż jednego pola.');
        return false;
      }
      
      else
        return true;
    },
  });
  return false;
}
  
function get_sort_order(isPreview)
{
    $.ajaxJSON({
      method: 'post',
      url: ajax_get_sort_order,
      data: {
      },

    callback: function(result) {
	 // $('#search-panel-dialog').dialog('close');
	 // grid.trigger("reloadGrid");
	  window.main_field = result['main_field'];
	  window.sort_order = 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_"+window.main_field+"'] span.s-ico",thd).show();
      $("tr th[id='scroll_"+window.main_field+"'] span.ui-icon-" + window.sort_order,thd).removeClass('ui-state-disabled');
	      
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
        return true;
    },
  });
}

function refresh_column_headers(){

  get_sort_order('true');
 /* var thd= $("thead:first", $('#scroll')[0].grid.hDiv).get(0);
  //var rules = $.evalJSON(grid.jqGrid('getGridParam', 'postData').sort_rules);
  
  $("tr th span.s-ico",thd).hide(); // tym sie chowa ikony
  $("tr th span.ui-icon",thd).addClass('ui-state-disabled');
  //$("text").remove('.sort_priority');
  $("tr th[id='scroll_"+main_field+"'] span.s-ico",thd).show();
 // for (var i = 0; i < rules.length; i++) {
 //   $("tr th[id='scroll_"+rules[i].field+"'] span.s-ico",thd).show();
  $("tr th[id='scroll_"+main_field+"'] span.ui-icon-" + sort_order,thd).removeClass('ui-state-disabled');*/
   // $('tr th div#jqgh_'+main_field+"'", thd).append('<text class="sort_priority">'+(1)+'</text>');
 // }
}


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

  // przeĂ„â€šĂ˘â‚¬ĹľÄ‚â€žĂ˘â‚¬Â¦Ă„â€šĂ‹ďż˝Ä‚Ë�Ă˘â‚¬ĹˇĂ‚Â¬Ă„Ä…Ă‹â€ˇadowanie moĂ„â€šĂ˘â‚¬ĹľÄ‚â€žĂ˘â‚¬Â¦Ă„â€šĂ˘â‚¬ĹľÄ‚â€ąÄąÄ„na pominÄ‚â€žĂ˘â‚¬ĹˇÄ‚Ë�Ă˘â€šÂ¬ÄąÄľĂ„â€šĂ‹ďż˝Ä‚Ë�Ă˘â‚¬ĹˇĂ‚Â¬Ä‚â€šĂ‚Â¦Ä‚â€žĂ˘â‚¬ĹˇÄ‚Ë�Ă˘â€šÂ¬ÄąÄľĂ„â€šĂ‹ďż˝Ä‚Ë�Ă˘â‚¬ĹˇĂ‚Â¬Ä‚â€ąĂ˘â‚¬Ë‡ jeĂ„â€šĂ˘â‚¬ĹľÄ‚â€žĂ˘â‚¬Â¦Ă„â€šĂ‹ďż˝Ä‚Ë�Ă˘â‚¬ĹˇĂ‚Â¬Ă„Ä…ÄąĹźli nie jesteĂ„â€šĂ˘â‚¬ĹľÄ‚â€žĂ˘â‚¬Â¦Ă„â€šĂ‹ďż˝Ä‚Ë�Ă˘â‚¬ĹˇĂ‚Â¬Ă„Ä…ÄąĹźmy w trybie filtrowania
  //if (filtering_mode){
  //  grid.trigger('reloadGrid');
 // }
    $.get(ajax_location, data, function(resp) {
      var selectedRow = resp['selected_id'];
      var rowIndex = resp['rowIndex'];
      var recordsCount = resp['records'];
    //  if (recordsCount > 0){
      //  if(window.activeLemmaPanel == 'preview_lemma')
      //    window.lastPrevSelectedId = resp['selected_id'];
      //  else
          window.lastSelectedId = resp['selected_id'];
        grid.jqGrid('scrollToRow', rowIndex, recordsCount);
        grid.jqGrid('setSelection', resp['selected_id']);
        //grid.jqGrid('scrollAndSet', selectedRow, rowIndex, recordsCount);
    //  }
    });
  });
}


function sort_column(colName, index, order) 
{
	$.ajaxJSON({
      method: 'post',
      url: ajax_sort_column,
      data: {colName: colName, sortOrder: order},
      
          callback: function(result) {
	 // $('#search-panel-dialog').dialog('close');
	 // grid.trigger("reloadGrid");
	  //alert(result['main_field']+'  '+result['order'])
    window.main_field = colName;
    window.sort_order = order;
    refresh_column_headers();
	      
    },
    error_callback: function(xhr, status, error) {
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
        return true;
    },
    
    });  
}


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

// dorobić, bo fajne
  if(!ax_auto_search)
    return;
  if(timeoutHnd)
    clearTimeout(timeoutHnd);
  timeoutHnd = setTimeout(findAndScroll, 500);
}


