
var slDrawing, slDrawing2;

var myCurrentShape = null;
var myPoints = new Array();

var i = 0;
var w = 0;
var veMap;

var tableName = "";
var shapedesc = "";
var shapetitle = "";
var shape = null;

var xpoint, ypoint;
var globalLayerType=2;

var tpopulation=0;

var globalAdminID;
var globalRecords=0;
var currentRecord=0;
var panToFirstMap = true;

var colorArray;

//Timeouts
var timeout2, drawTimeout, loadingTimeout;

var globalValue="";
var selectedPoints="";
var map, selectedFeature, clickselectcontrol, drawpolygon, drawline, drawpoint, measureControls, vector, distance, popup, DataSourceID;
var bufferPoint, bufferLine, bufferPolygon;
var savedShapeID;
var action = "1";

//Layers
var gstrt, gsat,ghyb;
var veroad, veaer, vehyb;

OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';

// avoid pink tiles
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.Util.onImageLoadErrorColor = "transparent";

function Init() {

    try {
        slDrawing = new VEShapeLayer();
        slDrawing2 = new VEShapeLayer();
    }
    catch (ex) {
        //is there internet kweli
    }


    /***********************************CREATE ELEMENTS***************************************/
//    var divThematicLayer = createDiv('divThematicLayer', 'thematic-layer', true);
//    divThematicLayer.innerHTML =
//    "Country:" +
//    "<div id='divAdmin1List'></div><br/>" +
//    "Type:" +
//    "<div id='divLayerTypes'></div><br/>" +
//    "Map:" +
//    "<div id='divLayers'></div><br/>" +
//    "<input type='button' value='Display' onclick ='DisplayMap();' />";

    var divLayerSwitcher = createDiv('layerswitcher', 'layer-switcher', true);
    divLayerSwitcher.innerHTML = "<div style='float:right; height: auto;'><img style='display: none' src='theme/default/img/close.gif' onclick ='SwitchLayers(false);' alt=''/><br/><br/></div>";

    var divLoading = createDiv('divLoading', 'patience-screen', true);
    divLoading.innerHTML = "<img src='Images/loadercircle2.gif' alt='Loading' /><div id='divMessage'></div>";
    divLoading.style.left = ((window.screen.width * 1) / 2 - (divLoading.style.width * 1 / 2)) - 75 + "px";
    divLoading.style.top = ((window.screen.height * 1) / 2) - 200 + "px";
    divLoading.style.width = "150px"; //Set this after setting left,top positions

    createDiv('divToolTip', 'tool-tip', true);

    /*****************************************************************************************/
    try {
        //--------------------------------------------------------------------------
        // Resize content to fill viewport
        //--------------------------------------------------------------------------

        var viewport_width;
        var viewport_height;
        var container_height;
        var container_height_string;
        var container_height_ie;
        var container_height_ie_string;
        var container_width;
        var container_width_string;
        var container_width_ie;
        var container_width_ie_string;

        // FF, Safari, Opera: window.innerWidth.
        // IE Quirksmode (attempting standards compliance): document.documentElement.clientWidth.
        // IE6: document.getElementsByTagName('body')[0].clientHeight;
        if (typeof window.innerWidth != 'undefined') {
            viewport_width = window.innerWidth;
            viewport_height = window.innerHeight;
        } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
            viewport_width = document.documentElement.clientWidth;
            viewport_height = document.documentElement.clientHeight;
        } else {
            viewport_width = document.getElementsByTagName('body')[0].clientWidth;
            viewport_height = document.getElementsByTagName('body')[0].clientHeight;
        }

        if (viewport_height <= 550) {
            // Height
            container_height = 550;
            container_height_ie = 534; // (550 - 16)
            // Width
            container_width = viewport_width;
            container_width_ie = viewport_width - 16;
        } else {
            // Height
            //container_height = viewport_height - 141;
            //container_height_ie = viewport_height - 125; // (141 - 16)
            // For some reason I need to subtract an additional 20px
            container_height = viewport_height - 147;
            container_height_ie = viewport_height - 157; // (141 - 16)
            // Width
            container_width = viewport_width - 2;
            container_width_ie = viewport_width - 2;
        }

        container_height_string = container_height + "px";
        container_height_ie_string = container_height_ie + "px";
        container_width_string = container_width + "px";
        container_width_ie_string = container_width_ie + "px";

        // Good Browsers
        if (typeof window.innerWidth != 'undefined') {
            document.getElementById("content").style.height = container_height_string;
            document.getElementById("map").style.height = container_height_string;
            document.getElementById("map").style.width = container_width_string;
            // IE Family
        } else {
            document.getElementById("content").style.height = container_height_ie_string;
            document.getElementById("map").style.height = container_height_ie_string;
            document.getElementById("map").style.width = container_width_ie_string;
        }
        //--------------------------------------------------------------------------
        //
        //--------------------------------------------------------------------------

        var panZoomBar = new OpenLayers.Control.PanZoomBar();
        panZoomBar.zoomWorldIcon = true;

        var options = {
            projection: new OpenLayers.Projection("EPSG:900913"),
            displayProjection: new OpenLayers.Projection("EPSG:4326"),
            units: "km",
            controls: [new OpenLayers.Control.Navigation(),
	        panZoomBar,
	        new OpenLayers.Control.KeyboardDefaults()],
            numZoomLevels: 15,
            maxResolution: 156543.0339,
            maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34),
				eventListeners: {
				'changebaselayer': function () {
					document.getElementById('layerswitcher').style.display = 'none';
					document.getElementById('layerswitcher').style.visibility = 'hidden';
				}
			}
        };

        map = new OpenLayers.Map("map", options);

        // create Google Mercator layers
        gstrt = new OpenLayers.Layer.Google(
			"Google Streets", { 'sphericalMercator': true });

        gsat = new OpenLayers.Layer.Google(
    		"Google Satellite", { type: G_SATELLITE_MAP, 'sphericalMercator': true, numZoomLevels: 22 });

        ghyb = new OpenLayers.Layer.Google(
			"Google Hybrid", { type: G_HYBRID_MAP, 'sphericalMercator': true });


        //    var zoomAttributes = {numZoomLevels: 19,minZoomLevel: 5,transitionEffect: 'resize'}
        //     ghyb = new OpenLayers.Layer.Google(
        //                "Google Hybrid",
        //                OpenLayers.Util.extend(zoomAttributes, { type: G_HYBRID_MAP }));

        // create Virtual Earth layers
        veroad = new OpenLayers.Layer.VirtualEarth(
			"Virtual Earth Roads", { 'type': VEMapStyle.Road, 'sphericalMercator': true });

        veaer = new OpenLayers.Layer.VirtualEarth(
			"Virtual Earth Aerial", { 'type': VEMapStyle.Aerial, 'sphericalMercator': true });

        vehyb = new OpenLayers.Layer.VirtualEarth(
			"Virtual Earth Hybrid", { 'type': VEMapStyle.Hybrid, 'sphericalMercator': true });

        // // create Yahoo layer
        //        var yahoo = new OpenLayers.Layer.Yahoo(
        //    			"Yahoo Street",
        //    			{ 'sphericalMercator': true }
        //    			);
        //        var yahoosat = new OpenLayers.Layer.Yahoo(
        //    			"Yahoo Satellite",
        //    			{ 'type': YAHOO_MAP_SAT, 'sphericalMercator': true }
        //    			);
        //    			var yahoohyb = new OpenLayers.Layer.Yahoo(
        //    			"Yahoo Hybrid",
        //    			{ 'type': YAHOO_MAP_HYB, 'sphericalMercator': true }
        //    			);

        // create a vector layer for drawing
        vector = new OpenLayers.Layer.Vector("My Areas of Interest", { 'displayInLayerSwitcher': false });

        //map.addLayers([vector, gstrt, gsat, ghyb, veroad, veaer, vehyb]);
        //map.addLayers([vector, gstrt]);
        map.addLayers([vector, gstrt, veroad, veaer, vehyb]);

        // ghyb.setZIndex(map.Z_INDEX_BASE['Popup'] - 1);
        // map.setLayerZIndex(ghyb, 0);
        // ghyb.setZIndex("1099");
        // map.layerContainerDiv.style.zIndex = "1101";

        var report = function(e) { OpenLayers.Console.log(e.type, e.feature.id); };

        var highlightCtrl = new OpenLayers.Control.SelectFeature(vector, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary",
            eventListeners: {
                beforefeaturehighlighted: report,
                featurehighlighted: OnCatchHover,
                featureunhighlighted: OnReleaseHover
            }
        });

        var selectCtrl = new OpenLayers.Control.SelectFeature(vector, { clickout: true });
        drawpolygon = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Polygon);
        drawline = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Path);
        drawpoint = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Point);
        clickselectcontrol = new OpenLayers.Control.SelectFeature(vector, { onSelect: onFeatureClick, onUnselect: onFeatureUnselect });

		var bufferFeature = function (feature) {
		
		    var distance = 1.0;
            var bufferDistance = prompt('Enter distance in KM', '');

            try 
			{
                distance = bufferDistance / 111.12;
				var in_options = { 'internalProjection': map.baseLayer.projection, 'externalProjection': new OpenLayers.Projection("EPSG:4326") };
				var wkt = new OpenLayers.Format.WKT(in_options);
				DDMService.Buffer(wkt.write(feature, false), distance, SuccessCallBack_Buffer, FailCallBack_Buffer);
						
				SwitchOffDrawing();
            }
            catch (err) {
                alert("Distance must be numeric.");
				bufferFeature(feature);
            }
		}

		bufferPoint = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Point, { featureAdded: bufferFeature });
		bufferLine = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Path, { featureAdded: bufferFeature });
		//bufferPolygon = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Polygon, { featureAdded: bufferFeature });
		
        map.addControl(highlightCtrl);
        map.addControl(selectCtrl);
        map.addControl(clickselectcontrol);
        map.addControl(drawpolygon);
        map.addControl(drawline);
        map.addControl(drawpoint);
		
		map.addControl(bufferPoint);
		map.addControl(bufferLine);
		//map.addControl(bufferPolygon);

        highlightCtrl.activate();
        selectCtrl.activate();
        clickselectcontrol.activate();

        // style the sketch fancy
        var sketchSymbolizers = {
            "Point": {
                pointRadius: 3,
                graphicName: "square",
                fillColor: "white",
                fillOpacity: 1,
                strokeWidth: 1,
                strokeOpacity: 1,
                strokeColor: "#333333"
            },
            "Line": {
                strokeWidth: 2,
                strokeOpacity: 1,
                strokeColor: "#666666",
                strokeDashstyle: "dash"
            },
            "Polygon": {
                strokeWidth: 1,
                strokeOpacity: 1,
                strokeColor: "#666666",
                fillColor: "white",
                fillOpacity: 0.3
            }
        };
        var style = new OpenLayers.Style();
        style.addRules([new OpenLayers.Rule({ symbolizer: sketchSymbolizers })]);

        var styleMap = new OpenLayers.StyleMap({ "default": style });

        measureControls = {
            line: new OpenLayers.Control.Measure(
            OpenLayers.Handler.Path, {
                persist: true,
                handlerOptions: {
                    layerOptions: { styleMap: styleMap }
                }
            }
        ),
            polygon: new OpenLayers.Control.Measure(
            OpenLayers.Handler.Polygon, {
                persist: true,
                handlerOptions: {
                    layerOptions: { styleMap: styleMap }
                }
            }
        )
        };

        // map.setCenter(new OpenLayers.LonLat(1.1864386394452, 34.7607421875), 4);
        map.setCenter(new OpenLayers.LonLat(3600000.0, 0.0), 3);

        /********************************LOAD CONTROLS***********************/
        var control;
        for (var key in measureControls) {
            control = measureControls[key];
            control.events.on({
                "measure": handleMeasurements,
                "measurepartial": handleMeasurements
            });
            map.addControl(control);
        }

        map.addControl(new OpenLayers.Control.MousePosition());
        map.addControl(new OpenLayers.Control.Scale()); //1 : 55M
        //map.addControl(new OpenLayers.Control.ScaleLine());
        //map.addControl(new OpenLayers.Control.LayerSwitcher());
        //map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false}));
        map.addControl(new OpenLayers.Control.LayerSwitcher({ 'div': OpenLayers.Util.getElement('layerswitcher'), 'ascending': true }));
        map.addControl(new OpenLayers.Control.OverviewMap());

        //        map.addControl(new OpenLayers.Control.MouseToolbar());

        //        map.addControl(new OpenLayers.Control.Permalink());
        //        map.addControl(new OpenLayers.Control.Permalink('permalink'));
        //        map.addControl(new OpenLayers.Control.KeyboardDefaults());

        //    map.setMapType(G_HYBRID_MAP);    
        //    map.addControl(new GMapTypeControl());
        //    map.addControl(new GLargeMapControl());
        //    map.addControl(new GOverviewMapControl(new GSize(140, 140)));

        //    if (GBrowserIsCompatible()) {
        //        var map = new GMap2(document.getElementById("map_canvas"));
        //        map.setCenter(new GLatLng(53.480998, -2.236748), 15);
        //        map.addControl(new GLargeMapControl());
        //        map.addControl(new GMapTypeControl());
        //        map.enableScrollWheelZoom();
        //        map.enableContinuousZoom();
        //    }
        /****************************************************************************************/

        modCursor(8); //Pan
    }
    catch (ex) {
        //An error has occured
    } 
}

