//-------------------------------------------
//javascript File Containing embedable Map functions
// Author Paul.hann@dundeecity.gov.uk date: March 09
//-------------------------------------------

//Globals
var myMap = '';
var origCopyright;
var navToolbar; //needed for zooming in
var factor = 50; // used with zoomtoPoint to create extent
var curScale;
//listeners

var IdentifyListener;
var zoomListner;
var editListener;

var nIden = 0;
var idenCount = 0;
var toggleWidth;
var hasResults = false;

var PopupMap;

var isNavHiden = false;
var isButtsHiden = false;

//xmlconfig
var MapConfig, myObject, layerLoadCount = 0;
var timer;
//Config Arrays
var myLayers = new Array();
var myIdentifys = new Array();
var myResults = new Array();
var LayerArray = new Array();
var myFinds = new Array();
var ID;

var editLocGraphic;

var infoWindowWidth = 250;
var infoWindowHeight = 160;
var hideMap = false;
var APLayer = "", LegendDef;

var MovGraphic, MoveGraphicLayer;
//dojo Includes
dojo.require("esri.map");
dojo.require("esri.tasks.identify");
dojo.require("esri.tasks.query");
dojo.require("esri.tasks.find");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.TitlePane");
dojo.require("dojo.fx");
dojo.require("dojox.widget.FisheyeList");
dojo.require("dojo.dnd.Mover");
dojo.require("dojo.dnd.Moveable");
dojo.require("dojo.dnd.move");
var m1, m2, fadeIn, fadeOut, wipeOut, wipeIn, slideRight, slideLeft, animOut, animIn;
var origGraphic;

//Added Aug 6th because problem with Avail now and TPO not printing without this variable.
if (typeof printmapname === 'undefined')
{var printmapname = "Location Map";}

var initDND = function(){
	//*******************************************************
	//sets up Movable components of map and animation for the navigation bar
	//*******************************************************
	
    if (dojo.byId("PopupMap") != null) { // see if using movable navigation or not
        PopupMap = new dojo.dnd.Moveable("PopupMap", {
            handle: "PopupMaphandle"
        });
        
        //used to set new coords for fisheye tool
        
        dojo.connect(PopupMap, "onMoveStop", function(mover){
           if (dijit.byId("butStrip") != null ) { dijit.byId("butStrip")._calcHitGrid();}
        });
        
        pfadeOut = dojo.fadeOut({
            node: "PopupMap",
            duration: 500,
            onEnd: function(){
              if (dijit.byId("butStrip") != null ) { dijit.byId("butStrip")._calcHitGrid();}
            }
        });
        pfadeIn = dojo.fadeIn({
            node: "PopupMap",
            duration: 1000,
            onEnd: function(){
                if (dijit.byId("butStrip") != null ) { dijit.byId("butStrip")._calcHitGrid();}
            }
        });
        pwipeOut = dojo.fx.wipeOut({
            node: "PopupMap",
            duration: 500
        });
        pwipeIn = dojo.fx.wipeIn({
            node: "PopupMap",
            duration: 500
        });
        pslideRight = dojo.fx.slideTo({
            node: "PopupMap",
            duration: 500,
            left: 10,
            top: -10
        });
        pslideLeft = dojo.fx.slideTo({
            node: "PopupMap",
            duration: 500,
            left: -1,
            top: -45
        });
        PManimOut = dojo.fx.combine([pfadeOut, pwipeOut, pslideRight]);
        PManimIn = dojo.fx.combine([pfadeIn, pwipeIn, pslideLeft]);
        
    }

    if (dojo.byId("Moveable1") != null) { // see if using movable navigation or not
        m1 = new dojo.dnd.Moveable("Nav_Control", {
            handle: "handle1"
        });
        
        //need to set new coords for fisheye tool
        
        dojo.connect(m1, "onMoveStop", function(mover){
           if (dijit.byId("butStrip") != null ) { dijit.byId("butStrip")._calcHitGrid();}
        });
        
        fadeOut = dojo.fadeOut({
            node: "Moveable1",
            duration: 500,
            onEnd: function(){
                dojo.byId("Nav_img").src = "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomout.png";
            }
        });
        fadeIn = dojo.fadeIn({
            node: "Moveable1",
            duration: 500,
            onEnd: function(){
                dojo.byId("Nav_img").src = "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png";
            }
        });
        wipeOut = dojo.fx.wipeOut({
            node: "Moveable1",
            duration: 500
        });
        wipeIn = dojo.fx.wipeIn({
            node: "Moveable1",
            duration: 500
        });
        slideRight = dojo.fx.slideTo({
            node: "Moveable1",
            duration: 500,
            left: 20,
            top: -40
        });
        slideLeft = dojo.fx.slideTo({
            node: "Moveable1",
            duration: 500,
            left: -1,
            top: -45
        });
        animOut = dojo.fx.combine([fadeOut, wipeOut, slideRight]);
        animIn = dojo.fx.combine([fadeIn, wipeIn, slideLeft]);
    }

};
dojo.addOnLoad(dojo.byId("PopupMap"), initDND)



function myfadeOut(){
	//*******************************************************
	//sets up fade out for the navigation bar
	//*******************************************************
    if (dojo.byId("Nav_img").src == "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomout.png") {
        animIn.play();
        
        
    }
    else {
        animOut.play();
    }
   if (dijit.byId("butStrip") != null ) { dijit.byId("butStrip")._calcHitGrid();}
}


//function to Load the map in the div.        
function mapInit(){
 
	
    if (myMap == '') // check if map exists already
    {
          
        if (hideMap) {
            dojo.byId("PopupMap").style.left = "-3000px";
            dojo.byId("PopupMap").style.top = "-600px";
            if (dojo.byId("tmp") != null){         dojo.byId("tmp").style.height = '1px';}
            
        };
		////Get Mapconfig Oject //getJsonObject in Prototype.js  
        
	MapConfig = getJsonObject(xmlPath, "Map").Map;
  
        ////Set the copyright statement
        setCopyright();
        
        ////initialise Layers and load map
        InitMapServiceLayers(ObjectToArray(MapConfig.MapServiceLayers[0].MapServiceLayer));
        
        if (dojo.byId("nav2") != null) {
            FEinit();
        }
        
        //// speed up pan   
        esriConfig.defaults.map.panDuration = 10; //time in milliseconds; default is 250 
        //// handlers
        
        // resizing of map
        dojo.connect(window, "onresize", function(){//connect to window's resize event
            clearTimeout(timer);//clear any existing resize timer
            timer = setTimeout(function(){
                myMap.resize();
                myMap.reposition();
            }, 500);//create new resize timer with delay of 500 milliseconds
        });

	dojo.query(".dijitSplitter").forEach(function(splitter) {
  dojo.connect(splitter, "onmouseup", function(){myMap.resize();});});



        // Tasks
        
        ////IE6 FIXES
        //Different Navbar image - ie 6 does not do transparencies
        if (Prototype.Browser.IE && getIEVersionNumber() < 7) {
            try {
                //document.getElementById("NavIMG").src = EnvPath + "dcc_GIS_Config/images/NAV2.PNG";
                //document.getElementById("NavIMG").useMap = "#NavIE6";
            } 
            catch (err) {
            }
        }
        
    }
    
}

dojo.addOnLoad(mapInit);


function InitMapServiceLayers(arrLayers)// initialises the layers required in the service, then loads the map and adds the map service layers
{

    myLayers = new Array(arrLayers.length - 1);
    
    for (i = 0; i < arrLayers.length; i++) {
    
        //get and resolve url
        myUrl = '';
        fixurl = (arrLayers[i].url).split(/\\/);
        for (var z = 0; z < fixurl.length; z++) {
            myUrl += fixurl[z];
        }
        // force use of dynamic AP whilst cache is updating
      /*   if (arrLayers[i].id == 'AerialPhoto' && arrLayers[i].type == 'Tiled' ) {
          arrLayers[i].type = 'Dynamic';
          myUrl = "http://mapsOnline.dundeeCity.gov.uk/arcgis/rest/services/AerialPhotoD/MapServer";
          }*/
          // end force  
        myObject = new Object();
        if (arrLayers[i].type == 'Tiled') {
        
            myObject.Opacity = 1;
            myTMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer(myUrl);
            myObject.Layer = myTMapServiceLayer;
            myObject.Label = arrLayers[i].id;
            myObject.Type = arrLayers[i].type;
            if (typeof arrLayers[i].SwatchPath != 'undefined') {
                fixswatch = (arrLayers[i].SwatchPath).split(/\\/);
                mySwatch = "";
                for (var z = 0; z < fixswatch.length; z++) {
                    mySwatch += fixswatch[z];
                }
                myObject.SwatchPath = mySwatch;
            }
            else {
                myObject.SwatchPath = "";
            }
            if (arrLayers[i].id == 'AerialPhoto' || arrLayers[i].id == 'AerialPhotoD') {
                APLayer = myObject.Layer;
            }
            if (typeof arrLayers[i].hide != 'undefined') {
                myObject.Layer.visible = false;
                myObject.Layer.visibleLayers = "";
      
            }
            myLayers[i] = myObject;
        }
        else 
            if (arrLayers[i].type == 'Dynamic') {
                
                myDMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(myUrl, {
                    transparent: true
                });
                
                myObject.Opacity = 1;
                myDMapServiceLayer.setDisableClientCaching(true);
                //myDMapServiceLayer.setImageFormat("png8");
                if (typeof arrLayers[i].Opacity != "undefined") {
                    myDMapServiceLayer.setOpacity(arrLayers[i].Opacity);
                    myObject.Opacity = arrLayers[i].Opacity;
                }
          
                myLayers[i] = myDMapServiceLayer;
                myObject.Layer = myDMapServiceLayer;
                myObject.Label = arrLayers[i].id;
                myObject.Type = arrLayers[i].type;
                if (typeof arrLayers[i].SwatchPath != 'undefined') {
                    fixswatch = (arrLayers[i].SwatchPath).split(/\\/);
                    mySwatch = "";
                    for (var z = 0; z < fixswatch.length; z++) {
                        mySwatch += fixswatch[z];
                    }
                    myObject.SwatchPath = mySwatch;
                }
                else {
                    myObject.SwatchPath = "";
                }
                if (arrLayers[i].id == 'AerialPhoto' || arrLayers[i].id == 'AerialPhotoD') {
                APLayer = myObject.Layer;
            }
            if (typeof arrLayers[i].hide != 'undefined') {
                myObject.Layer.visible = false;
                myObject.Layer.visibleLayers = "";
      
            }
                myLayers[i] = myObject;
                
            }
            
        //listener to fire once ALL layers loaded
      
         dojo.connect(myLayers[i].Layer, "onError", function(service){
              layerLoadCount++;
              alert("Unable to load all map layers. Error: " + service.details[0])
                if (layerLoadCount == (arrLayers.length)) {
               
                    LoadMapAndLayers();
                }
            });
            
        if (myLayers[i].Layer.loaded) {
            layerLoadCount++;
            if (layerLoadCount == (arrLayers.length)) {
            
                LoadMapAndLayers();
            }
            
        }
        else {
            dojo.connect(myLayers[i].Layer, "onLoad", function(service){
                layerLoadCount++;
                if (layerLoadCount == (arrLayers.length)) {
               
                    LoadMapAndLayers();
                }
            });
        }
    }
}


