/**
 *
 * @project     CWC2
 * @revision    $Id: cwcjsapi.js,v 1.71 2006/03/13 16:44:18 jlacroix Exp $
 * @purpose     Java Script API for CWC
 * @author      DM Solutions Group (assefa@dmsolutions.ca)
 * @copyright
 * <b>Copyright (c) 2002, DM Solutions Group Inc.</b>
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/************************************************************************/
/*                           CWCPoint constructor                       */
/*                                                                      */
/*      Utility class that is used with the AddPoint function.          */
/*      Defines the coordinates of the point as well as all the         */
/*      styles elements used to draw a point with a label.              */
/*                                                                      */
/*      Class initialize with the same values uses in the locate        */
/*      widget to create a point.                                       */
/************************************************************************/
function CWCPoint()
{
    this.x = -1;
    this.y = -1;
    this.symbol = 6;
    this.symbol_colour = "0,0,0"; //r,g,b
    this.symbol_size = 20;
    this.symbol_outlinecolour = "255,255,255";
    this.label = "new point";
    //font value not supported. points will be drawn with BITMAP fonts
    //this.font = "arial";

/* -------------------------------------------------------------------- */
/*      possible values are TINY, SMALL, MEDIUM, LARGE, GIANT           */
/* -------------------------------------------------------------------- */
    this.font_size = "MEDIUM";

    this.font_colour = "0,0,0"; //r,g,b
    this.font_outlinecolour = "255,255,255";
    this.marquee = "";  //ON or OFF (shadow)
/* -------------------------------------------------------------------- */
/*      valid values for position are                                   */
/*      UL, LR, UR, LL, CR, CL, UC, LC, CC, AUTO                        */
/* -------------------------------------------------------------------- */
    this.label_position = "CL";

    this.label_x_off = 5; //label offset x
    this.label_y_off = 0; //label offset y
}


/************************************************************************/
/*                           CWCRectangle constructor                   */
/*                                                                      */
/*      Utility class that is used with the AddRectangle function.      */
/*      Defines the coordinates of the rectangle as well as all the     */
/*      styles elements used to draw a line.                            */
/*                                                                      */
/************************************************************************/
function CWCRectangle()
{
    this.xmin = -1;
    this.ymin = -1;
    this.xmax = -1;
    this.ymax = -1;
    this.colour = "0,0,0"; //r,g,b

    //symbol and size are not supported at this point.
    this.symbol = 0;
    this.symbol_size = 0;
}



/************************************************************************/
/*                          CWCLayer constructor.                       */
/************************************************************************/

function CWCLayer(name)
{
    this.oMap = ""; //set by add layer function from the map object
    this.name = name;
    this.index = -1;
    this.status = "";
    this.type = -1;
    this.title = "";
    this.connection = "";
    this.connectiontype = -1; //should this be public or private?
    this.srs = "";
    this.version = "";
    this.format = "";
    this.formatlist = "";

    this.style = "";
    this.stylelist = "";

/* -------------------------------------------------------------------- */
/*      flag used to indicate a vector layer create by                  */
/*      CWCJSAPI. These layers are the only ones valid                  */
/*      for adding points or lines.                                     */
/* -------------------------------------------------------------------- */
    this.bCWCLayer = 0;
}

/************************************************************************/
/*                            CWCSetLayerStatus                         */
/*                                                                      */
/*      sets the layer status. Base on the mapserver status             */
/*      defintion : valid status value are :                            */
/*         "ON"                                                         */
/*         "OFF"                                                        */
/*         "DELETED"                                                    */
/*                                                                      */
/*        If the status is valid, this function will update a           */
/*      variable in the application object (LAYER_STATUS_CHANGED)       */
/*      which will be used when a map refresh is called.                */
/************************************************************************/
function CWCSetLayerStatus(status)
{
//	alert(status);
    var bValidStatus = false;
    if (status == "ON")
    {
        this.status = 1;
        bValidStatus = true;
    }
    else if (status == "OFF")
    {
        this.status = 0;
        bValidStatus = true;
    }
    else if (status == "DELETED")
    {
        this.status = 4;
        bValidStatus = true;
    }

    if (bValidStatus == true)
    {
        this.oMap.oApplication.LAYER_STATUS_MODIFIED = true;

        return true;
    }
    else
    {
        this.oMap.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oMap.oApplication.oMLT.Get("101", "Invalid layer status"));

        return false;
    }
}


/************************************************************************/
/*                            CWCGetLayerStatus                         */
/*                                                                      */
/*      return the layer status. Base on the mapserver status           */
/*      defintion :                                                     */
/*         ON = 1                                                       */
/*         DEFAULT = 2                                                  */
/*         OFF = 0                                                      */
/*         DELETED = 4                                                  */
/************************************************************************/
function CWCGetLayerStatus()
{
    if (this.status == 1 || this.status == 2) //on or default
    {
        return "ON";
    }
    else if (this.status == 0)
    {
        return "OFF";
    }
    else if (this.status == 4)
    {
        return "DELETED";
    }
    else
    {
        return "";
    }
}


/************************************************************************/
/*                             CWCGetLayerStyle                         */
/*                                                                      */
/*      return ths current style.                                       */
/************************************************************************/
function CWCGetLayerStyle()
{
    return this.style;
}


/************************************************************************/
/*                           CWCGetLayerStyleList                       */
/*                                                                      */
/*      Returns the current style list.                                 */
/************************************************************************/
function CWCGetLayerStyleList()
{
    aReturn = new Array();

    if (this.stylelist != "")
    {
        aReturn = this.stylelist.split(",");
    }

    return aReturn;
}


/************************************************************************/
/*                             CWCSetLayerStyle                         */
/*                                                                      */
/*      set the style of the layer. Validate to see if the style        */
/*      passed is in the list of stylelist for the layer.               */
/************************************************************************/
function CWCSetLayerStyle(szStyle)
{
    var bValidStyle = false;
    if (this.stylelist != "")
    {
        var aValidStyles = this.stylelist.split(",");
        var nStyles = aValidStyles.length;
        for (i=0; i<nStyles; i++)
        {
            if (szStyle == aValidStyles[i])
            {
                this.style = szStyle;
                this.oMap.oApplication.LAYER_STYLE_MODIFIED = true;
                bValidStyle = true;
                break;
            }
        }
    }

    if (bValidStyle == false)
        this.oMap.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oMap.oApplication.oMLT.Get("102", "Invalid layer style"));

    return bValidStyle
}

/************************************************************************/
/*                             CWCGetLayerType                          */
/*                                                                      */
/*      Return the layers's type.                                       */
/************************************************************************/
function CWCGetLayerType()
{
    if (this.type == 0)
      return "POINT";
    else if (this.type == 1)
      return "LINE";
    else if (this.type == 2)
      return "POLYGON";
    else if (this.type == 3)
      return "RASTER";
    else if (this.type == 4)
     return "ANNOTATION";
    else if (this.type == 5)
     return "QUERY";
    else if (this.type == 6)
     return "CIRCLE";
    else if (this.type == 7)
     return "GRATICULE";
    else
    {
        this.oMap.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oMap.oApplication.oMLT.Get("115", "Invalid layer type"));
        return false; //should never happen unless the user
                          //modified the type manually.
    }
}


/************************************************************************/
/*                          CWCSetLayerProjection                       */
/*                                                                      */
/*      Set the projection of the layer.                                */
/*      If a valid list exists in the application, use it to            */
/*      validate the projection passed as argument.                     */
/************************************************************************/
function CWCSetLayerProjection(projection)
{
    //should this be validated agains valid projections ??

     var nValidProj = this.oMap.validprojections.length;
     var  bValidProj = true;

     if (projection == null)
       bValidProj = false;

     if (nValidProj > 0 && bValidProj == true)
     {
         bValidProj = false;
         for (i=0; i<nValidProj; i++)
         {
             if (this.oMap.validprojections[i] == projection)
             {
                 bValidProj = true;
                 break;
             }
         }
     }

     if (bValidProj == false)
     {
         this.oMap.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oMap.oApplication.oMLT.Get("100", "Invalid Projection"));

         return false;
     }

     this.projection = projection;

     aHiddenVars = new Array(3);
     aHiddenVars[0] = new Array(2);
     aHiddenVars[0][0] =  "LAYER_PROJECTION_CHANGED";
     aHiddenVars[0][1] = "1";

     aHiddenVars[1] = new Array(2);
     aHiddenVars[1][0] =  "LAYER_INDEX";
     aHiddenVars[1][1] = this.index;

     aHiddenVars[2] = new Array(2);
     aHiddenVars[2][0] =  "PROJECTION";
     aHiddenVars[2][1] = projection;

     this.oMap.oApplication.CallServer("",aHiddenVars);
     return true;
}


/************************************************************************/
/*                             CWCPromoteLayer                          */
/*                                                                      */
/*      Promote layer (layer will be drawn later).                      */
/************************************************************************/
function CWCPromoteLayer()
{
    var aDrawingOrder = new Array(this.oMap.numlayers);
    if (this.oMap.layerdrawingorder != "")
      aDrawingOrder = this.oMap.layerdrawingorder.split(",");
    else
    {
        for (i=0; i<this.oMap.numlayers; i++)
          aDrawingOrder[i] = i;
    }

     for (i=0; i<this.oMap.numlayers; i++)
     {
         if (aDrawingOrder[i] == this.index)
         {
             if (i<this.oMap.numlayers -1)
             {  
                 ttt = "index i = " + i;
                 //alert(ttt);
                 aDrawingOrder[i] = aDrawingOrder[i+1];
                 aDrawingOrder[i+1] = this.index;

                 ttt = "value for index " + i + " = " + aDrawingOrder[i];
                 //alert(ttt);
                 ttt = "value for index " + (i+1) + " = " + aDrawingOrder[i+1];
                 //alert(ttt);

                 break;
             }
         }
     }
      
     var layerorder = "";
     for (i=0; i<this.oMap.numlayers; i++)
     {
         if (i == 0)
           layerorder += aDrawingOrder[i];
         else
           layerorder += ","+aDrawingOrder[i];
     }

     this.oMap.layerdrawingorder = layerorder;
     this.oMap.oApplication.LAYER_ORDER_MODIFIED = true;

     return true;
}


/************************************************************************/
/*                              CWCDemoteLayer                          */
/*                                                                      */
/*      Demote layer (layer will be drawn earlier).                     */
/************************************************************************/
function CWCDemoteLayer()
{
    var aDrawingOrder = new Array(this.oMap.numlayers);
    if (this.oMap.layerdrawingorder != "")
      aDrawingOrder = this.oMap.layerdrawingorder.split(",");
    else
    {
        for (i=0; i<this.oMap.numlayers; i++)
          aDrawingOrder[i] = i;
    }

     for (i=0; i<this.oMap.numlayers; i++)
     {
         if (aDrawingOrder[i] == this.index)
         {
             if (i>0)
             {
                 aDrawingOrder[i] = aDrawingOrder[i-1];
                 aDrawingOrder[i-1] = this.index;
                 break;
             }
         }
     }

      var layerorder = "";
     for (i=0; i<this.oMap.numlayers; i++)
     {
         if (i == 0)
           layerorder += aDrawingOrder[i];
         else
           layerorder += ","+aDrawingOrder[i];
     }

     this.oMap.layerdrawingorder = layerorder;
     this.oMap.oApplication.LAYER_ORDER_MODIFIED = true;

     return true;
}


/* ==================================================================== */
/*      Layer class prototypes.                                         */
/* ==================================================================== */

CWCLayer.prototype.GetStatus = CWCGetLayerStatus;
CWCLayer.prototype.SetStatus = CWCSetLayerStatus;

CWCLayer.prototype.GetStyle = CWCGetLayerStyle;
CWCLayer.prototype.GetStyleList = CWCGetLayerStyleList;
CWCLayer.prototype.SetStyle = CWCSetLayerStyle;

CWCLayer.prototype.GetType = CWCGetLayerType;

CWCLayer.prototype.SetProjection = CWCSetLayerProjection;

CWCLayer.prototype.Promote = CWCPromoteLayer;
CWCLayer.prototype.Demote = CWCDemoteLayer;


/* ==================================================================== */
/*      end of layer object class.                                      */
/* ==================================================================== */

