
        //Map
        var map = null;
        //VEShapeLayer
        var layer = new VEShapeLayer();
        var mapWidth = 635;
        var mapHeight = 425;
        var SoldierCount = 0;
        var zoomMax = 15;
        var zoomMin = 1;
        var defaultZoom = 4;
        var defaultLat = 39.479;
        var defaultLong = -96.0644;
        var defaultView = 'r';
		var defaultDataCode = 'U1|V1|D1|C1|M1|S1|';
		var dataCode;        
		var showDataCode = new Array();		
		var myLayer = null;
        var previousZoomLevel = null;
        var isFullScreen = 0;
        var strItemList = '';
        var showItemList = 1;
        var ulLat = 0;
        var ulLong = 0;
        var brLat = 0;
        var brLong = 0;
        var shareMyLocation = 1;


        String.prototype.ReplaceAll = function(stringToFind, stringToReplace) {
            var temp = this;
            var index = temp.indexOf(stringToFind);
            while (index != -1) {
                temp = temp.replace(stringToFind, stringToReplace);
                index = temp.indexOf(stringToFind);
            }
            return temp;
        }

        function ShowPopup(shapeIndexNum, shapeLat, shapeLong) {
           // alert(shapeLat);
            //shapeLatLong = new VELatLong(shapeLat, shapeLong);
            shape = layer.GetShapeByIndex(shapeIndexNum, new VELatLong(shapeLat, shapeLong));
            map.ShowInfoBox(shape);
        }

        function HidePopup()
        {
            map.HideInfoBox();
        }

        function openInSameWindow(chosenURL) {
            var newWindow = window.open(chosenURL, '');
            newWindow.focus();
            return false;
        }

      
        function ShowOnMap(mypinID) {
        //alert("tS" + mypinID + "t_" + map.GUID);
        document.getElementById("tS" + mypinID + "t_" + map.GUID).onmouseover();
        //divtoshow.style.display = 'block';
        }
        
        function ReleventMapItemImage(itemtype) {
        	//alert("yes");
        switch (itemtype) {
        	case "SF":
        		return "/mapping/sf.png"
        	break;
        	case "SM":
        		return "/mapping/sm.png"
        	break;
        	case "V":
        		return "/mapping/v.png"
        	break;
        	case "D":
        		return "/mapping/d.png"
        	break;
			case "C":
        		return "/mapping/c.png"
        	break;
			case "M":
        		return "/mapping/m.png"
        	break;
			case "U":
        		return "/mapping/u.png"
        	break;
        }
        	
        }
        
        
        function FullScreenToggle(mydiv) {
        mydiv.style.width = "100%";
        mydiv.style.height = "100%";
        isFullScreen = 1;
        }
        
		
		
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
		
