// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.5/standard/wwwroot/WEB-INF/config/modules/standard/redline/js/redline.js $
// $Date: 12-02-09 11:50 $
// $Revision: 15 $
// $Author: Nsm $
// ===============================================================

var maxGeoms;
var currentType;
var currentGeomobj = null;
var redlineDialog = null;

function redline_countgeoms()
{
    if(redlineObj==null)
    {
        return;
    }
    else 
    {
        return redlineObj.geoms.length;
    }
}

function redline_getGeomById(id)
{
    return redlineObj.geoms[id];
}

function redline_newGeom(geomobj)
{
    maxGeoms++;
    redlineObj.geoms[maxGeoms]=geomobj;
    return maxGeoms;
}

function RedlineObj(name)
{
    this.name = name;
    this.title = 'standard';
    this.geoms = new Array();
    this.drawingTypes = new Array();
    this.width = '250px';
    this.workflow = '';
    this.dialog = null;
    this.color = '#FF0000';
}

function RedlineDrawingType(dtname)
{
    this.name=dtname;
    this.inputvalues = new Array();
    this.options = new Array();
    this.defaultSelected = false;
    this.dynamiclayer ='RedlineDynamiclayer';
    this.displayname ='RedlineDrawingType';
    this.workflow = 'DrawingTypeWorkflow';
    this.height ='250px';
    this.rltype = 'RedlineType';
}

RedlineDrawingType.prototype.showHtml = function(boxname)
{
    var htmlbox = getElement(boxname);
    htmlbox.innerHTML = this.html;
}

function redline_getConfig(name)
{
    if(!redlineObj)  //if printObject not defined create new
        redlineObj = new RedlineObj(name);
    if(redlineObj.name != name)  //if printObject not current create new
        redlineObj = new RedlineObj(name);

    //read config
    var url = getServletUrl();
    url+= "?page=redline-config";
    url+= "&sessionid="+getSessionId();
    url+= "&profile="+getProfile();
    url+= "&redlineconfig="+redlineObj.name;
  
    redlineObj.getConfig(url);
    // Create and show dialog
    redlineObj.addDialog();
 
    // set drawing type
    redline_setDrawingType();
  
}

RedlineObj.prototype.getConfig = function(url)
{
    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 drawingtype = new RedlineDrawingType();
               
                var drawingNode = drawingtypesArray[m];
               
                //required fields
                drawingtype.name = drawingNode.getAttribute("name");
                drawingtype.dynamiclayer = drawingNode.getAttribute("dynamiclayer");
                drawingtype.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;
                   
                /*   
                try
                {
                    alert(drawingNode.getElementsByTagName("defaultsel")[0].firstChild.data);
                    * // og då sakal der tilføjes parentNode.getAttribute("name");
                }
                catch(exp){}
                */
                      
                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>';
                    for (var n= 0; n < optionArray.length; n++)
                    {
                        var displaytext = optionArray[n].getElementsByTagName("displaytext")[0].firstChild.nodeValue;                   
                        var otype = optionArray[n].getAttribute("type");
                        var defaultvalue = optionArray[n].getAttribute("defaultvalue");
                        if(!defaultvalue)
                            defaultvalue = '';
                        var onchageHandler = optionArray[n].getAttribute("onchange");
                        if(!onchageHandler)
                            onchageHandler = '';
                        else
                            onchageHandler = ' onkeyup="'+onchageHandler+'(this.value)"';

                        // to be replaced with a TD class name
                        dtHtml += '<tr><td width="60px">' + displaytext + '</td><td>';
                        if(otype=='input')
                        {
                            dtHtml += '<input id="' + optionArray[n].getAttribute("name") + m + '" value="'+defaultvalue+'"'+onchageHandler+'/>';
                        }
                        dtHtml +='</td></tr>';
                    }
                    drawingtype.html = dtHtml+'</table>';               
                }
                else
                {
                    drawingtype.html = "";
                   
                }
                  
                this.drawingTypes[m] = drawingtype;                
            }          
        }
        node = cbhttp_getNextNode(node);
    }
}

RedlineObj.prototype.cleanObjects = function(dialogClose)
{
    cbmapdrawer_currentDrawer.cleanObjects();
}

