//
//------------------------------------------------------------------------------
//   GLOBAL VARIABLES
//------------------------------------------------------------------------------
var map;

var BizMap = {};
BizMap.locX = "";
BizMap.locY = "";
BizMap.locatedAddress = "";
BizMap.activeCategoryId = "";
BizMap.blnLayersInfoLoaded = false;
BizMap.blnInitialPageLoadDone = false;
BizMap.blnSwitchedToOrthos = false;
BizMap.theMapScale = "";
BizMap.LoadLyrSpanIds = [];
BizMap.IMSlayers = "";   //Layers initially loaded to the map
BizMap.WMSlayers_poly = "";
BizMap.WMSlayers_other = "";
BizMap.Lyrs_Scales = {};
BizMap.RptXml = "";
BizMap.RptLyrContents = "";
BizMap.Lyrs_MetaData = [];
BizMap.Layers = {};
BizMap.HMFA = {};
BizMap.HMFA.counter = 0;
BizMap.HMFA.census_dictionary = {};

//NOTE -------------------------------------------------------------------------
//commented HMFA code can be searched using "HMFA CODE" string
// -----------------------------------------------------------------------------

//
//------------------------------------------------------------------------------
//   BUILDING THE MAP, BUILDING ALL THE PANELS
//------------------------------------------------------------------------------
//OGIS.agsCache = "http://rancocas20.sa:8399/arcgis/server/arcgiscache/";
//OGIS.agsCache = "http://cooper.oit.state.nj.us/mapcache/OGIS_basemap/Layers/";
//OGIS. = "/NJ_GeoServer/wfs";
//OGIS.OL_path = '/oit/gis/NJ_GEOTOOLS/openlayers/trunk_8461';
OGIS.URLs = {
	rest_basemap_top: '/ArcGIS/rest/services/basemap_v4_top/MapServer/export', 
	rest_basemap_bottom: '/ArcGIS/rest/services/basemap_v4_bottom/MapServer/export',
	agsCache_top: "/arcgiscache/basemap_v4_top/Layers", 
	agsCache_bottom: "/arcgiscache/basemap_v4_bottom/Layers", 
	urlWFS: "/NJ_GeoServer/wfs",
	orthos: "http://njwebmap.state.nj.us/njimagery",
	bizmap: "/NJ_OGC/wms/OIT_BizMap",
	//OL_path: '/oit/gis/NJ_GEOTOOLS/openlayers/trunk_8461',
	OL_path: '/oit/gis/NJ_GEOTOOLS/openlayers/stable_2.10',
	ext_blank: '/oit/gis/NJ_GEOTOOLS/extjs/2.2/resources/images/default/s.gif',
	//ext_blank: '/oit/gis/NJ_GEOTOOLS/extjs/ext-3.0.0/resources/images/default/s.gif',
	gcComponentUrl: "/OIT_LocationSearch93/servlet/geocode" //http://199.20.64.49/OIT_LocationSearch
};
OGIS.wms_layers = {};

