﻿// KGApplicationControl JScript File
var m_KGApplicationControl_appID = 0;
var m_KGApplicationControl_appKGID = 0;
var m_KGApplicationControl_appKGExecutionType = 'Native';
var m_KGApplicationControl_appKGDragDrop = 'false';

var m_applicationFrameLoadingDivTimeOut;
var m_applicationFrameCallbackStatus;
var m_applicationControlOpen = false;
var m_applicationKGID = 0;
var m_applicationKGGroupID = -1;
var m_dragBox;
var m_appForceOpen = false; // set to true to keep the application window open over page redirects etc.

function KGApplicationControl_CallbackDone_Wrapped(_args, _context, _controlDivID)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
	// set the callback status
	m_applicationFrameCallbackStatus = 'done';
	// hide the loading div
	HideOrShowApplicationControlLoadingDiv(false);
  
	if (_args.indexOf("Exception") == -1)
	{
		// First off is to convert our arguments into a proper object. What comes back should be JSON 
		// so we simply evaluate it into an object
		var retMessage = eval( '(' + _args + ')');
    
		if (retMessage.Action != "Unload")
		{
			// set overlay div size and position
			applicationBox = document.getElementById(_controlDivID);
			applicationBox.style.top = screen.height/4;//"30%"; //screen.height/3;
			applicationBox.style.height = screen.height/2;
			applicationBox.style.left = "15%";
			applicationBox.style.width = "900px";
    	
			OpenApplicationControl();
      
			var ApplicationFrame = document.getElementById("ApplicationFrame");
      
      switch (retMessage.Action)
      {
        case "Load":
          ApplicationFrame.src = retMessage.InterfaceURL;
          // reset the global var once load complete
          m_KGApplicationControl_appID = 0;
          m_KGApplicationControl_appKGID = 0;
          m_applicationKGID = retMessage.AppKGID;
          m_applicationKGGroupID = retMessage.AppKGGroupID;
          switch (retMessage.ExecutionType)
          {
            case "Native":
              m_appForceOpen = false;
              break;
            case "KGContextual":
              m_appForceOpen = true;
              break;
          }
          if (retMessage.MaximiseOnLoad)
            MaximiseKGApplicationControl();

          if (typeof loadAppKnowde == "object" && loadAppKnowde != null)
          {
            setTimeout((function(){ApplicationContextChanged(loadAppKnowde.kid, loadAppKnowde.kgid);}),100);
          }
          break;
        case "LoadAlert":
          ApplicationFrame.src = retMessage.InterfaceURL;
          ApplicationFrame.className = "applicationIFrame";
          ApplicationFrame.style.width = '100%';
          ApplicationFrame.style.height = '100%';
          // reset the global var once load complete
          m_KGApplicationControl_appID = 0;
          m_KGApplicationControl_appKGID = 0;
          m_applicationKGID = 0;
          m_applicationKGGroupID = 0;
          m_appForceOpen = false;
          
          if (retMessage.MaximiseOnLoad)
            MaximiseKGApplicationControl();

          break;
        case "ContextChanged":
          ApplicationFrame.src = retMessage.InterfaceURL;
          if (typeof loadAppKnowde == "object" && loadAppKnowde != null && retMessage.MaximiseOnLoad)
          {
            MaximiseKGApplicationControl();
		    loadAppKnowde = null;
          }
          break;
      }
    }
  }
  else
  {
    alert(_args);
  }
}

function KGApplicationControl_CallbackError(_args, _context)
{
  alert(_args);
}

