﻿// JScript File

function $Init_framework()
{
    document.write("<script language='jscript' src='../JSLocalizedConsts.aspx'></script>");
    
    document.write("<script language='jscript' src='../SGAPI/v1.0/SGCommon.js'></script>");
    document.write("<script language='vbscript' src='../SGAPI/v1.0/SGCommon.vbs'></script>");

    document.write("<script language='jscript' src='../SGAPI/v2.0/sgapi.js'></script>");
    
} $Init_framework();



function getParamValue(findParam, defaultValue)
{
    var arr = document.location.href.split("?");
    if (arr.length <= 1) return defaultValue;
    
    arr = arr[1].split("&");
    
    for (var i=0; i<arr.length; i++)
    {
        if (arr[i].indexOf(findParam) == 0 && arr[i].indexOf("=") == findParam.length)
        {
            arr = arr[i].split("=");
            return arr[1];
        }
    }

    return defaultValue;
}

function abspath()
{
    var abspath = "";
    abspath = unescape(window.location.href);
    
    // Remove query String 
    var index=abspath.indexOf("?");
    if (index > 0) abspath = abspath.substr (0,index-1);    
        
    index=abspath.lastIndexOf("/");
    var index2 = abspath.lastIndexOf("\\");
    
    index = (index > index2) ? index : index2;
    if (index <= 0) return abspath;

    abspath = abspath.substring(0,index);

    if(abspath.substring(0,1) == "/") abspath = abspath.slice(1);    

    var re = /file:\/\/\//gi;
    if (abspath.match(re) != null) abspath = abspath.replace(re,""); // if this is indeed a local file, we strip the "file://" prefix from it.    

    return(abspath);
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGS class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$SGS.prototype.AddResultPageURL   = _$SGS_AddResultPageURL;
$SGS.prototype.LinkResultsToGroup = _$SGS_LinkResultsToGroup;
$SGS.prototype.AddToFavorites     = _$SGS_AddToFavorites;
$SGS.prototype.FlyToID            = _$SGS_FlyToID;
$SGS.prototype.SetUserName        = _$SGS_SetUserName;
$SGS.prototype.UserName           = _$SGS_GetUserName;
$SGS.prototype.SetAddressField    = _$SGS_SetAddressField;
$SGS.prototype.TEMNGresizeframe   = _$SGS_TEMNGresizeframe;
$SGS.prototype._UserName          = "";
$SGS.prototype.favorites          = null;
$SGS.prototype.results            = null;
$SGS.prototype.events             = null;
$SGS.prototype.account            = null;
$SGS.prototype.tools              = null;
$SGS.prototype.layers             = null;
function $SGS()
{    
    this.favorites = new $SGSFavorites();
    this.results   = new $SGResults();
    this.events    = new $SGSEvents();
    this.account   = new $SGAccount();
    this.tools     = new $SGTools();
    this.layers    = new $SGLayers();
    
    sgFramework.globals.registerObject("___sgRMT___",ResetMenuTools);
}
// AddResultPageURL
function _$SGS_AddResultPageURL(ToolName, Description ,URL)
{
    return this.results.addPage(URL, Description);
}
function _$SGS_TEMNGresizeframe(a,b) { return; } //Backward compatibility
// LinkResultsToGroup;
function _$SGS_LinkResultsToGroup(sFrameName,GroupID)
{
    return this.results.attachNode(sFrameName ,GroupID);
}    
// AddToFavorites
function _$SGS_AddToFavorites(ObjID,Description,icon)
{
    if (typeof(ObjID) == "string" && ObjID.indexOf("0_") == 0) ObjID = new Number(ObjID.slice(2)) + 0.1; // ("0_XXXXX" -> XXXXX.1) support for calls from old pages. 
    
    this.favorites.add(ObjID, Description, icon);
    this.favorites.show();
}
// OpenFavorites
function _$SGS_OpenFavorites(extraStr)
{    
    this.favorites.show(extraStr);
}
// FlyToID
function _$SGS_FlyToID(id, code)
{
	 IPlane.FlyToObject (id,code);
}
// setUserName
function _$SGS_SetUserName(name)
{
    this._UserName = name;
}
// getUserName
function _$SGS_GetUserName()
{
    if (this._UserName.toLowerCase().indexOf("unregistered user") == -1)
        return (this._UserName);
    else
        return ("");
}
// SetAddressField
function _$SGS_SetAddressField(address)
{
    document.all["address"].value = address;
    document.all["address"].style.color = "black";
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGSFavorites class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$SGSFavorites.prototype.add    = _$SGSFavorites_add;
$SGSFavorites.prototype.remove = _$SGSFavorites_remove;
$SGSFavorites.prototype.show   = _$SGSFavorites_show;
$SGSFavorites.prototype.hide   = _$SGSFavorites_hide;
$SGSFavorites.prototype._favoritesNode  = null;
$SGSFavorites.prototype._favoritesPopup = null;
$SGSFavorites.prototype._init  = _$SGSFavorites_init;
function $SGSFavorites()
{    
    this._favoritesPopup = new SGPopup($Resources.Popups.Favorites,"Favorites.aspx");
}
function _$SGSFavorites_init()
{
    if (this._favoritesNode != null) return;
                
    var sgRoot = globe.root.parentNode();    
    this._favoritesNode = sgRoot.selectSingleNode("Favorites");
    if (this._favoritesNode == null)
    {
        //globe.teCore.TerraExplorer.DisplayErrorMessages = false;
        this._favoritesNode = globe.creator.createLayer(SGAppData("SkylineGlobeFavorites.fly"), "Favorites");
        if (this._favoritesNode == null)
            this._favoritesNode = globe.creator.createGroup("Favorites");
            
        sgRoot.appendChild(this._favoritesNode);
	}
	
	FavoritesDeletedGroup = sgRoot.selectSingleNode("FavoritesDeleted");
	if (FavoritesDeletedGroup == null)
	{
        FavoritesDeletedGroup = globe.creator.createGroup("FavoritesDeleted");
        sgRoot.appendChild(FavoritesDeletedGroup);
	}
}
function _$SGSFavorites_add(node, infoText, iconURL)
{
    this._init();
    if (node == null) return;
    if (iconURL == null) iconURL = SGAPI.toAbspath("images/FavoritesLocationIcon.gif");
    if (infoText == null) infoText = "";
    
    if (typeof(node) == "number")   // for backward competability 
        node = new SGNode(node);
    else if (!(node instanceof SGNode)) // a fix to a strange bug. still need investigating
        node = new SGNode(node.nodeId());
    
    node.setVisibility(true);
            
    node.setData("sgFavoriteData","<Favorites><icon>" + iconURL + "</icon><Description>" + infoText + "</Description></Favorites>");    
    this._favoritesNode.appendChild(node);
    
    var sgFavoritesRefreshFunc = sgFramework.globals.getObject("sgFavoritesRefreshFunc");
    if (sgFavoritesRefreshFunc != null) sgFavoritesRefreshFunc(true);
}
function _$SGSFavorites_remove(node)
{
    this._init();
    if (node == null) return;
    
    if (typeof(node) == "string")
    {
        node = this._favoritesNode.selectSingleNode(node);
        if (node == null) return;
    }
    
    if (typeof(node) == "number")   // for backward competability 
        node = new SGNode(node);
    else if (!(node instanceof SGNode)) // a fix to a strange bug. still need investigating
        node = new SGNode(node.nodeId());
            
    this._favoritesNode.removeChild(node);
    
    var sgFavoritesRefreshFunc = sgFramework.globals.getObject("sgFavoritesRefreshFunc");
    if (sgFavoritesRefreshFunc != null) sgFavoritesRefreshFunc(false);    
}
function _$SGSFavorites_show()
{
    this._init();
    var sgFavoritesRefreshFunc = sgFramework.globals.getObject("sgFavoritesRefreshFunc");
    if (sgFavoritesRefreshFunc != null) return; // already open
    
    var rect = globe.window.getRect();
    var favoritesWidth = 240;
    this._favoritesPopup.left   = rect.width-100-favoritesWidth;
    this._favoritesPopup.top    = 1;
    this._favoritesPopup.width  = favoritesWidth;
    this._favoritesPopup.height = rect.height/3*2;
    globe.showPopup(this._favoritesPopup);    
}
function _$SGSFavorites_hide()
{
    this._init();
    globe.removePopup(this._favoritesPopup);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGResults class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var ToolTRHeight = "50%";

$SGResults.prototype.addPage             = _$SGResults_addPage;
$SGResults.prototype.removePage          = _$SGResults_removePage;
$SGResults.prototype.toggle              = _$SGResults_toggle;
$SGResults.prototype.show                = _$SGResults_show;
$SGResults.prototype.hide                = _$SGResults_hide;
$SGResults.prototype.showHideResultGroup = _$SGResults_showHideResultGroup;
$SGResults.prototype.setNext             = _$SGResults_setNext;
$SGResults.prototype.setPrev             = _$SGResults_setPrev;
$SGResults.prototype.setResult           = _$SGResults_setResult;
$SGResults.prototype.attachNode          = _$SGResults_attachNode;
$SGResults.prototype._arrResultsIds      = null;
$SGResults.prototype._resultId           = -1;
$SGResults.prototype._currentResultId    = -1;
function $SGResults()
{
    this._arrResultsIds = new Array();
}
function _$SGResults_addPage(URL, description)
{
    this.show();
    this._resultId++;
    this._arrResultsIds[this._resultId] = -1;
    
	var resultName      = "Result"+this._resultId;
	var descriptionName = "Description"+this._resultId;
	var descriptionText = (description.length > 45) ? description.substring (0,41)+"..." : description.substring(0,45);

	document.all["ResultSpan"].insertAdjacentHTML("beforeEnd","<span id='"+resultName+"' style='height:100%;background-color:\"#F7F6F3\";'></span>");
    document.all[resultName].innerHTML = "<span class='s10bg' id='imgWait" + this._resultId + "'><center><img  src='"+SGAPI.toAbspath("images/loading-anim.gif")+"' align=absmiddle> SEARCHING</span></center><iframe OnLoad='HideWaitImage(" + this._resultId + ");' style='display:inline;width:100%;height:100%;background-color:#F7F6F3' bgcolor=#F7F6F3 FRAMEBORDER= 5px id=ResultiFrame" + this._resultId + " name=ResultiFrame" + this._resultId + " src='" + URL + "'></iframe>";
	document.all["HistoryResultDiv"].innerHTML += "<div class='menuItem' id='"+descriptionName+"'>&nbsp;"+descriptionText+"</div>";
	

    this.showHideResultGroup(true);
	this.setResult(this._resultId);
	document.all["ResultShowHide"].disabled = false;
	return this._resultId;
}
function _$SGResults_removePage(resultId)
{
    if (resultId == null || resultId == -1) resultId = this._currentResultId;
    if (resultId == -1) return;
    
    var spanName        = "Result"+resultId;
    var descriptionName = "Description"+resultId;
    var nodeId          = this._arrResultsIds[resultId];
    if (nodeId != null)
    {    
        if (nodeId != -1)
        {
            var node = new SGNode(nodeId);
            var parentNode = node.parentNode();
            if (parentNode != null) parentNode.removeChild(node); // The parent node might be null if the node was deleted from somewhere else
        }
        
        delete this._arrResultsIds[resultId];        
	    document.all["ResultSpan"].removeChild(document.all[spanName]);
	    
	    document.all["HistoryResultDiv"].removeChild(document.all[descriptionName]);
	    	    
	    document.all["ResultMiniTitle"].innerText="";
	    
	    this.setPrev();        	    	     
	    
	    // If this is the last open result page, hide the result pane
	    var bHide = true;
	    for (var i=0; i<this._arrResultsIds.length; i++)
	    {
	        if (this._arrResultsIds[i] != null)
	        {
	            bHide = false;
	            break;
	        }
	    }
	    if (bHide) this.hide();
    }
}
function _$SGResults_toggle()
{
    if (document.all["resultTable"].style.display=='none')
        this.show();
    else
        this.hide();
}
function _$SGResults_show()
{
    document.all["resultTable"].style.display='inline';
    document.all["ToolTR"].height=ToolTRHeight;
    document.all["ResultTR"].height='100%';    
    document.all["resultArrow"].src="images/arrowdown.gif";
}
function _$SGResults_hide()
{
    document.all["resultTable"].style.display='none';
    document.all["ToolTR"].height='100%';
    document.all["ResultTR"].height='22px';
    document.all["resultArrow"].src="images/arrowup.gif";
}
function _$SGResults_setResult(id)
{
    if (this._currentResultId != -1)
    {
        spanName = "Result"+this._currentResultId;
        if (document.getElementById(spanName) != null) document.all[spanName].style.display="none";
    }

    this._currentResultId = id;
    
	spanName = "Result"+id;
	document.all[spanName].style.display="inline";
	
	var descriptionName = "Description"+id;
	var descriptionText = document.all[descriptionName].innerText;
	if (descriptionText.length > 28) descriptionText = descriptionText.substring (0,24)+"...";
	document.all["ResultMiniTitle"].innerText = "(" + descriptionText + " )";
	
	
	var nodeId = this._arrResultsIds[id];
	if (nodeId != -1)
	{
	    var node = new SGNode(nodeId);
	    document.all["ResultShowHide"].checked = node.getVisibility();
	}
	else
	    document.all["ResultShowHide"].checked =  true;

    var nextValid = false;
    for (var n = id + 1; n < this._arrResultsIds.length; n++)
        if (this._arrResultsIds[n] != null) { nextValid = true; break; }
    
    var prevValid = false;
    for (var p = id - 1; p >= 0; p--)
        if (this._arrResultsIds[p] != null) { prevValid = true; break; }
        
    document.all["NextResultImg"].disabled = nextValid ? false : true;
    document.all["NextResultImg"].src      = nextValid ? "images/NextResult.gif" : "images/NextResultDisabled.gif";
    
	document.all["PrevResultImg"].disabled = prevValid ? false : true;
	document.all["PrevResultImg"].src      = prevValid ? "images/PrevResult.gif" : "images/PrevResultDisabled.gif";
}
function _$SGResults_showHideResultGroup(forceHide)
{
    if (this._currentResultId == -1) return;
    
    var spanName = "Result"+this._currentResultId;
	if (document.getElementById(spanName) == null) return;
	
    var nodeId = this._arrResultsIds[this._currentResultId];
    if (nodeId != null && nodeId != -1)
    {
         var node =  new SGNode(nodeId);
         if (forceHide == false)
            node.setVisibility(window.event.srcElement.checked);
         else
            node.setVisibility(false);
    }    
}
function _$SGResults_setNext()
{
    if (this._currentResultId == -1) return;
    
    var i = this._currentResultId + 1;
    while(true)
    {
        if (i >= this._arrResultsIds.length) i = 0;
        if (document.getElementById("Result"+i) != null) { this.setResult(i); break; }
        if (i == this._currentResultId) { document.all["ResultShowHide"].disabled = true; return; } // completed  the search without finding anything
        i++;
    }
}
function _$SGResults_setPrev()
{
    if (this._currentResultId == -1) return;
    
    var i = this._currentResultId - 1;
    while(true)
    {
        if (i < 0) i = this._arrResultsIds.length - 1;
        if (document.getElementById("Result"+i) != null) { this.setResult(i); break; } 
        if (i == this._currentResultId) { document.all["ResultShowHide"].disabled = true; return; } // completed  the search without finding anything
        i--;
    }
}
function _$SGResults_attachNode(sFrameName, node)
{
    var resultId;
    if (typeof(sFrameName) == "number")
    {
        resultId = sFrameName;
    }
    else
    {
        var r, re;           
        re = /ResultiFrame/g;      
        r = sFrameName.replace(re, "");    
        resultId = new Number(r);
    }
    
    if (this._arrResultsIds[resultId] == null) return;    
    
    
    if (typeof(node) == "number")   // for backward competability 
        node = new SGNode(node); 
    else if (!(node instanceof SGNode))  // a fix to a strange bug. still need investigating
        node = new SGNode(node.nodeId());

    if (node != null) this._arrResultsIds[resultId] = node.nodeId();
}

// History context menu

function onShowHistory()
{    
    var historyDiv = document.all["HistoryResultDiv"];
    
    if (historyDiv.innerHTML == "") return;
            
    historyDiv.style.leftPos+=10;
    historyDiv.style.posLeft=event.clientX - 170;
    historyDiv.style.posTop=event.clientY+10;
    historyDiv.style.display="";
    historyDiv.setCapture();        
}

function clickHistoryMenu()
{
    var historyDiv = document.all["HistoryResultDiv"];
    
    historyDiv.releaseCapture();
    historyDiv.style.display="none";
    el=event.srcElement;
    
    if (el.id.indexOf("Description") == 0)
    {
        var resId = el.id.slice(11);
        sgFramework.results.setResult(resId);
    }    
}

function switchHistoryMenu()
{
   el=event.srcElement;
   if (el.className=="menuItem") 
      el.className="highlightItem";
   else if (el.className=="highlightItem") 
      el.className="menuItem";
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGEvents class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$SGSEvents.prototype.attachEvent = _$SGSEvents_attachEvent;
$SGSEvents.prototype.detachEvent = _$SGSEvents_detachEvent;
$SGSEvents.prototype.fire        = _$SGSEvents_fire;
function $SGSEvents()
{
}
function _$SGSEvents_attachEvent(sEvent, fpNotify)
{
    var arrFrameworkEvents = sgFramework.globals.getObject("___sgFrameworkEvents___");
    if (arrFrameworkEvents == null) arrFrameworkEvents = new Array();
    sgFramework.globals.registerObject("___sgFrameworkEvents___",arrFrameworkEvents);

    var bValidEvent = (sEvent.indexOf("onShowTool") == 0 || sEvent.indexOf("onHideTool") == 0);
    if (!bValidEvent) return false;

    arrFrameworkEvents[sEvent] = fpNotify;

    return true;
}
function _$SGSEvents_detachEvent(sEvent, fpNotify)
{
    var arrFrameworkEvents = sgFramework.globals.getObject("___sgFrameworkEvents___");
    if (arrFrameworkEvents == null) return false;
    
    var bValidEvent = (sEvent.indexOf("onShowTool") == 0 || sEvent.indexOf("onHideTool") == 0);
    if (!bValidEvent) return false;

    for (var sExistingEvent in arrFrameworkEvents)
    {
        if (sExistingEvent == sEvent)
        {
            if (arrFrameworkEvents[sExistingEvent] == fpNotify)
            {
                arrFrameworkEvents[sExistingEvent] = null;
                return true;
            }
        }
    }
        
    return false;   
}
function _$SGSEvents_fire(sEvent)
{
    try
    {
        var arrFrameworkEvents = sgFramework.globals.getObject("___sgFrameworkEvents___");
        if (arrFrameworkEvents != null)
        {        
            var func = arrFrameworkEvents[sEvent];
            if (func != null) func();
        }  
    }
    catch (e){ return false;}
    
    return true;
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGSAccount class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$SGAccount.prototype.getKey  = $SGAccount_getKey;
$SGAccount.prototype.setKey  = $SGAccount_setKey;
$SGAccount.prototype.getUserId  = $SGAccount_getUserId;
$SGAccount.prototype.setUserId  = $SGAccount_setUserId;
$SGAccount.prototype.getUserName  = $SGAccount_getUserName;
$SGAccount.prototype.setUserName  = $SGAccount_setUserName;
function $SGAccount()
{ 
  this._key="";
  this._userId="";
  this._userName="";
}
function $SGAccount_getKey()              { return this._key;       }
function $SGAccount_setKey(key)           { this._key=key;          }
function $SGAccount_getUserId()           { return this._userId;    }
function $SGAccount_setUserId(userId)     { this._userId=userId;    }
function $SGAccount_getUserName()         { return this._userName;  }
function $SGAccount_setUserName(userName) { this._userName=userName;}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGTools class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$SGTools.prototype.showTool = $SGTools_showTool;
$SGTools.prototype.showToolById = $SGTools_showToolById;
$SGTools.prototype.addTool  = $SGTools_addTool;
$SGTools.prototype.removeToolById  = $SGTools_removeToolById;
function $SGTools()
{
}
function $SGTools_showTool(toolName)
{
    for (toolId in gMenuManager.ToolsArray)
    {
        tool = gMenuManager.ToolsArray[toolId];
        if (tool != null && tool.name == toolName) { tool.show(); return true; }
    }
    return false;
}
function $SGTools_showToolById(toolId)
{       
    var tool = gMenuManager.ToolsArray[toolId];
    if (tool != null) { tool.show(); return true; }    
    return false;
}

function $SGTools_addTool(id, name, iconURL, url, helpURL)
{
    menuXML=new ActiveXObject("MSXML.DOMDocument");
    

    if (id == -1)
    {    
        id = "LoaclTool:" + (new Date()).getTime();
        var strXML = "<MenuList><Menu type='tool' id='"+id+"' name='"+name+"' icon='"+iconURL+"' url='"+url+"' help='"+helpURL+"' /></MenuList>"
        menuXML.loadXML(strXML);                
    }
    else
    {        
        if (gMenuManager.MenusArray[id] != null) return; // already exist
        menuXML.async=false;
        menuXML.load("menu.aspx?getTool="+id);
        if (typeof(id) != "string") id = new String(id);
        addUserToolsToCookie(id);
    }
    
    
    var node=menuXML.selectSingleNode("//Menu");        
    if (node == null) return; // No such id was found in the database        
    gMenuManager.AddToolToMenu(node,false);        
    gMenuManager.rebuild();                    
    
    return id;    
}

function $SGTools_removeToolById(id)
{
    if (gMenuManager.RemoveToolFromMenu(id))
        return true;

    return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  $SGLayers class
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$SGLayers.prototype.showLayer = $SGLayers_showLayer;
$SGLayers.prototype.hideLayer = $SGLayers_hideLayer;
$SGLayers.prototype.getLayerVisibility = $SGLayers_getLayerVisibility;
$SGLayers.prototype.getLayersList = $SGLayers_getLayersList;
$SGLayers.prototype._getFunc = $SGLayers_getFunc;
$SGLayers.prototype._setUnhandledLayer = $SGLayers_setUnhandledLayer;

function $SGLayers()
{
}
function $SGLayers_getFunc(funcName)
{
    try { return SGAPI.SGFramework.globals.getObject(funcName); } catch(e) { return null; }
}
function $SGLayers_setUnhandledLayer(layerId, status)
{
    try 
    { 
        var _arrUnhandledLayerStatus = SGAPI.SGFramework.globals.getObject("_arrUnhandledLayerStatus");
        if (_arrUnhandledLayerStatus == null) 
        {
            _arrUnhandledLayerStatus = new Array();            
            SGAPI.SGFramework.globals.registerObject("_arrUnhandledLayerStatus", _arrUnhandledLayerStatus);
        }
        _arrUnhandledLayerStatus[layerId] = status;        
    } 
    catch(e) 
    { 
        return false; 
    }
    return true;
}
function $SGLayers_showLayer(layerId)
{
    try 
    { 
        return this._getFunc("__SGFramework_layers_showLayer__")(layerId); 
    } 
    catch(e) 
    {
        this._setUnhandledLayer(layerId, true);
        return null; // Original layer status is unknown at this time
    }
}
function $SGLayers_hideLayer(layerId)
{
    try 
    { 
        return this._getFunc("__SGFramework_layers_hideLayer__")(layerId); 
    } 
    catch(e) 
    { 
        this._setUnhandledLayer(layerId, false);    
        return null; // Original layer status is unknown at this time
    }
}

function $SGLayers_getLayerVisibility(layerId)
{
    try { return this._getFunc("__SGFramework_layers_getLayerVisibility__")(layerId); } catch(e) { return null; /* Original layer status is unknown at this time */ }
}
function $SGLayers_getLayersList()
{
    try { return this._getFunc("__SGFramework_layers_getLayersList__")(); } catch(e) { return null; }
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Misc functions
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var verticalSpliterDrag = false;
var deltaY = 0;
var spliterInterval = "";
var eventScreenY = 0;

function updateSpliterPos()
{
    if (verticalSpliterDrag)
    {        
        var newHeight = eventScreenY - deltaY;
        var newResultsHeight = document.all["DataProviderTR"].offsetTop - newHeight;
        var resultStatusOpen = (document.all["resultTable"].style.display=='inline');
                
        if (newHeight < 100) return;    // upper limit
        
        
        if (newResultsHeight < 30 + 100) // Size of the results is under 100px
        {
            if (newResultsHeight > 30)
            {    
                document.all["ResultTR"].height = "100px";    
                document.all["ToolTR"].height = "100%";
                    
                if (!resultStatusOpen)
                {
                    document.all["resultTable"].style.display='inline';
                    document.all["resultArrow"].src="images/arrowdown.gif";
                }                                
            }
            else if (resultStatusOpen)  // Size of the results is under 30px. if they are visible, close them.
            {
                sgFramework.results.hide();
            }                        
            return;                                                 
        }
        else 
        {   
            // Size of the results is above 100px. if they are not visible, make sure they are.
            if (!resultStatusOpen)
            {
                document.all["resultTable"].style.display='inline';
                document.all["resultArrow"].src="images/arrowdown.gif";        
            }
        }
        
        
        ToolTRHeight = newHeight + "px";
        document.all["ToolTR"].height = ToolTRHeight;
        document.all["ResultTR"].height = '100%';    
        document.all["VerticalSeperator"].style.backgroundColor='#FDDE89';
    }
}

function onVerticalSpliterMouseDown()
{
    document.all["VerticalSeperator"].setCapture(); 
    verticalSpliterDrag = true;    
    deltaY = event.screenY - document.all["ResultTR"].offsetTop + 3;        
    spliterInterval = window.setInterval(updateSpliterPos, 10);
}

function onVerticalSpliterMouseUp()
{
    window.clearInterval(spliterInterval);
    verticalSpliterDrag = false;
    document.all["VerticalSeperator"].releaseCapture();
    document.all["VerticalSeperator"].style.backgroundColor='#ffffff';
}

function onVerticalSpliterMouseMove()
{
    if (verticalSpliterDrag)
        eventScreenY = event.screenY;           
}

///////////////////////////////////////////////////////////////
// Menu

function MenuManager()
{   
  //property
  this.ToolsArray = new Array();  // cToolObj class
  this.CurrentShowedTool = null;
  
  //methods
  this.Reset=_MenuManager_Reset;
  this.AddToolToMenu=_MenuManager_AddToolToMenu;
  this.LoadFromXML=_MenuManager_LoadFromXML;
  this.UnloadTools=_MenuManager_UnloadTools;
  this.AddMenu=_MenuManager_AddMenu;
  this.onMenuItem = _MenuManager_onMenuItem;
  this.closeOpenMenus = _MenuManager_closeOpenMenus;
  this.openMenus = new Array();          
  this.rebuild = _MenuManager_rebuild;
  this.RemoveToolFromMenu = _MenuManager_RemoveToolFromMenu
  this.HideCurrentTool = _MenuManager_HideCurrentTool
  
  this.menuSite = null;
  this.startupToolId = "";
  this.startPageToolId = "";
  
  //const
  this.toolsContainer = "toolsTD";    
     
}

function _MenuManager_HideCurrentTool(fromShow)
{
    if (this.CurrentShowedTool != null)
    {
        if (fromShow == undefined) fromShow = false;
        this.CurrentShowedTool.hide(fromShow);        
    }
}

function _MenuManager_Reset()
{
    this.UnloadTools();    

    this.MenusArray = new Array();  // cMenuItem class
    this.AddMenu(new cMenuItem(this,"menu","root","","root"));

    this.toolsHistory = new ToolsHistory(2); // ToolsHistory(histoty size)
            
    this.menuSite = new SGMenu(document.all["MenuTD"], "root");    
}

function _MenuManager_rebuild()
{    
    // Delete all sub menus
    for (menuItemID in this.MenusArray)
        this.MenusArray[menuItemID].reset();
        
    if (this.menuSite != null)
        this.menuSite.Rebuild();            
}
function _MenuManager_AddMenu(MenuItem, addAtEnd)
{
    //if addAtEnd is true, then add as last item in array
    if(addAtEnd == true)
        this.MenusArray[MenuItem.id] = MenuItem;    
    else // else add menu item after more menu
    {
        var oldArr = this.MenusArray;
        this.MenusArray = new Array()
        for (menuItemID in oldArr)
        {
            if(menuItemID == "More")
                this.MenusArray[MenuItem.id] = MenuItem;            
            this.MenusArray[menuItemID] = oldArr[menuItemID];
        }
        // if we didn't find the more item, just add as last item
        if(this.MenusArray[MenuItem.id] == null)
            this.MenusArray[MenuItem.id] = MenuItem;    
    }
}

function _MenuManager_UnloadTools()
{
  var toolId;
  for(toolId in this.ToolsArray)
  {
     var tool=this.ToolsArray[toolId];
     tool.unload();
  }
}
function _MenuManager_LoadFromXML(xmldoc)
{
    this.Reset();
 
    var nodelist=xmldoc.selectNodes("//Menu")
	for (i=0; i<nodelist.length; i++) 
	{
	   node = nodelist.nextNode();	   
	   this.AddToolToMenu(node);
    }
   
    this.rebuild();
    
    if (this.startupToolId != "")    
        sgFramework.tools.showToolById(this.startupToolId);
        
    this.startupToolId = "";
}
//-----------------
function _MenuManager_AddToolToMenu(node,addAtEnd)
{
    if(addAtEnd == null)
        addAtEnd = true;
    type = node.getAttribute("type");
    id=node.getAttribute("id");
    name=node.getAttribute("name");
    url=node.getAttribute("url");
    icon=node.getAttribute("icon");
    menuIcon=node.getAttribute("menuIcon");
    helpurl=node.getAttribute("help");
    preload=node.getAttribute("preload");
    parentmenuid=node.getAttribute("parentmenuid");
    startPage=node.getAttribute("startPage");
    var parentmenuid_text = (parentmenuid) ? parentmenuid : "root";

    if (type == "tool")
    {      
        if (startPage==1)
        {
            this.startupToolId = id;
            this.startPageToolId = id;
        }
    
        this.ToolsArray[id] = new cToolObj(id,name,this.toolsContainer,url,this);
        this.ToolsArray[id].icon = icon;
        this.ToolsArray[id].helpUrl = helpurl;
        this.ToolsArray[id].init();
        if (preload==1)
           this.ToolsArray[id].load();
    }   


    var mi = new cMenuItem(this,type,id,parentmenuid_text,name,menuIcon);    
    this.AddMenu(mi, addAtEnd);
}

function _MenuManager_RemoveToolFromMenu(id)
{
    var tool = this.ToolsArray[id];
    if (tool == null) return;
    
    tool.hide();
    
    delete this.ToolsArray[id];    
        
    var MenuItem = this.MenusArray[tool.id];    
    
    delete this.MenusArray[tool.id];        
    
    var arrChildrenIDs = this.MenusArray[MenuItem.parentID].arrChildrenIDs;
    if (arrChildrenIDs != null)
    {
        for (var i=0; i<arrChildrenIDs.length; i++)
        {
            if (arrChildrenIDs[i] == MenuItem.id)
            {
                arrChildrenIDs.splice(i,1);
                break;
            }
        }    
    }        
    
    MenuItem.menuObj.parentElement.removeChild(MenuItem.menuObj);
    this.rebuild();
}

function _MenuManager_onMenuItem(id)
{    
    var menu = this.MenusArray[id];
    
    if (menu == undefined || menu.type == "command")
    {
        this.closeOpenMenus();
        if (id == "snapshot")
            globe.window.getSnapShot()
        if (id == "Business" || id == "SGPro" || id == "Developers" || id == "Tools")
        {
            var popup = new SGPopup($Resources.Popups.Marketplace, "../MarketPlace/MarketPlace.aspx?popup=1&subject="+id+"&page="+id+"Main.aspx&key="+sgFramework.account.getKey(), null, "bottom", "100%", "100%");
            popup.align = "bottom";
            popup.hideContentUntilLoaded = true;            
            globe.showPopup(popup);
        }    
        if (id == "Enterprise")
        {
            window.open ("../../../corporate/products/Overview.aspx");
        }
        if (id == "DeveloperForum")
        {
            window.open ("http://forum.skylinesoft.com");
        }           
        if (id == "APIReference")
        {
            var popup = new SGPopup($Resources.Popups.Help, "../SGAPI/v2.0/reference/index.html", null, "bottom", "100%", "100%");
            popup.align = "bottom";
            globe.showPopup(popup);
        }           
        if (id == "CreateTool" || id == "OpenLocalTool")
        {
            var open = "";
            var height="320"
            if (id == "OpenLocalTool")
            {
                open = "open=1";
                height=  "120"
            }
            var popup = new SGPopup("Developer", "../MarketPlace/Developers/NewTool.aspx?"+open+"&key="+sgFramework.account.getKey(), null, null, "460", height);
            popup.hideContentUntilLoaded = true;            
            globe.showPopup(popup);
        }            
        if (id == "PublishTool" || id == "UpdateTools") 
        {
            var update = "";
            if (id == "UpdateTools")
                update = "&update=1";
            var popup = new SGPopup("Developer", "../MarketPlace/Developers/PublishTool.aspx?key="+sgFramework.account.getKey()+update, null, null, "90%", "90%");
            popup.hideContentUntilLoaded = true;
            globe.showPopup(popup);
        }
    }    
    else if (menu.type == "menu")
        menu.showSubMenu();
    else if (menu.type == "tool")
    {
        this.closeOpenMenus();          
        this.ToolsArray[id].show();
    }
}
function _MenuManager_closeOpenMenus()
{
    for (var i=0; i < this.openMenus.length; i++)
        globe.removePopup("Menu_"+this.openMenus[i]);
    
    this.openMenus = new Array();
}

///////////////////////  cMenuItem class

function cMenuItem(menuManager,type, id,parentID,name,menuIcon)
{
   this.menuManager = menuManager;
   this.type = type;
   this.id=id;
   this.parentID=parentID;
   this.name = (type=="seperator") ? "seperator" : name;
   this.menuIcon = (menuIcon == null) ? "" : menuIcon;
   this.action="javascript:gMenuManager.onMenuItem(\""+id+"\");";
   this.menuObj = null;      
   this.arrChildrenIDs = null;
   this.originalParent = parentID;  
      
   this.showSubMenu = _MenuItem_showSubMenu;
   this.reset = _MenuItem_reset;
}
function _MenuItem_reset()
{
    this.menuObj = null;
    this.arrChildrenIDs = (this.type == "menu") ? new Array() : null;
    if (this.parentID == "More") this.parentID = this.originalParent;
}
function _MenuItem_showSubMenu()
{
    sgFramework.globals.registerObject("_menuMgr_", gMenuManager);
                
    var globeRect = globe.window.getRect();                
    var menuWidth = 130;
    var menuWidthOffset = menuWidth-2;            
    var menuItem   = gMenuManager.MenusArray[this.id];
    while (menuItem.parentID.indexOf("root") != 0) { menuItem = gMenuManager.MenusArray[menuItem.parentID]; }    
    var menuBasePos = menuItem.menuObj.offsetLeft + document.all["Menu_"+menuItem.parentID].parentElement.offsetLeft - 2;
    
    // calculate position
    var menuItem   = gMenuManager.MenusArray[this.id];    
    var top = -8, left = menuBasePos;
    if (gLeftSideWidth == 0) left += 300;// YGR - Agrandissement panel gauche 250;    
    while (menuItem.parentID.indexOf("root") != 0)
    {
        if (left + 2*menuWidthOffset + globeRect.left > screen.availWidth && menuWidthOffset > 0) menuWidthOffset = -(menuWidth-2); // make sure the menu do not open outside the screen        
        left += menuWidthOffset;        
        var parentMenu = gMenuManager.MenusArray[menuItem.parentID];
        if (parentMenu.arrChildrenIDs != null)
        {
            for (var i=0; i < parentMenu.arrChildrenIDs.length; i++)
                if (parentMenu.arrChildrenIDs[i] == menuItem.id) { top += i*20; break; }
        }        
        menuItem = gMenuManager.MenusArray[menuItem.parentID];
    }                  
    
    var childCount = this.arrChildrenIDs.length;
                    
    var subMenuPopup = new SGPopup(null, null, left, top, menuWidth);              
    var args = "";
    for (var i=0; i<childCount; i++)
    {
        var sep = (i==0) ? "?" : "&";        
        menuItem = gMenuManager.MenusArray[this.arrChildrenIDs[i]];
        args += sep + menuItem.name + "=" + menuItem.id;
        if (menuItem.type == "menu") args += "&menu=1";
        //if (menuItem.menuIcon != "") args += "&icon="+menuItem.menuIcon;
    }
    
    
    subMenuPopup.src = "SubMenu.htm" + args;
    subMenuPopup.height = childCount * 20 + 5;    
    subMenuPopup._ID = "Menu_"+this.id;             
    globe.showPopup (subMenuPopup);
    
    gMenuManager.openMenus.push(this.id);
    
}
///////////////////////  Menu class
function SGMenu(site,id)
{
   this.id = id;
   this.mainMenu=site;
   this.Rebuild=_SGMenu_Rebuild;
}

 
//----------------
// _SGMenu_Rebuild
function _SGMenu_Rebuild()
{
    var spanID = "Menu_" + this.id;
    this.mainMenu.innerHTML="<span id='"+spanID+"'></span>";    
    // const. Spacing between menu items
    var MenuSpacing = 8;

    var mimimizableMenuWidth = 0;   
    var nonmimimizableMenuWidth = 0;   
    var moreNode = null;

    for (menuItemID in gMenuManager.MenusArray)
    {
        if (menuItemID.indexOf("root") == 0) continue;
        
        MenuItem = gMenuManager.MenusArray[menuItemID];
        
        if (MenuItem.menuObj) continue;  // already "built".      
        if (!gbIsDeveloper && MenuItem.id == "Developer") continue;
        
        
        var newNode=document.createElement("span");
        newNode.id=MenuItem.id;

        // add the menus to the TD        
    
        if (MenuItem.id == "More")
            moreNode = newNode;

        if (MenuItem.parentID == "root")
        {            
            if (MenuItem.type == "seperator")
            {
                newNode.innerHTML="&nbsp;&nbsp;<img src='../images/MenuSeperator.bmp' border=0 align=absmiddle>";
            }
            else
            {
                var arrowStr = (MenuItem.type == "menu") ? "&nbsp;<img src='images/menuArrow.gif' border=0 align=absmiddle >" : "";
                var iconStr  = (MenuItem.menuIcon == "") ? "" : "<img src=\""+MenuItem.menuIcon+"\"border=0 align=absmiddle />&nbsp;";
                
                var btnStyle = (MenuItem.id != gMenuManager.startPageToolId) ? "MenuButton" : "MenuButtonH";
                if (MenuItem.id == "Solutions" || MenuItem.id == "Developer" || MenuItem.id == "Business")                
                    btnStyle = "MenuButton2";                
                
                if(MenuItem.id == "More")
                    newNode.innerHTML="<a id='"+MenuItem.id+"' onclick='"+MenuItem.action+"'><img id='MenuButton_"+MenuItem.id+"' src='images/moreMenu.gif' align=absmiddle style='margin-left:6;border:0;cursor:pointer' /></a>";
                else                
                    newNode.innerHTML="<a id='"+MenuItem.id+"' onclick='"+MenuItem.action+"'><div id='MenuButton_"+MenuItem.id+"' class=\""+btnStyle+"\" >"+iconStr+MenuItem.name+arrowStr+"</div></a>";
            }
            this.mainMenu.all["Menu_"+MenuItem.parentID].appendChild(newNode);    
                         
            if(moreNode == null)
            {
                // evrything after more node, may be minimized
                mimimizableMenuWidth += newNode.offsetWidth + MenuSpacing;
            }
            else
            {
                // evrything after more node, including it should be always visible. 
                nonmimimizableMenuWidth += newNode.offsetWidth + MenuSpacing;    
            }
        }
        
        gMenuManager.MenusArray[MenuItem.parentID].arrChildrenIDs.push(MenuItem.id);             
        MenuItem.menuObj = newNode;                
    }

    // width avaliable for minimizable part of menu 
    var avaliableWidth = document.all["MenuTD"].offsetWidth - nonmimimizableMenuWidth - 10;
 

    
    // Start move items to more         
    if (mimimizableMenuWidth  > avaliableWidth && moreNode != null)
    {        
        // we can't use precalculated avaliableWidth here, since width of menuTD will be changing
        while (mimimizableMenuWidth  > (document.all["MenuTD"].offsetWidth - nonmimimizableMenuWidth - 10))
        {                     
            m = moreNode.previousSibling;
            if (m == null) break;
            mimimizableMenuWidth -= (m.offsetWidth + MenuSpacing);
            MenuItem = gMenuManager.MenusArray[m.id];
            if (MenuItem != null)
            {            
                delete gMenuManager.MenusArray[MenuItem.parentID].arrChildrenIDs[MenuItem.id];
                this.mainMenu.all["Menu_"+MenuItem.parentID].removeChild(m);
                MenuItem.parentID = "More";
                
                gMenuManager.MenusArray[MenuItem.parentID].arrChildrenIDs.unshift(MenuItem.id); // put the new menu id at the beginning of the array
            }
        }
    }
    
    // if "More" menu doesn't have any items then  hide it
    if(moreNode != null)
    {
        if(gMenuManager.MenusArray["More"].arrChildrenIDs.length > 0)
            moreNode.style.display = '';
        else    
            moreNode.style.display = 'none';
    }
}

//--------------  cToolObj Class

// cToolObj
function cToolObj(id,name,parentID,URL,manager)
{
  this.id=id;
  this.parent = document.all[parentID];
  this.isloaded=false;
  this.theframe = null;
  this.URL = URL;
  this.manager = manager;
  this.icon = "";
  this.helpUrl = "";
  this.name = name;
  
  // Methods
  this.init=  _cToolObj_init;
  this.load=  _cToolObj_load;
  this.show = _cToolObj_show;
  this.hide = _cToolObj_hide;
  this.unload=_cToolObj_unload;

  this.thediv = document.createElement("DIV");
  this.thediv.id=id;
  this.parent.appendChild(this.thediv);
  this.thediv.style.display="none";

}
// init
function _cToolObj_init ()
{
  headerStr = "<table border=0 cellspacing=0 cellpadding=0 class='s9' height=100% width=246px><tr valign=center height=22px><td class='blueborderright' align=left valign=center> ";
  headerStr = headerStr + "&nbsp;<img src='"+this.icon+"' border=0 height=13px align=absmiddle>&nbsp;<b>"+name+"</b>";  
  
  if (this.helpUrl != "" && this.helpUrl != null)  
    headerStr = headerStr + "</td><td align=right valign=center class='blueborderleft' ><a onclick='OpenHtmlPopup(\""+this.helpUrl+"\",\""+$Resources.Popups.Help+"\")' style='cursor:pointer;'><span class='s9'><img src='images/helpTool.gif' alt='"+$Resources.Glossary.Help+"' border=0 align=absmiddle onmouseleave='this.src=\"images/helptool.gif\"' onmouseenter='this.src=\"images/helptool-h.gif\"'></span></a>&nbsp;";
  else
    headerStr = headerStr + "</td><td align=right valign=center class='blueborderleft' >";    
    
  if (this.id != this.manager.startPageToolId)
    headerStr = headerStr + " <a onclick='gMenuManager.HideCurrentTool()' style='cursor:pointer;'><img src='images/closeTool.gif' border=0 align=absmiddle alt='"+$Resources.Glossary.Close+"' onmouseleave='this.src=\"images/closetool.gif\"' onmouseenter='this.src=\"images/closetool-h.gif\"' /></a>"
    
  headerStr = headerStr + "&nbsp;</td></tr><tr><td width=250px height=1px bgcolor='#ffffff'></td></tr><tr><td id='ToolHolder' colspan=2 class='blueborder'></td></tr></table>";
  this.thediv.innerHTML = headerStr;
}  


// loadtool
function _cToolObj_load()
{
  this.theframe = document.createElement("IFrame");
  this.theframe.id='loading' + this.id;
  this.thediv.all["ToolHolder"].appendChild(this.theframe);
  //YGR - Agrandissement panel gauche
  //this.theframe.style.width = "248px";
  this.theframe.style.width = "298px";
  this.theframe.style.height = "100%";
  
  this.theframe.style.display="none";
  this.theframe.style.borderstyle="none";
  
  
  this.theToolframe = document.createElement("IFrame");
  this.theToolframe.id=this.id;
  this.thediv.all["ToolHolder"].appendChild(this.theToolframe);
  //YGR - Agrandissement panel gauche
  //this.theToolframe.style.width = "248px";
  this.theToolframe.style.width = "298px";
  this.theToolframe.style.height = "100%";
  
  this.theToolframe.style.display="none";
  this.theToolframe.style.borderstyle="none";
  
  this.isloaded=true;

  this.theframe.src = "loading.html?showImage=1";
  
  var sep = (this.URL.split("?").length > 1) ? "&" : "?";
  //var extraParam = (gsRequestQueryString == "") ? "" : "&"+gsRequestQueryString;
  
  this.theToolframe.src = this.URL+sep+"sgfid="+this.id+"&referrer="+lastReferrer + "&key="+sgFramework.account.getKey();//+extraParam;      
  
  var theframe = this.theframe;
  var theToolframe = this.theToolframe;
  var theDiv = this.thediv;
  this.theToolframe.tool = this;
  this.theToolframe.onreadystatechange = function()
  {    
    // if tool farme laoding is complete, remove loading frame, copy visibility setting from loading frame to real frame.
    // set reference tor eal frame in tool object
    if (theToolframe.readyState == "complete") 
    {
        
        theDiv.all["ToolHolder"].removeChild(theframe);
        theToolframe.style.display = theframe.style.display;
        theToolframe.tool.theframe = theToolframe;
        // remove circular reference between DOM and js to prevent memory leaks
        theToolframe.tool.theToolframe = null;
        theToolframe.tool = null;
        theToolframe.onreadystatechange = null;
    }   
  }
  
}

// showtool
function _cToolObj_show()
{        
    this.manager.HideCurrentTool(true);
        
    if (this.isloaded == false)
           this.load();  
    else
        SGS.events.fire("onShowTool" + this.id);
              
    this.thediv.style.display="inline";
    this.theframe.style.display="inline";
     
    var parentID = gMenuManager.MenusArray[this.id].parentID;
    if (parentID == "root") 
         document.all["MenuButton_"+this.id].className = "MenuButtonH";  // -----------> Need to rewrite this code to access the MenuItem object and change the class from there

    this.manager.CurrentShowedTool = this;
    
    this.manager.toolsHistory.push(this.id);
}
//hidetool
function _cToolObj_hide(fromShow)
{
    if (this.manager.CurrentShowedTool != null)
    {
        this.manager.CurrentShowedTool.thediv.style.display="none";
        if (this.manager.CurrentShowedTool.theframe != null) this.manager.CurrentShowedTool.theframe.style.display="none";
        
        SGS.events.fire("onHideTool" + this.manager.CurrentShowedTool.id);        
                
        this.manager.CurrentShowedTool = null;
        var parentID = gMenuManager.MenusArray[this.id].parentID;
        if (parentID == "root") 
            document.all["MenuButton_"+this.id].className = "MenuButton";  // -----------> Need to rewrite this code to access the MenuItem object and change the class from there
            
        if (fromShow != true)
        {            
            this.manager.toolsHistory.pop(); // remove the current tool.
            var toolId = this.manager.toolsHistory.pop();
            if (toolId != null) 
            { 
                var tool = this.manager.ToolsArray[toolId];
                if (tool != null) tool.show(); // The id will be added again by the show            
            }
            else
            {
                // If we have a tool that is served as start page, we show it after the user closed all of the tools in its history.
                if (this.manager.startPageToolId != "")
                    SGS.tools.showToolById(this.manager.startPageToolId);
            }
        }
    }        
}
// unloadtool
function _cToolObj_unload()
{   
   this.hide();
   
   if (this.isloaded)
   {
     if (this.theframe)
     {
       this.theframe.src="";
       this.thediv.all["ToolHolder"].removeChild(this.theframe);
       this.theframe.onreadystatechange = null;
       this.theframe=null;       
     }
     if(this.theToolframe)
     {
       this.theToolframe.src="";
       this.thediv.all["ToolHolder"].removeChild(this.theToolframe);
       this.theToolframe.onreadystatechange = null;
       this.theToolframe=null;       
     }
     this.isloaded=false;
   }
    
}

function refreshMenu(isDeveloper)
{
    gbIsDeveloper = new Boolean(isDeveloper);
    gMenuManager.rebuild();
}

function onInternalInitFinished(BaseFlyFileName, referrer, startPage, infoTree) {

    if (referrer == "" || referrer == null) referrer = "";

    if (startPage != "") document.all["startPageFrame"].src = startPage;

    globe.attachEvent("OnLoadFinished",         onLoadFinished);
    globe.attachEvent("OnTerraExplorerMessage", onTerraExplorerMessage);
    globe.attachEvent("OnRenderQualityChanged", onRenderQualityChanged);
    globe.attachEvent("OnInputModeChanged",     onInputModeChanged);
    globe.attachEvent("OnRButtonUp",            onRButtonUp);
    globe.attachEvent("OnLButtonDown",          onLButtonDown);    
                
    // TEMP ////////////////////////////////////////////
	ITerraExplorer   = globe.teCore.ITerraExplorer;
	IPlane           = globe.teCore.IPlane;
	IInformationTree = globe.teCore.IInformationTree;
	IObjectManager   = globe.teCore.IObjectManager;
	IRender          = globe.teCore.IRender;
	ITerrain = globe.teCore.ITerrain;
	ICoordSys = globe.teCore.ICoordSys;
	ISnapShot        = globe.teCore.ISnapShot;
	IContainer       = globe.teCore.IContainer;
    IScriptEngine    = globe.teCore.IScriptEngine;
    IMenu            = globe.teCore.IMenu;
    // TEMP //////////////////////

    var key = "";
    key = readCookie("usercookkey");

    document.all["LoginFrame"].src="LoginCom.aspx?key="+key ;       // This is the login
                       
	//TerraExplorerX.Caption = "TerraExplorer";

	if (globe.teCore.ITerraExplorer.Type == "Pro" && referrer == "")
	    document.all["mainLogo"].src = "images/LogoCG2009.jpg";
					
	if (BaseFlyFileName.length >0)
    	globe.teCore.ITerraExplorer.LoadEx(SGAPI.toAbspath(BaseFlyFileName), "user","vouna",false);
    else
    	globe.teCore.ITerraExplorer.LoadEx(SGAPI.toAbspath("SkyglobeLB.fly"),"user","vouna",false);
   	
    if (BaseFlyFileName.toLowerCase() == "globe.fly")
        document.all["DataProviderSpan"].innerHTML =" <a href='http:\\\\www.globexplorer.com' target='a'><img src='images/DataProviders/globexplorer.gif' border=0 align='absmiddle'></a>"+document.all["DataProviderSpan"].innerHTML;
    else
        document.all["DataProviderSpan"].innerHTML =" <a href='http:\\\\www.ign.fr' target='a'><img src='images/DataProviders/icube.gif' border=0 align='absmiddle'></a>"+document.all["DataProviderSpan"].innerHTML;

	globe.window.showControls(sgControlNavigation);
	globe.teCore.ITerraExplorer.SetParam(350,0); // Disable keyborad accelerators
	Menu(1022); // Drag navigation mode
	
    OpenNavigationControl();
	DrawMode = 0;
	PitchMode = 0;
	
    // Register all global services for external tools.    
    try { SGS = new $SGS(); } catch(e) {alert ("Error while creating SGS structure");}

    if (sgFramework.globals.registerObject("SkylineGlobeService", SGS) == false) alert("Error trying to register global name SkylineGlobeService");
    if (sgFramework.globals.registerObject("ViewerWindow", window) == false) alert ("Error trying to register global name ViewerWindow");
    
    sgFramework.globals.registerObject("frameworkRefreshMenu",refreshMenu);
    
    ///////////////////////////////////////////////////////////////
    /////////// TEMP REMOVE AFTER FEW DAYS          ///////////////
    ///////////////////////////////////////////////////////////////
    globe.teCore.IScriptEngine.RegisterGlobalName("SkylineGlobeService", SGS);
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    
    window.setInterval(onInterval, 1000);
    window.setTimeout(OpenNavigationTimer, 1000);
    
    sgFramework.globals.registerObject("ru_a15", replaceUrl);
    
    if (infoTree != null && infoTree != "")
    {                        
        var oRow = document.all["tbLeftPan"].insertRow(2);        
        var oCell = oRow.insertCell();
        oCell.innerHTML = "<div id='divTree' style='border:1px solid #627680'></div>";
        oRow.height = 300;        
        globe._createTree("divTree");               
        
        document.all["VerticalSeperator"].onmousedown = function() { return; };        
    }
}
function replaceUrl(url) { window.location.href = url; }

function getUserCookieName()
{
    var userName = sgFramework.account.getUserName();
    if (userName == "New Flayer") userName = "";    
    var cookieName = (userName != "") ? "SGTools_"+escape(userName) : "SGTools";

    return cookieName;
}

// This function append the user tool list (e.g. "201,807,99") to the one in the user cookie list.
// If one of the number in the input is negative, this number will be removed from the user cookie.
function addUserToolsToCookie(userTools)
{
    var maxUserTools = 5;
    
    var cookieName = getUserCookieName();
    
    cookieTools = readCookie(cookieName);       

    if (userTools != "")
    {        
        var arrRemove = new Array();    
    
        if (cookieTools!="") userTools += ","+cookieTools;
        var arrJoinedTools = userTools.split(",");
        var arr = new Array();        
        for (var l=0; l<arrJoinedTools.length; l++)
        {
            if (arrJoinedTools[l].indexOf("-") == 0)
            {                
                arrRemove[arrRemove.length] = arrJoinedTools[l].slice(1); // negative number
                continue;
            }
            
            var duplicate = false;
            for (var j=0; j<arr.length; j++)
                if (arrJoinedTools[l] == arr[j]) { duplicate=true; break; }
                
            if (!duplicate)
                arr[arr.length] = arrJoinedTools[l];
        }
        var newTools = "";
        for (l=0; l<arr.length && l<maxUserTools; l++)
        {
            var bAdd = true;
            for(var k=0; k<arrRemove.length; k++)
            {
                if (arrRemove[k] == arr[l]) bAdd = false;
            }
            
            if (bAdd)
            {
                if (newTools!="") newTools += ",";
                newTools += arr[l];
            }
        }
        writeCookie(cookieName, newTools);
    }    
}

var lastReferrer, lastIsDeveloper, lastBusinessId;

function ResetMenuTools()
{
    deleteCookie(getUserCookieName());    
    
    menuXML=new ActiveXObject("MSXML.DOMDocument");    
    menuXML.async=true;
    menuXML.onreadystatechange = MenuLoadFinish;
    
    var urlMenu = "menu.aspx?userTools=&referrer="+lastReferrer+"&dev="+lastIsDeveloper+"&BusinessId="+lastBusinessId;
    menuXML.load(urlMenu);
}

function BuildMenu(userTools,referrer,isDeveloper,BusinessId)
{
    gbIsDeveloper = (isDeveloper == "" || isDeveloper == null) ? false : true;

    var cookieName = getUserCookieName();
    
    if (userTools != "")
    {        
        if (userTools=="-1")
            deleteCookie(cookieName);
        else
        {
            addUserToolsToCookie(userTools);

            var arr = userTools.split(",");            
            gMenuManager.startupToolId = arr[0];            
        }
    }
    
    userTools = readCookie(cookieName);
  

    menuXML=new ActiveXObject("MSXML.DOMDocument");
    menuXML.async=true;
    menuXML.onreadystatechange = MenuLoadFinish;

    if (userTools == ""   || userTools == null) userTools = "";
    if (referrer == ""    || referrer == null) referrer = "";  
    if (BusinessId == ""  || BusinessId == null) BusinessId = "";
    isDeveloper = (gbIsDeveloper) ? "1" : "0";

    var urlMenu = "menu.aspx?userTools="+userTools+"&referrer="+referrer+"&dev="+isDeveloper+"&BusinessId="+BusinessId;
    
    lastReferrer = referrer;
    lastIsDeveloper = isDeveloper;
    lastBusinessId = BusinessId;

    menuXML.load(urlMenu);
}    

function MenuLoadFinish()
{
    if (menuXML.readyState == 4 && menuXML.parseError.errorCode == 0) 
    {    
        gMenuManager.LoadFromXML(menuXML);
    }
}

function ToolsHistory(size)
{
    this.maxSize = size;
    this.arrHistory = new Array();
    this.push = _ToolsHistory_push;
    this.pop  = _ToolsHistory_pop;
}
function _ToolsHistory_push(toolId)
{
    while (this.arrHistory.length >= this.maxSize) this.arrHistory.shift();
        
    this.arrHistory.push(toolId); 
}
function _ToolsHistory_pop()
{
    return this.arrHistory.pop();
}

function LogedIN(sKey) {
    gMenuManager.UnloadTools();
    document.all["LoginFrame"].src = "LoginCom.aspx?key="+sKey ;
    writeCookie ("usercookkey",sKey);        
}
function fLogOff()
{
    gMenuManager.UnloadTools();
    document.all["LoginFrame"].src = "LoginCom.aspx?uid=-1" ;
    deleteCookie ("usercookkey");
    // fix for upload layers staying after log off;
    globe.removePopup ($Resources.Popups.UploadLayer);
    
    //remove marketplace on logoff
    globe.removePopup ($Resources.Popups.Marketplace);
    IContainer.removeurl (5,$Resources.Popups.MyAccount);
}
function fLogOffVisiteur()
{
    gMenuManager.UnloadTools();
    document.all["LoginFrame"].src = "LoginCom.aspx?uid=-1" ;
    deleteCookie ("usercookkey");
    // fix for upload layers staying after log off;
    globe.removePopup ($Resources.Popups.UploadLayer);
    
    //remove marketplace on logoff
    globe.removePopup ($Resources.Popups.Marketplace);
    IContainer.removeurl (5,$Resources.Popups.MyAccount);
    
}

function CloseLoginAndOpenNewAccount()
{
    IContainer.removeurl (5,$Resources.Popups.SignIn);
    
    DisplayAccountWindow (abspath()+"/../WebClientProfile.aspx?New=1");
}
function DisplayAccountWindow (sURL)
{
    // JLO
    //AccountPopup = new SGPopup($Resources.Popups.MyAccount, sURL,5,5,"100%","100%");
    AccountPopup = new SGPopup($Resources.Popups.MyAccount, sURL, 5, 5, "800", "500");
    AccountPopup.hideContentUntilLoaded = true;
    globe.showPopup(AccountPopup);

}

/********Cookie handling methods********/
function writeCookie(CookieName, Value)
{
    date = new Date();
    date.setTime(date.getTime()+(365 * 24 * 60 * 60 * 1000));
    document.cookie=CookieName+"="+Value+"; expires=" + date.toGMTString();
  
}
function deleteCookie(CookieName) 
{ 
    date = new Date();
    date.setTime(date.getTime()-(100000));
    document.cookie=CookieName+"= ;expires=" + date.toGMTString();
}
function getCookieVal (offset) 
{
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
function readCookie (name) 
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	   while (i < clen) {
	      var j = i + alen;
	      if (document.cookie.substring(i, j) == arg)
	         return getCookieVal (j);
	      i = document.cookie.indexOf(" ", i) + 1;
	      if (i == 0)
	         break;
	   }
	return "";
}
/******End Cookie handling methods******/