function onFeatureClick(feature) {
    selectedFeature = feature;

    //first, remove the hover div - important or div will always show
    OnReleaseHover(feature);

    var featurePopup = null;

    var in_options = { 'internalProjection': map.baseLayer.projection, 'externalProjection': new OpenLayers.Projection("EPSG:4326") };
    var wkt = new OpenLayers.Format.WKT(in_options);
    var WKTshp = wkt.write(feature, false);

    switch (action) {
        case "delete":
            selectedFeature = OpenLayers.Util.removeItem(vector.features, feature);
            feature.layer = null; // feature has no layer at this point

            if (feature.geometry)
                vector.renderer.eraseFeatures(feature);

            //in the case that this feature is one of the selected features, 
            // remove it from that array as well.
            if (OpenLayers.Util.indexOf(vector.selectedFeatures, feature) != -1)
                OpenLayers.Util.removeItem(vector.selectedFeatures, feature);
            return;
            break;
        case "deleteAll":

            //vector.destroyFeatures(); 
            return;
            break;
        case "BufferShape":
            var distance = 1.0;
            var bufferDistance = prompt('Enter distance in KM', '');

            try {
                distance = bufferDistance / 111.12;
            }
            catch (err) {
                alert("Distance must be numeric.");
                return;
            }
            DDMService.Buffer(WKTshp, distance, SuccessCallBack_Buffer, FailCallBack_Buffer);
            return;
            break;

        default:
            break;
    }

    //Do this after buffer shape
    WKTshp = ShapeFromWKT(WKTshp);
    WKTshp = ShapeToWKT(WKTshp);

    selectedPoints = WKTshp; //set these points in case they need to be saved as scenario event.

    switch (feature.geometry.CLASS_NAME) {
        case "OpenLayers.Geometry.Point":
            if (feature.attributes["MotherID"] != null) {
                var motherFeature = vector.getFeatureById(feature.attributes["MotherID"]);

                if (motherFeature != null) {
                    if (motherFeature.popup != null) {
                        motherFeature.popup.show();
                    }
                }
            }
            return;
            break;
        case "OpenLayers.Geometry.Polygon":
            break;
        default:
            break;
    }

    if (feature.popup != null) {   //Has popup			
        if (feature.popup.visible != true)
            feature.popup.show();
    }
    else {
        var resetLink = "&nbsp;&nbsp;&nbsp;<a onclick=\"ResetFeature('" + feature.id + "');\" href=\"#\">Cancel</a><br/>";
        switch (feature.attributes["FeatureType"]) {
            case "DensityMap":

                ShowPopup(feature, "<div style='font-size:.71em;'><br/><div id='divShapeResults' style='text-align:center; height:auto; width:auto; overflow:visible;'><img height='20' width='20' src='Images/loadercircle2.gif' alt='loading..'/><br/>Generating density map, please wait ...</div>" + resetLink + "<p>Source:  <a href='http://www.ornl.gov/sci/landscan/index.html' target='_blank'>Landscan&trade; </a><br/></p></div>", null);
                DDMService.CreateShapeAndClipDensity(feature.id, WKTshp, 0, map.zoom + 2, feature.populationDensity, feature.mostPopulated, parseFloat(feature.leastPopulated), SuccessCallback_DensityMap, FailCallback_DensityMap);
                break;
            case "DifferenceMap":

                ShowPopup(feature, "<div style='font-size:.71em;'><br/><div id='divShapeResults' style='text-align:center; height:auto; width:auto; overflow:visible;'><img height='20' width='20' src='Images/loadercircle2.gif' alt='loading..'/><br/>Generating difference map, please wait ...</div>" + resetLink + "<p>Source:  <a href='http://www.ornl.gov/sci/landscan/index.html' target='_blank'>Landscan&trade; </a><br/></p></div>", null);
                DDMService.DifferenceMap(feature.id, WKTshp, parseInt(feature.attributes["LayerID"], 10), SuccessCallBack_DifferenceMap, FailCallBack_DifferenceMap);
                break;
            case "Scenario":

                ShowPopup(feature, "<div style='font-size:.71em;'><br/><div id='divShapeResults' style='text-align:center; height:auto; width:auto; overflow:visible;'><img height='20' width='20' src='Images/loadercircle2.gif' alt='loading..'/><br/>Estimating population, please wait ...</div>" + resetLink + "<p>Source: " + feature.attributes["LayerName"] + "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; and <a href='http://www.ornl.gov/sci/landscan/index.html' target='_blank'>Landscan&trade; </a><br/></p></div>", null);
                DDMService.CreateShapeAndClipForScenario(feature.id, WKTshp, parseInt(feature.attributes["LayerID"], 10), SucceededCallback_FeatureSelected, FailedCallback_FeatureSelected);
                break;
            default:

                ShowPopup(feature, "<div style='font-size:.71em;'><br/><div id='divShapeResults' style='text-align:center; height:auto; width:auto; overflow:visible;'><img height='20' width='20' src='Images/loadercircle2.gif' alt='loading..'/><br/>Estimating population, please wait ...</div>" + resetLink + "<p>Source:  <a href='http://www.ornl.gov/sci/landscan/index.html' target='_blank'>Landscan&trade; </a><br/></p></div>", null);
                DDMService.CreateShapeAndClip2(feature.id, WKTshp, 0, SucceededCallback_FeatureSelected, FailedCallback_FeatureSelected);
                break;
        }
    }

    //Diselect to retain onmouseclick event
    var unsel = new OpenLayers.Control.SelectFeature(feature, { clickout: true });
    unsel.unselect(feature);
}

