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

 **/

/*
// server variables
var gszAppRoot = 'http://atlas.2c1forest.org';
var gszPHPRelativeToFusion = '../php/';

// for saveMapLink default map loaded.
var gszMapFile = '/opt/wcs-fgs/apps/wcs-naecpa/map/themes/Base/elevation.map';
*/

var gszAppRoot = 'http://atlas.2c1forest.org/';
var gszPHPRelativeToFusion = '../php/';

// for saveMapLink default map loaded.
var gszMapFile = '/opt/wcs-fgs/apps/wcs-naecpa/map/themes/Base/elevation.map';
var gszTheme = 'Base';

var debugPDF = false;

// flag to set the metadata on fusions's default initialized map
var gbInitialMapMetaDataLoaded = false;

// get querystring.
var oQS = new queryString();
gszQSMapName = oQS.get("m");
gszQSGroupName = oQS.get("g");
var params = '';
 
if(gszQSMapName != null && gszQSGroupName != null ){
    gWillLoadFromQueryString = true;
    }
    else
    {
    gWillLoadFromQueryString = false;
    }



  resizeLayout = function() {
    var theBody = $('theBody').getSize();

    var pageSize = {}
    pageSize.height = theBody.y;
    pageSize.width =theBody.x;
    var newHeight = Math.max(200, pageSize.height - 240);
    
    $('mapAreaWraper').resize({height: newHeight});
    $('mapArea').resize({height: newHeight});
    $('mapToolbar').resize();
    $('rightFrame').resize({height: newHeight});
  }

