﻿
//This function returns the map to the default visible layers set 
//in the mxd.
//
//it's a little complicated for two reasons:
//
// 1 - if a layer is turned on in the mxd, but it's parent isn't,
//     it's marked as visible by default, so you need to check the 
//     status of it's ancestors.
//
// 2 - If you turn on a layer that represents a layer group, all
//     layers underneath it will be turned on.
function defaultVisible(myLayer)
{
    //Takes an array of layerinfos, returns an array of 
    //layer ids that default to on
    function extractDefaultVisibleIds(layerInfos)
    {
        //Helper function to check if any of the parents of the 
        //layer are invisible by default
        function isVisible(index)
        {
            var myLayerInfo = layerInfos[index];
            if(myLayerInfo.parentLayerId != -1)
            {
                return myLayerInfo.defaultVisibility && isVisible(layerInfos[index].parentLayerId);
            }
            else
            {
                return myLayerInfo.defaultVisibility;
            }
        }
        
        var visibleIds = [];
        for(var idx = 0; idx < layerInfos.length; idx++)
        {
            if(isVisible(idx) && (layerInfos[idx].subLayerIds == null))
            {
                visibleIds.push(layerInfos[idx].id);
            }
        }
        return visibleIds;
    }
    
    var visible;
    visible = extractDefaultVisibleIds(myLayer.layerInfos);
    myLayer.setVisibleLayers(visible);
}

//Make SetVisibleLayers work the way I want
function modifyLayers(dynamicLayer)
{
    dynamicLayer.setLayers = function(layerIndexArray)
    {
        this.visibleLayers = layerIndexArray;
        this.setVisibleLayers(layerIndexArray);
    }
    dynamicLayer.setLayers(eval(configuration["idxBase"]))
}

// Javascript used to switch the layers being displayed
function changeDisplay(displayname, serviceLayer)
{
    ({
        "Basemap": function(myLayer){myLayer.setLayers(eval(configuration["idxBase"]))},
        "Aerial": function(myLayer){myLayer.setLayers(eval(configuration["idxAerial"]))},
        "Economic": function(myLayer){myLayer.setLayers(eval(configuration["idxDevelopment"]))}
    })[displayname](serviceLayer);
}
