﻿// ############################################################################
// Purpose:  This module handles all functions on the Table of Contents Side Panel
//
// Structures:
//      tocLayer: a layer or groups of layers and its attributes in the table of contents, including whether you can identfify it, what layers to turn off, where is the download & metadata urls.
//      idGroup:  groups of Identify layers
// Functions:
//      refreshtoc: This function get the tocLayers from the server and store that  array in memory, then it called populateToc to render the table of contents (this needs to be called only once per session)
//      populateToc: This function renders the Table of contents side panel
//      toggleTOCLayer: changes the image of the folder/categories from open to close or close to open
//      checkInitialVisibility: check the visibility of the layer
//      updateLayerVisibility: Turns on or off the layer in table of contents
//
//      setActiveLayer: Changes the identify layer
//      setActiveLayer_onChange: event triggered when user changes the identify layer in the drop down menu.  Calls setActiveLayer.
//      updateActiveLayerElement: Refreshes the TOC images with the currently identifiable layer.
//      populateActiveLayerDropDown: populates the identify layer drop down list
//
//      <---- Unused functions relating to identifing mulitple layers ---->
//      clearIDlist: Clears the current identify layers in a multiple layer list table of contents (not used in this application)
//      isPartofCurrentIdentifyList: Unused in this application
//      setIdentifyLayerGroup: changes identify layers to predefined group of layers (i.e. districts layers) - (unused in this application)
//      updateIdOptions: changes the identify mode from single layer to mulitple layer
// ##############################################################################
var tocIsInitialized;


var allLayersThatID = [];
var activeLayerNames = [];
var activeLayerElement = "activelayers";
var activeLayer = "";


// Table of Contents
var categories = [];

// ################################################
// structure a table of contents entry
//function tocLayer(text, category, mapservice, layers, canID, metadataURL, downloadURL, isService) {
//    this.text = text;
//    this.category = category;
//    this.layers = layers;
//    this.mapservice = mapservice;
//    this.canidentify = canID;
//    this.metadataurl = metadataURL;
//    this.downloadurl = downloadURL;
//    this.isService = isService;
//    this.layerIDs = [];
//    this.isValid = false;
//}

// ################################################
// Call refreshtoc from the map.js showPanel routine... only called when user click on the toc button.
function refreshtoc() {
    if (!tocIsInitialized) {

        try {
            console.debug(tocLayers);

            dojo.forEach(tocLayers, function(tocLayer, indx) {
                try {
                if ((tocLayer.category != undefined) || (tocLayer.category != null)) {
            
                    if (dojo.indexOf(categories, tocLayer.category) < 0) {
                        categories.push(tocLayer.category);
                    }
                }
                } catch (ex) {
                    console.error("Error: ", ex);
                }
            });


            populateToc();

        } catch (Error) {
        dojo.byId("toc").innerHTML = "An error occurred while creating the table of contents: <br/>" + Error.message; 


        }
        
        
    }
//////            tocStore = new dojo.data.ItemFileReadStore({ url: "Data/toc.txt" });
//////            tocLayers = [];
//////            tocStore.fetch({
//////                onItem: function(item) {

//////                    if (!tocStore.hasAttribute(item, "endOfFile")) {

//////                        var text = tocStore.getValue(item, "text");
//////                        var category = tocStore.getValue(item, "category");
//////                        var layernames = tocStore.getValue(item, "layernames");
//////                        if (layernames == "")
//////                            layernames = text;
//////                        var mapservicename = tocStore.getValue(item, "mapservice");
//////                        var canID = tocStore.getValue(item, "canidentify");
//////                        var downloadURL = tocStore.getValue(item, "downloadurl");
//////                        var metadataURL = tocStore.getValue(item, "metadataurl");

//////                        var t = new tocLayer(text, category, mapservicename.toLowerCase(), layernames, canID, metadataURL, downloadURL, false);
//////                        tocLayers.push(t);

//////                    }
//////                },

//////                onError: function(errData, request) {
//////                    console.debug("Error");
//////                    console.debug(errData);
//////                    showConfigurationError("An Error occurred when trying to generate the table of contents");
//////                },

//////                onComplete: function() {
//////                    populateToc();
//////                }
//////            });
//////        }

//////        console.debug(tocLayers);

}


