﻿// KGSuggestionsControl JScript File
var global_SearchResult_ClickedItemID = 'none';


// CallbackTrigger Wapper for normal suggestion 
function KGSuggestionControl_CallbackTrigger_Wrapped(_searchPhrase, _searchPhraseKey, _cbreference, _srmIndex)
{
  //debugger;
  if(_searchPhrase != null && _searchPhrase.length)
  { 
    // filter special characters (number, leter and ')
    var iChars = "!@#$%^&*()+=-[]\\;,./{}|\":<>?";
    
    if(_searchPhrase=="\'")
       return;
    
    for (var si = 0; si < _searchPhrase.length; si++) 
    {
      var index1= iChars.indexOf(_searchPhrase.charAt(si));
  	  if (index1 != -1) 
  	    return;
  	}
  	
  }
  
  var args = _searchPhraseKey + '=' + _searchPhrase + '|SrmIndex=' + _srmIndex;
  
  if(_cbreference != null && _cbreference != "")
    eval(_cbreference);
}

// this will rerender table after call back
function KGSuggestionControl_CallbackDone_Wrapped(args, context, _suggestionTableID, _KGSuggestionControlDivId, _OverlaypositionCss, _ConceptTabbedViewHideOrShowControls)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var srmIndex;
  try
  {
    var argsSplit = args.split('[@|@]'); 
    srmIndex = argsSplit[1];
    args = argsSplit[0];
  }
  catch(e){}

  //debugger;
  if(args != '')
  {
    var holder = document.getElementById(_suggestionTableID)
    if(holder != null)
    {
      SetOuterHtml(holder, args);
	    document.getElementById(_KGSuggestionControlDivId).className= _OverlaypositionCss 
	    if(_ConceptTabbedViewHideOrShowControls != "" && _ConceptTabbedViewHideOrShowControls != null)
		    eval(_ConceptTabbedViewHideOrShowControls + '(0)');
	    try
	    {

		    SrmControl_RecordTimes(srmIndex);
	    }
	    catch(e){}
    }
    else
    {
      KGSuggestionControl_ProcessCallBackError('Suggestion Table not found in RegisterJavaScripts() of KGSuggestionControl.', '');
    }  
  }
}

// this will return message in case of error
function KGSuggestionControl_ProcessCallBackError_Wrapped(args, context, _thisClientID)
{
  // 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
  {
    document.getElementById(_thisClientID).innerHTML = '<tr><td>An error has occurred in RegisterJavaScript() of KGSuggestionControl.</td></tr>';
  }
}

// CallbackTrigger Wapper for Knowde Suggestion
function KGSuggestionControl_CallbackTrigger_Knowde_Wrapped(_nounTerm, _verbTerm, _nounKey, _verbKey , _cbreference, _srmIndex)
{
  var args = _nounKey + '=' + _nounTerm + "|"+_verbKey + '=' + _verbTerm + '|SrmIndex=' + _srmIndex;
  
  if(_cbreference != null && _cbreference != "")
    eval(_cbreference);
}

// this will rerender table for knowde suggestion after call back
function KGSuggestionControl_CallbackDone_Knowde_Wrapped(args, context, _suggestionTableID, _KGSuggestionControlDivId, _OverlaypositionCss, _ConceptTabbedViewHideOrShowControls)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var srmIndex;
  var hasResult_Knowde = "0";
  try
  {
    var argsSplit = args.split('[@|@]'); 
    srmIndex = argsSplit[1];
    args = argsSplit[0];
    hasResult_Knowde = argsSplit[2];
  }
  catch(e){}

  //debugger;
  var holder = document.getElementById(_suggestionTableID)
  if(holder != null)
  {
	if(document.activeElement.id == "MapViewTextBox")
	{
		if((hasResult_Knowde != null && hasResult_Knowde == "1")) // TS: Fix bug 3088
		{
			SetOuterHtml(holder,args);
			document.getElementById(_KGSuggestionControlDivId).className= _OverlaypositionCss 
			if(_ConceptTabbedViewHideOrShowControls != "" && _ConceptTabbedViewHideOrShowControls != null)
				eval(_ConceptTabbedViewHideOrShowControls + '(0)');
			try
			{
      
				SrmControl_RecordTimes(srmIndex);
			}
			catch(e){}
		}
		else // need to hide the Suggestions Box
		{
			HideSuggestionsControl();
		}
	}
  }
  else
  {
    KGSuggestionControl_ProcessCallBackError('Suggestion Table not found in RegisterJavaScripts() of KGSuggestionControl.', '');
  }  
}

