﻿// JScript File
var m_HideKnowde = null;
var globalKnowdePermissionsInFilterStatus = 'BOTH';
var globalKnowdePermissionsOutFilterStatus = 'BOTH';

//var USERSARRAY = null;
//var USERPERMISSIONRBTNARRAY = null;

function KnowdePermissionsControl_CallbackTrigger_Wrapped(_args, _cbreference)
{

  var args;
  
  args = 'ACTION=' + _args + appendKGInfo();
  
  eval(_cbreference);
}

function KnowdePermissionsControl_ProcessCallBackError_Wrapped(_args, _context, _controlID)
{
}

function HideKnowde()
{
  if (TestLinkEdit())
    return;

	if(m_HideKnowde == null)
		m_HideKnowde = document.getElementById("KnowdePermissionsControlID1");

  m_HideKnowde.style.top = screen.height/4;
	m_HideKnowde.style.left = "25%";
        
  globalKnowdePermissionsInFilterStatus = 'BOTH';
  globalKnowdePermissionsOutFilterStatus = 'BOTH';
  SetSessionProperty('KnowdePermissionInGridSort', globalKnowdePermissionsInFilterStatus);
  SetSessionProperty('KnowdePermissionOutGridSort', globalKnowdePermissionsOutFilterStatus);
  
  KnowdePermissionsControl_CallbackTrigger('LOAD'); 
}

function CloseKnowdePermissionsControl()
{
  HideKnowdePermissionsControl();
}

function KnowdePermissionsControl_ToggleCheckBox_Wrapped(_chkIdPrefix, _cbref)
{
  // this function is the onclick handler for when a user clicks any of the check boxes when setting up knowde permissions.
  // to distinguish between the two grids we pass through the gridId (_chkIdPrefix) to help us get the correct check boxes
  var groupCheckBoxStatus = document.getElementById(_chkIdPrefix + "_groupCheckBox").checked;
  var peopleCheckBoxStatus = document.getElementById(_chkIdPrefix + "_peopleCheckBox").checked;
  
  var filterStatus;
  
  if(peopleCheckBoxStatus == true && groupCheckBoxStatus == true)
  {
      filterStatus = 'BOTH';
      args += "SETUP=BOTH|"
  }
  else if(peopleCheckBoxStatus == true && groupCheckBoxStatus == false)
  {
      filterStatus = 'USERS';
      args += "SETUP=USERS|"
  }
  else if(peopleCheckBoxStatus == false && groupCheckBoxStatus == true)
  {
      filterStatus = 'GROUPS';
      args += "SETUP=GROUPS|"
  }
  else if(peopleCheckBoxStatus == false && groupCheckBoxStatus == false)
  {
      filterStatus = 'NEITHER';
      args += "SETUP=NEITHER|"
  }
  
  
  
  if(_chkIdPrefix == "InGroupList")
  {
    globalKnowdePermissionsInFilterStatus = filterStatus;
    SetSessionProperty('KnowdePermissionInGridSort', filterStatus);
    
    var args = "ACTION=TOGGLEIN" + appendKGInfo();
  }
  else
  {
    globalKnowdePermissionsOutFilterStatus = filterStatus;
    SetSessionProperty('KnowdePermissionOutGridSort', filterStatus);
    var args = "ACTION=TOGGLEOUT" + appendKGInfo();
  }
  
  eval(_cbref);
}

function KnowdePermissionsControl_CallbackDone_Wrapped(_args, _contentTableID, _inGrid, _outGrid)
{
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    
    var argsSplit = _args.split('[@|@]');
    var ctrlMode = argsSplit[0];
    var args = argsSplit[1];
    // if the permission check failed in the ProcessAJAXCallback (server side)
    if(args == "Permission Message")
    {
			alert("Sorry, you have insufficient permissions for this action");
			return;
    }
    // We need to split the HTML and the JS and eval the JS first
    var split = args.indexOf('~');
    if (split > - 1)
    {
      var html = args.substring(0, split);
      // Check if the HTML has CDATA sections that need evaluating
      if(html.indexOf('<![CDATA[') >= 0)
      {
        SplitAndEvalHTML(html);
      }   
      var js = args.substring(split + 1, args.length);
      EvalRegisterJavaScripts(js); 
    }

    if(ctrlMode == 'GRIDIN')
      window.setTimeout('SetHeadingCellClientTemplateId(' + _inGrid.Id + ', "' + ctrlMode + '"), 200');
    else if(ctrlMode == 'GRIDOUT')
      window.setTimeout('SetHeadingCellClientTemplateId(' + _outGrid.Id + ', "' + ctrlMode + '"), 200');
    
    if(ctrlMode == 'UPDATE')
    {
      document.getElementById("SiteOverlays_KnowdePermissionsControl1_OutGroupList_dom").style.height = "100%";
      document.getElementById("SiteOverlays_KnowdePermissionsControl1_InGroupList_dom").style.height = "100%";
      ShowKnowdePermissionsControl();
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }       
}