function populateToc() {

    var s = [];
    
   
    //write the Header
    s.push("<table width='100%' border='0' cellspacing='3' cellpadding='0'>");
    s.push("<tr><td><b>Identify Layer:</b></td><td><select id=\"activelayers\" style=\"font-size:x-small\" onchange=\"setActiveLayer_onChange();\"></select></td></tr>");
    s.push("<tr><td colspan='2' class='Bar'><b>MAP LAYERS:</b></td></tr>");
    s.push("<tr><td colspan='2'><input id='chkSample' type='checkbox' checked disabled> Visible<img src=\"images/id_on.png\"/> Identify<img src='images/i_download.gif' border='0'> Download<img src='images/i_meta.gif' border='0'> Info</td></tr>");
    s.push("</table>");

    dojo.forEach(categories, function(searchCategory) {

        var catIndex = dojo.indexOf(categories, searchCategory);
        var togglecmd = "toggleTOCLayer(\"" + catIndex + "\");"
        var imgName = "tocimg_" + catIndex;

        s.push("<div id=\"toc_labels\" class=\"detail-section\">");
        s.push("<div class=\"captionbr\" onmousedown='" + togglecmd + "'><img  id='" + imgName + "' src='images/i_plus.gif'/>" + searchCategory + "</div>");
        s.push("<div style=\"margin: 3px 3px 3px 25px;display:none\" id=\"toclist_" + catIndex + "\"   >");
        s.push("<table cellpadding=\"0\" border=\"0\" cellspacing=\"3\"><tbody>");
        var indx = 0;
        dojo.forEach(tocLayers, function(tocLayer, indx) {
            //alert( tocLayer.category + "   " + tocLayer.text);
            if (tocLayer.category == searchCategory) {

                // check initial visibility...
                var checked = "";
                var isChecked = checkInitialVisibility(tocLayer);
                //console.debug(isChecked + "   " + tocLayer.text);
                if (isChecked) {
                    checked = "checked=\"" + checked + "\"";
                    //console.debug(tocLayer.text + " is checked");
                }

                var name = "toc" + indx;

                var cmd = "toggleLayerVisibility('" + name + "'," + indx + ");";
                if (tocLayer.isService)
                    cmd = "toggleServiceVisibility('" + name + "'," + indx + ");";


                var canSelectHTML = "<img src=\"images/blank.gif\" alt=\"#\"/>";
                // if they can select the item
                if (tocLayer.canidentify) {

                    if (tocLayer.isValid) {
                        var idImageSrc = "images/id_off.png";
                        if (isPartofCurrentIdentifyList(tocLayer)) {
                            idImageSrc = "images/id_on.png";
                        }
                        canSelectHTML = "<input class=\"idimage\" id=\"img" + name + "\" type=\"image\" src=\"" + idImageSrc + "\" onclick=\"setActiveLayer(" + indx + ");\" />";

                        activeLayerNames.push(tocLayer);
                    }
                }

                // visibility button...
                var visBtn = "<input id=\"chk" + name + "\"" + checked + " type=\"checkbox\" onclick=\"" + cmd + "\" />";
                if ((tocLayer.layerIDs.length > 0) && (tocLayer.layerIDs[0] == -1) && (!tocLayer.isService))
                    visBtn = "<img src=\"images/blank.gif\" alt=\"#\"/>";



                var downloadtext = "&nbsp;";
                var metadatatext = "&nbsp;";
                if (tocLayer.metadataurl != "") {
                    metadatatext = "<a href=\"" + tocLayer.metadataurl + "\" target=\"_blank\"><img src='images/i_meta.gif' border='0'></a>";
                }

                if (tocLayer.downloadurl != "") {
                    downloadtext = "<a href=\"" + tocLayer.downloadurl + "\" target=\"_blank\"><img src='images/i_download.gif' border='0'></a>";
                }

                if (!tocLayer.isValid)
                    canSelectHTML = "<img src=\"images/missing.gif\" alt=\"#\" title=\"this layer is missing from map\"  />";


                s.push("<tr class=\"Row\" height=\"20\"><td>" + visBtn + "</td><td>" + canSelectHTML + "</td><td>" + tocLayer.text + "</td><td>" + downloadtext + "</td><td>" + metadatatext + "</td></tr>");
                //console.debug(name);
                
                console.debug(tocLayer);
            }

        });
        s.push("</tbody></table>");
        s.push("</div></div>");

    });


    // populate the toc node
    dojo.byId("toc").innerHTML = s.join("");
    populateActiveLayerDropDown();
    updateActiveLayerElement();

    try {
        // this is a work around...
        dojo.forEach(activeLayerNames, function(l, indx) {
            if (l.text == "Parcels") {
                var e = dojo.byId(activeLayerElement);
                e.value = indx;
                //setActiveLayer(indx);

            }
        });
    } catch (Error) {
    console.debug("An error occurred while trying to set active layer to parcels");
    }

    tocIsInitialized = true;

}

