/**
 * Pollution Probe - OGWA
 *
 * $Id$
 *
 * Copyright (c) 2008, DM Solutions Group Inc.
 */
var gszAppRoot = '/map/';
var gszPHPRelativeToFusion = '../map/php/';
var gAppInit = false;
var gszActiveMap = "";
var gCatalogLayersObj = null;
var layerInfoArea = null;
var searchResluts = null;
var popupObjects = {};
var popupID = 0;
var popupLastID = 0;
var aLayerMetaData = [];
var aGraphs = [];

var myDate = new Date();
var currentYear = myDate.getFullYear();
var currentMonth = myDate.getMonth();
var currentDay = myDate.getDay();

/* CHANGE GRAPH DEFAULT DATE */
var beginYear = currentYear - 15;
var beginMonth = 1;
var beginDay = 1;

var gStartDate = beginMonth +"-"+beginDay+"-"+beginYear+" 0:0:0";
var gEndDate = currentMonth +"-"+currentDay+"-"+currentYear+" 0:0:0";

var colours = [];

colours.push("3EADFA");
colours.push("FF6351");
colours.push("53F1D5");
colours.push("D44DD7");
colours.push("AEF92E");
colours.push("FFC039");
colours.push("AF95DF");
colours.push("FBA3D0");
colours.push("95ED83");
colours.push("FFE431");


function getWindowDimensions() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  gInnerWidth = myWidth
  gInnerHeight = myHeight;

}

d = {
    aLog:[],
    isInitialized:false,
    docLoaded:false,
    oDom:null,
    logText:"",
    
    log:function(){
        if(typeof(arguments[0]) == "object"){
            this.showObject(arguments[0]);
        }
        else
        {
        this.aLog.push(this.styleValue(arguments[0]));
        }
        
        if(this.oDom !== null){
            this.refresh();
        }
    },
    
    refresh:function(){
        this.logText = "";
        for(var i=0;i<this.aLog.length;i++){
            var logEntry = this.aLog[i] + "<br>";
            this.logText = this.logText + logEntry;
        }
        this.oDom.innerHTML = this.logText;
    },
    
    init:function(){
        this.oDom = document.createElement("DIV");
        this.oDom.id = "errorDiv";
        this.oDom.className = "dragme";
        var oBodyTag = document.body;
        oBodyTag.appendChild(this.oDom);
        this.log('Initialized');
    },
    
    showObject:function(){
        for (var item in arguments[0]){
            if(typeof(arguments[0][item]) == "object"){
                this.aLog.push(this.styleAttribute(item)+" : "+this.styleValue(arguments[0][item]));
            }
            else
            {
            this.aLog.push(this.styleAttribute(item)+" : "+this.styleValue(arguments[0][item]));
            }
        }
    },
    
    styleValue:function(){
        return "<span class='values'>"+arguments[0]+"</span>";
    },
    
    styleAttribute:function(){
        return "<span class='attribute'>"+arguments[0]+"</span>";
    },

    clear:function(){
        this.aLog = [];
        this.oDom.innerHTML = "";
    }
    
}


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

// get querystring. 
var oQS = new queryString();

//gMapName = oQS.get("map");
//gLocale = oQS.get("locale");
gExtents = oQS.get("extents");

 
window.onload = function() {
    getWindowDimensions();
    OpenLayers.Lang.fr = {};
    Fusion.initializeLocale();
    OpenLayers.Util.extend(OpenLayers.Lang[Fusion.locale], OGWA.Strings[Fusion.locale]);
    // init debugger;
    d.init();
    // Layout Definitions
    new Jx.Layout('thePage', {});
    new Jx.Layout('titleArea', {height: 110, bottom: null});
    new Jx.Layout('workArea', {height: null, top: 110});
    new Jx.Layout('toolbar', {height: 30, bottom: null});
    new Jx.Layout('mainMap', {height: null, top: 30});
    
    var s = new Jx.Splitter('workArea', 
        { 
            splitInto:2, 
            elements:[$('mapArea'),$('sideBar')],
            layout:'horizontal',
            containerOptions: [{},{minWidth:2, width: 250}],
            snappers: [null,$('sidebarCollapse')]
        }
    );

    $('thePage').resize();
    $('mapArea').resize();

    // Dialog Definitions

    var dialogWidth = 300;
    var  dialogHeight= 300;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);
    
    var d1 = new Jx.Dialog(
        {
            title: OpenLayers.i18n('Layer Information'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: 'infoDialog', 
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: true
        }
    );
    d1.domObj.id = 'infoDialog';

    var dialogWidth = 300;
    var  dialogHeight= 300;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);

    var d2 = new Jx.Dialog(
        {
            title: OpenLayers.i18n('Add Layers'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: '', 
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: true
        }
    );
    d2.domObj.id = 'addDialog';
    
    var dialogWidth = 400;
    var  dialogHeight= 125;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);


    var d3 = new Jx.Dialog(
        {
            title: OpenLayers.i18n('Save Map Link'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: 'saveMapLinkDialogContent',
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: false
       }
    );
    d3.domObj.id = 'linkDialog';

    var dialogWidth = 350;
    var  dialogHeight= 125;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);
    
    var d4 = new Jx.Dialog(
        {
            title: OpenLayers.i18n('Save Map Image'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: 'saveMapImageDialogContent', 
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: false,
            moveable:false
        }
    );
    d4.domObj.id= 'saveDialog';

    var dialogWidth =400;
    var  dialogHeight= 400;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);
    
    layerInfoArea = new Jx.Dialog(
        {
            title: OpenLayers.i18n('Layer Info Area'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: 'layerInfoArea', 
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: false
        }
    );
    layerInfoArea.domObj.id = 'layerInfoDialog';

    var dialogWidth = 600;
    var  dialogHeight= 300;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);

    searchResluts= new Jx.Dialog(
        {
            title: OpenLayers.i18n('Search Results'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: 'searchResluts', 
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: true
        }
    );
    searchResluts.domObj.id = 'searchReslutsDialog';

    var dialogWidth = 300;
    var  dialogHeight= 300;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);

    addToGraphDialog = new Jx.Dialog(
        {
            title: OpenLayers.i18n('Add to graph'),
            modal: false, 
            parentObj: 'thePage', 
            contentID: 'addToGraph', 
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: true
        }
    );
    d1.domObj.id = 'infoDialog';

    var dialogWidth = 600;
    var  dialogHeight= 150;
    var positionTop = (gInnerHeight/2)-(dialogHeight/2);
    var positionLeft = (gInnerWidth/2)-(dialogWidth/2);

    debug = new Jx.Dialog(
        {
            title: 'Pauls Debugger',
            modal: false,
            parentObj: 'thePage',
            contentID: 'errorDiv',
            width: dialogWidth,
            height: dialogHeight,
            top:positionTop,
            left:positionLeft,
            resizeable: true
        }
    );
    debug.domObj.id = 'debugger';
    
    // Toolbar definitions

    // Actions
    var a = new Jx.Action(function() {});
    var a1 = new Jx.Action(d1.open.bind(d1));
    var a2 = new Jx.Action(d2.open.bind(d2));
    var a3 = new Jx.Action(d3.open.bind(d3));
    var a4 = new Jx.Action(d4.open.bind(d4));
    
    var a5 = new Jx.Action(executeSearch.bind());
    var a6 = new Jx.Action(clearGraphs.bind());
    
    // Buttons
    b1 = new Jx.Button.Flyout({ image: '', tooltip: OpenLayers.i18n('Search'), label: OpenLayers.i18n('Search'), contentID: 'searchSheet' });
    var b2 = new Jx.Button.Flyout({ image: '', tooltip: OpenLayers.i18n('Print'), label: OpenLayers.i18n('Print'), contentID: 'printSheet' });
    var b3 = new Jx.Button(a2, {image: 'images/icons/add.png', label: OpenLayers.i18n('Add a layer')});

    var b4= new Jx.Button(a5, {image: 'images/icons/search.png', label: ''});
    b5 = new Jx.Button.Flyout({ image: '', tooltip: OpenLayers.i18n('Options'), label: OpenLayers.i18n('Options'), contentID: 'dateSelector' });
    var b6= new Jx.Button.Flyout({ image: '', tooltip: OpenLayers.i18n('Info'), label: OpenLayers.i18n('Info'), contentID: 'info' });

    var b7= new Jx.Button(a6, {image: '', label: OpenLayers.i18n('Clear')});

    
    // Menu Items
    //var menu1item1 = new Jx.MenuItem(a, {label: 'Map 1'});
    //var menu1item2 = new Jx.MenuItem(a, {label: 'Map 2'});

    var menu2item1 = new Jx.MenuItem(a3, {label: OpenLayers.i18n('Save Map Link')});
    var menu2item2 = new Jx.MenuItem(a4, {label: OpenLayers.i18n('Save Map Image')});

    // Menus
    gMenu1 = new Jx.Menu({label: OpenLayers.i18n('Maps')});
    gMenu1.domObj.id = 'mapsMenu';
    var menu2 = new Jx.Menu({label: OpenLayers.i18n('Save')});

   // menu1.add(menu1item1, menu1item2);
    menu2.add(menu2item1, menu2item2);

    var addToolbar = new Jx.Toolbar('addToolbar');

    var toolbar = new Jx.Toolbar('toolbar');
    //var layerToolbar = new Jx.Toolbar('layerToolbar');
    var graphToolbar = new Jx.Toolbar('graphToolbar');



    // Panel definitions

    var layerManager = new Jx.Panel({ contentID: 'legendTab'});
    var graphManager = new Jx.Panel({toolbar: $('graphToolbar'), contentID: 'graphTab'});
    var addManager = new Jx.Panel({toolbar: $('addToolbar'), contentID: 'addTab'});

    
    // Toolbars

    var t4 = new Jx.Tab(OpenLayers.i18n('Atlas'), {contentID: 'addAtlas'});
    var t5 = new Jx.Tab(OpenLayers.i18n('Services'), {contentID: 'addWMS'});

    var addTabSet = new Jx.TabSet(addManager.content);

    addTabSet.add(t4, t5);
    addToolbar.add(t4, t5);
    

     
    toolbar.domObj.id= 'leftTools';
    toolbar.domObj.id= 'layerTools';

    toolbar.add( gMenu1,b1, b2, menu2,b6);
   // layerToolbar.add(b3);
    graphToolbar.add(b5);
    graphToolbar.add(b7);
    




    graphManager.content.jxLayout.addSizeChangeListener({
        sizeChanged: function() {
                updateGraph();
            }
    });

    // Tabbed Sidebar
    
    var t1 = new Jx.Tab(OpenLayers.i18n('Legend'),  {content: layerManager.domObj});
    var t2 = new Jx.Tab(OpenLayers.i18n('Layers'), {content: addManager.domObj});
    t3 = new Jx.Tab(OpenLayers.i18n('Graphs'), {content: graphManager.domObj});
    
    var tsb = new Jx.TabBox($('sideBar'), 'top');
    tsb.add(t1,t2, t3);

    // Tabbed Dialog



    var options = {};
    options.applicationDefinitionURL = szApplicationRoot+'/ApplicationDefinition.php';

    Fusion.initialize(options);
    Fusion.registerForEvent(Fusion.Event.FUSION_INITIALIZED, onInitialize);

}