function HideOrShowApplicationControlLoadingDiv_Wrapped(_divId, _show, _message)
{
  if(m_applicationFrameLoadingDivTimeOut != null)
  {
    clearTimeout(m_applicationFrameLoadingDivTimeOut);
    m_applicationFrameLoadingDivTimeOut = null;
  }
  
  var div = null; 

  if(_divId != null && _divId != '')
    div = document.getElementById(_divId);
  if(_message == null)
    _message = 'Loading...';

  if(_show != null && _show == true && m_applicationFrameCallbackStatus != 'trigger')
  {
    // callback done has finished before the trigger time out to show the loading div, 
    // so don't need to show it anymore
    return;
  }
   
  if (div != null)
  {
    if(_show != null && _show == true && div.style.display != 'block')
    {
      var top = 60;
      var left = 172;
      
      // calculate the position based on the textView region
      var parentDiv = div.parentNode;
      
      //if(parentDiv.clientHeight != null && parentDiv.clientHeight != '' && parentDiv.clientHeight > 60)
        //top = 60;
          
      if(parentDiv.clientWidth != null && parentDiv.clientWidth != '' && parentDiv.clientWidth > 0)
        left = parentDiv.clientWidth/2 - 60;
        
      if(left <= 0)
        left = 0;
  
      div.innerHTML = "<img src='Images/LoadingBar.gif' width='21px' height='21px'/>&nbsp;" + _message;
      div.style.top = top + 'px';
      div.style.left = left + 'px';
      div.style.display = 'block';
    }
    else if(div.style.display != 'none')
    {
      div.style.display = 'none';
      div.innerHTML = '';
      div.style.top = '0px';
      div.style.left = '0px';
    }
  }
}

function OpenApplicationControl_wrapped(_hideDockButton, _imgDockInPageID)
{
  var docButton = document.getElementById(_imgDockInPageID);
  if (docButton != null)
  {
    if (_hideDockButton)
    {
      docButton.style.display = "none";
      globalHideDockButton = true;
    }
    else
    {
      docButton.style.display = "";
      globalHideDockButton = false;
    }
  }
  
  // make sure the docked window is close then the help control popup
  //if(document.getElementById('DockedApplicationWindowContainer') != null)
    //CloseDockedKGApplicationControl('ApplicationFrame');
  
  ShowKGApplicationControl();
  m_applicationControlOpen = true;
  // enable drag and drop KG into appWindow
  
  setupKGDragDropBox();
}

function KGApplicationControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{

  //var MapHelpBox = document.getElementById("KGHelpControlID1");
  //MapHelpBox.title = "Associated Text";
  
  //var imgDockInPage = document.getElementById(_imgDockInPageID);
  //if (imgDockInPage.style.display == "none")
    //imgDockInPage.style.display = "";
  var args;
  // Construct the callback arguments
  if(_args != null)
  { 
    args = _args;
    
    if(args.length > 0)
    {
      if(m_applicationFrameLoadingDivTimeOut != null)
      {
        clearTimeout(m_applicationFrameLoadingDivTimeOut);
        m_applicationFrameLoadingDivTimeOut = null;
      }
      
      if (m_applicationControlOpen)
      {
        // Make sure we clear the contents of the application window
        ClearApplicationFrame();
        // show the loading div
        m_applicationFrameLoadingDivTimeOut = window.setTimeout("HideOrShowApplicationControlLoadingDiv(true, 'Loading...')",10);
      }
      
      // the current status of the callback
      m_applicationFrameCallbackStatus = 'trigger';
      // trigger the callback
      eval(_callbackScript);
    }
  }
}

function CloseApplicationControl()
{  
	if(document.getElementById("GreyDiv") != null)
	{
	    purge(document.getElementById("GreyDiv"));
		document.getElementById("Form1").removeChild(document.getElementById("GreyDiv"));
		document.getElementById("m_cookieDiv").className = "m_cookieDivHidden";
		document.getElementById("miniGlobe").className = "miniGlobe";
	}
  var ApplicationBox = document.getElementById("KGApplicationControlID1");
  
  // reset the tooltip
  ApplicationBox.title = "Associated Text";
  // hide textview view option div
  //if(window.HideOrShowTextViewOptionDiv)
    //HideOrShowTextViewOptionDiv(false);
  
  // reset the view mode
  //if(window.SwitchTextViewViewMode)
    //SwitchTextViewViewMode("Single");
  
  ClearApplicationFrame()
  m_applicationControlOpen = false;
  m_appForceOpen = false;
  HideKGApplicationControl();
  ApplicationUnload();
  
  // if in profile page, refresh the alerting control
  if(window.location.href.toLowerCase().indexOf('options.aspx') > -1)
  {
    var args='action=load';
    KGAppAlertingControl_CallbackTrigger(args);
  }
  
}