window.onload = function(){
    if (document.all) {
    var pg = new Jx.Layout('thePage', {position:'relative', minWidth: 782, right: 0,onSizeChange:resizeLayout});
    } else {
    var pg = new Jx.Layout('thePage', {position:'relative', minWidth: 782, right: 19,onSizeChange:resizeLayout});
    }

    //pg.resize( pageSizeListener );
    new Jx.Layout('tabToolbar', {position:'relative'});
    new Jx.Layout('mapToolbar', {position:'relative', minWidth: 200, right: 250});
    new Jx.Layout('mapAreaWraper', {position:'relative', height:400, minWidth: 200, minHeight: 200, right: 200});
    new Jx.Layout('mapArea', {position:'relative',height: 400, minWidth: 200, minHeight: 200});
    var rf = new Jx.Layout('rightFrame', {position:'absolute', width:250, left: null,right:0,top:0});
    var rf2 = new Jx.Layout('rightTabset');
    
    var infoLayout = new Jx.Layout('infoArea', {position:'relative'});

// drawing tools toolbar


    var tabBox = new Jx.TabBox().add(
            new Jx.Button.Tab({label:'Atlas',content: 'addAtlas'}),
            new Jx.Button.Tab({label:'WMS',content: 'addWMS'})
        );

    d2 = new Jx.Dialog({
        id: 'WCSAddLayerDialog',
        label: 'Add Layer',
        modal: false,
        resize: false,
        width:400,
        height:400,
        content: tabBox
    });

    var tabBox2 = new Jx.TabBox().add(
           // new Jx.Button.Tab({label:'Add Point',content: 'addPoint'}),
            new Jx.Button.Tab({label:'Add GPS',content: 'importGPS'}),
            new Jx.Button.Tab({label:'Add Shapefile',content: 'importShapefile'})
        );

    addData = new Jx.Dialog({
        id: 'WCSAddData',
        label: 'Add Map Data',
        modal: false,
        resize: false,
        width:500,
        height:550,
        content: tabBox2
    });



// legend tools toolbar

  var legendtools = new Jx.Toolbar({scroll:false});
  legendtools.add( new Jx.Button({ image: 'images/icons/add.png', tooltip: 'Add layer', label: 'Add layer',onClick: function(){
                                    d2.open()
                                    } }));

// right tabs
/*

  var tabs = new Jx.Toolbar('tabToolbar');
  var tabset = new Jx.TabSet('rightTabset');

  //
  var t2 = new Jx.Button.Tab('Layers', {content: 'layerManager'});
  var t3 = new Jx.Button.Tab('My Map', {content: 'drawingPanel'});
  
  tabs.add( t2 , t3);
  tabset.add( t2, t3);

  */
/*
var legendPanel = new Jx.Panel({label: 'Display Legend', toolbar: $('legendToolbar'), tooltip: 'Show Legend' , contentID: 'layersArea'});
var drawingPanel = new Jx.Panel({label: 'Display Drawing Tools', toolbar: $('drawingToolbar'), tooltip: 'Show Drawing Tools', contentID: 'drawingArea'});
var layerManager = new Jx.Panel({label: 'Display Layer Manager', toolbar: $('layerManagerToolbar'), tooltip: 'Show Layer Manager', contentID: 'manageArea'});
*/


 var editToolbar = new Jx.Toolbar({id: 'EditToolbar', position: 'top'});

   var drawingPanel = new Jx.Panel({
       label: 'Features',
       contentId: 'drawingArea',
       collapse: false,
       maximize: true,
       hideTitle: true,
       toolbars: [editToolbar]
   });

    drawingtools = new Jx.Toolbar();
    
    var legendPanel =  new Jx.Panel({ label: 'Display Legend',contentId: 'layersArea', hideTitle: true});
   // var drawingPanel =  new Jx.Panel({ label: ' Drawing Tools',contentId: 'drawingArea',toolbars:[drawingtools], hideTitle: true});
    //drawingPanel.content.adopt(new Element('ul', {id: 'featureList'}));
    var layerManager =  new Jx.Panel({ label: 'Display Layer Manager',contentId: 'LayerManager', toolbars:[legendtools], hideTitle: true});
    
    var tabs = new Jx.Toolbar({parent: 'tabToolbar'});
    var tabset = new Jx.TabSet('rightTabset');

    var t1 = new Jx.Button.Tab({label:'Legend', content: legendPanel});
    var t2 = new Jx.Button.Tab({label:'Layers', content: layerManager});
    var t3 = new Jx.Button.Tab({label:'My Map', content: drawingPanel });

    tabs.add( t1, t2 , t3);
    tabset.add( t1, t2, t3);

   

  //rf.addSizeChangeListener(tabset);

// info tabs
/*
  var infoTabs = new Jx.Toolbar('infoTabbar', 'bottom');
  var infoTabContent = new Jx.TabSet('infoTabset');
*/
    var infoTabs = new Jx.Toolbar({scroll:false,parent: 'infoTabbar',position:'bottom'});
    var infoTabContent = new Jx.TabSet('infoTabset');


    //IE has an issue with the "position:'right'" set in the Button.Tab obj.

    var it1 = new Jx.Button.Tab({label:'Map Details',position:'relative',content: 'mapInfoArea',onDown: function(){infoLayout.resize();}});
    gIt2 = new Jx.Button.Tab({label: 'Layer Details',position:'relative',content: 'layerInfoArea',onDown: function(){infoLayout.resize();}});
    gIt3 = new Jx.Button.Tab({label: 'Query Details',position:'relative', content: 'queryInfoArea',onDown: function(){infoLayout.resize();}});
    var it4 = new Jx.Button.Tab({label:'Help',position:'relative',contentURL: 'help.html',onDown: function(){infoLayout.resize();}});
   
  
    infoTabs.add(it1, gIt2, gIt3,it4 );
    infoTabContent.add(it1, gIt2,gIt3,it4);

// save menu
  var saveMenu = new Jx.Menu({label: 'Save',tooltip: 'Save in multiple formats'});
  /*
  var saveLinkDialogObj = new Jx.Dialog(
        {
            title: 'Save Link',
            modal: false,
            parentObj: 'thePage',
            left: 200,
            top: 50,
            height: 150,
            helpHTML: '',
            contentID: 'saveLink',
            resizeable: false
        }
    );
*/

 var saveLinkDialogObj = new Jx.Dialog({
        label: 'Save Link',
        modal: false,
        width: 490,
        height: 150,
        content: 'saveLink'
        });

//  saveLinkDialogObj.domObj.id = "saveLinkDialog";

    saveMenu.add( new Jx.Menu.Item({
                                label: 'Save Map Link',
                                onClick: function(){
                                    saveLinkDialogObj.open()
                                    }
                            }));
    saveMenu.add( new Jx.Menu.Item({
                                label: 'Save Session',
                                onClick: function(){
                                    saveSession();
                                    }
                                }));
  /*
  var d1 = new Jx.Dialog(
        {
            title: 'Save Map Image',
            modal: false,
            parentObj: 'thePage',
            contentID: 'saveMapImage',
            handler: saveMapImageActions,
            height: 180,
            helpURL: null
        }
        */
 var d1 = new Jx.Dialog({
        label: 'Save Map Image',
        modal: false,
        width: 270,
        height: 200,
        content: 'saveMapImage'
        });

    saveMenu.add( new Jx.Menu.Item({label: 'Save Map Image', onClick: function(){d1.open()}}));
    
    var maptools = new Jx.Toolbar('mapToolbar');
    
    mapMenu = new Jx.Menu({label: 'Maps', tooltip: 'Select a map'}).addTo('mapToolbar');
    /*
    var loadSession = new Jx.Button.Flyout({
                                                    image: '',
                                                    tooltip: 'Load a session',
                                                    label: 'Load',
                                                    content: 'loadSheet' ,
                                                    onOpen:function(){
                                                            this.content.empty();
                                                            createSessionLoadForm(this.content);
                                                        }
                                                    }).addTo('mapToolbar');
    */
   loadSessionDialog = new Jx.Dialog({
        tooltip: 'Load a session',
        label: 'Load',
        content: 'loadSheet' ,
        onOpen:function(){
                this.content.empty();
                createSessionLoadForm(this.content);
            },
        modal: false,
        width: 320,
        height: 170,
        content: 'loadSheet'
        });
        
    var loadSession = new Jx.Button({label: 'Load', onClick: function(){loadSessionDialog.open()}})
    var addDataToMap = new Jx.Button({label: 'Add Data', onClick: function(){addData.open()}})
    
    loadSession.addTo('mapToolbar');
    addDataToMap.addTo('mapToolbar');
    saveMenu.addTo('mapToolbar');


  printSheetDialog = new Jx.Dialog({
        label: 'Print',
        modal: false,
        width: 270,
        height: 155,
        content: 'printViewSheet'
        });

  var quickViewDialog = new Jx.Dialog({
        label: 'Quickview',
        modal: false,
        width: 270,
        height: 365,
        content: 'quickviewSheet'
        });

  var panToDialog = new Jx.Dialog({
        label: 'Pan to',
        modal: false,
        width: 270,
        height: 200,
        content: 'zoomCcSheet'
        });
    
    var helpAtlas = new Jx.Button( {tooltip: 'Help on the Atlas', label: 'Help' , onClick:function(){showHelp()}});
    var printSheet= new Jx.Button({label: 'Print', onClick: function(){printSheetDialog.open()}})
    var quickView = new Jx.Button({label: 'Quickview', onClick: function(){quickViewDialog.open()}})
    var panTo = new Jx.Button({label: 'Pan To', onClick: function(){panToDialog.open()}})
    
    panTo.addTo('mapToolbar');
    quickView.addTo('mapToolbar');
    printSheet.addTo('mapToolbar');
    helpAtlas.addTo('mapToolbar');

  resizeLayout();
  $('thePage').style.visibility = 'visible';
  Fusion.initialize();

  Fusion.registerForEvent(Fusion.Event.FUSION_ERROR, onError);
  Fusion.registerForEvent(Fusion.Event.FUSION_INITIALIZED, onInitialize);
  
  // get menu items for big picture and my property

    var s = gszPHPRelativeToFusion + "enumerate.php";
    var opts = {parameters: params, onComplete: buildMenu.bind(null)};
    Fusion.ajaxRequest(s, opts);
  
};
function onError(eventId, error) {
   console.log('Fusion Error:\n'+error.toString());
}
/*
function saveMapImageActions - Js function for JX Dialog buttons
*/
function saveMapImageActions(){

    var saveMapImageFormat = $('saveMapImageFormat').value;
    saveMapImage(saveMapImageFormat,'');
}