function createDiv(divID, className, append) {

    var div = document.createElement("div");

    div.id = divID;
    //div.setAttribute("align", "center");

    if (className) {
        div.className = className;
    } else {
        div.style.height = 'auto';
        div.style.display = 'none';
        div.style.zIndex = '-1';
        div.style.visibility = 'hidden';
        div.style.overflow = 'visible';
        //div.style.margin = "0px auto";
    }

    if (append) {
        document.body.appendChild(div);
    }
    return div;
}

function GetPopupHeight(contentDIV) {
    var h = null;
    var d = createDiv("divid", null, true);
    d.style.display = 'block'; //allows offsetHeight
    d.innerHTML = contentDIV;
    h = d.offsetHeight;
    d.style.display = 'none';

    return h;
}

function ShowPopup(feature, contentDIV, position) {
    
    if (position == null) {
        position = feature.geometry.getBounds().getCenterLonLat();
        //position = 'lon=3453730.6855566,lat=2074195.1992578 lon=3453730.6855566 lat=2074195.1992578'
    }

    if (feature.popup != null) {
        if (feature.attributes["Demography"] == null) {
            feature.attributes["Demography"] = feature.popup.contentHTML;
        }

        feature.popup.hide();
        feature.popup.maxSize.h = GetPopupHeight(contentDIV) + 70;
        feature.popup.setContentHTML(contentDIV);        
        feature.popup.show();
    }
    else {

        var featurePopup = new OpenLayers.Popup.FramedCloud("chicken",
                    position,
                 new OpenLayers.Size(300, 300),
                    contentDIV,
                    null,
                    true,
                    onPopupClose);

        featurePopup.minSize.w = '275'; //limit width of the popup
        featurePopup.maxSize.w = '275';
        featurePopup.maxSize.h = GetPopupHeight(contentDIV) + 70;

        feature.popup = featurePopup;
        map.addPopup(featurePopup);
    }
}

function onFeatureUnselect(feature) {
    //DO nothing 
}

function AddWKTFeature(element) {
    var in_options =
   {
       'internalProjection': map.baseLayer.projection,
       'externalProjection': new OpenLayers.Projection("EPSG:4326")
   };

    var wkt = new OpenLayers.Format.WKT(in_options);
    var features = wkt.read(element);
    var bounds;
    if (features) {
        if (features.constructor != Array) {
            features = [features];
        }
        for (var i = 0; i < features.length; i++) {
            if (!bounds) {
                bounds = features[i].geometry.getBounds();
            } else {
                bounds.extend(features[i].geometry.getBounds());
            }
        }
        vector.addFeatures(features);
    }
    else {
        element = 'Bad input ';
    }
    return features;
}

function AddWKTFeatureAtt(element, admin1id, details, ltype, zone) {
    var in_options =
        {
            'internalProjection': map.baseLayer.projection,
            'externalProjection': new OpenLayers.Projection("EPSG:4326")
        };

    var wkt = new OpenLayers.Format.WKT(in_options);
    var features = wkt.read(element);
    var bounds;

    try {

        if (features) {
            if (features.constructor != Array) {
                features = [features];
            }
            for (var i = 0; i < features.length; ++i) {
                if (!bounds) {
                    bounds = features[i].geometry.getBounds();
                }
                else {
                    bounds.extend(features[i].geometry.getBounds());
                }
                features[i].attributes = { Admin1ID: admin1id, Info: details };

                //if this is a saved shape, add that attribute as shapeID
                if (details.indexOf("Saved shape") != -1) {
                    features[i].attributes["SavedShapeID"] = zone;
                }

                switch (ltype * 1) {
                    case 4:
                        features[i].style = FeatureStylesRandom(zone);             
                        break;
                    default:
                        break;
                }
            }
            
            vector.addFeatures(features);

            if (panToFirstMap == true) {
                map.zoomToExtent(bounds);
                map.zoomOut();
            }
        }
        else {
            element = 'Bad input';
        }
        // return features;
    }
    catch (err) { }
    finally {
        wkt = null;
        features = null;
        bounds = null;
    }
}