function ClearApplicationFrame()
{
  
  var ApplicationFrame = document.getElementById("ApplicationFrame");
  if (ApplicationFrame.src != null && ApplicationFrame.src != "")
  {
    var parent = ApplicationFrame.parentNode;
    
    var newApplicationFrame = document.createElement('iframe');
    newApplicationFrame.id = "ApplicationFrame";
    newApplicationFrame.className = "applicationIFrame";
    newApplicationFrame.frameBorder = 0;
      
    purge(ApplicationFrame);  
    parent.removeChild(ApplicationFrame);
    InsertAdjacentElement(parent,"beforeend", newApplicationFrame);
  }
  else
  {
    // Make sure we clear the contents of the document window
    ApplicationFrame.contentWindow.document.write("");
    ApplicationFrame.contentWindow.document.close();
  }
}

function LoadApplicationControl(_reload, _checkExistingOpenApp)
{
  if (window.KGApplicationControl_CallbackTrigger)
  {
		if(_reload == "true")
		{
		  if(_checkExistingOpenApp == "true")
		  { 
		    // for auto open app after go to other pages and back to home page by click a category
		    if(window.location.href.toLowerCase().indexOf('home.aspx?category=') != -1 && m_KGApplicationControl_appKGDragDrop == 'false')
		    {
		      if(!m_applicationControlOpen && m_KGApplicationControl_appID != 0 && m_KGApplicationControl_appKGExecutionType == 'KGContextual')
		      {
		        var args = 'Action=Load|AppID=' + m_KGApplicationControl_appID + '|AppKGID=' + m_KGApplicationControl_appKGID;
				    KGApplicationControl_CallbackTrigger(args);
		      }
		    }
		  }
		  else
		  {
			  if (m_KGApplicationControl_appID != 0)
			  {
				  var args = 'Action=Load|AppID=' + m_KGApplicationControl_appID + '|AppKGID=' + m_KGApplicationControl_appKGID;
				  KGApplicationControl_CallbackTrigger(args);
			  }
			  else if (m_applicationControlOpen)
			  {
				  CloseApplicationControl();
			  }
			}
    }
  }
  else
  {
    setTimeout("LoadApplicationControl('" + _reload + "', '" + _checkExistingOpenApp + "')", 100);
  }
}

function LoadApplicationControlAlert()
{
  if (window.KGApplicationControl_CallbackTrigger && g_exMapCtl)
  {
			if (m_KGApplicationControl_appID != 0)
			{
				var args = 'Action=LoadAlert|AppID=' + m_KGApplicationControl_appID + '|AppUrl=' + g_exMapCtl.url.replace(new RegExp('=',"g"),'[eq]');
				KGApplicationControl_CallbackTrigger(args);
			}
			else if (m_applicationControlOpen)
			{
				CloseApplicationControl();
			}
  }
}


var global_appKgID = "";
function ApplicationContextChanged(_knowdeID, _appKgID, _contextKGID)
{
//debugger;
	if(global_appKgID == "")
		global_appKgID = _appKgID;
	if(global_appKgID == _appKgID)
	{
		var args = 'Action=ContextChanged'
		if (_knowdeID != null)
			args += '|ClientKnowdeID=' + _knowdeID;
		if (_appKgID != null)
			args += '|AppKGID=' + _appKgID;
		if (_contextKGID != null)
			args += '|ContextKGID=' + _contextKGID;
		KGApplicationControl_CallbackTrigger(args);
  }
}

function ApplicationUnload()
{
	global_appKgID = "";
  var args = 'Action=Unload';
  KGApplicationControl_CallbackTrigger(args);
}