Ext.onReady(function(){
	    /*
	 *Building the Map with the necessary controls
	 *
	 */
	Ext.BLANK_IMAGE_URL = OGIS.URLs.ext_blank;
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    OpenLayers.ImgPath = OGIS.URLs.OL_path + '/img/';
    OpenLayers.Util.onImageLoadErrorColor = "transparent";
	OpenLayers.DOTS_PER_INCH = 96;
	//OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
	var options = {
		theme: null,
		projection: 'EPSG:102711',
		tileSize: new OpenLayers.Size(512, 512),
		controls: [new OpenLayers.Control.Navigation()],
		maxExtent: new OpenLayers.Bounds(93034,-23284,710334,970182), //NJ
		units: "ft",
		scales: [4000000, 3000000, 2500000, 1800000, 1125000, 570000, 300000, 150000, 75000, 37500, 25000, 12500, 6000, 2400, 1200]
		//maxResolution: 2000, // maxRes for other base layers than the AGS cache
		//numZoomLevels: 10
	};

	//create the map object
	OGIS.map = new OpenLayers.Map('olMap', options);

	//Assigning OGIS.map to a variable 'map' to pass it as a parameter to Geocoder
	map = OGIS.map;

	OGIS.map.addControl(new OpenLayers.Control.ScaleLine({maxWidth:150}));
	OGIS.map.addControl(new OpenLayers.Control.PanZoomBar());
	OGIS.map.addControl(new OpenLayers.Control.MousePosition({numDigits: 0}));

	Ext.QuickTips.init();
    /*
    for (var c = 0; c < catSet.length; c++){
        switch(catSet[c].category_name){
                case 'Environmental':
                     catSet[c].category_name = "<font color='#D65B4B'>" + catSet[c].category_name + "</font>";
                     break;
                case 'Economic Growth / Planning':
                     catSet[c].category_name = "<font color='#D65B4B'>" + catSet[c].category_name + "</font>";
                     break;
                case 'Work Force / Demographic':
                     catSet[c].category_name = "<font color='#D65B4B'>" + catSet[c].category_name + "</font>";
                     break;
                case 'HMFA':
                     catSet[c].category_name = "<font color='#D65B4B'>" + catSet[c].category_name + "</font>";
                     break;

        }
    }
    */
    //
    //--------------------------------------------------------------------------
    // 1) MAKING UP TOC (TABLE OF CATEGORIES) ITEMS (tocItems)
            //tocItems(parent) - catFieldSets(child) - chkBoxItems(child)
                //chkBoxItems - collection of layers under each Subcategory
                //catFieldSets - each set is a collection of Subcategories under each Category
                //tocItmes - each item for each Category
    // 2) MAKING UP LOCINFO (LOCATION INFO) ITEMS (locInfoItems)
                //locInfoItems - each item(is a div with associated subcategories, and layers) for one Category
    // 3) MAKING UP THE CHECKBOXES IN PRINTABLE REPORT PANEL (RptChkBoxContentOptionItems,RptChkBoxImageOptionItems)
                //RptChkBoxContentOptionItems - each item for the content under each Category
                //RptChkBoxImageOptionItems - each item for the associated map under each Category
    // 4) MAKING UP XML STRING THAT WILL BE FED TO REPORT GENERATING SERVLET (RptXml)
    // 5) MAKING UP A COLLECTION OF LAYERS AND THEIR SCALES(Lyrs_Scales)
    // 6) MAKING UP AN ARRAY OF LAYERS TO PROVIDE THE METADATA LINKS FOR THE LAYERS(Lyrs_MetaData)

    // 7) BUILDING THE MAP TEMPLATE(OGIS.map) WITH NECESSARY CONTROLS
    // 8) BUILDING find-a-location-panel WITH A FORM(FOR INPUT PARAMETERS) AND A DASHBOARD(TO DISPLAY RESULTS)
    // 9) BUILDING category-panel WITH tocItems
    //10) BUILDING HMFA TAB
    //11) BUILDING PRINTABLE REPORT TAB WITH RptChkBoxContentOptionItems,RptChkBoxImageOptionItems
    //12) BUILDING loc-info-items-panel WITH locInfoItems, HMFA TAB, AND PRINTABLE REPORT
    //13) BUILDING content-panel WITH MAP(OGIS.map), loc-info-items-panel, legendinfo
    //14) BUILDING OVERALL LAYOUT WITH ALL THE ABOVE PANELS USING VIEWPORT
    //15) CHECKING LAYER SCALES(to enable/disable corresponding check boxes),
    //    ADDING LAYER METADATA LINKS, ADDING LAYERS TO MAP, PROCESSING INPUT ADDRESS PARAMETERS IF ANY.
    //16) SPECIAL NOTE: on 01/28/2009 it was decided that for HMFA Category, the Location Info and Report will be
    //    processed differently than the other Categories.
    //--------------------------------------------------------------------------
    var tocItems = [];
    var locInfoItems = [];
    var RptChkBoxContentOptionItems = [];
    var RptChkBoxImageOptionItems = [];

    var LocInfoDivSet = document.getElementById('locInfo');

    for (c = 0; c < catSet.length; c++){

        var catIdn = catSet[c].category_idn;
        var catName = catSet[c].category_name;
        var catDisclaimer = catSet[c].disclaimer;
        var subcatSet = catSet[c].subcategories;



        var catFieldSets = [];

        //Making the first category open and the other categories collapse
        if (c == 0){
           BizMap.activeCategoryId = catIdn;
           blnCollapsed = false;
        }

        //Checking if the Category is HMFA to avoid building Location Info and PDF report parts
        var isHMFA = false;
        if (catIdn == "hmfa"){
           isHMFA = true;
        }

        //Creating div for each category under Location Info
        var newInfoDiv = document.createElement('div');
        var newInfoDivId = 'info_' + catIdn + 'Div';  //DEJUNG - to get the name of hmfa div under location info
        newInfoDiv.setAttribute('id',newInfoDivId);
        newInfoDiv.className = 'themeBlueBG';
        LocInfoDivSet.appendChild(newInfoDiv);
        var eachInfoDivContent = "";
        if (!isHMFA){
           eachInfoDivContent = "<div class='sz11 headerBlu bld OGIS_GC_Header' style='border-width:0px 0px 0px 0px;background-color:#eff7ff;padding-bottom:6pt;padding-top:4pt;padding-left:1em;'>" + catName + "&nbsp;<span id='" + catIdn + "_locAdr' class='sz8 headerBlu bld'></span><br />";
           eachInfoDivContent += "<span class='sz8 bk norm'>" + catDisclaimer + "</span></div>";
        }

        //Adding Category xml tags to RptXml
		
        if (!isHMFA){
           BizMap.RptXml += "<CAT><ID>" + catIdn + "</ID><NAME>" + catName + "</NAME><DISCLAIMER>" + catDisclaimer + "</DISCLAIMER>";
        }

        for (s = 0; s < subcatSet.length; s++){
             var subcatIdn = subcatSet[s].sub_category_idn;
	         var subcatName = subcatSet[s].subcategory_name;
	         var subcatDisclaimer = subcatSet[s].disclaimer;

             //Adding SubCategory info to LocInfo
	         eachInfoDivContent += "<div class='sz9 bld headerBlu' style='padding-left:1em;padding-bottom:4pt;padding-top:4pt;border-width:0px 0px 0px 0px; border-style:solid; border-color:#cccccc;background-color:#ffffff;'>" + subcatName + "</div>";

	         //Adding SubCategory xml tags to RptXml
			 
	         if (!isHMFA){
                BizMap.RptXml += "<SUBCAT><NAME>" + subcatName + "</NAME><DISCLAIMER>" + subcatDisclaimer + "</DISCLAIMER>";
             }

             var lyrSet = subcatSet[s].layers;
             var chkBoxItems = [];
             var tdColor = "";
             eachInfoDivContent += "<table border='0' width='100%' cellspacing='0'>";
	         for (a = 0; a < lyrSet.length; a++){

	              //---------------------------------
                  //NOTE:
                  //---------------------------------
	              //sga layer is used for map display
	              //sgaQL layer is used for query
	              //cnty layer is used for query
	              //---------------------------------
					
	              var lyrId = lyrSet[a].layerid;
				  OGIS.wms_layers[lyrId] = lyrSet[a].wms_layout_order;
		          var lyrName = lyrSet[a].layer_name;
		          var lyrDisclaimer = lyrSet[a].disclaimer;
		          var lyrVisibility = (lyrSet[a].visibility == "true") ? "checked" : "";
		          var lyrScale = lyrSet[a].maxscale;

		          //Collecting the visible layers of the active category
		          if (c == 0 && lyrSet[a].visibility == "true"){
					if (lyrSet[a].wms_layout_order == 0) {
						BizMap.WMSlayers_poly += ((BizMap.WMSlayers_poly == "") ? (lyrId) : ("," + lyrId));
					} else if (lyrSet[a].wms_layout_order == 1) {
						BizMap.WMSlayers_other += ((BizMap.WMSlayers_other == "") ? (lyrId) : ("," + lyrId));
					}
		          }

		          if (lyrSet[a].query_fields != 'none' && lyrId != "sga"){

                     var LyrName_In_LocInfo = (lyrId == "sgaQL") ? "Smart Growth Areas" : lyrName;

                     if (lyrName == "Public Use Airports"){
                         LyrName_In_LocInfo = "Public Use Airports (within 10 miles)";
                     }

                     //Adding layers info to LocInfo
                     tdColor = (tdColor != "") ? "" : "AliceBlueBG";
                     eachInfoDivContent += "<tr>";
                     eachInfoDivContent += "<td class='" + tdColor + " sz8 bld dgray' style='padding-left:2em;height:20pt;vertical-align:middle;width:75%;padding-top:2pt;padding-bottom:2pt;'>" + LyrName_In_LocInfo + "</td><td class='" + tdColor + " sz8 bld dgray' style='vertical-align:middle;padding-top:2pt;'><span id='" + catIdn + "_" + subcatIdn + "_" + lyrId + "_span' class='sz8 bk norm' style='padding-left:1em;'><img src='/oit/gis/OIT_BusinessMap/images/ajax-loader4.gif' border='0' /></span></td>";
                     eachInfoDivContent += "</tr>";
                     eachInfoDivContent += "<tr><td colspan='2' class='" + tdColor + " sz8 bld dgray' style='padding-left:2em;height:0pt;'><div id='" + catIdn + "_" + subcatIdn + "_" + lyrId + "_spansub' class='sz8 bk norm' style='padding-left:1em;'></div></td></tr>";
                     BizMap.LoadLyrSpanIds[BizMap.LoadLyrSpanIds.length] = catIdn + "_" + subcatIdn + "_" + lyrId + "_span";

		             //Adding Layer xml tags to RptXml
		             if (!isHMFA){
                        BizMap.RptXml += "<LYR><ID>" + lyrId + "</ID><NAME>" + LyrName_In_LocInfo + "</NAME><DISCLAIMER>" + lyrDisclaimer + "</DISCLAIMER></LYR>";
                     }

                  }

                  if (lyrId == "sgaQL"){
		             continue;
		          }

		          if (lyrId == "cnty"){
		             continue;
		          }

		          chkBoxItems[chkBoxItems.length] = new Ext.form.Checkbox({
                            id : 'lyrChkBox_' + lyrId + '_' + catIdn,
                            inputValue : lyrId,
                            boxLabel: "<span class='sz8' id='" + lyrId +  "_" + catIdn + "_lyrChkLabel'>" + lyrName + "</span>",
                            checked : lyrVisibility,
                            labelSeparator : "",
                            disabled:false,
                            //anchor : "100%",
                            listeners : {
                                    check : BizMap.signalMapRefresh
                            }
                  });
                  BizMap.Lyrs_MetaData.push(lyrId + "_" + catIdn + "_lyrChkLabel");
                  BizMap.Lyrs_Scales['lyrChkBox_' + lyrId + '_' + catIdn] = lyrScale;
	         }
             eachInfoDivContent += "</table>";

             catFieldSets[catFieldSets.length] = new Ext.form.FieldSet({
                                               autoHeight: true,
                                               layout : 'form',
                                               items:chkBoxItems,
                                               title: subcatName,
                                               labelWidth : 5,
                                               collapsible : false

             });
             //Finishing Subcategory xml tags for each Subcategory
			 
             if (!isHMFA){
		        BizMap.RptXml += "</SUBCAT>";
		     }
        }

        document.getElementById(newInfoDivId).innerHTML = eachInfoDivContent;

        tocItems[c] = {
		            id:catIdn,
		            title:catName,
		            autoScroll:true,
		            collapsed:blnCollapsed,
		            cls: 'custom-accordion', // look in layout-browser.css to see the CSS rules for this class
		            listeners : {
					          beforeexpand : BizMap.onCategoryChange
		            },
		            tools:[{
                            id:'refresh',
                            qtip: 'Refresh Map with selected Layers',
                            // hidden:true,
                            handler: function(event, toolEl, panel){
                                     BizMap.refreshMap();
                            }
                    }],
					items : ((catFieldSets.length == 0) ? null : catFieldSets)
	    };

	    locInfoItems[c] = {
   			            id:"info_" + catIdn,
			            title:catName,
			            contentEl : newInfoDivId,
			            autoScroll: true
	    };

        if (!isHMFA){
	    RptChkBoxContentOptionItems[RptChkBoxContentOptionItems.length] = new Ext.form.Checkbox({
                        id : 'RptChkBox_' + catIdn,
                        name : 'RptChkBox_' + catIdn,
                        inputValue : catIdn,
                        boxLabel : catName,
                        checked : true,
                        labelSeparator : ""//,
                        //cls:'txtAlignCenter'
        });

        RptChkBoxImageOptionItems[RptChkBoxImageOptionItems.length] = new Ext.form.Checkbox({
                        id : 'RptChkBoxImg_' + catIdn,
                        name : 'RptChkBoxImg_' + catIdn,
                        inputValue : catIdn,
                        boxLabel : " ",
                        checked : true,
                        labelSeparator : ""//,
                        //cls:'txtAlignCenter'
        });
        }


	    //Finishing Category xml tags for each Category
		
	    if (!isHMFA){
	       BizMap.RptXml += "</CAT>";
	    }
    }

	/*
	 *Building the Find a Location Panel
	 *
	 */
	var Find_a_Location_Panel = new Ext.TabPanel({
       id: 'find-a-location-panel',
       region: 'north', // this is what makes this panel into a region within the containing layout
       margins: '5 0 0 5',
       layoutOnTabChange:true,
       activeItem: 0,
       border: true,
       height:220,
       items: [
           new Ext.FormPanel({title: 'Find a Location', border: false, defaultType: 'textfield', labelWidth: 75,
               bodyStyle:'padding: 10px 5px 10px 10px',
               id: 'addSearchForm',
               keys : [{
                   key: Ext.EventObject.ENTER,
                   fn : GeocoderSupport.geocodeLoc
               }],
               items: [
                   {fieldLabel: 'Street',
                       name: 'street',
                       anchor:'98%'
                   },
                   {fieldLabel: 'Cross Street',
                       name: 'crossstreet',
                       anchor:'98%'
                   },
                   {fieldLabel: 'City',
                       name: 'city',
                       anchor:'85%'
                   },
                   {fieldLabel: 'Zip',
                       name: 'zip',
                       anchor:'60%'
                   },
                   {xtype: 'panel',
                       border: false,
                       items: [
                           {
                               /*
                               xtype: 'checkbox',
                               boxLabel: 'Locate Street If Address Not Found',
                               labelSeparator: '',
                               checked: true,
                               name: 'locStIfAddrNotFound'
                               */
                               xtype:'hidden',
                               name: 'locStIfAddrNotFound',
                               value: 'true'
                           }
                       ],
                       buttonAlign: 'right',
                       buttons: [
                           {text: 'Search',
                               id: 'cmdAddress',
                               handler: GeocoderSupport.geocodeLoc
                           },
                           {text: 'Reset',
                               id: 'cmdReset',
                               handler: BizMap.resetFindLocForm
                           }
                       ]

                   },
                   {
                     xtype:'hidden',
                     name : 'processRec'
                   },
                   {
                     xtype:'panel',
                     border: false,
                     //html: "(OR) <span class='sz8 bk'>Use the tool below</span><br /><table width='100%' cellspacing='0' cellpadding='0'><tr><td style='font-size:8pt;padding-right:5pt;text-align:right'>Click on this button,<br /> click on map to find a location</td><td><a href='javascript:GeocoderSupport.pointClick()'><img id='gc_on_off' src='/oit/gis/OIT_BusinessMap/images/geocode_off1.gif' /></a></td></tr></table>",
                     html: '<table cellspacing="0" cellpadding="0" width="97%" style="border: 1px dashed gray;background-color:WhiteSmoke;"><tbody><tr><td class="sz10 bld red" style="padding-left: 5px;">(OR)</td><td style="font-size: 8pt; padding-right: 5pt; text-align: right;">Click on this button, then<br/>click on map to select a location</td><td><a href="javascript:GeocoderSupport.pointClick()"><img id="gc_on_off" src="/oit/gis/OIT_BusinessMap/images/geocode_off1.gif"/></a></td></tr></tbody></table>'
                     //cls:'sz10 bld red'
                   }
               ]
           }),
           {contentEl:'DashBoard',id:'resultsDisp',cls:'txtAlignCenter', title: 'Results', autoScroll: true, border: false}
       ]
   });



   /*
	*Building the Category (Table Of Categories) Panel
	*
	*/
    var Table_Of_Categories_Panel = new Ext.Panel({
		id: 'category-panel',
		title: 'Categories',
		region: 'center', // this is what makes this panel into a region within the containing layout
		layout: 'accordion',
		margins: '0 0 5 5',
		header: false,
		border: false,
		bodyStyle: 'background-color:#DFE8F6', 
		// if all accordion panels are collapsed, this looks better in this layout
		defaults: {bodyStyle: 'padding:5px'},
		animCollapse: true,
		items: tocItems
	});



	/*
	 *Building the Location Info Panel
	 *
	 */
	//HMFA Code//
	//Adding the HTMA tab
	/*
	locInfoItems[locInfoItems.length] = {
   		id:"hmfaTab",
		title:"<span style='color:MediumAquaMarine;'>HMFA</spam>",
		html : 'Under test',
		autoScroll: true
	};*/

    //Adding the Printable Report Content
	
    locInfoItems[locInfoItems.length] = new Ext.FormPanel({
        frame:true,
        autoScroll: true,
        id : 'cntRpt',
        layout : 'table',
		border: false,
        autoWidth: true,
        defaults: {
                  // applied to each contained panel
                  //bodyStyle:'border-width:1px 1px 1px 1px; border-style:dashed; border-color:#000000; background:#ffffff;',
                  autoWidth: true,
				  border: false,
                  autoScroll:true
        },
        layoutConfig: {
                // The total column count must be specified here
                columns: 2
        },
        title: "<span style='color:#D65B4B;'>Printable Report</span>",
        width: '100%',
        items:[
            {
               html: 'Click on the "Generate Printable Report" button to generate a PDF document of the map(s) and report(s) selected below.',
               colspan: 2,
               cls:'sz9 headerBlu'
            },
            {
               html: '&nbsp;',
               colspan: 2
            },
            {
               html: 'Select Categories',
               cls:'sz9 headerBlu bld LPad30 txtUnderline'
            },
            {
                html: 'Include Map?',
                cls:'sz9 headerBlu bld txtAlignLeft txtUnderline'
            },
            {
               html: '&nbsp;',
               colspan: 2
            },
            {
                items : RptChkBoxContentOptionItems,
                cls:'sz9 noWrap LPad30'
            },

            {
                items : RptChkBoxImageOptionItems,
                cls:'txtAlignLeft sz9 noWrap'
            },
            {
               colspan: 2,
               html: '&nbsp;'
            },
            {
               items : new Ext.Button ({id:'locInfoRptBtn',text:'Generate Printable Report (PDF)',handler : BizMap.genRpt}),
               cls : 'LPad30'
            },
            {
               html: '&nbsp;'
            },
            {
               height: 50,
               html: '&nbsp;',
               colspan: 2
            }
            //HMFA Code//
            ,
            {
               html: 'HMFA Report',
               cls:'sz9 headerBlu bld LPad30 txtUnderline',
               colspan: 2
            },
            {
				colspan: 2,
				html: '&nbsp;'
            },
			{
                colspan:2,
                items: new Ext.form.Checkbox ({id:'chkMap',labelSeparator : "",checked:true,boxLabel:'Include map'}),
                cls:'sz9 LPad30'
            },
            {
                colspan:2,
                items: new Ext.form.Checkbox ({id:'chkHMFA',labelSeparator : "",checked:true,boxLabel:'Include HMFA section'}),
                cls:'sz9 LPad30'
            },
            {
				colspan:2,
                items: new Ext.form.Checkbox ({id:'chkCensus',labelSeparator : "",checked:true,boxLabel:'Include Census section'}),
                cls:'sz9 LPad30'
            },
			{
				colspan: 2,
				html: '&nbsp;'
            },
            {
                colspan:2,
                items : new Ext.Button ({id:'hmfaRptBtn', text:'Generate HMFA Report', handler : BizMap.genHMFARpt}),
                cls:'LPad30'
            }
        ]
    });

	var Loc_Info_Items_Panel = new Ext.TabPanel({
		id: 'loc-info-items-panel',
		defaults: {bodyStyle: 'background-color:#DFE8F6'},
		margins: '5 5 0 5',
		deferredRender:true,
		layoutOnTabChange:true,
		activeItem: 0,
		plain: false,
		border: false,
		items:locInfoItems,
		enableTabScroll : true,
		animScroll : true,
		tabPosition:'top'
	});


	/*
	 *Building the Panel that accommodates Map,Legend and Location Info panels
	 *
	 */
    var Map_Legend_LocInfo_Combined_Panel = new Ext.Panel({
		id: 'content-panel',
		region: 'center', // this is what makes this panel into a region within the containing layout
		layout:'tdgi_border',
		margins: '5 5 5 5',
		defaults: {
			split: true,
			useSplitTips: true
		},
		bodyBorder: false,
		border: false,
		items: [
			{
                title: 'Location Info',
				id: 'locationinfo-panel',
				region:'center',
				collapsible: false,
				floatable: false,
				autoScroll:true,
				width: 450,
				minSize: 100,
				maxSize: 800,
				activeItem : 1,
				layout:'card',
				collapseFirst : false,
				items : [
                      Loc_Info_Items_Panel,
                      {contentEl:'helpInfo', id:'helpDiv',title: 'Help',autoScroll:true, border: false,
                         tools:[{
                            id:'close',
                            qtip: 'Close Help document',
                            handler: function(event, toolEl, panel){
                                     if (!BizMap.isLocationFound()){
                                        return false;
                                     }
                                     Ext.getCmp('locationinfo-panel').layout.setActiveItem(0);
                            }
                         }]
                      }
                ],
                tools:[{
                            id:'help',
                            qtip: 'Open help document',
                            handler: function(event, toolEl, panel){
                                     Ext.getCmp('locationinfo-panel').layout.setActiveItem(1);
                            }
                    }]
			},
            {
				title: 'Map',
				collapsible: true,
				floatable: false,
				layout:'tdgi_border',
				region:'west',
				defaults: {
					split: true,
					useSplitTips: true
				},
				width : 300,
				minSize : 100,
				maxSize : 600,
				collapsedTitle: {
						//Just like an Ext.DomHelper config object
						element : {
							    // Required0
							    tag  : 'img',
							    // Required
							    src  : "/oit/gis/OIT_BusinessMap/images/MapPanel.gif",
							    // Set this if you need to.
							    style  : "margin-left:6px;"
						}
				},
				split:true,
				items: [
					{xtype: 'mapcomponent',
						header: false,
						id: 'Map-Panel',
						region:'center',
						collapsible: true,
						border: false,
						contentEl:'olMap',
						map: OGIS.map
					},
					{title: 'Legend',
					    collapsedTitle: {
						        //Just like an Ext.DomHelper config object
						        element : {
							            // Required0
							            tag  : 'div',
							            // Required
							            html : 'Legend',
							            // Set this if you need to.
							            style  : "margin-left:3px;margin-top:3px;color: #003366; font-weight: bold;"
						        }
					    },
						id: 'Legend-Panel',
						region:'south',
						bodyBorder: false,
						collapsible: true,
						collapsed: true,
						titleCollapse: true,
						floatable: false,
						height: 200,
						minSize: 100,
						maxSize: 300,
						autoScroll:true,
						contentEl : 'legendInfo',
						listeners : {
							  beforeexpand : BizMap.swapLegendImage
						},
                        split:true
					}
				]
			}
		]
	});

	/*
	 *Building the overall Layout that fits in all the above panels
	 *
	 */
    new Ext.Viewport({
		layout: 'border',
		title: 'Ext Layout Browser',
		items: [{
			xtype: 'box',
			region: 'north',
			applyTo: 'IW_Banner',
			height: 59
		},{
			layout: 'border',
	    	id: 'layout-browser',
	        region:'west',
	        border: false,
	        width: 275,
			items: [Find_a_Location_Panel, Table_Of_Categories_Panel]
		},
		Map_Legend_LocInfo_Combined_Panel
		],
        renderTo: Ext.getBody()
    });

    /*
	 * Immediate actions following the Layout build
	 *
	 */
    BizMap.blnInitialPageLoadDone = true;
	OGIS.map.events.register('moveend', null, BizMap.refreshMap);
	BizMap.theMapScale = OGIS.map.getScale();
	BizMap.checkLyrScales();

    //Appending metadata links next to the layer names
    for (var n = 0; n < BizMap.Lyrs_MetaData.length; n++){
	    if (BizMap.Lyrs_MetaData[n].indexOf("hmfa_") == 0){
			BizMap.Lyrs_MetaData[n] = BizMap.Lyrs_MetaData[n].replace("hmfa_", '');
			var tempLyrId = BizMap.Lyrs_MetaData[n].substring(0, BizMap.Lyrs_MetaData[n].indexOf("_"));
			tempLyrId = 'hmfa_' + tempLyrId;
			BizMap.Lyrs_MetaData[n] = "hmfa_" + BizMap.Lyrs_MetaData[n];
		} else {
			var tempLyrId = BizMap.Lyrs_MetaData[n].substring(0,BizMap.Lyrs_MetaData[n].indexOf("_"));
		}
	    Anchor=document.createElement("A");
        Anchor.href='/oit/gis/OIT_BusinessMap/dataDescriptions.htm#' + tempLyrId;
        Anchor.target='_blank';
        Anchor.innerHTML = "<img src='/oit/gis/OIT_BusinessMap/images/metadata.png' alt='View Metadata for this layer' title='View Metadata for this layer' style='' />";
		/*
		Required to migrate to /extjs/3.3.0
		if(document.getElementById(BizMap.Lyrs_MetaData[n]) != null) {
			document.getElementById(BizMap.Lyrs_MetaData[n]).parentNode.parentNode.parentNode.appendChild(Anchor);
		} 
		*/
		document.getElementById(BizMap.Lyrs_MetaData[n]).parentNode.parentNode.parentNode.appendChild(Anchor);
		
	}


    /*
	 * Creating and adding the necessary Layers
	 *
	 */
	//create the AGS cached layer
	var scales = [4000000, 3000000, 2500000, 1800000, 1125000, 570000, 300000, 150000, 75000, 37500, 25000, 12500, 6000, 2400, 1200];
    var AGSCacheConfig = {
			units: "ft",
			//upper-left corner of map cache. AGS uses upper-left instead of bottom-left like OpenLayers default
			tileOrigin: new OpenLayers.LonLat(-842000,1440000),
			//size of tiles in pixels
			tileSize: new OpenLayers.Size(512,512),
			//DPI of tiles
			DOTS_PER_INCH: 96,
			//scales for zoom levels
			scales : scales
		};


BizMap.Layers['ags_cache_bottom'] = new OpenLayers.Layer.ArcGIS93Rest( "base_map_b", 
						"/ArcGIS/rest/services/basemap_v4_bottom/MapServer/export",
		{layers:'_alllayers', format: "png24", transparent: true}, {singleTile: true, maxExtent: new OpenLayers.Bounds(-842000,-484000,1694000,1440000),buffer: 0}
	);
	
	
	

    BizMap.Layers['orthos'] = new OpenLayers.Layer.WMS( "base_ortho",
            OGIS.URLs.orthos,
            {transparent:'false', layers: "Natural2007", format:'image/jpeg',exceptions:'application/vnd.ogc.se_xml'},
            {isBaseLayer: true, singleTile: true, ratio:1.5, visibility: true, projection: 'EPSG:102711'}
    );
	BizMap.Layers['wms_poly'] = new OpenLayers.Layer.WMS( "WMS_poly",
            OGIS.URLs.bizmap,
            {transparent:'true', layers: BizMap.WMSlayers_poly, format:'image/png'},
            {isBaseLayer: false, scales: [4000000,1], singleTile: true, ratio:1.5, visibility: true, projection: 'EPSG:102711'}
    );
	

	
	
	BizMap.Layers['ags_cache_top'] = new OpenLayers.Layer.ArcGIS93Rest( "base_map_t",
		"/ArcGIS/rest/services/basemap_v4_top/MapServer/export",
		{layers: '_alllayers', format: "png8", transparent: true}, 
			{isBaseLayer: false, singleTile: true,  visibility: true, buffer: 0,
			maxExtent: new OpenLayers.Bounds(-842000,-484000,1694000,1440000)} 

	);
	
	
	BizMap.Layers['wms_other'] = new OpenLayers.Layer.WMS( "WMS_other",
            OGIS.URLs.bizmap,
            {transparent:'true', layers: BizMap.WMSlayers_other, format:'image/png'},
            {isBaseLayer: false, scales: [4000000,1], singleTile: true, ratio:1.5, visibility: true, projection: 'EPSG:102711'}
    );
    //HMFA Code//
    /*
    BizMap.Layers['hmfa_wms'] = new OpenLayers.Layer.WMS(
		"ogis:HMFA_SuperLayer - Ratio", "http://wading.oit.state.nj.us:8080/geoserver/wms",
		{transparent:'true',
			layers: 'ogis:HMFA_SuperLayer',
			format:'image/png',
			styles: ''//,
			//tiled: 'true',
			//tilesOrigin : "172887.36026829173,94666.4807471688"
		},
		{isBaseLayer: false,
			singleTile: true,
			ratio: 1.5,
			visibility: false,
			projection: 'EPSG:3432'
		}
	);
	*/

	//OGIS.map.addLayers([BizMap.Layers['ags_cache'],BizMap.Layers['orthos'],BizMap.Layers['hmfa_wms'],OGIS.basemap_WMS]);
	OGIS.map.addLayers([
		BizMap.Layers['ags_cache_bottom'],BizMap.Layers['orthos'],
		BizMap.Layers['wms_poly'],BizMap.Layers['ags_cache_top'],BizMap.Layers['wms_other']
	]);
	OGIS.map.setCenter(new OpenLayers.LonLat(426235, 476945), 2);

    /*
	 * Processing the address parameters(if any) during the initial load of the application
	 *
	 */
    var qp = OpenLayers.Util.getParameters();

    var ipStreet = (qp.street != undefined) ? qp.street : "";
    var ipCrossStreet = (qp.crossstreet != undefined) ? qp.crossstreet : "";
    var ipCity = (qp.city != undefined) ? qp.city : "";
    var ipZip = (qp.zip != undefined) ? qp.zip : "";

	if (ipStreet != "" || ipCrossStreet != "" || ipCity != "" || ipZip != ""){

	     Ext.getCmp('addSearchForm').getForm().findField('street').setValue(ipStreet);
         Ext.getCmp('addSearchForm').getForm().findField('crossstreet').setValue(ipCrossStreet);
         Ext.getCmp('addSearchForm').getForm().findField('city').setValue(ipCity);
         Ext.getCmp('addSearchForm').getForm().findField('zip').setValue(ipZip);
         //Ext.getCmp('addSearchForm').getForm().findField('locStIfAddrNotFound').setValue(true);
         Ext.getCmp('addSearchForm').getForm().findField('processRec').setValue("");

         ipStreet = "";
         ipCrossStreet = "";
         ipCity = "";
         ipZip = "";

         GeocoderSupport.geocodeLoc();
    }

	if (qp.hmfa != undefined){
		//logic here for switching toc items if hmfa=true
		if (qp.hmfa == 'true') Ext.getCmp('category-panel').items.items[3].expand();
	}
    /*
	 * Switching mechanism between the map and the orthos
	 *
	 */
    OpenLayers.Control.viewMap = OpenLayers.Class(OpenLayers.Control, {
        type: OpenLayers.Control.TYPE_TOOL,
        title: 'Switch to the map',
        eventListeners: {
           activate: function() {
               if (this.map) {
                   blnSwitchedToOrthos = false;
                   this.map.setBaseLayer(BizMap.Layers.ags_cache_bottom, true);
               }
           }
        },
        CLASS_NAME: "OpenLayers.Control.viewMap"
    });

    OpenLayers.Control.viewOrthos = OpenLayers.Class(OpenLayers.Control, {
        type: OpenLayers.Control.TYPE_TOOL,
        title: 'Switch to the orthos',
        eventListeners: {
           activate: function() {
               if (this.map) {
                   blnSwitchedToOrthos = true;
                   this.map.setBaseLayer(BizMap.Layers.orthos, false);
               }
           }
        },
        CLASS_NAME: "OpenLayers.Control.viewOrthos"
    });

    var vM = new OpenLayers.Control.viewMap();
    OGIS.panel = new OpenLayers.Control.Panel({defaultControl: vM});
    OGIS.panel.addControls([
       vM,
       new OpenLayers.Control.viewOrthos()
    ]);
    OGIS.map.addControl(OGIS.panel);
    OGIS.panel.div.className = 'olControlNoSelect OGIS_LS';
	
	$('info_hmfaDiv').innerHTML = '<div id="hmfa_sl_rpt" width="100%">' + HMFA_sl_rpt.replace(/{[^}]+}/g, '&nbsp;') + 
		'</div><div id="hmfa_census_rpt" width="100%">' + HMFA_census_rpt.replace(/{[^}]+}/g, '&nbsp;') + '</div>';
	
    /*
	 * Ending with the fading effect
	*/
    Ext.get('tempLoading').fadeOut({easing: 'easeIn', duration: 1, concurrent: false}); //,remove:true
});