/************************************************************************/
/*                        CWCMapObject constructor.                     */
/************************************************************************/
function CWCMapObject(oApp)
{
    this.oApplication = oApp;

    this.minx = 0;
    this.miny = 0;
    this.maxx = 0;
    this.maxy = 0;

    this.width = 0;
    this.height = 0;

    this.projection = "";
    this.validprojections = new Array();
    this.validprojectionNames = new Array();

    this.scale = -1;
    this.cellsize = -1;
    this.resolution = 72;
    this.units = 3; //meter

    this.zoomfactor = 2;

    this.layerdrawingorder ="";

    //cursor position
    this.cursorpos = new Array(2);
    this.cursorpos[0] = 0;
    this.cursorpos[1] = 0;

    this.numlayers = 0;
    this.aLayers = new Array();

    //allow resizing : is set by the mapdhtml widget if the
    //allow resize parameter is set to true.
    this.bAllowResize = 0;

/* ==================================================================== */
/*      define static values.                                           */
/* ==================================================================== */
    this.CWCINCHES = 0;
    this.CWCFEET = 1;
    this.CWCMILES = 2;
    this.CWCMETERS = 3;
    this.CWCKILOMETERS = 4;
    this.CWCDEGREES = 5;
    this.CWCPIXELS = 6;

    this.gaUnitPerMeter = new Array(6);
    this.gaUnitPerMeter[0] = 39.37; //inches;
    this.gaUnitPerMeter[1] = 3.2808; //feet
    this.gaUnitPerMeter[2] =  0.00062137; //Miles
    this.gaUnitPerMeter[3] =  1.0; //Meters
    this.gaUnitPerMeter[4] = 0.001; //Kilometers
    this.gaUnitPerMeter[5] =  0.000009044; //using value a 0 latitude 1degree = 110.57km

    this.gaMeterPerUnit = new Array(6);
    this.gaMeterPerUnit[0] =  0.0254; //inches
    this.gaMeterPerUnit[1] = 0.3048; //feet
    this.gaMeterPerUnit[2] = 1609.3445; //Miles
    this.gaMeterPerUnit[3] = 1.0; //Meters
    this.gaMeterPerUnit[4] = 1000.0; //Kilometers
    this.gaMeterPerUnit[5] = 110570; //using value a 0 latitude 1degree = 110.57km


    //same values as mapserver
    this.MS_GRATICULE = 10;

/* ==================================================================== */
/*      end define static values.                                       */
/* ==================================================================== */

}


/************************************************************************/
/*                             CWCGetProjection                         */
/*                                                                      */
/*      return the current projection.                                  */
/************************************************************************/
function CWCGetProjection()
{
    return this.projection;
}


/************************************************************************/
/*                           CWCChangeProjection                        */
/*                                                                      */
/*      function called by the js api users to change the projection.   */
/************************************************************************/
function CWCChangeProjection( projection )
{
    if (this.SetProjection(projection))
    {
        this.oApplication.UpdateProjection();
        return true;
    }
    else
        return false;

}

/************************************************************************/
/*                             CWCSetProjection                         */
/*                                                                      */
/*      set the projection of the map. If there is a list of valid      */
/*      projections  (set by ProjectionSelector widget), validate       */
/*      the new projection).                                            */
/************************************************************************/
function CWCSetProjection( projection )
{
    var nValidProj = this.validprojections.length;
    var  bValidProj = true;

    if (nValidProj == 0)
    {
      this.projection = projection;
      return true;
    }
    else if (nValidProj > 0)
    {
        bValidProj = false;
        for (i=0; i<nValidProj; i++)
        {
            if (this.validprojections[i] == projection)
            {
                this.projection = projection;
                bValidProj = true;
                break;
            }
        }
    }

    if (bValidProj == false)
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("100", "Invalid Projection"));

    return bValidProj;
}

/***********************************************************************/
/*                         CWCReprojectPoint                           */
/*                                                                     */
/*   Reproject a point from szProjectionFrom to szProjectionTo         */
/***********************************************************************/
function CWCReprojectPoint(szCallBack, nPointX, nPointY,
                           szProjectionFrom, szProjectionTo)
{
    var nValidProj = this.validprojections.length;
    var nbValidProj = 2;

    if (nValidProj > 0)
    {
        nbValidProj = 0;
        for (i=0; i<nValidProj; i++)
        {
            if (this.validprojections[i] == szProjectionFrom)
                nbValidProj++;

            if (this.validprojections[i] == szProjectionTo)
                nbValidProj++;
        }
    }

    if (nbValidProj == 2)
    {
      //CWCDHTML_ShowLayer("ActivityLayer");

        aHiddenVars = new Array(4);
        aHiddenVars[0] = new Array(2);
        aHiddenVars[0][0] =  "REPROJECT_POINT";
        aHiddenVars[0][1] = ""+nPointX+"|"+nPointY+"";

        aHiddenVars[1] = new Array(2);
        aHiddenVars[1][0] =  "REPROJECT_FROM";
        aHiddenVars[1][1] = szProjectionFrom;

        aHiddenVars[2] = new Array(2);
        aHiddenVars[2][0] =  "REPROJECT_TO";
        aHiddenVars[2][1] = szProjectionTo;

        aHiddenVars[3] = new Array(2);
        aHiddenVars[3][0] =  "FUNCTION_CALLBACK";
        aHiddenVars[3][1] = szCallBack;

        szOnLoad = 'goCWCJSAPI.PointReprojected()';

        this.oApplication.CallServer(szOnLoad, aHiddenVars);

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("100", "Invalid Projection"));

        return false;
    }
}


/************************************************************************/
/*                          CWCPointReprojected                         */
/*                                                                      */
/*      Called after a point is reprojected.                            */
/************************************************************************/
function CWCPointReprojected()
{
    var doc = this.GetDocumentObject();

    if (doc.forms[0].FUNCTION_CALLBACK != null &&
        doc.forms[0].REPROJECTED_POINT_X != null &&
        doc.forms[0].REPROJECTED_POINT_Y != null)
    {
        eval(doc.forms[0].FUNCTION_CALLBACK.value+'('+
                           doc.forms[0].REPROJECTED_POINT_X.value+','+
                           doc.forms[0].REPROJECTED_POINT_Y.value+');');
    }
}

/************************************************************************/
/*                               CWCAddLayer                            */
/*                                                                      */
/*      add a layer object.                                             */
/************************************************************************/
function CWCAddLayer(name)
{
    this.aLayers[this.numlayers] = new CWCLayer(name);
    oLayer = this.aLayers[this.numlayers];
    oLayer.oMap = this;
    this.numlayers++;
    return true;
}


/************************************************************************/
/*                            CWCAddWMSLayerMap                         */
/*                                                                      */
/*      Add a new wms layer in the map.                                 */
/************************************************************************/
function CWCAddWMSLayerMap(name, title, srs, connection, version, format)
{
    return this.oApplication.AddWMSLayer(name, title, srs, connection,
                                  version, format);
}



/************************************************************************/
/*                             CWCAddGridLayer                          */
/*                                                                      */
/*      Add new grid layer. Parameters are not manadatory.              */
/*      Description of the grid functionnality can be found at :        */
/*       http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?MapServerGrid     */
/************************************************************************/
function CWCAddGridLayer(name, projection, color,
                         labelfont, labelcolor, labelsize,
                         labelformat, minsubdivide, maxsubdivide,
                         mininterval, maxinterval, minarcs, maxarcs)

{
    var bGridExists;
    for (i=0; i<this.numlayers; i++)
    {
        oLayer = this.aLayers[i];
        if (oLayer.connectiontype == this.MS_GRATICULE)
        {
            bGridExists = true;
            break;
        }
    }

    if (bGridExists)
    {
        //generate ar error message that a grid layer exits already
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("103", "Grid layer already exist"));

        return false;
    }

    //call server to generate a new grid layer
     CWCDHTML_ShowLayer("ActivityLayer");

     aHiddenVars = new Array(14);
     aHiddenVars[0] = new Array(2);
     aHiddenVars[0][0] =  "ADD_NEW_GRID_LAYER";
     aHiddenVars[0][1] = "1";

     //name
     aHiddenVars[1] = new Array(2);
     aHiddenVars[1][0] =  "NAME";
     if (name != null)
     {
         aHiddenVars[1][1] = name;
     }
     else
     {
         aHiddenVars[1][1] = "GRID";
     }

     //projection
     aHiddenVars[2] = new Array(2);
     aHiddenVars[2][0] =  "PROJECTION";
     if (projection != null)
     {
         aHiddenVars[2][1] = projection;
     }
     else
     {
         aHiddenVars[2][1] = "";
     }

     //color
     szColor ="";
     if (color == null)
     {
         szColor = "";
     }
     else 
     {
         aColor = color.split(",");
         if (aColor.length != 3 || 
             aColor[0] < 0 ||  aColor[0] > 255 ||
             aColor[1] < 0 ||  aColor[1] > 255 ||
             aColor[2] < 0 ||  aColor[2] > 255) 
         {
             szColor = "";
         }
         else
           szColor = color;
     }

     aHiddenVars[3] = new Array(2);
     aHiddenVars[3][0] =  "COLOR";
     aHiddenVars[3][1] = szColor;


     //labelfont : not supported yet. Using bitmap
     aHiddenVars[4] = new Array(2);
     aHiddenVars[4][0] =  "LABELFONT";
     if (labelfont != null)
     {
         aHiddenVars[4][1] = labelfont;
     }
     else
     {
         aHiddenVars[4][1] = "";
     }
     aHiddenVars[4][1]="";

     //labelcolor
     szColor="";
     if (labelcolor == null)
     {
         szColor = "";
     }
     else 
     {
         aColor = labelcolor.split(",");
         if (aColor.length != 3 || 
             aColor[0] < 0 ||  aColor[0] > 255 ||
             aColor[1] < 0 ||  aColor[1] > 255 ||
             aColor[2] < 0 ||  aColor[2] > 255) 
         {
             szColor = "";
         }
         else
           szColor = labelcolor;
     }

         
     aHiddenVars[5] = new Array(2);
     aHiddenVars[5][0] =  "LABELCOLOR";
     aHiddenVars[5][1] = szColor;

     //labelsize
     aHiddenVars[6] = new Array(2);
     aHiddenVars[6][0] =  "LABELSIZE";
     if (labelsize != null)
     {
         nFontSize= 2;
         if (labelsize == "TINY")
           nFontSize = 0;
         else if ( labelsize == "SMALL")
           nFontSize = 1;
         else if (  labelsize == "MEDIUM")
           nFontSize = 2;
         else if ( labelsize == "LARGE")
           nFontSize = 3;
         else if (  labelsize == "GIANT")
           nFontSize = 4;
         aHiddenVars[6][1] = nFontSize;
     }
     else
     {
         aHiddenVars[6][1] = "";
     }

     //labelformat
     aHiddenVars[7] = new Array(2);
     aHiddenVars[7][0] =  "LABELFORMAT";
     if (labelformat != null)
     {
         aHiddenVars[7][1] = labelformat;
     }
     else
     {
         aHiddenVars[7][1] = "";
     }

     //minsubdivide
     aHiddenVars[8] = new Array(2);
     aHiddenVars[8][0] =  "MINSUBDIVIDE";
     if (minsubdivide != null)
     {
         aHiddenVars[8][1] = minsubdivide;
     }
     else
     {
         aHiddenVars[8][1] = "";
     }

     //maxsubdivide
     aHiddenVars[9] = new Array(2);
     aHiddenVars[9][0] =  "MAXSUBDIVIDE";
     if (maxsubdivide != null)
     {
         aHiddenVars[9][1] = maxsubdivide;
     }
     else
     {
         aHiddenVars[9][1] = "";
     }

     //mininterval
     aHiddenVars[10] = new Array(2);
     aHiddenVars[10][0] =  "MININTERVAL";
     if (mininterval != null)
     {
         aHiddenVars[10][1] = mininterval;
     }
     else
     {
         aHiddenVars[10][1] = "";
     }

     //maxinterval
     aHiddenVars[11] = new Array(2);
     aHiddenVars[11][0] =  "MAXINTERVAL";
     if (maxinterval != null)
     {
         aHiddenVars[11][1] = maxinterval;
     }
     else
     {
         aHiddenVars[11][1] = "";
     }

     //minarcs
     aHiddenVars[12] = new Array(2);
     aHiddenVars[12][0] =  "MINARCS";
     if (minarcs != null)
       aHiddenVars[12][1] = minarcs;
     else
       aHiddenVars[12][1] = "";

     //maxarcs
     aHiddenVars[13] = new Array(2);
     aHiddenVars[13][0] =  "MAXARCS";
     if (maxarcs != null)
       aHiddenVars[13][1] = maxarcs;
     else
       aHiddenVars[13][1] =  "";

     szOnLoad = 'goCWCJSAPI.NewLayerAdded()';

     this.oApplication.CallServer(szOnLoad, aHiddenVars);
     return true;
}