RedlineObj.prototype.addDialog = function()
{
    redlineDialog = new Dialog(cbInfo.getString('redline.redline.displayname'),redlineclose,'skitse_dialog');
    //redlineDialog.setDialogWidth(this.width);
    redlineDialog.setDialogWidth("300px");
    var html = '';
    html+='            <table border="0" id="'+this.name+'_print_dialog_table" class="divtable" style="width:100%;" style="corder:1px solid #FF0000">';
    if(this.workflow)
    {
        html+='                <tr align="left">';
        html+='                    <td colspan="2" id="'+this.name+'_print_header">'+this.workflow+'</td>';
        html+='                </tr>';
        html+='                <tr align="left">';
        html+='                    <td colspan="2">' +
              '                        <select id="redlineselect" style="width:100%;" onchange="redline_setDrawingType()">';
        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 onclick="cp_init(this.style.backgroundColor);" id="redline_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="redlinedrawingtypebox"></td></tr>';
        html+='                <tr>';
        html+='                  <td colspan="2" align="right"><span id="redline_buttons">';
        html+='                    <button class="menubutton" id="redline_ok_button" onclick="redline_ok_end();">'+cbInfo.getString('standard.button.ok')+'</button>';
        html+='                    <button class="menubutton" id="redline_undo_button" onclick="onDrawUndo();">'+cbInfo.getString('redline.dialog.undo')+'</button>';
        html+='                  </span></td>';
        html+='                </tr>';
    }
    html+='            </table>';

    redlineDialog.addContentHTML(html);
    redlineDialog.showDialog();
   
    // default color (måske skal colorPicker have en default farve!)
    this.setColor();
}

RedlineObj.prototype.setColor = function(color)
{
    if(color)
        this.color = color;
    var e = getElement("redline_selected_color")
    if(e)
        e.style.backgroundColor = this.color;
}

function redlineclose()
{
    cbmapdrawer_currentDrawer.dialogCancel();
}