function LoadMapAndLayers()//fired once all layers are initialised
{
  
    // create the map     
    if (typeof StartX == "undefined" && typeof ResultsFeatString == "undefined") // no specified zoom
    {
        myMap = new esri.Map(MapConfig.id, {
            slider: false
        });
    }
    else {
        if (typeof ResultsFeatString != "undefined") // zoom to a feature
        {
          
            //configured for single feature results
            var objResults = dojo.fromJson(ResultsFeatString);
            if (objResults.results.length > 0) {
                var graphic = esri.geometry.fromJson(objResults.results[0].geometry);
                if (objResults.results[0].geometryType == "esriGeometryPoint") {
                    myExtent = new esri.geometry.Extent(graphic.x - factor, graphic.y - factor, graphic.x + factor, graphic.y + factor, new esri.SpatialReference({
                        wkid: 27700
                    }));
                    
                }
                else {
                    myExtent = graphic.getExtent();
                }
                myMap = new esri.Map(MapConfig.id, {
                    slider: false,
                    extent: myExtent
                });
            }
            else {
                if (typeof StartX != "undefined") // zoom to an easting & northing
                {
                    myExtent = new esri.geometry.Extent(graphic.x - factor, graphic.y - factor, graphic.x + factor, graphic.y + factor, new esri.SpatialReference({
                        wkid: 27700
                    }));
                    myMap = new esri.Map(MapConfig.id, {
                        slider: false,
                        extent: myExtent
                    });
                }
            }
            
            
        }
        
        
    }
    
    
    
    AddMapServiceLayers(myMap, myLayers);
     //Remember the default info window sizes
      myMap.resize();
    myMap.reposition();
     if (typeof LegendScriptLoaded != 'undefined'){CreateLayerInfo();}// from legend.js
     if (typeof IntranetScriptLoaded != 'undefined'){LoadIGSTools();}// from intranetgis.js
    
   
    if (typeof dojo.byId("splitLoad") != 'undefined' && dojo.byId("splitLoad") != null )
    {
      dojo.byId("splitLoad").style.display = 'none';
      dijit.byId("mainBC").resize();
    
    } 
   


}

function AddMapServiceLayers(theMap, ArrayLayers)//loop through array of layers and add them one by one
{
  

	for (n = 0; n < ArrayLayers.length; n++) {
        theMap.addLayer(ArrayLayers[n].Layer);
    }
    
    
    
    dojo.byId("loadingIMG").style.display = "none";
    
    if (typeof showGraphic != "undefined") {
        var objResults = dojo.fromJson(ResultsFeatString);
        if (objResults.results.length > 0) {
            var graphic = esri.geometry.fromJson(objResults.results[0].geometry);
 		if (objResults.results[0].geometryType == "esriGeometryPoint") {
                	
	                showPrintableImageOnMap( graphic,objResults.results[0].attributes.ADDRESS,true, "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/home.png" ,"LocMap", 0, "0:UPRN='" + curUPRN + "'");
	                origGraphic = graphic;
                }
                else if (objResults.results[0].geometryType == "esriGeometryPolygon")
                {
                     symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.0]));
                     var pgraphic = new esri.Graphic(graphic, symbol, "", "")
                     myMap.graphics.add(pgraphic);
                }     
                else
                {
         	       symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 1);
          	      var pgraphic = new esri.Graphic(graphic, symbol, "", "")
          	      myMap.graphics.add(pgraphic);
                }

            
        }
    }
    if (typeof MapConfig.tasks != "undefined" && MapConfig.tasks[0] != null) {

        InitTasks();
    }
}

function InitTasks()//funtion to initialise Identify & Query Tasks
{
    var arrTasks;
    nIden = 0;
    nFinds = 0;

    try {
        arrTasks = ObjectToArray(MapConfig.tasks[0].task);
    } 
    catch (err) {
    }
    
    
    for (z = 0; z < arrTasks.length; z++) {
        myObject = new Object();
        switch (arrTasks[z].type) {
        
            case "Identify":
                //Change so that it can be used for any map service
                if (nIden == 0) {
                    IdentifyListener = dojo.connect(myMap, "onClick", doIdentify);
                }
                
                //get and resolve url
                myUrl = '';
                fixurl = (arrTasks[z].service).split(/\\/);
                for (l = 0; l < fixurl.length; l++) {
                    myUrl += fixurl[l];
                }
                
                identifyTask = new esri.tasks.IdentifyTask(myUrl);
                myObject.IdentifyTask = identifyTask;
                myObject.detailsTitle = arrTasks[z].detailsTitle;
                myObject.id = arrTasks[z].id;
                myObject.MoreFunction = arrTasks[z].MoreFunction;
                myObject.service = arrTasks[z].service;
                identifyParams = new esri.tasks.IdentifyParameters();
                identifyParams.dpi = 96;
                identifyParams.width = myMap.width;
                identifyParams.height = myMap.height;
                identifyParams.tolerance = 20;
                identifyParams.returnGeometry = arrTasks[z].returnGeometry;
                identifyParams.layerOption = eval(arrTasks[z].layerOption);
                
                identifyParams.layerIds = SetLayerIds(arrTasks[z]);
                myObject.IdentifyParams = identifyParams;
                myIdentifys[nIden] = myObject;
                nIden++;
                
                break;
            case "Find":
                //Change so that it can be used for any map service
                //get and resolve url
                myUrl = '';
                fixurl = (arrTasks[z].service).split(/\\/);
                for (l = 0; l < fixurl.length; l++) {
                    myUrl += fixurl[l];
                }
                
                findTask = new esri.tasks.FindTask(myUrl);
                myObject.FindTask = findTask;
                myObject.id = arrTasks[z].id;
                myObject.ZoomMethod = arrTasks[z].ZoomMethod;
                findParams = new esri.tasks.FindParameters();
                
                findParams.layerIds = SetLayerIds(arrTasks[z]);
                findParams.contains = false;
                sFields = '';
                fixFields = (arrTasks[z].searchFields).split(/\\u0027/);
                for (l = 0; l < fixFields.length; l++) {
                    sFields += l > 0 ? "'" + fixFields[l] : fixFields[l];
                }
                findParams.searchFields = eval(sFields);
                findParams.returnGeometry = arrTasks[z].returnGeometry;
                
                myObject.findParams = findParams;
                myFinds[nFinds] = myObject;
                nFinds++;
                
                break;
                
                
        }
        
    }
    
    
}

function arr_match(a1, a2)
{
  var array3 = new Array();
  for(var i=0;i<a1.length;i++) {
  for(var j=0;j<a2.length;j++) {
  if(a2[j] == a1[i]) {
  array3.push(a2[j]);
  }
  }
  }
  return array3;
}


function SetLayerIds(task)// used to define the layers used in an task
{
    taskURL = '';
    
    fixurlt = (task.service).split(/\\/);
    for (l = 0; l < fixurlt.length; l++) {
        taskURL += fixurlt[l];
    }
    if (typeof task.layerIds != 'undefined' )// when setting from xml
    {
      if (task.layerIds == null || task.layerIds == "Visible")// if there is no layerids tag set in teh xml or it is set to 'visible'
      {
          for (n = 0; n < myLayers.length; n++) {
              if (myLayers[n].Layer.url.toUpperCase() == taskURL.toUpperCase()) {
                  return myLayers[n].Layer.visibleLayers;
                  break;
              }
          }
          
          return null;
      }
      else {
          return eval(task.layerIds);
      }
    }
    else //setting from visible layers
    {
        for (n = 0; n < myLayers.length; n++) {
              if (myLayers[n].Layer.url.toUpperCase() == taskURL.toUpperCase()) {
                 
                  return arr_match(myLayers[n].Layer.visibleLayers, task.IdentifyParams.layerIds);
                  break;
              }
          }
          
          return null;
    
    }
    
    
    
}

function doIdentify(evt){

    scale = Math.round((myMap.extent.xmax-myMap.extent.xmin));
   
      if(scale < 500){ tolerance = 20;}
      else if(scale < 1000){ tolerance = 20;}
       else if(scale < 3000){ tolerance = 16;}
       else if(scale < 5000){ tolerance = 15;}
       else if(scale < 10000){ tolerance = 13;}
       else if(scale > 10000){ tolerance = 3;}
  
    
//alert(scale);

    hasResults = false;
    myPointOnMap = new esri.geometry.Point(evt.mapPoint.x, evt.mapPoint.y, new esri.SpatialReference({
        wkid: 27700
    }));
    idenCount = 0;
    myResults = new Array();
    for (idn = 0; idn < myIdentifys.length; idn++) {
        myIdentifys[idn].IdentifyParams.mapExtent = myMap.extent;
        myIdentifys[idn].IdentifyParams.geometry = myPointOnMap;
        myIdentifys[idn].IdentifyParams.tolerance = tolerance;
        var origIds =  myIdentifys[idn].IdentifyParams.layerIds;
        myIdentifys[idn].IdentifyParams.layerIds = SetLayerIds(myIdentifys[idn]);
        
        myIdentifys[idn].IdentifyTask.execute(myIdentifys[idn].IdentifyParams, function(idResults){
            var idenResultObj = new Object;
            
            idenResultObj.HasResults = (idResults[0] != undefined);
            hasResults = hasResults || idenResultObj.HasResults;
            idenResultObj.Results = idResults;
            idenResultObj.count = idResults.length;
            myResults[idenCount] = idenResultObj;
            idenCount++;
            
            if (idenCount == (myIdentifys.length)) {
                addToMap(evt);
            }
        });
         myIdentifys[idn].IdentifyParams.layerIds = origIds;
    }
    
    
}

