﻿function KGListViewControl_CallbackError(_args, _context)
{
  var alertMessage = "The ListView encountered an error. \n\n" + _args;
  alert(alertMessage);
}

function centerAlignCategoriesList()
{
	try
	{
		// When showing the enterprise category list - it should be center aligned.
		document.getElementById("TCC_GenesTabControl_headerCont").className =
		document.getElementById("TCC_GenesTabControl_headerCont").className + "Enterprise";
		document.getElementById("TCC_GenesTabControl_Grid").className =
		document.getElementById("TCC_GenesTabControl_Grid").className + "Enterprise";
		document.getElementById("TCC_GenesTabControl_PagCont").className =
		document.getElementById("TCC_GenesTabControl_PagCont").className + "Enterprise";
	}
	catch(e)
	{
		alert("Couldn't center align Categories" + e );
	}
}

function KGListViewControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback and before checking for exceptions
  if (CheckSessionTimeout())
    return;

  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGListViewControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var json = argsSplit[0];
  var javascripts = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  var retMsg = eval( '(' + json + ')' );
  var holderId = retMsg.HolderId;

  if (globalGenesTabMode == "Category") {
    htmlContent = htmlContent.replace('"TCC_GenesTabControl"', '"CategoriesControl"');
  	holderId = "CategoriesControl";
  }
  var holder = document.getElementById(holderId);
  if (!holder)
  {
    KGListViewControl_CallbackError('The holder doesn\'t exist ' + holderId);
    return;
  }
  
  // fill the control
  SetOuterHtml(holder, htmlContent);


  if (globalGenesTabMode == "Category")
  {
    window.setTimeout("SetFullPageContainerDivStyle('" + holderId + "')", 200);
  }
  
   // eval any javascripts
  if (javascripts)
    eval(javascripts);
  
  // fire the callbackCompleteMethod, if required
  var callbackCompleteMethod = retMsg.CallbackCompleteMethod;
  if (callbackCompleteMethod)
    eval(callbackCompleteMethod);
    
  var controlMode = retMsg.ControlMode;
  //debugger;
	if(controlMode != null && controlMode != "undefined" && controlMode != "" && controlMode == "Category")
	{
		// add sizing logic here
		setTimeout("centerAlignCategoriesList()", 10)
	}
}

function KGListViewControl_Pager_Wrapped(_type, _pagContId, _callbackTrigger)
{
  // clicked on any pager button
  // _type for which button
  
  // get the parameters
  var pagCont = document.getElementById(_pagContId); //container
  var curPage = parseInt(pagCont.getAttribute("CurPage")); //current page index - starts at one
  var lastPage = parseInt(pagCont.getAttribute("LastPage")); //last page index - starts at one
  
  // find out which page to get
  // or return early if it was an invalid button, e.g. First when you're already on the first page
  switch (_type)
  {
    case "First":
      if (curPage == 1)
        return;
      else
        curPage = 1;
      break;
    case "Prev":
      if (curPage == 1)
        return;
      else
        curPage--;  
      break;
    case "Next":
      if (curPage == lastPage)
        return;
      else
        curPage++;
      break;
    case "Last":
      if (curPage == lastPage)
        return;
      else
        curPage = lastPage;
      break;      
  }
  
  // callback to get the new page of data
  var args = "Base=True|Action=Page|PageIdx=" + curPage;
  eval(_callbackTrigger + "('" + args + "')");
  
  // note we don't adjust the CurPage attribute here
  // it will get set in callback done
  // if the user tries to page again before the callback finishes
  // it'll just repeat 
  // the current page index matches what the user can see
  // just incase something goes wrong in the callback
}

function KGListViewControl_GetPageInfo_Wrapped(_type, _pagContId)
{
  // if you only want the current page, call it with _type = "CurPage"
  // if you want all the info, don't use _type, leave it null
  // if you only want something else, could extend the _type = "CurPage" - I haven't done it because it didn't seem useful
  
  var pagCont = document.getElementById(_pagContId); //container
  
  if (!pagCont)
  {
    // e.g. if no KGs in MyKGs it has a message instead of the grid and pager
    if (_type == "CurPage")
      return 1;
    else
      return new PageInfo(1, 1, 0, 1);
  }
  
  // read useful paging variables from the paging container
  var curPage = parseInt(pagCont.getAttribute("CurPage")); //current page index - starts at one
  if (_type == "CurPage")
    return curPage;
    
  var lastPage = parseInt(pagCont.getAttribute("LastPage")); //last page index - starts at one
  var totalRecords = parseInt(pagCont.getAttribute("TotalRecords")); //total number of records
  var pageSize = parseInt(pagCont.getAttribute("PageSize")); //page size
  
  return new PageInfo(curPage, lastPage, totalRecords, pageSize);
}