/************************************************************************/
/*                            CWCGetLayerByIndice                       */
/*                                                                      */
/*      utility function to return the layer object based on the        */
/*      layer's indice.                                                 */
/************************************************************************/
function CWCGetLayerByIndice(indice)
{
    if (indice >=0 && indice < this.numlayers)
    {
        var oLayer = this.aLayers[indice];
        return oLayer;
    }

    return false;
}

/************************************************************************/
/*                            CWCGetLayerByName                         */
/*                                                                      */
/*      utility function to return the layer object based on the        */
/*      layer's name.                                                   */
/************************************************************************/
function CWCGetLayerByName(name)
{
    bFound = false;
    for (i=0; i<this.numlayers; i++)
    {
      if (this.aLayers[i].name == name)
      {
        bFound = true;
        oLayer = this.aLayers[i];
        break;
      }
    }
    if (bFound == true)
    {
        return oLayer;
    }
    else
      return false;
}

/* -------------------------------------------------------------------- */
/*      Zoom related functions.                                         */
/*                                                                      */
/* -------------------------------------------------------------------- */

/****************************************************************************
* Set the zoom factor used by the zoom functions
*
* @param factor : integer and should be >=2
*****************************************************************************/
function CWCSetZoomFactor(factor)
{
    if (factor >= 2)
    {
        this.zoomfactor = factor;

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("104", "Invalid zoom factor"));

        return false;
    }
}

/****************************************************************************
* Zoom in at the center of the map
*****************************************************************************/
function CWCZoomIn()
{
    this.oApplication.NAV_CMD = "ZOOM_IN";
    this.oApplication.NAV_INPUT_COORDINATES = ""+(this.width/2)+","+(this.height/2);
    this.oApplication.NAV_INPUT_TYPE = "POINT";
    this.oApplication.UpdateNavTools();
    return true;
}

/****************************************************************************
* Zoom in at pixel positions given
*
* @param x : integer. Value should be betwwen 0 and width of the map
* @param y : integer. Value should be betwwen 0 and height of the map
*****************************************************************************/
function CWCZoomInPix(x, y)
{
    if (x >=0 && x <= this.width &&
        y >=0 && y <= this.height)
    {
        this.oApplication.NAV_CMD = "ZOOM_IN";
        this.oApplication.NAV_INPUT_COORDINATES = ""+x+","+y;
        this.oApplication.NAV_INPUT_TYPE = "POINT";
        this.oApplication.UpdateNavTools();

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("105", "Invalid zoom pixel"));

        return false;
    }
}


/****************************************************************************
* Zoom out at the center of the map
*****************************************************************************/
function CWCZoomOut()
{
    this.oApplication.NAV_CMD = "ZOOM_OUT";
    this.oApplication.NAV_INPUT_COORDINATES = ""+(this.width/2)+","+(this.height/2);
    this.oApplication.NAV_INPUT_TYPE = "POINT";
    this.oApplication.UpdateNavTools();
    return true;
}

/****************************************************************************
* Zoom out at pixel positions given
*
* @param x : integer. Value should be betwwen 0 and width of the map
* @param y : integer. Value should be betwwen 0 and height of the map
*****************************************************************************/
function CWCZoomOutPix(x, y)
{
    if (x >=0 && x <= this.width &&
        y >=0 && y <= this.height)
    {
        this.oApplication.NAV_CMD = "ZOOM_OUT";
        this.oApplication.NAV_INPUT_COORDINATES = ""+x+","+y;
        this.oApplication.NAV_INPUT_TYPE = "POINT";
        this.oApplication.UpdateNavTools();

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("105", "Invalid zoom pixel"));

        return false;
    }
}


/****************************************************************************
* Zoom rectangle at pixel positions given
*
* @param x1 : First point X value. Should be betwwen 0 and width of the map
* @param y1 : First point Y value. Should be betwwen 0 and height of the map
* @param x2 : Second point X value. Should be betwwen 0 and width of the map
* @param y2 : Second point Y value. Should be betwwen 0 and height of the map
*****************************************************************************/
function CWCZoomRectPix(x1, y1, x2, y2)
{
    if (x1 >=0 && x1 <= this.width &&
        y1 >=0 && y1 <= this.height &&
        x2 >=0 && x2 <= this.width &&
        y2 >=0 && y2 <= this.height)
    {
        this.oApplication.NAV_CMD = "ZOOM_IN";
        this.oApplication.NAV_INPUT_COORDINATES = ""+x1+","+y1+";"+x2+","+y2;
        this.oApplication.NAV_INPUT_TYPE = "RECTANGLE";
        this.oApplication.UpdateNavTools();

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("105", "Invalid zoom pixel"));

        return false;
    }
}

/****************************************************************************
* Zoom to the full extents
*
*****************************************************************************/
function CWCZoomFull(x1, y1, x2, y2)
{
    this.oApplication.NAV_CMD = "ZOOM_FULL";
    this.oApplication.UpdateNavTools();
    return true;
}


/****************************************************************************
* Zoom to a certain scale
*
* @param scale : Scale value should be > 0
*****************************************************************************/
function CWCZoomScale(scale)
{
    if (scale > 0)
    {
        this.oApplication.SCALE_ZOOM = scale;
        this.oApplication.UpdateScaleZoom();

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("106", "Invalid zoom scale"));

        return false;
    }
}

/****************************************************************************
* Receneter at pixel positions given
*
* @param x : integer. Value should be betwwen 0 and width of the map
* @param y : integer. Value should be betwwen 0 and height of the map
*****************************************************************************/
function CWCRecenterPix(x, y)
{
    if (x >=0 && x <= this.width &&
        y >=0 && y <= this.height)
    {
        this.oApplication.NAV_CMD = "RECENTER";
        this.oApplication.NAV_INPUT_COORDINATES = ""+x+","+y;
        this.oApplication.NAV_INPUT_TYPE = "POINT";
        this.oApplication.UpdateNavTools();

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("107", "Invalid recenter coordinates"));

        return false;
    }
}


/************************************************************************/
/*                                CWCRefresh                            */
/*                                                                      */
/*      Refresh the map.                                                */
/************************************************************************/
function CWCRefresh()
{
    this.oApplication.RefreshMap();
    return true;
}

/************************************************************************/
/*                          CWCZoomToScale                              */
/*                                                                      */
/*      Zooms the map to a particular scale. This is used by            */
/*      the Scale widget                                                */
/************************************************************************/
function CWCZoomToScale(scale)
{
     CWCDHTML_ShowLayer("ActivityLayer");
     
     aHiddenVars = new Array(2);
     aHiddenVars[0] = new Array(2);
     aHiddenVars[0][0] =  "ZOOM_TO_SCALE";
     aHiddenVars[0][1] = "1";

     aHiddenVars[1] = new Array(2);
     aHiddenVars[1][0] =  "ZOOM_SCALE";
     aHiddenVars[1][1] = scale;

     this.CallServer("goCWCJSAPI.MapExtentsUpdated()",aHiddenVars);
     return true;
}

/************************************************************************/
/*                         CWCGetLayerDrawingOrder                      */
/*                                                                      */
/*      Return an array containning the drawing oder of the             */
/*      layers. The values in the array represents the layer index.     */
/************************************************************************/
function CWCGetLayerDrawingOrder()
{
/* -------------------------------------------------------------------- */
/*      if the layer order is empty, it means that layer drawing        */
/*      order follow the layers index.                                  */
/* -------------------------------------------------------------------- */
    if (this.layerdrawingorder == "")
    {
        aReturn = new Array(this.numlayers);
        for (i=0; i<this.numlayers; i++)
          aReturn[i] = i;
    }
    else
    {
        aReturn = this.layerdrawingorder.split(",");
    }

    return aReturn;
}


/************************************************************************/
/*                         CWCSetLayerDrawingOrder                      */
/*                                                                      */
/*      Takes an array containning the list of the layers index and     */
/*      will set the drawing order according to the indexes.            */
/*      The array should contain one entry per layer.                   */
/************************************************************************/
function CWCSetLayerDrawingOrder(aLayers)
{
    nLayers = aLayers.length;
    if (nLayers == this.numlayers)
    {
        aValidList = new Array(this.numlayers);

/* -------------------------------------------------------------------- */
/*      validate the contents of the array. We should have an entry     */
/*      for each layer.                                                 */
/* -------------------------------------------------------------------- */
        bValidList = true;
        for (i=0; i<nLayers; i++)
          aValidList[i] = 0;

         for (i=0; i<nLayers; i++)
         {
             if (aLayers[i] >=0 && aLayers[i] < this.numlayers)
             {
                 aValidList[aLayers[i]] = 1;
             }
             else
             {
                 bValidList = false;
                 break;
             }
         }

         if (bValidList == false)
         {
             this.oApplication.oErrorManager.Error(ERR_WARNING,
                                                   this.oApplication.oMLT.Get("108", "Invalid layer list"));

             return false;
         }

         for (i=0; i<nLayers; i++)
         {
             if (aValidList[i] == 0)
             {
                 bValidList = false;
                 break;
             }
         }
         if (bValidList == false)
         {
             this.oApplication.oErrorManager.Error(ERR_WARNING,
                                                   this.oApplication.oMLT.Get("108", "Invalid layer list"));

             return false;
         }

/* -------------------------------------------------------------------- */
/*      set the layerdrawingorder string with the new values and set    */
/*      the flag LAYER_ORDER_MODIFIED to be used when a refresh map     */
/*      is called.                                                      */
/* -------------------------------------------------------------------- */
         var layerorder = "";
         for (i=0; i<nLayers; i++)
         {
             if (i == 0)
               layerorder += aLayers[i];
             else
               layerorder += ","+aLayers[i];
         }

         this.layerdrawingorder = layerorder;
         this.oApplication.LAYER_ORDER_MODIFIED = true;

         return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("108", "Invalid layer list"));

        return false;
    }
}


/************************************************************************/
/*                              CWCSetViewSize                          */
/*                                                                      */
/*      Modify the width and height of the map view.                    */
/************************************************************************/
function CWCSetViewSize(width, height)
{
    if (width > 0 && height > 0 && this.bAllowResize == 1)
    {
        var szFormElement = ""+ this.oApplication.form + ".MAP_WIDTH.value = " + width;
        eval(szFormElement);

        szFormElement = ""+ this.oApplication.form + ".MAP_HEIGHT.value = " + height;
        eval(szFormElement);

        szFormElement = ""+ this.oApplication.form + ".submit()";
        eval(szFormElement);

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("109", "Invalid view size or resize not allowed"));

        return false;
    }
}


