﻿// JScript File
// for KGUserObjectSummaryControl
var selectedKGForDelete;
var selectedGroupIdForKGDelete;
var CurrentlyShowingUosMessageBox;
var m_UosMessageBox = null;
var m_UosNewVersionKGMessageBox = null;
var m_CurrentGridControl;

///////////////////////
// Ensures that the delete message box is on the page
function EnsureDeleteKGMessage(_parentControlDivId)
{
  m_UosMessageBox = document.getElementById("DeleteKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "DeleteKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "160px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost.</td></tr><tr><td align='right'><button type='button' onclick='KGUserObjectSummaryControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
    
    //var parentControlDiv = document.getElementById(_parentControlDivId);
    //InsertAdjacentElement(document.body,"afterBegin", m_UosMessageBox);
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost.</td></tr><tr><td align='right'><button type='button' onclick='KGUserObjectSummaryControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";

    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}

function TopZIndex()
//Find highest z index in current document and returns this value + 1 (so that
//the control using this value will appear on top of everything currently in  
//the page, but will appear behind everything called subsequently).  JPC.
//(inspired by http://domscripting.com/presentations/atmedia2006/slides/, slide 12)
{
  var maxZindex = 0;
  var elems = document.getElementsByTagName("div");
  
  for (var ti=0; ti<elems.length; ti++)
  {
    if (elems[ti].style.zindex > maxZindex)
    {
       maxZindex = parseInt(elems[ti].style.zindex);
    }
  }

  return maxZindex + 1;
}

/////////////////////
// Positions the supplied message box relative to the cursor
function PositionUosMessageBox(_parentControlDivId, _isKeyPressEvent, e)
{
  var parentControl = document.getElementById(_parentControlDivId); 
  
  if(_isKeyPressEvent)
  {
    // we don't know where the cursor is (may be off the page) so display in middle of parentControlDiv
    var coords = findPos(_parentControlDivId);
    m_UosMessageBox.style.top = coords[1] - 100; // (parentControl.offsetHeight/2);
    m_UosMessageBox.style.left = coords[0]; // (parentControl.offsetWidth/2) - (GetPixelWidth(m_UosMessageBox)/2);
  }
  else
  {
    //Displays messagebox relative to cursor  
    //Displays messagebox in middle of visible screen.  JPC.
    e = e || window.event;
    
    var btn = e.target || e.srcElement;
    var coords = findPos(btn);
    var x = e.clientX;
    var y = e.clientY;
    
    m_UosMessageBox.style.top = Math.min(document.body.clientHeight - GetPixelHeight(m_UosMessageBox),y + 30);     
    m_UosMessageBox.style.left = x / 2;//x - GetPixelWidth(m_UosMessageBox) / 2;
  }
  m_UosMessageBox.style.display = "block";
  m_UosMessageBox.style.zIndex = TopZIndex();
  m_UosMessageBox.style.visibility = "visible";
  focusOn("defaultButton");
  CurrentlyShowingUosMessageBox = true;
}

function focusOn(buttonId)
{
  var focusButton = document.getElementById(buttonId)
  if (focusButton != null)
  {
    // This line is necessary for the code to work with the WhatExists box.  
    // this may be due to my implementation of the box.  JPC
    focusButton.style.visiblity = "visible";  
    try
    {
        focusButton.focus();
    }
    catch(er)
    {
    }
  }
}

//////////////////
// Closes the message box
function CloseUOSMessageBox()
{
  if(m_UosMessageBox != null)
  {
    m_UosMessageBox.style.visibility = "hidden";
    m_UosMessageBox.style.display = "none";
    CurrentlyShowingUosMessageBox = false;
  }
}

function KGUserObjectSummaryControl_DislayDeleteKGMessage(_kgId, _groupId, _controlDivClientID, e)
{
  // debugger;
  
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);  
  selectedKGForDelete = _kgId;
  selectedGroupIdForKGDelete = _groupId;
  EnsureDeleteKGMessage(_controlDivClientID);
  PositionUosMessageBox(_controlDivClientID, false, e);
}

function KGUserObjectSummaryControl_DeleteKG()
{
  m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Deleting Knowledge Gene....</td></tr></table></div>';
  
  var args = 'action=deleteKG|kgId=' + selectedKGForDelete + '|groupId='+ selectedGroupIdForKGDelete;
  
  // if the KG being deleted is the only one on the last page, we'll need to decrease the current page (done at the server)
  //    only necessary if it's not the first page
  var pageInfo = PflPriv_ListView_GetPageInfo();
  if (pageInfo.CurPage > 1 && pageInfo.IsShowingSingleItem())
    args += '|pageBack=true';
  
  Pfl_KGUserObjectSummaryControl_CallbackTrigger(args);
}