/* 
function onInitialize - Fusion.Event Handler
*/ 
function onInitialize() {
    // init the debugger;
    
    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 pdfWidget = Fusion.getWidgetsByType('PDFLayoutRaster');
        if (pdfWidget.length > 0) {
            pdfWidget[0].registerForEvent(Fusion.Event.PDF_LAYOUT_REQ_STARTED, pdfLayoutStart);
            pdfWidget[0].registerForEvent(Fusion.Event.PDF_LAYOUT_REQ_FINISHED, pdfLayoutStop);
    }

    var searchWidget = Fusion.getWidgetsByType('Search');
    
        if (searchWidget.length > 0) {
            searchWidget[0].registerForEvent(Fusion.Event.SEARCH_REQ_STARTED, searchStarted);
            searchWidget[0].registerForEvent(Fusion.Event.SEARCH_REQ_FINISHED, searchFinished);
    }

    // activate PanQuery
    var panWidget = Fusion.getWidgetById('PanQuery');
    map.activateWidget(panWidget);

    // build options selects

    buildYearSelect("startYear",1);
    buildMonthSelect("startMonth",1);
    buildYearSelect("endYear",-1);
    buildMonthSelect("endMonth",-1);





}


/* 
function mapReloaded - Fusion.Event Handler
*/    
function mapReloaded(){
    d.log("mapReloaded");
}


/* 
function mapIsLoaded -  Fusion.Event Handler
*/    
function mapIsLoaded() {
    d.log("mapIsLoaded");
    var map = Fusion.getMapById('mapArea');

    // create the markers layer
    markerLayer = new OpenLayers.Layer.Markers( "Markers" );

    // set units 
    markerLayer.units = map.oMapOL.units;

    // add the marker layer to the OL Map.
    map.oMapOL.addLayer(markerLayer);

    // set the resolutions for the markers layer
    //markerLayer.maxResolution = map.oMapOL.baseLayer.maxResolution;
    //markerLayer.minResolution = map.oMapOL.baseLayer.minResolution;

    // populate the atlas layers
    catalogManagerInitialize();

    //store layer metadata to global aLayerMetaData

    var aLayers =map.aMaps[0].aLayers;

    for(var i=0; i<aLayers.length;i++){
        var aLayerObj = {};
        aLayerObj.layerName = aLayers[i].layerName;
        aLayerObj.metadata = aLayers[i].metadata;
        aLayerMetaData.push(aLayerObj);
    }

    var s = gszPHPRelativeToFusion + "getMetaData.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 locale = '&locale='+ gLocale;

    var params = session+mapName+locale;
    var opts = {parameters: params, onComplete: displayMapTitle.bind(null)};
    Fusion.ajaxRequest(s, opts);

    // set map extents if set in the query string
    if(gExtents != ""){
        setMapExtents(gExtents);
    }
    if(gAppInit == false){
        // build the map navigation
        getMapNav();
    }
    // set that the initial map and app has completed init
    gAppInit = true;

    // set extents to be a bit larger then the current area.
    var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];

    var bounds = new OpenLayers.Bounds(100000,4800000,600000,5500000);

    map._oMaxExtent = bounds
    map.oLayerOL.maxExtent = bounds
    
}


function getMapNav(){
    var s = gszPHPRelativeToFusion + "getMapNav.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 locale = '&locale='+ gLocale;

    var params = session+mapName+locale;
    var opts = {parameters: params, onComplete: buildMapNav.bind(null)};
    Fusion.ajaxRequest(s, opts);
}

function buildMapNav(r){
    d.log("buildMapNav");
    eval('var mapNav='+r.responseText);
    for(var i=0;i<mapNav.length;i++){
        var szMapFullPath = mapNav[i].path;
        var szMapName = mapNav[i].map;
        var a = new Jx.Action(loadMap.bind(null, szMapFullPath,szMapName));
        gMenu1.add( new Jx.MenuItem(a, {label: mapNav[i].title}));
    }
    
}

function loadMap(szMapFile,szMapName) {
    /*var mapWidget = Fusion.getMapById('mapArea');
    var maps = mapWidget.getAllMaps();
    var map = maps[0];

    map.loadMap(szMapFile);
    gszTheme = szMapName;*/

    document.location.href = buildMapURL(szMapName);
        
}

function displayMapTitle(r){
    d.log("displayMapTitle");
    eval('var mapMetadata='+r.responseText);
    $('mapTitle').innerHTML = mapMetadata.maptitle;
    $('mapAbstract').innerHTML = mapMetadata.mapabstract;
    $('infoTitle').innerHTML=  mapMetadata.maptitle;
    $('infoAbstract').innerHTML = mapMetadata.mapabstract;
    var oTopics = $('infoTopics');
    var oLinks = $('infoLinks');
    // clear out any child content
    oTopics.innerHTML = "";
    oLinks.innerHTML = "";
    var aRelatedLinks = mapMetadata.relatedLinks.split("\|");
    var aRelatedLinksHref = mapMetadata.relatedLinksHref.split("\|");
    var aRelatedTopics = mapMetadata.relatedTopics.split("\|");
    var aRelatedTopicsHref = mapMetadata.relatedTopicsHref.split("\|");

   var relatedLinksUl = document.createElement("UL");
   var relatedTopicsUl = document.createElement("UL");
   
    // create Related Links
   for(var i=0; i<aRelatedLinks.length;i++){
        var li = document.createElement("LI");
        var a = document.createElement("a");
        a.href = aRelatedLinksHref[i];
        a.innerHTML = aRelatedLinks[i];
        li.appendChild(a);
        relatedLinksUl.appendChild(li);
   }
   oLinks.appendChild(relatedLinksUl);
   // create Related Topics 
   for(var i=0; i<aRelatedTopics.length;i++){
        var li = document.createElement("LI");
        var a = document.createElement("a");
        a.href = aRelatedTopicsHref[i];
        a.innerHTML = aRelatedTopics[i];
        li.appendChild(a);
        relatedTopicsUl.appendChild(li);
   }
   oTopics.appendChild(relatedTopicsUl);

}