function addToMap(evt){

    //
    myMap.infoWindow.resize(infoWindowWidth, infoWindowHeight);
    
    if (hasResults) {
        myMap.infoWindow.setTitle(createUniqueLayerList());
        myMap.infoWindow.setContent(getResultContent(LayerArray[0].ResultArrPos, LayerArray[0].LayerName));
        
        myMap.infoWindow.show(evt.screenPoint, myMap.getInfoWindowAnchor(evt.screenPoint));
    }
    else {
    
        myMap.graphics.clear();
        myMap.infoWindow.hide();
        
    }
    
}

function createUniqueLayerList(){
    LayerArray = new Array();
    nlyrs = 0
    
    titleString = "<div class='infoResultHeader'>Select Layer: <select style='width:110px' id='lyrList' onchange='SelectLayer(this)'>";
    
    for (nRes = 0; nRes < myResults.length; nRes++) {
        if (myResults[nRes].HasResults) {
        
        
        
            for (mRes = 0; mRes < myResults[nRes].Results.length; mRes++) {
                var LyrObj = new Object;
                LyrObj.LayerName = myResults[nRes].Results[mRes].layerName.substring(myResults[nRes].Results[mRes].layerName.indexOf(".") + 1);
                LyrObj.ResultArrPos = nRes;
                LayerArray[nlyrs] = LyrObj;
                nlyrs++
            }
            
        }
        
        
    }
    
    LayerArray = uniqueArr(LayerArray);
    for (lList = 0; lList < LayerArray.length; lList++) {
        titleString += "<option id='" + LayerArray[lList].ResultArrPos + "'>" + LayerArray[lList].LayerName + "</option>";
    }
    
    
    titleString += "</select>";
    return titleString;
}

function SelectLayer(myselect){
    myMap.infoWindow.setContent(getResultContent(myselect.options[myselect.selectedIndex].id, myselect.options[myselect.selectedIndex].text));
    
    
}

function getResultContent(rsid, LayerName){

    var strdetail = 'Click to see attributes';
    if (myIdentifys[rsid].detailsTitle != null) {
        strdetail = myIdentifys[rsid].detailsTitle;
    }
    
    
    myMap.infoWindow.setContent("");
    var divString = "<div title='List of Results' class='InfoResultsListDiv'><ul> ";
    
    if (!(rsid < 0))// if RSID supplied i.e. Identify stores this to optimise display of results
    {
        var zRes = 0;
        
        for (zRes = 0; zRes < myResults[rsid].Results.length; zRes++) {
        
            if (myResults[rsid].Results[zRes].layerName == "DCC_MANAGER." + LayerName || myResults[rsid].Results[zRes].layerName == LayerName) {
            
                if (zRes % 2) {
                    divString += "<li onmouseover='HighlightFeature(myResults[" + rsid + "].Results[" + zRes + "].feature);'>";
                }
                else {
                    divString += "<li class='odds' onmouseover='HighlightFeature(myResults[" + rsid + "].Results[" + zRes + "].feature);'>";
                }
                divString += myResults[rsid].Results[zRes].value + "<font class='fontLink' title='" + strdetail + "'  onclick='showFeatureDetails(" + rsid + "," + zRes + " )' > (details...) </font>";
                //alert(myResults[rsid].Results[lRes].feature.attributes["Secondary Area"]);
            }
        }
    }
    else {
    
    }
    divString += "</ul></div>";
    return divString;
    
}

//Copied from www.developersnippets.com
function uniqueArr(a){
    temp = new Array();
    for (i = 0; i < a.length; i++) {
        if (!contains(temp, a[i].LayerName)) {
            temp.length += 1;
            var tmpObj = new Object;
            tmpObj.LayerName = a[i].LayerName;
            tmpObj.ResultArrPos = a[i].ResultArrPos;
            temp[temp.length - 1] = tmpObj;
            
        }
    }
    return temp;
}

//Will check for the Uniqueness
function contains(a, e){
    for (j = 0; j < a.length; j++) 
        if (a[j].LayerName == e) 
            return true;
    return false;
}

function showFeatureDetails(rsID, recID){
    if (myIdentifys[rsID].MoreFunction == null) {
        ////IE6 FIXES
        //Different Navbar image - ie 6 does not do transparencies and does not do zorder with selects
        if (Prototype.Browser.IE && getIEVersionNumber() < 7) {
            try {
                document.getElementById("lyrList").style.display = "none";
            } 
            catch (err) {
            }
        }
        
        
        var newdiv = document.createElement('div');
        newdiv.setAttribute('id', "ResultsDiv");
        
        newdiv.setAttribute('style', "width:" + MapConfig.width + "px; height:" + (parseFloat(MapConfig.height) + 25) + "px; position:absolute;z-index:200;");
        
        if (Prototype.Browser.IE) {
            newdiv.style.width = MapConfig.width;
            newdiv.style.height = parseFloat(MapConfig.height) + 25;
            newdiv.style.position = "absolute";
            newdiv.style.zIndex = 200;
        }
        
        
        
        strVal = "<div id='resultContents' style='left:" + ((MapConfig.width - 300) / 2) + "px; top:" + ((MapConfig.height - 300) / 2) + "px; '><table cellspacing=0 style='width:100%;'><thead> <tr height='20px'> <td style='padding-left:5px'> Results</td> <td align='right' style='cursor:pointer;' onclick='CloseResultsWindow(this);' title='Click to close'> <font color='blue' style='padding-right:10px;'>Close</font> </td> </tr> </thead><tr > <td colspan='2'> <div style='width:100%; height:265px;'><table>"
        for (att in myResults[rsID].Results[recID].feature.attributes) {
        
            strVal += "<tr><td width='50%' class='resultField'>" + att + "</td><td>" + myResults[rsID].Results[recID].feature.attributes[att] + "</td></tr>";
        }
        
        strVal += "</table></div></table></div>";
        newdiv.innerHTML = strVal;
        document.getElementById(MapConfig.id).appendChild(newdiv);
    }
    else {
        eval(myIdentifys[rsID].MoreFunction + "(" + rsID + "," + recID + ")");
    }
}


function CloseResultsWindow(myElem){

    ////IE6 FIXES
    //Different Navbar image - ie 6 does not do transparencies and does not do zorder with selects
    if (Prototype.Browser.IE && getIEVersionNumber() < 7) {
        try {
            document.getElementById("lyrList").style.display = "block";
        } 
        catch (err) {
        }
    }
    myElem.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(myElem.parentNode.parentNode.parentNode.parentNode.parentNode)
}

function toggleHiddenButtons(myElement)//Used to show the hidden buttons(dropdown div)  - fired by the more... button.
{
    theMoreBtn = dojo.byId("moreButton");
    theDiv = dojo.byId("HiddenButtons");
    
    //closeDivs(theDiv);
    
    if (theMoreBtn.value == "More...") {
    
        theDiv.className = "openMenuDiv";
        theDiv.style.display = "block";
        document.getElementById("HiddenButtons").style.top = "25px";
        document.getElementById("HiddenButtons").style.left = myElement.offsetLeft + "px";
        theMoreBtn.value = "More (x)";
        
        
    }
    else {
    
        //alert("here");
        //theDiv.className = "closedMenuDiv";
        theDiv.style.display = "none";
        theMoreBtn.value = "More...";
        
    }
    
    
    
    //Hide any other divs that are open...

}


function toggleDockButts()//used to hide / show the button bar
{

    if (isButtsHiden) {
        document.getElementById("butStrip").style.display = "block";
        document.getElementById("toggleButts").src = EnvPath + "dcc_GIS_Config/images/btToolbarCol.png";
        document.getElementById("btcol").style.left = toggleWidth;
        isButtsHiden = false;
    }
    else {
        document.getElementById("butStrip").style.display = "none";
        document.getElementById("toggleButts").src = EnvPath + "dcc_GIS_Config/images/btToolbarUnCol.png";
        toggleWidth = document.getElementById("btcol").style.left;
        document.getElementById("btcol").style.left = "0px";
        isButtsHiden = true;
    }
    
    
}


function setCopyright()//Loads current Copyright statement
{

    copyRight = getJsonObject(EnvPath + 'DCC_GIS_Config/XML/copyright.xml', 'smallMap');
    dojo.byId("Copyright").innerHTML = copyRight.smallMap.textcontent;
}


function goToFeaturesById(FindTaskId, Value, zoomIn){

    for (idf = 0; idf < myFinds.length; idf++) {
        if (myFinds[idf].id == FindTaskId) {
            ZoomMethod = myFinds[idf].ZoomMethod;
            myFinds[idf].findParams.searchText = Value;
            myFinds[idf].FindTask.execute(myFinds[idf].findParams, function(results){
            
                if (ZoomMethod != null) {
                    eval(ZoomMethod + '(results,' + zoomIn + ');');
                }
                else {
                    showFindResults(results);
                }
                
            });
            
        }
    }
    
    
    
    
}

function showFindResults(results){
    var totalExtent;
    
    myMap.graphics.clear();
    for (var i = 0, il = results.length; i < il; i++) {
        var curFeature = results[i];
        if (typeof curFeature.feature != 'undefined')
        { 
        graphic = curFeature.feature;
        }
        else
        {
        graphic = curFeature;
        
        }
        switch (graphic.geometry.type) {
            case "point":
                var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 5, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.25]));
                totalExtent = i == 0 ? new esri.geometry.Extent(parseFloat(graphic.geometry.x) - factor, parseFloat(graphic.geometry.y) - factor, parseFloat(graphic.geometry.x) + factor, parseFloat(graphic.geometry.y) + factor, myMap.spatialReference) : totalExtent.union(new esri.geometry.Extent(parseFloat(graphic.geometry.x) - factor, parseFloat(graphic.geometry.y) - factor, parseFloat(graphic.geometry.x) + factor, parseFloat(graphic.geometry.y) + factor, myMap.spatialReference));
                break;
            case "polyline":
                var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 1);
                totalExtent = i == 0 ? graphic.geometry.getExtent() : totalExtent.union(graphic.geometry.getExtent());
                break;
            case "polygon":
                //var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NONE, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
                var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.25]));
                totalExtent = i == 0 ? graphic.geometry.getExtent() : totalExtent.union(graphic.geometry.getExtent());
                break;
        }
        graphic.setSymbol(symbol);
        myMap.graphics.add(graphic);
        
        
        
        
        
    }
    
    myMap.setExtent(totalExtent.expand(2), true);
    myMap.resize();
    myMap.reposition();
    
}