/*
function onInitialize - Fusion.Event Handler
*/
function onInitialize() {
/*
    var pointFillColor = new Jx.Button.Color({
      color: '#00FF00',
      onChange: function() {  $('fillColor').value = this.options.color; }
    }).addTo('PointStyleFillColorButton');
    
    var pointOutlineColor = new Jx.Button.Color({
      color: '#00FF00',
      onChange: function() { $('strokeColor').value = this.options.color; }
    }).addTo('PointStyleOutlineColorButton');

    var lineOutlineColor = new Jx.Button.Color({
      color: '#00FF00',
      onChange: function() { $('strokeColor').value = this.options.color; }
    }).addTo('LineStyleColorButton');

    var polyOutlineColor = new Jx.Button.Color({
      color: '#00FF00',
      onChange: function() { $('strokeColor').value = this.options.color; }
    }).addTo('PolygonEdgeStyleColorButton');

    var polyFillColor = new Jx.Button.Color({
      color: '#00FF00',
      onChange: function() { $('fillColor').value = this.options.color; }
    }).addTo('PolygonFillForegroundStyleColorButton');
*/
    

    // render the flyouts with the colorPickers after fusion inits
    /*
    drawingtools.add(new Jx.Toolbar.Item($('LWE-DrawPoint')));
    
    var pointOptions = new Jx.Button.Flyout({content: 'pointOptions', tooltip: 'Edit Point Properties', halign: 'left' });
    pointOptions.domObj.addClass("drawingToolFlyout");
    drawingtools.add(pointOptions);

    drawingtools.add(new Jx.Toolbar.Item($('LWE-DrawLine')));
    
    var lineOptions = new Jx.Button.Flyout({content: 'lineOptions', tooltip: 'Edit Line Properties', halign: 'left' });
    lineOptions.domObj.addClass("drawingToolFlyout");
    drawingtools.add(lineOptions);
    
    drawingtools.add( new Jx.Toolbar.Item($('LWE-DrawPolygon')));
    
    var areaOptions =  new Jx.Button.Flyout({content: 'areaOptions', tooltip: 'Edit Polygon Properties', halign: 'left' });
    areaOptions.domObj.addClass("drawingToolFlyout");
    drawingtools.add(areaOptions);
    
    drawingtools.add(new Jx.Toolbar.Item($('LWE-DrawAnnotation')));
    
    var labelOptions = new Jx.Button.Flyout({content: 'labelOptions', tooltip: 'Edit Label Properties', halign: 'left' });
    labelOptions.domObj.addClass("drawingToolFlyout");
    drawingtools.add(labelOptions);
*/

   /* var a = Fusion.getWidgetsByType('Measure');
    if (a.length > 0) {
        a[0].registerForEvent(Fusion.Event.MEASURE_SEGMENT_COMPLETE, rulerDistanceChanged);
    }
    */
    
    $('thePage').resize();
	var map = Fusion.getMapById('mapArea');
    map.registerForEvent(Fusion.Event.MAP_LOADED, mapIsLoaded);
    map.registerForEvent(Fusion.Event.MAP_ACTIVE_LAYER_CHANGED, activeLayerChanged);
    map.registerForEvent(Fusion.Event.MAP_SELECTION_ON, selectionOn);
    map.registerForEvent(Fusion.Event.MAP_RELOADED, mapReloaded);
    
    var maps = map.getAllMaps();

    /*
    goFeatureManager = new Fusion.Tool.FeatureManager(maps[0]);
    if (goFeatureManager) {
        goFeatureManager.registerForEvent(Fusion.Event.FEATURE_ADDED, addToFeatureList);
        goFeatureManager.registerForEvent(Fusion.Event.FEATURE_DELETED, removeFromFeatureList);
    }
    */
	
	// for activityIndicator
    var widgets = Fusion.getWidgetsByType('ActivityIndicator');
    Element.addClass(widgets[0].domObj, 'activityIndicator');
}


/*
function showHelp - help clicked
*/
function showHelp(){
    document.location.href = "help.html";
    }
    
