// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.6/standard_upgrade_02/wwwroot/js/standard/theme.js $ 
// $Date: 15-07-11 15:21 $
// $Revision: 24 $ 
// $Author: Kpo $
// =============================================================== 

Theme = SpatialMap.Class({
    
    name: null,
    path: null,
    displayname:'',
    id: null,
    parentObject: null,

    visible: false,
    sessionid: null,
    maxscale: null,
    minscale: null,
    maxextent: null,
    singletile: false,
    format: 'IMAGE/PNG',
    
    clientlayers: [],
    renderingorder: 0,
    
    legend: null,
    legendElement: null,

    fLayers: [],
    nLayers: [],
    mapLayerID: [],
    
    htmlelement: null,
    buttontype: 'checkbutton',
    inputelement: null,
    
    status: 'ok',
    
    initialize: function (options) {
        // Add properties from options to this.
        SpatialMap.Util.applyDefaults (this,options);

        this.renderingorder = parseInt (this.renderingorder,10);
        this.format = (this.format == '' ? 'image/png' : this.format);
        this.visible = (this.visible == 'false' || !this.visible ? false : true);
        this.singletile = (this.singletile == 'false' || !this.singletile ? false : true);
        this.maxscale = (isNaN (parseFloat (this.maxscale)) ? null : parseFloat (this.maxscale));
        this.minscale = (isNaN (parseFloat (this.minscale)) ? null : parseFloat (this.minscale));

        // THEMESELECTOR - Change the onclick event
        if ($('chk'+this.name)) {
	        this.inputelement = $('chk'+this.name);
	        this.inputelement.onclick = SpatialMap.Function.bind(this.buttonClicked, this);
        }
    },

    getMapConfig: function () {
        if (this.haslayers == 'false') {
            return [];
        }

        var defaultLayer = {
            id: this.name + '_default',
            layername: this.name,
            maxScale: this.maxscale,
            minScale: this.minscale,
            maxextent: this.maxextent,
            singletile: this.singletile,
            basemap: false,
            format: this.format,
            visible: this.visible,
            loadHandler: SpatialMap.Function.bind(this.themeLoadHandler, this)
        };
        
        var cl = [];
        for (var i=0;i<this.clientlayers.length;i++) {
            var host = [];
            var type = null;
            var format = null;
            var layername = this.name;
            if (this.clientlayers[i].datasources) {
                for (var j=0;j<this.clientlayers[i].datasources.length;j++) {
                    var nexttype = null;
                    if (this.clientlayers[i].datasources[j].subtype) {
                        nexttype = this.clientlayers[i].datasources[j].subtype.toUpperCase();
                    } 
                    if (this.clientlayers[i].datasources[j].format) {
                        format = this.clientlayers[i].datasources[j].format;
                    } 
                    if ((type == null || type == nexttype)) {
                        type = nexttype;
                        layername = this.clientlayers[i].datasources[j].layers;
                        if (!layername && (!this.clientlayers[i].datasources[j].parameters || !this.clientlayers[i].datasources[j].parameters.sld)) {
                            layername = this.name; 
                        }
                        var url = this.clientlayers[i].datasources[j].url;
                        var prefix = (url.indexOf('?')+1 ? '&' : '?');
                        if (this.clientlayers[i].datasources[j].parameters) {
                            for (var name in this.clientlayers[i].datasources[j].parameters) {
                                url += prefix+name+'='+this.clientlayers[i].datasources[j].parameters[name];
                                prefix = '&';
                            }
                        }
                        host.push (url);
                    }
                }
            }

            this.clientlayers[i].parameters = this.clientlayers[i].parameters || {};
            if (this.clientlayers[i].parameters.singletile == 'true') {
                this.clientlayers[i].parameters.singletile = true;
            } else if (this.clientlayers[i].parameters.singletile == 'false') {
                this.clientlayers[i].parameters.singletile = false;
            } else {
                this.clientlayers[i].parameters.singletile = this.singletile;
            }
            //Add sessionid to clientlayer if no host name is added
            if (host.length == 0) {
            	this.clientlayers[i].parameters.sessionid = this.sessionid;
            }
            this.clientlayers[i].parameters.host = (host.length ? host : null);
            this.clientlayers[i].parameters.id = this.name + '_base_'+i;
            this.clientlayers[i].parameters.contenttype = type || 'WMS';
            if (!this.clientlayers[i].parameters.hasOwnProperty ('format')) {
            	this.clientlayers[i].parameters.format = format || this.format;
            }

            var a = this.getClientlayer (layername,this.clientlayers[i].parameters);
            cl.push (a);
        }

        var a = []; //cached layers
        var b = []; //wms layers

        for (var i=0;i<cl.length;i++) {
            if (!cl[i].maxScale || !cl[i].minScale || cl[i].maxScale > cl[i].minScale) {
                if (cl[i].contenttype == 'WMS') {
                    b.push (cl[i]);
                } else {
                    a.push (cl[i]);
                }
            }
        }
        
        var min = max = null;
        for (var i=0;i<a.length;i++) {
            if (a[i].maxScale == null) {
                max = null;
                break;
            } else {
                if (max == null || max < a[i].maxScale) {
                    max = a[i].maxScale;
                }
            }
        }
        for (var i=0;i<a.length;i++) {
            if (a[i].minScale == null) {
                min = null;
                break;
            } else {
                if (min == null || min > a[i].minScale) {
                    min = a[i].minScale;
                }
            }
        }
        
        if (a.length) {
            if (min != null) {
                for (var i=0;i<b.length;i++) {
                    if (b[i].minScale == null || min > b[i].minScale) {
                        var clone = this.cloneLayer (b[i],b[i].id+'_min');
                        clone.maxScale = min;
                        if (clone.maxScale == null || clone.minScale == null || clone.maxScale > clone.minScale) {
                            a.push (clone);
                        }
                    }
                }
            }
            
            if (max != null) {
                for (var i=0;i<b.length;i++) {
                    if (b[i].maxScale == null || max < b[i].maxScale) {
                        var clone = this.cloneLayer (b[i],b[i].id+'_max');
                        clone.minScale = max;
                        if (clone.maxScale == null || clone.minScale == null || clone.maxScale > clone.minScale) {
                            a.push (clone);
                        }
                    }
                }
            }
        } else {
            for (var i=0;i<b.length;i++) {
                var clone = this.cloneLayer (b[i],b[i].id+'_cached');
                a.push (clone);
            }
        }
            
        /**
         *  Add default layer if all scales not available
         *  in a normal layer
         */
        var cachedMin = null;
        var cachedMax = null;
        for (var i=0;i<a.length;i++) {
            if (!a[i].minScale) {
                cachedMin = null
                break;
            } else {
                if (cachedMin == null || cachedMin > a[i].minScale) {
                    cachedMin = a[i].minScale;
                }
            }
        }
        if (cachedMin != null) {
            if (!this.minscale || cachedMin > (this.minscale-0)) {
                var clone = this.cloneLayer (defaultLayer,defaultLayer.id+'_min');
                clone.maxScale = cachedMin;
                if (clone.maxScale == null || clone.minScale == null || clone.maxScale > clone.minScale) {
                    a.push (clone);
                }
            }
        }

        for (var i=0;i<a.length;i++) {
            if (!a[i].maxScale) {
                cachedMax = null
                break;
            } else {
                if (cachedMax == null || cachedMax < a[i].maxScale) {
                    cachedMax = a[i].maxScale;
                }
            }
        }
        if (cachedMax != null) {
            if (!this.maxscale || cachedMax < (this.maxscale-0)) {
                var clone = this.cloneLayer (defaultLayer,defaultLayer.id+'_max');
                clone.minScale = cachedMax;
                if (clone.maxScale == null || clone.minScale == null || clone.maxScale > clone.minScale) {
                    a.push (clone);
                }
            }
        }
        
        // Add cached layers
        this.nLayers = [];
        for (var i=0;i<a.length;i++) {
            this.nLayers.push (a[i].id);
        }
        
        if (b.length) {
            /**
             *  Add default layer if all scales not available
             *  in a fractional layer
             */
            var wmsMin = wmsMax = null;
            for (var i=0;i<b.length;i++) {
                if (!b[i].minScale) {
                    wmsMin = null
                    break;
                } else {
                    if (wmsMin == null || wmsMin > b[i].minScale) {
                        wmsMin = b[i].minScale;
                    }
                }
            }
            if (wmsMin != null) {
                var clone = this.cloneLayer (defaultLayer,defaultLayer.id+'_frac_min');
                clone.maxScale = wmsMin;
                if (clone.maxScale == null || clone.minScale == null || clone.maxScale > clone.minScale) {
                    b.push (clone);
                }
            }
    
            for (var i=0;i<b.length;i++) {
                if (!b[i].maxScale) {
                    wmsMax = null
                    break;
                } else {
                    if (wmsMax == null || wmsMax > b[i].maxScale) {
                        wmsMax = b[i].maxScale;
                    }
                }
            }
            if (wmsMax != null) {
                var clone = this.cloneLayer (defaultLayer,defaultLayer.id+'_frac_max');
                clone.minScale = wmsMax;
                if (clone.maxScale == null || clone.minScale == null || clone.maxScale > clone.minScale) {
                    b.push (clone);
                }
            }
        }

        // Add non cached layers
        this.fLayers = [];
        for (var i=0;i<b.length;i++) {
            if (a.length) {
                b[i].visible = false; //hide if a normal layer is available
            }
            this.fLayers.push (b[i].id);
        }
        
        var c = [];
        if (!a.length || !b.length) {
            c.push (defaultLayer);
        }
        if (!a.length) {
            this.nLayers.push (defaultLayer.id);
        }
        if (!b.length) {
            this.fLayers.push (defaultLayer.id);
        }
        
        
        var ra = a.concat (b,c);
        this.mapLayerID = [];
        for (var i=0;i<ra.length;i++) {
            this.mapLayerID.push ({id:ra[i].id,renderingorder:this.renderingorder});
        }
        
        return ra;
    },
    
    cloneLayer: function (layer,newid) {
        var returnLayer = {};
        for (var name in layer) {
            if (name == 'id') {
                returnLayer.id = newid;
            } else {
                returnLayer[name] = layer[name];
            }
        }
        return returnLayer;
    },
    
    getClientlayer: function (layername,parameters) {
        var layer = {
            host: parameters.host || cbKort.host,
            id: parameters.id,
            format: parameters.format,
            contenttype: parameters.contenttype,
			sessionid: (parameters.sessionid ? parameters.sessionid : null),
            layername: layername,
            maxScale: (isNaN (parseFloat (parameters.maxscale)) ? this.maxscale : parseFloat (parameters.maxscale)),
            minScale: (isNaN (parseFloat (parameters.minscale)) ? this.minscale : parseFloat (parameters.minscale)),
            maxextent: parameters.maxextent || this.maxextent,
            singleTile: parameters.singletile,
            buffer: (isNaN (parseInt (parameters.tilebuffer)) ? 0 : parseInt (parameters.tilebuffer)),
            basemap: (parameters.format && parameters.format.toUpperCase () == 'IMAGE/JPEG'),
            visible: this.visible,
            loadHandler: SpatialMap.Function.bind(this.themeLoadHandler, this)
        };
        if (parameters.contenttype.toUpperCase () == 'WMTS') {
            layer.type = 'wmts';
            layer.matrixSet = "View1";
            layer.tileOrigin = {
                x: 120000,
                y: 6500000
            }
            var matrixIds = [
                {identifier: "L00", resolution: 1638.4},
                {identifier: "L01", resolution: 819.2},
                {identifier: "L02", resolution: 409.6},
                {identifier: "L03", resolution: 204.8},
                {identifier: "L04", resolution: 102.4},
                {identifier: "L05", resolution: 51.2},
                {identifier: "L06", resolution: 25.6},
                {identifier: "L07", resolution: 12.8},
                {identifier: "L08", resolution: 6.4},
                {identifier: "L09", resolution: 3.2},
                {identifier: "L10", resolution: 1.6},
                {identifier: "L11", resolution: 0.8}
            ];
            layer.matrixIds = [];
            for (var i=0;i<cbKort.resolutions.length;i++) {
                for (var j=0;j<matrixIds.length;j++) {
                    if (cbKort.resolutions[i] == matrixIds[j].resolution) {
                        layer.matrixIds.push ({identifier: matrixIds[j].identifier, scaleDenominator: matrixIds[j].resolution/0.00028});
                        break;
                    }
                }
            }
        }
        return layer;
    },
    
    themeLoadHandler: function (event) {
    	event.toString = function () {return this.event;};
        cbKort.log ('Theme.themeLoadHandler () - ',event,this);
        var e = $('theme_'+this.name+'_checkboxtd');
        switch(event.event) {
	        case 'loadstart':
	        	this.status = 'ok';
	            e.className = 'themecheckboxtd_loading';
	            break;
	        case 'loadwarning':
	        	this.status = 'warning';
	        	break;
	        case 'loadfail':
	        	this.status = 'warning';
	        case 'loadend':
	        	if (this.status == 'warning') {
	        		e.className = 'themecheckboxtd_warning';
	        	} else {
	        		e.className = 'themecheckboxtd';
	        	}
	    }
        cbKort.events.fireEvent ('THEME_LOAD',event,this);
    },
    
    //THEMESELECTOR - click event
    buttonClicked: function () {
        this.setVisibility (this.inputelement.checked);
        themeChanged(this.path.split('.').pop(),this.name);
    },
    
    //NEW THEMESELECTOR
    draw: function (element) {
        if (element && typeof element != 'object') {
            element = $(element);
        }
        this.htmlelement = element;
        this.htmlelement.innerHTML = this.displayname;
        this.htmlelement.onclick = SpatialMap.Function.bind(this.setVisibility, this);
        this.setElementStyle ();
    },
    
    //NEW THEMESELECTOR
    setElementStyle: function () {
        if (this.htmlelement) {
            if (this.visible) {
                // set element as selected
                this.htmlelement.style.color = '#000000';
            } else {
                // set element as unselected
                this.htmlelement.style.color = '#999999';
            }
        }
    },

    setLegend: function (element) {
        var counter = 0;
        if (cbKort.legendVisible == true) {
            if (element && typeof element != 'object') {
                element = $(element);
            }
            this.legendElement = element;
            if (this.visible && this.haslayers != 'false') {
                if (this.legend === null) {
                    this.legend = [];
                    
                    var newelements = '<table><tbody><tr><td><div refname="' + this.name + '" class="infoboxcontent_foldimage_selected" id="legendthemetitlefolder_'+this.name+'"></div>' + 
                                      '<td><div refname="' + this.name + '" class="legendthemetitle" id="legendthemetitle_'+this.name+'">'+this.displayname+'</div></td></tr>' +
                                      '<tr><td></td><td><div class="legendthemecontent" id="legendthemecontent_'+this.name+'"></td></tr></tbody></table>';
                    this.legendElement.innerHTML = newelements;
    
                    jq('#legendthemetitle_' + this.name + ', #legendthemetitlefolder_' + this.name).click(
        		            function () {
        		                var content = jq('#legendthemecontent_' + jq(this).attr('refname')); 
        		                var folder  = jq('#legendthemetitlefolder_'+jq(this).attr('refname'))
        	                    try {
    	    		                if (content.css('display') == 'none' ) {
    	    	                        jq(folder).removeClass('infoboxcontent_foldimage_unselected').addClass('infoboxcontent_foldimage_selected');
    	    	                        content.slideDown('fast', legend_setSize);
    	    	                    } else {
    	    	                        jq(folder).removeClass('infoboxcontent_foldimage_selected').addClass('infoboxcontent_foldimage_unselected');
    	    	                        content.slideUp('fast', legend_setSize);
    	    	                    }
        		                } catch(e) { /* catch tool not installed exception from call to legend_setSize */ }
        		            }
        		        );
                    
                    //CALL server to get legend config and save it as an object list
                    var params = {
                        page: 'legend-data',
                        layers: this.name
                    }
                    var request = new CBhttp ();
                    var pcol = request.executeUrl(cbKort.getUrl (params));
                    if (pcol!=null) {
                        var rowlist = pcol.get(0).get(0);
                        if (rowlist!=null) {
                            var a = rowlist.size ();
                            for (var i=0;i<rowlist.size ();i++) {
                                var row = rowlist.row(i);
                                this.legend.push ({
                                    displayname: row.column('displayname').getValue(),
                                    minscale: row.column('minscale').getValue()-0,
                                    maxscale: row.column('maxscale').getValue()-0,
                                    url: row.column('url').getValue()+'&sessionid='+cbKort.sessionId
                                });
                            }
                        }
                    }
                }
                var newelements = '';
                var hide = true;
                for (var i=0;i<this.legend.length;i++) {
                    var cs = cbKort.getCurrentScale ();
                    if (this.legend [i].minscale == -1) {
                        this.legend [i].minscale = 0;
                    } 
                    if (this.legend [i].maxscale == -1) {
                        this.legend [i].maxscale = 999999999999;
                    } 
                    
                    if (this.legend [i].minscale <= cbKort.getCurrentScale () && cbKort.getCurrentScale () <= this.legend [i].maxscale) {
                        newelements += '<div class="legendthemeelement"><img class="legendthemeelement_img" src="'+this.legend[i].url+'"/><span class="legendthemeelement_text">'+this.legend[i].displayname+'</span></div>';
                        hide = false;
                        counter++;
                    }
                }
                if (hide) {
                    hideBlock (this.legendElement);
                } else {
                    $('legendthemecontent_'+this.name).innerHTML = newelements;
                    showBlock (this.legendElement);
                }
            } else {
                hideBlock (this.legendElement);
            }
        }
        return counter;
    },
    
    showLegend: function () {
        if (this.legendElement != null) {
            var counter = this.setLegend ('legendelement_' + this.name);
            if (counter) {
                showBlock (this.parentObject.legendElement);
            } else {
                hideBlock (this.legendElement);
            }
        }
    },
    
    setVisibility: function (visible) {
        var old = this.visible;
        this.visible = typeof visible == 'boolean' ? visible : !this.visible;
        if (this.visible != old) {
            this.showLegend ();

            //THEMESELECTOR - change
            this.inputelement.checked = visible;
            this.setElementStyle ();
            this.setMap ();
            
            cbKort.log ('THEME_CHANGED - ',SpatialMap.Util.extend ({},this));
            cbKort.events.fireEvent ('THEME_CHANGED',this);
            
            if (this.visible && this.buttontype == 'radiobutton') {
                this.parentObject.themeChanged (this);
            }
        }
    },
    
    setMap: function () {
        if (cbKort && cbKort.mapObj) {
            if (this.haslayers != 'false') {
                if (this.visible) {
                    if (this.mapLayerID.length == 0) {
                        var l = this.getMapConfig ();
                        for (var i=0;i<l.length;i++) {
                            cbKort.mapObj.addLayer (l[i]);
                        }
                    }
                    cbKort.setLayerOrder ();
                    if (cbKort.fractional) {
                        for (var i=0;i<this.nLayers.length;i++) {
                            cbKort.mapObj.hideLayer (this.nLayers[i]);
                        }
                        for (var i=0;i<this.fLayers.length;i++) {
                            cbKort.mapObj.showLayer (this.fLayers[i]);
                        }
                    } else {
                        for (var i=0;i<this.fLayers.length;i++) {
                            cbKort.mapObj.hideLayer (this.fLayers[i]);
                        }
                        for (var i=0;i<this.nLayers.length;i++) {
                            cbKort.mapObj.showLayer (this.nLayers[i]);
                        }
                    }
                } else {
                    for (var i=0;i<this.fLayers.length;i++) {
                        cbKort.mapObj.hideLayer (this.fLayers[i]);
                    }
                    for (var i=0;i<this.nLayers.length;i++) {
                        cbKort.mapObj.hideLayer (this.nLayers[i]);
                    }
                }
            }
            cbKort.setCopyRightText ();
        }
    },
    
    getCopyRightText: function () {
        if (this.visible && this.copyright) {
            for (var i=0;i<this.copyright.length;i++) {
                if (this.copyright[i].name == 'copyright-text') {
                    return [{name:this.name,text:this.copyright[i].value}];
                }
            }
        }
        return [];
    },
    
    getMapLayersID: function () {
        if (this.visible && this.mapLayerID.length) {
            return this.mapLayerID;
        }
        return [];
    },
    
    redraw: function () {
        for (var i=0;i<this.fLayers.length;i++) {
            cbKort.mapObj.redrawLayer (this.fLayers[i]);
        }
        for (var i=0;i<this.nLayers.length;i++) {
            cbKort.mapObj.redrawLayer (this.nLayers[i]);
        }
    },
    
    //For initalization
    setParentObject: function (obj) {
        this.parentObject = obj;
    },
    
    copyArray: function (array) {
        var returnArray = [];
        for (var i=0;i<array.length;i++) {
            returnArray.push(array[i]);
        }
        return returnArray;
    },
    
    toString: function () {
        return this.name;
    },

    CLASS_NAME: 'Theme'
});