function FeatureStyles(id) {
    var _style;

    switch (id * 1) {
        case 1:
            _style = {
                strokeColor: "Brown",
                fillColor: "#FFD9D9",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 2:
            _style = {
                strokeColor: "Brown",
                fillColor: "#DBB895",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 3:
            _style = {
                strokeColor: "Brown",
                fillColor: "#D7EBFF",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 4:
            _style = {
                strokeColor: "Brown",
                fillColor: "#FFFFB9",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 5:
            _style = {
                strokeColor: "Brown",
                fillColor: "#CDCD9C",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 6:
            _style = {
                strokeColor: "Brown",
                fillColor: "#B9FFB9",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 7:
            _style = {
                strokeColor: "Brown",
                fillColor: "#EEDDFF",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 8:
            _style = {
                strokeColor: "Brown",
                fillColor: "#B5E6B5",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 9:
            _style = {
                strokeColor: "Brown",
                fillColor: "#E1A6A6",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 10:
            _style = {
                strokeColor: "Brown",
                fillColor: "#D5F1FF",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 11:
            _style = {
                strokeColor: "Brown",
                fillColor: "#EEDDFF",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
        case 0: //default
        default:
            _style = {
                strokeColor: "Brown",
                fillColor: "#D7D7D7",
                strokeWidth: 1,
                pointRadius: 2,
                fillOpacity: 0.8,
                pointerEvents: "visiblePainted",
                hoverPointRadius: 2,
                hoverStrokeWidth: 2
            };
            break;
    }
    
    return _style;
}

function FeatureStylesRandom(id) {

    return {
        strokeColor: "Brown",
        fillColor: colorArray[id],
        strokeWidth: 1,
        pointRadius: 2,
        fillOpacity: 0.6,
        pointerEvents: "visiblePainted",
        hoverPointRadius: 2,
        hoverStrokeWidth: 2
    };
}

 function AddWKTPointStyleFeature(element, style, motherid) {
     var style_green =
           {
               strokeColor: "green",
               fillColor: "green",
               strokeWidth: 2,
               pointRadius: 1,
               pointerEvents: "visiblePainted"
           };

     var style_blue = {
         strokeColor: "blue",
         fillColor: "blue",
         strokeWidth: 2,
         pointRadius: 1,
         pointerEvents: "visiblePainted"
     };

     var style_red = {
         strokeColor: "red",
         fillColor: "red",
         strokeWidth: 2,
         pointRadius: 1,
         pointerEvents: "visiblePainted"
     };
     var style_orange = {
         strokeColor: "orange",
         fillColor: "orange",
         strokeWidth: 2,
         pointRadius: 1,
         pointerEvents: "visiblePainted"
     };

     var style_grey = {
         strokeColor: "gray",
         fillColor: "gray",
         strokeWidth: 2,
         pointRadius: 1,
         pointerEvents: "visiblePainted"
     };

     var style_white = {
         strokeColor: "white",
         fillColor: "white",
         strokeWidth: 2,
         pointRadius: 1,
         pointerEvents: "visiblePainted"
     };

     var in_options = {
         'internalProjection': map.baseLayer.projection,
         'externalProjection': new OpenLayers.Projection("EPSG:4326")
     };

     var wkt = new OpenLayers.Format.WKT(in_options);
     var features = wkt.read(element);
     var bounds;
     if (features) {
         if (features.constructor != Array) {
             features = [features];
         }
         for (var i = 0; i < features.length; ++i) {

             if (style == "red") {
                 features[i].style = style_red;
             }
             else if (style == "green") {
                 features[i].style = style_green;
             }
             else if (style == "blue") {
                 features[i].style = style_blue;
             }
             else if (style == "gray") {
                 features[i].style = style_grey;
             }
             else if (style == "orange") {
                 features[i].style = style_orange;
             }
             else if (style == "white") {
                 features[i].style = style_white;
             }

             features[i].attributes["MotherID"] = motherid;

             if (!bounds) {
                 bounds = features[i].geometry.getBounds();
             } else {
                 bounds.extend(features[i].geometry.getBounds());
             }
         }
         vector.addFeatures(features);

     } else {
         element = 'Bad input ';
     }
     return features;
 }
 
///<summary>Converts a VEShape object to WKT (Well-Known-Text) string representation.</summary>
 function ShapeTo2WKT(shape) {
     if (shape == null) {
         throw "VirtualEarthWKT.ShapeToWKT: 'shape' parameter can not be null.";
     }

     var wktTemplate = "";
     var wktGeomPoints = "";
     var shapePoints;

     try {
         // Figure out the WKT Geometry Type
         switch (shape.GetType()) {
             case VEShapeType.Pushpin:
                 wktTemplate = "POINT({points})";
                 break;
             case VEShapeType.Polygon:
                 wktTemplate = "POLYGON(({points}))";
                 break;
             case VEShapeType.Polyline:
                 wktTemplate = "LINESTRING({points})";
                 break;
             default:
                 throw "VirtualEarthWKT.ShapeToWKT: VEShapeType (" + shape.GetType() + ") not supported.";
                 break;
         }

         // Get the List of VELatLong objects represented as WKT compatible list of points
         shapePoints = shape.GetPoints();

         for (var i = 0; i < shapePoints.length; i++) {
             if (wktGeomPoints.length > 0) {
                 wktGeomPoints += ", ";
             }
             wktGeomPoints += shapePoints[i].Longitude + " " + shapePoints[i].Latitude;
         }
         // return WKT representation of the VEShape
         return wktTemplate.replace("{points}", wktGeomPoints);
     }
     catch (err) { }
     finally {
         wktTemplate = null;
         shapePoints = null;
         wktGeomPoints = null;
     } 
 }

 function ShapeTo2WKTLite(shape) {
     if (shape == null) {
         throw "VirtualEarthWKT.ShapeToWKT: 'shape' parameter can not be null.";
     }

     var wktTemplate = "";
     var wktGeomPoints = "";
     var shapePoints;

     try {
         // Figure out the WKT Geometry Type
         switch (shape.GetType()) {
             case VEShapeType.Pushpin:
                 wktTemplate = "POINT({points})";
                 break;
             case VEShapeType.Polygon:
                 wktTemplate = "POLYGON(({points}))";
                 break;
             case VEShapeType.Polyline:
                 wktTemplate = "LINESTRING({points})";
                 break;
             default:
                 throw "VirtualEarthWKT.ShapeToWKT: VEShapeType (" + shape.GetType() + ") not supported.";
                 break;
         }

         // Get the List of VELatLong objects represented as WKT compatible list of points
         shapePoints = shape.GetPoints();

//         for (var i = 0; i < shapePoints.length; i++) {
//             if (wktGeomPoints.length > 0) {
//                 wktGeomPoints += ", ";
//             }
//             wktGeomPoints += shapePoints[i].Longitude + " " + shapePoints[i].Latitude;
//         }

         for (var coord in shapePoints) {
             wktGeomPoints += shapePoints[i].Longitude + " " + shapePoints[i].Latitude + ",";
         }

         // return WKT representation of the VEShape
         return wktTemplate.replace("{points}", wktGeomPoints);
     }
     catch (err) { }
     finally {
         wktTemplate = null;
         shapePoints = null;
         wktGeomPoints = null;
     }
 }
 
///<summary>Converts a VEShape object to WKT (Well-Known-Text) string representation.</summary>
 function ShapeToWKT(shape) {
     if (shape == null) {
         throw "VirtualEarthWKT.ShapeToWKT: 'shape' parameter can not be null.";
     }
     var wktTemplate = "";
     var wktGeomPoints = "";
     var shapePoints;

     try {
         // Figure out the WKT Geometry Type
         switch (shape.GetType()) {
             case VEShapeType.Pushpin:
                 wktTemplate = "POINT({points})";
                 break;
             case VEShapeType.Polygon:
                 wktTemplate = "POLYGON(({points}))";
                 break;
             case VEShapeType.Polyline:
                 wktTemplate = "LINESTRING({points})";
                 break;
             default:
                 throw "VirtualEarthWKT.ShapeToWKT: VEShapeType (" + shape.GetType() + ") not supported.";
                 break;
         }
         // Get the List of VELatLong objects represented as WKT compatible list of points
         shapePoints = shape.GetPoints();
         for (var i = 0; i < shapePoints.length; i++) {
             if (wktGeomPoints.length > 0) {
                 wktGeomPoints += ", ";
             }
             wktGeomPoints += shapePoints[i].Longitude + "," + shapePoints[i].Latitude;
         }
         // return WKT representation of the VEShape
         return wktTemplate.replace("{points}", wktGeomPoints);
     } 
     catch (err) { }
     finally {
         wktTemplate = null;
         wktGeomPoints = null;
         shapePoints = null;
     } 
 }

///<summary>
///Converts WKT (Well-Known-Text) string representation of a point/polygon/linestring to a VEShape object.
///</summary>
function ShapeFromWKT(strWKT) {
    if (strWKT == null) {
        throw "VirtualEarthWKT.ShapeFromWKT: 'strWKT' parameter can not be null.";
    }
    if (strWKT.length == 0) {
        throw "VirtualEarthWKT.ShapeFromWKT: 'strWKT' parameter can not be an empty string.";
    }
    var shapeType = null;
    var wktPoints = null;

    // Get the Shape Type and list of "Longitude Latitude" location points
    switch (strWKT.substring(0, 5).toLowerCase()) {
        case "point":
            shapeType = VEShapeType.Pushpin;
            wktPoints = strWKT.substring(6, strWKT.length - 1);
            break;
        case "polyg":
            shapeType = VEShapeType.Polygon;
            wktPoints = strWKT.substring(9, strWKT.length - 2);
            break;
        case "lines":
            shapeType = VEShapeType.Polyline;
            wktPoints = strWKT.substring(11, strWKT.length - 1);
            break;
        default:
            throw "VirtualEarthWKT.ShapeFromWKT: Unknown WKT Geometry Type";
            break;
    }

    // split out the wkt points to be seperate
    wktPoints = wktPoints.split(",");

    // Convert the WKT Points to VELatLong locations
    var shapePoints = new Array();
    for (var i = 0; i < wktPoints.length; i++) {
        // Split the "Longitude Latitude" apart
        var loc = trimSpaces(wktPoints[i]).split(" ");
        // Create VELatLong location
        shapePoints[shapePoints.length] = new VELatLong(parseFloat(loc[1]), parseFloat(loc[0]));
    }

    // Return a VEShape that represents this WKT Geometry
    myPoints = shapePoints.toString();
    return new VEShape(shapeType, shapePoints);
}


function ZoomScenarioExtent(maxX, maxY, minX, minY) {
    //transform the coordinate into spherical mercator projection
    var extproj = new OpenLayers.Projection("EPSG:4326");

    //create bound(left, bottom, right, top)
    var ScenarioBounds = new OpenLayers.Bounds(minX, minY, maxX, maxY);
    //zoom to extend
    // ScenarioBounds.transform(map.baseLayer.projection, extproj);
    ScenarioBounds.transform(extproj, map.baseLayer.projection);
    
    map.zoomToExtent(ScenarioBounds);
}

//Demographic results of a shape
function SucceededCallback_FeatureSelected(result) {
    var temp = result.split("$");
    result = temp[0];

    var offset = result.indexOf("||");
    result = result.substring(offset + 2);

    //strip the || from server, replace with <br />
    result = result.replace(/\|\|/g, "<br />");

    var feature = ParseFeature(temp[0]);

    if (feature != null) {
        var popupTitle = "";
        var refreshLink = "";
        var cohortsLink = "";
        var densityMapLink = "";
        var dataSourceLink = "";
        var altDataSourceLink = "";
        var scenarioLink = "";
        var totArea = feature.totalArea;
        
        if (feature.attributes['Info'] != null)
            popupTitle = "<div style='font-weight:bold'>" + feature.attributes['Info'] + "</div>";

        refreshLink = "<br/><a onclick=\"RefreshFeature('" + feature.id + "');\" href=\"#\">Refresh</a><br />";

        if (temp[1] != null && temp[1].length > 0 && feature.attributes["SavedShapeID"] == null)
            scenarioLink = temp[1];

        if (totArea * 1 > 6000)
            densityMapLink = "<a onclick = \" alert('This shape is too large, try a smaller shape. (less than 6,000 Sq. KM.)');\" href=\"#\">View Density Map</a><br />";
        else
            densityMapLink = "<a onclick = \" GetDensityMap('" + feature.id + "');\" href=\"#\">View Density Map</a><br />";

        if (feature.attributes["LayerName"] != null)
            dataSourceLink = "Source: " + feature.attributes["LayerName"] + "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; and <a href='http://www.ornl.gov/sci/landscan/index.html' target='_blank'>Landscan&trade; "+temp[3]+"</a><br/>";
        else
            dataSourceLink = "Source: <a href='http://www.ornl.gov/sci/landscan/index.html' target='_blank'>Landscan&trade; "+temp[3]+"</a><br/>";

        if (feature.attributes['Admin1ID'] != null && (feature.estimatedPopulation * 1) > 0)
            cohortsLink = "<a onclick =\" window.open('Lib/DemographicDetail.aspx?Sum=" + feature.estimatedPopulation + "&Admin=" + feature.attributes['Admin1ID'] + "','Age_and_Sex_Cohorts','height=600,left=10,location=yes,menubar=no,resizable=yes,status=no,scrollbars=yes,toolbar=no,top=200,width=500');\" href=\"#\">View Age and Sex Estimates</a><br />";

        if (temp[2] != null && temp[2].length > 0)
            altDataSourceLink = "<a onclick =\" window.open('Forms/Data/changedatasource.aspx?spane=1&featureid=" + featureid + "&dslist=" + temp[2] + "','Alternative_Data_Source','height=300,left=100,location=yes,menubar=no,resizable=yes,status=no,scrollbars=yes,toolbar=no,top=200,width=400');\" href=\"#\">Alternative Data Source</a><br />";

        //check if its a saved shape then show modify shape link
        if (feature.attributes["SavedShapeID"] != null) {
            var isSavedShape = feature.attributes["SavedShapeID"];
            savedshapeID = isSavedShape.toString();
            result = result.replace("saveaffectedarea", "editaffectedarea");
            result = result.replace("Add to Scenario", "Modify shape details");
        }

        var demography = "<div style='font-size:.71em; text-align:left;'>" + popupTitle + "<br/><div id='divShapeResults' style='text-align:left;'>" + result + refreshLink + scenarioLink + cohortsLink + densityMapLink + dataSourceLink + altDataSourceLink + "</div>";

        feature.attributes["Demography"] = demography;

        ShowPopup(feature, demography, null);
    }
}

function FailedCallback_FeatureSelected(result) {

}

function RefreshFeature(featureid) {
    var feature = vector.getFeatureById(featureid);

    if (feature != null) {
        if (feature.attributes["HasDensityMap"] == true)
            ResetDensityMap(featureid);

        feature.attributes["HasDensityMap"] = false;

        feature.attributes["FeatureType"] = "Default";

        ResetPopup(feature);

        feature.estimatedPopulation = null;
        feature.totalArea = null;
        feature.populationDensity = null;
        feature.mostPopulated = null;
        feature.leastPopulated = null;
        feature.userLoggedIn = null;

        onFeatureClick(feature);
    }
}

function ResetFeature(featureid) {
    var feature = vector.getFeatureById(featureid);

    if (feature != null) {
        ResetPopup(feature);
    }
}

 function GetDensityMap(featureid) {
     var feature = vector.getFeatureById(featureid);

     if (feature != null) {
         if (feature.attributes["HasDensityMap"] == true)
             ResetDensityMap(featureid);

         feature.attributes["HasDensityMap"] = false;

         ResetPopup(feature);

         feature.attributes["FeatureType"] = "DensityMap";
         onFeatureClick(feature);
     }
 }

//hide and nullify
function ResetPopup(feature) {
    if (feature.popup != null) {
        feature.popup.hide();
        feature.popup = null;
    }
}

function ResetDensityMap(featureID) {
    //Delete all point in density map
}

function GetDifferenceMap(featureID, layerID) {
    var feature = vector.getFeatureById(featureID);

    if (feature != null) {
        feature.attributes["Demography"] = feature.popup.contentHTML;
        feature.attributes["FeatureType"] = "DifferenceMap";
        feature.attributes["LayerID"] = layerID;

        ResetPopup(feature);

        onFeatureClick(feature);
    }
}

function ParseFeature(popdata) {
    var points = popdata;
    var mdetails = "";

    if (points.length > 0) {
        var latLongTokens = points.split('||');
        var veLatLongs = new Array(latLongTokens.length - 1);
        var featuresid = latLongTokens[0].split(':')[1];

        var temppop = latLongTokens[1].split(':')[1].replace(/,/g, '').trim();
        var temparea = latLongTokens[2].split(':')[1].replace(/,/g, '').trim();
        var tempdensity = latLongTokens[3].split(':')[1].replace(/,/g, '').trim();
        var tempmostpop = latLongTokens[4].split(':')[1].replace(/,/g, '').trim();
        var templeastpop = parseFloat(latLongTokens[5].split(':')[1].replace(/,/g, '').trim());

        var temploggedIn = false;

        if (popdata.indexOf("saveaffectedarea") >= 0) {
            temploggedIn = true;
        }

        featureid = featuresid.split(' ').join(''); //remove spaces in featureid
        var feature = vector.getFeatureById(featureid);

        if (feature != null) {
            feature.estimatedPopulation = parseFloat(temppop);
            feature.totalArea = parseFloat(temparea);
            feature.populationDensity = parseFloat(tempdensity);
            feature.mostPopulated = parseFloat(tempmostpop);
            feature.leastPopulated = parseFloat(templeastpop);

            feature.userLoggedIn = temploggedIn;

            globalValue = feature.estimatedPopulation; //For Ken
        }

        return feature;
    }
}

function SuccessCallback_DensityMap(result) {
    var temp = result.split("$");
    var featureid = temp[0];
    var points = temp[1];
    var legendArray = temp[2].split(",");
    try {

        points = result.split("|");

        for (var i = 0; i < points.length - 1; i++) {
            var fts = points[i].split(",");
            var wkt = "POINT(" + fts[1].toString() + " " + fts[0].toString() + ")";
            var style = fts[2].toString();
            AddWKTPointStyleFeature(wkt, style, featureid);
        }

        var feature = vector.getFeatureById(featureid);

        //var totPop = feature.estimatedPopulation;
        var totArea = feature.totalArea;

        var mostPop = feature.mostPopulated;
        var leastPop = 0; //parseInt(feature.leastPopulated, 10);

        var popDen = feature.populationDensity;

        var veryHigh = parseInt(legendArray[0], 10);
        var high = parseInt(legendArray[1], 10);
        var medium = parseInt(legendArray[2], 10);
        var low = parseInt(legendArray[3], 10);
        var veryLow = parseInt(legendArray[4], 10);

        if (veryLow > low)
            low = veryLow + 1;

        if (low > medium)
            medium = low + 1;

        if (medium > high)
            high = medium + 1;

        if (high > veryHigh)
            veryHigh = high + 1;

        if (feature != null) {
            var demography = feature.attributes["Demography"];

            var legend = demography;

            if (totArea * 1 > 0) {
                legend +=
		    "<div id='divLegend' style='width:60%';font-style: normal; font-size: 0.75em; color: #000000; float:left;border: 0.5em solid #000000; padding-top:5px;>'" +
			    "<table align='left' cellpadding='0' cellspacing='0' style='width:100%;float:left;background-color: #F0F8FF; font-family: Segoe UI'>" +
				    "<tr style='font-weight: bold; background-color: #d7ebff'><td colspan='2' style='padding-bottom:2px'>Legend &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>" +
				    "<tr><td bgcolor='Red' style='border: 0.1em solid #000000'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;" + ((veryHigh * 1) + 1).toString() + " +</td></tr>" +
				    "<tr><td bgcolor='Blue' style='border: 0.1em solid #000000'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;" + ((high * 1) + 1).toString() + " - " + veryHigh + "</td></tr>" +
				    "<tr><td bgcolor='Green' style='border: 0.1em solid #000000'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;" + ((medium * 1) + 1).toString() + " - " + high + "</td></tr>" +
				    "<tr><td bgcolor='Orange' style='border: 0.1em solid #000000'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;" + ((low * 1) + 1).toString() + " - " + medium + "</td></tr>" +
				    "<tr><td bgcolor='Gray' style='border: 0.1em solid #000000'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;" + veryLow + " - " + low + "</td></tr>" +
				    "<tr><td bgcolor='White' style='border: 0.1em solid #000000'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;" + leastPop + "</td></tr>" +
				    "<tr><td colspan='2'>Person per sq. km.</td></tr>" +
			    "</table>" +
		    "</div>";
            }

            feature.attributes["HasDensityMap"] = true;

            var anchor = null;

            // anchor = new OpenLayers.LonLat((this.left + this.right) / 2, (this.bottom + this.top) / 2);        
            // anchor = new OpenLayers.LonLat((feature.geometry.getBounds().right) / 2, (this.bottom + this.top) / 2);        
            // anchor = new OpenLayers.Bounds(feature.geometry.getBounds().left, feature.geometry.getBounds().bottom, feature.geometry.getBounds().right, feature.geometry.getBounds().top);
        }
        ShowPopup(feature, legend, anchor);
    }
    catch (err) { }
    finally {
        temp = null;
        legendArray = null;
        points = null;
    } 
}

function FailCallback_DensityMap() {

}

function SuccessCallBack_DifferenceMap(result) {
    var temp = result.split("$");
    var featureID = temp[0];
    var points = temp[1].split("|");

    var feature = vector.getFeatureById(featureID);

    for (var i = 0; i < points.length; i++) {
        var fts = points[i].split(",");
        var wkt = "POINT(" + fts[1].toString() + " " + fts[0].toString() + ")";
        var style = fts[2].toString();
        AddWKTPointStyleFeature(wkt, style, featureID);
    }

    var contentDIV =
    "<div>" +
        "<table style='width: 23%;'>" +
            "<tr><td>Legend</td><td class='style1'>difference</td><td>&nbsp;</td></tr>" +
            "<tr><td>Red</td><td class='style1'>&gt;1000</td><td style='background-color:#FF0000'>&nbsp;</td></tr>" +
            "<tr><td>Blue</td><td class='style1'>&nbsp;btw 1000 &amp; 100&nbsp;</td><td tyle='background-color: blue' style='background-color: #0000FF'>&nbsp;</td></tr>" +
            "<tr><td>Green</td><td class='style1'>&gt; 100</td><td style='background-color:green' style='background-color: #00FF00'>&nbsp;</td></tr>" +
        "</table>" +
    "</div>";

    ShowPopup(feature, contentDIV, null);

    if (feature.popup != null) {
        feature.popup.setBorder("2px solid");
        feature.popup.setBackgroundColor("#f3f3f3");
    }
}

function FailCallBack_DifferenceMap(results) {

}

function LoadAlternateDS(layer, layerName, featureid) {
    var feature = vector.getFeatureById(featureid);

    if (feature != null) {
        ResetPopup(feature);

        feature.attributes["FeatureType"] = "Scenario";
        feature.attributes["LayerID"] = layer;
        feature.attributes["LayerName"] = layerName;

        onFeatureClick(feature);
    }
}

/*********************************************************************
*   Function: LoadArea
*   Purpose:Loads a saved shape, together with adjusted pop details. See ViewScenarioMap.aspx
*   Created By: Ken K.
**********************************************************************/
function LoadArea(result) {
    try {
        var tempresult = result.split("|");
        savedshapeID = tempresult[0];
        shapetitle = tempresult[1];
        //shapedesc=tempresult[1];
        //var tInfo = tempresult[1];
        var tPoints = tempresult[2];

        var testPoints = tPoints.split(",");
        var len = testPoints.length / 2;
        var alength = testPoints.length;
        latitude = new Array(len);
        longitude = new Array(len);
        var px = 0;
        var pj = 0;
        for (var index = 0; index < testPoints.length; index++) {
            if (index % 2 == 1) {
                // It's even
                latitude[pj] = parseFloat(testPoints[index]);
                pj = pj + 1;

            }
            else {
                // It's odd
                longitude[px] = parseFloat(testPoints[index]);
                px = px + 1;
            }

        }
        var veLatLongs = new Array();

        for (var x = 0; x < len; x++) {
            veLatLongs[x] = new VELatLong(latitude[x], longitude[x]);
        }

        // Create the VEShape object and assign parameters.
        shape = new VEShape(VEShapeType.Polygon, veLatLongs);
        shape.SetLineWidth(3);
        shape.SetLineColor(new VEColor(0, 0, 255, 1));
        shape.SetFillColor(new VEColor(0, 0, 255, 0.2));
        shape.SetTitle(shapetitle);
        shape.SetDescription(shapedesc);

        var wktshape = ShapeTo2WKT(shape);

        //AddWKTFeature(wktshape);
        if (savedShapeID != null) {
            var strtemp = " ";
            //remove spaces in shapeID
            savedShapeID = savedShapeID.replace(/strtemp/g, "");
        }
        AddWKTFeatureAtt(wktshape, "", shapetitle, 0, savedshapeID);
    }
    catch (Exception) {
        ////alert(Exception.message);
    }
}

/*********************************************************************
*   Function: modCursor
*   Purpose:Modifies Cursor appearance based on control variable passed
*   Created By: Aggrey Aywak
**********************************************************************/
function modCursor(ctype) {
    try {
        switch (ctype * 1) {
            case 0:
                document.getElementById("map").style.cursor = "default";
                break;
            case 1:
                document.getElementById("map").style.cursor = "pointer";
                break;
            case 2:
                document.getElementById("map").style.cursor = "crosshair";
                break;
            case 3: //
                document.getElementById("map").style.cursor = "hand";
                break;
            case 4: //
                document.getElementById("map").style.cursor = "auto";
                break;
            case 5: //Help, Analyze
                document.getElementById("map").style.cursor = "help";
                break;
            case 7: //Very busy
                document.getElementById("map").style.cursor = "wait";
                break;
            case 8: //Pan
                document.getElementById("map").style.cursor = "all-scroll";
                break;
            case 9: //Downloading, drawing ...
                document.getElementById("map").style.cursor = "progress";
                break;
            case 10: //Delete
                document.getElementById("map").style.cursor = "no-drop";
                break;
            default:
                break;
        }
    }
    catch (Exception) {
        //alert(Exception.message)
    }
}

function ShowPatienceON(message) {
    modCursor(9); //progress
    var divMessage = document.getElementById("divMessage");
    if (divMessage != null) {
        divMessage.innerHTML = message;
        ShowObject("divLoading");
        //clear the set timeout
        if (loadingTimeout)
            clearTimeout(loadingTimeout);
        loadingTimeout = setTimeout("HideLoadingAfterTimeout()", 10000);
    }
}

function ShowPatienceOFF() {
    modCursor(0); //default
    var divLoading = document.getElementById("divLoading");
    if (divLoading != null) {
        var divMessage = document.getElementById("divMessage");
        if (divMessage != null) {
            divMessage.innerHTML = "";
        }
        HideObject("divLoading");
    } 
}

function ShowLayer(lname, admin1id, ltype) {
    try {
        ShowPatienceON("Loading, Please wait ...");
        globalAdminID = admin1id;
        globalLayerType = ltype;

        panToFirstMap = true;
        tableName = lname;
        tpopulation = 0;
        DDMService.GetCountSortedArray(tableName, admin1id, SuccessCallback_ShowLayer, FailedCallback_ShowLayer);

    }
    catch (err) {
    }
}

function SuccessCallback_ShowLayer(results) {

    var temp = results.split("%");
    var arrLayers = null;
    var midPoint = temp[0];
    var wb = temp[1];
    var eb = temp[2];
    var nb = temp[3];
    var sb = temp[4];
    try {
        arrLayers = temp[5].split("$");
        layerCount = arrLayers.length;
        globalRecords = layerCount;
        currentRecord = 0;

        if (layerCount == 0) {
            alert('There are no maps for the selected theme available for display.');
            ShowPatienceOFF();
        }
        else {
            if (midPoint.length > 0) {
                // Pan To Map Bounds
                try {
                    panToFirstMap = false; //Avoid panning again

                    var lonLat = midPoint.split(",");
                    var proj = new OpenLayers.Projection("EPSG:4326");

                    // var point = new OpenLayers.LonLat(lonLat[0] * 1, lonLat[1] * 1);
                    
                    // point.transform(proj, map.getProjectionObject());
                    //map.setCenter(point);
                    //map.setCenter(point, getZoomExtent(parseInt(temp[1], 10)));
                    //map.setCenter(point, getZoomExtent(temp[1]));

                    var bounds = new OpenLayers.Bounds(wb, sb, eb, nb);
                    bounds.transform(proj, map.getProjectionObject());
                    map.zoomToExtent(bounds);

                } catch (err) {
                    panToFirstMap = true;
                }
            }

            if (globalLayerType * 1 == 4) {
                colorArray = genHexColors(layerCount);
            }

            for (j = 0; j<layerCount; j++) {

                //                if (fetchTimeout)
                //                    clearTimeout(fetchTimeout);
                //                fetchTimeout = setTimeout("LaunchHere()", 10);

                DDMService.FindPolyData2(tableName, arrLayers[j], globalLayerType, SuccessCallback_DrawLayers, FailedCallback_DrawLayers);
            }

            //            var fetchTimeout;
            //            for (j = 0; j < layerCount; j++) {

            //                if (fetchTimeout)
            //                    clearTimeout(fetchTimeout);

            //                var func = function() {
            //                    DDMService.FindPolyData2(tableName, arrLayers[j], globalLayerType, SuccessCallback_DrawLayers, FailedCallback_DrawLayers);
            //                }
            //                            
            //                //fetchTimeout = setTimeout("DDMService.FindPolyData2(" + tableName + "," + arrLayers[j] + "," + globalLayerType + "," + SuccessCallback_DrawLayers + "," + FailedCallback_DrawLayers + ")", 100);
            //                fetchTimeout = setTimeout(func, 100);
            //            } 
        }
    }
    catch (err) {
    }
}
function getZoomExtent(northToSouth) {
    var zm = parseInt(map.numZoomLevels / parseInt(northToSouth, 10), 10) - 1;
    return (zm > 4 ? zm : 4);
}

function FailedCallback_ShowLayer(results) {
    ShowPatienceOFF();
}

function LaunchHere() {
    clearTimeout(drawTimeout);
}

function SuccessCallback_DrawLayers(results) {
    currentRecord++;
    var innerDiv = "<div>Displaying map " + currentRecord + " of " + globalRecords + "</div>";
    ShowPatienceON(innerDiv);

    //Take a nap before drawing...
    if (drawTimeout)
        clearTimeout(drawTimeout);
    drawTimeout = setTimeout("LaunchHere()", 20); 

    try {
        var tempresponse = results.split("]");
        var ltype = tempresponse[0];
        var points = tempresponse[1];
        var info = "";
        var zone;

        switch (ltype * 1) {
            case 2:
                var continent = tempresponse[2];
                var region = tempresponse[3];
                var country = tempresponse[4];
                var province = tempresponse[5];
                var district = tempresponse[6];
                var division = tempresponse[7];

                info = continent + ", " + region + ": " + country;

                if (division != null && division.length > 1)
                { info = province + ", " + district + ": " + division; }
                else
                    if (district != null && district.length > 1)
                { info = country + ", " + province + ": " + district; }
                else
                    if (province != null && province.length > 1)
                { info = region + ", " + country + ": " + province; }
                break;
            case 4:
                zone = tempresponse[2];
                var livelihood = tempresponse[3];
                var livelihoodfr = tempresponse[4];

                if (livelihood != null && livelihood.length > 1)
                { info = livelihood; }
                break;
            default:
                break;
        }

        var latLongTokens = points.replace(/,/g, '');
        AddWKTFeatureAtt("POLYGON((" + latLongTokens.replace(/\|/g, ',') + "))", globalAdminID, info, ltype, zone);
        latLongTokens = null;
    }
    catch (err) {
        //catch errors
        ShowPatienceOFF();
    }
    finally {
        //avoid circular reference
        tempresponse = null;
        ltype = null;
        points = null;
        info = null;
        zone = null;
        results = null;
    }

    panToFirstMap = false; //Stop panning to other layers

    if (currentRecord * 1 == globalRecords * 1) {
        ShowPatienceOFF();
    } 
}

function FailedCallback_DrawLayers(result) {
    try {
        ShowPatienceOFF();
    }
    catch (Exception) {
    }
}

function SuccessCallBack_Buffer(result) {
    AddWKTFeature(result);
}

function FailCallBack_Buffer(result)
{ }

//**************************************************************************************//
//////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// FEATURE FUNCTIONS/////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//**************************************************************************************//

//Freehand doodle
function Draw() {
    SwitchOffDrawing(); //Deactivate all others first    

    action = "none";
    modCursor(2); //crosshair  

    drawpolygon.activate();
}

function HideObject(obj) {
    var _obj = document.getElementById(obj);
    if (_obj != null) {
        _obj.style.display = 'none';
        _obj.style.visibility = 'hidden';
    }
}

function ShowObject(obj) {
    var _obj = document.getElementById(obj);
    if (_obj != null) {
        _obj.style.display = 'block';
        _obj.style.visibility = 'visible';
        _obj.style.zIndex = '130';
    }
}

function SwitchOffDrawing() {
    turnoffmeasure();

    drawpolygon.deactivate();
    drawline.deactivate();
    drawpoint.deactivate();
    clickselectcontrol.deactivate();
	
	bufferPoint.deactivate();
	bufferLine.deactivate();

    HideObject("divToolTip");

    modCursor(8);  //All - Scroll or Pan
}

//Buffer from point
function BufferPoint() {
    SwitchOffDrawing(); //Deactivate all others first    

    action = "none";
    modCursor(2); //crosshair     

    //drawpoint.activate();
    bufferPoint.activate();
}

//Buffer from line
function BufferLine() {
    SwitchOffDrawing(); //Deactivate all others first     

    action = "none";
    modCursor(2); //crosshair

    //drawline.activate();
    bufferLine.activate();
}

//Buffer from shape
function BufferShape() {
    SwitchOffDrawing(); //Deactivate all others first    

    action = "BufferShape";
    modCursor(1); //hand pointer
	
	clickselectcontrol.activate();
}

//Get map demography
function AnalysePolygon() {
    SwitchOffDrawing(); //Deactivate all others first    

    action = "none";
    modCursor(5); //help

    clickselectcontrol.activate();
}

//Delete a layer
function ClearMapData() {
    SwitchOffDrawing(); //Deactivate all others first    

    action = "delete";
    modCursor(10); //delete

    clickselectcontrol.activate();
}

//Delete all layers
function ClearMapLayer() {
    SwitchOffDrawing(); //Deactivate all others first    
    //action = "deleteAll";    

    //clickselectcontrol.activate();   
    vector.destroyFeatures();
}

//chane to clear vector
function ClearPolygon(shpID) {
    try {
        var delShape = veMap.GetShapeByID(shpID);
        //Delete Shape
        slDrawing.DeleteShape(delShape);
    }
    catch (Exception) {
    }
}

function Measure() {
    turnonmeasure();
	var popup = OpenLayers.Util.getElement('winMeasures');
	if(!popup){
		var popup = new OpenLayers.Popup("winMeasures",
		map.getCenter(),
		new OpenLayers.Size(200, 150),
		"<div style='font-family: Arial, Helvetica, sans-serif; color: #FFFFFF;font-size: small; font-weight: bold; font-style: normal; padding: 10px;' id='MeasureDiv'><br/>"+
		"<input type='radio' name='type' value='polygon' id='polygonToggle' onclick='toggleControl(this);' /><label for='polygonToggle'>Measure Area (km<sup>2</sup>)</label><br />"+
		"<input type='radio' name='type' value='line' id='lineToggle' onclick='toggleControl(this);' /><label for='lineToggle'>Measure Distance KM)</label><br />&nbsp;&nbsp;"+
		"<input type='checkbox' name='geodesic' id='geodesicToggle' onclick='toggleGeodesic(this);' /><label for='geodesicToggle'>Use Geodesic Measure</label><br />" +
		"<div id='output' style='padding: 5px'></div></div>", true, onPopupDestroy);
		popup.setBorder("black 2px solid");
		popup.setBackgroundColor("#99CCFF");
		map.addPopup(popup);	
		document.getElementById('polygonToggle').checked = true;
	}	
    modCursor(2);  //crosshair
}

//Hide the popup
function onPopupClose(evt) {
    this.hide();
}

//destroy the popup
function onPopupDestroy(evt) {
    this.destroy();
	SwitchOffDrawing();
}

//**************************************************************************************//
//////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// GENERAL FUNCTIONS/////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//**************************************************************************************//


function Print() {
    window.print();
}

/**
Need to be rewritten to generic format
**/

function PrintMap() {
    try {
        var dummy = document.getElementById("printableMap");
        // dummy.style.left = 650 + "px";
        // dummy.style.top = 100+ "px";
        dummy.style.visibility = "visible";
        initFloatingWindowWithTabs('window6', Array('Print Map'), 800, 600, 600, 300, false, false, false, false, false);
        var printMap = new VEPrintableMap("divMap", "printableMap", veMap);
        printMap.Print();
    }
    catch (VEException) {
    }
}

function GeneratePrintableMap() {
    popup.hide();
    var oContent = document.getElementById('container').innerHTML;
    var olayers = document.getElementById('map_KiLayers_ViewPort').innerHTML;
    var oTitle = document.getElementById('Text1').Value;

    //strip some of elements
    var HTMLstring = "<HTML>";
    HTMLstring += "<HEAD>";
    HTMLstring += "<TITLE>Print Map</TITLE>";
    HTMLstring += "</HEAD>";
    HTMLstring += "<BODY onload='window.print()'>";
    HTMLstring += "<P>";
    HTMLstring += oTitle;
    HTMLstring += "</P>";
    HTMLstring += oContent;
    HTMLstring += "</BODY>";
    HTMLstring += "</HTML>";
    newwindow = window.open();
    newdocument = newwindow.document;
    newdocument.write(HTMLstring);
    newdocument.close();
}

function AddMap() {
    var tempwindow = document.getElementById("window5");
    tempwindow.style.visibility = "visible";
    initFloatingWindowWithTabs('window1', Array('Info', 'More info', 'The end'), 200, 200, 50, 50, true, false, false, true);
}

function handleMeasurements(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var element = document.getElementById('output');
    var out = "";
    if (order == 1) {
        out += "Measurement: " + measure.toFixed(3) + units;
    }
    else {
        out += "Measurement: " + measure.toFixed(3) + units + "<sup>2</" + "sup>";
    }
    element.innerHTML = out;
}

function toggleControl(element) {
    for (var key in measureControls) {
        var control = measureControls[key];
        if (element.value == key && element.checked) {
            control.activate();
        }
        else {
            control.deactivate();
        }
    }
}

function turnonmeasure() {
    for (var key in measureControls) {
        var control = measureControls[key];
        control.activate();
    }
}

function turnoffmeasure() {
    for (var key in measureControls) {
        var control = measureControls[key];
        control.deactivate();
    }
}

function toggleGeodesic(element) {
    for (var key in measureControls) {
        var control = measureControls[key];
        control.geodesic = element.checked;
    }
}


//**************************************************************************************//
//////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// UTILITY FUNCTIONS/////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//**************************************************************************************//


String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

function OnCatchHover(feature) {

    feature = feature.feature;

    if (feature.attributes['Info'] != null) {
        var info = feature.attributes['Info'];
        if (feature.popup == null) {
            ShowToolTip(info);
        }
    }
}

function SwitchLayers(showSL) {

	if(!map) return;
	
    var divLSwitcher = document.getElementById('layerswitcher');
	
    switch (showSL) {
        case true:

            if (map.layers.length < 6) {//initial count on page load == 2
                map.addLayer(gsat);
                map.addLayer(ghyb);
                map.setLayerIndex(gsat, 2);
                map.setLayerIndex(ghyb, 3);
            }
            
            divLSwitcher.style.backgroundColor = '#99CCFF';
            divLSwitcher.style.top = '300px';
            divLSwitcher.style.zIndex = '10';
            divLSwitcher.style.display = 'block';
            divLSwitcher.style.visibility = 'visible';
            break;
        case false:
            divLSwitcher.style.display = 'none';
            divLSwitcher.style.visibility = 'hidden';
            break;
        default: break;
    } 
}

function ShowToolTip(info) {

    var tm = setTimeout("DragToolTip()", 50);
    document.onmousemove = mouseMove;

    var divToolTip = document.getElementById("divToolTip");
    if (divToolTip != null) {
        divToolTip.innerHTML = info;
        ShowObject("divToolTip");
    }
    //clear the set timeout
    if (timeout2)
        clearTimeout(timeout2);
    timeout2 = setTimeout("HideToolTipAfterTimeout()", 4000);
}

function DragToolTip() {
    var divToolTip = document.getElementById("divToolTip");
    
    if (divToolTip != null) {
        divToolTip.style.left = xpoint + 10 + "px";
        divToolTip.style.top = ypoint + "px";
        divToolTip.style.textAlign = "left";

        ShowObject("divToolTip");
    }
}

function HideToolTipAfterTimeout() {
    HideObject("divToolTip");
}

function HideLoadingAfterTimeout() {
    HideObject("divLoading");
}

function mouseMove(ev) {
    ev = ev || window.event;

    if (ev.pageX || ev.pageY) {
        xpoint = ev.pageX;
        ypoint = ev.pageY;
    }
    else {
        xpoint = ev.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        ypoint = ev.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
}

function OnReleaseHover(feature) {
    HideObject("divToolTip");
}

function trimSpaces(str) {
    // Trim beginning spaces
    while (startsWith(str, " ")) {
        str = str.substring(1);
    }
    // Trim ending spaces
    while (endsWith(str, " ")) {
        str = str.substring(0, str.length - 1);
    }
    return str;
}

function startsWith(str, startstr) {
    return str.substring(0, startstr.length) == startstr;
}

function endsWith(str, endstr) {
    return str.substring(str.length - endstr.length) == endstr;
}

function InitDocument() {
    document.onmousedown = OnMouseDown;
    OnStatusResized();
}

function OnMouseDown(e) {
    parent.ForwardMouseDown(document, e);
    return false;
}

function OnStatusResized() {
    var width = 100;
    var logoW = 137;

    var leftFieldW = width - logoW - fieldsW - 3;
    if (leftFieldW < 10)
        leftFieldW = 10;

    var posX = 2;
    var elt;
    for (var i = 1; i < 5; i++) {
        elt = document.getElementById(i);
        elt.style.left = posX + "px";
        if (i == 1) {
            elt.style.width = (leftFieldW - 2) + "px";
            posX += leftFieldW;
        }
        else {
            var w = fieldSizes[i - 2];
            elt.style.width = (w - 2) + "px";
            posX += w;
        }
    }

    elt = document.getElementById("5");
    elt.style.left = (width - logoW - 1) + "px";
    return false;
}

if (typeof(Sys) != "undefined") 
	Sys.Application.notifyScriptLoaded();
	
	/*********************************************************************
*   Function: GetMapWidth
*   Purpose: Return the Map frame's width
*   Created By: Patrick Tsang
**********************************************************************/
function GetMapWidth() {
    if (BrowserDetect.browser == "Firefox") {
        var layout = top.g_oSiteInfo.siteLayout;
        if (layout.panelLayout == "VERTICAL") {
            //alert(layout.panelLayout);
            var sQuery = GetIPanelQuery().style;
            var sReport = GetIPanelReport().style;

            //docking
            if (sQuery.position != "absolute" && sReport.position != "absolute") {
                return (parseInt(top.document.body.clientWidth, 10) - layout.panelWidth - 2);
            }
            else {
                return (parseInt(top.document.body.clientWidth, 10) - 2);
            }
        }
        else {
            return top.document.getElementById("trViewer").clientWidth;
        }
    }
    else {
        return top.document.getElementById("ViewerFrame").clientWidth;
    }
}

function genHexColors(howMany) {
    var colors = new Array(howMany);
    tempArr = new Array(14);
    tempArr[0] = "0";
    tempArr[1] = "1";
    tempArr[2] = "2";
    tempArr[3] = "3";
    tempArr[4] = "4";
    tempArr[5] = "5";
    tempArr[5] = "6";
    tempArr[6] = "7";
    tempArr[7] = "8";
    tempArr[8] = "9";
    tempArr[9] = "a";
    tempArr[10] = "b";
    tempArr[11] = "c";
    tempArr[12] = "d";
    tempArr[13] = "e";
    tempArr[14] = "f";

    digit = new Array(5);

    for (c=0; c<howMany; c++) {
        color = "";
        for (i=0; i<6; i++) {
            digit[i] = tempArr[Math.round(Math.random() * 14)];
            color = color + digit[i];
        }
        colors[c] = "#" + color;
    }

    return colors;
}

///////////////////////THEMATIC LAYER///////////////////////

function OpenMap() {
    ShowObject("divThematicLayer");
}

function CloseMap() {
    HideObject("divThematicLayer");
}

function GetAdmin1List() {
    DDMService.Admin1List(SuccessCallBack_Admin1List, FailCallBack_Admin1List);
}

function GetLayerTypesByAdmin1(Admin1ID) {
    DDMService.RetrieveLayerTypesByAdmin(Admin1ID, SuccessCallBack_LayerTypes, FailCallBack_LayerTypes);
}

function GetLayersByAdmin(Admin1ID, lType) {
    DDMService.RetrieveLayersByAdmin(Admin1ID, lType, SuccessCallBack_Layers, FailCallBack_Layers);
}

function SuccessCallBack_Admin1List(results) {
    document.getElementById('divAdmin1List').innerHTML = results;
}

function SuccessCallBack_LayerTypes(results) {
    document.getElementById('divLayerTypes').innerHTML = results;
}

function SuccessCallBack_Layers(results) {
    document.getElementById('divLayers').innerHTML = results;
}

function FailCallBack_Admin1List(results) {
}

function FailCallBack_LayerTypes(results) {
}

function FailCallBack_Layers(results) {
}

function DisplayMap() {
    var layer = document.getElementById('ddlLayers').value;
    var admin1ID = document.getElementById('ddlAdmin1List').value;
    var lType = document.getElementById('ddlLayerTypes').value;

    if (layer != null && admin1ID != null && lType != null) {
        ShowLayer(layer, admin1ID, lType);
        CloseMap();
    }
    else {
        alert('Please select map to display.');
    }
}

//function pageLoad() {
//    GetAdmin1List();
//}



