//		function handleKeyPress(e)
//		{
//			var key=e.keyCode || e.which;
//			if (key==13)
//			{
//				alert('enter');
//				btnFind.click;
//			}
//		}
		        
				function findAddress(myAddress)
	      {
	         try
	         {
	            
	            map.Find(null, myAddress);
	            
	            
	         }
	         catch(e)
	         {
	            alert(e.message);
	         }
	      }


				function findLoc(mytxt)
	      {
	         try
	         {
	            map.Find(null, mytxt.value);
	         }
	         catch(e)
	         {
	            alert(e.message);
	         }
	      }

	      function filterShareLocation(intShareMyLocation) {
	          shareMyLocation = intShareMyLocation;
	      }

	      function convertDataCodeToArray() {
	          showDataCode = dataCode.split("|");
	          var lastItemIndex = showDataCode.length - 1;
	          showDataCode.remove(lastItemIndex);
	          lastItemIndex = showDataCode.length - 1;


	          
	      }
	      
        function filterdataCode(mychk) {

            //alert("BEGIN: " + dataCode);
		   
		   
		   //if the check box action is CHECK then...
		    if (mychk.checked) {
		        //ADD item to Show list ARRAY 
                
                //showDataCode.splice(2,0,"Lene");            
                showDataCode.push(mychk.value);	
            }
            
           //if the check box action is UNCHECK then...
            else
            {		
				//Remove item from show list ARRAY
				for (var i = 0; i < showDataCode.length; i++) {
				    if (showDataCode[i].indexOf(mychk.value) > -1) {
				        showDataCode.remove(i);

				    }

				}
            }
			
			//convert array back to datacode string
            var newDataCode = "";  //= defaultDataCode;

            var alphabet = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            //Add sorting index
            for (var i = 0; i < showDataCode.length; i++) {
                //alert(defaultDataCode.indexOf(showDataCode[i]) + "," + showDataCode[i]);
                showDataCode[i] = alphabet[defaultDataCode.indexOf(showDataCode[i])] + "," + showDataCode[i];
			    
			}
			
			//Sort
			showDataCode.sort();
			
			
			for (var i = 0; i < showDataCode.length; i++) {

			    //Remove Sorting index
	            showDataCode[i] = showDataCode[i].substring(showDataCode[i].indexOf(",") + 1)
	            //alert(showDataCode[i]);
	            
	            //Make new string
	            newDataCode = newDataCode + showDataCode[i] + "|";
	            
	        }


	        dataCode = newDataCode;
			
			//alert("END: " + newDataCode);
	
	
	
	
        AddSoldiers();
        }
        
		

		
        function GetMap() {

            map = new VEMap('myMap');
            map.SetCredentials("Anb__MvB46Psqtu9_tkGhUM9EcKFbkpugx-DFNjq_ZzL5AYB_sjh1wZAYbMjMl-q");
            map.SetDashboardSize(VEDashboardSize.Small);
            map.LoadMap(new VELatLong(defaultLat, defaultLong), defaultZoom ,defaultView ,false);

            //***new code added by andrew***
            //map.AttachEvent("onstartzoom", EventStartZoom);
            //map.AttachEvent("onchangeview", EventViewChange);
            //******************************

            map.AttachEvent("onendpan", AddSoldiers);
            map.AttachEvent("onendzoom", AddSoldiers);
          
            map.AttachEvent("onendzoom", function(obj) { zoomControl(obj); });
            
            
            AddSoldiers();

            map.AddShapeLayer(layer);

        }
        
        function zoomControl( obj ) {
            var currentZoom = obj.zoomLevel;
		
            if(currentZoom > zoomMax) {
                map.SetZoomLevel(zoomMax);
            } 
            else if(currentZoom < zoomMin) {
                map.SetZoomLevel(zoomMin);
            }
        }

        function PlacePinsOnMap(newdataCode) {
            
                //Retrieve the boundaries of the mapview
                var ulPixel = new VEPixel(0, 0);
                var brPixel = new VEPixel(mapWidth, mapHeight);
                var ulLatLong = map.PixelToLatLong(ulPixel);
                ulLat = ulLatLong.Latitude;
                ulLong = ulLatLong.Longitude;
                var brLatLong = map.PixelToLatLong(brPixel);
                brLat = brLatLong.Latitude;
                brLong = brLatLong.Longitude;
                
                if (showItemList == 1) {
                giveVBulbrLatLongs();
                }
                
                //Build the URL
                //The random URL-parameter avoids caching

                var url = "/mapping/"; 
                url += "GeocodeSoldiers2.ashx?";
                url += "ulLat=" + ulLat;
                url += "&ulLong=" + ulLong;
                url += "&brLat=" + brLat;
                url += "&brLong=" + brLong;
                url += "&mcat=" + newdataCode;
                url += "&random=" + Math.random();
                //alert(url);
                //Get the appropriate XMLHTTP object for the browser
                var xmlHttp = GetXmlHttp();

                //if we have a valid XMLHTTP object
                if (xmlHttp) {

                    xmlHttp.open("GET", url, true);

                    //set the callback
                    xmlHttp.onreadystatechange = function() {

                        if (xmlHttp.readyState == 4) //4 is a success
                        {

                            //server code creates JavaScript "on the fly" for us to
                            //execute

                            var result = xmlHttp.responseText;
                            if (result.indexOf('^^') > -1) {
                                result = result.ReplaceAll('^^', '"');
                                }
                            if (result.indexOf('~~') > -1) {  
                                result = result.ReplaceAll("~~", "\\\'");
                            }
                            //alert(result);

                            eval(result);

                            document.getElementById("divCounter").innerHTML = SoldierCount + " Map Items";
                            //document.getElementById("divItemList").innerHTML = strItemList;

                            if (SoldierCount <= 300) {


                                document.getElementById("divTooMany").setAttribute("style", "display:none;");
                            }
                            else {

                                document.getElementById("divTooMany").setAttribute("style", "display:block;");
                                //***new code added by andrew***


                                //******************************
                            }

                            // var myFucn = new Function(result);
                            // myFucn();

                        }
                    }
                    xmlHttp.send(null);

                }
                

        }

        //***new code added by andrew***
        function CreateLayer() {
            //Create the custom layer for the map dynamically on the map surface 
            myLayer = document.createElement('div');
            myLayer.style.position = "absolute";
            myLayer.style.top = "0px";
            myLayer.style.left = "0px";
            myLayer.style.width = mapWidth + "px";
            myLayer.style.height = mapHeight + "px";
            myLayer.style.zIndex = 1000;
            map.AddCustomLayer(myLayer);
        }

        function DeleteLayer() {
            if (myLayer != null) {
                map.RemoveCustomLayer(myLayer);
                myLayer = null;
            }
        }

        //Clear the shapes
        function ClearShapes() {
            //***new code added by andrew***
            if (myLayer != null) {
                myLayer.innerHTML = '';
            }
            //******************************        
            

        }