//
//------------------------------------------------------------------------------
//   FUNCTIONS RELATED TO HMFA QUERIES
//------------------------------------------------------------------------------
//HMFA Code//

OGIS.makeGMLgeometry = function(O){
	var xml = "";
	switch (O.conversionType){
		case "PointToBBOX":
			O.conversionType = "BBOX";
			O.geom.minX = parseFloat(O.geom.lon) - parseFloat(O.pointBuffer);
			O.geom.minY = parseFloat(O.geom.lat) - parseFloat(O.pointBuffer);
			O.geom.maxX = parseFloat(O.geom.lon) + parseFloat(O.pointBuffer);
			O.geom.maxY = parseFloat(O.geom.lat) + parseFloat(O.pointBuffer);
		break;
	}
	if(O.conversionType == "BBOX"){
		xml +=	'<gml:Box srsName="' + OGIS.map.getProjection() + '"><gml:coordinates>';
		xml +=		Math.round(O.geom.minX) + ',';
		xml +=		Math.round(O.geom.minY) + ' ';
		xml +=		Math.round(O.geom.maxX) + ',';
		xml +=		Math.round(O.geom.maxY);
		xml +=	'</gml:coordinates></gml:Box>';
	}
	return xml;
}

OGIS.makePostFilter = function(filterType, inXML){
	//OpenLayers.Console.log("Loading... please wait...");
	//OpenLayers.Console.log(inXML);

	var postTemplate = 	'<wfs:GetFeature service="WFS" version="1.0.0" outputFormat="JSON" ';
	postTemplate +=		' xmlns:wfs="http://www.opengis.net/wfs" ';
	postTemplate +=		' xmlns:ogc="http://www.opengis.net/ogc" ';
	postTemplate +=		' xmlns:gml="http://www.opengis.net/gml" ';
	postTemplate +=		' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
	postTemplate +=		' xsi:schemaLocation="http://www.opengis.net/wfs ';
	postTemplate +=		' http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd">';
	postTemplate +=			'<wfs:Query typeName="{ql}">';
//	postTemplate +=				'<ogc:PropertyName>the_geom</ogc:PropertyName>';
	postTemplate +=			'{pns}';
	postTemplate +=				'<ogc:Filter>';
	postTemplate +=					'<ogc:Intersects>';
	postTemplate +=						'<ogc:PropertyName>the_geom</ogc:PropertyName>';
	postTemplate +=						'{geom}';
	postTemplate +=					'</ogc:Intersects>';
	postTemplate +=				'</ogc:Filter>';
	postTemplate +=			'</wfs:Query>';
	postTemplate +=	'</wfs:GetFeature>';

	//  //SuperLayer report
	var pns = '';
	for (var i=0; i < HMFA_sl_layers.length; i++){
		pns +=			'<ogc:PropertyName>' + HMFA_sl_layers[i] + '</ogc:PropertyName>';
	}
	for (var ii=0; ii < HMFA_sl_programs.length; ii++){
		pns +=			'<ogc:PropertyName>' + HMFA_sl_programs[ii] + '</ogc:PropertyName>';
	}
	
	var postDict = {ql: HMFA_sl_queryLayer, pns: pns, geom: inXML.geoXML};
 	var postData = OGIS.String.supplant(postTemplate, postDict);
	
	//return;
	OpenLayers.Request.POST({
		url: OGIS.URLs.urlWFS,
		success: OGIS.processHMFA_sl,
		data: postData
	});

	// //Census Report
	BizMap.HMFA.counter = 0;
	BizMap.HMFA.census_dictionary = {};
	for (var a=0; a < HMFA_census.length; a++){
		var pns = '';
		for (var i=0; i < HMFA_census[a].fields.length; i++){
			pns +=			'<ogc:PropertyName>' + HMFA_census[a].fields[i] + '</ogc:PropertyName>';
		}
		
		var postDict = {ql: HMFA_census[a].layer, pns: pns, geom: inXML.geoXML};
		var postData = OGIS.String.supplant(postTemplate, postDict);
		
		OpenLayers.Request.POST({
			url: OGIS.URLs.urlWFS,
			success: OGIS.processHMFA_census,
			data: postData
		});
	}
}