/* 
function catalogManagerInitialize - Load browseCatalog and parse the catalog mapfile
                                    launch CB catalogListLayers to display the data.
*/
function catalogManagerInitialize(){
   // d.log("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)};
    console.log(params)
    console.log(s)
    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){
    d.log("catalogListLayers");
    //global gCatalogLayersObj 
    eval('gCatalogLayersObj='+r.responseText);
    
    //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);

    for(var i=0;i<gCatalogLayersObj.length;i++){
        var szOwsTitle = gCatalogLayersObj[i].owstitle;
        var li = document.createElement('li');
        ul.appendChild(li);
        
        var a = document.createElement('a');

        a.href="javascript:void(0)";
        a.layertype = gCatalogLayersObj[i].layertype;
        a.layername =  gCatalogLayersObj[i].name;
        a.owstitle =  gCatalogLayersObj[i].owstitle;
        a.group =  gCatalogLayersObj[i].group;
        a.srs = gCatalogLayersObj[i].srs;
        a.imageFormat = gCatalogLayersObj[i].imageformat;
        a.servername = gCatalogLayersObj[i].servername;
        
        a.addLayer = addCatalogLayer.bind(null, a);
        Event.observe(a, 'click', a.addLayer);
        
        li.appendChild(a);
        
        a.innerHTML = szOwsTitle;
        li.appendChild(a);
        }
}


/* 
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){
    d.log("addCatalogLayer");
    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){
    d.log("addCatalogLayerCB");
    var o = '';
    eval('o='+r.responseText);    

        if(o.addedLayer == true){
          var map = Fusion.getMapById('mapArea'); 
          var maps = map.getAllMaps();
          maps[0].reloadMap();
        } else {
           // d.log('addCatalogLayerCB:could not add layer');
        }
}
function updateLayerSelect(szValue){
    d.log("updateLayerSelect");
    $('wmsServerName').value= szValue;
}
/* 
function activeLayerChanged - called on MAP_ACTIVE_LAYER_CHANGED  returns the associated 
                              map file metadata then calls updateLayerDetails()

*/
function activeLayerChanged(eventID,layerObj){
    d.log("activeLayerChanged");
    // 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){
    d.log("updateLayerDetails");
    var szLayerMetaData = r.responseText;
    var oLayerInfoArea = document.getElementById("layerInfoArea");
    oLayerInfoArea.innerHTML = szLayerMetaData;
   
    layerInfoArea.open();
    }

/* 
function wmsManagerInitialize - Call browseCatalog.php to return the WMS layers from server
                                entered in $('wmsServerName').value
*/     
function wmsManagerInitialize(){
    d.log("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 searchStarted(){
    d.log("searchStarted");
    // get the map widget so we can get OL obj
    var mapWidget = Fusion.getMapById('mapArea');
    
    // grab the search widget and set it's output to be in the same projection as the OL obj
    var SearchWidget = Fusion.getWidgetsByType('Search');
    SearchWidget[0].setProjection("epsg:42304");
}

function searchFinished(eventID,widget,requestObj){
    d.log("searchFinished");

    if(typeof(requestObj.error) == "undefined"){
        var oSearchResultsDialog = $('FUSION_SEARCH_WIDGET_RESULTS');
        oSearchResultsDialog.innerHTML = null;
        var ul = document.createElement("UL");
        ul.id = "searchResultsList";

            for(var i=0;i<requestObj.length;i++){
                var szName = requestObj[i].name;
                var y = requestObj[i].y;
                var x = requestObj[i].x;
                var li = document.createElement("LI");
                ul.appendChild(li);

                var a = document.createElement("A");
                a.href ="javascript:addMarker("+x+","+y+",'"+szName+"');b1.hide();";
                a.innerHTML = szName;
                li.appendChild(a);
            }
        oSearchResultsDialog.appendChild(ul);
        oSearchResultsDialog.style.display = "block";       
    }
    else
    {
    // display error
    alert(requestObj.error);
    }

}



function pdfLayoutStart(){
    d.log("pdfLayoutStart");
        // add dynamic text to be set in the PDF when it is rendered.
        var pdfWidget = Fusion.getWidgetsByType('PDFLayoutRaster');
        var oObject = {};
        oObject.name = "title";
        oObject.value = $('pdfTitle').value.stripTags();
        pdfWidget[0].setTemplateVariable(oObject);
        var oObject = {};
        oObject.name = "abstract";       
        oObject.value = $('mapAbstract').innerHTML.stripTags();
        pdfWidget[0].setTemplateVariable(oObject);

        if(aGraphs.length>0 && aGraphs.length< 5 ){
            // 1-4 graphs
            $('PDFLAYOUT_SELECTED_TEMPLATE').value = "PDF-landscape-4";
        }

        if(aGraphs.length>4 &&aGraphs.length< 9 ){
        // up to 4 -8 graphs
            $('PDFLAYOUT_SELECTED_TEMPLATE').value = "PDF-landscape-8";
        }

        if(aGraphs.length ==0){
            $('PDFLAYOUT_SELECTED_TEMPLATE').value = "PDF-landscape";
        }

    
        // add graphs to template
        for(var i=0; i<aGraphs.length;i++){
            var oObject = {};
            oObject.name = "owtchart-"+i;
            oObject.value = aGraphs[i].imageFilenamePDF;
            pdfWidget[0].setTemplateVariable(oObject);
        }
        
    }

function pdfLayoutStop(eventID,widget,requestObj){
    d.log("pdfLayoutStop");

    if(typeof(requestObj.url) == "undefined"){
    }
    else
    {
    window.open(requestObj.url,'',"");
    }
}

function pdfSelectTemplate(){
    d.log("pdfSelectTemplate");
    $('PDFLAYOUT_SELECTED_TEMPLATE').value = $('pdfSelect').options[$('pdfSelect').selectedIndex].value;
    
}

/* 
function queryString - 
*/   
function queryString(qs){
    d.log("queryString");
    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 selectionOn - event handler for MAP_SELECTION_ON
*/

function selectionOn() {
    d.log("selectionOn");
    var mapWidget = Fusion.getMapById('mapArea'); 
    var maps = mapWidget.getAllMaps(); 
    var map = maps[0];

    // get the selection and trigger selectionLoaded with the obj
    map.getSelection(selectionLoaded.bind(null));
}

/*
function selectionLoaded - Sets up the FramedCloud properties, gets the lat lon of the loadedSelection and triggers addMarkerPopup
*/

function selectionLoaded(obj){
    d.log("selectionLoaded");

    // set defaults for the cloud popup
    var AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
        'autoSize': true,
        'minSize': new OpenLayers.Size(300,300),
        'fixedRelativePosition':true,
        'relativePosition':'tr'
    });

    // build the OL long/lat
    lonLat = new OpenLayers.LonLat(obj.fMaxX,obj.fMaxY);

    // add the marker
    addMarkerPopup(lonLat, AutoSizeFramedCloud, obj, true,true);

}
/*

function addMarkerPopup - Creates the OL Feature Marker and FramedCloud Popup if popupContentHTML is an object then triggers
                                            generatePopupContent
                                            
                                            if popupContentHTML is a string it has been called by the CGN Service
*/

function addMarkerPopup(ll, popupClass, popupContentHTML, closeBox, overflow,icon) {
    d.log("addMarkerPopup");
    // get map
    var map = Fusion.getMapById('mapArea');
    
    // build feature
    var feature = new OpenLayers.Feature(markerLayer, ll);
    feature.closeBox = closeBox;
    feature.popupClass = popupClass;

    // check to see if selection object was passed    
    if(typeof(popupContentHTML) == "object"){
        feature.data.popupContentHTML  = prepareQueryResultsDiv();       
    }
    else
    {
        // set text to the feature.
        feature.data.popupContentHTML = popupContentHTML;
    }

    feature.data.overflow = (overflow) ? "auto" : "hidden";

    // if no icon specified use OL default else use icon.png in images folder. 
    if(typeof(icon) == "undefined"){
        var size = new OpenLayers.Size(14,24);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var appHost = Fusion.getApplicationURL();
        var icon = new OpenLayers.Icon(appHost+'images/marker-2.png',size,offset);
        var marker = new OpenLayers.Marker(ll,icon);
    }
    else
    {
        // use original marker
        var size = new OpenLayers.Size(14,24);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var appHost = Fusion.getApplicationURL();
        var icon = new OpenLayers.Icon(appHost+'images/marker.png',size,offset);
        var marker = new OpenLayers.Marker(ll,icon);
    }

    // create popup and show it. 
    this.popup = feature.createPopup(feature.closeBox);
    map.oMapOL.addPopup(this.popup);
    this.popup.show();

    // add eventhandler for marker to popup
    var markerClick = function (evt) {
        if (this.popup == null) {
            this.popup = this.createPopup(this.closeBox);
            map.oMapOL.addPopup(this.popup);
            this.popup.show();
        } else {
            this.popup.toggle();
        }
        currentPopup = this.popup;
        OpenLayers.Event.stop(evt);
    };
    marker.events.register("mousedown", feature, markerClick);

    markerLayer.addMarker(marker);
    
    // is this a selectionObject?
    if(typeof(popupContentHTML) == "object"){
        // populate the cloud with the feature info.
        generatePopupContent(popupContentHTML,popupLastID,marker,this.popup);
    }
}