/*
        //View Change Event handler
        function EventViewChange() {
            //alert(SoldierCount); //bug= has previous count as "addsoldiers" hasn't run yet; need to add back in the separate code for getting the count!!
           alert("blabla");
		    if (SoldierCount > 300) {
                //if zoom level changed, then redraw the shapes, otherwise do nothing -- the map will position the pins on pan properly 
                var currentZoomLevel = map.GetZoomLevel();
                if (previousZoomLevel != currentZoomLevel) {
                    previousZoomLevel = currentZoomLevel;
                    //ClearShapes();
                    AddSoldiers();

                }

            }
            else {

                AddSoldiers();
            }
           
            //GetTotals();
            ////ClearShapes();
            ////RedrawShapes();
        }
*/

        //Start Zoom event handler 
        function EventStartZoom() {
            //When zoom is staretd clear the shapes before zoom since they will need to be redrawn
            ClearShapes();

        }        
        //******************************
        
        function AddSoldiers() {
            layer.DeleteAllShapes();
            
            //***new code added by andrew***
            //ClearShapes();
            //******************************
            PlacePinsOnMap(dataCode);

        }

        function GetXmlHttp() {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {

                    if (typeof XMLHttpRequest != "undefined") {
                        return new XMLHttpRequest();
                    }
                    else {
                        return null;
                    }
                }
            }

        }
        
//        function GetTotals() {
//            //Retrieve the boundaries of the mapview
//            var ulPixel = new VEPixel(0, 0);
//            var brPixel = new VEPixel(mapWidth, mapHeight);
//            var ulLatLong = map.PixelToLatLong(ulPixel);
//            var ulLat = ulLatLong.Latitude;
//            var ulLong = ulLatLong.Longitude;
//            var brLatLong = map.PixelToLatLong(brPixel);
//            var brLat = brLatLong.Latitude;
//            var brLong = brLatLong.Longitude;
//        
//            var url = "/mapping/";
//            url += "GetGeoTotals2.ashx?";
//            url += "ulLat=" + ulLat;
//            url += "&ulLong=" + ulLong;
//            url += "&brLat=" + brLat;
//            url += "&brLong=" + brLong;
//            url += "&mcat=SD";
//            url += "&random=" + Math.random();
//            
//            alert(url);
//            //Get the appropriate XMLHTTP object for the browser
//            var xmlHttp2 = GetXmlHttp();

//            //if we have a valid XMLHTTP object
//            if (xmlHttp2) {

//                xmlHttp2.open("GET", url, true);

//                //set the callback
//                xmlHttp2.onreadystatechange = function() {