OGIS.processHMFA_sl = function(response){
	//console.log(response);
	//$('info_hmfaDiv').innerHTML = response;
	//return;
	
	var format = new OpenLayers.Format.JSON();
    var features = format.read(response.responseText);
	var msgCodes = null;
	var msgCodeDictionary = {};
	//OpenLayers.Console.log(features.features[0]);
	//console.log(features.features[0]);
	if (features == null || features.features.length == 0){
		for (var a=0; a < HMFA_sl_layers.length; a++){
			msgCodeDictionary[HMFA_sl_layers[a]] = '<img src="/oit/gis/OIT_BusinessMap/hmfa/images/check_no.png" border="0" />';
		}
		for (var a2=0; a2 < HMFA_sl_programs.length; a2++){
			msgCodeDictionary[HMFA_sl_programs[a2]] = OGIS.Eligibility_Messages[HMFA_sl_programs[a2].substring(2)+'-D'] + '<br /><br />';
		}
	} else {
		for (var a=0; a < HMFA_sl_layers.length; a++){
			if (features.features[0].properties[HMFA_sl_layers[a]] == -1){
				msgCodeDictionary[HMFA_sl_layers[a]] = '<img src="/oit/gis/OIT_BusinessMap/hmfa/images/check_no.png" border="0" />';
			} else {
				msgCodeDictionary[HMFA_sl_layers[a]] = '<img src="/oit/gis/OIT_BusinessMap/hmfa/images/check_yes.png" border="0" />';
			}
		}
		
		for (var a2=0; a2 < HMFA_sl_programs.length; a2++){
			msgCodes = features.features[0].properties[HMFA_sl_programs[a2]].split(',');
			//console.log(features.features[0].properties[HMFA_programs[a2]].replace(" ", '').split(','));
			var msgContainer = '';
			for (var b=0; b < msgCodes.length; b++){
				//msgContainer += '<div style="width:100%">' + OGIS.Eligibility_Messages[msgCodes[b]] + '</div>';
				msgContainer += OGIS.Eligibility_Messages[msgCodes[b].replace(" ", '')] + '<br /><br />';
				//OpenLayers.Console.log(OGIS.Eligibility_Messages[msgCodes[b]]);
				//console.log(OGIS.Eligibility_Messages[msgCodes[b]]);
			}
			msgCodeDictionary[HMFA_sl_programs[a2]] = msgContainer;
		}
	}
	//OpenLayers.Console.log(msgCodeDictionary);
	$('hmfa_sl_rpt').innerHTML = OGIS.String.supplant(HMFA_table_rpt + HMFA_sl_rpt, msgCodeDictionary);
}

