[fusion-commits] r2105 - in branches/fusion-2.0: . common/php docs layers layers/Generic layers/MapGuide layers/MapGuide/php layers/MapServer layers/MapServer/php lib lib/OpenLayers lib/OpenLayers/theme/default templates/mapguide/standard templates/mapguide/standard/themes/crispin templates/mapguide/standard/themes/delicious templates/mapserver/standard templates/mapserver/standard/themes/crispin templates/mapserver/standard/themes/delicious text widgets widgets/About widgets/BufferPanel widgets/FeatureInfo widgets/Help widgets/Measure widgets/Print widgets/Query widgets/Query/classes widgets/Redline widgets/Search widgets/SelectWithin widgets/TaskPane widgets/Theme widgets/Theme/classes widgets/widgetinfo

svn_fusion at osgeo.org svn_fusion at osgeo.org
Wed Mar 24 14:31:39 EDT 2010


Author: madair
Date: 2010-03-24 14:31:34 -0400 (Wed, 24 Mar 2010)
New Revision: 2105

Added:
   branches/fusion-2.0/layers/MapGuide/php/cp_arr.gif
   branches/fusion-2.0/layers/MapGuide/php/cp_arr_dis.gif
   branches/fusion-2.0/layers/MapServer/php/RestoreState.php
   branches/fusion-2.0/layers/MapServer/php/updateSessionMapFile.php
   branches/fusion-2.0/text/en
   branches/fusion-2.0/text/en.json
   branches/fusion-2.0/text/fr
   branches/fusion-2.0/text/fr.json
   branches/fusion-2.0/widgets/BufferPanel/cp_arr.gif
   branches/fusion-2.0/widgets/BufferPanel/cp_arr_dis.gif
Removed:
   branches/fusion-2.0/widgets/Print/Print.html
Modified:
   branches/fusion-2.0/
   branches/fusion-2.0/BUILDING.TXT
   branches/fusion-2.0/COPYING.TXT
   branches/fusion-2.0/build.xml
   branches/fusion-2.0/common/php/Utilities.php
   branches/fusion-2.0/config_dist.json
   branches/fusion-2.0/docs/ApplicationDefinition.xml
   branches/fusion-2.0/layers/Generic/Generic.js
   branches/fusion-2.0/layers/Layers.js
   branches/fusion-2.0/layers/MapGuide/
   branches/fusion-2.0/layers/MapGuide/MapGuide.js
   branches/fusion-2.0/layers/MapGuide/MapGuideViewerApi.js
   branches/fusion-2.0/layers/MapGuide/php/Buffer.php
   branches/fusion-2.0/layers/MapGuide/php/ClearSelection.php
   branches/fusion-2.0/layers/MapGuide/php/ColorPicker.php
   branches/fusion-2.0/layers/MapGuide/php/ColorPicker.templ
   branches/fusion-2.0/layers/MapGuide/php/Common.php
   branches/fusion-2.0/layers/MapGuide/php/CreateSession.php
   branches/fusion-2.0/layers/MapGuide/php/GetSelectionProperties.php
   branches/fusion-2.0/layers/MapGuide/php/LayerInfo.php
   branches/fusion-2.0/layers/MapGuide/php/Legend.php
   branches/fusion-2.0/layers/MapGuide/php/LoadMap.php
   branches/fusion-2.0/layers/MapGuide/php/LoadScaleRanges.php
   branches/fusion-2.0/layers/MapGuide/php/MapMenu.php
   branches/fusion-2.0/layers/MapGuide/php/Measure.php
   branches/fusion-2.0/layers/MapGuide/php/Query.php
   branches/fusion-2.0/layers/MapGuide/php/SaveMap.php
   branches/fusion-2.0/layers/MapGuide/php/SaveMapFrame.php
   branches/fusion-2.0/layers/MapGuide/php/SaveSelection.php
   branches/fusion-2.0/layers/MapGuide/php/Selection.php
   branches/fusion-2.0/layers/MapGuide/php/SetLayers.php
   branches/fusion-2.0/layers/MapServer/
   branches/fusion-2.0/layers/MapServer/MapServer.js
   branches/fusion-2.0/layers/MapServer/php/CreateSession.php
   branches/fusion-2.0/layers/MapServer/php/LegendIcon.php
   branches/fusion-2.0/layers/MapServer/php/LoadMap.php
   branches/fusion-2.0/layers/MapServer/php/LoadScaleRanges.php
   branches/fusion-2.0/layers/MapServer/php/Maptip.php
   branches/fusion-2.0/layers/MapServer/php/SetLayers.php
   branches/fusion-2.0/lib/ApplicationDefinition.js
   branches/fusion-2.0/lib/Map.js
   branches/fusion-2.0/lib/OpenLayers/OpenLayers.js
   branches/fusion-2.0/lib/OpenLayers/theme/default/style.css
   branches/fusion-2.0/lib/fusion.js
   branches/fusion-2.0/lib/jxlib.uncompressed.js
   branches/fusion-2.0/templates/mapguide/standard/ApplicationDefinition.xml
   branches/fusion-2.0/templates/mapguide/standard/index.html
   branches/fusion-2.0/templates/mapguide/standard/themes/crispin/jxtheme.uncompressed.css
   branches/fusion-2.0/templates/mapguide/standard/themes/delicious/jxtheme.uncompressed.css
   branches/fusion-2.0/templates/mapserver/standard/ApplicationDefinition.xml
   branches/fusion-2.0/templates/mapserver/standard/themes/crispin/jxtheme.uncompressed.css
   branches/fusion-2.0/templates/mapserver/standard/themes/delicious/jxtheme.uncompressed.css
   branches/fusion-2.0/widgets/About/About.html
   branches/fusion-2.0/widgets/BasemapSwitcher.js
   branches/fusion-2.0/widgets/BufferPanel/Buffer.php
   branches/fusion-2.0/widgets/BufferPanel/BufferPanel.php
   branches/fusion-2.0/widgets/BufferPanel/BufferPanel.templ
   branches/fusion-2.0/widgets/BufferPanel/ColorPicker.php
   branches/fusion-2.0/widgets/BufferPanel/ColorPicker.templ
   branches/fusion-2.0/widgets/ExtentHistory.js
   branches/fusion-2.0/widgets/FeatureInfo.js
   branches/fusion-2.0/widgets/FeatureInfo/featureinfocontroller.php
   branches/fusion-2.0/widgets/FeatureInfo/featureinfomain.php
   branches/fusion-2.0/widgets/Help/Help.html
   branches/fusion-2.0/widgets/LayerManager.js
   branches/fusion-2.0/widgets/Legend.js
   branches/fusion-2.0/widgets/LinkToView.js
   branches/fusion-2.0/widgets/MapMenu.js
   branches/fusion-2.0/widgets/Maptip.js
   branches/fusion-2.0/widgets/Measure.js
   branches/fusion-2.0/widgets/Measure/Measure.php
   branches/fusion-2.0/widgets/Navigator.js
   branches/fusion-2.0/widgets/OverviewMap.js
   branches/fusion-2.0/widgets/Print.js
   branches/fusion-2.0/widgets/Print/printablepage.php
   branches/fusion-2.0/widgets/Query.js
   branches/fusion-2.0/widgets/Query/classes/query.php
   branches/fusion-2.0/widgets/Query/querycontroller.php
   branches/fusion-2.0/widgets/Query/querymain.php
   branches/fusion-2.0/widgets/Redline.js
   branches/fusion-2.0/widgets/Redline/Redline.css
   branches/fusion-2.0/widgets/Redline/Redline.php
   branches/fusion-2.0/widgets/Search/Search.php
   branches/fusion-2.0/widgets/Search/SearchPrompt.php
   branches/fusion-2.0/widgets/Select.js
   branches/fusion-2.0/widgets/SelectPolygon.js
   branches/fusion-2.0/widgets/SelectRadius.js
   branches/fusion-2.0/widgets/SelectWithin/SelectWithin.php
   branches/fusion-2.0/widgets/SelectWithin/SelectWithinPanel.php
   branches/fusion-2.0/widgets/TaskPane.js
   branches/fusion-2.0/widgets/TaskPane/TaskPane.html
   branches/fusion-2.0/widgets/Theme.js
   branches/fusion-2.0/widgets/Theme/classes/theme.php
   branches/fusion-2.0/widgets/Theme/themecontroller.php
   branches/fusion-2.0/widgets/Theme/thememain.php
   branches/fusion-2.0/widgets/widgetinfo/featureinfo.xml
   branches/fusion-2.0/widgets/widgetinfo/measure.xml
   branches/fusion-2.0/widgets/widgetinfo/query.xml
   branches/fusion-2.0/widgets/widgetinfo/redline.xml
   branches/fusion-2.0/widgets/widgetinfo/selectioninfo.xml
   branches/fusion-2.0/widgets/widgetinfo/theme.xml
Log:
re #243: merge of rev 1910-2104 with Fusion trunk


Property changes on: branches/fusion-2.0
___________________________________________________________________
Added: svn:mergeinfo
   + /trunk:1910-2103

Modified: branches/fusion-2.0/BUILDING.TXT
===================================================================
--- branches/fusion-2.0/BUILDING.TXT	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/BUILDING.TXT	2010-03-24 18:31:34 UTC (rev 2105)
@@ -16,10 +16,8 @@
 For some tasks, external executable files are used and must be available for 
 execution on the PATH environment variable.
 
-This script requires an HTDOCS environment variable be set to point to the
-document root directory of your web server.
+Targets available include:
 
-targets available include:
 prepare - creates a "build" subdirectory with all files required to be put on 
           the web server
 deploy  - places a copy of the build directory in the web server HTDOCS directory
@@ -42,11 +40,14 @@
 
 
 Properties that can be set (and their defaults) include:
-<property name="sfName"  value="${build.home}/lib/fusionSF"/>
-<property name="cssOutput"  value="${sfName}"/>
-<property name="cssFiles"  value=""/>
-<property name="appDef"  value=""/>
+  <property name="YUIcompressor"  value="${basedir}/utils/yuicompressor-2.3.6.jar"/>
+  <property name="sfName"  value="fusionSF"/>
+  <property name="buildOutput"  value="${build.home}/lib/${sfName}"/>
+  <property name="cssOutput"  value="${build.home}/lib/${sfName}"/>
+  <property name="cssFiles"  value=""/>
+  <property name="PHP" value="/usr/local/php5cgi/bin/php"/>
 
+
 These properties can be assigned a value when ant is invoked by using the
 -D command line option, e.g.:
 

Modified: branches/fusion-2.0/COPYING.TXT
===================================================================
--- branches/fusion-2.0/COPYING.TXT	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/COPYING.TXT	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,14 +1,9 @@
 Fusion License
 
-Scriptaculous and prototype are third party libraries included in the jx
-directory and are distributed under their own licenses.  Please see 
-MIT-LICENSE in the Scriptaculous directory for more information.
+Mootools is a third party library included in the jx distribution and is 
+distributed under an MIT-style license.  Please see the jxlib.uncompressed.js
+file for more information.
 
-ExplorerCanvas is Copyright 2006 Google Inc. and is distributed under 
-the Apache License Version 2.0, January 2004.
-
-JavaScript Scalebar for MapServer (widgets/scalebar/) is Copyright (c) 2005 Tim Schaub of CommEn Space (http://www.commenspace.org) and is distributed under the LGPL license.
-
 This license applies to all files obtained with the fusion source that are not
 explicitly covered by a separate license.
 

Modified: branches/fusion-2.0/build.xml
===================================================================
--- branches/fusion-2.0/build.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/build.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -74,7 +74,7 @@
   <property environment="env"/>
   <property name="app.name" value="fusion"/>
   <property name="app.path" value="/${app.name}"/>
-  <property name="app.version" value="1.1.x"/>
+  <property name="app.version" value="2.0.x"/>
   <property name="build.home" value="${basedir}/build"/>
   <property name="deploy.home" value="${basedir}/../${app.name}"/>
   <property name="dist.home" value="${basedir}/dist"/>
@@ -93,6 +93,7 @@
   <property name="buildOutput"  value="${build.home}/lib/${sfName}"/>
   <property name="cssOutput"  value="${build.home}/lib/${sfName}"/>
   <property name="cssFiles"  value=""/>
+  <property name="PHP" value="/usr/local/php5cgi/bin/php"/>
 
 
 <!-- ==================== Prepare Target ================================== -->
@@ -154,8 +155,7 @@
         <arg value="-i ./"/>
         <arg value="-o html ./docs"/>
         <arg value="-p ./docs/NaturalDocs"/>
-        <arg value="-xi ./scriptaculous"/>
-        <arg value="-xi ./lib"/>
+         <arg value="-xi ./lib"/>
         <arg value="-r"/>
         -->
         <arg line="/c perl C:\Progra~1\NaturalDocs\NaturalDocs -i ./lib -i ./widgets -o html ./docs/NaturalDocs -p ./docs/NaturalDocs -r"/>
@@ -185,9 +185,9 @@
     <xmlproperty file="${build.home}/appDefFileset.xml"/>
 
     <!-- convert the application definition file to JSON -->
-    <exec executable="php" os="Windows Vista, Windows XP"
+    <exec executable="${PHP}" dir="${build.home}"
               output="${build.home}/appDef.json">
-        <arg line="common\php\Xml2JSON.php --file='${appDef}'"/>
+        <arg line="${build.home}/common/php/Xml2JSON.php --file='${appDef}'"/>
     </exec>
 
   </target>
@@ -262,6 +262,8 @@
     <echo message="compressing..."/>
     <java jar="${YUIcompressor}" fork="true"
           output="${buildOutput}-compressed.js">
+        <arg value="--charset"/>
+        <arg value="utf-8"/>
         <arg value="${buildOutput}.js"/>
     </java>
     <copy file="${buildOutput}-compressed.js" todir="${basedir}/lib"/>
@@ -281,6 +283,8 @@
 
     <java jar="${YUIcompressor}" fork="true"
           output="${cssOutput}-compressed.css">
+        <arg value="--charset"/>
+        <arg value="utf-8"/>
         <arg value="${cssOutput}.css"/>
     </java>
   </target>
@@ -297,6 +301,8 @@
 
     <java jar="${YUIcompressor}" fork="true"
           output="${cssOutput}-compressed.css">
+        <arg value="--charset"/>
+        <arg value="utf-8"/>
         <arg value="${cssOutput}.css"/>
     </java>
   </target>

Modified: branches/fusion-2.0/common/php/Utilities.php
===================================================================
--- branches/fusion-2.0/common/php/Utilities.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/common/php/Utilities.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -26,35 +26,40 @@
 
 /* recursively convert a variable to its json representation */
 function var2json($var) {
-    $result = "";
-    if (is_object($var)) {
-        $result .= "{";
-        $sep = "";
-        foreach($var as $key => $val) {
-            $result .= $sep.'"'.$key.'":'.var2json($val);
-            $sep = ",";
-        }
-        $result .= "}";
-    } else if (is_array($var)) {
-        $result .= "[";
-        $sep = "";
-        for($i=0; $i<count($var); $i++) {
-            $result .= $sep.var2json($var[$i]);
-            $sep = ",";
-        }
-        $result .= "]";
-    } else if (is_string($var)) {
-        //$tmpStr = str_replace("'", "\'", $var);
-        $tmpStr = str_replace('"', '\"', $var);
-        $result = '"'.str_replace("\n", '\n', $tmpStr).'"';
-    } else if (is_bool($var)) {
-        $result = $var ? 'true' : 'false';
-    } else if (is_null($var)) {
-        $result = 'null';
-    }else {
-        $result = $var;
+    if (function_exists('json_encode')) {
+        $result = json_encode($var);
+    } else {
+        $result = "";
+        if (is_object($var)) {
+            $result .= "{";
+            $sep = "";
+            foreach($var as $key => $val) {
+                $result .= $sep.'"'.$key.'":'.var2json($val);
+                $sep = ",";
+            }
+            $result .= "}";
+        } else if (is_array($var)) {
+            $result .= "[";
+            $sep = "";
+            for($i=0; $i<count($var); $i++) {
+                $result .= $sep.var2json($var[$i]);
+                $sep = ",";
+            }
+            $result .= "]";
+        } else if (is_string($var)) {
+            //$tmpStr = str_replace("'", "\'", $var);
+            $tmpStr = str_replace('"', '\"', $var);
+            $result = '"'.str_replace("\n", '\n', $tmpStr).'"';
+        } else if (is_bool($var)) {
+            $result = $var ? 'true' : 'false';
+        } else if (is_null($var)) {
+            $result = 'null';
+        } else {
+            $result = $var;
+        }      
     }
-    return $result;
+
+    return utf8_encode($result);
 }
 
 function xml2json($domElement) {

Modified: branches/fusion-2.0/config_dist.json
===================================================================
--- branches/fusion-2.0/config_dist.json	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/config_dist.json	2010-03-24 18:31:34 UTC (rev 2105)
@@ -41,6 +41,10 @@
 	        web-accessible temporary legend images. */
 	    "legendIconCacheDir":"/ms4w/tmp/ms_tmp",
             /* The file  system path to where the maps are stored. */
-            "mapFileRoot":"/ms4w/apps/"
+        "mapFileRoot":"/ms4w/apps/",
+        /*The file  system path where the saved map sessions are stored.*/
+         "mapRestoreState":"/opt/fgs/apps/savedSession/",
+        /*The file  system path where the php sessions are stored.*/
+         "mapRestoreStateSession":"/opt/fgs/tmp/"
     }
 }


Property changes on: branches/fusion-2.0/config_dist.json
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/fusion-2.0/docs/ApplicationDefinition.xml
===================================================================
--- branches/fusion-2.0/docs/ApplicationDefinition.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/docs/ApplicationDefinition.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -480,7 +480,7 @@
     <Widget xsi:type="UiWidgetType">
       <Name>Measure</Name>
       <Type>Measure</Type>
-      <Description>Measure distances on the map.</Description>
+      <Description>Measure distances and areas on the map.</Description>
       <Extension xsi:type="CustomContentType">
         <Type>both</Type>
         <RulerTooltipContainer>RulerResult</RulerTooltipContainer>
@@ -497,7 +497,7 @@
     <Widget xsi:type="UiWidgetType">
       <Name>menuMeasure</Name>
       <Type>Measure</Type>
-      <Description>Measure distances on the map.</Description>
+      <Description>Measure distances and areas on the map.</Description>
       <Extension xsi:type="CustomContentType">
         <Type>both</Type>
         <RulerTooltipContainer>RulerResult</RulerTooltipContainer>

Modified: branches/fusion-2.0/layers/Generic/Generic.js
===================================================================
--- branches/fusion-2.0/layers/Generic/Generic.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/Generic/Generic.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -88,6 +88,7 @@
             this.oLayerOL.events.unregister("loadend", this, this.loadEnd);
             this.oLayerOL.events.unregister("loadcancel", this, this.loadEnd);
             this.oLayerOL.destroy();
+            this.oLayerOL = null;
         }
 
         switch (this.layerType) {
@@ -103,20 +104,33 @@
                 this.mapTag.layerOptions.type = G_SATELLITE_MAP;
                 break;
               case 'G_NORMAL_MAP':
+                this.mapTag.layerOptions.type = G_NORMAL_MAP;
               default:
-                this.mapTag.layerOptions.type = G_NORMAL_MAP;
+                // For the re-loaded Google layers
+                if(this.mapTag.layerOptions.type == G_PHYSICAL_MAP)
+                  this.mapTag.layerOptions.type = G_PHYSICAL_MAP;
+                else if(this.mapTag.layerOptions.type == G_HYBRID_MAP)
+                  this.mapTag.layerOptions.type = G_HYBRID_MAP;
+                else if(this.mapTag.layerOptions.type == G_SATELLITE_MAP)
+                  this.mapTag.layerOptions.type = G_SATELLITE_MAP;
+                else 
+                  this.mapTag.layerOptions.type = G_NORMAL_MAP;
                 break;
             }
             break;
-         case 'VirtualEarth':         
+         case 'VirtualEarth':
+             this.mapTag.layerOptions.animationEnabled = false;
              switch (this.mapTag.layerOptions.type) {   //VE layer types are enumerated values
                case 'Aerial':              //defined in VEMapStyle from the VE api
+               case 'a':
                  this.mapTag.layerOptions.type = VEMapStyle.Aerial;
                  break;
                case 'Shaded':
+               case 's':
                  this.mapTag.layerOptions.type = VEMapStyle.Shaded;
                  break;
                case 'Hybrid':
+               case 'h':
                  this.mapTag.layerOptions.type = VEMapStyle.Hybrid;
                  break;
                default:
@@ -127,12 +141,15 @@
          case 'Yahoo':
             switch (this.mapTag.layerOptions.type) {   //Yahoo is similar to google
               case 'YAHOO_MAP_SAT':              //defined by YMap, not a string
+              case 'YAHOO_SAT':
                 this.mapTag.layerOptions.type = YAHOO_MAP_SAT;
                 break;
               case 'YAHOO_MAP_HYB':
+              case 'YAHOO_HYB':
                 this.mapTag.layerOptions.type = YAHOO_MAP_HYB;
                 break;
               case 'YAHOO_MAP_REG':
+              case "YAHOO_REG":
               default:
                 this.mapTag.layerOptions.type = YAHOO_MAP_REG;
                 break;
@@ -149,12 +166,22 @@
         }
 
         if (!this.oLayerOL) {
-            if (!this.mapTag.layerOptions.maxExtent) {
-                this.mapTag.layerOptions.maxExtent = new OpenLayers.Bounds(-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892);
-            }
             if (typeof this.mapTag.layerOptions.sphericalMercator == 'undefined') {
                 this.mapTag.layerOptions.sphericalMercator = true;
             }
+            if (this.mapTag.layerOptions.sphericalMercator) {
+              if (!this.mapTag.layerOptions.maxExtent) {
+                  this.mapTag.layerOptions.maxExtent = new OpenLayers.Bounds(-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892);
+              }
+              this.mapTag.layerOptions.units = "m";
+              this.mapTag.layerOptions.projection = "EPSG:3785";
+            } else {
+              if (!this.mapTag.layerOptions.maxExtent) {
+                  this.mapTag.layerOptions.maxExtent = new OpenLayers.Bounds(-180,-90,180,90);
+              }
+              this.mapTag.layerOptions.units = "dd";
+              this.mapTag.layerOptions.projection = "EPSG:4326";
+            }
             if (typeof this.mapTag.layerOptions.numZoomLevels == 'undefined') {
                 this.mapTag.layerOptions.numZoomLevels = 20;
             }
@@ -163,6 +190,7 @@
             this.mapWidget.oMapOL.setOptions({fractionalZoom: false});
         }
 
+
         this.oLayerOL.events.register("loadstart", this, this.loadStart);
         this.oLayerOL.events.register("loadend", this, this.loadEnd);
         this.oLayerOL.events.register("loadcancel", this, this.loadEnd);
@@ -223,9 +251,13 @@
         this.drawMap();
     },
     
-    getLegendImageURL: function(fScale, layer, style) {
-      var url = null; //TODO: provide a generic icon url 
-      return url;
+    getLegendImageURL: function(fScale, layer, style,defaultIcon) {
+      //var url = null; //TODO: provide a generic icon url 
+      return defaultIcon;
+    },
+    
+    getSessionID: function() {
+        return '';
     }
 
 });

Modified: branches/fusion-2.0/layers/Layers.js
===================================================================
--- branches/fusion-2.0/layers/Layers.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/Layers.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -58,7 +58,8 @@
         this.registerEventID(Fusion.Event.LAYER_LOADED);
         this.registerEventID(Fusion.Event.LAYER_LOADING);
         this.registerEventID(Fusion.Event.MAP_LAYER_ORDER_CHANGED);
-
+        this.registerEventID(Fusion.Event.LAYER_PROPERTY_CHANGED);
+        
         this.mapWidget = map;
         this.oSelection = null;
         if (isMapWidgetLayer != null) {
@@ -75,17 +76,6 @@
         this.sMapResourceId = mapTag.resourceId ? mapTag.resourceId : '';
         this.mapInfo = mapTag.mapInfo;
         this.layerType = mapTag.type;
-
-        //projection info from the extension
-        if (mapTag.extension.ProjectionCode) {
-          this.projCode = mapTag.extension.ProjectionCode[0];
-        }
-        if (mapTag.extension.ProjectionDef) {
-          var projDef = mapTag.extension.ProjectionDef[0];
-          this.projCode = "APP-DEF-PROJ";
-          Proj4js.defs[this.projCode] = projDef;
-        }
-        
     },
 
     /**
@@ -328,6 +318,7 @@
         this.visible = o.visible;
         this.initiallyVisible = o.visible;
         this.actuallyVisible = o.actuallyVisible;
+        this.isBaseMapGroup = o.isBaseMapGroup;
         this.registerEventID(Fusion.Event.GROUP_PROPERTY_CHANGED);
     },
 
@@ -458,6 +449,7 @@
         this.visible = o.visible;
         this.initiallyVisible = o.visible;
         this.selectable = o.selectable;
+        this.isBaseMapLayer = o.isBaseMapLayer;
 
 
         //determine the layer type so that the correct icon can be displayed in the legend
@@ -484,7 +476,8 @@
             this.scaleRanges.push(scaleRange);
           }
         }
-        this.registerEventID(Fusion.Event.LAYER_PROPERTY_CHANGED);
+
+        //this.registerEventID(Fusion.Event.LAYER_PROPERTY_CHANGED);
     },
 
     supportsType: function(type) {
@@ -535,7 +528,7 @@
 
     set: function(property, value) {
         this[property] = value;
-        this.triggerEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, this);
+        this.oMap.triggerEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, this);
     }
 
 });
@@ -548,7 +541,7 @@
 
 Fusion.Layers.ScaleRange = OpenLayers.Class({
     styles: null,
-    initialize: function(o, layerType) {
+    initialize: function(o, layerType, iconOpt) {
         this.minScale = o.minScale;
         this.maxScale = o.maxScale;
         if (this.maxScale == 'infinity' || this.maxScale == 'auto') {
@@ -556,13 +549,13 @@
         }
         this.styles = [];
         if (!o.styles) {
-          var styleItem = new Fusion.Layers.StyleItem({legendLabel:'DWF'}, layerType);
+          var styleItem = new Fusion.Layers.StyleItem({legendLabel:'DWF'}, layerType, iconOpt);
           this.styles.push(styleItem);
           return;
         }
         var staticIcon = o.styles.length>1 ? false : layerType;
         for (var i=0; i<o.styles.length; i++) {
-            var styleItem = new Fusion.Layers.StyleItem(o.styles[i], staticIcon);
+            var styleItem = new Fusion.Layers.StyleItem(o.styles[i], staticIcon, iconOpt);
             this.styles.push(styleItem);
         }
     },
@@ -580,7 +573,10 @@
 
 Fusion.Layers.StyleItem = OpenLayers.Class({
     clientAgent: 'Fusion Viewer',
-    initialize: function(o, staticIcon) {
+    initialize: function(o, staticIcon, iconOpt) {
+        this.iconOpt = iconOpt;
+        this.iconX = o.icon_x || 0;
+        this.iconY = o.icon_y || 0;
         this.legendLabel = o.legendLabel;
         this.filter = o.filter;
         this.geometryType = o.geometryType;


Property changes on: branches/fusion-2.0/layers/MapGuide
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/fusion-2.0/layers/MapGuide/MapGuide.js
===================================================================
--- branches/fusion-2.0/layers/MapGuide/MapGuide.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/MapGuide.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -85,7 +85,7 @@
             this.nTolerance = 2; //pixels, default pixel tolernace for a point click; TBD make this configurable
           }
         }
-
+        
         rootOpts = {
           displayInLegend: this.bDisplayInLegend,
           expandInLegend: this.bExpandInLegend,
@@ -132,6 +132,13 @@
             var o;
             eval('o='+xhr.responseText);
             this.session[0] = o.sessionId;
+            var acceptLang = o.acceptLanguage.split(',');
+            //IE - en-ca,en-us;q=0.8,fr;q=0.5,fr-ca;q=0.3
+            for (var i=0; i<acceptLang.length; ++i) {
+              var locale = acceptLang[i].split(";");
+              Fusion.initializeLocale(locale[0]);
+              break;
+            }
             this.triggerEvent(Fusion.Event.MAP_SESSION_CREATED);
         }
     },
@@ -293,9 +300,12 @@
             }
 
             //set projection units and code if supplied
+            if (o.epsg != 0) {
+              this.mapTag.layerOptions.projection = "EPSG:" + o.epsg;
+            }
             //TODO: consider passing the metersPerUnit value into the framework
             //to allow for scaling that doesn't match any of the pre-canned units
-            this.units = Fusion.getClosestUnits(o.metersPerUnit);
+            this.mapTag.layerOptions.units = Fusion.getClosestUnits(o.metersPerUnit);
 
             //add in scales array if supplied
             if (o.FiniteDisplayScales && o.FiniteDisplayScales.length>0) {
@@ -312,15 +322,29 @@
                 this.oLayerOL.destroy();
             }
 
-            this.oLayerOL = this.createOLLayer(this._sMapname, this.bSingleTile,2);
+            this.oLayerOL = this.createOLLayer(this._sMapname, this.bSingleTile,2,false);
             this.oLayerOL.events.register("loadstart", this, this.loadStart);
             this.oLayerOL.events.register("loadend", this, this.loadEnd);
             this.oLayerOL.events.register("loadcancel", this, this.loadEnd);
 
+            
+            //remove the dynamic overlay layer if it was already created
+            if (this.oLayerOL2) {
+                this.oLayerOL2.destroy();
+            }
+
             //this is to distinguish between a regular map and an overview map
             this.bMapLoaded = true;
             if (this.bIsMapWidgetLayer) {
-              this.mapWidget.addMap(this);
+                this.mapWidget.addMap(this);
+                
+                //if we have a tiled map that also contains dynamic layers, we need to create
+                //an additional overlay layer to render them on top of the tiles
+                if(!this.bSingleTile && o.hasDynamicLayers) {
+                    this.oLayerOL2 = this.createOLLayer(this._sMapname + "_DynamicOverlay",true,2,true);
+                    this.mapWidget.oMapOL.addLayer(this.oLayerOL2);
+                    this.oLayerOL2.setVisibility(true);
+                }
             }
         }
         this.mapWidget._removeWorker();
@@ -389,6 +413,11 @@
             eval('o='+r.responseText);
             if (o.layers && o.layers.length > 0)
             {
+                var iconOpt = {
+                    url: o.icons_url || null,
+                    width: o.icons_width || 16,
+                    height: o.icons_height || 16
+                };
                 for (var i=0; i<o.layers.length; i++)
                 {
                     var oLayer = this.getLayerById(o.layers[i].uniqueId);
@@ -398,7 +427,7 @@
                         for (var j=0; j<o.layers[i].scaleRanges.length; j++)
                         {
                             var scaleRange = new Fusion.Layers.ScaleRange(o.layers[i].scaleRanges[j],
-                                                                                 oLayer.layerType);
+                                                                                 oLayer.layerType, iconOpt);
                             oLayer.scaleRanges.push(scaleRange);
                         }
                     }
@@ -515,7 +544,12 @@
         this.aHideGroups = [];
         this.aRefreshLayers = [];
 
-        this.oLayerOL.mergeNewParams(params);
+        if(this.oLayerOL2) {
+            this.oLayerOL2.mergeNewParams(params);
+        } else {
+            this.oLayerOL.mergeNewParams(params);
+        }
+        
     },
 
     drawSelection: function() {
@@ -531,7 +565,7 @@
      *
      * Returns an OpenLayers MapGuide layer object
      */
-    createOLLayer: function(layerName, bSingleTile, behavior) {
+    createOLLayer: function(layerName, bSingleTile, behavior, forceAsOverlay) {
       /* prevent the useOverlay flag based on MapGuide config element */
       this.useAsyncOverlay = Fusion.getConfigurationItem('mapguide', 'useAsyncOverlay');
       if (!this.useAsyncOverlay) {          //v2.0.1 or earlier
@@ -539,7 +573,6 @@
       }
       
       var layerOptions = {
-        units: this.units,
         maxResolution: 'auto',
         useOverlay: this.selectionAsOverlay,
         useAsyncOverlay: this.useAsyncOverlay,
@@ -586,8 +619,12 @@
         if (behavior == 5) {
           params.selectioncolor = this.selectionColor;
           params.format = this.selectionFormat;
-          layerOptions.isBaseLayer = false;
         }
+        
+        if(forceAsOverlay)
+        {
+            layerOptions.isBaseLayer = false;
+        }
 
       } else {
         params = {      //tiled version
@@ -609,8 +646,8 @@
       } else {
         url = Fusion.getConfigurationItem('mapguide', 'mapAgentUrl');
       }
-      var oLayerOL = new OpenLayers.Layer.MapGuide( layerName, url, params, layerOptions );
-      return oLayerOL;
+      var oNewLayerOL = new OpenLayers.Layer.MapGuide( layerName, url, params, layerOptions );
+      return oNewLayerOL;
     },
 
     /**
@@ -895,7 +932,7 @@
             if (oNode.hasSelection) {
               if (this.selectionAsOverlay) {
                 if (!this.queryLayer) {
-                  this.queryLayer = this.createOLLayer("query layer", true, 5);
+                  this.queryLayer = this.createOLLayer("query layer", true, 5, true);
                   this.mapWidget.oMapOL.addLayer(this.queryLayer);
                   this.mapWidget.registerForEvent(Fusion.Event.MAP_LOADING,
                         OpenLayers.Function.bind(this.removeQueryLayer, this));
@@ -904,6 +941,13 @@
                 }
               }
 
+              //Fix Ticket #1145.
+              //When the user invokes the setSelection() function to update the selection,
+              //clear the selection count for all layers before proceeding
+              for (var j=0; j<this.aLayers.length; ++j) {
+                this.aLayers[j].selectedFeatureCount = 0;
+              }
+
               // set the feature count on each layer making up this map
               for (var i=0; i<oNode.layers.length; ++i) {
                 var layerName = oNode.layers[i];
@@ -977,6 +1021,9 @@
         this.processGroupEvents(group, true);
         if (group.groupName == 'layerRoot') {
             this.oLayerOL.setVisibility(true);
+            this.oLayerOL2.setVisibility(true);
+        } else if (group.isBaseMapGroup) {
+            this.oLayerOL.setVisibility(true);
         } else {
             this.aShowGroups.push(group.uniqueId);
             if (!noDraw) {
@@ -988,6 +1035,9 @@
         this.processGroupEvents(group, false);
         if (group.groupName == 'layerRoot') {
             this.oLayerOL.setVisibility(false);
+            this.oLayerOL2.setVisibility(false);
+        } else if (group.isBaseMapGroup) {
+            this.oLayerOL.setVisibility(false);
         } else {
             this.aHideGroups.push(group.uniqueId);
             if (!noDraw) {
@@ -1156,18 +1206,25 @@
         this.mapWidget.triggerEvent(Fusion.Event.MAP_MAPTIP_REQ_FINISHED, this.oMaptip);
     },
     
-    getLegendImageURL: function(fScale, layer, style) {
-      var url = Fusion.getConfigurationItem('mapguide', 'mapAgentUrl');
-      url += "?OPERATION=GETLEGENDIMAGE&SESSION=" + layer.oMap.getSessionID();
-      url += "&VERSION=1.0.0&SCALE=" + fScale;
-      url += "&LAYERDEFINITION=" + encodeURIComponent(layer.resourceId);
-      url += "&THEMECATEGORY=" + style.categoryIndex;
-      url += "&TYPE=" + style.geometryType;
-      url += "&CLIENTAGENT=" + encodeURIComponent(this.clientAgent);
-      if (layer.noCache) {
-        url += "&TS=" + (new Date()).getTime();
-      }
-      return url;
+    getLegendImageURL: function(fScale, layer, style,defaultIcon) {
+        if(layer.layerTypes[0] == 4){
+            return defaultIcon;
+        }
+        else
+        {
+            var url = Fusion.getConfigurationItem('mapguide', 'mapAgentUrl');
+            url += "?OPERATION=GETLEGENDIMAGE&SESSION=" + layer.oMap.getSessionID();
+            url += "&VERSION=1.0.0&SCALE=" + fScale;
+            url += "&LAYERDEFINITION=" + encodeURIComponent(layer.resourceId);
+            url += "&THEMECATEGORY=" + style.categoryIndex;
+            url += "&TYPE=" + style.geometryType;
+            url += "&CLIENTAGENT=" + encodeURIComponent(this.clientAgent);
+            if (this.noCache) {
+                url += "&TS=" + (new Date()).getTime();
+            }
+            return url;
+        }
+
     },
 
 

Modified: branches/fusion-2.0/layers/MapGuide/MapGuideViewerApi.js
===================================================================
--- branches/fusion-2.0/layers/MapGuide/MapGuideViewerApi.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/MapGuideViewerApi.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -192,11 +192,13 @@
   window.setTimeout(mgApiDeactivate, 100);
   
   return false;
-}
-
-function mgApiDeactivate() {
-  mgApiActiveControl.deactivate();
-  mgApiActiveControl = null;
+}
+
+function mgApiDeactivate() {
+    if (mgApiActiveControl) {
+        mgApiActiveControl.deactivate();
+        mgApiActiveControl = null;
+    }
   if (mgApiActiveWidget) {
     var Fusion = window.top.Fusion;
     var mapWidget = Fusion.getWidgetById(mgApiMapWidgetId);

Modified: branches/fusion-2.0/layers/MapGuide/php/Buffer.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/Buffer.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/Buffer.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,12 @@
  *****************************************************************************/
 
 include ('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
+
 include ('Utilities.php');
 
 try {

Modified: branches/fusion-2.0/layers/MapGuide/php/ClearSelection.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/ClearSelection.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/ClearSelection.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,19 +29,24 @@
  *****************************************************************************/
 
 include "Common.php";
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 
 try
 {
     $resourceSrvc = $siteConnection->CreateService(MgServiceType::ResourceService);
-         
+
     $map = new MgMap();
     $map->Open($resourceSrvc, $mapName);
-        
+
     $sel = new MgSelection($map);
 
     $sel->Save($resourceSrvc, $mapName);
-} 
-catch(MgException $e) 
+}
+catch(MgException $e)
 {
     echo "ERROR: " . $e->GetMessage() . "\n";
     echo $e->GetDetails() . "\n";

Modified: branches/fusion-2.0/layers/MapGuide/php/ColorPicker.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/ColorPicker.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/ColorPicker.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -27,6 +27,12 @@
     $fusionMGpath = '../../../layers/MapGuide/php/';
     include $fusionMGpath . 'Common.php';
 
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
+
     $locale = GetDefaultLocale();
     $clr = "000000";
     $allowTransparency = 0;

Modified: branches/fusion-2.0/layers/MapGuide/php/ColorPicker.templ
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/ColorPicker.templ	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/ColorPicker.templ	2010-03-24 18:31:34 UTC (rev 2105)
@@ -38,9 +38,9 @@
 var agent = navigator.userAgent.toLowerCase();
 var msie = agent.indexOf("msie") != -1;
 var imgspin = new Image(28,22);
-imgspin.src = "../stdicons/cp_arr.gif";
+imgspin.src = "./cp_arr.gif";
 var imgspindis = new Image(28,22);
-imgspindis.src = "../stdicons/cp_arr_dis.gif";
+imgspindis.src = "./cp_arr_dis.gif";
 var r = 0, g = 0, b = 0;
 var initColor = "%s";
 var allowTransparency = %s;

Modified: branches/fusion-2.0/layers/MapGuide/php/Common.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/Common.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/Common.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -38,6 +38,10 @@
 
 $defaultExtensionDir = dirname(__FILE__)."/../../../../";
 $defaultInstallDir = realpath($defaultExtensionDir)."/../../";
+$initializationErrorOccurred = false;
+$initializationErrorMessage = null;
+$initializationErrorStackTrace = null;
+$initializationErrorDetail = null;
 
 /**
  * Developer's notes:
@@ -64,8 +68,10 @@
 include dirname(__FILE__)."/Constants.php";
 // Initialize
 
-MgInitializeWebTier($extensionDir. "/webconfig.ini");
-try {
+try
+{
+    MgInitializeWebTier($extensionDir. "/webconfig.ini");
+
     /* If no session has been established yet, then we use the credentials passed
      * to this script to connect to the site server.  By default, we use the
      * Anonymous user.
@@ -115,48 +121,63 @@
         }
         //echo "<current user: >".$_SESSION['username']. '</current>';
     }
-} catch (MgAuthenticationFailedException $afe) {
-    header('Content-type: text/xml');
-    echo "<Exception>";
-    echo "<Type>Authentication Failed</Type>";
-    echo "<Message>" . $afe->GetMessage() . "</Message>";
-    echo "<Details>" . $afe->GetDetails() . "</Details>";
-    echo "</Exception>";
-    exit;
-} catch (MgUserNotFoundException $unfe) {
-    header('Content-type: text/xml');
-    echo "<Exception>";
-    echo "<Type>User Not Found</Type>";
-    echo "<Message>" . $unfe->GetMessage() . "</Message>";
-    echo "<Details>" . $unfe->GetDetails() . "</Details>";
-    echo "</Exception>";
-    exit;
-} catch (MgSessionExpiredException $see) {
-    header('Content-type: text/xml');
-    echo "<Exception>";
-    echo "<Type>Session Expired</Type>";
-    echo "<Message>" . $see->GetMessage() . "</Message>";
-    echo "<Details>" . $see->GetDetails() . "</Details>";
-    echo "</Exception>";
-    exit;
-} catch (MgException $e) {
-    header('Content-type: text/xml');
-    echo "<Exception>";
-    echo "<Type>Exception</Type>";
-    echo "<Message>" . $e->GetMessage() . "</Message>";
-    echo "<Details>" . $e->GetDetails() . "</Details>";
-    echo "</Exception>";
-    exit;
+
+    //common resource service to be used by all scripts
+    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
+
+    if (isset($_REQUEST['mapname'])) {
+        $mapName = $_REQUEST['mapname'];
+        $mapResourceID = new MgResourceIdentifier( 'Session:'.$sessionID.'//'.$mapName.'.MapDefinition');
+        $mapStateID = new MgResourceIdentifier('Session:'.$sessionID.'//'.$mapName.'.'.MgResourceType::Map);
+    }
+
 }
+catch (MgException $e)
+{
+    $initializationErrorMessage = $e->GetMessage();
+    $initializationErrorDetail = $e->GetDetails();
+    $initializationErrorStackTrace = $e->GetStackTrace();
+    $initializationErrorOccurred = true;
+}
 
+function InitializationErrorOccurred()
+{
+    global $initializationErrorOccurred;
+    return $initializationErrorOccurred;
+}
 
-//common resource service to be used by all scripts
-$resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
+function DisplayInitializationErrorHTML()
+{
+    global $initializationErrorMessage, $initializationErrorDetail;
+    echo "<table class=\"RegText\" border=\"0\" cellspacing=\"0\" width=\"100%%\">";
+    echo "<tr><td class=\"Title\">Error<hr></td></tr>";
+    if($initializationErrorMessage != null)
+    {
+        $message = $initializationErrorMessage;
+        while(strpos($message, '\n'))
+        {
+            $message = str_replace('\n', '<br/>', $message);
+        }
+        echo "<tr><td>" . $message . "</td></tr>";
+    }
+    if ($initializationErrorDetail != null && (strlen($initializationErrorDetail) - strlen($initializationErrorMessage) > 4))
+    {
+        $detail = $initializationErrorDetail;
+        while(strpos($detail, '\n'))
+        {
+            $detail = str_replace('\n', '<br/>', $detail);
+        }
+        echo "<tr><td>" . $detail . "</td></tr>";
+    }
+    echo "</table>";
+}
 
-if (isset($_REQUEST['mapname'])) {
-    $mapName = $_REQUEST['mapname'];
-    $mapResourceID = new MgResourceIdentifier( 'Session:'.$sessionID.'//'.$mapName.'.MapDefinition');
-    $mapStateID = new MgResourceIdentifier('Session:'.$sessionID.'//'.$mapName.'.'.MgResourceType::Map);
+function DisplayInitializationErrorText()
+{
+    global $initializationErrorMessage, $initializationErrorDetail, $initializationErrorStackTrace;
+    echo "ERROR: " . $initializationErrorMessage . "\n";
+    echo $initializationErrorDetail . "\n";
+    echo $initializationErrorStackTrace . "\n";
 }
 
 function GetDefaultLocale()
@@ -170,7 +191,7 @@
     $pos = strrpos($thisFile, '\\');
     if ($pos == false)
         $pos = strrpos($thisFile, '/');
-    return substr($thisFile, 0, $pos+1) . "../../../../localized/";
+    return substr($thisFile, 0, $pos+1) . "../../../text/";
 }
 
 function FormatMessage($id, $locale, $params)

Modified: branches/fusion-2.0/layers/MapGuide/php/CreateSession.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/CreateSession.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/CreateSession.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,11 @@
  *****************************************************************************/
 
 include('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('Utilities.php');
 include('../../../common/php/Utilities.php');
 
@@ -42,6 +47,7 @@
     $result = null;
     $result->sessionId = $sessionId;
     $result->userName = $username;
+    $result->acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
     echo var2json($result);
     
     /* start a php session in the web tier as well, using same session id */

Modified: branches/fusion-2.0/layers/MapGuide/php/GetSelectionProperties.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/GetSelectionProperties.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/GetSelectionProperties.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -25,6 +25,11 @@
  */
 
 include('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('../../../common/php/Utilities.php');
 include('Utilities.php');
 
@@ -174,7 +179,7 @@
 
 
     } catch(MgException $e) {
-        echo "/* SetSelection Exception: " . $e->GetDetails()."*/";
+        echo "ERROR: " . $e->GetDetails() . "\n";
     }
 
 function GetParameters($params)

Modified: branches/fusion-2.0/layers/MapGuide/php/LayerInfo.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/LayerInfo.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/LayerInfo.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,11 @@
  *****************************************************************************/
 
 include ("Common.php");
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include ("Utilities.php");
 
 $featureService = $siteConnection->CreateService(MgServiceType::FeatureService);

Modified: branches/fusion-2.0/layers/MapGuide/php/Legend.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/Legend.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/Legend.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,11 @@
  *****************************************************************************/
 
 include ("Common.php");
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 
 // Converts a boolean to "yes" or "no"
 // --from MG Web Tier API Reference
@@ -56,11 +61,11 @@
 //TODO: make the temp location configurable
 $tempImgPath = "c:/Program Files/Apache Group/Apache2/htdocs/ms_tmp/";
 
-for($i=0;$i<$layers->GetCount();$i++) 
-{ 
+for($i=0;$i<$layers->GetCount();$i++)
+{
     $layer=$layers->GetItem($i);
     $layerDefinition = $layer->GetLayerDefinition();
-    
+
     echo '<layer>';
     echo '<uniqueid>'.$layer->GetObjectId().'</uniqueid>';
     echo '<layername>'.htmlentities($layer->GetName()).'</layername>';
@@ -77,14 +82,14 @@
     echo '<actuallyvisible>'.BooleanToString($layer->isVisible()).'</actuallyvisible>';
     buildScaleRanges($layer);
     echo '</layer>';
-} 
-echo "</layercollection>"; 
+}
+echo "</layercollection>";
 
 //Get layer groups as xml
 $groups = $map->GetLayerGroups();
-echo "<groupcollection>"; 
-for($i=0;$i<$groups->GetCount();$i++) 
-{ 
+echo "<groupcollection>";
+for($i=0;$i<$groups->GetCount();$i++)
+{
     $group=$groups->GetItem($i);
     $layerDefinition = $layer->GetLayerDefinition();
     echo '<group>';
@@ -102,8 +107,8 @@
     echo '<visible>'.BooleanToString($group->GetVisible()).'</visible>';
     echo '<actuallyvisible>'.BooleanToString($group->isVisible()).'</actuallyvisible>';
     echo '</group>';
-} 
-echo"</groupcollection>"; 
+}
+echo"</groupcollection>";
 
 echo "</legend>";
 
@@ -141,13 +146,13 @@
             $minScale = $minElt->item(0)->nodeValue;
         if($maxElt->length > 0)
             $maxScale = $maxElt->item(0)->nodeValue;
-        
+
         if($type != 0)
             break;
         $output .= '<scalerange>';
         $output .= '<minscale>'.$minScale.'</minscale>';
         $output .= '<maxscale>'.$maxScale.'</maxscale>';
-    
+
         $styleIndex = 0;
         for($ts=0, $count = count($typeStyles); $ts < $count; $ts++)
         {
@@ -191,4 +196,4 @@
 
     return $buffer;
 }
-?>
\ No newline at end of file
+?>

Modified: branches/fusion-2.0/layers/MapGuide/php/LoadMap.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/LoadMap.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/LoadMap.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -30,6 +30,11 @@
 
 include(dirname(__FILE__).'/../../../common/php/Utilities.php');
 include('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('Utilities.php');
 
 
@@ -71,18 +76,26 @@
     @$oMax = $extents->GetUpperRightCoordinate();
 
     @$srs = $map->GetMapSRS();
+    $epsgCode = "";
     if($srs != "")
     {
       @$csFactory = new MgCoordinateSystemFactory();
       @$cs = $csFactory->Create($srs);
       @$metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0);
+      try {
+        $epsgCode = $csFactory->ConvertWktToEpsgCode($srs);
+      } catch (MgException $e) {
+        //just catch the exception and set epsgCode to empty string
+      }
+
+
       //  $unitsType = $cs->GetUnits();
     }
     else
     {
       $metersPerUnit = 1.0;
       //$unitsType = "Meters";
-    }   
+    }
 
 
     header('Content-type: application/json');
@@ -91,6 +104,8 @@
     $mapObj->sessionId = $sessionID;
     $mapObj->mapId = $mapid;
     $mapObj->metersPerUnit = $metersPerUnit;
+    $mapObj->wkt = $srs;
+    $mapObj->epsg = $epsgCode;
     $mapObj->siteVersion = GetSiteVersion();
 
     $mapObj->mapTitle=addslashes($mapTitle);
@@ -101,15 +116,15 @@
     $mapObj->extent = array($oMin->GetX(), $oMin->GetY(), $oMax->GetX(), $oMax->GetY());
 
     $layers=$map->GetLayers();
-    
+
     //layers
     $mapObj->layers = array();
 
 
     $mapObj->layers = array();
-    for($i=0;$i<$layers->GetCount();$i++) 
-    { 
-        //only output layers that are part of the 'Normal Group' and 
+    for($i=0;$i<$layers->GetCount();$i++)
+    {
+        //only output layers that are part of the 'Normal Group' and
         //not the base map group used for tile maps.  (Where is the test for that Y.A.???)
 
         $layer=$layers->GetItem($i);
@@ -127,12 +142,22 @@
 
         $layerObj->resourceId = $layerDefinition->ToString();
         $layerObj->parentGroup = $layer->GetGroup() ? $layer->GetGroup()->GetObjectId() : '';
-        
+
         $layerObj->selectable = $layer->GetSelectable();
         $layerObj->visible = $layer->GetVisible();
         $layerObj->actuallyVisible = $layer->isVisible();
         $layerObj->editable = IsLayerEditable($resourceService, $layer);
 
+        $isBaseMapLayer = ($layer->GetLayerType() == MgLayerType::BaseMap);
+        $layerObj->isBaseMapLayer = $isBaseMapLayer;
+        if($isBaseMapLayer)
+        {
+        	$mapObj->hasBaseMapLayers = true;
+        }
+        else
+        {
+        	$mapObj->hasDynamicLayers = true;
+        }
 
         $layerObj->legendLabel = addslashes($layer->GetLegendLabel());
         $layerObj->displayInLegend = $layer->GetDisplayInLegend();
@@ -151,25 +176,25 @@
             $layerObj->maxScale = max($layerObj->maxScale, $oScaleRanges[$j]->maxScale);
         }
 
-        
+
         array_push($mapObj->layers, $layerObj);
-        
-    } 
 
+    }
+
     //Get layer groups as xml
     $groups = $map->GetLayerGroups();
     $mapObj->groups = array();
-    for($i=0;$i<$groups->GetCount();$i++) 
-    { 
+    for($i=0;$i<$groups->GetCount();$i++)
+    {
         $group=$groups->GetItem($i);
         array_push($mapObj->groups, OutputGroupInfo($group));
-    } 
+    }
 
     $mapObj->FiniteDisplayScales = array();
-    //FiniteDisplayScales for tiled maps    
+    //FiniteDisplayScales for tiled maps
     for ($i=0; $i<$map->GetFiniteDisplayScaleCount(); $i++)
     {
-    
+
         array_push($mapObj->FiniteDisplayScales, $map->GetFiniteDisplayScaleAt($i));
     }
     echo var2json($mapObj);
@@ -193,20 +218,20 @@
 /************************************************************************/
 function GetLayerTypesFromResourceContent($layer)
 {
-    $aLayerTypes = array();						
+    $aLayerTypes = array();
     global $resourceService;
 
     try
     {
         $dataSourceId = new MgResourceIdentifier($layer->GetFeatureSourceId());
         if($dataSourceId->GetResourceType() == MgResourceType::DrawingSource)
-          array_push($aLayerTypes, '5');// DWF 
+          array_push($aLayerTypes, '5');// DWF
         else
         {
             $resID = $layer->GetLayerDefinition();
             $layerContent = $resourceService->GetResourceContent($resID);
             $xmldoc = DOMDocument::loadXML(ByteReaderToString($layerContent));
-    
+
             $gridlayers = $xmldoc->getElementsByTagName('GridLayerDefinition');
             if ($gridlayers->length > 0)
               array_push($aLayerTypes, '4');// raster
@@ -250,7 +275,7 @@
     }
 }
 
-function buildScaleRanges($layer) 
+function buildScaleRanges($layer)
 {
     $aScaleRanges = array();
     global $resourceService;
@@ -287,31 +312,31 @@
             $minScale = $minElt->item(0)->nodeValue;
         if($maxElt->length > 0)
             $maxScale = $maxElt->item(0)->nodeValue;
-           
+
         $scaleRangeObj->minScale = $minScale;
         $scaleRangeObj->maxScale = $maxScale;
 
-        
+
         if($type != 0) {
             array_push($aScaleRanges, $scaleRangeObj);
             break;
         }
-            
-        
+
+
         $styleIndex = 0;
         for($ts=0, $count = count($typeStyles); $ts < $count; $ts++)
         {
             $typeStyle = $scaleRange->getElementsByTagName($typeStyles[$ts]);
             $catIndex = 0;
             for($st = 0; $st < $typeStyle->length; $st++) {
-                
+
                 $styleObj = NULL;
                 // We will check if this typestyle is going to be shown in the legend
                 $showInLegend = $typeStyle->item($st)->getElementsByTagName("ShowInLegend");
                 if($showInLegend->length > 0)
                     if($showInLegend->item(0)->nodeValue == "false")
                         continue;   // This typestyle does not need to be shown in the legend
-                        
+
                 $rules = $typeStyle->item(0)->getElementsByTagName($ruleNames[$ts]);
                 for($r = 0; $r < $rules->length; $r++) {
                     $rule = $rules->item($r);
@@ -330,7 +355,7 @@
             }
         }
         array_push($aScaleRanges, $scaleRangeObj);
-        
+
     }
     return $aScaleRanges;
 }
@@ -360,7 +385,9 @@
     $groupObj->parentUniqueId = $parent != null ? $parent->GetObjectId() : '';
     $groupObj->visible = $group->GetVisible();
     $groupObj->actuallyVisible = $group->isVisible();
-    
+    $isBaseMapGroup = ($group->GetLayerGroupType() == MgLayerGroupType::BaseMap);
+    $groupObj->isBaseMapGroup =  $isBaseMapGroup;
+
     return $groupObj;
 }
 

Modified: branches/fusion-2.0/layers/MapGuide/php/LoadScaleRanges.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/LoadScaleRanges.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/LoadScaleRanges.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -27,11 +27,16 @@
  * Utility function to load scale ranges for the layers. Initially
  * scale ranges were returned as part of in LoadMap.php. This allows
  * to reduce the size of information that is returned by LoadMap, by putting
- * elements that are unnessary to the map draw her.  
+ * elements that are unnessary to the map draw her.
  *****************************************************************************/
 
 
 include ("Common.php");
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('../../../common/php/Utilities.php');
 include('Utilities.php');
 
@@ -43,10 +48,10 @@
 $scaleObj = NULL;
 $scaleObj->layers = array();
 
-for($i=0;$i<$layers->GetCount();$i++) 
-{    
+for($i=0;$i<$layers->GetCount();$i++)
+{
     $layer=$layers->GetItem($i);
-    if (isset($_SESSION['scale_ranges']) && 
+    if (isset($_SESSION['scale_ranges']) &&
         isset($_SESSION['scale_ranges'][$layer->GetObjectId()]))
     {
         $scaleranges = $_SESSION['scale_ranges'][$layer->GetObjectId()];

Modified: branches/fusion-2.0/layers/MapGuide/php/MapMenu.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/MapMenu.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/MapMenu.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,11 @@
  *****************************************************************************/
 
 include ("Common.php");
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('../../../common/php/Utilities.php');
 
 //Get the folder to search within
@@ -48,7 +53,7 @@
 $result = NULL;
 
 $result->maps = array();
-for ( $i=0; $i < $aMapIds->length; $i++ ) { 
+for ( $i=0; $i < $aMapIds->length; $i++ ) {
     $mapId = new MgResourceIdentifier($aMapIds->item($i)->nodeValue);
     $md = NULL;
     $md->path = $aMapIds->item($i)->nodeValue;

Modified: branches/fusion-2.0/layers/MapGuide/php/Measure.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/Measure.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/Measure.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,14 +29,19 @@
  *****************************************************************************/
 
 include ('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include ('Utilities.php');
 
 try {
-    if (!isset($_REQUEST['session']) || 
+    if (!isset($_REQUEST['session']) ||
         !isset($_REQUEST['mapname']) ||
-        !isset($_REQUEST['x1']) || 
-        !isset($_REQUEST['y1']) || 
-        !isset($_REQUEST['x2']) || 
+        !isset($_REQUEST['x1']) ||
+        !isset($_REQUEST['y1']) ||
+        !isset($_REQUEST['x2']) ||
         !isset($_REQUEST['y2'])) {
         echo "<Error>Arguments missing </Error>";
         exit;
@@ -56,7 +61,7 @@
     } else {
         $distance = $srsMap->MeasureEuclideanDistance($x1, $y1, $x2, $y2);
     }
-    $distance = $srsMap->ConvertCoordinateSystemUnitsToMeters($distance);   
+    $distance = $srsMap->ConvertCoordinateSystemUnitsToMeters($distance);
     header('Content-type: application/json');
     header('X-JSON: true');
     echo "{distance:$distance}";
@@ -67,4 +72,4 @@
     echo $e->GetDetails() . "\n";
     echo $e->GetStackTrace() . "\n";
 }
-?>
\ No newline at end of file
+?>

Modified: branches/fusion-2.0/layers/MapGuide/php/Query.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/Query.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/Query.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -32,6 +32,11 @@
 try {
     /* set up the session */
     include ("Common.php");
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorText();
+        exit;
+    }
     include('../../../common/php/Utilities.php');
     include('Utilities.php');
 

Modified: branches/fusion-2.0/layers/MapGuide/php/SaveMap.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/SaveMap.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/SaveMap.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -28,6 +28,11 @@
  * Purpose: get map initial information
  *****************************************************************************/
 include('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 $format     = isset($_REQUEST['format']) ? $_REQUEST['format'] : 'PNG';
 $layout     = isset($_REQUEST['layout']) ? $_REQUEST['layout'] : null;
 $scale      = isset($_REQUEST['scale']) ? $_REQUEST['scale'] : null;
@@ -42,10 +47,10 @@
     $renderingService = $siteConnection->CreateService(MgServiceType::RenderingService);
     $map = new MgMap();
     $map->Open($resourceService, $mapName);
-    
+
     $selection = new MgSelection($map);
     $selection->Open($resourceService, $mapName);
-    
+
     //get current center as a coordinate
     $center = $map->GetViewCenter()->GetCoordinate();
 
@@ -65,9 +70,9 @@
                                             $aMargins[2],
                                             $aMargins[3]
                                             );
-        
+
         $dwfVersion = new MgDwfVersion('6.01','1.2');
-        
+
         $oImg = $mappingService->GeneratePlot($map,
                                           $center,
                                           $scale,

Modified: branches/fusion-2.0/layers/MapGuide/php/SaveMapFrame.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/SaveMapFrame.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/SaveMapFrame.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -25,7 +25,7 @@
  */
 
 /*****************************************************************************
- * Purpose: 
+ * Purpose:
  *****************************************************************************/
 ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 
@@ -44,7 +44,11 @@
 <H4>Preparing Image for download...</H4>
 <?php
 include('Common.php');
-
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorHTML();
+    exit;
+}
 $szLayout="";
 if (isset($_REQUEST['layout']) &&  $_REQUEST['layout'] != "") {
   $szLayout = "&layout=".$_REQUEST['layout'];

Modified: branches/fusion-2.0/layers/MapGuide/php/SaveSelection.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/SaveSelection.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/SaveSelection.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -25,6 +25,11 @@
  */
 
 include('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('../../../common/php/Utilities.php');
 include('Utilities.php');
 
@@ -88,7 +93,7 @@
 
 
     } catch(MgException $e) {
-        echo "/* SetSelection Exception: " . $e->GetDetails()."*/";
+        echo "ERROR: " . $e->GetDetails() . "\n";
     }
 
 function GetParameters($params)

Modified: branches/fusion-2.0/layers/MapGuide/php/Selection.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/Selection.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/Selection.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -25,11 +25,16 @@
  */
 
 /*****************************************************************************
- * Purpose: Get all attribute informations for elements in the 
+ * Purpose: Get all attribute informations for elements in the
  * current selection
  *****************************************************************************/
 
 include('Common.php');
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorText();
+    exit;
+}
 include('../../../common/php/Utilities.php');
 include('Utilities.php');
 
@@ -45,7 +50,7 @@
       $aLayers = split(",", $_REQUEST['layers']);
       $bAllLayers = 0;
     }
-    
+
     $aStartCount = array();
     if (isset($_REQUEST['startcount']) && $_REQUEST['startcount'] !='')
     {
@@ -58,7 +63,7 @@
         echo "error : number of layers and number of startcount should be the same";
         exit;
     }
-    
+
     $properties = $_SESSION['selection_array'];
 
     $aSelectedLayers = $properties->layers;
@@ -73,7 +78,7 @@
         for ($i=0; $i<count($aSelectedLayers); $i++)
         {
             $layerName =  $aSelectedLayers[$i];
-            if (($bAllLayers || in_array($layerName, $aLayers)) && 
+            if (($bAllLayers || in_array($layerName, $aLayers)) &&
                 isset($properties->$layerName) &&
                 $properties->$layerName->numelements > 0)
             {
@@ -82,10 +87,10 @@
                 $result->$layerName->propertyvalues = $properties->$layerName->propertyvalues;
                 $result->$layerName->propertytypes = $properties->$layerName->propertytypes;
                 $result->$layerName->metadatanames = $properties->$layerName->metadatanames;
-                
+
                 /*if start and count are given, validate them. If valid return the valid elements.
                   if not return all elements. */
-                 
+
                 $start = -1;
                 $count = -1;
                 if (count($aStartCount) > 0)
@@ -105,7 +110,7 @@
                     }
 
                     /*invalid entries*/
-                    if ($start < 0 || $count <=0 || 
+                    if ($start < 0 || $count <=0 ||
                         $start >= $properties->$layerName->numelements ||
                         $count > $properties->$layerName->numelements ||
                         ($start + $count) > $properties->$layerName->numelements)
@@ -123,7 +128,7 @@
                 }
                 //print_r($properties->$layerName);
                 $result->$layerName->numelements = $count;
-        
+
                 $result->$layerName->values = array();
                 $result->$layerName->metadata = array();
                 $iIndice = 0;

Modified: branches/fusion-2.0/layers/MapGuide/php/SetLayers.php
===================================================================
--- branches/fusion-2.0/layers/MapGuide/php/SetLayers.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapGuide/php/SetLayers.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -37,62 +37,67 @@
 try {
     /* set up the session */
     include ("Common.php");
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorText();
+        exit;
+    }
     include('../../../common/php/Utilities.php');
     include('Utilities.php');
 
-	/* the name of the layer in the map to query */
-	if ($_REQUEST['layerindex'] != '') {
-		$layers = explode(',',$_REQUEST['layerindex']);
-	} else {
-		$layers = array();
-	}
+    /* the name of the layer in the map to query */
+    if ($_REQUEST['layerindex'] != '') {
+        $layers = explode(',',$_REQUEST['layerindex']);
+    } else {
+        $layers = array();
+    }
 
     /* open the map from the session using the provided map name.  The map was
        previously created by calling LoadMap. */
     $map = new MgMap();
     $map->Open($resourceService, $mapName);
-	$mapLayers = $map->GetLayers();
-	
-	
-	$nIndex = count($layers);
-	$nLayers = $mapLayers->GetCount();
+    $mapLayers = $map->GetLayers();
+
+
+    $nIndex = count($layers);
+    $nLayers = $mapLayers->GetCount();
     for ($i=0; $i<$nLayers; $i++) {
-		if ($layers[$i] == $i) {
-			continue;
-		}
-		$found = -1;
-		for ($j=$i+1; $j<$nIndex; ++$j) {
-			if ($layers[$j] == $i) {
-				$found = $j;
-				break;
-			}
-		}
-		if ($found >= 0) {
-			$layerToMove = $mapLayers->GetItem($i);
-			//$layerDef = $layerToMove->GetLayerDefinition();
-			//$mapLayers->Insert($found, new MgLayerBase($layerDef,$resourceService));
-			$mapLayers->RemoveAt($i);
-			$mapLayers->Insert($found, $layerToMove);
-		} else {
-			$mapLayers->RemoveAt($i);
-		}
-		break;
-	}
-	/*
-	$nLayers = count($layers);
-	$layerDefs = array();
+        if ($layers[$i] == $i) {
+            continue;
+        }
+        $found = -1;
+        for ($j=$i+1; $j<$nIndex; ++$j) {
+            if ($layers[$j] == $i) {
+                $found = $j;
+                break;
+            }
+        }
+        if ($found >= 0) {
+            $layerToMove = $mapLayers->GetItem($i);
+            //$layerDef = $layerToMove->GetLayerDefinition();
+            //$mapLayers->Insert($found, new MgLayerBase($layerDef,$resourceService));
+            $mapLayers->RemoveAt($i);
+            $mapLayers->Insert($found, $layerToMove);
+        } else {
+            $mapLayers->RemoveAt($i);
+        }
+        break;
+    }
+    /*
+    $nLayers = count($layers);
+    $layerDefs = array();
     for ($i=0; $i<$nLayers; $i++) {
-		$layer = $mapLayers->GetItem($layers[$i]);
-		array_push($layerDefs, $layer->GetLayerDefinition() );
-	}
-	$mapLayers->Clear();
-	
-	$nLayers = count($layerDefs);
+        $layer = $mapLayers->GetItem($layers[$i]);
+        array_push($layerDefs, $layer->GetLayerDefinition() );
+    }
+    $mapLayers->Clear();
+
+    $nLayers = count($layerDefs);
     for ($i=0; $i<$nLayers; $i++) {
-		$layer = new MgLayer(new MgResourceIdentifier($layerDefs[$i]), $resourceService);
-		$mapLayers->Add($layer);
-	}
-	*/
+        $layer = new MgLayer(new MgResourceIdentifier($layerDefs[$i]), $resourceService);
+        $mapLayers->Add($layer);
+    }
+    */
 
     $map->Save($resourceService);
     echo "success: true";

Copied: branches/fusion-2.0/layers/MapGuide/php/cp_arr.gif (from rev 2103, trunk/layers/MapGuide/php/cp_arr.gif)
===================================================================
(Binary files differ)

Copied: branches/fusion-2.0/layers/MapGuide/php/cp_arr_dis.gif (from rev 2103, trunk/layers/MapGuide/php/cp_arr_dis.gif)
===================================================================
(Binary files differ)


Property changes on: branches/fusion-2.0/layers/MapServer
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/fusion-2.0/layers/MapServer/MapServer.js
===================================================================
--- branches/fusion-2.0/layers/MapServer/MapServer.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/MapServer.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -42,6 +42,8 @@
     layerMetadataKeys: null,
     oMaptip:null,
     bMapTipFired: false,
+    bRestoreMapState: false,
+    oRestoredState: {},
 
     //the map file
     sMapFile: null,
@@ -62,6 +64,16 @@
           Fusion.queryParams['theme'] = null;
         }
 
+        var restoreMapState = Fusion.getQueryParam('restoreState');
+        if (restoreMapState != '') {
+          //clear the query param after it has been used once
+          this.oRestoredState.id = restoreMapState;
+          Fusion.queryParams['restoreState'] = null;
+          // set flag to true so we can restore the map from a saved session.
+          this.bRestoreMapState = true;
+        }
+        
+
         this.mapMetadataKeys = mapTag.extension.MapMetadata ? mapTag.extension.MapMetadata[0] : null;
         this.layerMetadataKeys = mapTag.extension.LayerMetadata ? mapTag.extension.LayerMetadata[0] : null;
         
@@ -109,12 +121,63 @@
             var o;
             eval('o='+r.responseText);
             this.session[0] = o.sessionId;
-            this.triggerEvent(Fusion.Event.MAP_SESSION_CREATED);
+            var acceptLang = o.acceptLanguage.split(',');
+            //IE - en-ca,en-us;q=0.8,fr;q=0.5,fr-ca;q=0.3
+            //FF - en-us,en;q=0.5
+            for (var i=0; i<acceptLang.length; ++i) {
+              var locale = acceptLang[i].split(";");
+              Fusion.initializeLocale(locale[0]);
+              break;
+            }
+
+            /* Session is created, Check to see if we are going to restore a saved
+                map state and restore it if set to true.
+            */
+            if(this.bRestoreMapState == true){
+                var that = this;
+                var sl = Fusion.getScriptLanguage();
+                var scriptURL = 'layers/' + this.arch + '/' + sl + '/RestoreState.' + sl;
+
+                var params = {
+                    parameters: OpenLayers.Util.getParameterString({
+                        session: this.session[0] ,
+                        id: this.oRestoredState.id
+                    }),
+                    onComplete: function(xhr) {
+                        var o;
+                        eval('o='+xhr.responseText);
+                        that.restoreStateCB(o);
+                    }
+                };
+                Fusion.ajaxRequest(scriptURL,params);
+            }
+            else
+            {
+                // done with session create, fire the event.
+                this.triggerEvent(Fusion.Event.MAP_SESSION_CREATED);
+            }
+            
         }
     },
 
+    restoreStateCB: function(oResponse){
+        if(oResponse.error){
+            Fusion.reportError(new Fusion.Error(Fusion.Error.WARNING, "Error Restoring Map State - "+oResponse.error));
+        }
+        else
+        {
+        this.oRestoredState = oResponse;
+        }
+        // done with session create, fire the event.
+        this.triggerEvent(Fusion.Event.MAP_SESSION_CREATED);
+    },
+
     mapSessionCreated: function() {
-        if (this.sMapFile != '') {
+        // restore the mapfile from a saved state.
+        if(this.bRestoreMapState === true && this.oRestoredState.loadmap ){
+            this.loadMap(this.oRestoredState.loadmap);
+        }
+        else if (this.sMapFile != '') {
             this.loadMap(this.sMapFile);
         }
         window.setInterval(OpenLayers.Function.bind(this.pingServer, this), 
@@ -191,16 +254,12 @@
             if (o.projString.length > 0) {
               var epsg = o.projString.indexOf("init=");
               if (epsg >= 0) {
-                this.projCode = o.projString.substring(epsg+5).toUpperCase();
+                this.mapTag.layerOptions.projection = o.projString.substring(epsg+5).toUpperCase();
               } else {
-                this.projCode = o.mapName.toUpperCase();
-                Proj4js.defs[this.projCode] = o.projString;
+                this.mapTag.layerOptions.projection = o.mapName.toUpperCase();
+                Proj4js.defs[this.mapTag.layerOptions.projection] = o.projString;
               }
             }
-            if (this.projCode) {
-              this.mapWidget.setProjection(this.projCode);
-            }
-            this.mapWidget.setMetersPerUnit(o.metersPerUnit);
 
             this.mapTag.layerOptions.maxExtent = OpenLayers.Bounds.fromArray(o.extent);
 
@@ -230,12 +289,11 @@
             }
 
             //to allow for scaling that doesn't match any of the pre-canned units
-            this.units = Fusion.getClosestUnits(o.metersPerUnit);
+            this.mapTag.layerOptions.units = Fusion.getClosestUnits(o.metersPerUnit);
             
             var layerOptions = {
       				singleTile: true,
       				ratio: this.ratio,
-              units: this.units,
               maxResolution: 'auto',
       				minScale: maxScale,	//OL interpretation of min/max scale is reversed from Fusion
       				maxScale: minScale
@@ -247,7 +305,7 @@
               layers: this.aVisibleLayers.join(' '),
               session: this.getSessionID(),
               map: this._sMapFile,
-              map_imagetype: this.sImageType
+              map_imagetype: this._sImageType
             };
             OpenLayers.Util.extend(params, this.mapTag.layerParams);
 
@@ -267,9 +325,7 @@
 
             if (this.bIsMapWidgetLayer) {
               this.mapWidget.addMap(this);
-              this.mapWidget.oMapOL.units = this.oLayerOL.units;
             }
-
             this.bMapLoaded = true;
         }
         else
@@ -326,24 +382,24 @@
         Fusion.ajaxRequest(loadmapScript, options);
     },
 
-    scaleRangesLoaded: function(userFunc, r) 
-    {
-        if (r.status == 200) 
-        {
+    scaleRangesLoaded: function(userFunc, r) {
+        if (r.status == 200) {
             var o;
             eval('o='+r.responseText);
-            if (o.layers && o.layers.length > 0)
-            {
-                for (var i=0; i<o.layers.length; i++)
-                {
+            
+            if (o.layers && o.layers.length > 0) {
+                var iconOpt = {
+                    url: o.icons_url || null,
+                    width: o.icons_width || 16,
+                    height: o.icons_height || 16
+                };
+                for (var i=0; i<o.layers.length; i++) {
                     var oLayer = this.getLayerById(o.layers[i].uniqueId);
-                    if (oLayer)
-                    {
+                    if (oLayer) {
                         oLayer.scaleRanges = [];
-                        for (var j=0; j<o.layers[i].scaleRanges.length; j++) 
-                        {
+                        for (var j=0; j<o.layers[i].scaleRanges.length; j++) {
                             var scaleRange = new Fusion.Layers.ScaleRange(o.layers[i].scaleRanges[j], 
-                                                                                 oLayer.layerType);
+                                                                                 oLayer.layerType, iconOpt);
                             oLayer.scaleRanges.push(scaleRange);
                         }
                     }
@@ -393,31 +449,29 @@
     },
 
     mapLayersReset: function(aLayerIndex,r) {
-      if (r.status == 200) {
+        //console.log("mapLayersReset");
         var o;
         eval('o='+r.responseText);
-  			if (o.success) {
-  				var layerCopy = $A(this.aLayers);
-          var nLayers = layerCopy.length -1;
-          
-          //Mapserver has list of layers reversed from MapGuide
-          aLayerIndex.reverse();
-    
-  				this.aLayers = [];
-  				this.aVisibleLayers = [];
+        if (o.success) {
+            var layerCopy = $A(this.aLayers);
+            var nLayers = layerCopy.length -1;
+            //Mapserver has list of layers reversed from MapGuide
+            aLayerIndex.reverse();
 
-          for (var i=0; i<aLayerIndex.length; ++i) {
-            this.aLayers.push( layerCopy[ nLayers - aLayerIndex[i] ] );
-            if (this.aLayers[i].visible) {
-                this.aVisibleLayers.push(this.aLayers[i].layerName);
+            this.aLayers = [];
+            this.aVisibleLayers = [];
+
+            for (var i=0; i<aLayerIndex.length; ++i) {
+                this.aLayers.push( layerCopy[aLayerIndex[i] ] );
+                if (this.aLayers[i].visible) {
+                    this.aVisibleLayers.push(this.aLayers[i].layerName);
+                }
             }
-  				}
-  				//this.layerRoot.clear();
+            //this.layerRoot.clear();
+            this.drawMap();
+            this.triggerEvent(Fusion.Event.MAP_LAYER_ORDER_CHANGED);
+        }
 
-  				this.drawMap();
-  				this.triggerEvent(Fusion.Event.MAP_LAYER_ORDER_CHANGED);
-        }
-      }
     },
 
     parseMapLayersAndGroups: function(o) {
@@ -797,7 +851,7 @@
         }
     },
 
-    getLegendImageURL: function(fScale, layer, style) {
+    getLegendImageURL: function(fScale, layer, style,defaultIcon) {
         var sl = Fusion.getScriptLanguage();
         var url = Fusion.getFusionURL() + '/layers/' + this.arch + '/' + sl  + '/LegendIcon.' + sl;
         var sessionid = this.getSessionID();
@@ -817,6 +871,20 @@
             var geometry = 'POLYGON(('+ minx + ' ' + miny + ', ' + minx + ' ' + maxy + ', ' + maxx + ' ' + maxy + ', ' + maxx + ' ' + miny + ', ' + minx + ' ' + miny + '))';
             var selectionType = "INTERSECTS";
 
+           var aVisLayers = [];
+           
+           for(var i = 0; i<this.aLayers.length;i++ ){
+                var iLayerMinScale = this.aLayers[i].scaleRanges[0].minScale;
+                var iLayerMaxScale = this.aLayers[i].scaleRanges[0].maxScale;
+                var iCurrentScale = this.mapWidget.getScale();
+
+                if(iCurrentScale < iLayerMaxScale && iCurrentScale > iLayerMinScale){
+                    if(this.aLayers[i].isVisible() === true){
+                        aVisLayers.push(this.aLayers[i].layerName);
+                    }
+                }
+           }
+
             var loadmapScript = '/layers/'+ this.arch + '/php/Maptip.php';
             var params = {
                 'mapname': this._sMapname,
@@ -827,7 +895,9 @@
                 'layer': oMapTips.aLayers || '',
                 'textfield': oMapTips.aTextFields || '',
                 'label': oMapTips.aLabels || '',
-                'customURL': oMapTips.aCustomURL || ''
+                'customURL': oMapTips.aCustomURL || '',
+                'visLayers' : aVisLayers
+                
             }
             var parseMapTip = this.parseMapTip.bind(this);
             this.bMapTipFired = true;

Modified: branches/fusion-2.0/layers/MapServer/php/CreateSession.php
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/CreateSession.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/php/CreateSession.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -41,5 +41,6 @@
 $result = null;
 $result->sessionId = $sessionId;
 $result->userName = '';
+$result->acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
 echo var2json($result);
 ?>

Modified: branches/fusion-2.0/layers/MapServer/php/LegendIcon.php
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/LegendIcon.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/php/LegendIcon.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,125 +1,130 @@
-<?php
-/**
- * LegendIcon
- *
- * $Id$
- *
- * Copyright (c) 2007, DM Solutions Group Inc.
- * 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.
- */
+<?php
+/**
+ * LegendIcon
+ *
+ * $Id$
+ *
+ * Copyright (c) 2007, DM Solutions Group Inc.
+ * 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.
+ */
+
+/*****************************************************************************
+ * Purpose: Draw a legend icon
+ *****************************************************************************/
+
+/* set up the session */
+include(dirname(__FILE__).'/../../../common/php/Utilities.php');
+include(dirname(__FILE__).'/Common.php');
+include(dirname(__FILE__).'/Utilities.php');
 
-/*****************************************************************************
- * Purpose: Draw a legend icon
- *****************************************************************************/
-
-include(dirname(__FILE__).'/Common.php');
-
-if (!isset($mapName)) {
-    die('mapname not set');
-}
-
-$legendIconCacheFile = "";
-
-if (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
-      $configObj = $_SESSION['fusionConfig'];
-      /* if the legendIconCache dir is set */
-      if (isset($configObj->mapserver->legendIconCacheDir)) {
-        $legendIconCacheDir = $configObj->mapserver->legendIconCacheDir;
-
-        // check for closing '/'
-        $legendIconCacheDir = str_replace( '\\', '/', trim( $legendIconCacheDir ) );
-        if ( substr( $legendIconCacheDir, -1 ) != '/' )
-        {
-            $legendIconCacheDir .= '/';
-        }
-
-        $cacheLegendIcons = true;
-        $str = file_get_contents($_SESSION['maps'][$mapName]);
-        /* create a unique location for the map icons based on
-         * the content of the of map file.  If the content changes
-         * then the icons should be rebuilt anyway
-         */
-        $legendIconCacheDir = $legendIconCacheDir.md5($str)."/";
-        if (!is_dir($legendIconCacheDir)) {
-          mkdir($legendIconCacheDir);
-        }
-        /* TODO: can we figure out what the content type is? */
-        $legendIconCacheFile = $legendIconCacheDir."_".$REQUEST_VARS['layername']."_".$REQUEST_VARS['classindex'].".png";
-        /* if the icon exists, return it */
-        if (file_exists($legendIconCacheFile)) {
-            /* TODO: can we figure out what the content type is? */
-            header('Content-type: image/png');
-            $etag = '"' . md5_file($legendIconCacheFile) . '"';
-            header ("ETag: " . $etag );
-            $cache_time = mktime(0, 0, 0, 1, 1, 2004);
-            $expires = 3600 * 256;
-            header("last-modified: " . gmdate("D, d M Y H:i:s",$cache_time) . " GMT");
-            $inm = split(',', getenv("HTTP_IF_NONE_MATCH"));
-            $send_body = true;
-            foreach ($inm as $i) {
-            	  if (trim($i) == $etag || trim($i) == $cache_time) {
-            		    header ("HTTP/1.0 304 Not Modified");
-            		    $send_body = false;
-            		}
-          	}
-            //last modified test
-            if(getenv("HTTP_IF_MODIFIED_SINCE") == gmdate("D, d M Y H:i:s",$cache_time). " GMT") {
-              	header ("HTTP/1.0 304 Not Modified"); 
-              	$send_body = false;
-          	}
-            //more headers
-            header("Expires: " . gmdate("D, d M Y H:i:s",$cache_time+$expires) . " GMT");
-            header("Cache-Control: max-age=$expires, must-revalidate");
-            //header('Content-Length: ' . strlen($body));
-            //if we're not cacheing
-            if ($send_body) {
-                readfile($legendIconCacheFile);
-            }
-            exit;
-        }
-    }
-
-    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
-    $oLayer = $oMap->getLayerByName($REQUEST_VARS['layername']);
-    $oClass = $oLayer->getClass($REQUEST_VARS['classindex']);
-    $width = $oMap->legend->keysizex;
-    $height = $oMap->legend->keysizey;
-    if ($width <=0) {
-        $width = 16;
-    }
-    if ($height <=0) {
-        $height = 16;
-    }
-    $oImg = $oClass->createLegendIcon($width, $height);
-    /* TODO: can we figure out what the content type is? */
-    header('Content-type: image/png');
-    if ($cacheLegendIcons) {
-        $oImg->saveImage($legendIconCacheFile);
-        $etag = '"' . md5_file($legendIconCacheFile) . '"';
-        header ("ETag: " . $etag );
-        $cache_time = mktime(0, 0, 0, 1, 1, 2004);
-        $expires = 3600 * 256;
-        header("last-modified: " . gmdate("D, d M Y H:i:s",$cache_time) . " GMT");
-        readfile($legendIconCacheFile);
-    } else {
-      $oImg->saveImage("");
-    }
-    $oImg->free();
-}
-?>
+if (!isset($mapName)) {
+    die('mapname not set');
+}
+
+$mapFile = getSessionSavePath().$mapName.".map";
+$str = file_get_contents($mapFile);
+$legendIconCacheFile = "";
+
+if ($str) {
+      $configObj = $_SESSION['fusionConfig'];
+      /* if the legendIconCache dir is set */
+      if (isset($configObj->mapserver->legendIconCacheDir)) {
+        $legendIconCacheDir = $configObj->mapserver->legendIconCacheDir;
+
+        // check for closing '/'
+        $legendIconCacheDir = str_replace( '\\', '/', trim( $legendIconCacheDir ) );
+        if ( substr( $legendIconCacheDir, -1 ) != '/' )
+        {
+            $legendIconCacheDir .= '/';
+        }
+
+        $cacheLegendIcons = true;
+        //$str = file_get_contents($_SESSION['maps'][$mapName]);
+        /* create a unique location for the map icons based on
+         * the content of the of map file.  If the content changes
+         * then the icons should be rebuilt anyway
+         */
+        $legendIconCacheDir = $legendIconCacheDir.md5($str)."/";
+        if (!is_dir($legendIconCacheDir)) {
+          mkdir($legendIconCacheDir);
+        }
+        /* TODO: can we figure out what the content type is? */
+        $legendIconCacheFile = $legendIconCacheDir."_".$REQUEST_VARS['layername']."_".$REQUEST_VARS['classindex'].".png";
+        /* if the icon exists, return it */
+        if (file_exists($legendIconCacheFile)) {
+            /* TODO: can we figure out what the content type is? */
+            header('Content-type: image/png');
+            $etag = '"' . md5_file($legendIconCacheFile) . '"';
+            header ("ETag: " . $etag );
+            $cache_time = mktime(0, 0, 0, 1, 1, 2004);
+            $expires = 3600 * 256;
+            header("last-modified: " . gmdate("D, d M Y H:i:s",$cache_time) . " GMT");
+            $inm = split(',', getenv("HTTP_IF_NONE_MATCH"));
+            $send_body = true;
+            foreach ($inm as $i) {
+            	  if (trim($i) == $etag || trim($i) == $cache_time) {
+            		    header ("HTTP/1.0 304 Not Modified");
+            		    $send_body = false;
+            		}
+          	}
+            //last modified test
+            if(getenv("HTTP_IF_MODIFIED_SINCE") == gmdate("D, d M Y H:i:s",$cache_time). " GMT") {
+              	header ("HTTP/1.0 304 Not Modified"); 
+              	$send_body = false;
+          	}
+            //more headers
+            header("Expires: " . gmdate("D, d M Y H:i:s",$cache_time+$expires) . " GMT");
+            header("Cache-Control: max-age=$expires, must-revalidate");
+            //header('Content-Length: ' . strlen($body));
+            //if we're not cacheing
+            if ($send_body) {
+                readfile($legendIconCacheFile);
+            }
+            exit;
+        }
+    }
+
+    $oMap = ms_newMapObj($mapFile);
+    $oLayer = $oMap->getLayerByName($REQUEST_VARS['layername']);
+    $oClass = $oLayer->getClass($REQUEST_VARS['classindex']);
+    $width = $oMap->legend->keysizex;
+    $height = $oMap->legend->keysizey;
+    if ($width <=0) {
+        $width = 16;
+    }
+    if ($height <=0) {
+        $height = 16;
+    }
+    $oImg = $oClass->createLegendIcon($width, $height);
+    /* TODO: can we figure out what the content type is? */
+    header('Content-type: image/png');
+    if ($cacheLegendIcons) {
+        $oImg->saveImage($legendIconCacheFile);
+        $etag = '"' . md5_file($legendIconCacheFile) . '"';
+        header ("ETag: " . $etag );
+        $cache_time = mktime(0, 0, 0, 1, 1, 2004);
+        $expires = 3600 * 256;
+        header("last-modified: " . gmdate("D, d M Y H:i:s",$cache_time) . " GMT");
+        readfile($legendIconCacheFile);
+    } else {
+      $oImg->saveImage("");
+    }
+    $oImg->free();
+}
+?>


Property changes on: branches/fusion-2.0/layers/MapServer/php/LegendIcon.php
___________________________________________________________________
Deleted: svn:eol-style
   - native

Modified: branches/fusion-2.0/layers/MapServer/php/LoadMap.php
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/LoadMap.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/php/LoadMap.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,419 +1,420 @@
-<?php
-/**
- * LoadMap
- *
- * $Id$
- *
- * Copyright (c) 2007, DM Solutions Group Inc.
- * 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.
- */
-
-/*****************************************************************************
- * Purpose: Load a mapfile into the session and return information about the
- *          map to the client
- *****************************************************************************/
-
-/* Common starts the session */
-include(dirname(__FILE__).'/../../../common/php/Utilities.php');
-include(dirname(__FILE__).'/Common.php');
-include(dirname(__FILE__).'/Utilities.php');
-
-/* if scales are not set, these become the default values */
-define('MIN_SCALE', 1);
-define('MAX_SCALE', 1000000000);
-
-/* could potentially make this optional */
-$moveToSession = true;
-
-/**
-   TODO make it possible to specify only a relative path
-   in the WebLayout and have this code know where to
-   look for it on the server somehow
- */
-
-/* only do something if a mapfile was requested */
-if (isset($_REQUEST['mapfile'])) {
-
-    /* look for mapFileRoot specified in config.json and test to see if the map path in appdef is realitive to it.*/
-    $configObj = $_SESSION['fusionConfig'];
-    $szFusionRoot = dirname(__FILE__).'/../../../'; // TODO : not a very elegant way of doing this
-    $szDblSeparator = DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR;
-
-    $szMapFromFusionRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$szFusionRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
-    $szMapFileRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$configObj->mapserver->mapFileRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
-
-    if( file_exists($szMapFileRoot) ) {
-        /* use the realitive path specified in config.json */
-        $szMapFile = $szMapFileRoot;
-    }
-    else
-    {
-        if( file_exists($szMapFromFusionRoot) ) {
-            /* use the realitive path from fusion install root */
-            $szMapFile = $szMapFromFusionRoot;
-        }
-        else
-        {
-            /* use absolute path from appdef */
-            $szMapFile = $_REQUEST['mapfile'];
-        }
-    }
-
-    $oMap = ms_newMapObj($szMapFile);
-
-    /* optionally move the mapfile to the session */
-    if ($moveToSession) {
-        //path to map file in the session is used by the client
-        $mapId = getSessionSavePath().($oMap->name).".map";
-        //modify various paths if necessary
-        $pathToMap = dirname($szMapFile);
-        $cwd = getcwd();
-        chdir($pathToMap);
-        $shapePath = $oMap->shapepath;
-        $oMap->set('shapepath', realpath($shapePath));
-        $symbolSet = $oMap->symbolsetfilename;
-        if ($symbolSet != '') {
-            $oMap->setSymbolSet(realpath($symbolSet));
-        }
-        $fontSet = $oMap->fontsetfilename;
-        if ($fontSet != '') {
-            $oMap->setFontSet(realpath($fontSet));
-        }
-        /* need to modify all image symbols reference in the map file
-         eg STYLE
-             SYMBOL "../etc/markers/target-7.gif" : this is relative to the map file
-        */
-
-        for ($i=0; $i<$oMap->numlayers; $i++)
-        {
-            $oLayer = &$oMap->GetLayer($i);
-            /* check layername for invalid URI characters and replace */
-            $oLayer->set("name",replaceInvalidLayerName($oLayer->name));
-
-            for ($j=0; $j<$oLayer->numclasses; $j++)
-            {
-                $oClass = $oLayer->GetClass($j);
-                /* if keyimage is defined, change the path*/
-                if ($oClass->keyimage && strlen($oClass->keyimage) > 0)
-                {
-                     $oClass->set("keyimage", realpath($oClass->keyimage));
-                }
-                for ($k=0; $k<$oClass->numstyles; $k++)
-                {
-                    $oStyle = $oClass->getStyle($k);
-                    if ($oStyle->symbolname != "")
-                    {
-                        if (file_exists(realpath($oStyle->symbolname)))
-                        {
-                            $oStyle->set("symbolname", realpath($oStyle->symbolname));
-                        }
-                    }
-                }
-            }
-        }
-        $oMap->save($mapId);
-        chdir($cwd);
-    } else {
-        $mapId = $_REQUEST['mapfile'];
-    }
-} elseif (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
-    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
-    $mapId = getSessionSavePath().($oMap->name).".map";
-}
-
-$mapObj = NULL;
-if ($oMap) {
-    header('Content-type: application/json');
-    header('X-JSON: true');
-    $mapObj->sessionId = $sessionID;
-    $mapObj->mapId = $mapId;
-
-    $mapObj->metadata = NULL;
-    if (isset($_REQUEST['map_metadata'])) {
-        $mapMetadataKeys = explode(',',$_REQUEST['map_metadata']);
-        foreach($mapMetadataKeys as $key) {
-            $mapObj->metadata->$key = $oMap->getMetadata($key);
-        }
-    }
-
-    $mapObj->projString = $oMap->getProjection();
-    $mapObj->metersPerUnit = GetMetersPerUnit($oMap->units);
-
-    $mapObj->dpi = $oMap->resolution;
-    $mapObj->imagetype = $oMap->imagetype;
-    $mapObj->mapName = $oMap->name;
-    if (!isset($_SESSION['maps'])) {
-        $_SESSION['maps'] = array();
-    }
-    if (!isset($_SESSION['maps'][$mapObj->mapName])) {
-        $_SESSION['maps'][$mapObj->mapName] = $mapId;
-    }
-    $mapObj->extent = array( $oMap->extent->minx, $oMap->extent->miny,
-                             $oMap->extent->maxx, $oMap->extent->maxy );
-    $minScale = $oMap->web->minscale == -1 ? MIN_SCALE : $oMap->web->minscale;
-    $maxScale = $oMap->web->maxscale == -1 ? MAX_SCALE : $oMap->web->maxscale;
-    $title = $oMap->getmetadata('legend_title');
-    $mapObj->mapTitle = $title == "" ? $mapObj->mapName : $title;
-    //layers
-    $mapObj->layers = array();
-    for ($i=0;$i<$oMap->numlayers;$i++)
-    {
-        $layer=$oMap->getLayer($i);
-        $layerObj = NULL;
-
-        /* Status Default - If a layer is status Default trac it in layerObj */
-        if($layer->status == MS_DEFAULT)
-            $layerObj->statusdefault = true;
-         else
-            $layerObj->statusdefault = false;
-
-        /* rename layes names with invalid characters */
-        $layer->set("name",replaceInvalidLayerName($layer->name));
-
-        $layerObj->metadata = NULL;
-        if (isset($_REQUEST['layer_metadata'])) {
-            $layerMetadataKeys = explode(',',$_REQUEST['layer_metadata']);
-            foreach($layerMetadataKeys as $key) {
-                $layerObj->metadata->$key = $layer->getMetadata($key);
-            }
-        }
-
-        //$extent = $layer->getExtent();
-        $layerObj->extent = NULL;
-        $layerObj->extent->minx = NULL;
-        $layerObj->extent->maxx = NULL;
-        $layerObj->extent->miny = NULL;
-        $layerObj->extent->maxy = NULL;
-
-         // only proceed if extent is valid
-        if( isset($GLOBALS["extent"]) )
-        {
-            $layerObj->extent->minx = $extent->minx;
-            $layerObj->extent->maxx = $extent->maxx;
-            $layerObj->extent->miny = $extent->miny;
-            $layerObj->extent->maxy = $extent->maxy;
-        }
-
-         $layerObj->propertyMappings = '';
-         $layerObj->uniqueId = $i;
-         $layerObj->layerName = $layer->name;
-         switch($layer->type) {
-             case MS_LAYER_POINT:
-                $type = 0;
-                break;
-             case MS_LAYER_LINE:
-                $type = 1;
-                break;
-             case MS_LAYER_POLYGON:
-                $type = 2;
-                break;
-             case MS_LAYER_RASTER:
-                $type = 4;
-                break;
-             case MS_LAYER_ANNOTATION:
-                $type = 8;
-                break;
-             default:
-                $type = 0;
-         }
-         $layerObj->layerTypes = array($type);
-
-         $displayInLegend = strtolower($layer->getMetaData('displayInLegend'));
-         $layerObj->displayInLegend = $displayInLegend == 'false' ? false : true;
-
-         $expandInLegend = strtolower($layer->getMetaData('expandInLegend'));
-         $layerObj->expandInLegend = $expandInLegend == 'false' ? false : true;
-         $layerObj->resourceId = $layer->name;
-         $layerObj->parentGroup = $layer->group;
-
-         $legendLabel = $layer->getMetaData('legendLabel');
-         if ($legendLabel == '') {
-             $legendLabel = $layer->name;
-         }
-         $layerObj->legendLabel = $legendLabel;
-
-         $selectable = strtolower($layer->getMetaData('selectable'));
-         $layerObj->selectable = $selectable == 'true' ? true : false;
-
-         $layerObj->visible = ($layer->status == MS_ON || $layer->status == MS_DEFAULT);
-         $layerObj->actuallyVisible = true;
-
-         $editable = strtolower($layer->getMetaData('editable'));
-         $layerObj->editable = $editable == 'true' ? true : false;
-
-         /* process the classes.  The legend expects things
-          * organized by scale range so we have to first
-          * find all the scale breaks, then create ranges
-          * for each scale break pair, then slot the classes
-          * into the scale ranges that they apply to.
-          */
-
-         $aScaleRanges = array();
-         //create a default scale range for the layer as a whole
-         $layerMin = $layer->minscale == -1 ? $minScale : $layer->minscale;
-         $layerMax = $layer->maxscale == -1 ? $maxScale : $layer->maxscale;
-
-        /* check to see that the layer has a vaild scale range
-         * inside the defined map's main min max scale ranges
-         * set them to the maps scale ranges if they exceede 
-         */
-        if($layer->minscale != -1 && $layerMin < $minScale)
-            $layerMin = $minScale;
-
-        if($layer->maxscale != -1 && $layerMax > $maxScale)
-            $layerMax = $maxScale;
-
-         //find all the unique scale breaks in this layer
-         $aScaleBreaks = array($layerMin, $layerMax);
-         for ($j=0; $j<$layer->numclasses; $j++) {
-             $oClass = $layer->getClass($j);
-             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
-             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
-             if (!in_array($classMin, $aScaleBreaks)) {
-                 array_push($aScaleBreaks, $classMin);
-             }
-             if (!in_array($classMax, $aScaleBreaks)) {
-                 array_push($aScaleBreaks, $classMax);
-             }
-         }
-         //sort them
-         sort($aScaleBreaks);
-
-         //create scale ranges for each pair of breaks
-         for ($j=0; $j<count($aScaleBreaks)-1; $j++) {
-             $scaleRange = NULL;
-             $scaleRange->minScale = $aScaleBreaks[$j];
-             $scaleRange->maxScale = $aScaleBreaks[$j+1];
-             $scaleRange->styles = array();
-             array_push($aScaleRanges, $scaleRange);
-         }
-
-         //create classes and slot them into the scale breaks
-         for ($j=0; $j<$layer->numclasses; $j++) {
-             $oClass = $layer->getClass($j);
-             $classObj = NULL;
-             $classObj->legendLabel = $oClass->name;
-             $classObj->filter = $oClass->getExpression();
-             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
-             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
-             $classObj->minScale = $classMin;
-             $classObj->maxScale = $classMax;
-             $classObj->index = $j;
-             for ($k=0; $k<count($aScaleRanges); $k++) {
-                 if ($classMin < $aScaleRanges[$k]->maxScale &&
-                     $classMax > $aScaleRanges[$k]->minScale) {
-                     array_push($aScaleRanges[$k]->styles, $classObj);
-                 }
-             }
-         }
-         //$layerObj->scaleRanges = $aScaleRanges;
-         $_SESSION['scale_ranges'][$i] = $aScaleRanges;
-         /*get the min/max scale for the layer*/
-        $nCount = count($aScaleRanges);
-        $layerObj->minScale = $aScaleRanges[0]->minScale;
-        $layerObj->maxScale = $aScaleRanges[0]->maxScale;
-        for ($j=1; $j<$nCount; $j++)
-        {
-            $layerObj->minScale = min($layerObj->minScale, $aScaleRanges[$j]->minScale);
-            $layerObj->maxScale = max($layerObj->maxScale, $aScaleRanges[$j]->maxScale);
-        }
-        array_push($mapObj->layers, $layerObj);
-    }
-    $mapObj->groups = array();
-    $aGroups = $oMap->getAllGroupNames();
-    foreach($aGroups as $groupName) {
-        $aLayerIndexes = $oMap->getLayersIndexByGroup($groupName);
-        if (count($aLayerIndexes) > 0) {
-            array_push($mapObj->groups, getGroupObject($oMap->getLayer($aLayerIndexes[0])));
-        }
-    }
-    echo var2json($mapObj);
-}
-
-function getGroupObject($layer) {
-    $group = NULL;
-    $group->groupName = $layer->group;
-    $ll = $layer->getMetaData('groupLegendLabel');
-    $group->legendLabel = $ll != '' ? $ll : $group->groupName;
-    $group->uniqueId = $group->groupName;
-    $b = $layer->getMetaData('groupDisplayInLegend');
-    $group->displayInLegend = ($b == 'false') ? false : true;
-    $b = $layer->getMetaData('groupExpandInLegend');
-    $group->expandInLegend = ($b == 'false') ? false : true;
-    $group->layerGroupType = '';
-    /* parent is always not set for mapserver since we can't have nested groups */
-    $group->parentUniqueId = '';
-    $group->parent = '';
-    $b = $layer->getMetaData('groupVisible');
-    $group->visible = ($b == 'false') ? false : true;
-    $group->actuallyVisible = $layer->isVisible();
-    $group->groupParent = $layer->getMetaData('groupParent');
-
-    return $group;
-}
-
-function GetMetersPerUnit($unit)
-{
-    if ($unit == MS_INCHES)
-      return 0.0254;
-    else if ($unit == MS_FEET)
-      return 0.3048;
-    else if ($unit == MS_MILES)
-      return 1609.344;
-    else if ($unit == MS_METERS)
-      return 1;
-    else if ($unit == MS_KILOMETERS)
-      return 1000;
-    else if ($unit == MS_DD)
-      return 111118.7516;
-    else if ($unit == MS_PIXELS)
-      return 1;
-
-}
-
-function replaceInvalidLayerName($szLayerName){
-    /*
-    bug http://trac.osgeo.org/fusion/ticket/96 - Invalid characters in layer name (pdeschamps)
-
-    Fusion requests the map imavge via the Mapserver CGI to toggle the layer visibility.
-    The layer paramerter for the cgi uses spaces as a delimiter for the layer names this creates
-    an issue for the mapserver binary to toggle layers that have these reserved URI characters.
-    also removing characters that could pose potential issues with json.
-    */
-    $aInvalidLayerNameCharacters = array();
-    $aInvalidLayerNameCharacters[0] ="&";
-    $aInvalidLayerNameCharacters[1] =" ";
-    $aInvalidLayerNameCharacters[2] ="#";
-    $aInvalidLayerNameCharacters[3] ="\\";
-    $aInvalidLayerNameCharacters[4] ="=";
-    $aInvalidLayerNameCharacters[5] ="/";
-    $aInvalidLayerNameCharacters[6] ="'";
-
-    $aReplace[0] = "_";
-    $aReplace[1] = "_";
-    $aReplace[2] = "_";
-    $aReplace[3] = "_";
-    $aReplace[4] = "_";
-    $aReplace[5] = "_";
-    $aReplace[6] = "_";
-
-    return str_replace($aInvalidLayerNameCharacters,$aReplace,$szLayerName);
-}
-
-?>
+<?php
+/**
+ * LoadMap
+ *
+ * $Id$
+ *
+ * Copyright (c) 2007, DM Solutions Group Inc.
+ * 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.
+ */
+
+/*****************************************************************************
+ * Purpose: Load a mapfile into the session and return information about the
+ *          map to the client
+ *****************************************************************************/
+
+/* Common starts the session */
+include(dirname(__FILE__).'/../../../common/php/Utilities.php');
+include(dirname(__FILE__).'/Common.php');
+include(dirname(__FILE__).'/Utilities.php');
+
+/* if scales are not set, these become the default values */
+define('MIN_SCALE', 1);
+define('MAX_SCALE', 1000000000);
+
+/* could potentially make this optional */
+$moveToSession = true;
+
+/**
+   TODO make it possible to specify only a relative path
+   in the WebLayout and have this code know where to
+   look for it on the server somehow
+ */
+
+/* only do something if a mapfile was requested */
+if (isset($_REQUEST['mapfile'])) {
+
+    /* look for mapFileRoot specified in config.json and test to see if the map path in appdef is realitive to it.*/
+    $configObj = $_SESSION['fusionConfig'];
+    $szFusionRoot = dirname(__FILE__).'/../../../'; // TODO : not a very elegant way of doing this
+    $szDblSeparator = DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR;
+
+    $szMapFromFusionRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$szFusionRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
+    $szMapFileRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$configObj->mapserver->mapFileRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
+
+    if( file_exists($szMapFileRoot) ) {
+        /* use the realitive path specified in config.json */
+        $szMapFile = $szMapFileRoot;
+    }
+    else
+    {
+        if( file_exists($szMapFromFusionRoot) ) {
+            /* use the realitive path from fusion install root */
+            $szMapFile = $szMapFromFusionRoot;
+        }
+        else
+        {
+            /* use absolute path from appdef */
+            $szMapFile = $_REQUEST['mapfile'];
+        }
+    }
+
+    $oMap = ms_newMapObj($szMapFile);
+
+    /* optionally move the mapfile to the session */
+    if ($moveToSession) {
+        //path to map file in the session is used by the client
+        $mapId = getSessionSavePath().($oMap->name).".map";
+        //modify various paths if necessary
+        $pathToMap = dirname($szMapFile);
+        $cwd = getcwd();
+        chdir($pathToMap);
+        $shapePath = $oMap->shapepath;
+        $oMap->set('shapepath', realpath($shapePath));
+        $symbolSet = $oMap->symbolsetfilename;
+        if ($symbolSet != '') {
+            $oMap->setSymbolSet(realpath($symbolSet));
+        }
+        $fontSet = $oMap->fontsetfilename;
+        if ($fontSet != '') {
+            $oMap->setFontSet(realpath($fontSet));
+        }
+        /* need to modify all image symbols reference in the map file
+         eg STYLE
+             SYMBOL "../etc/markers/target-7.gif" : this is relative to the map file
+        */
+
+        for ($i=0; $i<$oMap->numlayers; $i++)
+        {
+            $oLayer = &$oMap->GetLayer($i);
+            /* check layername for invalid URI characters and replace */
+            $oLayer->set("name",replaceInvalidLayerName($oLayer->name));
+
+            for ($j=0; $j<$oLayer->numclasses; $j++)
+            {
+                $oClass = $oLayer->GetClass($j);
+                /* if keyimage is defined, change the path*/
+                if ($oClass->keyimage && strlen($oClass->keyimage) > 0)
+                {
+                     $oClass->set("keyimage", realpath($oClass->keyimage));
+                }
+                for ($k=0; $k<$oClass->numstyles; $k++)
+                {
+                    $oStyle = $oClass->getStyle($k);
+                    if ($oStyle->symbolname != "")
+                    {
+                        if (file_exists(realpath($oStyle->symbolname)))
+                        {
+                            $oStyle->set("symbolname", realpath($oStyle->symbolname));
+                        }
+                    }
+                }
+            }
+        }
+        $oMap->save($mapId);
+        chdir($cwd);
+    } else {
+        $mapId = $_REQUEST['mapfile'];
+    }
+} elseif (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
+    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
+    $mapId = getSessionSavePath().($oMap->name).".map";
+}
+
+$mapObj = NULL;
+if ($oMap) {
+    header('Content-type: application/json');
+    header('X-JSON: true');
+    $mapObj->sessionId = $sessionID;
+    $mapObj->mapId = $mapId;
+
+    $mapObj->metadata = NULL;
+    if (isset($_REQUEST['map_metadata'])) {
+        $mapMetadataKeys = explode(',',$_REQUEST['map_metadata']);
+        foreach($mapMetadataKeys as $key) {
+            $mapObj->metadata->$key = $oMap->getMetadata($key);
+        }
+    }
+
+    $mapObj->projString = $oMap->getProjection();
+    $mapObj->metersPerUnit = GetMetersPerUnit($oMap->units);
+
+    $mapObj->dpi = $oMap->resolution;
+    $mapObj->imagetype = $oMap->imagetype;
+    $mapObj->mapName = $oMap->name;
+    if (!isset($_SESSION['maps'])) {
+        $_SESSION['maps'] = array();
+    }
+    if (!isset($_SESSION['maps'][$mapObj->mapName])) {
+        $_SESSION['maps'][$mapObj->mapName] = $mapId;
+    }
+    $mapObj->extent = array( $oMap->extent->minx, $oMap->extent->miny,
+                             $oMap->extent->maxx, $oMap->extent->maxy );
+    $minScale = $oMap->web->minscale == -1 ? MIN_SCALE : $oMap->web->minscale;
+    $maxScale = $oMap->web->maxscale == -1 ? MAX_SCALE : $oMap->web->maxscale;
+    $title = $oMap->getmetadata('legend_title');
+    $mapObj->mapTitle = $title == "" ? $mapObj->mapName : $title;
+    //layers
+    $mapObj->layers = array();
+    for ($i=0;$i<$oMap->numlayers;$i++)
+    {
+        $layer=$oMap->getLayer($i);
+        $layerObj = NULL;
+
+        /* Status Default - If a layer is status Default trac it in layerObj */
+        if($layer->status == MS_DEFAULT)
+            $layerObj->statusdefault = true;
+         else
+            $layerObj->statusdefault = false;
+
+        /* rename layes names with invalid characters */
+        $layer->set("name",replaceInvalidLayerName($layer->name));
+
+        $layerObj->metadata = NULL;
+        if (isset($_REQUEST['layer_metadata'])) {
+            $layerMetadataKeys = explode(',',$_REQUEST['layer_metadata']);
+            foreach($layerMetadataKeys as $key) {
+                $layerObj->metadata->$key = $layer->getMetadata($key);
+            }
+        }
+
+        //$extent = $layer->getExtent();
+        $layerObj->extent = NULL;
+        $layerObj->extent->minx = NULL;
+        $layerObj->extent->maxx = NULL;
+        $layerObj->extent->miny = NULL;
+        $layerObj->extent->maxy = NULL;
+
+         // only proceed if extent is valid
+        if( isset($GLOBALS["extent"]) )
+        {
+            $layerObj->extent->minx = $extent->minx;
+            $layerObj->extent->maxx = $extent->maxx;
+            $layerObj->extent->miny = $extent->miny;
+            $layerObj->extent->maxy = $extent->maxy;
+        }
+
+         $layerObj->propertyMappings = '';
+         $layerObj->uniqueId = $i;
+         $layerObj->layerName = $layer->name;
+         switch($layer->type) {
+             case MS_LAYER_POINT:
+                $type = 0;
+                break;
+             case MS_LAYER_LINE:
+                $type = 1;
+                break;
+             case MS_LAYER_POLYGON:
+                $type = 2;
+                break;
+             case MS_LAYER_RASTER:
+                $type = 4;
+                break;
+             case MS_LAYER_ANNOTATION:
+                $type = 8;
+                break;
+             default:
+                $type = 0;
+         }
+         $layerObj->layerTypes = array($type);
+
+         $displayInLegend = strtolower($layer->getMetaData('displayInLegend'));
+         $layerObj->displayInLegend = $displayInLegend == 'false' ? false : true;
+
+         $expandInLegend = strtolower($layer->getMetaData('expandInLegend'));
+         $layerObj->expandInLegend = $expandInLegend == 'false' ? false : true;
+         $layerObj->resourceId = $layer->name;
+         $layerObj->parentGroup = $layer->group;
+
+         $legendLabel = $layer->getMetaData('legendLabel');
+         if ($legendLabel == '') {
+             $legendLabel = $layer->name;
+         }
+         $layerObj->legendLabel = $legendLabel;
+
+         $selectable = strtolower($layer->getMetaData('selectable'));
+         $layerObj->selectable = $selectable == 'true' ? true : false;
+
+         $layerObj->visible = ($layer->status == MS_ON || $layer->status == MS_DEFAULT);
+         $layerObj->actuallyVisible = true;
+
+         $editable = strtolower($layer->getMetaData('editable'));
+         $layerObj->editable = $editable == 'true' ? true : false;
+
+         /* process the classes.  The legend expects things
+          * organized by scale range so we have to first
+          * find all the scale breaks, then create ranges
+          * for each scale break pair, then slot the classes
+          * into the scale ranges that they apply to.
+          */
+
+         $aScaleRanges = array();
+         //create a default scale range for the layer as a whole
+         $layerMin = $layer->minscale == -1 ? $minScale : $layer->minscale;
+         $layerMax = $layer->maxscale == -1 ? $maxScale : $layer->maxscale;
+
+        /* check to see that the layer has a vaild scale range
+         * inside the defined map's main min max scale ranges
+         * set them to the maps scale ranges if they exceede 
+         */
+        if($layer->minscale != -1 && $layerMin < $minScale)
+            $layerMin = $minScale;
+
+        if($layer->maxscale != -1 && $layerMax > $maxScale)
+            $layerMax = $maxScale;
+
+         //find all the unique scale breaks in this layer
+         $aScaleBreaks = array($layerMin, $layerMax);
+         for ($j=0; $j<$layer->numclasses; $j++) {
+             $oClass = $layer->getClass($j);
+             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
+             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
+             if (!in_array($classMin, $aScaleBreaks)) {
+                 array_push($aScaleBreaks, $classMin);
+             }
+             if (!in_array($classMax, $aScaleBreaks)) {
+                 array_push($aScaleBreaks, $classMax);
+             }
+         }
+         //sort them
+         sort($aScaleBreaks);
+
+         //create scale ranges for each pair of breaks
+         for ($j=0; $j<count($aScaleBreaks)-1; $j++) {
+             $scaleRange = NULL;
+             $scaleRange->minScale = $aScaleBreaks[$j];
+             $scaleRange->maxScale = $aScaleBreaks[$j+1];
+             $scaleRange->styles = array();
+             array_push($aScaleRanges, $scaleRange);
+         }
+
+         //create classes and slot them into the scale breaks
+         for ($j=0; $j<$layer->numclasses; $j++) {
+             $oClass = $layer->getClass($j);
+             $classObj = NULL;
+             // Use formatted legend label as defined by CLASS->TITLE
+             $classObj->legendLabel = $oClass->title != '' ? $oClass->title : $oClass->name;
+             $classObj->filter = $oClass->getExpression();
+             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
+             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
+             $classObj->minScale = $classMin;
+             $classObj->maxScale = $classMax;
+             $classObj->index = $j;
+             for ($k=0; $k<count($aScaleRanges); $k++) {
+                 if ($classMin < $aScaleRanges[$k]->maxScale &&
+                     $classMax > $aScaleRanges[$k]->minScale) {
+                     array_push($aScaleRanges[$k]->styles, $classObj);
+                 }
+             }
+         }
+         //$layerObj->scaleRanges = $aScaleRanges;
+         $_SESSION['scale_ranges'][$mapName][$layer->name] = $aScaleRanges;
+         /*get the min/max scale for the layer*/
+        $nCount = count($aScaleRanges);
+        $layerObj->minScale = $aScaleRanges[0]->minScale;
+        $layerObj->maxScale = $aScaleRanges[0]->maxScale;
+        for ($j=1; $j<$nCount; $j++)
+        {
+            $layerObj->minScale = min($layerObj->minScale, $aScaleRanges[$j]->minScale);
+            $layerObj->maxScale = max($layerObj->maxScale, $aScaleRanges[$j]->maxScale);
+        }
+        array_push($mapObj->layers, $layerObj);
+    }
+    $mapObj->groups = array();
+    $aGroups = $oMap->getAllGroupNames();
+    foreach($aGroups as $groupName) {
+        $aLayerIndexes = $oMap->getLayersIndexByGroup($groupName);
+        if (count($aLayerIndexes) > 0) {
+            array_push($mapObj->groups, getGroupObject($oMap->getLayer($aLayerIndexes[0])));
+        }
+    }
+    echo var2json($mapObj);
+}
+
+function getGroupObject($layer) {
+    $group = NULL;
+    $group->groupName = $layer->group;
+    $ll = $layer->getMetaData('groupLegendLabel');
+    $group->legendLabel = $ll != '' ? $ll : $group->groupName;
+    $group->uniqueId = $group->groupName;
+    $b = $layer->getMetaData('groupDisplayInLegend');
+    $group->displayInLegend = ($b == 'false') ? false : true;
+    $b = $layer->getMetaData('groupExpandInLegend');
+    $group->expandInLegend = ($b == 'false') ? false : true;
+    $group->layerGroupType = '';
+    /* parent is always not set for mapserver since we can't have nested groups */
+    $group->parentUniqueId = '';
+    $group->parent = '';
+    $b = $layer->getMetaData('groupVisible');
+    $group->visible = ($b == 'false') ? false : true;
+    $group->actuallyVisible = $layer->isVisible();
+    $group->groupParent = $layer->getMetaData('groupParent');
+
+    return $group;
+}
+
+function GetMetersPerUnit($unit)
+{
+    if ($unit == MS_INCHES)
+      return 0.0254;
+    else if ($unit == MS_FEET)
+      return 0.3048;
+    else if ($unit == MS_MILES)
+      return 1609.344;
+    else if ($unit == MS_METERS)
+      return 1;
+    else if ($unit == MS_KILOMETERS)
+      return 1000;
+    else if ($unit == MS_DD)
+      return 111118.7516;
+    else if ($unit == MS_PIXELS)
+      return 1;
+
+}
+
+function replaceInvalidLayerName($szLayerName){
+    /*
+    bug http://trac.osgeo.org/fusion/ticket/96 - Invalid characters in layer name (pdeschamps)
+
+    Fusion requests the map imavge via the Mapserver CGI to toggle the layer visibility.
+    The layer paramerter for the cgi uses spaces as a delimiter for the layer names this creates
+    an issue for the mapserver binary to toggle layers that have these reserved URI characters.
+    also removing characters that could pose potential issues with json.
+    */
+    $aInvalidLayerNameCharacters = array();
+    $aInvalidLayerNameCharacters[0] ="&";
+    $aInvalidLayerNameCharacters[1] =" ";
+    $aInvalidLayerNameCharacters[2] ="#";
+    $aInvalidLayerNameCharacters[3] ="\\";
+    $aInvalidLayerNameCharacters[4] ="=";
+    $aInvalidLayerNameCharacters[5] ="/";
+    $aInvalidLayerNameCharacters[6] ="'";
+
+    $aReplace[0] = "_";
+    $aReplace[1] = "_";
+    $aReplace[2] = "_";
+    $aReplace[3] = "_";
+    $aReplace[4] = "_";
+    $aReplace[5] = "_";
+    $aReplace[6] = "_";
+
+    return str_replace($aInvalidLayerNameCharacters,$aReplace,$szLayerName);
+}
+
+?>


Property changes on: branches/fusion-2.0/layers/MapServer/php/LoadMap.php
___________________________________________________________________
Deleted: svn:eol-style
   - native

Modified: branches/fusion-2.0/layers/MapServer/php/LoadScaleRanges.php
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/LoadScaleRanges.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/php/LoadScaleRanges.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -32,53 +32,165 @@
  *****************************************************************************/
 
 /* set up the session */
-include ("Common.php");
-include('../../../common/php/Utilities.php');
-include ("Utilities.php");
+include(dirname(__FILE__).'/../../../common/php/Utilities.php');
+include(dirname(__FILE__).'/Common.php');
+include(dirname(__FILE__).'/Utilities.php');
 
+/*if (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
+    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
+}*/
+
+/* if scales are not set, these become the default values */
+define('MIN_SCALE', 1);
+define('MAX_SCALE', 1000000000);
+
+$oMap = ms_newMapObj(getSessionSavePath().$mapName.".map");
+
+if ($oMap) {
+	$minScale = $oMap->web->minscale == -1 ? MIN_SCALE : $oMap->web->minscale;
+	$maxScale = $oMap->web->maxscale == -1 ? MAX_SCALE : $oMap->web->maxscale;
+	//layers
+	for ($i=0;$i<$oMap->numlayers;$i++) {
+		$layer=$oMap->getLayer($i);
+		
+		/* rename layes names with invalid characters */
+		$layer->set("name",replaceInvalidLayerName($layer->name));
+		
+		switch($layer->type) {
+			case MS_LAYER_POINT:
+				$type = 0;
+				break;
+			case MS_LAYER_LINE:
+				$type = 1;
+				break;
+			case MS_LAYER_POLYGON:
+				$type = 2;
+				break;
+			case MS_LAYER_RASTER:
+				$type = 4;
+				break;
+			case MS_LAYER_ANNOTATION:
+				$type = 8;
+				break;
+			default:
+				$type = 0;
+		}
+		
+		$displayInLegend = strtolower($layer->getMetaData('displayInLegend'));
+		$expandInLegend = strtolower($layer->getMetaData('expandInLegend'));
+		$legendLabel = $layer->getMetaData('legendLabel');
+		if ($legendLabel == '') {
+			$legendLabel = $layer->name;
+		}
+		
+		$selectable = strtolower($layer->getMetaData('selectable'));
+		$editable = strtolower($layer->getMetaData('editable'));
+		
+		/* process the classes.  The legend expects things
+		* organized by scale range so we have to first
+		* find all the scale breaks, then create ranges
+		* for each scale break pair, then slot the classes
+		* into the scale ranges that they apply to.
+		*/
+		
+		$aScaleRanges = array();
+		//create a default scale range for the layer as a whole
+		$layerMin = $layer->minscale == -1 ? $minScale : $layer->minscale;
+		$layerMax = $layer->maxscale == -1 ? $maxScale : $layer->maxscale;
+		
+		/* check to see that the layer has a vaild scale range
+		 * inside the defined map's main min max scale ranges
+		 * set them to the maps scale ranges if they exceede 
+		 */
+		if($layer->minscale != -1 && $layerMin < $minScale)
+			$layerMin = $minScale;
+		
+		if($layer->maxscale != -1 && $layerMax > $maxScale)
+			$layerMax = $maxScale;
 
-if (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
-    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
-}
+		//find all the unique scale breaks in this layer
+		$aScaleBreaks = array($layerMin, $layerMax);
+		for ($j=0; $j<$layer->numclasses; $j++) {
+			$oClass = $layer->getClass($j);
+			$classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
+			$classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
+			if (!in_array($classMin, $aScaleBreaks)) {
+				array_push($aScaleBreaks, $classMin);
+			}
+			if (!in_array($classMax, $aScaleBreaks)) {
+				array_push($aScaleBreaks, $classMax);
+			}
+		}
+		//sort them
+		sort($aScaleBreaks);
+		
+		//create scale ranges for each pair of breaks
+		for ($j=0; $j<count($aScaleBreaks)-1; $j++) {
+			$scaleRange = NULL;
+			$scaleRange->minScale = $aScaleBreaks[$j];
+			$scaleRange->maxScale = $aScaleBreaks[$j+1];
+			$scaleRange->styles = array();
+			array_push($aScaleRanges, $scaleRange);
+		}
+		
+		//create classes and slot them into the scale breaks
+		for ($j=0; $j<$layer->numclasses; $j++) {
+			$oClass = $layer->getClass($j);
+			$classObj = NULL;
+			// Use formatted legend label as defined by CLASS->TITLE
+			$classObj->legendLabel = $oClass->title != '' ? $oClass->title : $oClass->name;
+			//$classObj->legendLabel = $oClass->name;
+			$classObj->filter = $oClass->getExpression();
+			$classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
+			$classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
+			$classObj->minScale = $classMin;
+			$classObj->maxScale = $classMax;
+			$classObj->index = $j;
+			for ($k=0; $k<count($aScaleRanges); $k++) {
+				if ($classMin < $aScaleRanges[$k]->maxScale &&
+					$classMax > $aScaleRanges[$k]->minScale) {
+					array_push($aScaleRanges[$k]->styles, $classObj);
+				}
+			}
+		}
+		//$layerObj->scaleRanges = $aScaleRanges;
+		$_SESSION['scale_ranges'][$mapName][$layer->name] = $aScaleRanges;
+	}
 
-$scaleObj = NULL;
-$scaleObj->layers = array();
+	$scaleObj = NULL;
+	$scaleObj->layers = array();
 
-define('ICON_SIZE', 16);
-$nIconWidth = $oMap->legend->keysizex;
-$nIconHeight = $oMap->legend->keysizey;
-if ($nIconWidth <=0)
+	define('ICON_SIZE', 16);
+	$nIconWidth = $oMap->legend->keysizex;
+	$nIconHeight = $oMap->legend->keysizey;
+	if ($nIconWidth <=0)
   $nIconWidth = ICON_SIZE;
-if ($nIconWidth <=0)
+	if ($nIconWidth <=0)
   $nIconWidth = ICON_SIZE;
-$nTotalClasses=0;
-$aIcons = array();
+	$nTotalClasses=0;
+	$aIcons = array();
 
-
-/*special case to force the the legend icons to be drawn using a gd driver
+	/*special case to force the the legend icons to be drawn using a gd driver
   This was fixed in ticket http://trac.osgeo.org/mapserver/ticket/2682 which
   will be available for mapserver version 5.2.1 and 5.4
   Note that we do not check the outputformat of the map (assuming that we are 
   using GD or AGG renderers)
-*/
-$nVersion = ms_GetVersionInt();
-if ($nVersion <= 50200) /*5.2 and before*/
+	*/
+	$nVersion = ms_GetVersionInt();
+	if ($nVersion <= 50200) /*5.2 and before*/
   $oMap->selectOutputFormat("png24");
 
 
-for($i=0;$i<$oMap->numlayers;$i++) 
-{    
-    if (isset($_SESSION['scale_ranges']) && isset($_SESSION['scale_ranges'][$i]))
+	for($i=0;$i<$oMap->numlayers;$i++) 
     {
         $layer = $oMap->getLayer($i);
-        $scaleranges = $_SESSION['scale_ranges'][$i];
-        //print_r($scaleranges);
-        //echo "aaa <br>";
+		if (isset($_SESSION['scale_ranges']) && isset($_SESSION['scale_ranges'][$mapName]) && isset($_SESSION['scale_ranges'][$mapName][$layer->name]))
+		{
+			$scaleranges = $_SESSION['scale_ranges'][$mapName][$layer->name];
         $layerObj = NULL;
         $layerObj->uniqueId = $i;
 
         /*generate the legend icons here*/
-        //echo count($scaleranges) . "<br>\n";
         $nScaleRanges = count($scaleranges);
         for ($j=0; $j<$nScaleRanges; $j++)
         {
@@ -102,8 +214,7 @@
     }
  }  
 
-if ($nTotalClasses > 0)
- {
+	if ($nTotalClasses > 0) {
      //set the image path and image dir based on what fusion config file
      $configObj = $_SESSION['fusionConfig'];
 
@@ -130,19 +241,47 @@
      for ($i=0; $i<$nTotalClasses;$i++)
        $oImage->pasteImage($aIcons[$i], -1, $i*$nIconWidth, 0);
 
-
      $scaleObj->icons_url = $oImage->saveWebImage();
      $scaleObj->icons_width = $nIconWidth;
      $scaleObj->icons_height = $nIconHeight;
 
       $oMap->web->set("imagepath", $original_imagepath);
       $oMap->web->set("imageurl", $original_imageurl);
+	}
+}
+
+function replaceInvalidLayerName($szLayerName){
+    /*
+    bug http://trac.osgeo.org/fusion/ticket/96 - Invalid characters in layer name (pdeschamps)
+
+    Fusion requests the map imavge via the Mapserver CGI to toggle the layer visibility.
+    The layer paramerter for the cgi uses spaces as a delimiter for the layer names this creates
+    an issue for the mapserver binary to toggle layers that have these reserved URI characters.
+    also removing characters that could pose potential issues with json.
+    */
+    $aInvalidLayerNameCharacters = array();
+    $aInvalidLayerNameCharacters[0] ="&";
+    $aInvalidLayerNameCharacters[1] =" ";
+    $aInvalidLayerNameCharacters[2] ="#";
+    $aInvalidLayerNameCharacters[3] ="\\";
+    $aInvalidLayerNameCharacters[4] ="=";
+    $aInvalidLayerNameCharacters[5] ="/";
+    $aInvalidLayerNameCharacters[6] ="'";
+
+    $aReplace[0] = "_";
+    $aReplace[1] = "_";
+    $aReplace[2] = "_";
+    $aReplace[3] = "_";
+    $aReplace[4] = "_";
+    $aReplace[5] = "_";
+    $aReplace[6] = "_";
       
- }
+    return str_replace($aInvalidLayerNameCharacters,$aReplace,$szLayerName);
+}
 
 header('Content-type: application/json');
 header('X-JSON: true');
 
 echo var2json($scaleObj);
 exit;
-
+?>
\ No newline at end of file

Modified: branches/fusion-2.0/layers/MapServer/php/Maptip.php
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/Maptip.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/php/Maptip.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -63,6 +63,7 @@
 /* a spatial filter in the form on a WKT geometry */
 $spatialFilter = (isset($_REQUEST['spatialfilter']) && $_REQUEST['spatialfilter'] != '') ? urldecode($_REQUEST['spatialfilter']) : false;
 
+
 header('Content-type: application/json');
 header('X-JSON: true');
 
@@ -82,52 +83,63 @@
     $aURL = array();
     $aTipLabel = array();
     foreach($aLayer as $key=>$layer){
-        $oLayer = @$oMap->GetLayerByName($layer);
+        if(isLayerVisible($layer) === TRUE){
+            $oLayer = @$oMap->GetLayerByName($layer);
 
-        // make sure the layer exists in the map.
-        if(is_object($oLayer)){
-            $oLayer->set('tolerance', 0);
+            // make sure the layer exists in the map.
+            if(is_object($oLayer)){
+                $oLayer->set('tolerance', 0);
 
-            if ($oLayer->type ==  MS_LAYER_RASTER || $oLayer->type == MS_LAYER_QUERY ||
-                    $oLayer->type ==  MS_LAYER_CIRCLE ||  $oLayer->type == MS_LAYER_CHART) {
-                    die("{'error':'maptips are only valid for vector layers'}");
-                }
+                if ($oLayer->type ==  MS_LAYER_RASTER || $oLayer->type == MS_LAYER_QUERY ||
+                        $oLayer->type ==  MS_LAYER_CIRCLE ||  $oLayer->type == MS_LAYER_CHART) {
+                        die("{'error':'maptips are only valid for vector layers'}");
+                    }
 
 
-            if (@$oLayer->queryByShape($oSpatialFilter) == MS_SUCCESS) {
+                if (@$oLayer->queryByShape($oSpatialFilter) == MS_SUCCESS) {
 
-                $oRes = $oLayer->getResult(0);
-                $oLayer->open();
+                    $oRes = $oLayer->getResult(0);
+                    $oLayer->open();
 
-                $oShape = $oLayer->getShape($oRes->tileindex,$oRes->shapeindex);
+                    $oShape = $oLayer->getShape($oRes->tileindex,$oRes->shapeindex);
 
-                $szMapTipText .= $oLayer->name." : ".$oShape->values[$aMapTipTextField[$key]].$szBreak;
+                    $szMapTipText .= $oLayer->name." : ".$oShape->values[$aMapTipTextField[$key]].$szBreak;
 
-                $szLabels = $aLabel[$key];
+                    $szLabels = $aLabel[$key];
 
-                $szMapTip  = $oShape->values[$aMapTipTextField[$key]];
-                $szURL = buildCustonUrl($oShape->values,$aMapTipURL[$key]);
+                    $szMapTip  = $oShape->values[$aMapTipTextField[$key]];
+                    $szURL = buildCustonUrl($oShape->values,$aMapTipURL[$key]);
 
-                $szMapTip = $szMapTip != "undefined" ? $szMapTip : "";
-                $szURL = $szURL != "undefined" ? $szURL : "";
-                $szLabels = $szLabels != "undefined" ? $szLabels : "";
+                    $szMapTip = $szMapTip != "undefined" ? $szMapTip : "";
+                    $szURL = $szURL != "undefined" ? $szURL : "";
+                    $szLabels = $szLabels != "undefined" ? $szLabels : "";
 
+                    array_push($aMapTips, $szMapTip);
+                    array_push($aURL, $szURL);
+                    array_push($aTipLabel,$szLabels);
 
-                array_push($aMapTips, $szMapTip);
-                array_push($aURL, $szURL);
-                array_push($aTipLabel,$szLabels);
-
-                $oLayer->close();
+                    $oLayer->close();
+                }
             }
         }
     }
-    echo "{'maptips':".var2json($aMapTips).",'url':".var2json($aURL).",'label':".var2json($aTipLabel)."}";
+    echo "{'maptips':".var2json($aMapTips).",'url':".var2json($aURL).",'label':".var2json($aTipLabel).",'test':'casper'}";
 }
 else
 {
 echo "{'maptips':'','url':'','label':''}";
 }
 
+function isLayerVisible($szLayerName){
+    $aVisLayers = split(",",$_POST["visLayers"]);
+    foreach($aVisLayers as $item){
+        if(trim($szLayerName) == trim($item)){
+            return true;
+        }
+    }
+    return false;
+}
+
 function buildCustonUrl($aValues,$url){
 
     if($url != ""){

Copied: branches/fusion-2.0/layers/MapServer/php/RestoreState.php (from rev 2103, trunk/layers/MapServer/php/RestoreState.php)
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/RestoreState.php	                        (rev 0)
+++ branches/fusion-2.0/layers/MapServer/php/RestoreState.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -0,0 +1,191 @@
+<?php
+ini_set("memory_limit","64M");
+dl('zip.so');
+ /* set up the session */
+include(dirname(__FILE__).'/Common.php');
+include('../../../common/php/Utilities.php');
+
+header('Content-type: application/json');
+header('X-JSON: true');
+
+isset($_REQUEST["session"])?$szSessionID = $_REQUEST["session"]:$szSessionID = NULL ;
+isset($_REQUEST["id"])?$loadSessionID = $_REQUEST["id"]:$loadSessionID = NULL ;
+
+$oReturn = NULL;
+
+if (isset($_SESSION['fusionConfig'])) {
+
+    $szStoreSessionPath = $_SESSION['fusionConfig']->mapserver->mapRestoreState;
+    $szFilePhpSession = $_SESSION['fusionConfig']->mapserver->mapRestoreStateSession;
+
+    $szDestination = $szFilePhpSession."/sess_".$szSessionID."/";
+
+    $szTmpFileName = $_FILES["sessionFile"]["tmp_name"];
+    $szZipFilename = $szStoreSessionPath."/ss_".$loadSessionID.".zip";
+    $szControlFile = $szStoreSessionPath."/".$loadSessionID.".dat";
+
+    if (file_exists($szZipFilename) && file_exists($szControlFile)){
+
+        $aData = readSessionSaveControlFile($szControlFile);
+        $bSuccessfull = unzip($szZipFilename, $szDestination, $create_zip_name_dir=true, $overwrite=true);
+
+            if($aData && $bSuccessfull === TRUE){
+                $oReturn->success = TRUE;
+                $oReturn->mapname = $aData["mapname"];
+                $oReturn->extents = $aData["_afCurrentExtents"];
+                $oReturn->vislayers = $aData["aVisibleLayers"];
+                $oReturn->sessionname = $aData["sessionName"];
+                $oReturn->loadmap = $szDestination."/".$oReturn->mapname.'.map';
+
+                $oMap = ms_newMapObj($oReturn->loadmap);
+                checkForGMLLayers($szDestination);
+                $oMap->save($oReturn->loadmap);
+                echo var2json($oReturn);
+            }
+            else
+            {
+                die("{'error':'Could not load session control file ".$loadSessionID. ".dat.'}");
+            }
+        }
+        else
+        {
+        die("{'error':'map state ".$loadSessionID. " does not exist.'}");
+        }
+    }
+    else
+    {
+    die("{'error':'PHP Session path is invalid.'}");
+    }
+
+function checkForGMLLayers($szDestination){
+    global $oMap;
+    @$oLayer = $oMap->getLayerByName("LWEGML-Point");
+    if($oLayer){
+    $oLayer->set("connection", $szDestination."/features.gml");
+    }
+    @$oLayer = $oMap->getLayerByName("LWEGML-Line");
+    if($oLayer){
+    $oLayer->set("connection", $szDestination."/features.gml");
+    }
+    @$oLayer = $oMap->getLayerByName("LWEGML-Polygon");
+    if($oLayer){
+    $oLayer->set("connection", $szDestination."/features.gml");
+    }
+    @$oLayer = $oMap->getLayerByName("LWEGML-Annotation");
+    if($oLayer){
+    $oLayer->set("connection", $szDestination."/features.gml");
+    }
+}
+
+function readSessionSaveControlFile($szFileName){
+
+$handle = @fopen($szFileName, "r");
+
+if($handle)
+    {
+    $szData = fread($handle, filesize($szFileName));
+    fclose($handle);
+    }
+
+return unserialize($szData);
+}
+
+function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
+{
+  if(function_exists("zip_open"))
+  {
+      if(!is_resource(zip_open($src_file)))
+      {
+          $src_file=dirname($_SERVER['SCRIPT_FILENAME'])."/".$src_file;
+      }
+
+      if (is_resource($zip = zip_open($src_file)))
+      {
+          $splitter = ($create_zip_name_dir === true) ? "." : "/";
+          if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
+
+          // Create the directories to the destination dir if they don't already exist
+          create_dirs($dest_dir);
+
+          // For every file in the zip-packet
+          while ($zip_entry = zip_read($zip))
+          {
+            // Now we're going to create the directories in the destination directories
+
+            // If the file is not in the root dir
+            $pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
+            if ($pos_last_slash !== false)
+            {
+              // Create the directory where the zip-entry should be saved (with a "/" at the end)
+              create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
+            }
+
+            // Open the entry
+            if (zip_entry_open($zip,$zip_entry,"r"))
+            {
+
+              // The name of the file to save on the disk
+              $file_name = $dest_dir.zip_entry_name($zip_entry);
+
+              // Check if the files should be overwritten or not
+              if ($overwrite === true || $overwrite === false && !is_file($file_name))
+              {
+                // Get the content of the zip entry
+                $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
+
+                if(!is_dir($file_name))
+                file_put_contents($file_name, $fstream );
+                // Set the rights
+                if(file_exists($file_name))
+                {
+                    chmod($file_name, 0755);
+                    //echo "<span style=\"color:#1da319;\">file saved: </span>".$file_name."<br />";
+                }
+                else
+                {
+                    //echo "<span style=\"color:red;\">file not found: </span>".$file_name."<br />";
+                }
+              }
+
+              // Close the entry
+              zip_entry_close($zip_entry);
+            }
+          }
+          // Close the zip-file
+          zip_close($zip);
+      }
+      else
+      {
+        return false;
+      }
+
+      return true;
+  }
+  else
+  {
+      if(version_compare(phpversion(), "5.2.0", "<"))
+      $infoVersion="(use PHP 5.2.0 or later)";
+      die("error:'You need to install/enable the php_zip.dll extension $infoVersion'");
+  }
+}
+
+function create_dirs($path)
+{
+  if (!is_dir($path))
+  {
+    $directory_path = "";
+    $directories = explode("/",$path);
+    array_pop($directories);
+
+    foreach($directories as $directory)
+    {
+      $directory_path .= $directory."/";
+      if (!is_dir($directory_path))
+      {
+        mkdir($directory_path);
+        chmod($directory_path, 0777);
+      }
+    }
+  }
+}
+?>
\ No newline at end of file

Modified: branches/fusion-2.0/layers/MapServer/php/SetLayers.php
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/SetLayers.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/layers/MapServer/php/SetLayers.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -65,7 +65,7 @@
 	}
 		echo "*/";
 } else {
-  echo "/* reordering layers */";
+
 	$res = $oMap->setlayersdrawingorder($layers);
 }
 
@@ -73,7 +73,7 @@
     $oMap->save($_SESSION['maps'][$mapName]);
     $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
     $newLayers = $oMap->getlayersdrawingorder();
-    echo "{success: true, layerindex: [".implode(",",$newLayers)."]}";
+    echo "{success: true, layerindex: [".implode(",",$layers)."]}";
 } else {
     echo "{success: false, layerindex: [".$_REQUEST['layerindex']."]}";
 }

Copied: branches/fusion-2.0/layers/MapServer/php/updateSessionMapFile.php (from rev 2103, trunk/layers/MapServer/php/updateSessionMapFile.php)
===================================================================
--- branches/fusion-2.0/layers/MapServer/php/updateSessionMapFile.php	                        (rev 0)
+++ branches/fusion-2.0/layers/MapServer/php/updateSessionMapFile.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -0,0 +1,51 @@
+<?php
+include 'Common.php';
+
+if (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
+    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
+    // set visible layers
+    setVisibleLayers(split(",",$_REQUEST["visLayers"]));
+    // update the layers list that is in use
+    //updateActiveLayers(split(",",$_REQUEST["layers"]));
+    
+    // save the mapfile
+    $oMap->save($_SESSION['maps'][$mapName]);
+    for ($i=0;$i<$oMap->numlayers;$i++){
+        $oLayer=&$oMap->GetLayer($i);
+        }
+} else {
+  exit;
+}
+    function setVisibleLayers($aLayers){
+    global $oMap;
+        for ($i=0;$i<$oMap->numlayers;$i++){
+            $oLayer=$oMap->GetLayer($i);
+            // turn off layer
+            $oLayer->set("status", MS_OFF);
+            for($j=0;$j<count($aLayers);$j++){
+                if($aLayers[$j] == $oLayer->name ){
+                    $oLayer->set("status", MS_ON);
+                }
+            }
+        }
+    }
+
+    function updateActiveLayers ($aLayers){
+    global $oMap;
+        for ($i=0;$i<$oMap->numlayers;$i++){
+            $oLayer=&$oMap->GetLayer($i);
+            
+            $bFoundLayer = false;
+            for($j=0;$j<count($aLayers);$j++){
+                if($aLayers[$j] == $oLayer->name ){
+                    $bFoundLayer = true;
+                }
+            }
+            // layer not found in list delete it
+            if($bFoundLayer == false){
+                $oLayer->set('status', MS_DELETE); 
+            }
+        }
+    }    
+    
+?>
\ No newline at end of file

Modified: branches/fusion-2.0/lib/ApplicationDefinition.js
===================================================================
--- branches/fusion-2.0/lib/ApplicationDefinition.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/lib/ApplicationDefinition.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -33,13 +33,13 @@
 Fusion.Lib.ApplicationDefinition = OpenLayers.Class({
     /**
      * Property: mapGroups
-     * 
-     * array of map groups, parsed from ApplicationDefinition.  A MapGroup 
+     *
+     * array of map groups, parsed from ApplicationDefinition.  A MapGroup
      * consists of one or more Maps that can be combined into the same
      * OpenLayers Map object
      */
     mapGroups: null,
-    
+
     /**
      * Property: widgetSets
      *
@@ -47,7 +47,7 @@
      * from the ApplicationDefinition.
      */
     widgetSets: null,
-    
+
     /**
      * Property: {Object} oBroker
      *
@@ -55,21 +55,21 @@
      * in the case we are running against a MapGuide server
      */
     oBroker: null,
-    
+
     /**
      * Property: {Array} searchDefinitions
      *
      * An array of search definitions
      */
     searchDefinitions: null,
-    
+
     /**
      * Property: {Array} searchCategories
      *
      * An array of search categories
      */
     searchCategories: null,
-    
+
     /**
      * Constructor: ApplicationDefinition
      *
@@ -81,20 +81,20 @@
      * an optional session id to initialize the application with, passed to
      * the map widgets when they are created.
      */
-     
-    initialize: function(sessionId) {   
+
+    initialize: function(sessionId) {
         //console.log('ApplicationDefinition initialize');
         this.sessionId = sessionId;
         this.oBroker = Fusion.getBroker();
         this.applicationDefinition =  Fusion.getApplicationDefinitionURL();
-        
+
         this.widgetSets = [];
         this.mapGroups = {};
         this.searchDefinitions = [];
         this.searchCategories = [];
         this.parse();
     },
-    
+
     /**
      * Function: parse
      *
@@ -111,15 +111,15 @@
             //TODO: emit an error
             return null;
         }
-        /* if the application definition is not in the mapguide server, 
+        /* if the application definition is not in the mapguide server,
            just load the xml*/
-        
+
         if ( (this.applicationDefinition.match('Library://') == null) &&
              (this.applicationDefinition.match('Session:') == null) ) {
             if (Fusion.appDefJson) {
                 this.parseAppDef(Fusion.appDefJson);
             } else {
-                Fusion.getXmlAsJson(this.applicationDefinition, 
+                Fusion.getXmlAsJson(this.applicationDefinition,
                               OpenLayers.Function.bind(this.getAppDefCB, this));
             }
         } else {
@@ -135,27 +135,30 @@
         }
         return true;
     },
-    
+
     createSessionThenGetAppDef: function() {
-      var r = new Fusion.Lib.MGRequest.MGCreateSession();
-      this.oBroker.dispatchRequest(r, OpenLayers.Function.bind(this.createSessionThenGetAppDefCB, this));
+      var sl = Fusion.getScriptLanguage();
+      var scriptURL = 'layers/' + 'MapGuide' + '/' + sl + '/CreateSession.' + sl;
+      var options = {onSuccess: OpenLayers.Function.bind(this.createSessionThenGetAppDefCB, this)};
+      Fusion.ajaxRequest(scriptURL, options);
     },
-    
+
     createSessionThenGetAppDefCB : function(xhr) {
-      if (xhr && typeof(xhr) == "object" && xhr.responseText) { 
-        this.sessionId = xhr.responseText; 
-        Fusion.sessionId = this.sessionId; 
+      if (xhr && typeof(xhr) == "object" && xhr.responseText) {
+        var o;
+        eval("o="+xhr.responseText);
+        this.sessionId = o.sessionId;
+        Fusion.sessionId = this.sessionId;
       }
       this.getAppDef();
     },
-	
 
-    getAppDef: function(){ 
-      var r = new Fusion.Lib.MGRequest.MGGetResourceContent(this.applicationDefinition); 
-      r.parameters.session = this.sessionId; 
-      r.parameters.format = 'application/json'; 
-      this.oBroker.dispatchRequest(r, 
-              OpenLayers.Function.bind(this.getAppDefCB, this)); 
+    getAppDef: function(){
+      var r = new Fusion.Lib.MGRequest.MGGetResourceContent(this.applicationDefinition);
+      r.parameters.session = this.sessionId;
+      r.parameters.format = 'application/json';
+      this.oBroker.dispatchRequest(r,
+              OpenLayers.Function.bind(this.getAppDefCB, this));
     },
 
     getAppDefCB: function(xhr) {
@@ -193,10 +196,10 @@
                 }
             }
         } else {
-          Fusion.reportError(new Fusion.Error(Fusion.Error.FATAL, 
+          Fusion.reportError(new Fusion.Error(Fusion.Error.FATAL,
                         OpenLayers.i18n('appDefParseError')));
         }
-        
+
         /* process WIDGET sets */
         if (appDef.WidgetSet) {
             for (var i=0; i<appDef.WidgetSet.length; i++) {
@@ -204,10 +207,10 @@
                 this.widgetSets.push(widgetSet);
             }
         } else {
-          Fusion.reportError(new Fusion.Error(Fusion.Error.FATAL, 
+          Fusion.reportError(new Fusion.Error(Fusion.Error.FATAL,
                       OpenLayers.i18n('widgetSetParseError')));
         }
-        
+
         /* process extensions */
         if (appDef.Extension) {
             var extension = appDef.Extension[0];
@@ -233,10 +236,10 @@
                     }
                 }
             }
-            
+
         }
     },
-    
+
     /**
      * Function: create
      *
@@ -248,7 +251,7 @@
             this.widgetSets[i].create(this);
         }
     },
-    
+
     /**
      * Function: getMapByName
      *
@@ -270,7 +273,7 @@
         }
         return map;
     },
-    
+
     /**
      * Function: getMapById
      *
@@ -278,7 +281,7 @@
      *
      * Parameter: {String} id
      *
-     * The map id to return.  ID is distinct from map.name in that id is the 
+     * The map id to return.  ID is distinct from map.name in that id is the
      * id of the HTML tag where the map widget is inserted.
      *
      * Returns: {Object} a map object or null if not found.
@@ -293,7 +296,7 @@
         }
         return map;
     },
-    
+
     /**
      * Function: getMapByIndice
      *
@@ -312,7 +315,7 @@
          }
          return map;
      },
-     
+
     /**
      * Function: getMapGroup
      *
@@ -327,7 +330,7 @@
      getMapGroup : function(mapGroupId) {
          return this.mapGroups[mapGroupId];
      },
-     
+
      /**
       * Function getWidgetsByType
       *
@@ -358,7 +361,7 @@
 Fusion.Lib.ApplicationDefinition.MapGroup = OpenLayers.Class({
     initialView: null,
     maps: null,
-    
+
     initialize: function(jsonNode) {
         this.mapId = jsonNode['@id'][0];
         this.maps = [];
@@ -445,7 +448,7 @@
             //TODO: do we need a warning that there are no layers in this map?
         }
     },
-    
+
     parseMapEventSubBlock: function(block) {
         var a = [];
         if (block.Layer && block.Layer instanceof Array) {
@@ -458,15 +461,15 @@
             for (var i=0; i<block.Group.length; i++) {
                 var group = block.Group[i];
                 a.push({type: 'group', name:group.Name[0], enable: group.Enable[0] == 'true' ? true : false});
-            }            
+            }
         }
         return a;
     },
-    
+
     getInitialView: function() {
         return this.initialView;
     },
-    
+
     setInitialView: function(view) {
         this.initialView = view;
     }
@@ -483,6 +486,7 @@
     type: null,
     singleTile: false,
     extension: null,
+    
     initialize: function(jsonNode) {
         /* TODO: type can be any supported OpenLayers type */
         this.type = jsonNode.Type[0];
@@ -496,7 +500,7 @@
             this.extension = {};
         }
         this.resourceId = this.extension.ResourceId ? this.extension.ResourceId[0] : '';
-        
+
         var tagOptions = this.extension.Options;
         this.layerOptions = {};
         if (tagOptions && tagOptions[0]) {
@@ -520,6 +524,22 @@
           }
         }
         
+        //projection info from the extension
+        //this.layerOptions.projection = "EPSG:4326";  //default to WGS84 lat long
+        if (this.extension.ProjectionCode) {
+          this.layerOptions.projection = this.extension.ProjectionCode[0];
+        }
+        if (this.extension.ProjectionDef) {
+          var projDef = this.extension.ProjectionDef[0];
+          if (!this.layerOptions.projection) {
+            this.layerOptions.projection = "APP-DEF-PROJ";
+          }
+          Proj4js.defs[this.layerOptions.projection] = projDef;
+        }
+        if (!this.layerOptions.projection) {
+          this.layerOptions.projection = "EPSG:4326";
+        }
+
         switch (this.type) {
           case 'MapGuide':
           case 'MapServer':
@@ -527,7 +547,19 @@
                   Fusion.require('layers/' + this.type + '/' + this.type + '.js');
             }
             break;
+          case "Google":
+          case "Yahoo":
+          case "VirtualEarth":
+              this.layerOptions.isBaseLayer = true;
+              this.layerOptions.sphericalMercator = true;
+              this.layerOptions.displayProjection = "EPSG:4326";
+              //no break here continue below to set EPSG:3785 as projCode
           default:
+            if (this.layerOptions.sphericalMercator) {
+              this.layerOptions.projection = "EPSG:3785";  //commercial map layer projection spherical mercator
+            } else {
+              this.layerOptions.projection = "EPSG:4326";  //WGS84 lat long
+            }
             if ( !Fusion.Layers.Generic ) {
               Fusion.require('layers/Generic/Generic.js');
             }
@@ -566,7 +598,7 @@
                 this.mapId = jsonNode.MapWidget[i].MapId[0];
             }
         }
-        
+
         /* process widgets */
         if (jsonNode.Widget) {
             for (var i=0; i<jsonNode.Widget.length; i++) {
@@ -584,9 +616,9 @@
                 this.containersByName[container.name] = container;
             }
         }
-        
+
     },
-    
+
     /**
      * Function: addWidgetInstance
      *
@@ -599,7 +631,7 @@
     addWidgetInstance: function(widget) {
         this.widgetInstances.push(widget);
     },
-    
+
     /**
      * Function: getMapWidget
      *
@@ -610,14 +642,14 @@
     getMapWidget: function() {
         return this.mapWidget;
     },
-    
+
     /**
      * Function: create
      *
      * create all the things required by this widgetSet, including
      * containers and widgets.
      *
-     * Parameter: {<Fusion.Lib.ApplicationDefinition>} 
+     * Parameter: {<Fusion.Lib.ApplicationDefinition>}
      *
      * the application definition that this widgetSet is part of
      */
@@ -631,15 +663,15 @@
           if (mapGroup) {
             this.mapId = paramMapId;
           } else {
-            Fusion.reportError(new Fusion.Error(Fusion.Error.WARNING, 
+            Fusion.reportError(new Fusion.Error(Fusion.Error.WARNING,
               "can't find MapGroup: " + paramMapId + ' - reverting to default map'));
           }
         }
-        
+
         if (!mapGroup) {
           mapGroup = appDef.getMapGroup(this.mapId);
         }
-        
+
         //create the Map widget for this WidgetSet
         this.mapWidget = new Fusion.Widget.Map(this.mapWidgetTag,mapGroup,this);
         this.mapWidget.setMenu();
@@ -674,7 +706,7 @@
         }
         return map;
     },
-    
+
     /**
      * Function getWidgetsByType
      *
@@ -695,11 +727,11 @@
         }
         return widgets;
     },
-    
+
     getWidgetByName: function(name) {
         return this.widgetTagsByName[name];
     },
-    
+
     getContainerByName: function(name) {
         return this.containersByName[name];
     }
@@ -738,7 +770,7 @@
             //TODO: is this a problem if there are no items?
         }
     },
-    
+
     create: function(widgetSet) {
         var container;
         if (this.type == 'Toolbar' || this.type == 'Statusbar') {
@@ -761,13 +793,13 @@
             container.domObj.jxLayout.resize({forceResize: true});
         }
     },
-    
+
     createWidgets: function(widgetSet, container) {
         for (var i=0; i<this.items.length; i++) {
             this.items[i].create(widgetSet, container, this.name + '_' + i);
         }
     }
-    
+
 });
 
 /****************************************************************************
@@ -806,9 +838,9 @@
             this.label = jsonNode.Label ? jsonNode.Label[0] : '';
             this.label = OpenLayers.i18n(this.label);
             this.disabled = jsonNode.Disabled ? (jsonNode.Disabled[0].toLowerCase() == 'true' ? true : false) : false;
-            
+
             //console.log('Widget: ' + this.type + ', ' + this.name + ', ' + this.description);
-        
+
             if (jsonNode.Extension) {
                 this.extension = jsonNode.Extension[0];
             } else {
@@ -820,7 +852,7 @@
             }
         }
     },
-    
+
     getMapWidget: function() {
         if (this.widgetSet) {
             return this.widgetSet.getMapWidget();
@@ -828,7 +860,7 @@
             return null;
         }
     },
-    
+
     /**
      * Function: create
      *
@@ -908,11 +940,11 @@
             case 'Multi':
                 this.multi = new Fusion.Lib.ApplicationDefinition.Multi(jsonNode);
                 break;
-            case 'Separator':   
+            case 'Separator':
                 break;
         }
     },
-      
+
     create: function(widgetSet, container, idx) {
         switch(this.type) {
             case 'Widget':
@@ -925,13 +957,13 @@
                         if (!widget.uiClass) {
                             widget.uiClass = Jx.Toolbar.Item;
                             widget.setUiObject(new widget.uiClass());
-                        } else if (widget.uiClass == Jx.Button || widget.uiClass == Jx.Button.Color || widget.uiClass == Jx.Menu) {
+                        } else if (widget.uiClass == Jx.Button || widget.uiClass == Jx.Button.Color || widget.uiClass == Jx.Menu || widget.uiClass == Jx.Button.Flyout) {
                             widget.setUiObject(new widget.uiClass({
                                 label: widgetTag.label,
                                 image: widgetTag.imageUrl,
                                 imageClass: widgetTag.imageClass,
                                 toggle: widget.isExclusive
-                            }));                            
+                            }));
                         }
                         container.add(widget.uiObj);
                         if (widget.uiObj.setEnabled) {
@@ -982,7 +1014,7 @@
                         }
                     }
                 } else {
-                  Fusion.reportError(new Fusion.Error(Fusion.Error.WARNING, 
+                  Fusion.reportError(new Fusion.Error(Fusion.Error.WARNING,
                     "can't find widget: " + this.widgetName));
                  }
                 break;
@@ -997,14 +1029,14 @@
                 };
                 if (container instanceof Jx.Toolbar) {
                     menu = new Jx.Menu(opt);
-                } else if (container instanceof Jx.Menu || 
-                           container instanceof Jx.Menu.Context || 
+                } else if (container instanceof Jx.Menu ||
+                           container instanceof Jx.Menu.Context ||
                            container instanceof Jx.Menu.SubMenu) {
                     menu = new Jx.Menu.SubMenu(opt);
                 }
                 container.add(menu);
                 this.flyout.create(widgetSet, menu);
-                
+
                 break;
             case 'Multi':
                 var multi;
@@ -1018,11 +1050,11 @@
                 container.add(multi);
                 this.multi.create(widgetSet, multi);
                 break;
-                
+
             case 'Separator':
                 if (container instanceof Jx.Toolbar) {
                     container.add(new Jx.Toolbar.Separator());
-                } else if (container instanceof( Jx.Menu) || 
+                } else if (container instanceof( Jx.Menu) ||
                            container instanceof(Jx.Menu.SubMenu) ||
                            container instanceof(Jx.Menu.Context)) {
                     container.add(new Jx.Menu.Separator());
@@ -1045,7 +1077,7 @@
     description: null,
     imageUrl: null,
     items: null,
-    
+
     initialize: function(jsonNode) {
         this.label = jsonNode.Label ? jsonNode.Label[0] : '';
         this.tooltip = jsonNode.Tooltip ? jsonNode.Tooltip[0] : '';
@@ -1058,13 +1090,13 @@
             }
         }
     },
-    
+
     create: function(widgetSet, menu) {
         for (var i=0; i<this.items.length; i++) {
             this.items[i].create(widgetSet, menu);
         }
     }
-    
+
 });
 
 /****************************************************************************
@@ -1080,7 +1112,7 @@
     description: null,
     imageUrl: null,
     items: null,
-    
+
     initialize: function(jsonNode) {
         this.label = jsonNode.Label ? jsonNode.Label[0] : '';
         this.tooltip = jsonNode.Tooltip ? jsonNode.Tooltip[0] : '';
@@ -1093,13 +1125,13 @@
             }
         }
     },
-    
+
     create: function(widgetSet, multi) {
         for (var i=0; i<this.items.length; i++) {
             this.items[i].create(widgetSet, multi);
         }
     }
-    
+
 });
 
 /****************************************************************************
@@ -1116,7 +1148,7 @@
     parameters: null,
     join: null,
     rule: null,
-    
+
     initialize: function(json) {
         this.id = json['@id'];
         this.name = json['@name'];
@@ -1151,7 +1183,7 @@
             }
         }
     },
-    
+
     getJoinUrl: function(params) {
         if (this.join) {
             return '&joinlayer='+this.join.layer+'&joinpk='+this.join.primaryKey+'&joinfk='+this.join.foreignKey;
@@ -1159,7 +1191,7 @@
             return '';
         }
     },
-    
+
     getFilterUrl: function(params) {
         return '&filter='+encodeURIComponent(this.rule.toString(params));
     }
@@ -1197,11 +1229,11 @@
         this.type = type;
         this.conditions = [];
     },
-    
+
     add: function(condition) {
         this.conditions.push(condition);
     },
-    
+
     remove: function(condition) {
         for (var i=0; i<this.conditions.length; i++) {
             if (this.conditions[i] == condition) {
@@ -1210,7 +1242,7 @@
             }
         }
     },
-    
+
     toString: function(params) {
         var conditions = [];
         for (var i=0; i<this.conditions.length; i++) {

Modified: branches/fusion-2.0/lib/Map.js
===================================================================
--- branches/fusion-2.0/lib/Map.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/lib/Map.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -27,6 +27,7 @@
  * Class: Fusion.Widget.Map
  *
  * generic class for map widgets. Provides common utility classes.
+ * This class provides a wrapper around the OpenLayers Map object.
  * **********************************************************************/
 
 Fusion.Event.MAP_EXTENTS_CHANGED = Fusion.Event.lastEventId++;
@@ -41,6 +42,7 @@
 Fusion.Event.MAP_RELOADED = Fusion.Event.lastEventId++;
 Fusion.Event.MAP_SESSION_CREATED = Fusion.Event.lastEventId++;
 Fusion.Event.MAP_MAPTIP_REQ_FINISHED = Fusion.Event.lastEventId++;
+Fusion.Event.MAP_MAP_GROUP_LOADED = Fusion.Event.lastEventId++;
 
 
 Fusion.Constant.LAYER_POINT_TYPE = 0;
@@ -51,37 +53,69 @@
 Fusion.Constant.LAYER_DWF_TYPE = 5;
 
 Fusion.Widget.Map = OpenLayers.Class(Fusion.Lib.EventMgr, {
+    
+    /** The DOM object that holds the map */
     _oDomObj: null,
+    
+    /** The id of DOM object */
     _sDomObj: '',
+    
+    /** The internal name used for the map, usually assigned by the server */
     _sMapname: '',
-    _nWidth: -1,
-    _nHeight: -1,
+    
+    /** conversion factor to convert from map units to meters */
     _fMetersperunit: -1,
+    
+    /** scale denominator value */
     _fScale: -1,
+    
+    /** Dots per inch setting for the server */
     _nDpi: 96,
+    
+    /** The current bounds of the map, this is updated on every map draw */
     _oCurrentExtents: null,
+    
+    /** The maximum extent of the map */
     maxExtent: new OpenLayers.Bounds(),
+    
+    /** counter of worker threads for the ActivityIndicator widget  */
     _nWorkers: 0,
+    
+    /** The context menu object for right click */
     oContextMenu: null,
+    
+    /** flag to disable the map context menu, set this in the Map extension  */
     bSupressContextMenu: false,
-
+    
+    /** an array to hold all the individual map layer objects */
     aMaps: null,
+    
+    /** flag to indicate if all the map layers are loaded */
     mapsLoaded: false,
+    
+    /** the root of the layer structure for the Legend */
     layerRoot: null,
+    
+    /** flag to indicate if the map is tiled or not, set in the Map extension */
     singleTile: true,
+    
+    /** flag to indicate if fractional zoom is supported, ie. allow any scale
+    *   value rather than a fixed set of scales
+    */
     fractionalZoom: true,
+    
+    /** The DOM object that holds the map */
     maxScale: null, //set this to a large number in AppDef to zoom out beyond maxExtent, e.g. 1 billion
 
     /**
      * construct a new view Fusion.Widget.Map class.
      */
-    initialize : function(widgetTag, mapGroup, widgetSet) {
+    initialize: function(widgetTag, mapGroup, widgetSet) {
         this.widgetTag = widgetTag;
         var name = widgetTag.name;
         this.aMaps = [];
         this.buttonSet = new Jx.ButtonSet();
         this.widgetSet = widgetSet;
-        this._nCellSize = -1;
         this._sDomObj = name;
         this._oDomObj = $(this._sDomObj);
         this.layerRoot = new Fusion.Layers.Group({
@@ -100,6 +134,7 @@
           this.fractionalZoom = widgetTag.extension.FractionalZoom[0]=='false'?false:true;
         }
 
+        //if there is a scales array specified, use that set and turn off fraczoom
         var scalesArray = null;
         if (widgetTag.extension.Scales) {
           scalesArray = widgetTag.extension.Scales[0].split(',');
@@ -112,11 +147,13 @@
           this.maxScale = parseInt(widgetTag.extension.MaxExtent[0]);
         }
 
+        //set the maxExtent
         var maxExtent = null;
         if (widgetTag.extension.MaxExtent) {
           maxExtent = OpenLayers.Bounds.fromString(widgetTag.extension.MaxExtent[0]);
         }
 
+        //create the OpenLayers Map object
         OpenLayers.DOTS_PER_INCH = this._nDpi;
         if (!this.oMapOL) {
             var options = {
@@ -135,6 +172,7 @@
             this.oMapOL = new OpenLayers.Map(this._sDomObj, options );
         }
 
+        //Fusion specific modifications to the OL map window style
         this.oMapOL.viewPortDiv.style.position = 'absolute';  //not the top level container so set it to absolute
         this.oMapOL.viewPortDiv.style.zIndex = 0;   //must explicitly set the z-index for FF3
 
@@ -168,6 +206,7 @@
         this.registerEventID(Fusion.Event.MAP_SELECTION_ON);
         this.registerEventID(Fusion.Event.MAP_SELECTION_OFF);
         this.registerEventID(Fusion.Event.MAP_MAPTIP_REQ_FINISHED);
+        this.registerEventID(Fusion.Event.MAP_MAP_GROUP_LOADED);
 
         this.registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.mapLoaded,this));
 
@@ -186,10 +225,28 @@
         this.loadMapGroup(mapGroup);
     },
 
+    /**
+     * Function: mapLoaded
+     *
+     * Callback for when all maps have been loaded
+     *
+     * Parameter: none.
+     *
+     * Return: none
+     */
     mapLoaded: function() {
       this.setViewOptions(this.getUnits());
     },
 
+    /**
+     * Function: setMenu
+     *
+     * Attaches a context menu as defined in the AppDef to the map
+     *
+     * Parameter: none.
+     *
+     * Return: none
+     */
     setMenu: function() {
         if (this.widgetTag.extension.MenuContainer) {
             var contextMenu = new Jx.Menu.Context();
@@ -201,6 +258,15 @@
         }
     },
 
+    /**
+     * Function: loadMapGroup
+     *
+     * Controls the creation of Layers based on the MapGroup object passed in
+     *
+     * Parameter: {Object} mapGroup - a representation of the MapGroup object
+     *
+     * Return: none
+     */
     loadMapGroup: function(mapGroup) {
         //clear any existing selection
         this.mapsLoaded = false;
@@ -213,7 +279,10 @@
             this.aMaps[i].oLayerOL.destroy();
           }
         }
-
+ 
+        this._fMetersperunit = -1;
+        this.oMapOL.center = null;
+        this.maxExtent = new OpenLayers.Bounds();
         this.aMaps = [];
         this.layerRoot.clear();
 
@@ -230,8 +299,20 @@
           }
           this.aMaps[i].registerForEvent(Fusion.Event.LAYER_LOADED, OpenLayers.Function.bind(this.layerLoaded,this));
         }
+        this.triggerEvent(Fusion.Event.MAP_MAP_GROUP_LOADED);
     },
 
+    /**
+     * Function: layerLoaded
+     *
+     * Called after each layer is loaded in the OL viewport.  Nothing happens 
+     * here until the last layer is laoded, then it sets the OL baselayer and
+     * zooms to the initial extent.
+     *
+     * Parameter: none
+     *
+     * Return: none
+     */
     layerLoaded: function() {
       for (var i=0; i<this.aMaps.length; ++i) {
         if (!this.aMaps[i].isMapLoaded()) {
@@ -242,16 +323,35 @@
       if (this.aMaps.length == 1) {
         this.oMapOL.setBaseLayer(this.aMaps[0].oLayerOL);
       }
+      /*
+        Are we restoring a saved map state?
+      */
+      if(this.aMaps[0].bRestoreMapState && this.aMaps[0].bRestoreMapState === true && typeof(this.aMaps[0].oRestoredState.extents) !=="undefined"){
+        var a = this.aMaps[0].oRestoredState.extents.split(',');
+        a[0] = parseFloat(a[0]);
+        a[1] = parseFloat(a[1]);
+        a[2] = parseFloat(a[2]);
+        a[3] = parseFloat(a[3]);
+        this.setExtents(new OpenLayers.Bounds(a[0], a[1], a[2],  a[3]));
+      }
+      else
+      {
       var initialExtent = this.setInitialExtents();
       this.setExtents(initialExtent);
+      }
+
       this.triggerEvent(Fusion.Event.MAP_LOADED);
     },
 
     /**
-     * Method: wheelChange
+     * Function: wheelChange
      *
+     * handles mouse wheel events by accummulating the events and setting a timer
+     * to do the actual zoom in/out
+     * 
      * Parameters:
-     * evt - {Event}
+     * evt - {Event} the mouse wheel event object
+     * deltaZ - {Integer} the number of ticks wheeled
      */
     wheelChange: function(evt, deltaZ) {
         if (this.wheelTimer) {
@@ -264,6 +364,17 @@
         this.wheelTimer = setTimeout(OpenLayers.Function.bind(function(){this.doWheelChange(evt, deltaZ);}, this), 200);
     },
 
+    /**
+     * Function: doWheelChange
+     *
+     * Carries out the actual map zoom based on the wheel movement
+     *
+     * Parameters:
+     * evt - {Event} the mouse wheel event object
+     * deltaZ - {Integer} the number of ticks wheeled
+     *
+     * Return: none
+     */
     doWheelChange: function(evt, deltaZ) {
         this.wheelTimer = null;
         if (this.cumulativeDelta == 0) {
@@ -310,50 +421,104 @@
     },
 
     /**
-     * returns the dom element
+     * Function: getDomObj
+     *
+     * returns the dom element for this widget
+     *
+     * Parameters: none
+     *
+     * Return: none
      */
     getDomObj: function() {
         return this._oDomObj;
     },
 
 
+    /**
+     * Function: getMapName
+     *
+     * returns the name of the baselayer map
+     *
+     * Parameters: none
+     *
+     * Return: {String} the name of the baselayer map
+     */
     getMapName: function() {
         //TODO: what is the mapname in the case of multiple map layer objects?
         //just return baselayer mapname for now
         return this.aMaps[0].getMapName();
     },
 
+    /**
+     * Function: getMapTitle
+     *
+     * returns the Title of the baselayer map.  This is a human-readable title
+     *
+     * Parameters: none
+     *
+     * Return: {String} the Title of the baselayer map
+     */
     getMapTitle: function() {
         //TODO: what is the map title in the case of multiple map layer objects?
         //just return baselayer mapTitle for now
         return this.aMaps[0]._sMapTitle;
     },
 
+    /**
+     * Function: getSessionID
+     *
+     * returns the server session ID
+     *
+     * Parameters: none
+     *
+     * Return: {String} the session ID
+     */
     getSessionID: function() {
         //TODO: what is the mapname in the case of multiple map layer objects?
         //just return baselayer session ID for now
         return this.aMaps[0].getSessionID();
     },
 
+    /**
+     * Function: getDomId
+     *
+     * returns the ID of dom element for this widget
+     *
+     * Parameters: none
+     *
+     * Return: {String} the id of the DOM element
+     */
     getDomId: function() {
         return this._sDomObj;
     },
 
+    /**
+     * Function: setMapOptions
+     *
+     * sets options on the OpenLayers map object, a wrapper for the OL function
+     *
+     * Parameters: {Object} options - has of option key/value pairs
+     *
+     * Return: none
+     */
     setMapOptions: function(options) {
         this.oMapOL.setOptions(options);
     },
 
+    /**
+     * Function: addMap
+     *
+     * adds a map/Layer to the map and registers some event handlers on the map
+     *
+     * Parameters: {Object} map - the map object to tbe added (really a layer object)
+     *
+     * Return: none
+     */
     addMap: function(map) {
 
         if (map.mapTag.layerOptions.maxExtent) {
-          this.projection = map.projection;
-          this.units = map.units;
           this.maxExtent.extend(map.mapTag.layerOptions.maxExtent);
-          this.oMapOL.setOptions({
-                  maxExtent: this.maxExtent,
-                  units: map.units,
-                  projection: this.projection
-          });
+          this.oMapOL.setOptions({maxExtent: this.maxExtent});
         }
 
         //if bRestrictExtent is null, use the default OL behaviour with somewhat restricted map navigation
@@ -367,19 +532,44 @@
           }
         }
         this.oMapOL.addLayer(map.oLayerOL);
-        map.registerForEvent(Fusion.Event.MAP_LOADED,
-                OpenLayers.Function.bind(this.mapLoadHandler, this));
+        if (map.oLayerOL.isBaseLayer) {
+          this.projection = map.projection;
+          this.units = map.units;
+          this.oMapOL.setOptions({
+                  units: map.units,
+                  projection: this.projection
+          });
+        }
+        
         map.registerForEvent(Fusion.Event.MAP_SELECTION_OFF,
                 OpenLayers.Function.bind(this.selectionHandler, this));
         map.registerForEvent(Fusion.Event.MAP_SELECTION_ON,
                 OpenLayers.Function.bind(this.selectionHandler, this));
     },
 
+    /**
+     * Function: getAllMaps
+     *
+     * returns the array of map objects
+     *
+     * Parameters: none
+     *
+     * Return: {Array} the array of map Objects
+     */
     getAllMaps: function() {
         return this.aMaps;
     },
 
-    //this uses setTimeout so this method can be called from an IFRAME
+    /**
+     * Function: reloadMap
+     *
+     * Called to reload all the map objects.
+     * this uses setTimeout so this method can be called from an IFRAME
+     *
+     * Parameters: none
+     *
+     * Return: none
+     */
     reloadMap: function() {
       for (var i=0; i<this.aMaps.length; ++i) {
         var map = this.aMaps[i];
@@ -387,6 +577,17 @@
       }
     },
 
+    /**
+     * Function: loadScaleRanges
+     *
+     * Loads the ScaleRange objects separate from the LoadMap sequence since
+     * this also generates sprites and is a relatively expensive operation.
+     *
+     * Parameters: {Function} userFunc - a user defined function to be called as a
+     *                                  callback
+     *
+     * Return: none
+     */
     loadScaleRanges: function(userFunc) {
       for (var i=0; i<this.aMaps.length; ++i) {
         var map = this.aMaps[i];
@@ -397,7 +598,9 @@
     /**
      * Function: query
      *
-     * dispatch query requests to maps
+     * dispatch query requests to the maps
+     *
+     * Parameters: {object} options - query options to be passed to each map
      */
     query: function(options) {
         this.lastQueryOptions = options;
@@ -408,25 +611,14 @@
     },
 
     /**
-     * Function: mapLoadHandler
+     * Function: selectionHandler
      *
      * handle selection events from maps and republish for
      * widgets as appropriate
-     */
-    mapLoadHandler: function() {
-        ++this.mapLoadCounter;
-        if (this.mapLoadCounter == this.aMaps.length) {
-            this._oInitialExtents = null;
-            this.fullExtents();
-            this.triggerEvent(Fusion.Event.MAP_LOADED);
-        }
-    },
-
-    /**
-     * Function: selectionHandler
      *
-     * handle selection events from maps and republish for
-     * widgets as appropriate
+     * Parameters: none
+     *
+     * Return: none
      */
     selectionHandler: function() {
         if (this.hasSelection()) {
@@ -439,7 +631,9 @@
     /**
      * Function: hasSelection
      *
-     * returns true if any map has a selection
+     * cehck to see if any of the maps have an active selection
+     *
+     * Returns: {Boolean} - true if any map has a selection
      */
      hasSelection: function() {
          for (var i=0; i<this.aMaps.length; i++ ) {
@@ -466,7 +660,7 @@
      /**
       * Function: getSelection
       *
-      * returns the current selection asynchronously in case we
+      * initiates a call to get the current selection asynchronously in case we
       * need to retrieve the details from the server
       */
      getSelection: function(callback, layers, startcount) {
@@ -482,6 +676,8 @@
          this.oSelection = {};
          this.nSelectionMaps = 0;
          for (var i=0; i<this.aMaps.length; i++ ) {
+		     if(this.aMaps[i].layerType == "Google" || this.aMaps[i].layerType == "Yahoo" ||this.aMaps[i].layerType == "VirtualEarth" )
+			     continue;
              this.nSelectionMaps++;
              this.aMaps[i].getSelection(
                     OpenLayers.Function.bind(this.accumulateSelection, this, this.aMaps[i]),
@@ -492,7 +688,11 @@
      /**
       * Function: setSelection
       *
-      * sets a Selection XML back to the server
+      * sets a Selection XML back to the server for each of the maps
+      *
+      * Parameters: 
+      * {String} selText - the selection string 
+      * {Boolean} zoomTo - if set, will zoom to the selection on completion
       */
       setSelection: function(selText, zoomTo) {
          for (var i=0; i<this.aMaps.length; i++ ) {
@@ -505,6 +705,10 @@
       *
       * accumulate the selection results from each map and when all have
       * reported in, pass the results to the callback function
+      *
+      * Parameters:
+      * {Object} map - the map object that has the selection
+      * {Object} oSelection - the Fusion selection object
       */
      accumulateSelection: function(map, oSelection) {
          this.oSelection[map._sMapname] = oSelection;
@@ -522,25 +726,33 @@
       * Function: setActiveLayer
       *
       * sets the active layer for selection/manipulation
+      *
+      * Parameters:
+      * {Object} oLayer - the layer to be set as active
       */
-    setActiveLayer: function( oLayer ) {
-        this.oActiveLayer = oLayer;
-        if (oLayer) {
-            this.oActiveMap = oLayer.map;
-        }
-        this.triggerEvent(Fusion.Event.MAP_ACTIVE_LAYER_CHANGED, oLayer);
-    },
+      setActiveLayer: function( oLayer ) {
+          this.oActiveLayer = oLayer;
+          if (oLayer) {
+              this.oActiveMap = oLayer.map;
+          }
+          this.triggerEvent(Fusion.Event.MAP_ACTIVE_LAYER_CHANGED, oLayer);
+      },
 
      /**
       * Function: getActiveLayer
       *
       * returns the active layer for selection/manipulation
+      *
+      * Returns:
+      * {Object} the active layer
       */
     getActiveLayer: function() {
         return this.oActiveLayer;
     },
 
     /**
+     * Function: _addWorker
+     * 
      * indicate that a new asynchronous process has started and make sure the
      * visual indicator is visible for the user.  This is intended to be used
      * internally by gMap but could be used by external tools if appropriate.
@@ -552,6 +764,8 @@
     },
 
     /**
+     * Function: _removeWorker
+     * 
      * indicate that an asynchronous process has completed and hide the
      * visual indicator if no remaining processes are active.  This is
      * intended to be used internally by gMap but could be used by
@@ -566,19 +780,57 @@
         this.triggerEvent(Fusion.Event.MAP_BUSY_CHANGED, this);
     },
 
+    /**
+     * Function: mapExtentsChanged
+     *
+     * OpenLayers event handler for whenever the map changes either zoom level
+     * of the center has changed.  This in turn triggers the Fusion event. 
+     *
+     * Parameters: none
+     *
+     * Return: none
+     */
     mapExtentsChanged: function() {
         this._oCurrentExtents = this.oMapOL.getExtent();
         this.triggerEvent(Fusion.Event.MAP_EXTENTS_CHANGED);
     },
 
+    /**
+     * Function: isBusy
+     *
+     * check to see if there are any outstanding requests to the server
+     *
+     * Parameters: none
+     *
+     * Return: {Boolean} true if there are active requests
+     */
     isBusy: function() {
         return this._nWorkers > 0;
     },
 
+    /**
+     * Function: sizeChanged
+     *
+     * callback for when the browser window size changes, simply calls resize 
+     * on the map viewport layout object
+     *
+     * Parameters: none
+     *
+     * Return: none
+     */
     sizeChanged: function() {
         this.resize();
     },
 
+    /**
+     * Function: resize
+     *
+     * handles the resizing of the maps and triggers a Fusion event
+     *
+     * Parameters: none
+     *
+     * Return: none
+     */
     resize: function() {
       if (!this.mapsLoaded) {
         return;
@@ -586,27 +838,57 @@
       //console.log('Fusion.Widget.Map.resize');
         this.oMapOL.updateSize();
         var d = $(this.getDomObj()).getContentBoxSize();
-        this._nWidth = d.width;
-        this._nHeight = d.height;
         if (this._oCurrentExtents) {
           this.setExtents(this._oCurrentExtents);
         }
         this.triggerEvent(Fusion.Event.MAP_RESIZED, this);
     },
 
+    /**
+     * Function: redraw
+     *
+     * redraws the map using current extents and zoom level.  A dummy parameter
+     * is added to the map request to ensure the map request is not cached.
+     *
+     * Parameters: none
+     *
+     * Return: none
+     */
     redraw: function() {
       for (var i=0; i<this.aMaps.length; i++ ) {
-        this.aMaps[i].oLayerOL.params.ts = (new Date()).getTime();
-        //mergeNewParams calls redraw on the layer, which will get called below anyway
-        //this.aMaps[i].oLayerOL.mergeNewParams({ts : (new Date()).getTime()});
+        if(this.aMaps[i].oLayerOL.params){
+            this.aMaps[i].oLayerOL.params.ts = (new Date()).getTime();
+            //mergeNewParams calls redraw on the layer, which will get called below anyway
+            //this.aMaps[i].oLayerOL.mergeNewParams({ts : (new Date()).getTime()});
+        }
       }
       this.oMapOL.setCenter(this.oMapOL.getCenter(), this.oMapOL.getZoom(), false, true);
     },
 
+    /**
+     * Function: setBackgroundColor
+     *
+     * sets the background color for the map
+     *
+     * Parameters: {String} color - the CSS color value to set as background
+     *
+     * Return: none
+     */
     setBackgroundColor: function(color) {
         this._oDomObj.style.backgroundColor = color;
     },
 
+    /**
+     * Function: setExtents
+     *
+     * handle selection events from maps and republish for
+     * widgets as appropriate
+     *
+     * Parameters: {Object} oExtents - an OpenLayers.Bounds object or an array 
+     *                            of 4 values that will be converted to Bounds
+     *
+     * Return: none
+     */
     setExtents: function(oExtents) {
         if (!oExtents) {
             Fusion.reportError(new Fusion.Error(Fusion.Error.WARNING,
@@ -627,10 +909,14 @@
     },
 
     /**
+     * Function: setInitialExtents
+     * 
      * determine the initialExtents of the map from (in order of precedence):
      * 1. a URL query parameter called 'extent'
      * 2. an <InitialView> specified in the MapGroup in AppDef
      * 3. the maxExtent as specified by the LoadMap call (default)
+     *
+     * Returns: {Object} an OpenLayers.Bounds object which is the initial extent
      */
     setInitialExtents: function() {
       var initialExtents;
@@ -659,7 +945,12 @@
     },
 
     /**
-     * sets the extent by examining all mapgroup map extents
+     * Function: getMapGroupExtent
+     *
+     * gets the intitial extents from all maps with or without including the
+     * extent of any Generic/commercial layers
+     * 
+     * Return: {Object} an OpenLayers.Bounds object which is the initial extent
      */
     getMapGroupExtent: function(includeGenericLayers) {
       var initialExtent;
@@ -673,6 +964,8 @@
     },
 
     /**
+     * Function: fullExtents
+     * 
      * sets the extent of the map to the max as returned by loadMap
      */
     fullExtents: function() {
@@ -680,10 +973,34 @@
       this.setExtents(extents);
     },
 
+    /**
+     * Function: isMapLoaded
+     * 
+     * returns if the map has finished loading (based on setting the 
+     * _oCurrentExtent value)
+     *
+     * Returns {Boolean} true if the map is loaded and extent has been set
+     */
     isMapLoaded: function() {
         return (this._oCurrentExtents) ? true : false;
     },
 
+    /**
+     * Function: zoom
+     * 
+     * sets the map zoom and extent.
+     *
+     * Parameters:
+     *   fX {Float} - new x coordinate value in map units
+     *   fY {Float} - new y coordinate value in map units
+     *   nFactor {Float} - zoom factor; positive values zoom in, negative out
+     *                  - if set to 0 or 1, the map is just recentered
+     *                  - if the map has fractional zoom enabled, the map resolution
+     *                  will be modified by this factor
+     *                  - with fixed scales, zoom up or down one level, depending on the sign
+     *
+     * Returns: none
+     */
     zoom: function(fX, fY, nFactor) {
         //do this differntly with OL code??
         if (nFactor == 1 || nFactor == 0) {
@@ -720,15 +1037,63 @@
         }
     },
 
+    /**
+     * Function: zoom
+     * 
+     * sets the map zoom and extent.
+     *
+     * Parameters:
+     *   fX {Float} - new x coordinate value in map units
+     *   fY {Float} - new y coordinate value in map units
+     *   nFactor {Float} - zoom factor; positive values zoom in, negative out
+     *                  - if set to 0 or 1, the map is just recentered
+     *                  - if the map has fractional zoom enabled, the map resolution
+     *                  will be modified by this factor
+     *                  - with fixed scales, zoom up or down one level, depending on the sign
+     *
+     * Returns: none
+     */
     zoomToScale: function(fScale) {
         var center = this.getCurrentCenter();
         var extent = this.getExtentFromPoint(center.x, center.y, fScale);
         this.setExtents(extent);
     },
 
-    queryRect : function(fMinX, fMinY, fMaxX, fMaxY) { },
+    /**
+     * Function: zoom
+     * 
+     * sets the map zoom and extent.
+     *
+     * Parameters:
+     *   fX {Float} - new x coordinate value in map units
+     *   fY {Float} - new y coordinate value in map units
+     *   nFactor {Float} - zoom factor; positive values zoom in, negative out
+     *                  - if set to 0 or 1, the map is just recentered
+     *                  - if the map has fractional zoom enabled, the map resolution
+     *                  will be modified by this factor
+     *                  - with fixed scales, zoom up or down one level, depending on the sign
+     *
+     * Returns: none
+     */
+    queryRect: function(fMinX, fMinY, fMaxX, fMaxY) { },
 
-    queryPoint : function(fX, fY) { },
+    /**
+     * Function: zoom
+     * 
+     * sets the map zoom and extent.
+     *
+     * Parameters:
+     *   fX {Float} - new x coordinate value in map units
+     *   fY {Float} - new y coordinate value in map units
+     *   nFactor {Float} - zoom factor; positive values zoom in, negative out
+     *                  - if set to 0 or 1, the map is just recentered
+     *                  - if the map has fractional zoom enabled, the map resolution
+     *                  will be modified by this factor
+     *                  - with fixed scales, zoom up or down one level, depending on the sign
+     *
+     * Returns: none
+     */
+    queryPoint: function(fX, fY) { },
 
     /**
      *
@@ -740,7 +1105,7 @@
      * @return an object with geographic coordinates in x and y properties of the
      *         object.
      */
-    pixToGeo : function( pX, pY ) {
+    pixToGeo: function( pX, pY ) {
         var lonLat = this.oMapOL.getLonLatFromPixel( new OpenLayers.Pixel(pX,pY) );
         if (lonLat != null) {
           return {x:lonLat.lon, y:lonLat.lat};
@@ -758,7 +1123,7 @@
      * @return an object with pixel coordinates in x and y properties of the
      *         object.
      */
-    geoToPix : function( gX, gY ) {
+    geoToPix: function( gX, gY ) {
         if (!(this._oCurrentExtents)) {
             return null;
         }
@@ -774,7 +1139,7 @@
      *
      * @return geographic measure
      */
-    pixToGeoMeasure : function(nPixels) {
+    pixToGeoMeasure: function(nPixels) {
         var resolution = this.oMapOL.getResolution();
         return (nPixels*resolution);
     },
@@ -785,12 +1150,10 @@
      *
      * @param projCode projection code
      */
-    setProjection: function(projCode) {
-        if (!Proj4js.defs[projCode]) {
-          Fusion.reportError( new Fusion.Error(Fusion.Error.WARNING,
-            'Projection definition not found for:'+projCode));
-        }
+    setProjection: function(projCode, units) {
+        this.projection = projCode;
         this.oMapOL.projection = projCode;
+        this.oMapOL.units = units;
     },
 
   /**

Modified: branches/fusion-2.0/lib/OpenLayers/OpenLayers.js
===================================================================
--- branches/fusion-2.0/lib/OpenLayers/OpenLayers.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/lib/OpenLayers/OpenLayers.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -11981,11 +11981,6 @@
                 style.addRule('olv\\:' + shapes[i], "behavior: url(#default#VML); " +
                               "position: absolute; display: inline-block;");
             }                  
-           var shapes = ['shape','rect', 'oval', 'fill', 'stroke', 'imagedata', 'group','textbox'];  
-           for (var i = 0, len = shapes.length; i < len; i++) { 
-               style.addRule('olv\\:' + shapes[i], "behavior: url(#default#VML); " +
-               "position: absolute; display: inline-block;"); 
-           }
         }
         
         OpenLayers.Renderer.Elements.prototype.initialize.apply(this, 
@@ -27389,6 +27384,14 @@
      */
     sphericalMercator: false, 
 
+    /**
+     * APIProperty: animationEnabled
+     * {Boolean} If set to true, the transition between zoom levels will be
+     *     animated. Set to false to match the zooming experience of other
+     *     layer types. Default is true.
+     */
+    animationEnabled: true, 
+
     /** 
      * Constructor: OpenLayers.Layer.VirtualEarth
      * 
@@ -27434,6 +27437,9 @@
 
             } catch (e) { }
             this.mapObject.HideDashboard();
+            if(typeof this.mapObject.SetAnimationEnabled == "function") {
+                this.mapObject.SetAnimationEnabled(this.animationEnabled);
+            }
         }
 
         //can we do smooth panning? this is an unpublished method, so we need 
@@ -27447,6 +27453,13 @@
         }
 
     },
+    
+    /**
+     * Method: onMapResize
+     */
+    onMapResize: function() {
+        this.mapObject.Resize(this.map.size.w, this.map.size.h);
+    },
 
     /** 
      * APIMethod: getWarningHTML
@@ -28865,9 +28878,7 @@
      * {Object} the modified style
      */
     createLiterals: function(style, feature) {
-        var context = OpenLayers.Util.extend({}, feature.data);
-        OpenLayers.Util.extend(context, feature.attributes);
-        OpenLayers.Util.extend(context, this.context);
+        var context = this.context || feature.attributes || feature.data;
         
         for (var i in this.propertyStyles) {
             style[i] = OpenLayers.Style.createLiteral(style[i], context, feature);

Modified: branches/fusion-2.0/lib/OpenLayers/theme/default/style.css
===================================================================
--- branches/fusion-2.0/lib/OpenLayers/theme/default/style.css	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/lib/OpenLayers/theme/default/style.css	2010-03-24 18:31:34 UTC (rev 2105)
@@ -75,11 +75,13 @@
     right: 0px;
 }
 
+/* removed for Fusion
 .olControlOverviewMapElement {
     padding: 10px 18px 10px 10px;
     background-color: #00008B;
     -moz-border-radius: 1em 0 0 0;
 }
+*/
 
 .olControlOverviewMapMinimizeButton {
     right: 0px;

Modified: branches/fusion-2.0/lib/fusion.js
===================================================================
--- branches/fusion-2.0/lib/fusion.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/lib/fusion.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -98,7 +98,7 @@
         Lib: {},
 
         /***************************************************************************
-         * Class: Fusion.Maps
+         * Class: Fusion.Layers
          * 
          * A set of classes that implement layer functionality for various server 
          * technologies.
@@ -112,21 +112,40 @@
          ***************************************************************************/
         Constant: {},
     
+        /**
+         * Pointer to the Application Definition, parsed into all the Fusion 
+         * objects: MapGroups, WidgetSets
+         */
         applicationDefinition: null,
     
         /**
-         * URL to the configuration file to use for this application.  The
-         * configuration file must be located on the same domain as the
-         * application template.
+         * URL of a proxy script if the map server is on a different domain/port
+         * that the application template to get around the same-origin policy
          */
-        sConfigFileURL : "",
-    
-        sWebAgentURL : "",
-        sWebTierURL : "",
-        sRedirectScript : "",  
-        bForceRedirect : false,
-        sScriptLang : "",
-        locale : 'en',
+        sRedirectScript: "",  
+        
+        /**
+         * A flag to force XHR calls through the proxy, defaults to false
+         */
+        bForceRedirect: false,
+        
+        /**
+         * the script programming language for server-side programming.  
+         * Typically set to 'php' but other server languages may be used. 
+         */
+        sScriptLang: "php",
+        
+        /**
+         * the locale setting for the browser and for localization of Fusion.
+         * This is the same as the locale setting in OpenLayers and is used as 
+         * the file name for localization files in the /text subdirectory 
+         */
+        locale: 'en',
+        
+        /**
+         * the hash of strings used for localization of Fusion.  Strings are
+         * indexed by a key which is used in calls to OpenLayers.i18n()
+         */
         Strings: {},    //locale specific strings
     
         /** URL to the directory from which fusion.js was loaded */
@@ -134,18 +153,25 @@
     
         /** 
          * configuration object that holds the server configuration as
-         * loaded from fusion/config.xml
+         * loaded from fusion/config.json
          */
         configuration: null,
     
-        /* broker instance for communicating with the mapagent */
+        /**
+        * broker instance for communicating with the mapagent, typically only
+        * used with MapGuide
+        */
         oBroker: null,
     
         /** An array of scripts that are queued to be loaded */
-        aScripts : [],
+        aScripts: [],
         /** An array of scripts that are currently being loaded */
         aLoadingScripts: [],
-        /** The current state during initialization of the application */
+        
+        /** 
+        * The current state during initialization of the application.  Valid 
+        * states are enumerated below 
+        */
         loadState: null,
  
         /** API loading has not begun */
@@ -157,7 +183,11 @@
         /** Loading is complete */
         LOAD_COMPLETE: 3,
     
-        /** unit related stuff */
+        /** 
+        * unit related stuff - the following values are the keys into the 
+        * unit related arrays below: aUnitPerMeter, aMeterPerUnit, aUnitNames
+        * and aUnitAbbr
+        */
         UNKNOWN: 0,
         INCHES: 1,
         FEET: 2,
@@ -172,6 +202,9 @@
         DECIMALDEGREES: 11,
         DMS: 12,
         PIXELS: 13,
+        /** 
+        * conversion factors to go from the specified units to meters
+        */
         aUnitPerMeter: [1.0, /* 0 - UNKNOWN */
                         39.37, /* 1 - INCHES */
                         3.2808, /* 2 - FEET */
@@ -187,6 +220,9 @@
                         0.000009044, /* 12 - DMS */
                         1.0 /* 13 - PIXELS */
                         ],
+        /** 
+        * conversion factors to go from meters to the specified units
+        */
         aMeterPerUnit: [1.0, /* 0 - UNKNOWN */
                         0.0254, /* 1 - INCHES */
                         0.3048, /* 2 - FEET */
@@ -201,9 +237,17 @@
                         111061.75033, /* 11 - DECIMALDEGREES */
                         111061.75033, /* 12 - DMS */
                         1.0 /* 13 - PIXELS */],
+                        
+        /** 
+        * the units names spelled out fully
+        */
         aUnitNames: ['Unknown','Inches', 'Feet', 'Yards', 'Miles', 'Nautical Miles',
                      'Millimeters', 'Centimeters', 'Meters', 'Kilometers', 
                      'Degrees', 'Decimal Degrees', 'Degrees Minutes Seconds', 'Pixels'],
+                     
+        /** 
+        * unit names abbreviations
+        */
         aUnitAbbr: ['unk', 'in', 'ft', 'yd', 'mi', 'nm', 
                     'mm', 'cm', 'm', 'km', 
                     '&deg;', '&deg;', '&deg;', 'px'],
@@ -211,23 +255,28 @@
         /**
          * Function: initialize
          *
-         * Initialize the Fusion application.
+         * Initialize the Fusion application.  This method must be called from
+         * the template's onload method once all script files have been loaded.
+         * Applications can register for the event Fusion.Event.FUSION_INITIALIZED
+         * to carry out further application initialization when all the Fusion
+         * objects have been created and are available.
          *
          * @param {Object} options
          *
          * Optional paramters that can be passed to initialize are:
          *
-         * {String} applicationDefinition - a URL or resource ID 
+         * {String} applicationDefinitionURL - a URL or resource ID 
          *          for an ApplicationDefinition file
          * {String} sessionId - a session id to start the application
          *          with.  Normally, applications are started without
          *          a session id and create one.  However, sometimes
          *          it is desirable to use an existing session.
          */
-        initialize : function(options) {
+        initialize: function(options) {
             options = options || {};
             var sessionIdParam = this.getQueryParam('Session');
-            this.sessionId = sessionIdParam || (options.sessionId || null);
+            // Override the pre-created sessionId by user specified sessionId(if exist)
+            this.sessionId = sessionIdParam || options.sessionId || this.sessionId;
         
             if (options.applicationDefinitionURL) {
                 this.applicationDefinitionURL = options.applicationDefinitionURL;            
@@ -248,15 +297,12 @@
             }
             this.initializeLocale();
 
-            this.sWebagentURL = "";
-            this.sScriptLang = "";
-
             /*
-                     * if the application has been loaded from the same host as
-                     * fusion is installed in, then technically we don't need to
-                     * use the redirect script because we conform to the 
-                     * Same Origin Policy for XmlHttpRequest to work.
-                     */
+             * if the application has been loaded from the same host as
+             * fusion is installed in, then technically we don't need to
+             * use the redirect script because we conform to the 
+             * Same Origin Policy for XmlHttpRequest to work.
+             */
             var test = window.location.protocol+'//'+window.location.host;
             var configUrl = 'config.json';
             //if (this.fusionURL.indexOf(test,0) == 0) {
@@ -267,9 +313,6 @@
                 configUrl += '&method=get';
             }
         
-            /*script language*/
-            this.sScriptLang = 'php';
-        
             if (Fusion.configuration) {
                 //config.json loaded via single file build
                 this.serverSet();
@@ -283,6 +326,19 @@
             }
         },
     
+        /**
+         * Function: initializeLocale
+         *
+         * Initialize the Strings hash with the requested locale.  This method
+         * simply extends the OpenLayers strings hash with strings specific
+         * to Fusion.  Add strings to the files in fusion/text/[locale].json.
+         * This method can be called before Fusion.initialize() if localized
+         * strings are required in the template initialization.
+         *
+         * @param {String} locale - the locale value e.g. 'en-CA' or simply 'en'
+         *                        for English
+         *
+         */
         initializeLocale: function(locale) {
           OpenLayers.Lang.setCode(locale ? locale : window._FusionLocale);
           this.locale = OpenLayers.Lang.code;
@@ -332,6 +388,7 @@
                     break;
             }
         },
+        
         /**
          * Function: loadQueuedScripts
          *
@@ -378,7 +435,7 @@
          *
          * The url of the script.
          */
-        queueScript : function(url) {
+        queueScript: function(url) {
             if(!document.getElementById(url) && !this.aScripts[url]) {
                 var script = document.createElement('script');
                 script.defer = false;
@@ -392,6 +449,7 @@
                 this.aScripts.push(script);
             }
         },
+        
         /**
          * Function: scriptFailed
          *
@@ -437,11 +495,12 @@
                 }
             }
         },
+        
         /**
          * Function: checkLoadingScripts
          *
-         * check if scripts have loaded.  In IE, scripts don't seem to fire the onload
-         * event.  Safari also seems to have some problems.
+         * check if scripts have loaded.  In IE, scripts don't seem to fire the
+         * onload event.  Safari also seems to have some problems.
          */
         checkLoadingScripts: function() {
             var agt=navigator.userAgent.toLowerCase();
@@ -460,13 +519,15 @@
                 }
             }
         },
+        
         /**
          * Function: loadConfig
          *
-         * asynchronously load the application definition through the broker and config
-         * manager.
+         * asynchronously load the application definition.  For MapGuide, also
+         * set up the broker object.  Once the AppDef is loaded/created advance
+         * the laod state.
          */
-        loadConfig : function() {
+        loadConfig: function() {
             var mapAgentUrl = this.getConfigurationItem('mapguide', 'mapAgentUrl');
             if (mapAgentUrl) {
                 this.oBroker = new Fusion.Lib.MGBroker();
@@ -494,7 +555,7 @@
          * Parameter {Object} r 
          * an XMLHttpRequest object
          */
-        getConfigCB : function(r) {
+        getConfigCB: function(r) {
             if (r.responseText) {  
                 eval("this.configuration="+r.responseText);
                 this.serverSet();
@@ -513,11 +574,11 @@
          * Parameter {Object} r 
          * an XMLHttpRequest object
          */
-        serverSet : function() {
+        serverSet: function() {
             var s = this.configuration.mapguide.webTierUrl;
             /* if it is set, use it ... otherwise assume fusion is installed in
-                      * the default location and compute the web tier url from that
-                      */
+             * the default location and compute the web tier url from that
+             */
             if (s) {
                 var nLength = s.length;
                 var slastChar =  s.charAt((nLength-1));
@@ -569,8 +630,8 @@
          *
          * Parameter: {Object} options
          *
-         * optional parameters to send with the request, passed directly to
-         * Prototype's Ajax.Request function
+         * optional parameters to send with the request, passed directly to the
+         * OpenLayers Ajax.Request function
          */
         ajaxRequest: function(scriptURL, options) {
             //console.log('options.parameters='+options.parameters);
@@ -612,22 +673,18 @@
         },
     
          /**
-         * Function: convertXML
+         * Function: getXmlAsJson
          *
-         * Optionally convert XML to JSON using a server-side script
+         * Convert XML to JSON using a server-side script
          * for requests that aren't available in JSON.
          *
-         * Parameter: {XmlHttpRequest} r
+         * Parameter: {String} url - the URL of the XML object to be converted;
+         *      this can be any URL and is not prepended with the Fusion URL
          *
-         * the XmlHttpRequest object
+         * Parameter: {Function} callback - a callback function to be called if 
+         *      the request is successful
          *
-         * Parameter: json
-         *
          * boolean indicator if the content is JSON or not.
-         *
-         * Parameter: callback
-         *
-         * callback method to be executed on success and will be passed a parsed json object
         */
         getXmlAsJson: function(url, callback) {
             var options = {
@@ -638,17 +695,40 @@
             var temp = new OpenLayers.Ajax.Request(url, options);
         },
     
+         /**
+         * Function: xml2json
+         *
+         * Callback method to convert the XNR response into an actual json object
+         * and triggers the call to the callback method
+         *
+         * Parameter: callback
+         *
+         * callback method to be executed on success and will be passed a parsed json object
+         *
+         * Parameter: {XmlHttpRequest} r
+         *
+         * the XmlHttpRequest object
+         *
+         * Parameter: json
+         *
+         * boolean indicator if the content is JSON or not (set by OpenLayers)
+         *
+        */
         xml2json: function(callback, r, json) {
           if (json) {
             var o;
             eval("o="+r.responseText);
             callback(o);
           } else {
-          if (r.status >= 400) {
-              Fusion.reportError(new Fusion.Error(Fusion.Error.FATAL,
-                  'xml2json: invalid XML document: ' + r.transport.responseText + " : " + r.request.url));
-              return;
-          }
+            if (r.status >= 400) {
+                var msg = r.transport.responseText;
+                if (msg == "") {
+                    msg = OpenLayers.i18n('serverNotAvailable');
+                }
+                Fusion.reportError(new Fusion.Error(Fusion.Error.FATAL,
+                  OpenLayers.i18n('invalidXMLDocument', {'msg':msg, 'url':r.request.url})));
+                return;
+            }
 
             var options = {
               onSuccess: callback,
@@ -671,7 +751,7 @@
          *
          * Returns: {Object} a map object or null if not found.
          */
-        getMapByName : function(name) {
+        getMapByName: function(name) {
             var map = null;
             if (this.applicationDefinition) {
                 map = this.applicationDefinition.getMapByName(name);
@@ -682,7 +762,7 @@
         /**
          * Function: getMapById
          *
-         * return a map widget that is associated with the given dom element
+         * return a map widget that is associated with the given DOM element
          * by id.
          *
          * Parameter: {String} id
@@ -691,7 +771,7 @@
          *
          * Returns: {Object} a map object or null if not found.
          */
-        getMapById : function(id) {
+        getMapById: function(id) {
             var map = null;
             if (this.applicationDefinition) {
                 map = this.applicationDefinition.getMapById(id);
@@ -702,7 +782,8 @@
         /**
          * Function: getMapByIndice
          *
-         * return the map widget at the given index
+         * return the map widget at the given index if there are more than one
+         * map elements specified in the AppDef
          *
          * Parameter: {String} indice
          *
@@ -710,7 +791,7 @@
          *
          * Returns: {Object} a map object or null if not found.
          */
-        getMapByIndice : function(indice) {
+        getMapByIndice: function(indice) {
             var map = null;
             if (this.applicationDefinition) {
                 map = this.applicationDefinition.getMapByIndice(indice);
@@ -765,6 +846,13 @@
             return widgets;
         },
     
+        /**
+         * Function getSearchDefinitions
+         *
+         * returns the SearchDefinition objects as defined in the AppDef.
+         *
+         * Returns: {Array} an array of searchDefinitions, which may be empty
+         */
         getSearchDefinitions: function() {
             if (this.applicationDefinition) {
                 return this.applicationDefinition.searchDefinitions;
@@ -773,6 +861,13 @@
             }
         },
     
+        /**
+         * Function getSearchCategories
+         *
+         * returns the SearchCategory objects as defined in the AppDef.
+         *
+         * Returns: {Array} an array of searchCategories, which may be empty
+         */
         getSearchCategories: function() {
             if (this.applicationDefinition) {
                 return this.applicationDefinition.searchCategories;
@@ -781,12 +876,21 @@
             }
         },
     
+        /**
+         * Function getApplicationDefinitionURL
+         *
+         * returns the URL of the Application Definition
+         *
+         * Returns: {String} a URL
+         */
         getApplicationDefinitionURL: function() { return this.applicationDefinitionURL; },
 
-      /**
+        /**
          * Function: getApplicationURL
          *
          * returns the applicaiton's absolute URL minus the filename.html part
+         *
+         * Returns: {String} a URL
          */
         getApplicationURL: function() { 
           var path = window.location.pathname;
@@ -797,8 +901,26 @@
           return window.location.protocol + "//" + window.location.host + path;
         },
     
+        /**
+         * Function: getFusionURL
+         *
+         * returns the application's absolute URL minus the filename.html part
+         *
+         * Returns: {String} a URL
+         */
         getFusionURL: function() {return this.fusionURL;},
     
+        /**
+         * Function: getConfigurationItem
+         *
+         * returns individual elements out of the Fusion config.json file
+         *
+         * Parameter: {String} arch - the server architecture (mapguide or mapserver)
+         *
+         * Parameter: {String} key - the config item to be returned
+         *
+         * Returns: {String} a the value for the key of null if not found
+         */
         getConfigurationItem: function(arch, key) { 
             if (this.configuration[arch] && (this.configuration[arch][key]!='undefined')) { 
                 return this.configuration[arch][key]; 
@@ -806,16 +928,73 @@
             return null; 
         },
     
+        /**
+         * Function: getScriptLanguage
+         *
+         * Accessor to return the server-side script language
+         *
+         * Returns: {String} the script language e.g. 'php'
+         */
         getScriptLanguage: function() { return this.configuration.general.scriptLanguage; },
     
+        /**
+         * Function: getRedirectScript
+         *
+         * Accessor to return the URL of the redirect script
+         *
+         * Returns: {String} a URL
+         */
         getRedirectScript: function() { return this.sRedirectScript; },
     
+        /**
+         * Function: getBroker
+         *
+         * Accessor to return the broker object (for MapGuide only).  The broker
+         * is used to prepare various queries to the MapGuide server.
+         *
+         * Returns: {Object} the broker object
+         */
         getBroker: function() { return this.oBroker; },
     
+        /**
+         * Function: require
+         *
+         * Marks a JavaScript file as required which puts it into the queue for
+         * loading during Fusion initialization.  Widget code is included
+         * through this mecahnism
+         *
+         * Parameter: {String} url - the URL of the JS file to be loaded
+         *
+         * Returns: none
+         */
         require: function(url) { this.queueScript(url); },
     
+        /**
+         * Function: reportError
+         *
+         * Triggers the Fusion.Event.FUSION_ERROR and passes along the error
+         * object to the callback functions registered for this event.  Widgets
+         * call Fusion.reportError(o) to inform the system of errors.
+         * Applications will typically register an event listener for the error
+         * event and do something to report the error to the user.  
+         * By default, errors are not reported since there is no listener
+         *
+         * Parameter: {Object} o - the error object which is typically a string
+         *
+         * Returns: none
+         */
         reportError: function(o) { this.triggerEvent(Fusion.Event.FUSION_ERROR, o); },
     
+        /**
+         * Function: unitFromName
+         *
+         * returns index into the units array for the given unit name or 
+         * abbreviation
+         *
+         * Parameter: {String} unit - the units name to look up
+         *
+         * Returns: {Integer} index into the units array
+         */
         unitFromName: function(unit) {
             switch(unit.toLowerCase()) {
                 case 'unknown':
@@ -874,6 +1053,16 @@
             }
         },
         
+        /**
+         * Function: unitFromName
+         *
+         * Given a unit, this method returns if the units system is one of:
+         * imperial, metric, degrees or device units
+         *
+         * Parameter: {Integer} unit - the units array index
+         *
+         * Returns: {String} the units system
+         */
         unitSystem: function(unit) {
             switch(unit) {
 
@@ -899,12 +1088,31 @@
             }
         },
     
+        /**
+         * Function: unitName
+         *
+         * Given a unit, this method returns the units name
+         *
+         * Parameter: {Integer} unit - the units array index
+         *
+         * Returns: {String} the units name
+         */
         unitName: function(unit) {
             if (unit >= Fusion.UNKNOWN && unit <= Fusion.PIXELS) {
               return (Fusion.aUnitNames[unit]);
             }
             return 'Unknown';
         },
+        
+        /**
+         * Function: unitAbbr
+         *
+         * Given a unit, this method returns the units abbreviation
+         *
+         * Parameter: {Integer} unit - the units array index
+         *
+         * Returns: {String} the units abbreviation
+         */
         unitAbbr: function(unit) {
             if (unit >= Fusion.UNKNOWN && unit <= Fusion.PIXELS) {
               return (Fusion.aUnitAbbr[unit]);
@@ -912,6 +1120,17 @@
             return 'Unk';
         },
 
+        /**
+         * Function: toMeter
+         *
+         * Converts a length value from native units into meters.  This is the
+         * identity transform if the input units are meters
+         *
+         * Parameter: {Integer} unit - the units array index
+         * Parameter: {Float} value - the value to be converted
+         *
+         * Returns: {Float} the value in meters
+         */
         toMeter: function(unit, value) {
             if (unit == Fusion.UNKNOWN) {
                 return value;
@@ -921,6 +1140,18 @@
             }
             return false;
         },
+
+        /**
+         * Function: fromMeter
+         *
+         * Converts a length value from meters into native units.  This is the
+         * identity transform if the native units are meters
+         *
+         * Parameter: {Integer} unit - the units array index
+         * Parameter: {Float} value - the value to be converted
+         *
+         * Returns: {Float} the value in native units
+         */
         fromMeter: function(unit, value) {
             if (unit == Fusion.UNKNOWN) {
                 return value;
@@ -930,6 +1161,18 @@
             }
             return false;
         },
+
+        /**
+         * Function: convert
+         *
+         * Converts a length value from one unit system into another.
+         *
+         * Parameter: {Integer} unitsIn - the units array index of the input
+         * Parameter: {Integer} unitsOut - the units array index of the output
+         * Parameter: {Float} value - the value to be converted
+         *
+         * Returns: {Float} the value in output units
+         */
         convert: function(unitsIn, unitsOut, value) {
             if (unitsIn >= Fusion.UNKNOWN && unitsIn < Fusion.PIXELS && 
                 unitsOut >= Fusion.UNKNOWN && unitsOut < Fusion.PIXELS) {
@@ -939,11 +1182,15 @@
         },
     
       /**
-         * initializes the meters per unit values when a new map is loaded.  Some systems make different 
-         * assumptions for the conversion of degrees to meters so this makes sure both Fusion and
-         * OpenLayers are using the same value.
+         * Function: initUnits
          *
-         * @param metersPerUnit the value returned by LoadMap.php for meters per unit
+         * initializes the meters per unit values when a new map is loaded.  
+         * Some systems make different assumptions for the conversion of degrees
+         * to meters so this makes sure both Fusion and OpenLayers are using 
+         * the same value.
+         *
+         * Parameter: {Float} metersPerUnit - the value returned by LoadMap.php
+         *                                    for meters per unit
          */
         initUnits: function(metersPerUnit) {
             var eps = 1000;
@@ -962,11 +1209,13 @@
             }
         },
     
-      /**
-         * find the OpenLayers units identifier given the Fusion metersPerUnit value
-         *
-         * @param metersPerUnit the value returned by LoadMap.php for meters per unit
-         */
+        /**
+        * Function: getClosestUnits
+        *
+        * find the OpenLayers units identifier given the Fusion metersPerUnit value
+        *
+        * @param metersPerUnit the value returned by LoadMap.php for meters per unit
+        */
         getClosestUnits: function(metersPerUnit) {
             var units = "degrees";
             var minDiff = 100000000;
@@ -981,6 +1230,16 @@
             return units;
         },
 
+        /**
+         * Function: addWidgetStyleSheet
+         *
+         * Dynamically load a CSS stylesheet.  The url will be prepended with
+         * the Fusion URL.
+         *
+         * Parameter: {String} url - the URL of the CSS file to be loaded
+         *
+         * Returns: none
+         */
         addWidgetStyleSheet: function(url) {
             var lnk = document.createElement('link');
             var hd = document.getElementsByTagName('HEAD')[0];
@@ -990,6 +1249,15 @@
             lnk.href = Fusion.getFusionURL()+url;
         },
 
+        /**
+         * Function: parseQueryString
+         *
+         * An initialization time function to parse the application URL parameters
+         * and stores them in an array.  They can be retrieved using 
+         * Fusion.getQueryParam(key).
+         *
+         * Returns: {Array} an array of the query params from when the page was loaded
+         */
         parseQueryString: function() {
             this.queryParams = [];
             var s=window.location.search;
@@ -1004,6 +1272,15 @@
             return this.queryParams;
         },
 
+        /**
+         * Function: getQueryParam
+         *
+         * Returns the query parameter value for a given parameter name
+         *
+         * Parameter: {String} p - the parameter to lookup
+         *
+         * Returns: parameter value or the empty string '' if not found
+         */
         getQueryParam: function(p) {
             if (!this.queryParams) {
                 this.parseQueryString();
@@ -1024,7 +1301,7 @@
 
         /**
          * Function: _getScriptLocation
-         * Return the path to this script.
+         * Return the path to this script for bootstrapping Fusion.
          *
          * Returns:
          * {String} Path to this script
@@ -1069,10 +1346,12 @@
     var locale = navigator.language ?
                   navigator.language.substring(0,2):    //e.g. en-CA becomes just en                  
                   navigator.userLanguage.substring(0,2);//only use the prefix part for now, 
-    var s = window.location.search.toLowerCase();
+    var s = window.location.search;
     var idx = s.indexOf('locale=');
     if (idx>0) {
-      locale = s.substring(idx+7,idx+9);
+      var temp = s.substring(idx+7);
+      var idx2 = temp.indexOf('&');
+      locale = temp.substring(0,idx2<0?temp.length:idx2);
     }
     window._FusionLocale = locale;
     
@@ -1088,10 +1367,10 @@
                             'lib/Map.js',
                             'layers/Layers.js',
                             'lib/Search.js',
-                            'text/en/strings.json'];
+                            'text/en.json'];
         if (locale != 'en') {
             coreScripts.push('lib/OpenLayers/Lang/'+locale+'.js');
-            coreScripts.push('text/'+locale+'/strings.json');
+            coreScripts.push('text/'+locale+'.json');
         }
         
         var agent = navigator.userAgent;
@@ -1147,7 +1426,7 @@
     
         var fusionURL = r + Fusion.getFusionURL() + configUrl; 
     
-        var xhr = new XMLHttpRequest(); 
+        var xhr = getXmlHttpRequest(); 
         xhr.open("GET", fusionURL, false); 
         xhr.send(null); 
     
@@ -1174,7 +1453,7 @@
         } 
         Fusion.configuration.mapguide.mapAgentUrl = s + 'mapagent/mapagent.fcgi'; 
         return Fusion.configuration.mapguide.mapAgentUrl; 
-    } 
+    }
     
     var addElement = function(element) { 
         if (!element) { 
@@ -1188,16 +1467,46 @@
         } 
     
         document.writeln('<script src="' + src + '"><\/script>'); 
-    } 
+    }
 
+    var getXmlHttpRequest = function(){	
+        try { return new XMLHttpRequest(); }
+        catch (e) { try { return new ActiveXObject('Msxml2.XMLHTTP'); } 
+        catch (e) { try { return new ActiveXObject('Microsoft.XMLHTTP'); }
+        catch (e) { return  null; }}}
+    }
+
+    /**
+     * Function: createSessionId
+     *
+     * Pre-create a session to avoid the 401 Unauthorized dialog
+     *
+     */
+    var createSessionId = function(){
+        var xhr = getXmlHttpRequest();
+        xhr.open("GET", Fusion.fusionURL+"layers/MapGuide/php/CreateSession.php",false);
+        xhr.send(null); 
+        var o;
+        eval('o='+xhr.responseText);
+        Fusion.sessionId = o.sessionId;
+    }
+
     var appDefUrl = Fusion.getQueryParam('ApplicationDefinition'); 
-    if(appDefUrl){
-        var xhr = new XMLHttpRequest(); 
+    if(appDefUrl && (
+        appDefUrl.indexOf('Library') == 0 ||
+        appDefUrl.indexOf('Session') == 0)){
+        var passedSessionId = Fusion.getQueryParam('Session'); 
+        if(passedSessionId == null || passedSessionId == "" ){
+            createSessionId();
+        }else{
+            Fusion.sessionId = passedSessionId;
+        }
+        var xhr = new getXmlHttpRequest(); 
         var mapAgentUrl = getAgentUrl(); 
-        xhr.open("GET", mapAgentUrl + "?OPERATION=GETRESOURCECONTENT&VERSION=1.0.0&LOCALE=en&CLIENTAGENT=MapGuide+Developer&RESOURCEID=" + appDefUrl + "&FORMAT=text%2Fxml", false); 
+        xhr.open("GET", mapAgentUrl + "?OPERATION=GETRESOURCECONTENT&VERSION=1.0.0&LOCALE=en&CLIENTAGENT=MapGuide+Developer&RESOURCEID=" + appDefUrl + "&FORMAT=text%2Fxml&SESSION="+ Fusion.sessionId, false); 
         xhr.send(null); 
         var appDefXML = xhr.responseXML.documentElement; 
-        
+
         if(appDefXML){
             var googleElement = appDefXML.getElementsByTagName("GoogleScript")[0]; 
             var yahooElement = appDefXML.getElementsByTagName("YahooScript")[0]; 
@@ -1208,5 +1517,6 @@
             addElement(veElement);
         }
     }
+    
 })();
 

Modified: branches/fusion-2.0/lib/jxlib.uncompressed.js
===================================================================
--- branches/fusion-2.0/lib/jxlib.uncompressed.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/lib/jxlib.uncompressed.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -4920,7 +4920,7 @@
 
 (function(){
   
-var special = ['À','à','Á','á','Â','â','Ã','ã','Ä','ä','Å','å','Ă','ă','Ą','ą','Ć','ć','Č','č','Ç','ç', 'Ď','ď','Đ','đ', 'È','è','É','é','Ê','ê','Ë','ë','Ě','ě','Ę','ę', 'Ğ','ğ','Ì','ì','Í','í','Î','î','Ï','ï', 'Ĺ','ĺ','Ľ','ľ','Ł','ł', 'Ñ','ñ','Ň','ň','Ń','ń','Ò','ò','Ó','ó','Ô','ô','Õ','õ','Ö','ö','Ø','ø','ő','Ř','ř','Ŕ','ŕ','Š','š','Ş','ş','Ś','ś', 'Ť','ť','Ť','ť','Ţ','ţ','Ù','ù','Ú','ú','Û','û','Ü','ü','Ů','ů', 'Ÿ','ÿ','ý','Ý','Ž','ž','Ź','ź','Ż','ż', 'Þ','þ','Ð','ð','ß','Œ','œ','Æ','æ','µ'];
+var special = ['À','à','�','á','Â','â','Ã','ã','Ä','ä','Å','å','Ă','ă','Ą','ą','Ć','ć','Č','�','Ç','ç', 'Ď','�','�','đ', 'È','è','É','é','Ê','ê','Ë','ë','Ě','ě','Ę','ę', 'Ğ','ğ','Ì','ì','�','í','Î','î','�','ï', 'Ĺ','ĺ','Ľ','ľ','�','ł', 'Ñ','ñ','Ň','ň','Ń','ń','Ò','ò','Ó','ó','�','ô','Õ','õ','Ö','ö','Ø','ø','ő','Ř','ř','�','ŕ','Š','š','Ş','ş','Ś','ś', 'Ť','ť','Ť','ť','Ţ','ţ','Ù','ù','Ú','ú','Û','û','Ü','ü','Ů','ů', 'Ÿ','ÿ','ý','�','Ž','ž','Ź','ź','Ż','ż', 'Þ','þ','�','ð','ß','Œ','œ','Æ','æ','µ'];
 
 var standard = ['A','a','A','a','A','a','A','a','Ae','ae','A','a','A','a','A','a','C','c','C','c','C','c','D','d','D','d', 'E','e','E','e','E','e','E','e','E','e','E','e','G','g','I','i','I','i','I','i','I','i','L','l','L','l','L','l', 'N','n','N','n','N','n', 'O','o','O','o','O','o','O','o','Oe','oe','O','o','o', 'R','r','R','r', 'S','s','S','s','S','s','T','t','T','t','T','t', 'U','u','U','u','U','u','Ue','ue','U','u','Y','y','Y','y','Z','z','Z','z','Z','z','TH','th','DH','dh','ss','OE','oe','AE','ae','u'];
 
@@ -4980,7 +4980,7 @@
 		MIT-style license.
 
 	Authors:
-		Sebastian Markbåge, Aaron Newton, Lennart Pilon, Valerio Proietti
+		Sebastian Markbåge, Aaron Newton, Lennart Pilon, Valerio Proietti
 */
 String.implement({
 
@@ -5021,7 +5021,7 @@
 		MIT-style license.
 
 	Authors:
-		Sebastian Markbåge, Aaron Newton
+		Sebastian Markbåge, Aaron Newton
 */
 
 var URI = new Class({
@@ -5167,7 +5167,7 @@
 		MIT-style license.
 
 	Authors:
-		Sebastian Markbåge
+		Sebastian Markbåge
 */
 
 URI = Class.refactor(URI, {
@@ -10239,33 +10239,39 @@
         /* get the chrome image from the background image of the element */
         /* the app: protocol check is for adobe air support */
         var src = c.getStyle('backgroundImage');
-        if (!(src.contains('http://') || src.contains('https://') || src.contains('file://') || src.contains('app:/'))) {
-            src = null;
-        } else {
-            src = src.slice(4,-1);
-            /* this only seems to be IE and Opera, but they add quotes
-             * around the url - yuck
-             */
-            if (src.charAt(0) == '"') {
-                src = src.slice(1,-1);
-            }
+        if(src != null)
+        { 
+        	if (!(src.contains('http://') || src.contains('https://') || src.contains('file://') || src.contains('app:/'))) 
+            {
+                src = null;
+            } 
+            else 
+            {
+                src = src.slice(4,-1);
+                /* this only seems to be IE and Opera, but they add quotes
+                 * around the url - yuck
+                 */
+                if (src.charAt(0) == '"') {
+                    src = src.slice(1,-1);
+                }
 
-            /* and remove the background image */
-            c.setStyle('backgroundImage', 'none');
+                /* and remove the background image */
+                c.setStyle('backgroundImage', 'none');
 
-            /* make chrome */
-            ['TR','TL','BL','BR'].each(function(s){
-                c.adopt(
-                    new Element('div',{
-                        'class':'jxChrome'+s
-                    }).adopt(
-                    new Element('img',{
-                        'class':'png24',
-                        src:src,
-                        alt: '',
-                        title: ''
-                    })));
-            }, this);
+                /* make chrome */
+                ['TR','TL','BL','BR'].each(function(s){
+                    c.adopt(
+                        new Element('div',{
+                            'class':'jxChrome'+s
+                        }).adopt(
+                        new Element('img',{
+                            'class':'png24',
+                            src:src,
+                            alt: '',
+                            title: ''
+                        })));
+                }, this);
+            }
         }
         if (!window.opera) {
             c.adopt(Jx.createIframeShim());
@@ -10579,6 +10585,7 @@
         
         if (typeof Drag != 'undefined') {
             new Drag(a, {
+                modifiers: {x: null, y: null},
                 onStart: function() {this.stop();}
             });
         }
@@ -17283,7 +17290,12 @@
             this.scrollLeft.domObj.addClass('jxBarScrollLeft');
             this.scrollLeft.addEvents({
                click: (function(){
-                   var from = this.scroller.getStyle('left').toInt();
+                   var from = 0;
+                   var leftStyle = this.scroller.getStyle('left');
+                   if(leftStyle)
+                   {
+                       from = leftStyle.toInt();
+                   }
                    if (isNaN(from)) { from = 0; }
                    var to = Math.min(from+100, 0);
                    if (to >= 0) {
@@ -17303,8 +17315,13 @@
             }).addTo(this.domObj);
             this.scrollRight.domObj.addClass('jxBarScrollRight');
             this.scrollRight.addEvents({
-               click: (function(){
-                   var from = this.scroller.getStyle('left').toInt();
+                click: (function(){
+                   var from = 0;
+                   var leftStyle = this.scroller.getStyle('left');
+                   if(leftStyle)
+                   {
+                       from = leftStyle.toInt();
+                   }
                    if (isNaN(from)) { from = 0; }
                    var to = Math.max(from - 100, this.scrollWidth);
                    if (to == this.scrollWidth) {
@@ -17363,7 +17380,12 @@
         }, this);
         if (this.scrollWidth < 0) {
             /* we need to show scrollers on at least one side */
-            var l = this.scroller.getStyle('left').toInt();
+            var l = 0;
+            var leftStyle = this.scroller.getStyle('left');
+            if(leftStyle)
+            {
+                l = leftStyle.toInt();
+            }
             if (l < 0) {
                 this.scrollLeft.domObj.setStyle('visibility','');
             } else {
@@ -17388,7 +17410,12 @@
              */
             this.scrollLeft.domObj.setStyle('visibility','hidden');
             this.scrollRight.domObj.setStyle('visibility','hidden');
-            var from = this.scroller.getStyle('left').toInt();
+            var from = 0;
+            var leftStyle = this.scroller.getStyle('left');
+            if(leftStyle)
+            {
+               from = leftStyle.toInt();
+            }            
             if (!isNaN(from) && from !== 0) {
                 if ($defined(this.scrollFx)) {
                     this.scrollFx.start('left', 0);
@@ -17465,7 +17492,12 @@
         //the component was first created.
         
         //So, get the left value first
-        var l = this.scroller.getStyle('left');
+        var l = 0;
+        var leftStyle = this.scroller.getStyle('left');
+        if(leftStyle)
+        {
+            l = leftStyle.toInt();
+        }
         //then check to see if it's auto or a zero length string 
         if (l === 'auto' || l.length <= 0) {
             //If so, set to 0.
@@ -18293,3 +18325,4 @@
     }
 });
 
+

Modified: branches/fusion-2.0/templates/mapguide/standard/ApplicationDefinition.xml
===================================================================
--- branches/fusion-2.0/templates/mapguide/standard/ApplicationDefinition.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapguide/standard/ApplicationDefinition.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -64,6 +64,8 @@
         <Type>MapGuide</Type>
         <SingleTile>false</SingleTile>
         <Extension>
+          <ProjectionCode>EPSG:42304</ProjectionCode>
+          <ProjectionDef>+title=LCC +proj=lcc +lat_1=49 +lat_2=77 +lat_0=49 +lon_0=-95 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs</ProjectionDef>
           <ResourceId>Library://Samples/Gmap/Maps/gmapTiled.MapDefinition</ResourceId>
         </Extension>
       </Map>
@@ -74,6 +76,8 @@
         <SingleTile>false</SingleTile>
         <Extension>
           <ResourceId>Library://Samples/Gmap/Maps/gmap.MapDefinition</ResourceId>
+          <ProjectionCode>EPSG:42304</ProjectionCode>
+          <ProjectionDef>+title=LCC +proj=lcc +lat_1=49 +lat_2=77 +lat_0=49 +lon_0=-95 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs</ProjectionDef>
         </Extension>
       </Map>
     </MapGroup>
@@ -139,7 +143,7 @@
       </Item>
       <Item xsi:type="WidgetItemType">
         <Function>Widget</Function>
-        <Widget>menuBuffer</Widget>
+        <Widget>toolbarBuffer</Widget>
       </Item>
     </Container>
 
@@ -688,7 +692,7 @@
     <Widget xsi:type="UiWidgetType">
       <Name>menuMeasure</Name>
       <Type>Measure</Type>
-      <StatusText>Measure distances on the map.</StatusText>
+      <StatusText>Measure distances and areas on the map.</StatusText>
       <Extension xsi:type="CustomContentType">
         <Type>both</Type>
         <MeasureTooltipContainer>MeasureResult</MeasureTooltipContainer>
@@ -745,7 +749,7 @@
     <Widget xsi:type="UiWidgetType">
       <Name>toolbarMeasure</Name>
       <Type>Measure</Type>
-      <StatusText>Measure distances on the map.</StatusText>
+      <StatusText>Measure distances and areas on the map.</StatusText>
       <Extension xsi:type="CustomContentType">
         <Type>both</Type>
         <MeasureTooltipContainer>MeasureResult</MeasureTooltipContainer>
@@ -1114,7 +1118,7 @@
       <Type>MapMenu</Type>
       <StatusText/>
       <Extension>
-        <Folder>Library://Samples/Sheboygan/</Folder>
+        <!--Folder>Library://Samples/Sheboygan/</Folder-->
       </Extension>
       <ImageUrl/>
       <ImageClass/>
@@ -1131,6 +1135,7 @@
       <Type>OverviewMap</Type>
       <Description/>
       <Extension xsi:type="CustomContentType">
+        <MapId>sheboygan</MapId>
       </Extension>
     </Widget>
     

Modified: branches/fusion-2.0/templates/mapguide/standard/index.html
===================================================================
--- branches/fusion-2.0/templates/mapguide/standard/index.html	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapguide/standard/index.html	2010-03-24 18:31:34 UTC (rev 2105)
@@ -94,27 +94,18 @@
 
 <div id="thePage" style="visibility: hidden">
 
-<div id="PanelPane">
-    <div id="Legend"></div>
-    <div id="SelectionPanel"></div>
-    <div id="OverviewMap"></div>
-</div>
-<div id="Map"><div id="Navigator"></div></div>
-<div id="Statusbar"></div>
-<div id="Statusbar"></div>
-<div id="MapTip"></div>
-<div id="TaskPane"></div>
-<div id="PoweredBy" class="statusBarItem">
-<a href="http://mapserver.gis.umn.edu.org/" target="_blank">
-  <img src="images/PoweredBy_MapServer.gif" width="137" height="18" border="0">
-</a>
-</div>
+  <div id="PanelPane">
+      <div id="Legend"></div>
+      <div id="SelectionPanel"></div>
+      <div id="OverviewMap"></div>
+  </div>
+  <div id="Map"><div id="Navigator"></div></div>
+  <div id="Statusbar"></div>
+  <div id="Statusbar"></div>
+  <div id="MapTip"></div>
+  <div id="TaskPane"></div>
 
 </div>
 
-<div id="BusyIndicator" style="visibility: hidden;">
-  <img src="images/icon_loading.gif" width="30" height="14">
-</div>
-
 </body>
 </html>

Modified: branches/fusion-2.0/templates/mapguide/standard/themes/crispin/jxtheme.uncompressed.css
===================================================================
--- branches/fusion-2.0/templates/mapguide/standard/themes/crispin/jxtheme.uncompressed.css	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapguide/standard/themes/crispin/jxtheme.uncompressed.css	2010-03-24 18:31:34 UTC (rev 2105)
@@ -2292,7 +2292,7 @@
 .jxBarBottom .jxBarScroller {
   position: absolute;
   /* much bigger than its container */
-  width: 10000%;
+  width: 1000%;
   overflow: hidden;
 }
 

Modified: branches/fusion-2.0/templates/mapguide/standard/themes/delicious/jxtheme.uncompressed.css
===================================================================
--- branches/fusion-2.0/templates/mapguide/standard/themes/delicious/jxtheme.uncompressed.css	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapguide/standard/themes/delicious/jxtheme.uncompressed.css	2010-03-24 18:31:34 UTC (rev 2105)
@@ -2293,7 +2293,7 @@
 .jxBarBottom .jxBarScroller {
   position: absolute;
   /* much bigger than its container */
-  width: 10000%;
+  width: 1000%;
   overflow: hidden;
 }
 

Modified: branches/fusion-2.0/templates/mapserver/standard/ApplicationDefinition.xml
===================================================================
--- branches/fusion-2.0/templates/mapserver/standard/ApplicationDefinition.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapserver/standard/ApplicationDefinition.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -674,7 +674,7 @@
     <Widget xsi:type="UiWidgetType">
       <Name>menuMeasure</Name>
       <Type>Measure</Type>
-      <StatusText>Measure distances on the map.</StatusText>
+      <StatusText>Measure distances and areas on the map.</StatusText>
       <Extension xsi:type="CustomContentType">
         <Type>distance</Type>
         <MeasureTooltipContainer>MeasureResult</MeasureTooltipContainer>
@@ -749,7 +749,7 @@
     <Widget xsi:type="UiWidgetType">
       <Name>toolbarMeasure</Name>
       <Type>Measure</Type>
-      <StatusText>Measure distances on the map.</StatusText>
+      <StatusText>Measure distances and areas on the map.</StatusText>
       <Extension xsi:type="CustomContentType">
         <Type>both</Type>
         <MeasureTooltipContainer>MeasureResult</MeasureTooltipContainer>

Modified: branches/fusion-2.0/templates/mapserver/standard/themes/crispin/jxtheme.uncompressed.css
===================================================================
--- branches/fusion-2.0/templates/mapserver/standard/themes/crispin/jxtheme.uncompressed.css	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapserver/standard/themes/crispin/jxtheme.uncompressed.css	2010-03-24 18:31:34 UTC (rev 2105)
@@ -2292,7 +2292,7 @@
 .jxBarBottom .jxBarScroller {
   position: absolute;
   /* much bigger than its container */
-  width: 10000%;
+  width: 1000%;
   overflow: hidden;
 }
 

Modified: branches/fusion-2.0/templates/mapserver/standard/themes/delicious/jxtheme.uncompressed.css
===================================================================
--- branches/fusion-2.0/templates/mapserver/standard/themes/delicious/jxtheme.uncompressed.css	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/templates/mapserver/standard/themes/delicious/jxtheme.uncompressed.css	2010-03-24 18:31:34 UTC (rev 2105)
@@ -2293,7 +2293,7 @@
 .jxBarBottom .jxBarScroller {
   position: absolute;
   /* much bigger than its container */
-  width: 10000%;
+  width: 1000%;
   overflow: hidden;
 }
 

Added: branches/fusion-2.0/text/en
===================================================================
--- branches/fusion-2.0/text/en	                        (rev 0)
+++ branches/fusion-2.0/text/en	2010-03-24 18:31:34 UTC (rev 2105)
@@ -0,0 +1,334 @@
+# Web surround localized strings
+# English language
+#
+# Important: This file must be saved with UTF-8 encoding
+#
+
+# General
+
+# Fonts - the 6 following entries are mandatory
+ at fontWindows        = Arial
+ at fontsizeWindows    = 8pt
+ at fontLinux          = Arial
+ at fontsizeLinux      = 8pt
+ at fontMacintosh      = Arial
+ at fontsizeMacintosh  = 8pt
+
+# Distances
+DISTANCEMILES       = Miles
+DISTANCEKILOMETERS  = Kilometers
+DISTANCEFEET        = Feet
+DISTANCEMETERS      = Meters
+
+# Fill Patterns/Values
+FILLSOLID           = Solid
+FILLNET             = Net
+FILLLINE            = Line
+FILLLINE45          = Line_45
+FILLLINE90          = Line_90
+FILLLINE135         = Line_135
+FILLSQUARE          = Square
+FILLBOX             = Box
+FILLCROSS           = Cross
+FILLDASH            = Dash
+FILLDOLMIT          = Dolmit
+FILLHEX             = Hex
+FILLSACNCR          = Sacncr
+FILLSTEEL           = Steel
+
+# Transparency
+TRANSPARENT         = transparent
+
+# Line Styles/Values
+LINESOLID           = Solid
+LINEDASH            = Dash
+LINEDOT             = Dot
+LINEDASHDOT         = DashDot
+LINEDASHDOTDOT      = DashDotDot
+LINERAIL            = Rail
+LINEBORDER          = Border
+LINEDIVIDE          = Divide
+LINEFENCELINE       = FenceLine
+
+# Buttons
+BUTTONOK            = OK
+BUTTONDONE          = Done
+BUTTONCANCEL        = Cancel
+BUTTONREFRESH       = Refresh
+BUTTONCLOSE         = Close
+BUTTONCLEAR         = Clear
+BUTTONSAVE          = Save
+
+# Colors
+COLORRED            = Red
+COLORGREEN          = Green
+COLORBLUE           = Blue
+
+# BufferReport
+BUFFERREPORTTITLE               = Create Buffer
+BUFFERREPORTCREATED             = %s has been created.
+BUFFERREPORTUPDATED             = %s has been updated.
+BUFFERREPORTFEATURESSINGULAR    = %s buffer feature was created.
+BUFFERREPORTFEATURESPLURAL      = %s buffer features were created.
+BUFFERREPORTWARNINGSINGULAR     = <b>Warning:</b> %s layer was excluded from buffer computation because its coordinate system is incompatible with the coordinate system of the map, or because it has no coordinate system at all
+BUFFERREPORTWARNINGPLURAL       = <b>Warning:</b> %s layers were excluded from buffer computation because their coordinate systems are incompatible with the coordinate system of the map, or because they have no coordinate system at all
+BUFFERREPORTERRORTITLE          = Buffer Error
+
+# Buffer
+BUFFERCLASSDESCR                = Feature class for buffer layer
+BUFFERSCHEMADESCR               = Temporary buffer schema
+BUFFERDIFFARBXY                 = Cannot compute a unique buffer around features with different 'Arbitrary X-Y' coordinate systems. Please uncheck the option 'Merge buffer areas' or select only one layer
+
+# BufferUI
+BUFFERTITLE                     = Create a Buffer
+BUFFERSUBTITLE                  = &nbsp;Buffer settings
+BUFFERINFOTEXT                  = Select features on the image.
+BUFFERDISTANCE                  = Distance around features:
+BUFFERLAYERS                    = Layers to include in the buffer:
+BUFFERNOLAYER                   = <No layer selected>
+BUFFERNAME                      = Name for the resulting buffer layer:
+BUFFERNAMETEXT                  = Buffer 1
+BUFFERMERGE                     = Merge buffer areas
+BUFFERFILLSTYLE                 = &nbsp;Fill style
+BUFFERFILLPATTERN               = Fill pattern:
+BUFFERFOREGROUNDCOLOR           = Foreground color:
+BUFFERTRANSPARENCY              = Transparency:
+BUFFERBACKGROUNDCOLOR           = Background color:
+BUFFERBORDERSTYLE               = &nbsp;Border style
+BUFFERBORDERLINEPATTERN         = Line pattern:
+BUFFERBORDERLINECOLOR           = Line color:
+BUFFERBORDERLINETHICKNESS       = Line thickness:
+BUFFERHELP                      = <li><p align="left">Results of the buffer are put into a new layer above the top feature layer. This buffer layer has the name you enter here.</li><li><p align="left">To create multiple buffer layers, use different buffer names.</li><li><p align="left">To hide buffer layers, turn them off.</li><li><p align="left">Buffer layers are temporary and are removed when you close the viewer.</li>
+BUFFERERRORZERODISTANCE         = Please enter a nonzero distance.
+BUFFERERRORNOLAYERNAME          = Please enter a layer name.
+BUFFERERRORNEGATIVETHICKNESS    = Please enter positive or null thickness.
+BUFFERERRORNOSELECTION          = Please select feature(s) to calculate a buffer around.
+
+# ColorPicker
+COLORPICKERDLGTITLE             = Select a color
+COLORPICKERTITLE                = Color palette
+COLORPICKERSUBTITLE             = Specify a color
+COLORPICKER100TRANSPARENCY      = 100%% transparency
+COLORPICKERHEXFORMAT            = Hex format
+
+# MeasureUI
+MEASUREDISTANCETITLE    = Measure Distance
+MEASUREAREATITLE        = Measure Area
+MEASUREBOTHTITLE        = Measure Distance And Area
+MEASUREINFO             = Click a start and end point.
+RESUME                  = Resume
+STOP                    = Stop
+CLEAR                   = Clear
+MILES                   = Miles
+KILOMETERS              = Kilometers
+MEASUREHELP             = <li>To measure multiple distances, continue clicking new points.</li><li>To finish, click &quot;Stop&quot;.</li><li>You can pan or zoom and continue measuring by clicking &quot;Resume&quot;.</li><li>To start over, click &quot;Clear&quot;.</li>
+SEGMENT                 = Segment
+LENGTH                  = Length
+TOTALLENGTH             = Total Length
+TOTALAREA               = Total Area
+MEASUREERROR            = Measure Error
+
+# Measure
+MEASUREFEATURECLASS     = Feature class for measure layer
+MEASURESCHEMADESCR      = Temporary measure schema
+MEASUREPARTIAL          = Partial
+MEASURETOTAL            = total
+MEASURELAYER            = Measure
+
+# FeatureInfoUI
+FEATUREINFOTITLE        = Feature Information
+FEATUREINFOSUBTITLE     = Select a Layer
+FEATUREINFOLAYER        = Layer:
+FEATUREINFOSELECTFEATURE= Select Features:
+FEATUREINFODIGITIZE     = Digitize:
+FEATUREINFOPOINT        = Point
+FEATUREINFORECTANGLE    = Rectangle
+FEATUREINFOPOLYGON      = Polygon
+FEATUREINFOTOTAL        = Total:
+FEATUREINFONOSELECTED   = no features selected.
+FEATUREINFOERROR        = Error
+FEATUREINFOFETCHINFO    = fetching feature info ...
+FEATUREINFOFEATURESEL   = features selected
+FEATUREINFOAREA         = Area: 
+FEATUREINFOAREAUNDEFINE = areaIdx undefined
+FEATUREINFONOINFO       = no layer info
+FEATUREINFONOFEATUREIN  = no features in selected layer.
+
+# QueryUI
+QUERYTITLE              = Query Features
+QUERYSELECTLAYER        = Select a Layer
+QUERYLAYER              = Layer:
+QUERYPROPERTYFILTER     = Property Filter
+QUERYPROPERTY           = Property:
+QUERYOPERATOR           = Operator:
+QUERYVALUE              = Value:
+QUERYSPATIALFILTER      = Spatial Filter
+QUERYDIGITIZE           = Digitize:
+QUERYRECTANGLE          = Rectangle
+QUERYPOLYGON            = Polygon
+QUERYCLEAR              = Clear
+QUERYOUTPUT             = Output
+QUERYOUTPUTPROPERTY     = Output property:
+QUERYEXECUTE            = Execute
+QUERYMAXRESULT          = Max results:
+QUERYRESULTS            = Results
+QUERYSCALE              = Scale:
+QUERYZOOM               = Zoom
+QUERYSELECT             = Select
+QUERYERROR              = Error
+QUERYEQUALTO            = Equal to
+QUERYNOTEQUALTO         = Not equal to
+QUERYGREATTHAN          = Greater than
+QUERYGREATTHANEQUAL     = Greater than or equal to
+QUERYLESSTHAN           = Less than
+QUERYLESSTHANEQUAL      = Less than or equal to
+QUERYBEGIN              = Begins with
+QUERYCONTAINS           = Contains
+
+# Theme UI
+THEMETITLE              = Theme Layer
+THEMESELECTLAYER        = Select a Layer
+THEMELAYER              = Layer:
+THEMENAME               = Theme Name:
+THEMECONDITIONS         = Define Conditions
+THEMEPROPERTY           = Property:
+THEMEMIN                = Min:
+THEMEMAX                = Max:
+THEMEDISTRIBUTION       = Distribution:
+THEMERULE               = # of Rules:
+THEMESCALERANGE         = Scale Range
+THEMESTYLERAMP          = Style Ramp
+THEMEFILLTRANS          = Fill Transparency:
+THEMEFILLCOLOR          = Fill Color:
+THEMEFROM               = From:
+THEMETO                 = To:
+THEMEBORDERCOLOR        = Border Color:
+THEMEAPPLY              = Apply
+THEMEERROR              = Error
+THEMEINDIVIDUAL         = Individual
+THEMEEQUAL              = Equal
+THEMESTANDARD           = Standard Deviation
+THEMEQUANTILE           = Quantile
+THEMEJENKS              = Jenks (Natural Breaks)
+
+# Redline UI
+REDLINEOPTIONS          = Digitizing Options
+REDLINESELECTLAYER      = Select Layer: 
+REDLINENEW              = New
+REDLINERENAME           = Rename
+REDLINEREMOVE           = Remove
+REDLINEDRAW             = Draw:
+REDLINEPOINT            = Point
+REDLINELINE             = Line
+REDLINERECTANGLE        = Rectangle
+REDLINEPOLYGON          = Polygon
+REDLINESAVE             = Save
+REDLINEUPLOAD           = Upload
+REDLINEFEATURES         = Features
+
+# HtmlViewerAbout
+HTMLABOUTTITLE          = About %s
+HTMLABOUTTITLEBAR       = MapGuide Viewer
+HTMLABOUTSERVERTITLE    = MapGuide Server
+HTMLABOUTVIEWERTITLE    = MapGuide Viewer
+HTMLABOUTSERVERVERSION  = %s (Version %s)
+HTMLABOUTVIEWERVERSION  = %s (Version %s)
+HTMLABOUTTEXT           = <br>This product is made available subject to the terms of GNU Lesser General Public License Version 2.1 ("LGPL").  A copy of the LGPL, as well as additional copyright notices and license terms applicable to portions of this product are set forth in the <a href="../localized/license_en.htm" target="blank">license</a> file.<br><br>All trademarks and registered trademarks mentioned herein are the property of their respective owners.<br><br>Copyright &copy; 2007 Autodesk, Inc.<br><br>
+HTMLABOUTLICENSE        = license file
+HTMLABOUTLICENSEFILE    = license_en.htm
+
+# LegendUI
+LEGENDLISTSEPARATOR     = ,
+
+# PrintablePageUi
+PRINTTITLE              = Get Printable Page
+PRINTELEMENTS           = Select the elements to include in the print layout.
+PRINTPAGETITLE          = Page title:
+PRINTLEGEND             = Legend
+PRINTNORTHARROW         = North arrow
+PRINTCREATEPAGE         = Create Page
+
+# PropertyCtrl
+PROPERTIESNONE          = None Selected
+PROPERTIESNAME          = Name
+PROPERTIESVALUE         = Value
+PROPERTIESITEMSEL       = Items selected: {0}
+
+# Search
+SEARCHDLGTITLE          = Search features
+SEARCHTITLE             = Search results
+SEARCHERROR             = Search error
+SEARCHREPORT            = Search report
+SEARCHLAYERNOTFOUND     = Layer {0} not found!
+SEARCHNOMULTIPROP       = Multi-properties identity not supported yet
+SEARCHTYYPENOTSUP       = Identity property type not supported yet ({0})
+SEARCHNOMATCHES         = No matches.
+
+# SearchPrompt
+SEARCHPROMPTFIND        = Find
+
+# SelectWithinUi
+SELECTWITHINTITLE       = Select Within
+SELECTWITHINAREAS       = Select areas on the image.
+SELECTWITHINRESTRICTION = Restrict results to selected layers:
+SELECTWITHINTEXT        = <li>If you continue to select areas on the image, click &quot;Refresh&quot; to update the layer list.</li><li>To finish and select all features within the highlighted areas, click &quot;Done&quot;.</li><li>To start over, click &quot;Clear&quot;.</li>
+
+# Error/Report
+REPORTTITLE             = Report
+
+# Legend UI
+REFRESH                 = Refresh
+EXPANDALL               = Expand
+COLLAPSEALL             = Collapse All
+DISPLAYALLINGROUP       = Display All in Group
+HIDEALLINGROUP          = Hide All in Group
+SHOWLONGTHEME           = Show Long Theme
+
+# Task Bar
+TASKS                   = Tasks
+
+# Viewer Options
+OPTIONSTITLE            = Viewer Options
+OPTIONSINFOTEXT         = Select viewing options for status bar and tool tips.
+OPTIONSDISTANCE         = Display distances in
+OPTIONSMETRIC           = Metric (Kilometers, Meters)
+OPTIONSUSENGLISH        = US/English (Miles, Feet)
+OPTIONSPOSITION         = Display cursor position in
+OPTIONSLATLON           = Latitude, Longitude (Degrees)
+OPTIONSMAPUNITS         = Map Coordinate System (X,Y)
+
+# AJAX Viewer
+VIEWERLAYERS            = Layers
+VIEWERPROPS             = Properties
+VIEWERPANNORTH          = Pan North
+VIEWERPANWEST           = Pan West
+VIEWERPANSOUTH          = Pan South
+VIEWERPANEAST           = Pan East
+VIEWERZOOMIN            = Zoom In
+VIEWERZOOMOUT           = Zoom Out
+VIEWERMOVESLIDER        = Drag to move slider
+VIEWERDRAGZOOM          = Drag to zoom
+ENDSEL                  = CTRL + click to end
+ENDSELSAFARI            = SHIFT + click to end
+DECIMALSEPARATOR        = .
+THOUSANDSEPARATOR       = ,
+
+# Main Frame
+NEEDLOGIN               = You must enter a valid login ID and password to access this site
+ALREADYINMEASURE        = Only one measure command is allowed in a web layout
+ACCESSDENIED            = Access Denied   
+LATLONCURPOS            = Lat: {0}, Lon: {1}
+MAPUNITSCURPOS          = X: {0}, Y: {1}
+FEATURESSELECTED        = {0} features selected
+FEATURESELECTED         = {0} feature selected
+MI                      = mi
+FT                      = ft
+IN                      = in
+KM                      = km
+MT                      = m
+CM                      = cm
+DIGALREADYRUNNING       = Cannot execute measure: A digitization command is in progress.
+MEASALREADYRUNNING      = Cannot execute digitization: A measure is in progress.
+
+# Localized Icon Files
+POWEREDBYICON           = PoweredBy_en.gif

Added: branches/fusion-2.0/text/en.json
===================================================================
--- branches/fusion-2.0/text/en.json	                        (rev 0)
+++ branches/fusion-2.0/text/en.json	2010-03-24 18:31:34 UTC (rev 2105)
@@ -0,0 +1,63 @@
+Fusion.Strings.en = {
+'scriptFailed': 'failed to load script: ${script}',
+'configParseError': 'Error parsing fusion configuration file, initialization aborted',
+'configLoadError': 'Error loading fusion configuration file, initialization aborted.' +
+                  'Make sure that you have copied config_dist.json to config.json ' +
+                  'and have configured the settings for your system',
+'ajaxError': 'Exception occurred in AJAX callback.\nMessage: ${exception}\nLocation: ${filename} (${line})\nResponse: ${response}',
+'importFailed': 'failed to import stylesheet: ${url}',
+'serverNotAvailable': '<h2>Server not available. Try to reload the application. If this problem persists, please contact the administrator</h2>',
+'invalidXMLDocument': 'xml2json: invalid XML document: ${msg} : ${url}',
+'registerEventError': 'Error registering eventID, invalid (empty) eventID.',
+'appDefLoadFailed': 'failed to load: ${script}',
+'appDefParseError': 'failed to parse ApplicationDefinition',
+'widgetSetParseError': 'failed to parse the WidgetSet',
+'fusionError': 'Fusion Error: ${type}\n${message}',
+'nullExtents': 'Map.setExtents called with null extents',
+'mapLoadError': 'Failed to load requested map:\n${error}',
+'setLayersError': "setLayers failure: ${error}",
+'printTitle': 'Printable Page ',
+'noSelection': 'No Selection',
+'selectionInfo': '${features} feature(s) selected on ${layers} layer(s)',
+'attribute': 'Attribute',
+'value': 'Value',
+'taskHome': 'return to the task pane home',
+'prevTask': 'go to previous task executed',
+'nextTask': 'go to next task executed',
+'taskList': 'Task List',
+'taskPane': 'Task Pane',
+'imperial': 'Imperial',
+'metric': 'Metric',
+'deg': 'Degrees',
+'refresh': 'Refresh',
+'expandAll': 'Expand All',
+'expand': 'Expand',
+'collapseAll': 'Collapse All',
+'collapse': 'Collapse',
+'defaultMapTitle': 'Map',
+'legendTitle': 'Legend',
+'selectionPanelTitle': 'Selection',
+'ovmapTitle': 'Overview Map',
+'ovmapTitleShort': 'Overview',
+'taskPaneTitle': 'Tasks',
+'segment': 'Segment ${seg}',
+'calculating': 'calculating ...',
+'panWest': 'Pan West',
+'panEast': 'Pan East',
+'panSouth': 'Pan South',
+'panNorth': 'Pan North',
+'zoomOut': 'Zoom Out',
+'zoomIn': 'Zoom In',
+'printCancel': 'Cancel',
+'printGenerate': 'Generate',
+'zoomRect': 'Zoom Rectangle',
+'maptipLinkText': 'Click for more information',
+'redlineLayerName': 'Digitizing Layer ',
+'printShowTitle':'Show Title?',
+'printOptions'	:'Options',
+'printTitleText':'Title',
+'printShowLegend':'Show Legend?',
+'printShowNorthArrow':'Show North Arrow?',
+
+'end': ''
+};

Added: branches/fusion-2.0/text/fr
===================================================================
--- branches/fusion-2.0/text/fr	                        (rev 0)
+++ branches/fusion-2.0/text/fr	2010-03-24 18:31:34 UTC (rev 2105)
@@ -0,0 +1,335 @@
+# Web surround localized strings
+# English language
+#
+# Important: This file must be saved with UTF-8 encoding
+#
+
+# General
+
+# Fonts - the 6 following entries are mandatory
+ at fontWindows        = Arial
+ at fontsizeWindows    = 8pt
+ at fontLinux          = Arial
+ at fontsizeLinux      = 8pt
+ at fontMacintosh      = Arial
+ at fontsizeMacintosh  = 8pt
+
+# Distances
+DISTANCEMILES       = Miles
+DISTANCEKILOMETERS  = Kilometers
+DISTANCEFEET        = Feet
+DISTANCEMETERS      = Meters
+
+# Fill Patterns/Values
+FILLSOLID           = Solid
+FILLNET             = Net
+FILLLINE            = Line
+FILLLINE45          = Line_45
+FILLLINE90          = Line_90
+FILLLINE135         = Line_135
+FILLSQUARE          = Square
+FILLBOX             = Box
+FILLCROSS           = Cross
+FILLDASH            = Dash
+FILLDOLMIT          = Dolmit
+FILLHEX             = Hex
+FILLSACNCR          = Sacncr
+FILLSTEEL           = Steel
+
+# Transparency
+TRANSPARENT         = transparent
+
+# Line Styles/Values
+LINESOLID           = Solid
+LINEDASH            = Dash
+LINEDOT             = Dot
+LINEDASHDOT         = DashDot
+LINEDASHDOTDOT      = DashDotDot
+LINERAIL            = Rail
+LINEBORDER          = Border
+LINEDIVIDE          = Divide
+LINEFENCELINE       = FenceLine
+
+# Buttons
+BUTTONOK            = OK
+BUTTONDONE          = Done
+BUTTONCANCEL        = Cancel
+BUTTONREFRESH       = Refresh
+BUTTONCLOSE         = Close
+BUTTONCLEAR         = Clear
+BUTTONSAVE          = Save
+
+# Colors
+COLORRED            = Red
+COLORGREEN          = Green
+COLORBLUE           = Blue
+
+# BufferReport
+BUFFERREPORTTITLE               = Create Buffer
+BUFFERREPORTCREATED             = %s has been created.
+BUFFERREPORTUPDATED             = %s has been updated.
+BUFFERREPORTFEATURESSINGULAR    = %s buffer feature was created.
+BUFFERREPORTFEATURESPLURAL      = %s buffer features were created.
+BUFFERREPORTWARNINGSINGULAR     = <b>Warning:</b> %s layer was excluded from buffer computation because its coordinate system is incompatible with the coordinate system of the map, or because it has no coordinate system at all
+BUFFERREPORTWARNINGPLURAL       = <b>Warning:</b> %s layers were excluded from buffer computation because their coordinate systems are incompatible with the coordinate system of the map, or because they have no coordinate system at all
+BUFFERREPORTERRORTITLE          = Buffer Error
+
+# Buffer
+BUFFERCLASSDESCR                = Feature class for buffer layer
+BUFFERSCHEMADESCR               = Temporary buffer schema
+BUFFERDIFFARBXY                 = Cannot compute a unique buffer around features with different 'Arbitrary X-Y' coordinate systems. Please uncheck the option 'Merge buffer areas' or select only one layer
+
+# BufferUI
+BUFFERTITLE                     = Create a Buffer
+BUFFERSUBTITLE                  = &nbsp;Buffer settings
+BUFFERINFOTEXT                  = Select features on the image.
+BUFFERDISTANCE                  = Distance around features:
+BUFFERLAYERS                    = Layers to include in the buffer:
+BUFFERNOLAYER                   = <No layer selected>
+BUFFERNAME                      = Name for the resulting buffer layer:
+BUFFERNAMETEXT                  = Buffer 1
+BUFFERMERGE                     = Merge buffer areas
+BUFFERFILLSTYLE                 = &nbsp;Fill style
+BUFFERFILLPATTERN               = Fill pattern:
+BUFFERFOREGROUNDCOLOR           = Foreground color:
+BUFFERTRANSPARENCY              = Transparency:
+BUFFERBACKGROUNDCOLOR           = Background color:
+BUFFERBORDERSTYLE               = &nbsp;Border style
+BUFFERBORDERLINEPATTERN         = Line pattern:
+BUFFERBORDERLINECOLOR           = Line color:
+BUFFERBORDERLINETHICKNESS       = Line thickness:
+BUFFERHELP                      = <li><p align="left">Results of the buffer are put into a new layer above the top feature layer. This buffer layer has the name you enter here.</li><li><p align="left">To create multiple buffer layers, use different buffer names.</li><li><p align="left">To hide buffer layers, turn them off.</li><li><p align="left">Buffer layers are temporary and are removed when you close the viewer.</li>
+BUFFERERRORZERODISTANCE         = Please enter a nonzero distance.
+BUFFERERRORNOLAYERNAME          = Please enter a layer name.
+BUFFERERRORNEGATIVETHICKNESS    = Please enter positive or null thickness.
+BUFFERERRORNOSELECTION          = Please select feature(s) to calculate a buffer around.
+
+# ColorPicker
+COLORPICKERDLGTITLE             = Select a color
+COLORPICKERTITLE                = Color palette
+COLORPICKERSUBTITLE             = Specify a color
+COLORPICKER100TRANSPARENCY      = 100%% transparency
+COLORPICKERHEXFORMAT            = Hex format
+
+# MeasureUI
+MEASUREDISTANCETITLE    = Measure Distance
+MEASUREAREATITLE        = Measure Area
+MEASUREBOTHTITLE        = Measure Distance And Area
+MEASUREINFO             = Click a start and end point.
+RESUME                  = Resume
+STOP                    = Stop
+CLEAR                   = Clear
+MILES                   = Miles
+KILOMETERS              = Kilometers
+MEASUREHELP             = <li>To measure multiple distances, continue clicking new points.</li><li>To finish, click &quot;Stop&quot;.</li><li>You can pan or zoom and continue measuring by clicking &quot;Resume&quot;.</li><li>To start over, click &quot;Clear&quot;.</li>
+SEGMENT                 = Segment
+TOTAL                   = Total
+LENGTH                  = Length
+TOTALLENGTH             = Total Length
+TOTALAREA               = Total Area
+MEASUREERROR            = Measure Error
+
+# Measure
+MEASUREFEATURECLASS     = Feature class for measure layer
+MEASURESCHEMADESCR      = Temporary measure schema
+MEASUREPARTIAL          = Partial
+MEASURETOTAL            = total
+MEASURELAYER            = Measure
+
+# FeatureInfoUI
+FEATUREINFOTITLE        = Feature Information
+FEATUREINFOSUBTITLE     = Select a Layer
+FEATUREINFOLAYER        = Layer:
+FEATUREINFOSELECTFEATURE= Select Features:
+FEATUREINFODIGITIZE     = Digitize:
+FEATUREINFOPOINT        = Point
+FEATUREINFORECTANGLE    = Rectangle
+FEATUREINFOPOLYGON      = Polygon
+FEATUREINFOTOTAL        = Total:
+FEATUREINFONOSELECTED   = no features selected.
+FEATUREINFOERROR        = Error
+FEATUREINFOFETCHINFO    = fetching feature info ...
+FEATUREINFOFEATURESEL   = features selected
+FEATUREINFOAREA         = Area: 
+FEATUREINFOAREAUNDEFINE = areaIdx undefined
+FEATUREINFONOINFO       = no layer info
+FEATUREINFONOFEATUREIN  = no features in selected layer.
+
+# QueryUI
+QUERYTITLE              = Query Features
+QUERYSELECTLAYER        = Select a Layer
+QUERYLAYER              = Layer:
+QUERYPROPERTYFILTER     = Property Filter
+QUERYPROPERTY           = Property:
+QUERYOPERATOR           = Operator:
+QUERYVALUE              = Value:
+QUERYSPATIALFILTER      = Spatial Filter
+QUERYDIGITIZE           = Digitize:
+QUERYRECTANGLE          = Rectangle
+QUERYPOLYGON            = Polygon
+QUERYCLEAR              = Clear
+QUERYOUTPUT             = Output
+QUERYOUTPUTPROPERTY     = Output property:
+QUERYEXECUTE            = Execute
+QUERYMAXRESULT          = Max results:
+QUERYRESULTS            = Results
+QUERYSCALE              = Scale:
+QUERYZOOM               = Zoom
+QUERYSELECT             = Select
+QUERYERROR              = Error
+QUERYEQUALTO            = Equal to
+QUERYNOTEQUALTO         = Not equal to
+QUERYGREATTHAN          = Greater than
+QUERYGREATTHANEQUAL     = Greater than or equal to
+QUERYLESSTHAN           = Less than
+QUERYLESSTHANEQUAL      = Less than or equal to
+QUERYBEGIN              = Begins with
+QUERYCONTAINS           = Contains
+
+# Theme UI
+THEMETITLE              = Theme Layer
+THEMESELECTLAYER        = Select a Layer
+THEMELAYER              = Layer:
+THEMENAME               = Theme Name:
+THEMECONDITIONS         = Define Conditions
+THEMEPROPERTY           = Property:
+THEMEMIN                = Min:
+THEMEMAX                = Max:
+THEMEDISTRIBUTION       = Distribution:
+THEMERULE               = # of Rules:
+THEMESCALERANGE         = Scale Range
+THEMESTYLERAMP          = Style Ramp
+THEMEFILLTRANS          = Fill Transparency:
+THEMEFILLCOLOR          = Fill Color:
+THEMEFROM               = From:
+THEMETO                 = To:
+THEMEBORDERCOLOR        = Border Color:
+THEMEAPPLY              = Apply
+THEMEERROR              = Error
+THEMEINDIVIDUAL         = Individual
+THEMEEQUAL              = Equal
+THEMESTANDARD           = Standard Deviation
+THEMEQUANTILE           = Quantile
+THEMEJENKS              = Jenks (Natural Breaks)
+
+# Redline UI
+REDLINEOPTIONS          = Digitizing Options
+REDLINESELECTLAYER      = Select Layer: 
+REDLINENEW              = New
+REDLINERENAME           = Rename
+REDLINEREMOVE           = Remove
+REDLINEDRAW             = Draw:
+REDLINEPOINT            = Point
+REDLINELINE             = Line
+REDLINERECTANGLE        = Rectangle
+REDLINEPOLYGON          = Polygon
+REDLINESAVE             = Save
+REDLINEUPLOAD           = Upload
+REDLINEFEATURES         = Features
+
+# HtmlViewerAbout
+HTMLABOUTTITLE          = About %s
+HTMLABOUTTITLEBAR       = MapGuide Viewer
+HTMLABOUTSERVERTITLE    = MapGuide Server
+HTMLABOUTVIEWERTITLE    = MapGuide Viewer
+HTMLABOUTSERVERVERSION  = %s (Version %s)
+HTMLABOUTVIEWERVERSION  = %s (Version %s)
+HTMLABOUTTEXT           = <br>This product is made available subject to the terms of GNU Lesser General Public License Version 2.1 ("LGPL").  A copy of the LGPL, as well as additional copyright notices and license terms applicable to portions of this product are set forth in the <a href="../localized/license_en.htm" target="blank">license</a> file.<br><br>All trademarks and registered trademarks mentioned herein are the property of their respective owners.<br><br>Copyright &copy; 2007 Autodesk, Inc.<br><br>
+HTMLABOUTLICENSE        = license file
+HTMLABOUTLICENSEFILE    = license_en.htm
+
+# LegendUI
+LEGENDLISTSEPARATOR     = ,
+
+# PrintablePageUi
+PRINTTITLE              = Get Printable Page
+PRINTELEMENTS           = Select the elements to include in the print layout.
+PRINTPAGETITLE          = Page title:
+PRINTLEGEND             = Legend
+PRINTNORTHARROW         = North arrow
+PRINTCREATEPAGE         = Create Page
+
+# PropertyCtrl
+PROPERTIESNONE          = None Selected
+PROPERTIESNAME          = Name
+PROPERTIESVALUE         = Value
+PROPERTIESITEMSEL       = Items selected: {0}
+
+# Search
+SEARCHDLGTITLE          = Search features
+SEARCHTITLE             = Search results
+SEARCHERROR             = Search error
+SEARCHREPORT            = Search report
+SEARCHLAYERNOTFOUND     = Layer {0} not found!
+SEARCHNOMULTIPROP       = Multi-properties identity not supported yet
+SEARCHTYYPENOTSUP       = Identity property type not supported yet ({0})
+SEARCHNOMATCHES         = No matches.
+
+# SearchPrompt
+SEARCHPROMPTFIND        = Find
+
+# SelectWithinUi
+SELECTWITHINTITLE       = Select Within
+SELECTWITHINAREAS       = Select areas on the image.
+SELECTWITHINRESTRICTION = Restrict results to selected layers:
+SELECTWITHINTEXT        = <li>If you continue to select areas on the image, click &quot;Refresh&quot; to update the layer list.</li><li>To finish and select all features within the highlighted areas, click &quot;Done&quot;.</li><li>To start over, click &quot;Clear&quot;.</li>
+
+# Error/Report
+REPORTTITLE             = Report
+
+# Legend UI
+REFRESH                 = Refresh
+EXPANDALL               = Expand
+COLLAPSEALL             = Collapse All
+DISPLAYALLINGROUP       = Display All in Group
+HIDEALLINGROUP          = Hide All in Group
+SHOWLONGTHEME           = Show Long Theme
+
+# Task Bar
+TASKS                   = Tasks
+
+# Viewer Options
+OPTIONSTITLE            = Viewer Options
+OPTIONSINFOTEXT         = Select viewing options for status bar and tool tips.
+OPTIONSDISTANCE         = Display distances in
+OPTIONSMETRIC           = Metric (Kilometers, Meters)
+OPTIONSUSENGLISH        = US/English (Miles, Feet)
+OPTIONSPOSITION         = Display cursor position in
+OPTIONSLATLON           = Latitude, Longitude (Degrees)
+OPTIONSMAPUNITS         = Map Coordinate System (X,Y)
+
+# AJAX Viewer
+VIEWERLAYERS            = Layers
+VIEWERPROPS             = Properties
+VIEWERPANNORTH          = Pan North
+VIEWERPANWEST           = Pan West
+VIEWERPANSOUTH          = Pan South
+VIEWERPANEAST           = Pan East
+VIEWERZOOMIN            = Zoom In
+VIEWERZOOMOUT           = Zoom Out
+VIEWERMOVESLIDER        = Drag to move slider
+VIEWERDRAGZOOM          = Drag to zoom
+ENDSEL                  = CTRL + click to end
+ENDSELSAFARI            = SHIFT + click to end
+DECIMALSEPARATOR        = .
+THOUSANDSEPARATOR       = ,
+
+# Main Frame
+NEEDLOGIN               = You must enter a valid login ID and password to access this site
+ALREADYINMEASURE        = Only one measure command is allowed in a web layout
+ACCESSDENIED            = Access Denied   
+LATLONCURPOS            = Lat: {0}, Lon: {1}
+MAPUNITSCURPOS          = X: {0}, Y: {1}
+FEATURESSELECTED        = {0} features selected
+FEATURESELECTED         = {0} feature selected
+MI                      = mi
+FT                      = ft
+IN                      = in
+KM                      = km
+MT                      = m
+CM                      = cm
+DIGALREADYRUNNING       = Cannot execute measure: A digitization command is in progress.
+MEASALREADYRUNNING      = Cannot execute digitization: A measure is in progress.
+
+# Localized Icon Files
+POWEREDBYICON           = PoweredBy_en.gif

Added: branches/fusion-2.0/text/fr.json
===================================================================
--- branches/fusion-2.0/text/fr.json	                        (rev 0)
+++ branches/fusion-2.0/text/fr.json	2010-03-24 18:31:34 UTC (rev 2105)
@@ -0,0 +1,54 @@
+Fusion.Strings.fr = {
+'scriptFailed': 'failed to load script: ${script}',
+'configParseError': 'Error parsing fusion configuration file, initialization aborted',
+'configLoadError': 'Error loading fusion configuration file, initialization aborted.' +
+                  'Make sure that you have copied config_dist.json to config.json ' +
+                  'and have configured the settings for your system',
+'ajaxError': 'Exception occurred in AJAX callback.\n${exception}\nLocation: ${file} (${line}))',
+'importFailed': 'failed to import stylesheet: ${url}',
+'registerEventError': 'Error registering eventID, invalid (empty) eventID.',
+'appDefLoadFailed': 'failed to load: ${script}',
+'appDefParseError': 'failed to parse ApplicationDefinition',
+'widgetSetParseError': 'failed to parse the WidgetSet',
+'fusionError': 'Fusion Error: ${type}\n${message}',
+'nullExtents': 'Map.setExtents called with null extents',
+'mapLoadError': 'Failed to load requested map:\n${error}',
+'setLayersError': "setLayers failure: ${error}",
+'printTitle': 'Printable Page ',
+'noSelection': 'Aucun Sélection',
+'selectionInfo': '${features} feature(s) selected on ${layers} layer(s)',
+'attribute': 'Attribute',
+'value': 'Value',
+'taskHome': 'return to the task pane home',
+'prevTask': 'go to previous task executed',
+'nextTask': 'go to next task executed',
+'taskList': 'Task List',
+'taskPane': 'Task Pane',
+'imperial': 'Imperial',
+'metric': 'Metric',
+'deg': 'Degrees',
+'refresh': 'Refresh',
+'expandAll': 'Expand All',
+'expand': 'Expand',
+'collapseAll': 'Collapse All',
+'collapse': 'Collapse',
+'defaultMapTitle': 'Map',
+'legendTitle': 'Legend',
+'selectionPanelTitle': 'Sélection',
+'ovmapTitle': 'Overview Map',
+'ovmapTitleShort': 'Overview',
+'taskPaneTitle': 'Tasks',
+'segment': 'Segment ${seg}',
+'calculating': 'calculating ...',
+'panWest': 'Ouest',
+'panEast': 'Est',
+'panSouth': 'Sud',
+'panNorth': 'Nord',
+'zoomOut': 'Cliquer pour réduire',
+'zoomIn': 'Cliquer pour agrandir',
+'printCancel': 'Cancel',
+'printGenerate': 'Generate',
+'maptipLinkText': 'Cliquer pour plus d information',
+
+'end': ''
+};

Modified: branches/fusion-2.0/widgets/About/About.html
===================================================================
--- branches/fusion-2.0/widgets/About/About.html	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/About/About.html	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,4 +1,4 @@
-<html>
+<html>
 <head>
     <title>About Fusion</title>
 </head>

Modified: branches/fusion-2.0/widgets/BasemapSwitcher.js
===================================================================
--- branches/fusion-2.0/widgets/BasemapSwitcher.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/BasemapSwitcher.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -22,25 +22,41 @@
 
 Fusion.Widget.BasemapSwitcher = OpenLayers.Class(Fusion.Widget, {
     uiClass: Jx.Menu,
-    options: {
-        'G_NORMAL_MAP': null,
-        'G_SATELLITE_MAP': null,
-        'G_HYBRID_MAP': null,
-        'YAHOO_MAP_REG': null,
-        'YAHOO_MAP_SAT': null,
-        'YAHOO_MAP_HYB': null,
-        'Road': null,
-        'Aerial': null,
-        'Hybrid': null,
-        'None': null
-    },
+
+    options: {},
+
     baseMaps: {},
 
     defaultBasemap: null,
 
-    menuItems: null,
+    menuItems: {},
 
     initializeWidget: function(widgetTag) {
+        this.getMap().registerForEvent(Fusion.Event.MAP_MAP_GROUP_LOADED, OpenLayers.Function.bind(this.setDefaultBasemap, this));
+    },
+
+    refreshSettings: function() {
+        this.baseMaps = {};
+        this.defaultBasemap = null;
+        this.menuItems = {};
+        this.options = {
+            'G_NORMAL_MAP': null,
+            'G_SATELLITE_MAP': null,
+            'G_HYBRID_MAP': null,
+            'YAHOO_MAP_REG': null,
+            'YAHOO_MAP_SAT': null,
+            'YAHOO_MAP_HYB': null,
+            'Road': null,
+            'Aerial': null,
+            'Hybrid': null,
+            'None': null
+        };
+    },
+
+    generateOptions: function() {
+        // Clear previous settings 
+        this.refreshSettings();
+
         var maps = this.getMap().aMaps;
         for (var i = 0, len = maps.length; i < len; i++) {
             var map = maps[i];
@@ -84,8 +100,6 @@
                                 this.baseMaps['G_HYBRID_MAP'] = map;
                                 break;
                             default:
-                                //this.options['G_NORMAL_MAP'] = map.mapTag.extension.Options[0].name[0];
-                                //this.baseMaps['G_NORMAL_MAP'] = map;
                                 break;
                         }
 
@@ -131,8 +145,6 @@
                                 this.baseMaps['YAHOO_MAP_HYB'] = map;
                                 break;
                             default:
-                                //this.options['YAHOO_MAP_REG'] = map.mapTag.extension.Options[0].name[0];
-                                //this.baseMaps['YAHOO_MAP_REG'] = map;
                                 break;
                         }
                         // The first non-MapGuide basemap will be the default basemap
@@ -176,8 +188,6 @@
                                 this.baseMaps['Hybrid'] = map;
                                 break;
                             default:
-                                //this.options['Road'] = map.mapTag.extension.Options[0].name[0];
-                                //this.baseMaps['Road'] = map;
                                 break;
                         }
                         // The first non-MapGuide basemap will be the default basemap
@@ -189,32 +199,15 @@
                 default:
                     break;
             }
-
         }
-
-        this.getMap().registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.setDefaultBasemap, this));
-        
-        this.menuItems = {};
+        if (!this.defaultBasemap) {
+            this.defaultBasemap = "None";
+        }
     },
 
     setUiObject: function(uiObj) {
         Fusion.Widget.prototype.setUiObject.apply(this, [uiObj]);
-        var buttonSet = new Jx.ButtonSet();
-        //set up the root menu
-        for (var key in this.options) {
-            if (this.options[key]) {
-                var menuItem = new Jx.Menu.Item({
-                    label: OpenLayers.i18n(this.options[key]),
-                    toggle: true,
-                    onDown: OpenLayers.Function.bind(this.setBasemap, this, key)
-                });
-                buttonSet.add(menuItem);
-                this.uiObj.add(menuItem);
-
-                this.menuItems[key] = menuItem;
-            }
-        }
-
+        this.setDefaultBasemap();
     },
 
     setBasemap: function(baseMap) {
@@ -232,6 +225,24 @@
     },
 
     setDefaultBasemap: function() {
+        this.generateOptions();
+        //re-generate the menu
+        this.uiObj.initialize();
+
+        //set up the root menu
+        var buttonSet = new Jx.ButtonSet();
+        for (var key in this.options) {
+            if (this.options[key]) {
+                var menuItem = new Jx.Menu.Item({
+                    label: OpenLayers.i18n(this.options[key]),
+                    toggle: true,
+                    onDown: OpenLayers.Function.bind(this.setBasemap, this, key)
+                });
+                buttonSet.add(menuItem);
+                this.uiObj.add(menuItem);
+                this.menuItems[key] = menuItem;
+            }
+        }
         this.menuItems[this.defaultBasemap].setActive(true);
         this.setBasemap(this.defaultBasemap);
     }

Modified: branches/fusion-2.0/widgets/BufferPanel/Buffer.php
===================================================================
--- branches/fusion-2.0/widgets/BufferPanel/Buffer.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/BufferPanel/Buffer.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -25,7 +25,13 @@
  */
 
     $fusionMGpath = '../../layers/MapGuide/php/';
+
     include $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
 
     $locale = GetDefaultLocale();
     $mapName = "";

Modified: branches/fusion-2.0/widgets/BufferPanel/BufferPanel.php
===================================================================
--- branches/fusion-2.0/widgets/BufferPanel/BufferPanel.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/BufferPanel/BufferPanel.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -26,7 +26,11 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     include $fusionMGpath . 'Common.php';
-
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
     $locale = GetDefaultLocale();
     $popup = 0;
     $mapName = "";

Modified: branches/fusion-2.0/widgets/BufferPanel/BufferPanel.templ
===================================================================
--- branches/fusion-2.0/widgets/BufferPanel/BufferPanel.templ	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/BufferPanel/BufferPanel.templ	2010-03-24 18:31:34 UTC (rev 2105)
@@ -57,6 +57,7 @@
 var decimalSeparator = "__#DECIMALSEPARATOR#__";    
 var agent = navigator.userAgent.toLowerCase();
 var msie = agent.indexOf("msie") != -1;
+var mapName;
 
 function InitDocument()
 {
@@ -70,7 +71,7 @@
 {
     var list = document.getElementById("layers");
     var listNames = document.getElementById("layerNames");
-    var mapName = document.getElementById('Frm').mapname.value;
+    mapName = document.getElementById('Frm').mapname.value;
     list.options.length = 0;
     var map = GetParent().Fusion.getMapByName(mapName);
     var layers = map.aMaps[0].getSelectedLayers();  
@@ -219,6 +220,9 @@
 
 function OnCancel()
 {
+    if(mapName == "undefined")
+        return;
+    
     var map = GetParent().Fusion.getMapByName(mapName);
     map.clearSelection();
     //mf.GotoHomePage();

Modified: branches/fusion-2.0/widgets/BufferPanel/ColorPicker.php
===================================================================
--- branches/fusion-2.0/widgets/BufferPanel/ColorPicker.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/BufferPanel/ColorPicker.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -26,7 +26,11 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     include $fusionMGpath . 'Common.php';
-
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
     $locale = GetDefaultLocale();
     $clr = "000000";
     $allowTransparency = 0;

Modified: branches/fusion-2.0/widgets/BufferPanel/ColorPicker.templ
===================================================================
--- branches/fusion-2.0/widgets/BufferPanel/ColorPicker.templ	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/BufferPanel/ColorPicker.templ	2010-03-24 18:31:34 UTC (rev 2105)
@@ -38,9 +38,9 @@
 var agent = navigator.userAgent.toLowerCase();
 var msie = agent.indexOf("msie") != -1;
 var imgspin = new Image(28,22);
-imgspin.src = "../stdicons/cp_arr.gif";
+imgspin.src = "./cp_arr.gif";
 var imgspindis = new Image(28,22);
-imgspindis.src = "../stdicons/cp_arr_dis.gif";
+imgspindis.src = "./cp_arr_dis.gif";
 var r = 0, g = 0, b = 0;
 var initColor = "%s";
 var allowTransparency = %s;

Copied: branches/fusion-2.0/widgets/BufferPanel/cp_arr.gif (from rev 2103, trunk/widgets/BufferPanel/cp_arr.gif)
===================================================================
(Binary files differ)

Copied: branches/fusion-2.0/widgets/BufferPanel/cp_arr_dis.gif (from rev 2103, trunk/widgets/BufferPanel/cp_arr_dis.gif)
===================================================================
(Binary files differ)

Modified: branches/fusion-2.0/widgets/ExtentHistory.js
===================================================================
--- branches/fusion-2.0/widgets/ExtentHistory.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/ExtentHistory.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -156,10 +156,10 @@
         b2.right += offset;
       }
       //calculate difference as percentage so all ranges of coordinates can be accommodated
-      equal = (Math.abs(b1.top - b2.top)/b2.top < this.EPS &&
-               Math.abs(b1.bottom - b2.bottom)/b2.bottom < this.EPS &&
-               Math.abs(b1.left - b2.left)/b2.left < this.EPS &&
-               Math.abs(b1.right - b2.right)/b2.right < this.EPS);
+      equal = (Math.abs((b1.top - b2.top) / b2.top) < this.EPS &&
+               Math.abs((b1.bottom - b2.bottom) / b2.bottom) < this.EPS &&
+               Math.abs((b1.left - b2.left) / b2.left) < this.EPS &&
+               Math.abs((b1.right - b2.right) / b2.right) < this.EPS);
       return equal;
     }
 });

Modified: branches/fusion-2.0/widgets/FeatureInfo/featureinfocontroller.php
===================================================================
--- branches/fusion-2.0/widgets/FeatureInfo/featureinfocontroller.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/FeatureInfo/featureinfocontroller.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -19,19 +19,24 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     require_once $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorText();
+        exit;
+    }
     require_once $fusionMGpath . 'Utilities.php';
     require_once $fusionMGpath . 'JSON.php';
     require_once 'classes/featureinfo.php';
 
     $args = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_GET;
-    
+
     try {
         $responseType = 'text/plain';
         $response = '';
-        
+
         $site = new MgSiteConnection();
         $site->Open(new MgUserInformation($args['SESSION']));
-        
+
         $resourceService = $site->CreateService(MgServiceType::ResourceService);
         $featureService =
             $site->CreateService(MgServiceType::FeatureService);
@@ -46,9 +51,9 @@
 
         $selection = new MgSelection($map);
         $selection->Open($resourceService, $mapName);
-        
+
         $properties = NULL;
-        
+
         if ($selection->Contains($layer, $className)) {
             $featureReader = $selection->GetSelectedFeatures($layer, $className, new MgStringCollection());
 
@@ -91,15 +96,15 @@
               $properties = BuildSelectionArray($featureReader, $layerName, $properties, true, $srsLayer, $bNeedsTransform, $layer);
 
         }
-  
-        $response = json_encode($properties);          
 
+        $response = json_encode($properties);
+
     } catch (MgException $e) {
         echo "ERROR: " . $e->GetMessage() . "\n";
         echo $e->GetDetails() . "\n";
         echo $e->GetStackTrace() . "\n";
     }
-    
+
     header('Content-Type: ' . $responseType);
     echo trim($response);
-?>
\ No newline at end of file
+?>

Modified: branches/fusion-2.0/widgets/FeatureInfo/featureinfomain.php
===================================================================
--- branches/fusion-2.0/widgets/FeatureInfo/featureinfomain.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/FeatureInfo/featureinfomain.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -19,6 +19,17 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     require_once $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
+    SetLocalizedFilesPath(GetLocalizationPath());
+    if(isset($_REQUEST['locale'])) {
+        $locale = $_REQUEST['locale'];
+    } else {
+        $locale = GetDefaultLocale();
+    }
     require_once $fusionMGpath . 'Utilities.php';
     require_once $fusionMGpath . '/JSON.php';
     require_once 'classes/featureinfo.php';
@@ -27,6 +38,24 @@
 
     $errorMsg = null;
     $errorDetail = null;
+    
+    $titleLocal = GetLocalizedString('FEATUREINFOTITLE', $locale );
+    $subtitleLocal = GetLocalizedString('FEATUREINFOSUBTITLE', $locale );
+    $layerLocal = GetLocalizedString('FEATUREINFOLAYER', $locale );
+    $selectFeatureLocal = GetLocalizedString('FEATUREINFOSELECTFEATURE', $locale );
+    $digitizeLocal = GetLocalizedString('FEATUREINFODIGITIZE', $locale );
+    $pointLocal = GetLocalizedString('FEATUREINFOPOINT', $locale );
+    $rectangleLocal = GetLocalizedString('FEATUREINFORECTANGLE', $locale );
+    $polygonLocal = GetLocalizedString('FEATUREINFOPOLYGON', $locale );
+    $totalLocal = GetLocalizedString('FEATUREINFOTOTAL', $locale );
+    $noSelectedLocal = GetLocalizedString('FEATUREINFONOSELECTED', $locale );
+    $errorLocal = GetLocalizedString('FEATUREINFOERROR', $locale );
+    $fetchInfoLocal = GetLocalizedString('FEATUREINFOFETCHINFO', $locale );
+    $featureSelLocal = GetLocalizedString('FEATUREINFOFEATURESEL', $locale );
+    $areaLocal = GetLocalizedString('FEATUREINFOAREA', $locale );
+    $areaUndefinedLocal = GetLocalizedString('FEATUREINFOAREAUNDEFINE', $locale );
+    $noLayerInfoLocal = GetLocalizedString('FEATUREINFONOINFO', $locale );
+    $noFeatureInLocal = GetLocalizedString('FEATUREINFONOFEATUREIN', $locale );
 
     try
     {
@@ -46,7 +75,7 @@
 ?>
 <html>
 <head>
-    <title>Feature Information</title>
+    <title><?php echo $titleLocal ?></title>
     <link rel="stylesheet" href="../../common/mgsamples.css" type="text/css">
     <script language="javascript" src="../../common/browserdetect.js"></script>
     <script language="javascript" src="../../common/json.js"></script>
@@ -68,7 +97,7 @@
 
         var properties = null;
         var results;
-        
+
         var reqHandler;
 
         function OnLayerChange() {
@@ -89,7 +118,7 @@
             var map = GetFusionMapWidget();
             map.clearSelection();
         }
-        
+
         function OnDigitizePoint() {
             DigitizePoint(OnPointDigitized);
         }
@@ -99,7 +128,7 @@
             var min = {x:point.X-tolerance,y:point.Y-tolerance};
             var max = {x:point.X+tolerance,y:point.Y+tolerance};
             var geom = 'POLYGON(('+ min.x + ' ' +  min.y + ', ' +  max.x + ' ' +  min.y + ', ' + max.x + ' ' +  max.y + ', ' + min.x + ' ' +  max.y + ', ' + min.x + ' ' +  min.y + '))';
-          
+
             SetSpatialFilter(geom);
         }
         function OnDigitizeRectangle() {
@@ -110,7 +139,7 @@
           var min = rectangle.Point1;
           var max = rectangle.Point2;
           var geom = 'POLYGON(('+ min.X + ' ' +  min.Y + ', ' +  max.X + ' ' +  min.Y + ', ' + max.X + ' ' +  max.Y + ', ' + min.X + ' ' +  max.Y + ', ' + min.X + ' ' +  min.Y + '))';
-        
+
           SetSpatialFilter(geom);
         }
 
@@ -138,13 +167,13 @@
 
             GetFusionMapWidget().query(options);
         }
-        
+
         function SelectionOn() {
             var layerSelect = document.getElementById("layerSelect");
             var reqParams = "SESSION=" + encodeURIComponent(session);
             reqParams += "&MAPNAME=" + encodeURIComponent(mapName);
             reqParams += "&LAYERNAME=" + encodeURIComponent(layerSelect.value);
-            
+
             if (msie)
                 reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
             else
@@ -153,18 +182,18 @@
             reqHandler.onreadystatechange = OnReadyStateChange;
             reqHandler.open("POST", "featureinfocontroller.php", true);
             reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-            
-            document.getElementById('totalFeatures').innerHTML = 'fetching feature info ...';
+
+            document.getElementById('totalFeatures').innerHTML = '<?php echo $fetchInfoLocal ?>';
             document.getElementById('totalArea').innerHTML = ''
             document.getElementById("layerSelect").disabled = true;
             document.getElementById("pointButton").disabled = true;
             document.getElementById("rectButton").disabled = true;
             document.getElementById("polyButtton").disabled = true;
             document.getElementById("busyImg").src = BUSY_IMAGE;
-            
+
             reqHandler.send(reqParams);
         }
-        
+
         function OnReadyStateChange()
         {
             var ready = reqHandler.readyState;
@@ -174,7 +203,7 @@
                 var results = reqHandler.responseText.parseJSON();
                 if (results) {
                     var layerSelect = document.getElementById('layerSelect');
-                
+
                     var layerInfo = results[layerSelect.value];
                     if (layerInfo) {
                         var areaIdx;
@@ -191,19 +220,19 @@
                                 var metadata = layerInfo.metadata[i];
                                 totalArea += metadata[areaIdx];
                             }
-                            document.getElementById('totalFeatures').innerHTML = n + ' features selected';
-                            document.getElementById('totalArea').innerHTML = 'Area: ' + totalArea + ' m<sup>2</sup>';
+                            document.getElementById('totalFeatures').innerHTML = n + '<?php echo $featureSelLocal ?>';
+                            document.getElementById('totalArea').innerHTML = '<?php echo $areaLocal ?>' + totalArea + ' m<sup>2</sup>';
                         } else {
-                            document.getElementById('totalArea').innerHTML = 'areaIdx undefined';
+                            document.getElementById('totalArea').innerHTML = '<?php echo $areaUndefinedLocal ?>';
                         }
                     } else {
-                        document.getElementById('totalArea').innerHTML = 'no layer info';
-                    }                  
+                        document.getElementById('totalArea').innerHTML = '<?php echo $noLayerInfoLocal ?>';
+                    }
                 } else {
-                  document.getElementById('totalFeatures').innerHTML = 'no features in selected layer.';
+                  document.getElementById('totalFeatures').innerHTML = '<?php echo $noFeatureInLocal ?>';
                 }
-                
-                
+
+
                 document.getElementById("layerSelect").disabled = false;
                 document.getElementById("pointButton").disabled = false;
                 document.getElementById("rectButton").disabled = false;
@@ -213,7 +242,7 @@
             }
         }
         function SelectionOff() {
-            document.getElementById('totalFeatures').innerHTML = 'no features selected.';
+            document.getElementById('totalFeatures').innerHTML = '<?php echo $noSelectedLocal ?>';
             document.getElementById('totalArea').innerHTML = '';
         }
 
@@ -228,7 +257,7 @@
             }
             OnLayerChange();
         }
-        
+
         function OnUnload() {
           var map = GetFusionMapWidget();
           map.deregisterForEvent(Fusion.Event.MAP_SELECTION_ON, SelectionOn);
@@ -245,9 +274,9 @@
 <?php if ($errorMsg == null) { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%">
-    <tr><td class="Title"><img id="busyImg" src="../../common/images/loader_inactive.gif" style="vertical-align:bottom">&nbsp;Feature Information<hr></td></tr>
-    <tr><td class="SubTitle">Select a Layer</td></tr>
-    <tr><td>Layer:</td></tr>
+    <tr><td class="Title"><img id="busyImg" src="../../common/images/loader_inactive.gif" style="vertical-align:bottom">&nbsp;<?php echo $titleLocal ?><hr></td></tr>
+    <tr><td class="SubTitle"><?php echo $subtitleLocal ?></td></tr>
+    <tr><td><?php echo $layerLocal ?></td></tr>
     <tr>
         <td class="RegText">
             <select size="1" class="Ctrl" id="layerSelect" onChange="OnLayerChange()" style="width: 100%">
@@ -265,32 +294,32 @@
     </tr>
     <tr><td class="Spacer"></td></tr>
 
-    <tr><td class="SubTitle">Select Features:</td></tr>
-    <tr><td>Digitize:</td></tr>
+    <tr><td class="SubTitle"><?php echo $selectFeatureLocal ?></td></tr>
+    <tr><td><?php echo $digitizeLocal ?></td></tr>
     <tr>
         <td align="center">
-            <input type="button" name="" value="Point" class="Ctrl" id="pointButton" onClick="OnDigitizePoint()" style="width: 30%">
-            <input type="button" name="" value="Rectangle" class="Ctrl" id="rectButton" onClick="OnDigitizeRectangle()" style="width: 30%">
-            <input type="button" name="" value="Polygon" class="Ctrl" id="polyButtton" onClick="OnDigitizePolygon()" style="width: 30%">
+            <input type="button" name="" value="<?php echo $pointLocal ?>" class="Ctrl" id="pointButton" onClick="OnDigitizePoint()" style="width: 30%">
+            <input type="button" name="" value="<?php echo $rectangleLocal ?>" class="Ctrl" id="rectButton" onClick="OnDigitizeRectangle()" style="width: 30%">
+            <input type="button" name="" value="<?php echo $polygonLocal ?>" class="Ctrl" id="polyButtton" onClick="OnDigitizePolygon()" style="width: 30%">
         </td>
     </tr>
     <tr><td class="Spacer"></td></tr>
-    <tr><td class="SubTitle">Total:</td></tr>
-    <tr><td id="totalFeatures">no features selected.</td></tr>
+    <tr><td class="SubTitle"><?php echo $totalLocal ?></td></tr>
+    <tr><td id="totalFeatures"><?php echo $noSelectedLocal ?></td></tr>
     <tr><td id="totalArea"></td></tr>
 </table>
 
 <?php } else if ($errorDetail == null || (strlen($errorDetail) - strlen($errorMsg) < 5)) { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%%">
-    <tr><td class="Title">Error<hr></td></tr>
+    <tr><td class="Title"><?php echo $errorLocal ?><hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
 </table>
 
 <?php } else { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%%">
-    <tr><td class="Title">Error<hr></td></tr>
+    <tr><td class="Title"><?php echo $errorLocal ?><hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
     <tr><td><?= $errorDetail ?></td></tr>
 </table>

Modified: branches/fusion-2.0/widgets/FeatureInfo.js
===================================================================
--- branches/fusion-2.0/widgets/FeatureInfo.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/FeatureInfo.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -36,6 +36,7 @@
 
 
 Fusion.Widget.FeatureInfo = OpenLayers.Class(Fusion.Widget, {
+    isExclusive: true,
     uiClass: Jx.Button,
     sFeatures : 'menubar=no,location=no,resizable=no,status=no',
 

Modified: branches/fusion-2.0/widgets/Help/Help.html
===================================================================
--- branches/fusion-2.0/widgets/Help/Help.html	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Help/Help.html	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,4 +1,4 @@
-<html>
+<html>
 <head>
     <title></title>
 </head>

Modified: branches/fusion-2.0/widgets/LayerManager.js
===================================================================
--- branches/fusion-2.0/widgets/LayerManager.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/LayerManager.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -53,31 +53,39 @@
 Fusion.Widget.LayerManager = OpenLayers.Class(Fusion.Widget,  {
     currentNode: null,
     bIsDrawn: false,
+    map: null,
     initializeWidget: function(widgetTag) {
+        //console.log("initializeWidget");
         var json = widgetTag.extension;
         this.delIconSrc = json.DeleteIcon ? json.DeleteIcon[0] : 'images/icons/select-delete.png';
     
         Fusion.addWidgetStyleSheet(widgetTag.location + 'LayerManager/LayerManager.css');
         this.cursorNormal = ["url('images/grab.cur'),move", 'grab', '-moz-grab', 'move'];
         this.cursorDrag = ["url('images/grabbing.cur'),move", 'grabbing', '-moz-grabbing', 'move'];
-        
-        this.getMap().registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.mapLoaded, this));
-        this.getMap().registerForEvent(Fusion.Event.MAP_RELOADED, OpenLayers.Function.bind(this.mapLoaded, this));
+        this.map = this.getMap();
+        this.map.registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.mapLoaded, this));
+        this.map.registerForEvent(Fusion.Event.MAP_RELOADED, OpenLayers.Function.bind(this.mapReLoaded, this));
+        // update changes to the legend in this widget
+        this.map.aMaps[0].registerForEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, OpenLayers.Function.bind(this.layerChanged,this));
     },
     
-   
     mapLoaded: function() {
         this.draw();
     },
-    
-   
+    layerChanged: function() {
+        this.updateSessionMapFile();
+    },
+    mapReLoaded: function(){
+        this.draw();
+   },
    /**
      * remove the dom objects representing the legend layers and groups
      */
     clear: function(node) {
+        //console.log("clear");
         while (node.childNodes.length > 0) {
           this.clear(node.childNodes[0]);
-            node.remove(node.childNodes[0]);
+            node.destroy(node.childNodes[0]);
         }
     },
   
@@ -87,9 +95,10 @@
      * @param r Object the reponse xhr object
      */
     draw: function(r) {
+        //console.log("draw");
       if (this.mapList) {
-        //this.clear(this.mapList);
-        //this.mapList.remove();
+        this.clear(this.mapList);
+        this.mapList.destroy();
         this.mapList = null;
       }
        
@@ -100,11 +109,12 @@
         
       //this processes the OL layers
       var map = this.getMap();
+
       for (var i=0; i<map.aMaps.length; ++i) {
         var mapBlock = document.createElement('li');
         mapBlock.className = 'jxLmanMap';
         mapBlock.id = 'mapBlock_'+i;
-        
+
         //add a handle so the map blocks can be re-arranged
         var handle = document.createElement('a');
         handle.innerHTML = map.aMaps[i]._sMapTitle;
@@ -125,17 +135,15 @@
     },
 
     processMapBlock: function(blockDom, map) {
+      //console.log("processMapBlock");
       var mapBlockList = document.createElement('ul');
       mapBlockList.className = 'jxLmanSet';
       mapBlockList.id = 'fusionLayerManager_'+map.getMapName();
       blockDom.appendChild(mapBlockList);
       map.layerPrefix = 'layer_';   //TODO make this unique for each block
-      
       //this process all layers within an OL layer
       var processArray = map.aLayers;
-      if (map.bLayersReversed) {
-        processArray.reverse();
-      }
+    
       for (var i=0; i<processArray.length; ++i) {
         var blockItem = document.createElement('li');
         blockItem.className = 'jxLmanLayer';
@@ -144,14 +152,14 @@
         this.createItemHtml(blockItem, processArray[i]);
         blockItem.layer = processArray[i];
       }
-      
-      /*
-      var options = [];
-      options.onUpdate = OpenLayers.Function.bind(this.updateLayer, this, map);
-      options.scroll = this.domObj.id;    //docs for this at: http://wiki.script.aculo.us/scriptaculous/show/Sortable.create
-      Position.includeScrollOffsets = true;
-      Sortable.create(mapBlockList.id, options);
-      */
+
+      var sortableOptions = {
+                constrain: true,
+                clone: false,
+                revert: true,
+                onComplete: OpenLayers.Function.bind(this.updateLayer, $(mapBlockList.id), map)
+            };
+    var mySortables = new Sortables(mapBlockList.id, sortableOptions);
     },
    
   createItemHtml: function(parent, layer) {
@@ -191,15 +199,15 @@
   },
   
   setGrabCursor: function(ev) {
-   // this.setCursor(this.cursorNormal, Event.element(ev) );
+    this.setCursor(this.cursorDrag, ev.currentTarget.parentNode);
   },
   
   setDragCursor: function(ev) {
-   // this.setCursor(this.cursorDrag, Event.element(ev) );
+   this.setCursor(this.cursorDrag, ev.currentTarget.parentNode);
   },
   
   setNormalCursor: function(ev) {
-    //this.setCursor('auto', Event.element(ev) );
+    this.setCursor('auto', ev.currentTarget.parentNode);
   },
   
   setCursor : function(cursor, domObj) {
@@ -219,30 +227,26 @@
   },
   
   updateLayer: function(map, ul) {
+   //console.log("updateLayer");
     //reorder the layers in the client as well as the session
     var aLayerIndex = [];
     var aIds = [];
-    var nLayers = ul.childNodes.length;
+    var nLayers = this.childNodes.length;
     for (var i=0; i<nLayers; ++i) {
-      aIds[i] = ul.childNodes[i].id.split('_');
+      aIds[i] = this.childNodes[i].id.split('_');
       var index = parseInt(aIds[i].pop());
-      if (map.bLayersReversed) {
-        index = nLayers - (index+1);
-      }
       aLayerIndex.push(index);
-      ul.childNodes[i].id = '';
+      this.childNodes[i].id = '';
     }
     
     //reset the ID's on the LI elements to be in order
-    for (var i=0; i<ul.childNodes.length; ++i) {
-      var node = ul.childNodes[i];
+    for (var i=0; i<this.childNodes.length; ++i) {
+      var node = this.childNodes[i];
       aIds[i].push(i);
       node.id = aIds[i].join('_');
       node.childNodes[1].checked = node.layer.isVisible()
     }
-    if (map.bLayersReversed) {
-      aLayerIndex.reverse();
-    }
+
     map.reorderLayers(aLayerIndex);
   },
    
@@ -251,6 +255,7 @@
   },
   
   deleteLayer: function(layer, ev) {
+   // console.log("deleteLayer");
     var targetLI = (new Event(ev)).target.parentNode;
     var ul = targetLI.parentNode;
     $(targetLI).dispose();
@@ -265,6 +270,34 @@
     } else {
       layer.hide();
     }
+  },
+  updateSessionMapFile: function(){
+   // console.log("updateSessionMapFile");
+    // get map
+    var map = this.getMap();
+    var aMaps = map.getAllMaps();
+    var currentMap = aMaps[0];
+    var sessionId = aMaps[0].getSessionID();
+
+    // get all layers
+    var oLayers = currentMap.aLayers;
+    var aLayerNames = [];
+    var visibleLayers = [];
+    for(var i=0;i<oLayers.length;i++){
+        aLayerNames.push(oLayers[i].layerName);
+        if(oLayers[i].visible == true){
+            visibleLayers.push(oLayers[i].layerName);
+        }
+    }
+
+    // prepare ajax req
+    var params =  '&session='+sessionId+'&mapname='+ this.getMap().getMapName()+'&visLayers='+visibleLayers+'&layers='+aLayerNames;
+    var options = {parameters: params};
+
+    // fire the request no need to return
+    var m = this.getMap().aMaps[0];
+    var url = 'layers/' + m.arch + '/' + Fusion.getScriptLanguage() + "/updateSessionMapFile." + Fusion.getScriptLanguage()
+    Fusion.ajaxRequest(  url, options);
   }
 
 });

Modified: branches/fusion-2.0/widgets/Legend.js
===================================================================
--- branches/fusion-2.0/widgets/Legend.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Legend.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,828 +1,946 @@
-/**
- * Fusion.Widget.Legend
- *
- * $Id$
- *
- * Copyright (c) 2007, DM Solutions Group Inc.
- * 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.
- */
-
- /********************************************************************
- * Class: Fusion.Widget.Legend
- *
- * A widget to display a legend of all layers.
- *
- * **********************************************************************/
-
-Fusion.Widget.Legend = OpenLayers.Class(Fusion.Widget,  {
-
-    /**
-     * Constant: defaultLayerDWFIcon
-     * {String} The default image for DWF layer
-     */
-    defaultLayerDWFIcon: 'images/icons/legend-DWF.png',
-    
-    /**
-     * Constant: defaultLayerRasterIcon
-     * {String} The default image for Raster layer
-     */
-    defaultLayerRasterIcon: 'images/icons/legend-raster.png',
-    
-    /**
-     * Constant: defaultLayerThemeIcon
-     * {String} The default image for layers that are currently themed.
-     */
-    defaultLayerThemeIcon: 'images/icons/legend-theme.png',
-
-    /**
-     * Constant: defaultDisabledLayerIcon
-     * {String} The default image for layers that are out of scale.
-     */
-    defaultDisabledLayerIcon: 'images/icons/legend-layer.png',
-
-    /**
-     * Constant: defaultRootFolderIcon
-     * {String} The default image for the root folder
-     */
-    defaultRootFolderIcon: 'images/icons/legend-map.png',
-    
-    /**
-     * Constant: defaultLayerInfoIcon
-     * {String} The default image for layer info
-     */
-    defaultLayerInfoIcon: 'images/icons/tree_layer_info.png',
-    
-    /**
-     * Constant: defaultGroupInfoIcon
-     * {String} The default image for groupd info
-     */
-    defaultGroupInfoIcon: 'images/icons/tree_group_info.png',
-    
-    initializeWidget: function(widgetTag) {
-        // TODO: maybe it's a good idea to do a function like Fusion.Widget.BindRenderer.. for limit the code
-        // duplication if we plan to apply this pattern to others widgets
-        Fusion.addWidgetStyleSheet(widgetTag.location + 'Legend/Legend.css');
-        
-        // TODO: maybe it's a good idea to do a function like Fusion.Widget.BindRenderer.. for limit the code
-        //       duplication if we plan to apply this pattern to others widgets
-        var json = widgetTag.extension;
-        if (json.LegendRenderer)
-        {
-            var renderer = eval(json.LegendRenderer[0]);
-            if (renderer && renderer.prototype.CLASS_NAME
-                && renderer.prototype.CLASS_NAME == "Fusion.Widget.Legend.LegendRenderer") {
-                this.renderer = new renderer(this, widgetTag);
-            } else if (typeof renderer == "function") {
-                var renderFunction = renderer;
-                this.renderer = new Fusion.Widget.Legend.LegendRenderer(this);
-                this.renderer.mapLoaded = renderFunction;
-                this.renderer.mapReloaded = renderFunction;
-                this.renderer.mapLoading = false;
-            } else {
-                this.renderer = new Fusion.Widget.Legend.LegendRendererDefault(this, widgetTag);
-            }
-        } else {
-            this.renderer = new Fusion.Widget.Legend.LegendRendererDefault(this, widgetTag);
-        }
-
-        if (this.renderer.mapReloaded)
-            this.getMap().registerForEvent(Fusion.Event.MAP_RELOADED,
-                                           OpenLayers.Function.bind(this.renderer.mapReloaded, this.renderer));
-        if (this.renderer.mapLoading)
-            this.getMap().registerForEvent(Fusion.Event.MAP_LOADING,
-                                           OpenLayers.Function.bind(this.renderer.mapLoading,this.renderer));
-        if (this.renderer.mapLoaded)
-            this.getMap().registerForEvent(Fusion.Event.MAP_LOADED,
-                                           OpenLayers.Function.bind(this.renderer.mapLoaded, this.renderer));
-    }
-});
-
-/* Class: Fusion.Widget.Legend.LegendRenderer
- * This is a class designed to help users to create their own renderer
- * for customize the legend.
- */
-Fusion.Widget.Legend.LegendRenderer = OpenLayers.Class(
-{
-     /**
-     * Property: oLegend
-     * {<Fusion.Widget.Legend>} The parent widget that uses
-     *                                  the renderer.
-     */
-    oLegend: null,
-
-    /**
-     * Property: layerRoot
-     * {Groups} The groups of all layers.
-     *
-     */
-    layerRoot: null,
-
-    initialize: function(legend) {
-        this.oLegend = legend;
-        this.layerRoot = this.getMap().layerRoot;
-    },
-
-    /**
-     * Method: renderLegend
-     * Abstract method that have the main purpose to draw the legend. This method
-     * should be implemented by all concrete class.
-     *
-     */
-    renderLegend: function() {},
-    
-    /**
-     * Method: mapLoading
-     * Abstract method that handle the event: Fusion.Event.MAP_LOADING. This method
-     * is optional.
-     *
-     */
-    mapLoading: function() {},
-
-    /**
-     * Method: mapLoaded
-     * Abstract method that handle the event: Fusion.Event.MAP_LOADED. This method
-     * occur only at the first load of the map and should be implemented by all concrete class.
-     *
-     */
-    mapLoaded: function() {},
-
-     /**
-     * Method: mapReloaded
-     * Abstract method that handle the event: Fusion.Event.MAP_RELOADED. This method
-     * should be implemented by all concrete class.
-     *
-     */
-    mapReloaded: function() {},
-
-    /**
-     * Method: getMap
-     * Helper method to obtains the map.
-     *
-     * Returns:
-     * {<Fusion.Maps>} The map that uses the SelectionPanel Widget.
-     */
-    getMap: function() {
-        return this.oLegend.getMap();
-    },
-
-    CLASS_NAME: "Fusion.Widget.Legend.LegendRenderer"
-});
-
-
-/* Class: Fusion.Widget.Legend.LegendRendererDefault
- * This class provide a default legend as a collapsable tree.
- *
- */
-
-Fusion.Widget.Legend.LegendRendererDefault = OpenLayers.Class(Fusion.Widget.Legend.LegendRenderer,
-{
-    /**
-     * Property: showRootFolder
-     * {Boolean} This controls whether the tree will have a single root node that
-     * contains the name of the map as its label.  By default, the root node does
-     * not appear.  Set to "true" or "1" to make the root node appear.
-     */
-    showRootFolder: false,
-
-    /**
-     * Property: currentNode
-     * {Jx.TreeNode} The current selected node.
-     */
-    currentNode: null,
-    
-    /**
-     * Property: bIsDrawn
-     * {Boolean} Determine if the map is drawn.
-     */
-    bIsDrawn: false,
-
-    /**
-     * Property: targetFolder
-     * {Jx.TreeFolder} The current TreeFolder that the mouse will interact with.
-     */
-    targetFolder: null,
-
-    /**
-     * Property: bIncludeVisToggle
-     * {Boolean} Determine if non-visible layer must be draw in the legend.
-     */
-    bIncludeVisToggle: true,
-   
-    initialize: function(legend, widgetTag) {   
-        Fusion.Widget.Legend.LegendRenderer.prototype.initialize.apply(this, [legend]);
-
-        var json = widgetTag.extension;
-        this.imgLayerDWFIcon = json.LayerDWFIcon ? json.LayerDWFIcon[0] : this.oLegend.defaultLayerDWFIcon;
-        this.imgLayerRasterIcon = json.LayerRasterIcon ? json.LayerRasterIcon[0] : this.oLegend.defaultLayerRasterIcon;
-        this.imgLayerThemeIcon = json.LayerThemeIcon ? json.LayerThemeIcon[0] : this.oLegend.defaultLayerThemeIcon;
-        this.imgDisabledLayerIcon = json.DisabledLayerIcon ? json.DisabledLayerIcon[0] : this.oLegend.defaultDisabledLayerIcon;
-        this.imgLayerInfoIcon = json.LayerInfoIcon ? json.LayerInfoIcon[0] : this.oLegend.defaultLayerInfoIcon;
-        this.imgGroupInfoIcon = json.GroupInfoIcon ? json.GroupInfoIcon[0] : this.oLegend.defaultGroupInfoIcon;
-       
-        //not used?
-        //this.layerInfoURL = json.LayerInfoURL ? json.LayerInfoURL[0] : '';
-        this.selectedLayer = null;
-       
-        this.oTree = new Jx.Tree({parent:this.oLegend.domObj});
-       
-        this.hideInvisibleLayers = (json.HideInvisibleLayers && json.HideInvisibleLayers[0]) == 'true' ? true : false;
-        //don't show the root folder by default
-        this.showRootFolder = (json.ShowRootFolder && json.ShowRootFolder[0] == 'true') ? true:false;
-        //do show the map folder by default
-        this.showMapFolder = (json.ShowMapFolder && json.ShowMapFolder[0] == 'false') ? false:true;
-        
-        if (!this.showRootFolder) {
-            //console.log('supressing root folder');
-            this.oRoot = this.oTree;
-        } else {
-           // console.log('showing root folder');
-            var opt = {
-                label: OpenLayers.i18n('defaultMapTitle'),
-                open: true,
-                draw: this.renderFolder,
-                contextMenu: this.getContextMenu(),
-                'class':'fusionLegendFolder'
-            };
-            this.oRoot = new Jx.TreeFolder(opt);
-            this.oTree.append(this.oRoot);
-            this.oRoot.options.contextMenu.add(
-                new Jx.Menu.Item({
-                    label: OpenLayers.i18n('collapse'),
-                    onClick: OpenLayers.Function.bind(this.collapseBranch, this, this.oRoot)
-                }),
-                new Jx.Menu.Item({
-                    label: OpenLayers.i18n('expand'),
-                    onClick: OpenLayers.Function.bind(this.expandBranch, this, this.oRoot)
-                })
-            );
-        }
-        
-        this.extentsChangedWatcher = this.update.bind(this);
-    },
-    
-    getContextMenu: function() {
-        return new Jx.Menu.Context(this.name).add(
-            new Jx.Menu.Item({
-                label: OpenLayers.i18n('refresh'),
-                onClick: OpenLayers.Function.bind(this.update, this)
-            }),
-            new Jx.Menu.Item({
-                label: OpenLayers.i18n('collapseAll'),
-                onClick: OpenLayers.Function.bind(this.collapseAll, this)
-            }),
-            new Jx.Menu.Item({
-                label: OpenLayers.i18n('expandAll'),
-                onClick: OpenLayers.Function.bind(this.expandAll, this)
-            })
-        );
-    },
-    
-    expandAll: function(folder) {
-        for (var i=0; i<this.oTree.nodes.length; i++) {
-            var item = this.oTree.nodes[i];
-            if (item instanceof Jx.TreeFolder) {
-              this.recurseTree('expand', item);
-            }
-        }
-        if (this.showRootFolder) {
-          this.oRoot.expand();
-        }
-    },
-    
-    collapseAll: function(folder) {
-        for (var i=0; i<this.oTree.nodes.length; i++) {
-            var item = this.oTree.nodes[i];
-            if (item instanceof Jx.TreeFolder) {
-              this.recurseTree('collapse', item);
-            }
-        }
-        if (this.showRootFolder) {
-          this.oRoot.collapse();
-        }
-    },
-    
-    collapseBranch: function(folder) {
-        folder.collapse();
-    },
-    
-    expandBranch: function(folder) {
-        folder.expand();
-    },
-    
-  /**
-     * recursively descend the tree applying the request operation which is either 'collapse' or 'expand'
-     *
-     * @param op the operation to execute
-     * @param the folder to operate on
-     */
-    recurseTree: function(op, folder) {
-        for (var i=0; i<folder.nodes.length; i++) {
-            var item = folder.nodes[i];
-            if (item instanceof Jx.TreeFolder) {
-                this.recurseTree(op, item);
-                item[op]();
-            }
-        }
-    },
-   
-    scaleRangesLoaded: function() {
-        this.layerRoot = this.getMap().layerRoot;
-        this.renderLegend();
-    },
-    mapLoading: function() {
-        this.getMap().deregisterForEvent(Fusion.Event.MAP_EXTENTS_CHANGED, this.extentsChangedWatcher);
-        this.clear();
-    },
-   
-    mapLoaded: function() {
-        this.getMap().registerForEvent(Fusion.Event.MAP_EXTENTS_CHANGED, this.extentsChangedWatcher);
-        this.getMap().loadScaleRanges(OpenLayers.Function.bind(this.scaleRangesLoaded, this));
-    },
-    
-    mapReloaded: function() {
-        this.getMap().loadScaleRanges(OpenLayers.Function.bind(this.scaleRangesLoaded, this));
-    },
-    /**
-     * the map state has become invalid in some way (layer added, removed,
-     * ect).  For now, we just re-request the map state from the server
-     * which calls draw which recreates the entire legend from scratch
-     *
-     * TODO: more fine grained updating of the legend would be nice
-     */
-    invalidate: function() {
-        this.draw();
-    },
-   
-    /**
-     * Callback for legend XML response. Creates a list of layers and sets up event
-     * handling. Create groups if applicable.
-     * TODO: error handling
-     *
-     * @param r Object the reponse xhr object
-     */
-    renderLegend: function(r) {
-        this.bIsDrawn = false;
-        this.clear();
-
-        if (this.showRootFolder) {
-            this.oRoot.itemLabelobj.innerHTML = this.getMap().getMapTitle();
-        }
-        var startGroup = this.layerRoot;
-        if (!this.showMapFolder) {
-          startGroup = this.layerRoot.groups[0];
-        }
-        if (!startGroup.legend) {
-            startGroup.legend = {};
-            startGroup.legend.treeItem = this.oRoot;
-        }
-        for (var i=0; i<startGroup.groups.length; i++) {
-            //startGroup.groups[i].visible = true;
-            this.processMapGroup(startGroup.groups[i], this.oRoot);
-        }
-        for (var i=0; i<startGroup.layers.length; i++) {
-            this.processMapLayer(startGroup.layers[i], this.oRoot);
-        }
-        this.bIsDrawn = true;
-        this.update();
-    },
-   
-    processMapGroup: function(group, folder) {
-        if (group.displayInLegend) {
-            /* make a 'namespace' on the group object to store legend-related info */
-            group.legend = {};
-            var opt = {
-                label: group.legendLabel,
-                open: group.expandInLegend,
-                draw: this.renderFolder,
-                contextMenu: this.getContextMenu(),
-                'class':'fusionLegendFolder'
-            };
-            group.legend.treeItem = new Jx.TreeFolder(opt);
-            group.legend.treeItem.domObj.store('data', group);
-            group.legend.treeItem.options.contextMenu.add(
-                new Jx.Menu.Item({
-                    label: OpenLayers.i18n('collapse'),
-                    onClick: OpenLayers.Function.bind(this.collapseBranch, this, group.legend.treeItem)
-                }),
-                new Jx.Menu.Item({
-                    label: OpenLayers.i18n('expand'),
-                    onClick: OpenLayers.Function.bind(this.expandBranch, this, group.legend.treeItem)
-                })
-            );
-
-            folder.append(group.legend.treeItem);
-            group.legend.treeItem.checkBox.checked = group.visible?true:false;
-            OpenLayers.Event.observe(group.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, group));
-
-            var groupInfo = group.oMap.getGroupInfoUrl(group.groupName);
-            if (groupInfo) {
-                var a = document.createElement('a');
-                a.href = groupInfo;
-                if (groupInfo.indexOf('javascript:') < 0) {
-                  a.target = '_blank';
-                }
-                var img = document.createElement('img');
-                Jx.addToImgQueue({element:img, src: this.imgGroupInfoIcon});
-                img.border = 0;
-                a.appendChild(img);
-                group.legend.treeItem.domObj.insertBefore(a, group.legend.treeItem.domObj.childNodes[4]);
-            }
-            if (this.oSelectionListener) {
-                group.legend.treeItem.addEvent('click', OpenLayers.Function.bind(this.selectionChanged, this));
-            }
-            for (var i=0; i<group.groups.length; i++) {
-                this.processMapGroup(group.groups[i], group.legend.treeItem);
-            }
-            for (var i=0; i<group.layers.length; i++) {
-                this.processMapLayer(group.layers[i], group.legend.treeItem);
-            }
-        }
-    },
-   
-    processMapLayer: function(layer, folder) {
-        /* make a 'namespace' on the layer object to store legend-related info */
-        layer.legend = {};
-        layer.legend.parentItem = folder;
-        layer.legend.currentRange = null;
-        layer.registerForEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, OpenLayers.Function.bind(this.layerPropertyChanged, this));
-    },
-   
-    layerPropertyChanged: function(eventID, layer) {
-        layer.legend.treeItem.checkBox.checked = layer.isVisible();
-    },
-
-    update: function() {
-        if (this.bIsDrawn) {
-            window.setTimeout(OpenLayers.Function.bind(this._update, this), 1);
-        }
-    },
-   
-    /**
-     * update the tree when the map scale changes
-     */
-    _update: function() {
-        var map = this.getMap();
-        var currentScale = map.getScale();
-        for (var i=0; i<map.layerRoot.groups.length; i++) {
-            this.updateGroupLayers(map.layerRoot.groups[i], currentScale);
-        }
-        for (var i=0; i<map.layerRoot.layers.length; i++) {
-            this.updateLayer(map.layerRoot.layers[i], currentScale);
-        }
-    },
-   
-    /**
-     * remove the dom objects representing the legend layers and groups
-     */
-    clear: function() {
-        while (this.oRoot.nodes.length > 0) {
-            this.oRoot.remove(this.oRoot.nodes[0]);
-        }
-    },
-    
-    selectionChanged: function(o) {
-        if (this.currentNode) {
-          //console.log(this.currentNode);
-            $(this.currentNode.domObj.childNodes[1]).removeClass('jxTreeItemSelected');
-        }
-        this.currentNode = o;
-        $(this.currentNode.domObj.childNodes[1]).addClass('jxTreeItemSelected');
-       
-        var data = o.domObj.retrieve('data');
-        if (data instanceof Fusion.Layers.Group) {
-            this.getMap().setActiveLayer(null);
-        } else {
-            this.getMap().setActiveLayer(data);
-        }
-    },
-    updateGroupLayers: function(group, fScale) {
-        for (var i=0; i<group.groups.length; i++) {
-            this.updateGroupLayers(group.groups[i], fScale);
-        }
-        for (var i=0; i<group.layers.length; i++) {
-            this.updateLayer(group.layers[i], fScale);
-        }
-    },
-    updateLayer: function(layer, fScale) {
-
-        if (!layer.displayInLegend || !layer.legend) {
-            return;
-        }
-        var range = layer.getScaleRange(fScale);
-        if (range == layer.legend.currentRange && layer.legend.treeItem) {
-            return;
-        }
-       
-        layer.legend.currentRange = range;
-        if (range != null) {
-            if (range.styles.length > 1) {
-                //tree item needs to be a folder
-                if (!layer.legend.treeItem) {
-                    layer.legend.treeItem = this.createFolderItem(layer);
-                    OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
-                    layer.parentGroup.legend.treeItem.append(layer.legend.treeItem);
-                } else if (layer.legend.treeItem instanceof Jx.TreeItem) {
-                    this.clearTreeItem(layer);
-                    layer.legend.treeItem = this.createFolderItem(layer);
-                    OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
-                    layer.parentGroup.legend.treeItem.append(layer.legend.treeItem);
-                } else {
-                    while(layer.legend.treeItem.nodes.length > 0) {
-                        layer.legend.treeItem.remove(layer.legend.treeItem.nodes[0]);
-                    }
-                }
-                for (var i=0; i<range.styles.length; i++) {
-                    var item = this.createTreeItem(layer,
-                                               range.styles[i], fScale, false);
-                    layer.legend.treeItem.append(item);
-                }
-            } else {
-               
-                var style = range.styles[0];
-                if (!layer.legend.treeItem) {
-                    layer.legend.treeItem = this.createTreeItem(layer, style, fScale, this.bIncludeVisToggle);
-                    OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
-                    
-                    layer.parentGroup.legend.treeItem.append(layer.legend.treeItem);
-                } else if (layer.legend.treeItem instanceof Jx.TreeFolder) {
-                    this.clearTreeItem(layer);
-                    layer.legend.treeItem = this.createTreeItem(layer, style, fScale, this.bIncludeVisToggle);
-                    OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
-                    
-                    layer.parentGroup.legend.treeItem.append(layer.legend.treeItem);
-                } else {
-                    if (range.styles.length > 0) {
-                        layer.legend.treeItem.domImg.style.backgroundImage = 'url('+layer.oMap.getLegendImageURL(fScale, layer, range.styles[0])+')' ;
-                        $(layer.legend.treeItem.domObj).removeClass('jxDisabled');
-                    } else {
-                        $(layer.legend.treeItem.domObj).addClass('jxDisabled');
-                    }
-                }
-            }
-            layer.legend.treeItem.checkBox.checked = layer.visible?true:false;
-            if (layer.layerTypes[0] == 4 || range.styles.length > 0) {
-              layer.legend.treeItem.checkBox.disabled = false;
-            } else {
-              layer.legend.treeItem.checkBox.disabled = true;
-            }
-        } else {
-            if (this.hideInvisibleLayers) {
-                if (layer.legend.treeItem) {
-                    layer.parentGroup.legend.treeItem.remove(layer.legend.treeItem);
-                    layer.legend.treeItem = null;
-                }
-            } else {
-                var newTreeItem = this.createTreeItem(layer, null, null, this.bIncludeVisToggle);
-                OpenLayers.Event.observe(newTreeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
-                if (layer.legend.treeItem) {
-                    layer.legend.treeItem.checkBox.disabled = true;
-                    layer.parentGroup.legend.treeItem.replace(newTreeItem, layer.legend.treeItem);
-                    layer.legend.treeItem.finalize();
-                } else {
-                    layer.parentGroup.legend.treeItem.append(newTreeItem);
-                }
-                layer.legend.treeItem = newTreeItem;
-            }
-        }
-        if (layer.legend.treeItem) {
-            layer.legend.treeItem.domObj.store('data', layer);
-        }
-    },
-    
-    createFolderItem: function(layer) {
-        var opt = {
-            label: layer.legendLabel == '' ? '&nbsp;' : layer.legendLabel,
-            isOpen: layer.expandInLegend,
-            draw: this.renderFolder,
-            'class':'fusionLegendItemCheckbox',
-            contextMenu: this.getContextMenu(),
-            // image overrides
-            image: this.imgLayerThemeIcon
-        };
-        var folder = new Jx.TreeFolder(opt);
-        folder.options.contextMenu.add(
-            new Jx.Menu.Item({
-                label: OpenLayers.i18n('collapse'),
-                onClick: OpenLayers.Function.bind(this.collapseBranch, this, folder)
-            }),
-            new Jx.Menu.Item({
-                label: OpenLayers.i18n('expand'),
-                onClick: OpenLayers.Function.bind(this.expandBranch, this, folder)
-            })
-        );
-        
-        
-        var layerInfo = layer.oMap.getLayerInfoUrl(layer.layerName);
-        if (layerInfo) {
-            var a = document.createElement('a');
-            a.href = layerInfo;
-            if (layerInfo.indexOf('javascript:') < 0) {
-              a.target = '_blank';
-            }
-            var img = document.createElement('img');
-            Jx.addToImgQueue({element:img, src:this.imgLayerInfoIcon});
-            img.border = 0;
-            a.appendChild(img);
-            folder.domObj.insertBefore(a, folder.domObj.childNodes[4]);
-        }
-        folder.addEvent('click', OpenLayers.Function.bind(this.selectionChanged, this));
-       
-        return folder;
-    },
-    createTreeItem: function(layer, style, scale, bCheckBox) {
-        var opt = {};
-        opt.statusIsDefault = layer.statusDefault;
-
-        if (bCheckBox ) {
-            opt.label = layer.legendLabel == '' ? '&nbsp;' : layer.legendLabel;
-            opt.draw = this.renderItemCheckBox;
-        } else {
-            opt.label = style.legendLabel == '' ? '&nbsp;' : style.legendLabel;
-            opt.draw = this.renderItem;
-        }
-        if (layer.layerTypes[0] == 4) {
-            if (style && style.staticIcon == Fusion.Constant.LAYER_DWF_TYPE) {
-                opt.image = this.imgLayerDWFIcon;
-            } else {
-                opt.image = this.imgLayerRasterIcon;
-            }
-        } else if (!style) {
-            opt.image = this.imgDisabledLayerIcon;
-            opt.enabled = false;
-        } else {
-            opt.image = layer.oMap.getLegendImageURL(scale, layer, style);
-        }
-        opt.contextMenu = this.getContextMenu(); 
-
-        var item = new Jx.TreeItem(opt);
-        if (bCheckBox) {
-            //item.domObj.insertBefore(layer.legend.checkBox, item.domObj.childNodes[1]);
-            /* only need to add layer info if it has a check box too */
-            var layerInfo = layer.oMap.getLayerInfoUrl(layer.layerName);
-            if (layerInfo) {
-                var a = document.createElement('a');
-                a.href = layerInfo;
-                if (layerInfo.indexOf('javascript:') < 0) {
-                  a.target = '_blank';
-                }
-                var img = document.createElement('img');
-                Jx.addToImgQueue({element:img, src: this.imgLayerInfoIcon});
-                img.border = 0;
-                a.appendChild(img);
-                item.domObj.insertBefore(a, item.domObj.childNodes[4]);
-            }
-        }
-
-        item.addEvent('click', OpenLayers.Function.bind(this.selectionChanged, this));
-       
-        return item;
-    },
-    clearTreeItem: function(layer) {
-        if (layer.legend.treeItem && layer.legend.treeItem.owner) {
-            layer.legend.treeItem.domObj.store('data', null);
-            layer.legend.treeItem.owner.remove(layer.legend.treeItem);
-            layer.legend.treeItem.finalize();
-            layer.legend.treeItem = null;
-        }
-    },
-    stateChanged: function(obj, event) {
-        if (obj.legend && obj.legend.treeItem.checkBox) {
-            if (obj.legend.treeItem.checkBox.checked) {
-                obj.show();
-            } else {
-                obj.hide();
-            }
-        }
-        OpenLayers.Event.stop(event, true);
-    },
-    
-    renderFolder: function() {
-        var domA = new Element('a',{
-            'class':this.options['class'],
-            href:'javascript:void(0)',
-            events: {
-                click: this.selected.bindWithEvent(this),
-                dblclick: this.selected.bindWithEvent(this),
-                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
-            }
-        });
-        
-        this.checkBox = document.createElement('input');
-        this.checkBox.type = 'checkbox';
-        
-        this.domImg = document.createElement('img');
-        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
-        this.domImg.src = Jx.aPixel.src;
-        
-        if (this.options.image) {
-            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
-        }
-
-        var domLabel = new Element('span',{
-            'class': 'fusionLegendLabel',
-            html: this.options.label
-        });
-        
-        domA.appendChild(this.checkBox);
-        domA.appendChild(this.domImg);
-        domA.appendChild(domLabel);
-
-        this.itemLabelobj = domA;
-
-        return domA;
-        
-    },
-    
-    renderItem: function() {
-
-        var domA = new Element('a', {
-            'class': 'fusionLegendItem',
-            href: 'javascript:void(0)',
-            events: {
-                click: this.selected.bindWithEvent(this),
-                dblclick: this.selected.bindWithEvent(this),
-                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
-            }
-        });
-        
-        
-        this.domImg = document.createElement('img');
-        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
-        this.domImg.src = Jx.aPixel.src;
-        
-        if (this.options.image) {
-            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
-        }
-        
-        var domLabel = new Element('span',{
-            'class': 'fusionLegendLabel',
-            html: this.options.label
-        });
-        
-        domA.appendChild(this.domImg);
-        domA.appendChild(domLabel);
-        this.itemLabelobj = domA;
-        
-        return domA;
-    },
-    
-    renderItemCheckBox: function() {
-        var domA = new Element('a', {
-            'class': 'fusionLegendItemCheckbox',
-            'href':'javascript:void(0);',
-            events: {
-                click: this.selected.bindWithEvent(this),
-                dblclick: this.selected.bindWithEvent(this),
-                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
-            }
-        });
-        
-        this.checkBox = document.createElement('input');
-        this.checkBox.type = 'checkbox';
-
-        /* layer is set to "status default" set checkbox to checked , disabled , read only*/
-        if(this.options.statusIsDefault){
-            this.checkBox.checked = true;
-            this.checkBox.disabled = true;
-            this.checkBox.readOnly = true;
-        }
-        
-        this.domImg = document.createElement('img');
-        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
-        this.domImg.src = Jx.aPixel.src;
-        
-        if (this.options.image) {
-            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
-        }
-        
-        var domLabel = new Element('span',{
-            'class': 'fusionLegendLabel',
-            html: this.options.label
-        });
-        
-        
-        domA.appendChild(this.checkBox);
-        domA.appendChild(this.domImg);
-        domA.appendChild(domLabel);
-        this.itemLabelobj = domA;
-
-        return domA;
-    }
-
-});
+/**
+ * Fusion.Widget.Legend
+ *
+ * $Id$
+ *
+ * Copyright (c) 2007, DM Solutions Group Inc.
+ * 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.
+ */
+
+ /********************************************************************
+ * Class: Fusion.Widget.Legend
+ *
+ * A widget to display a legend of all layers.
+ *
+ * **********************************************************************/
+
+Fusion.Widget.Legend = OpenLayers.Class(Fusion.Widget,  {
+
+    /**
+     * Constant: defaultLayerDWFIcon
+     * {String} The default image for DWF layer
+     */
+    defaultLayerDWFIcon: 'images/icons/legend-DWF.png',
+    
+    /**
+     * Constant: defaultLayerRasterIcon
+     * {String} The default image for Raster layer
+     */
+    defaultLayerRasterIcon: 'images/icons/legend-raster.png',
+    
+    /**
+     * Constant: defaultLayerThemeIcon
+     * {String} The default image for layers that are currently themed.
+     */
+    defaultLayerThemeIcon: 'images/icons/legend-theme.png',
+
+    /**
+     * Constant: defaultDisabledLayerIcon
+     * {String} The default image for layers that are out of scale.
+     */
+    defaultDisabledLayerIcon: 'images/icons/legend-layer.png',
+
+    /**
+     * Constant: defaultRootFolderIcon
+     * {String} The default image for the root folder
+     */
+    defaultRootFolderIcon: 'images/icons/legend-map.png',
+    
+    /**
+     * Constant: defaultLayerInfoIcon
+     * {String} The default image for layer info
+     */
+    defaultLayerInfoIcon: 'images/icons/tree_layer_info.png',
+    
+    /**
+     * Constant: defaultGroupInfoIcon
+     * {String} The default image for groupd info
+     */
+    defaultGroupInfoIcon: 'images/icons/tree_group_info.png',
+    
+    initializeWidget: function(widgetTag) {
+        // TODO: maybe it's a good idea to do a function like Fusion.Widget.BindRenderer.. for limit the code
+        // duplication if we plan to apply this pattern to others widgets
+        Fusion.addWidgetStyleSheet(widgetTag.location + 'Legend/Legend.css');
+        
+        // TODO: maybe it's a good idea to do a function like Fusion.Widget.BindRenderer.. for limit the code
+        //       duplication if we plan to apply this pattern to others widgets
+        var json = widgetTag.extension;
+        if (json.LegendRenderer)
+        {
+            var renderer = eval(json.LegendRenderer[0]);
+            if (renderer && renderer.prototype.CLASS_NAME
+                && renderer.prototype.CLASS_NAME == "Fusion.Widget.Legend.LegendRenderer") {
+                this.renderer = new renderer(this, widgetTag);
+            } else if (typeof renderer == "function") {
+                var renderFunction = renderer;
+                this.renderer = new Fusion.Widget.Legend.LegendRenderer(this);
+                this.renderer.mapLoaded = renderFunction;
+                this.renderer.mapReloaded = renderFunction;
+                this.renderer.mapLoading = false;
+            } else {
+                this.renderer = new Fusion.Widget.Legend.LegendRendererDefault(this, widgetTag);
+            }
+        } else {
+            this.renderer = new Fusion.Widget.Legend.LegendRendererDefault(this, widgetTag);
+        }
+
+        if (this.renderer.mapReloaded)
+            this.getMap().registerForEvent(Fusion.Event.MAP_RELOADED,
+                                           OpenLayers.Function.bind(this.renderer.mapReloaded, this.renderer));
+        if (this.renderer.mapLoading)
+            this.getMap().registerForEvent(Fusion.Event.MAP_LOADING,
+                                           OpenLayers.Function.bind(this.renderer.mapLoading,this.renderer));
+        if (this.renderer.mapLoaded)
+            this.getMap().registerForEvent(Fusion.Event.MAP_LOADED,
+                                           OpenLayers.Function.bind(this.renderer.mapLoaded, this.renderer));
+    }
+});
+
+/* Class: Fusion.Widget.Legend.LegendRenderer
+ * This is a class designed to help users to create their own renderer
+ * for customize the legend.
+ */
+Fusion.Widget.Legend.LegendRenderer = OpenLayers.Class(
+{
+     /**
+     * Property: oLegend
+     * {<Fusion.Widget.Legend>} The parent widget that uses
+     *                                  the renderer.
+     */
+    oLegend: null,
+
+    /**
+     * Property: layerRoot
+     * {Groups} The groups of all layers.
+     *
+     */
+    layerRoot: null,
+
+    initialize: function(legend) {
+        this.oLegend = legend;
+        this.layerRoot = this.getMap().layerRoot;
+    },
+
+    /**
+     * Method: renderLegend
+     * Abstract method that have the main purpose to draw the legend. This method
+     * should be implemented by all concrete class.
+     *
+     */
+    renderLegend: function() {},
+    
+    /**defaultDisabledLayerIcon
+     * Method: mapLoading
+     * Abstract method that handle the event: Fusion.Event.MAP_LOADING. This method
+     * is optional.
+     *
+     */
+    mapLoading: function() {},
+
+    /**
+     * Method: mapLoaded
+     * Abstract method that handle the event: Fusion.Event.MAP_LOADED. This method
+     * occur only at the first load of the map and should be implemented by all concrete class.
+     *
+     */
+    mapLoaded: function() {},
+
+     /**
+     * Method: mapReloaded
+     * Abstract method that handle the event: Fusion.Event.MAP_RELOADED. This method
+     * should be implemented by all concrete class.
+     *
+     */
+    mapReloaded: function() {},
+
+    /**
+     * Method: getMap
+     * Helper method to obtains the map.
+     *
+     * Returns:
+     * {<Fusion.Maps>} The map that uses the SelectionPanel Widget.
+     */
+    getMap: function() {
+        return this.oLegend.getMap();
+    },
+
+    CLASS_NAME: "Fusion.Widget.Legend.LegendRenderer"
+});
+
+
+/* Class: Fusion.Widget.Legend.LegendRendererDefault
+ * This class provide a default legend as a collapsable tree.
+ *
+ */
+
+Fusion.Widget.Legend.LegendRendererDefault = OpenLayers.Class(Fusion.Widget.Legend.LegendRenderer,
+{
+    /**
+     * Property: showRootFolder
+     * {Boolean} This controls whether the tree will have a single root node that
+     * contains the name of the map as its label.  By default, the root node does
+     * not appear.  Set to "true" or "1" to make the root node appear.
+     */
+    showRootFolder: false,
+
+    /**
+     * Property: currentNode
+     * {Jx.TreeNode} The current selected node.
+     */
+    currentNode: null,
+    
+    /**
+     * Property: bIsDrawn
+     * {Boolean} Determine if the map is drawn.
+     */
+    bIsDrawn: false,
+
+    /**
+     * Property: targetFolder
+     * {Jx.TreeFolder} The current TreeFolder that the mouse will interact with.
+     */
+    targetFolder: null,
+
+    /**
+     * Property: bIncludeVisToggle
+     * {Boolean} Determine if non-visible layer must be draw in the legend.
+     */
+    bIncludeVisToggle: true,
+   
+    initialize: function(legend, widgetTag) {   
+        Fusion.Widget.Legend.LegendRenderer.prototype.initialize.apply(this, [legend]);
+
+        var json = widgetTag.extension;
+        this.imgLayerDWFIcon = json.LayerDWFIcon ? json.LayerDWFIcon[0] : this.oLegend.defaultLayerDWFIcon;
+        this.imgLayerRasterIcon = json.LayerRasterIcon ? json.LayerRasterIcon[0] : this.oLegend.defaultLayerRasterIcon;
+        this.imgLayerThemeIcon = json.LayerThemeIcon ? json.LayerThemeIcon[0] : this.oLegend.defaultLayerThemeIcon;
+        this.imgDisabledLayerIcon = json.DisabledLayerIcon ? json.DisabledLayerIcon[0] : this.oLegend.defaultDisabledLayerIcon;
+        this.imgLayerInfoIcon = json.LayerInfoIcon ? json.LayerInfoIcon[0] : this.oLegend.defaultLayerInfoIcon;
+        this.imgGroupInfoIcon = json.GroupInfoIcon ? json.GroupInfoIcon[0] : this.oLegend.defaultGroupInfoIcon;
+       
+        //not used?
+        //this.layerInfoURL = json.LayerInfoURL ? json.LayerInfoURL[0] : '';
+        this.selectedLayer = null;
+       
+        this.oTree = new Jx.Tree({parent:this.oLegend.domObj});
+       
+        this.hideInvisibleLayers = (json.HideInvisibleLayers && json.HideInvisibleLayers[0]) == 'true' ? true : false;
+        //don't show the root folder by default
+        this.showRootFolder = (json.ShowRootFolder && json.ShowRootFolder[0] == 'true') ? true:false;
+        //do show the map folder by default
+        this.showMapFolder = (json.ShowMapFolder && json.ShowMapFolder[0] == 'false') ? false:true;
+        
+        if (!this.showRootFolder) {
+            //console.log('supressing root folder');
+            this.oRoot = this.oTree;
+        } else {
+           // console.log('showing root folder');
+            var opt = {
+                label: OpenLayers.i18n('defaultMapTitle'),
+                open: true,
+                draw: this.renderFolderCheckbox,
+                contextMenu: this.getContextMenu(),
+                'class':'fusionLegendFolder'
+            };
+            this.oRoot = new Jx.TreeFolder(opt);
+            this.oTree.append(this.oRoot);
+            this.oRoot.options.contextMenu.add(
+                new Jx.Menu.Item({
+                    label: OpenLayers.i18n('collapse'),
+                    onClick: OpenLayers.Function.bind(this.collapseBranch, this, this.oRoot)
+                }),
+                new Jx.Menu.Item({
+                    label: OpenLayers.i18n('expand'),
+                    onClick: OpenLayers.Function.bind(this.expandBranch, this, this.oRoot)
+                })
+            );
+        }
+        
+        this.extentsChangedWatcher = this.update.bind(this);
+    },
+    
+    getContextMenu: function() {
+        return new Jx.Menu.Context(this.name).add(
+            new Jx.Menu.Item({
+                label: OpenLayers.i18n('refresh'),
+                onClick: OpenLayers.Function.bind(this.update, this)
+            }),
+            new Jx.Menu.Item({
+                label: OpenLayers.i18n('collapseAll'),
+                onClick: OpenLayers.Function.bind(this.collapseAll, this)
+            }),
+            new Jx.Menu.Item({
+                label: OpenLayers.i18n('expandAll'),
+                onClick: OpenLayers.Function.bind(this.expandAll, this)
+            })
+        );
+    },
+    
+    expandAll: function(folder) {
+        for (var i=0; i<this.oTree.nodes.length; i++) {
+            var item = this.oTree.nodes[i];
+            if (item instanceof Jx.TreeFolder) {
+              this.recurseTree('expand', item);
+            }
+        }
+        if (this.showRootFolder) {
+          this.oRoot.expand();
+        }
+    },
+    
+    collapseAll: function(folder) {
+        for (var i=0; i<this.oTree.nodes.length; i++) {
+            var item = this.oTree.nodes[i];
+            if (item instanceof Jx.TreeFolder) {
+              this.recurseTree('collapse', item);
+            }
+        }
+        if (this.showRootFolder) {
+          this.oRoot.collapse();
+        }
+    },
+    
+    collapseBranch: function(folder) {
+        folder.collapse();
+    },
+    
+    expandBranch: function(folder) {
+        folder.expand();
+    },
+    
+  /**
+     * recursively descend the tree applying the request operation which is either 'collapse' or 'expand'
+     *
+     * @param op the operation to execute
+     * @param the folder to operate on
+     */
+    recurseTree: function(op, folder) {
+        for (var i=0; i<folder.nodes.length; i++) {
+            var item = folder.nodes[i];
+            if (item instanceof Jx.TreeFolder) {
+                this.recurseTree(op, item);
+                item[op]();
+            }
+        }
+    },
+   
+    scaleRangesLoaded: function() {
+        this.layerRoot = this.getMap().layerRoot;
+        this.renderLegend();
+    },
+    mapLoading: function() {
+        this.getMap().deregisterForEvent(Fusion.Event.MAP_EXTENTS_CHANGED, this.extentsChangedWatcher);
+        this.clear();
+    },
+   
+    mapLoaded: function() {
+        this.getMap().registerForEvent(Fusion.Event.MAP_EXTENTS_CHANGED, this.extentsChangedWatcher);
+        this.getMap().loadScaleRanges(OpenLayers.Function.bind(this.scaleRangesLoaded, this));
+    },
+    
+    mapReloaded: function() {
+        this.getMap().loadScaleRanges(OpenLayers.Function.bind(this.scaleRangesLoaded, this));
+    },
+    /**
+     * the map state has become invalid in some way (layer added, removed,
+     * ect).  For now, we just re-request the map state from the server
+     * which calls draw which recreates the entire legend from scratch
+     *
+     * TODO: more fine grained updating of the legend would be nice
+     */
+    invalidate: function() {
+        this.draw();
+    },
+   
+    /**
+     * Callback for legend XML response. Creates a list of layers and sets up event
+     * handling. Create groups if applicable.
+     * TODO: error handling
+     *
+     * @param r Object the reponse xhr object
+     */
+    /*renderLegend: function(r) {
+        this.bIsDrawn = false;
+        this.clear();
+
+        if (this.showRootFolder) {
+            this.oRoot.itemLabelobj.innerHTML = this.getMap().getMapTitle();
+        }
+        var startGroup = this.layerRoot;
+        if (!this.showMapFolder) {
+          startGroup = this.layerRoot.groups[0];
+        }
+        if (!startGroup.legend) {
+            startGroup.legend = {};
+            startGroup.legend.treeItem = this.oRoot;
+        }
+        for (var i=0; i<startGroup.groups.length; i++) {
+            //startGroup.groups[i].visible = true;
+            this.processMapGroup(startGroup.groups[i], this.oRoot);
+        }
+        for (var i=0; i<startGroup.layers.length; i++) {
+            this.processMapLayer(startGroup.layers[i], this.oRoot);
+        }
+        this.bIsDrawn = true;
+        this.update();
+    },*/
+    renderLegend: function(r) {
+        this.bIsDrawn = false;
+        this.clear();
+
+        if (this.showRootFolder) {
+            this.oRoot.itemLabelobj.innerHTML = this.getMap().getMapTitle();
+        }
+
+        if (this.showMapFolder) {
+        this.renderGroup(this.layerRoot);
+        } else {
+        if (this.layerRoot.groups.length > 0) {
+            for (var i = 0; i < this.layerRoot.groups.length; i++)
+                this.renderGroup(this.layerRoot.groups[i]);
+        } else {
+            for (var i = 0; i < group.layers.length; i++)
+                this.processMapLayer(group.layers[i], this.oRoot);
+        }
+        }
+
+        this.bIsDrawn = true;
+        this.update();
+    },
+    
+    renderGroup: function(group) {
+        if (!group.legend) {
+            group.legend = {};
+            group.legend.treeItem = this.oRoot;
+        }
+        for (var i = 0; i < group.groups.length; i++) {
+            this.processMapGroup(group.groups[i], this.oRoot);
+        }
+        for (var i = 0; i < group.layers.length; i++) {
+            this.processMapLayer(group.layers[i], this.oRoot);
+        }
+    },
+   
+    processMapGroup: function(group, folder) {
+        if (group.displayInLegend) {
+            /* make a 'namespace' on the group object to store legend-related info */
+            group.legend = {};
+            var opt = {
+                label: group.legendLabel,
+                open: group.expandInLegend,
+                draw: this.renderFolderCheckbox,
+                contextMenu: this.getContextMenu(),
+                'class':'fusionLegendFolder'
+            };
+            group.legend.treeItem = new Jx.TreeFolder(opt);
+            group.legend.treeItem.domObj.store('data', group);
+            group.legend.treeItem.options.contextMenu.add(
+                new Jx.Menu.Item({
+                    label: OpenLayers.i18n('collapse'),
+                    onClick: OpenLayers.Function.bind(this.collapseBranch, this, group.legend.treeItem)
+                }),
+                new Jx.Menu.Item({
+                    label: OpenLayers.i18n('expand'),
+                    onClick: OpenLayers.Function.bind(this.expandBranch, this, group.legend.treeItem)
+                })
+            );
+
+            folder.append(group.legend.treeItem);
+            if(group.legend.treeItem.checkBox)
+            {
+                group.legend.treeItem.checkBox.checked = group.visible?true:false;
+                OpenLayers.Event.observe(group.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, group));
+            }
+
+            var groupInfo = group.oMap.getGroupInfoUrl(group.groupName);
+            if (groupInfo) {
+                var a = document.createElement('a');
+                a.href = groupInfo;
+                if (groupInfo.indexOf('javascript:') < 0) {
+                  a.target = '_blank';
+                }
+                var img = document.createElement('img');
+                Jx.addToImgQueue({element:img, src: this.imgGroupInfoIcon});
+                img.border = 0;
+                a.appendChild(img);
+                group.legend.treeItem.domObj.insertBefore(a, group.legend.treeItem.domObj.childNodes[4]);
+            }
+            if (this.oSelectionListener) {
+                group.legend.treeItem.addEvent('click', OpenLayers.Function.bind(this.selectionChanged, this));
+            }
+            for (var i=0; i<group.groups.length; i++) {
+                this.processMapGroup(group.groups[i], group.legend.treeItem);
+            }
+            for (var i=0; i<group.layers.length; i++) {
+                this.processMapLayer(group.layers[i], group.legend.treeItem);
+            }
+        }
+    },
+   
+    processMapLayer: function(layer, folder) {
+        /* make a 'namespace' on the layer object to store legend-related info */
+        layer.legend = {};
+        layer.legend.parentItem = folder;
+        layer.legend.currentRange = null;
+        layer.oMap.registerForEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, OpenLayers.Function.bind(this.layerPropertyChanged, this));
+    },
+   
+    layerPropertyChanged: function(eventID, layer) {
+        if(layer.legend.treeItem.checkBox)
+        {
+            layer.legend.treeItem.checkBox.checked = layer.isVisible();
+        }
+    },
+
+    update: function() {
+        if (this.bIsDrawn) {
+            window.setTimeout(OpenLayers.Function.bind(this._update, this), 1);
+        }
+    },
+   
+    /**
+     * update the tree when the map scale changes
+     */
+    _update: function() {
+        var map = this.getMap();
+        var currentScale = map.getScale();
+        for (var i=0; i<map.layerRoot.groups.length; i++) {
+            this.updateGroupLayers(map.layerRoot.groups[i], currentScale);
+        }
+        for (var i=0; i<map.layerRoot.layers.length; i++) {
+            this.updateLayer(map.layerRoot.layers[i], currentScale);
+        }
+    },
+   
+    /**
+     * remove the dom objects representing the legend layers and groups
+     */
+    clear: function() {
+        while (this.oRoot.nodes.length > 0) {
+            this.oRoot.remove(this.oRoot.nodes[0]);
+        }
+    },
+    
+    selectionChanged: function(o) {
+        if (this.currentNode) {
+          //console.log(this.currentNode);
+            $(this.currentNode.domObj.childNodes[1]).removeClass('jxTreeItemSelected');
+        }
+        this.currentNode = o;
+        $(this.currentNode.domObj.childNodes[1]).addClass('jxTreeItemSelected');
+       
+        var data = o.domObj.retrieve('data');
+        if (data instanceof Fusion.Layers.Group) {
+            this.getMap().setActiveLayer(null);
+        } else {
+            this.getMap().setActiveLayer(data);
+        }
+    },
+    updateGroupLayers: function(group, fScale) {
+        for (var i=0; i<group.groups.length; i++) {
+            this.updateGroupLayers(group.groups[i], fScale);
+        }
+        for (var i=0; i<group.layers.length; i++) {
+            this.updateLayer(group.layers[i], fScale);
+        }
+    },
+    updateLayer: function(layer, fScale) {
+
+        var checkbox = layer.isBaseMapLayer ? false : this.bIncludeVisToggle;
+        if (!layer.displayInLegend || !layer.legend) {
+            return;
+        }
+        var range = layer.getScaleRange(fScale);
+        if (range == layer.legend.currentRange && layer.legend.treeItem) {
+            return;
+        }
+       
+        layer.legend.currentRange = range;
+        if (range != null) {
+            if (range.styles.length > 1) {
+                //tree item needs to be a folder
+                if (!layer.legend.treeItem) {
+                    layer.legend.treeItem = this.createFolderItem(layer, checkbox);
+                    if(layer.legend.treeItem.checkBox)
+                    {
+                        OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
+                    }
+                    layer.parentGroup.legend.treeItem.append(layer.legend.treeItem);
+                } else if (layer.legend.treeItem instanceof Jx.TreeItem) {
+                    var insertAt = this.clearTreeItem(layer);
+                    layer.legend.treeItem = this.createFolderItem(layer, checkbox);
+                    if(layer.legend.treeItem.checkBox)
+                    {
+                        OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
+                    }
+                    layer.parentGroup.legend.treeItem.insert(layer.legend.treeItem, insertAt);
+                } else {
+                    while(layer.legend.treeItem.nodes.length > 0) {
+                        layer.legend.treeItem.remove(layer.legend.treeItem.nodes[0]);
+                    }
+                }
+                for (var i=0; i<range.styles.length; i++) {
+                    var item = this.createTreeItem(layer, range.styles[i], fScale, false);
+                    layer.legend.treeItem.append(item);
+                }
+            } else {
+               
+                var style = range.styles[0];
+                if (style && !style.legendLabel) {
+                  style.legendLabel = layer.legendLabel;
+                }
+                if (!layer.legend.treeItem) {
+                    layer.legend.treeItem = this.createTreeItem(layer, style, fScale, checkbox);
+                    if (checkbox) {
+                      OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
+                    }
+                    
+                    layer.parentGroup.legend.treeItem.append(layer.legend.treeItem);
+                } else if (layer.legend.treeItem instanceof Jx.TreeFolder) {
+                    var insertAt = this.clearTreeItem(layer);
+                    layer.legend.treeItem = this.createTreeItem(layer, style, fScale, checkbox);
+                    if (checkbox) {
+                      OpenLayers.Event.observe(layer.legend.treeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
+                    }
+                    
+                    layer.parentGroup.legend.treeItem.insert(layer.legend.treeItem, insertAt);
+                } else {
+                    if (range.styles.length > 0) {
+                        layer.legend.treeItem.domImg.style.backgroundImage = 'url('+layer.oMap.getLegendImageURL(fScale, layer, range.styles[0])+')';
+                        layer.legend.treeItem.domImg.style.backgroundPosition = '0px 0px';
+                        $(layer.legend.treeItem.domObj).removeClass('jxDisabled');
+                    } else {
+                        $(layer.legend.treeItem.domObj).addClass('jxDisabled');
+                    }
+                }
+            }
+            if (checkbox) {
+              layer.legend.treeItem.checkBox.checked = layer.visible?true:false;
+              if (layer.layerTypes[0] == 4 || range.styles.length > 0) {
+                layer.legend.treeItem.checkBox.disabled = false;
+              } else {
+                layer.legend.treeItem.checkBox.disabled = true;
+              }
+            }
+        } else {
+            if (this.hideInvisibleLayers) {
+                if (layer.legend.treeItem) {
+                    layer.parentGroup.legend.treeItem.remove(layer.legend.treeItem);
+                    layer.legend.treeItem = null;
+                }
+            } else {
+              var newTreeItem = this.createTreeItem(layer, {legendLabel: layer.legendLabel}, null, checkbox);
+                if (checkbox) {
+                  OpenLayers.Event.observe(newTreeItem.checkBox, 'click', OpenLayers.Function.bind(this.stateChanged, this, layer));
+                }
+                if (layer.legend.treeItem) {
+                    if (checkbox) layer.legend.treeItem.checkBox.disabled = true;
+                    layer.parentGroup.legend.treeItem.replace(newTreeItem, layer.legend.treeItem);
+                    layer.legend.treeItem.finalize();
+                } else {
+                    layer.parentGroup.legend.treeItem.append(newTreeItem);
+                }
+                layer.legend.treeItem = newTreeItem;
+            }
+        }
+        if (layer.legend.treeItem) {
+            layer.legend.treeItem.domObj.store('data', layer);
+        }
+    },
+    
+    createFolderItem: function(layer, hasCheckbox) {
+        var opt = {
+            label: layer.legendLabel == '' ? '&nbsp;' : layer.legendLabel,
+            open: layer.expandInLegend,
+            draw: hasCheckbox ? this.renderFolderCheckbox : this.renderFolder,
+            'class':'fusionLegendItemCheckbox',
+            contextMenu: this.getContextMenu(),
+            // image overrides
+            image: this.imgLayerThemeIcon
+        };
+        var folder = new Jx.TreeFolder(opt);
+        folder.options.contextMenu.add(
+            new Jx.Menu.Item({
+                label: OpenLayers.i18n('collapse'),
+                onClick: OpenLayers.Function.bind(this.collapseBranch, this, folder)
+            }),
+            new Jx.Menu.Item({
+                label: OpenLayers.i18n('expand'),
+                onClick: OpenLayers.Function.bind(this.expandBranch, this, folder)
+            })
+        );
+        
+        
+        var layerInfo = layer.oMap.getLayerInfoUrl(layer.layerName);
+        if (layerInfo) {
+            var a = document.createElement('a');
+            a.href = layerInfo;
+            if (layerInfo.indexOf('javascript:') < 0) {
+              a.target = '_blank';
+            }
+            var img = document.createElement('img');
+            Jx.addToImgQueue({element:img, src:this.imgLayerInfoIcon});
+            img.border = 0;
+            a.appendChild(img);
+            folder.domObj.insertBefore(a, folder.domObj.childNodes[4]);
+        }
+        folder.addEvent('click', OpenLayers.Function.bind(this.selectionChanged, this));
+       
+        return folder;
+    },
+    createTreeItem: function(layer, style, scale, bCheckBox) {
+        var opt = {};
+        opt.statusIsDefault = layer.statusDefault;
+
+        if (bCheckBox ) {
+            opt.label = layer.legendLabel == '' ? '&nbsp;' : layer.legendLabel;
+            opt.draw = this.renderItemCheckBox;
+        } else {
+            opt.label = style.legendLabel == '' ? '&nbsp;' : style.legendLabel;
+            opt.draw = this.renderItem;
+        }
+        
+        if (!style) {
+            opt.image = this.imgDisabledLayerIcon;
+            opt.enabled = false;
+        } else {
+            if(style.iconOpt && style.iconOpt.url){
+                opt.image = style.iconOpt.url;
+            }else{
+                opt.image = layer.oMap.getLegendImageURL(scale, layer, style);
+            }
+        }
+        // MapGuide DWF and Raster layer
+        if (layer.layerTypes[0] == 4) {
+            if (style && style.staticIcon == Fusion.Constant.LAYER_DWF_TYPE) {
+                opt.image = this.imgLayerDWFIcon;
+            } else {
+                opt.image = this.imgLayerRasterIcon;
+            }
+            opt.enabled = true;
+        }
+        opt.contextMenu = this.getContextMenu();
+
+        var item = new Jx.TreeItem(opt);
+        if (style && style.iconOpt && style.iconX >= 0 && style.iconY >= 0) {
+            item.domImg;
+            item.domImg.style.backgroundImage = 'url('+opt.image+')';
+            item.domImg.src = Jx.aPixel.src;
+            item.domImg.style.backgroundPosition = (-1*style.iconX) + 'px ' + (-1*style.iconY) + 'px';
+            if (style.iconOpt.width) {
+                item.domImg.style.width = style.iconOpt.width + 'px';
+            }
+            if (style.iconOpt.height) {
+                item.domImg.style.height = style.iconOpt.height + 'px';
+            }
+        }
+        
+        if (bCheckBox) {
+            //item.domObj.insertBefore(layer.legend.checkBox, item.domObj.childNodes[1]);
+            /* only need to add layer info if it has a check box too */
+            var layerInfo = layer.oMap.getLayerInfoUrl(layer.layerName);
+            if (layerInfo) {
+                var a = document.createElement('a');
+                a.href = layerInfo;
+                if (layerInfo.indexOf('javascript:') < 0) {
+                  a.target = '_blank';
+                }
+                var img = document.createElement('img');
+                Jx.addToImgQueue({element:img, src: this.imgLayerInfoIcon});
+                img.border = 0;
+                a.appendChild(img);
+                item.domObj.insertBefore(a, item.domObj.childNodes[4]);
+            }
+        }
+
+        item.addEvent('click', OpenLayers.Function.bind(this.selectionChanged, this));
+       
+        return item;
+    },
+    clearTreeItem: function(layer) {
+        var prevSibling = null;
+        if (layer.legend.treeItem && layer.legend.treeItem.owner) {
+            prevSibling = layer.legend.treeItem.domObj.previousSibling;
+            layer.legend.treeItem.domObj.store('data', null);
+            layer.legend.treeItem.owner.remove(layer.legend.treeItem);
+            layer.legend.treeItem.finalize();
+            layer.legend.treeItem = null;
+        }
+        return prevSibling;
+    },
+    stateChanged: function(obj, event) {
+        if (obj.legend && obj.legend.treeItem.checkBox) {
+            if (obj.legend.treeItem.checkBox.checked) {
+                obj.show();
+            } else {
+                obj.hide();
+            }
+        }
+        OpenLayers.Event.stop(event, true);
+    },
+    
+    renderFolder: function() {
+        var domA = new Element('a',{
+            'class':this.options['class'],
+            href:'javascript:void(0)',
+            events: {
+                click: this.selected.bindWithEvent(this),
+                dblclick: this.selected.bindWithEvent(this),
+                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
+            }
+        });
+        
+        
+        this.domImg = document.createElement('img');
+        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
+        this.domImg.src = Jx.aPixel.src;
+        
+        if (this.options.image) {
+            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
+        }
+
+        var domLabel = new Element('span',{
+            'class': 'fusionLegendLabel',
+            html: this.options.label
+        });
+        
+        domA.appendChild(this.domImg);
+        domA.appendChild(domLabel);
+
+        this.itemLabelobj = domA;
+
+        return domA;
+        
+    },
+    
+    renderFolderCheckbox: function() {
+        var domA = new Element('a',{
+            'class':this.options['class'],
+            href:'javascript:void(0)',
+            events: {
+                click: this.selected.bindWithEvent(this),
+                dblclick: this.selected.bindWithEvent(this),
+                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
+            }
+        });
+
+        this.checkBox = document.createElement('input');
+        this.checkBox.type = 'checkbox';
+
+        this.domImg = document.createElement('img');
+        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
+        this.domImg.src = Jx.aPixel.src;
+
+        if (this.options.image) {
+            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
+        }
+
+        var domLabel = new Element('span',{
+            'class': 'fusionLegendLabel',
+            html: this.options.label
+        });
+
+        domA.appendChild(this.checkBox);
+        domA.appendChild(this.domImg);
+        domA.appendChild(domLabel);
+
+        this.itemLabelobj = domA;
+
+        return domA;
+
+    },
+    
+    renderItem: function() {
+
+        var domA = new Element('a', {
+            'class': 'fusionLegendItem',
+            href: 'javascript:void(0)',
+            events: {
+                click: this.selected.bindWithEvent(this),
+                dblclick: this.selected.bindWithEvent(this),
+                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
+            }
+        });
+        
+        
+        this.domImg = document.createElement('img');
+        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
+        this.domImg.src = Jx.aPixel.src;
+        
+        if (this.options.image) {
+            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
+        }
+        
+        var domLabel = new Element('span',{
+            'class': 'fusionLegendLabel',
+            html: this.options.label
+        });
+        
+        domA.appendChild(this.domImg);
+        domA.appendChild(domLabel);
+        this.itemLabelobj = domA;
+        
+        return domA;
+    },
+    
+    renderItemCheckBox: function() {
+        var domA = new Element('a', {
+            'class': 'fusionLegendItemCheckbox',
+            'href':'javascript:void(0);',
+            events: {
+                click: this.selected.bindWithEvent(this),
+                dblclick: this.selected.bindWithEvent(this),
+                contextmenu: this.options.contextMenu.show.bindWithEvent(this.options.contextMenu)
+            }
+        });
+        
+        this.checkBox = document.createElement('input');
+        this.checkBox.type = 'checkbox';
+
+        /* layer is set to "status default" set checkbox to checked , disabled , read only*/
+        if(this.options.statusIsDefault){
+            this.checkBox.checked = true;
+            this.checkBox.disabled = true;
+            this.checkBox.readOnly = true;
+        }
+        
+        this.domImg = document.createElement('img');
+        this.domImg.className = 'jxTreeIcon ' + (this.options.imageClass ? this.options.imageClass : '');
+        this.domImg.src = Jx.aPixel.src;
+        
+        if (this.options.image) {
+            this.domImg.style.backgroundImage = 'url('+this.options.image+')';
+        }
+        
+        var domLabel = new Element('span',{
+            'class': 'fusionLegendLabel',
+            html: this.options.label
+        });
+        
+        
+        domA.appendChild(this.checkBox);
+        domA.appendChild(this.domImg);
+        domA.appendChild(domLabel);
+        this.itemLabelobj = domA;
+
+        return domA;
+    }
+
+});


Property changes on: branches/fusion-2.0/widgets/Legend.js
___________________________________________________________________
Deleted: svn:eol-style
   - native

Modified: branches/fusion-2.0/widgets/LinkToView.js
===================================================================
--- branches/fusion-2.0/widgets/LinkToView.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/LinkToView.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -56,7 +56,7 @@
             join = '&';
           }
         }
-        this.anchorLabel = json.Label ? json.Label[0] : (this.domObj ? this.domObj.innerHTML : 'Link to View');
+        this.anchorLabel = json.Label ? json.Label[0] : (this.domObj ? (this.domObj.innerHTML ? this.domObj.innerHTML : 'Link to View') : 'Link to View');
 
         Fusion.addWidgetStyleSheet(widgetTag.location + 'LinkToView/LinkToView.css');
         this.anchor = document.createElement('a');
@@ -65,6 +65,11 @@
         this.anchor.innerHTML = this.anchorLabel;
         this.anchor.title = json.Tooltip ? json.Tooltip[0] : 'Right-click to copy or bookmark link to current view';
         
+        if(this.domObj){
+            this.domObj.innerHTML = '';
+            this.domObj.appendChild(this.anchor);
+        }
+        
         this.getMap().oMapOL.events.register("addlayer", this, this.setListener);
         this.enable();                   
     },

Modified: branches/fusion-2.0/widgets/MapMenu.js
===================================================================
--- branches/fusion-2.0/widgets/MapMenu.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/MapMenu.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -157,6 +157,17 @@
     //change the map, preserving current extents
     switchMap: function(data) {
         var ce = this.getMap().getCurrentExtents();
+        var dest = null;
+        for (var i=0; i<data.maps.length; ++i) {
+          dest = new OpenLayers.Projection(data.maps[i].layerOptions.projection);
+          if (data.maps[i].layerOptions.isBaseLayer) {
+            break;
+          }
+        }
+        if (!dest) {
+          dest = new OpenLayers.Projection("EPSG:4326");
+        }
+        ce = ce.transform(this.oMap.oMapOL.getProjectionObject(), dest);
         data.initialView = {minX:ce.left,
                             minY:ce.bottom,
                             maxX:ce.right,

Modified: branches/fusion-2.0/widgets/Maptip.js
===================================================================
--- branches/fusion-2.0/widgets/Maptip.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Maptip.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -49,13 +49,13 @@
 
 
 Fusion.Widget.Maptip = OpenLayers.Class(Fusion.Widget, {
-    oCurrentPosition: null,
+    oCurrentPosition: new OpenLayers.Pixel(0,0),
     oMapTipPosition: null,
     nTimer: null,
     delay: null,
     aLayers: null,
     bOverTip: false,
-    sWinFeatures: 'menubar=no,location=no,resizable=no,status=no',
+    sWinFeatures: 'menubar=no,location=no,resizable=no,status=no,scrollbars=yes',
     offset: new OpenLayers.Pixel(2,20),
     szTip: '',
     szHref:'',
@@ -154,6 +154,9 @@
             this.mapOffset = map._oDomObj.offsets;
 
             var p = map.getEventPosition(e);
+            if (p.x == this.oCurrentPosition.x && p.y == this.oCurrentPosition.y ) {
+              return;
+            }
             this.oCurrentPosition = p;
             this.oMapTipPosition = p;
 
@@ -228,21 +231,23 @@
             {
                 if (tip) {
                     var mapTipContent = document.createElement('DIV');
-                    mapTipContent.innerHTML = tip.replace(/\n/g, "<br>");
+                    mapTipContent.innerHTML = tip.replace(/\\n/g, "<br>");
                     contentDiv.appendChild(mapTipContent);
                     empty = false;
                 }
 
                 if (hyperlink) {
                     var mapTipContent = document.createElement('DIV');
-                    hyperlink =  hyperlink.replace(/\n/g, "<br>");
+                    hyperlink =  hyperlink.replace(/\\n/g, "<br>");
                     if ( hyperlink.indexOf("href=")>0 ) {
                       mapTipContent.innerHTML = hyperlink
                     } else {
                       var anchor = document.createElement('A');
-                      anchor.href = hyperlink;
+                      var openLink = OpenLayers.Function.bind(this.openLink, this, hyperlink);
+                      anchor.onclick = OpenLayers.Function.bindAsEventListener(openLink, this);
                       anchor.target = "_blank";
-                      anchor.innerHTML = hyperlink;
+                      anchor.href = 'javascript:void(0)';
+                      anchor.innerHTML = OpenLayers.i18n('maptipLinkText');
                       mapTipContent.appendChild(anchor);
                     }
                     contentDiv.appendChild(mapTipContent);

Modified: branches/fusion-2.0/widgets/Measure/Measure.php
===================================================================
--- branches/fusion-2.0/widgets/Measure/Measure.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Measure/Measure.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -23,16 +23,21 @@
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  */
- 
+
   $fusionMGpath = '../../layers/MapGuide/php/';
   include $fusionMGpath . 'Common.php';
+  if(InitializationErrorOccurred())
+  {
+      DisplayInitializationErrorHTML();
+      exit;
+  }
   SetLocalizedFilesPath(GetLocalizationPath());
   if(isset($_REQUEST['locale'])) {
     $locale = $_REQUEST['locale'];
   } else {
     $locale = GetDefaultLocale();
   }
-  
+
   $type = $_REQUEST['type'];
   switch ($type) {
       case 1:

Modified: branches/fusion-2.0/widgets/Measure.js
===================================================================
--- branches/fusion-2.0/widgets/Measure.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Measure.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -67,14 +67,16 @@
 
     /* Style for the polygon line used for area draw */    
     areaStyle: null,
-    
+    segmentLabels: true,
     initializeWidget: function(widgetTag) {
         this.asCursor = ['crosshair'];
         var json = widgetTag.extension;
         this.units = (json.Units && (json.Units[0] != '')) ?  Fusion.unitFromName(json.Units[0]): this.units;
         this.distPrecision = json.DistancePrecision ? parseInt(json.DistancePrecision[0]) : 4;
         this.areaPrecision = json.AreaPrecision ? parseInt(json.AreaPrecision[0]) : 4;  
-        
+        if(json.SegmentLabels){
+            this.segmentLabels = (json.SegmentLabels[0].toLowerCase == "true" && json.SegmentLabels[0]) ? true : false;
+        }
         this.sTarget = json.Target ? json.Target[0] : "";
         this.sBaseUrl = Fusion.getFusionURL() + 'widgets/Measure/Measure.php';
         
@@ -280,23 +282,42 @@
         var v = geom.getVertices();
         var map = this.getMap();
         var proj = map.oMapOL.baseLayer.projection;
+        var at = null;
+        var pixQuantity = 0;
         if (geom.CLASS_NAME.indexOf('LineString') != -1) {
             from = this.getMap().geoToPix(v[0].x,v[0].y);
             to = this.getMap().geoToPix(v[1].x,v[1].y);
             at = {x: (from.x + to.x) / 2, y: (from.y + to.y) / 2};
             quantity = geom.getGeodesicLength(proj);
             
+            //calculate the length in pixels
+            pixQuantity = Math.sqrt((to.x - from.x) * (to.x - from.x) + (to.y - from.y) * (to.y - from.y));
+            
             measureUnits = Fusion.METERS;
             if (measureUnits != this.units) {
               quantity = Fusion.convert(measureUnits, this.units, quantity);
             }
         } else {
+            if(geom.getArea() == 0)
+                return;
+
             var cg = geom.getCentroid();
             at = this.getMap().geoToPix(cg.x, cg.y);
             quantity = geom.getGeodesicArea(proj);
-            //TODO: result is in square meters - convert to other units?
+           
+            measureUnits = Fusion.METERS;
+            if (measureUnits != this.units) {
+                var rate = Fusion.convert(measureUnits, this.units, 1);
+                quantity = quantity * rate * rate;
+            }
+            
+            //calculate the area in square pixels
+            var resolution = this.getMap().getResolution();
+            pixQuantity = quantity / resolution / resolution;
+
         }
-        if (quantity > 1) {
+
+        if (pixQuantity > 1) {
             marker.setQuantity(quantity);
             this.positionMarker(marker, at);
         }
@@ -314,16 +335,21 @@
         if (!isNaN(t) && !isNaN(l)) {
             marker.domObj.style.top = t + 'px';
             marker.domObj.style.left = l + 'px';
-            marker.domObj.style.display = 'block';
+            if(this.segmentLabels === true){
+                marker.domObj.style.display = 'block';
+            }
         } else {
-            marker.domObj.style.display = 'none';
+            if(this.segmentLabels === true){
+                marker.domObj.style.display = 'none';
+            }
         }
     },
     
     onKeyPress: function(e) {
         var charCode = (e.charCode ) ? e.charCode : ((e.keyCode) ? e.keyCode : e.which);
         if (charCode == OpenLayers.Event.KEY_ESC) {
-            this.control.cancel();
+            this.deactivate();
+            this.activate();
         }
     },
     
@@ -345,6 +371,7 @@
         this.resetMeasure();
         OpenLayers.Event.observe(document,"keypress",this.keyHandler);
         this.loadDisplayPanel();
+        this.getMap().supressContextMenu(true);
     },
     
     loadDisplayPanel: function() {
@@ -376,7 +403,7 @@
                 this.totalDistanceMarker.domObj.parentNode != oDomElem) {
                 oDomElem.appendChild(this.totalDistanceMarker.domObj);
             }
-            this.totalDistanceMarker.domObj.addClass = 'divMeasureTotal';
+            this.totalDistanceMarker.domObj.addClass('divMeasureTotal');
             this.totalDistanceMarker.domObj.style.display = 'none';
             this.registerForEvent(Fusion.Event.MEASURE_CLEAR, OpenLayers.Function.bind(this.clearTotalDistance, this));  
             this.registerForEvent(Fusion.Event.MEASURE_SEGMENT_UPDATE, OpenLayers.Function.bind(this.updateTotalDistance, this));
@@ -393,6 +420,7 @@
         OpenLayers.Event.stopObserving(document, 'keypress', this.keyHandler);           
         this.control.deactivate();
         this.control.cancel();
+        this.getMap().supressContextMenu(false);
     },
     
     resetMeasure: function() {
@@ -459,12 +487,13 @@
      */
      updateDisplay: function(outputWin) {
         var outputDoc = outputWin.document;
+        var resolution = this.getMap().getResolution();
         this.clearDisplay(outputWin);
         var units = Fusion.unitAbbr(this.units);
         var value;
         var distPrecision = this.distPrecision;
-        var createEntry = function(idx, distance) {
-            if (distance < 1) {
+        var createEntry = function(idx, distance, resolution) {
+            if (distance / resolution < 1) {
                 return;
             }
             var tr = outputDoc.createElement('tr');
@@ -489,11 +518,11 @@
                 for (var i=0; i<this.distanceMarkers.length; i++) {
                     var distance = this.distanceMarkers[i].getQuantity();
                     totalDistance += distance;
-                    createEntry(i+1, distance);
+                    createEntry(i+1, distance, resolution);
                 }
                 if (this.lastMarker) {
                     totalDistance += this.lastMarker.getQuantity();
-                    createEntry(i+1, this.lastMarker.getQuantity());
+                    createEntry(i+1, this.lastMarker.getQuantity(), resolution);
                 }
                 var tDist = outputDoc.getElementById('totalDistance');
                 if (this.distPrecision == 0) {
@@ -546,6 +575,10 @@
           }
           var tDist = outputDoc.getElementById('totalDistance');
           tDist.innerHTML = '';
+          var tArea = outputDoc.getElementById('totalArea');
+          if(tArea){
+              tArea.innerHTML = '';
+          }
         }
     },
     
@@ -593,8 +626,9 @@
         this.precision = precision;
         this.label = label ? label:'';
         this.isArea = isArea || false;
-        this.domObj = document.createElement('div');
-        this.domObj.className = 'divMeasureMarker';
+        this.domObj = new Element('DIV', {});
+        
+       this.domObj.className = 'divMeasureMarker';
         this.calculatingImg = document.createElement('img');
         this.calculatingImg.src = Fusion.getFusionURL() + 'widgets/Measure/MeasurePending.gif';
         this.calculatingImg.width = 19;

Modified: branches/fusion-2.0/widgets/Navigator.js
===================================================================
--- branches/fusion-2.0/widgets/Navigator.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Navigator.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -196,7 +196,7 @@
                 olMap.zoomTo(olMap.getZoomForResolution(resolution));
                 this.bInternalChange = false;
             } else {
-                var zoom = olMap.baseLayer.resolutions.length - value;
+                var zoom = olMap.baseLayer.resolutions.length - value - 1;
                 this.bInternalChange = true;
                 olMap.zoomTo(zoom);
                 this.bInternalChange = false;
@@ -243,8 +243,8 @@
             this.slider.set(position);
             this.bInternalChange = false;
         } else {
-            this.slider.steps = map.baseLayer.resolutions.length;
-            var position = map.baseLayer.resolutions.length - map.getZoom();
+            this.slider.steps = map.baseLayer.resolutions.length - 1;
+            var position = map.baseLayer.resolutions.length -1 - map.getZoom();
             this.bInternalChange = true;
             this.slider.set(position);
             this.bInternalChange = false;
@@ -285,6 +285,9 @@
         for (var i=0; i<mapWidget.handlers.length; ++i) {
           var handler = mapWidget.handlers[i];
           if (handler.active) {
+            if(handler.CLASS_NAME == "OpenLayers.Handler.Box" && handler.zoomBox != undefined){
+              handler.removeBox();
+            }
             handler.deactivate();
             this.activeControls.push(handler);
           }

Modified: branches/fusion-2.0/widgets/OverviewMap.js
===================================================================
--- branches/fusion-2.0/widgets/OverviewMap.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/OverviewMap.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -59,7 +59,7 @@
         } else {
           this.mapObject = new Fusion.Layers.Generic(this, mapTag, false);
         }
-        this.mapObject.registerForEvent(Fusion.Event.LAYER_LOADED, OpenLayers.Function.bind(this.loadOverview, this));
+        //this.mapObject.registerForEvent(Fusion.Event.LAYER_LOADED, OpenLayers.Function.bind(this.loadOverview, this));
 
         //first set the size to the size of the DOM element if available
         if (this.domObj) {
@@ -73,28 +73,23 @@
         
         this.oMapOptions = {};  //TODO: allow setting some mapOptions in AppDef
 
-        //this.getMap().registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.mapWidgetLoaded, this));
+        this.getMap().registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.mapWidgetLoaded, this));
     },
     
     mapWidgetLoaded: function() 
     {
         var mapWidget = this.getMap();
-        if (this.sMapGroupId && (mapWidget.projection == this.mapObject.projection) ) {
-          this.loadOverview([this.mapObject.oLayerOL]);
+        if (this.sMapGroupId) {// && (mapWidget.projection == this.mapObject.projection) ) {
+          this.loadOverview(this.mapObject.oLayerOL);
         } else {
           //just use the base map layer
-          var extent = this.oMap._oCurrentExtents;
-          this.loadOverview([this.getMap().oMapOL.baseLayer.clone()]);
+          //setTimeout(OpenLayers.Function.bind(this.loadOverview, this), 5000);
+          this.loadOverview();
         }
     },
 
-    keymapLoaded: function() 
+    loadOverview: function(layer) 
     {
-        this.mapObject.oLayerOL.isBaseLayer = true;  
-    },
-
-    loadOverview: function() 
-    {
         if (this.control) {
           this.control.destroy();
         }
@@ -102,22 +97,25 @@
         var size = $(this.domObj).getContentBoxSize();
         this.oSize = new OpenLayers.Size(size.width, size.height);
         
-        this.mapObject.oLayerOL.isBaseLayer = true;  
-        if (this.mapObject.oLayerOL.singleTile) {
+        if (!layer) {
+            layer = this.getMap().oMapOL.baseLayer.clone();
+        }
+        layer.isBaseLayer = true; 
+        layer.ratio = 1.0;
+        if (layer.singleTile) {
           this.oMapOptions.numZoomLevels = 3;  //TODO: make this configurable?
         }
 
-        this.mapObject.oLayerOL.ratio = 1.0;
-        var mapOpts = {
+        var options = {
           div: this.domObj,
           size: this.oSize,
           minRatio: this.nMinRatio,
           maxRatio: this.nMaxRatio,
           mapOptions: this.oMapOptions,
-          layers: [this.mapObject.oLayerOL]
+          layers: [layer]
         };
 
-        this.control = new OpenLayers.Control.OverviewMap(mapOpts);
+        this.control = new OpenLayers.Control.OverviewMap(options);
         if (size.width == 0 || size.height == 0) {
           return;   //don't try to load if the container is not visible
         } else {

Deleted: branches/fusion-2.0/widgets/Print/Print.html
===================================================================
--- branches/fusion-2.0/widgets/Print/Print.html	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Print/Print.html	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,13 +0,0 @@
-<div class="PrintDialogForm">
-  <fieldset class="PrintDialogOptions">
-	  <legend>Options</legend>
-	  	<label class="block" for="dialogPrintShowtitle"><input name="dialogPrintShowtitle" id="dialogPrintShowtitle" type="checkbox" value="showtitle" checked>
-			Show Title?</label>
-		<label class="block" for="dialogPrintTitle">Title</label>
-		<input name="dialogPrintTitle" id="dialogPrintTitle" type="text" class="inputText" />
-		<label class="block" for="dialogPrintShowlegend"><input name="dialogPrintShowlegend" id="dialogPrintShowlegend" type="checkbox" value="showlegend" checked>
-			Show Legend?</label>
-		<label class="block" for="dialogPrintShowNorthArrow"><input name="dialogPrintShowNorthArrow" id="dialogPrintShowNorthArrow" type="checkbox" value="shownortharrow" checked>
-			Show North Arrow?</label>
-  </fieldset>
-</div>
\ No newline at end of file

Modified: branches/fusion-2.0/widgets/Print/printablepage.php
===================================================================
--- branches/fusion-2.0/widgets/Print/printablepage.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Print/printablepage.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -19,6 +19,11 @@
 
 $fusionMGpath = '../../layers/MapGuide/php/';
 include $fusionMGpath . 'Common.php';
+if(InitializationErrorOccurred())
+{
+    DisplayInitializationErrorHTML();
+    exit;
+}
 
     $locale = "en";
     $mapName = "";

Modified: branches/fusion-2.0/widgets/Print.js
===================================================================
--- branches/fusion-2.0/widgets/Print.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Print.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -82,14 +82,26 @@
             var o = {
                 label: OpenLayers.i18n('printTitle'),
                 id: 'printablePage',
-                contentURL : this.dialogContentURL,
-                onContentLoaded: OpenLayers.Function.bind(this.contentLoaded, this),
+                content : '<div class="PrintDialogForm">' +
+                              '<fieldset class="PrintDialogOptions">' +
+                                  '<legend>' + OpenLayers.i18n("printOptions") +'</legend>' +
+                                    '<label class="block" for="dialogPrintShowtitle"><input name="dialogPrintShowtitle" id="dialogPrintShowtitle" type="checkbox" value="showtitle" checked>' +
+                                         OpenLayers.i18n("printShowTitle") +'</label>' +
+                                    '<label class="block" for="dialogPrintTitle">' + OpenLayers.i18n("printTitleText") + '</label>' +
+                                    '<input name="dialogPrintTitle" id="dialogPrintTitle" type="text" class="inputText" />' +
+                                    '<label class="block" for="dialogPrintShowlegend"><input name="dialogPrintShowlegend" id="dialogPrintShowlegend" type="checkbox" value="showlegend" checked>' +
+                                         OpenLayers.i18n("printShowLegend") + '</label>' +
+                                    '<label class="block" for="dialogPrintShowNorthArrow"><input name="dialogPrintShowNorthArrow" id="dialogPrintShowNorthArrow" type="checkbox" value="shownortharrow" checked>' +
+                                         OpenLayers.i18n("printShowNorthArrow") + '</label>' +
+                              '</fieldset>' +
+                            '</div>',
                 width: 350,
                 height: 250,
                 resize: true,
                 toolbars: [toolbar]
             };
             var d = new Jx.Dialog(o);
+			d.addEvent("contentLoaded", this.contentLoaded.bind(this));
             toolbar.add(
                 new Jx.Button({
                     label: OpenLayers.i18n('printGenerate'),

Modified: branches/fusion-2.0/widgets/Query/classes/query.php
===================================================================
--- branches/fusion-2.0/widgets/Query/classes/query.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Query/classes/query.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -17,6 +17,9 @@
 //  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 //
 
+$fusionMGpath = '../../layers/MapGuide/php/';
+require_once $fusionMGpath . 'Common.php';
+
 require_once('property.php');
 require_once('feature.php');
 // require_once '../Common/JSON.php';
@@ -36,11 +39,27 @@
         $this->args = $args;
         $this->site = new MgSiteConnection();
         $this->site->Open(new MgUserInformation($args['SESSION']));
+        
+        SetLocalizedFilesPath(GetLocalizationPath());
+        if(isset($_REQUEST['locale'])) {
+            $locale = $_REQUEST['locale'];
+        } else {
+            $locale = GetDefaultLocale();
+        }
+        
+        $equalToLocal = GetLocalizedString('QUERYEQUALTO', $locale );
+        $notEqualToLocal = GetLocalizedString('QUERYNOTEQUALTO', $locale );
+        $greatThanLocal = GetLocalizedString('QUERYGREATTHAN', $locale );
+        $greatThanEqualLocal = GetLocalizedString('QUERYGREATTHANEQUAL', $locale );
+        $lessThanLocal = GetLocalizedString('QUERYLESSTHAN', $locale );
+        $lessThanEqualLocal = GetLocalizedString('QUERYLESSTHANEQUAL', $locale );
+        $beginLocal = GetLocalizedString('QUERYBEGIN', $locale );
+        $containsLocal = GetLocalizedString('QUERYCONTAINS', $locale );
 
-        $this->numOperators = array('Equal to', 'Not equal to', 'Greater than', 'Greater than or equal to', 'Less than', 'Less than or equal to');
+        $this->numOperators = array($equalToLocal, $notEqualToLocal, $greatThanLocal, $greatThanEqualLocal, $lessThanLocal, $lessThanEqualLocal);
         $this->numExpressions = array(' = %s', ' != %s', ' > %s', ' >= %s', ' < %s', ' <= %s');
 
-        $this->strOperators = array('Begins with', 'Contains', 'Equal to');
+        $this->strOperators = array($beginLocal, $containsLocal, $equalToLocal);
         $this->strExpressions = array(" like '%s%%'", " like '%%%s%%'", " = '%s'");
     }
 
@@ -209,8 +228,9 @@
         $featureService = $this->site->CreateService(MgServiceType::FeatureService);
         $resId = new MgResourceIdentifier($layer->GetFeatureSourceId());
         $featureClass = $layer->GetFeatureClassName();
+        $filter = $layer->GetFilter();
         $featureGeometry = $layer->GetFeatureGeometryName();
-
+        
         // Initialize the coordinate system transform
 
         $schemaAndClass = explode(":", $featureClass);
@@ -240,6 +260,7 @@
         $queryMax = (int) $this->args['QUERYMAX'];
         $queryOptions = new MgFeatureQueryOptions();
 
+        $propertyFilter = '';
         if ($this->args['USEPROPERTYFILTER'] == 'true')
         {
             $propertyFilter = $this->args['PROPERTYNAME'];
@@ -247,10 +268,18 @@
                 $propertyFilter .= sprintf($this->strExpressions[$this->args['OPERATOR']], $this->args['VALUE']);
             else
                 $propertyFilter .= sprintf($this->numExpressions[$this->args['OPERATOR']], $this->args['VALUE']);
-
+                
+            if($filter != '')
+                $propertyFilter = $propertyFilter . ' AND (' . $filter . ')';
+        }
+        else
+        {
+            if($filter != '')
+                $propertyFilter = $filter;
+        }
+        if($propertyFilter != '')
             $queryOptions->SetFilter($propertyFilter);
-        }
-
+        
         if ($this->args['USESPATIALFILTER'] == 'true')
         {
             $polygon = $this->CreatePolygonFromGeomText($this->args['GEOMTEXT']);
@@ -538,6 +567,13 @@
             $coords->Add($coord);
         }
 
+        //Some provider such as SQL Server Spatial, ODBC requires the polygon's start point must be the same as end point.
+        if(($count>2) && (($coords->GetItem(0)->GetX() != $coords->GetItem($count-1)->GetX()) || ($coords->GetItem(0)->GetY() != $coords->GetItem($count-1)->GetY())))
+        {
+            $coord = $geometryFactory->CreateCoordinateXY($coords->GetItem(0)->GetX(), $coords->GetItem(0)->GetY());
+            $coords->Add($coord);
+        }
+        
         $linearRing = $geometryFactory->CreateLinearRing($coords);
         $polygon = $geometryFactory->CreatePolygon($linearRing, null);
 

Modified: branches/fusion-2.0/widgets/Query/querycontroller.php
===================================================================
--- branches/fusion-2.0/widgets/Query/querycontroller.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Query/querycontroller.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -19,6 +19,11 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     require_once $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
     require_once $fusionMGpath . 'Utilities.php';
     require_once $fusionMGpath . 'JSON.php';
     require_once 'classes/query.php';
@@ -26,7 +31,7 @@
     $args = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_GET;
 
     // MgInitializeWebTier($configFilePath);
-    
+
     try {
 
       $query = new Query($args);
@@ -79,4 +84,4 @@
     <tr><td class="Title">Error<hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
     <tr><td><?= $errorDetail ?></td></tr>
-</table>
\ No newline at end of file
+</table>

Modified: branches/fusion-2.0/widgets/Query/querymain.php
===================================================================
--- branches/fusion-2.0/widgets/Query/querymain.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Query/querymain.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -19,14 +19,48 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     require_once $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }    
     require_once $fusionMGpath . 'Utilities.php';
     require_once $fusionMGpath . '/JSON.php';
     require_once 'classes/query.php';
+    
+    SetLocalizedFilesPath(GetLocalizationPath());
+    if(isset($_REQUEST['locale'])) {
+        $locale = $_REQUEST['locale'];
+    } else {
+        $locale = GetDefaultLocale();
+    }
 
     $args = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_GET;
 
     $errorMsg = null;
     $errorDetail = null;
+    
+    $titleLocal = GetLocalizedString('QUERYTITLE', $locale );
+    $selectLayerLocal = GetLocalizedString('QUERYSELECTLAYER', $locale );
+    $layerLocal = GetLocalizedString('QUERYLAYER', $locale );
+    $propertyFilterLocal = GetLocalizedString('QUERYPROPERTYFILTER', $locale );
+    $propertyLocal = GetLocalizedString('QUERYPROPERTY', $locale );
+    $operatorLocal = GetLocalizedString('QUERYOPERATOR', $locale );
+    $valueLocal = GetLocalizedString('QUERYVALUE', $locale );
+    $spatialFilterLocal = GetLocalizedString('QUERYSPATIALFILTER', $locale );
+    $digitizeLocal = GetLocalizedString('QUERYDIGITIZE', $locale );
+    $rectangleLocal = GetLocalizedString('QUERYRECTANGLE', $locale );
+    $polygonLocal = GetLocalizedString('QUERYPOLYGON', $locale );
+    $clearLocal = GetLocalizedString('QUERYCLEAR', $locale );
+    $outputLocal = GetLocalizedString('QUERYOUTPUT', $locale );
+    $outputPropertyLocal = GetLocalizedString('QUERYOUTPUTPROPERTY', $locale );
+    $executeLocal = GetLocalizedString('QUERYEXECUTE', $locale );
+    $maxResultLocal = GetLocalizedString('QUERYMAXRESULT', $locale );
+    $resultsLocal = GetLocalizedString('QUERYRESULTS', $locale );
+    $scaleLocal = GetLocalizedString('QUERYSCALE', $locale );
+    $zoomLocal = GetLocalizedString('QUERYZOOM', $locale );
+    $selectLocal = GetLocalizedString('QUERYSELECT', $locale );
+    $errorLocal = GetLocalizedString('QUERYERROR', $locale );
 
     try
     {
@@ -48,7 +82,7 @@
 ?>
 <html>
 <head>
-    <title>Query Features</title>
+    <title><?php echo $titleLocal ?></title>
     <link rel="stylesheet" href="../../common/mgsamples.css" type="text/css">
     <script language="javascript" src="../../common/browserdetect.js"></script>
     <script language="javascript" src="../../common/json.js"></script>
@@ -135,6 +169,9 @@
             {
                 ToggleSpatialFilter(document.getElementById("spatialFilter").checked);
             }
+            
+            if(document.getElementById("spatialFilter").checked == false)
+                ClearDigitization();
         }
 
         function OnDigitizeRectangle()
@@ -376,9 +413,9 @@
 <?php if ($errorMsg == null) { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%">
-    <tr><td class="Title"><img id="busyImg" src="../../common/images/loader_inactive.gif" style="vertical-align:bottom">&nbsp;Query Features<hr></td></tr>
-    <tr><td class="SubTitle">Select a Layer</td></tr>
-    <tr><td>Layer:</td></tr>
+    <tr><td class="Title"><img id="busyImg" src="../../common/images/loader_inactive.gif" style="vertical-align:bottom">&nbsp;<?php echo $titleLocal ?><hr></td></tr>
+    <tr><td class="SubTitle"><?php echo $selectLayerLocal ?></td></tr>
+    <tr><td><?php echo $layerLocal ?></td></tr>
     <tr>
         <td class="RegText">
             <select size="1" class="Ctrl" id="layerSelect" onChange="OnLayerChange()" style="width: 100%">
@@ -395,40 +432,40 @@
         </td>
     </tr>
     <tr><td class="Spacer"></td></tr>
-    <tr><td class="SubTitle"><input class="Ctrl" type="checkbox" id="propertyFilter" checked>&nbsp;Property Filter</td></tr>
-    <tr><td>Property:</td></tr>
+    <tr><td class="SubTitle"><input class="Ctrl" type="checkbox" id="propertyFilter" checked>&nbsp;<?php echo $propertyFilterLocal ?></td></tr>
+    <tr><td><?php echo $propertyLocal ?></td></tr>
     <tr>
         <td class="RegText">
             <select size="1" class="Ctrl" id="propertySelect" onChange="OnPropertyChange()" style="width: 100%">
             </select>
         </td>
     </tr>
-    <tr><td>Operator:</td></tr>
+    <tr><td><?php echo $operatorLocal ?></td></tr>
     <tr>
         <td class="RegText">
             <select size="1" class="Ctrl" id="operatorSelect" style="width: 100%">
             </select>
         </td>
     </tr>
-    <tr><td>Value:</td></tr>
+    <tr><td><?php echo $valueLocal ?></td></tr>
     <tr>
         <td class="RegText">
             <input maxlength="100" class="Ctrl" id="valueInput" style="width: 100%">
         </td>
     </tr>
     <tr><td class="Spacer"></td></tr>
-    <tr><td class="SubTitle"><input class="Ctrl" type="checkbox" onChange="OnToggleSpatialFilter()" id="spatialFilter">&nbsp;Spatial Filter</td></tr>
-    <tr><td>Digitize:</td></tr>
+    <tr><td class="SubTitle"><input class="Ctrl" type="checkbox" onclick ="OnToggleSpatialFilter()" id="spatialFilter">&nbsp;<?php echo $spatialFilterLocal ?></td></tr>
+    <tr><td><?php echo $digitizeLocal ?></td></tr>
     <tr>
         <td align="center">
-            <input type="button" name="" value="Rectangle" class="Ctrl" id="rectButton" onClick="OnDigitizeRectangle()" style="width: 30%">
-            <input type="button" name="" value="Polygon" class="Ctrl" id="polyButtton" onClick="OnDigitizePolygon()" style="width: 30%">
-            <input type="button" name="" value="Clear" class="Ctrl" id="clearButton" onClick="OnClearSpatialFilter()" style="width: 30%">
+            <input type="button" name="" value="<?php echo $rectangleLocal ?>" class="Ctrl" id="rectButton" onClick="OnDigitizeRectangle()" style="width: 30%">
+            <input type="button" name="" value="<?php echo $polygonLocal ?>" class="Ctrl" id="polyButtton" onClick="OnDigitizePolygon()" style="width: 30%">
+            <input type="button" name="" value="<?php echo $clearLocal ?>" class="Ctrl" id="clearButton" onClick="OnClearSpatialFilter()" style="width: 30%">
         </td>
     </tr>
     <tr><td class="Spacer"></td></tr>
-    <tr><td class="SubTitle">Output</td></tr>
-    <tr><td>Output property:</td></tr>
+    <tr><td class="SubTitle"><?php echo $outputLocal ?></td></tr>
+    <tr><td><?php echo $outputPropertyLocal ?></td></tr>
     <tr>
         <td class="RegText">
             <select size="1" class="Ctrl" id="outputSelect" style="width: 100%">
@@ -439,13 +476,13 @@
     <tr><td><hr></td></tr>
     <tr>
         <td>
-            <input id="executeBtn" class="Ctrl" name="" type="button" onClick="ExecuteQuery()" value="Execute" style="width:60px">
-            &nbsp;&nbsp;Max results:&nbsp;
+            <input id="executeBtn" class="Ctrl" name="" type="button" onClick="ExecuteQuery()" value="<?php echo $executeLocal ?>" style="width:60px">
+            &nbsp;&nbsp;<?php echo $maxResultLocal ?>&nbsp;
             <input name="" id="queryMax" class="Ctrl" type="text" value="100" size="5">
         </td>
     </tr>
     <tr><td class="Spacer"></td></tr>
-    <tr><td class="SubTitle">Results</td></tr>
+    <tr><td class="SubTitle"><?php echo $resultsLocal ?></td></tr>
     <tr>
         <td>
             <select class="Ctrl" id="resultSelect" size="15" onChange="OnResultChange()" style="width: 100%"></select>
@@ -453,9 +490,9 @@
     </tr>
     <tr>
         <td>
-            Scale:&nbsp;<input class="Ctrl" id="scaleInput" type="text" size="6" value="10000">
-            <input class="Ctrl" id="zoomBtn" type="button" onClick="ZoomToFeature()" value="Zoom" style="width:60px">
-            <input class="Ctrl" id="selectBtn" type="button" onClick="SelectFeature()" value="Select" style="width:60px">
+            <?php echo $scaleLocal ?>&nbsp;<input class="Ctrl" id="scaleInput" type="text" size="6" value="10000">
+            <input class="Ctrl" id="zoomBtn" type="button" onClick="ZoomToFeature()" value="<?php echo $zoomLocal ?>" style="width:60px">
+            <input class="Ctrl" id="selectBtn" type="button" onClick="SelectFeature()" value="<?php echo $selectLocal ?>" style="width:60px">
         </td>
     </tr>
 
@@ -464,14 +501,14 @@
 <?php } else if ($errorDetail == null || (strlen($errorDetail) - strlen($errorMsg) < 5)) { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%%">
-    <tr><td class="Title">Error<hr></td></tr>
+    <tr><td class="Title"><?php echo $errorLocal ?><hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
 </table>
 
 <?php } else { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%%">
-    <tr><td class="Title">Error<hr></td></tr>
+    <tr><td class="Title"><?php echo $errorLocal ?><hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
     <tr><td><?= $errorDetail ?></td></tr>
 </table>

Modified: branches/fusion-2.0/widgets/Query.js
===================================================================
--- branches/fusion-2.0/widgets/Query.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Query.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -37,6 +37,7 @@
 
 
 Fusion.Widget.Query = OpenLayers.Class(Fusion.Widget, {
+    isExclusive: true,
     uiClass: Jx.Button,
     sFeatures : 'menubar=no,location=no,resizable=no,status=no',
 

Modified: branches/fusion-2.0/widgets/Redline/Redline.css
===================================================================
--- branches/fusion-2.0/widgets/Redline/Redline.css	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Redline/Redline.css	2010-03-24 18:31:34 UTC (rev 2105)
@@ -13,9 +13,10 @@
   padding: 10px;
 }
 
-#RedlineWidget td, 
+#RedlineWidget td,
 #RedlineWidget th {
   text-align: left;
+  vertical-align: text-top;
   font-size: 12px;
   padding: 2px 10px;
   margin-bottom: 30px;
@@ -24,8 +25,10 @@
 
 #RedlineWidget th {
   font-weight: bold;
+  vertical-align: text-top;
 }
 
 #RedlineWidgetFeatureList {
   min-width: 250px;
-}
\ No newline at end of file
+  width: 250px;
+}

Modified: branches/fusion-2.0/widgets/Redline/Redline.php
===================================================================
--- branches/fusion-2.0/widgets/Redline/Redline.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Redline/Redline.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,30 @@
  *  The max file size should be setted in the php5.ini.
  *****************************************************************************/
 
+$fusionMGpath = '../../layers/MapGuide/php/';
+include $fusionMGpath . 'Common.php';
+  
+SetLocalizedFilesPath(GetLocalizationPath());
+if(isset($_REQUEST['locale'])) {
+    $locale = $_REQUEST['locale'];
+} else {
+    $locale = GetDefaultLocale();
+}
+
+$optionLocal = GetLocalizedString('REDLINEOPTIONS', $locale );
+$selectLayerLocal = GetLocalizedString('REDLINESELECTLAYER', $locale );
+$newLocal = GetLocalizedString('REDLINENEW', $locale );
+$renameLocal = GetLocalizedString('REDLINERENAME', $locale );
+$removeLocal = GetLocalizedString('REDLINEREMOVE', $locale );
+$drawLocal = GetLocalizedString('REDLINEDRAW', $locale );
+$pointLocal = GetLocalizedString('REDLINEPOINT', $locale );
+$lineLocal = GetLocalizedString('REDLINELINE', $locale );
+$rectangleLocal = GetLocalizedString('REDLINERECTANGLE', $locale );
+$polygonLocal = GetLocalizedString('REDLINEPOLYGON', $locale );
+$saveLocal = GetLocalizedString('REDLINESAVE', $locale );
+$uploadLocal = GetLocalizedString('REDLINEUPLOAD', $locale );
+$featuresLocal = GetLocalizedString('REDLINEFEATURES', $locale );
+
 $fileUpload = false;
 
 $action = $_POST['action'];
@@ -41,8 +65,8 @@
         $fileUpload = true;
 
         $target_path = tempnam(sys_get_temp_dir(), preg_replace("/\.[^\.]+$/", "", basename( $_FILES['uploadedfile']['name'])).'_');
-        
-        if (file_exists($target_path)) { 
+
+        if (file_exists($target_path)) {
             unlink($target_path);
         }
         $target_path = $target_path.'.gml';
@@ -77,85 +101,91 @@
             document.body.appendChild(div);
             <? } ?>
             <? if (isset($noFile)) {  echo "alert('Please select a file.');"; } ?>
-            
+
         }
       </script>
-
-      <h1>Digitizing Options</h1>
-      <table id="RedlineWidgetOptions" borders="1">
       
+      <table id="RedlineWidgetOptions" borders="1" width="100%">
       <tr>
-      <th>Select Layer: </th>
+      <td style="font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 13pt">
+      <?php echo $optionLocal ?>
+      <hr>
+      </td>
+      </tr>
+      <tr>
+      <td style="font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 8pt; background-color: #DCDCDC; color: black; height: 20px;"><?php echo $selectLayerLocal ?></td>
+      </tr>
+      <tr>
       <td>
       <select id="RedlineWidgetLayerList"></select>
       </td>
       </tr>
       <tr>
-      <td><!-- dummy col --></td>
       <td>
-        <button id="RedlineWidgetNewLayerButton">New</button>
-        <button id="RedlineWidgetRenameLayerButton">Rename</button>
-        <button id="RedlineWidgetRemoveLayerButton">Remove</button>
+        <button id="RedlineWidgetNewLayerButton"><?php echo $newLocal ?></button>
+        <button id="RedlineWidgetRenameLayerButton"><?php echo $renameLocal ?></button>
+        <button id="RedlineWidgetRemoveLayerButton"><?php echo $removeLocal ?></button>
       </td>
       </tr>
       <tr>
-        <th>Draw:</th>
+        <td style="font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 8pt; background-color: #DCDCDC; color: black; height: 20px;"><?php echo $drawLocal ?></td>
+       </tr> 
+       <tr> 
         <td>
           <input id="RedlineWidgetPointRadio" type="radio" name="RedlineWidgetDrawRadio"/>
-          <label for="RedlineWidgetPointeRadio">Point</label>
+          <label for="RedlineWidgetPointeRadio"><?php echo $pointLocal ?></label><br/>
           <input id="RedlineWidgetLineRadio" type="radio" name="RedlineWidgetDrawRadio"/>
-          <label for="RedlineWidgetLineRadio">Line</label>
+          <label for="RedlineWidgetLineRadio"><?php echo $lineLocal ?></label><br/>
           <input id="RedlineWidgetRectangleRadio" type="radio" name="RedlineWidgetDrawRadio"/>
-          <label for="RedlineWidgetRectangleRadio">Rectangle</label>
+          <label for="RedlineWidgetRectangleRadio"><?php echo $rectangleLocal ?></label><br/>
           <input id="RedlineWidgetPolygonRadio" type="radio" name="RedlineWidgetDrawRadio"/>
-          <label for="RedlineWidgetPolygonRadio">Polygon</label>
+          <label for="RedlineWidgetPolygonRadio"><?php echo $polygonLocal ?></label>
         </td>
       </tr>
       <tr>
-        <td colspan="2">
+        <td>
           <hr/>
-          <button id="RedlineWidgetSaveButton">Save</button>
+          <button id="RedlineWidgetSaveButton"><?php echo $saveLocal ?></button>
         </td>
       </tr>
       <tr>
-        <td id="RedlineWidgetUploadTd" colspan="2">
+        <td id="RedlineWidgetUploadTd">
           <form id="RedlineWidgetUploadForm" enctype="multipart/form-data" action="Redline.php" method="post">
              <input type="file" name="uploadedfile"/>
              <input type="hidden" name="action" value="upload"/>
              <br/>
-             <input id="RedlineWidgetUploadButton" type="submit" name="submit_element" value="Upload" />
+             <input id="RedlineWidgetUploadButton" type="submit" name="submit_element" value="<?php echo $uploadLocal ?>" />
           </form>
     </td>
       </tr>
-      <tr><td><!-- dummy col --></td></tr>
       <tr>
-        <th colspan="2">
-          Features
-          <hr/>
-        </th>
+        <td><hr/></td>
       </tr>
       <tr>
-        <td colspan="2">
+        <td style="font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 8pt; background-color: #DCDCDC; color: black; height: 20px;">
+          <?php echo $featuresLocal ?>
+        </td>
+        </tr>
+      <tr>
+        <td>
           <select id="RedlineWidgetFeatureList" size="10">
           </select>
         </td>
       </tr>
       <tr>
         <td>
-          <button id="RedlineWidgetRenameFeatureButton">Rename</button>
+          <button id="RedlineWidgetRenameFeatureButton"><?php echo $renameLocal ?></button>
+          <button id="RedlineWidgetRemoveFeatureButton"><?php echo $removeLocal ?></button>
         </td>
-        <td>
-          <button id="RedlineWidgetRemoveFeatureButton">Remove</button>
-        </td>
       </tr>
       </table>
-     
+
     </body>
   </html>
 
 
 <?php
-                                                     
+
 function returnFile($filename) {
 
 header("Content-type: text/xml");

Modified: branches/fusion-2.0/widgets/Redline.js
===================================================================
--- branches/fusion-2.0/widgets/Redline.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Redline.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -45,8 +45,11 @@
     // a reference to a redline taskPane
     taskPane: null,
 
-    // array of OL vector layer
-    vectorLayers: null,
+    // array of OL vector layer
+    vectorLayers: null,
+
+    // the default layer name
+    defaultLayerName: null,
 
     // the drawing controls
     drawControls: null,
@@ -72,8 +75,10 @@
     saveForm: null,
 
     initializeWidget: function(widgetTag) {
-        var json = widgetTag.extension;
-        this.mapWidget = Fusion.getWidgetById('Map');
+        var json = widgetTag.extension;
+        this.mapWidget = Fusion.getWidgetById('Map');
+
+        this.defaultLayerName = OpenLayers.i18n('redlineLayerName');
 
         // register Redline specific events
         this.registerEventID(Fusion.Event.REDLINE_FEATURE_ADDED);
@@ -97,11 +102,11 @@
  
         this.styleMap = new OpenLayers.StyleMap(defaultFeatureStyle);
         
-        // create one default layer, unless other redline widgets have created it
-        this.vectorLayers = this.mapWidget.oMapOL.getLayersByName('Digitizing Layer 0');
+        // create one default layer, unless other redline widgets have created it
+        this.vectorLayers = this.mapWidget.oMapOL.getLayersByName(this.defaultLayerName + '0');
     
-        if (!this.vectorLayers.length) {
-            this.vectorLayers[0] = new OpenLayers.Layer.Vector("Digitizing Layer 0", {styleMap: this.styleMap});
+        if (!this.vectorLayers.length) {
+            this.vectorLayers[0] = new OpenLayers.Layer.Vector(this.defaultLayerName + '0', { styleMap: this.styleMap });
             this.vectorLayers[0].redLineLayer = true;
             this.mapWidget.oMapOL.addLayers([this.vectorLayers[0]]);
         }
@@ -209,18 +214,34 @@
         }
         this.activateLayer(0);
         this.activateControl(this.defaultControl,0);
+        this.getMap().supressContextMenu(true);
     },
 
     // desactivate the redline widget
     deactivate: function() {
         this.activeControl.deactivate();
         this.activeControl = null;
+        this.getMap().supressContextMenu(false);
     },
    
     featureAdded: function(evt) {
-        this.triggerEvent(Fusion.Event.REDLINE_FEATURE_ADDED, evt.feature);
+        this.triggerEvent(Fusion.Event.REDLINE_FEATURE_ADDED, evt.feature);	
+		this.moveLayerToTop(evt.feature.layer);
     },
-
+    
+	// move the redline layer to the top and redraw it
+	moveLayerToTop: function(layer) {
+		var map = layer.map;
+		var baseIndex = map.getLayerIndex(layer);
+		
+		if(baseIndex != layer.map.layers.length-2)
+		{
+			// except for the current temp drawing layer, the redline layer is not on the top of the map.
+			map.setLayerIndex(layer,layer.map.layers.length-2)
+		}
+		layer.redraw();
+	},
+	
     // change active layer
     activateLayer: function(layerIndex) {
         this.activeLayer = this.vectorLayers[layerIndex];
@@ -256,8 +277,8 @@
     },
     
     newLayerFromFile: function(fileName) {
-        var i = this.vectorLayers.length;
-        this.vectorLayers[i] = new OpenLayers.Layer.Vector("Digitizing layer "+this.vectorLayers.length, {
+        var i = this.vectorLayers.length;
+        this.vectorLayers[i] = new OpenLayers.Layer.Vector(this.defaultLayerName + this.vectorLayers.length, {
             strategies: [new OpenLayers.Strategy.Fixed()],
             protocol: new OpenLayers.Protocol.HTTP({
                 url: Fusion.getFusionURL() +"widgets/Redline/Redline.php?"+"file="+fileName,
@@ -274,12 +295,29 @@
         this.vectorLayers[layerIndex].destroy();
         this.vectorLayers.splice(layerIndex,1);
         // we always keep at least one vector layer
-        if (this.vectorLayers.length == 0) {
-            this.vectorLayers[0] = new OpenLayers.Layer.Vector("Digitizing Layer 0", {styleMap: this.styleMap});
+        if (this.vectorLayers.length == 0) {
+            this.vectorLayers[0] = new OpenLayers.Layer.Vector(this.defaultLayerName + '0', { styleMap: this.styleMap });
             this.mapWidget.oMapOL.addLayers([this.vectorLayers[0]]);
             this.vectorLayers[0].redLineLayer = true;
         }
         this.activateLayer(0);
+    },
+
+    getUniqueLayerName: function() {
+        var offset = this.vectorLayers.length;
+        var exist = true;
+        while (exist) {
+            exist = false;
+            var i = 0;
+            while (!exist && i < this.vectorLayers.length) {
+                if ((this.defaultLayerName + offset) == this.vectorLayers[i].name)
+                    exist = true;
+                i++;
+            }
+            if (exist)
+                offset++;
+        }
+        return this.defaultLayerName + offset;
     }
 });
 
@@ -363,8 +401,8 @@
         doc.getElementById("RedlineWidgetRenameFeatureButton").onclick = OpenLayers.Function.bind(this.renameFeature, this);
     },
 
-    newLayer: function() {
-        var name = prompt("Layer name:", "Digitizing layer "+this.widget.vectorLayers.length);
+    newLayer: function() {
+        var name = prompt("Layer name:", this.widget.getUniqueLayerName());
         if (name!=null && name!="") {
             this.widget.newLayer(name);
             this.updateLayerList();

Modified: branches/fusion-2.0/widgets/Search/Search.php
===================================================================
--- branches/fusion-2.0/widgets/Search/Search.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Search/Search.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -29,6 +29,11 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     include $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
 
     //$logHandle = fopen("debug.log","at");
 

Modified: branches/fusion-2.0/widgets/Search/SearchPrompt.php
===================================================================
--- branches/fusion-2.0/widgets/Search/SearchPrompt.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Search/SearchPrompt.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -26,6 +26,11 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     include $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
 
     $locale = GetDefaultLocale();
     $popup = 0;

Modified: branches/fusion-2.0/widgets/Select.js
===================================================================
--- branches/fusion-2.0/widgets/Select.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Select.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -106,10 +106,11 @@
        * This function should be defined for all functions that register
        * as a widget in the map
        */
-    activate : function() {
+    activate: function() {
         this.handler.activate();
         //this.shiftHandler.activate();
         this.getMap().setCursor(this.asCursor);
+        this.getMap().supressContextMenu(true);
     },
 
     /**
@@ -117,10 +118,11 @@
        * This function should be defined for all functions that register
        * as a widget in the map
        **/
-    deactivate : function() {
+    deactivate: function() {
         this.handler.deactivate();
         //this.shiftHandler.deactivate();
         this.getMap().setCursor('auto');
+        this.getMap().supressContextMenu(false);
     },
 
     /**

Modified: branches/fusion-2.0/widgets/SelectPolygon.js
===================================================================
--- branches/fusion-2.0/widgets/SelectPolygon.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/SelectPolygon.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -65,6 +65,7 @@
     activate: function() {
         this.handler.activate();
         this.getMap().setCursor(this.asCursor);
+        this.getMap().supressContextMenu(true);
     },
 
     /**
@@ -76,6 +77,7 @@
     {
         this.handler.deactivate();
         this.getMap().setCursor('auto');
+        this.getMap().supressContextMenu(false);
     },
     
     /**

Modified: branches/fusion-2.0/widgets/SelectRadius.js
===================================================================
--- branches/fusion-2.0/widgets/SelectRadius.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/SelectRadius.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -113,6 +113,7 @@
         this.getMap().setCursor(this.asCursor);
         /*map units for tool tip*/
         this.units = this.getMap().getAllMaps()[0].units;
+        this.getMap().supressContextMenu(true);
         this.triggerEvent(Fusion.Event.RADIUS_WIDGET_ACTIVATED, true);
     },
 
@@ -124,6 +125,7 @@
     deactivate: function() {
         this.handler.deactivate();
         this.getMap().setCursor('auto');
+        this.getMap().supressContextMenu(false);
         /*icon button*/
         this.triggerEvent(Fusion.Event.RADIUS_WIDGET_ACTIVATED, false);
     },

Modified: branches/fusion-2.0/widgets/SelectWithin/SelectWithin.php
===================================================================
--- branches/fusion-2.0/widgets/SelectWithin/SelectWithin.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/SelectWithin/SelectWithin.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -26,6 +26,11 @@
 
   $fusionMGpath = '../../layers/MapGuide/php/';
   include $fusionMGpath . 'Common.php';
+  if(InitializationErrorOccurred())
+  {
+      DisplayInitializationErrorText();
+      exit;
+  }
   include $fusionMGpath . 'Utilities.php';
   include('../../common/php/Utilities.php');
 
@@ -43,7 +48,7 @@
     //load the map runtime state
     $map = new MgMap();
     $map->Open($resourceService, $mapName);
-    
+
     //object to hold response
     $result = NULL;
     $result->hasSelection = false;
@@ -59,7 +64,7 @@
       for ($i = 0; $i < count($layers); $i++) {
         $layerNames->Add($layers[$i]);
       }
-      
+
       // create a multi-polygon or a multi-geometry containing the input selected features
       $inputGeom = MultiGeometryFromSelection($featureSrvc, $resourceService, $map, $mapName);
       if ($inputGeom) {
@@ -69,15 +74,15 @@
           $resultSel = $fi->GetSelection();
           if( $resultSel) {
             $resultSel->Save($resourceService, $mapName);
-            
+
             //this needs to be re-opened for some reason
             $resultSel = new MgSelection($map);
             $resultSel->Open($resourceService, $mapName);
-	  
+
             $layers = $resultSel->GetLayers();
             if ($layers && $layers->GetCount() >= 0) {
               $result->hasSelection = true;
-              
+
               //set the extents for the selection object
               $oExtents = $resultSel->GetExtents($featureSrvc);
               if ($oExtents) {
@@ -96,7 +101,7 @@
                 $properties->extents->maxx = $oMax->GetX();
                 $properties->extents->maxy = $oMax->GetY();
               } else { echo "/* no extents */"; }
-              
+
               //get properties for individual features
               $result->layers = array();
               for ($i=0; $i<$layers->GetCount(); $i++) {
@@ -116,13 +121,13 @@
               }
 
               /*save selection in the session*/
-              $_SESSION['selection_array'] = $properties; 
+              $_SESSION['selection_array'] = $properties;
             } else { echo "/* layers false or 0 */"; }
           } else { echo "/* no resultsel */"; }
         } else { echo "/* no fi */"; }
       } else { echo "/*no multi geom*/"; }
     } else { echo "/* no layers */"; }
-    
+
     header('Content-type: application/json');
     header('X-JSON: true');
     echo var2json($result);
@@ -143,7 +148,7 @@
     }
     $geomColl = new MgGeometryCollection();
     $agfRW = new MgAgfReaderWriter();
-    $polyOnly = true;
+    $simplyPolygonOnly = true;
 
     for($i = 0; $i < $selLayers->GetCount(); $i++)
     {
@@ -157,23 +162,18 @@
         {
             $classDef = $features->GetClassDefinition();
             $geomPropName = $classDef->GetDefaultGeometryPropertyName();
-            $j = 0;
-            $isPoly = true;
             while($features->ReadNext())
             {
                 $geomReader = $features->GetGeometry($geomPropName);
                 $geom = $agfRW->Read($geomReader);
-                if($j ++ == 0)
+                $type = $geom->GetGeometryType();
+                if($type == MgGeometryType::MultiPolygon || $type == MgGeometryType::CurvePolygon || $type == MgGeometryType::MultiCurvePolygon)
                 {
-                    $type = $geom->GetGeometryType();
-                    if($type == MgGeometryType::MultiPolygon || $type == MgGeometryType::CurvePolygon || $type == MgGeometryType::MultiCurvePolygon)
-                    {
-                        $isPoly = false;
-                        $polyOnly = false;
-                    }
-                    else if($type != MgGeometryType::Polygon)
-                        break;
+                    $simplyPolygonOnly = false; 
                 }
+                else if($type != MgGeometryType::Polygon)
+                    continue;
+                    
                 $geomColl->Add($geom);
             }
             $features->Close();
@@ -183,7 +183,7 @@
         return null;
 
     $gf = new MgGeometryFactory();
-    if($polyOnly)
+    if($simplyPolygonOnly)
     {
         $polyColl = new MgPolygonCollection();
         for($i = 0; $i < $geomColl->GetCount(); $i++)

Modified: branches/fusion-2.0/widgets/SelectWithin/SelectWithinPanel.php
===================================================================
--- branches/fusion-2.0/widgets/SelectWithin/SelectWithinPanel.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/SelectWithin/SelectWithinPanel.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -26,6 +26,11 @@
 
     $fusionMGpath = '../../layers/MapGuide/php/';
     include $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
 
     $locale = GetDefaultLocale();
     $popup = "";

Modified: branches/fusion-2.0/widgets/TaskPane/TaskPane.html
===================================================================
--- branches/fusion-2.0/widgets/TaskPane/TaskPane.html	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/TaskPane/TaskPane.html	2010-03-24 18:31:34 UTC (rev 2105)
@@ -1,4 +1,4 @@
-<html>
+<html>
 <head>
 <style type="text/css">
     @import url(TaskPane.css);

Modified: branches/fusion-2.0/widgets/TaskPane.js
===================================================================
--- branches/fusion-2.0/widgets/TaskPane.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/TaskPane.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -28,11 +28,12 @@
  *
  * A utility widget that holds output from other widgets.
  ****************************************************************************/
+ 
+Fusion.Event.TASK_PANE_LOADED = Fusion.Event.lastEventId++;
 
-
 Fusion.Widget.TaskPane = OpenLayers.Class(Fusion.Widget, {
     aExecutedTasks: null,   //array of URLs for tasks execcuted in the TaskPane
-    nCurrentTask: 0,
+    nCurrentTask: -1,
     nTasks: 0,
     
     initializeWidget: function(widgetTag){
@@ -125,8 +126,9 @@
         //is added to the DOM
         this.oTaskPane.domObj.resize();
         
+        Fusion.registerEventID(Fusion.Event.TASK_PANE_LOADED);
         Fusion.registerForEvent(Fusion.Event.FUSION_INITIALIZED, OpenLayers.Function.bind(this.setTaskMenu, this));
-        this.getMap().registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.setContent, this, initialTask));
+        this.getMap().registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.setInitialContent, this, initialTask));
     },
     
     updateButtons: function() {
@@ -136,30 +138,57 @@
     
     gotoPrevTask: function() {
         this.nCurrentTask = this.nCurrentTask>0 ? --this.nCurrentTask : 0;
-        this.iframe.src = this.aExecutedTasks[this.nCurrentTask];
-        this.updateButtons();
+        var url = this.aExecutedTasks[this.nCurrentTask];
+        this.loadFrame(url);
     },
 
     gotoNextTask: function() {
         this.nCurrentTask = this.nCurrentTask<this.aExecutedTasks.length-1 ? 
                           ++this.nCurrentTask : this.aExecutedTasks.length-1;
-        this.iframe.src = this.aExecutedTasks[this.nCurrentTask];
-        this.updateButtons();
+        var url = this.aExecutedTasks[this.nCurrentTask];
+        this.loadFrame(url);
     },
 
     goHome: function() {
         this.nCurrentTask = 0;
-        this.iframe.src = this.aExecutedTasks[this.nCurrentTask];
-        this.updateButtons();
+        var url = this.aExecutedTasks[this.nCurrentTask];
+        this.loadFrame(url);
     },
 
+    setInitialContent: function(url) {
+        this.aExecutedTasks = [];
+        this.nCurrentTask = 0;
+        this.setContent(url);
+    },
+
     setContent: function(url) {
-        if (this.nCurrentTask < this.aExecutedTasks.length) {
-            this.aExecutedTasks.splice(this.nCurrentTask, this.aExecutedTasks.length - this.nCurrentTask);
+        Fusion.triggerEvent(Fusion.Event.TASK_PANE_LOADED);
+        
+        if (this.nCurrentTask < this.aExecutedTasks.length-1) {
+            //this.aExecutedTasks.splice(this.nCurrentTask, this.aExecutedTasks.length - this.nCurrentTask);
         }
         
-        this.aExecutedTasks.push(url);
+        //add in some common parameters if they aren't supplied already
+        var baseUrl = url.split("?");
+        var params = OpenLayers.Util.getParameters(url);
+        var mapLayers = this.getMap().getAllMaps();
+        if (!params["LOCALE"] && !params["locale"]) {
+          params["locale"] = Fusion.locale;
+        }
+        if (!params["SESSION"] && !params["session"]) {
+          params["session"] = mapLayers[0].getSessionID();
+        }
+        if (!params["MAPNAME"] && !params["mapname"]) {
+          params["mapname"] = mapLayers[0].getMapName();
+        }
+        var newUrl = baseUrl[0] + "?" + OpenLayers.Util.getParameterString(params);
+        
+        this.aExecutedTasks.push(newUrl);
         ++this.nCurrentTask;
+        this.loadFrame(url);
+    },
+    
+    loadFrame: function(url) {
         this.iframe.src = url;
         this.iframe.taskPaneId = this.widgetTag.name;
         this.updateButtons();
@@ -170,7 +199,7 @@
      * have been created.
      *
      */
-    setTaskMenu : function() {
+    setTaskMenu: function() {
         if (this.menuName) {
             var container = this.getMap().widgetSet.getContainerByName(this.menuName);
             if (container) {

Modified: branches/fusion-2.0/widgets/Theme/classes/theme.php
===================================================================
--- branches/fusion-2.0/widgets/Theme/classes/theme.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Theme/classes/theme.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -53,7 +53,10 @@
             if((substr($layer->GetName(), 0, 1) != "_") && (substr(strtoupper($layer->GetFeatureSourceId()), 0, 7) != "SESSION"))
             {
                 $resId = new MgResourceIdentifier($layer->GetFeatureSourceId());
-                $schemaClass = explode(':', $layer->GetFeatureClassName());
+                $layerFeatureClassName = $layer->GetFeatureClassName();
+                if($layerFeatureClassName == "") 
+                    continue;
+                $schemaClass = explode(':', $layerFeatureClassName);
 
                 $classDef = $featureService->GetClassDefinition($resId, $schemaClass[0], $schemaClass[1]);
                 $propDef = $classDef->GetProperties()->GetItem($layer->GetFeatureGeometryName());
@@ -147,6 +150,8 @@
 
         $featureService = $this->site->CreateService(MgServiceType::FeatureService);
         $resId = new MgResourceIdentifier($layer->GetFeatureSourceId());
+        
+        $filter = $layer->GetFilter();
 
 // Note: Should be able to do this:
 //
@@ -177,6 +182,8 @@
 
         $queryOptions = new MgFeatureQueryOptions();
         $queryOptions->AddFeatureProperty($this->args['PROPERTYNAME']);
+        if($filter != '')
+            $queryOptions->SetFilter($filter);
 
         $featureReader = $featureService->SelectFeatures($resId, $layer->GetFeatureClassName(), $queryOptions);
 
@@ -221,17 +228,27 @@
         $resId = new MgResourceIdentifier($layer->GetFeatureSourceId());
         $layerDefResId = $layer->GetLayerDefinition();
         $byteReader = $resourceService->GetResourceContent($layerDefResId);
+        
+        $filter = $layer->GetFilter();
 
         // Load the Layer Definition and Navigate to the specified <VectorScaleRange>
 
         $doc = DOMDocument::loadXML($byteReader->ToString());
         $version = $doc->documentElement->getAttribute('version');
         $template = 'templates/arearuletemplate-'.$version.'.xml';
-        $nodeList = $doc->getElementsByTagName('VectorScaleRange');
+        $layerDefList = $doc->getElementsByTagName('VectorLayerDefinition');
+        $layerDef = $layerDefList->item(0);
+        $nodeList = $layerDef->getElementsByTagName('VectorScaleRange');
 
         $vectorScaleRangecElement = $nodeList->item($this->args['SCALERANGEINDEX']);
+        $listLength = $nodeList->length;
+        for($index = 0; $index < $listLength; $index++)
+        {
+            $layerDef->removeChild($nodeList->item(0));
+        }
+        $layerDef->appendChild($vectorScaleRangecElement);
         $areaTypeStyle = $vectorScaleRangecElement->getElementsByTagName('AreaTypeStyle')->item(0);
-
+        
         // Remove any existing <AreaRule> elements.
 
         $areaRuleList = $areaTypeStyle->getElementsByTagName('AreaRule');
@@ -241,6 +258,11 @@
             $areaTypeStyle->removeChild($areaRuleList->item(0));
         }
 
+        $hasChild = $areaTypeStyle->hasChildNodes();
+        if($hasChild)
+        {
+          $element = $areaTypeStyle->childNodes->item(0);
+        }
 
         // Now create the new <AreaRule> elements.
 
@@ -252,33 +274,52 @@
 
         if ($this->args['DISTRO'] == 'INDIV_DIST')
         {
+            $values = array();
+            
             $aggregateOptions->AddFeatureProperty($this->args['PROPERTYNAME']);
             $aggregateOptions->SelectDistinct(true);
-
-            $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions);
+            if($filter != '')
+                $aggregateOptions->SetFilter($filter);
+            $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions);            
             while ($dataReader->ReadNext())
             {
                 $value = $this->GetFeaturePropertyValue($dataReader, $this->args['PROPERTYNAME']);
+                array_push($values, $value);
+            }
+            $dataReader->Close();
+            
+            if ($this->args['DATATYPE'] == MgPropertyType::String)
+                sort($values, SORT_STRING);
+            else
+                sort($values, SORT_NUMERIC);
 
+            for ($i = 0; $i < count($values); $i++)
+            {
                 $filterText = '&quot;' . $this->args['PROPERTYNAME'] . '&quot; = ';
                 if ($this->args['DATATYPE'] == MgPropertyType::String)
-                    $filterText .= "'" . $value . "'";
+                    $filterText .= "'" . $values[$i] . "'";
                 else
-                    $filterText .= $value;
-
+                    $filterText .= $values[$i];
+                    
                 $areaRuleXML = sprintf($areaRuleTemplate,
-                    $this->args['PROPERTYNAME'] . ': ' . $value,
+                    $this->args['PROPERTYNAME'] . ': ' . $values[$i],
                     $filterText,
                     $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']),
                     $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0));
 
                 $areaDoc = DOMDocument::loadXML($areaRuleXML);
                 $areaNode = $doc->importNode($areaDoc->documentElement, true);
-                $areaTypeStyle->appendChild($areaNode);
+                if($hasChild)
+                {
+                  $areaTypeStyle->insertBefore($areaNode, $element);
+                }
+                else
+                {
+                  $areaTypeStyle->appendChild($areaNode);
+                }
 
                 $portion += $increment;
             }
-            $dataReader->Close();
         }
         else
         {
@@ -286,6 +327,8 @@
 
             $aggregateOptions->AddComputedProperty('THEME_VALUE',
                 $this->args['DISTRO'] . '("' . $this->args['PROPERTYNAME'] . '",' . $this->args['NUMRULES'] . ',' . $this->args['MINVALUE'] . ',' . $this->args['MAXVALUE'] . ')');
+            if($filter != '')
+                $aggregateOptions->SetFilter($filter);
 
             $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions);
             while ($dataReader->ReadNext())
@@ -298,7 +341,7 @@
             for ($i = 0; $i < count($values) - 1; $i++)
             {
                 $filterText = '&quot;' . $this->args['PROPERTYNAME'] . '&quot; &gt;= ' . $values[$i] . ' AND &quot;' . $this->args['PROPERTYNAME'];
-                if ($i == count($values) - 1)
+                if ($i == count($values) - 2)
                     $filterText .= '&quot; &lt;= ' . $values[$i + 1];
                 else
                     $filterText .= '&quot; &lt; ' . $values[$i + 1];
@@ -311,7 +354,14 @@
 
                 $areaDoc = DOMDocument::loadXML($areaRuleXML);
                 $areaNode = $doc->importNode($areaDoc->documentElement, true);
-                $areaTypeStyle->appendChild($areaNode);
+                if($hasChild)
+                {
+                   $areaTypeStyle->insertBefore($areaNode, $element);
+                }
+                else
+                {
+                   $areaTypeStyle->appendChild($areaNode);
+                }
 
                 $portion += $increment;
             }

Modified: branches/fusion-2.0/widgets/Theme/themecontroller.php
===================================================================
--- branches/fusion-2.0/widgets/Theme/themecontroller.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Theme/themecontroller.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -18,6 +18,11 @@
 //
     $fusionMGpath = '../../layers/MapGuide/php/';
     require_once $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
     require_once $fusionMGpath . 'Utilities.php';
     require_once $fusionMGpath . 'JSON.php';
     require_once 'classes/theme.php';
@@ -55,7 +60,7 @@
         header('Content-Type: ' . $responseType);
         echo $response;
         exit;
-      }     
+      }
       catch (MgException $mge)
       {
           $errorMsg = $mge->GetMessage();
@@ -70,4 +75,4 @@
     <tr><td class="Title">Error<hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
     <tr><td><?= $errorDetail ?></td></tr>
-</table>
\ No newline at end of file
+</table>

Modified: branches/fusion-2.0/widgets/Theme/thememain.php
===================================================================
--- branches/fusion-2.0/widgets/Theme/thememain.php	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Theme/thememain.php	2010-03-24 18:31:34 UTC (rev 2105)
@@ -18,14 +18,51 @@
 //
     $fusionMGpath = '../../layers/MapGuide/php/';
     require_once $fusionMGpath . 'Common.php';
+    if(InitializationErrorOccurred())
+    {
+        DisplayInitializationErrorHTML();
+        exit;
+    }
     require_once $fusionMGpath . 'Utilities.php';
     require_once $fusionMGpath . 'JSON.php';
     require_once 'classes/theme.php';
+    
+    SetLocalizedFilesPath(GetLocalizationPath());
+    if(isset($_REQUEST['locale'])) {
+        $locale = $_REQUEST['locale'];
+    } else {
+        $locale = GetDefaultLocale();
+    }
 
     $args = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_GET;
 
     $errorMsg = null;
     $errorDetail = null;
+    
+    $titleLocal = GetLocalizedString('THEMETITLE', $locale );
+    $selectLayerLocal = GetLocalizedString('THEMESELECTLAYER', $locale );
+    $layerLocal = GetLocalizedString('THEMELAYER', $locale );
+    $nameLocal = GetLocalizedString('THEMENAME', $locale );
+    $conditionLocal = GetLocalizedString('THEMECONDITIONS', $locale );
+    $propertyLocal = GetLocalizedString('THEMEPROPERTY', $locale );
+    $minLocal = GetLocalizedString('THEMEMIN', $locale );
+    $maxLocal = GetLocalizedString('THEMEMAX', $locale );
+    $distributionLocal = GetLocalizedString('THEMEDISTRIBUTION', $locale );
+    $ruleLocal = GetLocalizedString('THEMERULE', $locale );
+    $scaleRangeLocal = GetLocalizedString('THEMESCALERANGE', $locale );
+    $styleRampLocal = GetLocalizedString('THEMESTYLERAMP', $locale );
+    $fillTransparencyLocal = GetLocalizedString('THEMEFILLTRANS', $locale );
+    $fillColorLocal = GetLocalizedString('THEMEFILLCOLOR', $locale );
+    $fromLocal = GetLocalizedString('THEMEFROM', $locale );
+    $toLocal = GetLocalizedString('THEMETO', $locale );
+    $borderColorLocal = GetLocalizedString('THEMEBORDERCOLOR', $locale );
+    $applyLocal = GetLocalizedString('THEMEAPPLY', $locale );
+    $errorLocal = GetLocalizedString('THEMEERROR', $locale );
+    $individualLocal = GetLocalizedString('THEMEINDIVIDUAL', $locale );
+    $equalLocal = GetLocalizedString('THEMEEQUAL', $locale );
+    $standardDeviationLocal = GetLocalizedString('THEMESTANDARD', $locale );
+    $quantileLocal = GetLocalizedString('THEMEQUANTILE', $locale );
+    $jenksLocal = GetLocalizedString('THEMEJENKS', $locale );
 
     try
     {
@@ -47,7 +84,7 @@
 ?>
 <html>
 <head>
-    <title>Theme Layer</title>
+    <title><?php echo $titleLocal ?></title>
     <link rel="stylesheet" href="../../common/mgsamples.css" type="text/css">
     <script language="javascript" src="../../common/browserdetect.js"></script>
     <script language="javascript" src="../../common/json.js"></script>
@@ -75,7 +112,7 @@
         var session = '<?= $args['SESSION'] ?>';
         var mapName = '<?= $args['MAPNAME'] ?>';
 
-        var distNameArray = '<?php $json = new Services_JSON(); echo $json->encode($theme->distNameArray) ?>'.parseJSON();
+        var distNameArray = ['<?= $individualLocal ?>', '<?= $equalLocal ?>', '<?= $standardDeviationLocal ?>', '<?= $quantileLocal  ?>', '<?= $jenksLocal ?>']; 
         var distValueArray = '<?php $json = new Services_JSON(); echo $json->encode($theme->distValueArray) ?>'.parseJSON();
 
         var themeReqHandler = null;
@@ -87,6 +124,11 @@
         function OnLayerChange()
         {
             var layerSelect = document.getElementById("layerSelect");
+
+            if(layerSelect.value == ""){
+                return;
+            }
+
             var propertySelect = document.getElementById("propertySelect");
             var scaleSelect = document.getElementById("scaleSelect");
 
@@ -336,9 +378,9 @@
 <?php if ($errorMsg == null) { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%">
-    <tr><td colspan="2" class="Title"><img id="busyImg" src="../../common/images/loader_pulse.gif" style="vertical-align:bottom">&nbsp;Theme Layer<hr></td></tr>
-    <tr><td colspan="2" class="SubTitle">Select a Layer</td></tr>
-    <tr><td colspan="2">Layer:</td></tr>
+    <tr><td colspan="2" class="Title"><img id="busyImg" src="../../common/images/loader_pulse.gif" style="vertical-align:bottom">&nbsp;<?php echo $titleLocal ?><hr></td></tr>
+    <tr><td colspan="2" class="SubTitle"><?php echo $selectLayerLocal ?></td></tr>
+    <tr><td colspan="2"><?php echo $layerLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <select size="1" class="Ctrl" id="layerSelect" onChange="OnLayerChange()" style="width: 100%">
@@ -354,48 +396,48 @@
               </select>
         </td>
     </tr>
-    <tr><td colspan="2">Theme Name:</td></tr>
+    <tr><td colspan="2"><?php echo $nameLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <input maxlength="100" class="Ctrl" id="themeName" style="width: 100%">
         </td>
     </tr>
     <tr><td colspan="2" class="Spacer"></td></tr>
-    <tr><td colspan="2" class="SubTitle">Define Conditions</td></tr>
-    <tr><td colspan="2">Property:</td></tr>
+    <tr><td colspan="2" class="SubTitle"><?php echo $conditionLocal ?></td></tr>
+    <tr><td colspan="2"><?php echo $propertyLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <select size="1" class="Ctrl" id="propertySelect" onChange="OnPropertyChange()" style="width: 100%">
               </select>
         </td>
     </tr>
-    <tr><td colspan="2">Min:</td></tr>
+    <tr><td colspan="2"><?php echo $minLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <input maxlength="100" class="Ctrl" id="minValue" style="width: 100%">
         </td>
     </tr>
-    <tr><td colspan="2">Max:</td></tr>
+    <tr><td colspan="2"><?php echo $maxLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <input maxlength="100" class="Ctrl" id="maxValue" style="width: 100%">
         </td>
     </tr>
-    <tr><td colspan="2">Distribution:</td></tr>
+    <tr><td colspan="2"><?php echo $distributionLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <select size="1" class="Ctrl" id="distroSelect" onChange="OnDistroChange()" style="width: 100%">
               </select>
         </td>
     </tr>
-    <tr><td colspan="2"># of Rules:</td></tr>
+    <tr><td colspan="2"><?php echo $ruleLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <input maxlength="10" class="Ctrl" id="numRules" value="8" style="width: 100%">
         </td>
     </tr>
     <tr><td colspan="2" class="Spacer"></td></tr>
-    <tr><td colspan="2" class="SubTitle">Scale Range</td></tr>
+    <tr><td colspan="2" class="SubTitle"><?php echo $scaleRangeLocal ?></td></tr>
     <tr>
         <td colspan="2" class="RegText">
             <select size="1" class="Ctrl" id="scaleSelect" style="width: 100%">
@@ -403,57 +445,57 @@
         </td>
     </tr>
     <tr><td colspan="2" class="Spacer"></td></tr>
-    <tr><td colspan="2" class="SubTitle">Style Ramp</td></tr>
-    <tr><td>Fill Transparency:</td></tr>
+    <tr><td colspan="2" class="SubTitle"><?php echo $styleRampLocal ?></td></tr>
+    <tr><td><?php echo $fillTransparencyLocal ?></td></tr>
     <tr>
         <td  colspan="2" class="RegText">
             <input class="Ctrl" id="fillTrans" type="text"  maxlength="3" value="0" style="width:90%">&nbsp;%
         </td>
     </tr>
     <tr><td colspan="2" class="Spacer"></td></tr>
-    <tr><td>Fill Color:</td></tr>
+    <tr><td><?php echo $fillColorLocal ?></td></tr>
     <tr>
         <td valign="top">
-            &nbsp;&nbsp;&nbsp;From:<br>
+            &nbsp;&nbsp;&nbsp;<?php echo $fromLocal ?><br>
             &nbsp;&nbsp;&nbsp;<span class="Swatch" id="fillFromSwatch" style="color: #FF0000; background-color: #FF0000">&nbsp;transparent&nbsp;</span>&nbsp;&nbsp;
             <input class="Ctrl" type="button" value="..." style="width: 22px;" onClick="PickColor(SET_FILL_FROM_COLOR,false,false)">
         </td>
         <td valign="top">
-            &nbsp;&nbsp;&nbsp;To:<br>
+            &nbsp;&nbsp;&nbsp;<?php echo $toLocal ?><br>
             &nbsp;&nbsp;&nbsp;<span class="Swatch" id="fillToSwatch" style="color: #0000FF; background-color: #0000FF">&nbsp;transparent&nbsp;</span>&nbsp;&nbsp;
             <input class="Ctrl" type="button" value="..." style="width: 22px;" onClick="PickColor(SET_FILL_TO_COLOR,false,false)">
         </td>
     </tr>
     <tr><td colspan="2" class="Spacer"></td></tr>
-    <tr><td>Border Color:</td></tr>
+    <tr><td><?php echo $borderColorLocal ?></td></tr>
     <tr>
         <td valign="top">
-            &nbsp;&nbsp;&nbsp;From:<br>
+            &nbsp;&nbsp;&nbsp;<?php echo $fromLocal ?><br>
             &nbsp;&nbsp;&nbsp;<span class="Swatch" id="lineFromSwatch" style="color: #000000; background-color: #000000">&nbsp;transparent&nbsp;</span>&nbsp;&nbsp;
             <input class="Ctrl" type="button" value="..." style="width: 22px;" onClick="PickColor(SET_LINE_FROM_COLOR,false,false)">
         </td>
         <td valign="top">
-            &nbsp;&nbsp;&nbsp;To:<br>
+            &nbsp;&nbsp;&nbsp;<?php echo $toLocal ?><br>
             &nbsp;&nbsp;&nbsp;<span class="Swatch" id="lineToSwatch" style="color: #000000; background-color: #000000">&nbsp;transparent&nbsp;</span>&nbsp;&nbsp;
             <input class="Ctrl" type="button" value="..." style="width: 22px;" onClick="PickColor(SET_LINE_TO_COLOR,false,false)">
         </td>
     </tr>
     <tr><td colspan="2" class="Spacer"></td></tr>
     <tr><td colspan="2" ><hr></td></tr>
-    <tr><td colspan="2" align="right"><input class="Ctrl" type="button" value="Apply" style="width: 60px;" onClick="ApplyTheme()"></td></tr>
+    <tr><td colspan="2" align="right"><input class="Ctrl" type="button" value="<?php echo $applyLocal ?>" style="width: 60px;" onClick="ApplyTheme()"></td></tr>
 </table>
 
-<?php } else if ($errorDetail == null || (strlen($errorDetail) - strlen($errorMsg) < 5)) { ?> 
+<?php } else if ($errorDetail == null || (strlen($errorDetail) - strlen($errorMsg) < 5)) { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%%">
-    <tr><td class="Title">Error<hr></td></tr>
+    <tr><td class="Title"><?php echo $errorLocal ?><hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
 </table>
 
 <?php } else { ?>
 
 <table class="RegText" border="0" cellspacing="0" width="100%%">
-    <tr><td class="Title">Error<hr></td></tr>
+    <tr><td class="Title"><?php echo $errorLocal ?><hr></td></tr>
     <tr><td><?= $errorMsg ?></td></tr>
     <tr><td><?= $errorDetail ?></td></tr>
 </table>

Modified: branches/fusion-2.0/widgets/Theme.js
===================================================================
--- branches/fusion-2.0/widgets/Theme.js	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/Theme.js	2010-03-24 18:31:34 UTC (rev 2105)
@@ -36,6 +36,7 @@
  * **********************************************************************/
 
 Fusion.Widget.Theme = OpenLayers.Class(Fusion.Widget, {
+    isExclusive: true,
     uiClass: Jx.Button,
     sFeatures : 'menubar=no,location=no,resizable=no,status=no',
 

Modified: branches/fusion-2.0/widgets/widgetinfo/featureinfo.xml
===================================================================
--- branches/fusion-2.0/widgets/widgetinfo/featureinfo.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/widgetinfo/featureinfo.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -6,7 +6,7 @@
     <Label>Feature Info</Label>
     <Tooltip>Click to display selected feature info</Tooltip>
     <ImageUrl>images/icons.png</ImageUrl>
-    <ImageClass>invoke-url</ImageClass>
+    <ImageClass>featureinfo</ImageClass>
     <StandardUi>true</StandardUi>
     <ContainableBy>Any</ContainableBy>
     <Parameter>

Modified: branches/fusion-2.0/widgets/widgetinfo/measure.xml
===================================================================
--- branches/fusion-2.0/widgets/widgetinfo/measure.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/widgetinfo/measure.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -4,7 +4,7 @@
   <Description>A widget that allows measurements to be made on the map</Description>
   <Location></Location>
   <Label>Measure</Label>
-  <Tooltip>Measure distances on the map</Tooltip>
+  <Tooltip>Measure distances and areas on the map</Tooltip>
   <StatusText></StatusText>
   <ImageUrl>images/icons.png</ImageUrl>
   <ImageClass>measure</ImageClass>

Modified: branches/fusion-2.0/widgets/widgetinfo/query.xml
===================================================================
--- branches/fusion-2.0/widgets/widgetinfo/query.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/widgetinfo/query.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -6,7 +6,7 @@
     <Label>Query</Label>
     <Tooltip>Click to execute a custom query</Tooltip>
     <ImageUrl>images/icons.png</ImageUrl>
-    <ImageClass>invoke-url</ImageClass>
+    <ImageClass>query</ImageClass>
     <StandardUi>true</StandardUi>
     <ContainableBy>Any</ContainableBy>
     <Parameter>

Modified: branches/fusion-2.0/widgets/widgetinfo/redline.xml
===================================================================
--- branches/fusion-2.0/widgets/widgetinfo/redline.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/widgetinfo/redline.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -6,7 +6,7 @@
     <Label>Redline</Label>
     <Tooltip>Click to draw redline features</Tooltip>
     <ImageUrl>images/icons.png</ImageUrl>
-    <ImageClass>invoke-url</ImageClass>
+    <ImageClass>redline</ImageClass>
     <StandardUi>true</StandardUi>
     <ContainableBy>Any</ContainableBy>
     <Parameter>

Modified: branches/fusion-2.0/widgets/widgetinfo/selectioninfo.xml
===================================================================
--- branches/fusion-2.0/widgets/widgetinfo/selectioninfo.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/widgetinfo/selectioninfo.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -15,7 +15,7 @@
     <Description>The format of the output string.</Description>
     <Type>String</Type>
     <Label>Template</Label>
-    <DefaultValue>{0} features selected on {1} layers</DefaultValue>
+    <DefaultValue>{0} feature(s) selected on {1} layer(s)</DefaultValue>
     <IsMandatory>false</IsMandatory>
   </Parameter>
   <Parameter>

Modified: branches/fusion-2.0/widgets/widgetinfo/theme.xml
===================================================================
--- branches/fusion-2.0/widgets/widgetinfo/theme.xml	2010-03-24 18:03:23 UTC (rev 2104)
+++ branches/fusion-2.0/widgets/widgetinfo/theme.xml	2010-03-24 18:31:34 UTC (rev 2105)
@@ -6,7 +6,7 @@
     <Label>Theme</Label>
     <Tooltip>Click to create a themed layer</Tooltip>
     <ImageUrl>images/icons.png</ImageUrl>
-    <ImageClass>invoke-url</ImageClass>
+    <ImageClass>theme</ImageClass>
     <StandardUi>true</StandardUi>
     <ContainableBy>Any</ContainableBy>
     <Parameter>



More information about the fusion-commits mailing list