﻿var globalCommunityVisibleTab;
var globalCommunityListViewShowAddBtn;
var globalCommunityKnowdeChanged;
var globalCommunityTabLoaded;
var globalCommunityContainerId;
var CommunityLinkAdminUser = false; // default false, but will be overwritten by CommunityTabControl
var globalCommunityiframesrc = '';

function LoadCommunityTab(_mode, _extraRepopArgs)
{   
  //changes the tab mode and loads the content

  // clear the new tab first so it looks tidy while the callback's happening
  KGCommunityTabControl_ClearTab(_mode);

  // switch to list view, user or iframe tab
  KGCommunityTabControl_SwitchTab(_mode, true);
  
  // repopulate the selected tab
  KGCommunityTabControl_RepopulateCurrentTab(_extraRepopArgs);
}

function LoadCommunityTabPageLoad(_addLink)
{
  if ( Splitter1 == undefined )
  {
    if ( _addLink == true )
      window.setTimeout('LoadCommunityTabPageLoad(true)', 100);
    else
      window.setTimeout('LoadCommunityTabPageLoad(false)', 100);
  }
  else
  {
    KGCommunityTabControl_Activate();
    ChangeTabToolStrip('communities');
    
    try
    {
      DoExpandMapViewPane('split');
    }
    catch(err)
    {
      if ( _addLink == true )
        window.setTimeout('LoadCommunityTabPageLoad(true)', 200);
      else
        window.setTimeout('LoadCommunityTabPageLoad(false)', 200);      
    }
    
    ShowSplitterArrowDown();
    globalSplitterSetting = "split";        
    
    if (_addLink)
      window.setTimeout('OpenKGAddCommunityLinkControl()');
  }
}

function KGCommunityTabControl_ClearTab(_mode)
{
  switch (_mode)
  {
    case "ListView":
      KGCommunityTabControl_ResetToLoading(KGCommunityTabControl_GetComCtlId());
      break;
    case "User":
      KGCommunityTabControl_ResetToLoading(KGCommunityTabControl_GetMemberCtlId());
      break;
    case "Iframe":
      KGCommunityTabControl_SetIframeSrc("");
      break;
  }
}

function KGCommunityTabControl_ResetToLoading(_ctlId)
{
  var ctl = document.getElementById(_ctlId);
  if (ctl)
    ctl.innerHTML = "<table class=\"MapLoadingIcon\" ><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>"
}

function KGCommunityTabControl_SwitchTab_Wrapped(_mode, _isRepop, _listViewTabId, _userTabId, _iframeTabId, _contactTabId)
{
  //changes the tab mode without loading any content
  //_isRepop should only be set to true when KGCommunityTabControl_RepopulateCurrentTab is going to be called
  //  i.e. from LoadCommunityTab
  
  SetCommunityTabButtons(_mode, globalCommunityVisibleTab, _isRepop); // call this BEFORE updating globalCommunityVisibleTab

  globalCommunityVisibleTab = _mode;
  // show the relevant tab and hide the other(s)
  var listViewTab = document.getElementById(_listViewTabId);
  var userTab = document.getElementById(_userTabId);
  var iframeTab = document.getElementById(_iframeTabId);
  var contactTab = document.getElementById(_contactTabId);

  
  listViewTab.style.display = "none";
  userTab.style.display = "none";
  iframeTab.style.display = "none";
  contactTab.style.display = "none";

  switch (_mode)
  {
    case "ListView":
      listViewTab.style.display = "block";
      break;
    case "User":
      userTab.style.display = "block";
      break;
    case "Iframe":
      iframeTab.style.display = "block";
      break;  
    case "Contact":
      contactTab.style.display = "block";
      break;
  }
}