/************************************************************************/
/*                               CWCAddPoint                            */
/*                                                                      */
/*      Add a point on a specific layer. Parameters :                   */
/*                                                                      */
/*      layername : the layer must be a layer added used the            */
/*                  createlayer function.                               */
/*      poinobj : parametrs used to draw the point (coordinates,        */
/*                colour ...)                                           */
/************************************************************************/
function CWCAddPoint(layername, pointobj)
{
    if (layername == null || layername == "")
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("116", "Invalid layer name"));

        return false;
    }

    oLayer = this.GetLayerByName(layername);
    if (oLayer == false)
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("116", "Invalid layer name"));

        return false;
    }

    if (oLayer.bCWCLayer != 1)
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("117", "Invalid layer. Features can only be added on layers created by the javascript api"));

        return false;
    }


    szType = oLayer.GetType();
    if (szType != "POINT")
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("118", "Invalid layer type. Points can only be added on points layers"));

        return false;
    }

    if (pointobj == null || pointobj.x == null)
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("119", "Invalid point class"));

        return false;
    }

    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(18);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "ADD_NEW_FEATURE";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "LOCATE_LATLONG";
    aHiddenVars[1][1] = ""+pointobj.label+"|"+pointobj.x+","+pointobj.y;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "LOCATE_ADD_ELEMENT";
    aHiddenVars[2][1] = "1";

    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "LOCATE_ELEMENT_TYPE";
    aHiddenVars[3][1] = "POINT";

    aHiddenVars[4] = new Array(2);
    aHiddenVars[4][0] =  "SYMBOL";
    aHiddenVars[4][1] = pointobj.symbol;

    aHiddenVars[5] = new Array(2);
    aHiddenVars[5][0] =  "SYMBOL_COLOUR";
    aHiddenVars[5][1] = pointobj.symbol_colour;

    aHiddenVars[6] = new Array(2);
    aHiddenVars[6][0] =  "SYMBOL_SIZE";
    aHiddenVars[6][1] = pointobj.symbol_size;

    aHiddenVars[7] = new Array(2);
    aHiddenVars[7][0] =  "SYMBOL_OUTLINECOLOUR";
    aHiddenVars[7][1] = pointobj.symbol_outlinecolour;

    aHiddenVars[8]= new Array(2);
    aHiddenVars[8][0] =  "FONT";
    aHiddenVars[8][1] = pointobj.font;

    //convert the font size to values used in mapserver.
    nFontSize= 2;
    if (pointobj.font_size == "TINY")
      nFontSize = 0;
    else if ( pointobj.font_size == "SMALL")
      nFontSize = 1;
    else if ( pointobj.font_size == "MEDIUM")
      nFontSize = 2;
    else if ( pointobj.font_size == "LARGE")
      nFontSize = 3;
    else if ( pointobj.font_size == "GIANT")
      nFontSize = 4;

    aHiddenVars[9]= new Array(2);
    aHiddenVars[9][0] =  "FONT_SIZE";
    aHiddenVars[9][1] = nFontSize;

    aHiddenVars[10]= new Array(2);
    aHiddenVars[10][0] =  "FONT_COLOUR";
    aHiddenVars[10][1] = pointobj.font_colour;

    aHiddenVars[11]= new Array(2);
    aHiddenVars[11][0] =  "FONT_OUTLINECOLOUR";
    aHiddenVars[11][1] = pointobj.font_outlinecolour;

    aHiddenVars[12]= new Array(2);
    aHiddenVars[12][0] =  "MARQUEE";
    aHiddenVars[12][1] = pointobj.marquee;

    //convert the label position string to the MS_XX integer
    //used in mapserver.
    nLabelPos = 0;
    if ( pointobj.label_position == "UL")
      nLabelPos = 0;
    else if (pointobj.label_position == "LR")
      nLabelPos = 1;
    else if (pointobj.label_position == "UR")
      nLabelPos = 2;
    else if (pointobj.label_position == "LL")
      nLabelPos = 3;
    else if (pointobj.label_position == "CR")
      nLabelPos = 4;
    else if (pointobj.label_position == "CL")
      nLabelPos = 5;
    else if (pointobj.label_position == "UC")
      nLabelPos = 6;
    else if (pointobj.label_position == "LC")
      nLabelPos = 7;
    else if (pointobj.label_position == "CC")
      nLabelPos = 8;
    else if (pointobj.label_position == "AUTO")
      nLabelPos = 9;

    aHiddenVars[13]= new Array(2);
    aHiddenVars[13][0] =  "LABEL_POSITION";
    aHiddenVars[13][1] = nLabelPos;

    aHiddenVars[14]= new Array(2);
    aHiddenVars[14][0] =  "LABEL_X_OFF";
    aHiddenVars[14][1] = pointobj.label_x_off;

    aHiddenVars[15]= new Array(2);
    aHiddenVars[15][0] =  "LABEL_X_OFF";
    aHiddenVars[15][1] = pointobj.label_x_off;

    aHiddenVars[16]= new Array(2);
    aHiddenVars[16][0] =  "LAYER_NAME";
    aHiddenVars[16][1] = layername;

    //added for comaptibility with the locate widget.
    aHiddenVars[17]= new Array(2);
    aHiddenVars[17][0] =  "LAYER_PROJECTION";
    aHiddenVars[17][1] = "";

    szOnLoad = 'goCWCJSAPI.NewElementAdded()';

    this.oApplication.CallServer(szOnLoad, aHiddenVars);

    return true;
}



/************************************************************************/
/*                            CWCAddRectangle                           */
/*                                                                      */
/*      Add a point on the map at a specified location. The label       */
/*      will be displayed at the point location. The units for the      */
/*      point can "PIX", "MAP", "LATLONG" (MAP indicates the same       */
/*      unit as the one currently used in the map file).                */
/************************************************************************/
function CWCAddRectangle(layername, rectobj)
{
    if (layername == null || layername == "")
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("116", "Invalid layer name"));

        return false;
    }


    oLayer = this.GetLayerByName(layername);
    if (oLayer == false)
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("116", "Invalid layer name"));

        return false;
    }

    if (oLayer.bCWCLayer != 1)
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("117", "Invalid layer. Features can only be added on layers created by the javascript api"));

        return false;
    }

    szType = oLayer.GetType();
    if (szType != "LINE")
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("120", "Invalid layer type. Rectangles can only be added on line layers"));

        return false;
    }

    if (rectobj == null || rectobj.xmin == null)
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
             this.oApplication.oMLT.Get("120", "Invalid rectangle class"));

        return false;
    }

    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(9);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "ADD_NEW_FEATURE";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "LOCATE_LATLONG";
    aHiddenVars[1][1] = "ttt|"+rectobj.xmin+","+rectobj.ymin+";"+rectobj.xmax+","+rectobj.ymax;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "LOCATE_ADD_ELEMENT";
    aHiddenVars[2][1] = "1";

    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "LOCATE_ELEMENT_TYPE";
    aHiddenVars[3][1] = "RECTANGLE";

    aHiddenVars[4] = new Array(2);
    aHiddenVars[4][0] =  "COLOUR";
    aHiddenVars[4][1] = rectobj.colour;

    aHiddenVars[5] = new Array(2);
    aHiddenVars[5][0] =  "SYMBOL";
    aHiddenVars[5][1] = rectobj.symbol;

    aHiddenVars[6] = new Array(2);
    aHiddenVars[6][0] =  "SYMBOL_SIZE";
    aHiddenVars[6][1] = rectobj.symbol_size;

    aHiddenVars[7]= new Array(2);
    aHiddenVars[7][0] =  "LAYER_NAME";
    aHiddenVars[7][1] = layername;

    //added for comaptibility with the locate widget.
    aHiddenVars[8]= new Array(2);
    aHiddenVars[8][0] =  "LAYER_PROJECTION";
    aHiddenVars[8][1] = "";

    szOnLoad = 'goCWCJSAPI.NewElementAdded()';

    this.oApplication.CallServer(szOnLoad, aHiddenVars);

    return true;

}

/************************************************************************/
/*                               CWCAddPointWidget                      */
/*                                                                      */
/*      Add a point on the map at a specified location. The label       */
/*      will be displayed at the point location. The units for the      */
/*      point can "PIX", "MAP", "LATLONG" (MAP indicates the same       */
/*      unit as the one currently used in the map file).                */
/*                                                                      */
/*      This function is only used by the locate widget and should      */
/*      not be available (docuemented) for the jsapi. The jsapi has     */
/*      an AddPoint function that should be used.                       */
/************************************************************************/
function CWCAddPointWidget(x,y, label, szUnit,  bAddElement, bZoomTo)
{
    if ((szUnit == "PIX") || (szUnit == "MAP") || (szUnit=="LATLONG"))
    {
        //bAddElement && bZoomTo are non manadtory arguments
        if (arguments.length == 4)
        {
            bAddElement = 1;
            bZoomTo = 0;
        }
        //alert(bAddElement);
        //alert(bZoomTo);
        this.oApplication.AddPointWidget(x,y, label, szUnit,
                                         bAddElement, bZoomTo);

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("110", "Invalid unit"));

        return false;
    }
}

/************************************************************************/
/*                               CWCAddRectangleWidget                  */
/*                                                                      */
/*      Add a rectangle on the map at a specified location. The label   */
/*      will be displayed int he rectangle. The units for the           */
/*      points can "PIX", "MAP", "LATLONG" (MAP indicates the same      */
/*      unit as the one currently used in the map file).                */
/*                                                                      */
/*      This function is only used by the locate widget and should      */
/*      not be available (docuemented) for the jsapi. The jsapi has     */
/*      an AddRectangle function that should be used.                   */
/************************************************************************/
function CWCAddRectangleWidget(x1,y1,x2,y2, label, szUnit,  bAddElement, bZoomTo)
{
    if ((szUnit == "PIX") || (szUnit == "MAP") || (szUnit=="LATLONG"))
    {
        //bAddElement && bZoomTo are non manadtory arguments
        if (arguments.length == 6)
        {
            bAddElement = 1;
            bZoomTo = 0;
        }
        //alert(bAddElement);
        //alert(bZoomTo);
        this.oApplication.AddRectangleWidget(x1,y1,x2,y2, label, szUnit,
                                         bAddElement, bZoomTo);

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("110", "Invalid unit"));

        return false;
    }
}

/* ==================================================================== */
/*      Utility functions.                                              */
/* ==================================================================== */
/****************************************************************************
* Converts from Geographic coordinates to Pixel coordinates. Returns an
* array of 2 elements containing the resulting x and y positions.
*
* @param x : Value should be between inside the map extents
* @param y : Value should be between inside the map extents
*****************************************************************************/
function CWCGeo2Pix(x,y)
{
    if (x >= this.minx && x <= this.maxx &&
        y >= this.miny && y <= this.maxy)
    {
        var dfDeltaMaxGeoX = this.maxx - this.minx;
        var dfDeltaMaxGeoY = this.maxy - this.miny;

        dfPixX = (this.width * (x -this.minx))/ dfDeltaMaxGeoX;
        dfPixY = this.height - ((this.height * (y -this.miny))/ dfDeltaMaxGeoY);

        aReturn = new Array(2);
        aReturn[0] = Math.round(dfPixX);
        aReturn[1] = Math.round(dfPixY);

        return aReturn;
    }
    else
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("111", "Invalid geographic coordinates"));

    return false;

}


/****************************************************************************
* Converts from Pixel to Geographic coordinates. Returns an
* array of 2 elements containing the resulting x and y positions.
*
* @param x : Value should be between 0 and the map width
* @param y : Value should be between 0 and the map height
*****************************************************************************/
function CWCPix2Geo(x, y)
{
    if (x >= 0 && x <= this.width &&
        y >= 0 && y <= this.height)
    {
        x_pct = (x / this.width);
        y_pct = 1 - (y / this.height);

        dfGeoX = this.minx + ( ( this.maxx -  this.minx) * x_pct);
        dfGeoY = this.miny + ( (this.maxy -  this.miny) * y_pct);

        aReturn = new Array(2);
        aReturn[0] = dfGeoX;
        aReturn[1] = dfGeoY;
        return aReturn;
    }
    else
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("112", "Invalid pixel coordinates"));

    return false;
}



/************************************************************************/
/*                              CWCGetDistance                          */
/*                                                                      */
/*      return the distance between two points.                         */
/************************************************************************/
function CWCGetDistance(x1, y1, x2, y2)
{
    var AB2 = Math.abs(x2 - x1) * Math.abs(x2 - x1);
    var AC2 = Math.abs(y2 - y1) * Math.abs(y2 - y1);

    var BC = Math.sqrt(AB2 + AC2);

    return BC;
}


/****************************************************************************
* Converts value from a specified unit to meter
*
* @param unit : should be a valid unit (0 to 5) see defintion of units at the
*               top of this file.
* @param value : value in the unit given as argument
*****************************************************************************/
function CWCConvertToMeter(unit, value)
{
    if (unit >=0 && unit <=5)
    {
      return (this.gaMeterPerUnit[unit] * value);
    }
    else
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("110", "Invalid unit"));

    return false;
}


/****************************************************************************
* Converts value from a meter to the specified unit
*
* @param unit : should be a valid unit (0 to 5) see defintion of units at the
*               top of this file.
* @param value : value in the meter
*****************************************************************************/
function CWCConvertFromMeter(unit, value)
{
    if (unit >=0 && unit <=5)
    {
        return (this.gaUnitPerMeter[unit] * value);
    }
    else
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("110", "Invalid unit"));

    return false;
}