/*
function addToFeatureList - add LWE drawing to feature list.
*/
/*
function addToFeatureList(eventId, layer, features) {
    var ul = $('featureList');
    for (var i=0; i<features.length; i++) {
        this.createFeatureListEntry(ul, layer, features[i]);
        }
    Fusion.getMapById('mapArea').redraw();
}

function clearOutFeatureList(){
    var ul = $('featureList');
    ul.innerHTML = "";
}
*/
/*
function wcsGetFeatureType - returns text,point,line,ploy from feature type.
*/
/*
function wcsGetFeatureType(feature){
     switch(feature.getType()) {
        case Fusion.Constant.LAYER_POINT_TYPE:
            if (feature.properties['text']) {
                return "text";
            } else {
                return "point";
            }
            break;
        case Fusion.Constant.LAYER_LINE_TYPE:
            return "line";
            break;
        case Fusion.Constant.LAYER_POLYGON_TYPE:
            return "poly";
            break;
        }
}
*/
/*
function createFeatureListEntry - Creates the LI item when a feature is added.
*/
/*
function createFeatureListEntry(ul, layer, feature) {

    var li = document.createElement('li');
    li.className = 'lmFeatureEntry lmFeature_'+ feature.status;
    li.feature = feature;
    li.featureID = feature.identityProperties.id
    li.featureType = wcsGetFeatureType(feature);

    ul.appendChild(li);
    
    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.feature = feature;
    cb.toggleFeature = toggleFeature.bind(null, cb)
//     Event.observe(cb, 'click', cb.toggleFeature);
    cb.addEvent('click',cb.toggleFeature);
    li.appendChild(cb);
    cb.checked = feature.properties['visible'];

    var img = document.createElement('img');
    img.border = 0;
    img.width = 16;
    img.height = 16;
    img.className = "png24";

    switch(feature.getType()) {
        case Fusion.Constant.LAYER_POINT_TYPE:
            if (feature.properties['text']) {
                img.src = 'images/annotation.png';
            } else {
                img.src = 'images/point.png';
            }
            break;
        case Fusion.Constant.LAYER_LINE_TYPE:
            img.src = 'images/line.png';
            break;
        case Fusion.Constant.LAYER_POLYGON_TYPE:
            img.src = 'images/area.png';
            break;
            
    }
    li.appendChild(img);
    
    var span = document.createElement('span');
    span.className = 'lmFeatureLabel';
    if (feature.getType() == Fusion.Constant.LAYER_POINT_TYPE &&
        feature.properties['text']) {
            span.innerHTML = feature.properties['text'];
    } else {
        span.innerHTML = feature.properties['fname'];
    }
    li.appendChild(span);
    
    var a = document.createElement('a');
    a.href="javascript:void(0)";
    a.feature = feature;
    a.deleteFeature = deleteFeature.bind(null, a.feature);
    //Event.observe(a, 'click', a.deleteFeature);

    a.addEvent('click',a.deleteFeature);
    
    var img = document.createElement('img');
    img.border=0;
    img.width=16;
    img.height=16;
    img.src='images/feature-delete.png';
    a.appendChild(img);
    li.appendChild(a);
    
    return li;
}
*/
/*
function toggleFeature - sets the visible flag on or off on the LWE Feature.
*/
/*
function toggleFeature(obj) {
    if (obj.feature) {
        //console.log('toggle ' + obj.feature.properties['fname']);
        
        obj.feature.properties['visible'] = obj.checked ? 1 : 0;
        goFeatureManager.saveFeature(obj.feature);
    }
}
*/
/*
function deleteFeature - deletes the clicked feature
*/
/*
function deleteFeature(feature) {
    if (feature) {
        //console.log('delete ' + feature.properties['fname']);
        goFeatureManager.deleteFeature(feature);
            
        var featureID = feature.identityProperties.id
        removeFromFeatureList(featureID,feature);
    }
}
*/
/*
function removeFromFeatureList - removes the deleted item "<LI>" from the feature list
*/
/*
function removeFromFeatureList(featureID,featureObj) {
    var ul = $('featureList');
    var toRemove = [];
    for (var i=0; i<ul.childNodes.length; i++) {
        var li = ul.childNodes[i];
        var feature = li.feature;
        var featureType = wcsGetFeatureType(featureObj);
        
        if((feature.identityProperties.id == featureID) && (featureType == li.featureType )){
            ul.removeChild(li);
            }
    }
    Fusion.getMapById('mapArea').redraw();
} 
*/
/*
  function selectionOn - event handler for MAP_SELECTION_ON
*/
function selectionOn() {
    // click the tab.
    gIt3.clicked();
}

/*
  function selectionLoaded - process the selection and crete the html for query results.
*/
function selectionLoaded(oSelection) {
  
    // TY Paul S for your awesome query code ;)
    // u r welcome (PS)
    oDivID = $('queryResultsContent');

    oDivID.innerHTML = '';
    var nLayers = oSelection.getNumLayers();
    var nTotal = oSelection.getNumElements();
    var ul = document.createElement('ul');
    oDivID.appendChild(ul);
    for (var i=0; i<nLayers; i++) {
        var layerObj = oSelection.getLayer(i);
        var li = document.createElement('li');
        ul.appendChild(li);
        var span = document.createElement('span');
        span.innerHTML = layerObj.getName();
        li.appendChild(span);
        var dl = document.createElement('dl');
        li.appendChild(dl);
        var nElements = layerObj.getNumElements();
        var nProperties = layerObj.getNumProperties();
        var aProperties = layerObj.getPropertyNames();
        for (var j=0; j<nElements; j++) {
            var hr = document.createElement('hr');
            var dt = document.createElement('dt');
            dt.innerHTML = 'Feature: ' + layerObj.getElementValue(j,0);
            dl.appendChild(dt);
            var dd = document.createElement('dd');
            dl.appendChild(dd);
            var innerUL = document.createElement('ul');
            dd.appendChild(innerUL);
            for (var k=0; k<nProperties; k++) {
                var innerLI = document.createElement('li');
                innerLI.innerHTML = '<span class="selectionLabel">'+aProperties[k] + '</span> : <span class="selectionValue">' + layerObj.getElementValue(j,k) + "</span>";
                innerUL.appendChild(innerLI);
            }
        }
    }
    // click query tab.
    gIt3.clicked();
}

/*
function mapReloaded - Fusion.Event Handler
*/
function mapReloaded(){

	
}

/*
function mapIsLoaded -  Fusion.Event Handler
*/
function mapIsLoaded() {
     //console.log("MAP_LOADED");
    // create contents for session load iFRAME
    
    // populate the atlas layers
    catalogManagerInitialize();
    // load map from querystring
   
   	// load the initial map metadata
	if(gbInitialMapMetaDataLoaded == false){
		loadInitialMapMetadata()
		// done set to true
		gbInitialMapMetaDataLoaded = true;
		}
   
    if(gWillLoadFromQueryString == true){
		// finished with flag reset to false;
    	gWillLoadFromQueryString = false;
        loadMapFromQueryString(gszQSMapName,gszQSGroupName);
            if(typeof(gLoadTheme) != "undefined"){
            loadTheme(gLoadTheme.szDescription,gLoadTheme.szMapFile,gLoadTheme.szTheme,gLoadTheme.szName,gLoadTheme.szShortAbstract,gLoadTheme.szTitle);
            }
        }
// clear out layer info area.
var oLayerInfoArea = document.getElementById("layerInfoArea");
oLayerInfoArea.innerHTML = "";
}