function SetCommunityTabButtons(_newTab, _oldTab, _isRepop)
{
  // Add Link button - show with the ListView
  // Show List button - show if new tab isn't ListView
  if (_newTab == "ListView") 
  {
    // if the ListView is going to repopulate, don't show the button until callback done
    //    because of the iframe logic it might switch to the iframe tab in callback done, then these buttons will change again quickly - looks odd
    if (!_isRepop) 
      KGCommunityTabControl_UpdateButtonsForListView(); // using a separate function here so it'll be exactly the same when it's called from callback done, just later
  }
  else // not showing the list view
  {
    KGCommunityTabControl_ShowHideAddLinkBtn(false);
    KGCommunityTabControl_ShowHideShowListBtn(true);
  }
  
  // Back to User button - show when we leave a user; hide when we show a user
  if (_newTab == "User") // hide the button when we're showing a user
    KGCommunityTabControl_ShowHideBackToUserBtn(false);
  else if (_oldTab == "User") // show the button when we leave a user page
    KGCommunityTabControl_ShowHideBackToUserBtn(true);
}

function KGCommunityTabControl_UpdateButtonsForListView()
{
  // are we in edit mode editing a new knowde
  var editingNewKnowde = m_bEditable && m_SelectedKnowdeEditing && m_IsEditFromNewKnowde;

  // hide the add link button if we are editing a new knowde
  //if (editingNewKnowde)
  KGCommunityTabControl_ShowHideAddLinkBtn(false);
  //else // otherwise do the usual check
  //  KGCommunityTabControl_ShowHideAddLinkBtn(globalCommunityListViewShowAddBtn);
  KGCommunityTabControl_ShowHideShowListBtn(false);
}
      
function KGCommunityTabControl_ShowHideAddLinkBtn(_show)
{
 //ShowHideButton(_show, "KGToolStrip_AddLinkButton")
 ShowHideButton(false, "KGToolStrip_AddLinkButton")
}

function KGCommunityTabControl_ShowHideBackToUserBtn(_show)
{
  ShowHideButton(_show, "KGToolStrip_BackToUser")
}

function KGCommunityTabControl_ShowHideShowListBtn(_show)
{
  ShowHideButton(_show, "KGToolStrip_ShowList")
}

function KGCommunityTabControl_ShowList()
{
  if (globalCommunityKnowdeChanged)
    LoadCommunityTab("ListView"); // do need to repopulate it - I'm not sure we can get to here atm
  else
    KGCommunityTabControl_SwitchTab("ListView"); // don't need to repopulate it
}

function KGCommunityTabControl_RepopulateCurrentTab(_extraRepopArgs)
{
  var whatId = GetGlobalHighlightedWhatId();
  
	if (globalCommunityVisibleTab == "ListView" || globalCommunityVisibleTab == "QueryHasLink")
	{
    if((window.globalLastSelectedKnowde && globalLastSelectedKnowde != null && globalLastSelectedKnowde != "undefined") || whatId != '')
    {
      var knowdeID = whatId;
			if(knowdeID == '')
			  knowdeID = returnKnowdeID(globalLastSelectedKnowde)
	    SetSessionProperty('CurrentKnowdeIDForTab', knowdeID); // could pass this in and set it during the callback for performance, but I think the CommunityLinkControl needs it aswell so it might get set too late
    }
	}
	
  // callback to inner control
  switch (globalCommunityVisibleTab)
  {
    case "ListView":

      var args = "Action=Load";
      if (_extraRepopArgs)
        args += "|" + _extraRepopArgs;
      KGCommunityControl_CallbackTrigger(args);    
      break;
    case "User":
      var args = "Action=Load"
      if (_extraRepopArgs)
        args += "|" + _extraRepopArgs;
      Com_KGMemberControl_CallbackTrigger(args);
      break;
    case "Iframe":
      // _extraRepopArgs holds the new src for the iframe
      // on a timeout to give the 'clear' chance to happen before loading the new page as loading the new page isn't very fast
      if ( _extraRepopArgs != undefined )
        setTimeout("KGCommunityTabControl_SetIframeSrc('" + _extraRepopArgs + "')", 10);
      break;
    case "QueryHasLink":
      var args = "Action=QueryHasLink";
      KGCommunityControl_CallbackTrigger(args);
      break;
  }
  globalCommunityTabLoaded = true;
}
  
function KGCommunityControl_CallbackError(_args, _context)
{
  var alertMessage = "The KGCommunityControl encountered an error. \n\n" + _args;
  alert(alertMessage);
}