function gotoCAGPoint(UPRN,graphic){
    ID = UPRN;
    dojo.xhrGet({
        url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/CAG/CAG.asmx/GetTayCAGPoints&HouseNo=&HouseName=&STREET_NAME=&POSTCODE=&UPRN=" + UPRN + "&IncludeStreetRecords=&Filter=",
        load: function(response, ioArgs){
        
            tag = "CAGPoint";
            
            if (window.ActiveXObject) {
            
            
                Rows = response.getElementsByTagName(tag);
                
                address = Rows[0].childNodes[0].childNodes[0].nodeValue
                easting = Rows[0].childNodes[6].childNodes[0].nodeValue;
                northing = Rows[0].childNodes[7].childNodes[0].nodeValue;
                
            }
            else {
                Rows = response.getElementsByTagName(tag);
                
                address = Rows[0].childNodes[1].textContent;
                easting = Rows[0].childNodes[13].textContent;
                northing = Rows[0].childNodes[15].textContent;
            }
            
            
            var myPointOnMap = new esri.geometry.Point(easting, northing, new esri.SpatialReference({
                wkid: 27700
            }));
            if (graphic){
             zoomListner = dojo.connect(myMap, "onExtentChange", function(){
                showMovableGraphic(myPointOnMap);
               
                dojo.disconnect(zoomListner);
               
            })}
                        
            zoomToPoint(myPointOnMap);
            return response;
        },
        error: function(response, ioArgs){
        
            alert("address not Found");
            return response;
        },
        handleAs: "xml"
    });
    
    
    
    
   
}


function gotoEN(e, n ,graphic){
    
            
            var myPointOnMap = new esri.geometry.Point(e, n, new esri.SpatialReference({
                wkid: 27700
            }));
            if (graphic){
             zoomListner = dojo.connect(myMap, "onExtentChange", function(){
                showMovableGraphic(myPointOnMap);
               
                dojo.disconnect(zoomListner);
               
            })}
                        
            zoomToPoint(myPointOnMap);
             
    
    
    
   
}


function showCAGPoint(UPRN, zoomin){
    ID = UPRN;
    dojo.xhrGet({
        url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/CAG/CAG.asmx/GetTayCAGPoints&HouseNo=&HouseName=&STREET_NAME=&POSTCODE=&UPRN=" + UPRN + "&IncludeStreetRecords=&Filter=",
        load: function(response, ioArgs){
        
            tag = "CAGPoint";
            
            if (window.ActiveXObject) {
            
            
                Rows = response.getElementsByTagName(tag);
                
                address = Rows[0].childNodes[0].childNodes[0].nodeValue
                easting = Rows[0].childNodes[6].childNodes[0].nodeValue;
                northing = Rows[0].childNodes[7].childNodes[0].nodeValue;
                
            }
            else {
                Rows = response.getElementsByTagName(tag);
                
                address = Rows[0].childNodes[1].textContent;
                easting = Rows[0].childNodes[13].textContent;
                northing = Rows[0].childNodes[15].textContent;
            }
            
            
            var myPointOnMap = new esri.geometry.Point(easting, northing, new esri.SpatialReference({
                wkid: 27700
            }));
            
            zoomListner = dojo.connect(myMap, "onExtentChange", function(){
                // showPinOnMap(myPointOnMap, address, true);
                showPrintableImageOnMap( myPointOnMap,address,true, "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/home.png" ,"LocMap", 0, "0:UPRN='" + UPRN + "'");
                //showImageOnMap(myPointOnMap, address, true, "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/home.png");
                dojo.disconnect(zoomListner);
               
            })
            
            
            zoomToPoint(myPointOnMap);
            return response;
        },
        error: function(response, ioArgs){
        
            alert("address not Found");
            return response;
        },
        handleAs: "xml"
    });
    
    
    
    
   
}

function zoomToPoint(myPoint){

    var mextent = new esri.geometry.Extent(parseFloat(myPoint.x) - factor, parseFloat(myPoint.y) - factor, parseFloat(myPoint.x) + factor, parseFloat(myPoint.y) + factor, myPoint.spatialReference);
    myMap.setExtent(mextent.expand(1));
    myMap.resize();
    myMap.reposition();
    return mextent;
}

function zoomExtent(extent){
    myMap.setExtent(extent.expand(2));
}

function showInfoWindow(myMapPoint, width, height, title, content){
    var mypoint = myMap.toScreen(myMapPoint);
    myMap.infoWindow.setTitle(title);
    myMap.infoWindow.setContent(content);
    if (width != '' || height != '') {
        myMap.infoWindow.resize(width, height);
    }
    myMap.infoWindow.show(mypoint, myMap.getInfoWindowAnchor(mypoint));
    
    
}

function showPinOnMap(myPoint, LabelString, clearExisting){
    if (clearExisting) {
        myMap.graphics.clear();
    }
    //    var symbol  = new esri.symbol.SimpleMarkerSymbol().setSize(10).setColor(new dojo.Color([255,0,0]));
    var symbol = new esri.symbol.PictureMarkerSymbol("http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/pin-red-28x28.png", 28, 28);
    var TXTsymbol = new esri.symbol.TextSymbol(LabelString.replace(/%20/g, " "), new esri.symbol.Font(12, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_BOLDER, "Serif"), new dojo.Color("blue"));
    
    TXTsymbol.yoffset = -40;
    var graphic = new esri.Graphic(myPoint, symbol);
    myMap.graphics.add(graphic);
    myMap.graphics.add(new esri.Graphic(myPoint, TXTsymbol));
    
}


function showMovableGraphic(myPoint){
  
    var symbol  = new esri.symbol.SimpleMarkerSymbol().setSize(20).setColor(new dojo.Color([255,0,255,0.4]));
  
  
    if (typeof MoveGraphicLayer == "undefined") {
        
        MoveGraphicLayer = new esri.layers.GraphicsLayer();
        myMap.addLayer(MoveGraphicLayer);
    }
    MoveGraphicLayer.clear();
    
    MovGraphic = new esri.Graphic(myPoint, symbol);
    MoveGraphicLayer.add(MovGraphic);
  
    
}




function showImageOnMap(myPoint, LabelString, clearExisting, pathToImage){
    if (clearExisting) {
        myMap.graphics.clear();
        
        if (typeof isInternet != "undefined") {
            arrgLayers = myMap.graphicsLayerIds;
            
            for (var tgl = 0; tgl < arrgLayers.length; tgl++) {
            
                myMap.removeLayer(myMap.getLayer(arrgLayers[tgl]));
            }
        }
    }
    
    if (typeof isInternet == "undefined") {
        gLayer = myMap.graphics;
    }
    else {
    
        gLayer = new esri.layers.GraphicsLayer();
        myMap.addLayer(gLayer);
    }
    
    var symbol = new esri.symbol.PictureMarkerSymbol(pathToImage, 30, 44);
    var Boxsymbol = new esri.symbol.PictureMarkerSymbol("http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/infoLabel.png", 230, 55);
    var Closesymbol = new esri.symbol.PictureMarkerSymbol("http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png", 20, 20);
    
    symbol.yoffset = 20;
    Boxsymbol.yoffset = -33;
    Closesymbol.yoffset = -17;
    Closesymbol.xoffset = 102;
    
    
    var graphic = new esri.Graphic(myPoint, symbol);
    gLayer.add(graphic);
    
    gLayer.add(new esri.Graphic(myPoint, Boxsymbol));
    gLayer.add(new esri.Graphic(myPoint, Closesymbol));
    
    var lbl = LabelString.replace(/%20/g, " ");
    var lbll = 0;
    
    var ArrWords = lbl.split(" ");
    strLine = "";
    lbRow = 0;
    
    for (var lbi = 0; lbi < ArrWords.length; lbi++) {
        if (strLine.length + ArrWords[lbi].length < 28) {
            strLine += ArrWords[lbi] + " ";
        }
        else {
        
            TXTsymbol = new esri.symbol.TextSymbol(strLine, new esri.symbol.Font(11, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_NORMAL, "Arial"), new dojo.Color("black"));
            TXTsymbol.yoffset = -20 - (lbRow * 12);
            TXTsymbol.xoffset = -10;
            gLayer.add(new esri.Graphic(myPoint, TXTsymbol));
            lbRow++;
            strLine = ArrWords[lbi] + " ";
            
        }
        
        
    }
    
    
    TXTsymbol = new esri.symbol.TextSymbol(strLine, new esri.symbol.Font(11, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_NORMAL, "Arial"), new dojo.Color("black"));
    TXTsymbol.yoffset = -20 - (lbRow * 12);
    TXTsymbol.xoffset = -10;
    gLayer.add(new esri.Graphic(myPoint, TXTsymbol));
    
    
    if (typeof isInternet == "undefined") {
        dojo.connect(myMap.graphics, "onClick", function(evt){
            var g = evt.graphic;
            if (g.symbol.type == "picturemarkersymbol" && g.symbol.url == "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png") {
            
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].hide();
                }
            }
            else {
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].show();
                }
            }
            
        });
    }
    else {
        dojo.connect(gLayer, "onClick", function(evt){
            var g = evt.graphic;
            
            if (g.symbol.type == "picturemarkersymbol" && g.symbol.url == "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png") {
            
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].hide();
                }
            }
            else {
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].show();
                }
            }
            
            
        });
        
    }
    
    
}

