﻿
dojo.declare("LegendNode", null, {

    node: null,
    srcNode: null,
    url: null,
    layernames: null,
    mapLayer: null,
    exlude: true,

    //constructor for layer with custom required option: layers, extent
    constructor: function(params, srcNode) {
        this.srcNode = srcNode;
        this.url = params.soapUrl;
        this.layernames = params.layernames;
        this.exlude = params.exclude;
        this.mapLayer = params.mapLayer;
    },

    startup: function() {

        this.node = document.createElement("DIV");
        this.srcNode.appendChild(this.node);
        var s = [];
        s.push("<div style=\"font-size:1.2em; color:gray;\">");
        s.push("<p><img src=\"Images/callbackActivityIndicator.gif\" alt=\"searching\" /></p><p>Generating Legend</p><p>Please be patient</p>");
        s.push("</div>");
        this.setContent(s.join(""));

        esri.request({
            url: "http://orthogonal.esri.com/restlegends/",
            content: { f: "json", soapUrl: this.url },
            callbackParamName: "callback",
            load: dojo.hitch(this, "onComplete"),
            error: dojo.hitch(this, "onError")
        });



    },

    setContent: function(content) {
        this.node.innerHTML = content;
    },

    onError: function(error) {
        this.node.innerHTML = "Error in processing..." + error.message;
    },

    onComplete: function(response) {

        var html = [];
        try {

            var excludeList = this.layernames;
            var visible = this.mapLayer.visibleLayers;
            
            dojo.forEach(response.layers, function(layer) {

                var indx = dojo.indexOf(visible, layer.layerId)
                console.debug(indx);
                if (dojo.indexOf(visible, layer.layerId) > -1) {
                    console.debug("is Visible - " + layer.layerName);
                    if (dojo.indexOf(excludeList, layer.layerName) == -1) {
                        html.push("<div>" + layer.layerName + "</div>");

                        dojo.forEach(layer.legend, function(legend) {
                            html.push("<div><img src=\"" + legend.url + "\" />" + legend.label + "</div>");
                        });
                        html.push("");
                    }
                }
            });

            this.node.innerHTML = html.join("");

            //legendIsInitialized = true;
        } catch (Error) {
            this.node.innerHTML = "<p>An Error occurred while generating the legend...</p><br/>" + Error.message;
        }
    }

});