//Colorpicker
function cp_init(color)
{
    colorPicker_options = {
        "r_values":"4",
        "g_values":"4",
        "b_values":"4",
        "table_rows":"8",
        "color":color,
        "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'),redline_cp_ok, null,colorPicker_options);
}

function redline_cp_ok(color)
{
    redlineObj.setColor(color);
    cbmapdrawer_currentDrawer.setColor(color);
    cbmapdrawer_currentDrawer.redrawObjects();
}

function show_help()
{
    var current_objType = getElement('redlineselect').value;
    var draw_help = getElement("draw_help");
    switch(current_objType)
    {
        case 'polygon':
            draw_help.innerHTML = _cbMapDefault_PolygonOptions.info;
            break;
        case 'rectangle':
            draw_help.innerHTML = _cbMapDefault_RectangleOptions.info;
            break;
        case 'circle_input':    
        case 'circle':
            draw_help.innerHTML = _cbMapDefault_CircleOptions.info;
            break;
        case 'line':
            draw_help.innerHTML = _cbMapDefault_LineOptions.info;
            break;
        case  'label':    
        case 'point':
            draw_help.innerHTML = _cbMapDefault_PointOptions.info;
            break;        
    }
}

function hide_help()
{
    getElement("draw_help").innerHTML ="";
}

//
function RedlineGeometry(dm,dynamiclayer)
{
    this.drawmode = dm;
    this.id = redline_newGeom(this);
    this.writepage ='redline-write';
    this.columnnames = 'text,color';
    this.data = '';
    this.dynamiclayer = dynamiclayer;
    this.radius;
}

function onDrawUndo()
{
    var opt = getElement('redlineselect').value;
    switch (opt)
    {
        case "polygon":
            this.data =cbmapdrawer_currentDrawer.cbdraw.points;
            this.data =cbmapdrawer_currentDrawer.cbdraw.points.pop();
            cbmapdrawer_currentDrawer.cbdraw.nPoints -=1;
            cbmapdrawer_currentDrawer.redrawObjects();
            break;
        case "line":
            this.data =cbmapdrawer_currentDrawer.cbdraw.points;
            this.data =cbmapdrawer_currentDrawer.cbdraw.points.pop();
            cbmapdrawer_currentDrawer.cbdraw.nPoints -=1;
            cbmapdrawer_currentDrawer.redrawObjects();
            break;
    }
}

function redline_ok_end()
{
    cbmapdrawer_currentDrawer.drawOK();
    redline_setDrawingType();
    //redlineDialog.hideDialog();
}

RedlineGeometry.prototype.onDrawSuccess = function(CBMapDrawer)
{
    this.data = "'" + CBMapDrawer.getWKT() +"'";
    var color = getElement("redline_selected_color").style.backgroundColor;
    if(color.substring(0,1)!='#')
    {
        if(color.substring(0,3)=='rgb')
        {
            color = color.substring(4,color.length-1);
            color = color.replace(/,/g,'');
        }
    }
    //todo: make this dynamic to retrieve inputvalues from drawingtype

    var columnnames = this.columnnames;
    var url = getServletUrl();
    if(this.drawmode=='circle' || this.drawmode=='circle-input')
    {
        columnnames += ",radius";
        url += "?page=redline-circle";       
        url += "&wkt=" + CBMapDrawer.getWKT();

        var radius = '0.1';
        var inputradius = getElement("redline_radius_input4");
        if(inputradius) {
            if(!isNaN(inputradius.value) && inputradius.value != '') {
                radius = inputradius.value;
            }
        } else {
            radius = CBMapDrawer.getRadius();
        }
        url += "&radius="+radius;

        var text = ' ';
        var inputtext = getElement("redline_text_input4");       
        if(inputtext) {
            if(inputtext.value.length > 0)
                text = inputtext.value;
        } else {
            text = radius;
        }
        url += "&text="+text;

        url += "&color=" + color;
    }
    else
    {
        var inputtext = getElement("redline_text_input2");         
        if(inputtext) {
            this.data +=";'" + inputtext.value +"'";
        } else {
            this.data +=";'-'";
        }
        url += "?page=redline-write";        
        url += "&row1="+this.data+";'"+color+"'";
    }
    url+= "&sessionid="+getSessionId();
    url+= "&profile="+getProfile();
    url+= "&dynamiclayer="+this.dynamiclayer;
    url+= "&columnnames="+columnnames;
    this.saveobject(url);
    
    this.init();
}

RedlineGeometry.prototype.init = function(opts)
{
    if(!opts)
    {
        opts = {
            "silent":"true",
            "clear_on_toolchange":"false",
            "color":getElement("redline_selected_color").style.backgroundColor
        };
    }

    if(this.drawmode =='polygon' || this.drawmode =='line')
    {
        getElement('redline_undo_button').disabled = false;
        showBlock(getElement('redline_buttons'));
    }
    else
    {
        getElement('redline_undo_button').disabled = true;
        hideBlock(getElement('redline_buttons'));
    }
  
    /*
     * create CBMapdraw object and start drawing
     */
    // alert("opts: "+opts +"\nthis.drawmode: "+ this.drawmode)
    if(this.drawmode=='polygon')
        CBMapDrawer_drawPolygon(this,opts);
    else if(this.drawmode=='rectangle')
        CBMapDrawer_drawRectangle(this,opts);
    else if(this.drawmode=='circle')
        CBMapDrawer_drawCircle(this,opts);
    else if(this.drawmode=='line')
        CBMapDrawer_drawLine(this,opts);
    else if(this.drawmode=='point')
        CBMapDrawer_drawPoint(this,opts);
    else if(this.drawmode=='circle-input')
    {
        opts.radius = this.radius;
        opts.autook = 'true';
        CBMapDrawer_drawCircle(this,opts);
    }
}

RedlineGeometry.prototype.redraw = function()
{
   /*
    * create CBMapdraw object and start drawing
    * CBMap_drawWkt(this.wkt);
    */   
}


RedlineGeometry.prototype.saveobject = function(url)
{
    /* we must define
          - dynamiclayer
          - columnnames
          - row1   
     */
    var waitstr = cbInfo.getString('redline.waiting.save');
    showWaitingBox(waitstr);

    var cbHttp  = new CBhttp();
    var pComp = cbHttp.executeUrl(url, false);
    cbKort.removeSearchResults('dynlayer_show_redline',false,waitstr);
    currentGeomobj = null;
    hideWaitingBox();
}

var redlineObj = null;

function redline_setDrawingType()
{
    var i = getElement('redlineselect').selectedIndex;
    currentType = redlineObj.drawingTypes[i];
    currentType.showHtml('redlinedrawingtypebox');
    currentGeomobj = new RedlineGeometry(currentType.rltype,currentType.dynamiclayer);
    currentGeomobj.init();
}
function redline_changeRadius(radius)
{
    if(currentGeomobj)
    {
        currentGeomobj.radius = radius;
        currentGeomobj.init();
    }
}