/************************************************************************/
/*                             CWCGetUnitIndice                         */
/*                                                                      */
/*      return the indice of the unit (indice will be used in the       */
/*      glabal arrays gaUnitPerMeter and gaMeterPerUnit) based on       */
/*      the unit string.                                                */
/************************************************************************/
function CWCGetUnitIndice(unitsstr)
{
    if (unitsstr == "INCHES")
    {
        return this.CWCINCHES;
    }
    else if (unitsstr == "FEET")
    {
        return this.CWCFEET;
    }
    else if (unitsstr == "MILES")
    {
        return this.CWCMILES;
    }
    else if (unitsstr == "METERS")
    {
        return this.CWCMETERS;
    }
    else if (unitsstr == "KILOMETERS")
    {
        return this.CWCKILOMETERS;
    }
    else if (unitsstr == "DEGREES")
    {
        return this.CWCDEGREES;
    }
    else if (unitsstr == "PIXELS")
    {
        return this.PIXELS;
    }
    else
    {
        return -1;
    }
}


/************************************************************************/
/*                             CWCGetUnitString                         */
/*                                                                      */
/*      return the string corresponding to the unit id.                 */
/************************************************************************/
function CWCGetUnitString(unit)
{
    if (unit == 0)
    {
        return "INCHES";
    }
    else if (unit == 1)
    {
        return "FEET";
    }
    else if (unit == 2)
    {
        return "MILES";
    }
    else if (unit == 3)
    {
        return "METERS";
    }
    else if (unit == 4)
    {
        return "KILOMETERS";
    }
    else if (unit == 5)
    {
        return "DEGREES";
    }
    else if (unit == 6)
    {
        return "PIXELS";
    }
    else
    {
        return "";
    }
}

/************************************************************************/
/*               CWCConvertUnit(inunitstr, outunitstr, value)            */
/*                                                                      */
/*      Converts from input unit to outpput unit. input and output      */
/*      unit should be "INCHES", "FEET", "MILES", "METERS",             */
/*      "KILOMETERS", "DEGREES".                                        */
/************************************************************************/
function CWCConvertUnit(inunitstr, outunitstr, value)
{
    inunit = this.GetUnitIndice(inunitstr);
    outunit = this.GetUnitIndice(outunitstr);

    if (inunit >=0 && inunit <=5 && outunit >=0 && outunit <=5)
    {
        tmpvalue = this.ConvertToMeter(inunit, value);
        returnvalue =  this.ConvertFromMeter(outunit, tmpvalue);
        return returnvalue;
    }

    return false;
}

/************************************************************************/
/*                              CWCAddNewLayer                          */
/*                                                                      */
/*      Create a new layer of a specified type.                         */
/*      name : the name of the layer                                    */
/*      type : POINT or LINE                                            */
/************************************************************************/
function CWCCreateNewLayer(name, type)
{
    if (type != "POINT" && type != "LINE")
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
                                              this.oApplication.oMLT.Get("115", "Invalid layer type"));
        return false;
    }

    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(3);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "CREATE_NEW_LAYER";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "NAME";
    aHiddenVars[1][1] = name;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "TYPE";
    aHiddenVars[2][1] = type;

    szOnLoad = 'goCWCJSAPI.NewLayerAdded()';

    this.oApplication.CallServer(szOnLoad, aHiddenVars);

     return true;
}

/************************************************************************/
/*                              CWCSetExtents                           */
/*                                                                      */
/*      Set the map extsnts. Coordinates are in map units.              */
/************************************************************************/
function CWCSetExtents(xmin, ymin, xmax, ymax)
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(3);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "NAV_CMD";
    aHiddenVars[0][1] = "ZOOM_BBOX";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "NAV_INPUT_TYPE";
    aHiddenVars[1][1] = "RECTANGLE";

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "NAV_INPUT_COORDINATES";
    aHiddenVars[2][1] = ""+xmin+","+ymin+","+xmax+","+ymax;


    szOnLoad = 'goCWCJSAPI.MapExtentsUpdated()';
    this.oApplication.CallServer(szOnLoad, aHiddenVars);

     return true;
}


/* ==================================================================== */
/*      Prototypes of the map object.                                   */
/* ==================================================================== */
CWCMapObject.prototype.AddLayer = CWCAddLayer; //private
CWCMapObject.prototype.GetLayer = CWCGetLayerByIndice;
CWCMapObject.prototype.GetLayerByName = CWCGetLayerByName;

CWCMapObject.prototype.AddWMSLayer = CWCAddWMSLayerMap;
CWCMapObject.prototype.AddGridLayer = CWCAddGridLayer;
CWCMapObject.prototype.CreateNewLayer = CWCCreateNewLayer;


CWCMapObject.prototype.GetProjection = CWCGetProjection;
CWCMapObject.prototype.SetProjection = CWCSetProjection; //private?
CWCMapObject.prototype.ChangeProjection = CWCChangeProjection;
CWCMapObject.prototype.ReprojectPoint = CWCReprojectPoint;

CWCMapObject.prototype.SetZoomFactor = CWCSetZoomFactor;
CWCMapObject.prototype.ZoomIn = CWCZoomIn;
CWCMapObject.prototype.ZoomOut = CWCZoomOut;
CWCMapObject.prototype.ZoomInPos = CWCZoomInPix;
CWCMapObject.prototype.ZoomOutPos = CWCZoomOutPix;
CWCMapObject.prototype.ZoomRect = CWCZoomRectPix;
CWCMapObject.prototype.ZoomFull = CWCZoomFull;
CWCMapObject.prototype.ZoomScale = CWCZoomScale;
CWCMapObject.prototype.Recenter = CWCRecenterPix;

CWCMapObject.prototype.SetExtents = CWCSetExtents;

CWCMapObject.prototype.Refresh = CWCRefresh;

CWCMapObject.prototype.SetViewSize = CWCSetViewSize;

CWCMapObject.prototype.SetLayerDrawingOrder = CWCSetLayerDrawingOrder;
CWCMapObject.prototype.GetLayerDrawingOrder = CWCGetLayerDrawingOrder;

CWCMapObject.prototype.AddPointWidget = CWCAddPointWidget; //private
CWCMapObject.prototype.AddRectangleWidget = CWCAddRectangleWidget; //private


CWCMapObject.prototype.AddPoint = CWCAddPoint;
CWCMapObject.prototype.AddRectangle = CWCAddRectangle;

CWCMapObject.prototype.Geo2Pix = CWCGeo2Pix;
CWCMapObject.prototype.Pix2Geo = CWCPix2Geo;

CWCMapObject.prototype.GetDistance = CWCGetDistance;

CWCMapObject.prototype.ConvertUnit = CWCConvertUnit;
CWCMapObject.prototype.ConvertFromMeter = CWCConvertFromMeter; //private
CWCMapObject.prototype.ConvertToMeter = CWCConvertToMeter; //private
CWCMapObject.prototype.GetUnitIndice = CWCGetUnitIndice; //private
CWCMapObject.prototype.GetUnitString = CWCGetUnitString; //private

/* ==================================================================== */
/*      End of Prototypes of the map object.                            */
/* ==================================================================== */


/************************************************************************/
/*                        CWCMLTObject constructor.                     */
/************************************************************************/
function CWCMLTObject(oApp)
{
    this.oApplication = oApp;

    this.aszMLT = new Array();
    this.szLanguage = "";
}

function CWCGet(nId, szDefault)
{
    if (this.aszMLT[nId] != null)
        return this.aszMLT[nId];
    else
        return szDefault;
}

function CWCSetLanguage(szTmpLanguage)
{
    if (szTmpLanguage != this.szLanguage)
    {
        this.szLanguage = szTmpLanguage;

        return this.LoadResource();
    }

    return true;
}

function CWCLoadResource()
{
    if (this.szLanguage != "")
    {
        aHiddenVars = new Array(1);
        aHiddenVars[0] = new Array(2);
        aHiddenVars[0][0] =  "LOAD_RESOURCE";
        aHiddenVars[0][1] = ""+this.szLanguage+"";

        szOnLoad = 'goCWCJSAPI.ResourceLoaded()';

        this.oApplication.CallServer(szOnLoad, aHiddenVars);

        return true;
    }
    else
    {
        this.oApplication.oErrorManager.Error(ERR_WARNING,
            this.oApplication.oMLT.Get("113", "Can't load resource. Invalid language"));

        return false;
    }
}

/************************************************************************/
/*                          CWCResourceLoaded                           */
/*                                                                      */
/*      Called after resource was loaded.                               */
/************************************************************************/
function CWCResourceLoaded()
{
    var doc = this.GetDocumentObject();

    if (doc.forms[0].NB_RESOURCE != null)
    {
        // loop all resource
        for (x=0;x<doc.forms[0].NB_RESOURCE.value;x++)
        {
            eval('nID=doc.forms[0].RESOURCE_ID_'+x+'.value;');
            eval('this.oMLT.aszMLT['+nID+']=doc.forms[0].RESOURCE_TXT_'+x+'.value;');
        }
    }
    return true;
}

/* ==================================================================== */
/*      Prototypes of the MLT object.                                   */
/* ==================================================================== */
CWCMLTObject.prototype.Get = CWCGet;
CWCMLTObject.prototype.LoadResource = CWCLoadResource;
CWCMLTObject.prototype.SetLanguage = CWCSetLanguage;

// Error type definitions
var ERR_FIRST = 0;
var ERR_NEXT = 0;
var ERR_NOTICE   = ERR_NEXT++;
var ERR_WARNING  = ERR_NEXT++;
var ERR_CRITICAL = ERR_NEXT++;
var ERR_FILE_IO  = ERR_NEXT++;

/************************************************************************/
/*                        CWCErrorManagerObject constructor.            */
/************************************************************************/
function CWCErrorManagerObject(oApp)
{
    this.oApplication = oApp;

    this.aError = new Array();
    this.nbError = 0;
}

function CWCError(nId, szError)
{
    this.aError[this.nbError] = new Array(nId, szError);
    this.nbError++;
    this.oApplication.TriggerEvent( ERROR_OCCURRED );
    return true;
}

function CWCPopLastError()
{
    if (this.nbError > 0)
    {
        this.nbError--;
        return this.aError[this.nbError];
    }
    else
        return false
}


/************************************************************************/
/*                            CWCGetServerErrors                        */
/*                                                                      */
/*      retreive errors from server. Called from the                    */
/*      map/keymap/scalebar widgets after the draw has been done.       */
/************************************************************************/
function CWCGetServerErrors()
{

    aHiddenVars = new Array(1);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] = "LOAD_SERVER_ERROR";
    aHiddenVars[0][1] = "1";

    szOnLoad = 'goCWCJSAPI.ServerErrorsLoaded()';

    this.oApplication.CallServer(szOnLoad, aHiddenVars);

    return true;
}

/************************************************************************/
/*                          CWCServerErrorsLoaded                       */
/*                                                                      */
/*      Called after server errors was loaded.                          */
/************************************************************************/
function CWCServerErrorsLoaded()
{
    var doc = this.GetDocumentObject();

    if (doc.forms[0].NB_ERROR != null)
    {
        // loop all errors
        for (x=0;x<doc.forms[0].NB_ERROR.value;x++)
        {
            eval('this.oErrorManager.aError['+x+'] = new Array(doc.forms[0].ERROR_ID_'+x+'.value, doc.forms[0].ERROR_TXT_'+x+'.value);');
        }
        this.TriggerEvent( ERROR_OCCURRED );
    }
    return true;
}

/* ==================================================================== */
/*      Prototypes of the ErrorManager object.                          */
/* ==================================================================== */
CWCErrorManagerObject.prototype.Error = CWCError;
CWCErrorManagerObject.prototype.PopLastError = CWCPopLastError;
CWCErrorManagerObject.prototype.GetServerErrors = CWCGetServerErrors;


/***********************************************************************
 * REGISTER EVENTS HERE.  MAKE SURE THAT YOU DEFINE YOUR EVENT AS A
 * JAVASCRIPT VARIABLE AND ASSIGN IT THE VALUE OF gnLastEventId AND THEN
 * INCREMENT gnLastEventId
 **********************************************************************/

gnLastEventId = 0;

