﻿// Common variables that can be used across all modules
var pageSize = 20;
var defaultPageNumber = 1;

var entityJsonReader =
{
  root: "EntityList",
  page: "PageNumber",
  total: "PageCount",
  records: "RecordCount",
  repeatitems: false,
  id: "Id"
};

$(document).ready(function() {
  // set defaults for all grids
  jQuery.extend(jQuery.jgrid.defaults,
    {
      toolbar: [true, "top"],
      datatype: 'local',
      loadui: 'disable',
      height: 'auto',
      gridview: true,
      viewrecords: true,
      multiselect: false,
      localReader: entityJsonReader,
      rowNum: pageSize,
      hidegrid: false,
      loadonce: false,
      autowidth: true,
      //deselectAfterSort: false, // Commented out for now - may need to put it back in to better handle our local grids and sorting since default is FALSE.
      emptyrecords: 'No records to view',
      recordtext: 'View {0} - {1} of {2}',
      pgtext: 'Page {0} of {1}'
    }
  );
  
});

// expects the $("#tblGrid") element as the parameter
function deletePageCheck(grid) {
  // handle delete only record on last page
  var page = grid[0].p.page;
  var lastPage = grid[0].p.lastpage;
  var recCount = grid[0].p.reccount;

  if ((page == lastPage) && (recCount == 1) && (page > 1)) {
    grid[0].p.page = page - 1;
  }
}

// Method to get Grid width expects the $("#tblGrid") element as the parameter
function getGridWidth(grid) {
  var noOfColumns = grid[0].p.colModel.length;
  var width =0;
  for (index=0;index < noOfColumns;index=index+1)
  {
    width = width + grid[0].p.colModel[index].width;
  }
  return width;
}

function rebindjsonLocal(grid, data) {
  var jsonToGrid = grid[0];
  jsonToGrid.p.data = data[jsonToGrid.p.localReader.root] != null ? data[jsonToGrid.p.localReader.root] : [];
  var recordCount = data[jsonToGrid.p.localReader.root] != null ? data[jsonToGrid.p.localReader.root].length : 0;
  grid.jqGrid('setGridParam', { rowNum: recordCount });
  grid.trigger('reloadGrid');
}

function getGridCheckboxId(gridid, rowid) {
  return '#jqg_' + gridid.replace('#', '') + '_' + rowid.toString();
}

$.fn.extend({
  /*
  * The toolbar has the following properties
  *	id of top toolbar: t_<tablename>
  *	id of bottom toolbar: tb_<tablename>
  *	class of toolbar: ui-userdata
  * elem is the toolbar name to which button needs to be added. This can be 
  *		#t_tablename - if button needs to be added to the top toolbar
  *		#tb_tablename - if button needs to be added to the bottom toolbar
  */
  toolbarButtonAdd: function(elem, p) {
    p = $.extend({
      caption: "newButton",
      title: '',
      buttonicon: 'ui-icon-newwin',
      onClickButton: null,
      position: "last",
      disabled: false
    }, p || {});
    var $elem = $(elem);
    var divString = "<div class='cts-editpane-commands' style='margin-top: 0px;'></div>";
    /* 
    * Step 1: check whether a div is already added. If not add
    * Step 2: If there is no div already added then add a div
    * Step 3: Make the element ready for addition to the div 
    * Step 4: Check the position and corresponding add the element
    * Step 5: Add other properties 
    */
    //step 1 
    return this.each(function() {
      if (!this.grid) { return; }
      if (elem.indexOf("#") != 0) {
        elem = "#" + elem;
      }
      //step 2
      if ($(elem).children('div').length === 0) {
        $(elem).append(divString)
        .attr('style', 'width=100%; height: auto;');
      }
      //step 3
      var input = "";
      if (p.disabled) {
        input = "<input class='ui-button ui-corner-all ui-state-disabled' disabled='disabled' type='button' value='" + p.caption + "'</input>";
      }
      else {
        input = "<input class='ui-button ui-state-default ui-corner-all' type='button' value='" + p.caption + "'</input>";
      }
      var tbd = $(input)
      .attr("title", p.title || "")
      .click(function(e) {
        if ($.isFunction(p.onClickButton)) { p.onClickButton(); }
        return false;
      })
      .hover(
        function() { $(this).addClass("ui-state-hover"); },
        function() { $(this).removeClass("ui-state-hover"); }
      );

      if (p.id) { $(tbd).attr("id", p.id); }
      if (p.align) { $(elem).attr("align", p.align); }

      var findnav = $(elem).children('div');

      if (p.position === 'first') {
        if ($(findnav).find('input').length === 0) {
          $(findnav).append(tbd);
        } else {
          $("input:eq(0)", findnav).before(tbd);
        }
      } else {
        $(findnav).append(tbd);
      }
    });
  }
});