function displayLayerMetadata(oObject){
    d.log("displayLayerMetadata");

    var rightContainer = $('popupRight-'+oObject.popupID);
    rightContainer.innerHTML = "";

    var oTitle = document.createElement("H1");
    var  oAbstract = document.createElement("P");

    oTitle.className = "queryLayerTitle";
    oAbstract.className = "queryLayerAbsttract";

    oTitle.innerHTML = oObject.layerMetadata.ows_title;
    oAbstract.innerHTML = oObject.layerMetadata.ows_abstract;
    
    rightContainer.appendChild(oTitle);
    rightContainer.appendChild(oAbstract);
}

/*
function generatePopupContent - This func populates the FramedCloud DIV's with the point query's features.
                                                       Sets up UI for the removal of the popup. triggers func. showFeature when a feature
                                                       is clicked. 
*/
function generatePopupContent(oObject,thePopupID,marker,popup){
    d.log("generatePopupContent");
    
    var leftContainer = $('popupLeft-'+thePopupID);
    var rightContainer = $('popupRight-'+thePopupID);
    var actionContainer = $('popupAction-'+thePopupID);

    var oA = document.createElement("A");
    actionContainer.appendChild(oA);

    oA.innerHTML = OpenLayers.i18n('Remove Marker');
    oA.href = "javascript:void(0);";

    oA.popup = popup;
    oA.marker = marker;
    oA.selectionObj = oObject;
    oA.popupID = thePopupID;

    oA.removeMarker = removeMarker.bind(null,oA);
    Event.observe(oA, 'click', oA.removeMarker);
    
    var oMainUL = document.createElement("UL");
    oMainUL.className = "featureList";
    leftContainer.appendChild(oMainUL);
    
    for(var a=0;a<oObject.aLayers.length;a++){
        //layers
        var aLayer = oObject.aLayers[a];
        
        var oLayerLI = document.createElement("LI");
        oLayerLI.className = "layerItem layerName";

        var oA = document.createElement("A");
        oA.href = "javascript:void(0);";
        oA.innerHTML = aLayer.sName;

        oA.layerMetadata = getLayerMetadata(aLayer.sName);
        oA.oObject = oObject;
        oA.popupID = thePopupID;
        
        oA.displayLayerMetadata = displayLayerMetadata.bind(null,oA);
        Event.observe(oA, 'click', oA.displayLayerMetadata);

        oLayerLI.appendChild(oA);
        oMainUL.appendChild(oLayerLI);
        
        var oFeatureUL = document.createElement("UL");
        
        oLayerLI.appendChild(oFeatureUL);
        
        for(var i=0;i<aLayer.aElements.length;i++){
            // features

            // for fred because to him 0 is not a number.
            var fredCount = ( i + 1); 
            var oA = document.createElement("A");

            oA.objectData = aLayer;
            oA.popupID = thePopupID;
            oA.selectedFeatureID = i;
            oA.layerName = aLayer.sName;

            var featureItem = getLayerFeatureByIndex(aLayer,i);
            
            // add links back to their parent div container
            oA.leftContainer = leftContainer;
            oA.rightContainer = rightContainer;
            
            oA.href = "javascript:void(0);";

            var featureLabel = getFeatureLabelField(aLayer.sName);

            if(featureLabel != false){
                oA.innerHTML = featureItem[featureLabel];
            }
            else
            {
                // no metadata specified for the features label so we are going to use the word "Feature 1" and so on
                oA.innerHTML = OpenLayers.i18n('Feature')+fredCount;
            }
            oA.layerMetadata = getLayerMetadata(aLayer.sName);
            oA.showFeature = showFeature.bind(null,oA);
            Event.observe(oA, 'click', oA.showFeature);
            
            var oFeatureLI = document.createElement("LI");
            oFeatureLI.className = "featureItem";
            
            // add this a tag to the object
            oA.clickedFeature = oA;
            oA.feature = featureItem;
            oFeatureLI.appendChild(oA)
            oFeatureUL.appendChild(oFeatureLI);
            //$('thePage').resize();
            $('mapArea').resize();

        }
    }

}

function getCSVDataSet(layerName,selectedCSVDataset){
    d.log("getCSVDataSet");
    var layerMetadata = getLayerMetadata(layerName);
    var csvDataSet = layerMetadata.csvDataSet.split("\|");
    var csvDataSet_Name = layerMetadata.csvDataSet_Name.split("\|");
    var csvDataSet_ID =  layerMetadata.csvDataSet_ID.split("\|");
    var csvDataSet_Unit =  layerMetadata.csvDataSet_Unit.split("\|");

    var oObject = {};
    
    // empty csvDataSet so return false
    if(csvDataSet ==""){
        return false;
    }
    
    if(selectedCSVDataset == null || typeof(selectedCSVDataset) == "undefined"){
        oObject.aCSVDataSet = csvDataSet;
        oObject.aCSVDataSet_ID = csvDataSet_ID;
        oObject.aCSVDataSet_Name = csvDataSet_Name;
        oObject.aCSVDataSet_Unit = csvDataSet_Unit;
        return oObject;
    }
    else
    {
        for(var a=0;a<csvDataSet.length+1;a++){

            if(csvDataSet[a] == selectedCSVDataset ){
                oObject.aCSVDataSet = csvDataSet[a];
                oObject.aCSVDataSet_ID = csvDataSet_ID[a];
                oObject.aCSVDataSet_Name = csvDataSet_Name[a];
                oObject.aCSVDataSet_Unit = csvDataSet_Unit[a];
            }
        }
        return oObject;
    }

return false;
    

}

function getPropertyValueByName(oSelObject,szName){

    for(var i=0;1<oSelObject.aPropertiesName.length;i++){
        if(oSelObject.aPropertiesName[i] == szName){
            return oSelObject.aElements[i];
        }
    }
    return false;
}

function resizeImage(img){
    img.width = img.parentNode.offsetWidth;
    img.height =  img.parentNode.offsetHeight;

}

function openWindow(theSrc){

    var sFeatures = 'menubar=no,location=no,resizable=no,status=no';
    var url = theSrc;
    window.open(url, "IMG", sFeatures);

}

/*
function showFeature - Display's the features attribute data, in the FramedCloud also checks to see if the attribute can be graphed
*/