MAP_EXTENT_CHANGED = gnLastEventId ++;
MAP_PROJECTION_CHANGED = gnLastEventId ++;
MAP_NEW_LAYER_ADDED = gnLastEventId ++;
MAP_NEW_ELEMENT_ADDED =  gnLastEventId ++;

LAYER_STATUS_CHANGED = gnLastEventId ++;
LAYER_STYLE_CHANGED = gnLastEventId ++;
LAYER_ORDER_CHANGED = gnLastEventId ++;


MOUSE_CLICKED =  gnLastEventId ++;

ERROR_OCCURRED = gnLastEventId ++;

/************************************************************************/
/*                       CWCApplication constructor.                    */
/************************************************************************/
function CWCApplication()
{
    this.oMap = new CWCMapObject(this);
    this.oMLT = new CWCMLTObject(this);
    this.oErrorManager = new CWCErrorManagerObject(this);

    //browser settings
    this.bNetscape4 = 0;
    this.bNetscape6 = 0;
    this.bIE = 0;

    this.aCallStack = new Array();
    this.nCallStackLength = 0;
    this.nCallStackPos = 0;
    this.bCall = false;

    if (navigator.appName == "Netscape")
    {
        if (navigator.appVersion[0] <= 4)
        {
            this.bNetscape4 = 1;
        }
        else
        {
            this.bNetscape6 =1;
        }
    }
    else if (navigator.appName == "Microsoft Internet Explorer")
    {
        this.bIE = 1;
    }
    else
        this.oErrorManager.Error(ERR_WARNING,
            this.oMLT.Get("114", "Browser not supported"));

/* ==================================================================== */
/*      a special flag used by Netscape 4 to create the Layer object    */
/*      the first time the GetDocuemntObject is called.                 */
/*                                                                      */
/* ==================================================================== */
    this.bFirstCallToContainer = true;

    //session id;
    this.sid = "";

    //doument form
    this.form = "document.forms[0]"; //TODO set for js api.

    //Navigation variables
    this.NAV_CMD = "";
    this.NAV_INPUT_COORDINATES = "";
    this.NAV_INPUT_TYPE = "";

    //Zoom scale
    this.SCALE_ZOOM = "";

    //compass panning
    this.NAV_PAN = "";

    //quickzoom
    this.NAV_QUICKZOOM = "";

    //mouse click position
    this.mouseclick = new Array(2);
    this.mouseclick[0] = 0;
    this.mouseclick[1] = 0;


    //layer status changed tracker.
    this.LAYER_STATUS_MODIFIED = false;

    //layer style changed tracker.
    this.LAYER_STYLE_MODIFIED = false;

    //layer order changed tracker.
    this.LAYER_ORDER_MODIFIED = false;

    //event registering functions
    this.CWCEvents = new Array();
    for (i=0; i<gnLastEventId; i++)
    {
        this.CWCEvents[i] = new Array();
    }

    //container that have the invisible layer or frame used to
    //communicate with the server.
    this.szContainerName = "";
    this.oContainer = "";

    //this is the URL that points to the directory that UpdateMap.php is in
    this.szURL = "";

    //variables use by netscape4
    this.bDebug = false;
    this.szLanguage = "";

/* -------------------------------------------------------------------- */
/*      properties. Initalized from cwcjsapi.widget.php.                */
/* -------------------------------------------------------------------- */
    this.aProperties = "";
}


/************************************************************************/
/*                              CWCGetProperty                          */
/*                                                                      */
/*      return the value of the property passes as argument.            */
/************************************************************************/
function CWCGetProperty(szProperty)
{
    var szValue = false;
    if (szProperty != null && szProperty != "" && this.aProperties != "" && 
        this.aProperties.length > 0)
    {
        var szTmp = szProperty.toLowerCase(szProperty);
        var nProperties = this.aProperties.length;
        for (i=0; i<nProperties; i++)
        {
            if ( this.aProperties[i][0] == szTmp)
            {
                szValue = this.aProperties[i][1];
                break;
            }
        }
    }
    return szValue;
}



/************************************************************************/
/*                             CWCMouseClicked                          */
/*                                                                      */
/*      Called map the mapdhtml when the user clicks on the map.        */
/************************************************************************/
function CWCMouseClicked(x,y)
{
    //alert("CWCMouseClicked");
    this.mouseclick[0] = x;
    this.mouseclick[1] =y;

    this.TriggerEvent(MOUSE_CLICKED);
    return true;
}


/************************************************************************/
/*                             CWCRegisterEvent                         */
/************************************************************************/
function CWCRegisterEvent(event, function_name)
{
    lastEvent = (this.CWCEvents[event]).length;
    this.CWCEvents[ event ][ lastEvent ] = function_name;
    return true;
}

function CWCDeregisterEvent( event, function_name )
{
    bFound = false;
    events = this.CWCEvents[event];
    for( i=0; i<events.length; i++ )
    {
        if (this.CWCEvents[event][i] == function_name )
        {
            this.CWCEvents[event][i] = "";
            bFound = true;
        }
    }
    return  bFound;
}

function CWCTriggerEvent( event )
{
    var i = 0;
    var nEvents = (this.CWCEvents[ event ]).length;
    for (i=0; i<nEvents; i++)
    {
        szFunction =  this.CWCEvents[ event ][ i ];
        if (szFunction != "")
        {
            szFunction = szFunction + '()';
            eval(szFunction);
        }
    }
    return true;
}


function CWCAddWMSLayerApp(name, title, srs, connection, version, format)
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(7);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "ADD_NEW_WMS_LAYER";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "LAYER_NAME";
    aHiddenVars[1][1] = name;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "LAYER_TITLE";
    aHiddenVars[2][1] = escape(title);

    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "LAYER_SRS";
    aHiddenVars[3][1] = srs;

    aHiddenVars[4] = new Array(2);
    aHiddenVars[4][0] =  "LAYER_CONNECTION";
    aHiddenVars[4][1] = connection;

    aHiddenVars[5] = new Array(2);
    aHiddenVars[5][0] =  "LAYER_VERSION";
    aHiddenVars[5][1] = version;

    aHiddenVars[6] = new Array(2);
    aHiddenVars[6][0] =  "LAYER_FORMAT";
    aHiddenVars[6][1] = format;

    szOnLoad = 'goCWCJSAPI.NewLayerAdded()';

    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}



/************************************************************************/
/*                             CWCNewLayerAdded                         */
/*                                                                      */
/*      Called after a new wms layer was added.                         */
/*      Updates the internal map object with the new layer.             */
/************************************************************************/
function CWCNewLayerAdded()
{
    var doc = this.GetDocumentObject();

    if (doc.forms[0].LAYER_NAME != null)
    {
        this.oMap.AddLayer(doc.forms[0].LAYER_NAME.value);
        oLayer = this.oMap.GetLayer(this.oMap.numlayers -1);
        oLayer.index = doc.forms[0].LAYER_INDEX.value;
        oLayer.status = doc.forms[0].LAYER_STATUS.value;
        oLayer.type = doc.forms[0].LAYER_TYPE.value;
        oLayer.title = doc.forms[0].LAYER_TITLE.value;
        oLayer.connection = doc.forms[0].LAYER_CONNECTION.value;
        oLayer.connectiontype = doc.forms[0].LAYER_CONNECTIONTYPE.value;
        oLayer.onlineresource = doc.forms[0].LAYER_ONLINERESOURCE.value;
        oLayer.srs = doc.forms[0].LAYER_SRS.value;
        oLayer.version = doc.forms[0].LAYER_VERSION.value;
        oLayer.format = doc.forms[0].LAYER_FORMAT.value;
        oLayer.formatlist = doc.forms[0].LAYER_FORMATLIST.value;
        oLayer.style = doc.forms[0].LAYER_STYLE.value;
        oLayer.stylelist = doc.forms[0].LAYER_STYLELIST.value;

/* -------------------------------------------------------------------- */
/*      flag used to indicate a vector layer create by                  */
/*      CWCJSAPI. These layers are the only ones valid                  */
/*      for adding points or lines.                                     */
/* -------------------------------------------------------------------- */
        oLayer.bCWCLayer = 1;

        this.TriggerEvent(MAP_NEW_LAYER_ADDED);
    }
    return true;

}


/************************************************************************/
/*                              CWCAddPointWigdteApp                    */
/************************************************************************/
function CWCAddPointWidgetApp(x,y,szLabel,szUnit, bAddElement, bZoomTo)
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(6);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "ADD_POINT_WIDGET";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "LOCATE_LATLONG";
    aHiddenVars[1][1] = ""+szLabel+"|"+x+","+y;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "LOCATE_ADD_ELEMENT";
    aHiddenVars[2][1] = bAddElement;

    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "LOCATE_COORD_UNIT";
    aHiddenVars[3][1] = szUnit;

    aHiddenVars[4] = new Array(2);
    aHiddenVars[4][0] =  "LOCATE_ELEMENT_TYPE";
    aHiddenVars[4][1] = "POINT";

    aHiddenVars[5] = new Array(2);
    aHiddenVars[5][0] =  "LOCATE_ZOOM_TO";
    aHiddenVars[5][1] = bZoomTo;

    szOnLoad = 'goCWCJSAPI.NewElementAdded()';
    if (bZoomTo)
    {
        szOnLoad += ";goCWCJSAPI.MapExtentsUpdated()";
    }
    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}

/************************************************************************/
/*                              CWCAddRectangleWidgetApp                */
/************************************************************************/
function CWCAddRectangleWidgetApp(x1,y1,x2,y2,szLabel,szUnit, bAddElement, bZoomTo)
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(6);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "ADD_RECTANGLE_WIDGET";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "LOCATE_LATLONG";
    aHiddenVars[1][1] = ""+szLabel+"|"+x1+","+y1+";"+x2+","+y2;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "LOCATE_ADD_ELEMENT";
    aHiddenVars[2][1] = bAddElement;

    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "LOCATE_COORD_UNIT";
    aHiddenVars[3][1] = szUnit;

    aHiddenVars[4] = new Array(2);
    aHiddenVars[4][0] =  "LOCATE_ELEMENT_TYPE";
    aHiddenVars[4][1] = "RECTANGLE";

    aHiddenVars[5] = new Array(2);
    aHiddenVars[5][0] =  "LOCATE_ZOOM_TO";
    aHiddenVars[5][1] = bZoomTo;

    szOnLoad = 'goCWCJSAPI.NewElementAdded()';
    if (bZoomTo)
    {
        szOnLoad += ";goCWCJSAPI.MapExtentsUpdated()";
    }
    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}


/************************************************************************/
/*                             CWNewElementAdded                        */
/*                                                                      */
/*      Generates an event when a new point or line is added.           */
/************************************************************************/
function CWNewElementAdded()
{
     this.TriggerEvent(MAP_NEW_ELEMENT_ADDED);
     return true;
}

function CWCJSAPIContainerSetVisibility(vis)
{

  if (this.bNetscape4)
    this.oContainer.visibility = (vis)? 'show' : 'hidden';
  else if (this.bIE)
  {
      document.all(this.szContainerName ).style.display = (vis)? '' : 'none';
  }
  else if (this.bNetscape6)
  {
      document.getElementById(this.szContainerName).style.visibility = (vis)? '' : 'hidden';
      this.oContainer.width = (vis)? 250 : 0;
      this.oContainer.height = (vis)? 100 : 0;
  }
  return true;
}


/************************************************************************/
/*                           CWCCreateDHTMLLayer                        */
/*                                                                      */
/*      Create a dhml layer : used only for netscape 4.                 */
/************************************************************************/
function CWCCreateDHTMLLayer()
{
    oLayer = new Layer(100);
    this.oContainer = oLayer;
    if (this.bDebug == true)
    {
        oLayer.visibility = 'show';
    }
    else
    {
        oLayer.visibility = 'hide';
    }
    return true;
}
/************************************************************************/
/*                           CWCGetDocumentObject                       */
/*                                                                      */
/*      return the document object.                                     */
/************************************************************************/
function CWCGetDocumentObject()
{
    //alert("CWCGetDocumentObject");
    if (this.bIE)
      return this.oContainer.document;
    else if (this.bNetscape6)
      return this.oContainer.contentDocument;
    else if (this.bNetscape4)
    {
        if (this.bFirstCallToContainer == true)
        {
            this.bFirstCallToContainer = false;

            //this.oContainer = new Layer(100);
            this.CreateDHTMLLayer();
            //alert("CreateCWCLayer call in CWCGetDocumentObject");
            //this.oContainer.name = "CWCJSAPILayer";
            this.oMLT.SetLanguage(this.szLanguage);
        }
        return this.oContainer.document;
    }
    else
        return null;
}