function toggleTOCLayer(name) {

    var listdivname = "toclist_" + name;
    var imgName = "tocimg_" + name;

    var o = dojo.byId(listdivname);
    if (o != null) {
        if (o.style.display == "none") {
            dojo.style(listdivname, { "display": "block" });
            dojo.byId(imgName).src = "images/i_minus.gif";
        } else {
            dojo.style(listdivname, { "display": "none" });
            dojo.byId(imgName).src = "images/i_plus.gif";
        }
    }
}

function checkInitialVisibility(tocLayer) {
    var isVisible = false;   
    var gLayer = map.getLayer(tocLayer.mapservice);
    if (gLayer != null) {
        isVisible = gLayer.visible;
        if (tocLayer.isService) {
            tocLayer.isValid = true;
            return isVisible;
        }
        else {
        
            if (tocLayer.layers.length == 0)
                tocLayer.layers = [ tocLayer.text ];
                      
            if ((tocLayer.layers.length > 0)) {
                var layers = tocLayer.layers;
                dojo.forEach(layers, function(layerName) {
                    var layerID = findLayerByName(layerName, tocLayer.mapservice);
                    tocLayer.layerIDs.push(layerID);
                    if (layerID > -1) {
                        tocLayer.isValid = true;
                        var li = gLayer.layerInfos[layerID];
                        if (li != null)
                            isVisible = li.defaultVisibility;
                    } else {
                        isVisible = false;
                    }
                });
            } else {
                tocLayer.layerIDs.push(-1);
                return false;
            }
        }
    }
    return isVisible

}

function toggleServiceVisibility(chkbox, indx) {

    try {
        var obj = dojo.byId("chk" + chkbox);
        var removeIt = !obj.checked;

        var t = tocLayers[indx];
        var layer = map.getLayer(t.mapservice);

        if (removeIt) {
            // hide the map service layer.
            layer.hide();
        } else {
            // show the map service layer
            layer.show();
        }
    } catch (error) {
        console.debug("Error occured in function 'updateLayerVisibility'");
        console.debug(Error);
    }

}

function toggleLayerVisibility(chkbox, indx) {

    try {

        var obj = dojo.byId("chk" + chkbox);
        var removeIt = !obj.checked;

        var t = tocLayers[indx];
        var layer = map.getLayer(t.mapservice);

        if (layer != null) {
            var visible = layer.visibleLayers;
            if (removeIt == true) {
                dojo.forEach(t.layerIDs, function(layerID) {
                    if (dojo.indexOf(visible, layerID) >= 0)
                        visible.splice(dojo.indexOf(visible, layerID), 1);
                });
            }
            else {
                //add it
                dojo.forEach(t.layerIDs, function(layerID) {
                    var li = layer.layerInfos[layerID]
                    if (li != undefined) {
                        visible.push(li.id);
                    }

                });
            }
            

            visible.sort(function(a, b) { return a - b; });
            
            console.debug(visible);
            
            showLoading();
            layer.setVisibleLayers(visible);
            
        }
    } catch (Error) {
        console.debug("Error occured in function 'updateLayerVisibility'");
        console.debug(Error);
    }

}