/*
     function createSessionLoadForm - create load session iframe content so we can post form
                                      data into a php file to process the loaded session data(zip)
*/
function createSessionLoadForm(domObj){
    var iframe = new Element('iframe', {
        src: 'blank.html',
        styles: {
            width: '100%',
            overflow: 'hidden'
        },
        events: {
            'load' : function() {
                var mapWidget = Fusion.getMapById('mapArea');
                var maps = mapWidget.getAllMaps();
                var map = maps[0];

                var session = 'session='+map.getSessionID();
                var mapName = '&mapname='+ map._sMapname;
                var params = session+mapName;
                var url = gszAppRoot+"/php/sessionSave.php?"+params;

                var iFrameContent = "";
                iFrameContent = iFrameContent + '<form enctype="multipart/form-data" name="loadSessionForm" action="'+url+'" method="POST"><div class="sheets">';
                iFrameContent = iFrameContent + '<label>Load Session</label>';
                iFrameContent = iFrameContent + '<input type="file" name="sessionFile"/>';
                iFrameContent = iFrameContent + '<span class="jxClearer"></span>';
                iFrameContent = iFrameContent + '<span class="sheetTip">Upload a previously saved session file to continue mapping</span>';
                iFrameContent = iFrameContent + '<span class="jxClearer"></span>';
                iFrameContent = iFrameContent + '<div class="sheetButtons">';

                iFrameContent = iFrameContent + '<input type="button" name="Button" onclick="document.forms[0].submit();parent.loadSessionDialog.close();" value="OK" style="width:70px" />';
                iFrameContent = iFrameContent + '<input type="hidden" name="sessionAction" value="load" /></div>';
                iFrameContent = iFrameContent + '<span class="jxClearer"></span>';
                iFrameContent = iFrameContent + '</div></form>';

                //window.loadSessionIFrame.document.body.innerHTML = "";
                //window.loadSessionIFrame.document.body.innerHTML = iFrameContent;
                //debugger;

                var doc = this.contentDocument;
                // IE uses contentWindow FF uses contentDocument
                if (doc == undefined || doc == null)
                    doc = this.contentWindow.document;
                doc.body.innerHTML = '';
                doc.body.innerHTML = iFrameContent;
            }
        }
    });
    iframe.setAttribute('scrolling','no');
    domObj.adopt(iframe);
}

function rulerDistanceChanged(eventID,widget,marker){
    var totalDistance = 0;
    var units = "";
    for(var i=0;i<widget.distanceMarkers.length-1;i++){
        totalDistance = parseFloat(totalDistance) + Math.round(parseFloat(widget.distanceMarkers[i].distance*100) /100);
        units = widget.distanceMarkers[i].unitAbbr;
    }
    marker.domObj.innerHTML  = marker.domObj.innerHTML + " <br>(" + totalDistance+" "+units+")";
}


/*
     function mapBusy - Fusions event handler when the map is busy / loading.
*/
/*
function mapBusy() {
  var map = Fusion.getMapById('mapArea');
  
  // if a mapfile is loaded again before the first is loaded this never clears
  // check every second if the map is busy.
  if(typeof(gMapBusyClearer) == "undefined")
      {
      gMapBusyClearer = self.setInterval("mapBusy()",1000);
      }
    
  $('BusyIndicator').style.display = map.isBusy() ? 'block' : 'none';
  //console.log("mapBusy:"+map.isBusy());
}
*/

/*
     function buildMenu - parse the returned JSON object from enumerate.php
                          to build the leftnav and top menu.
*/
function buildMenu(r) {

eval('buildMenuObject='+r.responseText);


buildMenuObject.each(function(subMenu) {

    var szName = subMenu[0].group;
    var szName = szName.replace(/_/ig, " ");
    var saveSubMenu = new Jx.Menu.SubMenu({label: szName});
    mapMenu.add(saveSubMenu);

    subMenu.each(function(obj){
        var szName = obj.label;
        var szTheme = obj.group;
        var szDescription = obj.description;
        var szMapFile  = obj.filename;
		var szShortAbstract  = obj.shortabstract;
		var szTitle  = obj.title;
        saveSubMenu.add( new Jx.Menu.Item({
                                                                label: szName,
                                                                onClick: function(){
                                                                    loadTheme(szDescription, szMapFile, szTheme, szName,szShortAbstract,szTitle);
                                                                    }
                                                                }));
        });
    });
}

/*

loadMapFromQueryString - Called after buildMenu if the global gWillLoadFromQueryString
                         is set to true. Loops thru the buildMenuObject and loads the
                         selected map file from the name and group.
*/
function loadMapFromQueryString(szMapName,szMapGroup){
    // loop thru buildMenuObject looking for group and mapname
    for(var i=0;i<buildMenuObject.length;i++){
        for(var j=0;j<buildMenuObject[i].length;j++){
            // found group
			//console.log("g1:"+buildMenuObject[i][j].group);
			//console.log("g2:"+szMapGroup);
			
            if(buildMenuObject[i][j].group == szMapGroup){
				//console.log('--- found group');
                var szMapFileName = buildMenuObject[i][j].filename
                var szFileName = szMapFileName.slice(szMapFileName.lastIndexOf("/")+1,szMapFileName.length);
                // found map
				
				//console.log(szFileName +":"+ szMapName+".map")
				
                if(szFileName == szMapName+".map"){
					//console.log('--- found map');
                    var szName = buildMenuObject[i][j].label;
                    var szTheme = buildMenuObject[i][j].group;
                    var szDescription = buildMenuObject[i][j].description;
                    var szMapFile  = buildMenuObject[i][j].filename;
					var szShortAbstract  = buildMenuObject[i][j].shortabstract;
					var szTitle = buildMenuObject[i][j].title;
					
                    // load theme
                    gLoadTheme = {"szDescription":szDescription, "szMapFile":szMapFile, "szTheme":szTheme, "szName":szName,"szShortAbstract":szShortAbstract,"szTitle":szTitle};
                    loadTheme(gLoadTheme.szDescription,gLoadTheme.szMapFile,gLoadTheme.szTheme,gLoadTheme.szName,gLoadTheme.szShortAbstract,gLoadTheme.szTitle);
                    }
                }
            
            }
        }
}