function CreatePDF(minx, miny, maxx, maxy, orientation, mapService){

    minx = "&xmin=" + minx;
    miny = "&yMin=" + miny;
    maxx = "&xMax=" + maxx;
    maxy = "&yMax=" + maxy;
    orientation = "&orientation=" + orientation;
    Webservice = "&mapservice=" + mapService;
    
    url = "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_WEB_SERVICES/DCC_GIS_Services.asmx/CreateLoprPDF" + minx + miny + maxx + maxy + orientation + Webservice;
    new Ajax.Request(url, {
        method: 'get',
        asynchronous: false,
        onSuccess: function(response){
            myXml = response.responseXML;
            LoadPDF(myXml);
            
            
        },
        onFailure: function(response){
            alert('Error...' + response.responseText)
        }
    });
    
    
}

function LoadPDF(myXml){
    if (window.ActiveXObject) {
        pdfPath = myXml.childNodes[1].childNodes[0].nodeValue;
    }
    else {
        pdfPath = myXml.firstChild.textContent;
    }
    window.open(pdfPath, "LoPR2");
}


/*
 * override the dojo 1.2, 1.3 version of dojo._setOpacity to revert back to the dojo 1.1 implementation
 * this version doesnt allow multiple filters on an element, but it is free from the memory spike issue */
(function(){
    var d = dojo;
    if (dojo.isIE) {
        dojo._setOpacity = function(/*DomNode*/node, /*Number*/ opacity){
            if (opacity == 1) {
                var filterRE = /FILTER:[^;]*;?/i;
                node.style.cssText = node.style.cssText.replace(filterRE, "");
                if (node.nodeName.toLowerCase() == "tr") {
                    d.query("> td", node).forEach(function(i){
                        i.style.cssText = i.style.cssText.replace(filterRE, "");
                    });
                }
            }
            else {
                var o = "Alpha(Opacity=" + opacity * 100 + ")";
                node.style.filter = o;
            }
            if (node.nodeName.toLowerCase() == "tr") {
                d.query("> td", node).forEach(function(i){
                    i.style.filter = o;
                });
            }
            return opacity;
        };
    }
})();

function doZoom(direction){

    //If using tiled service, do zoom with levels
    //If using dymanic service, do zoom with extents
    //If using a mix, do zoom with LEVELS????
    
    arrLayers = ObjectToArray(MapConfig.MapServiceLayers[0].MapServiceLayer);
    
    for (i = 0; i < arrLayers.length; i++) {
    
        layerType = arrLayers[i].type;
        if (layerType.toUpperCase() == "TILED") {
            zoomType = "useLevel";
            break;
        }
        else {
            zoomType = "useExtent";
        }
        
    }
    
    if (zoomType == "useLevel") {
    
        if (direction == "in") 
            myMap.setLevel(myMap.getLevel() + 1);
        else 
            myMap.setLevel(myMap.getLevel() - 1);
        
    }
    else 
        if (zoomType == "useExtent") {
        
            if (direction == "in") 
                myMap.setExtent(myMap.extent.expand(0.4));
            else 
                myMap.setExtent(myMap.extent.expand(1.9));
            
        }
    
}

function createVisibleLayersList(theMapServiceLayer){

    //Create a list of visible layers
    //Get all the visible fc layers from each of the map service layers.
    
    theVisiblefcLayers = "";
    //for (n=0;n<myLayers.length;n++){
    
    for (var i = 0; i < theMapServiceLayer.visibleLayers.length; i++) {
    
        theLayerInfos = theMapServiceLayer.layerInfos;
        if ((theLayerInfos[theMapServiceLayer.visibleLayers[i]].name).indexOf("DCC_MANAGER") == -1) 
            theVisiblefcLayers = theVisiblefcLayers + theLayerInfos[theMapServiceLayer.visibleLayers[i]].name + ";";
        
    }
    // }
    
    return theVisiblefcLayers;
    
}

function createToggleLayerList(){

    //Interim function to create list of layers that can be toggled on or off.
    //this needs to be able to work with multiple map services.
    theHTML = "";
    
    //****This should be bottom up - reverse
    
    var visible = [];
    var items = [];
    for (n = (myLayers.length - 1); n > -1; n--) {
    
        theLayerInfos = myLayers[n].Layer.layerInfos;
        //Refresh so that the layer layerinfo is up to date.
        myLayers[n].Layer.refresh();
        for (var i = 0, il = theLayerInfos.length; i < il; i++) {
        
            info = theLayerInfos[i];
            
            //If dealing with a DCC_Manager layer it is an OS layer and don't want to give user option to turn on or off
            isChecked = "";
            if ((info.name.toUpperCase()).indexOf("DCC_MANAGER") == -1) {
                theStyle = "";
                type = "checkbox";
                theLabel = "<label class='toc' for='" + info.id + "'>" + info.name + "</label><br>";
                for (var p = 0; p < myLayers[n].Layer.visibleLayers.length; p++) {
                    if (info.name == theLayerInfos[myLayers[n].Layer.visibleLayers[p]].name) 
                        isChecked = "checked";
                }
            }
            else {
                theStyle = "style='display:none' ";
                type = "checkbox";
                theLabel = "";
                for (var p = 0; p < myLayers[n].Layer.visibleLayers.length; p++) {
                    if (info.name == theLayerInfos[myLayers[n].Layer.visibleLayers[p]].name) 
                        isChecked = "checked";
                }
            }
            items[i] = "<input type='" + type + "' class='list_item'" + theStyle + " " + isChecked + " id='" + n + ";" + info.id + "' onclick='updateLayerVisibility();' />" + theLabel;
            theHTML += items[i];
            
        }//end for i
    }//end for n
    return theHTML;
    
    
}

function updateLayerVisibility(){


    //Get the inputs from the checkboxes (DCC_MANAGER layers
    //are included in this list (but hidden from user) so no
    //need to check for these again.
    var inputs = dojo.query(".list_item"), input;
    
    //For each map service in the map, go through and work out which layers are on
    for (var z = 0, zl = myLayers.length; z < zl; z++) {
    
        visibleArr = [];
        for (var i = 0, il = inputs.length; i < il; i++) {
        
            temp = inputs[i].id.split(";");
            mapserviceID = temp[0];
            layerID = temp[1];
            
            if (z == mapserviceID) {
                if (inputs[i].checked) {
                    visibleArr.push(layerID);
                }
            }
            
        }//end for
        myLayers[z].Layer.setVisibleLayers(visibleArr);
        
    }
}

function HighlightFeature(feature){
    myMap.graphics.clear();
    
    graphic = feature;
    
    switch (graphic.geometry.type) {
        case "point":
            var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 1), new dojo.Color([0, 255, 0, 0.25]));
            
            break;
        case "polyline":
            var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 1);
            
            break;
        case "polygon":
            var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.25]));
            
            break;
    }
    graphic.setSymbol(symbol);
    myMap.graphics.add(graphic);
}

function Navigate(mybt){

    var coords = dojo.coords(dojo.byId(mybt));
    
    if (dojo.isIE) {
        pos_x = window.event.offsetX ? (window.event.offsetX) : window.event.clientX - coords.x;
        pos_y = window.event.offsetY ? (window.event.offsetY) : window.event.clientY - coords.y;
        if (pos_y < 25) {
            myMap.panUp();
        }
        else 
            if (pos_y > 50) {
                myMap.panDown();
            }
            else 
                if (pos_x < 30) {
                    myMap.panLeft();
                }
                else 
                    if (pos_x > 40) {
                        myMap.panRight();
                    }
        
    }
}

function myClickHandler(event){
    var coords = dojo.coords(dojo.byId('nav2'));
    if (dojo.isIE) {
    
    }
    else {
    
        pos_x = event.offsetX ? (event.offsetX) : event.clientX - coords.x;
        
        pos_y = event.offsetY ? (event.offsetY) : event.clientY - coords.y;
    }
    if (pos_y < 25) {
        myMap.panUp();
    }
    else 
        if (pos_y > 50) {
            myMap.panDown();
        }
        else 
            if (pos_x < 30) {
                myMap.panLeft();
            }
            else 
                if (pos_x > 40) {
                    myMap.panRight();
                }
    
}


function FEinit(){

    button = dojo.byId('nav2').childNodes[1];
    
    if (!dojo.isIE) {
        dojo.connect(button, 'onclick', myClickHandler);
    }
    
}

function loadURL(rsID, recID){

    window.open(myResults[rsID].Results[recID].feature.attributes["URL"]);
}

//functiion for printing using ctr+m buttons
var isCtrl = false;

document.onkeyup = function(e){
    var KeyID = (window.event) ? event.keyCode : e.which;
    
    if (KeyID == 17) 
        isCtrl = false;
}
document.onkeydown = function(e){
    var KeyID = (window.event) ? event.keyCode : e.which;
    if (KeyID == 17) 
        isCtrl = true;
    if (KeyID == 77 && isCtrl == true) {
        sFields = "";
        fixFields = (MapConfig.buttons[0].button[3].events[0].event[0].eventfunction).split(/\\u0027/);
        for (l = 0; l < fixFields.length; l++) {
            sFields += l > 0 ? "'" + fixFields[l] : fixFields[l];
        }
        
        eval(sFields);
        
        return false;
    }
}


dojo.global.esri.Map.prototype.reposition = function(){
    //var pos = dojo.coords(this.container),
    var pos = dojo.coords(this.container, true), brdr = dojo._getBorderExtents(this.container);
    
    this.position.setX(pos.x + brdr.l);
    this.position.setY(pos.y + brdr.t);
    this.onReposition(this.position.x, this.position.y);
}

function loadHelp(){
    if (typeof MapConfig.Helpfiles != 'undefined') {
        window.open('http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/dcc_GIS_api/php/helpfiles.php?Helpfile=' + fixURL(MapConfig.Helpfiles));
    }
    else {
        window.open('http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/dcc_GIS_api/php/helpfiles.php');
    }
}

function fixURL(url){
    myUrl = '';
    fixurl = (url).split(/\\/);
    for (var z = 0; z < fixurl.length; z++) {
        myUrl += fixurl[z];
    }
    return myUrl;
}