// DragDropBox class
function DragDropBox(_box)
{
  // setup the drag box for dragging
  this.startDrag = function()
  {
    this.CurrentlyDragging = true;
    box.style.display = '';
  }
  
  // hide the drag box
  this.stopDrag = function()
  {
    this.CurrentlyDragging = false;
    box.style.display = 'none';
  }
  
  var box = _box;
  box.style.position = 'absolute';
  this.stopDrag();
  
  // return box id
  this.getId = function()
  {
    return box.id;
  }
  
  this.getBox = function()
  {
    return box;
  }
  
  // set box position
  this.setPosition = function(_x, _y)
  {
    if(box.childNodes.length > 0 && box.childNodes[0].tagName == 'group')
    {
      box.style.left = _x - box.childNodes[0].style.width.replace('px','')/2 + "px";
      box.style.top = _y - box.childNodes[0].style.height.replace('px','')/2 + "px";
    }
    else
    {
      box.style.left = _x - box.offsetWidth/2 + "px";
      box.style.top = _y - box.offsetHeight/2 + "px";
    }
  }
  
  // set the box size
  this.setSize = function(_height, _width)
  {
    box.style.height = _height + "px";
    box.style.width = _width + "px";
  }
  
  // insert the box into the _parent
  this.insertInto = function(_parent)
  {
    _parent.appendChild(box);
  }
  
  // remove the element from the DOM
  this.remove = function()
  {
    box.parentNode.removeChild(box);
  }
  
  // store the Target position and size
  this.setTarget = function(_target)
  {
    this.TargetTop = GetPixelTop(_target);
    this.TargetLeft = GetPixelLeft(_target);
    this.TargetWidth = _target.offsetWidth;
    this.TargetHeight = _target.offsetHeight;
  }
  
  // check to see if the coordinates _x, _y are within the target
  this.targetHit = function(_x, _y)
  {
    if (_x > this.TargetLeft && _x < this.TargetLeft + this.TargetWidth
         && _y > this.TargetTop && _y < this.TargetTop + this.TargetHeight)
      return true;
    else
      return false;
  }
  return true;
}

function setupKGDragDropBox()
{
  var kgDragDropBox = document.getElementById('KGDragDropBox');
  if(kgDragDropBox != null)
  {
    // remove the old one
    kgDragDropBox.parentNode.removeChild(kgDragDropBox);
  }
  kgDragDropBox = document.createElement('div');
  kgDragDropBox.id = 'KGDragDropBox';
  kgDragDropBox.className = 'docList_KGIcon';

  m_dragBox = new DragDropBox(kgDragDropBox);
  
  // insert the dragbox as a sibling of the ApplicationBox
  var ApplicationBox = document.getElementById("KGApplicationControlID1");
  m_dragBox.insertInto(ApplicationBox.parentNode);
  // set the size and position of the dragBox
//  var width = 100;
//  var height = 100;
//  m_dragBox.setSize(height, width);
}

function KGDragStart(e, _kgID, _knowdeID, _content)
{
  if (m_dragBox != null)
  {
    m_dragBox.KGID = _kgID;
    m_dragBox.KndID = _knowdeID;
    var box = m_dragBox.getBox();
    
    // set appearance
    if(_knowdeID == null)
    {
      box.className = 'docList_KGIcon';
    }else
    {
      box.className = '';
      if(_content != null)
      {
        box.innerHTML = _content;
      }
    }

    m_dragBox.startDrag();
    
    // set the dragbox target
    var ApplicationBox = document.getElementById("KGApplicationControlID1");
    m_dragBox.setTarget(ApplicationBox);
    
    e = e || window.event;
    var x, y;
    
    // Get cursor position with respect to the page.
    if (window.scrollX)
    {
      x = e.clientX + window.scrollX;
      y = e.clientY + window.scrollY;
    }
    else
    {
      x = e.clientX + document.documentElement.scrollLeft
        + document.body.scrollLeft;
      y = e.clientY + document.documentElement.scrollTop
        + document.body.scrollTop;
    }
    
    // show thee drag box where the mouse was clicked
    m_dragBox.setPosition(x, y);
    dragStart(e, m_dragBox.getId());
  }
}