/*
function buildSaveMapLink - Create the URL from the current map from the buildMenuObject
                            created in func. buildMenu
*/
function buildSaveMapLink(szMapName,szMapGroup){
    var szReturn = "";
    // loop thru buildMenuObject looking for group and mapname
    for(var i=0;i<buildMenuObject.length;i++){
        for(var j=0;j< buildMenuObject[i].length;j++){
            // found group
            if(buildMenuObject[i][j].group == szMapGroup){

                var szMapFileName = buildMenuObject[i][j].filename
                var szFileName = szMapFileName.slice(szMapFileName.lastIndexOf("/")+1,szMapFileName.length);
                
                var szReturnMapName = szMapName.slice(szMapName.lastIndexOf("/")+1,szMapName.length);
                szReturnMapName = szReturnMapName.split(".");
                
                // found map
                if(szMapFileName == szMapName){
                    var szName = buildMenuObject[i][j].label;
                    var szTheme = buildMenuObject[i][j].group;
                    var szDescription = buildMenuObject[i][j].description;
                    var szMapFile  = buildMenuObject[i][j].filename;
                    // load theme
                    var szReturn = gszAppRoot+'maps.html?m='+szReturnMapName[0]+'&g='+szMapGroup;
                    return szReturn;
                     }
                }
            
            }
        }
}
    
/*

buildMapUrls - This function goes thru the enumerated mapfiles and
               produces a list in console.log of the urls to load the
               map files. (administrative task)
*/
function buildMapUrls(){
	//console.log("name,group,url");
    for(var i=0;i<buildMenuObject.length;i++){
        for(var j=0;j< buildMenuObject[i].length;j++){
            var szMapFileName = buildMenuObject[i][j].filename
            var szFileName = szMapFileName.slice(szMapFileName.lastIndexOf("/")+1,szMapFileName.length);
            var szFileNameNoExtension = szFileName.slice(0,szFileName.indexOf("."));
           // console.log(buildMenuObject[i][j].label+","+buildMenuObject[i][j].group+","+"http://atlas.2c1forest.org/maps.html?m="+szFileNameNoExtension+"&g="+buildMenuObject[i][j].group);
        }
    }
}

/*
     function loadTheme - Load the selected map from the leftnav or top menu
                          also updates the 'mapInfoArea' with the content URL.
*/
function loadTheme(szDescription, szMapFile, szTheme, szName, szShortAbstract,szTitle) {

    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];

    if(gszMapFile != szMapFile ){
        // set new map file as current
        gszMapFile = szMapFile;
        map.loadMap(szMapFile);
		showMapMetadata(szDescription, szMapFile, szTheme, szName, szShortAbstract,szTitle);
        }
    // clear out features.
    //clearOutFeatureList();
   
}

function showMapMetadata(szDescription, szMapFile, szTheme, szName, szShortAbstract,szTitle){
	 // Update the application Title and subtitle
    var mainTitle = szTheme.replace(/_/ig, " ");
    var mainsubtitle = szName.replace(/_/ig, " ");
    
    document.getElementById("maintitle").innerHTML = szTitle;
    document.getElementById("mainsubtitle").innerHTML = szShortAbstract + ' &nbsp;<a href="#infoArea">Read more.</a>';
    
    // set globals for saveMapLink
    gszMapFile = szMapFile
    gszTheme = szTheme

    // update the mapInfoArea
    new Request.HTML({url:szDescription, update: $('mapInfoArea')}).get();
	}


/*
     function getMapDescription - Map Description is stored in an array when buildMenu is called
                                  the id of this description is bound to the link, this function
                                  returns the description.
*/
function getMapDescription(szId){
    return gMapDescription[szId];
}


/*
function queryString -
*/
function queryString(qs){
    this.params = {};
    this.get=queryString_get;

    if (qs == null)
        qs=location.search.substring(1,location.search.length);

    if (qs.length == 0) return;

    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&');
    
// split out each name=value pair
    for (var i=0;i<args.length;i++) {
        var value;
        var pair = args[i].split('=');
        var name = unescape(pair[0]);

        if (pair.length == 2)
            value = unescape(pair[1]);
        else
            value = name;
            
        this.params[name] = value;
    }
}

/*
function queryString_get - return the key values
*/
function queryString_get(key, default_) {
    // This silly looking line changes UNDEFINED to NULL
    if (default_ == null) default_ = null;
    
    var value=this.params[key];
    if (value==null) value=default_;
    
    return value;
}

/*
function activeLayerChanged - called on MAP_ACTIVE_LAYER_CHANGED  returns the associated
                              map file metadata then calls updateLayerDetails()

*/
function activeLayerChanged(eventID,layerObj){
    // call ajax to get the layer metadata
    var s = gszPHPRelativeToFusion + "getLayerMetadata.php";
    
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
    
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
    var params = session+mapName+"&selLayer="+layerObj.layerName;
    var opts = {parameters: params, onComplete: updateLayerDetails.bind(null)};
    Fusion.ajaxRequest(s, opts);
    }
    
/*
function updateLayerDetails(r) - Called from activeLayerChanged when a user clicks on a
                                 legend item we want to populate the LAYER DETAILS Tab
                                 witht he map's metadata.
                                 
                                 Then "CLICK" the "Layer Details" Tab.

*/
function updateLayerDetails(r){
    var szLayerMetaData = r.responseText;
    var oLayerInfoArea = document.getElementById("layerInfoArea");
    oLayerInfoArea.innerHTML = szLayerMetaData;
    gIt2.clicked();
    }

/*
     function saveMapImage - with the pdf framework create a pdf/jpg/gif/png using
                             the current extents and XML theme template(PDF) and
                             populate the hidden iFrame with the src to pass the
                             saved image / PDF to the user for download.

*/
// set to true to open it up in a new window
debugPDF = false;
function saveMapImage(szImgFormat,szTitle) {
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
    var szPixelWidth = $('pixelWidth').value;
    var szPixelHeight = $('pixelHeight').value;
    var szPortrait= false;
    
    if(szImgFormat == "pdf"){
         szPortrait = printSheet.content.getElementById('xmlTemplate').checked;
    }
    //var w = '&w='+map._nWidth;
    //var h = '&h='+map._nHeight;
    
    if(szPortrait == true){
        var template = "&template=template2";
        var w = '&w=432'
        var h = '&h=540'
        }
        else
        {
        var template = "&template=template1";
        var w = '&w=648'
        var h = '&h=394'
        }

    if(szPixelWidth != '' && szPixelHeight != '' && szImgFormat != 'pdf'){
        // Save Map Image
        var w = '&w='+szPixelWidth;
        var h = '&h='+szPixelHeight;
        }
    
    var aMapExtents = [];
    aMapExtents[0] = parseFloat(mapWidget._oCurrentExtents.left);
    aMapExtents[1] = parseFloat(mapWidget._oCurrentExtents.bottom);
    aMapExtents[2] = parseFloat(mapWidget._oCurrentExtents.right);
    aMapExtents[3] = parseFloat(mapWidget._oCurrentExtents.top);
    
    var paramExtents = "&extents="+aMapExtents;
    var params = session+mapName+w+h+template+paramExtents+"&selImageFormat="+szImgFormat+"&title="+szTitle
    var url = gszAppRoot+"/php/pdf/index.php?"+params;
    var oWindowSaveIframe = $("saveIframe");
    
    if (debugPDF== true) {
        window.open(url+params);
    }
    oWindowSaveIframe.src = url;
}