function showFeature(selectionObj){
    d.log("showFeature");
    // remove selected class on prior selected item if exists
    if(typeof(lastSelectedFeature) == "object"){
        lastSelectedFeature.removeClassName("selected")
    }
    
    // set this selected item to the last
    lastSelectedFeature = selectionObj.clickedFeature
    
    // add selected class
    selectionObj.clickedFeature.addClassName("selected");
    var rightContainer = $('popupRight-'+selectionObj.popupID);

    var aElements = selectionObj.objectData.aElements[selectionObj.selectedFeatureID];
    var aPropertiesName = selectionObj.objectData.aPropertiesName;

    // clear out the rightContainer
    rightContainer.innerHTML = "";

    if(selectionObj.layerMetadata.isPhotosLayer == "true"){
        var imageName = selectionObj.feature.IMAGE;
        var imageDescription = selectionObj.feature.DESCRIPTIO;

        var img = document.createElement("IMG");
        img.className = "photos";
        img.src = "./photos/"+imageName;
        img.alt = imageDescription;
        rightContainer.appendChild(img);
        img.onLoad = resizeImage.bind();
        img.resizeImage = resizeImage.bind(null,img);
        Event.observe(img, 'load', img.resizeImage);

        img.onClick = openWindow.bind();
        img.openWindow = openWindow.bind(null, img.src);
        Event.observe(img, 'click', img.openWindow);
        
        img.onClick = "javascript:openWindow("+ img.src+")";
 
    }
    else
    {
    // Create Table Head

    var table = document.createElement("TABLE");
    table.className = "attributeTable";
    rightContainer.appendChild(table);
    var tbody = document.createElement('tbody');
    table.appendChild(tbody);
    
    var tr = document.createElement("TR");
    tbody.appendChild(tr);

    // is graphable empty th
    var th = document.createElement("TH");
    th.innerHTML = OpenLayers.i18n('Graph');
    tr.appendChild(th);
    
    var th = document.createElement("TH");
    th.innerHTML = OpenLayers.i18n('Attribute');
    th.className = "attribute";
    tr.appendChild(th);

    var th = document.createElement("TH");
    th.innerHTML = OpenLayers.i18n('Value');
    th.className = "value";
    tr.appendChild(th);

    var csvDataSet = getCSVDataSet(selectionObj.layerName);

    // does the layer have a csv dataset?
        if(csvDataSet != false){
            // insert features for the graphable datasets first
            for(var i=0;i<csvDataSet.aCSVDataSet_Name.length;i++){
                var tr = document.createElement("TR");
                tbody.appendChild(tr);

                // is graphable TD
                var td = document.createElement("TD");
                var oA = document.createElement("A");

                oA.className = "addToGraph";

                oA.layerName = selectionObj.layerName
                oA.selectionObj = selectionObj;
                oA.chartstyle = "Bar";
                oA.feature = selectionObj.feature;
                oA.csvDataSet =csvDataSet;
                oA.csvDataSetIndex= i;

                oA.href = "javascript:void(0);";
                oA.alt = OpenLayers.i18n('Click here to add to graph.');
                oA.title = OpenLayers.i18n('Click here to add to graph.');

                oA.getNewGraphData = getNewGraphData.bind(null,oA);
                Event.observe(oA, 'click', oA.getNewGraphData);

                td.appendChild(oA);

                tr.appendChild(td);

                // attribute name
                var td = document.createElement("TD");

                td.innerHTML = csvDataSet.aCSVDataSet_Name[i]
                td.className = "attribute";
                tr.appendChild(td);

                // attribute value
                var td = document.createElement("TD");
                td.innerHTML = csvDataSet.aCSVDataSet[i]
                td.className = "value";
                tr.appendChild(td);
                $('mapArea').resize();
            }
        }

        // generate  features
        for(var i=0;i<aElements.length;i++){

            var tr = document.createElement("TR");
            tbody.appendChild(tr);

            // is graphable TD
            var td = document.createElement("TD");

            var layerName = selectionObj.objectData.sName;
            var attributeName = aPropertiesName[i];

            //check to see if it's an int.
            var testFloat = aElements[i] -1;

            //convert to float if applicable
            if(!isNaN(testFloat) && aElements[i] != '' ){
                var attributeValue = parseFloat(aElements[i]);
            }
            else
            {
                var attributeValue = aElements[i];
            }

            tr.appendChild(td);

            // attribute name
            var td = document.createElement("TD");

            td.innerHTML = aPropertiesName[i];
            td.className = "attribute";
            tr.appendChild(td);

            // attribute value
            var td = document.createElement("TD");
            td.innerHTML = attributeValue;
            td.className = "value";
            tr.appendChild(td);

        }
    } // end else if photos layer
}

function getLayerMetadata(szLayerName){
    d.log("getLayerMetadata");
    var oReturn = false;
        for(var i=0;i<aLayerMetaData.length;i++){
            if(aLayerMetaData[i].layerName == szLayerName ){
            // found
            oReturn = aLayerMetaData[i].metadata;
            }
        }
return oReturn;
}


/*
function isThisAttributeGraphable - Searches thru the global aLayerMetaData for layer metadata that matches
                                                          szLayerName,szAttributeName returns True if found. 
*/
function isThisAttributeGraphable(szLayerName,szAttributeName){
    d.log("isThisAttributeGraphable");
    var isGraphable = false;

    for(var z=0;z<aLayerMetaData.length;z++){
        // look for layer match on layername
        if(aLayerMetaData[z].layerName == szLayerName){
            var metadata = aLayerMetaData[z].metadata.graphFieldsCSV;
            aGraphableFields = metadata.split(",");
            
            // look for attribute 
            for(var a=0;a<aGraphableFields.length;a++){  
                if(aGraphableFields[a] == szAttributeName){
                    isGraphable = true;
                }
            }
            
        }
    }

    return isGraphable;

}

/*
function getLayerFeatureByIndex - Loops thru the layerSelectionObj and retuns a nice feature obj 
*/
function getLayerFeatureByIndex(layerSelectionObj,iIndex){
    d.log("getLayerFeatureByIndex");
    var oFeature = {};

    for(var i=0;i<layerSelectionObj.aPropertiesName.length;i++){
        oFeature[layerSelectionObj.aPropertiesName[i]] = layerSelectionObj.aElements[iIndex][i];
    }

return oFeature;
}

/*
function getFeatureLabelField - Searches thru the layermetadata to see if szLayerName is used as the feature label
*/
function getFeatureLabelField(szLayerName){
    d.log("getFeatureLabelField");
    var szReturn = false;

    for(var z=0;z<aLayerMetaData.length;z++){
        // look for layer match on layername
        if(aLayerMetaData[z].layerName == szLayerName){
            var szReturn = aLayerMetaData[z].metadata.queryFeatureLabel;
            
        }
    }
    return szReturn;
}


function searchGraphsForStationID(szItemID){
    d.log("searchGraphsForStationID");
    var szReturn = false;
    for(var a=0;a<aGraphs.length;a++){
        for(var j=0;j<aGraphs[a].stationID.length;j++){
            if(aGraphs[a].stationID[j] == szItemID){
                    return a;
                }
            }
    }
    return szReturn;
}

function searchGraphsForUnit(szUnit){
    d.log("searchGraphsForUnit");
    var szReturn = false;
    for(var a=0;a<aGraphs.length;a++){
        for(var j=0;j<aGraphs[a].units.length;j++){
            if(aGraphs[a].units[j] == szUnit){
                return a;
            }
        }
    }
    return szReturn;
}

function searchGraphsForParameter(parameter){
    d.log("searchGraphsForParameter");
    var szReturn = false;
    for(var a=0;a<aGraphs.length;a++){
        for(var j=0;j<aGraphs[a].units.length;j++){
            if(aGraphs[a].dataSetName[j] == parameter){
                    return a;
            }
        }
    }
    return szReturn;
}

function processGraphData(oObject){
    d.log("processGraphData");
    eval("var o="+oObject.responseText);

    var bNewGraph = true;

    var bFoundSameUnit = "";
    var bFoundSameStation = "";
    var selectedLayerDataSet = getCSVDataSet(this.layerName,this.selectedCSVDataSet);
    var staionID = this.selectionObj.feature[selectedLayerDataSet.aCSVDataSet_ID];
    // new graph.

    // search for Station ID in the aGraphs global
    var foundStation_Index = searchGraphsForStationID(staionID);
    // search for same units already in aGraphs global
    var foundUnit_Index = searchGraphsForUnit(this.selectedCSVDataSet_Unit);
    // search for same parameter "dataSET" in aGraphs global
    var foundParameter_Index = searchGraphsForParameter(this.selectedCSVDataSet_Name);

/*
    if(foundStation_Index !== false){
        // found a graph with the same stationID add to stationGraph
        aGraphs[foundStation_Index].stationID.push(staionID);
        aGraphs[foundStation_Index].units.push(this.selectedCSVDataSet_Unit);
        aGraphs[foundStation_Index].values.push(o);
        aGraphs[foundStation_Index].updateGraphData.push(this.updateGraphData);
        updateGraph(foundStation_Index);
        bNewGraph = false;
        
    }
    */

    if(foundUnit_Index !== false){
        // found a graph with the same units
         if(foundParameter_Index !== false){
            // found graph with same unit and same parameter
            
            aGraphs[foundParameter_Index].stationID.push(staionID);
            aGraphs[foundParameter_Index].units.push(this.selectedCSVDataSet_Unit);
            aGraphs[foundParameter_Index].values.push(o);
            aGraphs[foundParameter_Index].updateGraphData.push(this.updateGraphData);
            aGraphs[foundParameter_Index].features.push(this.feature);
            updateGraph(foundParameter_Index);
            bNewGraph = false;
         }

    }

    if(bNewGraph == true){
        var graph = {};
        // main graph label.
        //graph.label = "";
        graph.layerName = this.selectionObj.layerName;
        // names of the different datasets
        graph.dataSetName = [];
        // features for the datasets.
        graph.features = [];
        // values for the graph.
        graph.values = [];
        // units
        graph.units = [];
        // StationID
        graph.stationID = [];
        // update Graph Data
        graph.updateGraphData = [];

        graph.chartstyle  = "Line";
        graph.attribute = this.selectedCSVDataSet_Name;
        graph.layername = this.selectedCSVDataSet;

        // add units.
        graph.units.push(this.selectedCSVDataSet_Unit);

        // add stationIDs
        graph.stationID.push(staionID);

        // add dataset label
        graph.dataSetName.push(this.selectedCSVDataSet_Name);

        // add the values
        graph.values.push(o);

        // add layer feature
        graph.features.push(this.feature);

        // add data update information if dates change. 
        graph.updateGraphData.push(this.updateGraphData);

        // add graph image Filename
        graph.imageFilename = "";

        //pdf graph image
        graph.imageFilenamePDF = "";

        // add the graph to the global aGraphs
        aGraphs.push(graph);

        displayGraph(aGraphs.length-1);
    }
}