function KGCommunityControl_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)
  {
    KGCommunityControl_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 retMsg = eval( '(' + json + ')' );
  
  if (retMsg.KeepIframe)
  { // keep the iframe instead of loading the contents
    if (retMsg.IframeUrl != "")
    {
      // this will clear the tab before loading in the new src, so it's tidier incase it's slow
      KGCommunityTabControl_SetIframeSrc("");
      setTimeout("KGCommunityTabControl_SetIframeSrc('" + retMsg.IframeUrl + "')", 10);
    }
    
    KGCommunityTabControl_SwitchTab("Iframe");
    
    // need to show the community options
    var communitiesOptionsDiv = document.getElementById("TSC_TabStripControl_OptionDiv");
    if ( communitiesOptionsDiv != null )
    {
      communitiesOptionsDiv.style.display = "block";
    } 
  }
  else
  { // don't keep the iframe; do load the contents
    if (retMsg.Action == 'QueryHasLink')
    {
      // need to hide the community options
      var communitiesOptionsDiv = document.getElementById("TSC_TabStripControl_OptionDiv");
      if ( communitiesOptionsDiv != null )
      {
        communitiesOptionsDiv.style.display = "none";
      }     
    
      LoadCommunityTab('Contact');
      return;
    }
    var javascripts = argsSplit[1];
    var htmlContent = argsSplit[2];
    
    var holderId = retMsg.HolderId;

    var holder = document.getElementById(holderId);
    if (!holder)
    {
      KGCommunityControl_CallbackError('The holder doesn\'t exist ' + holderId);
      return;
    }
    
    // fill the control
    SetOuterHtml(holder, htmlContent);
    globalCommunityKnowdeChanged = false;
    globalCommunityContainerId = retMsg.ContainerId;
    
    // show the "ComingSoon" message if required
    if (retMsg.ShowComingSoon)
      KGCommunityControl_ShowHideComingSoon(true, retMsg.ContainerId, retMsg.ComingSoonCtrId);
    if(retMsg.ShowIframeMsg)
      KGCommunityControl_ShowMessageBox('NoLinkedConversation', 150, 10);
    
    // eval any javascripts
    if (javascripts)
      eval(javascripts);
    
    globalCommunityListViewShowAddBtn = retMsg.ShowAddLinkBtn;
    // update the buttons
    KGCommunityTabControl_UpdateButtonsForListView();
  }
}

function KGCommunityTabControl_SetIframeSrc(_src)
{
  var iframe = KGCommunityTabControl_GetIframe();
  iframe.src = _src;
  globalCommunityiframesrc = _src;
}

function SetBlogCommentName(_userName)
{
  return;
  // do this through a param 
  var iframe = window.frames['CommunityTabIFrame'];
  
  if (iframe != null && globalCommunityiframesrc.indexOf(location.hostname) != -1)
  {
    var nameField = iframe.document.getElementById('author');
    if (nameField != null)
      nameField.value = _userName;
  }
}

function KGCommunityTabControl_GetIframe()
{
  var iframeId = KGCommunityTabControl_GetIframeId();
  return document.getElementById(iframeId);
}

function KGCommunityControl_ShowHideComingSoon(_show, _containerId, _comingSoonCtrId)
{
  var container = document.getElementById(_containerId);
  var comingSoonCtr = document.getElementById(_comingSoonCtrId);
  
  if (_show)
  {
    // the container needs to be wider to fit them both in
    container.className = "KGCommunityControl_ContainerWide";
    comingSoonCtr.style.display = ""; // clear display none to display the message
  }
  else
  {
    container.className = "KGCommunityControl_Container";
    container.childNodes[1].style.position = 'relative';
    comingSoonCtr.style.display = "none";
  }
}

function KGCommunityControl_CommunityLinkRatingOnClick(_star, _kclID)
{
  // get the KGRatingControl to handle the star click
  var starRating = KGRatingControl_StarClicked(_star);
  
  // callback to save the setting
  var args = "Action=RateCommunityLink";
  args += "|KCLID=" + _kclID;
  args += "|Rating=" + starRating;
  KGCommunityControl_CallbackTrigger(args);
}

function setCommunityTabMode()
{ // knowde changed either from knowde click or new map
  globalCommunityKnowdeChanged = true; // will need to reload the list view for the new knowde
}