function PageInfo(curPage, lastPage, totalRecords, pageSize)
{
  this.CurPage = curPage;
  this.LastPage = lastPage;
  this.TotalRecords = totalRecords;
  this.PageSize = pageSize;
  
  this.IsShowingSingleItem = function()
  {
    // i.e. the only item on the last page
    // good to know incase you're removing the item, then the page will need to change
    // probably also want to check CurPage == 1 to see if it's the very last item (this method will return true)
    var result = false;
    
    // is it the last page? Is easiest to test so test it first
    if (this.CurPage == this.LastPage)
    {
      // calculate number of items on the last page
      var numOnLastPage = this.TotalRecords - this.PageSize * (this.LastPage - 1);
      if (numOnLastPage == 1)
        result = true;
    }
    
    return result;
  }
}



/*************** Show More List *****************/
function KGShowMoreListControl_CallbackError(_args, _context)
{
  var alertMessage = "The list control encountered an error. \n\n" + _args;
  alert(alertMessage);
}

function KGShowMoreListControl_CallbackDone(_args, _context)
{
  //debugger;
  // Check for a session time out before completing the callback and before checking for exceptions
  if (CheckSessionTimeout())
    return;

  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGShowMoreListControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var jsonResult = argsSplit[0];
  var javascripts = argsSplit[1];
  var htmlContent = _args.substring(argsSplit[0].length + argsSplit[1].length + 10);  // this way if the html contains the separator we can still get the full html

  jsonResult = jsonResult.replace(",}", "}");
  var retMsg = eval('(' + jsonResult + ')');
  var holderId = retMsg.HolderId;

  var holder = document.getElementById(holderId);
  if (!holder)
  {
    KGShowMoreListControl_CallbackError('The holder doesn\'t exist ' + holderId);
    return;
  }

  // fill the control
  SetOuterHtml(holder, htmlContent);

  // eval any javascripts
  if (javascripts)
    eval(javascripts);

  // fire the callbackCompleteScript, if required
  var callbackCompleteMethod = retMsg.CallbackCompleteClientScript;
  if (callbackCompleteMethod)
    eval(callbackCompleteMethod);

}


function KGShowMoreListControl_ShowMoreClick(_btn, _controlID, _loadOnDemandUrl, _pageSize, _showPageNumber)
{
  //debugger;
  // hide the button
  $(_btn).css("display", "none");
  // show loading icon 
  $(_btn).parent().find('.ShowMoreList_PagerLoadingIcon').html('<img src="images/bigLoader.gif" width="30px" height="30px" />'); //spinner.gif
  $(_btn).parent().find('.ShowMoreList_PagerLoadingIcon').css("display", "block");

  // get the end page
  var endPage = $(_btn).parent().attr("EndPage");
  var offSet = $(_btn).parent().attr("Offset");

  // get page id
  var lastPageID = $(_btn).parent().parent().find(".ShowMoreList_ContentContainer").find(".ShowMoreList_PageContainer:last").attr("id");
  if(lastPageID.lastIndexOf('_') != -1)
    lastPageID = lastPageID.substr(lastPageID.lastIndexOf('_') + 1);
  var pageID = parseInt(lastPageID) + 1;

  if (_loadOnDemandUrl.indexOf('?') == -1)
    _loadOnDemandUrl = _loadOnDemandUrl + '?'
  else
    _loadOnDemandUrl = _loadOnDemandUrl + '&'
  _loadOnDemandUrl = _loadOnDemandUrl + "PageID=" + pageID + "&PageSize=" + _pageSize + "&Offset=" + offSet;

  //var data = GetHtmlFromAshx(_loadOnDemandUrl);

  $.get(_loadOnDemandUrl,
    function (data)
    {
      //debugger;
      if (data != "")
      {
        // if return result aren't wrapped in page container 
        if (data.indexOf('ShowMoreList_PageContainer') == -1) 
        {
          // wrap data inside page container div and add pageNumber div if required
          var pageNumberHtml = '';
          if (_showPageNumber != null && _showPageNumber == true)
          {
            eval('pageNumberHtml = ' + _controlID + '_GetPageNumberDivHTML(' + pageID + ');');
          }

          data = "<div class='ShowMoreList_PageContainer' id='ShowMoreListPage_" + pageID + "'>" + pageNumberHtml + data + "</div>";
        }

        data = data.substr(0, 4) + " style='display:none;' " + data.substring(5);
       
        // append after the previous page div
        $(_btn).parent().parent().find(".ShowMoreList_ContentContainer").find(".ShowMoreList_PageContainer:last").after(data);
        $(_btn).parent().parent().find(".ShowMoreList_ContentContainer").find("#ShowMoreListPage_" + pageID).slideDown(2000);
      }
      // hide the loading icon and show the button
      $(_btn).parent().find('.ShowMoreList_PagerLoadingIcon').css("display", "none");
      $(_btn).parent().find('.ShowMoreList_PagerLoadingIcon').empty();

      // show the Show More button if there is result return and we haven't reach the end page yet
      if (data != "" && endPage > pageID)
        $(_btn).css("display", "block");
    });
}