//                    if (xmlHttp2.readyState == 4) //4 is a success
//                    {
//                        //server code creates JavaScript "on the fly" for us to
//                        //execute using eval()
//                        var result = xmlHttp2.responseText;
//                        eval(result);
//                        document.getElementById("divCounter").innerHTML = "Count: " + SoldierCount;
//                        if (SoldierCount <= 300) {
//                            PlacePinsOnMap();
//                            document.getElementById("divTooMany").setAttribute("style", "display:none;");
//                        }
//                        else {
//                            document.getElementById("divTooMany").setAttribute("style", "display:block;");
//                        }
//                    }
//                }
//                xmlHttp2.send(null);
//            }
//        }

        function gup(name) {
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var tmpURL = window.location.href;
            var results = regex.exec(tmpURL);
            if (results == null)
                return "";
            else
                return results[1];
        }
        function toggle(obj) {
            var el = document.getElementById(obj);
            if (el.style.display != 'none') {
                el.style.display = 'none';
            }
            else {
                el.style.display = '';
                if (document.getElementById('GetMapNum').value == 'unused') {
                    GetMap();
                    document.getElementById('GetMapNum').value = 'used';
                }
            }
        }
        
        function MapResize() //resize
        {
            if (isFullScreen == 1)
            {
                if (map != null)
                {    
                    if( typeof( window.innerWidth ) == 'number' )
                    {
                    //Non-IE
                    map.Resize(window.innerWidth,window.innerHeight);
                    } 
                    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
                    {
                    //IE 6+ in 'standards compliant mode'
                    map.Resize(document.documentElement.clientWidth,document.documentElement.clientHeight);
                    }
                }
            }
        }


        function MapGetDirections(startAddress, endAddress) {
            var options = new VERouteOptions;

            // Otherwise what's the point?
            options.DrawRoute = true;

            // So the map doesn't change:
            options.SetBestMapView = true;

            // Call this function when map route is determined:
            options.RouteCallback = ShowTurns;

            // Show as miles
            options.DistanceUnit = VERouteDistanceUnit.Mile;

            // Show the disambiguation dialog
            options.ShowDisambiguation = true;

            map.GetDirections([startAddress, endAddress], options);

        }

        function ShowTurns(route) {
            var turns = "<h3>Turn-by-Turn Directions</h3>";

            turns += "<p><b>Distance:</b> " + route.Distance.toFixed(1) + " miles";

            turns += "<br/><b>Time:</b> " + GetTime(route.Time) + "</p>";

            
                // Unroll route and populate DIV
                var legs = route.RouteLegs;
                var leg = null;
                var turnNum = 0;  // The turn #

                // Get intermediate legs
                var i2 = 0;
                //for (var i = 0; i < legs.length; i++) {
                    // Get this leg so we don't have to derefernce multiple times
                    leg = legs[i2];  // Leg is a VERouteLeg object

                    var legNum = i2 + 1;
                    //turns += "<br/><b>Distance for trip " + legNum + ":</b> " + leg.Distance.toFixed(1) + " miles" +
                     //      "<br/><b>Time for leg " + legNum + ":</b> " + GetTime(leg.Time) + "<br/><br/>";

                    // Unroll each intermediate leg
                    var turn = null;  // The itinerary leg
                    var legDistance = null;  // The distance for this leg

                    for (var j = 0; j < leg.Itinerary.Items.length; j++) {
                        turnNum++;

                        turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object

                        turns += "<b>" + turnNum + "</b>\t" + turn.Text;

                        legDistance = turn.Distance;

                        // So we don't show 0.0 for the arrival
                        if (legDistance > 0) {
                            // Round distances to 1/10ths
                            turns += " (" + legDistance.toFixed(1) + " miles";

                            // Append time if found
                            if (turn.Time != null) {
                                turns += "; " + GetTime(turn.Time);
                            }

                            turns += ")<br/>";
                        }
                    }

                   // turns += "<br/>";
                //}

                // Populate DIV with directions
                SetDirections(turns);
            
        }

        // time is an integer representing seconds
        // returns a formatted string
        function GetTime(time) {
            if (time == null) {
                return ("");
            }

            if (time > 60) {                                 // if time == 100
                var seconds = time % 60;       // seconds == 40
                var minutes = time - seconds;  // minutes == 60
                minutes = minutes / 60;    // minutes == 1


                if (minutes > 60) {                                     // if minutes == 100
                    var minLeft = minutes % 60;        // minLeft    == 40
                    var hours = minutes - minLeft;   // hours      == 60
                    hours = hours / 60;          // hours      == 1

                    return (hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
                }
                else {
                    return (minutes + " minutes, " + seconds + " seconds");
                }
            }
            else {
                return (time + " seconds");
            }
        }

        function SetDirections(s) {
            document.getElementById("directions").innerHTML = s;
  
        }