OGIS.processHMFA_census = function(response){
	//console.log(response);
	// $('hmfa_census_rpt').innerHTML = response;
	// return;
	BizMap.HMFA.counter++;
	
	var format = new OpenLayers.Format.JSON();
    var features = format.read(response.responseText);
	if (features == null || features.features.length == 0){ //features.features.length == 0 || 
		//alert("no features returned");
		//$('hmfa_census_rpt').innerHTML = '';
		return;
	} else {
		OpenLayers.Util.extend(BizMap.HMFA.census_dictionary, features.features[0].properties);
	}
	
	for (var x in features.features[0].properties){
		//if (x.hasOwnProperty(features.features[0].properties[x])){
		if (!isNaN(features.features[0].properties[x])){
			features.features[0].properties[x] = OGIS.Number.format(parseInt(features.features[0].properties[x]));
/*			if (features.features[0].properties[x].toString().indexOf('.') != -1){
				features.features[0].properties[x] = OGIS.Number.format(parseFloat(features.features[0].properties[x]),2);
			}
*/		}
//			alert(x + ' -- ' + features.features[0].properties[x]);
		//}
	}

	//OpenLayers.Console.log(features.features[0]);
	//console.log(features.features[0]);
	if (dd = 6) {
		$('hmfa_census_rpt').innerHTML = OGIS.String.supplant(HMFA_census_rpt, BizMap.HMFA.census_dictionary);
	}
}

OGIS.toggleCensusRPT = function(x) {
	if ($('census_rpt').style.display == "block"){
		//console.log("hide");
		x.src = "/oit/gis/OIT_BusinessMap/hmfa/images/show.gif";
		$('censusDisplay').style.borderBottomWidth = 1;
		$('census_rpt').style.display = "none";
	} else {
		//console.log("show");
		x.src = "/oit/gis/OIT_BusinessMap/hmfa/images/hide.gif";
		$('censusDisplay').style.borderBottomWidth = 0;
		$('census_rpt').style.display = "block";
	}
}

BizMap.genHMFARpt = function() {
	var frog = window.open("","wildebeast","width=725,height=800,scrollbars=1,resizable=1,toolbar=1,menubar=1");
	var fMapH = 350;
	var fMapW = 285;
	var dFromTop = 35;
	var dFromLeft = 5;
	var html = "<html><head>";
	html += '<title>HMFA Program Eligibility and Census Report</title>';
	html += '<link rel="stylesheet" type="text/css" href="/oit/gis/OIT_BusinessMap/hmfa/HMFA_styles.css" />';
	html += '</head><body>'; 
	//html += '<table cellspacing=0 cellpadding=0><tr><td>'; //width="625"
	html += '<b>Report for address:</b>&nbsp;&nbsp;' + BizMap.locatedAddress;
	//html += BizMap.locatedAddress + '<br />';
	var mapHTML = "";
	
		var cmSize = OGIS.map.getCurrentSize();
		var dMx = fMapW - cmSize.w;
		var dMy = fMapH - cmSize.h;
		
		//var mPxLoc = OGIS.map.getPixelFromLonLat(new OpenLayers.LonLat(myGC.marker.geometry.x,myGC.marker.geometry.y));
		//var rX = mPxLoc.x / cmSize.w;
		//var rY = mPxLoc.y / cmSize.h;
		var oldCoords = OGIS.map.getExtent();
		var mRes = OGIS.map.getResolution();
		var newCoords = {
			left: parseFloat(oldCoords.left) - ((dMx/2) * mRes),
			bottom: parseFloat(oldCoords.bottom) - ((dMy/2) * mRes),
			right: parseFloat(oldCoords.right) + ((dMx/2) * mRes),
			top: parseFloat(oldCoords.top) + ((dMy/2) * mRes)
		};
		
		var newMx = (((myGC.marker.geometry.x - newCoords.left) / mRes) - 10.5) ;
		var newMy = (((newCoords.top - myGC.marker.geometry.y) / mRes) - 25) ;
		
		//32.552083333333336
		//var newBBOX = {minX: tl.lon,};
		
		if (OGIS.map.baseLayer.name.indexOf('base_map') == 0){
			var theBaseUrl = 'http://' + document.location.hostname + OGIS.URLs.rest_basemap_bottom + "?bbox=" + 
				newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +
				"&bboxSR=&layers=&layerDefs=&size=" + fMapW + "," + fMapH + "&imageSR=&format=png&transparent=false&dpi=&f=image";
		} else {
			var theBaseUrl = BizMap.Layers['orthos'].grid[0][0].imgDiv.src;
				theBaseUrl = theBaseUrl.substring(0,theBaseUrl.toLowerCase().indexOf("bbox="));
				theBaseUrl = theBaseUrl + "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH;
		}
		
		var theBaseUrl_top = 'http://' + document.location.hostname + OGIS.URLs.rest_basemap_top + "?bbox=" + 
		newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +
		"&bboxSR=&layers=&layerDefs=&size=" + fMapW + "," + fMapH + "&imageSR=&format=png8&transparent=true&dpi=&f=image";
		// var newLocX = (cmSize['w'] * (theMarkerPxLoc.x / cmSize['w'])) - 10.5;
        // var newLocY = (cmSize['h'] - (cmSize['h'] * ((theMarkerPxLoc.y / cmSize['h'])))) + 25;
		
		
		// var theBaseUrl = OGIS.URLs.rest_basemap + "?bbox=" + 
			// OGIS.map.getExtent().toBBOX() +
			// "&bboxSR=&layers=&layerDefs=&size=" + cmSize['w'] + "," + cmSize['h'] + "&imageSR=&format=png&transparent=false&dpi=&f=image";
		
		
		//html += '<div style="background-color:red;text-align:center;width:100%;height:625px;">x<br />x<br />x<br />x<br />x<br />x</div><br />';
		mapHTML += '<div style="width:' + fMapW + ';height:' + fMapH + ';background-color:lavender;border: 1px solid black;overflow:hidden;position:absolute;top:' + dFromTop + 'px;left:' + dFromLeft + 'px;">';
		mapHTML += 	'<img border="0" src="' + theBaseUrl + '" style="z-index:1;position:absolute;top:0px;left:0px;">';
		//html += 	'<img border="0" src="' + theBaseUrl + '" style="z-index:1;position:absolute;top:' + dFromTop + 'px;left:' + dFromLeft + 'px;">';
		if (BizMap.WMSlayers_poly != ""){
           var imsUrl = BizMap.Layers['wms_poly'].grid[0][0].imgDiv.src;
           imsUrl = imsUrl.substring(0,imsUrl.toLowerCase().indexOf("bbox="));
           imsUrl = imsUrl + "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH;
			mapHTML += '<img src="' + unescape(imsUrl) + '" style="z-index:5;position:absolute;top:0px;left:0px;"/>';
		}
		mapHTML += '<img src="' + unescape(theBaseUrl_top) + '" style="z-index:9;position:absolute;top:0px;left:0px;"/>';
		if (BizMap.WMSlayers_other != ""){
           var imsUrl = BizMap.Layers['wms_other'].grid[0][0].imgDiv.src;
           imsUrl = imsUrl.substring(0,imsUrl.toLowerCase().indexOf("bbox="));
           imsUrl = imsUrl + "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH;
			mapHTML += '<img src="' + unescape(imsUrl) + '" style="z-index:10;position:absolute;top:0px;left:0px;"/>';
		}		
		mapHTML += '<img src="' + OpenLayers.ImgPath + 'marker.png" style="z-index:15;position:absolute;top:' + newMy + 'px;left:' + newMx + 'px;"/></div>';		

	if (Ext.getCmp('chkMap').checked == true){
		html += mapHTML;
	}
	if (Ext.getCmp('chkHMFA').checked == true){
		var newLeft = fMapW+dFromLeft+15;
		html += '<div style="position:absolute;left:' + newLeft +'px;top:' + dFromTop + 'px;">' + $('hmfa_sl_table').innerHTML + '</div>';//id="hmfa_sl_table_rpt"
	}
	html += '<div style="position:absolute;top:' + (fMapH+65) + 'px;left:' + dFromLeft + 'px;right:5px;">'; //width:' + (fMapW+2) + 'px;
	if (Ext.getCmp('chkHMFA').checked == true){
		html += $('hmfa_sl_msgs').innerHTML;//.replace('hmfa_table', 'hmfa_table_rpt');
	}
	if (Ext.getCmp('chkCensus').checked == true) html += '<br /><br />' + $('hmfa_census_rpt').innerHTML;
	html += '</div>';
	//html += $('hmfa_disclaimer').innerHTML;
	//html += '</table></tr></td>';
	html += "</body></html>";
	
	//html = html.replace('id=census_btn', 'id=census_btn style="display:none;"');
	//html = html.replace('id="census_btn"', 'id="census_btn" style="display:none;"');

	frog.document.open();
	frog.document.write(html);
	frog.document.close();
}