function ZoomToFeatures(service, layer, field, arrIDs, fImage)
{

 var xmin = 0, ymin=0, xmax = 0, ymax = 0;
 
 var arrFeaturePoints = new Array();
 var arrFeatureText = new Array();
 var arrWheres = new Array();
 arrQs = arrIDs.split(",");
 
 wherestring = "";
 for (var f = 0; f < arrQs.length; f++)
 {
    if (f>0){wherestring += " or ";}
    wherestring += field + " = " +arrQs[f];
    arrWheres[f] =  field + " = " +arrQs[f];
    
 }

 var mextent;
 
dojo.xhrGet({
    url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/ArcGIS/rest/services/"+service+"/MapServer/"+layer+"/query&where="+wherestring+"&f=json",
    load: function(response, ioArgs){
  
      for( var i = 0; i < response.features.length; i++)
      {
          if (response.geometryType == 'esriGeometryPoint')
          {
          if(xmin == 0 || xmin > response.features[i].geometry.x - factor){xmin = response.features[i].geometry.x-factor}
          if(xmax == 0 || xmax < response.features[i].geometry.x + factor){xmax = response.features[i].geometry.x+factor}
          if(ymin == 0 || ymin > response.features[i].geometry.y - factor){ymin = response.features[i].geometry.y-factor}
          if(ymax == 0 || ymax < response.features[i].geometry.y + factor){ymax = response.features[i].geometry.y+factor}        
          
          arrFeaturePoints[i] = new esri.geometry.Point(response.features[i].geometry.x,response.features[i].geometry.y, new esri.SpatialReference({ wkid: 27700 }));
          arrFeatureText[i] = response.features[i].attributes[response.displayFieldName];
	  
          }
           else  if (response.geometryType == 'esriGeometryPolygon') {
            var graphic = esri.geometry.fromJson(response.features[i].geometry);
                    arrFeaturePoints[i] = graphic;
          
                    if (typeof mextent == 'undefined')
                    {
                    mextent =     arrFeaturePoints[i].getExtent(); 
                    }
                    else
                    {
                    mextent = mextent.union(arrFeaturePoints[i].getExtent()); 
                    }
                     symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.0]));
                    // var pgraphic = new esri.Graphic(graphic, symbol, "", "")
                     //myMap.graphics.add(pgraphic);
                      mextent =   mextent.expand(1);
                }
                 else  {
            var graphic = esri.geometry.fromJson(response.features[i].geometry);
                    arrFeaturePoints[i] = graphic;
          
                    if (typeof mextent == 'undefined')
                    {
                    mextent =     arrFeaturePoints[i].getExtent(); 
                    }
                    else
                    {
                    mextent = mextent.union(arrFeaturePoints[i].getExtent()); 
                   
                    }
                  //   symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.0]));
               //      var pgraphic = new esri.Graphic(graphic, symbol, "", "")
                //     myMap.graphics.add(pgraphic);
                 mextent =   mextent.expand(1);
                }
         
            
   
            
     }
      zoomListner = dojo.connect(myMap, "onExtentChange", function(){
            
                for (var t=0;t<arrFeaturePoints.length;t++)
                {
                  if (response.geometryType == 'esriGeometryPoint')
{                    showPrintableImageOnMap( arrFeaturePoints[t],arrFeatureText[t],false, fImage,service, layer, layer + ":" + arrWheres[t]);}
                }    
                dojo.disconnect(zoomListner);
            })
          
  
   if (typeof mextent == 'undefined') {mextent = new esri.geometry.Extent(parseFloat(xmin) - factor, parseFloat(ymin) - factor, parseFloat(xmax) + factor, parseFloat(ymax) + factor,  new esri.SpatialReference({ wkid: 27700 }));}
   
    myMap.setExtent(mextent.expand(1));
    myMap.resize();
    myMap.reposition();
  
      return response;
    },
    error: function(response, ioArgs){
      alert("An error occurred, with response: " + response);
      return response;
    },
    handleAs: "json"
  });   

    
  

    





}






function ZoomToFeaturesAndUPRN(service, layer, field, arrIDs, fImage, UPRN, uImage, UPRNLayer)
{

 var xmin = 0, ymin=0, xmax = 0, ymax = 0;
 
 var arrFeaturePoints = new Array();
 var arrFeatureText = new Array();
 var arrUPRNPoints = new Array();
 arrQs = arrIDs.split(",");
  var myPointOnMap;
 
 wherestring = "";
 for (var f = 0; f < arrQs.length; f++)
 {
    if (f>0){wherestring += " or ";}
    wherestring += field + " = " +arrQs[f];
    
 }
//alert (wherestring);
 
dojo.xhrGet({
    url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/ArcGIS/rest/services/"+service+"/MapServer/"+layer+"/query&where="+wherestring+"&f=json",
    load: function(response, ioArgs){
  
      for( var i = 0; i < response.features.length; i++)
      {
          if (response.geometryType == 'esriGeometryPoint')
          {
          if(xmin == 0 || xmin > response.features[i].geometry.x - factor){xmin = response.features[i].geometry.x-factor}
          if(xmax == 0 || xmax < response.features[i].geometry.x + factor){xmax = response.features[i].geometry.x+factor}
          if(ymin == 0 || ymin > response.features[i].geometry.y - factor){ymin = response.features[i].geometry.y-factor}
          if(ymax == 0 || ymax < response.features[i].geometry.y + factor){ymax = response.features[i].geometry.y+factor}        
          
          arrFeaturePoints[i] = new esri.geometry.Point(response.features[i].geometry.x,response.features[i].geometry.y, new esri.SpatialReference({ wkid: 27700 }));
          arrFeatureText[i] = response.features[i].attributes[response.displayFieldName];
           
            
    
    
          }
          
         
            
   
            
     }
    
     ID = UPRN;
    dojo.xhrGet({
        url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/CAG/CAG.asmx/GetCAGPoints&HouseNo=&HouseName=&STREET_NAME=&POSTCODE=&UPRN=" + UPRN + "&IncludeStreetRecords=&Filter=",
        load: function(response, ioArgs){
        
            tag = "CAGPoint";
            
            if (window.ActiveXObject) {
            
            
                Rows = response.getElementsByTagName(tag);
                
                address = Rows[0].childNodes[0].childNodes[0].nodeValue
                easting = Rows[0].childNodes[6].childNodes[0].nodeValue;
                northing = Rows[0].childNodes[7].childNodes[0].nodeValue;
                
            }
            else {
                Rows = response.getElementsByTagName(tag);
                
                address = Rows[0].childNodes[1].textContent;
                easting = Rows[0].childNodes[13].textContent;
                northing = Rows[0].childNodes[15].textContent;
            }
               
          if(xmin == 0 || xmin > parseFloat(easting) - factor){xmin = parseFloat(easting)-factor}
          if(xmax == 0 || xmax < parseFloat(easting) + factor){xmax = parseFloat(easting)+factor}
          if(ymin == 0 || ymin > parseFloat(northing) - factor){ymin = parseFloat(northing)-factor}
          if(ymax == 0 || ymax < parseFloat(northing) + factor){ymax = parseFloat(northing)+factor}        
        
            
             myPointOnMap = new esri.geometry.Point(easting, northing, new esri.SpatialReference({
                wkid: 27700
            }));
            zoomListner = dojo.connect(myMap, "onExtentChange", function(){
                
                myMap.graphics.clear();
            
                for (var t=0;t<arrFeaturePoints.length;t++)
                {
                    showPrintableImageOnMap( arrFeaturePoints[t],arrFeatureText[t],false, fImage,service, layer, layer + ":" + wherestring);
                 
                }    
                dojo.disconnect(zoomListner);
                 showPrintableImageOnMap(myPointOnMap, address, false, uImage,"LocMap", UPRNLayer, UPRNLayer +":UPRN='"+UPRN+"'" );
            })
          
  
   var mextent = new esri.geometry.Extent(parseFloat(xmin) - factor, parseFloat(ymin) - factor, parseFloat(xmax) + factor, parseFloat(ymax) + factor,  new esri.SpatialReference({ wkid: 27700 }));
   
    myMap.setExtent(mextent.expand(1));
    myMap.resize();
    myMap.reposition();
         

            return response;
        },
        error: function(response, ioArgs){
        
            alert("address not Found");
            return response;
        },
        handleAs: "xml"
    });
    
    
    
    
     
     
     
      
  
      return response;
    },
    error: function(response, ioArgs){
      alert("An error occurred, with response: " + response);
      return response;
    },
    handleAs: "json"
  });   

    





}