function updateGraphData(oUpdateObj,aGraphIndex,aValuesIndex){
    d.log("updateGraphData");
    // Callback from updateGraphData update aGraphs
    if(this.CB_aGraphIndex >-1 && this.CB_aValuesIndex>-1){
        aGraphs[this.CB_aGraphIndex].values[this.CB_aValuesIndex] = eval(oUpdateObj.responseText);
    }
    else
    {
        // new update request.       
        var session = '?session='+oUpdateObj.session
        // globals start and end date
        var start = '&start='+gStartDate;
        var end = '&end='+gEndDate;    
        var paramName ='&parameter='+oUpdateObj.csvDataSet;
        var itemID = '&id='+oUpdateObj.itemID;

        // set properties to update the actual aGraphs data array. on a callback
        var oCallBack = {};
        oCallBack.CB_aGraphIndex = aGraphIndex;
        oCallBack.CB_aValuesIndex = aValuesIndex;
        
        var params = session+start+end+paramName+itemID;
        var appHost = Fusion.getApplicationURL();

        new Ajax.Request(appHost+'/php/getChartData.php'+params,
            {
                method:'get',
                onSuccess:updateGraphData.bind(oCallBack)
            });
    }
    updateGraph();
}


/*

function getNewGraphData - builds the global aGraphs which is used to generate the graphs then triggers addGraph

*/
function getNewGraphData(oObject){
    d.log("getNewGraphData");
    // click the graphToolbar
    t3.clicked();   

    var mapWidget = Fusion.getMapById('mapArea'); 
    var maps = mapWidget.getAllMaps(); 
    var map = maps[0];
    
    var s = gszPHPRelativeToFusion + "getChartData.php";

    var csvDataSet = oObject.csvDataSet.aCSVDataSet[oObject.csvDataSetIndex];
    var csvDataSet_Name = oObject.csvDataSet.aCSVDataSet_Name[oObject.csvDataSetIndex];
    var csvDataSet_ID = oObject.csvDataSet.aCSVDataSet_ID[oObject.csvDataSetIndex];
    var csvDataSet_Unit =  oObject.csvDataSet.aCSVDataSet_Unit[oObject.csvDataSetIndex];

    // check for float or string
    var testFloat = oObject.feature[csvDataSet_ID]-1;
     
        //convert to float if applicable
        if(!isNaN(testFloat)){
            var itemValue = parseFloat(oObject.feature[csvDataSet_ID]);
        }
        else
        {
            var itemValue = oObject.feature[csvDataSet_ID];
        }

    // clenup for the next callback
    oObject.selectedCSVDataSet = csvDataSet;
    oObject.selectedCSVDataSet_Name = csvDataSet_Name;
    oObject.selectedCSVDataSet_ID = csvDataSet_ID;
    oObject.selectedCSVDataSet_Unit = csvDataSet_Unit

    // create an update object 
    oObject.updateGraphData = {};
    oObject.updateGraphData.session = map.getSessionID();
    oObject.updateGraphData.csvDataSet = csvDataSet;
    oObject.updateGraphData.itemID = itemValue;

    // these are globals for now. 
    oObject.updateGraphData.start = gStartDate;
    oObject.updateGraphData.end = gEndDate;

    var session = '?session='+oObject.updateGraphData.session
    var paramName ='&parameter='+oObject.updateGraphData.csvDataSet;
    var start = '&start='+oObject.updateGraphData.start;
    var end = '&end='+oObject.updateGraphData.end;
    var itemID = '&id='+oObject.updateGraphData.itemID;
    
    // ?id=18343010001&parameter=wq_salinity&start=1-1-2003 12:0:1&end=1-1-2008 12:0:1
    
    var params = session+start+end+paramName+itemID;
    var appHost = Fusion.getApplicationURL();

    new Ajax.Request(appHost+'/php/getChartData.php'+params,
        {
            method:'get',
            onSuccess:processGraphData.bind(oObject)
        });
      
}

function createChartTitle(aGraph){
    d.log("createChartTitle");
    var szReturn = "";

    var labelField = getFeatureLabelField(aGraph.layerName);
    var labelValue =  aGraph.features[0][labelField];

   if(aGraph.stationID.length == 1){
       szReturn = aGraph.dataSetName.toString().replace(/','/g, ' ');
       szReturn = szReturn +" ["+aGraph.units.toString().replace(/','/g, ' ')+"]";
       szReturn = szReturn +" ("+ labelValue+")";
    }
    else
    {
         szReturn = aGraph.dataSetName.toString().replace(/','/g, ' ');
    }
    return szReturn;
}


function displayGraph(graphIndex){
    d.log("displayGraph");
    var graphTabContent = $('graphImages');

    var chartTitle = createChartTitle(aGraphs[graphIndex]);

    var oOWTChart = {};
    oOWTChart.values = aGraphs[graphIndex].values;
    oOWTChart.labels = aGraphs[graphIndex].labels;
    oOWTChart.title = chartTitle;
    oOWTChart.subtitle = aGraphs[graphIndex].attribute;
    oOWTChart.chartstyle = aGraphs[graphIndex].chartstyle;
    oOWTChart.units = aGraphs[graphIndex].units[0];


    /*
    creating this structure:

    <div id=graphMainContainer>
        <div className="graphImageContainer"><img><div id="graphLegend-0"></div></div>
        <div className="graphDataContainer">...</div>
    </div>
    */
   // debugger;
    
    var graphMainContainer = document.createElement("DIV");
    graphMainContainer.id = "GraphContainer-"+graphIndex;
    graphMainContainer.className = "graphContainer";

    // add the it to the main graph tab content
    graphTabContent.appendChild(graphMainContainer);    
    
    var divImageContainer = document.createElement("DIV");
    divImageContainer.id = "GraphImageContainer-"+graphIndex;
    divImageContainer.className = "graphImageContainer";
    graphMainContainer.appendChild(divImageContainer);

    var graphLegendContent = document.createElement("DIV");
    graphLegendContent.id = "graphLegendContent-"+graphIndex;
    graphLegendContent.className = "graphLegendContent";
    graphMainContainer.appendChild(graphLegendContent);

    var graphLegendButton = document.createElement("DIV");
    graphLegendButton.id = "graphLegendButton-"+graphIndex;
    graphLegendButton.className = "graphLegendButton";
    divImageContainer.appendChild(graphLegendButton);

    // create the legend content
    generateLegendContent();

    var img = document.createElement("IMG");
    
   // img.src = owtChart_buildChartURI(oOWTChart);
    // generate the image
    owtChart_generateGraphImage(oOWTChart,graphIndex);

    img.src = aGraphs[graphIndex].imageFilename;
    img.id = "graphImage-"+graphIndex;
    img.graphIndex = graphIndex;
    
    divImageContainer.appendChild(img);


    // Create the flyout button
    var jxButtonFlyout = new Jx.Button.Flyout({ image: '', tooltip: OpenLayers.i18n('Legend'), label: OpenLayers.i18n('Legend'), contentID: 'graphLegendContent-'+graphIndex});
    
    graphLegendButton.appendChild(jxButtonFlyout.domObj);

    
    // generate the content for the graph's data.
    generateGraphDataContent(graphIndex);
    // rebuildPDFChartImages
    generatePDFCharts();

}