var gLastSavedExtents = "";
function loadExtents(){
    if(gLastSavedExtents.length >1){
        zoomToExtents(gLastSavedExtents[0],gLastSavedExtents[1],gLastSavedExtents[2],gLastSavedExtents[3])
    }
}

function saveExtents(){
    gLastSavedExtents = [];
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    gLastSavedExtents[0] = parseFloat(mapWidget._oCurrentExtents.left);
    gLastSavedExtents[1] = parseFloat(mapWidget._oCurrentExtents.bottom);
    gLastSavedExtents[2] = parseFloat(mapWidget._oCurrentExtents.right);
    gLastSavedExtents[3] = parseFloat(mapWidget._oCurrentExtents.top);

}

/*
     function updateZoomScale - AJAX Call to wcsReproject to take in lat long and reproject
                                wcsReproject.php returns JS OBJECT with x y and scale.
*/
function zoomScale(szScale,szX,szY){
    var s = gszPHPRelativeToFusion+ "wcsReproject.php";
    szScale = szScale.replace(/,/ig,"");
    szScale = szScale.replace(/\s/ig,"");
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
    var xParam = '&x=' + szX;
    var yParam = '&y=' +szY;
    var scaleParam = '&scale='+szScale;
    var params = session+mapName+xParam+yParam+scaleParam;
    var opts = {parameters: params, onComplete: updateZoomScale.bind(null)};
    Fusion.ajaxRequest(s, opts);
    }
/*
     function updateZoomScale - Call back that sets the current center xy and scale level from zoomScale
*/
function updateZoomScale(r){
    var o
    eval('o='+r.responseText);
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];

    mapWidget.zoom(parseFloat(o.x),parseFloat(o.y),1);
    mapWidget.zoomToScale(parseFloat(o.scale));
    }

/*
     function saveSession - pass extents, visable layers, session to hidden iframe to
                            have user download a zip file of the saved session.
*/
debugSaveSession = 1;
function saveSession(){
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
     
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
     
    var aMapExtents  = [];
     
    aMapExtents[0] = parseFloat(mapWidget._oCurrentExtents.left);
    aMapExtents[1] = parseFloat(mapWidget._oCurrentExtents.bottom);
    aMapExtents[2] = parseFloat(mapWidget._oCurrentExtents.right);
    aMapExtents[3] = parseFloat(mapWidget._oCurrentExtents.top);
     
     var extents = '&extents='+aMapExtents;
     var layers = '&layers='+map.aVisibleLayers;
     var params = session+mapName+extents+layers+"&sessionAction=save";
    
     var url = gszAppRoot+"/php/sessionSave.php?"+params;
     var oWindowSaveIframe = $("saveIframe");
/*    
     if(debugSaveSession == 1){
          window.open(url);
          }
          else
          {*/
          oWindowSaveIframe.src = url;
         // }
}
    
/*
     function quickViewSearch - Called onKeyUp for the search, then calls ajax to 'eomfTownshipLookup'
                                which reutnrs an JSON object array of the results.
                                using a SQLITE3 DB of locations and their coordinates.
*/
function quickViewSearch(szSearchString) {
    // clear it if cleared
    if (szSearchString.length > 0) {
        $('quickViewSearchResults').innerHTML = '';
    }
    
    if (szSearchString.length >= 1) {
        var s = gszPHPRelativeToFusion +"quickView.php";
        var mapWidget = Fusion.getMapById('mapArea');
        
        var maps = mapWidget.getAllMaps();
        var map = maps[0];
        var session = 'session='+map.getSessionID();
        var mapName = '&mapname='+ map._sMapname;
        var searchString = '&s='+szSearchString;
        var params = session+mapName+searchString;
        var opts = {parameters: params, onComplete: quickViewSearchCallBack.bind(null)};
        Fusion.ajaxRequest(s, opts);
        }
}     

/*
     function quickViewSearchCallBack - Clears the results DIV 'quickViewSearchResults' and then
                                        loops thru the JSON array of objects to 'addQuickViewSearchItem'
*/
function quickViewSearchCallBack(r) {
    var o;
    eval('o='+r.responseText);

    // clear the current search restuls.
    $('quickViewSearchResults').innerHTML = '';

    // loop through object array.
    for (i=0;i<o.length;i++) {
        addQuickViewSearchItem(o[i].name,o[i].minx,o[i].miny,o[i].maxx,o[i].maxy)      ;
    }
}
     
/*
     function addQuickViewSearchItem - Add an "a" tag to the search results which calles
                                       the function 'zoomToExtents' to change the extents.
*/
function addQuickViewSearchItem(name,minx,miny,maxx,maxy) {
    var oDiv = $('quickViewSearchResults');
    var sContent = oDiv.innerHTML;
    var sNewContent = '<a href="javascript:zoomToExtents('+minx+','+miny+','+maxx+','+maxy+')">'+name+'</a><br>';
    oDiv.innerHTML = sContent+sNewContent;
}

/*
     function zoomToExtents - zooms to a given set of extents.
*/
function zoomToExtents(minx,miny,maxx,maxy) {
    var a = [];
    a[0] = parseFloat(minx);
    a[1] = parseFloat(miny);
    a[2] = parseFloat(maxx);
    a[3] = parseFloat(maxy);
  
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
  
    map.mapWidget.setExtents(new OpenLayers.Bounds(a[0], a[1], a[2],  a[3]));
}