function KGCommunityTabControl_Activate()
{
  // could be a knowde click or a tab click
  // might need to reload some content, might not
  
  var mode = "QueryHasLink";
  if (CommunityLinkAdminUser)
    mode = "ListView";
  
  if (globalCommunityKnowdeChanged) // knowde changed since the last repop
  {
    if (globalCommunityVisibleTab == "Iframe")
    {
      var iframe = KGCommunityTabControl_GetIframe();
      var extraRepopArgs = "IsIframe=true|Url=" + iframe.src; // urls shouldn't contain pipes - it's caught in the add link validation
      LoadCommunityTab(mode, extraRepopArgs); // mode depends whether conversation from that domain is linked to new knowde
      // assume it's the ListView and switch back to the iframe later if not
      //    means we can do it all in one callback to the CommunityControl, because if we need an iframe we just send back the src; if we need the ListView we can get the ListView same as usual
      // tiny thing to watch - the ListView tab will get cleared and then if it's an iframe not repopulated
      //    but globalCommunityKnowdeChanged isn't updated in that case so we still know that tab needs repopulating
    }
    else // not showing iframe - default to list view, unless it was on an iframe conversation
      LoadCommunityTab(mode);
  }
  else // knowde hasn't changed
  {
    if (globalCommunityTabLoaded) // we already have something to show, so just leave it
      return;
    else 
      LoadCommunityTab(mode); // load a list view
  }
}
function KGCommunityControl_OpenLinkInNewWindow(e, _url, _divClientID, _newWindowAtts)
{
  e = e || window.event;
  //debugger;
  
  window.open(_url, _divClientID + '_linkWindow', _newWindowAtts);
  KGCommunityControl_ShowMessageBox('LinkInNewWindow', 120, e.y - 70);
}

function KGCommunityControl_ShowMessageBox(_type, _posX, _posY)
{
  if(_type != 'LinkInNewWindow' && _type != 'NoLinkedConversation')
    return;
    
  // check cookie setting
  if(WM_readCookie('Message_' + _type) == "off")
    return;
    
  var container = document.getElementById(globalCommunityContainerId);
  if(container != null && container.childNodes.length == 3)
  {
    var msgBoxDiv = container.childNodes[2];
    if(msgBoxDiv != null)
    {
      var userMsg = '';
      if(_type == 'LinkInNewWindow')
        userMsg += 'This site has been opened in a new browser. The linked site has not yet implemented the required technology to be embedded in our site.';
      else if(_type == 'NoLinkedConversation')
        userMsg += 'No linked conversations for the current domain have been found. You are therefore viewing the list view for this Knowde.';
      userMsg += '<br /><br />';
      userMsg += '<div style="width:100%;"><span style="float: left; margin-top: 3px; color: grey;"><INPUT id="MessageCheckBox_' + _type + '" type="checkbox" />Do not show this message again</span><input type="button" class="CommunityLinkControlBtn" value="OK" onclick="KGCommunityControl_HideMessageBox(\''+ _type + '\');"/></div>';
          
      msgBoxDiv.innerHTML = userMsg;
      
      // position the box
      if(_posX < 0)
        _posX = 5;
      if(_posY < 0)
        _posY = 5;        
        
      // check TCC scroll postiion
      var tcc = document.getElementById('TCC');
      if(tcc != null && tcc.parentNode != null)
      {
        var scrollTop = tcc.parentNode.scrollTop;
        if(_posY < scrollTop)
          _posY = scrollTop;
      }

      msgBoxDiv.style.left = _posX + 'px';
      msgBoxDiv.style.top = _posY + 'px';
      msgBoxDiv.style.position = 'absolute';
      msgBoxDiv.style.display = 'block';
    }
  }
  
}

function KGCommunityControl_HideMessageBox(_type)
{
  var cb = document.getElementById('MessageCheckBox_' + _type);
  if(cb != null && cb.checked == true)
  {
    WM_setCookie('Message_' + _type,'off', m_helpCookieExpiration); // turn it off, cookie expire in 7 days
  }
  
  var container = document.getElementById(globalCommunityContainerId);
  if(container != null && container.childNodes.length == 3)
  {
    var msgBoxDiv = container.childNodes[2];
    if(msgBoxDiv != null)
    {
      msgBoxDiv.style.display = 'none';
      msgBoxDiv.innerHTML = '';
    }
  }
}