//
//------------------------------------------------------------------------------
//   OTHER FUNCTIONS SPECIFIC TO BIZMAP APPLICATION
//------------------------------------------------------------------------------
/**
 * Function: showDiv
 * Shows a div
 *
 * Parameters:
 * divId - {String}
 *
 * Returns:
 *
*/
BizMap.showDiv = function(c) {
    if (document.getElementById && document.getElementById(c)!= null){
       node = document.getElementById(c).style.display='';
       return;
    }
    else if (document.layers && document.layers[c]!= null){
        document.layers[c].display = '';
        return;
    }
}

/**
 * Function: hideDiv
 * Hides a div
 *
 * Parameters:
 * divId - {String}
 *
 * Returns:
 *
*/
BizMap.hideDiv = function(c) {
    if (document.getElementById && document.getElementById(c)!= null){
       node = document.getElementById(c).style.display='none';
       return;
    }
    else if (document.layers && document.layers[c]!= null){
         document.layers[c].display = 'none';
         return;
    }
}

/**
 * Function: isLocationFound
 * This function is associated to the Reset button in "Find a Location" screen.
 *
 * Parameters: None
 *
 * Returns: {boolean} <true/false>
 *
*/
BizMap.isLocationFound = function(){
    //OGIS.msgAlert('','function : isLocationfound');
    if (BizMap.locX != null && BizMap.locX != "" && BizMap.locY != null && BizMap.locY != "" && BizMap.locatedAddress != null && BizMap.locatedAddress != ""){
       return true;
    }
    return false;
}

/**
 * Function: resetFindLocForm
 * This function is associated to the Reset button in "Find a Location" screen.
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.resetFindLocForm = function(){

    //Resetting the address input form
    Ext.getCmp('addSearchForm').getForm().findField('street').setValue("");
    Ext.getCmp('addSearchForm').getForm().findField('crossstreet').setValue("");
    Ext.getCmp('addSearchForm').getForm().findField('city').setValue("");
    Ext.getCmp('addSearchForm').getForm().findField('zip').setValue("");
    //Ext.getCmp('addSearchForm').getForm().findField('locStIfAddrNotFound').setValue(true);
    Ext.getCmp('addSearchForm').getForm().findField('processRec').setValue("");

    //Resetting the location info panel with the Help document
    BizMap.resetLocInfoPanel();
    Ext.getCmp('locationinfo-panel').layout.setActiveItem(1);

    //Resetting the location parameters
    BizMap.locX = "";
    BizMap.locY = "";
    BizMap.locatedAddress = "";

    //Resetting the star marker
    if (myGC != null){
       if (myGC.marker != null) myGC.marker = null;
       if (myGC.markerLayer != null) myGC.markerLayer.destroyFeatures();
    }
    OGIS.map.setCenter(new OpenLayers.LonLat(426235, 476945), 2);
}

/**
 * Function: resetLocInfoPanel
 * Called from geocoder_callback_support.js when a location is found (either through
 * geocoding a location using address parameters OR by clicking on the map) and before
 * loading the layer information into locInfo panels
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.resetLocInfoPanel = function(){
   
    if (BizMap.blnLayersInfoLoaded){
       BizMap.blnLayersInfoLoaded = false;
       for (var y = 0; y < BizMap.LoadLyrSpanIds.length; y++){
           var div1 = BizMap.LoadLyrSpanIds[y];
           var div2 = BizMap.LoadLyrSpanIds[y] + "sub";
	       document.getElementById(div1).innerHTML = "<span style='vertical-align:top;padding-top:2pt;'></span><img src='/oit/gis/OIT_BusinessMap/images/ajax-loader4.gif' border='0' />";
	       document.getElementById(div2).innerHTML = "";

	   }
	}
}

/**
 * Function: activateResultsTab
 * Called from geocoder_callback_support.js to switch tabs from Find a Location to
 * Results tab.
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.activateResultsTab = function(){
    var FindLocComponent = Ext.getCmp('find-a-location-panel');
    var searchWindowTab = Ext.getCmp('addSearchForm');
    var resultsWindowTab = Ext.getCmp('resultsDisp');
    FindLocComponent.setActiveTab(resultsWindowTab);
}

/**
 * Function: checkLyrScales
 * Checks the Map Scale against the maxscale of Layers and enables/disables the layers in Table of Contents
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.checkLyrScales = function(){

    for (lyr in BizMap.Lyrs_Scales){

        var eachLyr = Ext.getCmp(lyr);
        //var eachLyrZoomInImgId = lyr + "_ZinImg";

        if ((BizMap.Lyrs_Scales[lyr] == "") || parseInt(BizMap.Lyrs_Scales[lyr]) > parseInt(BizMap.theMapScale)){
           eachLyr.enable();
           //BizMap.hideDiv(eachLyrZoomInImgId);
        }
        else {
             eachLyr.disable();
             //BizMap.showDiv(eachLyrZoomInImgId);
        }

    }
}

/**
 * Function: onCategoryChange
 * On Category change in Table of Categories: a) Swaps the Legend and b)refreshes the map
 *
 * Parameters:
 * Panel - {Object}
 *
 * Returns:
 *
*/
BizMap.onCategoryChange = function(thisPanel){
    //Capturing the id of active category
    BizMap.activeCategoryId = thisPanel.id;

    //Swapping the legend image in Legend-Panel to match active category
    BizMap.swapLegendImage(thisPanel);

    //Show Location Info of active category in locationinfo-panel
    //BizMap.showActiveCategoryLocationInfo();

    //Refresh the map
    BizMap.refreshMap();
}

/**
 * Function: swapLegendImage
 * Swaps the Legend in accordance with the active category in Table of Categories
 *
 * Parameters:
 * Panel - {Object}
 *
 * Returns:
 *
*/
BizMap.swapLegendImage = function (thisPanel){
    //try to use eval
    if (BizMap.activeCategoryId != ""){
        if (document.images['legendImage'].src != '/oit/gis/OIT_BusinessMap/images/mapLegend_' + BizMap.activeCategoryId + '.png'){
	        document.images['legendImage'].src = '/oit/gis/OIT_BusinessMap/images/mapLegend_' + BizMap.activeCategoryId + '.png';
	    }
	}
    else {
         document.images['legendImage'].src = '/oit/gis/OIT_BusinessMap/images/pixel.gif';
    }
}

/**
 * Function: loadLocationInfo
 * Called from geocoder_callback_support.js when a location is found. Loads the layer info
 * in Location Info screen and shows the active category's location info
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.loadLocationInfo = function(){
	BizMap.resetLocInfoPanel();
    //console.warn(myGC.marker);
    try {
        BizMap.locX = myGC.marker.geometry.x;
        BizMap.locY = myGC.marker.geometry.y;
        BizMap.locatedAddress = myGC.marker.attributes.locationAddress;
    }
    catch (err){}
	
	var xml = OGIS.makeGMLgeometry({conversionType: "PointToBBOX", geom: {lon: BizMap.locX, lat: BizMap.locY}, pointBuffer: 1});
	OGIS.makePostFilter("Intersect", {geoXML: xml});
    
	//OGIS.msgAlert('','locX ' + BizMap.locX);
    //OGIS.msgAlert('','locY ' + BizMap.locY);
    //OGIS.msgAlert('','locatedAddress ' + BizMap.locatedAddress);
    if (BizMap.isLocationFound()){
        BizMap.showActiveCategoryLocationInfo();
        BizMap.loadLayersInfo();
        //HMFA Code//BizMap.loadHMFAInfo();
    }
    else {
         BizMap.makeHelpActive();
    }
}

/**
 * Function: makeHelpActive
 * Called when page is initially loaded and whenever location was not found
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.makeHelpActive = function(){
    //OGIS.msgAlert('','function : makeHelpActive');
    Ext.getCmp('locationinfo-panel').layout.setActiveItem(1);
}

/**
 * Function: refreshMap
 * Refreshes the map with the selected layers when
 * 1) any map tool is used
 * 2) any layer is selected under any category and user requests for a map refresh
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.refreshMap = function(){
    //OGIS.msgAlert('','function : refreshMap');
    var checkedLyrsOfActiveCategory = BizMap.getListOfLayers(BizMap.activeCategoryId);
    //if (checkedLyrsOfActiveCategory != null && checkedLyrsOfActiveCategory != "" && BizMap.IMSlayers != checkedLyrsOfActiveCategory){
    if (BizMap.WMSlayers_poly != checkedLyrsOfActiveCategory.poly){
       BizMap.WMSlayers_poly = checkedLyrsOfActiveCategory.poly;
       BizMap.Layers['wms_poly'].mergeNewParams({layers : checkedLyrsOfActiveCategory.poly});
    }
	if (BizMap.WMSlayers_other != checkedLyrsOfActiveCategory.other){
       BizMap.WMSlayers_other = checkedLyrsOfActiveCategory.other;
       BizMap.Layers['wms_other'].mergeNewParams({layers : checkedLyrsOfActiveCategory.other});
    }
    BizMap.theMapScale = OGIS.map.getScale();
    BizMap.checkLyrScales();
    return;
}

/**
 * Function: signalMapRefresh
 * Alerts user to refresh the map whenever any layer is selected under any category
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.signalMapRefresh = function(thisObj){
    //OGIS.msgAlert('','function : raiseMapRefreshFlag');
    if (BizMap.blnInitialPageLoadDone){
       var xbx = Ext.getCmp('category-panel').layout.activeItem.tools.refresh;
       xbx.frame("ff0000", 1, { duration: .75 });
    }
}

/**
 * Function: getListOfLayers
 * Called from refreshMap to get a comma delimited list of selected layers under active category
 *
 * Parameters: None
 *
 * Returns: {String}
 *
*/
BizMap.getListOfLayers = function(catId){
    var checkedLyrs = {poly: '', other: ''};
    var fldSets = Ext.getCmp(catId).items.items;

    for (a = 0; a < fldSets.length; a++){
        //if (fldSets[a].checkbox.dom.checked == false){
        //   continue;
        //}
        var chkBoxes = fldSets[a].items.items;
        for (c = 0; c < chkBoxes.length; c++){
            if (chkBoxes[c].checked == true){
               if (OGIS.wms_layers[chkBoxes[c].inputValue] == 0){
				checkedLyrs.poly += ((checkedLyrs.poly == "") ? (chkBoxes[c].inputValue) : ("," + chkBoxes[c].inputValue));
			   } else {
			   checkedLyrs.other += ((checkedLyrs.other == "") ? (chkBoxes[c].inputValue) : ("," + chkBoxes[c].inputValue));
			   }
               // if (checkedLyrs == ""){
                  // checkedLyrs = chkBoxes[c].inputValue;
               // }
               // else {
                    // checkedLyrs = chkBoxes[c].inputValue + "," + checkedLyrs;
               // }
            }
        }
    }
    return checkedLyrs;
}