// ############################################
// Identify functionality
function initIdentifyCombo() {

    dojo.forEach(tocLayers, function(tocLayer, indx) {
        if (tocLayer.canidentify) {
            if (tocLayer.isValid) 
                activeLayerNames.push(tocLayer);
        }
    });

    populateActiveLayerDropDown();
    updateActiveLayerElement();

    try {
        // this is a work around...
        dojo.forEach(activeLayerNames, function(l, indx) {
            if (l.text == "Parcels") {
                var e = dojo.byId(activeLayerElement);
                e.value = indx;
                //setActiveLayer(indx);

            }
        });
    } catch (Error) {
        console.debug("An error occurred while trying to set active layer to parcels");
    }
    
}

function setActiveLayer(indx) {

    var identifyMany = false;

    // get the TOC layer
    var t = tocLayers[indx];
    if (t.isValid) {
        // go through each node in the toc and turn the identify icon off...
        var namelist = dojo.query(".idimage");
        console.debug(namelist);
        dojo.forEach(namelist, function(img) {
            img.src = "images/id_off.png";
        });
           
        var idLayerIDs = [];
        dojo.forEach(t.layerIDs, function(layerID) {
            idLayerIDs.push(parseInt(layerID));
        });
        var idElement = dojo.byId("imgtoc" + indx);
        idElement.src = "images/id_on.png";
        activeLayer = t;
        updateActiveLayerElement();

        // get the layer ids to identify on
        layersToIdentify = idLayerIDs;
        initIdentifyFunctionality();
       
   }

}

function setActiveLayer_onChange() {

    var e = dojo.byId(activeLayerElement);
    var indx = e.value;
    var selected = activeLayerNames[indx];
    dojo.forEach(tocLayers, function(t, indx) {
        if (selected.text == t.text) {
            setActiveLayer(indx);
        }
    });
}

function updateActiveLayerElement() {
    var e = dojo.byId(activeLayerElement);
    dojo.forEach(activeLayerNames, function(n, indx) {
        if (activeLayer.text == n.text)
            e.value = indx;
    });
}

function populateActiveLayerDropDown() {
    var e = dojo.byId(activeLayerElement);
    dojo.forEach(activeLayerNames, function(n, indx) {
        var opt = document.createElement("option");
        opt.value = indx;
        opt.innerHTML = n.text;
        e.appendChild(opt);
    });
}


function clearIDList() {

    layersToIdentify = [];
    initIdentifyFunctionality();
    updateActiveLayerElement();

    // go through each node in the toc and turn the identify icon off...
    var namelist = dojo.query(".idimage");
    console.debug(namelist);
    dojo.forEach(namelist, function(img) {
        console.debug(img);
        img.src = "images/id_off.png";
    });
}

function isPartofCurrentIdentifyList(t) {
    var bFound = false;
    dojo.forEach(t.layerIDs, function(layerID) {
        if (dojo.indexOf(layersToIdentify, parseInt(layerID)) > -1)
            bFound = true;
    });


    return bFound;

}

function setIdentifyLayerGroup(indx) {

    var g = idGroups[indx];
    layersToIdentify = g.layers;
    initIdentifyFunctionality();
    updateActiveLayerElement();
}


// Tightly tied to the ID options
function updateIdOptions() {
    console.debug("on change: " + idLayerOption);
    idLayerOption = dojo.byId("idoption_select").value;
    initIdentifyFunctionality();
}