// this will return message for knowde suggestion in case of error
function KGSuggestionControl_ProcessCallBackError_Knowde_Wrapped(args, context, _thisClientID)
{
  // 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
  {
    document.getElementById(_thisClientID).innerHTML = '<tr><td>An error has occurred in RegisterJavaScript() of KGSuggestionControl for Knowde Suggestion.</td></tr>';
  }
}

// Hide SuggestionControl Java Script Handler
function HideSuggestionsControl_Wrapped(_KGSuggestionControlDivId, _overlayPositionHidden_CSSClass, _ConceptTabbedViewHideOrShowControls)
{
  //debugger;
  if(_KGSuggestionControlDivId != null && document.getElementById(_KGSuggestionControlDivId) != null)
  {
    if (document.getElementById(_KGSuggestionControlDivId).className !=_overlayPositionHidden_CSSClass)
    {  
			//Only need to hide it if it isn't already hidden?
			// hide the droplists for earlier IE versions
			if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0")
			{
				ShowDropLists();
			}
      document.getElementById(_KGSuggestionControlDivId).className=_overlayPositionHidden_CSSClass;
      if (typeof SetFocusToDefaultElement != "undefined")
        eval(SetFocusToDefaultElement); //Bug 2234.
    }
    if (_ConceptTabbedViewHideOrShowControls != "" && _ConceptTabbedViewHideOrShowControls != null)
      eval(_ConceptTabbedViewHideOrShowControls + '(1)');
  }
}