function SplitAndEvalHTML(_html)
{
  //debugger;
  try
  {
    // extract all the cdatas lines from callback result
    var cdatas = _html.split('<![CDATA[');
    
    // loop through the cdatas and process each of them
    // ignoring the first one coz it is just HTML
    var z = 0;
    for(z = 1; z < cdatas.length; z++)
    {
      // javascript starting position
      var posStart = cdatas[z].indexOf('window');
      
      // javascript ending position 
      var posEnd = cdatas[z].lastIndexOf('//]]');
      
      if(posStart > -1 && posEnd > -1)
      {
        // attemp to extract the javascript
        var jscript = cdatas[z].substring(posStart, posEnd);
       
        // Now we have the potential jscript we need to execute it to reinitiallise the grid
        if(jscript.length != 0)
        {        
          // redefine the init script on Page
          eval(jscript);     
        }
      }      
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function SetHeadingCellClientTemplateId(_grid, _ctrlMode)
{
//debugger;
  var FirstColumn = _grid.get_table().get_columns()[2];
  
  var filterStatus;
  
  if(_ctrlMode == 'GRIDIN')
    filterStatus = globalKnowdePermissionsInFilterStatus;
  else
    filterStatus = globalKnowdePermissionsOutFilterStatus;
  

  switch (filterStatus)
  {
    case 'BOTH':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxBoth');
        break;
    case 'USERS':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxUsers');
        break;
    case 'GROUPS':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxGroups');
        break;
    case 'NEITHER':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxNeither');
        break;
    default:
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxBoth');
        break;
  }
  //eval("window.setTimeout('" +  _grid + ".Render()', 200)");
  _grid.Render();
}

function KnowdePermissionsControl_ConfigureMembers_Wrapped(_inGridID, _outGridID, _mode, _cbref)
{
  //debugger;
  //var args = 'ACTION=CONFIGURE|KGID=' + currentlySelectedKG + '|KNOWDEID=' + returnKnowdeID(globalLastSelectedKnowde) + '|USER=';
  var args = 'ACTION=CONFIGURE' + appendKGInfo() + '|USER=';
  
  // The format of the attached args for the user is as follows...
  // x_y_z
  // where x is either the user id or perm group id
  // y is the permission. 1 if adding to hide list and 0 if adding to visible list
  // z is an id for item type. 1 is a perm group and 0 is a user.  This is needed server side when saving to db
  switch (_mode)
  {
    case 'ADD':
      // get the array of selected items
      var selectedItems = _inGridID.GetSelectedItems();
      
      // Loop thougth them and collect the UserID append to the callback args
      for(var x=0; x<selectedItems.length; x++)
      {
        var item = selectedItems[x];
        var userID = item.GetMember('UserID').Text;
        
        //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item.GetMember('ID').Text;
          args = args + groupID + '_1_1' + ';';
        }
        else          
          args = args + userID + '_1_0' + ';';
      }  
      
      if(selectedItems.length > 0)
        eval(_cbref);
      break;
    case 'ADDALL':
      for(var k=0; k<_inGridID.Data.length; k++)
      {
         var item = _inGridID.Data[k];
         var userID = item[0];
         
         //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item[1];
          args = args + groupID + '_1_1' + ';';
        }
        else          
          args = args + userID + '_1_0' + ';';              
      }
      
      if(_inGridID.Data.length > 0)
        eval(_cbref);
      break;
    case 'REMOVE':
      // get the array of selected items
      var selectedItems = _outGridID.GetSelectedItems();      

      // Loop thougth them and collect the UserID append to the callback args
      for(var x=0; x<selectedItems.length; x++)
      {
        var item = selectedItems[x];
        var userID = item.GetMember('UserID').Text;
        
        //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item.GetMember('ID').Text;
          args = args + groupID + '_0_1' + ';';
        }
        else          
          args = args + userID + '_0_0' + ';';         
      }
        
      if(selectedItems.length > 0)
        eval(_cbref);
      break;
    case 'REMOVEALL':
      for(var k=0; k<_outGridID.Data.length; k++)
      {
         var item = _outGridID.Data[k];
         var userID = item[0];
         
        //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item[1];
          args = args + groupID + '_0_1' + ';';
        }
        else          
          args = args + userID + '_0_0' + ';';   
      }
      if(_outGridID.Data.length > 0)
        eval(_cbref);
      break;
  }
}

function appendKGInfo()
{
//debugger;
  var kgInfo;
  
  return kgInfo = '|KGID=' + currentlySelectedKG + '|KNOWDEID=' +  returnKnowdeID(globalLastSelectedKnowde) + '|PARENTKNOWDEID=' + globalLastSelectedKnowde.getAttribute('parentKnowdeID') + '|MAPDIRECTION=' + globalMapDirection;
}

//function updateUserList(_cbref)
//{
//  //debugger;  
//  try
//  {
//    //set up the array
//    if(USERSARRAY == null)
//    {
//      USERSARRAY = new Array();
//      USERPERMISSIONRBTNARRAY = new Array();
//    }     
//    
//    // Add user and permission to array
//    USERSARRAY[_userID] = _permisionID;   
//    USERPERMISSIONRBTNARRAY[_userID] = _configButton.id;
//    return true;
//  }
//  catch (e) 
//  {
//    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
//    debugger;
//  }       
//}

//function KnowdePermissionsControl_Save_Wrapped(_clientId, _mode, _cbref)
//{
//   // Do save stuff              
//   var users = '';
//   if(USERSARRAY != null && USERSARRAY.length > 0)
//   {          
//      for (var i in USERSARRAY)
//      {
//         users += USERSARRAY[i] + ':';
//      } 
//   }
//   USERSARRAY = null; 
//   
//   eval(_cbref)
//}