function EnsureCopyKGMessage(_parentControlDivId)
{
  m_UosMessageBox = document.getElementById("CopyKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "CopyKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "120px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Copying Knowledge Gene....</td></tr></table></div>';
    
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}


function KGUserObjectSummaryControl_CopyKG(_kgId, _controlDivClientID, e)
{
  //debugger;
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);  
  EnsureCopyKGMessage(_controlDivClientID);
  PositionUosMessageBox(_controlDivClientID, false, e);

  var args = 'action=copyKG|kgId=' + _kgId;
  
  Pfl_KGUserObjectSummaryControl_CallbackTrigger(args);
}


function KGUserObjectSummaryControl_CallbackTrigger_Wrapped(_args, _cbReference)
{
  // pass back the current page numbers
  // alternative could be to save them in the session, but it could lead to a lot of bugs if they aren't cleared properly
  _args += '|curPagePriv=' + PflPriv_ListView_GetPageInfo("CurPage");
  _args += '|curPagePub=' + PflPub_ListView_GetPageInfo("CurPage");
  
  CallbackTrigger_Wrapped(_args, _cbReference);
}

// CallbackDone
function KGUserObjectSummaryControl_CallbackDone(_args, _context)
{
  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGUserObjectSummaryControl_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 ..." 
  }
  
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var holderId = argsSplit[0];
  var kgvalid = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  // search for the control container
  var holder = document.getElementById(holderId);
  
  // Test if the container is found
  // Yes: replace the innerHTML with the callback result
  //  No: call CallbackError with Content div not found error message
  if(holder != null)
  {
    // holder.innerHTML = args.substring(args.indexOf('=') + 1);
    holder.innerHTML = htmlContent;
    
    CurrentlyRenamingKGID = null;
    
    
    // make sure the publish control is hidden, otherwise it will pop to top left after rerender
    if(g_publishHolderId != null && window.KGPublishOptionControl_HideMenu)
    {
      KGPublishOptionControl_HideMenu(g_publishHolderId);
    }
  
    CloseUOSMessageBox();
  }//end if(holder ....
  else
  {
    KGUserObjectSummaryControl_CallbackError('ContentDiv not found in KGUserObjectSummaryControl.', '');
  }
  
  // kg might have been removed
  if(kgvalid.toLowerCase() == 'false')
     window.setTimeout("ClearActiveKG()",200);
}

// CallbackError Handling
function KGUserObjectSummaryControl_CallbackError(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    //debugger;
    alert(args);
  }
}

function PublicKGs_OnCallbackError()
{
  KGUserObjectSummaryControl_CallbackError('login', '');
}

// PublicKG grid will call this for handlling item clicks
// It will populate the m_CurrentGridControl global variable 
// for further processing
function KGUserObjectSummaryControl_OnClientSideSelect_NoRedirect(kgId, selectedKgAuthorId)
{
  PrepareSessionForMapView(kgId, selectedKgAuthorId);
  // Fix for disappearing pane problem (assigned to JPC, but fix suggested by CM - thanks!)
  var mapViewCollapsed = PaneBStatus();
  if (mapViewCollapsed == false) // map view is visible, reload it
    MapViewControl1_CallbackTrigger();
    
 // global_TabbedWindowsControl_CurrentlySelectedTab = "Indexed Documents";
  //KGTabbedWindowsControl_SelectTabById('Indexed Documents');
  //KGTabbedWindowsControl_CallbackTrigger('KGSelected', -1); 
  KGTabbedWindowsControl_KGSelected(null, selectedKgAuthorId, kgId, false, false);
  //global_TabbedWindowsControl_CurrentlySelectedTab = "Indexed Documents";
}

function KGUserObjectSummaryControl_OnClientSideSelect_WithRedirect(kgId, selectedKgAuthorId, _redirectUrl)
{
  PrepareSessionForMapView(kgId, selectedKgAuthorId); 
  // new default map will be load, clear old session
  SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
  SetSessionProperty('SplitView', 'false');
  	  
  var currentLocation = window.location.href;
  var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
	window.location = hostURL + _redirectUrl;
}

