// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.6/standard/wwwroot/WEB-INF/config/modules/standard/redline/js/redline.js $
// $Date: 27-09-11 12:09 $
// $Revision: 20 $
// $Author: Nsm $
// ===============================================================

var redlineObj = null;
function redline_getConfig(name) {
    if(!redlineObj) {  //if printObject not defined create new
        redlineObj = new Redline(name);
    }
    if(redlineObj.name != name) { //if printObject not current create new
        redlineObj.removeAll ();
        redlineObj = new RedlineObj(name);
    }

    redlineObj.showDialog();
}

function redline_removeAll() {
    if(redlineObj) {
        redlineObj.removeAll ();
    }
}

Redline = SpatialMap.Class({
    name: null,
    title: 'standard',
    drawingTypes: [],
    width: '250px',
    workflow: '',
    dialog: null,
    color: null,
    toolMode: null,
    drawMode: null,
    radius: 100,
    features: [],
    active: false,
    
    initialize: function (name) {
        this.name = name;
        this.color = new Color ('#FF0000');
        this.getConfig ();
    },
    
    setColor: function (color) {
        if (color) {
            this.color.set (color);
        }
        $('redline_'+this.name+'_selected_color').style.backgroundColor = this.color.hex;
        this.setMode ();
    },
    
    getColor: function () {
        var colorPicker_options = {
            "r_values":"4",
            "g_values":"4",
            "b_values":"4",
            "table_rows":"8",
            "color":this.color.hex,
            "silent":"false",
            "autook":"false",
            "title":cbInfo.getString('standard.misc.draw.polygon'),
            "okbuttontext":cbInfo.getString('standard.button.ok'),
            "cancelbuttontext":cbInfo.getString('redline.dialog.undo')};
       
        CreateColorPicker(cbInfo.getString('redline.dialog.colorpicker'),SpatialMap.Function.bind(this.setColor, this), null,colorPicker_options);
    },
    
    toolChange: function () {
        this.active = false;
    },
    
    showDialog: function () {
        if (this.dialog == null) {
            this.createDialog ();
        }
        if (this.toolmode == null) {
            this.toolmode = cbKort.registerToolMode(null, null, null, null, true, SpatialMap.Function.bind(this.toolChange, this));
        }
        this.dialog.showDialog ();
        this.setColor ();
    },
    
    closeDialog: function () {
        this.dialog.closeDialog ();
        this.closeHandler ();
    },
    
    createDialog: function () {
        this.dialog = new Dialog(cbInfo.getString('redline.redline.displayname'),SpatialMap.Function.bind(this.closeHandler, this));
        this.dialog.setDialogWidth(this.width);
        var html ='            <table border="0" class="divtable">';
        if(this.workflow)
        {
            html+='                <tr align="left">';
            html+='                    <td colspan="2">'+this.workflow+'</td>';
            html+='                </tr>';
            html+='                <tr align="left">';
            html+='                    <td colspan="2">' +
                  '                        <select id="redline_'+this.name+'_select" style="width:100%;">';
            for(var i=0;i<this.drawingTypes.length;i++)
                html+= '                       <option value="' + this.drawingTypes[i].name + '"'+(this.drawingTypes[i].defaultSelected ? ' selected="true"' : '')+'>'+this.drawingTypes[i].displayname+'</option>';           
            html+='                        </select>' +
                    '                   </td>';
            html+='                </tr>';
            html+='                <tr>';
            html+='                  <td>'+cbInfo.getString('redline.dialog.color')+'</td>';
            html+='                  <td align="right" valign="top">' +
                  '                    <div id="redline_'+this.name+'_selected_color" title="'+cbInfo.getString("redline.dialog.select_color")+'" style="width:100px;height:20px;border-style:none;background-color:#0000FF;"/>';
                  '                  </td>';
            html+='                </tr>';
            html+='                <tr><td colspan="2" id="redline_'+this.name+'_drawingtypebox"></td></tr>';
        }
        html    +='            </table>';
    
        this.dialog.addContentHTML(html);
        $('redline_'+this.name+'_select').onchange = SpatialMap.Function.bind(this.setMode, this);
        $('redline_'+this.name+'_selected_color').onclick = SpatialMap.Function.bind(this.getColor, this);
    },
    
    closeHandler: function () {
        this.active = false;
        cbKort.setToolMode ();
    },
    
    setMode: function () {
        if (!this.active) {
            cbKort.setToolMode (this.toolmode);
            this.active = true;
        }
        this.drawmode = $('redline_'+this.name+'_select').value;
        
        var drawingType = this.getDrawingType (this.drawmode);
        if (drawingType != null) {
            if (this.activemode != this.drawmode) {
                cbKort.log ('Redline.setMode () - drawMode: ',this.drawmode);
                $('redline_'+this.name+'_drawingtypebox').innerHTML = drawingType.html;
                for (var i=0;i<drawingType.options.length;i++) {
                    if (drawingType.options [i].urlparam == 'radius') {
                        this.radiusElement = $(drawingType.options [i].id);
                        if (this.radius) {
                            this.radiusElement.value = this.radius;
                        }
                        this.radiusElement.onkeyup = SpatialMap.Function.bind(this.setMode, this);
                        break;
                    } else if (drawingType.options [i].urlparam == 'text') {
                        this.textElement = $(drawingType.options [i].id);
                        if (!this.text) {
                            this.text = '';
                        }
                        this.textElement.value = this.text;
                        this.textElement.onkeyup = SpatialMap.Function.bind(this.setMode, this);
                        break;
                    }
                }
            }
            
        }
        this.activemode = this.drawmode;
        var style = {
            fillColor: this.color.hex,
            fillOpacity: 0.6,
            pointRadius: 1,
            strokeColor: this.color.hex,
            strokeOpacity: 0.6,
            strokeWidth: 3            
        }
      
        if(this.drawmode=='polygon') {
            cbKort.mapObj.drawPolygon (SpatialMap.Function.bind(this.featureAdded, this),{styles: style,keyboard:true});
        } else if(this.drawmode=='rectangle') {
            cbKort.mapObj.drawRegularPolygon (SpatialMap.Function.bind(this.featureAdded, this),{draw: {sides: 4, irregular: true},styles: style});
        } else if(this.drawmode=='circle') {
            style.fillColor = '#FFFFFF';
            style.fillOpacity = 0.1;
            cbKort.mapObj.drawRegularPolygon (SpatialMap.Function.bind(this.featureAdded, this),{draw: {sides: 40},styles: style});
        } else if(this.drawmode=='line') {
            cbKort.mapObj.drawLine (SpatialMap.Function.bind(this.featureAdded, this),{styles: style,keyboard:true});
        } else if(this.drawmode=='point') {
            cbKort.mapObj.drawPoint (SpatialMap.Function.bind(this.featureAdded, this),{styles: style});
        } else if(this.drawmode=='label') {
            if (this.textElement) {
                if (this.textElement.value || this.textElement.value == '') {
                    this.text = this.textElement.value;
                }
            }
            style.label = this.text;
            style.fontColor= this.color.hex;
            style.fontSize = '12px';
            style.fontFamily = 'Arial';
            style.fontWeight = 'bold';
            style.labelAlign = 'lb';
            style.labelXOffset = 3;
            style.labelYOffset = 3;
            cbKort.mapObj.drawPoint (SpatialMap.Function.bind(this.featureAdded, this),{styles: style});
        } else if(this.drawmode=='circle_input') {
            style.fillColor = '#FFFFFF';
            style.fillOpacity = 0.1;
            if (this.radiusElement) {
                if (this.radiusElement.value) {
                    this.radius = this.radiusElement.value;
                }
            }
            cbKort.mapObj.drawRegularPolygon (SpatialMap.Function.bind(this.featureAdded, this),{draw: {sides: 40, radius: this.radius},styles: style});
        } else {
            cbKort.mapObj.panZoom ();
        }
    },
    
    featureAdded: function (feature) {
        this.features.push (feature.id);
        var drawingtype = this.getDrawingType (this.drawmode);
        var val = "'" + feature.wkt + "';'"+(this.text || "-")+"';'"+this.color.rgb+"'";
        var params = {
            page: 'dynamiclayer-write',
            dynamiclayer: drawingtype.dynamiclayer,
            row1: encodeURIComponent (val),
            columnnames: 'text,color',
            shape_wkt : feature.wkt,
            dynamicdatasource : 'redline',
            text: (encodeURIComponent(this.text) || "-"),
            color: this.color.rgb
        };
        var url = cbKort.getUrl (params);
        var cbHttp  = new CBhttp();
        cbHttp.executeUrlAsync(url, false);
        var obj = {
        	wkt: feature.wkt.toString(),
        	url:url
    	};
        cbKort.log ('Redline.featureAdded () - ',obj,this);
        cbKort.events.fireEvent ('REDLINE_FEATURE_ADDED',obj,this);
    },
    
    removeAll: function () {
        cbKort.mapObj.deleteFeature (this.features);
        this.features = [];
        cbKort.log ('Redline.removeAll ()');
        var params = {
            page: 'dynamiclayer-delete',
            dynamiclayer: 'redline-line, redline-point, redline-polygon, redline-circle',
            dynamicdatasource: 'redline'
        };
        var url = cbKort.getUrl (params);
        var cbHttp  = new CBhttp();
        cbHttp.executeUrlAsync(url, false);
    },
    
    getDrawingType: function (mode) {
        for (var i=0;i<this.drawingTypes.length;i++) {
            if (this.drawingTypes [i].name == mode) {
                return this.drawingTypes [i];
            }
        }
        return null;
    },
    
    getConfig: function () {
        var params = {
            page: 'redline-config',
            redlineconfig: this.name
        };
        var url = cbKort.getUrl (params);
        var domDoc = cbhttp_getRequestDom(url);
        var root = domDoc.getElementsByTagName("redlineconfig")[0];
        var j = cbhttp_getLength(root);
        var node = cbhttp_getFirstChild(root);
        for (var iNode = 0; iNode < j; iNode++) {
            if(node.nodeName == 'title')
                this.title = cbhttp_getNodeValue(node);
            if(node.nodeName == 'workflow')
                this.workflow = cbhttp_getNodeValue(node);
            if(node.nodeName == 'width')
                this.width = cbhttp_getNodeValue(node);           
            if(node.nodeName == 'drawingtypes') {
                var drawingtypesArray = node.getElementsByTagName("drawingtype");
                //for each drawingtype node
                for (var m = 0; m < drawingtypesArray.length; m++) {               
                    var drawingNode = drawingtypesArray[m];
                    var drawingtype = {
                        name: drawingNode.getAttribute("name"),
                        options: [],
                        defaultSelected: false,
                        dynamiclayer: drawingNode.getAttribute("dynamiclayer"),
                        displayname:'RedlineDrawingType',
                        workflow: 'DrawingTypeWorkflow',
                        rltype: drawingNode.getAttribute("rltype")
                    };
                   
                    //optional fields
                    if(drawingNode.getElementsByTagName("displayname")[0])
                       drawingtype.displayname = drawingNode.getElementsByTagName("displayname")[0].firstChild.nodeValue;
    
                    if(drawingNode.getElementsByTagName("workflow")[0])
                       drawingtype.workflow = drawingNode.getElementsByTagName("workflow")[0].firstChild.nodeValue;
                       
                    if(drawingNode.getElementsByTagName("defaultsel")) {
                        //drawingtype.defaultSelected = (drawingNode.getElementsByTagName("defaultsel")[0]=="true")? true:false;
                        // vi skal finde en bedre måde at gøre dette på, evt. ændre xml strukturen så <defaultsel /> er en childNode af <drawingtypes />.
                        try {
                            drawingtype.defaultSelected = (drawingNode.getElementsByTagName("defaultsel")[0].firstChild.data =="true")? true:false;
                        } catch(exp){}
                    }
                    if(drawingNode.getElementsByTagName("options")[0]) {
                        var optionsNode= drawingNode.getElementsByTagName("options")[0];
                        var optionArray= optionsNode.getElementsByTagName("option");
                        var dtHtml = '<table>';
                        drawingtype.options = [];
                        for (var n= 0; n < optionArray.length; n++) {
                            var displaytext = optionArray[n].getElementsByTagName("displaytext")[0].firstChild.nodeValue;                   
                            var otype = optionArray[n].getAttribute("type");
                            drawingtype.options.push ({
                                id: optionArray[n].getAttribute("name") + m,
                                otype: otype,
                                displayname: displaytext,
                                urlparam: optionArray[n].getAttribute("urlparam")
                            });
                            var defaultvalue = optionArray[n].getAttribute("defaultvalue");
                            if(!defaultvalue)
                                defaultvalue = '';
    
                            dtHtml += '<tr><td width="100px">' + displaytext + '</td><td align="right">';
                            if(otype=='input') {
                                dtHtml += '<input style="width:100px;" id="' + optionArray[n].getAttribute("name") + m + '" value="'+defaultvalue+'"/>';
                            }
                            dtHtml +='</td></tr>';
                        }
                        drawingtype.html = dtHtml+'</table>';               
                    } else {
                        drawingtype.html = "";
                    }
                    this.drawingTypes[m] = drawingtype;                
                }          
            }
            node = cbhttp_getNextNode(node);
        }
    },

    CLASS_NAME: 'Redline'
});