/**
 * Function: loadLayersInfo
 * Called from loadLocationInfo to load the layers info (ajax call to load each layer info)
 * into locationinfo-panel
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.loadLayersInfo = function(){
    
    if (!BizMap.isLocationFound() || BizMap.blnLayersInfoLoaded){
       return;
    }
    Ext.getCmp('locationinfo-panel').layout.setActiveItem(0);
	//clear out Report Layer Contents so values don't carry from one PDF to next
	BizMap.RptLyrContents = " ";
    for (c = 0; c < catSet.length; c++){
         var catIdn = catSet[c].category_idn;
         if (catIdn == "hmfa"){
            //DEJUNG -- will add hmfa layer loading code here
            continue;
         }
         var subcatSet = catSet[c].subcategories;
         for (s = 0; s < subcatSet.length; s++){
	          var subcatIdn = subcatSet[s].sub_category_idn;
	          var lyrSet = subcatSet[s].layers;
	            for (a = 0; a < lyrSet.length; a++){
             	    var lyrIdn = lyrSet[a].layerid;
             	    if (lyrSet[a].query_fields == "none"){
             	       continue;
             	    }
		            if (lyrIdn.indexOf("02orthos") == -1){
		                var lyrQryFlds = lyrSet[a].query_fields;
		                var lyrFldAlias = lyrSet[a].alias;
		                var lyrProxySrch = lyrSet[a].proximity_search;
		                var lyrNotes = lyrSet[a].notes;
		                var lyrDisclaimer = lyrSet[a].disclaimer;
		                var lyrUrl = "LoadEachLayer.jsp?lyrId=" + escape(lyrIdn) + "&lyrQryFlds=" + escape(lyrQryFlds) + "&lyrFldAlias=" + escape(lyrFldAlias) + "&lyrProxySrch=" + escape(lyrProxySrch) + "&lyrNotes=" + escape(lyrNotes) + "&lyrDisclaimer=" + escape(lyrDisclaimer) + "&locX=" + BizMap.locX + "&locY=" + BizMap.locY;
                        var lyrContentDivId = catIdn + "_" + subcatIdn + "_" + lyrIdn + "_span";
                        BizMap.makeAjaxCall_LoadEachLayer(lyrUrl,lyrContentDivId);
                    }

		        }

	     }
	     if (c == (catSet.length - 1)){
	        BizMap.blnLayersInfoLoaded = true;
	     }

    }
}

/**
 * Function: showActiveCategoryLocationInfo
 * Makes the appropriate category active in locationinfo-panel(based on active category in table of categories)
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.showActiveCategoryLocationInfo = function(){
    //OGIS.msgAlert('','function : showActiveCategoryLocationInfo');
    if (BizMap.isLocationFound()){
       for (c = 0; c < catSet.length; c++){
           var catIdn = catSet[c].category_idn;
           if (catIdn == "hmfa"){
              //DEJUNG -- will add the hmfa header here
              continue;
           }
           $(catIdn + '_locAdr').innerHTML = "at " + BizMap.locatedAddress; //DEJUNG - will get the locatedAddress using this variable
       }
       var locInfoCmp = Ext.getCmp('loc-info-items-panel');
       locInfoCmp.setActiveTab('info_' + BizMap.activeCategoryId);
    }
}

/**
 * Function: makeAjaxCall_LoadEachLayer
 * Called from loadLayersInfo to make an ajax call to load each layer information
 *
 * Parameters: None
 *
 * Returns: {String}
 *
*/
BizMap.makeAjaxCall_LoadEachLayer = function(passedUrl, destinationDivId){
     
    document.getElementById(destinationDivId+'sub').innerHTML = '';
	document.getElementById(destinationDivId).innerHTML = '&nbsp;';
	
	OpenLayers.Request.GET({
        	url:passedUrl,
        	success:function(response){
                    BizMap.processLoadEachLyrResponse(response.responseText,destinationDivId);
				
            },
            failure:function(){
                    OGIS.msgAlert('','Unable to process the Request.\nEither your browser does not support AJAX\n Or internal error!');
                    return false;
            }
			
    });
}