// Setting the session variables for MapView to load the correct map
function PrepareSessionForMapView(kgId, selectedKgAuthorId)
{ 
  //debugger;
  // merge as one server call
  var keys = 'SelectedPersonalKGID|MapViewDisplayMode|KGTabbedWindowsControl1_SelectedTab|SelectedAuthorID|IndexedDocListMode|KGMapViewCollapsed|KGExpandMap|TriggerMapViewCallbackOnload';
	var values = kgId + '|KGMapView|Indexed Documents|' + selectedKgAuthorId + '|IndexedDocuments|false|true|true';
  SetSessionProperty(keys, values, true);
	/*SetSessionProperty('SelectedPersonalKGID', kgId);
  SetSessionProperty('MapViewDisplayMode', "KGMapView");
  SetSessionProperty('KGTabbedWindowsControl1_SelectedTab', 'Indexed Documents');
  SetSessionProperty('SelectedAuthorID', selectedKgAuthorId);
  //global_TabbedWindowsControl_CurrentlySelectedTab = "Indexed Documents";
  SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
  SetSessionProperty('KGMapViewCollapsed',false);
  SetSessionProperty('KGExpandMap',true); //flip the splitter to show the map in button toolbar callback done (KGMapViewCollapsed is removed in aspx.cs)
  SetSessionProperty('TriggerMapViewCallbackOnload', "true");*/
}

function KGUserObjectSummaryControl_DetailsButtonClicked(kgId, _controlDivClientID)
{
  // cancels KGRename
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);
  
  KGDetailsControl_CallbackTrigger(kgId);
}

var CurrentlyRenamingKGID = null;

// Show the input field
function KGUserObjectSummaryControl_StartKGRename(_kgId, _controlDivClientID)
{
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);
  var KGName = document.getElementById("KGName" + _kgId);
  var TextBox = document.getElementById("KGNameTextBox" + _kgId);
  var editBtn = document.getElementById("KGNameEditButton" + _kgId);
  var confirmEditBtn = document.getElementById("KGNameConfirmEditButton" + _kgId);
  
  if (KGName != null && TextBox != null && editBtn != null && confirmEditBtn != null)
  {
    KGName.className = "KGUserObjectSummaryControl_Hidden";
    TextBox.className = "KGUserObjectSummaryControl_Shown KGUserObjectSummaryControl_KGNameTextBox";
    TextBox.value = GetInnerText(KGName);
    editBtn.className = "KGUserObjectSummaryControl_Hidden";
    confirmEditBtn.className = "KGUserObjectSummaryControl_Shown";
    TextBox.focus();
    TextBox.select();
  }
  CurrentlyRenamingKGID = _kgId;
}

// Cancel the Edit and hide the input field
function KGUserObjectSummaryControl_CancelKGRename(_kgId, _controlDivClientID)
{
  if (_kgId != null)
  {
    var KGName = document.getElementById("KGName" + _kgId);
    var TextBox = document.getElementById("KGNameTextBox" + _kgId);
    var editBtn = document.getElementById("KGNameEditButton" + _kgId);
    var confirmEditBtn = document.getElementById("KGNameConfirmEditButton" + _kgId);
    
    if (KGName != null && TextBox != null && editBtn != null && confirmEditBtn != null)
    {
      KGName.className = "KGUserObjectSummaryControl_Shown";
      TextBox.className = "KGUserObjectSummaryControl_Hidden";
      editBtn.className = "KGUserObjectSummaryControl_Shown";
      confirmEditBtn.className = "KGUserObjectSummaryControl_Hidden";
    }
    
    // set the focus to the control div
    var parentControlDiv = document.getElementById(_controlDivClientID);
    if (parentControlDiv != null)
      parentControlDiv.focus();
  }
  CurrentlyRenamingKGID = null;
  CloseUOSMessageBox();
}

// confirm the new KG name
function KGUserObjectSummaryControl_KGRenameRequestConfirmation(_kgId, _controlDivClientID, _isKeyPressEvent, e)
{
	KGUserObjectSummaryControl_CommitKGRename(_kgId);
}

// make the callback
function KGUserObjectSummaryControl_CommitKGRename(_kgId)
{
  var TextBox = document.getElementById("KGNameTextBox" + _kgId);
  if (TextBox != null)
  {
    var args = 'action=renameKG|kgId=' + _kgId + '|kgName='+ TextBox.value;
    Pfl_KGUserObjectSummaryControl_CallbackTrigger(args);
  }
}