/************************************************************************/
/*                      CWCUpdateExtentsFromContainer                   */
/*                                                                      */
/*      Update the extents in the jsapi using values from the container.*/
/************************************************************************/
function CWCUpdateExtentsFromContainer()
{
    var doc = this.GetDocumentObject();//(this.bIE ) ? this.oContainer.document : this.oContainer.contentDocument;
    if(doc.forms[0].MAP_EXTENT_MINX)
    {
        this.oMap.minx = doc.forms[0].MAP_EXTENT_MINX.value;
        this.oMap.miny = doc.forms[0].MAP_EXTENT_MINY.value;
        this.oMap.maxx = doc.forms[0].MAP_EXTENT_MAXX.value;
        this.oMap.maxy = doc.forms[0].MAP_EXTENT_MAXY.value;
    }
    if (doc.forms[0].MAP_SCALE != null)
    {
         this.oMap.scale = doc.forms[0].MAP_SCALE.value;
    }
    if (doc.forms[0].MAP_CELLSIZE != null)
      this.oMap.cellsize = doc.forms[0].MAP_CELLSIZE.value;

    if (doc.forms[0].MAP_WIDTH != null)
      this.oMap.width = doc.forms[0].MAP_WIDTH.value;
    if (doc.forms[0].MAP_HEIGHT != null)
      this.oMap.height = doc.forms[0].MAP_HEIGHT.value;

    return true;
}

/************************************************************************/
/*                           CWCMapExtentsUpdated                       */
/************************************************************************/
function CWCMapExtentsUpdated()
{
    this.UpdateExtentsFromContainer();
    this.TriggerEvent( MAP_EXTENT_CHANGED );
    return true;
}



/************************************************************************/
/*                                CWCUpdate                             */
/*                                                                      */
/*      Use the dynamic html to set the action and forms varaibales     */
/*      and submit the page.                                            */
/************************************************************************/
function CWCUpdateNavTools()
{
  
    if (this.NAV_CMD == "PAN_MAP")
    {
        CWCDHTML_HideLayer("MapLayerDiv");
    }
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(4);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "NAV_CMD";
    aHiddenVars[0][1] = this.NAV_CMD;

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "NAV_INPUT_COORDINATES";
    aHiddenVars[1][1] = this.NAV_INPUT_COORDINATES;

    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "NAV_INPUT_TYPE";
    aHiddenVars[2][1] = this.NAV_INPUT_TYPE;

    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "ZOOMFACTOR";
    aHiddenVars[3][1] = this.oMap.zoomfactor;

    szOnLoad = 'goCWCJSAPI.MapExtentsUpdated()';

    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}

/************************************************************************/
/*                              CWCCallServer                           */
/************************************************************************/
function CWCCallServer(szOnLoad, aHiddenVars)
{
    //alert(szOnLoad);
    this.aCallStack[this.nCallStackLength] = new Array(szOnLoad, aHiddenVars);
    this.nCallStackLength++;

    if (this.nCallStackLength == 1)
    {
        this.CallServerFromStack();
    }
    return true;
}

/************************************************************************/
/*                              CWCCallServerFromStack                  */
/************************************************************************/
function CWCCallServerFromStack()
{
    //alert("CWCCallServerFromStack");

    szOnLoad = this.aCallStack[this.nCallStackPos][0];
    aHiddenVars = this.aCallStack[this.nCallStackPos][1];

    var d = new Date();
    var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
    var szURL = this.szURL + "UpdateMap.php?sid=" + this.sid;

    if (this.bIE == 1 || this.bNetscape6 == 1)
    {
        var doc = this.GetDocumentObject();//(this.bIE ) ? this.oContainer.document : this.oContainer.contentDocument;

    // init var for syncron call
        this.bLoaded = false;

        doc.open();
        doc.write('<html><body>');
        doc.write('<form name="myform" method="post" target="" ');
        doc.write(' action="' + szURL + '&U=' + unique + '">');

        //szHidden for debugging
        //szHidden = "";
        if (aHiddenVars != "")
        {
            nHidden = aHiddenVars.length;
            for (i=0; i<nHidden; i++)
            {
                //szHidden for debugging
                //szHidden += '<input type="hidden" name="'+aHiddenVars[i][0]+'" value="' + aHiddenVars[i][1] + '">';
                doc.write('<input type="hidden" name="'+aHiddenVars[i][0]+'" value="' + aHiddenVars[i][1] + '">');
            }
        }

        //onload function to call
        if (szOnLoad != "")
        {
            doc.write('<input type="hidden" name="ONLOAD_FUNCTION" value= "'+szOnLoad+'">');
        }

        doc.write('</form></body></html>');
        doc.close();
        //szHidden for debugging
        //alert(szHidden);

        doc.forms['myform'].submit();
    }
    else if (this.bNetscape4 == 1)
    {
        //alert("CWCCallServerFromStack : netscape4");

        szURL += '&NETSCAPE4=1&U=' + unique;
        if (szOnLoad != "")
        {
            szURL += '&ONLOAD_FUNCTION=' + szOnLoad;
        }
        if (aHiddenVars != "")
        {
            nHidden = aHiddenVars.length;
            for (i=0; i<nHidden; i++)
            {
                szURL += '&' + aHiddenVars[i][0] + "=" + aHiddenVars[i][1];
            }
        }
        //ttt = "url = " + szURL;
        //alert(ttt);

        oLayer = this.GetDocumentObject();
        oLayer = this.oContainer;
        oLayer.src = szURL;

    }

    return true;
}

function CWCCheckCallStack()
{
    this.nCallStackPos++;

    if (this.nCallStackPos < this.nCallStackLength)
    {
        this.CallServerFromStack();
    }
    else
    {
        this.nCallStackPos = 0;
        this.nCallStackLength = 0;
    }
    return true;
}

/************************************************************************/
/*                            UpdateNavQuickZoom                        */
/*                                                                      */
/*      Quick zoom update.                                              */
/************************************************************************/
function CWCUpdateNavQuickZoom()
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(1);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "NAV_QUICKZOOM";
    aHiddenVars[0][1] = this.NAV_QUICKZOOM;

    this.CallServer("goCWCJSAPI.MapExtentsUpdated()", aHiddenVars);
    return true;
}

/************************************************************************/
/*                            CWCUpdateScaleZoom                        */
/*                                                                      */
/*      Calls UpdateMap when for zooming using a scale value.           */
/************************************************************************/
function CWCUpdateScaleZoom()
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(2);

    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "NAV_CMD";
    aHiddenVars[0][1] = "SCALE_ZOOM";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "SCALE_ZOOM";
    aHiddenVars[1][1] = this.SCALE_ZOOM;

    szOnLoad = 'goCWCJSAPI.MapExtentsUpdated()';

    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}

/************************************************************************/
/*                    CWCUpdateExpressionBuilder                        */
/*                                                                      */
/*      Calls UpdateMap when applying an expression.                    */
/************************************************************************/
function CWCUpdateExpressionBuilder( szFilter, nLayerIndex, szExpressions,
         nApplyToMap, szSLDName, szWFSConnection, szLayerType, szSLDFile  )
{
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(1);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "WFS_FILTER";
    aHiddenVars[0][1] = szFilter;
    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "WFS_FILTER_LAYER_INDEX";
    aHiddenVars[1][1] = nLayerIndex; 
    aHiddenVars[2] = new Array(2);
    aHiddenVars[2][0] =  "WFS_FILTER_EXPRESSIONLIST";
    aHiddenVars[2][1] = szExpressions;
    aHiddenVars[3] = new Array(2);
    aHiddenVars[3][0] =  "WFS_FILTER_APPLYTOMAP";
    aHiddenVars[3][1] = nApplyToMap;
    aHiddenVars[4] = new Array(2);
    aHiddenVars[4][0] =  "WFS_FILTER_SLD";
    aHiddenVars[4][1] = szSLDName;
    aHiddenVars[5] = new Array(2);
    aHiddenVars[5][0] =  "WFS_FILTER_CONNECTION";
    aHiddenVars[5][1] = szWFSConnection;
    aHiddenVars[6] = new Array(2);
    aHiddenVars[6][0] =  "WFS_FILTER_LAYERTYPE";
    aHiddenVars[6][1] = szLayerType;
    aHiddenVars[7] = new Array(2);
    aHiddenVars[7][0] =  "WFS_APPLY_EXPRESSIONLIST";
    aHiddenVars[7][1] = "1";
    aHiddenVars[8] = new Array(2);
    aHiddenVars[8][0] =  "WFS_FILTER_SLD_FILE";
    aHiddenVars[8][1] = szSLDFile;    
   
    szOnLoad = 'goCWCJSAPI.MapExtentsUpdated()';
    this.CallServer(szOnLoad, aHiddenVars);

    return true;
}

/************************************************************************/
/*                            CWCUpdateCompassPan                       */
/*                                                                      */
/*      Calls UpdateMap when panning                        .           */
/************************************************************************/
function CWCUpdateCompassPan()
{
    //alert("CWCUpdateCompassPan");
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(1);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "NAV_PAN";
    aHiddenVars[0][1] = this.NAV_PAN;

    szOnLoad = 'goCWCJSAPI.MapExtentsUpdated()';

    this.CallServer(szOnLoad, aHiddenVars);
    return true;

}

/************************************************************************/
/*                       CWCProcessLegendTemplate                       */
/*                                                                      */
/*      Calls UpdateMap to re-process the legend template.              */
/************************************************************************/
function CWCProcessLegendTemplate(nID)
{
    //alert(nID);
    CWCDHTML_ShowLayer("ActivityLayer");

    aHiddenVars = new Array(2);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "PROCESS_L_TEMPLATE";
    aHiddenVars[0][1] = "1";
    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "PROCESS_L_TEMPLATE_ID";
    aHiddenVars[1][1] = nID;

    szOnLoad = 'goCWCJSAPI.LegendTemplateProcessed()';

    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}

/************************************************************************/
/*                     CWCLegendTemplateProcessed                       */
/*                                                                      */
/*      Updates the hidden form variable to the results of the process  */
/*      legend template.                                                */
/************************************************************************/
function CWCLegendTemplateProcessed()
{
    var doc = this.GetDocumentObject();//(this.bIE ) ? this.oContainer.document : this.oContainer.contentDocument;
    if(doc.forms[0].UPDATE_LEGEND_TEMPLATE_RESULTS)
    {
        checkString = doc.forms[0].UPDATE_LEGEND_TEMPLATE_RESULTS.value;
        var newString = "";

        // loop through each letter
        for (var i = 0; i < checkString.length; i++)
        {
            // check for #!#, and #!!#
            if ( checkString.substr(i,3) == "#!#" )
            {
                newString = newString + "'";
                i = i + 2;
            }
            else
            {
                if ( checkString.substr(i,4) == "#!!#" )
                {
                    newString = newString + "\"";
                    i = i + 3;
                }
                else
                    newString = newString + checkString.substr(i,1);
            }
        }
	//alert( 'newstring:'+newString);
        // update the div tag
        this.GetDocumentDivObject("legendTemplateDiv").innerHTML =
                                            "<table>" + newString + "</table>";
    }
    return true;
}

/************************************************************************/
/*                        CWCGetDocumentDivObject                       */
/*                                                                      */
/*      This function returns the correct div object for the current    */
/*      browser.                                                        */
/************************************************************************/
function CWCGetDocumentDivObject( szDIVName )
{
    // return object based on browser and version
    if ( this.bNetscape4 == 1 )
        return document.layers[szDIVName];
    if ( this.bNetscape6 == 1 )
        return document.getElementById(szDIVName);
    if ( this.bIE == 1 )
        return document.all[szDIVName];

    // throw error
    this.oErrorManager.Error(ERR_WARNING,
                          this.oMLT.Get("114", "Browser not supported"));

    // return empty object
    return "";
}

/**
 * internal function to update the projection from a container
 */