BizMap.processLoadEachLyrResponse = function(theResponse,destinationDivId){
           
           theResponse = theResponse.trim();
           BizMap.RptLyrContents += "LYR_DELIMITER";
           if (theResponse.indexOf("<table") != -1){
               document.getElementById(destinationDivId).innerHTML = "";
               destinationDivId = destinationDivId + "sub";
           }
           if (theResponse.indexOf("+++") != -1){
              var arrayOfTheResponse = theResponse.split("+++");
              document.getElementById(destinationDivId).innerHTML = arrayOfTheResponse[0];
              BizMap.RptLyrContents += arrayOfTheResponse[1];
           }
           else {
                document.getElementById(destinationDivId).innerHTML = theResponse;
           }
		   
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

BizMap.clearLayersSelection = function(thisObj){
    OGIS.msgAlert('','function : clearLayersSelection 1255');
}

//
//------------------------------------------------------------------------------
//   START - FUNCTIONS RELATED TO REPORT GENERATION
//------------------------------------------------------------------------------
/**
 * Function: genRpt
 * This function collects the information(that needs to be listed in the report),
 * triggers the report generation by submitting a form.
 *
 * Parameters: None
 *
 * Returns: None
 *
*/
BizMap.genRpt = function(){
    
        document.rptForm.infoXML.value = BizMap.RptXml;
	
        document.rptForm.infoData.value = BizMap.RptLyrContents;

        //********************************************************
        //the following form values should be obtained dynamically
        //********************************************************

        //Getting a list of the categories requested by user to be shown on the Report
        document.rptForm.selectedCats.value = BizMap.getListOfSelectedCatsForRpt();
		 

        //Getting a list of the maps(associated to categories) requested by user to be shown on the Report
        document.rptForm.selectedCatImages.value = BizMap.getListOfSelectedCatImagesForRpt();
		 

        //Getting the complete list of the layers under all the categories
        document.rptForm.lyrList.value = BizMap.getListOfLayersForRpt();
		 
		
		if (BizMap.getListOfSelectedCatsForRpt() == "" && BizMap.getListOfSelectedCatImagesForRpt() == ""){
		   
			return;
		
		}
        if (BizMap.theMapScale == ""){
           BizMap.theMapScale = OGIS.map.getScale();
        }
        document.rptForm.mapScale.value = BizMap.theMapScale;

	var fMapH = 400; //in pixels -- intMapPositionX property in pdfRpt (Map X position from left side of the PDF page - set as 90 in PDF generator)
	var fMapW = 800; //in pixels -- intMapPositionY property in pdfRpt (Map Y position from left bottom corner of the PDF page - calculated based on the height defined here)

	var cmSize = OGIS.map.getCurrentSize();
	var dMx = fMapW - cmSize.w;
	var dMy = fMapH - cmSize.h;
		
	var oldCoords = OGIS.map.getExtent();
	var mRes = OGIS.map.getResolution();
	var newCoords = {
		left: parseFloat(oldCoords.left) - ((dMx/2) * mRes),
		bottom: parseFloat(oldCoords.bottom) - ((dMy/2) * mRes),
		right: parseFloat(oldCoords.right) + ((dMx/2) * mRes),
		top: parseFloat(oldCoords.top) + ((dMy/2) * mRes)
	};
		
	var newMx = (((myGC.marker.geometry.x - newCoords.left) / mRes) - 10.5);
	var newMy = fMapH - ((newCoords.top - myGC.marker.geometry.y) / mRes);

        document.rptForm.curMinX.value = newCoords.left;
        document.rptForm.curMinY.value = newCoords.bottom;
        document.rptForm.curMaxX.value = newCoords.right;
        document.rptForm.curMaxY.value = newCoords.top;

        document.rptForm.locAddr.value = BizMap.locatedAddress;
        document.rptForm.locX.value = BizMap.locX;
        document.rptForm.locY.value = BizMap.locY;

        //Adding the Base Map Url to mapsUrl
		//if multiple basemap urls, then separated by "####"
		//if multiple categories, then separated by "##@##"
		var theBaseUrl = '';
		if (OGIS.map.baseLayer.name.indexOf('base_map') == 0){
			theBaseUrl = 'http://' + document.location.hostname + OGIS.URLs.rest_basemap_bottom + "?bbox=" + 
			newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top + 
			"&bboxSR=&layers=&layerDefs=&size=" + fMapW + "," + fMapH + "&imageSR=&format=png&transparent=false&dpi=&f=image";
		} else {
            theBaseUrl = BizMap.Layers['orthos'].grid[0][0].imgDiv.src;
            theBaseUrl = theBaseUrl.substring(0,theBaseUrl.toLowerCase().indexOf("bbox="));
			theBaseUrl = theBaseUrl + "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH;
        }
		
		theBaseUrl += '####' + 'http://' + document.location.hostname + OGIS.URLs.rest_basemap_top + "?bbox=" + 
		newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +
		"&bboxSR=&layers=&layerDefs=&size=" + fMapW + "," + fMapH + "&imageSR=&format=png8&transparent=true&dpi=&f=image";	
		
	
		var workingCats = document.rptForm.selectedCatImages.value.split(',');
		if (workingCats[0] == "") workingCats = [];
		var mapLayerUrls = '';
		
		for (var yyy = 0; yyy < workingCats.length; yyy++){			
			// if (BizMap.WMSlayers_poly != ""){
				// var imsUrl = BizMap.Layers['wms_poly'].grid[0][0].imgDiv.src;
				// imsUrl = imsUrl.substring(0,imsUrl.toLowerCase().indexOf("bbox="));
				// imsUrl = imsUrl + "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH;
			// } else {
				// imsUrl = 'none';
			// }
			
			if (BizMap.getListOfLayersForRptWMS(workingCats[yyy]) != '') {
				
				var checkedLyrs = {poly: '', other: ''};
				var fldSets = Ext.getCmp(workingCats[yyy]).items.items;

				for (a = 0; a < fldSets.length; a++){
					//if (fldSets[a].checkbox.dom.checked == false){
					//   continue;
					//}
					var chkBoxes = fldSets[a].items.items;
					for (c = 0; c < chkBoxes.length; c++){
						if (chkBoxes[c].checked == true){
						   if (OGIS.wms_layers[chkBoxes[c].inputValue] == 0){
							checkedLyrs.poly += ((checkedLyrs.poly == "") ? (chkBoxes[c].inputValue) : 
							("," + chkBoxes[c].inputValue));
						   } else {
						   checkedLyrs.other += ((checkedLyrs.other == "") ? (chkBoxes[c].inputValue) : 
						   ("," + chkBoxes[c].inputValue));
						   }
						}
					}
				}
				
				if (checkedLyrs.poly != ''){
					var wms_p = BizMap.Layers['wms_poly'].grid[0][0].imgDiv.src;
					wms_p = wms_p.substring(0,wms_p.toLowerCase().indexOf("bbox=")).replace(/LAYERS=[^&]*&/, '');
					wms_p += "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH + "&";
					wms_p += "LAYERS=" + checkedLyrs.poly;
				} else {
					wms_p = 'none';
				}

				if (checkedLyrs.other != ''){
					var wms_o = BizMap.Layers['wms_other'].grid[0][0].imgDiv.src;
					wms_o = wms_o.substring(0,wms_o.toLowerCase().indexOf("bbox=")).replace(/LAYERS=[^&]*&/, '');
					wms_o += "BBOX=" + newCoords.left + "," + newCoords.bottom + "," + newCoords.right + "," + newCoords.top +"&WIDTH=" + fMapW + "&HEIGHT=" + fMapH + "&";
					wms_o += "LAYERS=" + checkedLyrs.other;
				} else {
					wms_o = 'none';
				}
				var wms = wms_p + "####" + wms_o;
			} else {
				var wms = 'none####none';
			}
			//checkedLyrs += ((checkedLyrs == "") ? (LyrId_CatId) : ("@" + LyrId_CatId));
			if (yyy < workingCats.length-1){
				mapLayerUrls = mapLayerUrls + wms + '##@##';
			} else {
				mapLayerUrls = mapLayerUrls + wms;
			}
		}
		
        //Adding the Layers Url to mapsUrl
		 
		document.rptForm.baseMapUrls.value = theBaseUrl;
		document.rptForm.mapLayerUrls.value = mapLayerUrls;
        document.rptForm.pdfMapWidth.value = fMapW;
        document.rptForm.pdfMapHeight.value = fMapH;

        /*
         * ===============================================================
         * MarkerX, Y calculations to make them compatible with PDF report
         * ===============================================================
         * The Delimiter ##@## for multiple urls
         * The original map in OIT_BusinessMap is stretched to 800X600 pixels in PDF report
         * Hence the Marker X, Ys to be calculated in proportionate to the stretched map in PDF report ==> theMarkerPxLoc.x*(PDFMapWidth/OGIS.map.getSize().w) AND theMarkerPxLoc.y*(PDFMapHeight/OGIS.map.getSize().h)

         * Absolute positioning in PDF pages start from lower left end of the page
         * The Marker positions that we obtain from MarkerPxLoc are from top left end of OGIS.map
         * So the Marker Y position is obtained by deducting the MarkerPxLoc.Y from map height ==> thePdfMapHeight - parseInt(theMarkerPxLoc.y * parseFloat(thePdfMapHeight/OGIS.map.getSize().h))
         */

        document.rptForm.markerLocX.value = parseInt(newMx);
        document.rptForm.markerLocY.value = parseInt(newMy);

        var theMarkerUrl = 'http://' + document.location.hostname + OpenLayers.ImgPath + 'marker.png';

        document.rptForm.markerUrl.value = theMarkerUrl;
        document.rptForm.submit();
}

/**
 * Function: getListOfSelectedCatsForRpt
 * This function returns the comma delimited list of the categories(that is category ids)
 * to be printed in the Printable Report.
 *
 * Parameters: None
 *
 * Returns: String
 *
*/
BizMap.getListOfSelectedCatsForRpt = function(){
    var checkedCats = "";
    for (c = 0; c < catSet.length; c++){
        var catIdn = catSet[c].category_idn;
        if (catIdn == "hmfa"){
           continue;
        }
         var contentChkBoxStatus = Ext.getCmp('cntRpt').getForm().findField('RptChkBox_'+catIdn).getValue();
         if (contentChkBoxStatus){
            checkedCats = (checkedCats == "") ? catIdn : (checkedCats + "," + catIdn);
         }
    }
    return checkedCats;
}

/**
 * Function: getListOfSelectedCatImagesForRpt
 * This function returns the comma delimited list of the images to be printed in the
 * Printable Report.
 *
 * Parameters: None
 *
 * Returns: String
 *
*/
BizMap.getListOfSelectedCatImagesForRpt = function(){
    var checkedCatImages = "";
    for (c = 0; c < catSet.length; c++){
        var catIdn = catSet[c].category_idn;
        if (catIdn == "hmfa"){
           continue;
        }
         var contentChkBoxStatus = Ext.getCmp('cntRpt').getForm().findField('RptChkBoxImg_'+catIdn).getValue();
         if (contentChkBoxStatus){
            checkedCatImages = (checkedCatImages == "") ? catIdn : (checkedCatImages + "," + catIdn);
         }
    }
    return checkedCatImages;
}

/**
 * Function: getListOfLayersForRpt
 * This function returns the "@" delimited list of the layers to be printed in the
 * Printable Report.
 *
 * Parameters: None
 *
 * Returns: String
 *
*/
BizMap.getListOfLayersForRpt = function(theCAT){
    var checkedLyrs = "";

    for (var d = 0; d < catSet.length; d++){
        var cId = catSet[d].category_idn;
        if (cId == "hmfa"){
           continue;
        }
        var fldSets = Ext.getCmp(cId).items.items;

        for (a = 0; a < fldSets.length; a++){
            var chkBoxes = fldSets[a].items.items;
            for (c = 0; c < chkBoxes.length; c++){
                if (chkBoxes[c].checked == true){
                   var LyrId_CatId = chkBoxes[c].inputValue + "_" + cId;
                   checkedLyrs += ((checkedLyrs == "") ? (LyrId_CatId) : ("@" + LyrId_CatId));
                }
            }
        }
    }

    //To show the counties,municipalities,streets,orthos in the report from OIT_BizMap (as of now)
    var orthoLyrs = "02orthosM1_ev@02orthosM2_ev@02orthosM3_ev@02orthosM4_ev@02orthosM5_ev@02orthosM6_ev@02orthosM1_ec@02orthosM2_ec@02orthosM3_ec@02orthosM4_ec@02orthosM5_ec@02orthosM6_ec@02orthosM1_dg@02orthosM2_dg@02orthosM3_dg@02orthosM4_dg@02orthosM5_dg@02orthosM6_dg";
    var defaultLyrs = "cnty_ev@muni_ev@street_ev@cnty_ec@muni_ec@street_ec@cnty_dg@muni_dg@street_dg";
    checkedLyrs += (checkedLyrs == "") ? defaultLyrs : ("@" + defaultLyrs);
    if (blnSwitchedToOrthos && parseInt(BizMap.theMapScale) <= 30000){
       checkedLyrs += (checkedLyrs == "") ? orthoLyrs : ("@" + orthoLyrs);
    }

    return checkedLyrs;
}

BizMap.getListOfLayersForRptWMS = function(theCAT){
    var checkedLyrs = "";
        var cId = theCAT;
        var fldSets = Ext.getCmp(cId).items.items;

        for (a = 0; a < fldSets.length; a++){
            var chkBoxes = fldSets[a].items.items;
            for (c = 0; c < chkBoxes.length; c++){
                if (chkBoxes[c].checked == true){
                   var LyrId_CatId = chkBoxes[c].inputValue;
                   checkedLyrs += ((checkedLyrs == "") ? (LyrId_CatId) : ("@" + LyrId_CatId));
                }
            }
        }

    return checkedLyrs;
}
//following is the url to the example where they showed how to add title to a collapsed panel bar
//http://tdg-i.com/30/how-to-get-titles-in-collapsed-panels-for-border-layout

//http://vega.oit.state.nj.us/NJ_OGC/wms/OIT_BizMap?TRANSPARENT=true&LAYERS=midatl1000%2Cmidatl500&FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A102711&BBOX=400000,0,900000,400000&WIDTH=512&HEIGHT=512
//http://oit-jtfrh71/ol/20080714_7505_Repository/examples/scales_work/simple.js