function KGDragCancel()
{
  m_dragBox.stopDrag();
}

function KGDragStop(e)
{
  //debugger;
  KGDragCancel();
  
    // empty drag box
    var box = m_dragBox.getBox();
    box.innerHTML = '';
  
  e = e || window.event;
  var x, y;
  
  // Get cursor position with respect to the page.
  if (window.scrollX)
  {
    x = e.clientX + window.scrollX;
    y = e.clientY + window.scrollY;
  }
  else
  {
    x = e.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = e.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  
  if (m_dragBox.targetHit(x, y))
  {
    // dragbox dropped on the app window.  Callback the app control
    var contextKGID = m_dragBox.KGID;
    var contextKndID = m_dragBox.KndID;
    
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    //if (currentPage.indexOf('home') > -1 || currentPage.length == 0)
    //{
      //ApplicationContextChanged('', '', contextKGID);
    //}
    //else
    //{
     var keys = 'ApplicationContextKGID';
	   var values = contextKGID;

      //SetSessionProperty('ApplicationContextKGID', contextKGID);
      if(contextKndID != null)
      {
        //SetSessionProperty('ApplicationContextKID', contextKndID);
        keys += '|ApplicationContextKID';
        values += '|' + contextKndID;
      }
      keys += '|ApplicationDragDropTriggerred|SelectedPersonalKGID|MapViewDisplayMode|KGTabbedWindowsControl1_SelectedTab|IndexedDocListMode|KGMapViewCollapsed|KGExpandMap|TriggerMapViewCallbackOnload';
      values += '|true|' + m_applicationKGID + '|KGMapView|Indexed Documents|IndexedDocuments|false|true|true';
      SetSessionProperty(keys, values, true);
      
      /*SetSessionProperty('ApplicationDragDropTriggerred', 'true');
      SetSessionProperty('SelectedPersonalKGID', m_applicationKGID);
      SetSessionProperty('MapViewDisplayMode', "KGMapView");
      SetSessionProperty('KGTabbedWindowsControl1_SelectedTab', 'Indexed Documents');
      //SetSessionProperty('SelectedAuthorID', selectedKgAuthorId);
      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");*/

      var currentLocation = window.location.href;
      var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
      if(m_applicationKGGroupID > 0)
	      window.location = hostURL + 'Home.aspx?category=' + m_applicationKGGroupID;
	    else
	      window.location = hostURL + 'Home.aspx';
    //}
    
  }
  
}

var appBoxWidth;
var appBoxHeight;
var appBoxTop;
var appBoxLeft;
  
function MaximiseKGApplicationControl_Wrapped(_appBoxID, _maximiseBtnId)
{
//debugger;
// get the help box
  var appBox = document.getElementById(_appBoxID);
  
  // store the help box'x current width, height and positioning for a 'restore'
  appBoxWidth = appBox.style.width;
  appBoxHeight = appBox.style.height;
  appBoxTop = appBox.style.top;
  appBoxLeft = appBox.style.left;
  
  // Set the help windows new properties
  appBox.style.width = document.body.clientWidth;
  appBox.style.height = document.body.clientHeight;
  appBox.style.top = "0";
  appBox.style.left = "0";
  
  // change image and onclick handler
  document.getElementById(_maximiseBtnId).className = "RestoreButtonImage";
  document.getElementById(_maximiseBtnId).onclick = function(){RestoreKGApplicationControl(_appBoxID, _maximiseBtnId)}; 
}

function RestoreKGApplicationControl(_appBoxID, _restoreBtnId)
{
//debugger;
  var appBox = document.getElementById(_appBoxID);
  
  // reset the old size and positioning
  appBox.style.top = appBoxTop;
  appBox.style.left = appBoxLeft;
  appBox.style.width = appBoxWidth;
  appBox.style.height = appBoxHeight;
  
  // change image and onclick handler
  document.getElementById(_restoreBtnId).className = "MaximiseButtonImage";
  document.getElementById(_restoreBtnId).onclick = function(){MaximiseKGApplicationControl()}; 
}