// KGName input field onkeypress handler
function KGUserObjectSummaryControl_KGNameTextBoxKeyPress(_kgId, _controlDivClientID, e)
{
  CancelBubble(e);
  e = e || window.event;
  if(e && e.type == "keydown")
  {
    switch(e.keyCode)
    {
      case 13: // Enter Key
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
        KGUserObjectSummaryControl_KGRenameRequestConfirmation(_kgId, _controlDivClientID, true, e);
        break;
      case 27: // Esc
        KGUserObjectSummaryControl_CancelKGRename(_kgId, _controlDivClientID);
        break;
    }
  }
}

// KGName input field onclick handler
function KGUserObjectSummaryControl_KGNameTextBoxClick(_kgId, e)
{
  // prevent the row onclick handler firing
  CancelBubble(e);
}

///////////////////////
// Ensures that the delete message box is on the page
function EnsureRenameKGMessage(_parentControlDivId, _kgName, _kgId)
{
  m_UosMessageBox = document.getElementById("RenameKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "RenameKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "130px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
  // whether the message box exists or not, the innerHTML needs to be set otherwise the displayed KGname may be incorrect
  if (_kgName == null || _kgName == "")
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Rename Knowledge Gene</td></tr><tr><td rowspan='2' valign='top'><img src='images/KGLogo.png' height='50' width='50'/></td><td>Please enter a new name for the Knowledge Gene<sup>&#174;</sup></td></tr><tr><td align='right'><button type='button' onclick='CloseUOSMessageBox();KGUserObjectSummaryControl_StartKGRename(" + _kgId + ", \"" + _parentControlDivId + "\")'>OK</button><button id = defaultButton type='button' onclick='KGUserObjectSummaryControl_CancelKGRename(" + CurrentlyRenamingKGID + ", \"" + _parentControlDivId + "\");'>Cancel</button></td></tr></table></div>";
  else
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Rename Knowledge Gene</td></tr><tr><td rowspan='2' valign='top'><img src='images/KGLogo.png' height='50' width='50'/></td><td>Are you sure you want to rename this Knowledge Gene<sup>&#174;</sup> to \"" + _kgName + "\"</td></tr><tr><td align='right'><button type='button' onclick='KGUserObjectSummaryControl_CommitKGRename(" + _kgId + ")'>Yes</button><button id = defaultButton type='button' onclick='KGUserObjectSummaryControl_CancelKGRename(" + CurrentlyRenamingKGID + ", \"" + _parentControlDivId + "\");'>Cancel</button></td></tr></table></div>";
}

/* New version KG stuff */
function EnsureNewVersionKGMessage(_userId, _kgId, _newPublishedKGId, e)
{
  m_UosMessageBox = document.getElementById("DeleteKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "DeleteKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "500px"
    m_UosMessageBox.style.height = "260px";
    m_UosMessageBox.style.position = "absolute";
    
    document.body.appendChild(m_UosMessageBox);
  }
  
  m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td class='NewVersionMsgBoxHeader'>New Version Available</td></tr><tr><td class='NewVersionKGText'>The Author has published a new version of this Knowledge Gene. Please be aware that the Author may have deleted (or changed the context of) Knowdes to which you have added your own content. If so, unavoidably this content would be lost. BUT you do not have to adopt the new Knowledge Gene, the current version will always remain available to you unless you yourself delete it from your library.<br/><br/>However, your own content will be carried over in all other circumstances so you may wish adopt the new version.  Both versions remain available to you so we recommend you explore the new version and make your decision at leisure.</td></tr><tr><td align='right'><span class='NewVersionKGTextLink' onclick='javascript:KGNewVersionClick(" + _userId + "," + _kgId + "," + _newPublishedKGId + ")'>Show new version</span>&nbsp;&nbsp;<span id = defaultButton class='NewVersionKGTextLink' onclick='javascript:CloseUOSMessageBox()'>Cancel</span></td></tr></table></div>";
  m_UosMessageBox.style.zIndex = TopZIndex();;
  
  PositionUosMessageBox("SiteOverlays_LoginView1_KGPublishOptionControl1_KGPublishOptionTable", false, e);
}

function KGNewVersionClick(_userId, _kgId, _newPublishedKGId)
{
  CloseUOSMessageBox();
  
  KGTabbedWindowsControl_MyHK_KGSelected(null, _userId, _newPublishedKGId, false, 0);
}