function owtChart_generateGraphImage(oOWTChart,graphIndex){

    oOWTChart.graphIndex = graphIndex;
    if(typeof(oOWTChart.responseText) == "undefined"){
            var appHost = Fusion.getApplicationURL();
            var owtchartdata = owtChart_buildChartURI(oOWTChart);
            new Ajax.Request(appHost+'/php/owtchart.php',
                {
                    method:'post',
                    parameters: {owtchart: owtchartdata},
                    onSuccess:owtChart_generateGraphImage.bind(oOWTChart)
                });
            }
            else
            {
           // alert(oOWTChart.responseText);
            eval("var imageURL = "+oOWTChart.responseText);
            aGraphs[this.graphIndex].imageFilename =  imageURL;
            $('graphImage-'+this.graphIndex).src = imageURL;
            }
    
}

function owtChart_generateGraphImage_PDF(oOWTChart,graphIndex,szWidth){

    oOWTChart.graphIndex = graphIndex;
    if(typeof(oOWTChart.responseText) == "undefined"){
            var appHost = Fusion.getApplicationURL();
            var owtchartdata = owtChart_buildChartURI(oOWTChart,szWidth);
            new Ajax.Request(appHost+'/php/owtchart.php',
                {
                    method:'post',
                    parameters: {owtchart: owtchartdata},
                    onSuccess:owtChart_generateGraphImage_PDF.bind(oOWTChart)
                });
            }
            else
            {
           // alert(oOWTChart.responseText);
            eval("var imageURL = "+oOWTChart.responseText);
            aGraphs[this.graphIndex].imageFilenamePDF =  imageURL;
            }

}




function generateLegendContent(){
d.log("generateLegendContent");
    for(var a =0;a<aGraphs.length;a++){
    
        var oDomObj = $('graphLegendContent-'+a);
        oDomObj.innerHTML = "";
        
        for(var i=0;i<aGraphs[a].stationID.length;i++){
            /*
            <div class="legendSwatch colour_bebada"></div><div class="legendLabel">STATIONID</div>
            */

            var swatchDiv = document.createElement("DIV");
            swatchDiv.className = "legendSwatch colour_"+colours[i];
            oDomObj.appendChild(swatchDiv);

            var swatchLabel = document.createElement("DIV");
            swatchLabel.className = "legendLabel";
            var labelField = getFeatureLabelField(aGraphs[a].layerName);
            var labelValue =  aGraphs[a].features[i][labelField];
            swatchLabel.innerHTML = labelValue ;//aGraphs[a].stationID[i];
           

            oDomObj.appendChild(swatchLabel);
        }
    }
    
}

function generateGraphDataContent(graphIndex){
d.log("generateGraphDataContent");
    var  graphDataContainer = $('graphTableData');

    // clear out the Data DIV
    graphDataContainer.innerHTML = "";

    // for each graph
    for(var i =0;i<aGraphs.length;i++){
        generateGraphDatasetTable(graphDataContainer,i);
    }  
    
}

function generateGraphDatasetTable(oDomObject,graphIndex){
d.log("generateGraphDatasetTable");
    var h1 = document.createElement("H1");
    h1.innerHTML = OpenLayers.i18n('Graph')+" "+(graphIndex+1);
    oDomObject.appendChild(h1);
    // create the table
    var table = document.createElement("TABLE");
    table.className = "dataTable";
    oDomObject.appendChild(table);

    // get the graph data for this table
    var aGraphData = aGraphs[graphIndex];

    // create the table headers
    var tr = document.createElement("TR");
    table.appendChild(tr);

    var th = document.createElement("TH");
    th.innerHTML = OpenLayers.i18n('Date');
    tr.appendChild(th);
    
    // make the table headers for the stationIDs
    for(var i=0;i<aGraphData.values.length;i++){
        var th = document.createElement("TH");
        var labelField = getFeatureLabelField(aGraphData.layerName);
        var labelValue = aGraphData.features[i][labelField];
        th.innerHTML = aGraphData.dataSetName+" : "+labelValue;//aGraphData.stationID[i];
        tr.appendChild(th);

    }

    var dataset = aGraphData.values;

    var colCount = dataset.length;
    var rowCount = dataset[0].length-1;

    for(var row=0;row<rowCount;row++){

        var tr = document.createElement("TR");
        table.appendChild(tr);
        
        for(var col=0;col<colCount;col++){

            if(col == 0 ){
                var td = document.createElement("TD");
                td.innerHTML = dataset[col][row].thedate;
                tr.appendChild(td);
            }

            var td = document.createElement("TD");

               if(dataset[col][row].thevalue == null){
                    td.innerHTML = OpenLayers.i18n('No Data / Donnees indisponibles');
               }
               else
               {
                td.innerHTML = dataset[col][row].thevalue;
               }
            
            tr.appendChild(td);
        }

    }

}

function getRowData(aGraphDataSet,iRow){
d.log("getRowData");
    var aReturn = [];
    var colCount = aGraphDataSet.length;

    for(var z=0;z<aGraphDataSet;z++){
        for(var v=0;v<colCount;v++){
            aReturn.push(aGraphDataSet[z][v])
        }
    }

    return aReturn;
    
}

/*

function updateGraphType - decreped. leaving incase it gets decided otherwise. 

*/


function updateGraphType(oSelect){
d.log("updateGraphType");
    aGraphs[oSelect.graphIndex].chartstyle = oSelect.options[oSelect.selectedIndex].value;
    updateGraph();
}

/*
function updateGraph - loops thru the global aGraphs and rebuilds the image src for the graph.
*/
function updateGraph(){
d.log("updateGraph");
    //update all graphs.
    for(var i =0;i<aGraphs.length;i++){
        var graphImage = $('graphImage-'+i);
        var owtChart = {};
        owtChart.values = aGraphs[i].values;
        owtChart.labels = aGraphs[i].labels;
        owtChart.title = createChartTitle(aGraphs[i]);
        owtChart.subtitle = aGraphs[i].attribute;
        owtChart.chartstyle = aGraphs[i].chartstyle;
        owtChart.units = aGraphs[i].units[0];

        owtChart_generateGraphImage(owtChart,i);
        generateGraphDataContent(i);
    }
    // rebuild the legends.
    generateLegendContent();
    // rebuildPDFChartImages
    generatePDFCharts();
}

function generatePDFCharts(){

 for(var i =0;i<aGraphs.length;i++){
        var graphImage = $('graphImage-'+i);
        var owtChart = {};
        owtChart.values = aGraphs[i].values;
        owtChart.labels = aGraphs[i].labels;
        owtChart.title = createChartTitle(aGraphs[i]);
        owtChart.subtitle = aGraphs[i].attribute;
        owtChart.chartstyle = aGraphs[i].chartstyle;
        owtChart.units = aGraphs[i].units[0];
        owtChart_generateGraphImage_PDF(owtChart,i,1000);
    }

}

/*
findGraphIndex - This func. returns the index of the found graph from the global aGraphs
*/
function findGraphIndex(szLayerName,szAttributeName){
d.log("findGraphIndex");
var foundIndex = -1;
    for(var i=0;i<aGraphs.length;i++){
        if(aGraphs[i].layername == szLayerName && aGraphs[i].attribute == szAttributeName ){
            foundIndex = i;
        }
    }
    return foundIndex;
}


/*
prepareQueryResultsDiv - OL Expects the innerHTML for the popup but we need it to be dynamic. thus this
                                           function insert's some div's with incremented ID's so we can inject content into them.
*/
function prepareQueryResultsDiv(){
d.log("prepareQueryResultsDiv");
    // set the last id to this one.
    popupLastID = popupID;

    // create the default structure for the popups
    var szDiv = "<div class=\"popupLeft\" id=\"popupLeft-"+popupLastID+"\"><div class=\"feature\">"+OpenLayers.i18n('Features')+"</div></div>";
    szDiv = szDiv +"<div class=\"popupRight\" id=\"popupRight-"+popupLastID+"\"></div>";
    szDiv = szDiv +"<div class=\"popupAction\" id=\"popupAction-"+popupLastID+"\"></div>";
    
    // increment the id
    popupID++;

    // return the structure
    return szDiv;
    
}


/*
function addMarker - called from the CGN Service to place a marker / cloud with the results
*/

function addMarker(iLon,iLat,label){
d.log("addMarker");
    var AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
        'autoSize': true,
        'fixedRelativePosition':true,
        'relativePosition':'tr'
    });

    lonLat = new OpenLayers.LonLat(iLon,iLat);

    popupContentHTML = "<div id='addMarker'>"+label+"</div>";
    addMarkerPopup(lonLat, AutoSizeFramedCloud, popupContentHTML, true,true,"help");
}