// OnClick event handler in Table Row <tr>
function KGSuggestionControl_onTableRowClickHandler_Wrapped(_selectedConceptId, _highlightedConceptId, _ITEMCONTEXT_CSSCLASS, _CONTEXT_SEPARATOR, _PARENTCONTEXT_SEPARATOR, _thisCallBackMethod, _redirectUrl, _ConceptTabbedViewCallBack, _srmIndex, _rootConceptName, _domainName, e)
{
  if (window.CloseApplicationControl && m_applicationControlOpen && !m_appForceOpen)
  {
    CloseApplicationControl();
  }
	SetSessionProperty("SuggestionClick", "true");
	var el;
	if(e)
	{
		el = e.target || e.srcElement;
  }
  else
  {
		el = this.event.target || this.event.srcElement;
  }
  if(el != null && el.className == _ITEMCONTEXT_CSSCLASS)
  {
    el = el.parentNode;
  }
  if(el != null && el.innerHTML !=null)
  {
    // Fix Bug 3465
    // using title which holds the tooltip of table cell
    var rootPhraseName = '';
    var searchPhrase = el.title;
    SetSessionProperty('SearchContextTextBool', "true");
    SetSessionProperty('SearchContextText', el.innerText);
    if(searchPhrase != null && searchPhrase !='')
    {
        var index1 = searchPhrase.indexOf(_CONTEXT_SEPARATOR);
        var index2 = searchPhrase.lastIndexOf(_PARENTCONTEXT_SEPARATOR);
        if(index1 > 0)
        {
          var originalSearchPhrase = searchPhrase;
          var stringLength = originalSearchPhrase.length;
          searchPhrase = searchPhrase.substring(0, index1);
          if(index2 < 0) // word - word1
          {
             if(stringLength > index1+1)
               rootPhraseName = originalSearchPhrase.substring(index1+1, stringLength);
          }
          else // word - word1, word2
          {
             var startIndex2 = index2+_PARENTCONTEXT_SEPARATOR.length
             if(stringLength > startIndex2)
               rootPhraseName = originalSearchPhrase.substring(startIndex2, stringLength);
          }
        }
        else
        {
          // No contexts in searchPhrase
          rootPhraseName = searchPhrase;
        }
    }
    else // using inner html when title(tooltip) is null
    {
        searchPhrase = el.innerHTML;
        var index1 = searchPhrase.indexOf(_CONTEXT_SEPARATOR);
        if(index1 > 0)
        {
          searchPhrase = searchPhrase.substring(0, index1);
          // Get root display phrase for display as title and tab text
          rootPhraseName = el.innerHTML.substring(index1 + _CONTEXT_SEPARATOR.length);
          var indexc1 = rootPhraseName.lastIndexOf(_PARENTCONTEXT_SEPARATOR);
          var indexc2 = rootPhraseName.lastIndexOf('<');
          var indexc3 = rootPhraseName.indexOf('>');
          if(indexc1 > 0 && indexc2 > 0)
          {
            rootPhraseName = rootPhraseName.substring(indexc1 + _PARENTCONTEXT_SEPARATOR.length, indexc2);
          }
          else if(indexc1 <= 0 && indexc3 > 0 && indexc2 > 0 && indexc2 > indexc3)
          {
            rootPhraseName = rootPhraseName.substring(indexc3+1, indexc2);
          }else
          {
            rootPhraseName = searchPhrase;
          }
        }
        else
        {
          // No contexts in searchPhrase
          rootPhraseName = searchPhrase;
        }    
    }
    
    
    // store in session

    // test only 
    SetSessionProperty('SearchResult_SearchRootPhraseName', rootPhraseName);
    var keys = 'SearchResultTreeViewRootNode|SelectedKnowdeSiblingInfo|KGSuggestion_SearchKeywords';
	  var values = _selectedConceptId + '||';
    SetSessionProperty(keys, values, true);
    /*SetSessionProperty('SearchResultTreeViewRootNode', _selectedConceptId);
    // new default map will be load, clear old session
    SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
    SetSessionProperty('KGSuggestion_SearchKeywords','');*/
    
    
    if (window.SearchResult_ResetTreeScrollingVariables)
      SearchResult_ResetTreeScrollingVariables();
        
		if(el.title == "Domains Table")
			searchPhrase = _rootConceptName;
			
    // Set searchPhrase of KGSearchTextBox by calling KGSearchTextBox Trigger
    // the searchphrase.replace(/\'/g, "\\" + "\'") replaces an apostrophe, with it's escape character ("'" becomes "\'")
    // the "g" ensures all occurances of the apostrophe are replaced rather than just the first.
    eval(_thisCallBackMethod + '(\'' + searchPhrase.replace(/'/g, "\\" + "\'") + '\');');
    
    // Call ConceptTabbedView CallBack Trigger
    var itemCellId = el.id;
    var itemKey = '0';
    var itemType = '0';
    var itemName = '';
    var hightlightedConceptId = '-1';
    var selectedConceptKnowdeId = '-1';
    
    // Get Hightlighted Concept Id
    if(_highlightedConceptId != null && _highlightedConceptId != '')
    {
      var kcindex = _highlightedConceptId.indexOf('-');
      if(kcindex != -1)
      {
        hightlightedConceptId = _highlightedConceptId.substring(0, kcindex);
        selectedConceptKnowdeId = _highlightedConceptId;
      }else{
        hightlightedConceptId = _highlightedConceptId;
        selectedConceptKnowdeId = _highlightedConceptId;
      }
    }
    
    if(itemCellId != null)
    {
      var itemValues = itemCellId.split(_CONTEXT_SEPARATOR);
      if(_selectedConceptId != null && _selectedConceptId !='' && _selectedConceptId != '-1')
        itemKey = _selectedConceptId;
      else if(itemValues!=null && itemValues[0]!=null)
        itemKey = itemValues[0];
      if(itemValues!=null && itemValues[1]!=null)
        itemType = itemValues[1];
      if(itemValues!=null && itemValues[2]!=null)
        itemName = itemValues[2];
    }
    if(itemName == "")
			itemName = _rootConceptName;
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
    
    // add the new selected concept knowde id
    var selectedItemValueString = itemKey + '|' + itemName + '|' + selectedConceptKnowdeId; // rootId|itemName|conceptId-knowdeId

    var keys = 'PageSession_HighlightedConceptId|PageSession_KGSelectedConceptID|SearchResult_NewRootConceptID|HideSearchResultItemInfo|KGShowResultsTab|KGHideSemanticTreeCheckBox|SearchResult_ClickedItemID';
	  var values = hightlightedConceptId + '|' + selectedConceptKnowdeId + '|-1|false|true|false|' + itemKey;
    SetSessionProperty(keys, values, true);

    SetSessionProperty('SearchResultItemClickInfo', selectedItemValueString); 
    
    /*SetSessionProperty('PageSession_HighlightedConceptId', hightlightedConceptId);
    // Set the highlighted concept as the selected concept
    SetSessionProperty('PageSession_KGSelectedConceptID', selectedConceptKnowdeId);  
    SetSessionProperty('SearchResult_NewRootConceptID', -1); // clear tree focus status
    
    SetSessionProperty('HideSearchResultItemInfo', 'false');
    
    //SetSessionProperty('ConceptTabbedView_SelectedTab', 'Results');
    SetSessionProperty('KGShowResultsTab', 'true');
    SetSessionProperty('KGHideSemanticTreeCheckBox',false);
    SetSessionProperty('SearchResult_ClickedItemID', itemKey);*/
    SetSessionProperty('CurrentDomain', _domainName);  //For domain indicator (task 2865)*/
     
    global_SearchResult_ClickedItemID = itemKey;
    
    
    // switch tab
    if (window.KGNavigationControl_SwitchTabs)
      KGNavigationControl_SwitchTabs('Results', rootPhraseName);
    else
    {
      SetSessionProperty('ConceptTreeTabbedView_SelectedTab', 'Results');
      global_ConceptTabbedControl_CurrentlySelectedTab = 'Results';
      SetSessionProperty('KGNavigationControl_SemanticTreeTitleSubFix', rootPhraseName.replace('&','%26'));
    }
    
    SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');

    if (_redirectUrl != "" && _redirectUrl != null)
    {
      // need redirection

      SetSessionProperty('PageSession_LibrarySelectedItemID', itemKey);
      SetSessionProperty('PageSession_LibrarySelectedItemTypeID', itemType);
      SetSessionProperty('PageSession_LibrarySelectedItemName', itemName);
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
        {
          SetSessionProperty('Srm_T0', m_srmT0[_srmIndex]);
          SetSessionProperty('Srm_Action', m_srmAction[_srmIndex] + "," + currentPage + "," + searchPhrase + "," + _selectedConceptId);
          SetSessionProperty('Srm_Callbacks', 1);
        }
      } catch(ex){}
      window.location = hostURL + _redirectUrl;

    }
    else
    {
      // callback
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
        {
          m_srmCallbacks[_srmIndex] = 2;
          m_srmAction[_srmIndex] += "," + currentPage + "," + searchPhrase + "," + _selectedConceptId;
        }
      } catch(ex){}
        
      if (window.CancelEdit)
        CancelEdit(true);
      
      // escape all occurrences of apostrophe in item and rootPhraseNames
      rootPhraseName.replace(/'/g, "\\" + "\'");
      itemName.replace(/'/g, "\\" + "\'");
      rootPhraseName.replace(/'/g, "")
      eval(_ConceptTabbedViewCallBack + '(\'' + itemKey + '\',\'' + itemType + '\',\'' + itemName + '\', \'' + rootPhraseName + '\', _srmIndex);');
    }
  }
  else
  {
    alert('The searchPhrase is null!');
  }
}

function KGSuggestionControl_ExternalSearchClick_Wrapper(_thisCallBackMethod, _redirectUrl, _ConceptTabbedViewCallBack, _srmIndex)
{
		SetSessionProperty("SuggestionClick", "true");
    // new default map will be load, clear old session
    SetSessionProperty('SelectedKnowdeSiblingInfo', '');	

    if (window.SearchResult_ResetTreeScrollingVariables)
      SearchResult_ResetTreeScrollingVariables();
      
    SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
    // hide the semantic tree
    SetSessionProperty('KGNavigationControl_SemanticTreeVisible', false);

    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
   
    if (_redirectUrl != "" && _redirectUrl != null)
    {
      // need redirection
      SetSessionProperty('PageSession_KGSelectedConceptID', '0');
      SetSessionProperty('KGMapViewCollapsed',true);
      SetSessionProperty('KGHideSemanticTreeCheckBox',true);
      // set search phrase
      var searchBox = KGSearchControl1_GetSearchBox();
      var searchPhrase = '';
      if(searchBox != null && searchBox.value!=null && searchBox.value!='')
      {
         SetSessionProperty('KGSuggestion_SearchKeywords',searchBox.value);
         window.location = hostURL + _redirectUrl;
         
      }
      
    }

}

// OnClick event handler in Table Row for click on user <tr>
function KGSuggestionControl_onTableRowClickHandler_User_Wrapped(_userIdsString, _userName, _thisCallBackMethod, _redirectUrl)
{    
//debugger;
 
	 // new default map will be load, clear old session
	 var keys = 'SelectedKnowdeSiblingInfo|KGSuggestion_SearchKeywords';
	 var values = '|';
   SetSessionProperty(keys, values, true);

	 //SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
	 //SetSessionProperty('KGSuggestion_SearchKeywords','');
    
  // Set searchPhrase of KGSearchTextBox by calling KGSearchTextBox Trigger
  // the searchphrase.replace(/\'/g, "\\" + "\'") replaces an apostrophe, with it's escape character ("'" becomes "\'")
  // the "g" ensures all occurances of the apostrophe are replaced rather than just the first.
  eval(_thisCallBackMethod + '(\'' + _userName.replace(/'/g, "\\" + "\'") + '\');');
  
  var currentLocation = window.location.href;
  var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
  var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
  
  if (_userIdsString.indexOf('|') < 0)
  {// there's only one user with that name
    var querystring = '?user=' + _userIdsString;
    window.location = hostURL + 'options.aspx' + querystring;
  }
  else
  {// more than one user share the name, go to multi user search page
    var keys = 'KG_RedirectFrom|KGMapViewCollapsed|RemoveSelectedConcept|IndexedDocListMode';
	  var values = 'KGSearchControl|true||IndexedDocuments';
    SetSessionProperty(keys, values, true);

    //SetSessionProperty('KG_RedirectFrom','KGSearchControl')
    SetSessionProperty('MultiUserSearchPage', _userName + '@' + _userIdsString);
    //SetSessionProperty('KGMapViewCollapsed', true);
    //SetSessionProperty('RemoveSelectedConcept', ''); // see SessionPropertiesAshxHandler.cs
    //SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
      
    /*if (window.KGTabbedWindowsControl_CallbackTrigger)//Check if we are on the map view page
    {//callback
      if (window.CancelEdit)
        CancelEdit(true);
      
      //DoCollapseMapViewPane();
      globalIndexedDocsPageLoaded = false;
      KGTabbedWindowsControl_CallbackTrigger('TabSelected, Indexed Documents');
      KGButtonToolbar_IndexedDocListLoaded(true);
    }
    else
    {//redirect to MapTabbedView page*/
      window.location = hostURL + _redirectUrl;
    //}
  }
}

// set up correct session variables so the result tree will auto expand the selected context
function KGSuggestionControl_PrepareTreeAutoExpand(_expandedNodes)
{
  // for result tree auto expansion
  SetSessionProperty('SearchResultsNodeStatus', _expandedNodes);
}

// OnClick event handler for seleting noun phrase of Knowde in MapView in Table Row <tr>
function KGSuggestionControl_onTableRowClickNounHandler_Wrapped(_CONTEXT_SEPARATOR, _CallBackMethod_KnowdeNoun, e)
{
  var el = e.target || e.srcElement;
  var itemCellId = null;
  var itemType = null;
  var nounTerm = null;
  var verbTerm = null;
  
  if(el != null )
    itemCellId = el.id;
    
  if(itemCellId != null)
  {
    var itemValues = itemCellId.split(_CONTEXT_SEPARATOR);
    // Cell ID: Key - Type - Noun - Verb
    if(itemValues != null && itemValues.length >= 4) 
    {
      if(itemValues!=null && itemValues[1]!=null)
        itemType = itemValues[1];
      if(itemValues!=null && itemValues[2]!=null)
        nounTerm = itemValues[2];
      if(itemValues!=null && itemValues[3]!=null)
        verbTerm = itemValues[3];
        
      if(itemType != null && itemType == "1"  && itemValues!=null && itemValues[2]!=null) 
      { // verb moved up because of noun is empty
        verbTerm = itemValues[2];
        nounTerm = null;
      }
        
    }
  }

  if(el != null)
  {
    if (itemType == null)
      itemType = '';
  
    if(nounTerm != null)
    {
      // to be continue..
      nounTerm = nounTerm.replace(/'/g, "\\" + "\'");
    }
    else
    {
      nounTerm = '';
    }
      
    if(verbTerm != null)
    {
      verbTerm = verbTerm.replace(/'/g, "\\" + "\'");
    }
    else
    {
      verbTerm = '';
    }
   
    if (itemType != null && (verbTerm != '' || nounTerm !='' ) )
    {
     // Set Noun Phrase of Selected Knowde in MapView by calling SetKnowdeNounMapView javascript
     eval(_CallBackMethod_KnowdeNoun + '(\'' + itemType +'\',\''+ nounTerm + '\',\'' + verbTerm + '\');');
    }
    
    // Hide Suggestion Control
    HideSuggestionsControl();
  }
  else
  {
    alert('The searchPhrase is null!');
  }
}