function ZoomToTwoUPRNs(UPRN1, uImage1, printLayer1, UPRN2, uImage2, printLayer2, showLabels)
{

 var xmin = 0, ymin=0, xmax = 0, ymax = 0;
 
 
 wherestring = "";
     
    dojo.xhrGet({
        url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/CAG/CAG.asmx/GetCAGPoints&HouseNo=&HouseName=&STREET_NAME=&POSTCODE=&UPRN=" + UPRN1 + "&IncludeStreetRecords=&Filter=",
        load: function(response, ioArgs){
        
            tag = "CAGPoint";
            
            if (window.ActiveXObject) {
            
            
                Rows = response.getElementsByTagName(tag);
                
                address1 = Rows[0].childNodes[0].childNodes[0].nodeValue
                easting = Rows[0].childNodes[6].childNodes[0].nodeValue;
                northing = Rows[0].childNodes[7].childNodes[0].nodeValue;
                
            }
            else {
                Rows = response.getElementsByTagName(tag);
                
                address1 = Rows[0].childNodes[1].textContent;
                easting = Rows[0].childNodes[13].textContent;
                northing = Rows[0].childNodes[15].textContent;
            }
               
          if(xmin == 0 || xmin > parseFloat(easting) - factor){xmin = parseFloat(easting)-factor}
          if(xmax == 0 || xmax < parseFloat(easting) + factor){xmax = parseFloat(easting)+factor}
          if(ymin == 0 || ymin > parseFloat(northing) - factor){ymin = parseFloat(northing)-factor}
          if(ymax == 0 || ymax < parseFloat(northing) + factor){ymax = parseFloat(northing)+factor}        
        
            
             myPointOnMap1 = new esri.geometry.Point(easting, northing, new esri.SpatialReference({
                wkid: 27700
            }));
            dojo.xhrGet({
        url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/CAG/CAG.asmx/GetCAGPoints&HouseNo=&HouseName=&STREET_NAME=&POSTCODE=&UPRN=" + UPRN2 + "&IncludeStreetRecords=&Filter=",
        load: function(response, ioArgs){
        
            tag = "CAGPoint";
            
            if (window.ActiveXObject) {
            
            
                Rows = response.getElementsByTagName(tag);
                
                address2 = Rows[0].childNodes[0].childNodes[0].nodeValue
                easting = Rows[0].childNodes[6].childNodes[0].nodeValue;
                northing = Rows[0].childNodes[7].childNodes[0].nodeValue;
                
            }
            else {
                Rows = response.getElementsByTagName(tag);
                
                address2 = Rows[0].childNodes[1].textContent;
                easting = Rows[0].childNodes[13].textContent;
                northing = Rows[0].childNodes[15].textContent;
            }
               
          if(xmin == 0 || xmin > parseFloat(easting) - factor){xmin = parseFloat(easting)-factor}
          if(xmax == 0 || xmax < parseFloat(easting) + factor){xmax = parseFloat(easting)+factor}
          if(ymin == 0 || ymin > parseFloat(northing) - factor){ymin = parseFloat(northing)-factor}
          if(ymax == 0 || ymax < parseFloat(northing) + factor){ymax = parseFloat(northing)+factor}        
        
            
             myPointOnMap2 = new esri.geometry.Point(easting, northing, new esri.SpatialReference({
                wkid: 27700
            }));
            zoomListner = dojo.connect(myMap, "onExtentChange", function(){
                
              if(!showLabels) {address1 = ""; address2 = "";}
            
              showPrintableImageOnMap(myPointOnMap1, address1, true, uImage1,"LocMap", printLayer1, printLayer1 +":UPRN='"+UPRN1+"'" );
              showPrintableImageOnMap(myPointOnMap2, address2, false, uImage2,"LocMap", printLayer2, printLayer2 +":UPRN='"+UPRN2+"'" );
            })
          
  
   var mextent = new esri.geometry.Extent(parseFloat(xmin) - factor, parseFloat(ymin) - factor, parseFloat(xmax) + factor, parseFloat(ymax) + factor,  new esri.SpatialReference({ wkid: 27700 }));
   
    myMap.setExtent(mextent.expand(1));
    myMap.resize();
    myMap.reposition();
         

            return response;
        },
        error: function(response, ioArgs){
        
            alert("address not Found");
            return response;
        },
        handleAs: "xml"
    });


            return response;
        },
        error: function(response, ioArgs){
        
            alert("address not Found");
            return response;
        },
        handleAs: "xml"
    });



}

function showPrintableImageOnMap(myPoint, LabelString, clearExisting, pathToImage, Service, Layer, Definition){
    if (clearExisting) {
       
       
  
         if (typeof myMap.graphicsLayerIds != "undefined") {
        //if (typeof isInternet != "undefined") {
            arrgLayers = myMap.graphicsLayerIds;
            
            for (var tgl = arrgLayers.length -1; tgl >-1; tgl--) {
             
                myMap.removeLayer(myMap.getLayer(arrgLayers[tgl]));
                
            }
        }
         myMap.graphics.clear();
    }
    
   // if (typeof isInternet == "undefined") {
  //      gLayer = myMap.graphics;
 //   }
  //  else {
    
        gLayer = new esri.layers.GraphicsLayer();
        myMap.addLayer(gLayer);
  //  }
    
    var symbol = new esri.symbol.PictureMarkerSymbol(pathToImage, 30, 44);
    symbol.yoffset = 20;
    var attributes = {"service": Service, "Layer": Layer, "LayerDef":Definition};
    
    var graphic = new esri.Graphic(myPoint, symbol, attributes);
    gLayer.add(graphic);
    
    if (typeof MapConfig.HideLabel == 'undefined')
    {
    
    if (LabelString.length>0)
    {
    var Boxsymbol = new esri.symbol.PictureMarkerSymbol("http://Mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/infoLabel.png", 230, 55);
    var Closesymbol = new esri.symbol.PictureMarkerSymbol("http://Mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png", 20, 20);
    
    
    Boxsymbol.yoffset = -33;
    Closesymbol.yoffset = -17;
    Closesymbol.xoffset = 102;
    
    
    gLayer.add(new esri.Graphic(myPoint, Boxsymbol));
    gLayer.add(new esri.Graphic(myPoint, Closesymbol));
    
    var lbl = LabelString.replace(/%20/g, " ");
    var lbll = 0;
    
    var ArrWords = lbl.split(" ");
    strLine = "";
    lbRow = 0;
    
    for (var lbi = 0; lbi < ArrWords.length; lbi++) {
        if (strLine.length + ArrWords[lbi].length < 29) {
            strLine += ArrWords[lbi] + " ";
        }
        else {
        
            TXTsymbol = new esri.symbol.TextSymbol(strLine, new esri.symbol.Font(12, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_NORMAL, "Serif"), new dojo.Color("black"));
            TXTsymbol.yoffset = -20 - (lbRow * 13);
            TXTsymbol.xoffset = -10;
            gLayer.add(new esri.Graphic(myPoint, TXTsymbol));
            lbRow++;
            strLine = ArrWords[lbi] + " ";
            
        }
        
        
    }
    
    
    TXTsymbol = new esri.symbol.TextSymbol(strLine, new esri.symbol.Font(12, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_NORMAL, "Serif"), new dojo.Color("black"));
    TXTsymbol.yoffset = -20 - (lbRow * 13);
    TXTsymbol.xoffset = -10;
    gLayer.add(new esri.Graphic(myPoint, TXTsymbol));
    
    }
   /* if (typeof isInternet == "undefined") {
        dojo.connect(myMap.graphics, "onClick", function(evt){
            var g = evt.graphic;
            if (g.symbol.type == "picturemarkersymbol" && g.symbol.url == "http://Mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png") {
            
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].hide();
                }
            }
            else {
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].show();
                }
            }
            
        });
    }
    else {*/
        dojo.connect(gLayer, "onClick", function(evt){
            var g = evt.graphic;
            
            if (g.symbol.type == "picturemarkersymbol" && g.symbol.url == "http://Mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/i_zoomin.png") {
            
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].hide();
                }
            }
            else {
                for (var glg = 1; glg < g._graphicsLayer.graphics.length; glg++) {
                    g._graphicsLayer.graphics[glg].show();
                }
            }
            
            
        });
        
    //}
  }  
    
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function GetServiceString() // identifies visible layers & definition queries
{

    LegendDef = "";

    var ServiceString =""

    for (var lyrid = 0; lyrid < myLayers.length; lyrid++) 
    {
         
       if (myLayers[lyrid].Layer.visibleLayers != "" && myLayers[lyrid].Layer.visible)
       {
        var showLayers = "" + myLayers[lyrid].Layer.visibleLayers ;
        //showLayers =  showLayers.replace(",," ,"");
        if (Right(showLayers, 1) == ",") {showLayers = showLayers.substring(0, showLayers.length - 1);}
        if (myLayers[lyrid].SwatchPath.length >0){
          if (LegendDef.length >0){LegendDef+= "~";}
          //Example of LegendDef string would be really handy here...
          LegendDef += myLayers[lyrid].SwatchPath + "^" + showLayers + "^" + myLayers[lyrid].Label;
          
        }
        ServiceString += myLayers[lyrid].Label+"~";
       
     
      ServiceString +=  "show:" + showLayers + "~";
       /*  ServiceString +=  "~"
       if (myLayers[lyrid].SwatchPath != "")
        {
         ServiceString +=  myLayers[lyrid].SwatchPath;
        }*/
        layerDefinition = myLayers[lyrid].Layer.layerDefinitions;
        if (layerDefinition != 'undefined' && layerDefinition != null)
        {
            lyrDefString = "";
            for (var lyrdef = 0; lyrdef <myLayers[lyrid].Layer.layerDefinitions.length; lyrdef++) 
            {
                lyrDefString += lyrdef + ":" + myLayers[lyrid].Layer.layerDefinitions[lyrdef] + ";";
            }
            
            ServiceString += lyrDefString;
        }
      
        ServiceString += "~" + myLayers[lyrid].Opacity;
          
        if (lyrid < myLayers.length -1){ServiceString += "|";}
      }
    }
    
    if (ServiceString.substr(ServiceString.length - 1) == "|")
    {ServiceString = ServiceString.substr(0,ServiceString.length - 1);}
    

    //get service strings from graphics
    
     if (typeof myMap.graphicsLayerIds != "undefined" && myMap.graphicsLayerIds.length > 0) {
        //if (typeof isInternet != "undefined") {
            arrgLayers = myMap.graphicsLayerIds;
            GserviceString = "";  
            for (var tgl = 0; tgl < arrgLayers.length ; tgl++) {
             
               //arrgLayers[tgl];
             
              gLayer = myMap.getLayer(arrgLayers[tgl]);
              
              arrServices = new Array();
              var s = 0;
              for (var g = 0; g< gLayer.graphics.length; g++)
              {
                if (typeof gLayer.graphics[g].attributes != 'undefined')
                {
                 if (typeof gLayer.graphics[g].attributes.service != 'undefined')
                 { 
                 
                         GserviceString +=  "|" + gLayer.graphics[g].attributes.service + "~show:"+gLayer.graphics[g].attributes.Layer +"~" +  gLayer.graphics[g].attributes.LayerDef  + "~1";
                   
                 }
                }
             
              
              }   
            }
        }
        else
        {
      gLayer = myMap.graphics;
      GserviceString = "";  
      arrServices = new Array();
      var s = 0;
      for (var g = 0; g< gLayer.graphics.length; g++)
      {
        if (typeof gLayer.graphics[g].attributes != 'undefined')
        {
         if (typeof gLayer.graphics[g].attributes.service != 'undefined')
         { 
         
                 GserviceString +=  "|" + gLayer.graphics[g].attributes.service + "~show:"+gLayer.graphics[g].attributes.Layer +"~" +  gLayer.graphics[g].attributes.LayerDef + "~1";
               
            
           
         }
        }
     
      
      }
       // append to service string
    }
          
    //alert(ServiceString + GserviceString);
    return ServiceString + GserviceString ;


}
var strMapTitle = 'My Dundee Map';