/*
function removeAllMarkers - removes all the markers in the "markerLayer" obj.
*/
function removeAllMarkers(){
d.log("removeAllMarkers");

    while(markerLayer.markers.length > 0){
        markerLayer.removeMarker(markerLayer.markers[markerLayer.markers.length-1]);
    }
}

/*
function removeMarker - removes the marker and it's associated framedCloud from the app.
*/

function removeMarker(oObject){
d.log("removeMarker");
    // delete the marker
    markerLayer.removeMarker(oObject.marker);
    // delete the popup
    oObject.popup.destroy();
}

/*
function sortNumerical - Utility func to sort an array numerically. 
*/

function sortNumerical(a,b)
{
return a - b;
}

/*
function owtChart_getMinMax - returns the min and max values of the array.
*/
function owtChart_getMinMax(aValue){

    aTmp = aValue;

    aTmp.sort(sortNumerical);

    var returnVar = {}

    returnVar.max =  aTmp[aValue.length-1];
    //returnVar.min=  aTmp[0];
    returnVar.min=  0;

    return returnVar

}

function owtChart_getColourSets(colorSets){
    var szReturn = "";
    var szSeparator = "";
        for(var i=0;i<colorSets;i++){

            szReturn = szReturn + szSeparator + colours[i];
            szSeparator = "!";
        }
    return szReturn

}

/*

function owtChart_buildChartURI - builds the URI for the owtChart bin. 

*/
function owtChart_buildChartURI(owtChart,szWidth){
d.log("owtChart_buildChartURI");

   var theValues = generateOWTChartValues(owtChart.values);
   var theXLables = generateXLabels(owtChart.values);
    var chart_Width = null;
   var chart_Type = "Type=Line";//+owtChart.chartstyle;
   if(typeof(szWidth) =="undefined"){
        chart_Width = "\nW="+$('GraphContainer-0').offsetWidth;
   }
   else
   {
        chart_Width = "\nW="+szWidth;
   }
   
   var chart_Height = "\nH="+300;

   var chart_DataSets = "\nNumSets="+owtChart.values.length;
   var chart_numberPts = "\nNumPts="+theValues.count/owtChart.values.length;
   var chart_values = "\nVals="+theValues.values;
   var chart_Title = "\nTitle="+owtChart.title;
   var chart_XLabels = "\nXLabels="+theXLables.values;
   var chart_Colors = "\nSetColors="+owtChart_getColourSets(owtChart.values.length);
   var chart_Stack = "\nStackType="+"Beside";
   var chart_Ytitle = "";
   
   if( typeof(owtChart.units) !="undefined"){
        var chart_Ytitle = "\nYTitle="+owtChart.units;
   }

   return chart_Type+chart_Width+chart_Height+chart_DataSets+chart_numberPts+chart_values+chart_Title+chart_XLabels+chart_Colors+chart_Stack+chart_Ytitle;
   
}

function generateOWTChartValues(oVal){
d.log("generateOWTChartValues");
var oReturn = {};
var szSeparator = "";
oReturn.count = 0;
oReturn.values = "";

    for(var i=0;i<oVal.length;i++){
        for(var a=0;a<oVal[i].length;a++){
             oReturn.values = oReturn.values + szSeparator + oVal[i][a].thevalue;
             oReturn.count++;
             szSeparator = "!";
        }
    }

return oReturn;
}

function generateXLabels(oVal){
d.log("generateXLabels");
var oReturn = {};
var szSeparator = "";
oReturn.count = 0;
oReturn.values = "";

    // use the firstdataset's labels for all 
    for(var a=0;a<oVal[0].length;a++){
        oReturn.values = oReturn.values + szSeparator + oVal[0][a].thedate;
        oReturn.count++;
        szSeparator = ";";
    }


return oReturn;
}

function getCurrentMapImageURL(){
d.log("getCurrentMapImageURL");
    var map = Fusion.getMapById('mapArea');
    map.aMaps[0].oLayerOL.grid[0][0].imgDiv.src
    $('saveMapImageSRC').href = map.aMaps[0].oLayerOL.grid[0][0].imgDiv.src;
    return map.aMaps[0].oLayerOL.grid[0][0].imgDiv.src;
}

function buildCurrentURL(){
d.log("buildCurrentURL");
    var appURL = Fusion.getApplicationURL()+"index.php";
    var mapName = "?map="+gszTheme;
    var locale = "&locale="+gLocale;
    var currentExtents = "&extents="+getCurrentExtents();

    $('saveMapLinkHref').value = appURL+mapName+locale+currentExtents;

    return appURL+mapName+locale+currentExtents;

}

function buildMapURL(szMapName){
d.log("buildMapURL");
    var appURL = Fusion.getApplicationURL()+"index.php";
    var mapName = "?map="+szMapName;
    var locale = "&locale="+gLocale;

    return appURL+mapName+locale;

}



function getCurrentExtents(){
d.log("getCurrentExtents");
    var map = Fusion.getMapById('mapArea');
    var aMapExtents = [];
    aMapExtents[0] = parseFloat(map._oCurrentExtents.left);
    aMapExtents[1] = parseFloat(map._oCurrentExtents.bottom);
    aMapExtents[2] = parseFloat(map._oCurrentExtents.right);
    aMapExtents[3] = parseFloat(map._oCurrentExtents.top);

    return aMapExtents;
}

function setMapExtents(szExtents) {
d.log("setMapExtents");

    if(szExtents != "" && szExtents != null){
        var mapWidget = Fusion.getMapById('mapArea'); 
        var maps = mapWidget.getAllMaps(); 
        var map = maps[0];
        var a = szExtents.split(",");
    
        map.mapWidget.setExtents(new OpenLayers.Bounds(parseFloat(a[0]), parseFloat(a[1]), parseFloat(a[2]),  parseFloat(a[3])));
    }
}

function processSearchInput(oObject){
    $('FUSION_SEARCH_WIDGET_SEARCH_DATA').value = oObject.value;    
}

function executeSearch(){

}

function generateDateString(month,day,year,hr,min,sec){

    return month+"-"+day+"-"+year+" "+hr+":"+min+":"+sec;

}

function graphDatesChanged(){

    var bFoundError = false;

    var aStart = [];
    aStart.push($('startYear').value);
    aStart.push($('startMonth').value);
    aStart.push($('startDay').value);

    var aEnd = []
    aEnd.push($('endYear').value);
    aEnd.push($('endMonth').value);
    aEnd.push($('endDay').value);

    // validate the dates
    for(var i=0;i<aStart.length;i++){
        if(aStart[i] == "" || isNaN((aStart[i]-1)) == true){
            bFoundError = true;
        }
    }

    for(var i=0;i<aStart.length;i++){
        if(aEnd[i] == "" || isNaN((aEnd[i]-1)) == true){
            bFoundError = true;
        }
    }

    if(bFoundError){
        alert(OpenLayers.i18n('Invalid Date'));
    }

    // prepare globals
    gStartDate = generateDateString(aStart[2],aStart[1],aStart[0],0,0,0);
    gEndDate = generateDateString(aEnd[2],aEnd[1],aEnd[0],23,59,59);

    // update graph data.
    for(var i=0;i<aGraphs.length;i++){
        for(var j=0;j<aGraphs[i].values.length;j++){
            updateGraphData(aGraphs[i].updateGraphData[j],i,j);
        }
    }
    // update the graphs with the new data.
    updateGraph();
}

function clearGraphs(){

  var oGraphImages = $('graphImages');
  var oGraphTable = $('graphTableData');
  
  oGraphImages.innerHTML = "";
  oGraphTable.innerHTML = "";
  aGraphs = [];

}

function buildYearSelect(szID,szFirstOrLast){

    var oSelect = document.getElementById(szID);
    var beginYear = 1889;
    var myDate = new Date();
    var endYear = myDate.getFullYear();
    var iYears = endYear - beginYear;
    
    for(i=0;i<iYears+1;i++)
        {
        oSelect.options[i] = new Option(beginYear+i,beginYear+i);
        }

    if(szFirstOrLast == 1){
        oSelect.options[0].selected = true
    }
    else
    {
        oSelect.options[iYears-1].selected = true
    }
}

function buildMonthSelect(szID,szFirstOrLast){
    var oSelect = document.getElementById(szID);

    for(i=0;i<12;i++)
        {
        oSelect.options[i] = new Option(i+1,i+1);
        }
        
    if(szFirstOrLast == 1){
        oSelect.options[0].selected = true
    }
    else
    {
        oSelect.options[11].selected = true
    }
        
}