function CWCUpdateProjectionFromContainer()
{
    var doc = this.GetDocumentObject();//(this.bIE ) ? this.oContainer.document : this.oContainer.contentDocument;
    if(doc.forms[0].MAP_PROJECTION)
    {
        this.oMap.projection = doc.forms[0].MAP_PROJECTION.value;
    }
    return true;
}

/**
 * the projection has been updated.  Get the values into the map object
 * and update all the event listeners
 */
function CWCProjectionUpdated()
{
    this.UpdateProjectionFromContainer();
    this.TriggerEvent( MAP_PROJECTION_CHANGED );
    this.MapExtentsUpdated();
    return true;
}

/**
 * update the projection
 */
function CWCUpdateProjection()
{
    CWCDHTML_ShowLayer("ActivityLayer");


    aHiddenVars = new Array(1);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "MAP_PROJECTION";
    aHiddenVars[0][1] = this.oMap.projection;

    szOnLoad = 'goCWCJSAPI.ProjectionUpdated()';

    this.CallServer(szOnLoad, aHiddenVars);
    return true;
}


/************************************************************************/
/*                          CWCLayerStatusUpdated                       */
/*                                                                      */
/*      Trigger event for layer status changed. Called after a          */
/*      refrsh map is done.                                             */
/************************************************************************/
function CWCLayerStatusUpdated()
{
    //test for deleted layers
    aNewLayers = new Array();
    idx = 0;
    for (i=0; i<this.oMap.numlayers; i++)
    {
        if (this.oMap.aLayers[i].status != 4)
        {
            aNewLayers[idx] = this.oMap.aLayers[i];
            aNewLayers[idx].index = idx;
            idx ++;
        }
    }
    this.oMap.layerdrawingorder="";
    this.oMap.aLayers = aNewLayers;
    this.oMap.numlayers = this.oMap.aLayers.length;
    
    this.TriggerEvent(LAYER_STATUS_CHANGED);
    //reset the layer status tracker
    this.LAYER_STATUS_MODIFIED = false;
    return true;
}

/************************************************************************/
/*                          CWCLayerStyleUpdated                        */
/*                                                                      */
/*      Trigger event for layer style changed. Called after a           */
/*      refrsh map is done.                                             */
/************************************************************************/
function CWCLayerStyleUpdated()
{
    this.TriggerEvent(LAYER_STYLE_CHANGED);
    //reset the layer status tracker
    this.LAYER_STYLE_MODIFIED = false;
    return true;
}

/************************************************************************/
/*                          CWCLayerOrderUpdated                        */
/*                                                                      */
/*      Trigger event for layer drawing order is changed. Called after a*/
/*      refrsh map is done.                                             */
/************************************************************************/
function CWCLayerOrderUpdated()
{
/* ==================================================================== */
/*      If the layer order is updated, we have to sync the layers in    */
/*      the jsapi which the map on the server. (using the session,      */
/*      the temporary map file saved on the server was saved with       */
/*      the new layer order).                                           */
/* ==================================================================== */
    aOrder = this.oMap.layerdrawingorder.split(",");
    if (aOrder.length == this.oMap.numlayers)
    {
        //alert ("CWCLayerOrderUpdated");
        //alert( this.oMap.layerdrawingorder);
        aNewLayerArray = new Array(this.oMap.numlayers);
        for (i=0; i<this.oMap.numlayers; i++)
        {
            aNewLayerArray[i] = this.oMap.aLayers[aOrder[i]];
            aNewLayerArray[i].index = i;
        }
        
        this.oMap.aLayers = aNewLayerArray;
    }
    
    this.TriggerEvent(LAYER_ORDER_CHANGED);
    //reset the layer oder tracker
    this.oMap.layerdrawingorder="";
    this.LAYER_ORDER_MODIFIED = false;
    return true;
}


/************************************************************************/
/*                              CWCRefreshMap                           */
/*                                                                      */
/*      Used to update on the server layer status, layer                */
/*      styles(TODO).                                                   */
/************************************************************************/
function CWCRefreshMap()
{
    if (this.LAYER_STATUS_MODIFIED == true || this.LAYER_ORDER_MODIFIED == true ||
        this.LAYER_STYLE_MODIFIED == true )
    {
        CWCDHTML_ShowLayer("ActivityLayer");

        var iParams = 0;
        if (this.LAYER_STATUS_MODIFIED == true)
        {
            iParams++; //for "LAYER_STATUS_CHANGED
            iParams += this.oMap.numlayers; //each layer is sent in the url
        }
        if (this.LAYER_ORDER_MODIFIED == true )
        {
            iParams++; //for LAYER_ORDER_CHANGED
        }
        if (this.LAYER_STYLE_MODIFIED == true)
        {
            iParams++; //for LAYER_STYLE_CHANGED
             for (i=0; i<this.oMap.numlayers; i++)
             {
                 var oLayer = this.oMap.aLayers[i];
                 if (oLayer.style != "")
                 {
                     iParams++; //each layer that has a style is sent in the url
                 }
             }
        }
        aHiddenVars = new Array(iParams);

        iParams = 0;

        if (this.LAYER_STATUS_MODIFIED == true)
        {
            aHiddenVars[iParams] = new Array(2);
            aHiddenVars[iParams][0] =  "LAYER_STATUS_CHANGED";
            aHiddenVars[iParams][1] = "1";
            iParams++;
            for (i=0; i<this.oMap.numlayers; i++)
            {
                var oLayer = this.oMap.aLayers[i];
                aHiddenVars[iParams] = new Array(2);
                aHiddenVars[iParams][0] =  oLayer.name;
                aHiddenVars[iParams][1] = oLayer.status;
                iParams++;
            }
        }
        if (this.LAYER_ORDER_MODIFIED == true)
        {
            aHiddenVars[iParams] = new Array(2);
            aHiddenVars[iParams][0] =  "LAYER_ORDER_CHANGED";
            aHiddenVars[iParams][1] = this.oMap.layerdrawingorder;
            iParams++;
        }

        if (this.LAYER_STYLE_MODIFIED == true)
        {
            aHiddenVars[iParams] = new Array(2);
            aHiddenVars[iParams][0] =  "LAYER_STYLE_CHANGED";
            aHiddenVars[iParams][1] = "1";
            iParams++;
            for (i=0; i<this.oMap.numlayers; i++)
            {
                var oLayer = this.oMap.aLayers[i];
                if (oLayer.style != "")
                {
                    aHiddenVars[iParams] = new Array(2);
                    aHiddenVars[iParams][0] =  oLayer.name;
                    aHiddenVars[iParams][1] = escape(oLayer.style);
                    iParams++;
                }
            }
        }
        szOnLoadFunc = "";
        if (this.LAYER_STATUS_MODIFIED == true)
        {
            szOnLoadFunc += "goCWCJSAPI.LayerStatusUpdated();";
        }
        if (this.LAYER_ORDER_MODIFIED == true)
        {
            szOnLoadFunc += "goCWCJSAPI.LayerOrderUpdated();";
        }
        if (this.LAYER_STYLE_MODIFIED == true)
        {
            szOnLoadFunc += "goCWCJSAPI.LayerStyleUpdated();";
        }

        this.CallServer(szOnLoadFunc, aHiddenVars);
    }
    return true;
}


/************************************************************************/
/*                              CWCLoadContext                          */
/*                                                                      */
/*      Load a context. Submits the page.                               */
/************************************************************************/
function CWCLoadContext(szContext)
{
    if (szContext != "")
    {
        var szFormElement = ""+ this.form + ".CONTEXT.value = '" + szContext + "'";
        eval(szFormElement);

        szFormElement = ""+ this.form + ".submit()";
        eval(szFormElement);

        return true;
    }
    else
    {
        return false;
    }
}


/************************************************************************/
/*                             CWCContextSaved                          */
/*                                                                      */
/*      Called when the context has finished saving.                    */
/************************************************************************/
function CWCContextSaved()
{
    var doc = this.GetDocumentObject();

    if (doc.forms[0].FUNCTION_CALLBACK != null &&
        doc.forms[0].FILENAME != null)
    {
        eval(doc.forms[0].FUNCTION_CALLBACK.value+'("'+doc.forms[0].FILENAME.value+'");');
    }
}
        

/************************************************************************/
/*                              CWCSaveContext                          */
/*                                                                      */
/*      Save context and call the callback function passed as           */
/*      argument with the url to the file to download.                  */
/************************************************************************/
function CWCSaveContext(szCallBack)
{
    aHiddenVars = new Array(2);
    aHiddenVars[0] = new Array(2);
    aHiddenVars[0][0] =  "SAVE_CONTEXT";
    aHiddenVars[0][1] = "1";

    aHiddenVars[1] = new Array(2);
    aHiddenVars[1][0] =  "FUNCTION_CALLBACK";
    aHiddenVars[1][1] = szCallBack;
    
    szOnLoad = 'goCWCJSAPI.ContextSaved()';
    
    this.CallServer(szOnLoad, aHiddenVars);

    return true;
}
/* -------------------------------------------------------------------- */
/*      application class prototypes.                                   */
/* -------------------------------------------------------------------- */

CWCApplication.prototype.GetProperty = CWCGetProperty;

CWCApplication.prototype.RegisterEvent = CWCRegisterEvent;
CWCApplication.prototype.DeRegisterEvent = CWCDeregisterEvent;

CWCApplication.prototype.TriggerEvent = CWCTriggerEvent;

CWCApplication.prototype.MouseClicked = CWCMouseClicked;

CWCApplication.prototype.CallServer = CWCCallServer;
CWCApplication.prototype.CallServerFromStack = CWCCallServerFromStack;
CWCApplication.prototype.CheckCallStack = CWCCheckCallStack;
CWCApplication.prototype.UpdateNavTools = CWCUpdateNavTools;
CWCApplication.prototype.UpdateScaleZoom = CWCUpdateScaleZoom;
CWCApplication.prototype.UpdateCompassPan = CWCUpdateCompassPan;
CWCApplication.prototype.UpdateNavQuickZoom = CWCUpdateNavQuickZoom;

CWCApplication.prototype.RefreshMap = CWCRefreshMap;

CWCApplication.prototype.ZoomToScale = CWCZoomToScale;

CWCApplication.prototype.LayerStatusUpdated = CWCLayerStatusUpdated;
CWCApplication.prototype.LayerOrderUpdated = CWCLayerOrderUpdated;
CWCApplication.prototype.LayerStyleUpdated = CWCLayerStyleUpdated;

CWCApplication.prototype.AddWMSLayer = CWCAddWMSLayerApp;
CWCApplication.prototype.NewLayerAdded = CWCNewLayerAdded;

CWCApplication.prototype.AddPointWidget = CWCAddPointWidgetApp;
CWCApplication.prototype.AddRectangleWidget = CWCAddRectangleWidgetApp;
CWCApplication.prototype.NewElementAdded = CWNewElementAdded;

CWCApplication.prototype.MapExtentsUpdated = CWCMapExtentsUpdated;
CWCApplication.prototype.UpdateExtentsFromContainer = CWCUpdateExtentsFromContainer;

CWCApplication.prototype.ProcessLegendTemplate = CWCProcessLegendTemplate;
CWCApplication.prototype.LegendTemplateProcessed = CWCLegendTemplateProcessed;

CWCApplication.prototype.UpdateProjection = CWCUpdateProjection;
CWCApplication.prototype.ProjectionUpdated = CWCProjectionUpdated;
CWCApplication.prototype.UpdateProjectionFromContainer = CWCUpdateProjectionFromContainer;
CWCApplication.prototype.PointReprojected = CWCPointReprojected;

CWCApplication.prototype.ContainerSetVisibility = CWCJSAPIContainerSetVisibility;
CWCApplication.prototype.GetDocumentObject = CWCGetDocumentObject;
CWCApplication.prototype.GetDocumentDivObject = CWCGetDocumentDivObject;
CWCApplication.prototype.CreateDHTMLLayer = CWCCreateDHTMLLayer;


CWCApplication.prototype.ResourceLoaded = CWCResourceLoaded;
CWCApplication.prototype.ServerErrorsLoaded = CWCServerErrorsLoaded;

CWCApplication.prototype.LoadContext = CWCLoadContext;
CWCApplication.prototype.SaveContext = CWCSaveContext;
CWCApplication.prototype.ContextSaved = CWCContextSaved;

CWCApplication.prototype.UpdateExpressionBuilder = CWCUpdateExpressionBuilder;

