﻿// JScript File
var timer
      dojo.require("esri.map");
      dojo.require("esri.tasks.query");
        var dynamicLayer
      var map, queryTask, query;
      var featureSet;
dojo.addOnLoad(init);
      function zoomIn(){
        var zoomLevel = map.getLevel()
        var newLevel = zoomLevel + 1
        map.setLevel(newLevel)
      }
      function zoomOut(){
        var zoomLevel = map.getLevel()
        var newLevel = zoomLevel - 1
        map.setLevel(newLevel)
      }
      
      function resizeMap(){
        map.reposition()
      }
      
      function init() {
        var customExtent = new esri.geometry.Extent(366200, 233000, 409300, 275100, new esri.SpatialReference({ "wkid": 27700 }));
        map = new esri.Map("mapDiv", { extent: customExtent, logo:false });
        //map = new esri.Map("mapDiv");

        // Adds in the service containing the vector maps
        var tiledLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://gis.worcestershire.gov.uk/ArcGIS/rest/services/VectorMapMobile_Cached/MapServer");
        map.addLayer(tiledLayer);

        //create and add new layer
        dynamicLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://gis.worcestershire.gov.uk/ArcGIS/rest/services/ThermalData/MapServer");
        map.addLayer(dynamicLayer);

        //Listen for click event on the map, when the user clicks on the map call executeQueryTask function.
        dojo.connect(map, "onClick", executeQueryTask);

        //Listen for infoWindow onHide event
        dojo.connect(map.infoWindow, "onHide", function() {map.graphics.clear();});
        if (dynamicLayer.loaded) {
            zoomPC(dynamicLayer);
        }
        else {
            dojo.connect(dynamicLayer, "onLoad", zoomPC);
        }

        //build query task
        queryTask = new esri.tasks.QueryTask("http://gis.worcestershire.gov.uk/ArcGIS/rest/services/ThermalData/MapServer/0");

        //Can listen for onComplete event to process results or can use the callback option in the queryTask.execute method.
        //dojo.connect(queryTask, "onComplete", showResults);

        //build query filter
        query = new esri.tasks.Query();
        query.returnGeometry = true;
        query.outFields = ["TOID", "MAPPING"];
//connect to window's resize event
  dojo.connect(window, "onresize", function() {
    //clear any existing resize timer
    clearTimeout(timer);
    //create new resize timer with delay of 500 milliseconds
    timer = setTimeout(function() { map.reposition(); }, 500);
  });

      }

      function executeQueryTask(evt) {
        map.infoWindow.hide();
        map.graphics.clear();
        featureSet = null;

        //onClick event returns the evt point where the user clicked on the map.
        //This is contains the mapPoint (esri.geometry.point) and the screenPoint (pixel xy where the user clicked).
        //set query geometry = to evt.mapPoint Geometry
        query.geometry = evt.mapPoint;

        //Execute task and call showResults on completion
        queryTask.execute(query, function(fset) {
          if (fset.features.length === 1) {
            showFeature(fset.features[0],evt);
          } else if (fset.features.length !== 0) {
            showFeatureSet(fset,evt);
          }
        });
      }

      function showFeature(feature,evt) {
        map.graphics.clear();

        //set symbol
        //NB - 4th parameter in second colour definition is level of opaqueness from 0.0 to 1.0
        var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,255,255]), 2), new dojo.Color([255,255,0,0.0]));
        feature.setSymbol(symbol);

        //construct infowindow title and content
        var attr = feature.attributes;
        var title = "Energy Efficiency Information";
        var effValue = -1;
        var effCategory = "not available";
        effValue = attr.MAPPING;
        
        switch (true)
        {
            case effValue >= 0 && effValue < 80:
            effCategory = "Good"; break;
            case effValue >= 80 && effValue < 115:
            effCategory = "Average Good"; break;
            case effValue >= 115 && effValue < 131:
            effCategory = "Average"; break;
            case effValue >= 131 && effValue < 161:
            effCategory = "Average Poor"; break;
            case effValue >= 161 && effValue < 256:
            effCategory = "Poor"; break;
            case effValue >= 256:
            effCategory = "Unclassified"; break;
            case effValue = -1:
            effCategory = "Not Available - sorry"; break;
            default:
            effCategory = "Not Available.  Sorry, an error has occurred.";
        }
        
        
    // Creates the content of the pop-up information box
      var content = "The energy efficiency rating of this building is <b>" + effCategory
                  + "</b>.<br/><br/>Find out how to <a href=http://worcestershire.whub.org.uk/home/wcc-chief-exec-ways_to_insulate_your_home target=_blank>reduce heat loss from your home</a>."
                  + "<br/><br/><i>Link opens in a new window</i>.";
        map.graphics.add(feature);

        map.infoWindow.setTitle(title);
        map.infoWindow.setContent(content);

        (evt) ? map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint)) : null;
      }

      function showFeatureSet(fset,evt) {
        //remove all graphics on the maps graphics layer
        map.graphics.clear();
        var screenPoint = evt.screenPoint;

        featureSet = fset;

        var numFeatures = featureSet.features.length;

        //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the infowindow.
        var title = "You have selected " + numFeatures + " buildings.";
        var content = "Please select desired building from the list below.<br />";

        for (var i=0; i<numFeatures; i++) {
          var graphic = featureSet.features[i];
          }
        map.infoWindow.setTitle(title);
        map.infoWindow.setContent(content);
        map.infoWindow.show(screenPoint,map.getInfoWindowAnchor(evt.screenPoint));
      }
      function zoomGaz(x,y) {// zooms to coords specified in bottom right input boxes        
        map.graphics.clear();
        var x1 = Math.abs(x);
        var y1 = Math.abs(y);               
        var pointGaz = new esri.geometry.Point(x1,y1, new esri.SpatialReference({ wkid: 27700 }));
        var markerSymbolGaz = new  esri.symbol.PictureMarkerSymbol('images/pin_blue.gif', 40, 40);
        var graphicGaz = new esri.Graphic(pointGaz);
        graphicGaz.setSymbol(markerSymbolGaz);       
        var extentGaz = new esri.geometry.Extent(x1-100, y1-100, x1+100, y1+100);
        map.graphics.add(graphicGaz);
        map.setExtent(extentGaz);
      }

      function stringFilter (input) {//remove space from pcs
       s = input.value;
       filteredValues = " ";     // Characters stripped out
       var i;
       var returnString = "";
       for (i = 0; i < s.length; i++) {  // Search through string and append unfiltered values to returnString.
       var c = s.charAt(i);
       if (filteredValues.indexOf(c) == -1) returnString += c;
        }
        input.value = returnString;
      }


      
      
      /*
     * 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 zoomPC(){
    pc = document.getElementById("hiddenPC").innerHTML
    pc = pc.replace("<SPAN id=lblPC>", "")
    pc = pc.replace("</SPAN>", "")
    if (pc != ""){
        CallServer(pc, 'True');
    }
}
function CallServer(arg, context) {
    WebForm_DoCallback('__Page', arg, ReceiveServerData, context, null, false);
}
function ReceiveServerData(context) {

    if (context.indexOf(",") != -1) {
        xy = context.split(",")
        x = xy[0]
        y = xy[1]

        extent = 300
        var urlX = Math.abs(x);
        var urlY = Math.abs(y);
        var extentGaz = new esri.geometry.Extent(urlX - extent, urlY - extent, urlX + extent, urlY + extent);
        map.setExtent(extentGaz);
    }
}