/*
function catalogManagerInitialize - Load browseCatalog and parse the catalog mapfile
                                    launch CB catalogListLayers to display the data.
*/
function catalogManagerInitialize(){
    
    var s = gszPHPRelativeToFusion + "browseCatalog.php";
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
    var action = '&action=listLayersAtlas';
    var params = session+mapName+action;
    var opts = {parameters: params, onComplete: catalogListLayers.bind(null)};
    Fusion.ajaxRequest(s, opts);
}
/*
function catalogListLayers - CB from catalogManagerInitialize() with object create the html
                             required to add the layers to the map. clicking on image spawns
                             addCatalogLayer which inturn add's the clicked layer to the map.
*/
function catalogListLayers(r){
    //global gCatalogLayersObj
    eval('gCatalogLayersObj='+r.responseText);
    if(gCatalogLayersObj.error){
        alert(gCatalogLayersObj.error);
        return;
    }
    //fred made me do it ;)
    if(gCatalogLayersObj[0].layertype == "wms"){
        var oDivID = $('catalogLayersContent');
        }
        else
        {
        var oDivID = $('catalogLayersContentAtlas');
        }
    oDivID.innerHTML = '';
    var ul = document.createElement('ul');
    ul.id = 'catalogListLayerUL';
    oDivID.appendChild(ul);
    var aImg = [];
    for(var i=0;i<gCatalogLayersObj.length;i++){
        
        var szOwsTitle = gCatalogLayersObj[i].owstitle;
        var li = document.createElement('li');
        ul.appendChild(li);
        if(gCatalogLayersObj[i].name !== null && gCatalogLayersObj[i].name !=="OGC:WMS" && gCatalogLayersObj[i].name.toUpperCase !=="WMS"){
            aImg[i] = document.createElement('img');

            aImg[i].border = 0;
            aImg[i].width = 16;
            aImg[i].height = 16;
            aImg[i].alt = 'Add Layer to map';
            aImg[i].title = 'Add Layer to map';
            aImg[i].src = 'images/icons/add.png';

            aImg[i].layertype = gCatalogLayersObj[i].layertype;
            aImg[i].layername =  gCatalogLayersObj[i].name;
            aImg[i].owstitle =  gCatalogLayersObj[i].owstitle;
            aImg[i].group =  gCatalogLayersObj[i].group;
            aImg[i].srs = gCatalogLayersObj[i].srs;
            aImg[i].imageFormat = gCatalogLayersObj[i].imageformat;
            aImg[i].servername = gCatalogLayersObj[i].servername;

            //aImg[i].addLayer = addCatalogLayer.bind(null);

            aImg[i].addEvent( 'click', function(){
                addCatalogLayer(this);
            });

            li.appendChild(aImg[i]);
        }
        
        var span = document.createElement('span');
        span.innerHTML = szOwsTitle;
        li.appendChild(span);
        }
}
/*
function addCatalogLayer - adds the clicked layer from the interface created by catalogListLayers
                           then loads browseCatalog.php to add the clicked layer to the current
                           session map file. calls addCatalogLayerCB for a return responce.

*/
function addCatalogLayer(cb){
    var s = gszPHPRelativeToFusion + "browseCatalog.php";
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
    
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
    var action = '&action=addLayer';
    
    var layertype     = '&layertype='     +cb.layertype;
    var layername     = '&layername='     +cb.layername;
    var group         = '&group='         +cb.group;
    var owstitle      = '&owstitle='      +cb.owstitle;
    var srs           = '&srs='           +cb.srs;
    var imageFormat   = '&imageFormat='   +cb.imageFormat;
    var servername    = '&servername='    +cb.servername;
    
    // switch image to a different src.
    cb.src = 'images/icons/legend-layer.png';
  
    var params = session+mapName+action+layertype+layername+group+owstitle+srs+imageFormat+servername;
    var opts = {parameters: params, onComplete: addCatalogLayerCB.bind(null)};
    Fusion.ajaxRequest(s, opts);
}
/*
function addCatalogLayerCB - CB func from addCatalogLayer. The Layer is now added to mapfile,
                             if o.addedLayer = true else something when wrong.
*/
function addCatalogLayerCB(r){
    var o = '';
    eval('o='+r.responseText);

        if(o.addedLayer == true){
          var map = Fusion.getMapById('mapArea');
          var maps = map.getAllMaps();
          maps[0].reloadMap();
        } else {
           // console.log('addCatalogLayerCB:could not add layer');
        }
}

/*
function wmsManagerInitialize - Call browseCatalog.php to return the WMS layers from server
                                entered in $('wmsServerName').value
*/
function wmsManagerInitialize(){
    var s = gszPHPRelativeToFusion + "browseCatalog.php";
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];
    var session = 'session='+map.getSessionID();
    var mapName = '&mapname='+ map._sMapname;
    var action = '&action=listLayersWMS';
    var serverName = '&server='+$('wmsServerName').value;
    var params = session+mapName+action+serverName;
    var opts = {parameters: params, onComplete: catalogListLayers.bind(null)};
    Fusion.ajaxRequest(s, opts);
}


/*
function loadInitialMapMetadata - load the initial map's metadata (loaded by fusion)
\
*/
function loadInitialMapMetadata(){
	var szDefaultMap = buildMenuObject[0][1];
	szDefaultMap.szDescription
    showMapMetadata(szDefaultMap.description, szDefaultMap.filename, szDefaultMap.group, szDefaultMap.label, szDefaultMap.shortabstract,szDefaultMap.title)
	}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
    
/*

function populateLWEInputs -  first argument is the cvs string. The following arguments are the id's
to where the split strings values gets passed to.
*/
function populateLWEInputs(){
    var args = populateLWEInputs.arguments;
    var aCSV = args[0].split(",");

    for (var i = 0; i < aCSV.length; i++) {
        //console.log(args[i+1]+":"+aCSV[i].trim());
        $(args[i+1]).value = aCSV[i].trim();
    }
}

function updateLayerSelect(szValue){
    $('wmsServerName').value= szValue;
}