function CreatePDFwithDefs(strTitle)
{
   //Added 6th Aug to deal with maps with no title
   if (typeof strTitle == 'undefined')
        strTitle = "Map";
        
   dojo.query(".dojoxFisheyeListItemImage", document).forEach("item.style.cursor = 'wait'");
    //dojo.byId("dojoxFisheyeListItemImage");
   
       serviceString = "?serviceString="+GetServiceString() ;
       minx = "&xmin=" + myMap.extent.xmin.toString();
       miny = "&yMin=" + myMap.extent.ymin.toString();
       maxx = "&xMax=" + myMap.extent.xmax.toString();
       maxy = "&yMax=" + myMap.extent.ymax.toString();
       orientation = "&orientation=portrait";
       theTitle = "&theTitle=" + strTitle;
       ldef= "&LDef=" + LegendDef;
    
    //Added PMcG to temporarily allow private services to print
    var vApp = (strTitle == "Community Warden Incidents") ? "PrintingPrivate" : "Printing";
       
    window.open("http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/" + vApp + "/Printing.asmx/CreatePDFMultiService"+ serviceString+minx + miny + maxx + maxy + orientation + theTitle + ldef);    
    /*
     dojo.xhrGet({
    url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/Printing/Printing.asmx/CreatePDFMultiService"+ serviceString+minx + miny + maxx + maxy + orientation + theTitle + ldef,
    load: function(response, ioArgs){
         if (window.ActiveXObject)
        {
            pdfPath = response.childNodes[1].childNodes[0].nodeValue;
        }
        else
        {
            pdfPath = response.firstChild.textContent;
        }
            window.open(pdfPath, "");
        //
           dojo.query(".dojoxFisheyeListItemImage", document).forEach("item.style.cursor = 'pointer'");
      return response;
    },
    error: function(response, ioArgs){
      
      alert ("address not Found");
        dojo.query(".dojoxFisheyeListItemImage", document).forEach("item.style.cursor = 'pointer'");
      return response;
    },
    handleAs: "xml"
  });
  */
}


function toggleAP(){
    if (APLayer != '') {
        if (APLayer.visible) {
            APLayer.hide();
        }
        else {
            APLayer.show()
        }
    }

}


function zoomDundee(){
    myExtent = new esri.geometry.Extent(334160, 728508, 348632, 735821, new esri.SpatialReference({
        wkid: 27700
    }));
    myMap.setExtent(myExtent.expand(2));
    myMap.resize();
    myMap.reposition();
}
function getJsonObject( XmlPath, NodeName)
    {
    var result;
      dojo.xhrPost({
        url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/DCC_SERVICES/XML/XMLHandler.asmx/GetJsonFromXMLFile&filePath=" + XmlPath +"&nodeName=" + NodeName,
        load: function(response, ioArgs){
                    
              myXml = response;
                

                if (window.ActiveXObject)
                {
                    
                     result =  eval( "(" + myXml.childNodes[1].childNodes[0].nodeValue + ')' ); 
                }
                else{
                    result =   eval("(" +  myXml.childNodes[0].childNodes[0].textContent + ')' );
                }
                         
            
           
            return result;
        },
        error: function(response, ioArgs){
        
            alert("address not Found");
            return response;
        },
        handleAs: "xml",
        sync: true
    });
     return result;
}

function ObjectToArray( obj)
{
    if( !obj) return new Array();
    if( !obj.length) return new Array(obj);
    return obj;
}
function togglaBaseMap(node)
{

toggleAP();
//var basediv = dojo.byId("BaseMap"); 
//dojo.isIE ?  nodeid = 0 :  nodeId = 1;
//APLayer.visible? basediv.childNodes[nodeid].src = "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/BaseMap.png" : basediv.childNodes[nodeid].src = "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/Baseap.png";

if (APLayer.visible)
{
node.innerHTML= "Map";
origCopyright = dojo.byId("Copyright").innerHTML;
//dojo.query("backgroundbut_label", node).forEach("item.innerHTML = 'http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/BaseMap.png';");
//dojo.query(".dojoxFisheyeListItemLabel", basediv).forEach("item.innerHTML = 'Click to Switch off Aerial Photography';")
dojo.byId("Copyright").innerHTML +=  "  Aerial Photography © Get Mapping 2010.";

}
else
{
dojo.byId("Copyright").innerHTML = origCopyright;
//dojo.query(".dojoxFisheyeListItemImage", basediv).forEach("item.src = 'http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/BaseAP.png';");

//dojo.query(".dojoxFisheyeListItemLabel", basediv).forEach("item.innerHTML = 'Click to Switch on Aerial Photography';");
node.innerHTML= "Aerial Photo";
}


//APLayer.visible? basediv.childNodes[2].innerHTML = "Click to Switch off Aerial Photography" : basediv.childNodes[2].innerHTML = "Click to Switch on Aerial Photography";
}

// added for intranetgis ->
dojo.require("esri.toolbars.draw");
dojo.require("esri.tasks.geometry");
dojo.require("dijit.Dialog");
dojo.require("dojo.io.iframe");
dojo.require("dijit.form.ComboBox");
dojo.require("esri.tasks.gp");
var curScale, markupTool;
var markupLayer;

var toolbar, PointGP, mySessionID;

 function zoomToScale(scale)
 {
    if (scale != ""){
    thewidth = myMap.extent.getWidth();
    theheight = myMap.extent.getHeight();
    themidx = myMap.extent.xmax - thewidth/2;
    themidy = myMap.extent.ymax - theheight/2;
    
    scaleval =  scale * (dojo.byId("myMap").clientWidth/96)*0.0254;
    scalevalH =  scale * (dojo.byId("myMap").clientHeight/96)*0.0254;
    newextent = new esri.geometry.Extent(themidx - scaleval/2, themidy - scalevalH/2  , themidx + scaleval/2, themidy + scalevalH/2 , myMap.spatialReference)
    myMap.setExtent(newextent);
 }
 
 }
 
    function showCoordinates(evt) {
        //get myMapPoint from event
        var mp = evt.mapPoint;
        //display mouse coordinates
        window.status = "Coordinates : " +  Math.round(mp.x) + ", " + Math.round(mp.y) ;
      }
      
 function ExecuteGraphicGeoProcessor(params)
      {
      
      xurl = "http://mapsonline.dundeecity.gov.uk/ArcGIS/rest/services/GraphicsAdd/GPServer/" + params
      
            dojo.xhrPost({
        url: xurl,
        load: function(response, ioArgs){
              // dojo.byId("edlngth").value = response.lengths[0].toFixed(2) + " m ";
              //try {dojo.byId("edarea").value = response.areas[0].toFixed(2) + " sqm";}catch(error) {}
                    
             // alert (response ) ;
              
            return response;
        },
        error: function(response, ioArgs){
                  
            return response;
        },
        handleAs: "json",
        sync: false
    });
      
      
      }
    
    
 
 
 function gotoAddress()
{
    

    //get address coords
    var list = document.getElementById('ListSel');
  
   tag = "CAGPoint";
   
   var easting = 0;
   var northing = 0;
   var UPRN;
   var address = list.value;

     if (resultsXML != undefined && address != "" && address != "Too many many results returned! Please refine search."&& address != "" && address != "No results returned! Please refine search.")
   {
      if (window.ActiveXObject)
                {
                

                Rows = resultsXML.getElementsByTagName(tag);
               
                 for (var i=0, il=resultsXML.getElementsByTagName(tag).length; i<il; i++) 
                        {
                         
                            if (Rows[i].childNodes[0].childNodes[0].nodeValue == address)
                           {
                            easting = Rows[i].childNodes[6].childNodes[0].nodeValue;
                            northing = Rows[i].childNodes[7].childNodes[0].nodeValue;
                            UPRN = Rows[i].childNodes[5].childNodes[0].nodeValue;
                            
                            break;
                           }
                           }
            
            }
            else
            {
                 Rows = resultsXML.getElementsByTagName(tag);
               
                  for (var i=0, il=resultsXML.getElementsByTagName(tag).length; i<il; i++) 
                        {
                           
                           if (Rows[i].childNodes[1].textContent == address)
                           {
                           easting = Rows[i].childNodes[13].textContent;
                           northing = Rows[i].childNodes[15].textContent;
                            UPRN = Rows[i].childNodes[11].textContent;
                            break;
                           }
                           
                            
                        }
            }
    
    myAddressPoint = new esri.geometry.Point(easting,northing, new esri.SpatialReference({ wkid: 27700 })); 
    showPrintableImageOnMap( myAddressPoint ,address ,true, "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/home.png" ,"LocMap", 0, "0:UPRN='" + UPRN + "'");
    theExtent = new esri.geometry.Extent(parseFloat(myAddressPoint.x) - factor, parseFloat(myAddressPoint.y) - factor, parseFloat(myAddressPoint.x) + factor, parseFloat(myAddressPoint.y) + factor, myAddressPoint.spatialReference); 
     
      list.parentNode.parentNode.removeChild(list.parentNode);
      zoomExtent(theExtent);

      
    }
 else{alert("Please select a valid address");
   var rowList = dojo.query(".dijitAccordionBody");
        for(var i = 0; i < rowList.length; i++ ){
    rowList[i].style.cursor='auto';}}  

}

function zoomAllDundee(){
    myExtent = new esri.geometry.Extent(334160, 728508, 348632, 735821, new esri.SpatialReference({
        wkid: 27700
    }));
    myMap.setExtent(myExtent.expand(2));
    myMap.resize();
    myMap.reposition();
}

function clearAllGraphics()
        {
        
        myMap.graphics.clear();
            arrgLayers = myMap.graphicsLayerIds;
            
            for (var tgl = 0; tgl < arrgLayers.length; tgl++) {
            
                myMap.removeLayer(myMap.getLayer(arrgLayers[tgl]));
            }
             markupLayer = null;   
             
             
              xurl = "http://mapsonline.dundeecity.gov.uk/ArcGIS/rest/services/GraphicsAdd/GPServer/ClearGraphics/execute?Identifier=" + mySessionID;
      
            dojo.xhrPost({
        url: xurl,
        load: function(response, ioArgs){
              // dojo.byId("edlngth").value = response.lengths[0].toFixed(2) + " m ";
              //try {dojo.byId("edarea").value = response.areas[0].toFixed(2) + " sqm";}catch(error) {}
                    
             // alert (response ) ;
              
            return response;
        },
        error: function(response, ioArgs){
                  
            return response;
        },
        handleAs: "json",
        sync: false
    });
        }
 
 // -end of intranet tools